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
refactor(autocomplete): wire the clear and full-text search buttons
Elian Doran7a38b8f77780
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.tsindex 41e729b547..ea96c06fe2 100644--- a/apps/client/src/services/note_autocomplete_bak.spec.ts+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts@@ -144,36 +144,6 @@ describe("autocompleteSource (via dataset)", () => {noteAutocomplete.init();});- it("does the slow-search placeholder branch when fastSearch is false", async () => {- server.get = vi.fn(async () => [{ noteTitle: "R" }]) as typeof server.get;- const cbRows: any[][] = [];- const { dataset } = initAndGetSource({ fastSearch: false });- await new Promise<void>((resolve) => {- let count = 0;- dataset.source("hi", (rows) => {- cbRows.push(rows);- if (++count === 2) resolve();- });- });- // first cb: searching placeholder, second cb: actual results- expect(cbRows[0][0].noteTitle).toBe("hi");- expect("highlightedNotePathTitle" in cbRows[0][0]).toBe(true);- expect(cbRows[1]).toEqual([{ noteTitle: "R" }]);- expect(server.get).toHaveBeenCalledWith(- expect.stringContaining("fastSearch=false")- );- });-- it("returns early on blank term when fastSearch is false", async () => {- server.get = vi.fn(async () => [{ noteTitle: "R" }]) as typeof server.get;- const { dataset } = initAndGetSource({ fastSearch: false });- const cb = vi.fn();- // blank term -> autocompleteSource returns before touching the server / cb- await runSourceRaw(dataset, " ", cb);- expect(cb).not.toHaveBeenCalled();- expect(server.get).not.toHaveBeenCalled();- });-it("appends a search-notes suggestion when allowJumpToSearchNotes", async () => {server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;const { dataset } = initAndGetSource({ allowJumpToSearchNotes: true });@@ -327,50 +297,6 @@ describe("initNoteAutocomplete wiring", () => {expect(result).toBe($el);});- it("adds all buttons and wires their click handlers", () => {- const $group = $(`<div class="input-group"></div>`);- const $el = makeEl();- $group.append($el);- noteAutocomplete.initNoteAutocomplete($el);-- expect($el.hasClass("note-autocomplete-input")).toBe(true);- expect($group.find(".input-clearer-button").length).toBe(1);- expect($group.find(".full-text-search-button").length).toBe(1);- expect($group.find(".go-to-selected-note-button").length).toBe(1);-- const onInput = vi.fn();- $el.on("input", onInput);-- // clear button -> autocomplete("val", "") + change trigger. Also re-triggers "input" so- // consumers tracking the live query (e.g. jump_to_note.tsx's actualText ref) don't go- // stale when the value is cleared programmatically instead of by typing.- $group.find(".input-clearer-button").trigger("click");- expect(autocompleteCalls.some((c) => c[0] === "val" && c[1] === "")).toBe(true);- expect(onInput).toHaveBeenCalled();-- // full text search button click- $el.autocomplete("val", "search me");- $group.find(".full-text-search-button").trigger("click");- });-- it("hides the go-to button only when hideGoToSelectedNoteButton is set", () => {- const $group = $(`<div class="input-group"></div>`);- const $el = makeEl();- $group.append($el);- noteAutocomplete.initNoteAutocomplete($el, { hideGoToSelectedNoteButton: true });- expect($group.find(".go-to-selected-note-button").length).toBe(0);- expect($group.find(".full-text-search-button").length).toBe(1);- });-- it("hides all buttons when hideAllButtons is set", () => {- const $group = $(`<div class="input-group"></div>`);- const $el = makeEl();- $group.append($el);- noteAutocomplete.initNoteAutocomplete($el, { hideAllButtons: true });- expect($group.find(".input-clearer-button").length).toBe(0);- expect($group.find(".go-to-selected-note-button").length).toBe(0);- });-it("Ctrl+Enter triggers a search-notes selection when allowJumpToSearchNotes", () => {const $el = makeEl();const selected = vi.fn();@@ -385,30 +311,7 @@ describe("initNoteAutocomplete wiring", () => {expect(payload.action).toBe("search-notes");});- it("Shift+Enter performs a full text search", () => {- const $el = makeEl();- noteAutocomplete.initNoteAutocomplete($el);- $el.autocomplete("val", "some text");- const callsBefore = autocompleteCalls.length;- const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });- $el.trigger(ev);- // fullTextSearch re-runs the search: it clears val ("val", "") and then- // re-sets it to the captured search string ("val", "some text"). Assert- // BOTH setter calls happened after the Shift+Enter, proving the body after- // the blank-string guard actually ran (not merely the getter read).- const setterCallsAfter = autocompleteCalls- .slice(callsBefore)- .filter((c) => c[0] === "val" && c[1] !== undefined)- .map((c) => c[1]);- expect(setterCallsAfter).toContain("");- expect(setterCallsAfter).toContain("some text");- // the clear ("val", "") must precede the re-set ("val", "some text")- expect(setterCallsAfter.indexOf("")).toBeLessThan(setterCallsAfter.indexOf("some text"));- // and the input ends up re-populated with the search string- expect($el.autocomplete("val")).toBe("some text");- });-- it("ignores keydowns that are not Ctrl+Enter / Shift+Enter", () => {+ it("ignores keydowns that are not Ctrl+Enter", () => {const $el = makeEl();const selected = vi.fn();($el as any).on("autocomplete:selected", selected);@@ -416,9 +319,8 @@ describe("initNoteAutocomplete wiring", () => {// a plain key press -> neither handler fires its body$el.trigger($.Event("keydown", { key: "a" }));- // Ctrl without Enter, Shift without Enter+ // Ctrl without Enter$el.trigger($.Event("keydown", { ctrlKey: true, key: "a" }));- $el.trigger($.Event("keydown", { shiftKey: true, key: "b" }));expect(selected).not.toHaveBeenCalled();});@@ -481,23 +383,6 @@ describe("initNoteAutocomplete wiring", () => {expect($el.autocomplete("val")).toBe("composed");});- it("autocomplete:closed clears text when the input is blank", () => {- const $el = makeEl();- noteAutocomplete.initNoteAutocomplete($el);- $el.val("");- $el.trigger("autocomplete:closed");- // clearText sets the path to ""- expect($el.attr("data-note-path")).toBe("");- });-- it("autocomplete:closed leaves a non-blank input untouched", () => {- const $el = makeEl();- noteAutocomplete.initNoteAutocomplete($el);- $el.val("keep me");- $el.attr("data-note-path", "root/keep");- $el.trigger("autocomplete:closed");- expect($el.attr("data-note-path")).toBe("root/keep");- });});describe("autocomplete:selected handler", () => {@@ -598,32 +483,3 @@ describe("autocomplete:selected handler", () => {expect(handlers["autocomplete:noteselected"]).toBeDefined();});});--describe("public helpers", () => {- beforeEach(() => {- vi.clearAllMocks();- registerAutocompleteStub();- server.get = vi.fn(async () => []) as typeof server.get;- noteAutocomplete.init();- });-- it("returns early when the search string is blank (Shift+Enter on empty input)", () => {- const $el = makeEl();- noteAutocomplete.initNoteAutocomplete($el);- $el.autocomplete("val", " ");- const callsBefore = autocompleteCalls.length;- const ev = $.Event("keydown", { shiftKey: true, key: "Enter" });- $el.trigger(ev);- // `fullTextSearch` bails out at the blank-string guard, so the only autocomplete call it- // can make is the getter read on its first line. Running on would have written- // ["val", ""] and then ["val", " "], so the absence of any setter call is what- // separates the two paths.- const callsAfter = autocompleteCalls.slice(callsBefore);- const setterCalls = callsAfter.filter((c) => c[0] === "val" && c[1] !== undefined);- expect(setterCalls).toEqual([]);- // every autocomplete call after Shift+Enter is at most the guard's getter read- expect(callsAfter.every((c) => c[0] === "val" && c[1] === undefined)).toBe(true);- // setSelectedNotePath (which runs only on the non-early path) was not called- expect($el.attr("data-note-path") ?? "").toBe("");- });-});diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.tsindex 7806728462..384e5c915d 100644--- a/apps/client/src/services/note_autocomplete_bak.ts+++ b/apps/client/src/services/note_autocomplete_bak.ts@@ -12,24 +12,9 @@ const SELECTED_NOTE_PATH_KEY = "data-note-path";const SELECTED_EXTERNAL_LINK_KEY = "data-external-link";async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void, options: Options = {}) {- const fastSearch = options.fastSearch !== false;- if (fastSearch === false) {- if (term.trim().length === 0) {- return;- }- cb([- {- noteTitle: term,- highlightedNotePathTitle: t("quick-search.searching")- }- ]);- }-const length = term.trim().length;- let results = await getNoteSuggestions(term, { allowCreatingNotes: options.allowCreatingNotes, fastSearch });-- options.fastSearch = true;+ let results = await getNoteSuggestions(term, { allowCreatingNotes: options.allowCreatingNotes });if (length >= 1 && options.allowJumpToSearchNotes) {results = results.concat([@@ -54,27 +39,6 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => voidcb(results);}-// `autocomplete("val", ...)` does not dispatch a native "input" event, so each function below-// fires one to keep consumers bound to it, such as NoteAutocomplete's onTextChange, in sync.--function clearText($el: JQuery<HTMLElement>) {- $el.setSelectedNotePath("");- $el.autocomplete("val", "").trigger("change");- $el.trigger("input");-}--function fullTextSearch($el: JQuery<HTMLElement>, options: Options) {- const searchString = $el.autocomplete("val") as unknown as string;- if (options.fastSearch === false || searchString?.trim().length === 0) {- return;- }- $el.trigger("focus");- options.fastSearch = false;- $el.autocomplete("val", "");- $el.setSelectedNotePath("");- $el.autocomplete("val", searchString);-}-function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {if ($el.hasClass("note-autocomplete-input")) {// clear any event listener added in previous invocation of this function@@ -101,29 +65,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.addClass("note-autocomplete-input");- const $clearTextButton = $("<a>").addClass("input-group-text input-clearer-button bx bxs-tag-x").prop("title", t("note_autocomplete.clear-text-field"));-- const $fullTextSearchButton = $("<a>")- .addClass("input-group-text full-text-search-button bx bx-search")- .prop("title", `${t("note_autocomplete.full-text-search")} (Shift+Enter)`);-- const $goToSelectedNoteButton = $("<a>").addClass("input-group-text go-to-selected-note-button bx bx-arrow-to-right");-- if (!options.hideAllButtons) {- $el.after($clearTextButton).after($fullTextSearchButton);- }-- if (!options.hideGoToSelectedNoteButton && !options.hideAllButtons) {- $el.after($goToSelectedNoteButton);- }-- $clearTextButton.on("click", () => clearText($el));-- $fullTextSearchButton.on("click", (e) => {- fullTextSearch($el, options);- return false;- });-if (options.allowJumpToSearchNotes) {$el.on("keydown", (event) => {if (event.ctrlKey && event.key === "Enter") {@@ -134,14 +75,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {}});}- $el.on("keydown", async (event) => {- if (event.shiftKey && event.key === "Enter") {- // Prevent Enter from triggering autoComplete.- event.stopImmediatePropagation();- event.preventDefault();- fullTextSearch($el, options);- }- });$el.on("keydown", (event) => {const isPlainEnter = event.key === "Enter"&& !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;@@ -240,12 +173,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {$el.trigger("autocomplete:noteselected", [suggestion]);});- $el.on("autocomplete:closed", () => {- if (!String($el.val())?.trim()) {- clearText($el);- }- });-// clear any event listener added in previous invocation of this function$el.off("autocomplete:noteselected");diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 4fa4de17b5..7bc24bebba 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -412,6 +412,82 @@ describe("NoteAutocomplete's suggestion list", () => {expect(document.activeElement).not.toBe(input);});+ function button(selector: string) {+ const found = document.querySelector<HTMLElement>(selector);+ if (!found) throw new Error(`no ${selector} rendered`);+ return found;+ }++ it("empties the field and reports a cleared selection from the clear button", async () => {+ const onChange = vi.fn();+ const noteIdChanged = vi.fn();+ const onTextChange = vi.fn();+ const input = await mount({ onChange, noteIdChanged, onTextChange });+ await type(input, "a");+ await press(input, "Enter");++ await act(async () => { button(".input-clearer-button").click(); });++ expect(input.value).toBe("");+ expect(input.dataset.notePath).toBe("");+ expect(onTextChange).toHaveBeenLastCalledWith("");+ expect(onChange).toHaveBeenLastCalledWith(null);+ expect(noteIdChanged).toHaveBeenLastCalledWith(undefined);+ });++ it("searches the content from the full-text button, saying so until the results come", async () => {+ let finish: (rows: Suggestion[]) => void = () => {};+ const onChange = vi.fn();+ const input = await mount({ onChange });+ await type(input, "al");+ getNoteSuggestions.mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }));++ const mouseDown = new MouseEvent("mousedown", { bubbles: true, cancelable: true });+ button(".full-text-search-button").dispatchEvent(mouseDown);+ await act(async () => { button(".full-text-search-button").click(); });+ await settle();++ expect(mouseDown.defaultPrevented).toBe(true);+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { fastSearch: false });+ expect(rows()).toHaveLength(1);+ expect(rows()[0].querySelector(".search-result-title")).not.toBeNull();+ expect(rows()[0].getAttribute("role")).toBeNull();++ // Enter waits for the results rather than taking a row of the fast search.+ await press(input, "Enter");+ expect(input.dataset.notePath).toBe("");++ await act(async () => { finish([ notes[1] ]); });+ await settle();+ expect(rows()).toHaveLength(1);+ expect(rows()[0].querySelector(".search-result-title")?.textContent).toBe("X / Beta");+ expect(onChange).not.toHaveBeenCalled();++ // The next keystroke searches the titles again.+ await type(input, "alp");+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("alp");+ });++ it("searches the content on Shift+Enter, keeping the key from the host", async () => {+ const onKeyDown = vi.fn();+ const input = await mount({ onKeyDown });++ // Nothing to search for in an empty field.+ const empty = new KeyboardEvent("keydown", { key: "Enter", shiftKey: true, bubbles: true, cancelable: true });+ await act(async () => { input.dispatchEvent(empty); });+ await settle();+ expect(getNoteSuggestions).not.toHaveBeenCalled();++ await type(input, "al");+ const shiftEnter = new KeyboardEvent("keydown", { key: "Enter", shiftKey: true, bubbles: true, cancelable: true });+ await act(async () => { input.dispatchEvent(shiftEnter); });+ await settle();++ expect(shiftEnter.defaultPrevented).toBe(true);+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { fastSearch: false });+ expect(onKeyDown).not.toHaveBeenCalledWith(shiftEnter);+ });+it("spans the whole field, the buttons included", async () => {const input = await mount();const group = input.closest(".input-group");diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex a015095857..0ac8d028a0 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -54,10 +54,27 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,const [ value, setValue ] = useState("");const [ notePath, setNotePath ] = useState("");+ // Counts the full-text searches asked for since the last keystroke, which resets it, so that each+ // one changes `source` and so searches again.+ const [ fullTextSearchCount, setFullTextSearchCount ] = useState(0);+ const [ isSearchingFullText, setSearchingFullText ] = useState(false);+const isCommandPalette = !!opts?.isCommandPalette;- const source = useCallback(async (query: string) => (isCommandPalette && query.startsWith(">")- ? getCommandSuggestions(query)- : getNoteSuggestions(query)), [ isCommandPalette ]);+ const source = useCallback(async (query: string) => {+ if (isCommandPalette && query.startsWith(">")) {+ return getCommandSuggestions(query);+ }+ if (!fullTextSearchCount) {+ return getNoteSuggestions(query);+ }++ setSearchingFullText(true);+ try {+ return await getNoteSuggestions(query, { fastSearch: false });+ } finally {+ setSearchingFullText(false);+ }+ }, [ isCommandPalette, fullTextSearchCount ]);const schedule = useMemo(() => createSearchScheduler(), []);const pickSuggestion = useCallback((suggestion: Suggestion) => {@@ -86,8 +103,34 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,schedule});+ /** Drops the selected note, and reports that to the host. */+ function clearSelection() {+ setNotePath("");+ onChange?.(null);+ // The callers tell a cleared selection by `undefined` (`noteId ?? "root"`), which the prop's+ // type does not admit.+ noteIdChanged?.(undefined as unknown as string);+ }++ function clearText() {+ setValue("");+ setFullTextSearchCount(0);+ onTextChange?.("");+ clearSelection();+ }++ /** Searches the content of the notes as well as their titles, for the text in the field. */+ function fullTextSearch() {+ if (!value.trim()) return;+ setNotePath("");+ setFullTextSearchCount((count) => count + 1);+ autocomplete.open();+ inputRef.current?.focus();+ }+/** Puts `query` in the field with `selectedPath` as its selection, and lists the suggestions. */function showSuggestionsFor(query: string, selectedPath = "") {+ setFullTextSearchCount(0);setNotePath(selectedPath);setValue(query);// Written at once as well, so a caller can select the text right after the call.@@ -146,19 +189,28 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,onInput={(e) => {const newValue = e.currentTarget.value;setValue(newValue);+ setFullTextSearchCount(0);autocomplete.handleInput();onTextChange?.(newValue);}}onChange={(e) => {// Emptying the field clears the selection.- if (e.currentTarget.value) return;- setNotePath("");- onChange?.(null);- // The callers tell a cleared selection by `undefined` (`noteId ?? "root"`),- // which the prop's type does not admit.- noteIdChanged?.(undefined as unknown as string);+ if (!e.currentTarget.value) clearSelection();}}onKeyDown={(e) => {+ if (e.key === "Enter" && e.shiftKey) {+ // Kept from the host and the list, as the jQuery plugin did.+ e.preventDefault();+ e.stopPropagation();+ fullTextSearch();+ return;+ }+ // The rows of the fast search stay behind the row saying it is searching, so Enter+ // waits for the full-text results instead of taking one of them.+ if (e.key === "Enter" && isSearchingFullText) {+ e.preventDefault();+ return;+ }// A list in the host's container stays until a pick, so the keys that close a// popup are left to the host, such as a dialog closing on Escape.if (!container || (e.key !== "Escape" && e.key !== "Tab")) {@@ -184,6 +236,9 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,<aclassName="input-group-text full-text-search-button bx bx-search"title={`${t("note_autocomplete.full-text-search")} (Shift+Enter)`}+ // Keeps the focus in the input, which the list closes without.+ onMouseDown={(e) => e.preventDefault()}+ onClick={fullTextSearch}/><aclassName="input-group-text show-recent-notes-button bx bx-time"@@ -195,12 +250,13 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,<aclassName="input-group-text input-clearer-button bx bxs-tag-x"title={t("note_autocomplete.clear-text-field")}+ onClick={clearText}/></>}- {autocomplete.isShown && (container+ {(autocomplete.isShown || (autocomplete.isOpen && isSearchingFullText)) && (container? container.current && createPortal(- <NoteSuggestionList autocomplete={autocomplete} />,+ <NoteSuggestionList autocomplete={autocomplete} searchingFor={isSearchingFullText ? value : undefined} />,container.current): groupRef.current && (<Popup@@ -213,15 +269,21 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,escapeDismisses={false}onDismiss={autocomplete.close}>- <NoteSuggestionList autocomplete={autocomplete} />+ <NoteSuggestionList autocomplete={autocomplete} searchingFor={isSearchingFullText ? value : undefined} /></Popup>))}</div>);}-/** The list of suggestions, in the markup of `autocomplete.js`. */-function NoteSuggestionList({ autocomplete }: { autocomplete: ReturnType<typeof useAutocomplete<Suggestion>> }) {+/**+ * The list of suggestions, in the markup of `autocomplete.js`. With `searchingFor`, the query of a+ * search in progress, it shows a row saying so in place of the suggestions.+ */+function NoteSuggestionList({ autocomplete, searchingFor }: {+ autocomplete: ReturnType<typeof useAutocomplete<Suggestion>>;+ searchingFor?: string;+}) {return (<spanclassName="aa-dropdown-menu"@@ -232,7 +294,12 @@ function NoteSuggestionList({ autocomplete }: { autocomplete: ReturnType<typeof><div className="aa-dataset-0"><span className="aa-suggestions">- {autocomplete.items.map((suggestion, index) => (+ {searchingFor !== undefined && (+ <div className="aa-suggestion">+ <NoteSuggestion suggestion={{ noteTitle: searchingFor, highlightedNotePathTitle: t("quick-search.searching") }} />+ </div>+ )}+ {searchingFor === undefined && autocomplete.items.map((suggestion, index) => (<divkey={`${suggestion.action ?? ""}:${suggestion.notePath ?? suggestion.commandId ?? index}`}id={autocomplete.itemId(index)}