Files
AppleHillsProduction/Assets/Scripts/UI/CardSystem/UIPageController.cs
2025-10-14 15:54:11 +02:00

111 lines
3.4 KiB
C#

using System;
using System.Collections.Generic;
using Core;
using UnityEngine;
namespace AppleHills.UI.CardSystem
{
/// <summary>
/// Manages UI page transitions and maintains a stack of active pages.
/// Pages are pushed onto a stack for navigation and popped when going back.
/// </summary>
public class UIPageController : MonoBehaviour
{
private static UIPageController _instance;
public static UIPageController Instance => _instance;
private Stack<UIPage> _pageStack = new Stack<UIPage>();
public UIPage CurrentPage => _pageStack.Count > 0 ? _pageStack.Peek() : null;
// Event fired when the page stack changes
public event Action<UIPage> OnPageChanged;
private void Awake()
{
if (_instance != null && _instance != this)
{
Destroy(gameObject);
return;
}
_instance = this;
}
/// <summary>
/// Pushes a new page onto the stack, hiding the current page and showing the new one.
/// </summary>
public void PushPage(UIPage page)
{
if (page == null) return;
// Hide current page if there is one
if (_pageStack.Count > 0)
{
UIPage currentPage = _pageStack.Peek();
currentPage.TransitionOut();
}
// Push and show new page
_pageStack.Push(page);
page.TransitionIn();
OnPageChanged?.Invoke(page);
Logging.Debug($"[UIPageController] Pushed page: {page.PageName}");
}
/// <summary>
/// Pops the current page from the stack and shows the previous page.
/// </summary>
public void PopPage()
{
if (_pageStack.Count <= 0) return;
// Hide and pop current page
UIPage currentPage = _pageStack.Pop();
currentPage.TransitionOut();
// Show previous page if there is one
if (_pageStack.Count > 0)
{
UIPage previousPage = _pageStack.Peek();
previousPage.TransitionIn();
OnPageChanged?.Invoke(previousPage);
Logging.Debug($"[UIPageController] Popped to previous page: {previousPage.PageName}");
}
else
{
OnPageChanged?.Invoke(null);
Logging.Debug("[UIPageController] Popped last page, no pages left in stack");
}
}
/// <summary>
/// Clears all pages from the stack.
/// </summary>
public void ClearStack()
{
if (_pageStack.Count <= 0) return;
// Hide current page
UIPage currentPage = _pageStack.Peek();
currentPage.TransitionOut();
// Clear stack
_pageStack.Clear();
OnPageChanged?.Invoke(null);
Logging.Debug("[UIPageController] Cleared page stack");
}
/// <summary>
/// Handles back button input and navigates to the previous page if possible.
/// </summary>
private void Update()
{
if (UnityEngine.Input.GetKeyDown(KeyCode.Escape) && _pageStack.Count > 0)
{
_pageStack.Peek().OnBackPressed();
}
}
}
}