Skip to content

Build your personal knowledge base with Trilium Notes

fix(search): save the search string before the search buttons run it

Elian Doran604a4433943b
diff --git a/apps/client/src/widgets/search/SearchDefinition.spec.tsx b/apps/client/src/widgets/search/SearchDefinition.spec.tsx
new file mode 100644
index 0000000000..ed656321d4
--- /dev/null
+++ b/apps/client/src/widgets/search/SearchDefinition.spec.tsx
@@ -0,0 +1,111 @@
+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 bulk_action from "../../services/bulk_action";
+import search from "../../services/search";
+import server from "../../services/server";
+import toast from "../../services/toast";
+import { renderInto } from "../../test/render";
+import SearchDefinition from "./SearchDefinition";
+
+// Echoes the key, so a spec can find a button by its label.
+vi.mock("../../services/i18n", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../../services/i18n")>()),
+ t: (key: string) => key
+}));
+
+// Stands in for the CodeMirror editor, which loads on demand and is covered by its own spec.
+let editorProps: { onChange(value: string): void, onEnter(): void } | undefined;
+vi.mock("./SearchStringEditor", () => ({
+ default: (props: { onChange(value: string): void, onEnter(): void }) => {
+ editorProps = props;
+ return <input />;
+ }
+}));
+
+let resolveSetLabel: (() => void) | undefined;
+
+beforeEach(() => {
+ editorProps = undefined;
+ resolveSetLabel = undefined;
+ vi.spyOn(attributes, "setLabel").mockImplementation(() => new Promise<void>((resolve) => {
+ resolveSetLabel = resolve;
+ }));
+ vi.spyOn(search, "runSearchNote").mockResolvedValue({ error: undefined });
+ vi.spyOn(server, "post").mockResolvedValue(undefined);
+ vi.spyOn(bulk_action, "parseActions").mockReturnValue([]);
+ vi.spyOn(toast, "showMessage").mockImplementation(() => {});
+});
+
+afterEach(() => {
+ vi.restoreAllMocks();
+});
+
+describe("the search definition", () => {
+ it.each([
+ [ "search", "search_definition.search_button", () => search.runSearchNote ],
+ [ "search & execute", "search_definition.search_execute", () => server.post ]
+ ])("saves a search string still being typed before the %s button runs it", async (_, label, getRequest) => {
+ const container = renderDefinition();
+
+ act(() => editorProps?.onChange("#book #year"));
+ const button = [ ...container.querySelectorAll("button") ].find((b) => b.textContent?.includes(label));
+ expect(button).toBeDefined();
+ act(() => button?.click());
+ await settle();
+
+ expect(attributes.setLabel).toHaveBeenCalledWith("search1", "searchString", "#book #year");
+ // The search must not reach the server before the label it reads is saved.
+ expect(getRequest()).not.toHaveBeenCalled();
+
+ resolveSetLabel?.();
+ await settle();
+
+ expect(getRequest()).toHaveBeenCalledTimes(1);
+ });
+
+ it("saves the search string before Enter runs it", async () => {
+ renderDefinition();
+
+ act(() => editorProps?.onChange("#book #year"));
+ act(() => editorProps?.onEnter());
+ await settle();
+
+ expect(attributes.setLabel).toHaveBeenCalledWith("search1", "searchString", "#book #year");
+ expect(search.runSearchNote).not.toHaveBeenCalled();
+
+ resolveSetLabel?.();
+ await settle();
+
+ expect(search.runSearchNote).toHaveBeenCalledTimes(1);
+ });
+});
+
+function renderDefinition() {
+ const note = {
+ noteId: "search1",
+ title: "search1",
+ getLabelValue: (name: string) => (name === "searchString" ? "#book" : null),
+ getAttribute: (type: string, name: string) =>
+ (type === "label" && name === "searchString" ? {} : undefined),
+ getAttributes: () => [],
+ isHiddenCompletely: () => false
+ } as unknown as FNote;
+
+ let container: HTMLDivElement | undefined;
+ act(() => {
+ container = renderInto(<SearchDefinition note={note} ntxId="ntx1" />);
+ });
+ if (!container) {
+ throw new Error("The search definition did not render.");
+ }
+ return container;
+}
+
+async function settle() {
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ });
+}
diff --git a/apps/client/src/widgets/search/SearchDefinition.tsx b/apps/client/src/widgets/search/SearchDefinition.tsx
index f964606925..961d28ff0f 100644
--- a/apps/client/src/widgets/search/SearchDefinition.tsx
+++ b/apps/client/src/widgets/search/SearchDefinition.tsx
@@ -1,7 +1,7 @@
import "./SearchDefinition.css";
import { SaveSearchNoteResponse } from "@triliumnext/commons";
-import { useContext, useEffect, useState } from "preact/hooks";
+import { useContext, useEffect, useRef, useState } from "preact/hooks";
import { Fragment } from "preact/jsx-runtime";
import appContext from "../../components/app_context";
@@ -31,6 +31,13 @@ export default function SearchDefinition({ note, ntxId }: {
const parentComponent = useContext(ParentComponent);
const [ searchOptions, setSearchOptions ] = useState<{ availableOptions: SearchOption[], activeOptions: SearchOption[] }>();
const [ error, setError ] = useState<{ message: string }>();
+ const flushRef = useRef<() => Promise<void>>(null);
+
+ // The server reads the search options from the note's attributes, so a value still waiting
+ // in a `SpacedUpdate` is saved first.
+ async function savePendingOptions() {
+ await flushRef.current?.();
+ }
function refreshOptions() {
if (!note) return;
@@ -56,6 +63,7 @@ export default function SearchDefinition({ note, ntxId }: {
return;
}
+ await savePendingOptions();
const result = await search.runSearchNote(parentComponent, noteId, ntxId);
if (result) {
setError(result.error ? { message: result.error } : undefined);
@@ -118,6 +126,7 @@ export default function SearchDefinition({ note, ntxId }: {
attributeType={attributeType}
note={note}
refreshResults={refreshResults}
+ flushRef={flushRef}
error={error}
additionalAttributesToDelete={additionalAttributesToDelete}
defaultValue={defaultValue}
@@ -125,7 +134,11 @@ export default function SearchDefinition({ note, ntxId }: {
})}
</tbody>
<BulkActionsList note={note} />
- <SearchButtonBar note={note} refreshResults={refreshResults} />
+ <SearchButtonBar
+ note={note}
+ refreshResults={refreshResults}
+ savePendingOptions={savePendingOptions}
+ />
</table>
)}
</div>
@@ -133,11 +146,13 @@ export default function SearchDefinition({ note, ntxId }: {
);
}
-function SearchButtonBar({ note, refreshResults }: {
+function SearchButtonBar({ note, refreshResults, savePendingOptions }: {
note: FNote;
refreshResults(): void;
+ savePendingOptions(): Promise<void>;
}) {
async function searchAndExecuteActions() {
+ await savePendingOptions();
await server.post(`search-and-execute-note/${note.noteId}`);
refreshResults();
toast.showMessage(t("search_definition.actions_executed"), 3000);
diff --git a/apps/client/src/widgets/search/SearchDefinitionOptions.spec.tsx b/apps/client/src/widgets/search/SearchDefinitionOptions.spec.tsx
index e7824972dd..83f0e2d487 100644
--- a/apps/client/src/widgets/search/SearchDefinitionOptions.spec.tsx
+++ b/apps/client/src/widgets/search/SearchDefinitionOptions.spec.tsx
@@ -98,6 +98,7 @@ function renderOption(note: FNote, container?: HTMLDivElement, error?: { message
<Component
note={note}
refreshResults={() => {}}
+ flushRef={{ current: null }}
error={error}
attributeName="searchString"
attributeType="label"
diff --git a/apps/client/src/widgets/search/SearchDefinitionOptions.tsx b/apps/client/src/widgets/search/SearchDefinitionOptions.tsx
index d23b56075c..9e19657715 100644
--- a/apps/client/src/widgets/search/SearchDefinitionOptions.tsx
+++ b/apps/client/src/widgets/search/SearchDefinitionOptions.tsx
@@ -1,11 +1,11 @@
import { AttributeType } from "@triliumnext/commons";
import clsx from "clsx";
-import { ComponentChildren, VNode } from "preact";
+import { ComponentChildren, RefObject, VNode } from "preact";
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 attributes, { removeOwnedAttributesByNameOrType } from "../../services/attributes";
import { t } from "../../services/i18n";
import server from "../../services/server";
import SpacedUpdate from "../../services/spaced_update";
@@ -33,6 +33,8 @@ export interface SearchOption {
interface SearchOptionProps {
note: FNote;
refreshResults: () => void;
+ /** Set by an option that saves its value with a delay, to a function that saves it at once. */
+ flushRef: RefObject<(() => Promise<void>) | null>;
attributeName: string;
attributeType: "label" | "relation";
additionalAttributesToDelete?: { type: "label" | "relation", name: string }[];
@@ -143,21 +145,22 @@ function SearchOption({ note, className, title, titleIcon, children, help, attri
);
}
-function SearchStringOption({ note, refreshResults, error, ...restProps }: SearchOptionProps) {
- const [ searchString, setSearchString ] = useNoteLabel(note, "searchString");
+function SearchStringOption({ note, refreshResults, flushRef, error, ...restProps }: SearchOptionProps) {
+ const [ searchString ] = useNoteLabel(note, "searchString");
const currentValue = useRef(searchString ?? "");
const prepare = useCallback(() => currentValue.current, []);
const commit = useCallback(async (text: string) => {
appContext.lastSearchString = text;
- setSearchString(text);
+ // Awaited, so a search run after the flush reads the saved label.
+ await attributes.setLabel(note.noteId, "searchString", text);
if (note.title.startsWith(t("search_string.search_prefix"))) {
await server.put(`notes/${note.noteId}/title`, {
title: `${t("search_string.search_prefix")} ${text.length < 30 ? text : `${text.substr(0, 30)}…`}`
});
}
- }, [ note, setSearchString ]);
+ }, [ note ]);
const spacedUpdateRef = useRef<SpacedUpdate<string> | undefined>(undefined);
if (!spacedUpdateRef.current) {
@@ -179,6 +182,13 @@ function SearchStringOption({ note, refreshResults, error, ...restProps }: Searc
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [ note ]);
+ useEffect(() => {
+ flushRef.current = () => spacedUpdate.updateNowIfNecessary();
+ return () => {
+ flushRef.current = null;
+ };
+ }, [ flushRef, spacedUpdate ]);
+
return <>
<SearchOption
title={t("search_string.title_column")}
@@ -210,10 +220,7 @@ function SearchStringOption({ note, refreshResults, error, ...restProps }: Searc
currentValue.current = text;
spacedUpdate.scheduleUpdate();
}}
- onEnter={async () => {
- await spacedUpdate.updateNowIfNecessary();
- refreshResults();
- }}
+ onEnter={refreshResults}
/>
</SearchOption>
{error?.message && (