From df3aa047876aaa23c6b9d3181745ce4a883b347f Mon Sep 17 00:00:00 2001 From: Elian Doran Date: Fri, 22 Aug 2025 23:33:02 +0300 Subject: [PATCH] chore(react): proper legacy widget injection & event handling --- apps/client/src/widgets/basic_widget.ts | 2 ++ apps/client/src/widgets/react/hooks.tsx | 37 +++++++++++++++++-------- 2 files changed, 27 insertions(+), 12 deletions(-) diff --git a/apps/client/src/widgets/basic_widget.ts b/apps/client/src/widgets/basic_widget.ts index ff3ea276c..b783e7a21 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(name: T, handler: EventHandler) { diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsx index 82fe5545e..a1654eb42 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(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 }); + } + + const renderedWidget = widget.render(); + return [ widget, renderedWidget ]; + }, [widgetFactory]); + + // 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 }); } - }, [ widget ]); - - if (parentComponent) { - parentComponent.child(widget); - } + }, [ noteContext ]); return
} \ No newline at end of file