SukiToastManager.cs 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. namespace SukiUI.Toasts
  5. {
  6. // It's important that events are raised BEFORE removing them from the manager so that the animation only plays once.
  7. public class SukiToastManager : ISukiToastManager
  8. {
  9. public event SukiToastManagerEventHandler? OnToastQueued;
  10. public event SukiToastManagerEventHandler? OnToastDismissed;
  11. public event EventHandler? OnAllToastsDismissed;
  12. private readonly List<ISukiToast> _toasts = new();
  13. public void Queue(ISukiToast toast)
  14. {
  15. _toasts.Add(toast);
  16. OnToastQueued?.Invoke(this, new SukiToastManagerEventArgs(toast));
  17. }
  18. public void Dismiss(ISukiToast toast)
  19. {
  20. if (!_toasts.Contains(toast)) return;
  21. OnToastDismissed?.Invoke(this, new SukiToastManagerEventArgs(toast));
  22. _toasts.Remove(toast);
  23. }
  24. public void Dismiss(int count)
  25. {
  26. if (!_toasts.Any()) return;
  27. if (count > _toasts.Count) count = _toasts.Count;
  28. for (var i = 0; i < count; i++)
  29. {
  30. var removed = _toasts[i];
  31. OnToastDismissed?.Invoke(this, new SukiToastManagerEventArgs(removed));
  32. _toasts.RemoveAt(i);
  33. }
  34. }
  35. public void EnsureMaximum(int maxAllowed)
  36. {
  37. if (_toasts.Count <= maxAllowed) return;
  38. Dismiss(_toasts.Count - maxAllowed);
  39. }
  40. public void DismissAll()
  41. {
  42. if (!_toasts.Any()) return;
  43. OnAllToastsDismissed?.Invoke(this, EventArgs.Empty);
  44. _toasts.Clear();
  45. }
  46. public bool IsDismissed(ISukiToast toast) => !_toasts.Contains(toast);
  47. }
  48. }