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,33 @@
<UserControl x:Class="Ursa.Demo.Pages.ToastDemo"
xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:vm="using:Ursa.Demo.ViewModels"
x:DataType="vm:ToastDemoViewModel"
d:DesignHeight="450"
d:DesignWidth="800"
mc:Ignorable="d">
<Design.DataContext>
<vm:ToastDemoViewModel />
</Design.DataContext>
<StackPanel>
<StackPanel Orientation="Horizontal" Spacing="20">
<Button Command="{Binding ShowNormal}" CommandParameter="{Binding $self.Content}" Content="Information" />
<Button Command="{Binding ShowNormal}" CommandParameter="{Binding $self.Content}" Content="Success" Classes="Success" />
<Button Command="{Binding ShowNormal}" CommandParameter="{Binding $self.Content}" Content="Warning" Classes="Warning" />
<Button Command="{Binding ShowNormal}" CommandParameter="{Binding $self.Content}" Content="Error" Classes="Danger" />
</StackPanel>
<StackPanel Orientation="Horizontal" Spacing="20">
<StackPanel.Styles>
<Style Selector="Button">
<Setter Property="Theme" Value="{DynamicResource SolidButton}" />
</Style>
</StackPanel.Styles>
<Button Command="{Binding ShowLight}" CommandParameter="{Binding $self.Content}" Content="Information" />
<Button Command="{Binding ShowLight}" CommandParameter="{Binding $self.Content}" Content="Success" Classes="Success" />
<Button Command="{Binding ShowLight}" CommandParameter="{Binding $self.Content}" Content="Warning" Classes="Warning" />
<Button Command="{Binding ShowLight}" CommandParameter="{Binding $self.Content}" Content="Error" Classes="Danger" />
</StackPanel>
</StackPanel>
</UserControl>

View File

@@ -0,0 +1,25 @@
using Avalonia;
using Avalonia.Controls;
using Ursa.Controls;
using Ursa.Demo.ViewModels;
namespace Ursa.Demo.Pages;
public partial class ToastDemo : UserControl
{
private ToastDemoViewModel _viewModel;
public ToastDemo()
{
InitializeComponent();
_viewModel = new ToastDemoViewModel();
DataContext = _viewModel;
}
protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
{
base.OnAttachedToVisualTree(e);
var topLevel = TopLevel.GetTopLevel(this);
_viewModel.ToastManager = new WindowToastManager(topLevel) { MaxItems = 3 };
}
}

View File

@@ -67,6 +67,7 @@ public class MainViewViewModel : ViewModelBase
MenuKeys.MenuKeyTreeComboBox => new TreeComboBoxDemoViewModel(),
MenuKeys.MenuKeyTwoTonePathIcon => new TwoTonePathIconDemoViewModel(),
MenuKeys.MenuKeyThemeToggler => new ThemeTogglerDemoViewModel(),
MenuKeys.MenuKeyToast => new ToastDemoViewModel(),
MenuKeys.MenuKeyToolBar => new ToolBarDemoViewModel(),
MenuKeys.MenuKeyTimeBox => new TimeBoxDemoViewModel(),
MenuKeys.MenuKeyPinCode => new PinCodeDemoViewModel(),

View File

@@ -53,6 +53,7 @@ public class MenuViewModel: ViewModelBase
new() { MenuHeader = "Timeline", Key = MenuKeys.MenuKeyTimeline },
new() { MenuHeader = "TreeComboBox", Key = MenuKeys.MenuKeyTreeComboBox },
new() { MenuHeader = "TwoTonePathIcon", Key = MenuKeys.MenuKeyTwoTonePathIcon},
new() { MenuHeader = "Toast", Key = MenuKeys.MenuKeyToast },
new() { MenuHeader = "ToolBar", Key = MenuKeys.MenuKeyToolBar },
new() { MenuHeader = "Time Box", Key = MenuKeys.MenuKeyTimeBox },
};
@@ -102,6 +103,7 @@ public static class MenuKeys
public const string MenuKeyTwoTonePathIcon = "TwoTonePathIcon";
public const string MenuKeyThemeToggler = "ThemeToggler";
public const string MenuKeyTreeComboBox = "TreeComboBox";
public const string MenuKeyToast = "Toast";
public const string MenuKeyToolBar = "ToolBar";
public const string MenuKeyPinCode = "PinCode";
public const string MenuKeyTimeBox = "TimeBox";

View File

@@ -0,0 +1,57 @@
using System;
using Avalonia.Controls.Notifications;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using Ursa.Controls;
namespace Ursa.Demo.ViewModels;
public partial class ToastDemoViewModel : ObservableObject
{
public WindowToastManager? ToastManager { get; set; }
[RelayCommand]
public void ShowNormal(object obj)
{
if (obj is string s)
{
Enum.TryParse<NotificationType>(s, out var notificationType);
ToastManager?.Show(
new Toast("This is message"),
type: notificationType);
}
// ToastManager?.Show(new ToastDemoViewModel
// {
// Content = "This is message",
// ToastManager = ToastManager
// });
}
[RelayCommand]
public void ShowLight(object obj)
{
if (obj is string s)
{
Enum.TryParse<NotificationType>(s, out var notificationType);
ToastManager?.Show(
new Toast("This is message"),
type: notificationType,
classes: ["Light"]);
}
}
public string? Content { get; set; }
[RelayCommand]
public void YesCommand()
{
ToastManager?.Show(new Toast("Yes!"));
}
[RelayCommand]
public void NoCommand()
{
ToastManager?.Show(new Toast("No!"));
}
}

View File

@@ -0,0 +1,196 @@
<ResourceDictionary xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:u="https://irihi.tech/ursa">
<Design.PreviewWith>
<ThemeVariantScope RequestedThemeVariant="Dark">
<StackPanel>
<u:ToastCard>
Hello, Semi.Avalonia!
</u:ToastCard>
<u:ToastCard NotificationType="Success">
<u:Toast Content="Hello, Semi.Avalonia!" />
</u:ToastCard>
<u:ToastCard NotificationType="Warning">
<u:Toast Content="Hello, Semi.Avalonia!" />
</u:ToastCard>
<u:ToastCard NotificationType="Error">
<u:Toast Content="Hello, Semi.Avalonia!" />
</u:ToastCard>
</StackPanel>
</ThemeVariantScope>
</Design.PreviewWith>
<ControlTheme x:Key="{x:Type u:WindowToastManager}" TargetType="u:WindowToastManager">
<Setter Property="Margin" Value="0" />
<Setter Property="Template">
<ControlTemplate>
<ReversibleStackPanel Name="PART_Items" />
</ControlTemplate>
</Setter>
<Style Selector="^ /template/ ReversibleStackPanel#PART_Items">
<Setter Property="VerticalAlignment" Value="Top" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
</ControlTheme>
<ControlTheme x:Key="{x:Type u:ToastCard}" TargetType="u:ToastCard">
<Setter Property="UseLayoutRounding" Value="True" />
<Setter Property="MinWidth" Value="{DynamicResource NotificationCardMinWidth}" />
<Setter Property="RenderTransformOrigin" Value="50%,75%" />
<Setter Property="BorderThickness" Value="{DynamicResource NotificationCardBorderThickness}" />
<Setter Property="BorderBrush" Value="{DynamicResource NotificationCardBorderBrush}" />
<Setter Property="Background" Value="{DynamicResource NotificationCardBackground}" />
<Setter Property="CornerRadius" Value="{DynamicResource NotificationCardCornerRadius}" />
<Setter Property="Template">
<ControlTemplate TargetType="u:ToastCard">
<LayoutTransformControl Name="PART_LayoutTransformControl" UseRenderTransform="True">
<Border
Margin="{DynamicResource NotificationCardMargin}"
Background="{TemplateBinding Background}"
CornerRadius="{TemplateBinding CornerRadius}">
<Border
x:Name="PART_RootBorder"
Padding="{DynamicResource NotificationCardPadding}"
BoxShadow="{DynamicResource NotificationCardBoxShadow}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}"
CornerRadius="{TemplateBinding CornerRadius}">
<DockPanel>
<PathIcon
Name="NotificationIcon"
Width="{DynamicResource NotificationCardIconWidth}"
Height="{DynamicResource NotificationCardIconHeight}"
Margin="{DynamicResource NotificationCardIconMargin}"
VerticalAlignment="Top"
IsVisible="False"
Data="{DynamicResource NotificationCardInformationIconPathData}" />
<ContentControl
Name="PART_Content"
Content="{TemplateBinding Content}">
<ContentControl.DataTemplates>
<DataTemplate DataType="u:IToast">
<SelectableTextBlock
Foreground="{DynamicResource NotificationCardMessageForeground}"
FontSize="{DynamicResource NotificationCardMessageFontSize}"
FontWeight="{DynamicResource NotificationCardMessageFontWeight}"
Text="{Binding Content}"
TextWrapping="Wrap" />
</DataTemplate>
<DataTemplate DataType="x:String">
<SelectableTextBlock
Foreground="{DynamicResource NotificationCardMessageForeground}"
FontSize="{DynamicResource NotificationCardMessageFontSize}"
FontWeight="{DynamicResource NotificationCardMessageFontWeight}"
Text="{Binding}"
TextWrapping="Wrap" />
</DataTemplate>
</ContentControl.DataTemplates>
</ContentControl>
</DockPanel>
</Border>
</Border>
</LayoutTransformControl>
</ControlTemplate>
</Setter>
<ControlTheme.Animations>
<Animation
Easing="QuadraticEaseIn"
FillMode="Forward"
Duration="0:0:0.45">
<KeyFrame Cue="0%">
<Setter Property="Opacity" Value="0" />
<Setter Property="TranslateTransform.Y" Value="20" />
<Setter Property="ScaleTransform.ScaleX" Value="0.85" />
<Setter Property="ScaleTransform.ScaleY" Value="0.85" />
</KeyFrame>
<KeyFrame Cue="30%">
<Setter Property="TranslateTransform.Y" Value="-20" />
</KeyFrame>
<KeyFrame Cue="100%">
<Setter Property="Opacity" Value="1" />
<Setter Property="TranslateTransform.Y" Value="0" />
<Setter Property="ScaleTransform.ScaleX" Value="1" />
<Setter Property="ScaleTransform.ScaleY" Value="1" />
</KeyFrame>
</Animation>
</ControlTheme.Animations>
<Style Selector="^[IsClosing=true] /template/ LayoutTransformControl#PART_LayoutTransformControl">
<Setter Property="RenderTransformOrigin" Value="50%,0%" />
<Style.Animations>
<Animation
Easing="QuadraticEaseOut"
FillMode="Forward"
Duration="0:0:0.75">
<KeyFrame Cue="0%">
<Setter Property="TranslateTransform.X" Value="0" />
<Setter Property="ScaleTransform.ScaleY" Value="1" />
</KeyFrame>
<KeyFrame Cue="70%">
<Setter Property="TranslateTransform.X" Value="800" />
<Setter Property="ScaleTransform.ScaleY" Value="1" />
</KeyFrame>
<KeyFrame Cue="100%">
<Setter Property="ScaleTransform.ScaleY" Value="0" />
<Setter Property="TranslateTransform.X" Value="800" />
</KeyFrame>
</Animation>
</Style.Animations>
</Style>
<Style Selector="^[IsClosing=true]">
<Style.Animations>
<Animation
Easing="QuadraticEaseOut"
FillMode="Forward"
Duration="0:0:1.25">
<KeyFrame Cue="100%">
<Setter Property="IsClosed" Value="True" />
</KeyFrame>
</Animation>
</Style.Animations>
</Style>
<Style Selector="^:information /template/ PathIcon#NotificationIcon">
<Setter Property="IsVisible" Value="True" />
<Setter Property="Foreground" Value="{DynamicResource NotificationCardInformationIconForeground}" />
<Setter Property="Data" Value="{DynamicResource NotificationCardInformationIconPathData}" />
</Style>
<Style Selector="^:success /template/ PathIcon#NotificationIcon">
<Setter Property="IsVisible" Value="True" />
<Setter Property="Foreground" Value="{DynamicResource NotificationCardSuccessIconForeground}" />
<Setter Property="Data" Value="{DynamicResource NotificationCardSuccessIconPathData}" />
</Style>
<Style Selector="^:warning /template/ PathIcon#NotificationIcon">
<Setter Property="IsVisible" Value="True" />
<Setter Property="Foreground" Value="{DynamicResource NotificationCardWarningIconForeground}" />
<Setter Property="Data" Value="{DynamicResource NotificationCardWarningIconPathData}" />
</Style>
<Style Selector="^:error /template/ PathIcon#NotificationIcon">
<Setter Property="IsVisible" Value="True" />
<Setter Property="Foreground" Value="{DynamicResource NotificationCardErrorIconForeground}" />
<Setter Property="Data" Value="{DynamicResource NotificationCardErrorIconPathData}" />
</Style>
<Style Selector="^.Light">
<Setter Property="Background" Value="{DynamicResource SemiColorBackground0}" />
<Style Selector="^:information /template/ Border#PART_RootBorder">
<Setter Property="BorderBrush" Value="{DynamicResource SemiColorInformation}" />
<Setter Property="Background" Value="{DynamicResource SemiColorInformationLight}" />
</Style>
<Style Selector="^:success /template/ Border#PART_RootBorder">
<Setter Property="BorderBrush" Value="{DynamicResource SemiColorSuccess}" />
<Setter Property="Background" Value="{DynamicResource SemiColorSuccessLight}" />
</Style>
<Style Selector="^:warning /template/ Border#PART_RootBorder">
<Setter Property="BorderBrush" Value="{DynamicResource SemiColorWarning}" />
<Setter Property="Background" Value="{DynamicResource SemiColorWarningLight}" />
</Style>
<Style Selector="^:error /template/ Border#PART_RootBorder">
<Setter Property="BorderBrush" Value="{DynamicResource SemiColorDanger}" />
<Setter Property="Background" Value="{DynamicResource SemiColorDangerLight}" />
</Style>
</Style>
</ControlTheme>
</ResourceDictionary>

View File

@@ -46,6 +46,7 @@
<ResourceInclude Source="TreeComboBox.axaml"/>
<ResourceInclude Source="Skeleton.axaml" />
<ResourceInclude Source="TwoTonePathIcon.axaml" />
<ResourceInclude Source="Toast.axaml" />
<ResourceInclude Source="ToolBar.axaml" />
<ResourceInclude Source="TimeBox.axaml"/>
<ResourceInclude Source="UrsaView.axaml" />

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);
}
}