Skip to content

Build your personal knowledge base with Trilium Notes

feat(search): draw the search field's completions with the app's own lists

Elian Doran3bc1841e1b56
diff --git a/apps/client/src/stylesheets/style.css b/apps/client/src/stylesheets/style.css
index 34f57e4a4a..abcfd1d791 100644
--- a/apps/client/src/stylesheets/style.css
+++ b/apps/client/src/stylesheets/style.css
@@ -639,7 +639,7 @@ body.mobile .dropdown-menu .dropdown-submenu {
/* Firefox draws the caret against the spacer CodeMirror puts before the placeholder widget,
short (https://bugzilla.mozilla.org/show_bug.cgi?id=904846). The spacer must stay in layout:
CodeMirror measures a position next to a widget from its rect, and a hidden one reads as
- zeros, which hides the completion popup as off-screen. */
+ zeros, which places a completion list at the caret off-screen. */
@supports (-moz-appearance: none) {
.cm-editor .cm-widgetBuffer:has(+ .cm-placeholder) {
vertical-align: baseline;
diff --git a/apps/client/src/widgets/quick_search.spec.tsx b/apps/client/src/widgets/quick_search.spec.tsx
index 5857c92666..4ff011dfad 100644
--- a/apps/client/src/widgets/quick_search.spec.tsx
+++ b/apps/client/src/widgets/quick_search.spec.tsx
@@ -1,4 +1,3 @@
-import { type CompletionContext, completionStatus, startCompletion } from "@codemirror/autocomplete";
import type { EditorView } from "@codemirror/view";
import type { QuickSearchResponse } from "@triliumnext/commons";
import { options, type VNode } from "preact";
@@ -12,11 +11,12 @@ import server from "../services/server";
import { renderInto } from "../test/render";
import QuickSearch from "./quick_search";
import { ParentComponent } from "./react/react_utils";
+import type { SearchCompletion, SearchEntry } from "./ribbon/search_completions";
// The completions fetch attribute names and values through the server, so a spec that opens them
-// supplies its own source.
+// supplies its own.
const completions = vi.hoisted(() => ({
- source: null as ((context: CompletionContext) => unknown) | null
+ at: null as ((before: string, explicit: boolean) => SearchCompletion | null) | null
}));
// Echoes the key and its interpolation, so a spec can tell which message a row shows.
vi.mock("../services/i18n", async (importOriginal) => ({
@@ -25,15 +25,14 @@ vi.mock("../services/i18n", async (importOriginal) => ({
}));
vi.mock("./ribbon/search_completions", () => ({
- searchCompletionSource: (context: CompletionContext) => completions.source?.(context) ?? null,
- searchCompletionIcon: () => undefined,
- searchCompletionReactivates: () => false
+ searchCompletionAt: (before: string, explicit: boolean) => completions.at?.(before, explicit) ?? null,
+ filterSearchEntries: (entries: SearchEntry[]) => entries
}));
describe("QuickSearch", () => {
afterEach(() => {
vi.restoreAllMocks();
- completions.source = null;
+ completions.at = null;
});
it("renders the search field, focuses it on the quickSearch shortcut and marks a typed query", async () => {
@@ -313,7 +312,10 @@ describe("QuickSearch", () => {
it("drops an open completion list on Escape before the results", async () => {
vi.spyOn(server, "get").mockResolvedValue(response(3, []));
- completions.source = () => ({ from: 0, options: [ { label: "and" }, { label: "asc" } ] });
+ completions.at = (before, explicit) => (explicit ? {
+ kind: "entries", key: "keywords", from: before.length, query: "", preselect: true,
+ entries: () => [ { id: "and", title: "and", insert: "and" }, { id: "asc", title: "asc", insert: "asc" } ]
+ } : null);
const { editor } = await mount();
typeQuery(editor, "a");
@@ -321,13 +323,14 @@ describe("QuickSearch", () => {
await waitForResults(3);
editor.focus();
- startCompletion(editor);
- await vi.waitFor(() => expect(completionStatus(editor.state)).toBe("active"));
- // The list drops the keys pressed within its `interactionDelay` of opening.
- await new Promise((resolve) => setTimeout(resolve, 100));
+ act(() => {
+ editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key: " ", ctrlKey: true, bubbles: true, cancelable: true }));
+ });
+ const completionList = () => document.querySelector(".note-autocomplete-menu:not(.quick-search-menu)");
+ await vi.waitFor(() => expect(completionList()).not.toBeNull());
pressKey(editor.contentDOM, "Escape");
- expect(completionStatus(editor.state)).toBe(null);
+ await vi.waitFor(() => expect(completionList()).toBeNull());
expect(menu()).not.toBeNull();
pressKey(editor.contentDOM, "Escape");
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index f5edd17e01..7f0c185903 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -182,17 +182,18 @@ export interface AutocompleteListHandle {
handleKeyDown(e: KeyboardEvent): boolean;
}
+/** The least width of an {@link AutocompleteList}, whose anchor at a caret has none. */
+const CARET_LIST_MIN_WIDTH = 220;
+
/**
* The dropdown of a {@link FormAutocomplete} for a query typed somewhere else, such as after a `#` in
* a text editor, which keeps the focus and forwards its keys through `handleRef`. It opens with
* nothing highlighted, so Enter stays with the host until an entry is arrowed to.
*/
-export function AutocompleteList({ query, source, anchor, minWidth, renderItem, onPick, handleRef, elementRef }: {
+export function AutocompleteList({ query, source, anchor, renderItem, onPick, handleRef, elementRef }: {
query: string;
source(query: string): Promise<string[]>;
anchor: DropdownAnchor;
- /** See {@link FormAutocompleteProps.dropdownMinWidth}. */
- minWidth?: number;
renderItem?(item: string): ComponentChildren;
onPick(item: string): void;
handleRef: MutableRef<AutocompleteListHandle | null>;
@@ -210,7 +211,7 @@ export function AutocompleteList({ query, source, anchor, minWidth, renderItem,
<AutocompleteDropdown
autocomplete={autocomplete}
anchor={anchor}
- minWidth={minWidth}
+ minWidth={CARET_LIST_MIN_WIDTH}
renderItem={renderItem}
elementRef={elementRef}
/>
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.css
index f7e5e7161f..6acccaa6f0 100644
--- a/apps/client/src/widgets/react/Menu.css
+++ b/apps/client/src/widgets/react/Menu.css
@@ -71,10 +71,9 @@ body.desktop .dropdown-item.dropdown-submenu.submenu-open,
* mark a second row until the pointer moves. The row looks unhovered meanwhile, as in the resting
* `.dropdown-item` rule. `!important` and the extra classes outrank the theme's `:hover` rule in
* style.css, whose values these undo. A popup whose rows take focus themselves, such as the quick
- * search's results, sets the class too; its focused row is the keys' row. So does a search field's
- * completion popup, whose keys' row CodeMirror marks with `aria-selected`.
+ * search's results, sets the class too; its focused row is the keys' row.
*/
-.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, [aria-selected="true"], .submenu-open, :focus) {
+.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, .submenu-open, :focus) {
color: var(--menu-text-color) !important;
background-color: transparent !important;
border-color: transparent !important;
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index f109d6847f..b33eefaa10 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -22,7 +22,7 @@ import { collectShortcutHints } from "../../services/shortcut_hints";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
import type { AutocompleteListHandle } from "./FormAutocomplete";
-import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList, renderNoteSuggestion } from "./NoteAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList } from "./NoteAutocomplete";
import { ParentComponent } from "./react_utils";
async function render(props: NoteAutocompleteProps = {}) {
@@ -276,20 +276,6 @@ describe("NoteAutocomplete's suggestion list", () => {
expect(input.getAttribute("aria-activedescendant")).toBe(alpha.id);
});
- it("renders a row's content for a list it does not hold, as its own rows hold it", async () => {
- const input = await mount();
- await type(input, "al");
- const beta = rows()[1];
- const content = beta.querySelector(":scope > span");
-
- // Class-less, as the menu's `.dropdown-item > span:not([class])` lays out.
- const rendered = renderNoteSuggestion(notes[1]);
- expect(rendered.tagName).toBe("SPAN");
- expect(rendered.hasAttribute("class")).toBe(false);
- expect(content).not.toBe(null);
- expect(rendered.innerHTML).toBe(content?.innerHTML);
- });
-
it("gives each kind of row its icon, and never shows a content snippet", async () => {
getNoteSuggestions.mockResolvedValue([
{ action: "search-notes", highlightedNotePathTitle: "S" },
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 35868ca4f7..5c5e8ff8b8 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -1,9 +1,10 @@
import "./Menu.css";
import "./NoteAutocomplete.css";
+import type { ReferenceElement } from "@floating-ui/dom";
import { NOTE_TYPE_ICONS } from "@triliumnext/commons";
import clsx from "clsx";
-import { type ComponentChildren, type RefObject, render } from "preact";
+import { type ComponentChildren, type RefObject, render, type VNode } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
@@ -502,22 +503,24 @@ export interface CommandEntry {
/**
* Lists commands for a query typed somewhere else, such as after a `/` in a text editor, as the
* command palette lists its own after a `>`. The host keeps the focus and forwards its keys through
- * `handleRef`. It opens on the best match, so Enter takes it.
+ * `handleRef`. It opens on the best match, so Enter takes it, unless `preselect` is off.
*/
-export function CommandMentionList<T extends CommandEntry>({ query, source, anchor, className, onPick, handleRef, elementRef }: {
+export function CommandMentionList<T extends CommandEntry>({ query, source, anchor, className, preselect = true, onPick, handleRef, elementRef }: {
query: string;
/** The entries for a query, looked up as soon as it changes, with no debounce. */
source(query: string): Promise<T[]>;
anchor: PopupProps["anchor"];
/** A class for the popup, beside its own. */
className?: string;
+ /** Opens the list with the best match highlighted, so that Enter takes it. */
+ preselect?: boolean;
onPick(entry: T): void;
handleRef: MutableRef<AutocompleteListHandle | null>;
elementRef?: PopupProps["elementRef"];
}) {
// The focus stays where the query is typed, so there is no field to return it to.
const inputRef = useRef<HTMLInputElement>(null);
- const autocomplete = useAutocomplete({ query, source, onPick, inputRef, autoActivate: true, textOf: commandTitle, schedule: lookUpNow });
+ const autocomplete = useAutocomplete({ query, source, onPick, inputRef, autoActivate: preselect, textOf: commandTitle, schedule: lookUpNow });
// The host shows the list by mounting it and closes it by unmounting it.
useEffect(() => autocomplete.open(), []);
@@ -548,6 +551,47 @@ export function CommandMentionList<T extends CommandEntry>({ query, source, anch
);
}
+/** What a list drawn by {@link createHostedList} is given to draw itself with. */
+export interface HostedListProps {
+ /** At the caret, placed again each time the query changes. */
+ anchor: ReferenceElement;
+ handleRef: MutableRef<AutocompleteListHandle | null>;
+ elementRef(element: HTMLElement | null): void;
+}
+
+/**
+ * A list an editor hosts for the query typed after a marker, such as for CKEditor's
+ * `mention.hostedFeeds` or CodeMirror's `hostedMention()`. It renders what `draw` returns for each
+ * query, at the caret, and forwards the editor's keys to it.
+ */
+export function createHostedList<S extends { caretRect(): DOMRect; editable: HTMLElement | null }>(
+ draw: (state: S, list: HostedListProps) => VNode
+) {
+ const container = document.createElement("div");
+ const handleRef: { current: AutocompleteListHandle | null } = { current: null };
+ let element: HTMLElement | null = null;
+ const elementRef = (el: HTMLElement | null) => { element = el; };
+ const unmount = () => {
+ render(null, container);
+ element = null;
+ };
+
+ return {
+ show(state: S) {
+ // A new anchor each time, so the list is placed again at the caret. Its `contextElement`
+ // places it again as the containers around the editor scroll.
+ const anchor = { getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined };
+ render(draw(state, { anchor, handleRef, elementRef }), container);
+ },
+ hide: unmount,
+ handleKeyDown: (e: KeyboardEvent) => handleRef.current?.handleKeyDown(e) ?? false,
+ get element() {
+ return element;
+ },
+ destroy: unmount
+ };
+}
+
function CommandIcon({ entry }: { entry: CommandEntry }) {
if (entry.iconSvg) {
return <RawHtml className="tn-icon note-suggestion-svg-icon" html={entry.iconSvg} />;
@@ -722,17 +766,6 @@ function SuggestionRowContent({ icon, header, details, trailing }: {
</>;
}
-/**
- * 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;
-}
-
/**
* 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.
diff --git a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx
index 0907d23e70..d031459b23 100644
--- a/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx
+++ b/apps/client/src/widgets/ribbon/SearchStringEditor.spec.tsx
@@ -8,11 +8,10 @@ import { renderInto } from "../../test/render";
import { ParentComponent } from "../react/react_utils";
import SearchStringEditor from "./SearchStringEditor";
-// The completions fetch attribute names and values through the server; nothing here opens the popup.
+// The completions fetch attribute names and values through the server; nothing here opens their list.
vi.mock("./search_completions", () => ({
- searchCompletionSource: () => null,
- searchCompletionIcon: () => undefined,
- searchCompletionReactivates: () => false
+ searchCompletionAt: () => null,
+ filterSearchEntries: () => []
}));
describe("SearchStringEditor", () => {
diff --git a/apps/client/src/widgets/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.ts
index 6388b633d0..0538178498 100644
--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts
@@ -1,451 +1,296 @@
-import type { CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/field_editor";
import { beforeEach, describe, expect, it, vi } from "vitest";
import server from "../../services/server";
-import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";
-import { searchCompletionIcon, searchCompletionNote, searchCompletionReactivates, searchCompletionSource } from "./search_completions";
+import { filterSearchEntries, type SearchCompletion, searchCompletionAt, type SearchEntry } from "./search_completions";
// The descriptions are catalogue lookups, which specs don't initialize; the keys identify them.
vi.mock("../../services/i18n", () => ({ t: (key: string) => key }));
-// Stubbed at the same seam the sidebar's picker fetches through, so the spec needs no server and
-// none of the attribute popup behind it. `isBuiltinAttribute` is left real: what it marks is the
-// point of these tests.
-vi.mock("../attribute_widgets/attribute_detail", () => ({ fetchAttributeNames: vi.fn() }));
-// Modules loaded behind `services/attributes` request through this one as they load, so the stub
-// answers from the start rather than from the first `beforeEach`.
+// Modules loaded behind this one request through the server as they load, so the stub answers from
+// the start rather than from the first `beforeEach`.
vi.mock("../../services/server", () => ({ default: { get: vi.fn(async () => []) } }));
beforeEach(() => {
- vi.mocked(fetchAttributeNames).mockReset().mockResolvedValue([ "book", "archived" ]);
vi.mocked(server.get).mockReset().mockResolvedValue([ "fiction", "science fiction" ]);
});
-describe("searchCompletionSource", () => {
+const KEYWORDS = [ "#", "#!", "~", "~!", "note", "and", "or", "not", "orderBy", "limit" ];
+
+describe("searchCompletionAt", () => {
it("offers the note object and the keywords for a word only when asked, anchored at its start", async () => {
// A plain word is most often a search term, so typing one opens nothing.
- expect(await complete("#book AND no")).toBeNull();
+ expect(complete("#book AND no")).toBeNull();
- const result = await complete("#book AND no", { explicit: true });
+ const result = complete("#book AND no", { explicit: true });
- expect(result?.from).toBe(10);
- expect(labelsOf(result)).toEqual([ "#", "#!", "~", "~!", "note", "and", "or", "not", "orderBy", "limit" ]);
- // Both complete with what has to follow them.
- expect(optionFor(result, "note")?.apply).toBe("note.");
- expect(optionFor(result, "not")?.apply).toBe("not(");
- expect(optionFor(result, "note")?.detail).toBe("search_completion.note");
+ expect(result).toMatchObject({ kind: "entries", from: 10, query: "no", preselect: true });
+ expect(await titlesOf(result)).toEqual(KEYWORDS);
+ // Both complete with what has to follow them, which the list then opens on.
+ expect((await entryFor(result, "note"))?.insert).toBe("note.");
+ expect((await entryFor(result, "not"))?.insert).toBe("not(");
+ expect((await entryFor(result, "note"))?.description).toBe("search_completion.note");
});
it("offers the sort directions only once an orderBy is open", async () => {
- expect(labelsOf(await complete("#book de", { explicit: true }))).not.toContain("desc");
+ expect(await titlesOf(complete("#book de", { explicit: true }))).not.toContain("desc");
- const ordering = await complete("#book orderBy #year de", { explicit: true });
+ const ordering = complete("#book orderBy #year de", { explicit: true });
- expect(labelsOf(ordering)).toContain("desc");
- expect(optionFor(ordering, "asc")?.detail).toBe("order_by.asc");
+ expect(await titlesOf(ordering)).toContain("desc");
+ expect((await entryFor(ordering, "asc"))?.description).toBe("order_by.asc");
});
it("narrows an orderBy to what can follow the key being written", async () => {
// A key is a property path or an attribute name, which the branches above answer for.
- expect(labelsOf(await complete("#book orderBy n", { explicit: true }))).toEqual([ "#", "~", "note" ]);
- expect(labelsOf(await complete("#book orderBy ", { explicit: true }))).toEqual([ "#", "~", "note" ]);
+ expect(await titlesOf(complete("#book orderBy n", { explicit: true }))).toEqual([ "#", "~", "note" ]);
+ expect(await titlesOf(complete("#book orderBy ", { explicit: true }))).toEqual([ "#", "~", "note" ]);
// Once a key stands there it can be sorted, followed by another, or cut short.
- expect(labelsOf(await complete("#book orderBy note.title d", { explicit: true })))
+ expect(await titlesOf(complete("#book orderBy note.title d", { explicit: true })))
.toEqual([ "asc", "desc", "limit" ]);
- expect(labelsOf(await complete("#book orderBy note.title desc, note.dateCreated a", { explicit: true })))
+ expect(await titlesOf(complete("#book orderBy note.title desc, note.dateCreated a", { explicit: true })))
.toEqual([ "asc", "desc", "limit" ]);
// A comma opens the next key, which has no direction of its own yet.
- expect(labelsOf(await complete("#book orderBy note.title, n", { explicit: true }))).toEqual([ "#", "~", "note" ]);
+ expect(await titlesOf(complete("#book orderBy note.title, n", { explicit: true }))).toEqual([ "#", "~", "note" ]);
// An ordering names a key and sorts on it; nothing in it is compared.
- expect(await complete("#book orderBy note.title =")).toBeNull();
+ expect(complete("#book orderBy note.title =")).toBeNull();
// Outside an ordering the keywords are untouched.
- expect(labelsOf(await complete("#book n", { explicit: true })))
- .toEqual([ "#", "#!", "~", "~!", "note", "and", "or", "not", "orderBy", "limit" ]);
+ expect(await titlesOf(complete("#book n", { explicit: true }))).toEqual(KEYWORDS);
});
- it("offers every operator once one of their characters is typed", async () => {
- const result = await complete("#year >");
+ it("offers every operator once one of their characters is typed, with nothing highlighted", async () => {
+ const result = complete("#year >");
- expect(result?.from).toBe(6);
- expect(labelsOf(result)).toEqual([
+ expect(result).toMatchObject({ kind: "entries", from: 6, query: ">", preselect: false });
+ expect(await titlesOf(result)).toEqual([
"=", "!=", "*=*", "=*", "*=", ">", ">=", "<", "<=", "%=", "~=", "~*"
]);
- expect(result?.options.every((option) => option.detail)).toBe(true);
+ expect((await entriesOf(result)).every((entry) => entry.description)).toBe(true);
});
it("offers only the operators the operand accepts", async () => {
// `note.text` is matched, never ordered or compared exactly.
- expect(labelsOf(await complete("note.text >"))).toEqual([ "*=*" ]);
- expect(labelsOf(await complete("~author.text ="))).toEqual([ "*=*" ]);
+ expect(await titlesOf(complete("note.text >"))).toEqual([ "*=*" ]);
+ expect(await titlesOf(complete("~author.text ="))).toEqual([ "*=*" ]);
// Content is matched too, but with every matching operator.
- const content = labelsOf(await complete("note.content ="));
+ const content = await titlesOf(complete("note.content ="));
expect(content).toContain("%=");
expect(content).not.toContain(">=");
- expect(labelsOf(await complete("note.rawContent ="))).toEqual(content);
+ expect(await titlesOf(complete("note.rawContent ="))).toEqual(content);
// A relation is compared only through a property of the note it names.
- expect(await complete("~author =")).toBeNull();
- expect(await complete("note.relations.author >")).toBeNull();
+ expect(complete("~author =")).toBeNull();
+ expect(complete("note.relations.author >")).toBeNull();
// An explicit request past one is left with the keywords alone.
- expect(labelsOf(await complete("~author ", { explicit: true })))
- .toEqual([ "#", "#!", "~", "~!", "note", "and", "or", "not", "orderBy", "limit" ]);
+ expect(await titlesOf(complete("~author ", { explicit: true }))).toEqual(KEYWORDS);
// The last segment decides, and a name the user chose after `labels.` restricts nothing.
- expect(labelsOf(await complete("note.parents.title >"))).toContain(">");
- expect(labelsOf(await complete("note.labels.text ="))).toContain("=");
+ expect(await titlesOf(complete("note.parents.title >"))).toContain(">");
+ expect(await titlesOf(complete("note.labels.text ="))).toContain("=");
});
it("offers path segments after a dot, anchored at the segment being typed", async () => {
- const root = await complete("note.");
+ const root = complete("note.");
- expect(root?.from).toBe(5);
- expect(labelsOf(root)).toContain("title");
- expect(labelsOf(root)).toContain("parents");
- expect(labelsOf(root)).toContain("content");
+ expect(root).toMatchObject({ kind: "entries", from: 5, query: "" });
+ expect(await titlesOf(root)).toContain("title");
+ expect(await titlesOf(root)).toContain("parents");
+ expect(await titlesOf(root)).toContain("content");
- const partial = await complete("#book AND note.date");
+ const partial = complete("#book AND note.date");
- expect(partial?.from).toBe(15);
- expect(labelsOf(partial)).toEqual(labelsOf(root));
+ expect(partial).toMatchObject({ from: 15, query: "date" });
+ expect(await titlesOf(partial)).toEqual(await titlesOf(root));
});
it("walks a path through a relation and through a traversal", async () => {
- expect(labelsOf(await complete("~author."))).toContain("title");
- expect(labelsOf(await complete("note.parents."))).toContain("title");
- expect(labelsOf(await complete("~author.relations.son."))).toContain("title");
+ expect(await titlesOf(complete("~author."))).toContain("title");
+ expect(await titlesOf(complete("note.parents."))).toContain("title");
+ expect(await titlesOf(complete("~author.relations.son."))).toContain("title");
});
- it("stops where a terminal property ends the path", async () => {
- expect(await complete("note.title.")).toBeNull();
- expect(await complete("note.labels.publicationYear.")).toBeNull();
+ it("stops where a terminal property ends the path", () => {
+ expect(complete("note.title.")).toBeNull();
+ expect(complete("note.labels.publicationYear.")).toBeNull();
});
- it("stays quiet on empty space, and offers everything when asked explicitly", async () => {
- expect(await complete("#book ")).toBeNull();
+ it("stays quiet on empty space, and offers everything when asked explicitly, the markers first", async () => {
+ expect(complete("#book ")).toBeNull();
- const explicit = await complete("#book ", { explicit: true });
+ const explicit = complete("#book ", { explicit: true });
- expect(explicit?.from).toBe(6);
+ expect(explicit).toMatchObject({ from: 6, query: "" });
// The words and the four attribute markers, then every operator.
- expect(explicit?.options).toHaveLength(22);
- // CodeMirror sorts by score and ignores the order offered, so the markers are boosted
- // to the top rather than merely listed first.
- // Each negated marker sits directly under the one it negates.
- expect(optionFor(explicit, "#")?.boost).toBe(99);
- expect(optionFor(explicit, "#!")?.boost).toBe(98);
- expect(optionFor(explicit, "~")?.boost).toBe(97);
- expect(optionFor(explicit, "~!")?.boost).toBe(96);
-
- // Everything that leaves a clause unfinished reopens the popup on what follows it.
- const reopening = explicit?.options.filter(searchCompletionReactivates).map((o) => o.label);
- expect(reopening).toEqual([ "#", "#!", "~", "~!", "note", "not" ]);
+ const titles = await titlesOf(explicit);
+ expect(titles).toHaveLength(22);
+ expect(titles.slice(0, 4)).toEqual([ "#", "#!", "~", "~!" ]);
});
describe("attribute names", () => {
- it("fetches labels for #, anchored past the prefix and past a negation", async () => {
- const result = await complete("towers #bo");
-
- expect(fetchAttributeNames).toHaveBeenCalledWith("label", "");
- expect(result?.from).toBe(8);
- expect(labelsOf(result)).toEqual([ "book", "archived" ]);
-
- expect((await complete("#!bo"))?.from).toBe(2);
- // What the negated marker inserts on its own, which reopens the popup on the name.
- expect(labelsOf(await complete("#!"))).toEqual([ "book", "archived" ]);
- expect(labelsOf(await complete("~!"))).toEqual([ "book", "archived" ]);
+ it("offers labels for #, anchored past the prefix and past a negation", () => {
+ expect(complete("towers #bo")).toMatchObject({ kind: "attributes", type: "label", from: 8, query: "bo" });
+ expect(complete("#!bo")).toMatchObject({ kind: "attributes", type: "label", from: 2, query: "bo" });
+ // What the markers insert on their own, which opens the list on the name.
+ expect(complete("#!")).toMatchObject({ kind: "attributes", type: "label", query: "" });
+ expect(complete("~!")).toMatchObject({ kind: "attributes", type: "relation", query: "" });
});
- it("ranks a built-in below a name of the user's own that matches as well", async () => {
- const result = await complete("#a");
-
- expect(optionFor(result, "archived")?.boost).toBe(-99);
- expect(optionFor(result, "book")?.boost).toBeUndefined();
- });
-
- it("fetches relations for ~, and for the segment after note.relations.", async () => {
- await complete("~aut");
-
- expect(fetchAttributeNames).toHaveBeenCalledWith("relation", "");
-
- const inPath = await complete("note.relations.aut");
-
- expect(fetchAttributeNames).toHaveBeenLastCalledWith("relation", "");
- expect(inPath?.from).toBe(15);
- expect(labelsOf(inPath)).toEqual([ "book", "archived" ]);
- });
-
- it("fetches labels for the segment after note.labels.", async () => {
- const result = await complete("note.labels.");
-
- expect(fetchAttributeNames).toHaveBeenCalledWith("label", "");
- expect(result?.from).toBe(12);
+ it("offers relations for ~, and the names after note.labels. and note.relations.", () => {
+ expect(complete("~aut")).toMatchObject({ kind: "attributes", type: "relation", query: "aut" });
+ expect(complete("note.relations.aut")).toMatchObject({ kind: "attributes", type: "relation", from: 15, query: "aut" });
+ expect(complete("note.labels.")).toMatchObject({ kind: "attributes", type: "label", from: 12, query: "" });
});
it("leaves the fuzzy operators to the operator branch", async () => {
- expect(labelsOf(await complete("note.title ~="))).toContain("~=");
- expect(fetchAttributeNames).not.toHaveBeenCalled();
- });
+ const result = complete("note.title ~=");
- it("offers nothing when the request fails", async () => {
- vi.mocked(fetchAttributeNames).mockRejectedValue(new Error("offline"));
-
- expect(await complete("#bo")).toBeNull();
+ expect(result?.kind).toBe("entries");
+ expect(await titlesOf(result)).toContain("~=");
});
});
describe("attribute values", () => {
it("offers the values a label holds, anchored at the value and quoted where the lexer would split it", async () => {
- const result = await complete("#genre = fic");
+ const result = complete("#genre = fic");
+ expect(result).toMatchObject({ kind: "entries", key: "values:genre", from: 9, query: "fic", preselect: false });
+ expect(await titlesOf(result)).toEqual([ "fiction", "science fiction" ]);
expect(server.get).toHaveBeenCalledWith("attribute-values/genre");
- expect(result?.from).toBe(9);
- expect(labelsOf(result)).toEqual([ "fiction", "science fiction" ]);
- expect(optionFor(result, "fiction")?.apply).toBeUndefined();
- expect(optionFor(result, "science fiction")?.apply).toBe("\"science fiction\"");
+ expect((await entryFor(result, "fiction"))?.insert).toBe("fiction");
+ expect((await entryFor(result, "science fiction"))?.insert).toBe("\"science fiction\"");
});
it("quotes a value spelled like a reserved operand, whatever its case", async () => {
vi.mocked(server.get).mockResolvedValue([ "note", "Today", "monthly" ]);
- const result = await complete("#genre = t");
+ const result = complete("#genre = t");
// Bare, `note` is rejected as a keyword and `today` resolves to a date.
- expect(optionFor(result, "note")?.apply).toBe("\"note\"");
- expect(optionFor(result, "Today")?.apply).toBe("\"Today\"");
- expect(optionFor(result, "monthly")?.apply).toBeUndefined();
+ expect((await entryFor(result, "note"))?.insert).toBe("\"note\"");
+ expect((await entryFor(result, "Today"))?.insert).toBe("\"Today\"");
+ expect((await entryFor(result, "monthly"))?.insert).toBe("monthly");
});
it("closes a quote the user opened rather than adding another", async () => {
- const result = await complete("#genre = \"science f");
+ const result = complete("#genre = \"science f");
- expect(result?.from).toBe(10);
- expect(optionFor(result, "science fiction")?.apply).toBe("science fiction\"");
+ expect(result).toMatchObject({ from: 10, query: "science f" });
+ expect((await entryFor(result, "science fiction"))?.insert).toBe("science fiction\"");
});
- it("leaves the operator being typed to the operator branch", async () => {
- expect(labelsOf(await complete("#genre ="))).toContain("=*");
- expect(server.get).not.toHaveBeenCalled();
+ it("leaves the operator being typed to the operator branch", () => {
+ expect(complete("#genre =")).toMatchObject({ kind: "entries", key: "operators" });
});
it("stops once the value is finished, so the keywords follow it", async () => {
- expect(labelsOf(await complete("#genre = fiction an", { explicit: true }))).toContain("and");
- expect(labelsOf(await complete("#genre = \"science fiction\" an", { explicit: true }))).toContain("and");
- expect(server.get).not.toHaveBeenCalled();
+ expect(await titlesOf(complete("#genre = fiction an", { explicit: true }))).toContain("and");
+ expect(await titlesOf(complete("#genre = \"science fiction\" an", { explicit: true }))).toContain("and");
});
- it("follows a value through note.labels., and leaves relations alone", async () => {
- await complete("note.labels.genre *=* fic");
-
- expect(server.get).toHaveBeenCalledWith("attribute-values/genre");
+ it("follows a value through note.labels., and leaves relations alone", () => {
+ expect(complete("note.labels.genre *=* fic")).toMatchObject({ key: "values:genre" });
// The endpoint collects label values only; a relation's value is a note ID.
- await complete("~author = jo");
-
- expect(server.get).toHaveBeenCalledTimes(1);
- });
-
- it("offers nothing when the request fails", async () => {
- vi.mocked(server.get).mockRejectedValue(new Error("offline"));
-
- expect(await complete("#genre = fic")).toBeNull();
+ expect(complete("~author = jo")).toBeNull();
});
});
describe("property values", () => {
it("offers the values an enumerable property holds, and asks the server for none of them", async () => {
- const types = await complete("note.type = co");
+ const types = complete("note.type = co");
- expect(types?.from).toBe(12);
- expect(labelsOf(types)).toContain("code");
- expect(labelsOf(types)).toContain("contentWidget");
+ expect(types).toMatchObject({ from: 12, query: "co" });
+ expect(await titlesOf(types)).toContain("code");
+ expect(await titlesOf(types)).toContain("contentWidget");
+ expect((await entryFor(types, "code"))?.icon).toBe("bx bx-code");
- expect(labelsOf(await complete("note.isProtected = t"))).toEqual([ "true", "false" ]);
+ expect(await titlesOf(complete("note.isProtected = t"))).toEqual([ "true", "false" ]);
// A space settles the operator, so the values come without typing one; directly after it
// the operator can still be growing into `!=` or `=*`.
- expect(labelsOf(await complete("note.isProtected = "))).toEqual([ "true", "false" ]);
- expect(labelsOf(await complete("note.isProtected ="))).toContain("=*");
- expect(labelsOf(await complete("note.isArchived = t"))).toEqual([ "true", "false" ]);
+ expect(await titlesOf(complete("note.isProtected = "))).toEqual([ "true", "false" ]);
+ expect(await titlesOf(complete("note.isProtected ="))).toContain("=*");
+ expect(await titlesOf(complete("note.isArchived = t"))).toEqual([ "true", "false" ]);
- const mimes = await complete("note.mime = pyt");
+ const mimes = complete("note.mime = pyt");
- expect(optionFor(mimes, "text/x-python")?.detail).toBe("Python");
+ expect((await entryFor(mimes, "text/x-python"))?.description).toBe("Python");
// The lexer splits a bare `text/x-python` at the dash, so the value is inserted quoted.
- expect(optionFor(mimes, "text/x-python")?.apply).toBe("\"text/x-python\"");
+ expect((await entryFor(mimes, "text/x-python"))?.insert).toBe("\"text/x-python\"");
expect(server.get).not.toHaveBeenCalled();
});
it("follows the property through a traversal and a relation, and leaves the rest alone", async () => {
- expect(labelsOf(await complete("note.parents.type = co"))).toContain("code");
- expect(labelsOf(await complete("note.type = code and note.mime = pyt"))).toContain("text/x-python");
- expect(labelsOf(await complete("~author.type = co"))).toContain("code");
+ expect(await titlesOf(complete("note.parents.type = co"))).toContain("code");
+ expect(await titlesOf(complete("note.type = code and note.mime = pyt"))).toContain("text/x-python");
+ expect(await titlesOf(complete("~author.type = co"))).toContain("code");
// A property whose values nothing can enumerate falls through to the keywords, which
// wait to be asked for, and a label that happens to share a property's name is still a
// label.
- expect(await complete("note.title = so")).toBeNull();
- expect(labelsOf(await complete("note.title = so", { explicit: true })))
- .toEqual([ "#", "#!", "~", "~!", "note", "and", "or", "not", "orderBy", "limit" ]);
- expect(labelsOf(await complete("note.labels.type = fic"))).toEqual([ "fiction", "science fiction" ]);
+ expect(complete("note.title = so")).toBeNull();
+ expect(await titlesOf(complete("note.title = so", { explicit: true }))).toEqual(KEYWORDS);
+ expect(complete("note.labels.type = fic")).toMatchObject({ key: "values:type" });
});
it("offers the smart dates after a date property, unquoted so the parser resolves them", async () => {
- const dates = await complete("note.dateCreated >= t");
+ const dates = await entriesOf(complete("note.dateCreated >= t"));
- expect(labelsOf(dates)).toEqual([
+ expect(dates.map((date) => date.title)).toEqual([
"now", "now-60", "today", "today-30", "month", "month-1", "year", "year-1"
]);
// Quoting one would make it the text it spells instead of a date.
- expect(dates?.options.every((option) => option.apply === undefined)).toBe(true);
- expect(dates?.options.every((option) => option.detail)).toBe(true);
+ expect(dates.every((date) => date.insert === date.title && date.description)).toBe(true);
for (const property of [ "dateModified", "utcDateCreated", "utcDateModified" ]) {
- expect(labelsOf(await complete(`note.${property} < `))).toContain("today");
+ expect(await titlesOf(complete(`note.${property} < `))).toContain("today");
}
// A quote the user opened is a date they are spelling out themselves.
- expect(await complete("note.dateCreated >= \"2")).toBeNull();
+ expect(complete("note.dateCreated >= \"2")).toBeNull();
});
});
-});
-
-describe("searchCompletionIcon", () => {
- it("draws attribute names, the system ones with a cog rather than their own kind", async () => {
- vi.mocked(fetchAttributeNames).mockResolvedValue([ "book", "archived" ]);
- const labels = await complete("#a");
-
- expect(iconFor(labels, "book")).toBe("bx bx-hash");
- expect(iconFor(labels, "archived")).toBe("bx bx-cog");
-
- vi.mocked(fetchAttributeNames).mockResolvedValue([ "author", "template", "archived" ]);
- const relations = await complete("~a");
-
- expect(iconFor(relations, "author")).toBe("bx bx-transfer");
- expect(iconFor(relations, "template")).toBe("bx bx-cog");
- // Built-in as a label, an ordinary name as a relation.
- expect(iconFor(relations, "archived")).toBe("bx bx-transfer");
- });
- it("leaves everything else undrawn", async () => {
- expect(iconFor(await complete("no", { explicit: true }), "note")).toBeUndefined();
- expect(iconFor(await complete("or", { explicit: true }), "orderBy")).toBeUndefined();
- expect(iconFor(await complete("note."), "title")).toBeUndefined();
- // The marker is the icon; drawing one beside it reads as noise.
- expect(iconFor(await complete("no", { explicit: true }), "#")).toBeUndefined();
- expect(iconFor(await complete("no", { explicit: true }), "~")).toBeUndefined();
- expect(iconFor(await complete("#year >"), ">=")).toBeUndefined();
- });
-});
-
-function iconFor(result: CompletionResult | null, label: string) {
- const option = optionFor(result, label);
-
- return option ? searchCompletionIcon(option) : "no such option";
-}
+ describe("note mentions", () => {
+ it("offers the notes for a standalone @, from the marker, and leaves one inside an attribute name to the names", () => {
+ expect(complete("@Al")).toEqual({ kind: "notes", from: 0, query: "Al" });
+ // Neither the values of the label it is compared with nor, when asked, the keywords.
+ expect(complete("#author = @Al")).toEqual({ kind: "notes", from: 10, query: "Al" });
+ expect(complete("#book AND @", { explicit: true })).toEqual({ kind: "notes", from: 10, query: "" });
-describe("note mentions", () => {
- const NOTES = [
- { notePath: "root/abc123", noteTitle: "Foo", notePathTitle: "Root / Foo", icon: "bx bx-file" },
- { notePath: "root/proj/def456", noteTitle: "Foobar", notePathTitle: "Root / Projects / Foobar", icon: "bx bx-note" }
- ];
-
- beforeEach(() => vi.mocked(server.get).mockResolvedValue(NOTES));
-
- it("offers the notes an @ names and inserts the id, taking the marker with it", async () => {
- const result = await complete("~template.noteId = @Fo");
-
- expect(server.get).toHaveBeenCalledWith("autocomplete?query=Fo&activeNoteId=none&fastSearch=true");
- // Offered from past the `@`, so "Fo" is matched against the titles.
- expect(result?.from).toBe(20);
- expect(labelsOf(result)).toEqual([ "Foo", "Foobar" ]);
- expect(optionFor(result, "Foobar")?.boost).toBeLessThan(optionFor(result, "Foo")?.boost ?? 0);
-
- // The `@` at 19 is rewritten along with the "Fo" after it.
- expect(dispatchOf(result, "Foo", 22)).toEqual({
- changes: { from: 19, to: 22, insert: "abc123" },
- selection: { anchor: 25 }
+ // `@` is a name character to the lexer, so the names go on being offered.
+ expect(complete("#foo@")).toMatchObject({ kind: "attributes", query: "foo@" });
});
});
+});
- it("carries each note's result, to be drawn as the note autocomplete draws it", async () => {
- const result = await complete("@Fo");
-
- expect(result?.from).toBe(1);
- expect(searchCompletionNote(optionFor(result, "Foo") ?? { label: "" })).toBe(NOTES[0]);
- expect(searchCompletionNote(optionFor(result, "Foobar") ?? { label: "" })).toBe(NOTES[1]);
- // Neither an icon nor a detail of its own: the note row draws both.
- expect(searchCompletionIcon(optionFor(result, "Foo") ?? { label: "" })).toBeUndefined();
- expect(optionFor(result, "Foo")?.detail).toBeUndefined();
- // Anything else is drawn by CodeMirror.
- expect(searchCompletionNote({ label: "note", type: "namespace" })).toBeUndefined();
- });
-
- it("answers with the recently visited notes before anything is typed", async () => {
- const result = await complete("#book AND @");
-
- expect(server.get).toHaveBeenCalledWith("autocomplete?query=&activeNoteId=none&fastSearch=true");
- expect(labelsOf(result)).toEqual([ "Foo", "Foobar" ]);
- });
-
- it("opens on a standalone @ but not on one inside an attribute name", async () => {
- const inName = await complete("#foo@");
-
- expect(server.get).not.toHaveBeenCalledWith(expect.stringContaining("autocomplete?"));
- expect(labelsOf(inName)).toEqual([ "book", "archived" ]);
-
- // The same text with the marker standing on its own does reach the notes.
- expect(labelsOf(await complete("#foo @"))).toEqual([ "Foo", "Foobar" ]);
- });
-
- it("skips a suggestion carrying no note", async () => {
- vi.mocked(server.get).mockResolvedValue([ { noteTitle: "External", externalLink: "https://example.com" }, ...NOTES ]);
+describe("filterSearchEntries", () => {
+ it("keeps the entries holding the query, ignoring case, those starting with it first", () => {
+ const entries = [ "contentSize", "dateCreated", "content", "childrenCount", "title" ]
+ .map((title) => ({ id: title, title, insert: title }));
- expect(labelsOf(await complete("@Fo"))).toEqual([ "Foo", "Foobar" ]);
+ expect(filterSearchEntries(entries, "CONT").map((entry) => entry.title)).toEqual([ "contentSize", "content" ]);
+ expect(filterSearchEntries(entries, "c").map((entry) => entry.title))
+ .toEqual([ "contentSize", "content", "childrenCount", "dateCreated" ]);
+ expect(filterSearchEntries(entries, "")).toEqual(entries);
});
});
-/** Runs an option's rewrite against a stand-in editor and hands back what it dispatched. */
-function dispatchOf(result: CompletionResult | null, label: string, to: number) {
- const option = optionFor(result, label);
- const apply = option?.apply;
-
- if (typeof apply !== "function" || !option) {
- throw new Error(`The '${label}' option inserts a fixed string rather than rewriting.`);
- }
-
- let dispatched: unknown;
- apply({ dispatch: (spec: unknown) => { dispatched = spec; } } as never, option, 0, to);
-
- return dispatched;
-}
-
-async function complete(text: string, opts?: { explicit?: boolean }) {
- return await searchCompletionSource(contextAt(text, opts));
+function complete(text: string, { explicit = false } = {}) {
+ return searchCompletionAt(text, explicit);
}
-function labelsOf(result: CompletionResult | null): string[] {
- return (result?.options ?? []).map((option) => option.label);
+async function entriesOf(result: SearchCompletion | null): Promise<SearchEntry[]> {
+ return result?.kind === "entries" ? await result.entries() : [];
}
-function optionFor(result: CompletionResult | null, label: string) {
- return result?.options.find((option) => option.label === label);
+async function titlesOf(result: SearchCompletion | null) {
+ return (await entriesOf(result)).map((entry) => entry.title);
}
-/** Stands in for the editor's context, whose `matchBefore` anchors the pattern at the cursor. */
-function contextAt(text: string, { explicit = false } = {}): CompletionContext {
- const pos = text.length;
-
- return {
- pos,
- explicit,
- matchBefore(expr: RegExp) {
- // Flags carry over, the way CodeMirror's own `ensureAnchor` keeps them.
- const match = new RegExp(`(?:${expr.source})$`, expr.flags).exec(text);
- return match ? { from: pos - match[0].length, to: pos, text: match[0] } : null;
- }
- } as unknown as CompletionContext;
+async function entryFor(result: SearchCompletion | null, title: string) {
+ return (await entriesOf(result)).find((entry) => entry.title === title);
}
diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.ts
index 4b9e9f5fc5..ead3823704 100644
--- a/apps/client/src/widgets/ribbon/search_completions.ts
+++ b/apps/client/src/widgets/ribbon/search_completions.ts
@@ -1,87 +1,115 @@
-import type { Completion, CompletionContext, CompletionResult } from "@triliumnext/codemirror/src/field_editor";
-import { ALLOWED_NOTE_TYPES, allowedSearchOperators, type AutocompleteResult, MIME_TYPES_DICT, SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
+import { ALLOWED_NOTE_TYPES, allowedSearchOperators, MIME_TYPES_DICT, NOTE_TYPE_ICONS, SEARCH_NOTE_PATH, SEARCH_NOTE_PATH_SEGMENTS } from "@triliumnext/commons";
-import { isBuiltinAttribute } from "../../services/attributes";
import { t } from "../../services/i18n";
import server from "../../services/server";
-import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";
+import type { CommandEntry } from "../react/NoteAutocomplete";
-/** A branch answers at once, or after what it offers has been fetched. */
-type CompletionOutcome = CompletionResult | Promise<CompletionResult | null> | null;
+/**
+ * What can be completed at the cursor of a search string: what a pick replaces, from `from` up to
+ * the cursor, and which list offers it.
+ *
+ * - `notes`: the notes an `@` picks, listed as the note autocomplete lists them.
+ * - `attributes`: the label or relation names in the database, listed as the attribute panel lists them.
+ * - `entries`: everything else the syntax offers, listed as the command palette lists its commands.
+ */
+export type SearchCompletion = { from: number; query: string } & (
+ | { kind: "notes" }
+ | { kind: "attributes"; type: "label" | "relation" }
+ | {
+ kind: "entries";
+ /** Identifies the entries among the others offered at the same place. */
+ key: string;
+ entries(): SearchEntry[] | Promise<SearchEntry[]>;
+ /** Opens the list with the best match highlighted, so that Enter takes it. */
+ preselect: boolean;
+ }
+);
+
+/** An entry of the syntax, and the text a pick inserts for it. */
+export interface SearchEntry extends CommandEntry {
+ insert: string;
+}
/**
- * Offers Trilium's search syntax: the `note` object, the keywords, the property path that hangs off
- * `note` or off a relation, the comparison operators — whose spellings (`*=*`, `=*`, `~=`) are the
- * part of the syntax hardest to recall — the label and relation names in the database, and the
- * values a label is compared against.
+ * Offers Trilium's search syntax at the end of `before`, the text of the line up to the cursor: the
+ * notes picked with `@`, the `note` object, the keywords, the property path that hangs off `note`
+ * or off a relation, the comparison operators — whose spellings (`*=*`, `=*`, `~=`) are the part of
+ * the syntax hardest to recall — the label and relation names in the database, and the values a
+ * label or a property is compared against. `explicit` is set where the user asked with Ctrl-Space.
*/
-export function searchCompletionSource(context: CompletionContext): CompletionOutcome {
- // Read before the rest: `@` is a name character to the lexer, so the branches below would
- // answer for one typed inside an attribute name.
- const mention = context.matchBefore(NOTE_MENTION);
+export function searchCompletionAt(before: string, explicit: boolean): SearchCompletion | null {
+ const context = { before, pos: before.length, explicit };
+
+ // Read before the rest: `@` is a name character to the lexer, so the branches below would answer
+ // for one typed inside an attribute name, and the value branches for the query after it.
+ const mention = matchBefore(context, NOTE_MENTION);
if (mention) {
- const typedAt = mention.text.indexOf("@");
+ const at = mention.from + mention.text.indexOf("@");
- return noteCompletions(mention.text.slice(typedAt + 1), mention.from + typedAt);
+ return { kind: "notes", from: at, query: before.slice(at + 1) };
}
- const path = context.matchBefore(PROPERTY_PATH);
+ const path = matchBefore(context, PROPERTY_PATH);
if (path) {
- return pathCompletions(path.text, context.pos);
+ return pathCompletion(path.text, context.pos);
}
// `~=` and `~*` reach the operators below instead: an attribute name cannot be spelled with
// either character, so the pattern finds nothing ending at the cursor.
- const attribute = context.matchBefore(ATTRIBUTE_PREFIX);
+ const attribute = matchBefore(context, ATTRIBUTE_PREFIX);
if (attribute) {
- const isNegated = attribute.text[1] === "!";
+ const from = attribute.from + (attribute.text[1] === "!" ? 2 : 1);
- return attributeCompletions(
- attribute.text[0] === "#" ? "label" : "relation",
- attribute.from + (isNegated ? 2 : 1)
- );
+ return { kind: "attributes", type: attribute.text[0] === "#" ? "label" : "relation", from, query: before.slice(from) };
}
const value = labelValueBeingTyped(context);
if (value) {
- return valueCompletions(value.name, context.pos - value.typed.length, value.quote);
+ const { name, quote } = value;
+
+ return entries(context, `values:${name}`, context.pos - value.typed.length, () => labelValues(name, quote));
}
const property = propertyValueBeingTyped(context);
if (property) {
- return {
- from: context.pos - property.typed.length,
- options: property.options,
- validFor: validForValue(property.quote)
- };
+ return entries(context, `property:${property.property}`, context.pos - property.typed.length, () => property.entries);
}
// An ordering names a key and sorts on it, comparing nothing.
const ordering = orderingPosition(context);
- const operators = () => (ordering === "none" ? operatorOptions(context) : []);
+ const operators = () => (ordering === "none" ? operatorEntries(context) : []);
- const operator = context.matchBefore(OPERATOR_PREFIX);
+ const operator = matchBefore(context, OPERATOR_PREFIX);
if (operator) {
- const options = operators();
-
- return options.length ? { from: operator.from, options, validFor: OPERATOR_PREFIX } : null;
+ return operators().length ? entries(context, "operators", operator.from, operators) : null;
}
// A plain word is most often a search term, so the keywords wait for Ctrl-Space.
- const word = context.matchBefore(WORD_PREFIX);
+ const word = matchBefore(context, WORD_PREFIX);
if (word) {
- if (!context.explicit) return null;
- return { from: word.from, options: wordOptions(ordering), validFor: WORD_PREFIX };
+ return explicit ? entries(context, `words:${ordering}`, word.from, () => wordEntries(ordering)) : null;
}
// Ctrl-Space on empty space asks for everything on offer.
- if (context.explicit) {
- return { from: context.pos, options: [ ...wordOptions(ordering), ...operators() ] };
+ if (explicit) {
+ return entries(context, `all:${ordering}`, context.pos, () => [ ...wordEntries(ordering), ...operators() ]);
}
return null;
}
+/**
+ * The entries whose title holds `query`, ignoring case: those it starts first, then the rest, each
+ * in the order they are offered in.
+ */
+export function filterSearchEntries(entries: SearchEntry[], query: string) {
+ const typed = query.toLowerCase();
+ const starting = entries.filter(({ title }) => title.toLowerCase().startsWith(typed));
+ const containing = entries.filter(({ title }) => !title.toLowerCase().startsWith(typed) && title.toLowerCase().includes(typed));
+
+ return [ ...starting, ...containing ];
+}
+
/**
* A note picked with `@`, which opens only where a value can stand — at the start, or after
* whitespace, an opening bracket or an operator. `@` is a name character to the lexer, so one
@@ -95,7 +123,6 @@ const WORD_PREFIX = /[a-zA-Z]+/;
const SEGMENT = "[^\\s#~().,=<>*!%+\\-'\"`]";
/** The `note` object or a relation, followed by the dotted path walked from it. */
const PROPERTY_PATH = new RegExp(`(?:^|[\\s(])(?:note|~${SEGMENT}+)(?:\\.${SEGMENT}*)+`);
-const SEGMENT_TYPED = new RegExp(`${SEGMENT}*`);
/** Matches once an `orderBy` has been opened anywhere before the cursor. */
const ORDER_BY_BEFORE = /orderby[^]*/i;
/** A `#label` or `~relation`, either optionally negated with `!`. */
@@ -121,8 +148,6 @@ const PROPERTY_COMPARISON = new RegExp(
`(?:note|~${SEGMENT}+)(?:\\.${SEGMENT}+)*\\.(${SEGMENT}+)\\s*[=!*<>%~]+(\\s*[^\\s#~()]*)`
);
const QUOTES = [ "\"", "'", "`" ];
-/** A bare value runs until whitespace or a character that would start another clause. */
-const VALUE_TYPED = /[^\s#~()'"`]*/;
/** What the lexer reads as structure, so a value holding one of these only survives in quotes. */
const VALUE_NEEDS_QUOTES = /[\s"'`\\#~().=*<>!%+,-]/;
/**
@@ -132,122 +157,30 @@ const VALUE_NEEDS_QUOTES = /[\s"'`\\#~().=*<>!%+,-]/;
*/
const RESERVED_VALUES = new Set([ "note", "now", "today", "month", "year" ]);
-/** A completion for a note, drawn as a row of the note autocomplete from the result it carries. */
-interface NoteCompletion extends Completion {
- note: AutocompleteResult;
+/** The text before the cursor, and whether the user asked with Ctrl-Space. */
+interface Context {
+ before: string;
+ pos: number;
+ explicit: boolean;
}
-/**
- * Offers the notes matching what follows an `@`, through the call the jump-to dialog reads, and
- * inserts the id of the one picked. The id is what the query keeps, so it goes on matching the
- * note after a rename; with nothing typed yet the call answers with the recently visited notes.
- */
-async function noteCompletions(term: string, atPos: number): Promise<CompletionResult | null> {
- let suggestions: AutocompleteResult[];
- try {
- suggestions = await server.get<AutocompleteResult[]>(
- `autocomplete?query=${encodeURIComponent(term)}&activeNoteId=none&fastSearch=true`
- );
- } catch {
- return null;
- }
+/** Where `expr` matches ending at the cursor, and what it matches there. */
+function matchBefore({ before }: Context, expr: RegExp) {
+ const match = new RegExp(`(?:${expr.source})$`, expr.flags).exec(before);
- const options: NoteCompletion[] = [];
-
- for (const [ index, suggestion ] of suggestions.entries()) {
- const noteId = suggestion.notePath?.split("/").filter(Boolean).pop();
- if (!noteId || !suggestion.noteTitle) {
- continue;
- }
-
- options.push({
- label: suggestion.noteTitle,
- note: suggestion,
- // The call ranks the notes; this keeps that order among the ones matching as well as
- // each other, while leaving a distinctly better match free to rise past them.
- boost: -index,
- // Rewrites the `@` along with what was typed after it. CodeMirror would replace only
- // what it matched against, which starts past the `@`.
- apply: (view, _completion, _from, to) => view.dispatch({
- changes: { from: atPos, to, insert: noteId },
- selection: { anchor: atPos + noteId.length }
- })
- });
- }
-
- // Offered from past the `@`, so what was typed is matched against the titles rather than
- // against a marker no title carries.
- return options.length ? { from: atPos + 1, options } : null;
+ return match ? { from: match.index, text: match[0] } : null;
}
-/**
- * Fetches the label or relation names the database holds, through the same call the sidebar's
- * attribute picker makes, and marks the built-in ones as that picker does. The whole set is asked
- * for once and narrowed by `validFor` as more of the name is typed, rather than per keystroke.
- */
-async function attributeCompletions(type: "label" | "relation", from: number): Promise<CompletionResult | null> {
- let names: string[];
- try {
- names = await fetchAttributeNames(type, "");
- } catch {
- return null;
- }
-
- return {
- from,
- options: names.map((name) => {
- const isBuiltin = isBuiltinAttribute(type, name);
-
- return {
- label: name,
- type: isBuiltin ? SYSTEM_ATTRIBUTE : type,
- boost: isBuiltin ? BUILTIN_BOOST : undefined
- };
- }),
- validFor: SEGMENT_TYPED
- };
-}
-
-/** Stands in for a completion's own type, a name Trilium attaches a meaning to being marked first. */
-const SYSTEM_ATTRIBUTE = "system-attribute";
-
-/**
- * The furthest CodeMirror lets an option be moved down, which it adds to the match score. Penalties
- * there run to the hundreds, so a built-in sinks below a name of the user's own that matches as
- * well, while a distinctly better match keeps its place.
- */
-const BUILTIN_BOOST = -99;
-
-/**
- * The furthest an option can be moved up, the other end of {@link BUILTIN_BOOST}. CodeMirror never
- * reads the order options are offered in — it sorts by match score, and a pattern of a character or
- * two scores everything alike, leaving the tie to be broken by label. That puts `~` last of all, so
- * the markers carry the boost instead.
- */
-const MARKER_BOOST = 99;
-
-const COMPLETION_ICONS: Record<string, string> = {
- [SYSTEM_ATTRIBUTE]: "bx bx-cog",
- label: "bx bx-hash",
- relation: "bx bx-transfer"
-};
-
-/** The icon an option is drawn with. Only the attribute names carry one. */
-export function searchCompletionIcon(completion: Completion): string | undefined {
- return completion.type ? COMPLETION_ICONS[completion.type] : undefined;
-}
-
-/** The note an option offers, which is drawn as the note autocomplete draws it. */
-export function searchCompletionNote(completion: Completion): AutocompleteResult | undefined {
- return "note" in completion ? (completion as NoteCompletion).note : undefined;
+function entries(context: Context, key: string, from: number, list: () => SearchEntry[] | Promise<SearchEntry[]>): SearchCompletion {
+ return { kind: "entries", key, from, query: context.before.slice(from), entries: list, preselect: context.explicit };
}
/**
* Reads the label name and the part of its value typed so far out of the text before the cursor,
* and answers nothing where the cursor does not stand in a value.
*/
-function labelValueBeingTyped(context: CompletionContext) {
- const comparison = context.matchBefore(LABEL_COMPARISON);
+function labelValueBeingTyped(context: Context) {
+ const comparison = matchBefore(context, LABEL_COMPARISON);
const match = comparison && LABEL_COMPARISON.exec(comparison.text);
if (!match) {
return null;
@@ -263,8 +196,8 @@ function labelValueBeingTyped(context: CompletionContext) {
* The values a note property is compared against, for the properties holding a closed set of them.
* The rest — a title, a date, a count — are the user's to type.
*/
-function propertyValueBeingTyped(context: CompletionContext) {
- const comparison = context.matchBefore(PROPERTY_COMPARISON);
+function propertyValueBeingTyped(context: Context) {
+ const comparison = matchBefore(context, PROPERTY_COMPARISON);
const match = comparison && PROPERTY_COMPARISON.exec(comparison.text);
if (!match) {
return null;
@@ -279,15 +212,17 @@ function propertyValueBeingTyped(context: CompletionContext) {
// A quote the user opened is a value they are spelling out, so the ones that mean anything
// only bare are dropped. For a date property that leaves nothing to offer.
- const options = values()
+ const offered = values()
.filter(({ verbatim }) => !(verbatim && value.quote))
- .map(({ label, detail, verbatim }) => {
- const applied = verbatim ? label : applyValue(label, value.quote);
-
- return { label, detail, apply: applied === label ? undefined : applied };
- });
-
- return options.length ? { ...value, options } : null;
+ .map(({ label, detail, icon, verbatim }) => ({
+ id: label,
+ title: label,
+ description: detail,
+ icon,
+ insert: verbatim ? label : applyValue(label, value.quote)
+ }));
+
+ return offered.length ? { ...value, property: property.toLowerCase(), entries: offered } : null;
}
/**
@@ -316,8 +251,8 @@ function valueBeingTyped(tail: string) {
* already use, so a type or a MIME added there is offered here without further work.
*/
const PROPERTY_VALUES = new Map<string, () => PropertyValue[]>([
- [ "type", () => ALLOWED_NOTE_TYPES.map((noteType) => ({ label: noteType })) ],
- [ "mime", () => MIME_TYPES_DICT.map(({ mime, title }) => ({ label: mime, detail: title })) ],
+ [ "type", () => ALLOWED_NOTE_TYPES.map((noteType) => ({ label: noteType, icon: noteTypeIcon(noteType) })) ],
+ [ "mime", () => MIME_TYPES_DICT.map(({ mime, title }) => ({ label: mime, detail: title, icon: "bx bx-code-alt" })) ],
[ "isprotected", booleanValues ],
[ "isarchived", booleanValues ],
[ "datecreated", dateValues ],
@@ -329,12 +264,17 @@ const PROPERTY_VALUES = new Map<string, () => PropertyValue[]>([
interface PropertyValue {
label: string;
detail?: string;
+ icon: string;
/** Inserted as it stands, the parser reading it as something other than the text it spells. */
verbatim?: boolean;
}
+function noteTypeIcon(noteType: string) {
+ return (NOTE_TYPE_ICONS as Record<string, string>)[noteType] ?? "bx bx-note";
+}
+
function booleanValues(): PropertyValue[] {
- return [ { label: "true" }, { label: "false" } ];
+ return [ { label: "true", icon: "bx bx-toggle-right" }, { label: "false", icon: "bx bx-toggle-left" } ];
}
/**
@@ -344,43 +284,25 @@ function booleanValues(): PropertyValue[] {
*/
function dateValues(): PropertyValue[] {
return [
- { label: "now", detail: t("search_completion.date_now"), verbatim: true },
- { label: "now-60", detail: t("search_completion.date_now_offset"), verbatim: true },
- { label: "today", detail: t("search_completion.date_today"), verbatim: true },
- { label: "today-30", detail: t("search_completion.date_today_offset"), verbatim: true },
- { label: "month", detail: t("search_completion.date_month"), verbatim: true },
- { label: "month-1", detail: t("search_completion.date_month_offset"), verbatim: true },
- { label: "year", detail: t("search_completion.date_year"), verbatim: true },
- { label: "year-1", detail: t("search_completion.date_year_offset"), verbatim: true }
- ];
+ { label: "now", detail: t("search_completion.date_now") },
+ { label: "now-60", detail: t("search_completion.date_now_offset") },
+ { label: "today", detail: t("search_completion.date_today") },
+ { label: "today-30", detail: t("search_completion.date_today_offset") },
+ { label: "month", detail: t("search_completion.date_month") },
+ { label: "month-1", detail: t("search_completion.date_month_offset") },
+ { label: "year", detail: t("search_completion.date_year") },
+ { label: "year-1", detail: t("search_completion.date_year_offset") }
+ ].map((value) => ({ ...value, icon: "bx bx-calendar", verbatim: true }));
}
/**
- * Offers the values `name` already holds across the database. Only labels reach here: a relation's
- * value is a note ID, and the endpoint behind this collects label values alone.
+ * The values `name` already holds across the database. Only labels reach here: a relation's value
+ * is a note ID, and the endpoint behind this collects label values alone.
*/
-async function valueCompletions(name: string, from: number, quote: string): Promise<CompletionResult | null> {
- let values: string[];
- try {
- values = await server.get<string[]>(`attribute-values/${encodeURIComponent(name)}`);
- } catch {
- return null;
- }
-
- return {
- from,
- options: values.map((value) => {
- const applied = applyValue(value, quote);
+async function labelValues(name: string, quote: string): Promise<SearchEntry[]> {
+ const values = await server.get<string[]>(`attribute-values/${encodeURIComponent(name)}`);
- return { label: value, apply: applied === value ? undefined : applied };
- }),
- validFor: validForValue(quote)
- };
-}
-
-/** How far the offered values stay valid as more of the one being typed arrives. */
-function validForValue(quote: string) {
- return quote ? new RegExp(`[^${quote}]*`) : VALUE_TYPED;
+ return values.map((value) => ({ id: value, title: value, icon: "bx bx-purchase-tag-alt", insert: applyValue(value, quote) }));
}
/**
@@ -408,7 +330,7 @@ function escapeInQuotes(value: string, quote: string) {
* `note.relations.` that is an attribute name; after `note.title.` it is nothing at all, a
* terminal property having nothing to walk onto.
*/
-function pathCompletions(path: string, pos: number): CompletionOutcome {
+function pathCompletion(path: string, pos: number): SearchCompletion | null {
const segments = path.split(".");
const typed = segments[segments.length - 1];
const previous = segments[segments.length - 2];
@@ -416,7 +338,7 @@ function pathCompletions(path: string, pos: number): CompletionOutcome {
const from = pos - typed.length;
if (previous === "labels" || previous === "relations") {
- return attributeCompletions(previous === "labels" ? "label" : "relation", from);
+ return { kind: "attributes", type: previous === "labels" ? "label" : "relation", from, query: typed };
}
// A segment follows the root, a traversal, or the relation name reached through `relations`.
@@ -428,31 +350,31 @@ function pathCompletions(path: string, pos: number): CompletionOutcome {
return null;
}
- return { from, options: segmentOptions(), validFor: SEGMENT_TYPED };
+ return { kind: "entries", key: "segments", from, query: typed, entries: segmentEntries, preselect: false };
}
/**
* Everything spelled as a word: the `note` object and the keywords that join, order and cut down a
- * query. Built per request rather than once, so the options read the catalogue after i18n has
+ * query. Built per request rather than once, so the entries read the catalogue after i18n has
* loaded and follow a language switched while the app is running.
*/
-function wordOptions(ordering: OrderingPosition): Completion[] {
+function wordEntries(ordering: OrderingPosition): SearchEntry[] {
// Both complete with what has to follow them: a bare `note`, or a `not` without its
- // parenthesised sub-expression, is never a clause on its own.
- const noteObject: Completion = { label: "note", apply: "note.", type: "namespace", detail: t("search_completion.note") };
- const limit: Completion = { label: "limit", type: "keyword", detail: t("search_completion.keyword_limit") };
+ // parenthesised sub-expression, is never a clause on its own. The list then opens on that.
+ const noteObject = entry("note", t("search_completion.note"), "bx bx-note", "note.");
+ const limit = entry("limit", t("search_completion.keyword_limit"), "bx bx-list-ol");
// The characters the whole syntax turns on, and the only part of it a reader cannot arrive at
// by typing a word, so they lead. `ValueExtractor` rewrites either into a path, so a sort key
- // takes them too. Drawn as keywords: the marker is already the icon.
- const attributeMarkers: Completion[] = [
- { label: "#", apply: "#", type: "keyword", boost: MARKER_BOOST, detail: t("search_completion.label_marker") },
- { label: "#!", apply: "#!", type: "keyword", boost: MARKER_BOOST - 1, detail: t("search_completion.label_marker_negated") },
- { label: "~", apply: "~", type: "keyword", boost: MARKER_BOOST - 2, detail: t("search_completion.relation_marker") },
- { label: "~!", apply: "~!", type: "keyword", boost: MARKER_BOOST - 3, detail: t("search_completion.relation_marker_negated") }
+ // takes them too.
+ const attributeMarkers = [
+ entry("#", t("search_completion.label_marker"), "bx bx-hash"),
+ entry("#!", t("search_completion.label_marker_negated"), "bx bx-hash"),
+ entry("~", t("search_completion.relation_marker"), "bx bx-transfer"),
+ entry("~!", t("search_completion.relation_marker_negated"), "bx bx-transfer")
];
// A sort key names the value to order by, which a negated marker has none of: `ValueExtractor`
// reads `#!foo` as a label named `!foo` and would quietly order by one no note carries.
- const sortKeyMarkers = attributeMarkers.filter(({ label }) => !label.endsWith("!"));
+ const sortKeyMarkers = attributeMarkers.filter(({ title }) => !title.endsWith("!"));
if (ordering === "key") {
return [ ...sortKeyMarkers, noteObject ];
@@ -460,8 +382,8 @@ function wordOptions(ordering: OrderingPosition): Completion[] {
if (ordering === "sorted") {
return [
- { label: "asc", type: "keyword", detail: t("order_by.asc") },
- { label: "desc", type: "keyword", detail: t("order_by.desc") },
+ entry("asc", t("order_by.asc"), "bx bx-sort-up"),
+ entry("desc", t("order_by.desc"), "bx bx-sort-down"),
limit
];
}
@@ -469,26 +391,18 @@ function wordOptions(ordering: OrderingPosition): Completion[] {
return [
...attributeMarkers,
noteObject,
- { label: "and", type: "keyword", detail: t("search_completion.keyword_and") },
- { label: "or", type: "keyword", detail: t("search_completion.keyword_or") },
- { label: "not", apply: "not(", type: "keyword", detail: t("search_completion.keyword_not") },
- { label: "orderBy", type: "keyword", detail: t("search_completion.keyword_order_by") },
+ entry("and", t("search_completion.keyword_and"), "bx bx-git-merge"),
+ entry("or", t("search_completion.keyword_or"), "bx bx-git-merge"),
+ entry("not", t("search_completion.keyword_not"), "bx bx-block", "not("),
+ entry("orderBy", t("search_completion.keyword_order_by"), "bx bx-sort-alt-2"),
limit
];
}
-/**
- * Whether picking `completion` reopens the popup. Every option that inserts one of these leaves a
- * clause unfinished: `note.`, `#` and `#!` are waiting for a name, `not(` for a sub-expression.
- */
-export function searchCompletionReactivates(completion: Completion): boolean {
- const applied = completion.apply;
-
- return typeof applied === "string" && OPENERS.includes(applied.slice(-1));
+function entry(title: string, description: string | undefined, icon: string, insert = title): SearchEntry {
+ return { id: title, title, description, icon, insert };
}
-const OPENERS = [ ".", "(", "#", "~", "!" ];
-
/**
* Where the cursor stands in an `orderBy`, which decides what can follow it.
* `parseOrderByAndLimit()` reads a property path, then an optional `asc` or `desc`, then either a
@@ -496,8 +410,8 @@ const OPENERS = [ ".", "(", "#", "~", "!" ];
*/
type OrderingPosition = "none" | "key" | "sorted";
-function orderingPosition(context: CompletionContext): OrderingPosition {
- const ordering = context.matchBefore(ORDER_BY_BEFORE);
+function orderingPosition(context: Context): OrderingPosition {
+ const ordering = matchBefore(context, ORDER_BY_BEFORE);
if (!ordering) {
return "none";
}
@@ -514,12 +428,9 @@ function orderingPosition(context: CompletionContext): OrderingPosition {
return written ? "sorted" : "key";
}
-function segmentOptions(): Completion[] {
- return SEARCH_NOTE_PATH_SEGMENTS.map((segment) => ({
- label: segment,
- type: "property",
- detail: SEGMENT_DETAILS[segment] ? t(SEGMENT_DETAILS[segment]) : undefined
- }));
+function segmentEntries(): SearchEntry[] {
+ return SEARCH_NOTE_PATH_SEGMENTS.map((segment) =>
+ entry(segment, SEGMENT_DETAILS[segment] ? t(SEGMENT_DETAILS[segment]) : undefined, "bx bx-detail"));
}
/**
@@ -553,33 +464,31 @@ const SEGMENT_DETAILS: Record<string, string> = {
};
/** The operators the operand standing before the cursor can be compared with. */
-function operatorOptions(context: CompletionContext): Completion[] {
+function operatorEntries(context: Context): SearchEntry[] {
const allowed = allowedOperators(context);
return [
- { label: "=", detail: t("search_completion.operator_equal") },
- { label: "!=", detail: t("search_completion.operator_not_equal") },
- { label: "*=*", detail: t("search_completion.operator_contains") },
- { label: "=*", detail: t("search_completion.operator_starts_with") },
- { label: "*=", detail: t("search_completion.operator_ends_with") },
- { label: ">", detail: t("search_completion.operator_greater_than") },
- { label: ">=", detail: t("search_completion.operator_greater_or_equal") },
- { label: "<", detail: t("search_completion.operator_less_than") },
- { label: "<=", detail: t("search_completion.operator_less_or_equal") },
- { label: "%=", detail: t("search_completion.operator_regex") },
- { label: "~=", detail: t("search_completion.operator_fuzzy_equal") },
- { label: "~*", detail: t("search_completion.operator_fuzzy_contains") }
- ]
- .filter(({ label }) => !allowed || allowed.has(label))
- .map((option) => ({ ...option, type: "keyword" }));
+ entry("=", t("search_completion.operator_equal"), "bx bx-math"),
+ entry("!=", t("search_completion.operator_not_equal"), "bx bx-math"),
+ entry("*=*", t("search_completion.operator_contains"), "bx bx-math"),
+ entry("=*", t("search_completion.operator_starts_with"), "bx bx-math"),
+ entry("*=", t("search_completion.operator_ends_with"), "bx bx-math"),
+ entry(">", t("search_completion.operator_greater_than"), "bx bx-math"),
+ entry(">=", t("search_completion.operator_greater_or_equal"), "bx bx-math"),
+ entry("<", t("search_completion.operator_less_than"), "bx bx-math"),
+ entry("<=", t("search_completion.operator_less_or_equal"), "bx bx-math"),
+ entry("%=", t("search_completion.operator_regex"), "bx bx-math"),
+ entry("~=", t("search_completion.operator_fuzzy_equal"), "bx bx-math"),
+ entry("~*", t("search_completion.operator_fuzzy_contains"), "bx bx-math")
+ ].filter(({ title }) => !allowed || allowed.has(title));
}
/**
* What the operand restricts the comparison to, `undefined` standing for no restriction. Offering
* more would build a query the parser rejects.
*/
-function allowedOperators(context: CompletionContext): ReadonlySet<string> | undefined {
- const comparison = context.matchBefore(COMPARISON_OPERAND);
+function allowedOperators(context: Context): ReadonlySet<string> | undefined {
+ const comparison = matchBefore(context, COMPARISON_OPERAND);
const operand = comparison && COMPARISON_OPERAND.exec(comparison.text)?.[1];
if (!operand) {
return undefined;
@@ -587,4 +496,3 @@ function allowedOperators(context: CompletionContext): ReadonlySet<string> | und
return allowedSearchOperators(operand);
}
-
diff --git a/apps/client/src/widgets/search_field_editor.css b/apps/client/src/widgets/search_field_editor.css
index 4a03c429b8..c1de38d614 100644
--- a/apps/client/src/widgets/search_field_editor.css
+++ b/apps/client/src/widgets/search_field_editor.css
@@ -29,57 +29,11 @@
}
/* Over a `Popup` (1200, Popup.css): the quick search's results hang off this field, and the
- completions and lint tooltips have to cover them. */
+ lint tooltips have to cover them. */
.cm-editor .cm-tooltip {
z-index: 1210;
}
- /*
- * The popup carries the note autocomplete's menu classes (`search_field_editor.ts`), which draw
- * its frame and rows. These rules undo only what CodeMirror's theme sets over them: its
- * `&light .cm-tooltip` and `.cm-tooltip-autocomplete > ul > li` outweigh `.dropdown-menu` and
- * `.dropdown-item`.
- */
- .cm-editor .cm-tooltip.cm-tooltip-autocomplete {
- border-color: var(--dropdown-border-color);
- overflow: hidden;
-
- /* CodeMirror sets monospace on the popup; the field itself is in the UI font. */
- & > ul {
- font-family: inherit;
- max-height: 18em;
- }
-
- /* Bootstrap's row padding, which the Next theme overrides with `!important`. */
- & > ul > li {
- flex-wrap: wrap;
- padding: var(--bs-dropdown-item-padding-y) var(--bs-dropdown-item-padding-x);
- line-height: inherit;
- }
-
- /* Matches the `.tn-menu-gap` beside a note row's icon. */
- .cm-completion-glyph {
- margin-inline-end: 0.5em;
- opacity: 0.7;
- }
-
- /* Matches the second line of a command row, `.note-suggestion-description`. */
- .cm-completionDetail {
- flex-basis: 100%;
- margin-left: 0;
- font-size: small;
- font-style: normal;
- color: var(--muted-text-color);
- overflow: hidden;
- text-overflow: ellipsis;
- }
-
- & > ul > li[aria-selected] {
- background: var(--suggestion-active-background-color);
- color: var(--suggestion-active-text-color);
- }
- }
-
.cm-editor .cm-tooltip.cm-tooltip-hover {
--search-lint-tooltip-background: var(--tooltip-background-color, transparent);
diff --git a/apps/client/src/widgets/search_field_editor.spec.tsx b/apps/client/src/widgets/search_field_editor.spec.tsx
new file mode 100644
index 0000000000..51e36b707d
--- /dev/null
+++ b/apps/client/src/widgets/search_field_editor.spec.tsx
@@ -0,0 +1,115 @@
+import { EditorSelection } from "@codemirror/state";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+const { getNoteSuggestions } = vi.hoisted(() => ({
+ getNoteSuggestions: vi.fn<(term: string, options?: NoteSuggestionOptions) => Promise<Suggestion[]>>()
+}));
+
+vi.mock("../services/note_autocomplete", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("../services/note_autocomplete")>()),
+ getNoteSuggestions
+}));
+// The attribute names, and the linter asking the server to read the query, which nothing here is about.
+vi.mock("../services/server", () => ({
+ default: {
+ get: vi.fn(async (url: string) => (url.startsWith("attribute-names/") ? [ "book", "bookmark" ] : [])),
+ post: vi.fn(async () => ({}))
+ }
+}));
+
+import type { NoteSuggestionOptions, Suggestion } from "../services/note_autocomplete";
+import { createSearchFieldEditor } from "./search_field_editor";
+
+describe("createSearchFieldEditor", () => {
+ let editor: ReturnType<typeof createSearchFieldEditor> | undefined;
+ let onEnter: ReturnType<typeof vi.fn<() => void>>;
+
+ beforeEach(() => {
+ onEnter = vi.fn<() => void>();
+ const parent = document.createElement("div");
+ document.body.append(parent);
+ editor = createSearchFieldEditor({ parent, onEnter });
+ editor.focus();
+ });
+
+ afterEach(() => {
+ editor?.destroy();
+ editor = undefined;
+ });
+
+ it("lists the notes for an @ as the note autocomplete does, and puts the id of the one picked in its place", async () => {
+ getNoteSuggestions.mockResolvedValue([
+ { notePath: "root/projects/abc123", noteTitle: "Alpha", notePathTitle: "Projects / Alpha", highlightedNotePathTitle: "<b>Al</b>pha" },
+ { notePath: "root/def456", noteTitle: "Alpine", notePathTitle: "Alpine", highlightedNotePathTitle: "<b>Al</b>pine" }
+ ]);
+
+ type("#book @Al");
+ const rows = () => menuRows(".note-autocomplete-menu");
+ await vi.waitFor(() => expect(rows()).toEqual([ "Alpha", "Alpine" ]));
+ // At most ten notes, and no rows creating one: a query names notes that exist.
+ expect(getNoteSuggestions).toHaveBeenLastCalledWith("Al", { allowCreatingNotes: undefined, limit: 10 });
+
+ // The first note is highlighted, so Enter takes it rather than running the search.
+ await press("Enter");
+ await vi.waitFor(() => expect(text()).toBe("#book abc123"));
+ await vi.waitFor(() => expect(rows()).toEqual([]));
+ expect(onEnter).not.toHaveBeenCalled();
+ });
+
+ it("lists the names after # as the attribute panel does, leaving Enter to the search until one is arrowed to", async () => {
+ type("#bo");
+ const rows = () => menuRows(".form-autocomplete-dropdown");
+ await vi.waitFor(() => expect(rows()).toEqual([ "book", "bookmark" ]));
+
+ await press("Enter");
+ expect(onEnter).toHaveBeenCalledOnce();
+
+ await press("ArrowDown");
+ await press("ArrowDown");
+ await press("Enter");
+ await vi.waitFor(() => expect(text()).toBe("#bookmark"));
+ expect(onEnter).toHaveBeenCalledOnce();
+ });
+
+ it("lists the rest of the syntax as the command palette lists its commands, and opens on what a pick leaves to complete", async () => {
+ type("#book ");
+ await press(" ", { ctrlKey: true });
+ const rows = () => menuRows(".note-autocomplete-menu").map((row) => row.split("search_completion.")[0]);
+ await vi.waitFor(() => expect(rows()).toContain("orderBy"));
+
+ // Asked for, the list opens on the best match, so Enter takes it.
+ type("no");
+ await vi.waitFor(() => expect(rows()[0]).toBe("note"));
+ await press("Enter");
+ await vi.waitFor(() => expect(text()).toBe("#book note."));
+
+ // `note.` leaves a property to name, which the list now offers.
+ await vi.waitFor(() => expect(rows()).toContain("title"));
+ type("ti");
+ await vi.waitFor(() => expect(rows()[0]).toBe("title"));
+ await press("ArrowDown");
+ await press("Enter");
+ await vi.waitFor(() => expect(text()).toBe("#book note.title"));
+ });
+
+ function type(inserted: string) {
+ const view = editor;
+ if (!view) throw new Error("expected an editor");
+ const at = view.state.selection.main.head;
+ view.dispatch({ changes: { from: at, insert: inserted }, selection: EditorSelection.cursor(at + inserted.length) });
+ }
+
+ /** Presses a key, and lets the list render what it did before the next one, as between two key presses. */
+ async function press(key: string, init: KeyboardEventInit = {}) {
+ editor?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));
+ await new Promise((resolve) => setTimeout(resolve, 0));
+ }
+
+ function text() {
+ return editor?.state.doc.toString();
+ }
+});
+
+function menuRows(menu: string) {
+ return [ ...document.querySelectorAll(`${menu} [role=option]`) ].map((row) => row.textContent ?? "");
+}
diff --git a/apps/client/src/widgets/search_field_editor.ts b/apps/client/src/widgets/search_field_editor.ts
deleted file mode 100644
index fdf3285796..0000000000
--- a/apps/client/src/widgets/search_field_editor.ts
+++ /dev/null
@@ -1,87 +0,0 @@
-import "./search_field_editor.css";
-
-import { type NoteChip, triliumNoteChips } from "@triliumnext/codemirror/src/extensions/trilium_note_chips";
-import { triliumSearchHighlighter } from "@triliumnext/codemirror/src/extensions/trilium_search_highlighter";
-import { type SearchLintMessages, triliumSearchLinter } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";
-import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "@triliumnext/codemirror/src/field_editor";
-import type { SearchLintResponse } from "@triliumnext/commons";
-
-import froca from "../services/froca";
-import { t } from "../services/i18n";
-import server from "../services/server";
-import { renderNoteSuggestion } from "./react/NoteAutocomplete";
-import { searchCompletionIcon, searchCompletionNote, searchCompletionReactivates, searchCompletionSource } from "./ribbon/search_completions";
-
-/** The class the styles in `search_field_editor.css` are scoped under. */
-export const SEARCH_FIELD_EDITOR_CLASS = "search-string-editor";
-
-/** What a caller supplies; the highlighting, linting and completions are fixed. */
-export type SearchFieldEditorConfig = Omit<FieldEditorConfig,
- "extensions" | "completionSource" | "completionIcon" | "renderCompletion" | "completionClasses" | "activateOnCompletion">;
-
-/**
- * Builds the editor a search string is written in: the query highlighter, the linter and the
- * attribute/property completions over {@link createFieldEditor}. The quick search and the saved
- * search's ribbon both use it, so a query reads and reports the same way in either field.
- *
- * The parent element needs {@link SEARCH_FIELD_EDITOR_CLASS} for the styles to apply.
- */
-export function createSearchFieldEditor(config: SearchFieldEditorConfig): FieldEditor {
- return createFieldEditor({
- ...config,
- extensions: [
- triliumSearchHighlighter,
- triliumSearchLinter(searchLintMessages(), validateOnServer),
- triliumNoteChips(resolveNoteChip)
- ],
- completionSource: searchCompletionSource,
- completionIcon: searchCompletionIcon,
- renderCompletion: (completion) => {
- const note = searchCompletionNote(completion);
-
- return note ? renderNoteSuggestion(note) : null;
- },
- // The note autocomplete's menu, so a note picked with `@` is offered as it is there. The
- // highlighted option is the one CodeMirror selects, which the pointer does not move.
- completionClasses: {
- popup: "dropdown-menu show tn-dropdown-menu tn-menu-keyboard note-autocomplete-menu",
- option: "dropdown-item"
- },
- activateOnCompletion: searchCompletionReactivates
- });
-}
-
-/**
- * Names the note an id in the query stands for. Froca answers for one it already holds without a
- * round trip, so a chip for a note on screen is drawn in the same pass the id appears in.
- */
-function resolveNoteChip(noteId: string): NoteChip | Promise<NoteChip | null> | null {
- const cached = froca.getNoteFromCache(noteId);
- if (cached) {
- return { title: cached.title, icon: cached.getIcon() };
- }
-
- return froca.getNote(noteId, true).then((note) => note && { title: note.title, icon: note.getIcon() });
-}
-
-/**
- * Asks the engine to read the query without running it, for the faults the rules in the editor do
- * not cover. Only reached once those rules are satisfied, so a query they already object to costs
- * no request.
- */
-async function validateOnServer(searchString: string) {
- const { error } = await server.post<SearchLintResponse>("search/lint", { searchString });
-
- return error;
-}
-
-/** Read once the editor is built, so the wording follows a language switched while the app runs. */
-function searchLintMessages(): SearchLintMessages {
- return {
- relationNeedsProperty: t("search_lint.relation_needs_property"),
- textNeedsContains: t("search_lint.text_needs_contains"),
- contentNotOrdered: t("search_lint.content_not_ordered"),
- compareTheTitle: t("search_lint.compare_the_title"),
- useOperator: (operator) => t("search_lint.use_operator", { operator })
- };
-}
diff --git a/apps/client/src/widgets/search_field_editor.tsx b/apps/client/src/widgets/search_field_editor.tsx
new file mode 100644
index 0000000000..3907ae9ffd
--- /dev/null
+++ b/apps/client/src/widgets/search_field_editor.tsx
@@ -0,0 +1,155 @@
+import "./search_field_editor.css";
+
+import { hostedCompletion, type HostedCompletionState } from "@triliumnext/codemirror/src/extensions/hosted_completion";
+import { type NoteChip, triliumNoteChips } from "@triliumnext/codemirror/src/extensions/trilium_note_chips";
+import { triliumSearchHighlighter } from "@triliumnext/codemirror/src/extensions/trilium_search_highlighter";
+import { type SearchLintMessages, triliumSearchLinter } from "@triliumnext/codemirror/src/extensions/trilium_search_lint";
+import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "@triliumnext/codemirror/src/field_editor";
+import type { SearchLintResponse } from "@triliumnext/commons";
+
+import froca from "../services/froca";
+import { t } from "../services/i18n";
+import server from "../services/server";
+import { AttributeNameSuggestion, fetchAttributeNames } from "./attribute_widgets/attribute_detail";
+import { AutocompleteList } from "./react/FormAutocomplete";
+import { CommandMentionList, createHostedList, NoteMentionList } from "./react/NoteAutocomplete";
+import { filterSearchEntries, type SearchCompletion, searchCompletionAt, type SearchEntry } from "./ribbon/search_completions";
+
+/** The class the styles in `search_field_editor.css` are scoped under. */
+export const SEARCH_FIELD_EDITOR_CLASS = "search-string-editor";
+
+/** What a caller supplies; the highlighting, linting and completions are fixed. */
+export type SearchFieldEditorConfig = Omit<FieldEditorConfig, "extensions">;
+
+/**
+ * Builds the editor a search string is written in: the query highlighter, the linter and the
+ * completions over {@link createFieldEditor}. The quick search and the saved search's ribbon both
+ * use it, so a query reads and reports the same way in either field.
+ *
+ * The completions are the app's own lists: a note picked with `@` from the note autocomplete's, a
+ * label or relation name from the attribute panel's, and the rest of the syntax from the command
+ * palette's.
+ *
+ * The parent element needs {@link SEARCH_FIELD_EDITOR_CLASS} for the styles to apply.
+ */
+export function createSearchFieldEditor(config: SearchFieldEditorConfig): FieldEditor {
+ return createFieldEditor({
+ ...config,
+ extensions: [
+ triliumSearchHighlighter,
+ triliumSearchLinter(searchLintMessages(), validateOnServer),
+ triliumNoteChips(resolveNoteChip),
+ hostedCompletion({ match: searchCompletionAt, list: createSearchCompletionList })
+ ]
+ });
+}
+
+/**
+ * Lists what {@link searchCompletionAt} finds at the cursor, and puts what is picked in place of
+ * what it covers. A note goes into the query as its id, which goes on matching the note after a
+ * rename.
+ */
+function createSearchCompletionList() {
+ // The entries a list was opened on, kept while it stays open at the same place, so the values
+ // of a label are fetched once rather than per keystroke.
+ let cached: { key: string; entries: Promise<SearchEntry[]> } | undefined;
+
+ const list = createHostedList<HostedCompletionState<SearchCompletion>>((state, props) => {
+ const { match } = state;
+ const at = `${match.kind}:${match.from}`;
+
+ switch (match.kind) {
+ case "notes":
+ return (
+ <NoteMentionList
+ key={at}
+ {...props}
+ query={match.query}
+ onPick={(notePath) => {
+ // Without creation rows, a pick is always a note that exists.
+ if (typeof notePath === "string") {
+ state.commit(notePath.split("/").at(-1) ?? notePath);
+ }
+ }}
+ />
+ );
+ case "attributes":
+ return (
+ <AutocompleteList
+ key={`${at}:${match.type}`}
+ {...props}
+ query={match.query}
+ source={(query) => fetchAttributeNames(match.type, query)}
+ renderItem={(name) => <AttributeNameSuggestion type={match.type} name={name} />}
+ onPick={state.commit}
+ />
+ );
+ case "entries": {
+ const key = `${at}:${match.key}`;
+ if (cached?.key !== key) {
+ cached = { key, entries: Promise.resolve(match.entries()) };
+ }
+ const { entries } = cached;
+
+ return (
+ <CommandMentionList<SearchEntry>
+ key={key}
+ {...props}
+ query={match.query}
+ preselect={match.preselect}
+ source={async (query) => filterSearchEntries(await entries, query)}
+ onPick={(entry) => state.commit(entry.insert)}
+ />
+ );
+ }
+ }
+ });
+
+ return {
+ show: list.show,
+ hide() {
+ cached = undefined;
+ list.hide();
+ },
+ handleKeyDown: list.handleKeyDown,
+ get element() {
+ return list.element;
+ },
+ destroy: list.destroy
+ };
+}
+
+/**
+ * Names the note an id in the query stands for. Froca answers for one it already holds without a
+ * round trip, so a chip for a note on screen is drawn in the same pass the id appears in.
+ */
+function resolveNoteChip(noteId: string): NoteChip | Promise<NoteChip | null> | null {
+ const cached = froca.getNoteFromCache(noteId);
+ if (cached) {
+ return { title: cached.title, icon: cached.getIcon() };
+ }
+
+ return froca.getNote(noteId, true).then((note) => note && { title: note.title, icon: note.getIcon() });
+}
+
+/**
+ * Asks the engine to read the query without running it, for the faults the rules in the editor do
+ * not cover. Only reached once those rules are satisfied, so a query they already object to costs
+ * no request.
+ */
+async function validateOnServer(searchString: string) {
+ const { error } = await server.post<SearchLintResponse>("search/lint", { searchString });
+
+ return error;
+}
+
+/** Read once the editor is built, so the wording follows a language switched while the app runs. */
+function searchLintMessages(): SearchLintMessages {
+ return {
+ relationNeedsProperty: t("search_lint.relation_needs_property"),
+ textNeedsContains: t("search_lint.text_needs_contains"),
+ contentNotOrdered: t("search_lint.content_not_ordered"),
+ compareTheTitle: t("search_lint.compare_the_title"),
+ useOperator: (operator) => t("search_lint.use_operator", { operator })
+ };
+}
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
index a210f0a046..a2829564de 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.tsx
@@ -1,20 +1,15 @@
import "./mention_list_view.css";
-import type { ReferenceElement } from "@floating-ui/dom";
import type { EmojiSuggestion, MentionFeedObjectItem, MentionHostedList, MentionHostedListState, SlashCommandConfig, SlashCommandDefinition, SlashCommandItem, TriliumEmojiMention, TriliumSlashCommands } from "@triliumnext/ckeditor5";
import clsx from "clsx";
-import { type ComponentChildren, render, type VNode } from "preact";
-import type { MutableRef } from "preact/hooks";
+import type { ComponentChildren } from "preact";
-import { AutocompleteList, type AutocompleteListHandle } from "../../react/FormAutocomplete";
-import { type CommandEntry, CommandMentionList, NoteMentionList } from "../../react/NoteAutocomplete";
+import { AutocompleteList } from "../../react/FormAutocomplete";
+import { type CommandEntry, CommandMentionList, createHostedList, NoteMentionList } from "../../react/NoteAutocomplete";
/** The editor a list for a plugin's marker is created for. */
type HostEditor = Parameters<NonNullable<SlashCommandConfig["list"]>>[0];
-/** The least width of an {@link createAutocompleteMentionList} list, whose caret anchor has none. */
-const AUTOCOMPLETE_MENTION_MIN_WIDTH = 220;
-
/**
* Lists the notes for the query typed after `@` as the note autocomplete does, for the editor config's
* `mention.hostedFeeds`, and mentions the note picked as a reference link.
@@ -28,7 +23,7 @@ export function createNoteMentionList({ allowCreatingNotes, preselect, getParent
*/
getParentNotePath?(): string | null | undefined;
} = {}): MentionHostedList {
- return createHostedList((state, list) => (
+ return createHostedList<MentionHostedListState>((state, list) => (
<NoteMentionList
{...list}
query={state.query}
@@ -52,12 +47,11 @@ export function createAutocompleteMentionList({ source, renderItem, toMention }:
renderItem?(item: string): ComponentChildren;
toMention(item: string): MentionFeedObjectItem;
}): MentionHostedList {
- return createHostedList((state, list) => (
+ return createHostedList<MentionHostedListState>((state, list) => (
<AutocompleteList
{...list}
query={state.query}
source={source}
- minWidth={AUTOCOMPLETE_MENTION_MIN_WIDTH}
renderItem={renderItem}
onPick={(item) => state.commit(toMention(item))}
/>
@@ -72,7 +66,7 @@ export function createSlashCommandList(editor: HostEditor): MentionHostedList {
const palette = editor.plugins.get("TriliumSlashCommands") as TriliumSlashCommands;
const source = async (query: string) => palette.search(query).map(toCommandEntry);
- return createHostedList((state, list) => (
+ return createHostedList<MentionHostedListState>((state, list) => (
<CommandMentionList<SlashCommandEntry>
{...list}
query={state.query}
@@ -91,7 +85,7 @@ export function createEmojiList(editor: HostEditor): MentionHostedList {
const emoji = editor.plugins.get("TriliumEmojiMention") as TriliumEmojiMention;
const source = async (query: string) => emoji.search(query).map(toEmojiEntry);
- return createHostedList((state, list) => (
+ return createHostedList<MentionHostedListState>((state, list) => (
<CommandMentionList<EmojiEntry>
{...list}
query={state.query}
@@ -101,44 +95,6 @@ export function createEmojiList(editor: HostEditor): MentionHostedList {
));
}
-/** What a list drawn by {@link createHostedList} is given to draw itself with. */
-interface HostedListProps {
- /** At the caret, placed again each time the query changes. */
- anchor: ReferenceElement;
- handleRef: MutableRef<AutocompleteListHandle | null>;
- elementRef(element: HTMLElement | null): void;
-}
-
-/**
- * A {@link MentionHostedList} that renders what `draw` returns for each query, and forwards the
- * editor's keys to it.
- */
-function createHostedList(draw: (state: MentionHostedListState, list: HostedListProps) => VNode): MentionHostedList {
- const container = document.createElement("div");
- const handleRef: { current: AutocompleteListHandle | null } = { current: null };
- let element: HTMLElement | null = null;
- const elementRef = (el: HTMLElement | null) => { element = el; };
- const unmount = () => {
- render(null, container);
- element = null;
- };
-
- return {
- show(state) {
- // A new anchor each time, so the list is placed again at the caret. Its `contextElement`
- // places it again as the containers around the editor scroll.
- const anchor = { getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined };
- render(draw(state, { anchor, handleRef, elementRef }), container);
- },
- hide: unmount,
- handleKeyDown: (e) => handleRef.current?.handleKeyDown(e) ?? false,
- get element() {
- return element;
- },
- destroy: unmount
- };
-}
-
type SlashCommandEntry = CommandEntry & { definition: SlashCommandDefinition };
/** What the palette commits for an entry, which `TriliumSlashCommands` then runs. */
diff --git a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html
index 5fc171bb8c..5f52288da2 100644
--- a/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html
+++ b/apps/server/src/assets/doc_notes/en/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.html
@@ -97,9 +97,11 @@
operators, values, and notes after <code>@</code>. Keywords such as <code>and</code>, <code>or</code>, <code>not</code>, <code>orderBy</code> and <code>limit</code> appear
only on <kbd>Ctrl</kbd>+<kbd>Space</kbd>, since a plain word is usually
a search term.</p>
-<p>No suggestion is selected when the list opens, so <kbd>Enter</kbd> runs
+<p>No suggestion is selected when a list opens on its own, so <kbd>Enter</kbd> runs
the search as typed. To insert a suggestion, select it with <kbd>Down</kbd> and
- press <kbd>Enter</kbd>.</p>
+ press <kbd>Enter</kbd>. The list opened with <kbd>Ctrl</kbd>+<kbd>Space</kbd> and
+ the notes after <code>@</code> open on the best match instead, so <kbd>Enter</kbd> inserts
+ it.</p>
<p>The autocomplete offers:</p>
<ul>
<li>
@@ -113,10 +115,9 @@
<p>Contextual enumerations such as <code>note.type = "</code> or <code>note.mime = "</code>.</p>
</li>
<li>
- <p><a href="#root/_help_HI6GBBIduIgv">Label</a> names by typing <code>#</code>,
- with user-defined ones shown first.</p>
+ <p><a href="#root/_help_HI6GBBIduIgv">Label</a> names by typing <code>#</code>.</p>
<ul>
- <li>A gear icon indicates system attributes.</li>
+ <li>A small gear on the name's icon indicates a system attribute.</li>
<li>After typing the label name, the value is also autocompleted with values
that are present in the database.</li>
</ul>
diff --git a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
index 3374ff06e9..abdca5d65d 100644
--- a/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
+++ b/docs/User Guide/User Guide/Basic Concepts and Features/Navigation/Search.md
@@ -52,16 +52,16 @@ To help with the syntax, Trilium offers an autocomplete functionality which can
Some suggestions also open on their own as you type: label and relation names after `#` and `~`, fields after `.`, operators, values, and notes after `@`. Keywords such as `and`, `or`, `not`, `orderBy` and `limit` appear only on <kbd>Ctrl</kbd>+<kbd>Space</kbd>, since a plain word is usually a search term.
-No suggestion is selected when the list opens, so <kbd>Enter</kbd> runs the search as typed. To insert a suggestion, select it with <kbd>Down</kbd> and press <kbd>Enter</kbd>.
+No suggestion is selected when a list opens on its own, so <kbd>Enter</kbd> runs the search as typed. To insert a suggestion, select it with <kbd>Down</kbd> and press <kbd>Enter</kbd>. The list opened with <kbd>Ctrl</kbd>+<kbd>Space</kbd> and the notes after `@` open on the best match instead, so <kbd>Enter</kbd> inserts it.
The autocomplete offers:
* Basic operators such as `*=` and keywords (`limit`, `not`).
* Fields for object-like fields such as `note` or `~relation`, triggered by typing `.`.
* Contextual enumerations such as `note.type = "` or `note.mime = "`.
-* [Label](../../Advanced%20Usage/Attributes/Labels.md) names by typing `#`, with user-defined ones shown first.
+* [Label](../../Advanced%20Usage/Attributes/Labels.md) names by typing `#`.
- * A gear icon indicates system attributes.
+ * A small gear on the name's icon indicates a system attribute.
* After typing the label name, the value is also autocompleted with values that are present in the database.
* [Relation](../../Advanced%20Usage/Attributes/Relations.md) names by typing `~`.
* [Note ID](../../Advanced%20Usage/Note%20ID.md)s can be inserted easily by typing `@` and looking for a note.
diff --git a/packages/codemirror/src/extensions/hosted_completion.spec.ts b/packages/codemirror/src/extensions/hosted_completion.spec.ts
new file mode 100644
index 0000000000..82be7dcfab
--- /dev/null
+++ b/packages/codemirror/src/extensions/hosted_completion.spec.ts
@@ -0,0 +1,252 @@
+import { EditorSelection } from "@codemirror/state";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { createFieldEditor, type FieldEditor, type FieldEditorConfig } from "../field_editor.js";
+import { hostedCompletion, type HostedCompletionList, type HostedCompletionState } from "./hosted_completion.js";
+
+let editor: FieldEditor | undefined;
+
+afterEach(() => {
+ editor?.destroy();
+ editor = undefined;
+ vi.restoreAllMocks();
+});
+
+interface TestMatch {
+ from: number;
+ query: string;
+ explicit: boolean;
+}
+
+/**
+ * An `@` where a value can stand, the query running to whitespace, as the search field has it; and
+ * when asked explicitly, the word before the caret, empty as it can be.
+ */
+function match(before: string, explicit: boolean): TestMatch | null {
+ const mention = /(?:^|\s)@([^\s@]*)$/.exec(before);
+ if (mention) {
+ const from = before.length - mention[1].length - 1;
+ return { from, query: mention[1], explicit };
+ }
+
+ const word = /\w*$/.exec(before)?.[0] ?? "";
+ return explicit ? { from: before.length - word.length, query: word, explicit } : null;
+}
+
+describe("hostedCompletion", () => {
+ it("shows what matches before the caret as it changes, and hides the list once nothing does", async () => {
+ const { list, shown } = build();
+
+ type("#book @");
+ await vi.waitFor(() => expect(shown()?.match.query).toBe(""));
+ expect(shown()?.editable).toBe(editor?.dom);
+
+ type("Fo");
+ await vi.waitFor(() => expect(shown()?.match.query).toBe("Fo"));
+ expect(list.show).toHaveBeenCalledTimes(2);
+
+ // Neither a selection change that keeps the text before the caret nor an empty update shows
+ // it again.
+ editor?.dispatch({ selection: EditorSelection.cursor(9) });
+ editor?.dispatch({});
+ await settle();
+ expect(list.show).toHaveBeenCalledTimes(2);
+
+ type(" ");
+ expect(list.hide).toHaveBeenCalledOnce();
+
+ // Neither inside a word nor over a selection.
+ type("#foo@");
+ // Set while blurred: happy-dom reports a range set in a focused editor during the update.
+ editor?.contentDOM.blur();
+ editor?.dispatch({ changes: { from: 0, insert: "@" }, selection: EditorSelection.range(0, 1) });
+ editor?.focus();
+ await settle();
+ expect(list.show).toHaveBeenCalledTimes(2);
+ });
+
+ it("puts what the list commits in place of the match, and reads the result again as typing", async () => {
+ const { list, shown } = build({ doc: "#book\n" });
+
+ // Typed faster than the list is shown, the older text is never shown.
+ type("@F");
+ type("o");
+ await vi.waitFor(() => expect(shown()?.match.query).toBe("Fo"));
+ expect(list.show).toHaveBeenCalledOnce();
+ // On the second line, the match starts past the first.
+ shown()?.commit("abc123");
+
+ expect(editor?.state.doc.toString()).toBe("#book\nabc123");
+ expect(editor?.state.selection.main.head).toBe(12);
+ expect(list.hide).toHaveBeenCalledOnce();
+
+ // The list it was shown for has closed, so a late commit changes nothing.
+ shown()?.commit("def456");
+ expect(editor?.state.doc.toString()).toBe("#book\nabc123");
+
+ // A commit that leaves something to complete opens the list on it.
+ type(" @Ba");
+ await vi.waitFor(() => expect(shown()?.match.query).toBe("Ba"));
+ const before = shown();
+ shown()?.commit("x @");
+ await vi.waitFor(() => expect(shown()).not.toBe(before));
+ expect(shown()?.match.query).toBe("");
+ expect(editor?.state.doc.toString()).toBe("#book\nabc123 x @");
+
+ // An edit before an open list's match shows it again, and its commit lands on the match.
+ const moved = shown();
+ editor?.dispatch({ changes: { from: 0, insert: "~author " } });
+ await vi.waitFor(() => expect(shown()).not.toBe(moved));
+ shown()?.commit("def456");
+ expect(editor?.state.doc.toString()).toBe("~author #book\nabc123 x def456");
+ });
+
+ it("forwards the keys to the open list, which takes them from the field", async () => {
+ const onArrowDown = vi.fn(() => true);
+ const { list, shown } = build({ onArrowDown });
+
+ // Closed, the field has the key.
+ expect(press("ArrowDown")).toBe(true);
+ expect(onArrowDown).toHaveBeenCalledOnce();
+
+ type("@");
+ await vi.waitFor(() => expect(shown()).toBeDefined());
+ vi.mocked(list.handleKeyDown).mockReturnValueOnce(true);
+ expect(press("ArrowDown")).toBe(true);
+ expect(onArrowDown).toHaveBeenCalledOnce();
+
+ // A key the list declines reaches the field, and so does any while an IME composes.
+ expect(press("ArrowDown")).toBe(true);
+ expect(onArrowDown).toHaveBeenCalledTimes(2);
+ vi.mocked(list.handleKeyDown).mockClear();
+ press("ArrowDown", { isComposing: true });
+ expect(list.handleKeyDown).not.toHaveBeenCalled();
+ });
+
+ it("closes on Escape for that match alone, and leaves Escape to the field while the list shows nothing", async () => {
+ const onEscape = vi.fn(() => true);
+ const { list, shown, setElement } = build({ onEscape });
+
+ type("@");
+ await vi.waitFor(() => expect(shown()).toBeDefined());
+ expect(press("Escape")).toBe(true);
+ expect(onEscape).toHaveBeenCalledOnce();
+ expect(list.hide).not.toHaveBeenCalled();
+
+ setElement(document.createElement("div"));
+ expect(press("Escape")).toBe(true);
+ expect(onEscape).toHaveBeenCalledOnce();
+ expect(list.hide).toHaveBeenCalledOnce();
+
+ // Typing on in the same match, even past an edit before it, leaves it closed.
+ type("Fo");
+ editor?.dispatch({ changes: { from: 0, insert: "#book " } });
+ await settle();
+ expect(list.show).toHaveBeenCalledOnce();
+
+ // Another match opens it again.
+ type(" @");
+ await vi.waitFor(() => expect(list.show).toHaveBeenCalledTimes(2));
+ expect(shown()?.match.query).toBe("");
+ });
+
+ it("asks for an explicit match on Ctrl-Space or Alt-`, until the list closes", async () => {
+ const { list, shown, setElement } = build();
+
+ type("#book bo");
+ await settle();
+ expect(list.show).not.toHaveBeenCalled();
+
+ expect(press(" ", { ctrlKey: true })).toBe(true);
+ await vi.waitFor(() => expect(shown()?.match).toEqual({ from: 6, query: "bo", explicit: true }));
+
+ // Asked for while the list is open, or closed with Escape, it shows the list again.
+ expect(press("`", { altKey: true })).toBe(true);
+ await vi.waitFor(() => expect(list.show).toHaveBeenCalledTimes(2));
+ setElement(document.createElement("div"));
+ press("Escape");
+ expect(list.hide).toHaveBeenCalledOnce();
+ press(" ", { ctrlKey: true });
+ await vi.waitFor(() => expect(list.show).toHaveBeenCalledTimes(3));
+
+ // Once the list closes, typing alone offers nothing again, past the word it closed on too.
+ press("Escape");
+ type(" x");
+ await settle();
+ expect(list.show).toHaveBeenCalledTimes(3);
+ });
+
+ it("closes as the editor loses the focus, and takes the list down with it", async () => {
+ const { list, shown } = build();
+
+ type("@Fo");
+ await vi.waitFor(() => expect(shown()).toBeDefined());
+ editor?.contentDOM.blur();
+ await vi.waitFor(() => expect(list.hide).toHaveBeenCalledOnce());
+
+ editor?.destroy();
+ editor = undefined;
+ expect(list.destroy).toHaveBeenCalledOnce();
+ });
+
+ it("places the list at the caret, or at the editor where the caret has no place on screen", async () => {
+ const { shown } = build();
+ type("@");
+ await vi.waitFor(() => expect(shown()).toBeDefined());
+ const view = editor;
+ if (!view) throw new Error("expected an editor");
+
+ vi.spyOn(view, "coordsAtPos").mockReturnValue({ left: 10, right: 11, top: 20, bottom: 36 });
+ expect(shown()?.caretRect()).toEqual(new DOMRect(10, 20, 1, 16));
+
+ vi.spyOn(view, "coordsAtPos").mockReturnValue(null);
+ vi.spyOn(view.contentDOM, "getBoundingClientRect").mockReturnValue(new DOMRect(1, 2, 3, 4));
+ expect(shown()?.caretRect()).toEqual(new DOMRect(1, 2, 3, 4));
+ });
+});
+
+function build(config: Partial<FieldEditorConfig> = {}) {
+ let element: HTMLElement | null = null;
+ let state: HostedCompletionState<TestMatch> | undefined;
+ const list = {
+ show: vi.fn((shown: HostedCompletionState<TestMatch>) => { state = shown; }),
+ hide: vi.fn(),
+ handleKeyDown: vi.fn(() => false),
+ get element() { return element; },
+ destroy: vi.fn()
+ } satisfies HostedCompletionList<TestMatch>;
+
+ const parent = document.createElement("div");
+ document.body.appendChild(parent);
+ editor = createFieldEditor({
+ parent,
+ ...config,
+ extensions: [ hostedCompletion({ match, list: () => list }) ]
+ });
+ editor.focus();
+ editor.dispatch({ selection: EditorSelection.cursor(editor.state.doc.length) });
+
+ return {
+ list,
+ shown: () => state,
+ setElement: (el: HTMLElement | null) => { element = el; }
+ };
+}
+
+/** Types `text` at the caret, leaving the caret after it. */
+function type(text: string) {
+ const view = editor;
+ if (!view) throw new Error("expected an editor");
+ const from = view.state.selection.main.head;
+ view.dispatch({ changes: { from, insert: text }, selection: EditorSelection.cursor(from + text.length) });
+}
+
+/** Waits out the measure pass the list is shown in, so a list that was not shown is known not to be. */
+function settle() {
+ return new Promise((resolve) => setTimeout(resolve, 50));
+}
+
+/** Presses a key on the editor and answers whether a binding handled it. */
+function press(key: string, init: KeyboardEventInit = {}) {
+ return !editor?.contentDOM.dispatchEvent(new KeyboardEvent("keydown", { key, bubbles: true, cancelable: true, ...init }));
+}
diff --git a/packages/codemirror/src/extensions/hosted_completion.ts b/packages/codemirror/src/extensions/hosted_completion.ts
new file mode 100644
index 0000000000..3c7d8bec72
--- /dev/null
+++ b/packages/codemirror/src/extensions/hosted_completion.ts
@@ -0,0 +1,213 @@
+import { type EditorState, type Extension, Prec } from "@codemirror/state";
+import { EditorView, ViewPlugin, type ViewUpdate } from "@codemirror/view";
+
+/** What {@link HostedCompletionConfig.match} finds before the caret. */
+export interface HostedCompletionMatch {
+ /** Where the text a pick replaces starts, as an offset into the text before the caret. */
+ from: number;
+}
+
+/** What a {@link HostedCompletionList} is shown for, each time the text before the caret changes. */
+export interface HostedCompletionState<M extends HostedCompletionMatch> {
+ match: M;
+ /** Where the caret is, in viewport coordinates. */
+ caretRect(): DOMRect;
+ /** The editor's element. A list anchored at {@link caretRect} watches the containers around it. */
+ editable: HTMLElement;
+ /** Replaces what stands between the match's `from` and the caret with `text`, as a pick does. */
+ commit(text: string): void;
+}
+
+/** A host's list for {@link hostedCompletion}. */
+export interface HostedCompletionList<M extends HostedCompletionMatch> {
+ show(state: HostedCompletionState<M>): void;
+ hide(): void;
+ /**
+ * Handles a key pressed in the editor while the list is open, other than Escape, which closes it.
+ * Returns whether the list took the key, which then reaches the editor no further.
+ */
+ handleKeyDown(event: KeyboardEvent): boolean;
+ /** The list's element while it shows entries. Escape closes the list only then. */
+ readonly element: HTMLElement | null;
+ destroy?(): void;
+}
+
+export interface HostedCompletionConfig<M extends HostedCompletionMatch> {
+ /**
+ * What can be completed at the caret, read from the text of the line before it, or `null` where
+ * nothing can. `explicit` is set after Ctrl-Space, which asks for completions where typing alone
+ * offers none.
+ */
+ match(before: string, explicit: boolean): M | null;
+ /** Creates the list, once per editor. */
+ list(view: EditorView): HostedCompletionList<M>;
+}
+
+/**
+ * Hands what can be completed at the caret to a list the host runs entirely: what it lists, how it
+ * draws it, which entry is highlighted and what a pick inserts. The editor keeps the focus, forwards
+ * its keys to the list while it is open and puts what the list commits in place of the text the
+ * match covers. A commit is read again like typing, so a pick that leaves something to complete,
+ * such as `note.`, opens the list on what follows it.
+ *
+ * The counterpart of CKEditor's `mention.hostedFeeds`, so that a host can serve both editors with
+ * the same lists. The list closes when nothing matches, when the editor loses the focus, and on
+ * Escape, after which it stays closed for that match.
+ */
+export function hostedCompletion<M extends HostedCompletionMatch>({ match, list }: HostedCompletionConfig<M>): Extension {
+ const plugin = ViewPlugin.fromClass(class {
+ private readonly list: HostedCompletionList<M>;
+ /** Where the open list's match starts in the document, or `-1` while it is closed. */
+ private from = -1;
+ /** The text before the caret the open list was shown for. */
+ private before = "";
+ /** Asked for with Ctrl-Space, until the list closes. */
+ private explicit = false;
+ /** Where the match Escape closed the list on starts, which keeps it closed. */
+ private dismissedAt = -1;
+
+ constructor(private readonly view: EditorView) {
+ this.list = list(view);
+ }
+
+ update(update: ViewUpdate) {
+ if (update.docChanged && this.dismissedAt >= 0) {
+ // With `assoc` 1, so text inserted right before the match leaves it on the match.
+ this.dismissedAt = update.changes.mapPos(this.dismissedAt, 1);
+ }
+
+ if (update.docChanged || update.selectionSet || update.focusChanged) {
+ this.sync();
+ }
+ }
+
+ handleKeyDown(event: KeyboardEvent) {
+ if (event.isComposing) {
+ return false;
+ }
+
+ if (isExplicitRequest(event)) {
+ this.explicit = true;
+ this.dismissedAt = -1;
+ this.from = -1;
+ this.sync();
+ } else if (this.from < 0) {
+ return false;
+ } else if (event.key === "Escape") {
+ // A list showing nothing leaves Escape to the field.
+ if (!this.list.element) {
+ return false;
+ }
+
+ this.dismissedAt = this.from;
+ this.close();
+ } else if (!this.list.handleKeyDown(event)) {
+ return false;
+ }
+
+ event.preventDefault();
+ return true;
+ }
+
+ destroy() {
+ this.list.hide();
+ this.list.destroy?.();
+ }
+
+ private sync() {
+ const found = this.view.hasFocus ? matchAt(this.view.state, match, this.explicit) : null;
+ if (found?.from !== this.dismissedAt) {
+ this.dismissedAt = -1;
+ }
+
+ if (!found || this.dismissedAt >= 0) {
+ this.close();
+ return;
+ }
+
+ if (found.from === this.from && found.before === this.before) {
+ return;
+ }
+
+ this.from = found.from;
+ this.before = found.before;
+ // Shown once the update is over: the list reads the caret's place, which CodeMirror does
+ // not allow during one.
+ this.view.requestMeasure({
+ read: () => null,
+ write: () => {
+ // A later update has replaced or closed the list meanwhile.
+ if (this.from !== found.from || this.before !== found.before) return;
+
+ this.list.show({
+ match: found.match,
+ caretRect: () => caretRect(this.view),
+ editable: this.view.dom,
+ commit: (text) => this.commit(found.from, text)
+ });
+ }
+ });
+ }
+
+ private commit(from: number, text: string) {
+ if (this.from !== from) {
+ return;
+ }
+
+ this.explicit = false;
+ this.view.dispatch({
+ changes: { from, to: this.view.state.selection.main.head, insert: text },
+ selection: { anchor: from + text.length },
+ userEvent: "input.complete"
+ });
+ }
+
+ private close() {
+ this.explicit = false;
+ if (this.from < 0) {
+ return;
+ }
+
+ this.from = -1;
+ this.before = "";
+ this.list.hide();
+ }
+ }, {
+ eventHandlers: {
+ keydown(event) {
+ return this.handleKeyDown(event);
+ }
+ }
+ });
+
+ // Ahead of the field's keymap, so the list takes Enter and the arrows while it is open.
+ return Prec.highest(plugin);
+}
+
+/** Ctrl-Space, or Alt-` as CodeMirror binds it on a Mac, where Ctrl-Space switches the input source. */
+function isExplicitRequest(event: KeyboardEvent) {
+ return (event.ctrlKey && event.key === " ") || (event.altKey && event.key === "`");
+}
+
+/** What `match` finds before the caret, with where it starts in the document. */
+function matchAt<M extends HostedCompletionMatch>(state: EditorState, match: HostedCompletionConfig<M>["match"], explicit: boolean) {
+ const { main } = state.selection;
+ if (!main.empty) {
+ return null;
+ }
+
+ const line = state.doc.lineAt(main.head);
+ const before = line.text.slice(0, main.head - line.from);
+ const found = match(before, explicit);
+
+ return found && { match: found, from: line.from + found.from, before };
+}
+
+function caretRect(view: EditorView) {
+ const coords = view.coordsAtPos(view.state.selection.main.head);
+ if (!coords) {
+ return view.contentDOM.getBoundingClientRect();
+ }
+
+ return new DOMRect(coords.left, coords.top, coords.right - coords.left, coords.bottom - coords.top);
+}
diff --git a/packages/codemirror/src/field_editor.spec.ts b/packages/codemirror/src/field_editor.spec.ts
index bd79cceb41..ed96d13900 100644
--- a/packages/codemirror/src/field_editor.spec.ts
+++ b/packages/codemirror/src/field_editor.spec.ts
@@ -1,4 +1,3 @@
-import { completionStatus, startCompletion } from "@codemirror/autocomplete";
import { EditorSelection } from "@codemirror/state";
import { afterEach, describe, expect, it, vi } from "vitest";
@@ -50,7 +49,7 @@ describe("createFieldEditor", () => {
expect(onChange).toHaveBeenLastCalledWith("#book\n and #author\n ");
});
- it("answers ArrowDown and Escape once the completion popup has passed them on", () => {
+ it("answers ArrowDown and Escape, which then reach the caret no further", () => {
const onArrowDown = vi.fn().mockReturnValue(true);
const onEscape = vi.fn().mockReturnValue(true);
editor = build({ doc: "#book\n#year", onArrowDown, onEscape });
@@ -76,60 +75,6 @@ describe("createFieldEditor", () => {
expect(editor.state.selection.main.head).toBeGreaterThan(0);
});
- it("leaves ArrowDown and Escape to the completion popup while it is open", async () => {
- const onArrowDown = vi.fn().mockReturnValue(true);
- const onEscape = vi.fn().mockReturnValue(true);
- const view = build({
- doc: "#b",
- completionSource: () => ({ from: 0, options: [ { label: "#book" }, { label: "#borrowed" } ] }),
- onArrowDown,
- onEscape
- });
- editor = view;
- view.dispatch({ selection: EditorSelection.cursor(2) });
-
- // The popup drops both keys for `interactionDelay` after it opens; neither reaches the
- // field in that window, since the field's own commands move focus out of the editor.
- await openCompletion(view);
- pressKey(view, "ArrowDown");
- expect(onArrowDown).not.toHaveBeenCalled();
-
- await openCompletion(view);
- pressKey(view, "Escape");
- expect(onEscape).not.toHaveBeenCalled();
-
- // Closed, so the field gets both keys back.
- expect(completionStatus(view.state)).toBe(null);
- pressKey(view, "ArrowDown");
- pressKey(view, "Escape");
- expect(onArrowDown).toHaveBeenCalledOnce();
- expect(onEscape).toHaveBeenCalledOnce();
- });
-
- it("selects no completion on opening, so Enter runs the field's command until one is picked", async () => {
- const onEnter = vi.fn();
- const view = build({
- doc: "a",
- completionSource: () => ({ from: 0, options: [ { label: "and" }, { label: "asc" } ] }),
- onEnter
- });
- editor = view;
- view.dispatch({ selection: EditorSelection.cursor(1) });
-
- await openCompletion(view);
- await waitOutInteractionDelay();
- pressKey(view, "Enter");
- expect(onEnter).toHaveBeenCalledOnce();
- expect(view.state.doc.toString()).toBe("a");
-
- await openCompletion(view);
- await waitOutInteractionDelay();
- pressKey(view, "ArrowDown");
- pressKey(view, "Enter");
- expect(onEnter).toHaveBeenCalledOnce();
- expect(view.state.doc.toString()).toBe("and");
- });
-
it("holds a single-line field to one line, flattening the breaks in what is inserted", () => {
const onChange = vi.fn();
editor = build({ singleLine: true, onChange });
@@ -173,65 +118,6 @@ describe("createFieldEditor", () => {
expect(editor.contentDOM.getAttribute("aria-label")).toBe("Search string");
});
- it("draws a completion with the icon the consumer answers for it", async () => {
- const view = build({
- doc: "#b",
- completionSource: () => ({ from: 0, options: [ { label: "#book" }, { label: "#borrowed" } ] }),
- completionIcon: (completion) => completion.label === "#book" ? "bx bx-hash" : undefined
- });
- editor = view;
- view.dispatch({ selection: EditorSelection.cursor(2) });
-
- await openCompletion(view);
-
- // The option answering nothing is drawn without a glyph, rather than with an empty one.
- const glyphs = Array.from(document.querySelectorAll(".cm-tooltip-autocomplete li"))
- .map((option) => option.querySelector(".cm-completion-glyph"));
- expect(glyphs.map((glyph) => glyph?.className)).toEqual([ "cm-completion-glyph bx bx-hash", undefined ]);
- expect(glyphs[0]?.getAttribute("aria-hidden")).toBe("true");
- // Supplying the icons replaces CodeMirror's own.
- expect(document.querySelector(".cm-completionIcon")).toBe(null);
- });
-
- it("draws a completion whole where the consumer renders it, and classes the popup", async () => {
- const view = build({
- doc: "#b",
- completionSource: () => ({ from: 0, options: [ { label: "#book" }, { label: "#borrowed", detail: "Lent" } ] }),
- completionIcon: () => "bx bx-hash",
- renderCompletion: (completion) => {
- if (completion.label !== "#borrowed") return null;
- const element = document.createElement("span");
- element.textContent = "Borrowed";
- return element;
- },
- completionClasses: { popup: "my-menu", option: "my-item" }
- });
- editor = view;
- view.dispatch({ selection: EditorSelection.cursor(2) });
-
- await openCompletion(view);
-
- const popup = document.querySelector(".cm-tooltip-autocomplete");
- expect(popup?.classList.contains("my-menu")).toBe(true);
- const [ book, borrowed ] = Array.from(popup?.querySelectorAll("li") ?? []);
- expect(book.classList.contains("my-item")).toBe(true);
- expect(borrowed.classList.contains("my-item")).toBe(true);
-
- // A completion the consumer renders nothing for keeps its icon and label.
- expect(book.querySelector(".cm-completion-glyph")).not.toBe(null);
- expect(book.querySelector(".cm-completionLabel")?.textContent).toBe("#book");
-
- // The rendered one replaces the icon, and the label and detail after it are hidden.
- const whole = borrowed.querySelector("[data-completion-whole]");
- expect(whole?.textContent).toBe("Borrowed");
- expect(borrowed.querySelector(".cm-completion-glyph")).toBe(null);
- // The test DOM does not apply the editor's injected styles, so the rule is looked up instead.
- expect(borrowed.querySelector(".cm-completionLabel")).not.toBe(null);
- expect(borrowed.querySelector(".cm-completionDetail")).not.toBe(null);
- const rules = Array.from(document.querySelectorAll("style"), (style) => style.textContent).join("\n");
- expect(rules).toMatch(/\.ͼ\w+ \[data-completion-whole\] ~ \.cm-completionLabel, \.ͼ\w+ \[data-completion-whole\] ~ \.cm-completionDetail\s*\{\s*display: none/);
- });
-
it("keeps the line breaks in inserted text", () => {
const onChange = vi.fn();
editor = build({ onChange });
@@ -249,17 +135,6 @@ function build(config: Partial<FieldEditorConfig> = {}): FieldEditor {
return createFieldEditor({ parent, ...config });
}
-/** Opens the completion popup and waits until it is showing. */
-async function openCompletion(view: FieldEditor) {
- startCompletion(view);
- await vi.waitFor(() => expect(completionStatus(view.state)).toBe("active"));
-}
-
-/** The popup drops the keys pressed within `interactionDelay` (75ms by default) of opening. */
-function waitOutInteractionDelay() {
- return new Promise((resolve) => setTimeout(resolve, 100));
-}
-
/** Presses a key on the editor and answers whether a binding handled it. */
function pressKey(editor: FieldEditor, key: string, init: KeyboardEventInit = {}) {
return !editor.contentDOM.dispatchEvent(new KeyboardEvent("keydown", {
diff --git a/packages/codemirror/src/field_editor.ts b/packages/codemirror/src/field_editor.ts
index 72ce53a69c..337018ed1f 100644
--- a/packages/codemirror/src/field_editor.ts
+++ b/packages/codemirror/src/field_editor.ts
@@ -1,14 +1,7 @@
-import { autocompletion, type Completion, completionStatus, type CompletionSource } from "@codemirror/autocomplete";
import { history, historyKeymap, standardKeymap } from "@codemirror/commands";
import { ChangeSet, type ChangeSpec, EditorState, type Extension } from "@codemirror/state";
import { EditorView, keymap, placeholder } from "@codemirror/view";
-/**
- * The types a consumer needs to write a {@link FieldEditorConfig.completionSource}, re-exported
- * so it does not have to depend on `@codemirror/autocomplete` itself.
- */
-export type { Completion, CompletionContext, CompletionResult, CompletionSource } from "@codemirror/autocomplete";
-
export interface FieldEditorConfig {
parent: HTMLElement;
/** Text the editor starts with. */
@@ -16,30 +9,11 @@ export interface FieldEditorConfig {
placeholder?: string;
/** Names the field for assistive technology, where a placeholder is a hint rather than a name. */
ariaLabel?: string;
- /** Extra extensions, such as a highlighter for whatever syntax the value holds. */
- extensions?: Extension[];
- /** Completions to offer as the value is typed. Without one, the editor has no autocompletion. */
- completionSource?: CompletionSource;
/**
- * The icon classes a completion is drawn with, such as `bx bx-hash`. Completions it answers
- * nothing for are drawn without one; supplying it at all replaces CodeMirror's own icons.
+ * Extra extensions, such as a highlighter for whatever syntax the value holds, or the
+ * completions of `hostedCompletion()`.
*/
- completionIcon?(completion: Completion): string | undefined;
- /**
- * Draws a completion whole, in place of its icon, label and detail, for one that needs more
- * than a line of text. Completions it answers `null` for are drawn as usual.
- */
- renderCompletion?(completion: Completion): HTMLElement | null;
- /**
- * Classes for the completion popup and for each of its options, so the host can draw the popup
- * as one of its own menus.
- */
- completionClasses?: { popup: string; option: string };
- /**
- * Whether picking a completion reopens the popup on what follows it, for one that inserts an
- * opening rather than a finished value.
- */
- activateOnCompletion?(completion: Completion): boolean;
+ extensions?: Extension[];
/**
* Whether the value is confined to one line, the way an input is: Shift-Enter does nothing and
* a line break in inserted text becomes a space. Long values scroll sideways instead of
@@ -51,11 +25,11 @@ export interface FieldEditorConfig {
/** Runs when Enter is pressed; Shift-Enter inserts a line break, unless {@link singleLine}. */
onEnter?(): void;
/**
- * Runs when ArrowDown is pressed and no completion is open or pending, for a field whose
- * results are listed below it. Returns whether the key was taken; `false` moves the caret.
+ * Runs when ArrowDown is pressed, for a field whose results are listed below it. Returns whether
+ * the key was taken; `false` moves the caret.
*/
onArrowDown?(): boolean;
- /** Runs when Escape is pressed and no completion is open or pending. Returns as {@link onArrowDown}. */
+ /** Runs when Escape is pressed. Returns as {@link onArrowDown}. */
onEscape?(): boolean;
}
@@ -65,16 +39,13 @@ export type FieldEditor = EditorView;
/**
* Builds a CodeMirror editor for a form field's value: text editing, undo history and wrapped
* display, and nothing else — no gutter and no language. Highlighting and completion are the
- * consumer's to supply, through `extensions` and `completionSource`.
+ * consumer's to supply, through `extensions`.
*
* Enter runs `onEnter` instead of inserting a line break, so the field answers the key the way an
* input does. Shift-Enter, which `standardKeymap` binds to `insertNewlineAndIndent`, breaks the
* line and keeps its indentation, for a value the user lays out over several of them; `singleLine`
- * holds the value to one line instead.
- *
- * `onArrowDown` and `onEscape` run only while no completion is open or pending, so a key the popup
- * drops does not move focus out of the editor instead. An IME keeps Enter for as long as it is
- * composing.
+ * holds the value to one line instead. An extension at a higher precedence, such as an open
+ * completion list, takes these keys first. An IME keeps them for as long as it is composing.
*
* It sits apart from the editor in `index.ts` so a consumer that wants a plain input does not
* load the language, theme and completion machinery a code note needs.
@@ -97,8 +68,8 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {
// Swallowed rather than left to `insertNewlineAndIndent`, whose line break and
// indentation `flattenToOneLine` would otherwise turn into stray spaces.
...(config.singleLine ? [ { key: "Shift-Enter", run: () => true } ] : []),
- { key: "ArrowDown", run: (view) => keyBelongsToField(view) && !!config.onArrowDown?.() },
- { key: "Escape", run: (view) => keyBelongsToField(view) && !!config.onEscape?.() },
+ { key: "ArrowDown", run: (view) => !view.composing && !!config.onArrowDown?.() },
+ { key: "Escape", run: (view) => !view.composing && !!config.onEscape?.() },
...standardKeymap,
...historyKeymap
]),
@@ -119,28 +90,6 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {
extensions.push(EditorView.contentAttributes.of({ "aria-label": config.ariaLabel }));
}
- if (config.completionSource) {
- const { completionIcon: icon, renderCompletion, completionClasses } = config;
-
- // The completion keymap is registered at the highest precedence, so Enter picks the
- // selected option while the popup is open and reaches `onEnter` the rest of the time.
- // Nothing is selected as the popup opens, so Enter on a plain search term runs the search
- // instead of completing the term; ArrowDown selects an option first.
- extensions.push(autocompletion({
- override: [ config.completionSource ],
- activateOnTyping: true,
- selectOnOpen: false,
- activateOnCompletion: config.activateOnCompletion,
- icons: !icon && !renderCompletion,
- addToOptions: icon || renderCompletion ? [ {
- position: ICON_POSITION,
- render: (completion) => markWhole(renderCompletion?.(completion)) ?? renderIcon(icon?.(completion))
- } ] : [],
- tooltipClass: completionClasses && (() => completionClasses.popup),
- optionClass: completionClasses && (() => completionClasses.option)
- }), wholeCompletionTheme);
- }
-
return new EditorView({
parent: config.parent,
doc: config.doc ?? "",
@@ -171,47 +120,3 @@ const flattenToOneLine = EditorState.transactionFilter.of((tr) => {
scrollIntoView: tr.scrollIntoView
};
});
-
-/**
- * Whether a navigation key the completion popup declined belongs to the field. The popup drops
- * ArrowDown and Escape for `interactionDelay` after it opens, and a key dropped that way must not
- * reach {@link FieldEditorConfig.onArrowDown}, which moves focus out of the editor entirely.
- */
-function keyBelongsToField(view: EditorView) {
- return !view.composing && completionStatus(view.state) === null;
-}
-
-/** Where CodeMirror draws its own icons, which {@link FieldEditorConfig.completionIcon} takes over. */
-const ICON_POSITION = 20;
-
-/**
- * Marks what {@link FieldEditorConfig.renderCompletion} draws, so the label and detail after it are
- * hidden. An attribute rather than a class, so the host's rules for a class-less element still apply.
- */
-const WHOLE_COMPLETION_ATTRIBUTE = "data-completion-whole";
-
-const wholeCompletionTheme = EditorView.baseTheme({
- // Two selectors rather than an `:is()`: the theme scopes each part of a list split at its commas.
- [`[${WHOLE_COMPLETION_ATTRIBUTE}] ~ .cm-completionLabel, [${WHOLE_COMPLETION_ATTRIBUTE}] ~ .cm-completionDetail`]: {
- display: "none"
- }
-});
-
-function markWhole(element: HTMLElement | null | undefined) {
- element?.setAttribute(WHOLE_COMPLETION_ATTRIBUTE, "");
-
- return element;
-}
-
-function renderIcon(classes: string | undefined) {
- if (!classes) {
- return null;
- }
-
- const element = document.createElement("span");
- element.className = `cm-completion-glyph ${classes}`;
- // The label beside it already says what the icon repeats.
- element.setAttribute("aria-hidden", "true");
-
- return element;
-}