//-----------------------------------------------------------------------
//
// Copyright (c) lanedirt. All rights reserved.
// Licensed under the AGPLv3 license. See LICENSE.md file in the project root for full license information.
//
//-----------------------------------------------------------------------
namespace AliasVault.Client.Services;
///
/// Handles global notifications that should be displayed to the user, such as success or error messages. These messages
/// are stored in this object which is scoped to the current session. This allows the messages to be cached until
/// they actually have been displayed. So they can survive redirects and page reloads.
///
public sealed class GlobalNotificationService
{
///
/// Allow other components to subscribe to changes in the event object.
///
public event Action? OnChange;
///
/// Gets success messages that should be displayed to the user.
///
private List SuccessMessages { get; } = [];
///
/// Gets error messages that should be displayed to the user.
///
private List ErrorMessages { get; } = [];
///
/// Adds a success message to the list of messages that should be displayed to the user.
///
/// The message to add.
/// Whether to notify state change to subscribers. Defaults to false.
/// Set this to true if you want to show the added message instantly instead of waiting for the notification
/// display to rerender (e.g. after navigation).
public void AddSuccessMessage(string message, bool notifyStateChanged = false)
{
SuccessMessages.Add(message);
// Notify subscribers that a message has been added.
if (notifyStateChanged)
{
NotifyStateChanged();
}
}
///
/// Adds an error message to the list of messages that should be displayed to the user.
///
/// The message to add.
/// Whether to notify state change to subscribers. Defaults to false.
/// Set this to true if you want to show the added message instantly instead of waiting for the notification
/// display to rerender (e.g. after navigation).
public void AddErrorMessage(string message, bool notifyStateChanged = false)
{
ErrorMessages.Add(message);
// Notify subscribers that a message has been added.
if (notifyStateChanged)
{
NotifyStateChanged();
}
}
///
/// Returns a dictionary with messages that should be displayed to the user. After this method is called,
/// the messages are automatically cleared.
///
/// Dictionary with messages that are ready to be displayed on the next page load.
public List> GetMessagesForDisplay()
{
var messages = new List>();
foreach (var message in SuccessMessages)
{
messages.Add(new KeyValuePair("success", message));
}
foreach (var message in ErrorMessages)
{
messages.Add(new KeyValuePair("error", message));
}
// Clear messages
SuccessMessages.Clear();
ErrorMessages.Clear();
return messages;
}
///
/// Clear all messages.
///
public void ClearMessages()
{
SuccessMessages.Clear();
ErrorMessages.Clear();
NotifyStateChanged();
}
private void NotifyStateChanged() => OnChange?.Invoke();
}