Skip to content

Build your personal knowledge base with Trilium Notes

refactor(autocomplete): bring back the action rows of the note autocomplete

Elian Doran8fd730535131
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index 0c919d5fb1..defe0c562a 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -1,7 +1,14 @@
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const { getActiveContextNoteId, getInboxTarget, translate, logError, getAllCommands, searchCommands } = vi.hoisted(() => ({
+const {
+ getActiveContextNoteId, getActiveContext, getInboxTarget, getInboxNotePath, chooseNoteType, createNote, translate, logError,
+ getAllCommands, searchCommands
+} = vi.hoisted(() => ({
getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),
+ getActiveContext: vi.fn<() => { hoistedNoteId: string } | undefined>(() => ({ hoistedNoteId: "hoisted" })),
+ getInboxNotePath: vi.fn<() => Promise<string | undefined>>(async () => "root/inbox"),
+ chooseNoteType: vi.fn(),
+ createNote: vi.fn(),
getInboxTarget: vi.fn<() => Promise<unknown>>(
async () => ({ kind: "inbox", noteId: "inb", title: "Inbox" })
),
@@ -18,11 +25,15 @@ vi.mock("./command_registry.js", () => ({
}));
vi.mock("../components/app_context.js", () => ({
- default: { tabManager: { getActiveContextNoteId } }
+ default: { tabManager: { getActiveContextNoteId, getActiveContext } }
}));
vi.mock("./date_notes.js", () => ({
- default: { getInboxTarget }
+ default: { getInboxTarget, getInboxNotePath }
+}));
+
+vi.mock("./note_create.js", () => ({
+ default: { chooseNoteType, createNote }
}));
vi.mock("./i18n.js", async (importOriginal) => ({
@@ -43,12 +54,13 @@ vi.mock("./ws.js", () => ({
}));
import type { CommandDefinition } from "./command_registry.js";
-import noteAutocomplete, { createSearchScheduler, getCommandSuggestions, getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
+import noteAutocomplete, { createNoteFromSuggestion, createSearchScheduler, getCommandSuggestions, getNoteSuggestions, type Suggestion } from "./note_autocomplete.js";
import server from "./server.js";
beforeEach(() => {
vi.clearAllMocks();
getActiveContextNoteId.mockReturnValue("activeNote");
+ getActiveContext.mockReturnValue({ hoistedNoteId: "hoisted" });
server.get = vi.fn(async () => []) as typeof server.get;
});
@@ -128,6 +140,22 @@ describe("getNoteSuggestions", () => {
await getNoteSuggestions("New", { allowCreatingNotes: true });
expect(logError).toHaveBeenCalledWith(expect.stringContaining("nope"));
});
+
+ it("adds the external-link row first for a URL, and the search row last for any term", async () => {
+ server.get = vi.fn(async () => [ { noteTitle: "A", notePath: "root/a" } ]) as typeof server.get;
+ const all = { allowCreatingNotes: true, allowJumpToSearchNotes: true, allowExternalLinks: true };
+
+ const rows = await getNoteSuggestions("https://example.com/x", all);
+ expect(rows.map((r) => r.action)).toEqual([ "external-link", "create-note", "create-child-note", undefined, "search-notes" ]);
+ expect(rows[0]).toMatchObject({ externalLink: "https://example.com/x", highlightedNotePathTitle: "note_autocomplete.insert-external-link" });
+ expect(rows[4]).toMatchObject({ noteTitle: "https://example.com/x", highlightedNotePathTitle: "note_autocomplete.search-for" });
+
+ // Not a URL, and a blank term: neither row is offered.
+ expect((await getNoteSuggestions("plain", all)).map((r) => r.action)).not.toContain("external-link");
+ expect((await getNoteSuggestions(" ", all)).map((r) => r.action)).toEqual([ undefined ]);
+ // And only when asked for.
+ expect((await getNoteSuggestions("https://example.com/x")).map((r) => r.action)).toEqual([ undefined ]);
+ });
});
describe("autocompleteSourceForCKEditor", () => {
@@ -290,3 +318,43 @@ describe("getCommandSuggestions", () => {
expect(searchCommands).toHaveBeenCalledWith("hello");
});
});
+
+describe("createNoteFromSuggestion", () => {
+ beforeEach(() => {
+ chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });
+ createNote.mockResolvedValue({ note: { getBestNotePathString: (hoisted: string) => `root/${hoisted}/created` } });
+ });
+
+ it("creates the note in the inbox, or under the row's parent, and returns its path", async () => {
+ expect(await createNoteFromSuggestion({ action: "create-note", noteTitle: "Created" })).toBe("root/hoisted/created");
+ expect(createNote).toHaveBeenLastCalledWith("root/inbox", expect.objectContaining({ title: "Created", type: "text", activate: false }));
+
+ await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "Child", parentNoteId: "parent" });
+ expect(createNote).toHaveBeenLastCalledWith("parent", expect.objectContaining({ title: "Child" }));
+ expect(getInboxNotePath).toHaveBeenCalledTimes(1);
+ });
+
+ it("puts the note where the type chooser says, over the row's own parent", async () => {
+ chooseNoteType.mockResolvedValue({ success: true, noteType: "code", notePath: "chosen/path" });
+
+ await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "X", parentNoteId: "p" });
+ expect(createNote).toHaveBeenCalledWith("chosen/path", expect.objectContaining({ type: "code" }));
+ });
+
+ it.each([
+ { when: "the type chooser is canceled", arrange: () => chooseNoteType.mockResolvedValue({ success: false }) },
+ { when: "there is no inbox", arrange: () => getInboxNotePath.mockResolvedValueOnce(undefined) }
+ ])("creates nothing when $when", async ({ arrange }) => {
+ arrange();
+
+ expect(await createNoteFromSuggestion({ action: "create-note", noteTitle: "X" })).toBeUndefined();
+ expect(createNote).not.toHaveBeenCalled();
+ });
+
+ it("returns nothing for a note that was not created", async () => {
+ createNote.mockResolvedValue({ note: undefined });
+ getActiveContext.mockReturnValue(undefined);
+
+ expect(await createNoteFromSuggestion({ action: "create-note", noteTitle: "X" })).toBeUndefined();
+ });
+});
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index d2bb75f089..377147e714 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -5,6 +5,7 @@ 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 noteCreateService from "./note_create.js";
import server from "./server.js";
import { escapeHtml } from "./utils.js";
import { logError } from "./ws.js";
@@ -61,37 +62,94 @@ async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNot
}));
}
+export interface NoteSuggestionOptions {
+ /** Adds the two note-creation rows ahead of the notes, for a non-blank term. */
+ allowCreatingNotes?: boolean;
+ /** Adds a row that runs a search for a non-blank term, after the notes. */
+ allowJumpToSearchNotes?: boolean;
+ /** Adds a row that inserts a term that is a URL as an external link, ahead of everything. */
+ allowExternalLinks?: boolean;
+ /** Searches the titles only, as autocompletion does, or the content as well. */
+ fastSearch?: boolean;
+}
+
/**
- * Returns the notes matching `term`, or the recently visited notes when `term` is blank. With
- * `allowCreatingNotes`, a non-blank term also gets the two note-creation rows, ahead of the notes.
+ * Returns the notes matching `term`, or the recently visited notes when `term` is blank, with the
+ * action rows the options ask for.
*/
-export async function getNoteSuggestions(term: string, { allowCreatingNotes = false, fastSearch = true } = {}): Promise<Suggestion[]> {
+export async function getNoteSuggestions(term: string, { allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks, fastSearch = true }: NoteSuggestionOptions = {}): Promise<Suggestion[]> {
const activeNoteId = appContext.tabManager.getActiveContextNoteId();
+ const hasTerm = term.trim().length >= 1;
// Runs concurrently with the search, so naming the destination costs a request but no wait.
- const pendingInboxTarget = term.trim().length >= 1 && allowCreatingNotes ? getInboxTarget() : null;
+ const pendingInboxTarget = hasTerm && allowCreatingNotes ? getInboxTarget() : null;
- const results = await server.get<AutocompleteResult[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}`);
- if (!pendingInboxTarget) {
- return results;
+ const results: Suggestion[] = await server.get<AutocompleteResult[]>(`autocomplete?query=${encodeURIComponent(term)}&activeNoteId=${activeNoteId}&fastSearch=${fastSearch}`);
+ const before: Suggestion[] = [];
+ const after: Suggestion[] = [];
+
+ if (allowExternalLinks && /^[a-z]+:\/\/.+/i.test(term)) {
+ before.push({
+ action: "external-link",
+ externalLink: term,
+ highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term: escapeHtml(term) })
+ });
}
// Both rows stay above the results: the CKEditor mention feed renders only the first
// `mention.dropdownLimit` items.
- return [
- {
+ if (pendingInboxTarget) {
+ before.push({
action: "create-note",
noteTitle: term,
highlightedNotePathTitle: buildCreateNoteTitle(term, await pendingInboxTarget)
- },
- {
+ }, {
action: "create-child-note",
noteTitle: term,
parentNoteId: activeNoteId || "root",
highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term: escapeHtml(term) })
- },
- ...results
- ];
+ });
+ }
+
+ if (hasTerm && allowJumpToSearchNotes) {
+ after.push({
+ action: "search-notes",
+ noteTitle: term,
+ highlightedNotePathTitle: t("note_autocomplete.search-for", { term: escapeHtml(term) })
+ });
+ }
+
+ return [ ...before, ...results, ...after ];
+}
+
+/**
+ * Creates the note a creation row offers, under the parent the user picks in the type chooser, or
+ * else in the inbox (`create-note`) or under the row's parent (`create-child-note`). Returns the
+ * new note's path, or nothing when the chooser is canceled or no parent is found.
+ */
+export async function createNoteFromSuggestion(suggestion: Suggestion) {
+ const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();
+ if (!success) {
+ return;
+ }
+
+ const parentNotePath = notePath ?? (suggestion.action === "create-note"
+ ? await dateNoteService.getInboxNotePath()
+ : suggestion.parentNoteId);
+ if (!parentNotePath) {
+ return;
+ }
+
+ const { note } = await noteCreateService.createNote(parentNotePath, {
+ title: suggestion.noteTitle,
+ activate: false,
+ type: noteType,
+ templateNoteId,
+ cloneToNoteIds
+ });
+
+ const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
+ return note?.getBestNotePathString(hoistedNoteId);
}
/**
diff --git a/apps/client/src/services/note_autocomplete_bak.spec.ts b/apps/client/src/services/note_autocomplete_bak.spec.ts
index d24c18abd2..801ed2b956 100644
--- a/apps/client/src/services/note_autocomplete_bak.spec.ts
+++ b/apps/client/src/services/note_autocomplete_bak.spec.ts
@@ -107,66 +107,6 @@ function lastCommandWith(arg: any) {
return autocompleteCalls.some((c) => c[0] === arg && c[1] === undefined);
}
-// ---------------------------------------------------------------------------
-// Exercise the internal autocompleteSource via the dataset.source registered
-// during initNoteAutocomplete (it is not exported, so we go through the public
-// init path and capture the dataset callbacks).
-// ---------------------------------------------------------------------------
-
-function initAndGetSource(options?: any) {
- const $el = makeEl();
- noteAutocomplete.initNoteAutocomplete($el, options);
- return { $el, dataset: lastDatasets![0] };
-}
-
-/** Runs the dataset.source and resolves with the rows it passes to cb. */
-function runSource(dataset: Dataset, term: string): Promise<any[]> {
- return new Promise((resolve) => {
- dataset.source(term, (rows) => resolve(rows));
- });
-}
-
-/**
- * Fires the (debounced) dataset.source with the given cb and waits long enough
- * for the debounce timer + the awaited body to flush, even when cb is never called.
- */
-function runSourceRaw(dataset: Dataset, term: string, cb: (rows: any[]) => void): Promise<void> {
- dataset.source(term, cb);
- return new Promise((resolve) => setTimeout(resolve, 30));
-}
-
-describe("autocompleteSource (via dataset)", () => {
- beforeEach(() => {
- vi.clearAllMocks();
- getActiveContextNoteId.mockReturnValue("activeNote");
- registerAutocompleteStub();
- server.get = vi.fn(async () => []) as typeof server.get;
- noteAutocomplete.init();
- });
-
- it("appends a search-notes suggestion when allowJumpToSearchNotes", async () => {
- server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
- const { dataset } = initAndGetSource({ allowJumpToSearchNotes: true });
- const rows = await runSource(dataset, "term");
- expect(rows[rows.length - 1].action).toBe("search-notes");
- });
-
- it("prepends an external-link suggestion when allowExternalLinks and term is a URL", async () => {
- server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
- const { dataset } = initAndGetSource({ allowExternalLinks: true });
- const rows = await runSource(dataset, "https://example.com/x");
- expect(rows[0].action).toBe("external-link");
- expect(rows[0].externalLink).toBe("https://example.com/x");
- });
-
- it("does not add a search-notes suggestion for an empty term", async () => {
- server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;
- const { dataset } = initAndGetSource({ allowJumpToSearchNotes: true, allowExternalLinks: true });
- const rows = await runSource(dataset, " ");
- expect(rows.every((r) => r.action !== "search-notes")).toBe(true);
- });
-});
-
describe("$.fn jQuery extensions (init)", () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -262,33 +202,6 @@ describe("initNoteAutocomplete wiring", () => {
expect(result).toBe($el);
});
- it("Ctrl+Enter triggers a search-notes selection when allowJumpToSearchNotes", () => {
- const $el = makeEl();
- const selected = vi.fn();
- ($el as any).on("autocomplete:selected", selected);
- noteAutocomplete.initNoteAutocomplete($el, { allowJumpToSearchNotes: true });
-
- $el.autocomplete("val", "find this");
- const ev = $.Event("keydown", { ctrlKey: true, key: "Enter" });
- $el.trigger(ev);
- expect(selected).toHaveBeenCalled();
- const payload = selected.mock.calls[0][1];
- expect(payload.action).toBe("search-notes");
- });
-
- it("ignores keydowns that are not Ctrl+Enter", () => {
- const $el = makeEl();
- const selected = vi.fn();
- ($el as any).on("autocomplete:selected", selected);
- noteAutocomplete.initNoteAutocomplete($el, { allowJumpToSearchNotes: true });
-
- // a plain key press -> neither handler fires its body
- $el.trigger($.Event("keydown", { key: "a" }));
- // Ctrl without Enter
- $el.trigger($.Event("keydown", { ctrlKey: true, key: "a" }));
- expect(selected).not.toHaveBeenCalled();
- });
-
// Issue #5669: autocomplete.js empties its suggestion list only a tick after closing
// it, and its Enter handler selects from the closed-but-not-yet-emptied dropdown, so
// a fast second Enter right after a selection would consume a stale suggestion row.
@@ -364,73 +277,6 @@ describe("autocomplete:selected handler", () => {
return new Promise((r) => setTimeout(r, 0));
}
- it("handles an external-link selection", async () => {
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "external-link", externalLink: "https://e.com" });
- expect($el.attr("data-external-link")).toBe("https://e.com");
- expect(handlers["autocomplete:externallinkselected"]).toBeDefined();
- });
-
- it("handles a search-notes selection by triggering searchNotes", async () => {
- const { $el } = initWithSelected();
- await fireSelected($el, { action: "search-notes", noteTitle: "query" });
- expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "query" });
- });
-
- it("creates a note in the inbox then selects it", async () => {
- chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });
- createNote.mockResolvedValue({ note: { getBestNotePathString: () => "root/created" } });
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "create-note", noteTitle: "Created" });
- expect(chooseNoteType).toHaveBeenCalled();
- expect(createNote).toHaveBeenCalledWith("root/inbox", expect.objectContaining({ title: "Created", type: "text" }));
- expect(handlers["autocomplete:noteselected"]).toBeDefined();
- expect(handlers["autocomplete:noteselected"].notePath).toBe("root/created");
- });
-
- it("creates a child note under the suggested parent", async () => {
- chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });
- createNote.mockResolvedValue({ note: { getBestNotePathString: () => "root/created" } });
- const { $el } = initWithSelected();
- await fireSelected($el, { action: "create-child-note", noteTitle: "Created", parentNoteId: "parent" });
- expect(getInboxNotePath).not.toHaveBeenCalled();
- expect(createNote).toHaveBeenCalledWith("parent", expect.objectContaining({ title: "Created" }));
- });
-
- it("aborts when the inbox cannot be resolved", async () => {
- chooseNoteType.mockResolvedValue({ success: true, noteType: "text" });
- getInboxNotePath.mockResolvedValueOnce(undefined);
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "create-note", noteTitle: "X" });
- expect(createNote).not.toHaveBeenCalled();
- expect(handlers["autocomplete:noteselected"]).toBeUndefined();
- });
-
- it("aborts the create-note flow when the type chooser is cancelled", async () => {
- chooseNoteType.mockResolvedValue({ success: false });
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "create-note", noteTitle: "X", parentNoteId: "p" });
- expect(createNote).not.toHaveBeenCalled();
- expect(handlers["autocomplete:noteselected"]).toBeUndefined();
- });
-
- it("uses the chosen notePath as parent and tolerates a missing created note", async () => {
- chooseNoteType.mockResolvedValue({ success: true, noteType: "text", notePath: "chosen/path" });
- createNote.mockResolvedValue({ note: undefined });
- getActiveContext.mockReturnValue(undefined);
- const { $el, handlers } = initWithSelected();
- await fireSelected($el, { action: "create-note", noteTitle: "X", parentNoteId: "p" });
- expect(createNote).toHaveBeenCalledWith("chosen/path", expect.any(Object));
- // The missing-note branch must be tolerated end to end: note?.getBestNotePathString
- // and getActiveContext()?.hoistedNoteId are both undefined and must not throw.
- // The flow still falls through to fire autocomplete:noteselected with an
- // undefined notePath (rather than crashing inside the async handler).
- expect(handlers["autocomplete:noteselected"]).toBeDefined();
- expect(handlers["autocomplete:noteselected"].notePath).toBeUndefined();
- // the selection was written back as a cleared path (setSelectedNotePath(undefined))
- expect($el.attr("data-note-path") ?? "").toBe("");
- });
-
it("handles a plain note selection", async () => {
const { $el, handlers } = initWithSelected();
await fireSelected($el, { action: undefined, notePath: "root/n", noteTitle: "N" });
diff --git a/apps/client/src/services/note_autocomplete_bak.ts b/apps/client/src/services/note_autocomplete_bak.ts
index 2fab0d4ee4..f98f625351 100644
--- a/apps/client/src/services/note_autocomplete_bak.ts
+++ b/apps/client/src/services/note_autocomplete_bak.ts
@@ -1,10 +1,5 @@
-import appContext from "../components/app_context.js";
-import dateNoteService from "./date_notes.js";
import froca from "./froca.js";
-import { t } from "./i18n.js";
import { createSearchScheduler, getNoteSuggestions, type Options, type Suggestion } from "./note_autocomplete.js";
-import noteCreateService from "./note_create.js";
-import { escapeHtml } from "./utils.js";
// this key needs to have this value, so it's hit by the tooltip
const SELECTED_NOTE_PATH_KEY = "data-note-path";
@@ -12,31 +7,7 @@ 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 = {}) {
- const length = term.trim().length;
-
- let results = await getNoteSuggestions(term, { allowCreatingNotes: options.allowCreatingNotes });
-
- if (length >= 1 && options.allowJumpToSearchNotes) {
- results = results.concat([
- {
- action: "search-notes",
- noteTitle: term,
- highlightedNotePathTitle: `${t("note_autocomplete.search-for", { term: escapeHtml(term) })} <kbd style='color: var(--muted-text-color); background-color: transparent; float: right;'>Ctrl+Enter</kbd>`
- }
- ]);
- }
-
- if (term.match(/^[a-z]+:\/\/.+/i) && options.allowExternalLinks) {
- results = [
- {
- action: "external-link",
- externalLink: term,
- highlightedNotePathTitle: t("note_autocomplete.insert-external-link", { term: escapeHtml(term) })
- } as Suggestion
- ].concat(results);
- }
-
- cb(results);
+ cb(await getNoteSuggestions(term, { allowCreatingNotes: options.allowCreatingNotes }));
}
function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
@@ -53,16 +24,6 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {
$el.addClass("note-autocomplete-input");
- if (options.allowJumpToSearchNotes) {
- $el.on("keydown", (event) => {
- if (event.ctrlKey && event.key === "Enter") {
- // Prevent Ctrl + Enter from triggering autoComplete.
- event.stopImmediatePropagation();
- event.preventDefault();
- $el.trigger("autocomplete:selected", { action: "search-notes", noteTitle: $el.autocomplete("val") });
- }
- });
- }
$el.on("keydown", (event) => {
const isPlainEnter = event.key === "Enter"
&& !event.ctrlKey && !event.shiftKey && !event.altKey && !event.metaKey;
@@ -104,50 +65,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 === "external-link") {
- $el.setSelectedNotePath(null);
- $el.setSelectedExternalLink(suggestion.externalLink);
-
- $el.autocomplete("val", suggestion.externalLink);
-
- $el.autocomplete("close");
-
- $el.trigger("autocomplete:externallinkselected", [suggestion]);
-
- return;
- }
-
- if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {
- const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();
- if (!success) {
- return;
- }
-
- const parentNotePath = notePath ?? (suggestion.action === "create-note"
- ? await dateNoteService.getInboxNotePath()
- : suggestion.parentNoteId);
- if (!parentNotePath) {
- return;
- }
-
- const { note } = await noteCreateService.createNote(parentNotePath, {
- title: suggestion.noteTitle,
- activate: false,
- type: noteType,
- templateNoteId,
- cloneToNoteIds
- });
-
- const hoistedNoteId = appContext.tabManager.getActiveContext()?.hoistedNoteId;
- suggestion.notePath = note?.getBestNotePathString(hoistedNoteId);
- }
-
- if (suggestion.action === "search-notes") {
- const searchString = suggestion.noteTitle;
- appContext.triggerCommand("searchNotes", { searchString });
- return;
- }
-
$el.setSelectedNotePath(suggestion.notePath);
$el.setSelectedExternalLink(null);
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.css
index 60d95f88dd..b57909abc4 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.css
+++ b/apps/client/src/widgets/react/NoteAutocomplete.css
@@ -101,3 +101,10 @@ span.aa-dropdown-menu .aa-suggestion {
background-color: var(--active-item-background-color);
}
}
+
+/* The shortcut of the row that runs a search, at the end of its title line. */
+.search-notes-action .text > kbd {
+ float: inline-end;
+ color: var(--muted-text-color);
+ background-color: transparent;
+}
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 038a376ae2..a2cd0624fd 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -2,18 +2,21 @@ import { createRef, render as preactRender } from "preact";
import { act } from "preact/test-utils";
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-const { getNoteSuggestions, getCommandSuggestions } = vi.hoisted(() => ({
- getNoteSuggestions: vi.fn<(term: string) => Promise<Suggestion[]>>(async () => []),
+const { getNoteSuggestions, getCommandSuggestions, createNoteFromSuggestion } = vi.hoisted(() => ({
+ createNoteFromSuggestion: vi.fn<(suggestion: Suggestion) => Promise<string | undefined>>(),
+ getNoteSuggestions: vi.fn<(term: string, options?: NoteSuggestionOptions) => Promise<Suggestion[]>>(async () => []),
getCommandSuggestions: vi.fn<(term: string) => Suggestion[]>(() => [])
}));
vi.mock("../../services/note_autocomplete", async (importOriginal) => ({
...(await importOriginal<typeof import("../../services/note_autocomplete")>()),
getNoteSuggestions,
- getCommandSuggestions
+ getCommandSuggestions,
+ createNoteFromSuggestion
}));
-import type { Suggestion } from "../../services/note_autocomplete";
+import appContext from "../../components/app_context";
+import type { NoteSuggestionOptions, Suggestion } from "../../services/note_autocomplete";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps } from "./NoteAutocomplete";
@@ -165,13 +168,18 @@ describe("NoteAutocomplete's suggestion list", () => {
await settle();
}
- async function press(input: HTMLInputElement, key: string) {
+ async function press(input: HTMLInputElement, key: string, modifiers: KeyboardEventInit = {}) {
await act(async () => {
- input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true }));
+ input.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...modifiers }));
});
await settle();
}
+ /** The queries the notes were looked up for, in order. */
+ function queries() {
+ return getNoteSuggestions.mock.calls.map(([ query ]) => query);
+ }
+
function rows() {
return [ ...document.querySelectorAll<HTMLElement>(".note-autocomplete-menu > .tn-menu-scroll > .dropdown-item") ];
}
@@ -180,7 +188,7 @@ describe("NoteAutocomplete's suggestion list", () => {
const input = await mount();
await type(input, "al");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al");
+ expect(queries().at(-1)).toBe("al");
const [ alpha, beta ] = rows();
expect(rows()).toHaveLength(2);
expect(document.querySelector(".note-autocomplete-menu")?.className)
@@ -239,10 +247,10 @@ describe("NoteAutocomplete's suggestion list", () => {
});
}
// No timer has run, so the debounce of `FormAutocomplete` would not have searched yet.
- expect(getNoteSuggestions.mock.calls).toEqual([ [ "a" ] ]);
+ expect(queries()).toEqual([ "a" ]);
await settle();
- expect(getNoteSuggestions.mock.calls).toEqual([ [ "a" ], [ "alp" ] ]);
+ expect(queries()).toEqual([ "a", "alp" ]);
});
it("lists the recent notes from the clock button, emptying the field", async () => {
@@ -264,7 +272,7 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(input.value).toBe("");
expect(input.dataset.notePath).toBe("");
expect(onTextChange).toHaveBeenLastCalledWith("");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("");
+ expect(queries().at(-1)).toBe("");
expect(rows()).toHaveLength(2);
expect(document.activeElement).toBe(input);
});
@@ -295,7 +303,7 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(input.dataset.notePath).toBe("");
expect(latestOnTextChange).toHaveBeenCalledWith("");
expect(firstOnTextChange).not.toHaveBeenCalled();
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("");
+ expect(queries().at(-1)).toBe("");
expect(rows()).toHaveLength(2);
expect(document.activeElement).toBe(input);
});
@@ -354,7 +362,7 @@ describe("NoteAutocomplete's suggestion list", () => {
// Elsewhere a `>` is only text to search for.
const plain = await mount();
await type(plain, "> cmd");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("> cmd");
+ expect(queries().at(-1)).toBe("> cmd");
expect(getCommandSuggestions).toHaveBeenCalledTimes(1);
});
@@ -394,7 +402,7 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(input.value).toBe("al");
expect(onTextChange).toHaveBeenCalledWith("al");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al");
+ expect(queries().at(-1)).toBe("al");
expect(rows()).toHaveLength(2);
});
@@ -411,7 +419,7 @@ describe("NoteAutocomplete's suggestion list", () => {
await settle();
expect(input.dataset.notePath).toBe("root/x/b");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("Beta");
+ expect(queries().at(-1)).toBe("Beta");
expect(rows()).toHaveLength(2);
expect(document.activeElement).not.toBe(input);
});
@@ -452,7 +460,7 @@ describe("NoteAutocomplete's suggestion list", () => {
await settle();
expect(mouseDown.defaultPrevented).toBe(true);
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { fastSearch: false });
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", expect.objectContaining({ fastSearch: false }));
expect(rows()).toHaveLength(1);
expect(rows()[0].querySelector(".search-result-title")).not.toBeNull();
expect(rows()[0].getAttribute("role")).toBeNull();
@@ -469,7 +477,7 @@ describe("NoteAutocomplete's suggestion list", () => {
// The next keystroke searches the titles again.
await type(input, "alp");
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("alp");
+ expect(queries().at(-1)).toBe("alp");
});
it("searches the content on Shift+Enter, keeping the key from the host", async () => {
@@ -488,7 +496,7 @@ describe("NoteAutocomplete's suggestion list", () => {
await settle();
expect(shiftEnter.defaultPrevented).toBe(true);
- expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", { fastSearch: false });
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", expect.objectContaining({ fastSearch: false }));
expect(onKeyDown).not.toHaveBeenCalledWith(shiftEnter);
});
@@ -515,7 +523,98 @@ describe("NoteAutocomplete's suggestion list", () => {
await act(async () => { input.dispatchEvent(new Event("compositionend", { bubbles: true })); });
await settle();
- expect(getNoteSuggestions.mock.calls).toEqual([ [ "nih" ] ]);
+ expect(queries()).toEqual([ "nih" ]);
+ });
+
+ describe("action rows", () => {
+ const searchRow: Suggestion = { action: "search-notes", noteTitle: "al", highlightedNotePathTitle: "Search for al" };
+ const linkRow: Suggestion = { action: "external-link", externalLink: "https://e.com", highlightedNotePathTitle: "Insert" };
+ const createRow: Suggestion = { action: "create-note", noteTitle: "New", highlightedNotePathTitle: "Create New" };
+
+ let triggerCommand: ReturnType<typeof vi.spyOn>;
+ beforeEach(() => {
+ triggerCommand = vi.spyOn(appContext, "triggerCommand").mockImplementation(() => Promise.resolve() as never);
+ createNoteFromSuggestion.mockReset();
+ });
+
+ afterEach(() => {
+ triggerCommand.mockRestore();
+ });
+
+ it("asks for the rows the options allow", async () => {
+ const input = await mount({ opts: { allowCreatingNotes: true, allowJumpToSearchNotes: true, allowExternalLinks: true } });
+ await type(input, "al");
+
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("al", {
+ allowCreatingNotes: true, allowJumpToSearchNotes: true, allowExternalLinks: true
+ });
+ });
+
+ it("runs a search from its row, with its shortcut shown, leaving the field", async () => {
+ const onChange = vi.fn();
+ getNoteSuggestions.mockResolvedValue([ searchRow ]);
+ const input = await mount({ onChange });
+ await type(input, "al");
+
+ expect(rows()[0].querySelector("kbd")?.textContent).toBe("Ctrl+Enter");
+ await press(input, "Enter");
+ expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "al" });
+ expect(onChange).not.toHaveBeenCalled();
+ expect(input.value).toBe("al");
+ });
+
+ it("runs a search on Ctrl+Enter where allowed, keeping the key from other listeners", async () => {
+ const input = await mount({ opts: { allowJumpToSearchNotes: true } });
+ await type(input, "al");
+ const laterListener = vi.fn();
+ input.addEventListener("keydown", laterListener);
+
+ await press(input, "Enter", { ctrlKey: true });
+ expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "al" });
+ expect(laterListener).not.toHaveBeenCalled();
+
+ triggerCommand.mockClear();
+ const plain = await mount();
+ await type(plain, "al");
+ await press(plain, "Enter", { ctrlKey: true });
+ expect(triggerCommand).not.toHaveBeenCalled();
+ });
+
+ it("fills in an external link from its row, with no note selected", async () => {
+ const onChange = vi.fn();
+ const noteIdChanged = vi.fn();
+ getNoteSuggestions.mockResolvedValue([ linkRow ]);
+ const input = await mount({ onChange, noteIdChanged });
+ await type(input, "https://e.com");
+ await press(input, "Enter");
+
+ expect(input.value).toBe("https://e.com");
+ expect(input.dataset.notePath).toBe("");
+ expect(onChange).toHaveBeenCalledWith(linkRow);
+ expect(noteIdChanged).not.toHaveBeenCalled();
+ });
+
+ it("creates a note from its row and reports it as picked, or nothing when canceled", async () => {
+ const onChange = vi.fn();
+ const noteIdChanged = vi.fn();
+ getNoteSuggestions.mockResolvedValue([ createRow ]);
+ createNoteFromSuggestion.mockResolvedValueOnce("root/inbox/created");
+ const input = await mount({ onChange, noteIdChanged });
+ await type(input, "New");
+ await press(input, "Enter");
+
+ expect(createNoteFromSuggestion).toHaveBeenCalledWith(createRow);
+ expect(onChange).toHaveBeenCalledWith({ ...createRow, notePath: "root/inbox/created" });
+ expect(noteIdChanged).toHaveBeenCalledWith("created");
+ expect(input.value).toBe("New");
+ expect(input.dataset.notePath).toBe("root/inbox/created");
+
+ onChange.mockClear();
+ createNoteFromSuggestion.mockResolvedValueOnce(undefined);
+ await type(input, "New");
+ await press(input, "Enter");
+ expect(onChange).not.toHaveBeenCalled();
+ });
});
it("spans the whole field, the buttons included", async () => {
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 2865b25cbc..ee2df1ca96 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -6,9 +6,10 @@ import type { RefObject } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
+import appContext from "../../components/app_context";
import froca from "../../services/froca";
import { t } from "../../services/i18n";
-import { createSearchScheduler, getCommandSuggestions, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
+import { createSearchScheduler, createNoteFromSuggestion, getCommandSuggestions, getNoteSuggestions, type Options, type Suggestion } from "../../services/note_autocomplete";
import { useAutocomplete } from "./FormAutocomplete";
import { useSyncedRef } from "./hooks";
import Icon from "./Icon";
@@ -61,31 +62,27 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
const [ fullTextSearchCount, setFullTextSearchCount ] = useState(0);
const [ isSearchingFullText, setSearchingFullText ] = useState(false);
- const isCommandPalette = !!opts?.isCommandPalette;
+ const { isCommandPalette, allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks } = opts ?? {};
const source = useCallback(async (query: string) => {
if (isCommandPalette && query.startsWith(">")) {
return getCommandSuggestions(query);
}
+
+ const options = { allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks };
if (!fullTextSearchCount) {
- return getNoteSuggestions(query);
+ return getNoteSuggestions(query, options);
}
setSearchingFullText(true);
try {
- return await getNoteSuggestions(query, { fastSearch: false });
+ return await getNoteSuggestions(query, { ...options, fastSearch: false });
} finally {
setSearchingFullText(false);
}
- }, [ isCommandPalette, fullTextSearchCount ]);
+ }, [ isCommandPalette, allowCreatingNotes, allowJumpToSearchNotes, allowExternalLinks, fullTextSearchCount ]);
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;
- }
-
+ const selectNote = useCallback((suggestion: Suggestion) => {
setValue(suggestion.noteTitle ?? "");
setNotePath(suggestion.notePath ?? "");
onChange?.(suggestion);
@@ -94,6 +91,32 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
}
}, [ onChange, noteIdChanged ]);
+ const pickSuggestion = useCallback((suggestion: Suggestion) => {
+ switch (suggestion.action) {
+ case "command":
+ // The host runs it; the field keeps what was typed.
+ onChange?.(suggestion);
+ break;
+ case "search-notes":
+ void appContext.triggerCommand("searchNotes", { searchString: suggestion.noteTitle });
+ break;
+ case "external-link":
+ setValue(suggestion.externalLink ?? "");
+ setNotePath("");
+ onChange?.(suggestion);
+ break;
+ case "create-note":
+ case "create-child-note":
+ // Reported as a picked note once created, with the row's `action` kept.
+ void createNoteFromSuggestion(suggestion).then((notePath) => {
+ if (notePath) selectNote({ ...suggestion, notePath });
+ });
+ break;
+ default:
+ selectNote(suggestion);
+ }
+ }, [ onChange, selectNote ]);
+
const autocomplete = useAutocomplete({
query: value,
source,
@@ -202,6 +225,14 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
onKeyDown={(e) => {
// An Enter while composing commits the input method's candidate instead.
const isEnter = e.key === "Enter" && !e.isComposing;
+ if (isEnter && e.ctrlKey && allowJumpToSearchNotes) {
+ // Kept from the host's other listeners, such as a Ctrl+Enter shortcut of its
+ // own, as the jQuery plugin did.
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ void appContext.triggerCommand("searchNotes", { searchString: value });
+ return;
+ }
if (isEnter && e.shiftKey) {
// Kept from the host and the list, as the jQuery plugin did.
e.preventDefault();
@@ -376,7 +407,7 @@ function NoteSuggestionMenuItem({ suggestion }: { suggestion: Suggestion }) {
<RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />
{description && <RawHtml className="search-result-attributes" html={description} />}
</div>
- {isCommand && suggestion.commandShortcut && <kbd>{suggestion.commandShortcut}</kbd>}
+ {suggestionShortcut(suggestion) && <kbd>{suggestionShortcut(suggestion)}</kbd>}
</span>
);
}
@@ -402,6 +433,7 @@ function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
<div className={clsx("note-suggestion", suggestion.action === "search-notes" && "search-notes-action")}>
<span className={clsx("icon", suggestionIcon(suggestion))} />
<span className="text">
+ {suggestionShortcut(suggestion) && <kbd>{suggestionShortcut(suggestion)}</kbd>}
<RawHtml className="search-result-title" html={suggestion.highlightedNotePathTitle ?? ""} />
{suggestion.highlightedAttributeSnippet && (
<RawHtml className="search-result-attributes" html={suggestion.highlightedAttributeSnippet} />
@@ -421,6 +453,14 @@ function suggestionIcon(suggestion: Suggestion) {
}
}
+/** The keys that act on a row from the field, without picking it from the list. */
+function suggestionShortcut(suggestion: Suggestion) {
+ switch (suggestion.action) {
+ case "command": return suggestion.commandShortcut;
+ case "search-notes": return "Ctrl+Enter";
+ }
+}
+
function suggestionText(suggestion: Suggestion) {
return suggestion.noteTitle ?? "";
}