Skip to content

Build your personal knowledge base with Trilium Notes

feat(autocomplete): list the notes first, the search and creation rows after them

Elian Doran1c2452495912
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.ts
index d905e94485..5ffc04f5c2 100644
--- a/apps/client/src/services/note_autocomplete.spec.ts
+++ b/apps/client/src/services/note_autocomplete.spec.ts
@@ -76,22 +76,22 @@ describe("getNoteSuggestions", () => {
expect(getInboxTarget).not.toHaveBeenCalled();
});
- it("places both creation rows above the results", async () => {
+ it("places both creation rows last, after the results", async () => {
server.get = vi.fn(async () => [ { noteTitle: "Existing", notePath: "root/y" } ]) as typeof server.get;
const rows = await getNoteSuggestions("New", { allowCreatingNotes: true });
- expect(rows.map((r) => r.action)).toEqual([ "create-note", "create-child-note", undefined ]);
- expect(rows.map((r) => r.noteTitle)).toEqual([ "New", "New", "Existing" ]);
+ expect(rows.map((r) => r.action)).toEqual([ undefined, "create-note", "create-child-note" ]);
+ expect(rows.map((r) => r.noteTitle)).toEqual([ "Existing", "New", "New" ]);
// The inbox is resolved when the row is picked, so the row carries no parent.
- expect(rows[0].parentNoteId).toBeUndefined();
- expect(rows[1].parentNoteId).toBe("activeNote");
+ expect(rows[1].parentNoteId).toBeUndefined();
+ expect(rows[2].parentNoteId).toBe("activeNote");
});
it("uses root as the child-note parent when there is no active note", async () => {
getActiveContextNoteId.mockReturnValue(null);
const rows = await getNoteSuggestions("New", { allowCreatingNotes: true });
- expect(rows[1]).toMatchObject({ action: "create-child-note", parentNoteId: "root" });
+ expect(rows.find((r) => r.action === "create-child-note")).toMatchObject({ parentNoteId: "root" });
});
it("adds no creation rows for a blank term", async () => {
@@ -141,14 +141,14 @@ describe("getNoteSuggestions", () => {
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 () => {
+ it("adds the external-link row first for a URL, and the search row after the notes 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.map((r) => r.action)).toEqual([ "external-link", undefined, "search-notes", "create-note", "create-child-note" ]);
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.show-in-full-search" });
+ expect(rows[2]).toMatchObject({ noteTitle: "https://example.com/x", highlightedNotePathTitle: "note_autocomplete.show-in-full-search" });
// Not a URL, and a blank term: neither row is offered.
expect((await getNoteSuggestions("plain", all)).map((r) => r.action)).not.toContain("external-link");
diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.ts
index f6a99c16ef..3bf99d57d9 100644
--- a/apps/client/src/services/note_autocomplete.ts
+++ b/apps/client/src/services/note_autocomplete.ts
@@ -48,6 +48,10 @@ export interface Options {
*/
async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNotes = true): Promise<MentionFeedObjectItem[]> {
const rows = await getNoteSuggestions(queryText, { allowCreatingNotes });
+ // The creation rows go first here: the mention list renders only the first
+ // `mention.dropdownLimit` items, which a long result list would push them past.
+ const isCreation = (row: Suggestion) => row.action === "create-note" || row.action === "create-child-note";
+ rows.sort((a, b) => Number(isCreation(b)) - Number(isCreation(a)));
return rows.map((row) => ({
action: row.action,
@@ -62,7 +66,7 @@ async function autocompleteSourceForCKEditor(queryText: string, allowCreatingNot
}
export interface NoteSuggestionOptions {
- /** Adds the two note-creation rows ahead of the notes, for a non-blank term. */
+ /** Adds the two note-creation rows last, after the notes and the search row, for a non-blank term. */
allowCreatingNotes?: boolean;
/** Adds a row that runs a search for a non-blank term, after the notes. */
allowJumpToSearchNotes?: boolean;
@@ -95,10 +99,17 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes, all
});
}
- // Both rows stay above the results: the CKEditor mention feed renders only the first
- // `mention.dropdownLimit` items.
+ if (hasTerm && allowJumpToSearchNotes) {
+ after.push({
+ action: "search-notes",
+ noteTitle: term,
+ highlightedNotePathTitle: t("note_autocomplete.show-in-full-search", { term: escapeHtml(term) })
+ });
+ }
+
+ // Last, so that Up from the first note reaches them first; the search rows have keys of their own.
if (pendingInboxTarget) {
- before.push({
+ after.push({
action: "create-note",
noteTitle: term,
highlightedNotePathTitle: buildCreateNoteTitle(term, await pendingInboxTarget)
@@ -110,14 +121,6 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes, all
});
}
- if (hasTerm && allowJumpToSearchNotes) {
- after.push({
- action: "search-notes",
- noteTitle: term,
- highlightedNotePathTitle: t("note_autocomplete.show-in-full-search", { term: escapeHtml(term) })
- });
- }
-
return [ ...before, ...results, ...after ];
}
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index 605f7bfcc7..3312a45662 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -236,6 +236,11 @@ interface UseAutocompleteOptions<T> {
keepOpenOnPick?: boolean | ((item: T) => boolean);
/** See {@link FormAutocompleteProps.autoActivate}. */
autoActivate?: boolean;
+ /**
+ * The entry `autoActivate` opens the list on when none matches the query, in place of the first
+ * one that can be taken. A negative index falls back to that first one.
+ */
+ fallbackIndex?(items: T[]): number;
/** See {@link FormAutocompleteProps.isHeading}. */
isHeading?(item: T): boolean;
/** The text of an entry, which `autoActivate` matches against the query. Defaults to `String(item)`. */
@@ -256,7 +261,7 @@ interface UseAutocompleteOptions<T> {
* field's events to the `handle*` functions. Entries are fetched while the list is open, debounced
* or paced by `schedule`, and a response to a superseded query is discarded.
*/
-export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled, openOnFocus, openOnEnter, keepOpenOnPick, autoActivate, isHeading, textOf = String, schedule }: UseAutocompleteOptions<T>) {
+export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled, openOnFocus, openOnEnter, keepOpenOnPick, autoActivate, fallbackIndex, isHeading, textOf = String, schedule }: UseAutocompleteOptions<T>) {
const [ isOpen, setIsOpen ] = useState(false);
// What an input method is composing is not yet what the user means, so nothing is looked up for
// it until the composition ends.
@@ -312,7 +317,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
if (latestQuery.current === queryId) {
setItems(suggestions);
scrollToActive.current = true;
- setActiveIndex(autoActivate ? bestMatchIndex(suggestions, query, isHeading, textOf) : -1);
+ setActiveIndex(autoActivate ? bestMatchIndex(suggestions, query, isHeading, textOf, fallbackIndex) : -1);
}
};
@@ -323,7 +328,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
const timeout = setTimeout(lookUp, DEBOUNCE_MS);
return () => clearTimeout(timeout);
- }, [ isOpen, isComposing, query, source, autoActivate, isHeading, textOf, schedule ]);
+ }, [ isOpen, isComposing, query, source, autoActivate, fallbackIndex, isHeading, textOf, schedule ]);
// Keep the highlighted entry in sight: it can be picked out on opening, or arrowed past the
// bottom of a list taller than the room the dropdown was given.
@@ -436,17 +441,19 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,
}
/**
- * Which entry a list opens on: the one the field's text names, or the first that can be taken, so
- * that a field whose text stands for a choice already made opens on it and one being typed into
- * opens on its best candidate. Matched the way the sources filter — ignoring case and surrounding
- * space.
+ * Which entry a list opens on: the one the field's text names, or else the one `fallbackIndex` picks or
+ * the first that can be taken, so that a field whose text stands for a choice already made opens on it
+ * and one being typed into opens on its best candidate. Matched the way the sources filter — ignoring
+ * case and surrounding space.
*/
-function bestMatchIndex<T>(items: T[], text: string, isHeading: ((item: T) => boolean) | undefined, textOf: (item: T) => string) {
+function bestMatchIndex<T>(items: T[], text: string, isHeading: ((item: T) => boolean) | undefined, textOf: (item: T) => string, fallbackIndex?: (items: T[]) => number) {
const canBeTaken = (item: T) => !isHeading?.(item);
const trimmed = text.trim().toLowerCase();
const exact = items.findIndex((item) => canBeTaken(item) && textOf(item).toLowerCase() === trimmed);
- return exact >= 0 ? exact : items.findIndex(canBeTaken);
+ if (exact >= 0) return exact;
+ const fallback = fallbackIndex?.(items) ?? -1;
+ return fallback >= 0 ? fallback : items.findIndex(canBeTaken);
}
/**
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index f3c45fcafa..db569b30db 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -654,6 +654,33 @@ describe("NoteAutocomplete's suggestion list", () => {
});
});
+ it("opens on the first note, with the creation rows last and a line of their own", async () => {
+ getNoteSuggestions.mockResolvedValue([ ...notes, searchRow, createRow ]);
+ const input = await mount();
+ await type(input, "al");
+
+ expect(rows()[0].classList.contains("tn-menu-active")).toBe(true);
+ const dividers = [ ...document.querySelectorAll(".note-autocomplete-menu .dropdown-divider") ];
+ expect(dividers).toHaveLength(2);
+ expect(dividers[0].nextElementSibling).toBe(fullTextRow());
+ expect(dividers[1].previousElementSibling?.querySelector(".bx-file-find")).not.toBeNull();
+ expect(dividers[1].nextElementSibling?.querySelector(".bx-plus")).not.toBeNull();
+
+ // Up from the first note wraps to the creation row, the search rows having keys of their own.
+ await press(input, "ArrowUp");
+ expect(allRows().at(-1)?.querySelector(".bx-plus")).not.toBeNull();
+ expect(allRows().at(-1)?.classList.contains("tn-menu-active")).toBe(true);
+ });
+
+ it("opens on creating the note when no note matches, past the search rows ahead of it", async () => {
+ getNoteSuggestions.mockResolvedValue([ searchRow, createRow ]);
+ const input = await mount();
+ await type(input, "New");
+
+ const active = allRows().find((row) => row.classList.contains("tn-menu-active"));
+ expect(active?.querySelector(".bx-plus")).not.toBeNull();
+ });
+
it("sets both search rows apart from the notes with one line", async () => {
getNoteSuggestions.mockResolvedValue([ ...notes, searchRow ]);
const input = await mount();
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 4ac223b993..db25cd18fa 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -4,7 +4,7 @@ import "./NoteAutocomplete.css";
import { NOTE_TYPE_ICONS } from "@triliumnext/commons";
import clsx from "clsx";
import { type RefObject, render } from "preact";
-import { createPortal, type CSSProperties, Fragment } from "preact/compat";
+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";
@@ -141,6 +141,7 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
disabled: readOnly,
autoActivate: true,
textOf: suggestionText,
+ fallbackIndex: createWhenNoNote,
// The row runs the search again over the notes' content, into the same list.
keepOpenOnPick: (suggestion) => suggestion.action === "full-text-search",
schedule
@@ -363,21 +364,20 @@ function NoteSuggestionList({ autocomplete, searchingFor }: {
<NoteSuggestion suggestion={{ noteTitle: searchingFor, highlightedNotePathTitle: t("quick-search.searching") }} />
</div>
)}
- {searchingFor === undefined && autocomplete.items.map((suggestion, index) => (
- <Fragment key={`${suggestion.action ?? ""}:${suggestion.notePath ?? suggestion.commandId ?? index}`}>
- {startsSearchRows(autocomplete.items, index) && <div className="note-suggestion-separator" role="separator" />}
- <div
- id={autocomplete.itemId(index)}
- className={clsx("aa-suggestion", index === autocomplete.activeIndex && "aa-cursor")}
- role="option"
- aria-selected={index === autocomplete.activeIndex}
- onMouseMove={(e) => autocomplete.hover(index, e)}
- onClick={() => autocomplete.pick(suggestion)}
- >
- <NoteSuggestion suggestion={suggestion} />
- </div>
- </Fragment>
- ))}
+ {searchingFor === undefined && autocomplete.items.map((suggestion, index) => [
+ startsGroup(autocomplete.items, index) && <div key={`separator-${index}`} className="note-suggestion-separator" role="separator" />,
+ <div
+ key={suggestionKey(suggestion, index)}
+ id={autocomplete.itemId(index)}
+ className={clsx("aa-suggestion", index === autocomplete.activeIndex && "aa-cursor")}
+ role="option"
+ aria-selected={index === autocomplete.activeIndex}
+ onMouseMove={(e) => autocomplete.hover(index, e)}
+ onClick={() => autocomplete.pick(suggestion)}
+ >
+ <NoteSuggestion suggestion={suggestion} />
+ </div>
+ ])}
</span>
</div>
</span>
@@ -405,21 +405,20 @@ function NoteSuggestionMenu({ autocomplete, searchingFor }: {
<NoteSuggestionMenuItem suggestion={{ noteTitle: searchingFor, highlightedNotePathTitle: t("quick-search.searching") }} />
</li>
)}
- {searchingFor === undefined && autocomplete.items.map((suggestion, index) => (
- <Fragment key={`${suggestion.action ?? ""}:${suggestion.notePath ?? suggestion.commandId ?? index}`}>
- {startsSearchRows(autocomplete.items, index) && <FormDropdownDivider />}
- <li
- id={autocomplete.itemId(index)}
- className={clsx("dropdown-item", index === autocomplete.activeIndex && "tn-menu-active")}
- role="option"
- aria-selected={index === autocomplete.activeIndex}
- onMouseMove={(e) => autocomplete.hover(index, e)}
- onClick={() => autocomplete.pick(suggestion)}
- >
- <NoteSuggestionMenuItem suggestion={suggestion} />
- </li>
- </Fragment>
- ))}
+ {searchingFor === undefined && autocomplete.items.map((suggestion, index) => [
+ startsGroup(autocomplete.items, index) && <FormDropdownDivider key={`divider-${index}`} />,
+ <li
+ key={suggestionKey(suggestion, index)}
+ id={autocomplete.itemId(index)}
+ className={clsx("dropdown-item", index === autocomplete.activeIndex && "tn-menu-active")}
+ role="option"
+ aria-selected={index === autocomplete.activeIndex}
+ onMouseMove={(e) => autocomplete.hover(index, e)}
+ onClick={() => autocomplete.pick(suggestion)}
+ >
+ <NoteSuggestionMenuItem suggestion={suggestion} />
+ </li>
+ ])}
</menu>
);
}
@@ -491,13 +490,40 @@ function NoteSuggestion({ suggestion }: { suggestion: Suggestion }) {
);
}
-/** Whether a line goes above the row at `index`: the first of the rows searching for the query, after a note. */
-function startsSearchRows(items: Suggestion[], index: number) {
- return index > 0 && isSearchRow(items[index]) && !isSearchRow(items[index - 1]);
+/**
+ * Which group of the list a row belongs to: the notes (with an external link or a command), the
+ * rows searching further for the query, or the rows creating a note from it.
+ */
+function rowGroup(suggestion: Suggestion) {
+ switch (suggestion.action) {
+ case "full-text-search":
+ case "search-notes":
+ return "search";
+ case "create-note":
+ case "create-child-note":
+ return "create";
+ default:
+ return "note";
+ }
+}
+
+/**
+ * With no note to open, the list opens on creating one rather than on the search rows ahead of it, so
+ * Enter still makes the note a title names. Negative, for the first row, while there are notes.
+ */
+function createWhenNoNote(items: Suggestion[]) {
+ return items.some((suggestion) => rowGroup(suggestion) === "note")
+ ? -1
+ : items.findIndex((suggestion) => suggestion.action === "create-note");
+}
+
+/** Whether a line goes above the row at `index`: the first of a group, after the rows of another. */
+function startsGroup(items: Suggestion[], index: number) {
+ return index > 0 && rowGroup(items[index]) !== rowGroup(items[index - 1]);
}
-function isSearchRow(suggestion: Suggestion) {
- return suggestion.action === "full-text-search" || suggestion.action === "search-notes";
+function suggestionKey(suggestion: Suggestion, index: number) {
+ return `${suggestion.action ?? ""}:${suggestion.notePath ?? suggestion.commandId ?? index}`;
}
function suggestionIcon(suggestion: Suggestion) {
@@ -545,8 +571,9 @@ function withFullTextSearchRow(rows: Suggestion[], query: string): Suggestion[]
noteTitle: query,
highlightedNotePathTitle: t("note_autocomplete.include-note-contents", { term: escapeHtml(query) })
};
- const last = rows.at(-1);
- return last?.action === "search-notes" ? [ ...rows.slice(0, -1), row, last ] : [ ...rows, row ];
+ // Right after the notes: ahead of the row opening the full search and of the creation rows.
+ const at = rows.findIndex((suggestion) => rowGroup(suggestion) !== "note");
+ return at < 0 ? [ ...rows, row ] : [ ...rows.slice(0, at), row, ...rows.slice(at) ];
}
/**
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.html
index e832af9a64..f303f15b5b 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.html
@@ -48,6 +48,10 @@
run it without selecting it.</li>
</ul>
</li>
+ <li>The options are listed after the notes: first those that search further,
+ then those that create a note. <kbd>Enter</kbd> opens the note that matches
+ best, or creates the note when none matches. Otherwise, press <kbd>↑</kbd> from
+ the first note to reach the options to create a note.</li>
</ul>
<h2>Recent notes</h2>
<p>Jump to note also has the ability to show the list of recently viewed
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.md
index 275ca33e7c..b44dd0e84b 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Jump to & command palette.md
@@ -22,6 +22,7 @@ In addition to searching for notes, it is also possible to search for commands.
* When the title search does not find a note, the two options at the end of the list search further:
* _Include note contents in the results_ searches the content of the notes as well as their titles, and lists what it finds in place of the current results, without leaving the dialog. Press <kbd>Shift</kbd>+<kbd>Enter</kbd> to run it without selecting it.
* _Show all results in full search_ opens the query in the full <a class="reference-link" href="Search.md">Search</a>, in a new tab, where its options can refine it. Press <kbd>Ctrl</kbd>+<kbd>Enter</kbd> to run it without selecting it.
+* The options are listed after the notes: first those that search further, then those that create a note. <kbd>Enter</kbd> opens the note that matches best, or creates the note when none matches. Otherwise, press <kbd>↑</kbd> from the first note to reach the options to create a note.
## Recent notes