feat: add new Toast.

This commit is contained in:
Zhang Dian
2024-09-05 01:36:10 +08:00
parent 2b42760673
commit f0b23e1bdf
13 changed files with 858 additions and 0 deletions

View File

@@ -0,0 +1,22 @@
using Avalonia.Metadata;
namespace Ursa.Controls;
/// <summary>
/// Represents a toast manager that can show arbitrary content.
/// Managed toast managers can show any content.
/// </summary>
/// <remarks>
/// Because toast managers of this type are implemented purely in managed code, they
/// can display arbitrary content, as opposed to toast managers which display toasts
/// using the host operating system's toast mechanism.
/// </remarks>
[NotClientImplementable]
public interface IManagedToastManager : IToastManager
{
/// <summary>
/// Shows a toast.
/// </summary>
/// <param name="content">The content to be displayed.</param>
void Show(object content);
}

View File

@@ -0,0 +1,38 @@
using Avalonia.Controls.Notifications;
using Avalonia.Metadata;
namespace Ursa.Controls;
/// <summary>
/// Represents a toast that can be shown in a window or by the host operating system.
/// </summary>
[NotClientImplementable]
public interface IToast
{
/// <summary>
/// Gets the toast message.
/// </summary>
string? Content { get; }
/// <summary>
/// Gets the <see cref="NotificationType"/> of the toast.
/// </summary>
NotificationType Type { get; }
/// <summary>
/// Gets the expiration time of the toast after which it will automatically close.
/// If the value is <see cref="TimeSpan.Zero"/> then the toast will remain open until the user closes it.
/// </summary>
TimeSpan Expiration { get; }
/// <summary>
/// Gets an Action to be run when the toast is clicked.
/// </summary>
Action? OnClick { get; }
/// <summary>
/// Gets an Action to be run when the toast is closed.
/// </summary>
Action? OnClose { get; }
}

View File

@@ -0,0 +1,17 @@
using Avalonia.Metadata;
namespace Ursa.Controls;
/// <summary>
/// Represents a toast manager that can be used to show toasts in a window or using
/// the host operating system.
/// </summary>
[NotClientImplementable]
public interface IToastManager
{
/// <summary>
/// Show a toast.
/// </summary>
/// <param name="toast">The toast to be displayed.</param>
void Show(IToast toast);
}

View File

@@ -0,0 +1,80 @@
using System.ComponentModel;
using System.Runtime.CompilerServices;
using Avalonia.Controls.Notifications;
namespace Ursa.Controls;
/// <summary>
/// A toast that can be shown in a window or by the host operating system.
/// </summary>
/// <remarks>
/// This class represents a toast that can be displayed either in a window using
/// <see cref="WindowToastManager"/> or by the host operating system (to be implemented).
/// </remarks>
public class Toast : IToast, INotifyPropertyChanged
{
private string? _content;
/// <summary>
/// Initializes a new instance of the <see cref="Toast"/> class.
/// </summary>
/// <param name="content">The content to be displayed in the toast.</param>
/// <param name="type">The <see cref="NotificationType"/> of the toast.</param>
/// <param name="expiration">The expiry time at which the toast will close.
/// Use <see cref="TimeSpan.Zero"/> for toasts that will remain open.</param>
/// <param name="onClick">An Action to call when the toast is clicked.</param>
/// <param name="onClose">An Action to call when the toast is closed.</param>
public Toast(
string? content,
NotificationType type = NotificationType.Information,
TimeSpan? expiration = null,
Action? onClick = null,
Action? onClose = null)
{
Content = content;
Type = type;
Expiration = expiration ?? TimeSpan.FromSeconds(5);
OnClick = onClick;
OnClose = onClose;
}
/// <summary>
/// Initializes a new instance of the <see cref="Toast"/> class.
/// </summary>
public Toast() : this(null)
{
}
/// <inheritdoc/>
public string? Content
{
get => _content;
set
{
if (_content != value)
{
_content = value;
OnPropertyChanged();
}
}
}
/// <inheritdoc/>
public NotificationType Type { get; set; }
/// <inheritdoc/>
public TimeSpan Expiration { get; set; }
/// <inheritdoc/>
public Action? OnClick { get; set; }
/// <inheritdoc/>
public Action? OnClose { get; set; }
public event PropertyChangedEventHandler? PropertyChanged;
protected virtual void OnPropertyChanged([CallerMemberName] string? propertyName = null)
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
}

View File

@@ -0,0 +1,198 @@
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Notifications;
using Avalonia.Interactivity;
using Avalonia.LogicalTree;
namespace Ursa.Controls;
/// <summary>
/// Control that represents and displays a toast.
/// </summary>
[PseudoClasses(PC_Information, PC_Success, PC_Warning, PC_Error)]
public class ToastCard : ContentControl
{
public const string PC_Information = ":information";
public const string PC_Success = ":success";
public const string PC_Warning = ":warning";
public const string PC_Error = ":error";
private bool _isClosing;
static ToastCard()
{
CloseOnClickProperty.Changed.AddClassHandler<Button>(OnCloseOnClickPropertyChanged);
}
/// <summary>
/// Initializes a new instance of the <see cref="ToastCard"/> class.
/// </summary>
public ToastCard()
{
UpdateNotificationType();
}
/// <summary>
/// Determines if the toast is already closing.
/// </summary>
public bool IsClosing
{
get => _isClosing;
private set => SetAndRaise(IsClosingProperty, ref _isClosing, value);
}
/// <summary>
/// Defines the <see cref="IsClosing"/> property.
/// </summary>
public static readonly DirectProperty<ToastCard, bool> IsClosingProperty =
AvaloniaProperty.RegisterDirect<ToastCard, bool>(nameof(IsClosing), o => o.IsClosing);
/// <summary>
/// Determines if the toast is closed.
/// </summary>
public bool IsClosed
{
get => GetValue(IsClosedProperty);
set => SetValue(IsClosedProperty, value);
}
/// <summary>
/// Defines the <see cref="IsClosed"/> property.
/// </summary>
public static readonly StyledProperty<bool> IsClosedProperty =
AvaloniaProperty.Register<ToastCard, bool>(nameof(IsClosed));
/// <summary>
/// Gets or sets the type of the toast
/// </summary>
public NotificationType NotificationType
{
get => GetValue(NotificationTypeProperty);
set => SetValue(NotificationTypeProperty, value);
}
/// <summary>
/// Defines the <see cref="NotificationType" /> property
/// </summary>
public static readonly StyledProperty<NotificationType> NotificationTypeProperty =
AvaloniaProperty.Register<ToastCard, NotificationType>(nameof(NotificationType));
/// <summary>
/// Defines the <see cref="ToastClosed"/> event.
/// </summary>
public static readonly RoutedEvent<RoutedEventArgs> ToastClosedEvent =
RoutedEvent.Register<ToastCard, RoutedEventArgs>(nameof(ToastClosed), RoutingStrategies.Bubble);
/// <summary>
/// Raised when the <see cref="ToastCard"/> has closed.
/// </summary>
public event EventHandler<RoutedEventArgs>? ToastClosed
{
add => AddHandler(ToastClosedEvent, value);
remove => RemoveHandler(ToastClosedEvent, value);
}
public static bool GetCloseOnClick(Button obj)
{
_ = obj ?? throw new ArgumentNullException(nameof(obj));
return obj.GetValue(CloseOnClickProperty);
}
public static void SetCloseOnClick(Button obj, bool value)
{
_ = obj ?? throw new ArgumentNullException(nameof(obj));
obj.SetValue(CloseOnClickProperty, value);
}
/// <summary>
/// Defines the CloseOnClick property.
/// </summary>
public static readonly AttachedProperty<bool> CloseOnClickProperty =
AvaloniaProperty.RegisterAttached<ToastCard, Button, bool>("CloseOnClick", defaultValue: false);
private static void OnCloseOnClickPropertyChanged(AvaloniaObject d, AvaloniaPropertyChangedEventArgs e)
{
var button = (Button)d;
var value = (bool)e.NewValue!;
if (value)
{
button.Click += Button_Click;
}
else
{
button.Click -= Button_Click;
}
}
/// <summary>
/// Called when a button inside the Toast is clicked.
/// </summary>
private static void Button_Click(object? sender, RoutedEventArgs e)
{
var btn = sender as ILogical;
var toast = btn?.GetLogicalAncestors().OfType<ToastCard>().FirstOrDefault();
toast?.Close();
}
/// <summary>
/// Closes the <see cref="ToastCard"/>.
/// </summary>
public void Close()
{
if (IsClosing)
{
return;
}
IsClosing = true;
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs e)
{
base.OnPropertyChanged(e);
if (e.Property == ContentProperty && e.NewValue is IToast toast)
{
SetValue(NotificationTypeProperty, toast.Type);
}
if (e.Property == NotificationTypeProperty)
{
UpdateNotificationType();
}
if (e.Property == IsClosedProperty)
{
if (!IsClosing && !IsClosed)
{
return;
}
RaiseEvent(new RoutedEventArgs(ToastClosedEvent));
}
}
private void UpdateNotificationType()
{
switch (NotificationType)
{
case NotificationType.Error:
PseudoClasses.Add(":error");
break;
case NotificationType.Information:
PseudoClasses.Add(":information");
break;
case NotificationType.Success:
PseudoClasses.Add(":success");
break;
case NotificationType.Warning:
PseudoClasses.Add(":warning");
break;
}
}
}

View File

@@ -0,0 +1,188 @@
using System.Collections;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Metadata;
using Avalonia.Controls.Notifications;
using Avalonia.Controls.Primitives;
using Avalonia.Layout;
using Avalonia.Threading;
using Avalonia.VisualTree;
namespace Ursa.Controls;
/// <summary>
/// An <see cref="IToastManager"/> that displays toasts in a <see cref="Window"/>.
/// </summary>
[TemplatePart("PART_Items", typeof(Panel))]
public class WindowToastManager : TemplatedControl, IManagedToastManager
{
private IList? _items;
/// <summary>
/// Defines the <see cref="MaxItems"/> property.
/// </summary>
public static readonly StyledProperty<int> MaxItemsProperty =
AvaloniaProperty.Register<WindowToastManager, int>(nameof(MaxItems), 5);
/// <summary>
/// Defines the maximum number of toasts visible at once.
/// </summary>
public int MaxItems
{
get => GetValue(MaxItemsProperty);
set => SetValue(MaxItemsProperty, value);
}
/// <summary>
/// Initializes a new instance of the <see cref="WindowToastManager"/> class.
/// </summary>
/// <param name="host">The TopLevel that will host the control.</param>
public WindowToastManager(TopLevel? host) : this()
{
if (host is not null)
{
InstallFromTopLevel(host);
}
}
/// <summary>
/// Initializes a new instance of the <see cref="WindowToastManager"/> class.
/// </summary>
public WindowToastManager()
{
}
static WindowToastManager()
{
HorizontalAlignmentProperty.OverrideDefaultValue<WindowToastManager>(HorizontalAlignment.Stretch);
VerticalAlignmentProperty.OverrideDefaultValue<WindowToastManager>(VerticalAlignment.Stretch);
}
/// <inheritdoc/>
protected override void OnApplyTemplate(TemplateAppliedEventArgs e)
{
base.OnApplyTemplate(e);
var itemsControl = e.NameScope.Find<Panel>("PART_Items");
_items = itemsControl?.Children;
}
/// <inheritdoc/>
public void Show(IToast content)
{
Show(content, content.Type, content.Expiration, content.OnClick, content.OnClose);
}
/// <inheritdoc/>
public void Show(object content)
{
if (content is IToast toast)
{
Show(toast, toast.Type, toast.Expiration, toast.OnClick, toast.OnClose);
}
else
{
Show(content, NotificationType.Information);
}
}
/// <summary>
/// Shows a Toast
/// </summary>
/// <param name="content">the content of the toast</param>
/// <param name="type">the type of the toast</param>
/// <param name="expiration">the expiration time of the toast after which it will automatically close. If the value is Zero then the toast will remain open until the user closes it</param>
/// <param name="onClick">an Action to be run when the toast is clicked</param>
/// <param name="onClose">an Action to be run when the toast is closed</param>
/// <param name="classes">style classes to apply</param>
public async void Show(object content,
NotificationType type,
TimeSpan? expiration = null,
Action? onClick = null,
Action? onClose = null,
string[]? classes = null)
{
Dispatcher.UIThread.VerifyAccess();
var toastControl = new ToastCard
{
Content = content,
NotificationType = type
};
// Add style classes if any
if (classes != null)
{
foreach (var @class in classes)
{
toastControl.Classes.Add(@class);
}
}
toastControl.ToastClosed += (sender, args) =>
{
onClose?.Invoke();
_items?.Remove(sender);
};
toastControl.PointerPressed += (sender, args) =>
{
onClick?.Invoke();
(sender as ToastCard)?.Close();
};
Dispatcher.UIThread.Post(() =>
{
_items?.Add(toastControl);
if (_items?.OfType<ToastCard>().Count(i => !i.IsClosing) > MaxItems)
{
_items.OfType<ToastCard>().First(i => !i.IsClosing).Close();
}
});
if (expiration == TimeSpan.Zero)
{
return;
}
await Task.Delay(expiration ?? TimeSpan.FromSeconds(5));
toastControl.Close();
}
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
}
/// <summary>
/// Installs the <see cref="WindowToastManager"/> within the <see cref="AdornerLayer"/>
/// </summary>
private void InstallFromTopLevel(TopLevel topLevel)
{
topLevel.TemplateApplied += TopLevelOnTemplateApplied;
var adorner = topLevel.FindDescendantOfType<VisualLayerManager>()?.AdornerLayer;
if (adorner is not null)
{
adorner.Children.Add(this);
AdornerLayer.SetAdornedElement(this, adorner);
}
}
private void TopLevelOnTemplateApplied(object? sender, TemplateAppliedEventArgs e)
{
if (Parent is AdornerLayer adornerLayer)
{
adornerLayer.Children.Remove(this);
AdornerLayer.SetAdornedElement(this, null);
}
// Reinstall toast manager on template reapplied.
var topLevel = (TopLevel)sender!;
topLevel.TemplateApplied -= TopLevelOnTemplateApplied;
InstallFromTopLevel(topLevel);
}
}