using Telerik.Blazor; using Telerik.Blazor.Components; namespace Prefab.Web.Client.Services; /// /// Defines a contract for displaying notifications of various types, such as errors, successes, and warnings, within an /// application. /// /// 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. public interface INotificationService { void Attach(TelerikNotification notification); void ShowError(string message); void ShowSuccess(string message); void ShowWarning(string message); } /// /// Provides functionality to display error, success, and warning notifications using a Telerik notification component. /// /// 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. public class NotificationService : INotificationService { private readonly Queue _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()); } } }