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
fix(autocomplete): create a mention's child note under the edited note, and hold Tab on stale entries
Elian Doranb3eb2f380134
diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex c8b58322eb..bdee145376 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -301,6 +301,15 @@ describe("createNoteFromSuggestion", () => {expect(getInboxNotePath).toHaveBeenCalledTimes(1);});+ it("puts a child note under the parent the host gives, over the row's own", async () => {+ await createNoteFromSuggestion({ action: "create-child-note", noteTitle: "Child", parentNoteId: "active" }, "root/edited");+ expect(createNote).toHaveBeenLastCalledWith("root/edited", expect.objectContaining({ title: "Child" }));++ // The host's parent is for a child note only; the other row still goes to the inbox.+ await createNoteFromSuggestion({ action: "create-note", noteTitle: "Inboxed" }, "root/edited");+ expect(createNote).toHaveBeenLastCalledWith("root/inbox", expect.objectContaining({ title: "Inboxed" }));+ });+it("puts the note where the type chooser says, over the row's own parent", async () => {chooseNoteType.mockResolvedValue({ success: true, noteType: "code", notePath: "chosen/path" });diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex e1e732bc15..2a967a6517 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -104,10 +104,14 @@ export async function getNoteSuggestions(term: string, { allowCreatingNotes, all/*** Creates the note a creation row offers, under the parent the user picks in the type chooser, or- * else in the inbox (`create-note`) or under the row's parent (`create-child-note`). Returns the- * new note's path, or nothing when the chooser is canceled or no parent is found.+ * else in the inbox (`create-note`) or under `childParentNotePath` or the row's parent+ * (`create-child-note`). Returns the new note's path, or nothing when the chooser is canceled or no+ * parent is found.+ *+ * @param childParentNotePath the note a host is editing, which the row's parent, the active note,+ * need not be.*/-export async function createNoteFromSuggestion(suggestion: Suggestion) {+export async function createNoteFromSuggestion(suggestion: Suggestion, childParentNotePath?: string | null) {const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();if (!success) {return;@@ -115,7 +119,7 @@ export async function createNoteFromSuggestion(suggestion: Suggestion) {const parentNotePath = notePath ?? (suggestion.action === "create-note"? await dateNoteService.getInboxNotePath()- : suggestion.parentNoteId);+ : childParentNotePath ?? suggestion.parentNoteId);if (!parentNotePath) {return;}diff --git a/apps/client/src/widgets/layout/StatusBar.tsx b/apps/client/src/widgets/layout/StatusBar.tsxindex 543e011e0f..229bd32095 100644--- a/apps/client/src/widgets/layout/StatusBar.tsx+++ b/apps/client/src/widgets/layout/StatusBar.tsx@@ -458,6 +458,7 @@ function AttributesPane({ note, noteContext, attributesShown, setAttributesShown{editorMounted && <AttributeEditor{...context}api={api}+ notePath={noteContext.notePath}ntxId={noteContext.ntxId}// The panel's title bar already carries the same help.hideHelpButtondiff --git a/apps/client/src/widgets/react/FormAutocomplete.tsx b/apps/client/src/widgets/react/FormAutocomplete.tsxindex c24727d95a..f5edd17e01 100644--- a/apps/client/src/widgets/react/FormAutocomplete.tsx+++ b/apps/client/src/widgets/react/FormAutocomplete.tsx@@ -226,12 +226,7 @@ export function useForwardedKeys<T>(autocomplete: ReturnType<typeof useAutocomplhandleRef.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;- }+ if (e.key === "Tab" && autocomplete.takeHighlighted(e)) return true;autocomplete.handleKeyDown(e);return e.defaultPrevented;}@@ -359,10 +354,18 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,// next render: a second Enter in the same task then reaches the host's form (issue #5669).const pickedSinceRender = useRef(false);pickedSinceRender.current = false;- // Whether the entries on show answer an older query than the field's text. An Enter pressed then- // is held in `enterHeld` and picks from the newer query's entries once they arrive.+ // Whether the entries on show answer an older query than the field's text. An Enter (or a+ // forwarded Tab) pressed then is held in `keyHeld` and picks from the newer query's entries once+ // they arrive.const isStale = useRef(false);- const enterHeld = useRef(false);+ const keyHeld = useRef(false);+ // A host that forwards its keys changes `query` without `handleInput`, and a key can arrive+ // before the lookup effect runs.+ const renderedQuery = useRef(query);+ if (renderedQuery.current !== query) {+ renderedQuery.current = query;+ isStale.current = true;+ }const pickLatest = useRef(pick);pickLatest.current = pick;// Set when the keyboard or a new list moves the highlight, which the effect below scrolls into view.@@ -385,7 +388,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,// Invalidates in-flight queries too, so a late response cannot repopulate a closed dropdown.latestQuery.current++;isStale.current = false;- enterHeld.current = false;+ keyHeld.current = false;setIsOpen(false);setActiveIndex(-1);setItems([]);@@ -419,8 +422,8 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,setItems(suggestions);scrollToActive.current = true;setActiveIndex(index);- if (enterHeld.current) {- enterHeld.current = false;+ if (keyHeld.current) {+ keyHeld.current = false;if (index >= 0) pickLatest.current(suggestions[index]);}}@@ -462,6 +465,27 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,inputRef.current?.focus();}+ /**+ * Picks the highlighted entry for a key that confirms it, or holds the key until the entries for+ * a newer query arrive. Returns whether the key was taken.+ */+ function takeHighlighted(e: KeyboardEvent) {+ // Without `autoActivate` the newer entries open with nothing highlighted, so a key pressed+ // before they arrive belongs to the host.+ if (!isShown || activeIndex < 0 || pickedSinceRender.current || (!autoActivate && isStale.current)) {+ return false;+ }+ // Consume the key so it does not also reach the surrounding form or dialog.+ e.preventDefault();+ e.stopPropagation();+ if (isStale.current) {+ keyHeld.current = true;+ } else {+ pick(items[activeIndex]);+ }+ return true;+ }+function handleKeyDown(e: KeyboardEvent) {// The keys belong to the input method, such as the Enter that commits a candidate.if (e.isComposing) return;@@ -480,19 +504,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,break;case "Enter":- // Without `autoActivate` the newer entries open with nothing highlighted, so an Enter- // pressed before they arrive belongs to the host.- if (isShown && activeIndex >= 0 && !pickedSinceRender.current- && (autoActivate || !isStale.current)) {- // Consume the key so it does not also reach the surrounding form or dialog.- e.preventDefault();- e.stopPropagation();- if (isStale.current) {- enterHeld.current = true;- } else {- pick(items[activeIndex]);- }- } else if (openOnEnter) {+ if (!takeHighlighted(e) && openOnEnter) {open();}break;@@ -533,8 +545,8 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,handleInput() {// The lookup effect runs after the next render, and a key can arrive before it.isStale.current = true;- // A held Enter confirms the text it was pressed on, not text typed after it.- enterHeld.current = false;+ // A held key confirms the text it was pressed on, not text typed after it.+ keyHeld.current = false;open();},handleFocus() {@@ -548,6 +560,7 @@ export function useAutocomplete<T>({ query, source, onPick, inputRef, disabled,setIsComposing(false);},handleKeyDown,+ takeHighlighted,/** The field's combobox attributes. */comboboxProps: {role: "combobox",diff --git a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsxindex 2ab903fd93..f109d6847f 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.spec.tsx@@ -3,7 +3,7 @@ import { act } from "preact/test-utils";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";const { getNoteSuggestions, getCommandSuggestions, createNoteFromSuggestion } = vi.hoisted(() => ({- createNoteFromSuggestion: vi.fn<(suggestion: Suggestion) => Promise<string | undefined>>(),+ createNoteFromSuggestion: vi.fn<(suggestion: Suggestion, childParentNotePath?: string | null) => Promise<string | undefined>>(),getNoteSuggestions: vi.fn<(term: string, options?: NoteSuggestionOptions) => Promise<Suggestion[]>>(async () => []),getCommandSuggestions: vi.fn<(term: string) => Suggestion[]>(() => [])}));@@ -1192,6 +1192,32 @@ describe("NoteMentionList", () => {await unmount();});+ it("holds Tab and Enter pressed on a refined query until its notes arrive, and takes from those", async () => {+ const handleRef = createRef<AutocompleteListHandle>() as { current: AutocompleteListHandle | null };+ const host = document.createElement("div");+ const onPick = vi.fn();+ const draw = (text: string) => preactRender(<NoteMentionList query={text} anchor={anchor} onPick={onPick} handleRef={handleRef} />, host);+ const press = (key: string) => handleRef.current?.handleKeyDown(new KeyboardEvent("keydown", { key, cancelable: true })) ?? false;++ for (const key of [ "Tab", "Enter" ]) {+ getNoteSuggestions.mockResolvedValue(notes);+ await act(async () => draw("al"));+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ expect(rows()[0].classList.contains("tn-menu-active")).toBe(true);++ // Pressed as soon as the host shows the newer query, before the list has looked it up.+ getNoteSuggestions.mockResolvedValue([ notes[1] ]);+ draw("be");+ expect(press(key)).toBe(true);+ expect(onPick).not.toHaveBeenCalled();++ await act(async () => { await vi.advanceTimersByTimeAsync(300); });+ expect(onPick).toHaveBeenCalledExactlyOnceWith("root/b");+ onPick.mockClear();+ await act(async () => preactRender(null, host));+ }+ });+it("takes the keys while it shows notes, and reports the path of the one Enter or a click picks", async () => {const { onPick, press, unmount } = await show("al");@@ -1227,8 +1253,19 @@ describe("NoteMentionList", () => {// With no note to open, the list opens on the creation row.expect(await press("Enter")).toBe(true);- expect(createNoteFromSuggestion).toHaveBeenCalledWith(createRow);+ expect(createNoteFromSuggestion).toHaveBeenCalledWith(createRow, undefined);expect(await onPick.mock.calls[0]?.[0]).toBe("root/inbox/created");await unmount();});++ it("creates a child note under the note the host edits", async () => {+ const childRow: Suggestion = { action: "create-child-note", noteTitle: "al", parentNoteId: "active", highlightedNotePathTitle: "Create child note" };+ getNoteSuggestions.mockResolvedValue([ childRow ]);+ createNoteFromSuggestion.mockResolvedValueOnce("root/edited/created");+ const { press, unmount } = await show("al", { allowCreatingNotes: true, parentNotePath: "root/edited" });++ expect(await press("Enter")).toBe(true);+ expect(createNoteFromSuggestion).toHaveBeenCalledExactlyOnceWith(childRow, "root/edited");+ await unmount();+ });});diff --git a/apps/client/src/widgets/react/NoteAutocomplete.tsx b/apps/client/src/widgets/react/NoteAutocomplete.tsxindex 114fee0bde..35868ca4f7 100644--- a/apps/client/src/widgets/react/NoteAutocomplete.tsx+++ b/apps/client/src/widgets/react/NoteAutocomplete.tsx@@ -438,10 +438,12 @@ export default function NoteAutocomplete({ id, inputRef: externalInputRef, text,* creation row: `onPick` then receives a promise, settling on `undefined` where the creation is* canceled.*/-export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect = true, onPick, handleRef, elementRef }: {+export function NoteMentionList({ query, anchor, allowCreatingNotes, parentNotePath, preselect = true, onPick, handleRef, elementRef }: {query: string;anchor: PopupProps["anchor"];allowCreatingNotes?: boolean;+ /** The note the host edits, which a child note is created under. */+ parentNotePath?: string | null;/** Opens the list with an entry highlighted, so that Enter takes it. */preselect?: boolean;onPick(notePath: string | Promise<string | undefined>): void;@@ -459,7 +461,7 @@ export function NoteMentionList({ query, anchor, allowCreatingNotes, preselect =source,onPick: (suggestion: Suggestion) => {if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {- onPick(createNoteFromSuggestion(suggestion));+ onPick(createNoteFromSuggestion(suggestion, parentNotePath));} else if (suggestion.notePath) {onPick(suggestion.notePath);}diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 84acee25c3..7be1a173f2 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -36,24 +36,11 @@ type AttributeCommandNames = FilteredCommandNames<CommandData>;*/const BLINK_DURATION = 300;-// 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,- // Relation targets are note titles, which contain spaces.- allowSpaces: true,- list: () => createNoteMentionList({ allowCreatingNotes: true, preselect: false })- }-];-interface AttributeEditorProps {api: MutableRef<AttributeEditorImperativeHandlers | null>;note: FNote;componentId: string;+ notePath?: string | null;ntxId?: string | null;hidden?: boolean;/**@@ -70,7 +57,7 @@ export interface AttributeEditorImperativeHandlers {renderOwnedAttributes(ownedAttributes: FAttribute[]): Promise<void>;}-export default function AttributeEditor({ api, note, componentId, ntxId, hidden, hideHelpButton }: AttributeEditorProps) {+export default function AttributeEditor({ api, note, componentId, notePath, ntxId, hidden, hideHelpButton }: AttributeEditorProps) {const [ currentValue, setCurrentValue ] = useState("");const [ error, setError ] = useState<unknown>();const [ needsSaving, setNeedsSaving ] = useState(false);@@ -83,6 +70,10 @@ export default function AttributeEditor({ api, note, componentId, ntxId, hidden,const currentValueRef = useRef(currentValue);const wrapperRef = useRef<HTMLDivElement>(null);const editorRef = useRef<CKEditorApi>();+ // The editor outlives a switch to another note, so its `@` list reads the path as it opens.+ const notePathRef = useRef(notePath);+ notePathRef.current = notePath;+ const hostedMentions = useMemo(() => buildHostedMentions(() => notePathRef.current), []);// The CKEditor bundle is heavy and this component mounts in always-visible containers// (e.g. the status bar), so the editor class is loaded on demand to keep CKEditor out@@ -407,6 +398,25 @@ export default function AttributeEditor({ api, note, componentId, ntxId, hidden,* 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.*/+/**+ * The lists for the markers typed in the editor. 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.+ */+function buildHostedMentions(getNotePath: () => string | null | undefined): MentionHostedFeed[] {+ return [+ attributeNameMention("#", "label"),+ attributeNameMention("~", "relation"),+ {+ marker: "@",+ minimumCharacters: 0,+ // Relation targets are note titles, which contain spaces.+ allowSpaces: true,+ list: () => createNoteMentionList({ allowCreatingNotes: true, preselect: false, getParentNotePath: getNotePath })+ }+ ];+}+function attributeNameMention(marker: "#" | "~", type: "label" | "relation"): MentionHostedFeed {return {marker,diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex 56ac53c09c..05ac1b0473 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -35,7 +35,8 @@ export interface BuildEditorOptions {contentLanguage: string | null;templates: SnippetDefinition[];/**- * Names the note the editor is open on, for the AI assistant to say where a run is writing.+ * Names the note the editor is open on, for the AI assistant to say where a run is writing and+ * for the `@` list to create a child note under.* A getter rather than the note itself: switching notes reuses the editor, so anything captured* here would name the note that happened to be open when it was built.*/@@ -311,7 +312,10 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConfiminimumCharacters: 0,// Note titles contain spaces, so the query must be allowed to as well.allowSpaces: true,- list: () => createNoteMentionList({ allowCreatingNotes: true })+ list: () => createNoteMentionList({+ allowCreatingNotes: true,+ getParentNotePath: () => opts.getNoteLocation?.()?.notePath+ })}] : []};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.tsxindex 76886d85c4..bd362c8792 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@@ -60,6 +60,23 @@ describe("createNoteMentionList", () => {expect(await canceled.commit.mock.calls[0]?.[0]).toBeUndefined();canceled.list.destroy?.();});++ it("creates a child note under the note the editor is open on when the row is picked", async () => {+ const childRow = { action: "create-child-note", noteTitle: "al", parentNoteId: "active", highlightedNotePathTitle: "Create child" };+ getNoteSuggestions.mockResolvedValue([ childRow ] as never);+ createNoteFromSuggestion.mockResolvedValue(undefined);+ let editedNotePath = "root/first";+ const list = createNoteMentionList({ allowCreatingNotes: true, getParentNotePath: () => editedNotePath });+ const commit = vi.fn<MentionHostedListState["commit"]>();+ // The editor is reused for the next note, so the parent is read as the list is shown.+ editedNotePath = "root/second";+ await act(async () => list.show({ query: "al", caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit }));+ await act(async () => { await vi.advanceTimersByTimeAsync(300); });++ list.handleKeyDown(new KeyboardEvent("keydown", { key: "Enter", cancelable: true }));+ expect(createNoteFromSuggestion).toHaveBeenLastCalledWith(childRow, "root/second");+ list.destroy?.();+ });});describe("createAutocompleteMentionList", () => {@@ -136,6 +153,25 @@ describe("createSlashCommandList", () => {expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "snippet-0", definition: definitions[1] });list.destroy?.();});++ it("runs on Tab the command of the refined query, not the one highlighted before it", async () => {+ const search = vi.fn((query: string) => query === "g" ? [ definitions[1] ] : definitions);+ const editor = { plugins: { get: () => ({ search }) } } as unknown as Parameters<NonNullable<SlashCommandConfig["list"]>>[0];+ const list = createSlashCommandList(editor);+ const commit = vi.fn<MentionHostedListState["commit"]>();+ const show = (query: string) => list.show({ query, caretRect: () => new DOMRect(10, 10, 1, 16), editable: null, commit });++ await act(async () => show(""));+ await act(async () => {});+ show("g");+ expect(list.handleKeyDown(new KeyboardEvent("keydown", { key: "Tab", cancelable: true }))).toBe(true);+ expect(commit).not.toHaveBeenCalled();++ // Rendered outside `act`, the lookup effect waits for the next frame.+ await act(() => new Promise((resolve) => setTimeout(resolve, 100)));+ expect(commit).toHaveBeenCalledExactlyOnceWith({ id: "snippet-0", definition: definitions[1] });+ list.destroy?.();+ });});describe("createEmojiList", () => {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.tsxindex 1a7fe07549..a210f0a046 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@@ -19,15 +19,21 @@ 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.*/-export function createNoteMentionList({ allowCreatingNotes, preselect }: {+export function createNoteMentionList({ allowCreatingNotes, preselect, getParentNotePath }: {allowCreatingNotes?: boolean;preselect?: boolean;+ /**+ * The note the editor is open on, which a child note is created under. A getter, as switching+ * notes reuses the editor.+ */+ getParentNotePath?(): string | null | undefined;} = {}): MentionHostedList {return createHostedList((state, list) => (<NoteMentionList{...list}query={state.query}allowCreatingNotes={allowCreatingNotes}+ parentNotePath={getParentNotePath?.()}preselect={preselect}onPick={(notePath) => state.commit(typeof notePath === "string"? toMention(notePath)