513 lines
16 KiB
C#
513 lines
16 KiB
C#
#nullable enable
|
|
using System;
|
|
using Cysharp.Threading.Tasks;
|
|
using UnityEngine;
|
|
using UnityEngine.UIElements;
|
|
using UVC.UIToolkit.Util;
|
|
|
|
namespace UVC.UIToolkit
|
|
{
|
|
/// <summary>
|
|
/// 모달 창 컴포넌트.
|
|
/// 사용자 정의 콘텐츠를 포함할 수 있는 모달 대화상자입니다.
|
|
/// </summary>
|
|
/// <remarks>
|
|
/// <para><b>사용 전 초기화:</b></para>
|
|
/// <para>
|
|
/// Modal을 표시하기 전에 <c>UTKModal.SetRoot(rootVisualElement)</c>로 루트를 설정해야 합니다.
|
|
/// </para>
|
|
/// </remarks>
|
|
/// <example>
|
|
/// <para><b>C# 코드에서 사용:</b></para>
|
|
/// <code>
|
|
/// // 초기화 (root 설정 필요)
|
|
/// UTKModal.SetRoot(rootVisualElement);
|
|
///
|
|
/// // Static Factory로 생성
|
|
/// var modal = UTKModal.Create("설정", UTKModal.ModalSize.Medium);
|
|
/// modal.OnClosed += () => Debug.Log("모달 닫힘");
|
|
///
|
|
/// // 콘텐츠 추가
|
|
/// var content = new Label("모달 내용");
|
|
/// modal.Add(content);
|
|
///
|
|
/// // 푸터에 버튼 추가
|
|
/// modal.AddToFooter(new UTKButton("확인", "", UTKButton.ButtonVariant.Primary));
|
|
/// modal.AddToFooter(new UTKButton("취소", "", UTKButton.ButtonVariant.Normal));
|
|
///
|
|
/// // 화면에 표시
|
|
/// modal.Show();
|
|
/// </code>
|
|
/// <para><b>Async/Await 방식:</b></para>
|
|
/// <code>
|
|
/// // 모달이 닫힐 때까지 대기
|
|
/// var modal = UTKModal.Create("설정", UTKModal.ModalSize.Medium);
|
|
/// modal.Add(new Label("모달 내용"));
|
|
///
|
|
/// var closeBtn = new UTKButton("닫기", "", UTKButton.ButtonVariant.Primary);
|
|
/// closeBtn.OnClicked += () => modal.Close();
|
|
/// modal.AddToFooter(closeBtn);
|
|
///
|
|
/// await modal.ShowAsync();
|
|
/// Debug.Log("모달이 닫혔습니다.");
|
|
/// </code>
|
|
/// <para><b>Async/Await + IUTKModalContent 방식:</b></para>
|
|
/// <code>
|
|
/// // IUTKModalContent<T> 구현 콘텐츠에서 결과 반환
|
|
/// var modal = UTKModal.Create("사용자 정보", UTKModal.ModalSize.Medium);
|
|
/// var form = new UserFormContent(); // VisualElement + IUTKModalContent<UserData>
|
|
/// modal.Add(form);
|
|
///
|
|
/// var submitBtn = new UTKButton("제출", "", UTKButton.ButtonVariant.Primary);
|
|
/// submitBtn.OnClicked += () => modal.Close();
|
|
/// modal.AddToFooter(submitBtn);
|
|
///
|
|
/// UserData? result = await modal.ShowAsync<UserData>();
|
|
/// if (result != null)
|
|
/// Debug.Log($"이름: {result.Name}");
|
|
/// </code>
|
|
/// <para><b>UXML에서 사용:</b></para>
|
|
/// <code>
|
|
/// <ui:UXML xmlns:utk="UVC.UIToolkit">
|
|
/// <utk:UTKModal title="설정" size="Medium" show-close-button="true">
|
|
/// <ui:Label text="모달 내용을 여기에 추가하세요" />
|
|
/// </utk:UTKModal>
|
|
/// </ui:UXML>
|
|
/// </code>
|
|
/// </example>
|
|
/// <summary>
|
|
/// 모달 콘텐츠 인터페이스.
|
|
/// VisualElement를 상속한 클래스에서 구현하여 모달의 결과 값을 반환합니다.
|
|
/// </summary>
|
|
/// <typeparam name="T">결과 타입</typeparam>
|
|
/// <example>
|
|
/// <code>
|
|
/// public class UserFormContent : VisualElement, IUTKModalContent<UserData>
|
|
/// {
|
|
/// private UTKInputField _nameField;
|
|
/// private UTKInputField _emailField;
|
|
///
|
|
/// public UserFormContent()
|
|
/// {
|
|
/// _nameField = new UTKInputField("이름");
|
|
/// _emailField = new UTKInputField("이메일");
|
|
/// Add(_nameField);
|
|
/// Add(_emailField);
|
|
/// }
|
|
///
|
|
/// public UserData? GetResult()
|
|
/// {
|
|
/// return new UserData(_nameField.value, _emailField.value);
|
|
/// }
|
|
/// }
|
|
/// </code>
|
|
/// </example>
|
|
public interface IUTKModalContent<T> where T : class
|
|
{
|
|
/// <summary>
|
|
/// 모달 닫힐 때 호출되어 결과 값을 반환합니다.
|
|
/// </summary>
|
|
T? GetResult();
|
|
}
|
|
|
|
[UxmlElement]
|
|
public partial class UTKModal : VisualElement, IDisposable
|
|
{
|
|
#region Constants
|
|
private const string USS_PATH = "UIToolkit/Modal/UTKModal";
|
|
#endregion
|
|
|
|
#region Fields
|
|
private static VisualElement? _root;
|
|
|
|
private bool _disposed;
|
|
private UTKModalBlocker? _blocker;
|
|
private VisualElement? _header;
|
|
private Label? _titleLabel;
|
|
private UTKButton? _closeButton;
|
|
private VisualElement? _content;
|
|
private VisualElement? _footer;
|
|
|
|
private string _title = "Modal";
|
|
private bool _showCloseButton = true;
|
|
private bool _closeOnBackdropClick = false;
|
|
private ModalSize _size = ModalSize.Medium;
|
|
|
|
private UniTaskCompletionSource? _closeTcs;
|
|
private Action? _onCloseResultHandler;
|
|
#endregion
|
|
|
|
#region Events
|
|
/// <summary>닫힘 이벤트</summary>
|
|
public event Action? OnClosed;
|
|
#endregion
|
|
|
|
#region Properties
|
|
/// <summary>모달 제목</summary>
|
|
[UxmlAttribute("title")]
|
|
public string Title
|
|
{
|
|
get => _title;
|
|
set
|
|
{
|
|
_title = value;
|
|
if (_titleLabel != null) _titleLabel.text = value;
|
|
}
|
|
}
|
|
|
|
/// <summary>닫기 버튼 표시 여부</summary>
|
|
[UxmlAttribute("show-close-button")]
|
|
public bool ShowCloseButton
|
|
{
|
|
get => _showCloseButton;
|
|
set
|
|
{
|
|
_showCloseButton = value;
|
|
if (_closeButton != null)
|
|
{
|
|
_closeButton.style.display = value ? DisplayStyle.Flex : DisplayStyle.None;
|
|
}
|
|
}
|
|
}
|
|
|
|
/// <summary>배경 클릭 시 닫기 여부</summary>
|
|
[UxmlAttribute("close-on-backdrop-click")]
|
|
public bool CloseOnBackdropClick
|
|
{
|
|
get => _closeOnBackdropClick;
|
|
set
|
|
{
|
|
if (_closeOnBackdropClick == value) return;
|
|
_closeOnBackdropClick = value;
|
|
UpdateBackdropClickHandler();
|
|
}
|
|
}
|
|
|
|
/// <summary>모달 크기</summary>
|
|
[UxmlAttribute("size")]
|
|
public ModalSize Size
|
|
{
|
|
get => _size;
|
|
set
|
|
{
|
|
_size = value;
|
|
UpdateSize();
|
|
}
|
|
}
|
|
|
|
/// <summary>콘텐츠 컨테이너</summary>
|
|
public VisualElement? ContentContainer => _content;
|
|
|
|
/// <summary>푸터 컨테이너</summary>
|
|
public VisualElement? FooterContainer => _footer;
|
|
#endregion
|
|
|
|
#region Enums
|
|
public enum ModalSize
|
|
{
|
|
Small,
|
|
Medium,
|
|
Large,
|
|
FullScreen
|
|
}
|
|
#endregion
|
|
|
|
#region Constructor
|
|
public UTKModal()
|
|
{
|
|
UTKThemeManager.Instance.ApplyThemeToElement(this);
|
|
|
|
var uss = Resources.Load<StyleSheet>(USS_PATH);
|
|
if (uss != null)
|
|
{
|
|
styleSheets.Add(uss);
|
|
}
|
|
|
|
CreateUI();
|
|
SetupEvents();
|
|
SubscribeToThemeChanges();
|
|
}
|
|
|
|
public UTKModal(string title, ModalSize size = ModalSize.Medium) : this()
|
|
{
|
|
Title = title;
|
|
Size = size;
|
|
}
|
|
#endregion
|
|
|
|
#region Static Methods
|
|
/// <summary>
|
|
/// 기본 루트 요소 설정.
|
|
/// 모든 Modal은 이 루트의 panel.visualTree에 표시됩니다.
|
|
/// </summary>
|
|
/// <param name="root">Modal을 표시할 기본 루트 요소</param>
|
|
public static void SetRoot(VisualElement root)
|
|
{
|
|
_root = root;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 기본 루트 요소 반환
|
|
/// </summary>
|
|
public static VisualElement? GetRoot() => _root;
|
|
|
|
private static void ValidateRoot()
|
|
{
|
|
if (_root == null)
|
|
{
|
|
throw new InvalidOperationException("UTKModal.SetRoot()를 먼저 호출하여 기본 루트 요소를 설정해야 합니다.");
|
|
}
|
|
}
|
|
#endregion
|
|
|
|
#region Static Factory
|
|
/// <summary>
|
|
/// 모달 생성 (화면에 표시하려면 Show() 호출 필요)
|
|
/// </summary>
|
|
public static UTKModal Create(string title, ModalSize size = ModalSize.Medium)
|
|
{
|
|
ValidateRoot();
|
|
return new UTKModal(title, size);
|
|
}
|
|
#endregion
|
|
|
|
#region UI Creation
|
|
private void CreateUI()
|
|
{
|
|
AddToClassList("utk-modal");
|
|
|
|
// Header
|
|
_header = new VisualElement { name = "header" };
|
|
_header.AddToClassList("utk-modal__header");
|
|
hierarchy.Add(_header);
|
|
|
|
_titleLabel = new Label { name = "title", text = _title };
|
|
_titleLabel.AddToClassList("utk-modal__title");
|
|
_header.Add(_titleLabel);
|
|
|
|
_closeButton = new UTKButton("close-btn", UTKMaterialIcons.Close);
|
|
_closeButton.Variant = UTKButton.ButtonVariant.Text;
|
|
_closeButton.IconOnly = true;
|
|
_closeButton.IconSize = 16;
|
|
_closeButton.AddToClassList("utk-modal__close-btn");
|
|
_header.Add(_closeButton);
|
|
|
|
// Content
|
|
_content = new VisualElement { name = "content" };
|
|
_content.AddToClassList("utk-modal__content");
|
|
hierarchy.Add(_content);
|
|
|
|
// Footer
|
|
_footer = new VisualElement { name = "footer" };
|
|
_footer.AddToClassList("utk-modal__footer");
|
|
hierarchy.Add(_footer);
|
|
|
|
UpdateSize();
|
|
}
|
|
|
|
private void SetupEvents()
|
|
{
|
|
_closeButton?.RegisterCallback<ClickEvent>(_ => Close());
|
|
|
|
RegisterCallback<KeyDownEvent>(evt =>
|
|
{
|
|
if (evt.keyCode == KeyCode.Escape)
|
|
{
|
|
Close();
|
|
evt.StopPropagation();
|
|
}
|
|
}, 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);
|
|
}
|
|
#endregion
|
|
|
|
#region Methods
|
|
private void UpdateSize()
|
|
{
|
|
RemoveFromClassList("utk-modal--small");
|
|
RemoveFromClassList("utk-modal--medium");
|
|
RemoveFromClassList("utk-modal--large");
|
|
RemoveFromClassList("utk-modal--fullscreen");
|
|
|
|
var sizeClass = _size switch
|
|
{
|
|
ModalSize.Small => "utk-modal--small",
|
|
ModalSize.Large => "utk-modal--large",
|
|
ModalSize.FullScreen => "utk-modal--fullscreen",
|
|
_ => "utk-modal--medium"
|
|
};
|
|
AddToClassList(sizeClass);
|
|
}
|
|
|
|
/// <summary>
|
|
/// backdrop 클릭 핸들러 등록/해제
|
|
/// </summary>
|
|
private void UpdateBackdropClickHandler()
|
|
{
|
|
if (_blocker == null) return;
|
|
|
|
// 항상 먼저 해제하여 중복 등록 방지
|
|
_blocker.OnBlockerClicked -= Close;
|
|
|
|
if (_closeOnBackdropClick)
|
|
{
|
|
_blocker.OnBlockerClicked += Close;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 콘텐츠 추가
|
|
/// </summary>
|
|
public new void Add(VisualElement element)
|
|
{
|
|
_content?.Add(element);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 푸터에 요소 추가
|
|
/// </summary>
|
|
public void AddToFooter(VisualElement element)
|
|
{
|
|
_footer?.Add(element);
|
|
_footer?.AddToClassList("utk-modal__footer--has-children");
|
|
UTKChildAnnotator.AnnotateChild(_footer);
|
|
}
|
|
|
|
/// <summary>
|
|
/// 푸터 표시/숨김
|
|
/// </summary>
|
|
public void SetFooterVisible(bool visible)
|
|
{
|
|
if (_footer != null)
|
|
{
|
|
_footer.style.display = visible ? DisplayStyle.Flex : DisplayStyle.None;
|
|
}
|
|
}
|
|
|
|
/// <summary>
|
|
/// 모달을 화면에 표시
|
|
/// </summary>
|
|
public void Show()
|
|
{
|
|
ValidateRoot();
|
|
|
|
_blocker = UTKModalBlocker.Show(_root!, 0.5f, false);
|
|
UpdateBackdropClickHandler();
|
|
|
|
// panel.visualTree에 직접 추가
|
|
var root = _root!.panel?.visualTree ?? _root!;
|
|
root.Add(this);
|
|
|
|
// 중앙 정렬
|
|
style.position = Position.Absolute;
|
|
style.left = Length.Percent(50);
|
|
style.top = Length.Percent(50);
|
|
style.translate = new Translate(Length.Percent(-50), Length.Percent(-50));
|
|
}
|
|
|
|
/// <summary>
|
|
/// 모달을 화면에 표시하고 닫힐 때까지 대기
|
|
/// </summary>
|
|
public UniTask ShowAsync()
|
|
{
|
|
_closeTcs = new UniTaskCompletionSource();
|
|
Show();
|
|
return _closeTcs.Task;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 모달을 화면에 표시하고 닫힐 때 IUTKModalContent<T> 콘텐츠의 결과를 반환.
|
|
/// Add()된 자식 중 IUTKModalContent<T>를 구현한 첫 번째 요소에서 GetResult()를 호출합니다.
|
|
/// </summary>
|
|
/// <typeparam name="T">결과 타입</typeparam>
|
|
/// <returns>콘텐츠의 결과 값. 콘텐츠가 없으면 default(T)</returns>
|
|
public UniTask<T?> ShowAsync<T>() where T : class
|
|
{
|
|
var tcs = new UniTaskCompletionSource<T?>();
|
|
|
|
_onCloseResultHandler = () =>
|
|
{
|
|
var result = FindModalContent<T>()?.GetResult();
|
|
tcs.TrySetResult(result);
|
|
};
|
|
|
|
Show();
|
|
return tcs.Task;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 콘텐츠에서 IUTKModalContent<T>를 구현한 첫 번째 요소를 찾습니다.
|
|
/// </summary>
|
|
private IUTKModalContent<T>? FindModalContent<T>() where T : class
|
|
{
|
|
if (_content == null) return null;
|
|
|
|
for (int i = 0; i < _content.childCount; i++)
|
|
{
|
|
if (_content[i] is IUTKModalContent<T> modalContent)
|
|
return modalContent;
|
|
}
|
|
return null;
|
|
}
|
|
|
|
/// <summary>
|
|
/// 모달 닫기
|
|
/// </summary>
|
|
public void Close()
|
|
{
|
|
// 결과 핸들러 먼저 호출 (ShowAsync<T> 사용 시)
|
|
_onCloseResultHandler?.Invoke();
|
|
_onCloseResultHandler = null;
|
|
|
|
OnClosed?.Invoke();
|
|
RemoveFromHierarchy();
|
|
if (_blocker != null)
|
|
{
|
|
_blocker.OnBlockerClicked -= Close;
|
|
_blocker.Hide();
|
|
}
|
|
_blocker = null;
|
|
_closeTcs?.TrySetResult();
|
|
_closeTcs = null;
|
|
}
|
|
#endregion
|
|
|
|
#region IDisposable
|
|
public void Dispose()
|
|
{
|
|
if (_disposed) return;
|
|
_disposed = true;
|
|
|
|
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
|
|
UnregisterCallback<AttachToPanelEvent>(OnAttachToPanelForTheme);
|
|
UnregisterCallback<DetachFromPanelEvent>(OnDetachFromPanelForTheme);
|
|
OnClosed = null;
|
|
_blocker = null;
|
|
}
|
|
#endregion
|
|
}
|
|
}
|