Skip to content

Build your personal knowledge base with Trilium Notes

feat(script api): add api.createNote() for frontend note creation

Elian Doran9973ca36d49c
diff --git a/apps/client/src/services/frontend_script_api.spec.ts b/apps/client/src/services/frontend_script_api.spec.ts
index a4860c71e3..8deec2be42 100644
--- a/apps/client/src/services/frontend_script_api.spec.ts
+++ b/apps/client/src/services/frontend_script_api.spec.ts
@@ -9,6 +9,7 @@ import FrontendScriptApi, { BackendScriptingDisabledError, type Api, type Entity
import { preactAPI } from "./frontend_script_api_preact.js";
import froca from "./froca.js";
import linkService from "./link.js";
+import noteCreateService from "./note_create.js";
import noteTooltipService from "./note_tooltip.js";
import options from "./options.js";
import protectedSessionService from "./protected_session.js";
@@ -452,6 +453,20 @@ describe("froca passthroughs", () => {
window.glob.instanceName = "inst-A";
expect(makeApi().getInstanceName()).toBe("inst-A");
});
+
+ it("createNote delegates to the note-create service and defaults opts to {}", async () => {
+ const note = buildNote({ title: "Created" });
+ const createNote = vi.spyOn(noteCreateService, "createNote").mockResolvedValue({ note, branch: undefined });
+ const api = makeApi();
+
+ const result = await api.createNote("root", { title: "Created", type: "text" });
+ expect(createNote).toHaveBeenCalledWith("root", { title: "Created", type: "text" });
+ expect(result).toEqual({ note, branch: undefined });
+
+ // opts defaults to an empty object when omitted
+ await (api.createNote as (p: string) => Promise<unknown>)("root");
+ expect(createNote).toHaveBeenLastCalledWith("root", {});
+ });
});
describe("commands and events", () => {
diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.ts
index ae986e709c..a76082f78c 100644
--- a/apps/client/src/services/frontend_script_api.ts
+++ b/apps/client/src/services/frontend_script_api.ts
@@ -5,6 +5,7 @@ import DOMPurify from "dompurify";
import appContext from "../components/app_context.js";
import type Component from "../components/component.js";
import type NoteContext from "../components/note_context.js";
+import type FBranch from "../entities/fbranch.js";
import type FNote from "../entities/fnote.js";
import BasicWidget, { ReactWrappedWidget } from "../widgets/basic_widget.js";
import NoteContextAwareWidget from "../widgets/note_context_aware_widget.js";
@@ -15,6 +16,7 @@ import froca from "./froca.js";
import { preactAPI } from "./frontend_script_api_preact.js";
import { t } from "./i18n.js";
import linkService from "./link.js";
+import noteCreateService, { type CreateNoteOpts } from "./note_create.js";
import noteTooltipService from "./note_tooltip.js";
import options from "./options.js";
import protectedSessionService from "./protected_session.js";
@@ -232,6 +234,18 @@ export interface Api {
*/
reloadNotes(noteIds: string[]): Promise<void>;
+ /**
+ * Creates a new note as a child of the given parent, entirely on the frontend — no backend
+ * scripting required (unlike `api.runOnBackend(() => api.createTextNote(...))`). By default the
+ * new note is activated in the current tab with its title focused for editing; pass
+ * `{ activate: false }` to create it silently.
+ *
+ * @param parentNotePath note path (or noteId) of the parent under which to create the note
+ * @param opts creation options — e.g. `{ title, content, type, mime, activate }`
+ * @returns the created note and its branch, resolved from the frontend cache
+ */
+ createNote(parentNotePath: string, opts?: CreateNoteOpts): Promise<{ note: FNote | null; branch: FBranch | undefined }>;
+
/**
* Instance name identifies particular Trilium instance. It can be useful for scripts
* if some action needs to happen on only one specific instance.
@@ -661,6 +675,7 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig
this.getNote = async (noteId) => await froca.getNote(noteId);
this.getNotes = async (noteIds, silentNotFoundError = false) => await froca.getNotes(noteIds, silentNotFoundError);
this.reloadNotes = async (noteIds) => await froca.reloadNotes(noteIds);
+ this.createNote = async (parentNotePath, opts = {}) => await noteCreateService.createNote(parentNotePath, opts);
this.getInstanceName = () => window.glob.instanceName;
this.formatDateISO = utils.formatDateISO;
this.parseDate = utils.parseDate;
diff --git a/apps/server/src/assets/llm/skills/frontend_scripting.md b/apps/server/src/assets/llm/skills/frontend_scripting.md
index 97c72e47ae..dc5ca661ea 100644
--- a/apps/server/src/assets/llm/skills/frontend_scripting.md
+++ b/apps/server/src/assets/llm/skills/frontend_scripting.md
@@ -223,6 +223,13 @@ Concrete examples:
- `searchForNotes(searchString)` - search with full query syntax
- `searchForNote(searchString)` - search returning first result
+### Note creation
+- `createNote(parentNotePath, opts?)` - create a note under `parentNotePath` (a noteId or path) **entirely on the frontend — no backend scripting required.** `opts` accepts `{ title, content, type, mime, templateNoteId, isProtected, activate, focus, target, attributes }` and returns `{ note, branch }` from the cache. The new note is activated with its title focused by default; pass `{ activate: false }` to create it silently. **Prefer this over `runOnBackend(() => api.createTextNote(...))`** — the backend variant needs backend scripting, which is off by default.
+
+```jsx
+const { note } = await createNote(parentNoteId, { title: "New task", type: "text" });
+```
+
### Calendar/date notes
- `getTodayNote()` - get/create today's note
- `getDayNote(date)` / `getWeekNote(date)` / `getMonthNote(month)` / `getYearNote(year)`
diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.ts
index 02b8d6d181..9329aca84d 100644
--- a/packages/commons/src/lib/script_api.ts
+++ b/packages/commons/src/lib/script_api.ts
@@ -292,6 +292,41 @@ interface RightPanelWidget extends NoteContextAwareWidget {
/** Constructor type allowing `class X extends api.Widget { … }`. */
type WidgetClass<T> = new (...args: unknown[]) => T;
+/** An attribute to create together with a note (see {@link ScriptCreateNoteOpts.attributes}). */
+export interface ScriptCreateAttribute {
+ type: "label" | "relation";
+ name: string;
+ value?: string;
+ isInheritable?: boolean;
+ position?: number;
+}
+
+/** Options accepted by {@link FrontendApi.createNote}. */
+export interface ScriptCreateNoteOpts {
+ /** Title of the new note. */
+ title?: string | null;
+ /** Content of the new note (HTML for text notes, source for code notes, etc.). */
+ content?: string | null;
+ /** Note type, e.g. "text" (default), "code", "book". */
+ type?: string;
+ /** MIME type, e.g. "application/javascript;env=frontend" for a frontend code note. */
+ mime?: string;
+ /** Note ID of a template to apply to the new note. */
+ templateNoteId?: string;
+ /** Create the note as protected (only takes effect when a protected session is available). */
+ isProtected?: boolean;
+ /** Activate (open) the new note after creation. Defaults to `true`. */
+ activate?: boolean;
+ /** Which part of the activated note to focus. Defaults to "title". */
+ focus?: "title" | "content";
+ /** Where to place the note relative to the parent/target: "into" (default) or "after". */
+ target?: string;
+ /** Branch ID used together with `target: "after"`. */
+ targetBranchId?: string;
+ /** Attributes to set atomically on creation. */
+ attributes?: ScriptCreateAttribute[];
+}
+
/**
* The `api` global available inside **frontend** script notes
* (`application/javascript;env=frontend`).
@@ -440,6 +475,17 @@ export interface FrontendApi {
* Update frontend tree (note) cache from the backend.
*/
reloadNotes(noteIds: string[]): Promise<void>;
+ /**
+ * Creates a new note as a child of the given parent, entirely on the frontend — no backend
+ * scripting required (unlike `api.runOnBackend(() => api.createTextNote(...))`). By default the
+ * new note is activated in the current tab with its title focused for editing; pass
+ * `{ activate: false }` to create it silently.
+ *
+ * @param parentNotePath note path (or noteId) of the parent under which to create the note
+ * @param opts creation options — e.g. `{ title, content, type, mime, activate }`
+ * @returns the created note and its branch, resolved from the frontend cache
+ */
+ createNote(parentNotePath: string, opts?: ScriptCreateNoteOpts): Promise<{ note: ScriptFNote | null; branch: ScriptFBranch | null }>;
/**
* Instance name identifies particular Trilium instance. It can be useful for scripts
* if some action needs to happen on only one specific instance.