Skip to content

Build your personal knowledge base with Trilium Notes

fix(react/dialogs): events triggering even when modal is hidden

Elian Doran11f6462a319a
diff --git a/apps/client/src/widgets/dialogs/bulk_actions.tsx b/apps/client/src/widgets/dialogs/bulk_actions.tsx
index 8071bb5a19..f1b10d33f2 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 d645e37df1..1a37d65766 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<T extends EventNames>(eventName: T, handler: (data: EventData<T>) => 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<T extends EventNames>(eventName: T, handler: (data: EventData<T>) => 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<T extends EventNames>(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<void>, interval = 1000) {