594 lines
19 KiB
C#
594 lines
19 KiB
C#
#nullable enable
|
|
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// 숫자 입력 필드에 위/아래 스테퍼 버튼이 붙은 컴포넌트.
|
|
/// TextInput 오른쪽에 위, 아래 버튼이 세로로 배치됩니다.
|
|
/// 키보드 화살표, 마우스 휠, 버튼 클릭으로 값을 조절할 수 있습니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>UTKIntStepper란?</b></para>
|
|
/// <para>숫자를 편리하게 증감할 수 있는 입력 컴포넌트입니다.</para>
|
|
/// <list type="bullet">
|
|
/// <item><description><b>버튼 클릭</b>: ▲/▼ 버튼으로 값 증감</description></item>
|
|
/// <item><description><b>키보드</b>: ↑/↓ 화살표 키로 값 증감</description></item>
|
|
/// <item><description><b>마우스 휠</b>: 호버 상태에서 휠로 값 조절</description></item>
|
|
/// <item><description><b>직접 입력</b>: 텍스트 필드에 숫자 직접 입력</description></item>
|
|
/// </list>
|
|
/// <para><b>주요 기능:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description>최소/최대값 제한 (MinValue, MaxValue)</description></item>
|
|
/// <item><description>증감 단위 설정 (Step)</description></item>
|
|
/// <item><description>순환 모드 (WrapAround) - 최대에서 최소로, 최소에서 최대로</description></item>
|
|
/// <item><description>Validation 함수를 통한 입력 검증 (FocusOut 시 자동 호출)</description></item>
|
|
/// <item><description>에러 상태 시 붉은 외곽선 + 에러 메시지 표시</description></item>
|
|
/// </list>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 기본 스테퍼 생성
|
|
/// var stepper = new UTKIntStepper();
|
|
/// stepper.MinValue = 0;
|
|
/// stepper.MaxValue = 100;
|
|
/// stepper.Value = 50;
|
|
/// stepper.Step = 5; // 5씩 증감
|
|
///
|
|
/// // 값 변경 이벤트
|
|
/// stepper.OnValueChanged += (value) => {
|
|
/// Debug.Log($"현재 값: {value}");
|
|
/// };
|
|
///
|
|
/// // 범위와 초기값을 지정하는 생성자
|
|
/// var volumeStepper = new UTKIntStepper(0, 100, 80, 10); // min, max, initial, step
|
|
///
|
|
/// // 순환 모드 활성화 (100 → 0, 0 → 100)
|
|
/// stepper.WrapAround = true;
|
|
///
|
|
/// // 프로그래밍 방식으로 값 변경
|
|
/// stepper.Increment(); // Step만큼 증가
|
|
/// stepper.Decrement(); // Step만큼 감소
|
|
/// stepper.SetValue(75); // 직접 설정
|
|
///
|
|
/// // 읽기 전용 (사용자가 수정할 수 없음)
|
|
/// var readOnlyStepper = new UTKIntStepper(0, 100, 50, 1);
|
|
/// readOnlyStepper.IsReadOnly = true;
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code><![CDATA[
|
|
/// <!-- 기본 스테퍼 -->
|
|
/// <utk:UTKIntStepper value="50" min-value="0" max-value="100" />
|
|
///
|
|
/// <!-- 증감 단위 설정 -->
|
|
/// <utk:UTKIntStepper value="10" step="5" />
|
|
///
|
|
/// <!-- 순환 모드 -->
|
|
/// <utk:UTKIntStepper value="1" min-value="1" max-value="12" wrap-around="true" />
|
|
///
|
|
/// <!-- 읽기 전용 -->
|
|
/// <utk:UTKIntStepper value="50" is-readonly="true" />
|
|
/// ]]></code>
|
|
/// <para><b>실제 활용 예시 (월 선택기):</b></para>
|
|
/// <code>
|
|
/// // 월 선택 스테퍼 (1~12 순환)
|
|
/// var monthStepper = new UTKIntStepper(1, 12, DateTime.Now.Month, 1);
|
|
/// monthStepper.WrapAround = true; // 12월 다음 1월, 1월 이전 12월
|
|
/// monthStepper.OnValueChanged += (month) => {
|
|
/// UpdateCalendar(month);
|
|
/// };
|
|
/// </code>
|
|
/// <para><b>Validation (입력 검증):</b></para>
|
|
/// <code>
|
|
/// var monthStepper = new UTKIntStepper(1, 12, 1, 1);
|
|
/// monthStepper.ErrorMessage = "유효하지 않은 월입니다.";
|
|
/// monthStepper.Validation = () => monthStepper.Value >= 1 && monthStepper.Value <= 12;
|
|
///
|
|
/// bool isValid = monthStepper.Validate();
|
|
/// monthStepper.ClearError();
|
|
/// </code>
|
|
/// </example>
|
|
[UxmlElement]
|
|
public partial class UTKIntStepper : VisualElement, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Input/UTKIntStepper";
|
|
#endregion
|
|
|
|
#region UXML Attributes
|
|
[UxmlAttribute("value")]
|
|
public int Value
|
|
{
|
|
get => _value;
|
|
set => SetValue(value);
|
|
}
|
|
|
|
[UxmlAttribute("min-value")]
|
|
public int MinValue
|
|
{
|
|
get => _minValue;
|
|
set
|
|
{
|
|
_minValue = value;
|
|
ClampValue();
|
|
}
|
|
}
|
|
|
|
[UxmlAttribute("max-value")]
|
|
public int MaxValue
|
|
{
|
|
get => _maxValue;
|
|
set
|
|
{
|
|
_maxValue = value;
|
|
ClampValue();
|
|
}
|
|
}
|
|
|
|
[UxmlAttribute("step")]
|
|
public int Step
|
|
{
|
|
get => _step;
|
|
set => _step = Math.Max(1, value);
|
|
}
|
|
|
|
[UxmlAttribute("wrap-around")]
|
|
public bool WrapAround
|
|
{
|
|
get => _wrapAround;
|
|
set => _wrapAround = value;
|
|
}
|
|
|
|
/// <summary>읽기 전용 상태. true일 때 사용자가 값을 수정할 수 없음</summary>
|
|
[UxmlAttribute("is-readonly")]
|
|
public bool IsReadOnly
|
|
{
|
|
get => _isReadOnly;
|
|
set
|
|
{
|
|
_isReadOnly = value;
|
|
UpdateReadOnlyState();
|
|
EnableInClassList("utk-number-stepper--readonly", value);
|
|
}
|
|
}
|
|
|
|
/// <summary>에러 메시지. 비어있지 않으면 에러 상태로 표시</summary>
|
|
[UxmlAttribute("error-message")]
|
|
public string ErrorMessage
|
|
{
|
|
get => _errorMessage;
|
|
set
|
|
{
|
|
_errorMessage = value;
|
|
var hasError = !string.IsNullOrEmpty(value);
|
|
EnableInClassList("utk-number-stepper--error", hasError);
|
|
UpdateErrorLabel(hasError ? value : null);
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Fields
|
|
private bool _disposed;
|
|
private bool _isReadOnly;
|
|
private int _value;
|
|
private int _minValue = int.MinValue;
|
|
private int _maxValue = int.MaxValue;
|
|
private int _step = 1;
|
|
private bool _wrapAround;
|
|
private bool _isUpdating;
|
|
private bool _isHovered;
|
|
|
|
private string _errorMessage = "";
|
|
private Func<bool>? _validation;
|
|
private Label? _errorLabel;
|
|
|
|
private TextField? _textField;
|
|
private Button? _upButton;
|
|
private Button? _downButton;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>검증 함수. FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시</summary>
|
|
public Func<bool>? Validation
|
|
{
|
|
get => _validation;
|
|
set => _validation = value;
|
|
}
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>값이 변경될 때 발생</summary>
|
|
public event Action<int>? OnValueChanged;
|
|
|
|
/// <summary>Tab 키가 눌렸을 때 발생 (다음 요소로 포커스 이동용)</summary>
|
|
public event Action? OnTabPressed;
|
|
|
|
/// <summary>Shift+Tab 키가 눌렸을 때 발생 (이전 요소로 포커스 이동용)</summary>
|
|
public event Action? OnShiftTabPressed;
|
|
#endregion
|
|
|
|
#region Constructor
|
|
|
|
public UTKIntStepper()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
LoadStyleSheet();
|
|
CreateUI();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
}
|
|
|
|
public UTKIntStepper(bool isReadOnly = false): this()
|
|
{
|
|
_isReadOnly = isReadOnly;
|
|
}
|
|
|
|
public UTKIntStepper(int minValue, int maxValue, int initialValue = 0, int step = 1, bool isReadOnly = false): this()
|
|
{
|
|
_isReadOnly = isReadOnly;
|
|
_minValue = minValue;
|
|
_maxValue = maxValue;
|
|
_step = Math.Max(1, step);
|
|
_value = Mathf.Clamp(initialValue, minValue, maxValue);
|
|
}
|
|
|
|
private void LoadStyleSheet()
|
|
{
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
}
|
|
}
|
|
|
|
private void SubscribeToThemeChanges()
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
RegisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
RegisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
}
|
|
|
|
private void OnAttachToPanelForTheme(AttachToPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
|
|
private void OnDetachFromPanelForTheme(DetachFromPanelEvent evt)
|
|
{
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
}
|
|
|
|
private void OnThemeChanged(UTKTheme theme)
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
}
|
|
#endregion
|
|
|
|
#region Public Methods
|
|
public void SetValue(int newValue, bool notify = true)
|
|
{
|
|
int clampedValue = ClampValueInternal(newValue);
|
|
if (_value != clampedValue)
|
|
{
|
|
_value = clampedValue;
|
|
UpdateDisplay();
|
|
if (notify)
|
|
{
|
|
OnValueChanged?.Invoke(_value);
|
|
RunValidation();
|
|
}
|
|
}
|
|
}
|
|
|
|
public void Increment()
|
|
{
|
|
if (_wrapAround && _value + _step > _maxValue)
|
|
{
|
|
SetValue(_minValue);
|
|
}
|
|
else
|
|
{
|
|
SetValue(_value + _step);
|
|
}
|
|
}
|
|
|
|
public void Decrement()
|
|
{
|
|
if (_wrapAround && _value - _step < _minValue)
|
|
{
|
|
SetValue(_maxValue);
|
|
}
|
|
else
|
|
{
|
|
SetValue(_value - _step);
|
|
}
|
|
}
|
|
|
|
public void SetRange(int min, int max)
|
|
{
|
|
_minValue = min;
|
|
_maxValue = max;
|
|
ClampValue();
|
|
}
|
|
|
|
/// <summary>컴포넌트의 활성화 상태를 설정합니다.</summary>
|
|
public new void SetEnabled(bool enabled)
|
|
{
|
|
base.SetEnabled(enabled);
|
|
EnableInClassList("utk-number-stepper--disabled", !enabled);
|
|
}
|
|
|
|
/// <summary>텍스트 필드에 포커스를 설정합니다.</summary>
|
|
public new void Focus()
|
|
{
|
|
_textField?.Focus();
|
|
}
|
|
|
|
/// <summary>강제로 Validation을 실행하여 에러 상태를 업데이트합니다.</summary>
|
|
public bool Validate()
|
|
{
|
|
return RunValidation();
|
|
}
|
|
|
|
/// <summary>에러 상태를 수동으로 해제합니다.</summary>
|
|
public void ClearError()
|
|
{
|
|
ErrorMessage = "";
|
|
}
|
|
#endregion
|
|
|
|
#region Private Methods - UI Creation
|
|
private void CreateUI()
|
|
{
|
|
AddToClassList("utk-number-stepper");
|
|
|
|
// Text Field
|
|
_textField = new TextField { name = "stepper-input" };
|
|
_textField.AddToClassList("utk-number-stepper__input");
|
|
_textField.isReadOnly = _isReadOnly;
|
|
|
|
// TextField 내부 input 스타일링
|
|
_textField.RegisterCallback<AttachToPanelEvent>(_ =>
|
|
{
|
|
var input = _textField.Q<VisualElement>("unity-text-input");
|
|
if (input != null)
|
|
{
|
|
input.AddToClassList("utk-number-stepper__text-input");
|
|
}
|
|
});
|
|
|
|
Add(_textField);
|
|
|
|
// Button Container (위/아래 버튼을 세로로 배치)
|
|
var buttonContainer = new VisualElement { name = "stepper-buttons" };
|
|
buttonContainer.AddToClassList("utk-number-stepper__buttons");
|
|
|
|
// Up Button
|
|
_upButton = new Button { name = "stepper-up", text = UTKMaterialIcons.KeyboardArrowUp };
|
|
_upButton.AddToClassList("utk-number-stepper__btn");
|
|
_upButton.AddToClassList("utk-number-stepper__btn--up");
|
|
_upButton.SetEnabled(!_isReadOnly);
|
|
UTKMaterialIcons.ApplyIconStyle(_upButton, 14);
|
|
buttonContainer.Add(_upButton);
|
|
|
|
// Down Button
|
|
_downButton = new Button { name = "stepper-down", text = UTKMaterialIcons.KeyboardArrowDown };
|
|
_downButton.AddToClassList("utk-number-stepper__btn");
|
|
_downButton.AddToClassList("utk-number-stepper__btn--down");
|
|
_downButton.SetEnabled(!_isReadOnly);
|
|
UTKMaterialIcons.ApplyIconStyle(_downButton, 14);
|
|
buttonContainer.Add(_downButton);
|
|
|
|
Add(buttonContainer);
|
|
|
|
UpdateDisplay();
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
_upButton?.RegisterCallback<ClickEvent>(OnUpButtonClick);
|
|
_downButton?.RegisterCallback<ClickEvent>(OnDownButtonClick);
|
|
|
|
_textField?.RegisterCallback<ChangeEvent<string>>(OnTextFieldChanged);
|
|
_textField?.RegisterCallback<KeyDownEvent>(OnTextFieldKeyDown, TrickleDown.TrickleDown);
|
|
_textField?.RegisterCallback<FocusOutEvent>(OnTextFieldFocusOut);
|
|
|
|
RegisterCallback<MouseEnterEvent>(OnMouseEnter);
|
|
RegisterCallback<MouseLeaveEvent>(OnMouseLeave);
|
|
RegisterCallback<WheelEvent>(OnWheelEvent);
|
|
}
|
|
#endregion
|
|
|
|
#region Event Handlers
|
|
private void OnUpButtonClick(ClickEvent evt) => Increment();
|
|
private void OnDownButtonClick(ClickEvent evt) => Decrement();
|
|
|
|
private void OnTextFieldChanged(ChangeEvent<string> evt)
|
|
{
|
|
if (_isUpdating) return;
|
|
|
|
if (int.TryParse(evt.newValue, out int parsed))
|
|
{
|
|
SetValue(parsed);
|
|
}
|
|
else
|
|
{
|
|
// 유효하지 않은 입력이면 이전 값으로 복원
|
|
UpdateDisplay();
|
|
}
|
|
}
|
|
|
|
private void OnTextFieldFocusOut(FocusOutEvent evt)
|
|
{
|
|
RunValidation();
|
|
}
|
|
|
|
private void OnTextFieldKeyDown(KeyDownEvent evt)
|
|
{
|
|
if (evt.keyCode == KeyCode.UpArrow)
|
|
{
|
|
Increment();
|
|
evt.StopPropagation();
|
|
}
|
|
else if (evt.keyCode == KeyCode.DownArrow)
|
|
{
|
|
Decrement();
|
|
evt.StopPropagation();
|
|
}
|
|
else if (evt.keyCode == KeyCode.Tab)
|
|
{
|
|
if (evt.shiftKey && OnShiftTabPressed != null)
|
|
{
|
|
OnShiftTabPressed.Invoke();
|
|
evt.StopImmediatePropagation();
|
|
}
|
|
else if (!evt.shiftKey && OnTabPressed != null)
|
|
{
|
|
OnTabPressed.Invoke();
|
|
evt.StopImmediatePropagation();
|
|
}
|
|
}
|
|
}
|
|
|
|
private void OnMouseEnter(MouseEnterEvent evt) => _isHovered = true;
|
|
private void OnMouseLeave(MouseLeaveEvent evt) => _isHovered = false;
|
|
|
|
private void OnWheelEvent(WheelEvent evt)
|
|
{
|
|
if (!_isHovered) return;
|
|
|
|
if (evt.delta.y < 0)
|
|
{
|
|
Increment();
|
|
}
|
|
else if (evt.delta.y > 0)
|
|
{
|
|
Decrement();
|
|
}
|
|
evt.StopPropagation();
|
|
}
|
|
#endregion
|
|
|
|
#region Private Methods - Logic
|
|
private void UpdateDisplay()
|
|
{
|
|
if (_textField == null) return;
|
|
|
|
_isUpdating = true;
|
|
_textField.value = _value.ToString();
|
|
_isUpdating = false;
|
|
}
|
|
|
|
private void ClampValue()
|
|
{
|
|
SetValue(_value, notify: false);
|
|
}
|
|
|
|
private int ClampValueInternal(int value)
|
|
{
|
|
return Mathf.Clamp(value, _minValue, _maxValue);
|
|
}
|
|
|
|
private void UpdateReadOnlyState()
|
|
{
|
|
if (_textField != null)
|
|
{
|
|
_textField.isReadOnly = _isReadOnly;
|
|
}
|
|
|
|
if (_upButton != null)
|
|
{
|
|
_upButton.SetEnabled(!_isReadOnly);
|
|
}
|
|
|
|
if (_downButton != null)
|
|
{
|
|
_downButton.SetEnabled(!_isReadOnly);
|
|
}
|
|
}
|
|
|
|
private bool RunValidation()
|
|
{
|
|
if (_validation == null) return true;
|
|
|
|
var isValid = _validation.Invoke();
|
|
if (isValid)
|
|
{
|
|
EnableInClassList("utk-number-stepper--error", false);
|
|
UpdateErrorLabel(null);
|
|
}
|
|
else
|
|
{
|
|
EnableInClassList("utk-number-stepper--error", true);
|
|
UpdateErrorLabel(_errorMessage);
|
|
}
|
|
return isValid;
|
|
}
|
|
|
|
private void UpdateErrorLabel(string? message)
|
|
{
|
|
if (string.IsNullOrEmpty(message))
|
|
{
|
|
if (_errorLabel != null)
|
|
{
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
}
|
|
return;
|
|
}
|
|
|
|
if (_errorLabel == null)
|
|
{
|
|
_errorLabel = new Label();
|
|
_errorLabel.AddToClassList("utk-number-stepper__error-message");
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
Add(_errorLabel);
|
|
}
|
|
|
|
_errorLabel.text = message;
|
|
_errorLabel.style.display = DisplayStyle.Flex;
|
|
}
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
|
|
// 이벤트 콜백 해제
|
|
_upButton?.UnregisterCallback<ClickEvent>(OnUpButtonClick);
|
|
_downButton?.UnregisterCallback<ClickEvent>(OnDownButtonClick);
|
|
|
|
_textField?.UnregisterCallback<ChangeEvent<string>>(OnTextFieldChanged);
|
|
_textField?.UnregisterCallback<KeyDownEvent>(OnTextFieldKeyDown, TrickleDown.TrickleDown);
|
|
_textField?.UnregisterCallback<FocusOutEvent>(OnTextFieldFocusOut);
|
|
|
|
UnregisterCallback<MouseEnterEvent>(OnMouseEnter);
|
|
UnregisterCallback<MouseLeaveEvent>(OnMouseLeave);
|
|
UnregisterCallback<WheelEvent>(OnWheelEvent);
|
|
|
|
// 이벤트 null 처리
|
|
OnValueChanged = null;
|
|
OnTabPressed = null;
|
|
OnShiftTabPressed = null;
|
|
|
|
// UI 참조 정리
|
|
_validation = null;
|
|
_errorLabel = null;
|
|
_textField = null;
|
|
_upButton = null;
|
|
_downButton = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|