Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): run the command palette on the rewritten autocomplete

Elian Doran5f45b07afbfc
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index d6a3e57671..0c919d5fb1 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const { getActiveContextNoteId, getInboxTarget, translate, logError } = vi.hoisted(() => ({
+const { getActiveContextNoteId, getInboxTarget, translate, logError, getAllCommands, searchCommands } = vi.hoisted(() => ({
getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
getInboxTarget: vi.fn<() => Promise<unknown>>(
async () => ({ kind: "inbox", noteId: "inb", title: "Inbox" })
@@ -8,7 +8,13 @@ const { getActiveContextNoteId, getInboxTarget, translate, logError } = vi.hoist
// i18next is never initialized here, so the real `t` returns undefined. Echoing the key keeps
// the label assertions about which string is chosen rather than about its English.
translate: vi.fn((key: string, _opts?: Record<string, unknown>) => key),
- logError: vi.fn()
+ logError: vi.fn(),
+ getAllCommands: vi.fn(() => [] as CommandDefinition[]),
+ searchCommands: vi.fn((_query: string) => [] as CommandDefinition[])
+}));
+
+vi.mock("./command_registry.js", () => ({
+ default: { getAllCommands, searchCommands }
}));
vi.mock("../components/app_context.js", () => ({
@@ -36,7 +42,8 @@ vi.mock("./ws.js", () => ({
logError
}));
-import noteAutocomplete, { createSearchScheduler, getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
+import type { CommandDefinition } from "./command_registry.js";
+import noteAutocomplete, { createSearchScheduler, getCommandSuggestions, getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
import server from "./server.js";
beforeEach(() => {
@@ -260,3 +267,26 @@ describe("createSearchScheduler", () => {
expect(ran).toEqual([ "h", "hi" ]);
});
});
+
+describe("getCommandSuggestions", () => {
+ const command: CommandDefinition = { id: "cmd1", name: "Cmd One", description: "desc", shortcut: "Ctrl+1", icon: "bx bx-cog" };
+
+ it("lists every command for a bare marker, and searches what follows it", () => {
+ getAllCommands.mockReturnValue([ command ]);
+ expect(getCommandSuggestions(">")).toEqual([ {
+ action: "command",
+ commandId: "cmd1",
+ noteTitle: "Cmd One",
+ notePathTitle: ">Cmd One",
+ highlightedNotePathTitle: "Cmd One",
+ commandDescription: "desc",
+ commandShortcut: "Ctrl+1",
+ icon: "bx bx-cog"
+ } ]);
+ expect(searchCommands).not.toHaveBeenCalled();
+
+ searchCommands.mockReturnValue([ { id: "c", name: "C" } ]);
+ expect(getCommandSuggestions("> hello").map((row) => row.commandId)).toEqual([ "c" ]);
+ expect(searchCommands).toHaveBeenCalledWith("hello");
+ });
+});
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index c9bd4b6763..e646b65f2c 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -2,6 +2,7 @@ import type { MentionFeedObjectItem } from "@triliumnext/ckeditor5";
import type { AutocompleteResult, InboxTargetResponse } from "@triliumnext/commons";
import appContext from "../components/app_context.js";
+import commandRegistry from "./command_registry.js";
import dateNoteService from "./date_notes.js";
import { t } from "./i18n.js";
import server from "./server.js";
@@ -93,6 +94,26 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes = fa
];
}
+/**
+ * Returns the commands matching what follows the `>` that opens `term`, or every command when
+ * nothing follows it.
+ */
+export function getCommandSuggestions(term: string): Suggestion[] {
+ const query = term.substring(1).trim();
+ const commands = query ? commandRegistry.searchCommands(query) : commandRegistry.getAllCommands();
+
+ return commands.map((command) => ({
+ action: "command",
+ commandId: command.id,
+ noteTitle: command.name,
+ notePathTitle: `>${command.name}`,
+ highlightedNotePathTitle: command.name,
+ commandDescription: command.description,
+ commandShortcut: command.shortcut,
+ icon: command.icon
+ }));
+}
+
/**
* Paces one input's searches: the first keystroke after a pause queries immediately, a burst typed
* faster than {@link SEARCH_DEBOUNCE_MS} collapses into one search that runs once it stops, and at
@@ -196,8 +217,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, _options?: Options) {
return $el;
}
-function showAllCommands(_$el: JQuery<HTMLElement>) {}
-
function setText(_$el: JQuery<HTMLElement>, _text: string) {}
/** Installs the `$.fn` helpers `NoteAutocomplete` and the dialogs call, as no-ops. */
@@ -215,7 +234,6 @@ function init() {
export default {
autocompleteSourceForCKEditor,
initNoteAutocomplete,
- 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 0e1837f7a7..2c8a5c40b8 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -5,7 +5,7 @@ import $ from "jquery";
const {
triggerCommand, getActiveContextNoteId, getActiveContext, chooseNoteType, createNote,
- getInboxNotePath, getInboxTarget, translate, getAllCommands, searchCommands, logError
+ getInboxNotePath, getInboxTarget, translate, logError
} = vi.hoisted(() => ({
triggerCommand: vi.fn(),
getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
@@ -19,8 +19,6 @@ const {
// i18next is never initialised here, so the real `t` returns undefined. Echoing the key
// keeps the label assertions about which string is chosen rather than about its English.
translate: vi.fn((key: string, _opts?: Record<string, unknown>) => key),
- getAllCommands: vi.fn(() => [] as any[]),
- searchCommands: vi.fn(() => [] as any[]),
logError: vi.fn()
}));
@@ -47,10 +45,6 @@ vi.mock("./i18n.js", async (importOriginal) => ({
t: translate
}));
-vi.mock("./command_registry.js", () => ({
- default: { getAllCommands, searchCommands }
-}));
-
// Narrows the blanket ws mock from test/setup.ts to a spy, so what the module reports can be asserted.
vi.mock("./ws.js", () => ({
default: {
@@ -150,36 +144,6 @@ describe("autocompleteSource (via dataset)", () => {
noteAutocomplete.init();
});
- it("returns command suggestions in command-palette mode (all commands, empty query)", async () => {
- getAllCommands.mockReturnValue([
- { id: "cmd1", name: "Cmd One", description: "desc", shortcut: "Ctrl+1", icon: "bx bx-cog" }
- ]);
- const { dataset } = initAndGetSource({ isCommandPalette: true });
- const rows = await runSource(dataset, ">");
- expect(getAllCommands).toHaveBeenCalled();
- expect(searchCommands).not.toHaveBeenCalled();
- expect(rows).toEqual([
- {
- action: "command",
- commandId: "cmd1",
- noteTitle: "Cmd One",
- notePathTitle: ">Cmd One",
- highlightedNotePathTitle: "Cmd One",
- commandDescription: "desc",
- commandShortcut: "Ctrl+1",
- icon: "bx bx-cog"
- }
- ]);
- });
-
- it("uses searchCommands when a command query is provided", async () => {
- searchCommands.mockReturnValue([{ id: "c", name: "C" }]);
- const { dataset } = initAndGetSource({ isCommandPalette: true });
- const rows = await runSource(dataset, "> hello");
- expect(searchCommands).toHaveBeenCalledWith("hello");
- expect(rows[0].commandId).toBe("c");
- });
-
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[][] = [];
@@ -231,33 +195,6 @@ describe("autocompleteSource (via dataset)", () => {
const rows = await runSource(dataset, " ");
expect(rows.every((r) => r.action !== "search-notes")).toBe(true);
});
-
- it("renders a command suggestion with description and shortcut", () => {
- const { dataset } = initAndGetSource();
- const html = dataset.templates.suggestion({
- action: "command",
- highlightedNotePathTitle: "Cmd",
- commandDescription: "Does a thing",
- commandShortcut: "Ctrl+K",
- icon: "bx bx-cog"
- });
- expect(html).toContain("command-suggestion");
- expect(html).toContain("command-name");
- expect(html).toContain("command-description");
- expect(html).toContain("command-shortcut");
- expect(html).toContain("bx bx-cog");
- });
-
- it("renders a command suggestion without description/shortcut and a default icon", () => {
- const { dataset } = initAndGetSource();
- const html = dataset.templates.suggestion({
- action: "command",
- highlightedNotePathTitle: "Cmd"
- });
- expect(html).toContain("bx bx-terminal");
- expect(html).not.toContain("command-description");
- expect(html).not.toContain("command-shortcut");
- });
});
describe("source debounce", () => {
@@ -576,7 +513,7 @@ describe("autocomplete:selected handler", () => {
const $el = makeEl();
const handlers: Record<string, any> = {};
noteAutocomplete.initNoteAutocomplete($el);
- ["autocomplete:commandselected", "autocomplete:externallinkselected", "autocomplete:noteselected"].forEach((evt) => {
+ ["autocomplete:externallinkselected", "autocomplete:noteselected"].forEach((evt) => {
$el.on(evt, (_e: any, s: any) => (handlers[evt] = s));
});
return { $el, handlers };
@@ -587,13 +524,6 @@ describe("autocomplete:selected handler", () => {
return new Promise((r) => setTimeout(r, 0));
}
- it("handles a command selection", async () => {
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "command", commandId: "x" });
- expect(lastCommandWith("close")).toBe(true);
- expect(handlers["autocomplete:commandselected"]).toBeDefined();
- });
-
it("handles an external-link selection", async () => {
const { $el, handlers } = initWithSelected();
await fireSelected($el, { action: "external-link", externalLink: "https://e.com" });
@@ -688,26 +618,6 @@ describe("public helpers", () => {
expect(onInput).toHaveBeenCalled();
});
- it("showAllCommands sets the '>' prefix and opens", () => {
- const $el = makeEl();
- const onInput = vi.fn();
- $el.on("input", onInput);
- noteAutocomplete.showAllCommands($el);
- // val was set to ">"
- expect($el.autocomplete("val")).toBe(">");
- expect(lastCommandWith("open")).toBe(true);
- expect(onInput).toHaveBeenCalled();
- });
-});
-
-describe("fullTextSearch guards", () => {
- 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);
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index 37216c3586..3aa80c84b0 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -1,5 +1,4 @@
import appContext from "../components/app_context.js";
-import commandRegistry from "./command_registry.js";
import dateNoteService from "./date_notes.js";
import froca from "./froca.js";
import { t } from "./i18n.js";
@@ -13,31 +12,6 @@ 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 = {}) {
- // Check if we're in command mode
- if (options.isCommandPalette && term.startsWith(">")) {
- const commandQuery = term.substring(1).trim();
-
- // Get commands (all if no query, filtered if query provided)
- const commands = commandQuery.length === 0
- ? commandRegistry.getAllCommands()
- : commandRegistry.searchCommands(commandQuery);
-
- // Convert commands to suggestions
- const commandSuggestions: Suggestion[] = commands.map(cmd => ({
- action: "command",
- commandId: cmd.id,
- noteTitle: cmd.name,
- notePathTitle: `>${cmd.name}`,
- highlightedNotePathTitle: cmd.name,
- commandDescription: cmd.description,
- commandShortcut: cmd.shortcut,
- icon: cmd.icon
- }));
-
- cb(commandSuggestions);
- return;
- }
-
const fastSearch = options.fastSearch !== false;
if (fastSearch === false) {
if (term.trim().length === 0) {
@@ -96,13 +70,6 @@ function setText($el: JQuery<HTMLElement>, text: string) {
$el.autocomplete("open");
}
-function showAllCommands($el: JQuery<HTMLElement>) {
- $el.setSelectedNotePath("");
- $el.autocomplete("val", ">");
- $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) {
@@ -218,25 +185,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
});
},
displayKey: "notePathTitle",
- templates: {
- suggestion: (suggestion) => {
- if (suggestion.action === "command") {
- let html = `<div class="command-suggestion">`;
- html += `<span class="command-icon ${escapeHtml(suggestion.icon || "bx bx-terminal")}"></span>`;
- html += `<div class="command-content">`;
- html += `<div class="command-name">${suggestion.highlightedNotePathTitle}</div>`;
- if (suggestion.commandDescription) {
- html += `<div class="command-description">${suggestion.commandDescription}</div>`;
- }
- html += `</div>`;
- if (suggestion.commandShortcut) {
- html += `<kbd class="command-shortcut">${suggestion.commandShortcut}</kbd>`;
- }
- html += '</div>';
- return html;
- }
- }
- },
// we can't cache identical searches because notes can be created / renamed, new recent notes can be added
cache: false
}
@@ -245,12 +193,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
//@ts-expect-error The `autocomplete:selected` handler takes an extra `suggestion` argument that jQuery's `.on()` typings don't model.
$el.on("autocomplete:selected", async (event: Event, suggestion: Suggestion) => {
- if (suggestion.action === "command") {
- $el.autocomplete("close");
- $el.trigger("autocomplete:commandselected", [suggestion]);
- return;
- }
-
if (suggestion.action === "external-link") {
$el.setSelectedNotePath(null);
$el.setSelectedExternalLink(suggestion.externalLink);
@@ -369,7 +311,6 @@ function init() {
export default {
initNoteAutocomplete,
- showAllCommands,
setText,
init
};
diff --git a/apps/client/src/widgets/dialogs/jump_to_note.tsx b/apps/client/src/widgets/dialogs/jump_to_note.tsx
index 609d167f17..c16cc5eb3e 100644
--- a/apps/client/src/widgets/dialogs/jump_to_note.tsx
+++ b/apps/client/src/widgets/dialogs/jump_to_note.tsx
@@ -5,7 +5,7 @@ import { useRef, useState } from "preact/hooks";
import appContext from "../../components/app_context";
import commandRegistry from "../../services/command_registry";
import { t } from "../../services/i18n";
-import note_autocomplete, { Suggestion } from "../../services/note_autocomplete";
+import type { Suggestion } from "../../services/note_autocomplete";
import shortcutService from "../../services/shortcuts";
import Button from "../react/Button";
import { useTriliumEvent } from "../react/hooks";
@@ -84,7 +84,7 @@ export default function JumpToNoteDialogComponent() {
handleRef.current?.showRecentNotes();
break;
case "commands":
- note_autocomplete.showAllCommands($autoComplete);
+ handleRef.current?.showAllCommands();
break;
}
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 11a8cd24c1..f3ae9973de 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -2,13 +2,15 @@ import { createRef, render as preactRender } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const { getNoteSuggestions } = vi.hoisted(() => ({
- getNoteSuggestions: vi.fn<(term: string) => Promise<Suggestion[]>>(async () => [])
+const { getNoteSuggestions, getCommandSuggestions } = vi.hoisted(() => ({
+ getNoteSuggestions: vi.fn<(term: string) => Promise<Suggestion[]>>(async () => []),
+ getCommandSuggestions: vi.fn<(term: string) => Suggestion[]>(() => [])
}));
vi.mock("../../services/note_autocomplete", async (importOriginal) => ({
...(await importOriginal<typeof import("../../services/note_autocomplete")>()),
- getNoteSuggestions
+ getNoteSuggestions,
+ getCommandSuggestions
}));
import type { Suggestion } from "../../services/note_autocomplete";
@@ -123,11 +125,18 @@ describe("NoteAutocomplete's suggestion list", () => {
{ notePath: "root/x/b", noteTitle: "Beta", notePathTitle: "X / Beta", highlightedNotePathTitle: "X / Beta",
highlightedAttributeSnippet: "#tag" }
];
+ const commands: Suggestion[] = [
+ { action: "command", commandId: "cmd1", noteTitle: "Cmd One", highlightedNotePathTitle: "Cmd One",
+ commandDescription: "Does a thing", commandShortcut: "Ctrl+1", icon: "bx bx-cog" },
+ { action: "command", commandId: "cmd2", noteTitle: "Cmd Two", highlightedNotePathTitle: "Cmd Two" }
+ ];
beforeEach(() => {
vi.useFakeTimers();
getNoteSuggestions.mockReset();
getNoteSuggestions.mockResolvedValue(notes);
+ getCommandSuggestions.mockReset();
+ getCommandSuggestions.mockReturnValue(commands);
});
afterEach(() => {
@@ -314,6 +323,56 @@ describe("NoteAutocomplete's suggestion list", () => {
host.remove();
});
+ it("lists the commands for a `>` in a command palette, in the plugin's markup", async () => {
+ const input = await mount({ opts: { isCommandPalette: true } });
+ await type(input, "> cmd");
+
+ expect(getCommandSuggestions).toHaveBeenLastCalledWith("> cmd");
+ expect(getNoteSuggestions).not.toHaveBeenCalled();
+ const [ described, bare ] = rows();
+ expect(described.querySelector(".command-suggestion > .command-icon")?.className).toBe("command-icon bx bx-cog");
+ expect(described.querySelector(".command-content > .command-name")?.textContent).toBe("Cmd One");
+ expect(described.querySelector(".command-content > .command-description")?.textContent).toBe("Does a thing");
+ expect(described.querySelector(".command-suggestion > kbd.command-shortcut")?.textContent).toBe("Ctrl+1");
+ expect(bare.querySelector(".command-icon")?.className).toBe("command-icon bx bx-terminal");
+ expect(bare.querySelector(".command-description, .command-shortcut")).toBeNull();
+
+ // Elsewhere a `>` is only text to search for.
+ const plain = await mount();
+ await type(plain, "> cmd");
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("> cmd");
+ expect(getCommandSuggestions).toHaveBeenCalledTimes(1);
+ });
+
+ it("reports a picked command and leaves the field as it was", async () => {
+ const onChange = vi.fn();
+ const noteIdChanged = vi.fn();
+ const input = await mount({ opts: { isCommandPalette: true }, onChange, noteIdChanged });
+ await type(input, ">");
+ await press(input, "Enter");
+
+ expect(onChange).toHaveBeenCalledWith(commands[0]);
+ expect(noteIdChanged).not.toHaveBeenCalled();
+ expect(input.value).toBe(">");
+ expect(input.dataset.notePath).toBe("");
+ expect(rows()).toHaveLength(0);
+ });
+
+ it("lists every command through the handle", async () => {
+ const handleRef = createRef<NoteAutocompleteHandle>();
+ const onTextChange = vi.fn();
+ const input = await mount({ opts: { isCommandPalette: true }, handleRef, onTextChange });
+
+ await act(async () => { handleRef.current?.showAllCommands(); });
+ await settle();
+
+ expect(input.value).toBe(">");
+ expect(onTextChange).toHaveBeenLastCalledWith(">");
+ expect(getCommandSuggestions).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 5db77c644a..69252184d3 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -7,7 +7,7 @@ import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useR
import froca from "../../services/froca";
import { t } from "../../services/i18n";
-import { createSearchScheduler, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
+import { createSearchScheduler, getCommandSuggestions, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
import { useAutocomplete } from "./FormAutocomplete";
import { useSyncedRef } from "./hooks";
import Popup from "./Popup";
@@ -39,6 +39,8 @@ export interface NoteAutocompleteProps {
export interface NoteAutocompleteHandle {
/** Empties the field, lists the recently visited notes and focuses the field. */
showRecentNotes(): void;
+ /** Puts `>` in the field, lists every command and focuses the field. */
+ showAllCommands(): void;
}
export default function NoteAutocomplete({ id, inputRef: externalInputRef, text, placeholder, container, containerStyle, opts, onChange, onTextChange, onKeyDown, onBlur, noteIdChanged, noteId, readOnly, tabIndex, handleRef }: NoteAutocompleteProps) {
@@ -57,10 +59,19 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
}, [ text, noteId ]);
- const source = useCallback((query: string) => getNoteSuggestions(query), []);
+ const isCommandPalette = !!opts?.isCommandPalette;
+ const source = useCallback(async (query: string) => (isCommandPalette && query.startsWith(">")
+ ? getCommandSuggestions(query)
+ : getNoteSuggestions(query)), [ isCommandPalette ]);
const schedule = useMemo(() => createSearchScheduler(), []);
const pickSuggestion = useCallback((suggestion: Suggestion) => {
+ // The host runs a command; the field keeps what was typed.
+ if (suggestion.action === "command") {
+ onChange?.(suggestion);
+ return;
+ }
+
setValue(suggestion.noteTitle ?? "");
setNotePath(suggestion.notePath ?? "");
onChange?.(suggestion);
@@ -80,18 +91,22 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
schedule
});
- /** Empties the query, which the server answers with the recently visited notes, and lists them. */
- function showRecentNotes() {
+ /** Puts `query` in the field, drops the selection, lists the suggestions and focuses the field. */
+ function showSuggestionsFor(query: string) {
setNotePath("");
- setValue("");
- onTextChange?.("");
+ setValue(query);
+ onTextChange?.(query);
autocomplete.open();
inputRef.current?.focus();
}
+ // An empty query is answered with the recently visited notes.
+ const showRecentNotes = () => showSuggestionsFor("");
+ const showAllCommands = () => showSuggestionsFor(">");
+
// Refreshed on every render, so a call from outside reaches the current callbacks.
useLayoutEffect(() => {
- if (handleRef) handleRef.current = { showRecentNotes };
+ if (handleRef) handleRef.current = { showRecentNotes, showAllCommands };
});
const showButtons = !opts?.hideAllButtons;
@@ -201,7 +216,7 @@ function NoteSuggestionList({ autocomplete }: { autocomplete: ReturnType<typeof
<span className="aa-suggestions">
{autocomplete.items.map((suggestion, index) => (
<div
- key={`${suggestion.action ?? ""}:${suggestion.notePath ?? index}`}
+ key={`${suggestion.action ?? ""}:${suggestion.notePath ?? suggestion.commandId ?? index}`}
id={autocomplete.itemId(index)}
className={clsx("aa-suggestion", index === autocomplete.activeIndex && "aa-cursor")}
role="option"
@@ -220,6 +235,21 @@ function NoteSuggestionList({ autocomplete }: { autocomplete: ReturnType<typeof
/** One row of the list, in the markup of the jQuery plugin's suggestion template. */
function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
+ if (suggestion.action === "command") {
+ return (
+ <div className="command-suggestion">
+ <span className={clsx("command-icon", suggestion.icon || "bx bx-terminal")} />
+ <div className="command-content">
+ <div className="command-name">{suggestion.highlightedNotePathTitle}</div>
+ {suggestion.commandDescription && (
+ <div className="command-description">{suggestion.commandDescription}</div>
+ )}
+ </div>
+ {suggestion.commandShortcut && <kbd className="command-shortcut">{suggestion.commandShortcut}</kbd>}
+ </div>
+ );
+ }
+
return (
<div className={clsx("note-suggestion", suggestion.action === "search-notes" && "search-notes-action")}>
<span className={clsx("icon", suggestionIcon(suggestion))} />
diff --git a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
index 91f6febeab..2f8a19f1dc 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete_bak.tsx
@@ -12,8 +12,7 @@ export default function NoteAutocomplete({ inputRef: externalInputRef, text, onC
// clear any event listener added in previous invocation of this function
$autoComplete
- .off("autocomplete:noteselected")
- .off("autocomplete:commandselected")
+ .off("autocomplete:noteselected");
note_autocomplete.initNoteAutocomplete($autoComplete, opts);
}, [opts]);
@@ -33,12 +32,10 @@ export default function NoteAutocomplete({ inputRef: externalInputRef, text, onC
}
};
$autoComplete
- .on("autocomplete:externallinkselected", autoCompleteListener)
- .on("autocomplete:commandselected", autoCompleteListener);
+ .on("autocomplete:externallinkselected", autoCompleteListener);
return () => {
$autoComplete
- .off("autocomplete:externallinkselected", autoCompleteListener)
- .off("autocomplete:commandselected", autoCompleteListener);
+ .off("autocomplete:externallinkselected", autoCompleteListener);
};
}
}, [opts, onChange, noteIdChanged])