585 lines
20 KiB
C#
585 lines
20 KiB
C#
#nullable enable
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// 드롭다운 메뉴 컴포넌트.
|
|
/// 여러 옵션 중 하나를 선택할 수 있는 UI 컨트롤입니다.
|
|
/// 선택된 항목은 체크 아이콘으로 표시됩니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>드롭다운(Dropdown)이란?</b></para>
|
|
/// <para>
|
|
/// 드롭다운은 클릭하면 펼쳐지는 옵션 목록에서 하나를 선택하는 UI 컴포넌트입니다.
|
|
/// 많은 옵션을 작은 공간에 담을 수 있어 화면 공간을 효율적으로 사용합니다.
|
|
/// 라디오 버튼과 비슷하지만, 옵션이 많을 때 더 적합합니다.
|
|
/// </para>
|
|
///
|
|
/// <para><b>주요 속성:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description><c>Label</c> - 드롭다운 라벨 텍스트</description></item>
|
|
/// <item><description><c>Choices</c> - 선택 가능한 옵션 목록 (쉼표로 구분된 문자열)</description></item>
|
|
/// <item><description><c>SelectedIndex</c> - 현재 선택된 인덱스 (0부터 시작, -1은 선택 안 됨)</description></item>
|
|
/// <item><description><c>SelectedValue</c> - 현재 선택된 텍스트 값 (읽기 전용)</description></item>
|
|
/// <item><description><c>Placeholder</c> - 선택되지 않았을 때 표시되는 텍스트</description></item>
|
|
/// <item><description><c>IsEnabled</c> - 활성화/비활성화 상태</description></item>
|
|
/// </list>
|
|
///
|
|
/// <para><b>주요 메서드:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description><c>SetOptions(List<string>)</c> - 전체 옵션 목록 교체</description></item>
|
|
/// <item><description><c>AddOption(string)</c> - 옵션 하나 추가</description></item>
|
|
/// <item><description><c>SetSelectedIndex(int, bool)</c> - 인덱스로 선택 (notify: 이벤트 발생 여부)</description></item>
|
|
/// <item><description><c>SetSelectedValue(string, bool)</c> - 값으로 선택 (notify: 이벤트 발생 여부)</description></item>
|
|
/// </list>
|
|
///
|
|
/// <para><b>주요 이벤트:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description><c>OnSelectionChanged</c> - 선택 변경 시 발생 (인덱스, 값 전달)</description></item>
|
|
/// </list>
|
|
///
|
|
/// <para><b>실제 활용 예시:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description>정렬 옵션 - 이름순, 날짜순, 크기순</description></item>
|
|
/// <item><description>언어 선택 - 한국어, English, 日本語</description></item>
|
|
/// <item><description>국가/지역 선택</description></item>
|
|
/// <item><description>해상도, 품질 설정</description></item>
|
|
/// <item><description>파일 형식 선택</description></item>
|
|
/// </list>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 국가 선택 드롭다운
|
|
/// var countryDropdown = new UTKDropdown();
|
|
/// countryDropdown.Label = "국가 선택";
|
|
/// countryDropdown.SetOptions(new List<string> { "한국", "미국", "일본", "중국" });
|
|
///
|
|
/// // 선택 변경 이벤트 (인덱스와 값 모두 전달)
|
|
/// countryDropdown.OnSelectionChanged += (index, value) => {
|
|
/// Debug.Log($"선택: [{index}] {value}");
|
|
/// };
|
|
///
|
|
/// // 생성자로 한 번에 설정
|
|
/// var sortDropdown = new UTKDropdown("정렬", new List<string> { "이름", "날짜", "크기" });
|
|
///
|
|
/// // 기본값 설정 (인덱스로)
|
|
/// sortDropdown.SelectedIndex = 0; // 첫 번째 항목 선택
|
|
///
|
|
/// // 기본값 설정 (값으로)
|
|
/// sortDropdown.SetSelectedValue("날짜");
|
|
///
|
|
/// // 동적으로 옵션 추가
|
|
/// countryDropdown.AddOption("독일");
|
|
///
|
|
/// // 이벤트 없이 값 변경 (초기화 시 유용)
|
|
/// sortDropdown.SetSelectedValue("크기", notify: false);
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code>
|
|
/// <!-- 기본 드롭다운 (쉼표로 구분) -->
|
|
/// <utk:UTKDropdown label="정렬" choices="이름,날짜,크기" />
|
|
///
|
|
/// <!-- 기본값 지정 (index로) -->
|
|
/// <utk:UTKDropdown label="언어"
|
|
/// choices="한국어,English,日本語"
|
|
/// index="0" />
|
|
///
|
|
/// <!-- 플레이스홀더 사용 -->
|
|
/// <utk:UTKDropdown label="국가"
|
|
/// choices="한국,미국,일본,중국"
|
|
/// placeholder="국가를 선택하세요" />
|
|
///
|
|
/// <!-- 비활성화 상태 -->
|
|
/// <utk:UTKDropdown label="선택" is-enabled="false"
|
|
/// choices="옵션1,옵션2,옵션3"
|
|
/// index="1" />
|
|
/// </code>
|
|
/// </example>
|
|
[UxmlElement]
|
|
public partial class UTKDropdown : VisualElement, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Dropdown/UTKDropdownUss";
|
|
private const string DEFAULT_PLACEHOLDER = "Select";
|
|
#endregion
|
|
|
|
#region Fields
|
|
private bool _disposed;
|
|
private Label? _labelElement;
|
|
private VisualElement? _inputContainer;
|
|
private Label? _displayLabel;
|
|
private VisualElement? _dropdownIconContainer;
|
|
private UTKLabel? _dropdownIcon;
|
|
private VisualElement? _popupContainer;
|
|
private ScrollView? _optionsScrollView;
|
|
|
|
private string _label = "";
|
|
private List<string> _choices = new();
|
|
private int _selectedIndex = -1;
|
|
private string _placeholder = DEFAULT_PLACEHOLDER;
|
|
private bool _isEnabled = true;
|
|
private bool _isPopupOpen;
|
|
|
|
private readonly StyleSheet? _loadedUss;
|
|
|
|
// 옵션 항목과 체크 아이콘 추적
|
|
private readonly List<(VisualElement container, UTKLabel checkIcon)> _optionItems = new();
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>선택 변경 이벤트 (선택된 인덱스, 선택된 값)</summary>
|
|
public event Action<int, string>? OnSelectionChanged;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>라벨 텍스트</summary>
|
|
[UxmlAttribute("label")]
|
|
public string Label
|
|
{
|
|
get => _label;
|
|
set
|
|
{
|
|
_label = value;
|
|
if (_labelElement != null)
|
|
{
|
|
_labelElement.text = value;
|
|
_labelElement.style.display = string.IsNullOrEmpty(value) ? DisplayStyle.None : DisplayStyle.Flex;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>선택 가능한 옵션 목록</summary>
|
|
[UxmlAttribute("choices")]
|
|
public string Choices
|
|
{
|
|
get => string.Join(",", _choices);
|
|
set
|
|
{
|
|
if (string.IsNullOrEmpty(value))
|
|
{
|
|
_choices.Clear();
|
|
}
|
|
else
|
|
{
|
|
_choices = new List<string>(value.Split(','));
|
|
}
|
|
RebuildOptions();
|
|
}
|
|
}
|
|
|
|
/// <summary>선택된 인덱스</summary>
|
|
[UxmlAttribute("index")]
|
|
public int SelectedIndex
|
|
{
|
|
get => _selectedIndex;
|
|
set => SetSelectedIndex(value, true);
|
|
}
|
|
|
|
/// <summary>선택된 값 (읽기 전용)</summary>
|
|
public string? SelectedValue => _selectedIndex >= 0 && _selectedIndex < _choices.Count ? _choices[_selectedIndex] : null;
|
|
|
|
/// <summary>플레이스홀더 텍스트</summary>
|
|
[UxmlAttribute("placeholder")]
|
|
public string Placeholder
|
|
{
|
|
get => _placeholder;
|
|
set
|
|
{
|
|
_placeholder = value;
|
|
UpdateDisplayText();
|
|
}
|
|
}
|
|
|
|
/// <summary>활성화 상태</summary>
|
|
[UxmlAttribute("is-enabled")]
|
|
public bool IsEnabled
|
|
{
|
|
get => _isEnabled;
|
|
set
|
|
{
|
|
_isEnabled = value;
|
|
SetEnabled(value);
|
|
EnableInClassList("utk-dropdown--disabled", !value);
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Constructor
|
|
public UTKDropdown() : base()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
_loadedUss = uss;
|
|
}
|
|
|
|
CreateUI();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
}
|
|
|
|
public UTKDropdown(string label, List<string>? options = null) : this()
|
|
{
|
|
Label = label;
|
|
if (options != null)
|
|
{
|
|
SetOptions(options);
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region UI Creation
|
|
private void CreateUI()
|
|
{
|
|
AddToClassList("utk-dropdown");
|
|
focusable = true;
|
|
|
|
// 라벨
|
|
_labelElement = new Label();
|
|
_labelElement.AddToClassList("utk-dropdown__label");
|
|
Add(_labelElement);
|
|
|
|
// 입력 컨테이너
|
|
_inputContainer = new VisualElement();
|
|
_inputContainer.AddToClassList("utk-dropdown__input");
|
|
Add(_inputContainer);
|
|
|
|
// 표시 라벨
|
|
_displayLabel = new Label(_placeholder);
|
|
_displayLabel.AddToClassList("utk-dropdown__display");
|
|
_displayLabel.AddToClassList("utk-dropdown__display--placeholder");
|
|
_inputContainer.Add(_displayLabel);
|
|
|
|
// 드롭다운 아이콘 컨테이너
|
|
_dropdownIconContainer = new VisualElement();
|
|
_dropdownIconContainer.AddToClassList("utk-dropdown__icon-container");
|
|
_inputContainer.Add(_dropdownIconContainer);
|
|
|
|
// 드롭다운 아이콘
|
|
_dropdownIcon = new UTKLabel(UTKMaterialIcons.ArrowDropDown, 24);
|
|
_dropdownIcon.AddToClassList("utk-dropdown__icon");
|
|
_dropdownIconContainer.Add(_dropdownIcon);
|
|
|
|
// 팝업 컨테이너
|
|
_popupContainer = new VisualElement();
|
|
_popupContainer.AddToClassList("utk-dropdown__popup");
|
|
_popupContainer.style.display = DisplayStyle.None;
|
|
Add(_popupContainer);
|
|
|
|
// 옵션 스크롤뷰
|
|
_optionsScrollView = new ScrollView(ScrollViewMode.Vertical);
|
|
_optionsScrollView.AddToClassList("utk-dropdown__options");
|
|
_popupContainer.Add(_optionsScrollView);
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
// 입력 컨테이너 클릭 시 팝업 토글
|
|
_inputContainer?.RegisterCallback<ClickEvent>(OnInputClicked);
|
|
|
|
// 외부 클릭 감지를 위한 루트 패널 이벤트
|
|
RegisterCallback<AttachToPanelEvent>(OnAttachedToPanel);
|
|
RegisterCallback<DetachFromPanelEvent>(OnDetachedFromPanel);
|
|
}
|
|
|
|
private void SubscribeToThemeChanges()
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
RegisterCallback<DetachFromPanelEvent>(_ =>
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
});
|
|
}
|
|
|
|
private void OnThemeChanged(UTKTheme theme)
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
#endregion
|
|
|
|
#region Event Handlers
|
|
private void OnInputClicked(ClickEvent evt)
|
|
{
|
|
if (!_isEnabled) return;
|
|
|
|
_isPopupOpen = !_isPopupOpen;
|
|
|
|
if (_popupContainer != null)
|
|
{
|
|
if (_isPopupOpen)
|
|
{
|
|
OpenPopup();
|
|
}
|
|
else
|
|
{
|
|
ClosePopup();
|
|
}
|
|
}
|
|
|
|
EnableInClassList("utk-dropdown--open", _isPopupOpen);
|
|
|
|
evt.StopPropagation();
|
|
}
|
|
|
|
private void OpenPopup()
|
|
{
|
|
if (_popupContainer == null || _inputContainer == null || panel == null) return;
|
|
|
|
// 아이콘 변경
|
|
if (_dropdownIcon is UTKLabel iconLabel)
|
|
{
|
|
iconLabel.SetMaterialIcon(UTKMaterialIcons.ArrowDropUp);
|
|
}
|
|
|
|
// 팝업을 루트로 이동
|
|
if (_popupContainer.parent != panel.visualTree)
|
|
{
|
|
_popupContainer.RemoveFromHierarchy();
|
|
panel.visualTree.Add(_popupContainer);
|
|
UTKThemeManager.Instance.ApplyThemeToElement(_popupContainer);
|
|
if (_loadedUss != null)
|
|
{
|
|
_popupContainer.styleSheets.Add(_loadedUss);
|
|
}
|
|
}
|
|
|
|
// 드롭다운의 월드 위치 계산
|
|
var inputBounds = _inputContainer.worldBound;
|
|
|
|
_popupContainer.style.position = Position.Absolute;
|
|
_popupContainer.style.left = inputBounds.x;
|
|
_popupContainer.style.top = inputBounds.yMax + 2; // 2px 간격
|
|
_popupContainer.style.width = inputBounds.width;
|
|
_popupContainer.style.display = DisplayStyle.Flex;
|
|
}
|
|
|
|
private void ClosePopup()
|
|
{
|
|
_isPopupOpen = false;
|
|
|
|
// 아이콘 복원
|
|
if (_dropdownIcon is UTKLabel iconLabel)
|
|
{
|
|
iconLabel.SetMaterialIcon(UTKMaterialIcons.ArrowDropDown);
|
|
}
|
|
|
|
if (_popupContainer != null)
|
|
{
|
|
_popupContainer.style.display = DisplayStyle.None;
|
|
|
|
// 팝업을 원래 위치(드롭다운 내부)로 되돌림
|
|
if (_popupContainer.parent != this)
|
|
{
|
|
_popupContainer.RemoveFromHierarchy();
|
|
Add(_popupContainer);
|
|
}
|
|
}
|
|
|
|
EnableInClassList("utk-dropdown--open", false);
|
|
}
|
|
|
|
private void OnAttachedToPanel(AttachToPanelEvent evt)
|
|
{
|
|
if (panel != null)
|
|
{
|
|
panel.visualTree.RegisterCallback<PointerDownEvent>(OnPanelPointerDown, TrickleDown.TrickleDown);
|
|
}
|
|
}
|
|
|
|
private void OnDetachedFromPanel(DetachFromPanelEvent evt)
|
|
{
|
|
if (panel != null)
|
|
{
|
|
panel.visualTree.UnregisterCallback<PointerDownEvent>(OnPanelPointerDown, TrickleDown.TrickleDown);
|
|
}
|
|
}
|
|
|
|
private void OnPanelPointerDown(PointerDownEvent evt)
|
|
{
|
|
if (!_isPopupOpen) return;
|
|
|
|
var target = evt.target as VisualElement;
|
|
if (target == null) return;
|
|
|
|
// 입력 컨테이너 클릭 확인
|
|
if (_inputContainer != null && target.FindCommonAncestor(_inputContainer) == _inputContainer)
|
|
{
|
|
return; // 입력 영역 클릭이면 무시
|
|
}
|
|
|
|
// 팝업 컨테이너 클릭 확인
|
|
if (_popupContainer != null && target.FindCommonAncestor(_popupContainer) == _popupContainer)
|
|
{
|
|
return; // 팝업 내부 클릭이면 무시
|
|
}
|
|
|
|
// 외부 클릭이면 팝업 닫기
|
|
ClosePopup();
|
|
}
|
|
|
|
private void OnOptionClicked(int index)
|
|
{
|
|
SetSelectedIndex(index, true);
|
|
ClosePopup();
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
/// <summary>
|
|
/// 옵션 목록 설정
|
|
/// </summary>
|
|
public void SetOptions(List<string> options)
|
|
{
|
|
_choices = options ?? new List<string>();
|
|
RebuildOptions();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 옵션 추가
|
|
/// </summary>
|
|
public void AddOption(string option)
|
|
{
|
|
_choices.Add(option);
|
|
RebuildOptions();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 선택된 인덱스 설정
|
|
/// </summary>
|
|
public void SetSelectedIndex(int index, bool notify)
|
|
{
|
|
if (index < -1 || index >= _choices.Count) return;
|
|
if (_selectedIndex == index) return;
|
|
|
|
_selectedIndex = index;
|
|
UpdateDisplayText();
|
|
UpdateCheckIcons();
|
|
|
|
if (notify && _selectedIndex >= 0)
|
|
{
|
|
OnSelectionChanged?.Invoke(_selectedIndex, _choices[_selectedIndex]);
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 값으로 선택
|
|
/// </summary>
|
|
public void SetSelectedValue(string? selectedValue, bool notify = true)
|
|
{
|
|
if (selectedValue == null)
|
|
{
|
|
SetSelectedIndex(-1, notify);
|
|
return;
|
|
}
|
|
|
|
var idx = _choices.IndexOf(selectedValue);
|
|
if (idx >= 0)
|
|
{
|
|
SetSelectedIndex(idx, notify);
|
|
}
|
|
}
|
|
|
|
private void RebuildOptions()
|
|
{
|
|
if (_optionsScrollView == null) return;
|
|
|
|
_optionItems.Clear();
|
|
_optionsScrollView.Clear();
|
|
|
|
for (int i = 0; i < _choices.Count; i++)
|
|
{
|
|
var index = i; // 클로저 캡처 방지
|
|
var optionContainer = new VisualElement();
|
|
optionContainer.AddToClassList("utk-dropdown__option");
|
|
|
|
// 체크 아이콘 (선택된 항목 표시)
|
|
var checkIcon = new UTKLabel(UTKMaterialIcons.Check, 16);
|
|
checkIcon.AddToClassList("utk-dropdown__check-icon");
|
|
checkIcon.style.display = _selectedIndex == i ? DisplayStyle.Flex : DisplayStyle.None;
|
|
optionContainer.Add(checkIcon);
|
|
|
|
// 옵션 라벨
|
|
var optionLabel = new Label(_choices[i]);
|
|
optionLabel.AddToClassList("utk-dropdown__option-label");
|
|
optionContainer.Add(optionLabel);
|
|
|
|
// 클릭 이벤트
|
|
optionContainer.RegisterCallback<ClickEvent>(evt =>
|
|
{
|
|
OnOptionClicked(index);
|
|
evt.StopPropagation();
|
|
});
|
|
|
|
// 마우스 호버 이벤트
|
|
optionContainer.RegisterCallback<MouseEnterEvent>(_ =>
|
|
{
|
|
optionContainer.AddToClassList("utk-dropdown__option--hover");
|
|
});
|
|
optionContainer.RegisterCallback<MouseLeaveEvent>(_ =>
|
|
{
|
|
optionContainer.RemoveFromClassList("utk-dropdown__option--hover");
|
|
});
|
|
|
|
_optionItems.Add((optionContainer, checkIcon));
|
|
_optionsScrollView.Add(optionContainer);
|
|
}
|
|
|
|
UpdateDisplayText();
|
|
}
|
|
|
|
private void UpdateDisplayText()
|
|
{
|
|
if (_displayLabel == null) return;
|
|
|
|
if (_selectedIndex < 0 || _selectedIndex >= _choices.Count)
|
|
{
|
|
_displayLabel.text = _placeholder;
|
|
_displayLabel.AddToClassList("utk-dropdown__display--placeholder");
|
|
}
|
|
else
|
|
{
|
|
_displayLabel.text = _choices[_selectedIndex];
|
|
_displayLabel.RemoveFromClassList("utk-dropdown__display--placeholder");
|
|
}
|
|
}
|
|
|
|
private void UpdateCheckIcons()
|
|
{
|
|
for (int i = 0; i < _optionItems.Count; i++)
|
|
{
|
|
var (_, checkIcon) = _optionItems[i];
|
|
checkIcon.style.display = _selectedIndex == i ? DisplayStyle.Flex : DisplayStyle.None;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
OnSelectionChanged = null;
|
|
|
|
_inputContainer?.UnregisterCallback<ClickEvent>(OnInputClicked);
|
|
|
|
if (panel != null)
|
|
{
|
|
panel.visualTree.UnregisterCallback<PointerDownEvent>(OnPanelPointerDown);
|
|
}
|
|
|
|
_optionItems.Clear();
|
|
}
|
|
#endregion
|
|
}
|
|
}
|