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(search): keep a pending search string with the note it was typed into
Elian Doran35dc60a6ce6a
diff --git a/apps/client/src/widgets/ribbon/SearchDefinitionOptions.spec.tsx b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.spec.tsxnew file mode 100644index 0000000000..21036ef026--- /dev/null+++ b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.spec.tsx@@ -0,0 +1,103 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++import FNote from "../../entities/fnote";+import attributes from "../../services/attributes";+import { renderInto } from "../../test/render";+import { SEARCH_OPTIONS } from "./SearchDefinitionOptions";++// Stands in for the CodeMirror editor, which loads on demand and is covered by its own spec.+let editorProps: { noteId: string, currentValue: string, onChange(value: string): void } | undefined;+vi.mock("./SearchStringEditor", () => ({+ default: (props: { noteId: string, currentValue: string, onChange(value: string): void }) => {+ editorProps = props;+ return <input />;+ }+}));++beforeEach(() => {+ vi.useFakeTimers();+ editorProps = undefined;+ vi.spyOn(attributes, "setLabel").mockResolvedValue(undefined);+});++afterEach(() => {+ vi.useRealTimers();+ vi.restoreAllMocks();+});++describe("the search string option", () => {+ it("saves a change still pending at a note switch against the note it was typed into", () => {+ const container = renderOption(noteWith("search1", "#book"));++ act(() => editorProps?.onChange("#book #year"));+ // The switch lands inside the debounce interval, so the change has not been written yet.+ expect(attributes.setLabel).not.toHaveBeenCalled();++ renderOption(noteWith("search2", "#author"), container);+ act(() => void vi.advanceTimersByTime(5000));++ expect(attributes.setLabel).toHaveBeenCalledTimes(1);+ expect(attributes.setLabel).toHaveBeenCalledWith("search1", "searchString", "#book #year");+ // The editor is handed the note now displayed, so what it shows is that note's query.+ expect(editorProps?.noteId).toBe("search2");+ expect(editorProps?.currentValue).toBe("#author");+ });++ it("writes a change made after the switch to the note now displayed", () => {+ const container = renderOption(noteWith("search1", "#book"));++ renderOption(noteWith("search2", "#author"), container);+ act(() => editorProps?.onChange("#author = tolkien"));+ act(() => void vi.advanceTimersByTime(5000));++ expect(attributes.setLabel).toHaveBeenCalledTimes(1);+ expect(attributes.setLabel).toHaveBeenCalledWith("search2", "searchString", "#author = tolkien");+ });+});++function noteWith(noteId: string, searchString: string) {+ return {+ noteId,+ title: noteId,+ getLabelValue: (name: string) => (name === "searchString" ? searchString : null),+ getAttribute: () => undefined,+ getAttributes: () => []+ } as unknown as FNote;+}++function renderOption(note: FNote, container?: HTMLDivElement) {+ const option = SEARCH_OPTIONS.find(({ attributeName }) => attributeName === "searchString");+ if (!option) {+ throw new Error("The search string option is missing from SEARCH_OPTIONS.");+ }++ const Component = option.component;+ const vnode = (+ <table><tbody>+ <Component+ note={note}+ refreshResults={() => {}}+ attributeName="searchString"+ attributeType="label"+ />+ </tbody></table>+ );++ if (container) {+ act(() => render(vnode, container));+ return container;+ }++ let rendered: HTMLDivElement | undefined;+ act(() => {+ rendered = renderInto(vnode);+ });++ if (!rendered) {+ throw new Error("The option did not render.");+ }++ return rendered;+}diff --git a/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsxindex 72c5f65423..584c4c9a33 100644--- a/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx+++ b/apps/client/src/widgets/ribbon/SearchDefinitionOptions.tsx@@ -1,19 +1,20 @@import { AttributeType } from "@triliumnext/commons";import clsx from "clsx";import { ComponentChildren, VNode } from "preact";-import { useMemo, useRef } from "preact/hooks";+import { useCallback, useEffect, useMemo, useRef } from "preact/hooks";import appContext from "../../components/app_context";import FNote from "../../entities/fnote";import { removeOwnedAttributesByNameOrType } from "../../services/attributes";import { t } from "../../services/i18n";import server from "../../services/server";+import SpacedUpdate from "../../services/spaced_update";import { openInAppHelpFromUrl } from "../../services/utils";import Admonition from "../react/Admonition";import FormSelect from "../react/FormSelect";import FormTextBox from "../react/FormTextBox";import HelpRemoveButtons from "../react/HelpRemoveButtons";-import { useNoteLabel, useNoteRelation, useSpacedUpdate, useTooltip } from "../react/hooks";+import { useNoteLabel, useNoteRelation, useTooltip } from "../react/hooks";import Icon from "../react/Icon";import NoteAutocomplete from "../react/NoteAutocomplete";import SearchStringEditor from "./SearchStringEditor";@@ -145,17 +146,38 @@ function SearchOption({ note, className, title, titleIcon, children, help, attrifunction SearchStringOption({ note, refreshResults, error, ...restProps }: SearchOptionProps) {const [ searchString, setSearchString ] = useNoteLabel(note, "searchString");const currentValue = useRef(searchString ?? "");- const spacedUpdate = useSpacedUpdate(async () => {- const searchString = currentValue.current;- appContext.lastSearchString = searchString;- setSearchString(searchString);++ const prepare = useCallback(() => currentValue.current, []);+ const commit = useCallback(async (text: string) => {+ appContext.lastSearchString = text;+ setSearchString(text);if (note.title.startsWith(t("search_string.search_prefix"))) {await server.put(`notes/${note.noteId}/title`, {- title: `${t("search_string.search_prefix")} ${searchString.length < 30 ? searchString : `${searchString.substr(0, 30)}…`}`+ title: `${t("search_string.search_prefix")} ${text.length < 30 ? text : `${text.substr(0, 30)}…`}`});}- }, 1000);+ }, [ note, setSearchString ]);++ const spacedUpdateRef = useRef<SpacedUpdate<string>>();+ if (!spacedUpdateRef.current) {+ spacedUpdateRef.current = new SpacedUpdate<string>({ key: note.noteId, prepare, commit }, 1000);+ }+ const spacedUpdate = spacedUpdateRef.current;++ // The ribbon reuses this component across note switches, so rebind on every render: `rebind`+ // snapshots a still-pending change against the previous note rather than the new one (#9614).+ useEffect(() => {+ spacedUpdate.rebind(note.noteId, prepare, commit);+ });++ // Runs after the rebind above, so the previous note's text has already been snapshotted.+ useEffect(() => {+ currentValue.current = searchString ?? "";+ // A `searchString` that changed on its own is the save echoing back, and must not drop+ // what is being typed.+ // eslint-disable-next-line react-hooks/exhaustive-deps+ }, [ note ]);return <><SearchOption@@ -182,6 +204,7 @@ function SearchStringOption({ note, refreshResults, error, ...restProps }: SearcclassName="search-string"autoFocusplaceholder={t("search_string.placeholder")}+ noteId={note.noteId}currentValue={searchString ?? ""}onChange={text => {currentValue.current = text;diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsxnew file mode 100644index 0000000000..aa8646c838--- /dev/null+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx@@ -0,0 +1,77 @@+import { render } from "preact";+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import { renderInto } from "../../test/render";+import SearchStringEditor from "./SearchStringEditor";++// The completions fetch attribute names and values through the server; nothing here opens the popup.+vi.mock("./search_completions", () => ({+ searchCompletionSource: () => null,+ searchCompletionIcon: () => undefined+}));++describe("SearchStringEditor", () => {+ it("replaces the document when the ribbon switches notes, focused or not", async () => {+ const onChange = vi.fn();+ const { container, editor } = await mount({ noteId: "search1", currentValue: "#book", onChange });++ editor.focus();+ expect(editor.hasFocus).toBe(true);++ // The save echoing the typed text back leaves a focused editor alone, caret and all.+ editor.dispatch({ changes: { from: 5, insert: " #year" } });+ onChange.mockClear();+ rerender(container, { noteId: "search1", currentValue: "#book", onChange });+ expect(editor.state.doc.toString()).toBe("#book #year");++ // Adopting the new note's query is not an edit; reporting it would save that query+ // straight back over itself.+ rerender(container, { noteId: "search2", currentValue: "#author = tolkien", onChange });+ expect(editor.state.doc.toString()).toBe("#author = tolkien");+ expect(onChange).not.toHaveBeenCalled();+ });++ it("follows a value that changed outside an unfocused editor, and reports what is typed", async () => {+ const onChange = vi.fn();+ const { container, editor } = await mount({ noteId: "search1", currentValue: "#book", onChange });++ rerender(container, { noteId: "search1", currentValue: "#book #year", onChange });+ expect(editor.state.doc.toString()).toBe("#book #year");+ expect(onChange).not.toHaveBeenCalled();++ editor.dispatch({ changes: { from: 11, insert: " = 1954" } });+ expect(onChange).toHaveBeenCalledWith("#book #year = 1954");+ });+});++interface Props {+ noteId: string;+ currentValue: string;+ onChange: (value: string) => void;+}++/** Renders the editor and waits for the CodeMirror modules it imports on demand. */+async function mount(props: Props) {+ const container = renderInto(<SearchStringEditor {...props} onEnter={() => {}} />);++ const { EditorView } = await import("@codemirror/view");+ let editor: InstanceType<typeof EditorView> | null = null;+ for (let attempt = 0; attempt < 50 && !editor; attempt++) {+ await new Promise((resolve) => setTimeout(resolve, 1));+ const dom = container.querySelector(".cm-editor");+ editor = dom instanceof HTMLElement ? EditorView.findFromDOM(dom) : null;+ }++ if (!editor) {+ throw new Error(`The editor did not mount: ${container.innerHTML}`);+ }++ return { container, editor };+}++function rerender(container: HTMLDivElement, props: Props) {+ act(() => {+ render(<SearchStringEditor {...props} onEnter={() => {}} />, container);+ });+}diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.tsxindex 12fa6e1593..749e0141c2 100644--- a/apps/client/src/widgets/ribbon/SearchStringEditor.tsx+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.tsx@@ -8,6 +8,8 @@ import { searchCompletionIcon, searchCompletionSource } from "./search_completiointerface SearchStringEditorProps {currentValue: string;+ /** The note `currentValue` belongs to. A change to it replaces the document. */+ noteId: string;placeholder?: string;className?: string;autoFocus?: boolean;@@ -22,13 +24,16 @@ interface SearchStringEditorProps {* CodeMirror loads on demand: `RibbonDefinition` imports the tab holding this component* statically, so a static import here would put the editor in the initial bundle.*/-export default function SearchStringEditor({ currentValue, placeholder, className, autoFocus, onChange, onEnter }: SearchStringEditorProps) {+export default function SearchStringEditor({ currentValue, noteId, placeholder, className, autoFocus, onChange, onEnter }: SearchStringEditorProps) {const parentRef = useRef<HTMLDivElement>(null);const editorRef = useRef<SingleLineEditor>();// The editor is built once, so it reaches the current props through a ref rather than// through the closure of the render that created it.const propsRef = useRef({ currentValue, onChange, onEnter });propsRef.current = { currentValue, onChange, onEnter };+ // Set while the effect below writes `currentValue` into the document, so `onChange` does not+ // report it as an edit the user made.+ const isAdopting = useRef(false);useEffect(() => {let editor: SingleLineEditor | undefined;@@ -49,7 +54,11 @@ export default function SearchStringEditor({ currentValue, placeholder, classNamextensions: [ triliumSearchHighlighter ],completionSource: searchCompletionSource,completionIcon: searchCompletionIcon,- onChange: (value) => propsRef.current.onChange(value),+ onChange: (value) => {+ if (!isAdopting.current) {+ propsRef.current.onChange(value);+ }+ },onEnter: () => propsRef.current.onEnter()});editorRef.current = editor;@@ -68,19 +77,28 @@ export default function SearchStringEditor({ currentValue, placeholder, classNam// eslint-disable-next-line react-hooks/exhaustive-deps}, []);- // Follows a value that changed outside the editor, such as the ribbon switching to another- // search note. A focused editor is left alone: the debounced save echoes the typed text back- // as `currentValue`, and replacing the document would drop the caret to the end.+ // Follows a value that changed outside the editor. Under the same `noteId` a focused editor+ // keeps its document, since the debounced save echoes the typed text back and replacing the+ // document would drop the caret to the end.+ const shownNoteId = useRef(noteId);useEffect(() => {const editor = editorRef.current;- if (!editor || editor.hasFocus || editor.state.doc.toString() === currentValue) {+ const switchedNote = shownNoteId.current !== noteId;+ shownNoteId.current = noteId;++ if (!editor || editor.state.doc.toString() === currentValue || (editor.hasFocus && !switchedNote)) {return;}- editor.dispatch({- changes: { from: 0, to: editor.state.doc.length, insert: currentValue }- });- }, [ currentValue ]);+ isAdopting.current = true;+ try {+ editor.dispatch({+ changes: { from: 0, to: editor.state.doc.length, insert: currentValue }+ });+ } finally {+ isAdopting.current = false;+ }+ }, [ currentValue, noteId ]);return <div ref={parentRef} className={clsx("search-string-editor form-control tn-input-field", className)} />;}