Files
prefab-page-detail/Prefab.Web.Client/Services/INotificationService.cs
2025-10-27 17:39:18 -04:00

78 lines
2.6 KiB
C#

using Telerik.Blazor;
using Telerik.Blazor.Components;
namespace Prefab.Web.Client.Services;
/// <summary>
/// Defines a contract for displaying notifications of various types, such as errors, successes, and warnings, within an
/// application.
/// </summary>
/// <remarks>Implementations of this interface provide methods to present user-facing messages in a consistent
/// manner. The interface supports attaching a notification component and displaying messages with different severity
/// levels. This is typically used to inform users about the outcome of operations or to alert them to important
/// events.</remarks>
public interface INotificationService
{
void Attach(TelerikNotification notification);
void ShowError(string message);
void ShowSuccess(string message);
void ShowWarning(string message);
}
/// <summary>
/// Provides functionality to display error, success, and warning notifications using a Telerik notification component.
/// </summary>
/// <remarks>This service queues notifications if the Telerik notification component is not yet attached, and
/// displays them once the component becomes available. It is intended to be used as an abstraction for showing
/// user-facing notifications in applications that utilize Telerik UI components.</remarks>
public class NotificationService : INotificationService
{
private readonly Queue<NotificationModel> _pending = new();
private TelerikNotification? _notification;
public void Attach(TelerikNotification notification)
{
_notification = notification ?? throw new ArgumentNullException(nameof(notification));
FlushPending();
}
public void ShowError(string message) =>
Show(message, ThemeConstants.Notification.ThemeColor.Error);
public void ShowSuccess(string message) =>
Show(message, ThemeConstants.Notification.ThemeColor.Success);
public void ShowWarning(string message) =>
Show(message, ThemeConstants.Notification.ThemeColor.Warning);
private void Show(string message, string themeColor)
{
var model = new NotificationModel
{
Text = message,
ThemeColor = themeColor,
CloseAfter = 3000
};
if (_notification is { } notification)
{
notification.Show(model);
return;
}
_pending.Enqueue(model);
}
private void FlushPending()
{
if (_notification is not { } notification)
{
return;
}
while (_pending.Count > 0)
{
notification.Show(_pending.Dequeue());
}
}
}