SHA256
87 lines
3.1 KiB
C#
87 lines
3.1 KiB
C#
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using MelonLoader;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace ADOFAIRenderer.Data
|
|
{
|
|
/// <summary>
|
|
/// Binds a UI Toolkit <see cref="DropdownField"/> to an enum type.
|
|
/// Populates choices from enum names and provides typed access to the selected value.
|
|
/// </summary>
|
|
/// <typeparam name="T">The enum type to bind.</typeparam>
|
|
public class EnumDropdownBinder<T> where T : struct, Enum
|
|
{
|
|
private readonly DropdownField? _dropdown;
|
|
private readonly List<T> _values;
|
|
private Action<T>? _onValueChanged;
|
|
|
|
/// <summary>
|
|
/// The currently selected enum value.
|
|
/// </summary>
|
|
public T Value => _dropdown != null && _dropdown.index >= 0 && _dropdown.index < _values.Count
|
|
? _values[_dropdown.index]
|
|
: default;
|
|
|
|
/// <summary>
|
|
/// Queries a <see cref="DropdownField"/> by name from the root VisualElement,
|
|
/// populates it with enum names, and selects the default value.
|
|
/// </summary>
|
|
/// <param name="rootVisualElement">The root VisualElement loaded from the UXML bundle.</param>
|
|
/// <param name="fieldName">The name of the DropdownField in the UXML.</param>
|
|
/// <param name="defaultValue">The initial selected value. Defaults to the first enum member.</param>
|
|
public EnumDropdownBinder(VisualElement rootVisualElement, string fieldName, T? defaultValue = null)
|
|
{
|
|
_values = Enum.GetValues(typeof(T)).Cast<T>().ToList();
|
|
|
|
_dropdown = rootVisualElement.Q<DropdownField>(fieldName);
|
|
if (_dropdown == null)
|
|
{
|
|
Melon<RenderMod>.Logger.Error(
|
|
$"DropdownField '{fieldName}'을(를) 찾을 수 없습니다.");
|
|
return;
|
|
}
|
|
|
|
_dropdown.choices = _values.Select(v => v.ToString()).ToList();
|
|
|
|
// Register the callback BEFORE setting index so the initial selection fires it too
|
|
_dropdown.RegisterValueChangedCallback(_ =>
|
|
{
|
|
_onValueChanged?.Invoke(Value);
|
|
});
|
|
|
|
var initial = defaultValue ?? _values[0];
|
|
_dropdown.index = _values.IndexOf(initial);
|
|
}
|
|
|
|
/// <summary>
|
|
/// Registers a callback that fires when the selection changes, providing the new enum value.
|
|
/// </summary>
|
|
public void OnValueChanged(Action<T> callback)
|
|
{
|
|
_onValueChanged = callback;
|
|
|
|
// Fire immediately with current value so the caller gets the initial state
|
|
if (_dropdown != null)
|
|
{
|
|
callback(Value);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// Sets the selected enum value and updates the dropdown index.
|
|
/// </summary>
|
|
/// <param name="value">The enum value to set.</param>
|
|
public void SetValue(T value)
|
|
{
|
|
if (_dropdown == null) return;
|
|
int idx = _values.IndexOf(value);
|
|
if (idx >= 0)
|
|
{
|
|
_dropdown.index = idx;
|
|
}
|
|
}
|
|
}
|
|
}
|