Skip to content

Build your personal knowledge base with Trilium Notes

refactor(attributes): complete # and ~ names with the attribute panel's list

Elian Doranef74a9c18c56
diff --git a/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css b/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css
index da66f22e8e..ff7ee5a8a0 100644
--- a/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css
+++ b/apps/client/src/widgets/attribute_widgets/attribute_name_suggestion.css
@@ -1,11 +1,10 @@
/*
- * One row of an attribute name completion, shared by the detail popup's name field and by the `#`/`~`
- * completion in the inline attribute editor. Both list the very same names, so both mark the ones
- * Trilium attaches a meaning to in the same way.
+ * One row of an attribute name completion, shared by every list of attribute names: the detail
+ * popup's name field, the attributes panel's name box and the `#`/`~` completion in the inline
+ * attribute editor. All of them mark the names Trilium attaches a meaning to in the same way.
*
- * Deliberately not nested under a widget root: the popup portals its dropdown to the body and the
- * inline editor's panel lives in a CKEditor balloon, so neither row shares an ancestor with the
- * widget that spawned it.
+ * Not nested under a widget root: each list is portalled to the body, so no row shares an ancestor
+ * with the widget that spawned it.
*/
.attr-name-suggestion {
@@ -27,22 +26,7 @@
flex-shrink: 0;
}
-/*
- * The badge is sized relative to the row it sits in, and the popup's dropdown still carries a
- * slightly larger font than the mention panel does — so the same rule leaves the marker heavier
- * here. Nudged down so that the two lists read alike.
- */
+/* The badge is sized relative to the row, whose font the dropdown sets. */
.form-autocomplete-dropdown .attr-name-suggestion .ext-badge {
font-size: 0.65em;
}
-
-/*
- * The mention panel sizes its rows to their content, so without a width the markers would sit right
- * after each name and zig-zag down the list. The popup's dropdown takes the width of its input and
- * needs none of this.
- */
-.ck-mentions .ck.ck-button.attr-name-suggestion-button {
- display: flex;
- justify-content: flex-start;
- min-width: 220px;
-}
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index f8a64e67d6..c60027d1ac 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -2,7 +2,7 @@ import "./FormAutocomplete.css";
import type { ComponentChildren, RefObject } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
-import { useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
+import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
import FormTextBox from "./FormTextBox";
import { useUniqueName } from "./hooks";
@@ -18,6 +18,9 @@ const VIEWPORT_MARGIN = 8;
type FormTextBoxProps = Parameters<typeof FormTextBox>[0];
+/** What the dropdown is placed under: an element, or a rect such as a caret's. */
+type DropdownAnchor = Pick<Element, "getBoundingClientRect">;
+
interface FormAutocompleteProps extends Omit<FormTextBoxProps, "onChange"> {
currentValue: string;
onChange(newValue: string): void;
@@ -106,8 +109,11 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
const ownInputRef = useRef<HTMLInputElement>(null);
const inputEl = inputRef ?? ownInputRef;
const fieldRef = useRef<HTMLDivElement>(null);
- const [ position, setPosition ] = useState<CSSProperties>();
const isDisabled = !!(restProps.readOnly || restProps.disabled);
+ // The wrapper where there is one, so a field carrying chips is spanned whole.
+ const anchor = useMemo<DropdownAnchor>(() => ({
+ getBoundingClientRect: () => (fieldRef.current ?? inputEl.current)?.getBoundingClientRect() ?? new DOMRect()
+ }), [ inputEl ]);
const autocomplete = useAutocomplete({
query: currentValue,
@@ -121,31 +127,6 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
autoActivate,
isHeading
});
- const { isOpen, items, activeIndex, itemId, pick } = autocomplete;
-
- // Keep the dropdown glued to the input.
- useLayoutEffect(() => {
- if (!isOpen || !items.length) {
- return;
- }
-
- const reposition = () => {
- // The wrapper where there is one, so a field carrying chips is spanned whole.
- const anchor = fieldRef.current ?? inputEl.current;
- if (anchor) {
- setPosition(computeDropdownPosition(anchor, dropdownMinWidth));
- }
- };
-
- reposition();
- window.addEventListener("resize", reposition);
- // Capture: the input may live inside a scrolling container rather than the document.
- window.addEventListener("scroll", reposition, true);
- return () => {
- window.removeEventListener("resize", reposition);
- window.removeEventListener("scroll", reposition, true);
- };
- }, [ isOpen, items.length, inputEl, dropdownMinWidth ]);
const field = (
<FormTextBox
@@ -190,38 +171,142 @@ export default function FormAutocomplete({ currentValue, onChange, source, openO
? <div ref={fieldRef} className="tn-field form-autocomplete-field">{leading}{field}{trailing}</div>
: field}
- {isOpen && items.length > 0 && position && createPortal(
- <ul
- className="form-autocomplete-dropdown"
- role="listbox"
- style={position}
- // Keeps the input focused, so the blur handler does not close the dropdown
- // before the click lands on an item.
- onMouseDown={(e) => e.preventDefault()}
- >
- {items.map((item, index) => (
- isHeading?.(item)
- ? <li key={item} className="form-autocomplete-heading" role="presentation">
- {renderItem ? renderItem(item) : item}
- </li>
- : <li
- key={item}
- id={itemId(index)}
- className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
- role="option"
- aria-selected={index === activeIndex}
- onMouseMove={(e) => autocomplete.hover(index, e)}
- onClick={() => pick(item)}
- >
- {renderItem ? renderItem(item) : item}
- </li>
- ))}
- </ul>,
- document.body)}
+ <AutocompleteDropdown
+ autocomplete={autocomplete}
+ anchor={anchor}
+ minWidth={dropdownMinWidth}
+ renderItem={renderItem}
+ isHeading={isHeading}
+ />
</>
);
}
+/** Drives an {@link AutocompleteList} from where its query is typed. */
+export interface AutocompleteListHandle {
+ /** Handles a key pressed where the query is typed, and returns whether the list took it. */
+ handleKeyDown(e: KeyboardEvent): boolean;
+}
+
+/**
+ * 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 }: {
+ 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>;
+ elementRef?(element: HTMLElement | null): void;
+}) {
+ // 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 });
+
+ // The host shows the list by mounting it and closes it by unmounting it.
+ useEffect(() => autocomplete.open(), []);
+ useForwardedKeys(autocomplete, handleRef);
+
+ return (
+ <AutocompleteDropdown
+ autocomplete={autocomplete}
+ anchor={anchor}
+ minWidth={minWidth}
+ renderItem={renderItem}
+ elementRef={elementRef}
+ />
+ );
+}
+
+/**
+ * Takes the keys forwarded from where a list's query is typed. Tab takes the highlighted entry, as
+ * Enter does, where a field leaves Tab to move the focus.
+ */
+export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocomplete<T>>, handleRef: MutableRef<AutocompleteListHandle | null>) {
+ useLayoutEffect(() => {
+ handleRef.current = {
+ handleKeyDown(e) {
+ if (!autocomplete.isShown) return false;
+ const highlighted = autocomplete.items[autocomplete.activeIndex];
+ if (e.key === "Tab" && highlighted !== undefined) {
+ e.preventDefault();
+ autocomplete.pick(highlighted);
+ return true;
+ }
+ autocomplete.handleKeyDown(e);
+ return e.defaultPrevented;
+ }
+ };
+ });
+}
+
+/**
+ * The list of a {@link useAutocomplete}, portalled to the body and kept under `anchor` as the page
+ * scrolls or resizes.
+ */
+function AutocompleteDropdown({ autocomplete, anchor, minWidth, renderItem, isHeading, elementRef }: {
+ autocomplete: ReturnType<typeof useAutocomplete<string>>;
+ anchor: DropdownAnchor;
+ minWidth?: number;
+ renderItem?(item: string): ComponentChildren;
+ isHeading?(item: string): boolean;
+ elementRef?(element: HTMLElement | null): void;
+}) {
+ const [ position, setPosition ] = useState<CSSProperties>();
+ const { isShown, items, activeIndex, itemId, pick } = autocomplete;
+
+ useLayoutEffect(() => {
+ if (!isShown) {
+ return;
+ }
+
+ const reposition = () => setPosition(computeDropdownPosition(anchor, minWidth));
+ reposition();
+ window.addEventListener("resize", reposition);
+ // Capture: the anchor can live inside a scrolling container rather than the document.
+ window.addEventListener("scroll", reposition, true);
+ return () => {
+ window.removeEventListener("resize", reposition);
+ window.removeEventListener("scroll", reposition, true);
+ };
+ }, [ isShown, items.length, anchor, minWidth ]);
+
+ return isShown && position ? createPortal(
+ <ul
+ ref={elementRef}
+ className="form-autocomplete-dropdown"
+ role="listbox"
+ style={position}
+ // Keeps the focus where the query is typed, so its blur does not close the dropdown
+ // before the click lands on an item.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {items.map((item, index) => (
+ isHeading?.(item)
+ ? <li key={item} className="form-autocomplete-heading" role="presentation">
+ {renderItem ? renderItem(item) : item}
+ </li>
+ : <li
+ key={item}
+ id={itemId(index)}
+ className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
+ role="option"
+ aria-selected={index === activeIndex}
+ onMouseMove={(e) => autocomplete.hover(index, e)}
+ onClick={() => pick(item)}
+ >
+ {renderItem ? renderItem(item) : item}
+ </li>
+ ))}
+ </ul>,
+ document.body) : null;
+}
+
interface UseAutocompleteOptions<T> {
/** The text in the field, which `source` is queried with. */
query: string;
@@ -526,8 +611,8 @@ export function stepOver<T>(items: T[], from: number, delta: number, isHeading?:
* Exported for its own tests: everything it reads is measured from the layout, which is what a
* component test in a headless DOM has none of.
*/
-export function computeDropdownPosition(input: HTMLElement, minWidth = 0): CSSProperties {
- const rect = input.getBoundingClientRect();
+export function computeDropdownPosition(anchor: DropdownAnchor, minWidth = 0): CSSProperties {
+ const rect = anchor.getBoundingClientRect();
const viewportHeight = document.documentElement.clientHeight;
const viewportWidth = document.documentElement.clientWidth;
const spaceBelow = viewportHeight - rect.bottom - VIEWPORT_MARGIN;
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
index 225619de8f..e94c9000b9 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx
@@ -21,7 +21,8 @@ import type { NoteSuggestionOptions, Suggestion } from "../../services/note_auto
import { collectShortcutHints } from "../../services/shortcut_hints";
import { buildNote } from "../../test/easy-froca";
import { renderInto } from "../../test/render";
-import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList, type NoteMentionListHandle, renderNoteSuggestion } from "./NoteAutocomplete";
+import type { AutocompleteListHandle } from "./FormAutocomplete";
+import NoteAutocomplete, { type NoteAutocompleteHandle, type NoteAutocompleteProps, NoteMentionList, renderNoteSuggestion } from "./NoteAutocomplete";
import { ParentComponent } from "./react_utils";
async function render(props: NoteAutocompleteProps = {}) {
@@ -1131,7 +1132,7 @@ describe("NoteMentionList", () => {
/** Shows the list for `query` where nothing has the focus, as a text editor's caret does. */
async function show(query: string, props: Partial<Parameters<typeof NoteMentionList>[0]> = {}) {
const onPick = vi.fn();
- const handleRef = createRef<NoteMentionListHandle>() as { current: NoteMentionListHandle | null };
+ const handleRef = createRef<AutocompleteListHandle>() as { current: AutocompleteListHandle | null };
const host = document.createElement("div");
const draw = async (text: string) => {
await act(async () => {
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 6fa6840533..9137303ff7 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -15,7 +15,7 @@ import { escapeHtml, isMobile } from "../../services/utils";
import { ShortcutHintOverlayButton } from "../shortcut_hints/shortcut_hint_button";
import { AttributeSnippetBadges } from "./Badge";
import Button from "./Button";
-import { useAutocomplete } from "./FormAutocomplete";
+import { type AutocompleteListHandle, useAutocomplete, useForwardedKeys } from "./FormAutocomplete";
import { FormDropdownDivider, FormListHeader } from "./FormList";
import FormToggle from "./FormToggle";
import { useContextualShortcutHints, useSyncedRef } from "./hooks";
@@ -431,12 +431,6 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,
);
}
-/** Drives a {@link NoteMentionList} from where its query is typed. */
-export interface NoteMentionListHandle {
- /** Handles a key pressed where the query is typed, and returns whether the list took it. */
- handleKeyDown(e: KeyboardEvent): boolean;
-}
-
/**
* The note autocomplete's list for a query typed somewhere else, such as after an `@` in a text
* editor, which keeps the focus and forwards its keys through `handleRef`. It lists what the field
@@ -451,7 +445,7 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect =
/** Opens the list with an entry highlighted, so that Enter takes it. */
preselect?: boolean;
onPick(notePath: string | Promise<string | undefined>): void;
- handleRef: MutableRef<NoteMentionListHandle | null>;
+ handleRef: MutableRef<AutocompleteListHandle | null>;
elementRef?: PopupProps["elementRef"];
}) {
// The focus stays where the query is typed, so there is no field to return it to.
@@ -479,23 +473,7 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect =
// The host shows the list by mounting it and closes it by unmounting it.
useEffect(() => autocomplete.open(), []);
-
- useLayoutEffect(() => {
- handleRef.current = {
- handleKeyDown(e) {
- if (!autocomplete.isShown) return false;
- const highlighted = autocomplete.items[autocomplete.activeIndex];
- // Tab takes the highlighted note, as Enter does, where a field leaves Tab to move the focus.
- if (e.key === "Tab" && highlighted) {
- e.preventDefault();
- autocomplete.pick(highlighted);
- return true;
- }
- autocomplete.handleKeyDown(e);
- return e.defaultPrevented;
- }
- };
- });
+ useForwardedKeys(autocomplete, handleRef);
return autocomplete.isShown && (
<NoteSuggestionPopup anchor={anchor} elementRef={elementRef}>
diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx
index 87064d86a1..b9e5f42a5a 100644
--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx
+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.spec.tsx
@@ -1,42 +1,7 @@
import type { ModelPosition } from "@triliumnext/ckeditor5";
-import { describe, expect, it, vi } from "vitest";
+import { describe, expect, it } from "vitest";
-import server from "../../../services/server";
-import { fetchAttributeNames, getClickIndex, getPreprocessedData, renderAttributeName } from "./AttributeEditor";
-
-describe("fetchAttributeNames", () => {
- it("prefixes each name with the marker that inserts it, and asks for the names by an escaped query", async () => {
- const get = vi.fn(async () => [ "author", "priority" ]);
- server.get = get as unknown as typeof server.get;
-
- expect(await fetchAttributeNames("relation", "a b")).toEqual([
- { id: "~author", name: "author" },
- { id: "~priority", name: "priority" }
- ]);
- expect(get).toHaveBeenCalledExactlyOnceWith("attribute-names/?type=relation&query=a%20b");
-
- expect((await fetchAttributeNames("label", "")).map((item) => item.id)).toEqual([ "#author", "#priority" ]);
- });
-});
-
-describe("renderAttributeName", () => {
- it("marks a name Trilium reads for itself, and leaves an invented one as bare text", () => {
- const builtin = renderAttributeName("label", "archived");
-
- // `ck-button_with-text` keeps the label visible, and the reset opt-out keeps the badge styled.
- expect(builtin.classList.contains("ck-button_with-text")).toBe(true);
- expect(builtin.querySelector(".attr-name-suggestion")?.classList.contains("ck-reset_all-excluded")).toBe(true);
- expect(builtin.querySelector(".attr-name-suggestion-name")?.textContent).toBe("archived");
- expect(builtin.querySelector(".ext-badge.outline")).not.toBeNull();
-
- const invented = renderAttributeName("label", "myOwnLabel");
- expect(invented.querySelector(".attr-name-suggestion-name")?.textContent).toBe("myOwnLabel");
- expect(invented.querySelector(".ext-badge")).toBeNull();
-
- // A name that is a built-in of the other type is not one here.
- expect(renderAttributeName("relation", "archived").querySelector(".ext-badge")).toBeNull();
- });
-});
+import { getClickIndex, getPreprocessedData } from "./AttributeEditor";
describe("getPreprocessedData", () => {
it("reduces a reference link back to the note path it stands for, and resolves the entities around it", () => {
diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
index 3d39f3fa6f..84acee25c3 100644
--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx
@@ -1,7 +1,6 @@
-import "../../attribute_widgets/attribute_name_suggestion.css";
import "./AttributeEditor.css";
-import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, MentionHostedFeed, TriliumMentionFeed } from "@triliumnext/ckeditor5";
+import type { AttributeEditor as CKEditorAttributeEditor, ModelElement, ModelNode, ModelPosition, MentionHostedFeed } from "@triliumnext/ckeditor5";
import { AttributeType } from "@triliumnext/commons";
import clsx from "clsx";
import { createPortal } from "preact/compat";
@@ -13,7 +12,7 @@ import FNote from "../../../entities/fnote";
import contextMenu from "../../../menus/context_menu";
import attribute_parser, { Attribute } from "../../../services/attribute_parser";
import attribute_renderer from "../../../services/attribute_renderer";
-import attributes, { isBuiltinAttribute } from "../../../services/attributes";
+import attributes from "../../../services/attributes";
import froca from "../../../services/froca";
import { t } from "../../../services/i18n";
import { ATTRIBUTE_HELP_PAGE } from "../../../services/in_app_help";
@@ -21,12 +20,12 @@ import link from "../../../services/link";
import server from "../../../services/server";
import { isIMEComposing } from "../../../services/shortcuts";
import { escapeQuotes, getErrorMessage } from "../../../services/utils";
-import AttributeDetailWidget from "../../attribute_widgets/attribute_detail";
+import AttributeDetailWidget, { AttributeNameSuggestion, fetchAttributeNames } from "../../attribute_widgets/attribute_detail";
import ActionButton from "../../react/ActionButton";
import CKEditor, { CKEditorApi } from "../../react/CKEditor";
import HelpDropdown from "../../react/HelpDropdown";
import { useLegacyImperativeHandlers, useLegacyWidget, useTriliumEvent } from "../../react/hooks";
-import { createMentionListView, createNoteMentionList } from "../../type_widgets/text/mention_list_view";
+import { createAutocompleteMentionList, createNoteMentionList } from "../../type_widgets/text/mention_list_view";
import AttributeHelp from "./AttributeHelp";
type AttributeCommandNames = FilteredCommandNames<CommandData>;
@@ -37,26 +36,11 @@ type AttributeCommandNames = FilteredCommandNames<CommandData>;
*/
const BLINK_DURATION = 300;
-// `preselectFirstItem: false` throughout: in this editor Enter means "save the attributes", so an
-// open panel must not silently swallow it into committing whichever suggestion happens to be first.
-const mentionSetup: TriliumMentionFeed[] = [
- {
- marker: "#",
- feed: (queryText) => fetchAttributeNames("label", queryText),
- itemRenderer: (item) => renderAttributeName("label", (item as AttributeNameItem).name),
- minimumCharacters: 0,
- preselectFirstItem: false
- },
- {
- marker: "~",
- feed: (queryText) => fetchAttributeNames("relation", queryText),
- itemRenderer: (item) => renderAttributeName("relation", (item as AttributeNameItem).name),
- minimumCharacters: 0,
- preselectFirstItem: false
- }
-];
-
+// Every list opens with nothing highlighted: in this editor Enter means "save the attributes", so an
+// open list must not swallow it into committing whichever suggestion happens to be first.
const hostedMentions: MentionHostedFeed[] = [
+ attributeNameMention("#", "label"),
+ attributeNameMention("~", "relation"),
{
marker: "@",
minimumCharacters: 0,
@@ -288,7 +272,7 @@ export default function AttributeEditor({ api, note, componentId, ntxId, hidden,
config={{
toolbar: { items: [] },
placeholder: t("attribute_editor.placeholder"),
- mention: { feeds: mentionSetup, hostedFeeds: hostedMentions, listView: createMentionListView },
+ mention: { feeds: [], hostedFeeds: hostedMentions },
licenseKey: "GPL",
language: "en"
}}
@@ -419,61 +403,20 @@ export default function AttributeEditor({ api, note, componentId, ntxId, hidden,
);
}
-interface AttributeNameItem {
- /** The marker and the name, which is what committing the suggestion inserts. */
- id: string;
- name: string;
-}
-
-export async function fetchAttributeNames(type: "label" | "relation", queryText: string): Promise<AttributeNameItem[]> {
- const names = await server.get<string[]>(`attribute-names/?type=${type}&query=${encodeURIComponent(queryText)}`);
- const marker = type === "label" ? "#" : "~";
-
- return names.map((name) => ({ id: `${marker}${name}`, name }));
-}
-
/**
- * One completed attribute name, marking the ones Trilium itself attaches a meaning to — the same
- * distinction the detail popup's name field draws, on the same names, so that the two agree.
- *
- * Built as DOM rather than rendered from the popup's `AttributeNameSuggestion` component: the mention
- * panel drops and rebuilds its rows on every keystroke with no unmount hook to run, so a Preact root
- * per row would leak. The badge markup is mirrored from `Badge` rather than restyled, so that both
- * surfaces still take their look from the one stylesheet.
+ * Completes the name typed after `marker` as the attributes panel's name box completes it, from the
+ * same names drawn the same way, and inserts the name picked behind the marker.
*/
-export function renderAttributeName(type: "label" | "relation", name: string) {
- const button = document.createElement("button");
- button.type = "button";
- button.tabIndex = -1;
- // `ck-button_with-text` is load-bearing, not cosmetic: the base button styles hide
- // `.ck-button__label` outright without it, leaving the row showing nothing but its badge.
- button.classList.add("ck", "ck-button", "ck-button_with-text", "attr-name-suggestion-button");
-
- const row = document.createElement("span");
- // The balloon hosting the panel resets everything inside it (`.ck-reset_all` zeroes borders,
- // padding, width, colour and font on every descendant), which would strip the badge back to bare
- // text. `ck-reset_all-excluded` is CKEditor's opt-out for embedded content and covers the whole
- // subtree, so the row is styled by the client's stylesheets exactly as the popup's row is.
- row.classList.add("attr-name-suggestion", "ck-reset_all-excluded");
- button.append(row);
-
- const label = document.createElement("span");
- label.classList.add("ck", "ck-button__label", "attr-name-suggestion-name");
- label.textContent = name;
- row.append(label);
-
- if (isBuiltinAttribute(type, name)) {
- const badge = document.createElement("span");
- badge.classList.add("ext-badge", "outline");
- row.append(badge);
-
- const badgeText = document.createElement("span");
- badgeText.classList.add("text");
- badgeText.textContent = t("attribute_names.system");
- badge.append(badgeText);
- }
-
- return button;
+function attributeNameMention(marker: "#" | "~", type: "label" | "relation"): MentionHostedFeed {
+ return {
+ marker,
+ minimumCharacters: 0,
+ list: () => createAutocompleteMentionList({
+ source: (query) => fetchAttributeNames(type, query),
+ renderItem: (name) => <AttributeNameSuggestion type={type} name={name} />,
+ toMention: (name) => ({ id: `${marker}${name}` })
+ })
+ };
}
/** The attributes as plain text: reference links back down to their note path, entities resolved. */
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
index a72688ca4b..cedae373d6 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.spec.tsx
@@ -13,7 +13,7 @@ vi.mock("../../../services/note_autocomplete", async (importOriginal) => ({
createNoteFromSuggestion
}));
-import { createMentionListView, createNoteMentionList } from "./mention_list_view";
+import { createAutocompleteMentionList, createMentionListView, createNoteMentionList } from "./mention_list_view";
describe("createMentionListView", () => {
const views: ReturnType<typeof createMentionListView>[] = [];
@@ -184,3 +184,44 @@ describe("createNoteMentionList", () => {
canceled.list.destroy?.();
});
});
+
+describe("createAutocompleteMentionList", () => {
+ beforeEach(() => {
+ vi.useFakeTimers();
+ });
+
+ afterEach(() => {
+ vi.useRealTimers();
+ });
+
+ it("lists the source's entries as a field's dropdown, and takes one only once it is arrowed to", async () => {
+ const source = vi.fn(async (query: string) => [ `${query}One`, `${query}Two` ]);
+ const list = createAutocompleteMentionList({
+ source,
+ renderItem: (item) => <b>{item}</b>,
+ toMention: (item) => ({ id: `#${item}` })
+ });
+ const commit = vi.fn<MentionHostedListState["commit"]>();
+ const key = (k: string) => list.handleKeyDown(new KeyboardEvent("keydown", { key: k, cancelable: true }));
+
+ await act(async () => list.show({ query: "ab", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));
+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });
+
+ expect(source).toHaveBeenLastCalledWith("ab");
+ expect(list.element?.matches(".form-autocomplete-dropdown")).toBe(true);
+ expect([ ...(list.element?.querySelectorAll(".form-autocomplete-item > b") ?? []) ].map((row) => row.textContent))
+ .toEqual([ "abOne", "abTwo" ]);
+ // Nothing is highlighted, so Enter stays with the editor.
+ expect(key("Enter")).toBe(false);
+ expect(commit).not.toHaveBeenCalled();
+
+ await act(async () => { key("ArrowDown"); });
+ await act(async () => { key("ArrowDown"); });
+ expect(key("Tab")).toBe(true);
+ expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "#abTwo" });
+
+ await act(async () => list.hide());
+ expect(list.element).toBeNull();
+ list.destroy?.();
+ });
+});
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 3f0a19d76b..621d14ccaf 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,15 +1,19 @@
import "./mention_list_view.css";
-import type { MentionHostedList, MentionListEntry, MentionListState, MentionListView } from "@triliumnext/ckeditor5";
+import type { MentionFeedObjectItem, MentionHostedList, MentionListEntry, MentionListState, MentionListView } from "@triliumnext/ckeditor5";
import clsx from "clsx";
-import { render } from "preact";
+import { type ComponentChildren, render } from "preact";
import { useLayoutEffect, useRef } from "preact/hooks";
-import { NoteMentionList, type NoteMentionListHandle } from "../../react/NoteAutocomplete";
+import { AutocompleteList, type AutocompleteListHandle } from "../../react/FormAutocomplete";
+import { NoteMentionList } from "../../react/NoteAutocomplete";
import Popup from "../../react/Popup";
+/** The least width of an {@link createAutocompleteMentionList} list, whose caret anchor has none. */
+const AUTOCOMPLETE_MENTION_MIN_WIDTH = 220;
+
/**
- * Draws a text editor's suggestion list (`#`/`~` attributes, `/` commands, emoji) as the note
+ * Draws a text editor's suggestion list (`/` commands, emoji) as the note
* autocomplete's menu, in a {@link Popup} at the caret, for the editor config's `mention.listView`.
*
* `TriliumMentionUI` keeps everything but the drawing: when the list opens and closes, the keys, the
@@ -60,7 +64,7 @@ export function createNoteMentionList({ allowCreatingNotes, preselect }: {
preselect?: boolean;
} = {}): MentionHostedList {
const container = document.createElement("div");
- const handle: { current: NoteMentionListHandle | null } = { current: null };
+ const handle: { current: AutocompleteListHandle | null } = { current: null };
let element: HTMLDivElement | null = null;
return {
@@ -93,6 +97,49 @@ export function createNoteMentionList({ allowCreatingNotes, preselect }: {
};
}
+/**
+ * Lists what `source` has for the query typed after a marker as a form field's autocomplete lists
+ * it, for the editor config's `mention.hostedFeeds`, and mentions the entry picked as `toMention`
+ * makes it.
+ */
+export function createAutocompleteMentionList({ source, renderItem, toMention }: {
+ source(query: string): Promise<string[]>;
+ renderItem?(item: string): ComponentChildren;
+ toMention(item: string): MentionFeedObjectItem;
+}): MentionHostedList {
+ const container = document.createElement("div");
+ const handle: { current: AutocompleteListHandle | null } = { current: null };
+ let element: HTMLElement | null = null;
+
+ return {
+ show(state) {
+ render(<AutocompleteList
+ query={state.query}
+ source={source}
+ // A new anchor each time the query changes, so it is placed again at the caret.
+ anchor={{ getBoundingClientRect: state.caretRect }}
+ minWidth={AUTOCOMPLETE_MENTION_MIN_WIDTH}
+ renderItem={renderItem}
+ onPick={(item) => state.commit(toMention(item))}
+ handleRef={handle}
+ elementRef={(el) => { element = el; }}
+ />, container);
+ },
+ hide() {
+ render(null, container);
+ element = null;
+ },
+ handleKeyDown: (e) => handle.current?.handleKeyDown(e) ?? false,
+ get element() {
+ return element;
+ },
+ destroy() {
+ render(null, container);
+ element = null;
+ }
+ };
+}
+
/** The mention `MentionCustomization` turns into a reference link to `notePath`. */
function toMention(notePath: string) {
return { id: `@${notePath}`, notePath };