2023-08-23 01:59:40 +08:00
|
|
|
using System;
|
2023-08-12 01:43:24 +08:00
|
|
|
using System.Collections;
|
|
|
|
using System.Collections.Generic;
|
|
|
|
using BITKit.UX;
|
|
|
|
using UnityEngine;
|
|
|
|
using UnityEngine.UIElements;
|
2023-08-23 01:59:40 +08:00
|
|
|
// ReSharper disable MemberCanBePrivate.Global
|
2023-08-12 01:43:24 +08:00
|
|
|
public class UXBuilder : MonoBehaviour
|
|
|
|
{
|
2023-10-02 23:24:56 +08:00
|
|
|
[SerializeReference, SubclassSelector]
|
2023-08-12 01:43:24 +08:00
|
|
|
private IVisualElementProvider visualElementProvider;
|
|
|
|
|
|
|
|
[SerializeField] private VisualTreeAsset visualTreeAsset;
|
|
|
|
|
2023-08-23 01:59:40 +08:00
|
|
|
[SerializeField] private bool clearOnStart;
|
|
|
|
|
2023-08-12 01:43:24 +08:00
|
|
|
private readonly List<VisualElement> instances = new();
|
2023-08-27 02:58:19 +08:00
|
|
|
public VisualElement VisualElement => visualElementProvider.GetVisualElement();
|
2023-08-23 01:59:40 +08:00
|
|
|
private IList ItemSource
|
|
|
|
{
|
|
|
|
get => _itemSource;
|
|
|
|
set => OnBindItemSource(value);
|
|
|
|
}
|
|
|
|
private IList _itemSource;
|
|
|
|
|
|
|
|
|
2023-10-02 23:24:56 +08:00
|
|
|
public T Build<T>() where T : VisualElement,new()
|
2023-08-12 01:43:24 +08:00
|
|
|
{
|
2023-10-02 23:24:56 +08:00
|
|
|
var clone =visualTreeAsset is not null ? visualTreeAsset.CloneTree()[0] : new T();
|
2023-08-12 01:43:24 +08:00
|
|
|
visualElementProvider.GetVisualElement().Add(clone);
|
|
|
|
instances.Add(clone);
|
|
|
|
return clone as T;
|
|
|
|
}
|
2023-08-23 01:59:40 +08:00
|
|
|
public T Build<T>(Func<VisualElement> createFactory) where T : VisualElement
|
|
|
|
{
|
|
|
|
var clone = createFactory.Invoke();
|
|
|
|
visualElementProvider.GetVisualElement().Add(clone);
|
|
|
|
instances.Add(clone);
|
|
|
|
return clone as T;
|
|
|
|
}
|
|
|
|
public UXContainer BuildAsContainer(Func<VisualElement> createFactory) => new(Build<VisualElement>(createFactory));
|
2023-08-12 01:43:24 +08:00
|
|
|
public UXContainer BuildAsContainer() => new(Build<VisualElement>());
|
|
|
|
|
|
|
|
public void Clear()
|
|
|
|
{
|
|
|
|
foreach (var x in instances)
|
|
|
|
{
|
|
|
|
visualElementProvider.GetVisualElement().Remove(x);
|
|
|
|
}
|
|
|
|
|
|
|
|
instances.Clear();
|
|
|
|
}
|
2023-08-23 01:59:40 +08:00
|
|
|
|
|
|
|
private void OnBindItemSource(IList source)
|
|
|
|
{
|
|
|
|
_itemSource = source;
|
|
|
|
}
|
|
|
|
|
|
|
|
public void Rebuild()
|
|
|
|
{
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
|
|
private void Start()
|
|
|
|
{
|
|
|
|
if (clearOnStart)
|
|
|
|
{
|
|
|
|
visualElementProvider.GetVisualElement().Clear();
|
|
|
|
}
|
|
|
|
}
|
2023-08-12 01:43:24 +08:00
|
|
|
}
|