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): send requests only to the displayed type widget (closes #11751)
Elian Doran2b110f192244
diff --git a/apps/client/src/widgets/NoteDetail.spec.ts b/apps/client/src/widgets/NoteDetail.spec.tsindex 62f4c34a97..a4b1530679 100644--- a/apps/client/src/widgets/NoteDetail.spec.ts+++ b/apps/client/src/widgets/NoteDetail.spec.ts@@ -1,7 +1,10 @@import { h, render } from "preact";+import { useContext } from "preact/hooks";import { act } from "preact/test-utils";import { afterEach, describe, expect, it, vi } from "vitest";+import type { EventData } from "../components/app_context";+import Component from "../components/component";import NoteContext from "../components/note_context";import type FNote from "../entities/fnote";import froca from "../services/froca";@@ -10,8 +13,10 @@ import froca from "../services/froca";// global the test env doesn't provide. The pure function under test never touches the tree, so stub it.vi.mock("./note_tree", () => ({ default: class {} }));-import { getExtendedWidgetType, useDeferredDetailFocus } from "./NoteDetail";-import { isContextInActiveTab } from "./react/hooks";+import { getExtendedWidgetType, NoteDetailWrapper, useDeferredDetailFocus } from "./NoteDetail";+import { isContextInActiveTab, useTriliumEvent } from "./react/hooks";+import { ContainerVisibilityContext, ParentComponent } from "./react/react_utils";+import type { TypeWidgetProps } from "./type_widgets/type_widget";const FAKE_NOTE_ID = "blob-stub-note";@@ -143,3 +148,81 @@ describe("useDeferredDetailFocus", () => {expect(replay).not.toHaveBeenCalled();});});++describe("NoteDetailWrapper", () => {+ const host = document.createElement("div");+ const received: string[] = [];+ let typeWidgetParent: Component | null = null;+ let hostComponent = new Component();++ function TypeWidget() {+ typeWidgetParent = useContext(ParentComponent);+ useTriliumEvent("findInText", () => received.push("findInText"));+ useTriliumEvent("executeWithCodeEditor", () => received.push("executeWithCodeEditor"));+ useTriliumEvent("entitiesReloaded", () => received.push("entitiesReloaded"));+ useTriliumEvent("noteSwitched", () => received.push("noteSwitched"));+ return h("div", {});+ }++ function renderWrapper(isVisible: boolean, containerVisible = true) {+ const wrapper = h(NoteDetailWrapper, {+ Element: TypeWidget, type: "editableText", isVisible, isFullHeight: false,+ props: {} as TypeWidgetProps+ });+ act(() => render(+ h(ParentComponent.Provider, { value: hostComponent },+ h(ContainerVisibilityContext.Provider, { value: containerVisible }, wrapper)),+ host+ ));+ }++ async function dispatchAll() {+ await hostComponent.handleEventInChildren("findInText", {});+ await hostComponent.handleEventInChildren("executeWithCodeEditor",+ { ntxId: "ntx", resolve: () => {} } as unknown as EventData<"executeWithCodeEditor">);+ await hostComponent.handleEventInChildren("entitiesReloaded",+ {} as EventData<"entitiesReloaded">);+ await hostComponent.handleEventInChildren("noteSwitched", {} as EventData<"noteSwitched">);+ }++ afterEach(() => {+ render(null, host);+ received.length = 0;+ typeWidgetParent = null;+ hostComponent = new Component();+ });++ it("sends requests only to the displayed type widget, and syncs a hidden one", async () => {+ renderWrapper(false);+ await dispatchAll();+ expect(received).toEqual([ "entitiesReloaded", "noteSwitched" ]);++ received.length = 0;+ renderWrapper(true, false);+ await dispatchAll();+ expect(received).toEqual([ "entitiesReloaded", "noteSwitched" ]);++ received.length = 0;+ renderWrapper(true);+ await dispatchAll();+ expect(received).toEqual(+ [ "findInText", "executeWithCodeEditor", "entitiesReloaded", "noteSwitched" ]);+ });++ it("gives the type widget a parent that saves and commands as the host", () => {+ const triggerCommand = vi.spyOn(hostComponent, "triggerCommand");+ renderWrapper(true);++ const parent = typeWidgetParent;+ if (!parent) throw new Error("The type widget did not render.");+ expect(parent).not.toBe(hostComponent);+ expect(parent.componentId).toBe(hostComponent.componentId);+ expect(hostComponent.children).toContain(parent);++ parent.triggerCommand("hoistNote", { noteId: "root" });+ expect(triggerCommand).toHaveBeenCalledWith("hoistNote", { noteId: "root" });++ render(null, host);+ expect(hostComponent.children).not.toContain(parent);+ });+});diff --git a/apps/client/src/widgets/NoteDetail.tsx b/apps/client/src/widgets/NoteDetail.tsxindex 31c706a0c9..9bf9f13370 100644--- a/apps/client/src/widgets/NoteDetail.tsx+++ b/apps/client/src/widgets/NoteDetail.tsx@@ -3,9 +3,12 @@ import "./NoteDetail.css";import clsx from "clsx";import { note } from "mermaid/dist/rendering-util/rendering-elements/shapes/note.js";import { isValidElement, VNode } from "preact";-import { useCallback, useContext, useEffect, useRef, useState } from "preact/hooks";+import {+ useCallback, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState+} from "preact/hooks";-import appContext, { type EventData } from "../components/app_context";+import appContext, { type EventData, type EventNames } from "../components/app_context";+import Component from "../components/component";import NoteContext from "../components/note_context";import FNote from "../entities/fnote";import type { PrintReport } from "../print";@@ -30,7 +33,7 @@ import {import Icon from "./react/Icon";import NoItems from "./react/NoItems";import { NoteListWithLinks } from "./react/NoteList";-import { ContainerVisibilityContext } from "./react/react_utils";+import { ContainerVisibilityContext, ParentComponent } from "./react/react_utils";import { TypeWidgetProps } from "./type_widgets/type_widget";/**@@ -275,13 +278,14 @@ export function useDeferredDetailFocus(isReady: boolean, replay: (data: EventDat* Wraps a single note type widget, in order to keep it in the DOM even after the user has switched away to another note type. This allows faster loading of the same note type again. The properties are cached, so that they are updated only* while the widget is visible, to avoid rendering in the background. When not visible, the DOM element is simply hidden.*/-function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: { Element: (props: TypeWidgetProps) => VNode, type: ExtendedNoteType, isVisible: boolean, isFullHeight: boolean, props: TypeWidgetProps }) {+export function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: { Element: (props: TypeWidgetProps) => VNode, type: ExtendedNoteType, isVisible: boolean, isFullHeight: boolean, props: TypeWidgetProps }) {// False when an enclosing dialog (e.g. the quick-edit popup) is hidden but kept in the DOM, so a widget// there is told it isn't displayed even though it's the context's current type — letting a media player// inside a closed popup stop, just like one in a navigated-away tab.const containerVisible = useContext(ContainerVisibilityContext);const [ cachedProps, setCachedProps ] = useState(props);const wrapperRef = useRef<HTMLDivElement>(null);+ const eventGate = useTypeWidgetEventGate(isVisible && containerVisible);useEffect(() => {if (isVisible) {@@ -309,11 +313,61 @@ function NoteDetailWrapper({ Element, type, isVisible, isFullHeight, props }: {height: isFullHeight ? "100%" : ""}}>- <Element {...cachedProps} isVisible={isVisible && containerVisible} />+ <ParentComponent.Provider value={eventGate}>+ <Element {...cachedProps} isVisible={isVisible && containerVisible} />+ </ParentComponent.Provider></div>);}+/**+ * Events that reach a type widget while `NoteDetailWrapper` hides it. They keep its state current+ * for when it is displayed again; every other event is meant for the displayed type widget only.+ */+const EVENTS_FOR_HIDDEN_TYPE_WIDGETS = new Set<EventNames>([+ "entitiesReloaded", "frocaReloaded", "refreshEmbeddedNote", "searchRefreshed", "apiLogMessages",+ "themeChanged", "protectedSessionStarted", "readOnlyTemporarilyDisabled", "contextDataChanged",+ "setNoteContext", "activeContextChanged", "activeNoteChanged", "hoistedNoteChanged",+ "noteSwitched", "noteSwitchedAndActivated", "beforeNoteSwitch", "noteTypeMimeChanged",+ "beforeNoteContextRemove"+]);++/**+ * Stands between `NoteDetail`'s component and one cached type widget, and stops the events in+ * `handleEventInChildren()` that a hidden type widget must not answer. It takes the host's+ * `componentId`, so the type widget's saves still count as `NoteDetail`'s own.+ */+class TypeWidgetEventGate extends Component {+ isDisplayed = true;++ constructor(host: Component | null) {+ super();+ if (host) {+ this.componentId = host.componentId;+ this.setParent(host);+ }+ }++ handleEventInChildren<T extends EventNames>(name: T, data: EventData<T>) {+ if (!this.isDisplayed && !EVENTS_FOR_HIDDEN_TYPE_WIDGETS.has(name)) return null;+ return super.handleEventInChildren(name, data);+ }+}++function useTypeWidgetEventGate(isDisplayed: boolean) {+ const host = useContext(ParentComponent);+ const gate = useMemo(() => new TypeWidgetEventGate(host), [ host ]);+ gate.isDisplayed = isDisplayed;++ useLayoutEffect(() => {+ if (!host) return;+ host.child(gate);+ return () => host.removeChild(gate);+ }, [ host, gate ]);++ return gate;+}+/*** Covers the note detail while the note's content is being fetched, so the user is not left* looking at (and typing into) the previous note's content when the blob is slow to arrive.