Skip to content

Build your personal knowledge base with Trilium Notes

chore(react): proper legacy widget injection & event handling

Elian Dorandf3aa047876a
diff --git a/apps/client/src/widgets/basic_widget.ts b/apps/client/src/widgets/basic_widget.ts
index ff3ea276cb..b783e7a216 100644
--- a/apps/client/src/widgets/basic_widget.ts
+++ b/apps/client/src/widgets/basic_widget.ts
@@ -302,6 +302,8 @@ export class ReactWrappedWidget extends BasicWidget {
for (const listener of this.listeners[name]) {
listener(data);
}
+
+ super.handleEvent(name, data);
}
registerHandler<T extends EventNames>(name: T, handler: EventHandler) {
diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx
index 82fe5545e5..a1654eb42d 100644
--- a/apps/client/src/widgets/react/hooks.tsx
+++ b/apps/client/src/widgets/react/hooks.tsx
@@ -418,26 +418,39 @@ export function useLegacyWidget(widgetFactory: () => BasicWidget, { noteContext
noteContext?: NoteContext;
} = {}) {
const ref = useRef<HTMLDivElement>(null);
- const widget = useMemo(widgetFactory, []);
const parentComponent = useContext(ParentComponent);
- useEffect(() => {
- if (!ref.current) return;
+ // Render the widget once.
+ const [ widget, renderedWidget ] = useMemo(() => {
+ const widget = widgetFactory();
- const $container = $(ref.current);
- $container.empty();
- widget.render().appendTo($container);
+ if (parentComponent) {
+ parentComponent.child(widget);
+ }
if (noteContext && widget instanceof NoteContextAwareWidget) {
- console.log("Injecting note context", noteContext);
widget.setNoteContextEvent({ noteContext });
- widget.activeContextChangedEvent({ noteContext });
}
- }, [ widget ]);
+
+ const renderedWidget = widget.render();
+ return [ widget, renderedWidget ];
+ }, [widgetFactory]);
- if (parentComponent) {
- parentComponent.child(widget);
- }
+ // Attach the widget to the parent.
+ useEffect(() => {
+ if (ref.current) {
+ ref.current.innerHTML = "";
+ renderedWidget.appendTo(ref.current);
+ }
+ }, [ renderedWidget ]);
+
+ // Inject the note context.
+ useEffect(() => {
+ console.log("Injecting note context");
+ if (noteContext && widget instanceof NoteContextAwareWidget) {
+ widget.activeContextChangedEvent({ noteContext });
+ }
+ }, [ noteContext ]);
return <div ref={ref} />
}
\ No newline at end of file