Skip to content

Build your personal knowledge base with Trilium Notes

feat(text): list the slash commands as the command palette lists its own

Elian Doran453c7e5ac648
diff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsx
index cf02314ad9..ed5190a91f 100644
--- a/apps/client/src/widgets/react/FormAutocomplete.tsx
+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx
@@ -1,7 +1,6 @@
import "./FormAutocomplete.css";
import type { ReferenceElement } from "@floating-ui/dom";
-import clsx from "clsx";
import type { ComponentChildren, RefObject } from "preact";
import { type MutableRef, useCallback, useEffect, useLayoutEffect, useRef, useState } from "preact/hooks";
@@ -185,34 +184,23 @@ export interface AutocompleteListHandle {
/**
* 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`. Without
- * `autoActivate` it opens with nothing highlighted, so Enter stays with the host until an entry is
- * arrowed to.
+ * 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<T = string>({ query, source, schedule, anchor, minWidth, className, autoActivate, keyOf, textOf, renderItem, onPick, handleRef, elementRef }: {
+export function AutocompleteList({ query, source, anchor, minWidth, renderItem, onPick, handleRef, elementRef }: {
query: string;
- source(query: string): Promise<T[]>;
- /** See `useAutocomplete`'s `schedule`. */
- schedule?(lookUp: () => Promise<void>): void;
+ source(query: string): Promise<string[]>;
anchor: DropdownAnchor;
/** See {@link FormAutocompleteProps.dropdownMinWidth}. */
minWidth?: number;
- /** A class for the dropdown, beside its own. */
- className?: string;
- /** See {@link FormAutocompleteProps.autoActivate}. */
- autoActivate?: boolean;
- /** Tells the entries apart, for an entry that is not a string. Defaults to `String(item)`. */
- keyOf?(item: T): string;
- /** See `useAutocomplete`'s `textOf`. */
- textOf?(item: T): string;
- renderItem?(item: T): ComponentChildren;
- onPick(item: T): void;
+ renderItem?(item: string): ComponentChildren;
+ onPick(item: string): 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, schedule, onPick, inputRef, autoActivate, textOf });
+ const autocomplete = useAutocomplete({ query, source, onPick, inputRef });
// The host shows the list by mounting it and closes it by unmounting it.
useEffect(() => autocomplete.open(), []);
@@ -223,8 +211,6 @@ export function AutocompleteList<T = string>({ query, source, schedule, anchor,
autocomplete={autocomplete}
anchor={anchor}
minWidth={minWidth}
- className={className}
- keyOf={keyOf}
renderItem={renderItem}
elementRef={elementRef}
/>
@@ -257,14 +243,12 @@ export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocompl
* The list of a {@link useAutocomplete}, in a {@link Popup} under `anchor`, which places it again as
* the list or the anchor changes size or moves.
*/
-function AutocompleteDropdown<T>({ autocomplete, anchor, minWidth = 0, className, keyOf = String, renderItem = String, isHeading, elementRef }: {
- autocomplete: ReturnType<typeof useAutocomplete<T>>;
+function AutocompleteDropdown({ autocomplete, anchor, minWidth = 0, renderItem, isHeading, elementRef }: {
+ autocomplete: ReturnType<typeof useAutocomplete<string>>;
anchor: DropdownAnchor | null;
minWidth?: number;
- className?: string;
- keyOf?(item: T): string;
- renderItem?(item: T): ComponentChildren;
- isHeading?(item: T): boolean;
+ renderItem?(item: string): ComponentChildren;
+ isHeading?(item: string): boolean;
elementRef?: PopupProps["elementRef"];
}) {
const { isShown, items, activeIndex, itemId, pick } = autocomplete;
@@ -276,7 +260,7 @@ function AutocompleteDropdown<T>({ autocomplete, anchor, minWidth = 0, className
return (
<Popup
anchor={anchor}
- className={clsx("form-autocomplete-dropdown", className)}
+ className="form-autocomplete-dropdown"
elementRef={elementRef}
// As wide as the field, or as `minWidth` where that is more.
style={{ width: `${Math.max(anchor.getBoundingClientRect().width, minWidth)}px` }}
@@ -290,11 +274,11 @@ function AutocompleteDropdown<T>({ autocomplete, anchor, minWidth = 0, className
>
{items.map((item, index) => (
isHeading?.(item)
- ? <li key={keyOf(item)} className="form-autocomplete-heading" role="presentation">
- {renderItem(item)}
+ ? <li key={item} className="form-autocomplete-heading" role="presentation">
+ {renderItem ? renderItem(item) : item}
</li>
: <li
- key={keyOf(item)}
+ key={item}
id={itemId(index)}
className={`form-autocomplete-item ${index === activeIndex ? "active" : ""}`}
role="option"
@@ -302,7 +286,7 @@ function AutocompleteDropdown<T>({ autocomplete, anchor, minWidth = 0, className
onMouseMove={(e) => autocomplete.hover(index, e)}
onClick={() => pick(item)}
>
- {renderItem(item)}
+ {renderItem ? renderItem(item) : item}
</li>
))}
</ul>
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.css b/apps/client/src/widgets/react/NoteAutocomplete.css
index 9e94eb061b..c13a6088e5 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.css
+++ b/apps/client/src/widgets/react/NoteAutocomplete.css
@@ -128,6 +128,16 @@
color: var(--muted-text-color);
}
+ /* An icon drawn as SVG markup, sized and coloured as a font icon's glyph. */
+ .note-suggestion-svg-icon > svg {
+ width: 1em;
+ height: 1em;
+
+ & *:not([fill]) {
+ fill: currentColor;
+ }
+ }
+
.note-suggestion-attributes {
display: flex;
flex-wrap: wrap;
diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsx
index 9137303ff7..2465c32180 100644
--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx
+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx
@@ -3,7 +3,7 @@ import "./NoteAutocomplete.css";
import { NOTE_TYPE_ICONS } from "@triliumnext/commons";
import clsx from "clsx";
-import { type RefObject, render } from "preact";
+import { type ComponentChildren, type RefObject, render } from "preact";
import { createPortal, type CSSProperties } from "preact/compat";
import { type MutableRef, useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "preact/hooks";
@@ -482,6 +482,76 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect =
);
}
+/** An entry of a {@link CommandMentionList}, drawn as the command palette draws a command. */
+export interface CommandEntry {
+ id: string;
+ title: string;
+ description?: string;
+ /** The classes of a font icon. */
+ icon?: string;
+ /** An icon as SVG markup, in place of {@link CommandEntry.icon}. */
+ iconSvg?: string;
+}
+
+/**
+ * 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.
+ */
+export function CommandMentionList<T extends CommandEntry>({ query, source, anchor, className, 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;
+ 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 });
+
+ // The host shows the list by mounting it and closes it by unmounting it.
+ useEffect(() => autocomplete.open(), []);
+ useForwardedKeys(autocomplete, handleRef);
+
+ return autocomplete.isShown && (
+ <NoteSuggestionPopup anchor={anchor} elementRef={elementRef} className={className}>
+ <menu
+ className="tn-menu-scroll"
+ role="listbox"
+ // Keeps the focus where the query is typed, which closes the list without it.
+ onMouseDown={(e) => e.preventDefault()}
+ >
+ {autocomplete.items.map((entry, index) => (
+ <SuggestionOption key={entry.id} autocomplete={autocomplete} index={index}>
+ <span>
+ <SuggestionRowContent
+ icon={entry.iconSvg
+ ? <RawHtml className="tn-icon note-suggestion-svg-icon" html={entry.iconSvg} />
+ : <Icon icon={entry.icon ?? "bx bx-terminal"} />}
+ header={<span className="search-result-title">{entry.title}</span>}
+ details={entry.description && <span className="note-suggestion-description">{entry.description}</span>}
+ />
+ </span>
+ </SuggestionOption>
+ ))}
+ </menu>
+ </NoteSuggestionPopup>
+ );
+}
+
+function commandTitle(entry: CommandEntry) {
+ return entry.title;
+}
+
+/** Runs a lookup at once, for a source that answers from memory. */
+function lookUpNow(lookUp: () => Promise<void>) {
+ void lookUp();
+}
+
/** The popup the suggestions are listed in, below `anchor` where there is room. */
function NoteSuggestionPopup({ className, ...props }: PopupProps) {
return (
@@ -552,22 +622,34 @@ function NoteSuggestionMenu({ autocomplete, searchingFor, className }: {
recentGroups[index] && recentGroups[index] !== recentGroups[index - 1] && (
<FormListHeader key={`heading-${index}`} text={recentGroupTitle(recentGroups[index])} />
),
- <li
- key={suggestionKey(suggestion, index)}
- id={autocomplete.itemId(index)}
- className={clsx("dropdown-item", index === autocomplete.activeIndex && "tn-menu-active")}
- role="option"
- aria-selected={index === autocomplete.activeIndex}
- onMouseMove={(e) => autocomplete.hover(index, e)}
- onClick={() => autocomplete.pick(suggestion)}
- >
+ <SuggestionOption key={suggestionKey(suggestion, index)} autocomplete={autocomplete} index={index}>
<NoteSuggestionMenuItem suggestion={suggestion} />
- </li>
+ </SuggestionOption>
])}
</menu>
);
}
+/** The menu row of the entry at `index`, which the pointer highlights and a click picks. */
+function SuggestionOption<T>({ autocomplete, index, children }: {
+ autocomplete: ReturnType<typeof useAutocomplete<T>>;
+ index: number;
+ children: ComponentChildren;
+}) {
+ return (
+ <li
+ id={autocomplete.itemId(index)}
+ className={clsx("dropdown-item", index === autocomplete.activeIndex && "tn-menu-active")}
+ role="option"
+ aria-selected={index === autocomplete.activeIndex}
+ onMouseMove={(e) => autocomplete.hover(index, e)}
+ onClick={() => autocomplete.pick(autocomplete.items[index])}
+ >
+ {children}
+ </li>
+ );
+}
+
/** One row of the menu, laid out as the rows of `FormListItem` are. */
function NoteSuggestionMenuItem({ suggestion }: { suggestion: Suggestion }) {
return (
@@ -587,15 +669,14 @@ function NoteSuggestionMenuItemContent({ suggestion }: { suggestion: Suggestion
? suggestion.highlightedParentPathTitle
: undefined;
- return <>
- <Icon icon={icon} />
- <span className="tn-menu-gap" />
- <div className="note-suggestion-text">
- <div className="note-suggestion-header">
+ return (
+ <SuggestionRowContent
+ icon={<Icon icon={icon} />}
+ header={<>
<RawHtml className="search-result-title" html={title} />
{parentPath && <span className="note-suggestion-path"><RawHtml html={parentPath} /></span>}
- </div>
- {isCommand
+ </>}
+ details={isCommand
? suggestion.commandDescription && (
<span className="note-suggestion-description">{suggestion.commandDescription}</span>
)
@@ -603,8 +684,26 @@ function NoteSuggestionMenuItemContent({ suggestion }: { suggestion: Suggestion
snippet={suggestion.highlightedAttributeSnippet}
className="note-suggestion-attributes"
/>}
+ trailing={<SuggestionShortcut suggestion={suggestion} />}
+ />
+ );
+}
+
+/** A row's content: the icon, the title line, what goes under it, and the keys at the end. */
+function SuggestionRowContent({ icon, header, details, trailing }: {
+ icon: ComponentChildren;
+ header: ComponentChildren;
+ details?: ComponentChildren;
+ trailing?: ComponentChildren;
+}) {
+ return <>
+ {icon}
+ <span className="tn-menu-gap" />
+ <div className="note-suggestion-text">
+ <div className="note-suggestion-header">{header}</div>
+ {details}
</div>
- <SuggestionShortcut suggestion={suggestion} />
+ {trailing}
</>;
}
diff --git a/apps/client/src/widgets/type_widgets/text/mention_list_view.css b/apps/client/src/widgets/type_widgets/text/mention_list_view.css
index cc08a46647..703bf57fee 100644
--- a/apps/client/src/widgets/type_widgets/text/mention_list_view.css
+++ b/apps/client/src/widgets/type_widgets/text/mention_list_view.css
@@ -28,57 +28,15 @@
max-height: var(--ck-mention-list-max-height);
}
-/* The `/` palette is long, and the query only narrows it, so it is given more height than a field's list. */
-.form-autocomplete-dropdown.slash-command-list > .form-autocomplete-list {
- max-height: var(--ck-mention-list-max-height);
-}
-
-.slash-command-list .slash-command {
- --slash-command-icon-size: calc(var(--ck-icon-size, 20px) * 0.8);
- display: flex;
- align-items: center;
- gap: 10px;
-}
-
-.slash-command-list .slash-command-icon {
- display: flex;
- flex-shrink: 0;
- align-items: center;
- justify-content: center;
- width: var(--slash-command-icon-size);
- height: var(--slash-command-icon-size);
- /* A snippet's font icon, a little inside the box an svg fills. */
- font-size: calc(var(--slash-command-icon-size) * 0.85);
- line-height: 1;
-
- & > svg {
- width: 100%;
- height: 100%;
- }
-
- /* As CKEditor's `ck-icon_inherit-color`: the icons draw in the text's colour. */
- & svg *:not([fill]) {
- fill: currentColor;
- }
-}
-
-.slash-command-list .slash-command-text {
- display: flex;
- flex-direction: column;
- min-width: 0;
- line-height: 1.2;
-}
-
-.slash-command-list :is(.slash-command-title, .slash-command-description) {
- overflow: hidden;
- text-overflow: ellipsis;
-}
-
-.slash-command-list .slash-command-title {
- font-weight: bold;
+/*
+ * The `/` palette, at a width that fits all but the longest descriptions, and given more height than
+ * a list usually is: it is long, and the query only narrows it.
+ */
+.slash-command-menu {
+ width: 350px;
+ max-width: calc(100vw - 10px);
}
-.slash-command-list .slash-command-description {
- font-size: 0.85em;
- opacity: 0.75;
+.slash-command-menu > .tn-menu-scroll {
+ max-height: var(--ck-mention-list-max-height);
}
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 1bab62b6bc..07b6461fad 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
@@ -230,7 +230,7 @@ describe("createSlashCommandList", () => {
{ id: "snippet-0", title: "Greeting", iconClass: "tn-icon bx bx-note", iconColorClass: "use-note-color" }
];
- it("lists the palette's entries for the query, opening on the first, and commits the one picked", async () => {
+ it("lists the palette's entries as the command palette lists commands, opening on the first, and commits the one picked", async () => {
const search = vi.fn(() => definitions);
const editor = { plugins: { get: () => ({ search }) } } as unknown as Parameters<NonNullable<SlashCommandConfig["list"]>>[0];
const list = createSlashCommandList(editor);
@@ -242,15 +242,15 @@ describe("createSlashCommandList", () => {
await act(async () => {});
expect(search).toHaveBeenLastCalledWith("q");
- expect(list.element?.matches(".form-autocomplete-dropdown.slash-command-list")).toBe(true);
- const [ quote, greeting ] = [ ...(list.element?.querySelectorAll(".form-autocomplete-item") ?? []) ];
- expect(quote.classList.contains("active")).toBe(true);
- expect(quote.querySelector(".slash-command-icon > svg.quote")).not.toBeNull();
- expect(quote.querySelector(".slash-command-title")?.textContent).toBe("Block quote");
- expect(quote.querySelector(".slash-command-description")?.textContent).toBe("Insert a quote.");
+ expect(list.element?.matches(".dropdown-menu.note-autocomplete-menu.slash-command-menu")).toBe(true);
+ const [ quote, greeting ] = [ ...(list.element?.querySelectorAll(".tn-menu-scroll > .dropdown-item") ?? []) ];
+ expect(quote.classList.contains("tn-menu-active")).toBe(true);
+ expect(quote.querySelector(".tn-icon.note-suggestion-svg-icon > svg.quote")).not.toBeNull();
+ expect(quote.querySelector(".search-result-title")?.textContent).toBe("Block quote");
+ expect(quote.querySelector(".note-suggestion-description")?.textContent).toBe("Insert a quote.");
// A snippet's font icon, in its colour, and no description where it has none.
- expect(greeting.querySelector(".slash-command-icon.bx-note.use-note-color")).not.toBeNull();
- expect(greeting.querySelector(".slash-command-description")).toBeNull();
+ expect(greeting.querySelector(".tn-icon.bx-note.use-note-color")).not.toBeNull();
+ expect(greeting.querySelector(".note-suggestion-description")).toBeNull();
await act(async () => { key("ArrowDown"); });
expect(key("Enter")).toBe(true);
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 0cd020c2eb..1581c5eb7c 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
@@ -6,15 +6,11 @@ import { type ComponentChildren, render } from "preact";
import { useLayoutEffect, useRef } from "preact/hooks";
import { AutocompleteList, type AutocompleteListHandle } from "../../react/FormAutocomplete";
-import Icon from "../../react/Icon";
-import { NoteMentionList } from "../../react/NoteAutocomplete";
+import { type CommandEntry, CommandMentionList, NoteMentionList } from "../../react/NoteAutocomplete";
import Popup from "../../react/Popup";
-import RawHtml from "../../react/RawHtml";
/** The least width of an {@link createAutocompleteMentionList} list, whose caret anchor has none. */
const AUTOCOMPLETE_MENTION_MIN_WIDTH = 220;
-/** The width of the `/` palette, which fits all but the longest descriptions. */
-const SLASH_COMMAND_LIST_WIDTH = 350;
/**
* Draws a text editor's suggestion list (emoji) as the note
@@ -145,31 +141,25 @@ export function createAutocompleteMentionList({ source, renderItem, toMention }:
}
/**
- * Lists the `/` palette's entries for the query as a form field's autocomplete lists its own, for the
+ * Lists the `/` palette's entries for the query as the command palette lists its commands, for the
* editor config's `slashCommand.list`, opening on the best match so that Enter runs it.
*/
export function createSlashCommandList(editor: Parameters<NonNullable<SlashCommandConfig["list"]>>[0]): MentionHostedList {
const palette = editor.plugins.get("TriliumSlashCommands") as TriliumSlashCommands;
- const source = async (query: string) => palette.search(query);
+ const source = async (query: string) => palette.search(query).map(toCommandEntry);
const container = document.createElement("div");
const handle: { current: AutocompleteListHandle | null } = { current: null };
let element: HTMLElement | null = null;
return {
show(state) {
- render(<AutocompleteList<SlashCommandDefinition>
+ render(<CommandMentionList<SlashCommandEntry>
query={state.query}
source={source}
- schedule={lookUpNow}
// A new anchor each time the query changes, so it is placed again at the caret.
anchor={{ getBoundingClientRect: state.caretRect, contextElement: state.editable ?? undefined }}
- minWidth={SLASH_COMMAND_LIST_WIDTH}
- className="slash-command-list"
- autoActivate
- keyOf={(definition) => definition.id}
- textOf={(definition) => definition.title}
- renderItem={(definition) => <SlashCommandRow definition={definition} />}
- onPick={(definition) => state.commit(toSlashCommandItem(definition))}
+ className="slash-command-menu"
+ onPick={({ definition }) => state.commit(toSlashCommandItem(definition))}
handleRef={handle}
elementRef={(el) => { element = el; }}
/>, container);
@@ -189,28 +179,23 @@ export function createSlashCommandList(editor: Parameters<NonNullable<SlashComma
};
}
+type SlashCommandEntry = CommandEntry & { definition: SlashCommandDefinition };
+
+/** What the palette commits for an entry, which `TriliumSlashCommands` then runs. */
function toSlashCommandItem(definition: SlashCommandDefinition): SlashCommandItem {
return { id: definition.id, definition };
}
-/** Looks the palette's entries up at once: the catalog is in memory, so there is nothing to wait for. */
-function lookUpNow(lookUp: () => Promise<void>) {
- void lookUp();
-}
-
-/** One entry of the `/` palette: its icon, its title and what it does. */
-function SlashCommandRow({ definition }: { definition: SlashCommandDefinition }) {
- return (
- <span className="slash-command">
- {definition.iconClass
- ? <Icon className="slash-command-icon" icon={clsx(definition.iconClass, definition.iconColorClass)} />
- : <RawHtml className="slash-command-icon" html={definition.icon} />}
- <span className="slash-command-text">
- <span className="slash-command-title">{definition.title}</span>
- {definition.description && <span className="slash-command-description">{definition.description}</span>}
- </span>
- </span>
- );
+/** A palette entry as a command row: a snippet's font icon in its colour, or the entry's SVG. */
+function toCommandEntry(definition: SlashCommandDefinition): SlashCommandEntry {
+ return {
+ id: definition.id,
+ title: definition.title,
+ description: definition.description,
+ icon: definition.iconClass ? clsx(definition.iconClass, definition.iconColorClass) : undefined,
+ iconSvg: definition.iconClass ? undefined : definition.icon,
+ definition
+ };
}
/** The mention `MentionCustomization` turns into a reference link to `notePath`. */