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
feat(autocomplete): offer creating a note in the inbox (closes #6817)
Elian Doran24070d069b0e
diff --git a/apps/client/src/services/date_notes.ts b/apps/client/src/services/date_notes.tsindex f452e55dec..838f1d3c75 100644--- a/apps/client/src/services/date_notes.ts+++ b/apps/client/src/services/date_notes.ts@@ -11,6 +11,13 @@ async function getInboxNote() {return await froca.getNote(note.noteId);}+/** Resolves the inbox note to a note path, for callers that create notes there. */+async function getInboxNotePath() {+ const inboxNote = await getInboxNote();++ return inboxNote?.getBestNotePathString();+}+async function getTodayNote() {return await getDayNote(dayjs().format("YYYY-MM-DD"));}@@ -135,6 +142,7 @@ async function getRecentLlmChats(limit: number = 10): Promise<RecentLlmChat[]> {export default {getInboxNote,+ getInboxNotePath,getTodayNote,getDayNote,getWeekFirstDayNote,diff --git a/apps/client/src/services/note_autocomplete.spec.ts b/apps/client/src/services/note_autocomplete.spec.tsindex 4c71dd4eed..80cf754599 100644--- a/apps/client/src/services/note_autocomplete.spec.ts+++ b/apps/client/src/services/note_autocomplete.spec.ts@@ -3,12 +3,13 @@ import $ from "jquery";// --- Mocks (hoisted above imports) ----const { triggerCommand, getActiveContextNoteId, getActiveContext, chooseNoteType, createNote, getAllCommands, searchCommands } = vi.hoisted(() => ({+const { triggerCommand, getActiveContextNoteId, getActiveContext, chooseNoteType, createNote, getInboxNotePath, getAllCommands, searchCommands } = vi.hoisted(() => ({triggerCommand: vi.fn(),getActiveContextNoteId: vi.fn<() => string | null>(() => "activeNote"),getActiveContext: vi.fn<() => any>(() => ({ hoistedNoteId: "hoisted" })),chooseNoteType: vi.fn(),createNote: vi.fn(),+ getInboxNotePath: vi.fn<() => Promise<string | undefined>>(async () => "root/inbox"),getAllCommands: vi.fn(() => [] as any[]),searchCommands: vi.fn(() => [] as any[])}));@@ -27,6 +28,10 @@ vi.mock("./note_create.js", () => ({default: { chooseNoteType, createNote }}));+vi.mock("./date_notes.js", () => ({+ default: { getInboxNotePath }+}));+vi.mock("./command_registry.js", () => ({default: { getAllCommands, searchCommands }}));@@ -105,7 +110,7 @@ describe("note_autocomplete", () => {]) as typeof server.get;const result = (await noteAutocomplete.autocompleteSourceForCKEditor("Foo")) as any[];- // autocompleteSourceForCKEditor forces allowCreatingNotes -> a create-note row is prepended.+ // autocompleteSourceForCKEditor forces allowCreatingNotes -> the creation rows are prepended.const mapped = result.find((r) => r.notePath === "root/abc");expect(mapped).toEqual({action: "search-notes",@@ -122,7 +127,7 @@ describe("note_autocomplete", () => {it("falls back to empty name when notePathTitle is missing", async () => {server.get = vi.fn(async () => []) as typeof server.get;const result = (await noteAutocomplete.autocompleteSourceForCKEditor("X")) as any[];- // only the synthetic create-note row remains; it has no notePathTitle.+ // only the synthetic creation rows remain; they have no notePathTitle.const createRow = result.find((r) => r.action === "create-note");expect(createRow).toBeDefined();expect(createRow!.name).toBe("");@@ -275,21 +280,24 @@ describe("autocompleteSource (via dataset)", () => {expect(server.get).not.toHaveBeenCalled();});- it("prepends a create-note suggestion when allowCreatingNotes and term is non-empty", async () => {+ it("prepends create-note and create-child-note suggestions when allowCreatingNotes and term is non-empty", async () => {server.get = vi.fn(async () => [{ noteTitle: "Existing", notePath: "root/y" }]) as typeof server.get;const { dataset } = initAndGetSource({ allowCreatingNotes: true });const rows = await runSource(dataset, "New");expect(rows[0].action).toBe("create-note");- expect(rows[0].parentNoteId).toBe("activeNote");- expect(rows[1].noteTitle).toBe("Existing");+ // the inbox is resolved on selection, so the row carries no parent+ expect(rows[0].parentNoteId).toBeUndefined();+ expect(rows[1].action).toBe("create-child-note");+ expect(rows[1].parentNoteId).toBe("activeNote");+ expect(rows[2].noteTitle).toBe("Existing");});- it("uses root as parent when there is no active note", async () => {+ it("uses root as the child-note parent when there is no active note", async () => {getActiveContextNoteId.mockReturnValue(null);server.get = vi.fn(async () => []) as typeof server.get;const { dataset } = initAndGetSource({ allowCreatingNotes: true });const rows = await runSource(dataset, "New");- expect(rows[0].parentNoteId).toBe("root");+ expect(rows[1].parentNoteId).toBe("root");});it("appends a search-notes suggestion when allowJumpToSearchNotes", async () => {@@ -311,8 +319,9 @@ describe("autocompleteSource (via dataset)", () => {server.get = vi.fn(async () => [{ noteTitle: "A", notePath: "root/a" }]) as typeof server.get;const { dataset } = initAndGetSource({ allowCreatingNotes: true, allowJumpToSearchNotes: true, allowExternalLinks: true });const rows = await runSource(dataset, " ");- // length === 0 so neither create-note nor search-notes nor external-link added+ // length === 0 so neither creation row nor search-notes nor external-link addedexpect(rows.every((r) => r.action !== "create-note")).toBe(true);+ expect(rows.every((r) => r.action !== "create-child-note")).toBe(true);expect(rows.every((r) => r.action !== "search-notes")).toBe(true);});@@ -357,6 +366,8 @@ describe("autocompleteSource (via dataset)", () => {.toContain("bx bx-search");expect(dataset.templates.suggestion({ action: "create-note", highlightedNotePathTitle: "C" })).toContain("bx bx-plus");+ expect(dataset.templates.suggestion({ action: "create-child-note", highlightedNotePathTitle: "C" }))+ .toContain("bx bx-plus");expect(dataset.templates.suggestion({ action: "external-link", highlightedNotePathTitle: "E" })).toContain("bx bx-link-external");});@@ -766,18 +777,35 @@ describe("autocomplete:selected handler", () => {expect(triggerCommand).toHaveBeenCalledWith("searchNotes", { searchString: "query" });});- it("creates a note then selects it", async () => {- const note = buildNote({ title: "Created" });+ it("creates a note in the inbox then selects it", async () => {chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });createNote.mockResolvedValue({ note: { getBestNotePathString: () => "root/created" } });const { $el, handlers } = initWithSelected();- await fireSelected($el, { action: "create-note", noteTitle: "Created", parentNoteId: "parent" });+ await fireSelected($el, { action: "create-note", noteTitle: "Created" });expect(chooseNoteType).toHaveBeenCalled();- expect(createNote).toHaveBeenCalledWith("parent", expect.objectContaining({ title: "Created", type: "text" }));+ expect(createNote).toHaveBeenCalledWith("root/inbox", expect.objectContaining({ title: "Created", type: "text" }));expect(handlers["autocomplete:noteselected"]).toBeDefined();expect(handlers["autocomplete:noteselected"].notePath).toBe("root/created");});+ it("creates a child note under the suggested parent", async () => {+ chooseNoteType.mockResolvedValue({ success: true, noteType: "text", templateNoteId: undefined, notePath: undefined });+ createNote.mockResolvedValue({ note: { getBestNotePathString: () => "root/created" } });+ const { $el } = initWithSelected();+ await fireSelected($el, { action: "create-child-note", noteTitle: "Created", parentNoteId: "parent" });+ expect(getInboxNotePath).not.toHaveBeenCalled();+ expect(createNote).toHaveBeenCalledWith("parent", expect.objectContaining({ title: "Created" }));+ });++ it("aborts when the inbox cannot be resolved", async () => {+ chooseNoteType.mockResolvedValue({ success: true, noteType: "text" });+ getInboxNotePath.mockResolvedValueOnce(undefined);+ const { $el, handlers } = initWithSelected();+ await fireSelected($el, { action: "create-note", noteTitle: "X" });+ expect(createNote).not.toHaveBeenCalled();+ expect(handlers["autocomplete:noteselected"]).toBeUndefined();+ });+it("aborts the create-note flow when the type chooser is cancelled", async () => {chooseNoteType.mockResolvedValue({ success: false });const { $el, handlers } = initWithSelected();diff --git a/apps/client/src/services/note_autocomplete.ts b/apps/client/src/services/note_autocomplete.tsindex a5f9809cc0..609d649180 100644--- a/apps/client/src/services/note_autocomplete.ts+++ b/apps/client/src/services/note_autocomplete.ts@@ -2,6 +2,7 @@ import type { MentionFeedObjectItem } from "@triliumnext/ckeditor5";import appContext from "../components/app_context.js";import commandRegistry from "./command_registry.js";+import dateNoteService from "./date_notes.js";import froca from "./froca.js";import { t } from "./i18n.js";import noteCreateService from "./note_create.js";@@ -32,7 +33,7 @@ export interface Suggestion {notePathTitle?: string;notePath?: string;highlightedNotePathTitle?: string;- action?: string | "create-note" | "search-notes" | "external-link" | "command";+ action?: string | "create-note" | "create-child-note" | "search-notes" | "external-link" | "command";parentNoteId?: string;icon?: string;commandId?: string;@@ -134,8 +135,13 @@ async function autocompleteSource(term: string, cb: (rows: Suggestion[]) => void{action: "create-note",noteTitle: term,- parentNoteId: activeNoteId || "root",highlightedNotePathTitle: t("note_autocomplete.create-note", { term })+ } as Suggestion,+ {+ action: "create-child-note",+ noteTitle: term,+ parentNoteId: activeNoteId || "root",+ highlightedNotePathTitle: t("note_autocomplete.create-child-note", { term })} as Suggestion].concat(results);}@@ -356,7 +362,7 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {let iconClass = suggestion.icon ?? "bx bx-note";if (suggestion.action === "search-notes") {iconClass = "bx bx-search";- } else if (suggestion.action === "create-note") {+ } else if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {iconClass = "bx bx-plus";} else if (suggestion.action === "external-link") {iconClass = "bx bx-link-external";@@ -405,12 +411,20 @@ function initNoteAutocomplete($el: JQuery<HTMLElement>, options?: Options) {return;}- if (suggestion.action === "create-note") {+ if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {const { success, noteType, templateNoteId, notePath, cloneToNoteIds } = await noteCreateService.chooseNoteType();if (!success) {return;}- const { note } = await noteCreateService.createNote( notePath || suggestion.parentNoteId, {++ const parentNotePath = notePath ?? (suggestion.action === "create-note"+ ? await dateNoteService.getInboxNotePath()+ : suggestion.parentNoteId);+ if (!parentNotePath) {+ return;+ }++ const { note } = await noteCreateService.createNote(parentNotePath, {title: suggestion.noteTitle,activate: false,type: noteType,diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.jsonindex dfb34e9573..58571662bc 100644--- a/apps/client/src/translations/en/translation.json+++ b/apps/client/src/translations/en/translation.json@@ -2977,7 +2977,8 @@},"note_autocomplete": {"search-for": "Search for \"{{term}}\"",- "create-note": "Create and link child note \"{{term}}\"",+ "create-note": "Create note \"{{term}}\"",+ "create-child-note": "Create child note \"{{term}}\"","insert-external-link": "Insert external link to \"{{term}}\"","clear-text-field": "Clear text field","show-recent-notes": "Show recent notes",diff --git a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsxindex 5191e145c9..e873af033f 100644--- a/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx+++ b/apps/client/src/widgets/ribbon/components/AttributeEditor.tsx@@ -14,6 +14,7 @@ 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 dateNoteService from "../../../services/date_notes";import froca from "../../../services/froca";import { t } from "../../../services/i18n";import { ATTRIBUTE_HELP_PAGE } from "../../../services/in_app_help";@@ -250,14 +251,14 @@ export default function AttributeEditor({ api, note, componentId, notePath, ntxI$el.text(title);},- createNoteForReferenceLink: async (title: string) => {- let result;- if (notePath) {- result = await note_create.createNoteWithTypePrompt(notePath, {- activate: false,- title- });- }+ createNoteForReferenceLink: async (title: string, intoInbox: boolean) => {+ const parentNotePath = intoInbox ? await dateNoteService.getInboxNotePath() : notePath;+ if (!parentNotePath) return;++ const result = await note_create.createNoteWithTypePrompt(parentNotePath, {+ activate: false,+ title+ });return result?.note?.getBestNotePathString();}diff --git a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsxindex 0b5a9ee11d..3ac9bcb2ab 100644--- a/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx+++ b/apps/client/src/widgets/type_widgets/llm_chat/ChatInputBar.tsx@@ -39,7 +39,7 @@ const mentionFeeds: MentionFeed[] = [const iconElement = document.createElement("span");let iconClass = item.icon ?? "bx bx-note";- if (item.action === "create-note") {+ if (item.action === "create-note" || item.action === "create-child-note") {iconClass = "bx bx-plus";}iconElement.className = iconClass;diff --git a/apps/client/src/widgets/type_widgets/text/EditableText.tsx b/apps/client/src/widgets/type_widgets/text/EditableText.tsxindex a3fadb8936..a41923b551 100644--- a/apps/client/src/widgets/type_widgets/text/EditableText.tsx+++ b/apps/client/src/widgets/type_widgets/text/EditableText.tsx@@ -7,6 +7,7 @@ import { useCallback, useEffect, useRef, useState } from "preact/hooks";import appContext from "../../../components/app_context";import { consumeBookmark } from "../../../services/bookmark_jump";+import dateNoteService from "../../../services/date_notes";import dialog from "../../../services/dialog";import { t } from "../../../services/i18n";import link, { parseNavigationStateFromUrl } from "../../../services/link";@@ -159,8 +160,8 @@ export default function EditableText({ note, parentComponent, ntxId, noteContextlinkEmbedService.renderMentionPreview(container, metadata, editable);},// Creating notes in @-completion- async createNoteForReferenceLink(title: string) {- const notePath = noteContext?.notePath;+ async createNoteForReferenceLink(title: string, intoInbox: boolean) {+ const notePath = intoInbox ? await dateNoteService.getInboxNotePath() : noteContext?.notePath;if (!notePath) return;const resp = await note_create.createNoteWithTypePrompt(notePath, {diff --git a/apps/client/src/widgets/type_widgets/text/config.ts b/apps/client/src/widgets/type_widgets/text/config.tsindex ddf6652d8d..be4a08f778 100644--- a/apps/client/src/widgets/type_widgets/text/config.ts+++ b/apps/client/src/widgets/type_widgets/text/config.ts@@ -305,7 +305,7 @@ export async function buildConfig(opts: BuildEditorOptions): Promise<EditorConficonst iconElement = document.createElement("span");// Choose appropriate icon based on actionlet iconClass = suggestion.icon ?? "bx bx-note";- if (suggestion.action === "create-note") {+ if (suggestion.action === "create-note" || suggestion.action === "create-child-note") {iconClass = "bx bx-plus";}iconElement.className = iconClass;diff --git a/packages/ckeditor5/src/augmentation.ts b/packages/ckeditor5/src/augmentation.tsindex a8f968f37d..3461787b91 100644--- a/packages/ckeditor5/src/augmentation.ts+++ b/packages/ckeditor5/src/augmentation.ts@@ -24,7 +24,7 @@ declare global {interface EditorComponent extends Component {loadReferenceLinkTitle($el: JQuery<HTMLElement>, href: string): Promise<void>;- createNoteForReferenceLink(title: string): Promise<string>;+ createNoteForReferenceLink(title: string, intoInbox: boolean): Promise<string | undefined>;loadIncludedNote(noteId: string, $el: JQuery<HTMLElement>, boxSize?: string): void;/*** Reads a page's preview metadata through the host. Never rejects: any failure — networkdiff --git a/packages/ckeditor5/src/plugins/mention_customization.spec.ts b/packages/ckeditor5/src/plugins/mention_customization.spec.tsindex 250ac11499..cfa5fadccd 100644--- a/packages/ckeditor5/src/plugins/mention_customization.spec.ts+++ b/packages/ckeditor5/src/plugins/mention_customization.spec.ts@@ -80,15 +80,18 @@ describe("MentionCustomization", () => {expect(getModelData(editor.model)).toContain("noteAbc");});- it("creates a note then inserts the reference link for a create-note mention", async () => {+ it.each([+ { action: "create-note", intoInbox: true },+ { action: "create-child-note", intoInbox: false }+ ])("creates a note then inserts the reference link for a $action mention", async ({ action, intoInbox }) => {setModelData(editor.model, "<paragraph>foo[]bar</paragraph>");editor.execute("mention", {- mention: { id: "@Brand new note", action: "create-note", noteTitle: "Brand new note" },+ mention: { id: "@Brand new note", action, noteTitle: "Brand new note" },marker: "@"});- expect(createNoteForReferenceLink).toHaveBeenCalledWith("Brand new note");+ expect(createNoteForReferenceLink).toHaveBeenCalledWith("Brand new note", intoInbox);// Wait for the createNoteForReferenceLink promise (and the chained// getReferenceLinkTitle promise from the referenceLink command) to resolve.diff --git a/packages/ckeditor5/src/plugins/mention_customization.ts b/packages/ckeditor5/src/plugins/mention_customization.tsindex 6fff23ed0d..cf87183763 100644--- a/packages/ckeditor5/src/plugins/mention_customization.ts+++ b/packages/ckeditor5/src/plugins/mention_customization.ts@@ -38,7 +38,7 @@ interface MentionOpts {interface MentionAttribute {id: string;- action?: "create-note";+ action?: "create-note" | "create-child-note";noteTitle: string;notePath: string;}@@ -58,12 +58,15 @@ class CustomMentionCommand extends Command {model.insertContent( writer.createText( mention.id, {} ), range );});}- else if (mention.action === 'create-note') {+ else if (mention.action === 'create-note' || mention.action === 'create-child-note') {const editorEl = this.editor.editing.view.getDomRoot();const component = glob.getComponentByEl<EditorComponent>(editorEl);+ const intoInbox = mention.action === 'create-note';- component.createNoteForReferenceLink(mention.noteTitle).then(notePath => {- this.insertReference(range, notePath);+ component.createNoteForReferenceLink(mention.noteTitle, intoInbox).then(notePath => {+ if (notePath) {+ this.insertReference(range, notePath);+ }});}else {diff --git a/packages/trilium-e2e/src/support/app.ts b/packages/trilium-e2e/src/support/app.tsindex 4cd4263c96..74789b4dd3 100644--- a/packages/trilium-e2e/src/support/app.ts+++ b/packages/trilium-e2e/src/support/app.ts@@ -107,13 +107,13 @@ export default class App {await autocomplete.clear();await autocomplete.pressSequentially(noteTitle);- // The second suggestion is the best candidate; the first is "Create a- // new note". Asserting on the suggestion itself (instead of the parent+ // The best candidate follows the two creation suggestions ("Create note" and+ // "Create child note"). Asserting on the suggestion itself (instead of the parent// `.note-detail-empty-results`, which also contains the recent-notes// list) ensures the dropdown actually opened.const suggestionSelector = this.currentNoteSplit.locator(".note-detail-empty-results .aa-suggestion")- .nth(1);+ .nth(2);await expect(suggestionSelector).toContainText(noteTitle);await suggestionSelector.click();}