BITKit/Src/Unity/Scripts/UX/Service/UI Toolkit/UIToolkitSubPanel.cs

142 lines
3.7 KiB
C#

using System;
using System.Collections;
using System.Collections.Generic;
using Cysharp.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using UnityEngine;
using UnityEngine.UIElements;
namespace BITKit.UX
{
public class UIToolkitSubPanel<T> :IUXPanel where T : IUXPanel
{
private readonly IServiceProvider _serviceProvider;
protected readonly T Panel;
protected readonly ValidHandle IsVisible=new();
private readonly ValidHandle _busy = new();
public UIToolkitSubPanel(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
Panel = serviceProvider.GetRequiredService<T>();
Panel.OnInitiated += OnInitiated;
Panel.OnInitiatedAsync += OnInitiatedAsync;
if (Panel is UIToolKitPanel uiToolKitPanel)
{
if (uiToolKitPanel.WaitUtilInitialized.Task.Status is UniTaskStatus.Succeeded)
{
OnInitiatedAsync().Forget();
OnInitiated();
}
}
Panel.OnEntry +=()=> IsVisible.RemoveDisableElements(this);
Panel.OnExit +=()=> IsVisible.AddDisableElements(this);
IsVisible.AddListener(IsVisibleCallback);
}
private async void IsVisibleCallback(bool x)
{
await _busy;
using var busy = _busy.GetHandle();
if (x)
{
OnEntry?.Invoke();
OnEntryAsync?.Invoke();
OnEntryCompleted?.Invoke();
}
else
{
OnExit?.Invoke();
OnExitAsync?.Invoke();
OnExitCompleted?.Invoke();
}
}
protected virtual UniTask OnInitiatedAsync()
{
UXUtils.Inject(this,Panel.Root as VisualElement);
return UniTask.CompletedTask;
}
protected virtual void OnInitiated()
{ UXUtils.Inject(this,Panel.Root as VisualElement);
}
bool IEntryElement.IsEntered
{
get => Panel.IsEntered;
set => Panel.IsEntered = value;
}
void IEntryElement.Entry()
{
Panel.Entry();
}
UniTask IEntryElement.EntryAsync()
{
return Panel.EntryAsync();
}
void IEntryElement.Entered()
{
Panel.Entered();
}
void IEntryElement.Exit()
{
Panel.Exit();
}
UniTask IEntryElement.ExitAsync()
{
return Panel.ExitAsync();
}
void IEntryElement.Exited()
{
Panel.Exited();
}
bool IUXPanel.IsWindow => Panel.IsWindow;
string IUXPanel.Index => Panel.Index;
bool IUXPanel.AllowCursor => Panel.AllowCursor;
bool IUXPanel.AllowInput => Panel.AllowInput;
object IUXPanel.Root => Panel.Root;
public event Action OnEntry;
public event Func<UniTask> OnEntryAsync;
public event Action OnEntryCompleted;
public event Action OnExit;
public event Func<UniTask> OnExitAsync;
public event Action OnExitCompleted;
event Action IUXPanel.OnInitiated
{
add => Panel.OnInitiated += value;
remove => Panel.OnInitiated -= value;
}
event Func<UniTask> IUXPanel.OnInitiatedAsync
{
add => Panel.OnInitiatedAsync += value;
remove => Panel.OnInitiatedAsync -= value;
}
void IUXPanel.OnTick(float deltaTime)
{
Panel.OnTick(deltaTime);
}
}
}