Files
XRLib/Assets/Scripts/UVC/UIToolkit/Modal/UTKAlert.cs

609 lines
22 KiB
C#
Raw Normal View History

2026-01-08 20:15:57 +09:00
#nullable enable
using System;
using Cysharp.Threading.Tasks;
2026-01-08 20:15:57 +09:00
using UnityEngine;
using UnityEngine.UIElements;
namespace UVC.UIToolkit
{
/// <summary>
/// Alert 팝업 컴포넌트.
/// 사용자에게 중요한 정보를 알립니다.
/// </summary>
2026-01-13 20:39:45 +09:00
/// <example>
/// <para><b>C# 코드에서 사용:</b></para>
/// <code>
/// // 초기화 (root 설정 필요)
/// UTKAlert.Initialize(rootVisualElement);
///
/// // 기본 알림
/// await UTKAlert.Show("알림", "작업이 완료되었습니다.");
///
/// // 확인 대화상자
/// bool confirmed = await UTKAlert.ShowConfirm("삭제 확인", "정말 삭제하시겠습니까?");
/// if (confirmed) {
/// // 삭제 실행
/// }
///
/// // 타입별 알림
/// await UTKAlert.ShowSuccess("성공", "저장되었습니다.");
/// await UTKAlert.ShowError("오류", "파일을 찾을 수 없습니다.");
/// await UTKAlert.ShowWarning("경고", "변경사항이 저장되지 않았습니다.");
/// </code>
/// <para><b>UXML에서 사용:</b></para>
/// <code>
/// <ui:UXML xmlns:utk="UVC.UIToolkit">
/// <!-- Alert는 주로 C# 코드로 동적 생성합니다 -->
/// <utk:UTKAlert Title="알림" Message="메시지" AlertType="Info" />
/// </ui:UXML>
/// </code>
/// </example>
2026-01-08 20:15:57 +09:00
[UxmlElement]
public partial class UTKAlert : VisualElement, IDisposable
{
#region Constants
private const string USS_PATH = "UIToolkit/Modal/UTKAlert";
#endregion
#region Fields
private static VisualElement? _root;
2026-01-08 20:15:57 +09:00
private bool _disposed;
private UTKModalBlocker? _blocker;
private Label? _titleLabel;
private Label? _messageLabel;
private VisualElement? _buttonContainer;
private string _title = "";
private string _message = "";
private AlertType _alertType = AlertType.Info;
private string _confirmLabel = "OK";
private string _cancelLabel = "Cancel";
private EventCallback<KeyDownEvent>? _keyDownCallback;
private VisualElement? _keyEventTarget;
2026-01-08 20:15:57 +09:00
#endregion
#region Events
/// <summary>닫힘 이벤트</summary>
public event Action? OnClosed;
/// <summary>확인 이벤트</summary>
public event Action? OnConfirm;
/// <summary>취소 이벤트</summary>
public event Action? OnCancel;
#endregion
#region Properties
/// <summary>제목</summary>
[UxmlAttribute]
public string Title
{
get => _title;
set
{
_title = value;
if (_titleLabel != null)
{
_titleLabel.text = value;
_titleLabel.style.display = string.IsNullOrEmpty(value) ? DisplayStyle.None : DisplayStyle.Flex;
}
}
}
/// <summary>메시지</summary>
[UxmlAttribute]
public string Message
{
get => _message;
set
{
_message = value;
if (_messageLabel != null) _messageLabel.text = value;
}
}
/// <summary>알림 유형</summary>
[UxmlAttribute]
public AlertType Type
{
get => _alertType;
set
{
_alertType = value;
UpdateType();
}
}
#endregion
#region Enums
public enum AlertType
{
Info,
Success,
Warning,
Error,
Confirm
}
#endregion
#region Constructor
public UTKAlert()
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
var uss = Resources.Load<StyleSheet>(USS_PATH);
if (uss != null)
{
styleSheets.Add(uss);
}
CreateUI();
SubscribeToThemeChanges();
}
public UTKAlert(string title, string message, AlertType type = AlertType.Info) : this()
{
Title = title;
Message = message;
Type = type;
}
#endregion
#region Static Methods
/// <summary>
/// 기본 루트 요소 설정
/// </summary>
/// <param name="root">Alert를 표시할 기본 루트 요소</param>
public static void SetRoot(VisualElement root)
{
_root = root;
}
/// <summary>
/// 기본 루트 요소 반환
/// </summary>
public static VisualElement? GetRoot() => _root;
#endregion
#region Static Factory (without parent)
/// <summary>
/// Info 알림 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert ShowInfo(string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return Show(_root!, title, message, AlertType.Info, onClose, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Success 알림 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert ShowSuccess(string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return Show(_root!, title, message, AlertType.Success, onClose, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Warning 알림 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert ShowWarning(string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return Show(_root!, title, message, AlertType.Warning, onClose, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Error 알림 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert ShowError(string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return Show(_root!, title, message, AlertType.Error, onClose, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Confirm 대화상자 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert ShowConfirm(string title, string message, Action? onConfirm, Action? onCancel = null, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
{
ValidateRoot();
var alert = Show(_root!, title, message, AlertType.Confirm, null, closeOnBlockerClick, confirmLabel, cancelLabel);
alert.OnConfirm = onConfirm;
alert.OnCancel = onCancel;
return alert;
}
/// <summary>
/// 알림 표시 (SetRoot로 설정된 루트 사용)
/// </summary>
public static UTKAlert Show(string title, string message, AlertType type = AlertType.Info, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
{
ValidateRoot();
return Show(_root!, title, message, type, onClose, closeOnBlockerClick, confirmLabel, cancelLabel);
}
private static void ValidateRoot()
{
if (_root == null)
{
throw new InvalidOperationException("UTKAlert.SetRoot()를 먼저 호출하여 기본 루트 요소를 설정해야 합니다.");
}
}
#endregion
#region Static Factory Async (without parent)
/// <summary>
/// Info 알림 표시 (비동기, SetRoot로 설정된 루트 사용)
/// </summary>
public static UniTask ShowInfoAsync(string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return ShowAsync(_root!, title, message, AlertType.Info, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Success 알림 표시 (비동기, SetRoot로 설정된 루트 사용)
/// </summary>
public static UniTask ShowSuccessAsync(string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return ShowAsync(_root!, title, message, AlertType.Success, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Warning 알림 표시 (비동기, SetRoot로 설정된 루트 사용)
/// </summary>
public static UniTask ShowWarningAsync(string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return ShowAsync(_root!, title, message, AlertType.Warning, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Error 알림 표시 (비동기, SetRoot로 설정된 루트 사용)
/// </summary>
public static UniTask ShowErrorAsync(string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
ValidateRoot();
return ShowAsync(_root!, title, message, AlertType.Error, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Confirm 대화상자 표시 (비동기, SetRoot로 설정된 루트 사용)
/// </summary>
/// <returns>확인 버튼 클릭 시 true, 취소 버튼 클릭 시 false</returns>
public static UniTask<bool> ShowConfirmAsync(string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
{
ValidateRoot();
return ShowConfirmAsync(_root!, title, message, closeOnBlockerClick, confirmLabel, cancelLabel);
}
#endregion
#region Static Factory Async (with parent)
/// <summary>
/// Info 알림 표시 (비동기)
/// </summary>
public static UniTask ShowInfoAsync(VisualElement parent, string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
return ShowAsync(parent, title, message, AlertType.Info, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Success 알림 표시 (비동기)
/// </summary>
public static UniTask ShowSuccessAsync(VisualElement parent, string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
return ShowAsync(parent, title, message, AlertType.Success, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Warning 알림 표시 (비동기)
/// </summary>
public static UniTask ShowWarningAsync(VisualElement parent, string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
return ShowAsync(parent, title, message, AlertType.Warning, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Error 알림 표시 (비동기)
/// </summary>
public static UniTask ShowErrorAsync(VisualElement parent, string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK")
{
return ShowAsync(parent, title, message, AlertType.Error, closeOnBlockerClick, confirmLabel);
}
/// <summary>
/// Confirm 대화상자 표시 (비동기)
/// </summary>
/// <returns>확인 버튼 클릭 시 true, 취소 버튼 클릭 시 false</returns>
public static UniTask<bool> ShowConfirmAsync(VisualElement parent, string title, string message, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
{
var tcs = new UniTaskCompletionSource<bool>();
var alert = Show(parent, title, message, AlertType.Confirm, null, closeOnBlockerClick, confirmLabel, cancelLabel);
alert.OnConfirm = () => tcs.TrySetResult(true);
alert.OnCancel = () => tcs.TrySetResult(false);
alert.OnClosed = () => tcs.TrySetResult(false);
return tcs.Task;
}
/// <summary>
/// 알림 표시 (비동기)
/// </summary>
public static UniTask ShowAsync(VisualElement parent, string title, string message, AlertType type, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
{
var tcs = new UniTaskCompletionSource();
var alert = Show(parent, title, message, type, () => tcs.TrySetResult(), closeOnBlockerClick, confirmLabel, cancelLabel);
return tcs.Task;
}
#endregion
#region Static Factory (with parent)
2026-01-08 20:15:57 +09:00
/// <summary>
/// Info 알림 표시
/// </summary>
public static UTKAlert ShowInfo(VisualElement parent, string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
2026-01-08 20:15:57 +09:00
{
return Show(parent, title, message, AlertType.Info, onClose, closeOnBlockerClick, confirmLabel);
2026-01-08 20:15:57 +09:00
}
/// <summary>
/// Success 알림 표시
/// </summary>
public static UTKAlert ShowSuccess(VisualElement parent, string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
2026-01-08 20:15:57 +09:00
{
return Show(parent, title, message, AlertType.Success, onClose, closeOnBlockerClick, confirmLabel);
2026-01-08 20:15:57 +09:00
}
/// <summary>
/// Warning 알림 표시
/// </summary>
public static UTKAlert ShowWarning(VisualElement parent, string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
2026-01-08 20:15:57 +09:00
{
return Show(parent, title, message, AlertType.Warning, onClose, closeOnBlockerClick, confirmLabel);
2026-01-08 20:15:57 +09:00
}
/// <summary>
/// Error 알림 표시
/// </summary>
public static UTKAlert ShowError(VisualElement parent, string title, string message, Action? onClose = null, bool closeOnBlockerClick = false, string confirmLabel = "OK")
2026-01-08 20:15:57 +09:00
{
return Show(parent, title, message, AlertType.Error, onClose, closeOnBlockerClick, confirmLabel);
2026-01-08 20:15:57 +09:00
}
/// <summary>
/// Confirm 대화상자 표시
/// </summary>
public static UTKAlert ShowConfirm(VisualElement parent, string title, string message, Action? onConfirm, Action? onCancel = null, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
2026-01-08 20:15:57 +09:00
{
var alert = Show(parent, title, message, AlertType.Confirm, null, closeOnBlockerClick, confirmLabel, cancelLabel);
2026-01-08 20:15:57 +09:00
alert.OnConfirm = onConfirm;
alert.OnCancel = onCancel;
return alert;
}
/// <summary>
/// 알림 표시
/// </summary>
/// <param name="parent">부모 요소</param>
/// <param name="title">제목</param>
/// <param name="message">메시지</param>
/// <param name="type">알림 유형</param>
/// <param name="onClose">닫힘 콜백</param>
/// <param name="closeOnBlockerClick">배경 클릭 시 닫힘 여부</param>
/// <param name="confirmLabel">확인 버튼 레이블</param>
/// <param name="cancelLabel">취소 버튼 레이블 (Confirm 타입에서만 사용)</param>
public static UTKAlert Show(VisualElement parent, string title, string message, AlertType type, Action? onClose, bool closeOnBlockerClick = false, string confirmLabel = "OK", string cancelLabel = "Cancel")
2026-01-08 20:15:57 +09:00
{
var alert = new UTKAlert(title, message, type);
alert.OnClosed = onClose;
alert._confirmLabel = confirmLabel;
alert._cancelLabel = cancelLabel;
alert.UpdateButtons();
2026-01-08 20:15:57 +09:00
alert._blocker = UTKModalBlocker.Show(parent, 0.5f, closeOnBlockerClick);
if (closeOnBlockerClick)
{
alert._blocker.OnBlockerClicked += alert.Close;
}
else
{
// closeOnBlockerClick이 false일 때 blocker 클릭 시 Alert로 포커스 유지
alert._blocker.OnBlockerClicked += () => alert.Focus();
}
2026-01-08 20:15:57 +09:00
alert._blocker.Add(alert);
// 중앙 정렬
alert.style.position = Position.Absolute;
alert.style.left = Length.Percent(50);
alert.style.top = Length.Percent(50);
alert.style.translate = new Translate(Length.Percent(-50), Length.Percent(-50));
// ESC 키 이벤트 등록
alert.RegisterEscapeKey(parent);
// Alert에 포커스 설정 (키보드 이벤트 수신을 위해)
alert.focusable = true;
alert.schedule.Execute(() => alert.Focus());
2026-01-08 20:15:57 +09:00
return alert;
}
#endregion
#region UI Creation
private void CreateUI()
{
AddToClassList("utk-alert");
// Title (상단 왼쪽)
_titleLabel = new Label { name = "title" };
_titleLabel.AddToClassList("utk-alert__title");
Add(_titleLabel);
2026-01-08 20:15:57 +09:00
// Content (가운데 메시지)
2026-01-08 20:15:57 +09:00
var contentContainer = new VisualElement { name = "content" };
contentContainer.AddToClassList("utk-alert__content");
Add(contentContainer);
_messageLabel = new Label { name = "message" };
_messageLabel.AddToClassList("utk-alert__message");
contentContainer.Add(_messageLabel);
// Buttons
2026-01-08 20:15:57 +09:00
_buttonContainer = new VisualElement { name = "buttons" };
_buttonContainer.AddToClassList("utk-alert__buttons");
Add(_buttonContainer);
UpdateType();
}
private void SubscribeToThemeChanges()
{
UTKThemeManager.Instance.OnThemeChanged += OnThemeChanged;
RegisterCallback<DetachFromPanelEvent>(_ =>
{
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
});
}
private void OnThemeChanged(UTKTheme theme)
{
UTKThemeManager.Instance.ApplyThemeToElement(this);
}
#endregion
#region Methods
private void UpdateType()
{
RemoveFromClassList("utk-alert--info");
RemoveFromClassList("utk-alert--success");
RemoveFromClassList("utk-alert--warning");
RemoveFromClassList("utk-alert--error");
RemoveFromClassList("utk-alert--confirm");
var typeClass = _alertType switch
{
AlertType.Success => "utk-alert--success",
AlertType.Warning => "utk-alert--warning",
AlertType.Error => "utk-alert--error",
AlertType.Confirm => "utk-alert--confirm",
_ => "utk-alert--info"
};
AddToClassList(typeClass);
// 버튼 업데이트
UpdateButtons();
}
private void UpdateButtons()
{
if (_buttonContainer == null) return;
_buttonContainer.Clear();
if (_alertType == AlertType.Confirm)
{
var cancelBtn = new UTKButton(_cancelLabel, "", UTKButton.ButtonVariant.Normal);
2026-01-08 20:15:57 +09:00
cancelBtn.AddToClassList("utk-alert__btn");
cancelBtn.OnClicked += () =>
{
OnCancel?.Invoke();
Close();
};
_buttonContainer.Add(cancelBtn);
var confirmBtn = new UTKButton(_confirmLabel, "", UTKButton.ButtonVariant.Primary);
2026-01-08 20:15:57 +09:00
confirmBtn.AddToClassList("utk-alert__btn");
confirmBtn.OnClicked += () =>
{
OnConfirm?.Invoke();
Close();
};
_buttonContainer.Add(confirmBtn);
}
else
{
var okBtn = new UTKButton(_confirmLabel, "", UTKButton.ButtonVariant.Primary);
2026-01-08 20:15:57 +09:00
okBtn.AddToClassList("utk-alert__btn");
okBtn.OnClicked += Close;
_buttonContainer.Add(okBtn);
}
}
/// <summary>
/// ESC 키 이벤트 등록
/// </summary>
private void RegisterEscapeKey(VisualElement parent)
{
_keyEventTarget = parent;
_keyDownCallback = evt =>
{
if (evt.keyCode == KeyCode.Escape)
{
evt.StopPropagation();
HandleEscapeKey();
}
};
// 패널에 키 이벤트 등록 (포커스와 관계없이 캡처)
_keyEventTarget.RegisterCallback(_keyDownCallback, TrickleDown.TrickleDown);
}
/// <summary>
/// ESC 키 해제
/// </summary>
private void UnregisterEscapeKey()
{
if (_keyDownCallback != null && _keyEventTarget != null)
{
_keyEventTarget.UnregisterCallback(_keyDownCallback, TrickleDown.TrickleDown);
_keyDownCallback = null;
_keyEventTarget = null;
}
}
/// <summary>
/// ESC 키 처리
/// </summary>
private void HandleEscapeKey()
{
if (_alertType == AlertType.Confirm)
{
// Confirm 타입: 취소 처리
OnCancel?.Invoke();
}
Close();
}
2026-01-08 20:15:57 +09:00
/// <summary>
/// 알림 닫기
/// </summary>
public void Close()
{
UnregisterEscapeKey();
2026-01-08 20:15:57 +09:00
OnClosed?.Invoke();
if (_blocker != null)
{
_blocker.OnBlockerClicked -= Close;
_blocker.Hide();
}
_blocker = null;
}
#endregion
#region IDisposable
public void Dispose()
{
if (_disposed) return;
_disposed = true;
UTKThemeManager.Instance.OnThemeChanged -= OnThemeChanged;
OnClosed = null;
OnConfirm = null;
OnCancel = null;
_blocker = null;
}
#endregion
}
}