From 11f6462a319ad6bf7fb5e443d03b49c51b8077a1 Mon Sep 17 00:00:00 2001 From: Elian Doran Date: Sun, 10 Aug 2025 15:11:43 +0300 Subject: [PATCH] fix(react/dialogs): events triggering even when modal is hidden --- .../src/widgets/dialogs/bulk_actions.tsx | 2 +- apps/client/src/widgets/react/hooks.tsx | 22 +++++++++++++------ 2 files changed, 16 insertions(+), 8 deletions(-) diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsx index 8071bb5a1..f1b10d33f 100644 --- a/apps/client/src/widgets/dialogs/bulk_actions.tsx +++ b/apps/client/src/widgets/dialogs/bulk_actions.tsx @@ -46,7 +46,7 @@ function BulkActionComponent() { row.type === "label" && row.name === "action" && row.noteId === "_bulkAction")) { refreshExistingActions(); } - }); + }, shown); } return ( diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx index d645e37df..1a37d6576 100644 --- a/apps/client/src/widgets/react/hooks.tsx +++ b/apps/client/src/widgets/react/hooks.tsx @@ -1,15 +1,23 @@ -import { useCallback, useContext, useEffect, useMemo, useRef, useState } from "preact/hooks"; +import { useContext, useEffect, useRef } from "preact/hooks"; import { EventData, EventNames } from "../../components/app_context"; import { ParentComponent } from "./ReactBasicWidget"; import SpacedUpdate from "../../services/spaced_update"; -export default function useTriliumEvent(eventName: T, handler: (data: EventData) => void) { +/** + * Allows a React component to react to Trilium events (e.g. `entitiesReloaded`). When the desired event is triggered, the handler is invoked with the event parameters. + * + * Under the hood, it works by altering the parent (Trilium) component of the React element to introduce the corresponding event. + * + * @param eventName the name of the Trilium event to listen for. + * @param handler the handler to be invoked when the event is triggered. + * @param enabled determines whether the event should be listened to or not. Useful to conditionally limit the listener based on a state (e.g. a modal being displayed). + */ +export default function useTriliumEvent(eventName: T, handler: (data: EventData) => void, enabled = true) { const parentWidget = useContext(ParentComponent); useEffect(() => { - if (!parentWidget) { - console.warn("useTriliumEvent: No widget context found"); + if (!parentWidget || !enabled) { return; - } + } // Create a unique handler name for this specific event listener const handlerName = `${eventName}Event`; @@ -25,11 +33,11 @@ export default function useTriliumEvent(eventName: T, hand handler(data); }; - // Cleanup: restore original handler on unmount + // Cleanup: restore original handler on unmount or when disabled return () => { parentWidget[handlerName] = originalHandler; }; - }, [parentWidget]); + }, [parentWidget, enabled, eventName, handler]); } export function useSpacedUpdate(callback: () => Promise, interval = 1000) {