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): render the note autocomplete's input in Preact
Elian Doranb578011072fe
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxnew file mode 100644index 0000000000..3bcfcf57cd--- /dev/null+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -0,0 +1,107 @@+import { act } from "preact/test-utils";+import { describe, expect, it, vi } from "vitest";++import { buildNote } from "../../test/easy-froca";+import { renderInto } from "../../test/render";+import NoteAutocomplete, { type NoteAutocompleteProps } from "./NoteAutocomplete";++async function render(props: NoteAutocompleteProps = {}) {+ let container = document.createElement("div");+ await act(async () => {+ container = renderInto(<NoteAutocomplete {...props} />);+ });+ // Lets `froca.getNote()` resolve the title of a `noteId`.+ await act(async () => {+ await new Promise((resolve) => setTimeout(resolve));+ });++ const input = container.querySelector<HTMLInputElement>("input");+ if (!input) throw new Error("no input rendered");+ return { container, input };+}++/** The classes of the buttons after the input, in document order. */+function buttonClasses(container: HTMLElement) {+ return [ ...container.querySelectorAll(".input-group > a") ].map((button) => button.className);+}++describe("NoteAutocomplete", () => {+ it("renders the input with the classes and attributes of the jQuery plugin", async () => {+ const { container, input } = await render({ id: "picker", placeholder: "Find" });++ expect(container.firstElementChild?.className).toBe("input-group");+ expect(input.className).toBe("note-autocomplete form-control note-autocomplete-input aa-input");+ expect(input.id).toBe("picker");+ expect(input.placeholder).toBe("Find");+ expect(input.getAttribute("autocomplete")).toBe("off");+ expect(input.getAttribute("dir")).toBe("auto");+ });++ it("sets tabIndex on the input only when the host gives one", async () => {+ expect((await render({ tabIndex: 205 })).input.getAttribute("tabindex")).toBe("205");+ expect((await render()).input.hasAttribute("tabindex")).toBe(false);+ });++ it("places the buttons after the input in the plugin's order, as the options allow", async () => {+ expect(buttonClasses((await render()).container)).toEqual([+ "input-group-text go-to-selected-note-button bx bx-arrow-to-right disabled",+ "input-group-text full-text-search-button bx bx-search",+ "input-group-text show-recent-notes-button bx bx-time",+ "input-group-text input-clearer-button bx bxs-tag-x"+ ]);++ const withoutGoTo = buttonClasses((await render({ opts: { hideGoToSelectedNoteButton: true } })).container);+ expect(withoutGoTo).toHaveLength(3);+ expect(withoutGoTo[0]).toContain("full-text-search-button");++ expect(buttonClasses((await render({ opts: { hideAllButtons: true } })).container)).toEqual([]);+ });++ it("shows the title of the note given, and enables going to it", async () => {+ const note = buildNote({ title: "Target" });+ const { container, input } = await render({ noteId: note.noteId });++ expect(input.value).toBe("Target");+ expect(input.dataset.notePath).toBe(note.noteId);+ const goTo = container.querySelector(".go-to-selected-note-button");+ expect(goTo?.classList.contains("disabled")).toBe(false);+ expect(goTo?.getAttribute("href")).toBe(`#${note.noteId}`);+ });++ it("shows the text given, trimmed, with no note selected", async () => {+ const { container, input } = await render({ text: " query " });++ expect(input.value).toBe("query");+ expect(input.dataset.notePath).toBe("");+ expect(container.querySelector(".go-to-selected-note-button")?.getAttribute("href")).toBe("#");+ });++ it("reports typing, and the selected note id on blur", async () => {+ const note = buildNote({ title: "Target" });+ const onTextChange = vi.fn();+ const onBlur = vi.fn();+ const { input } = await render({ noteId: note.noteId, onTextChange, onBlur });++ await act(async () => {+ input.value = "Targ";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ expect(onTextChange).toHaveBeenCalledWith("Targ");++ await act(async () => {+ input.focus();+ input.blur();+ });+ expect(onBlur).toHaveBeenLastCalledWith(note.noteId);++ await act(async () => {+ input.value = " ";+ input.dispatchEvent(new Event("input", { bubbles: true }));+ });+ await act(async () => {+ input.focus();+ input.blur();+ });+ expect(onBlur).toHaveBeenLastCalledWith("");+ });+});diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 3dbd2a0486..922e99a31c 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -1,7 +1,12 @@+import clsx from "clsx";import type { RefObject } from "preact";import type { CSSProperties } from "preact/compat";+import { useEffect, useState } from "preact/hooks";+import froca from "../../services/froca";+import { t } from "../../services/i18n";import type { Options, Suggestion } from "../../services/note_autocomplete";+import { useSyncedRef } from "./hooks";export interface NoteAutocompleteProps {id?: string;@@ -23,6 +28,70 @@ export interface NoteAutocompleteProps {tabIndex?: number;}-export default function NoteAutocomplete(_props: NoteAutocompleteProps) {- return <div>Hello world</div>;+export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, containerStyle, opts, onTextChange, onKeyDown, onBlur, noteId, readOnly, tabIndex }: NoteAutocompleteProps) {+ const inputRef = useSyncedRef<HTMLInputElement>(externalInputRef);+ 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 showButtons = !opts?.hideAllButtons;+ const showGoToButton = showButtons && !opts?.hideGoToSelectedNoteButton;++ return (+ <div className="input-group" style={containerStyle}>+ <input+ id={id}+ ref={inputRef}+ // `note-autocomplete-input` and `aa-input` are the classes the jQuery plugin used to+ // add, which the stylesheets and the global `$(".aa-input")` closers still select.+ className="note-autocomplete form-control note-autocomplete-input aa-input"+ value={value}+ readOnly={readOnly}+ tabIndex={tabIndex}+ placeholder={placeholder ?? t("add_link.search_note")}+ autoComplete="off"+ spellcheck={false}+ dir="auto"+ data-note-path={notePath}+ onInput={(e) => {+ const newValue = e.currentTarget.value;+ setValue(newValue);+ onTextChange?.(newValue);+ }}+ onKeyDown={onKeyDown}+ onBlur={() => onBlur?.(value.trim() ? notePath.split("/").at(-1) ?? "" : "")}+ />++ {showGoToButton && (+ <a+ className={clsx("input-group-text go-to-selected-note-button bx bx-arrow-to-right", !notePath.trim() && "disabled")}+ href={`#${notePath}`}+ />+ )}++ {showButtons && <>+ <a+ className="input-group-text full-text-search-button bx bx-search"+ title={`${t("note_autocomplete.full-text-search")} (Shift+Enter)`}+ />+ <a+ className="input-group-text show-recent-notes-button bx bx-time"+ title={t("note_autocomplete.show-recent-notes")}+ />+ <a+ className="input-group-text input-clearer-button bx bxs-tag-x"+ title={t("note_autocomplete.clear-text-field")}+ />+ </>}+ </div>+ );}diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsxdeleted file mode 100644index 191eb43864..0000000000--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.spec.tsx+++ /dev/null@@ -1,40 +0,0 @@-import { act } from "preact/test-utils";-import { describe, expect, it, vi } from "vitest";--vi.mock("../../services/note_autocomplete", () => ({- default: { initNoteAutocomplete: vi.fn(), setText: vi.fn() }-}));--import $ from "jquery";--import { renderInto } from "../../test/render";-import NoteAutocomplete from "./NoteAutocomplete_bak";--// The autocomplete plugin is not loaded here, so the calls that clear an empty input are stubbed.-type PluggedIn = {- autocomplete(...args: unknown[]): PluggedIn;- setSelectedNotePath(path: string): void;-};-($.fn as unknown as PluggedIn).autocomplete = function (this: PluggedIn) { return this; };-($.fn as unknown as PluggedIn).setSelectedNotePath = vi.fn();--describe("NoteAutocomplete", () => {- it("sets tabIndex on the input only when the host gives one", async () => {- let container = document.createElement("div");- await act(async () => {- container = renderInto(<NoteAutocomplete id="ordered" tabIndex={205} />);- });- const ordered = container.querySelector("input.note-autocomplete");- expect(ordered).not.toBeNull();- expect(ordered?.id).toBe("ordered");- expect(ordered?.getAttribute("tabindex")).toBe("205");-- await act(async () => {- container = renderInto(<NoteAutocomplete id="unordered" />);- });- const unordered = container.querySelector("input.note-autocomplete");- expect(unordered).not.toBeNull();- expect(unordered?.id).toBe("unordered");- expect(unordered?.hasAttribute("tabindex")).toBe(false);- });-});diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsxindex cded1ef9d0..49008c3128 100644--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx@@ -1,10 +1,9 @@-import { t } from "../../services/i18n";import { useEffect } from "preact/hooks";import note_autocomplete from "../../services/note_autocomplete";import { useSyncedRef } from "./hooks";import type { NoteAutocompleteProps } from "./NoteAutocomplete";-export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, onChange, onTextChange, container, containerStyle, opts, noteId, noteIdChanged, onKeyDown, onBlur, readOnly, tabIndex }: NoteAutocompleteProps) {+export default function NoteAutocomplete({ inputRef: externalInputRef, text, onChange, container, opts, noteId, noteIdChanged }: NoteAutocompleteProps) {const ref = useSyncedRef<HTMLInputElement>(externalInputRef);useEffect(() => {@@ -20,15 +19,6 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,...opts,container: container?.current});- if (onTextChange) {- $autoComplete.on("input", () => onTextChange($autoComplete[0].value));- }- if (onKeyDown) {- $autoComplete.on("keydown", (e) => e.originalEvent && onKeyDown(e.originalEvent));- }- if (onBlur) {- $autoComplete.on("blur", () => onBlur($autoComplete.getSelectedNoteId() ?? ""));- }}, [opts, container?.current]);// On change event handlers.@@ -66,29 +56,11 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,}, [opts, container?.current, onChange, noteIdChanged])useEffect(() => {- if (!ref.current) return;- const $autoComplete = $(ref.current);+ if (!ref.current || noteId || !text) return;- if (noteId) {- $autoComplete.setNote(noteId);- } else if (text) {- note_autocomplete.setText($autoComplete, text);- } else {- $autoComplete.setSelectedNotePath("");- $autoComplete.autocomplete("val", "");- ref.current.value = "";- }+ // Opens the dropdown on the given text.+ note_autocomplete.setText($(ref.current), text);}, [text, noteId]);- return (- <div className="input-group" style={containerStyle}>- <input- id={id}- ref={ref}- className="note-autocomplete form-control"- readOnly={readOnly}- tabIndex={tabIndex}- placeholder={placeholder ?? t("add_link.search_note")} />- </div>- );+ return null;}