From 8414f9547810a42dda3a4594477401efa6eab8b3 Mon Sep 17 00:00:00 2001 From: Frederik Bolding Date: Fri, 21 Oct 2022 17:23:44 +0200 Subject: [PATCH] Add clear function for NotificationController --- .../NotificationController.test.ts | 20 +++++++++++++++++ src/notification/NotificationController.ts | 22 ++++++++++++++++++- 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/src/notification/NotificationController.test.ts b/src/notification/NotificationController.test.ts index 89a4686bf37..da2e135154d 100644 --- a/src/notification/NotificationController.test.ts +++ b/src/notification/NotificationController.test.ts @@ -110,4 +110,24 @@ describe('NotificationController', () => { expect(Object.values(controller.state.notifications)).toHaveLength(0); }); + + it('action: NotificationController:clear', async () => { + const unrestricted = getUnrestrictedMessenger(); + const messenger = getRestrictedMessenger(unrestricted); + + const controller = new NotificationController({ + messenger, + }); + + expect( + await unrestricted.call('NotificationController:show', origin, message), + ).toBeUndefined(); + const notifications = Object.values(controller.state.notifications); + expect(notifications).toHaveLength(1); + expect( + await unrestricted.call('NotificationController:clear'), + ).toBeUndefined(); + + expect(Object.values(controller.state.notifications)).toHaveLength(0); + }); }); diff --git a/src/notification/NotificationController.ts b/src/notification/NotificationController.ts index 87c0c2da363..5cc264dfe0a 100644 --- a/src/notification/NotificationController.ts +++ b/src/notification/NotificationController.ts @@ -57,11 +57,17 @@ export type MarkNotificationRead = { handler: NotificationController['markRead']; }; +export type ClearNotifications = { + type: `${typeof name}:clear`; + handler: NotificationController['clear']; +}; + export type NotificationControllerActions = | GetNotificationControllerState | ShowNotification | DismissNotification - | MarkNotificationRead; + | MarkNotificationRead + | ClearNotifications; export type NotificationControllerMessenger = RestrictedControllerMessenger< typeof name, @@ -122,6 +128,10 @@ export class NotificationController extends BaseController< `${name}:markRead` as const, (ids: string[]) => this.markRead(ids), ); + + this.messagingSystem.registerActionHandler(`${name}:clear` as const, () => + this.clear(), + ); } /** @@ -173,4 +183,14 @@ export class NotificationController extends BaseController< } }); } + + /** + * Clears the state of the controller, removing all notifications. + * + */ + clear() { + this.update(() => { + return { ...defaultState }; + }); + } }