using System.Collections.ObjectModel; using System.Windows; using System.Windows.Automation; using System.Windows.Automation.Peers; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Threading; using Titano.Ui.Mvvm; namespace Titano.Ui.Controls; /// One in-window notification (DESIGN ยง4: 420 px, accent left edge, one action, 8 s, hover pauses). public sealed class Toast : ObservableObject { public required string Title { get; init; } public string? Message { get; init; } public string? ActionText { get; init; } public ICommand? ActionCommand { get; init; } public string? ActionToolTip { get; init; } public TimeSpan Lifetime { get; init; } = TimeSpan.FromSeconds(8); /// Something failed: screen readers say it at once, ahead of other notices (assertive, not polite). public bool IsError { get; init; } } /// /// Bottom-right stack of s with auto-dismiss. Screen readers hear each toast as it appears; the /// timers pause while the pointer or the keyboard focus is on a toast; brings the keyboard /// to the newest one, Esc dismisses the focused one and focus then returns where it came from; running a toast's /// action closes it. /// public class ToastHost : ItemsControl { private readonly Dictionary _timers = []; private IInputElement? _returnFocus; static ToastHost() { DefaultStyleKeyProperty.OverrideMetadata(typeof(ToastHost), new FrameworkPropertyMetadata(typeof(ToastHost))); } public ToastHost() { ItemsSource = Toasts; CommandBindings.Add(new CommandBinding(DismissCommand, (_, e) => { if (e.Parameter is Toast t) Dismiss(t); })); AddHandler(ButtonBase.ClickEvent, new RoutedEventHandler(OnButtonClick)); } public static RoutedCommand DismissCommand { get; } = new(nameof(DismissCommand), typeof(ToastHost)); public ObservableCollection Toasts { get; } = []; private bool IsHeld => IsMouseOver || IsKeyboardFocusWithin; public void Show(Toast toast) { Toasts.Add(toast); while (Toasts.Count > 3) Dismiss(Toasts[0]); var timer = new DispatcherTimer { Interval = toast.Lifetime }; timer.Tick += (_, _) => Dismiss(toast); _timers[toast] = timer; timer.IsEnabled = !IsHeld; Announce(toast); } public void Dismiss(Toast toast) { if (_timers.Remove(toast, out var timer)) timer.Stop(); var hadFocus = IsKeyboardFocusWithin; Toasts.Remove(toast); if (hadFocus && !IsKeyboardFocusWithin && _returnFocus is UIElement { IsVisible: true } previous) previous.Focus(); } /// Moves the keyboard to the newest toast's first control; false when no toast is shown. public bool FocusNewest() { if (Toasts.Count == 0) return false; UpdateLayout(); return ItemContainerGenerator.ContainerFromIndex(Toasts.Count - 1) is UIElement container && container.MoveFocus(new TraversalRequest(FocusNavigationDirection.First)); } protected override void OnPreviewGotKeyboardFocus(KeyboardFocusChangedEventArgs e) { base.OnPreviewGotKeyboardFocus(e); if (e.OldFocus is not DependencyObject old || !IsAncestorOf(old)) _returnFocus = e.OldFocus; } protected override void OnIsKeyboardFocusWithinChanged(DependencyPropertyChangedEventArgs e) { base.OnIsKeyboardFocusWithinChanged(e); UpdateTimers(); } protected override void OnMouseEnter(MouseEventArgs e) { base.OnMouseEnter(e); UpdateTimers(); } protected override void OnMouseLeave(MouseEventArgs e) { base.OnMouseLeave(e); UpdateTimers(); } protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); if (e.Handled || e.Key != Key.Escape || (e.OriginalSource as FrameworkElement)?.DataContext is not Toast toast) return; Dismiss(toast); e.Handled = true; } /// Hovering or focusing any toast holds them all; leaving restarts their full lifetime. private void UpdateTimers() { var held = IsHeld; foreach (var timer in _timers.Values) { timer.Stop(); if (!held) timer.Start(); } } /// The action executes right after its Click event; the toast closes once it has run. private void OnButtonClick(object sender, RoutedEventArgs e) { if (e.OriginalSource is ButtonBase { DataContext: Toast toast, Command: { } command } && ReferenceEquals(command, toast.ActionCommand)) Dispatcher.BeginInvoke(() => Dismiss(toast)); } /// /// A UI Automation notification rather than a live region: a toast is a new element, not a text that changes, and /// the host's peer is always in the tree. Notices queue (polite); errors interrupt (assertive). /// private void Announce(Toast toast) { var text = string.IsNullOrEmpty(toast.Message) ? toast.Title : toast.Title + " " + toast.Message; UIElementAutomationPeer.CreatePeerForElement(this)?.RaiseNotificationEvent( AutomationNotificationKind.Other, toast.IsError ? AutomationNotificationProcessing.ImportantAll : AutomationNotificationProcessing.All, text, "Titano.Toast"); } }