485 lines
16 KiB
C#
485 lines
16 KiB
C#
#nullable enable
|
|
using System;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// 입력 필드 컴포넌트.
|
|
/// Unity TextField를 래핑하여 커스텀 스타일을 적용합니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>주요 기능:</b></para>
|
|
/// <list type="bullet">
|
|
/// <item><description>플레이스홀더, 비밀번호, 멀티라인 지원</description></item>
|
|
/// <item><description>스타일 변형 (Default, Filled, Outlined)</description></item>
|
|
/// <item><description>Validation 함수를 통한 입력 검증 (Submit/FocusOut 시 자동 호출)</description></item>
|
|
/// <item><description>에러 상태 시 붉은 외곽선 + 에러 메시지 표시</description></item>
|
|
/// </list>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 기본 입력 필드
|
|
/// var input = new UTKInputField();
|
|
/// input.label = "이름";
|
|
/// input.Placeholder = "이름을 입력하세요";
|
|
/// input.OnValueChanged += (value) => Debug.Log($"입력값: {value}");
|
|
///
|
|
/// // 비밀번호 입력 필드
|
|
/// var password = new UTKInputField();
|
|
/// password.label = "비밀번호";
|
|
/// password.isPasswordField = true;
|
|
///
|
|
/// // 변형 스타일
|
|
/// input.Variant = UTKInputField.InputFieldVariant.Outlined;
|
|
/// </code>
|
|
/// <para><b>Validation (입력 검증):</b></para>
|
|
/// <code>
|
|
/// // 검증 함수 설정 (Func<bool>)
|
|
/// var emailInput = new UTKInputField("이메일", "example@email.com");
|
|
/// emailInput.ErrorMessage = "올바른 이메일 형식이 아닙니다.";
|
|
/// emailInput.Validation = () => emailInput.Value.Contains("@");
|
|
/// // → Submit(Enter) 또는 FocusOut 시 자동으로 검증
|
|
/// // → 실패 시 붉은 외곽선 + 에러 메시지 표시, 통과 시 자동 해제
|
|
///
|
|
/// // 필수 입력 검증
|
|
/// var nameInput = new UTKInputField("이름");
|
|
/// nameInput.ErrorMessage = "이름은 필수 항목입니다.";
|
|
/// nameInput.Validation = () => !string.IsNullOrWhiteSpace(nameInput.Value);
|
|
///
|
|
/// // 강제 검증 호출 (예: 폼 제출 버튼 클릭 시)
|
|
/// bool isValid = nameInput.Validate();
|
|
/// if (!isValid) return; // 검증 실패
|
|
///
|
|
/// // 에러 수동 해제
|
|
/// nameInput.ClearError();
|
|
///
|
|
/// // 에러 메시지 직접 설정 (Validation 없이)
|
|
/// input.ErrorMessage = "서버 오류가 발생했습니다.";
|
|
/// input.ErrorMessage = ""; // 오류 제거
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code><![CDATA[
|
|
/// <ui:UXML xmlns:utk="UVC.UIToolkit">
|
|
/// <!-- 기본 입력 필드 -->
|
|
/// <utk:UTKInputField label="이름" />
|
|
///
|
|
/// <!-- 플레이스홀더 -->
|
|
/// <utk:UTKInputField label="이메일" placeholder="example@email.com" />
|
|
///
|
|
/// <!-- 비밀번호 필드 -->
|
|
/// <utk:UTKInputField label="비밀번호" is-password-field="true" />
|
|
///
|
|
/// <!-- 여러 줄 입력 -->
|
|
/// <utk:UTKInputField label="설명" multiline="true" />
|
|
///
|
|
/// <!-- 에러 메시지 (C#에서 Validation 설정 권장) -->
|
|
/// <utk:UTKInputField label="이메일" error-message="올바른 이메일 형식이 아닙니다." />
|
|
///
|
|
/// <!-- 비활성화 -->
|
|
/// <utk:UTKInputField label="읽기전용" is-enabled="false" value="수정 불가" />
|
|
///
|
|
/// <!-- label min-width 설정 -->
|
|
/// <utk:UTKInputField label="이름" label-min-width="120" />
|
|
/// </ui:UXML>
|
|
/// ]]></code>
|
|
/// <para><b>Label Min-Width 설정:</b></para>
|
|
/// <code>
|
|
/// // label이 있을 때 .unity-label의 min-width를 설정
|
|
/// var input = new UTKInputField("이름");
|
|
/// input.LabelMinWidth = 120f; // 120px
|
|
/// // -1이면 미설정 (기본값)
|
|
/// </code>
|
|
/// </example>
|
|
[UxmlElement]
|
|
public partial class UTKInputField : TextField, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Input/UTKInputField";
|
|
#endregion
|
|
|
|
#region Fields
|
|
private bool _disposed;
|
|
private bool _isEnabled = true;
|
|
private string _errorMessage = "";
|
|
private float _labelMinWidth = -1f;
|
|
private InputFieldVariant _variant = InputFieldVariant.Default;
|
|
private Func<bool>? _validation;
|
|
private Label? _errorLabel;
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>값 변경 이벤트</summary>
|
|
public event Action<string>? OnValueChanged;
|
|
/// <summary>포커스 이벤트</summary>
|
|
public event Action? OnFocused;
|
|
/// <summary>포커스 해제 이벤트</summary>
|
|
public event Action? OnBlurred;
|
|
/// <summary>엔터 키 이벤트</summary>
|
|
public event Action<string>? OnSubmit;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>입력 값</summary>
|
|
public string Value
|
|
{
|
|
get => value;
|
|
set => SetValue(value, true);
|
|
}
|
|
|
|
/// <summary>플레이스홀더 텍스트</summary>
|
|
[UxmlAttribute("placeholder")]
|
|
public string Placeholder
|
|
{
|
|
get => textEdition.placeholder;
|
|
set => textEdition.placeholder = value;
|
|
}
|
|
|
|
/// <summary>에러 메시지. 비어있지 않으면 에러 상태로 표시</summary>
|
|
[UxmlAttribute("error-message")]
|
|
public string ErrorMessage
|
|
{
|
|
get => _errorMessage;
|
|
set
|
|
{
|
|
_errorMessage = value;
|
|
var hasError = !string.IsNullOrEmpty(value);
|
|
EnableInClassList("utk-input--error", hasError);
|
|
UpdateErrorLabel(hasError ? value : null);
|
|
}
|
|
}
|
|
|
|
/// <summary>검증 함수. Submit/FocusOut 시 호출되어 false 반환 시 ErrorMessage 표시</summary>
|
|
public Func<bool>? Validation
|
|
{
|
|
get => _validation;
|
|
set => _validation = value;
|
|
}
|
|
|
|
/// <summary>활성화 상태</summary>
|
|
[UxmlAttribute("is-enabled")]
|
|
public bool IsEnabled
|
|
{
|
|
get => _isEnabled;
|
|
set
|
|
{
|
|
_isEnabled = value;
|
|
SetEnabled(value);
|
|
EnableInClassList("utk-input--disabled", !value);
|
|
}
|
|
}
|
|
|
|
/// <summary>label이 있을 때 .unity-label의 min-width (px). -1이면 미설정</summary>
|
|
[UxmlAttribute("label-min-width")]
|
|
public float LabelMinWidth
|
|
{
|
|
get => _labelMinWidth;
|
|
set
|
|
{
|
|
_labelMinWidth = value;
|
|
ApplyLabelMinWidth();
|
|
}
|
|
}
|
|
|
|
/// <summary>읽기 전용</summary>
|
|
public new bool isReadOnly
|
|
{
|
|
get => base.isReadOnly;
|
|
set
|
|
{
|
|
base.isReadOnly = value;
|
|
EnableInClassList("utk-input--readonly", value);
|
|
}
|
|
}
|
|
|
|
/// <summary>멀티라인 모드</summary>
|
|
public new bool multiline
|
|
{
|
|
get => base.multiline;
|
|
set
|
|
{
|
|
base.multiline = value;
|
|
EnableInClassList("utk-input--multiline", value);
|
|
}
|
|
}
|
|
|
|
/// <summary>스타일 변형</summary>
|
|
[UxmlAttribute("variant")]
|
|
public InputFieldVariant Variant
|
|
{
|
|
get => _variant;
|
|
set
|
|
{
|
|
_variant = value;
|
|
UpdateVariant();
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Enums
|
|
public enum InputFieldVariant
|
|
{
|
|
Default,
|
|
Filled,
|
|
Outlined
|
|
}
|
|
#endregion
|
|
|
|
#region Constructor
|
|
public UTKInputField() : base()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
}
|
|
|
|
SetupStyles();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
|
|
// UXML에서 로드될 때 속성이 설정된 후 UI 갱신
|
|
// Unity 6의 소스 생성기는 Deserialize에서 필드에 직접 값을 할당하므로
|
|
// AttachToPanelEvent를 사용하여 패널에 연결된 후 UI를 갱신
|
|
RegisterCallback<AttachToPanelEvent>(OnAttachToPanel);
|
|
}
|
|
|
|
public UTKInputField(string label, string placeholder = "") : this()
|
|
{
|
|
this.label = label;
|
|
Placeholder = placeholder;
|
|
}
|
|
#endregion
|
|
|
|
#region Setup
|
|
private void SetupStyles()
|
|
{
|
|
AddToClassList("utk-input");
|
|
UpdateVariant();
|
|
|
|
// label 설정 후 LabelMinWidth 적용
|
|
schedule.Execute(() => ApplyLabelMinWidth());
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
RegisterCallback<ChangeEvent<string>>(OnTextValueChanged);
|
|
RegisterCallback<FocusInEvent>(OnFocusIn);
|
|
RegisterCallback<FocusOutEvent>(OnFocusOut);
|
|
RegisterCallback<KeyDownEvent>(OnKeyDown, TrickleDown.TrickleDown);
|
|
}
|
|
|
|
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);
|
|
}
|
|
|
|
private void ApplyLabelMinWidth()
|
|
{
|
|
if (string.IsNullOrEmpty(label)) return;
|
|
var labelElement = this.Q<Label>(className: "unity-label");
|
|
if (labelElement == null) return;
|
|
|
|
if (_labelMinWidth >= 0)
|
|
{
|
|
labelElement.style.minWidth = _labelMinWidth;
|
|
}
|
|
else
|
|
{
|
|
labelElement.style.minWidth = StyleKeyword.Null;
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Event Handlers
|
|
private void OnAttachToPanel(AttachToPanelEvent evt)
|
|
{
|
|
// UXML 속성이 설정된 후 한 번만 UI 갱신
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanel);
|
|
UpdateVariant();
|
|
|
|
// IsEnabled 상태 적용
|
|
SetEnabled(_isEnabled);
|
|
EnableInClassList("utk-input--disabled", !_isEnabled);
|
|
}
|
|
|
|
private void OnTextValueChanged(ChangeEvent<string> evt)
|
|
{
|
|
OnValueChanged?.Invoke(evt.newValue);
|
|
}
|
|
|
|
private void OnFocusIn(FocusInEvent evt)
|
|
{
|
|
EnableInClassList("utk-input--focused", true);
|
|
OnFocused?.Invoke();
|
|
}
|
|
|
|
private void OnFocusOut(FocusOutEvent evt)
|
|
{
|
|
EnableInClassList("utk-input--focused", false);
|
|
OnBlurred?.Invoke();
|
|
RunValidation();
|
|
}
|
|
|
|
private void OnKeyDown(KeyDownEvent evt)
|
|
{
|
|
if (evt.keyCode == KeyCode.Return && !multiline)
|
|
{
|
|
OnSubmit?.Invoke(value);
|
|
RunValidation();
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
/// <summary>
|
|
/// 값 설정
|
|
/// </summary>
|
|
public void SetValue(string newValue, bool notify)
|
|
{
|
|
if (value == newValue) return;
|
|
|
|
if (notify)
|
|
{
|
|
value = newValue ?? "";
|
|
}
|
|
else
|
|
{
|
|
SetValueWithoutNotify(newValue ?? "");
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 강제로 Validation을 실행하여 에러 상태를 업데이트합니다.
|
|
/// </summary>
|
|
/// <returns>Validation이 null이면 true, 아니면 Validation 결과</returns>
|
|
public bool Validate()
|
|
{
|
|
return RunValidation();
|
|
}
|
|
|
|
/// <summary>
|
|
/// 선택 영역 설정
|
|
/// </summary>
|
|
public void SelectAll()
|
|
{
|
|
textSelection.SelectAll();
|
|
}
|
|
|
|
/// <summary>에러 상태를 수동으로 해제합니다.</summary>
|
|
public void ClearError()
|
|
{
|
|
ErrorMessage = "";
|
|
}
|
|
|
|
private bool RunValidation()
|
|
{
|
|
if (_validation == null) return true;
|
|
|
|
var isValid = _validation.Invoke();
|
|
if (isValid)
|
|
{
|
|
// 검증 통과 시 에러 상태 해제
|
|
EnableInClassList("utk-input--error", false);
|
|
UpdateErrorLabel(null);
|
|
}
|
|
else
|
|
{
|
|
// 검증 실패 시 에러 상태 표시
|
|
EnableInClassList("utk-input--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-input__error-message");
|
|
_errorLabel.style.display = DisplayStyle.None;
|
|
Add(_errorLabel);
|
|
}
|
|
|
|
_errorLabel.text = message;
|
|
_errorLabel.style.display = DisplayStyle.Flex;
|
|
}
|
|
|
|
private void UpdateVariant()
|
|
{
|
|
RemoveFromClassList("utk-input--default");
|
|
RemoveFromClassList("utk-input--filled");
|
|
RemoveFromClassList("utk-input--outlined");
|
|
|
|
var variantClass = _variant switch
|
|
{
|
|
InputFieldVariant.Filled => "utk-input--filled",
|
|
InputFieldVariant.Outlined => "utk-input--outlined",
|
|
_ => "utk-input--default"
|
|
};
|
|
AddToClassList(variantClass);
|
|
}
|
|
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
UnregisterCallback<ChangeEvent<string>>(OnTextValueChanged);
|
|
UnregisterCallback<FocusInEvent>(OnFocusIn);
|
|
UnregisterCallback<FocusOutEvent>(OnFocusOut);
|
|
UnregisterCallback<KeyDownEvent>(OnKeyDown);
|
|
|
|
OnValueChanged = null;
|
|
OnFocused = null;
|
|
OnBlurred = null;
|
|
OnSubmit = null;
|
|
_validation = null;
|
|
_errorLabel = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|