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): open the note list on text handed to the field
Elian Doran6437164f5c26
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex e646b65f2c..d2bb75f089 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -217,8 +217,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, _options?: Options) {return $el;}-function setText(_$el: JQuery<HTMLElement>, _text: string) {}-/** Installs the `$.fn` helpers `NoteAutocomplete` and the dialogs call, as no-ops. */function init() {$.fn.getSelectedNotePath = () => "";@@ -234,6 +232,5 @@ function init() {export default {autocompleteSourceForCKEditor,initNoteAutocomplete,- setText,init};diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.tsindex 2c8a5c40b8..41e729b547 100644--- a/apps/client/src/services/note_autocomplete_bak.spec.ts+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts@@ -607,17 +607,6 @@ describe("public helpers", () => {noteAutocomplete.init();});- it("setText sets the trimmed value and opens the dropdown", () => {- const $el = makeEl();- const onInput = vi.fn();- $el.on("input", onInput);- noteAutocomplete.setText($el, " hello ");- expect(lastCommandWith("open")).toBe(true);- expect($el.attr("data-note-path")).toBe("");- // re-triggers "input" so consumers tracking the live query stay in sync- expect(onInput).toHaveBeenCalled();- });-it("returns early when the search string is blank (Shift+Enter on empty input)", () => {const $el = makeEl();noteAutocomplete.initNoteAutocomplete($el);diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.tsindex 3aa80c84b0..7806728462 100644--- a/apps/client/src/services/note_autocomplete_bak.ts+++ b/apps/client/src/services/note_autocomplete_bak.ts@@ -63,13 +63,6 @@ function clearText($el: JQuery<HTMLElement>) {$el.trigger("input");}-function setText($el: JQuery<HTMLElement>, text: string) {- $el.setSelectedNotePath("");- $el.autocomplete("val", text.trim());- $el.trigger("input");- $el.autocomplete("open");-}-function fullTextSearch($el: JQuery<HTMLElement>, options: Options) {const searchString = $el.autocomplete("val") as unknown as string;if (options.fastSearch === false || searchString?.trim().length === 0) {@@ -311,6 +304,5 @@ function init() {export default {initNoteAutocomplete,- setText,init};diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsxindex 149adc0aae..cd9f726ffe 100644--- a/apps/client/src/widgets/dialogs/add_link.tsx+++ b/apps/client/src/widgets/dialogs/add_link.tsx@@ -6,7 +6,7 @@ import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutoimport { useRef, useState, useEffect } from "preact/hooks";import tree from "../../services/tree";import froca from "../../services/froca";-import note_autocomplete, { Suggestion } from "../../services/note_autocomplete";+import type { Suggestion } from "../../services/note_autocomplete";import { logError } from "../../services/ws";import FormGroup from "../react/FormGroup.js";import { refToJQuerySelector } from "../react/react_utils";@@ -163,13 +163,8 @@ export default function AddLinkDialog() {if (!text) {handleRef.current?.showRecentNotes();} else {- note_autocomplete.setText($autocompleteEl, text);-- // What `setText` fills the field with is something being typed, which has nothing picked- // behind it; the note the dialog opens on is picked already.- if (currentNotePath) {- $autocompleteEl.setSelectedNotePath(currentNotePath);- }+ // The note the dialog opens on is picked already, so the field selects it.+ handleRef.current?.setText(text, currentNotePath);}// to be able to quickly remove entered textdiff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 1583ee5ad2..4fa4de17b5 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -383,6 +383,35 @@ describe("NoteAutocomplete's suggestion list", () => {expect(document.activeElement).toBe(input);});+ it("lists the suggestions for the text given", async () => {+ const onTextChange = vi.fn();+ const input = await mount({ text: " al ", onTextChange });+ await settle();++ expect(input.value).toBe("al");+ expect(onTextChange).toHaveBeenCalledWith("al");+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al");+ expect(rows()).toHaveLength(2);+ });++ it("sets the text through the handle at once, with its note selected, and lists it", async () => {+ const handleRef = createRef<NoteAutocompleteHandle>();+ const input = await mount({ handleRef });+ input.blur();++ // Read before any render, as Add Link selects the text right after the call.+ act(() => {+ handleRef.current?.setText(" Beta ", "root/x/b");+ expect(input.value).toBe("Beta");+ });+ await settle();++ expect(input.dataset.notePath).toBe("root/x/b");+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("Beta");+ expect(rows()).toHaveLength(2);+ expect(document.activeElement).not.toBe(input);+ });+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 2838e13e49..a015095857 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -41,6 +41,11 @@ export interface NoteAutocompleteHandle {showRecentNotes(): void;/** Puts `>` in the field, lists every command and focuses the field. */showAllCommands(): void;+ /**+ * Puts `text`, trimmed, in the field and lists its suggestions, leaving the focus where it is.+ * `selectedPath` is the note the text stands for, where it names one already.+ */+ setText(text: string, selectedPath?: string): void;}export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, container, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex, handleRef }: NoteAutocompleteProps) {@@ -49,16 +54,6 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,const [ value, setValue ] = useState("");const [ notePath, setNotePath ] = useState("");- useEffect(() => {- if (noteId) {- setNotePath(noteId);- void froca.getNote(noteId, true).then((note) => setValue(note?.title ?? ""));- } else {- setNotePath("");- setValue(text?.trim() ?? "");- }- }, [ text, noteId ]);-const isCommandPalette = !!opts?.isCommandPalette;const source = useCallback(async (query: string) => (isCommandPalette && query.startsWith(">")? getCommandSuggestions(query)@@ -91,24 +86,43 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,schedule});- /** Puts `query` in the field, drops the selection, lists the suggestions and focuses the field. */- function showSuggestionsFor(query: string) {- setNotePath("");+ /** Puts `query` in the field with `selectedPath` as its selection, and lists the suggestions. */+ function showSuggestionsFor(query: string, selectedPath = "") {+ setNotePath(selectedPath);setValue(query);+ // Written at once as well, so a caller can select the text right after the call.+ if (inputRef.current) inputRef.current.value = query;onTextChange?.(query);autocomplete.open();+ }++ function showAndFocus(query: string) {+ showSuggestionsFor(query);inputRef.current?.focus();}// An empty query is answered with the recently visited notes.- const showRecentNotes = () => showSuggestionsFor("");- const showAllCommands = () => showSuggestionsFor(">");+ const showRecentNotes = () => showAndFocus("");+ const showAllCommands = () => showAndFocus(">");+ const setText = (newText: string, selectedPath?: string) => showSuggestionsFor(newText.trim(), selectedPath);// Refreshed on every render, so a call from outside reaches the current callbacks.useLayoutEffect(() => {- if (handleRef) handleRef.current = { showRecentNotes, showAllCommands };+ if (handleRef) handleRef.current = { showRecentNotes, showAllCommands, setText };});+ useEffect(() => {+ if (noteId) {+ setNotePath(noteId);+ void froca.getNote(noteId, true).then((note) => setValue(note?.title ?? ""));+ } else if (text?.trim()) {+ setText(text);+ } else {+ setNotePath("");+ setValue("");+ }+ }, [ text, noteId ]);+const showButtons = !opts?.hideAllButtons;const showGoToButton = showButtons && !opts?.hideGoToSelectedNoteButton;diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsxindex 2f8a19f1dc..02d9a16477 100644--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx@@ -3,7 +3,7 @@ import note_autocomplete from "../../services/note_autocomplete";import { useSyncedRef } from "./hooks";import type { NoteAutocompleteProps } from "./NoteAutocomplete";-export default function NoteAutocomplete({ inputRef: externalInputRef, text, onChange, opts, noteId, noteIdChanged }: NoteAutocompleteProps) {+export default function NoteAutocomplete({ inputRef: externalInputRef, onChange, opts, noteIdChanged }: NoteAutocompleteProps) {const ref = useSyncedRef<HTMLInputElement>(externalInputRef);useEffect(() => {@@ -40,12 +40,5 @@ export default function NoteAutocomplete({ inputRef: externalInputRef, text, onC}}, [opts, onChange, noteIdChanged])- useEffect(() => {- if (!ref.current || noteId || !text) return;-- // Opens the dropdown on the given text.- note_autocomplete.setText($(ref.current), text);- }, [text, noteId]);-return null;}