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(client): resolve the note contexts of every dialog and embedded pane
Elian Doraneeb701da0a4e
diff --git a/apps/client/src/components/tab_manager.spec.ts b/apps/client/src/components/tab_manager.spec.tsindex 1451ee6817..de8d3404e9 100644--- a/apps/client/src/components/tab_manager.spec.ts+++ b/apps/client/src/components/tab_manager.spec.ts@@ -270,4 +270,21 @@ describe("note contexts outside the tab row", () => {expect(tm.getCommandContext("_popup-editor")).toBe(popupContext);expect(tm.getCommandContext(undefined)).toBe(tab);});++ it("forgets a context once unregistered, and resolves an unknown one to nothing", async () => {+ const tm = new TabManager();+ await openEmptyTabs(tm, 1);+ const replaced = new NoteContext("_tree-popup");+ const current = new NoteContext("_tree-popup");++ tm.registerDetachedContext(replaced);+ tm.registerDetachedContext(current);+ // Unregistering the context a host replaced leaves the one it replaced it with.+ tm.unregisterDetachedContext(replaced);+ expect(tm.getCommandContext("_tree-popup")).toBe(current);++ tm.unregisterDetachedContext(current);+ expect(tm.getCommandContext("_tree-popup")).toBeNull();+ expect(tm.getCommandContext("_nowhere")).toBeNull();+ });});diff --git a/apps/client/src/components/tab_manager.ts b/apps/client/src/components/tab_manager.tsindex 86a18c01f1..e3bacd622d 100644--- a/apps/client/src/components/tab_manager.ts+++ b/apps/client/src/components/tab_manager.ts@@ -79,6 +79,13 @@ export default class TabManager extends Component {}}+ /** Removes `noteContext`, unless another context has since been registered under its `ntxId`. */+ unregisterDetachedContext(noteContext: NoteContext) {+ if (noteContext.ntxId && this.detachedContexts.get(noteContext.ntxId) === noteContext) {+ this.detachedContexts.delete(noteContext.ntxId);+ }+ }+get mainNoteContexts(): NoteContext[] {return this.noteContexts.filter((nc) => !nc.mainNtxId);}@@ -228,9 +235,13 @@ export default class TabManager extends Component {return this.activeNtxId ? this.getNoteContextById(this.activeNtxId).getMainContext() : null;}- /** Returns the note context with the given `ntxId`, or the active one when `ntxId` is empty. */+ /** Returns the note context with the given `ntxId`, or the active one when `ntxId` is empty. Returns `null` for an unknown `ntxId`. */getCommandContext(ntxId: string | null | undefined): NoteContext | null {- return ntxId ? this.getNoteContextById(ntxId) : this.getActiveContext();+ if (!ntxId) {+ return this.getActiveContext();+ }++ return this.noteContexts.find((nc) => nc.ntxId === ntxId) ?? this.detachedContexts.get(ntxId) ?? null;}getActiveContextNotePath(): string | null {diff --git a/apps/client/src/widgets/EmbeddedNotePane.tsx b/apps/client/src/widgets/EmbeddedNotePane.tsxindex aa3ada83a9..2a882f7f5a 100644--- a/apps/client/src/widgets/EmbeddedNotePane.tsx+++ b/apps/client/src/widgets/EmbeddedNotePane.tsx@@ -14,7 +14,7 @@ import link from "../services/link";import ActionButton from "./react/ActionButton";import Dropdown, { DropdownPanel } from "./react/Dropdown";import { FormListItem } from "./react/FormList";-import { useNoteContext } from "./react/hooks";+import { useDetachedNoteContext, useNoteContext } from "./react/hooks";import { NoteContextContext, ParentComponent } from "./react/react_utils";/*@@ -46,6 +46,7 @@ export function useEmbeddedNoteContext(note: FNote | undefined, ntxId: string) {const parentComponent = useContext(ParentComponent);const [ noteContext ] = useState(() => new NoteContext(ntxId));const [ component ] = useState(() => new Component());+ useDetachedNoteContext(noteContext);useEffect(() => {if (!parentComponent) return;diff --git a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsxindex 117cf9a3c1..cc6edcbda0 100644--- a/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx+++ b/apps/client/src/widgets/collections/geomap/DetailPane.spec.tsx@@ -176,12 +176,14 @@ describe("DetailPane", () => {container = document.createElement("div");document.body.appendChild(container);- // `tabManager` is only built when the app starts, and the pane asks it where the reader is- // hoisted.+ // `tabManager` is only built when the app starts. The pane asks it where the reader is+ // hoisted, and registers its note context with it.(appContext as unknown as { tabManager: unknown }).tabManager = {getActiveContext: () => undefined,getActiveContextNotePath: () => undefined,- openContextWithNote: async () => undefined+ openContextWithNote: async () => undefined,+ registerDetachedContext: () => undefined,+ unregisterDetachedContext: () => undefined};editorAskedToSave.mockClear();onRelocate.mockClear();@@ -191,7 +193,6 @@ describe("DetailPane", () => {});afterEach(() => {- (appContext as unknown as { tabManager: unknown }).tabManager = undefined;mapComponent = undefined;if (container) {@@ -199,6 +200,7 @@ describe("DetailPane", () => {container.remove();container = undefined;}+ (appContext as unknown as { tabManager: unknown }).tabManager = undefined;});/** Stands in for the map's own component, which is what the pane hangs under. */diff --git a/apps/client/src/widgets/dialogs/OptionsDialog.tsx b/apps/client/src/widgets/dialogs/OptionsDialog.tsxindex aec4426e3a..04b81874c3 100644--- a/apps/client/src/widgets/dialogs/OptionsDialog.tsx+++ b/apps/client/src/widgets/dialogs/OptionsDialog.tsx@@ -11,7 +11,7 @@ import utils, { isElectron, isStandalone } from "../../services/utils";import NoteDetail from "../NoteDetail";import FormList, { FormListItem } from "../react/FormList";import HelpButton from "../react/HelpButton";-import { useChildNotes, useContainedLinkNavigation, useNoteContext, useTriliumEvent } from "../react/hooks";+import { useChildNotes, useContainedLinkNavigation, useDetachedNoteContext, useNoteContext, useTriliumEvent } from "../react/hooks";import { DetailPane, MasterDetailHeader, MasterPane, useMobileMasterDetail } from "../react/master_detail";import Modal from "../react/Modal";import { NoteContextContext, ParentComponent } from "../react/react_utils";@@ -35,6 +35,7 @@ export default function OptionsDialog() {const [ shown, setShown ] = useState(false);const parentComponent = useContext(ParentComponent);const [ noteContext, setNoteContext ] = useState(() => new NoteContext("_options-dialog"));+ useDetachedNoteContext(noteContext);// Remembers the page last viewed this session so reopening the dialog lands there instead of// always on Appearance. Kept in component state (resets on reload), not persisted.const [ lastSection, setLastSection ] = useState<string | null>(null);diff --git a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsxindex 15702c1bf8..1e457b56d2 100644--- a/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx+++ b/apps/client/src/widgets/dialogs/PopupEditor.spec.tsx@@ -10,6 +10,7 @@ const mocks = vi.hoisted(() => ({openInNewTab: vi.fn(),openContextWithNote: vi.fn(),registerDetachedContext: vi.fn(),+ unregisterDetachedContext: vi.fn(),getNote: vi.fn(),getAttachment: vi.fn(),/** Every context the popup created, newest last — one is built per open. */@@ -26,7 +27,8 @@ vi.mock("../../components/app_context", () => ({tabManager: {openInNewTab: mocks.openInNewTab,openContextWithNote: mocks.openContextWithNote,- registerDetachedContext: mocks.registerDetachedContext+ registerDetachedContext: mocks.registerDetachedContext,+ unregisterDetachedContext: mocks.unregisterDetachedContext}}}));diff --git a/apps/client/src/widgets/dialogs/PopupEditor.tsx b/apps/client/src/widgets/dialogs/PopupEditor.tsxindex c904be7618..4285a1a7b3 100644--- a/apps/client/src/widgets/dialogs/PopupEditor.tsx+++ b/apps/client/src/widgets/dialogs/PopupEditor.tsx@@ -19,7 +19,7 @@ import TitleRow from "../layout/TitleRow";import NoteDetail from "../NoteDetail";import PromotedAttributes from "../PromotedAttributes";import { DropdownPanel, type DropdownHandle } from "../react/Dropdown";-import { useContainedLinkNavigation, useNoteContext, useNoteLabel, useTriliumEvent } from "../react/hooks";+import { useContainedLinkNavigation, useDetachedNoteContext, useNoteContext, useNoteLabel, useTriliumEvent } from "../react/hooks";import Modal from "../react/Modal";import { NoteContextContext, ParentComponent, POPUP_EDITOR_NTX_ID } from "../react/react_utils";import { BacklinksWidget, useBacklinkCount } from "../sidebar/Backlinks";@@ -47,6 +47,7 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =const [ noteContext, setNoteContext ] = useState(() => new NoteContext(ntxId));const modalRef = useRef<HTMLDivElement>(null);const isMobile = utils.isMobile();+ useDetachedNoteContext(noteContext);useTriliumEvent(openCommand, async ({ noteIdOrPath, viewScope, showNoteTypeSwitcher }) => {const noteId = tree.getNoteIdAndParentIdFromUrl(noteIdOrPath);@@ -77,7 +78,6 @@ export default function PopupEditor({ ntxId = POPUP_EDITOR_NTX_ID, openCommand =// Events triggered at note context level (e.g. the save indicator) would not work since the note context has no parent component. Propagate events to parent component so that they can be handled properly.noteContext.triggerEvent = (name, data) => parentComponent?.handleEventInChildren(name, data);- appContext.tabManager.registerDetachedContext(noteContext);setNoteContext(noteContext);setShown(true);});diff --git a/apps/client/src/widgets/dialogs/TreePopupEditor.tsx b/apps/client/src/widgets/dialogs/TreePopupEditor.tsxindex 73d9f99c6f..3b902f109f 100644--- a/apps/client/src/widgets/dialogs/TreePopupEditor.tsx+++ b/apps/client/src/widgets/dialogs/TreePopupEditor.tsx@@ -8,7 +8,7 @@ import TitleRow from "../layout/TitleRow";import NoteTreeWidget from "../note_tree";import NoteDetail from "../NoteDetail";import PromotedAttributes from "../PromotedAttributes";-import { useContainedLinkNavigation, useLegacyWidget, useTriliumEvent } from "../react/hooks";+import { useContainedLinkNavigation, useDetachedNoteContext, useLegacyWidget, useTriliumEvent } from "../react/hooks";import Modal from "../react/Modal";import { NoteContextContext, ParentComponent } from "../react/react_utils";@@ -25,6 +25,7 @@ export default function TreePopupEditor() {const parentComponent = useContext(ParentComponent);const [ noteContext, setNoteContext ] = useState(() => new NoteContext("_tree-popup"));const modalRef = useRef<HTMLDivElement>(null);+ useDetachedNoteContext(noteContext);useTriliumEvent("openInTreePopup", async ({ noteIdOrPath, hoistedNoteId }) => {// Fresh context per open so the sidebar tree is hoisted to the requested subtree.diff --git a/apps/client/src/widgets/react/hooks.spec.tsx b/apps/client/src/widgets/react/hooks.spec.tsxindex 4c0fcd6d00..c6aee1e8c6 100644--- a/apps/client/src/widgets/react/hooks.spec.tsx+++ b/apps/client/src/widgets/react/hooks.spec.tsx@@ -5,10 +5,14 @@ import { useRef } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import appContext from "../../components/app_context";+import type NoteContext from "../../components/note_context";+import type TabManager from "../../components/tab_manager";import { buildNote } from "../../test/easy-froca";import {type DelayedVisibilityPhase,useDelayedVisibility,+ useDetachedNoteContext,useFocusWithin,useImperativeSearchHighlighlighting,useMediaQuery,@@ -128,6 +132,36 @@ describe("useDelayedVisibility", () => {});});+describe("useDetachedNoteContext", () => {+ it("registers the context while it is in use, and unregisters it once replaced or unmounted", () => {+ const tabManager = appContext.tabManager;+ const registerDetachedContext = vi.fn();+ const unregisterDetachedContext = vi.fn();+ appContext.tabManager = { registerDetachedContext, unregisterDetachedContext } as unknown as TabManager;+ try {+ const first = { ntxId: "_tree-popup" } as NoteContext;+ const second = { ntxId: "_tree-popup" } as NoteContext;+ function Host({ noteContext }: { noteContext: NoteContext }) {+ useDetachedNoteContext(noteContext);+ return null;+ }+ const container = document.createElement("div");++ act(() => render(<Host noteContext={first} />, container));+ expect(registerDetachedContext).toHaveBeenLastCalledWith(first);++ act(() => render(<Host noteContext={second} />, container));+ expect(unregisterDetachedContext).toHaveBeenLastCalledWith(first);+ expect(registerDetachedContext).toHaveBeenLastCalledWith(second);++ act(() => render(null, container));+ expect(unregisterDetachedContext).toHaveBeenLastCalledWith(second);+ } finally {+ appContext.tabManager = tabManager;+ }+ });+});+describe("useFocusWithin", () => {let container: HTMLElement;let isFocusWithin: boolean | undefined;diff --git a/apps/client/src/widgets/react/hooks.tsx b/apps/client/src/widgets/react/hooks.tsxindex e542792114..54ef7507c0 100644--- a/apps/client/src/widgets/react/hooks.tsx+++ b/apps/client/src/widgets/react/hooks.tsx@@ -571,6 +571,17 @@ export function isContextInActiveTab(* Similar to {@link useNoteContext}, but instead of using the note context from the split container that the component is part of, it uses the active note context instead* (the note currently focused by the user).*/+/**+ * Registers `noteContext`, built outside the tab row, with `TabManager` for as long as the component+ * uses it, so that commands naming its `ntxId` resolve to it.+ */+export function useDetachedNoteContext(noteContext: NoteContext) {+ useEffect(() => {+ appContext.tabManager.registerDetachedContext(noteContext);+ return () => appContext.tabManager.unregisterDetachedContext(noteContext);+ }, [ noteContext ]);+}+export function useActiveNoteContext() {const [ noteContext, setNoteContext ] = useState<NoteContext | undefined>(appContext.tabManager.getActiveContext() ?? undefined);const [ notePath, setNotePath ] = useState<string | null | undefined>();