Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): offer full-text search as a row instead of a button

Elian Doranefa1be3f3560
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index 9657e452b3..0800211d97 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -20,7 +20,7 @@ const SEARCH_DEBOUNCE_MS = 50;
* A client row sets `action` to its kind and fills in only the fields that kind uses.
*/
export interface Suggestion extends Partial<AutocompleteResult> {
- action?: string | "create-note" | "create-child-note" | "search-notes" | "external-link" | "command";
+ action?: string | "create-note" | "create-child-note" | "search-notes" | "full-text-search" | "external-link" | "command";
externalLink?: string;
parentNoteId?: string;
commandId?: string;
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 0b791d66c8..6a7f528dd0 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -3082,7 +3082,7 @@
"create-child-note": "Create child note \"{{term}}\"",
"insert-external-link": "Insert external link to \"{{term}}\"",
"clear-text-field": "Clear text field",
- "full-text-search": "Full text search"
+ "search-note-contents": "Search note contents for \"{{term}}\""
},
"note_tooltip": {
"note-has-been-deleted": "Note has been deleted.",
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index a9fa2d7a86..2c631b5807 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -229,8 +229,11 @@ interface UseAutocompleteOptions<T> {
openOnFocus?: boolean;
/** See {@link FormAutocompleteProps.openOnEnter}. */
openOnEnter?: boolean;
- /** See {@link FormAutocompleteProps.keepOpenOnPick}. */
- keepOpenOnPick?: boolean;
+ /**
+ * See {@link FormAutocompleteProps.keepOpenOnPick}. A function decides per entry, for an entry
+ * that refreshes the list rather than choosing from it.
+ */
+ keepOpenOnPick?: boolean | ((item: T) => boolean);
/** See {@link FormAutocompleteProps.autoActivate}. */
autoActivate?: boolean;
/** See {@link FormAutocompleteProps.isHeading}. */
@@ -331,7 +334,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
pickedSinceRender.current = true;
onPick(item);
- if (keepOpenOnPick) {
+ if (typeof keepOpenOnPick === "function" ? keepOpenOnPick(item) : keepOpenOnPick) {
// Nothing is highlighted until the refreshed entries arrive, so Enter cannot take twice
// what the list is about to stop offering.
setActiveIndex(-1);
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.css
index e5df6778af..52613ba274 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.css
+++ b/apps/client/src/widgets/react/NoteAutocomplete.css
@@ -10,7 +10,7 @@
}
/* One class, so the next theme's input-group rules override these. */
-:is(.full-text-search-button, .go-to-selected-note-button, .input-clearer-button) {
+:is(.go-to-selected-note-button, .input-clearer-button) {
cursor: pointer;
}
@@ -18,7 +18,7 @@
background: inherit !important;
}
-.input-group > :is(.full-text-search-button, .go-to-selected-note-button),
+.input-group > .go-to-selected-note-button,
.note-autocomplete ~ .input-clearer-button {
font-size: 1.3em;
padding-inline: 5px;
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 5e20362b41..cdfaebfe30 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -61,13 +61,11 @@ describe("NoteAutocomplete", () => {
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 input-clearer-button bx bxs-tag-x"
]);
const withoutGoTo = buttonClasses((await render({ opts: { hideGoToSelectedNoteButton: true } })).container);
- expect(withoutGoTo).toHaveLength(2);
- expect(withoutGoTo[0]).toContain("full-text-search-button");
+ expect(withoutGoTo).toEqual([ "input-group-text input-clearer-button bx bxs-tag-x" ]);
expect(buttonClasses((await render({ opts: { hideAllButtons: true } })).container)).toEqual([]);
});
@@ -179,10 +177,19 @@ describe("NoteAutocomplete's suggestion list", () => {
return getNoteSuggestions.mock.calls.map(([ query ]) => query);
}
+ /** The rows of the popup, without the full-text search row a non-blank query always ends with. */
function rows() {
+ return allRows().filter((row) => row !== fullTextRow());
+ }
+
+ function allRows() {
return [ ...document.querySelectorAll<HTMLElement>(".note-autocomplete-menu > .tn-menu-scroll > .dropdown-item") ];
}
+ function fullTextRow() {
+ return allRows().find((row) => row.querySelector("kbd")?.textContent === "Shift+Enter");
+ }
+
it("lists the notes as the rows of a menu, the first one highlighted", async () => {
const input = await mount();
await type(input, "al");
@@ -330,7 +337,7 @@ describe("NoteAutocomplete's suggestion list", () => {
await type(input, "a");
const menu = host.querySelector<HTMLElement>(":scope > span.aa-dropdown-menu");
- expect(menu?.querySelectorAll(".aa-suggestion")).toHaveLength(2);
+ expect(menu?.querySelectorAll(".aa-suggestion")).toHaveLength(3);
// In the host's flow, with no position of its own.
expect(menu?.hasAttribute("style")).toBe(false);
expect(document.querySelector(".note-autocomplete-menu")).toBeNull();
@@ -339,7 +346,7 @@ describe("NoteAutocomplete's suggestion list", () => {
input.focus();
input.blur();
});
- expect(host.querySelectorAll(".aa-suggestion")).toHaveLength(2);
+ expect(host.querySelectorAll(".aa-suggestion")).toHaveLength(3);
// Both are left to the host, as a dialog closes on Escape.
const reachedHost: string[] = [];
@@ -348,7 +355,7 @@ describe("NoteAutocomplete's suggestion list", () => {
await press(input, "Escape");
await press(input, "Tab");
document.body.removeEventListener("keydown", listen);
- expect(host.querySelectorAll(".aa-suggestion")).toHaveLength(2);
+ expect(host.querySelectorAll(".aa-suggestion")).toHaveLength(3);
expect(reachedHost).toEqual([ "Escape", "Tab" ]);
await press(input, "Enter");
@@ -462,19 +469,35 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(noteIdChanged).toHaveBeenLastCalledWith(undefined);
});
- it("searches the content from the full-text button, saying so until the results come", async () => {
+ it("offers searching the content after the notes, for a non-blank query only", async () => {
+ const input = await mount();
+ await type(input, "al");
+
+ const row = fullTextRow();
+ expect(row).toBeDefined();
+ expect(allRows().at(-1)).toBe(row);
+ expect(row?.querySelector("kbd")?.textContent).toBe("Shift+Enter");
+ expect(row?.querySelector(".tn-icon")?.className).toBe("bx bx-search tn-icon");
+ // The first note keeps the highlight, though the row's title is the query itself.
+ expect(rows()[0].classList.contains("tn-menu-active")).toBe(true);
+
+ await type(input, " ");
+ expect(rows()).toHaveLength(2);
+ expect(fullTextRow()).toBeUndefined();
+ });
+
+ it("searches the content from its row, 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(); });
+ const row = fullTextRow();
+ if (!row) throw new Error("no full-text search row rendered");
+ await act(async () => { row.click(); });
await settle();
- expect(mouseDown.defaultPrevented).toBe(true);
expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", expect.objectContaining({ fastSearch: false }));
expect(rows()).toHaveLength(1);
expect(rows()[0].querySelector(".search-result-title")).not.toBeNull();
@@ -572,6 +595,8 @@ describe("NoteAutocomplete's suggestion list", () => {
await type(input, "al");
expect(rows()[0].querySelector("kbd")?.textContent).toBe("Ctrl+Enter");
+ // Past the full-text search row ahead of it.
+ await press(input, "ArrowDown");
await press(input, "Enter");
expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "al" });
expect(onChange).not.toHaveBeenCalled();
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 5e6898e9ad..806e372f61 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -2,7 +2,7 @@ import "./Menu.css";
import "./NoteAutocomplete.css";
import clsx from "clsx";
-import type { RefObject } from "preact";
+import { type RefObject, render } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
@@ -10,6 +10,7 @@ import appContext from "../../components/app_context";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
import { createSearchScheduler, createNoteFromSuggestion, getCommandSuggestions, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
+import { escapeHtml } from "../../services/utils";
import { useAutocomplete } from "./FormAutocomplete";
import { useSyncedRef } from "./hooks";
import Icon from "./Icon";
@@ -77,7 +78,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
const options = { allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks };
if (!fullTextSearchCount) {
- return getNoteSuggestions(query, options);
+ return withFullTextSearchRow(await getNoteSuggestions(query, options), query);
}
setSearchingFullText(true);
@@ -98,7 +99,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
}, [ onChange, noteIdChanged ]);
- const pickSuggestion = useCallback((suggestion: Suggestion) => {
+ function pickSuggestion(suggestion: Suggestion) {
switch (suggestion.action) {
case "command":
// The host runs it; the field keeps what was typed.
@@ -107,6 +108,9 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
case "search-notes":
void appContext.triggerCommand("searchNotes", { searchString: suggestion.noteTitle });
break;
+ case "full-text-search":
+ fullTextSearch();
+ break;
case "external-link":
setValue(suggestion.externalLink ?? "");
setNotePath("");
@@ -122,7 +126,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
default:
selectNote(suggestion);
}
- }, [ onChange, selectNote ]);
+ }
const autocomplete = useAutocomplete({
query: value,
@@ -132,6 +136,8 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
disabled: readOnly,
autoActivate: true,
textOf: suggestionText,
+ // The row runs the search again over the notes' content, into the same list.
+ keepOpenOnPick: (suggestion) => suggestion.action === "full-text-search",
schedule
});
@@ -287,13 +293,6 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
)}
{showButtons && <>
- <a
- className="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}
- />
<a
className="input-group-text input-clearer-button bx bxs-tag-x"
title={t("note_autocomplete.clear-text-field")}
@@ -406,23 +405,40 @@ function NoteSuggestionMenu({ autocomplete, searchingFor }: {
/** One row of the menu, laid out as the rows of `FormListItem` are. */
function NoteSuggestionMenuItem({ suggestion }: { suggestion: Suggestion }) {
- const isCommand = suggestion.action === "command";
- const icon = isCommand ? (suggestion.icon || "bx bx-terminal") : suggestionIcon(suggestion);
- const description = isCommand ? suggestion.commandDescription : suggestion.highlightedAttributeSnippet;
-
return (
<span>
- <Icon icon={icon} />
- <span className="tn-menu-gap" />
- <div className="note-suggestion-text">
- <RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />
- {description && <RawHtml className="search-result-attributes" html={description} />}
- </div>
- {suggestionShortcut(suggestion) && <kbd>{suggestionShortcut(suggestion)}</kbd>}
+ <NoteSuggestionMenuItemContent suggestion={suggestion} />
</span>
);
}
+function NoteSuggestionMenuItemContent({ suggestion }: { suggestion: Suggestion }) {
+ const isCommand = suggestion.action === "command";
+ const icon = isCommand ? (suggestion.icon || "bx bx-terminal") : suggestionIcon(suggestion);
+ const description = isCommand ? suggestion.commandDescription : suggestion.highlightedAttributeSnippet;
+
+ return <>
+ <Icon icon={icon} />
+ <span className="tn-menu-gap" />
+ <div className="note-suggestion-text">
+ <RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />
+ {description && <RawHtml className="search-result-attributes" html={description} />}
+ </div>
+ {suggestionShortcut(suggestion) && <kbd>{suggestionShortcut(suggestion)}</kbd>}
+ </>;
+}
+
+/**
+ * Draws `suggestion` as the content of a `.dropdown-item` in a `.note-autocomplete-menu`, for a
+ * list this component does not render, such as a search field's completions.
+ */
+export function renderNoteSuggestion(suggestion: Suggestion): HTMLElement {
+ const element = document.createElement("span");
+ render(<NoteSuggestionMenuItemContent suggestion={suggestion} />, element);
+
+ return element;
+}
+
/** One row of the list. */
function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
if (suggestion.action === "command") {
@@ -441,7 +457,7 @@ function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
}
return (
- <div className={clsx("note-suggestion", suggestion.action === "search-notes" && "search-notes-action")}>
+ <div className={clsx("note-suggestion", (suggestion.action === "search-notes" || suggestion.action === "full-text-search") && "search-notes-action")}>
<span className={clsx("icon", suggestionIcon(suggestion))} />
<span className="text">
{suggestionShortcut(suggestion) && <kbd>{suggestionShortcut(suggestion)}</kbd>}
@@ -457,6 +473,7 @@ function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
function suggestionIcon(suggestion: Suggestion) {
switch (suggestion.action) {
case "search-notes": return "bx bx-search";
+ case "full-text-search": return "bx bx-search";
case "create-note": return "bx bx-plus";
case "create-child-note": return "bx bx-subdirectory-right";
case "external-link": return "bx bx-link-external";
@@ -469,10 +486,32 @@ function suggestionShortcut(suggestion: Suggestion) {
switch (suggestion.action) {
case "command": return suggestion.commandShortcut;
case "search-notes": return "Ctrl+Enter";
+ case "full-text-search": return "Shift+Enter";
}
}
+/**
+ * Adds the row that searches the notes' content as well as their titles, ahead of the row that opens
+ * a search, for a non-blank query.
+ */
+function withFullTextSearchRow(rows: Suggestion[], query: string): Suggestion[] {
+ if (!query.trim()) return rows;
+
+ const row: Suggestion = {
+ action: "full-text-search",
+ noteTitle: query,
+ highlightedNotePathTitle: t("note_autocomplete.search-note-contents", { term: escapeHtml(query) })
+ };
+ const last = rows.at(-1);
+ return last?.action === "search-notes" ? [ ...rows.slice(0, -1), row, last ] : [ ...rows, row ];
+}
+
+/**
+ * The text the list opens highlighted on when it equals the query. Empty for an action row, whose
+ * title is the query itself.
+ */
function suggestionText(suggestion: Suggestion) {
+ if (suggestion.action && suggestion.action !== "command") return "";
return suggestion.noteTitle ?? "";
}