From feec0a84149c0ae0c4ec53755d019051552e970f Mon Sep 17 00:00:00 2001 From: Ajay Bura <32841439+ajbura@users.noreply.github.com> Date: Mon, 16 Dec 2024 18:29:12 +0530 Subject: [PATCH] add notification mode hook --- src/app/hooks/useNotificationMode.ts | 66 ++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/app/hooks/useNotificationMode.ts diff --git a/src/app/hooks/useNotificationMode.ts b/src/app/hooks/useNotificationMode.ts new file mode 100644 index 00000000..8487d5f6 --- /dev/null +++ b/src/app/hooks/useNotificationMode.ts @@ -0,0 +1,66 @@ +import { PushRuleAction, PushRuleActionName, TweakName } from 'matrix-js-sdk'; +import { useCallback, useMemo } from 'react'; + +export enum NotificationMode { + OFF = 'OFF', + Notify = 'Notify', + NotifyLoud = 'NotifyLoud', +} + +type NotificationModeOptions = { + soundValue?: string; + highlight?: boolean; +}; +export const getNotificationModeActions = ( + mode: NotificationMode, + options?: NotificationModeOptions +): PushRuleAction[] => { + if (mode === NotificationMode.OFF) return []; + + const actions: PushRuleAction[] = [PushRuleActionName.Notify]; + + if (mode === NotificationMode.NotifyLoud) { + actions.push({ + set_tweak: TweakName.Sound, + value: options?.soundValue ?? 'default', + }); + } + + if (options?.highlight) { + actions.push({ + set_tweak: TweakName.Highlight, + value: true, + }); + } + + return actions; +}; + +export type GetNotificationModeCallback = (mode: NotificationMode) => PushRuleAction[]; +export const useNotificationModeActions = ( + options?: NotificationModeOptions +): GetNotificationModeCallback => { + const getAction: GetNotificationModeCallback = useCallback( + (mode) => getNotificationModeActions(mode, options), + [options] + ); + + return getAction; +}; + +export const useNotificationActionsMode = (actions: PushRuleAction[]): NotificationMode => { + const mode: NotificationMode = useMemo(() => { + const soundTweak = actions.find( + (action) => typeof action === 'object' && action.set_tweak === TweakName.Sound + ); + const notify = actions.find( + (action) => typeof action === 'string' && action === PushRuleActionName.Notify + ); + + if (notify && soundTweak) return NotificationMode.NotifyLoud; + if (notify) return NotificationMode.Notify; + return NotificationMode.OFF; + }, [actions]); + + return mode; +};