Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): drive the note autocomplete through a handle

Elian Doran4bba8a1bbdd8
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index c13d0793de..c9bd4b6763 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -196,8 +196,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, _options?: Options) {
return $el;
}
-function showRecentNotes(_$el: JQuery<HTMLElement>) {}
-
function showAllCommands(_$el: JQuery<HTMLElement>) {}
function setText(_$el: JQuery<HTMLElement>, _text: string) {}
@@ -212,14 +210,11 @@ function init() {
$.fn.setNote = async () => {};
}
-export function triggerRecentNotes(_inputElement: HTMLInputElement | null | undefined) {}
-
// #endregion
export default {
autocompleteSourceForCKEditor,
initNoteAutocomplete,
- showRecentNotes,
showAllCommands,
setText,
init
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
index 43781e6435..2d995e37ff 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -67,7 +67,7 @@ vi.mock("./ws.js", () => ({
import server from "./server.js";
import froca from "./froca.js";
import { buildNote } from "../test/easy-froca.js";
-import noteAutocomplete, { triggerRecentNotes } from "./note_autocomplete_bak.js";
+import noteAutocomplete from "./note_autocomplete_bak.js";
type Dataset = {
displayKey: string;
@@ -696,16 +696,6 @@ describe("public helpers", () => {
expect(onInput).toHaveBeenCalled();
});
- it("showRecentNotes clears path, blanks val, opens and focuses", () => {
- const $el = makeEl();
- const onInput = vi.fn();
- $el.on("input", onInput);
- noteAutocomplete.showRecentNotes($el);
- expect(lastCommandWith("open")).toBe(true);
- expect($el.attr("data-note-path")).toBe("");
- expect(onInput).toHaveBeenCalled();
- });
-
it("showAllCommands sets the '>' prefix and opens", () => {
const $el = makeEl();
const onInput = vi.fn();
@@ -716,17 +706,6 @@ describe("public helpers", () => {
expect(lastCommandWith("open")).toBe(true);
expect(onInput).toHaveBeenCalled();
});
-
- it("triggerRecentNotes is a no-op for a missing element", () => {
- expect(() => triggerRecentNotes(null)).not.toThrow();
- expect(() => triggerRecentNotes(undefined)).not.toThrow();
- });
-
- it("triggerRecentNotes shows recent notes for a real element", () => {
- const input = document.createElement("input");
- triggerRecentNotes(input);
- expect(lastCommandWith("open")).toBe(true);
- });
});
describe("fullTextSearch guards", () => {
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index 12dcc0e032..638445efb3 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -96,14 +96,6 @@ function setText($el: JQuery<HTMLElement>, text: string) {
$el.autocomplete("open");
}
-function showRecentNotes($el: JQuery<HTMLElement>) {
- $el.setSelectedNotePath("");
- $el.autocomplete("val", "");
- $el.trigger("input");
- $el.autocomplete("open");
- $el.trigger("focus");
-}
-
function showAllCommands($el: JQuery<HTMLElement>) {
$el.setSelectedNotePath("");
$el.autocomplete("val", ">");
@@ -382,24 +374,8 @@ function init() {
};
}
-/**
- * Convenience function which triggers the display of recent notes in the autocomplete input and focuses it.
- *
- * @param inputElement - The input element to trigger recent notes on.
- */
-export function triggerRecentNotes(inputElement: HTMLInputElement | null | undefined) {
- if (!inputElement) {
- return;
- }
-
- const $el = $(inputElement);
- showRecentNotes($el);
- $el.trigger("focus").trigger("select");
-}
-
export default {
initNoteAutocomplete,
- showRecentNotes,
showAllCommands,
setText,
init
diff --git a/apps/client/src/widgets/dialogs/add_link.tsx b/apps/client/src/widgets/dialogs/add_link.tsx
index a90dc61d67..149adc0aae 100644
--- a/apps/client/src/widgets/dialogs/add_link.tsx
+++ b/apps/client/src/widgets/dialogs/add_link.tsx
@@ -2,7 +2,7 @@ import { t } from "../../services/i18n";
import Modal from "../react/Modal";
import Button from "../react/Button";
import FormRadioGroup from "../react/FormRadioGroup";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import { useRef, useState, useEffect } from "preact/hooks";
import tree from "../../services/tree";
import froca from "../../services/froca";
@@ -161,7 +161,7 @@ export default function AddLinkDialog() {
|| opts?.text;
if (!text) {
- note_autocomplete.showRecentNotes($autocompleteEl);
+ handleRef.current?.showRecentNotes();
} else {
note_autocomplete.setText($autocompleteEl, text);
@@ -190,6 +190,7 @@ export default function AddLinkDialog() {
}
const autocompleteRef = useRef<HTMLInputElement>(null);
+ const handleRef = useRef<NoteAutocompleteHandle>(null);
return (
<Modal
@@ -229,6 +230,7 @@ export default function AddLinkDialog() {
<FormGroup label={t("add_link.note")} name="note">
<NoteAutocomplete
inputRef={autocompleteRef}
+ handleRef={handleRef}
onChange={setSuggestion}
opts={{
allowExternalLinks: true,
diff --git a/apps/client/src/widgets/dialogs/clone_to.tsx b/apps/client/src/widgets/dialogs/clone_to.tsx
index 3a455679bf..5df093721e 100644
--- a/apps/client/src/widgets/dialogs/clone_to.tsx
+++ b/apps/client/src/widgets/dialogs/clone_to.tsx
@@ -2,12 +2,12 @@ import { useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context";
import { t } from "../../services/i18n";
import Modal from "../react/Modal";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import froca from "../../services/froca";
import FormGroup from "../react/FormGroup";
import FormTextBox from "../react/FormTextBox";
import Button from "../react/Button";
-import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";
+import { Suggestion } from "../../services/note_autocomplete";
import { logError } from "../../services/ws";
import tree from "../../services/tree";
import branches from "../../services/branches";
@@ -20,7 +20,7 @@ export default function CloneToDialog() {
const [ prefix, setPrefix ] = useState("");
const [ suggestion, setSuggestion ] = useState<Suggestion | null>(null);
const [ shown, setShown ] = useState(false);
- const autoCompleteRef = useRef<HTMLInputElement>(null);
+ const autocompleteRef = useRef<NoteAutocompleteHandle>(null);
useTriliumEvent("cloneNoteIdsTo", ({ noteIds }) => {
if (!noteIds || noteIds.length === 0) {
@@ -65,7 +65,7 @@ export default function CloneToDialog() {
<Button text={t("clone_to.clone_to_selected_note")} keyboardShortcut="Enter" />
</>}
onSubmit={onSubmit}
- onShown={() => triggerRecentNotes(autoCompleteRef.current)}
+ onShown={() => autocompleteRef.current?.showRecentNotes()}
onHidden={() => setShown(false)}
show={shown}
>
@@ -75,7 +75,7 @@ export default function CloneToDialog() {
<NoteAutocomplete
placeholder={t("clone_to.search_for_note_by_its_name")}
onChange={setSuggestion}
- inputRef={autoCompleteRef}
+ handleRef={autocompleteRef}
/>
</FormGroup>
<FormGroup name="clone-prefix" label={t("clone_to.prefix_optional")} title={t("clone_to.cloned_note_prefix_title")}>
diff --git a/apps/client/src/widgets/dialogs/include_note.tsx b/apps/client/src/widgets/dialogs/include_note.tsx
index c03a4e4327..639a0f4e1f 100644
--- a/apps/client/src/widgets/dialogs/include_note.tsx
+++ b/apps/client/src/widgets/dialogs/include_note.tsx
@@ -3,9 +3,9 @@ import { t } from "../../services/i18n";
import FormGroup from "../react/FormGroup";
import FormRadioGroup from "../react/FormRadioGroup";
import Modal from "../react/Modal";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import Button from "../react/Button";
-import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";
+import { Suggestion } from "../../services/note_autocomplete";
import tree from "../../services/tree";
import froca from "../../services/froca";
import { useTriliumEvent, useTriliumOption } from "../react/hooks";
@@ -28,14 +28,14 @@ export default function IncludeNoteDialog() {
setShown(true);
});
- const autoCompleteRef = useRef<HTMLInputElement>(null);
+ const autocompleteRef = useRef<NoteAutocompleteHandle>(null);
return (
<Modal
className="include-note-dialog"
title={t("include_note.dialog_title")}
size="lg"
- onShown={() => triggerRecentNotes(autoCompleteRef.current)}
+ onShown={() => autocompleteRef.current?.showRecentNotes()}
onHidden={() => setShown(false)}
onSubmit={async () => {
if (!suggestion?.notePath || !editorApiRef.current) return;
@@ -53,7 +53,7 @@ export default function IncludeNoteDialog() {
<NoteAutocomplete
placeholder={t("include_note.placeholder_search")}
onChange={setSuggestion}
- inputRef={autoCompleteRef}
+ handleRef={autocompleteRef}
opts={{
hideGoToSelectedNoteButton: true,
allowCreatingNotes: true
diff --git a/apps/client/src/widgets/dialogs/jump_to_note.tsx b/apps/client/src/widgets/dialogs/jump_to_note.tsx
index 29ce394c1a..609d167f17 100644
--- a/apps/client/src/widgets/dialogs/jump_to_note.tsx
+++ b/apps/client/src/widgets/dialogs/jump_to_note.tsx
@@ -10,7 +10,7 @@ import shortcutService from "../../services/shortcuts";
import Button from "../react/Button";
import { useTriliumEvent } from "../react/hooks";
import Modal from "../react/Modal";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import { refToJQuerySelector } from "../react/react_utils";
const KEEP_LAST_SEARCH_FOR_X_SECONDS = 120;
@@ -22,6 +22,7 @@ export default function JumpToNoteDialogComponent() {
const [ lastOpenedTs, setLastOpenedTs ] = useState<number>(0);
const containerRef = useRef<HTMLDivElement>(null);
const autocompleteRef = useRef<HTMLInputElement>(null);
+ const handleRef = useRef<NoteAutocompleteHandle>(null);
const [ isCommandMode, setIsCommandMode ] = useState(mode === "commands");
const [ initialText, setInitialText ] = useState(isCommandMode ? "> " : "");
const actualText = useRef<string>(initialText);
@@ -80,7 +81,7 @@ export default function JumpToNoteDialogComponent() {
case "last-search":
break;
case "recent-notes":
- note_autocomplete.showRecentNotes($autoComplete);
+ handleRef.current?.showRecentNotes();
break;
case "commands":
note_autocomplete.showAllCommands($autoComplete);
@@ -130,6 +131,7 @@ export default function JumpToNoteDialogComponent() {
title={<NoteAutocomplete
placeholder={t("jump_to_note.search_placeholder")}
inputRef={autocompleteRef}
+ handleRef={handleRef}
container={containerRef}
text={initialText}
opts={{
diff --git a/apps/client/src/widgets/dialogs/move_to.tsx b/apps/client/src/widgets/dialogs/move_to.tsx
index b1375d7d5b..2c567d3141 100644
--- a/apps/client/src/widgets/dialogs/move_to.tsx
+++ b/apps/client/src/widgets/dialogs/move_to.tsx
@@ -2,10 +2,10 @@ import Modal from "../react/Modal";
import { t } from "../../services/i18n";
import NoteList from "../react/NoteList";
import FormGroup from "../react/FormGroup";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
import Button from "../react/Button";
import { useRef, useState } from "preact/hooks";
-import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";
+import { Suggestion } from "../../services/note_autocomplete";
import tree from "../../services/tree";
import froca from "../../services/froca";
import branches from "../../services/branches";
@@ -16,7 +16,7 @@ export default function MoveToDialog() {
const [ movedBranchIds, setMovedBranchIds ] = useState<string[]>();
const [ suggestion, setSuggestion ] = useState<Suggestion | null>(null);
const [ shown, setShown ] = useState(false);
- const autoCompleteRef = useRef<HTMLInputElement>(null);
+ const autocompleteRef = useRef<NoteAutocompleteHandle>(null);
useTriliumEvent("moveBranchIdsTo", ({ branchIds }) => {
setMovedBranchIds(branchIds);
@@ -52,7 +52,7 @@ export default function MoveToDialog() {
<Button text={t("move_to.move_button")} keyboardShortcut="Enter" />
</>}
onSubmit={onSubmit}
- onShown={() => triggerRecentNotes(autoCompleteRef.current)}
+ onShown={() => autocompleteRef.current?.showRecentNotes()}
onHidden={() => setShown(false)}
show={shown}
>
@@ -62,7 +62,7 @@ export default function MoveToDialog() {
<FormGroup name="parent-note" label={t("move_to.target_parent_note")}>
<NoteAutocomplete
onChange={setSuggestion}
- inputRef={autoCompleteRef}
+ handleRef={autocompleteRef}
/>
</FormGroup>
</Modal>
diff --git a/apps/client/src/widgets/dialogs/note_picker.tsx b/apps/client/src/widgets/dialogs/note_picker.tsx
index 698083970f..d2b913a684 100644
--- a/apps/client/src/widgets/dialogs/note_picker.tsx
+++ b/apps/client/src/widgets/dialogs/note_picker.tsx
@@ -1,13 +1,13 @@
import { useRef, useState } from "preact/hooks";
import { t } from "../../services/i18n";
-import { Suggestion, triggerRecentNotes } from "../../services/note_autocomplete";
+import { Suggestion } from "../../services/note_autocomplete";
import tree from "../../services/tree";
import Button from "../react/Button";
import FormGroup from "../react/FormGroup";
import { useTriliumEvent } from "../react/hooks";
import Modal from "../react/Modal";
-import NoteAutocomplete from "../react/NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
export interface NotePickerDialogOptions {
/** Names what the note is wanted for; the stock title only asks for one. */
@@ -29,7 +29,7 @@ export interface NotePickerDialogOptions {
*/
export default function NotePickerDialog() {
const opts = useRef<NotePickerDialogOptions>();
- const inputRef = useRef<HTMLInputElement>(null);
+ const autocompleteRef = useRef<NoteAutocompleteHandle>(null);
const [ suggestion, setSuggestion ] = useState<Suggestion | null>(null);
const [ shown, setShown ] = useState(false);
// Held apart from the suggestion because the answer is reported once the modal is out of the
@@ -48,7 +48,7 @@ export default function NotePickerDialog() {
title={opts.current?.title ?? t("note_picker.title")}
size="lg"
zIndex={2000}
- onShown={() => triggerRecentNotes(inputRef.current)}
+ onShown={() => autocompleteRef.current?.showRecentNotes()}
onSubmit={() => {
pickedNoteId.current = tree.getNoteIdFromUrl(suggestion?.notePath);
setShown(false);
@@ -76,7 +76,7 @@ export default function NotePickerDialog() {
label={opts.current?.message ?? t("note_picker.label")}
>
<NoteAutocomplete
- inputRef={inputRef}
+ handleRef={autocompleteRef}
onChange={setSuggestion}
opts={{ hideAllButtons: true }}
/>
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 0dd4aadd87..c3b6e00ff5 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -1,3 +1,4 @@
+import { createRef, render as preactRender } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
@@ -13,7 +14,7 @@ vi.mock("../../services/note_autocomplete", async (importOriginal) => ({
import type { Suggestion } from "../../services/note_autocomplete";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
-import NoteAutocomplete, { type NoteAutocompleteProps } from "./NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps } from "./NoteAutocomplete";
async function render(props: NoteAutocompleteProps = {}) {
let container = document.createElement("div");
@@ -259,6 +260,37 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(document.activeElement).toBe(input);
});
+ it("lists the recent notes through the handle, with the callbacks of the latest render", async () => {
+ const handleRef = createRef<NoteAutocompleteHandle>();
+ const firstOnTextChange = vi.fn();
+ let container = document.createElement("div");
+ await act(async () => {
+ container = renderInto(<NoteAutocomplete handleRef={handleRef} onTextChange={firstOnTextChange} />);
+ });
+ const input = container.querySelector("input");
+ if (!input) throw new Error("no input rendered");
+ await type(input, "a");
+ await press(input, "Enter");
+
+ const latestOnTextChange = vi.fn();
+ await act(async () => {
+ preactRender(<NoteAutocomplete handleRef={handleRef} onTextChange={latestOnTextChange} />, container);
+ });
+ input.blur();
+ firstOnTextChange.mockClear();
+
+ await act(async () => { handleRef.current?.showRecentNotes(); });
+ await settle();
+
+ expect(input.value).toBe("");
+ expect(input.dataset.notePath).toBe("");
+ expect(latestOnTextChange).toHaveBeenCalledWith("");
+ expect(firstOnTextChange).not.toHaveBeenCalled();
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("");
+ expect(rows()).toHaveLength(2);
+ expect(document.activeElement).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.tsx
index 4741c50f44..8cee381b5b 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -3,7 +3,7 @@ import "./NoteAutocomplete.css";
import clsx from "clsx";
import type { RefObject } from "preact";
import type { CSSProperties } from "preact/compat";
-import { useCallback, useEffect, useMemo, useRef, useState } from "preact/hooks";
+import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
@@ -31,9 +31,17 @@ export interface NoteAutocompleteProps {
readOnly?: boolean;
/** Places the input in the tab order of a host that orders its fields with `tabIndex`. */
tabIndex?: number;
+ /** Receives the functions that drive the field from outside it. */
+ handleRef?: MutableRef<NoteAutocompleteHandle | null>;
}
-export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex }: NoteAutocompleteProps) {
+/** Drives a note autocomplete from outside it, for a caller that decides when. */
+export interface NoteAutocompleteHandle {
+ /** Empties the field, lists the recently visited notes and focuses the field. */
+ showRecentNotes(): void;
+}
+
+export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex, handleRef }: NoteAutocompleteProps) {
const inputRef = useSyncedRef<HTMLInputElement>(externalInputRef);
const groupRef = useRef<HTMLDivElement>(null);
const [ value, setValue ] = useState("");
@@ -81,6 +89,11 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
inputRef.current?.focus();
}
+ // Refreshed on every render, so a call from outside reaches the current callbacks.
+ useLayoutEffect(() => {
+ if (handleRef) handleRef.current = { showRecentNotes };
+ });
+
const showButtons = !opts?.hideAllButtons;
const showGoToButton = showButtons && !opts?.hideGoToSelectedNoteButton;
diff --git a/apps/client/src/widgets/type_widgets/Empty.tsx b/apps/client/src/widgets/type_widgets/Empty.tsx
index e020342c42..eaf9ab93fa 100644
--- a/apps/client/src/widgets/type_widgets/Empty.tsx
+++ b/apps/client/src/widgets/type_widgets/Empty.tsx
@@ -5,12 +5,11 @@ import { useContext, useEffect, useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context";
import FNote from "../../entities/fnote";
import { t } from "../../services/i18n";
-import note_autocomplete from "../../services/note_autocomplete";
import search from "../../services/search";
import { isMobile } from "../../services/utils";
import FormGroup from "../react/FormGroup";
-import NoteAutocomplete from "../react/NoteAutocomplete";
-import { ParentComponent, refToJQuerySelector } from "../react/react_utils";
+import NoteAutocomplete, { type NoteAutocompleteHandle } from "../react/NoteAutocomplete";
+import { ParentComponent } from "../react/react_utils";
import { TypeWidgetProps } from "./type_widget";
export default function Empty({ ntxId }: TypeWidgetProps) {
@@ -44,12 +43,10 @@ function MobileNoteSearch() {
function DesktopNoteSearch({ ntxId }: { ntxId: string | null }) {
const resultsContainerRef = useRef<HTMLDivElement>(null);
- const autocompleteRef = useRef<HTMLInputElement>(null);
+ const handleRef = useRef<NoteAutocompleteHandle>(null);
- // Show recent notes.
useEffect(() => {
- const $autoComplete = refToJQuerySelector(autocompleteRef);
- note_autocomplete.showRecentNotes($autoComplete);
+ handleRef.current?.showRecentNotes();
}, []);
return (
@@ -58,7 +55,7 @@ function DesktopNoteSearch({ ntxId }: { ntxId: string | null }) {
<NoteAutocomplete
placeholder={t("empty.search_placeholder")}
container={resultsContainerRef}
- inputRef={autocompleteRef}
+ handleRef={handleRef}
opts={{
hideGoToSelectedNoteButton: true,
allowCreatingNotes: true,