com.alicizax.unity.framework/Runtime/UI/UIBase/UIStateMachine.cs

83 lines
3.2 KiB
C#
Raw Normal View History

2025-12-24 20:44:36 +08:00
using System;
using System.Collections.Generic;
namespace AlicizaX.UI.Runtime
{
/// <summary>
/// UI State Machine - Validates state transitions for UI lifecycle.
/// Helps catch bugs early and ensures proper UI lifecycle management.
/// </summary>
internal static class UIStateMachine
{
private static readonly Dictionary<UIState, HashSet<UIState>> _validTransitions = new()
{
[UIState.Uninitialized] = new() { UIState.CreatedUI },
[UIState.CreatedUI] = new() { UIState.Loaded },
[UIState.Loaded] = new() { UIState.Initialized },
[UIState.Initialized] = new() { UIState.Opened },
[UIState.Opened] = new() { UIState.Closed, UIState.Destroying },
[UIState.Closed] = new() { UIState.Opened, UIState.Destroying },
[UIState.Destroying] = new() { UIState.Destroyed },
[UIState.Destroyed] = new() { }
};
/// <summary>
/// Checks if a state transition is valid.
/// </summary>
/// <param name="from">Current state</param>
/// <param name="to">Target state</param>
/// <returns>True if transition is valid</returns>
public static bool IsValidTransition(UIState from, UIState to)
{
return _validTransitions.TryGetValue(from, out var validStates) && validStates.Contains(to);
}
/// <summary>
/// Validates a state transition and logs error if invalid.
/// </summary>
/// <param name="uiName">Name of the UI for logging</param>
/// <param name="from">Current state</param>
/// <param name="to">Target state</param>
/// <returns>True if transition is valid</returns>
public static bool ValidateTransition(string uiName, UIState from, UIState to)
{
if (IsValidTransition(from, to))
return true;
Log.Error($"[UI] Invalid state transition for {uiName}: {from} -> {to}");
return false;
}
/// <summary>
/// Gets all valid next states from the current state.
/// </summary>
/// <param name="currentState">Current state</param>
/// <returns>Set of valid next states</returns>
public static HashSet<UIState> GetValidNextStates(UIState currentState)
{
return _validTransitions.TryGetValue(currentState, out var states)
? states
: new HashSet<UIState>();
}
/// <summary>
/// Gets a human-readable description of the state.
/// </summary>
public static string GetStateDescription(UIState state)
{
return state switch
{
UIState.Uninitialized => "Not yet created",
UIState.CreatedUI => "UI logic created, awaiting resource load",
UIState.Loaded => "Resources loaded, awaiting initialization",
UIState.Initialized => "Initialized, ready to open",
UIState.Opened => "Currently visible and active",
UIState.Closed => "Hidden but cached",
UIState.Destroying => "Being destroyed",
UIState.Destroyed => "Fully destroyed",
_ => "Unknown state"
};
}
}
}