Build your personal knowledge base with Trilium Notes
TypeScript electronelectron-appknowledge-baseknowledge-graphknowledge-managementknowledge-management-graphlocal-firstnote-managmentnote-takernote-takingnotebooknotesnotes-apppersonal-knowledge-basepersonal-wikiscriptableself-hostedself-hostingwiki
style(search): draw the completions as the note autocomplete's menu
Elian Doran61a5f3089520
diff --git a/apps/client/src/widgets/react/Menu.css b/apps/client/src/widgets/react/Menu.cssindex 6acccaa6f0..f7e5e7161f 100644--- a/apps/client/src/widgets/react/Menu.css+++ b/apps/client/src/widgets/react/Menu.css@@ -71,9 +71,10 @@ 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.+ * 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`.*/-.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, .submenu-open, :focus) {+.tn-menu-keyboard .dropdown-item:hover:not(.disabled, .active, .dropdown-container-item, .tn-menu-active, [aria-selected="true"], .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.tsxindex 4df242b91b..e1c70c8b10 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -19,7 +19,7 @@ import appContext from "../../components/app_context";import type { NoteSuggestionOptions, Suggestion } from "../../services/note_autocomplete";import { buildNote } from "../../test/easy-froca";import { renderInto } from "../../test/render";-import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps } from "./NoteAutocomplete";+import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, renderNoteSuggestion } from "./NoteAutocomplete";async function render(props: NoteAutocompleteProps = {}) {let container = document.createElement("div");@@ -208,6 +208,20 @@ 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/ribbon/search_completions.spec.ts b/apps/client/src/widgets/ribbon/search_completions.spec.tsindex c8e4d93f7c..6388b633d0 100644--- a/apps/client/src/widgets/ribbon/search_completions.spec.ts+++ b/apps/client/src/widgets/ribbon/search_completions.spec.ts@@ -3,7 +3,7 @@ import { beforeEach, describe, expect, it, vi } from "vitest";import server from "../../services/server";import { fetchAttributeNames } from "../attribute_widgets/attribute_detail";-import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./search_completions";+import { searchCompletionIcon, searchCompletionNote, searchCompletionReactivates, searchCompletionSource } 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 }));@@ -362,7 +362,6 @@ describe("note mentions", () => {// 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, "Foo")?.detail).toBe("Root / Foo");expect(optionFor(result, "Foobar")?.boost).toBeLessThan(optionFor(result, "Foo")?.boost ?? 0);// The `@` at 19 is rewritten along with the "Fo" after it.@@ -372,12 +371,17 @@ describe("note mentions", () => {});});- it("draws each note with its own icon", async () => {+ 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(searchCompletionIcon(optionFor(result, "Foo") ?? { label: "" })).toBe("bx bx-file");- expect(searchCompletionIcon(optionFor(result, "Foobar") ?? { label: "" })).toBe("bx bx-note");+ 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 () => {diff --git a/apps/client/src/widgets/ribbon/search_completions.ts b/apps/client/src/widgets/ribbon/search_completions.tsindex 195b116a4e..4b9e9f5fc5 100644--- a/apps/client/src/widgets/ribbon/search_completions.ts+++ b/apps/client/src/widgets/ribbon/search_completions.ts@@ -132,9 +132,9 @@ const VALUE_NEEDS_QUOTES = /[\s"'`\\#~().=*<>!%+,-]/;*/const RESERVED_VALUES = new Set([ "note", "now", "today", "month", "year" ]);-/** A completion drawn with an icon of its own, which {@link COMPLETION_ICONS} cannot supply. */+/** A completion for a note, drawn as a row of the note autocomplete from the result it carries. */interface NoteCompletion extends Completion {- noteIcon?: string;+ note: AutocompleteResult;}/**@@ -162,8 +162,7 @@ async function noteCompletions(term: string, atPos: number): Promise<CompletionRoptions.push({label: suggestion.noteTitle,- detail: suggestion.notePathTitle,- noteIcon: suggestion.icon,+ 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,@@ -235,13 +234,14 @@ const COMPLETION_ICONS: Record<string, string> = {/** The icon an option is drawn with. Only the attribute names carry one. */export function searchCompletionIcon(completion: Completion): string | undefined {- if ("noteIcon" in completion && typeof completion.noteIcon === "string") {- return completion.noteIcon;- }-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;+}+/*** 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.diff --git a/apps/client/src/widgets/search_field_editor.css b/apps/client/src/widgets/search_field_editor.cssindex 167060009e..955143678b 100644--- a/apps/client/src/widgets/search_field_editor.css+++ b/apps/client/src/widgets/search_field_editor.css@@ -34,16 +34,15 @@z-index: 1210;}- /* Outweighs CodeMirror's `&light .cm-tooltip`, which carries two classes. */+ /*+ * 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 {- font-size: 0.8125em;- background: var(--menu-background-color-no-backdrop, var(--main-background-color));- color: var(--menu-text-color, var(--main-text-color));- border: 1px solid var(--dropdown-border-color, var(--main-border-color));- border-radius: var(--dropdown-border-radius, var(--bs-border-radius));- box-shadow: 0 5px 10px rgba(0, 0, 0, var(--dropdown-shadow-opacity, 0.2));+ border-color: var(--dropdown-border-color);overflow: hidden;- padding: var(--suggestion-list-padding);/* CodeMirror sets monospace on the popup; the field itself is in the UI font. */& > ul {@@ -51,28 +50,26 @@max-height: 18em;}- /* A mention row's metrics, over the 1.84/13px line CKEditor gives `.ck-button__label`. */+ /* Bootstrap's row padding, which the Next theme overrides with `!important`. */& > ul > li {- display: flex;flex-wrap: wrap;- align-items: center;- padding: var(--suggestion-item-padding-block) var(--suggestion-item-padding-inline);- border-radius: 6px;- line-height: calc(1.84 * 13px);+ 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.4em;+ margin-inline-end: 0.5em;opacity: 0.7;}+ /* Matches the second line of a note row, `.search-result-attributes`. */.cm-completionDetail {flex-basis: 100%;margin-left: 0;- font-size: 0.75em;- line-height: 1.84;+ font-size: small;font-style: normal;- opacity: 0.75;+ color: var(--muted-text-color);overflow: hidden;text-overflow: ellipsis;}diff --git a/apps/client/src/widgets/search_field_editor.ts b/apps/client/src/widgets/search_field_editor.tsindex 4731e659e5..fdf3285796 100644--- a/apps/client/src/widgets/search_field_editor.ts+++ b/apps/client/src/widgets/search_field_editor.ts@@ -9,13 +9,15 @@ import type { SearchLintResponse } from "@triliumnext/commons";import froca from "../services/froca";import { t } from "../services/i18n";import server from "../services/server";-import { searchCompletionIcon, searchCompletionReactivates, searchCompletionSource } from "./ribbon/search_completions";+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" | "activateOnCompletion">;+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@@ -34,6 +36,17 @@ export function createSearchFieldEditor(config: SearchFieldEditorConfig): FieldE],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});}diff --git a/packages/codemirror/src/field_editor.spec.ts b/packages/codemirror/src/field_editor.spec.tsindex 00fedf24fb..bd79cceb41 100644--- a/packages/codemirror/src/field_editor.spec.ts+++ b/packages/codemirror/src/field_editor.spec.ts@@ -193,6 +193,45 @@ describe("createFieldEditor", () => {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 });diff --git a/packages/codemirror/src/field_editor.ts b/packages/codemirror/src/field_editor.tsindex fba57069f2..72ce53a69c 100644--- a/packages/codemirror/src/field_editor.ts+++ b/packages/codemirror/src/field_editor.ts@@ -25,6 +25,16 @@ export interface FieldEditorConfig {* nothing for are drawn without one; supplying it at all replaces CodeMirror's own icons.*/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.@@ -110,7 +120,7 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {}if (config.completionSource) {- const icon = config.completionIcon;+ 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.@@ -121,9 +131,14 @@ export function createFieldEditor(config: FieldEditorConfig): FieldEditor {activateOnTyping: true,selectOnOpen: false,activateOnCompletion: config.activateOnCompletion,- icons: !icon,- addToOptions: icon ? [ { position: ICON_POSITION, render: (completion) => renderIcon(icon(completion)) } ] : []- }));+ 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({@@ -169,6 +184,25 @@ function keyBelongsToField(view: EditorView) {/** 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;