Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
fix(geomap): let the text editor find its host in the detail pane
Elian Dorancc6c55b266c1
diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsxindex dfd62b5869..7d7e145594 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx@@ -11,7 +11,7 @@ import froca from "../../../services/froca";import link from "../../../services/link";import server from "../../../services/server";import { buildNote } from "../../../test/easy-froca";-import { useNoteContext, useTriliumEvent } from "../../react/hooks";+import { useLegacyImperativeHandlers, useNoteContext, useTriliumEvent } from "../../react/hooks";import { ParentComponent } from "../../react/react_utils";import DetailPane from "./DetailPane";import { ParentMap } from "./map";@@ -34,6 +34,9 @@ vi.mock("../../NoteDetail", () => ({default: () => {const { note, viewScope } = useNoteContext();useTriliumEvent("beforeNoteContextRemove", editorAskedToSave);+ // The text editor puts what it offers the app onto its parent component, and reaches it again+ // from the DOM (see the host test below). Registered here as the real editor registers it.+ useLegacyImperativeHandlers({ loadReferenceLinkTitle: async () => {} });return (<divclassName="note-detail-stub"@@ -420,6 +423,30 @@ describe("DetailPane", () => {expect(pane()?.querySelector(".note-detail-stub")?.getAttribute("data-floating-toolbar")).toBe("true");});+ /**+ * Regression test for `component.loadReferenceLinkTitle is not a function`, which a marker+ * whose note carried a reference link died on.+ *+ * Everything the text editor asks of the app it asks of a component it finds from its own+ * element — `glob.getComponentByEl(editor.editing.view.getDomRoot())` — while what it offers+ * is put onto the component it was mounted under. The pane mounts it under one of its own, so+ * unless the pane says in the DOM which component that is, the editor arrives at the widget+ * enclosing the map, which answers to none of it.+ */+ it("stands for its own component where the editor looks for one", async () => {+ const map = fakeMap();+ await openPane(map);++ const editorEl = pane()?.querySelector(".note-detail-stub");+ const host = appContext.getComponentByEl(editorEl as HTMLElement);++ // The pane itself is what carries it, and what it carries is the component the editor's+ // own registration landed on — the pane's, not the map's.+ expect(pane()?.getAttribute("data-component-id")).toBeTruthy();+ expect(host).not.toBe(mapComponent);+ expect(typeof host?.loadReferenceLinkTitle).toBe("function");+ });+/*** Switching markers announces a note switch the editor saves on, but closing the pane* announces nothing — the widgets are only unmounted — so the pane says it itself.diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.tsxindex b954b1b9e4..a69d5e6a5b 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.tsx@@ -2,7 +2,7 @@ import "./DetailPane.css";import clsx from "clsx";import type { Map as MapLibreGLMap, MapMouseEvent } from "maplibre-gl";-import { useCallback, useContext, useEffect, useState } from "preact/hooks";+import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import Component from "../../../components/component";@@ -13,7 +13,7 @@ import link from "../../../services/link";import TitleRow from "../../layout/TitleRow";import NoteDetail from "../../NoteDetail";import ActionButton from "../../react/ActionButton";-import { useNoteColorClass, useNoteLabel } from "../../react/hooks";+import { useLegacyComponentElement, useNoteColorClass, useNoteLabel } from "../../react/hooks";import PromotedAttributes from "../../PromotedAttributes";import OverlayPanel, { OverlayPanelBody } from "../../react/OverlayPanel";import { NoteContextContext, ParentComponent } from "../../react/react_utils";@@ -170,8 +170,20 @@ function MarkerDetails({ note, isReadOnly, onClose, onRelocate }: { note: FNote;// stands in, which is the map's colour and not the marker's.const colorClass = useNoteColorClass(note);+ /*+ * The pane stands for its component in the DOM, which is how the text editor finds its host:+ * every call it makes back into the app resolves one from the element it is mounted in (see+ * `useLegacyComponentElement`). The pane provides a component of its own — the whole point of it+ * being a component is that the map does not hear the pane's note switches — so without this the+ * editor arrives at the widget enclosing the map instead, which answers to none of what it asks+ * for: a note carrying a reference link died on `loadReferenceLinkTitle is not a function`.+ */+ const paneRef = useRef<HTMLDivElement>(null);+ useLegacyComponentElement(paneRef);+return (<OverlayPanel+ containerRef={paneRef}className={clsx("geo-detail-pane", colorClass)}header={<TitleRow compact />}close={{ text: t("geo-map.close-details"), onClick: onClose }}diff --git a/apps/client/src/widgets/react/OverlayPanel.tsx b/apps/client/src/widgets/react/OverlayPanel.tsxindex 5b051f0840..6e3d3d8dca 100644--- a/apps/client/src/widgets/react/OverlayPanel.tsx+++ b/apps/client/src/widgets/react/OverlayPanel.tsx@@ -1,7 +1,7 @@import "./OverlayPanel.css";import clsx from "clsx";-import { ComponentChildren } from "preact";+import { ComponentChildren, RefObject } from "preact";import ActionButton from "./ActionButton";import Icon from "./Icon";@@ -10,6 +10,9 @@ interface OverlayPanelProps {/** Where the panel stands, how wide it is and whatever else is peculiar to it, styled by* whoever puts it there. */className?: string;+ /** The panel's own element, for a caller that has something to do with it — marking it as where+ * its component is found, say (see `useLegacyComponentElement`). */+ containerRef?: RefObject<HTMLDivElement>;/*** What heads the panel: a {@link TabStrip} where it is divided into tabs, or an* {@link OverlayPanelTitle} where there is only the one thing to show.@@ -35,9 +38,10 @@ interface OverlayPanelProps {* left to the caller, which is what differs between two of them. The same division* {@link OverlayToolbar} makes for the bars those canvases carry.*/-export default function OverlayPanel({ className, header, close, children }: OverlayPanelProps) {+export default function OverlayPanel({ className, containerRef, header, close, children }: OverlayPanelProps) {return (<div+ ref={containerRef}className={clsx("tn-overlay-panel", className)}/* Keep interactions inside the panel from reaching the canvas underneath. */onMouseDown={(e) => e.stopPropagation()}diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex 82d0a6d368..978d2e0023 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -1222,6 +1222,45 @@ export function useLegacyImperativeHandlers(handlers: Record<string, Function>)}, [ handlers ]);}+/**+ * Marks an element as the one the parent component is found at, which is how anything outside the+ * component tree asks for it: `appContext.getComponentByEl` climbs the DOM to the nearest element+ * bearing a component and reads it off there.+ *+ * The counterpart of {@link useLegacyImperativeHandlers} — that hook writes methods onto the parent+ * component, and this is what lets a caller holding only a DOM node arrive at the same object. The+ * text editor is the caller that matters: every one of its calls back into the app resolves the host+ * that way (`glob.getComponentByEl(editor.editing.view.getDomRoot())` — reference-link titles,+ * included notes, link embeds), so an editor mounted in a subtree whose parent component the DOM+ * cannot name reaches whichever widget happens to enclose it and dies on the first of those calls.+ *+ * Only needed where a subtree provides a `ParentComponent` of its own. A component built as a widget+ * marks its own element (see `BasicWidget.render`), and a React tree mounted under one answers to+ * that same widget, so the two already agree everywhere else.+ */+export function useLegacyComponentElement(elRef: RefObject<HTMLElement>) {+ const parentComponent = useContext(ParentComponent);++ useEffect(() => {+ const el = elRef.current;+ if (!el || !parentComponent) return;++ // The attribute is what the lookup searches by; the component itself is handed over as a+ // property of the element, which is where jQuery's `.prop("component")` reads it from. No+ // `component` class as a widget adds: nothing looks for it, and it carries the theme's+ // styling with it.+ el.dataset.componentId = parentComponent.componentId;+ (el as ComponentElement).component = parentComponent;++ return () => {+ delete el.dataset.componentId;+ delete (el as ComponentElement).component;+ };+ }, [ elRef, parentComponent ]);+}++type ComponentElement = HTMLElement & { component?: Component };+/*** Registers this widget's contextual shortcut hints on its host component. When the user requests* contextual shortcut help (Alt+F1 by default), the dispatcher walks up from the focused element