using System.Globalization;
using System.Windows;
using System.Windows.Automation;
using System.Windows.Automation.Peers;
using System.Windows.Threading;
using Chronos.Core.Localization;
namespace Chronos.App.Infrastructure;
///
/// A status line screen readers announce when it changes (a live region): LiveRegion.Text becomes the element's
/// accessible name and every later change raises . The element's
/// (Polite, or Assertive for errors) must be set as well.
///
public static class LiveRegion
{
public static readonly DependencyProperty TextProperty = DependencyProperty.RegisterAttached(
"Text", typeof(string), typeof(LiveRegion), new PropertyMetadata(null, OnTextChanged));
///
/// The data and language the last text came from: a recycled list row showing another item, or every status
/// relabelled by a language switch, is not news.
///
private static readonly DependencyProperty SourceProperty = DependencyProperty.RegisterAttached(
"Source", typeof(Origin), typeof(LiveRegion), new PropertyMetadata(null));
public static string? GetText(DependencyObject element) => (string?)element.GetValue(TextProperty);
public static void SetText(DependencyObject element, string? value) => element.SetValue(TextProperty, value);
private static void OnTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (d is not FrameworkElement element) return;
AutomationProperties.SetName(element, (string?)e.NewValue ?? string.Empty);
var origin = new Origin(element.DataContext, Loc.Culture);
var sameSource = element.GetValue(SourceProperty) is Origin last && ReferenceEquals(last.Data, origin.Data) && last.Culture.Equals(origin.Culture);
element.SetValue(SourceProperty, origin);
// The first value arrives with the screen: only what changes while it is shown is announced, once layout has shown
// it (a status that appears with its text is still collapsed when the text arrives).
if (!sameSource || !element.IsLoaded || e.NewValue is null || !AutomationPeer.ListenerExists(AutomationEvents.LiveRegionChanged)) return;
element.Dispatcher.InvokeAsync(() => UIElementAutomationPeer.CreatePeerForElement(element)?.RaiseAutomationEvent(AutomationEvents.LiveRegionChanged),
DispatcherPriority.Background);
}
private sealed record Origin(object? Data, CultureInfo Culture);
}