Skip to content

Build your personal knowledge base with Trilium Notes

feat(codemirror/autocomplete): basic JSX support

Elian Doran4f10153ca801
diff --git a/apps/client/src/services/frontend_script_api.ts b/apps/client/src/services/frontend_script_api.ts
index e67ce12e73..55292d5a44 100644
--- a/apps/client/src/services/frontend_script_api.ts
+++ b/apps/client/src/services/frontend_script_api.ts
@@ -1,4 +1,5 @@
import { dayjs, formatLogMessage } from "@triliumnext/commons";
+import type { FrontendApi as PublicFrontendApi, ScriptFNote as PublicScriptFNote } from "@triliumnext/commons/src/lib/script_api.js";
import appContext from "../components/app_context.js";
import type Component from "../components/component.js";
@@ -730,3 +731,15 @@ function FrontendScriptApi(this: Api, startNote: FNote, currentNote: FNote, orig
export default FrontendScriptApi as any as {
new(startNote: FNote, currentNote: FNote, originEntity: Entity | null, $container: JQuery<HTMLElement> | null): Api;
};
+
+// --- Drift guards -----------------------------------------------------------
+// The public script API surface lives in @triliumnext/commons (self-contained so
+// it can feed the in-editor language service and the script-deployer). These
+// checks fail to compile — naming the offending member — if that public surface
+// claims an `api`/`FNote` member that has since been renamed or removed here.
+type _MissingApiMembers = Exclude<keyof PublicFrontendApi, keyof Api>;
+type _MissingFNoteMembers = Exclude<keyof PublicScriptFNote, keyof FNote>;
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const _apiDriftGuard: [_MissingApiMembers] extends [never] ? true : _MissingApiMembers = true;
+// eslint-disable-next-line @typescript-eslint/no-unused-vars
+const _fnoteDriftGuard: [_MissingFNoteMembers] extends [never] ? true : _MissingFNoteMembers = true;
diff --git a/apps/script-deployer/src/trilium-env.d.ts b/apps/script-deployer/src/trilium-env.d.ts
index 31a81e4c2c..6d8249ea37 100644
--- a/apps/script-deployer/src/trilium-env.d.ts
+++ b/apps/script-deployer/src/trilium-env.d.ts
@@ -8,11 +8,14 @@
* runtime — but providing declarations here gives us editor
* intellisense and `tsc` checking for scripts in the `scripts/` dir.
*
- * Types are pulled directly from the real implementations so they
- * stay in sync automatically.
+ * The frontend `api` surface comes from the shared public script-API module in
+ * `@triliumnext/commons` — the same definition the in-editor language service
+ * uses — so the deployer and the editor agree. It's kept honest against the real
+ * implementation by drift guards in `frontend_script_api.ts`. The Preact API is
+ * still pulled directly from its real implementation.
*/
-type FrontendApi = import("@triliumnext/client/src/services/frontend_script_api").Api;
+type FrontendApi = import("@triliumnext/commons/src/lib/script_api").FrontendApi;
type PreactApi = typeof import("@triliumnext/client/src/services/frontend_script_api_preact").preactAPI;
/**
diff --git a/packages/codemirror/src/type_completion/frontend_api.ts b/packages/codemirror/src/type_completion/frontend_api.ts
deleted file mode 100644
index 851f72d2c1..0000000000
--- a/packages/codemirror/src/type_completion/frontend_api.ts
+++ /dev/null
@@ -1,125 +0,0 @@
-/**
- * Ambient type definitions fed to the TypeScript language service when editing
- * a **frontend** script note (`application/javascript;env=frontend`).
- *
- * This is a hand-curated subset of the real `Api` interface declared in
- * `apps/client/src/services/frontend_script_api.ts`. It is intentionally a
- * standalone `.d.ts` (no imports) so it can be loaded directly into the
- * in-browser virtual TypeScript environment without resolving the client's
- * whole transitive type graph.
- *
- * Follow-up (see PoC notes): replace this curated stub with an auto-generated,
- * fully-faithful declaration produced from the live source at build time.
- */
-export default /* ts */ `
-interface FAttribute {
- attributeId: string;
- type: "label" | "relation";
- name: string;
- value: string;
- isInheritable: boolean;
-}
-
-interface FNote {
- noteId: string;
- title: string;
- type: string;
- mime: string;
- isProtected: boolean;
- getParentNotes(): FNote[];
- getChildNotes(): Promise<FNote[]>;
- getAttributes(type?: string, name?: string): FAttribute[];
- getOwnedAttributes(type?: string, name?: string): FAttribute[];
- getLabelValue(name: string): string | null;
- getLabels(name?: string): FAttribute[];
- hasLabel(name: string): boolean;
- getContent(): Promise<string>;
- getNoteComplement(): Promise<unknown>;
-}
-
-interface NoteContext {
- ntxId: string | null;
- note: FNote | null;
- notePath: string | null;
- getCodeEditor(): Promise<unknown>;
- getTextEditor(): Promise<unknown>;
-}
-
-/** Trilium frontend script API, exposed to "JS frontend" code notes as the global \`api\`. */
-interface FrontendApi {
- /** Note where the script started executing (the event entrypoint). */
- startNote: FNote;
- /** Note where the script is currently executing. */
- currentNote: FNote;
- /** Entity whose event triggered this execution (or null). */
- originEntity: unknown | null;
- /** day.js instance for date manipulation. See https://day.js.org */
- dayjs: (date?: string | number | Date) => { format(template: string): string };
-
- /** Activates a note in the tree and in the note detail. */
- activateNote(notePath: string): Promise<void>;
- /** Activates a newly created note, ensuring the frontend has fully synced first. */
- activateNewNote(notePath: string): Promise<void>;
- /** Opens a note in a new tab. */
- openTabWithNote(notePath: string, activate: boolean): Promise<void>;
- /** Opens a note in a new split. */
- openSplitWithNote(notePath: string, activate: boolean): Promise<void>;
-
- /** Executes the given (synchronous) function on the backend. */
- runOnBackend(func: (...args: unknown[]) => unknown, params?: unknown[]): Promise<unknown>;
- /** Executes the given async function on the backend with manual transaction handling. */
- runAsyncOnBackendWithManualTransactionHandling(func: (...args: unknown[]) => unknown, params?: unknown[]): Promise<unknown>;
-
- /** Powerful attribute/value search, e.g. "#dateModified =* MONTH AND #log". */
- searchForNotes(searchString: string): Promise<FNote[]>;
- /** Returns the first note matching the search, or null. */
- searchForNote(searchString: string): Promise<FNote | null>;
- /** Returns a note by its ID (loading it into the cache if needed). */
- getNote(noteId: string): Promise<FNote | null>;
- /** Returns multiple notes by their IDs. */
- getNotes(noteIds: string[], silentNotFoundError?: boolean): Promise<FNote[]>;
-
- /** Returns the active note context. */
- getActiveContext(): NoteContext | null;
- /** Returns the note currently active in the detail. */
- getActiveContextNote(): FNote | null;
- /** Returns the CodeMirror editor of the active code note, if any. */
- getActiveContextCodeEditor(): Promise<unknown>;
- /** Returns the text editor of the active text note, if any. */
- getActiveContextTextEditor(): Promise<unknown>;
-
- /** Calendar helpers. */
- getDayNote(date: string): Promise<FNote | null>;
- getTodayNote(): Promise<FNote | null>;
- getWeekNote(date: string): Promise<FNote | null>;
- getMonthNote(month: string): Promise<FNote | null>;
- getYearNote(year: string): Promise<FNote | null>;
-
- /** Shows an info-level toast message to the user. */
- showMessage(message: string, delay?: number): void;
- /** Shows an error-level toast message to the user. */
- showError(message: string, delay?: number): void;
- /** Shows a confirm dialog; resolves to true if confirmed. */
- showConfirmDialog(message: string): Promise<boolean>;
- /** Shows a prompt dialog; resolves to the entered string. */
- showPromptDialog(props: { title?: string; message?: string; defaultValue?: string }): Promise<string | null>;
-
- /** Binds a global keyboard shortcut to a handler. */
- bindGlobalShortcut(keyboardShortcut: string, handler: () => void, namespace?: string): void;
- /** Waits until the frontend is fully synced with the backend. */
- waitUntilSynced(): Promise<void>;
- /** Reloads the given notes from the server into the cache. */
- reloadNotes(noteIds: string[]): Promise<void>;
-
- /** Writes a line to the script log (visible in the UI). */
- log(message: string): void;
- /** Generates a random alphanumeric string of the given length. */
- randomString(length: number): string;
- /** Formats a note size (in bytes) into a human-readable string. */
- formatSize(size: number): string;
- /** Triggers a Trilium command. */
- triggerCommand(name: string, data?: Record<string, unknown>): void;
-}
-
-declare const api: FrontendApi;
-`;
diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.ts
index 40e31486b1..790bc798b8 100644
--- a/packages/codemirror/src/type_completion/index.spec.ts
+++ b/packages/codemirror/src/type_completion/index.spec.ts
@@ -1,6 +1,6 @@
import { describe, expect, it } from "vitest";
-import { getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND } from "./index.js";
+import { getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SCRIPT_MIME_JSX } from "./index.js";
/** "Property 'x' does not exist on type 'y'." */
const TS_UNKNOWN_PROPERTY = 2339;
@@ -93,4 +93,38 @@ describe("script note diagnostics", () => {
);
expect(codes).toContain(TS_UNKNOWN_PROPERTY);
}, TIMEOUT);
+
+ it("parses JSX in render notes without nagging about intrinsic elements (TS7026)", async () => {
+ // Minimal JSX support: intrinsic elements have no typing yet and fall back
+ // to `any` — which must stay quiet rather than erroring on every tag.
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "const el = <div className=\"box\"><span>hi</span></div>;"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
+ it("resolves the trilium:preact import a render note uses (TS2307)", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { h, Fragment } from \"trilium:preact\";\nexport default function App() { return <><div>hi</div></>; }"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
+ it("provides jQuery to JSX render notes (browser runtime, like frontend)", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "const $widget = $('<div>'); $widget.addClass('active');"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
+ it("still surfaces real errors in JSX notes (unknown api member)", async () => {
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "api.thisMethodDoesNotExist();\nconst el = <div/>;"
+ );
+ expect(codes).toContain(TS_UNKNOWN_PROPERTY);
+ }, TIMEOUT);
});
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index 1a4d5dc688..6bc1a90f58 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -2,7 +2,6 @@ import type { CompletionSource } from "@codemirror/autocomplete";
import type { Extension } from "@codemirror/state";
import backendApiDts from "./backend_api.js";
-import frontendApiDts from "./frontend_api.js";
/**
* Full IntelliSense for backend/frontend script notes.
@@ -20,14 +19,43 @@ import frontendApiDts from "./frontend_api.js";
export const SCRIPT_MIME_FRONTEND = "application/javascript;env=frontend";
export const SCRIPT_MIME_BACKEND = "application/javascript;env=backend";
+/**
+ * JSX render notes. They run in the browser like frontend scripts but are
+ * transpiled (sucrase) to Preact `h`/`Fragment` calls before execution — see
+ * `buildJsx` in `packages/trilium-core/src/services/script.ts`.
+ */
+export const SCRIPT_MIME_JSX = "text/jsx";
export function isScriptMime(mime: string): boolean {
- return mime === SCRIPT_MIME_FRONTEND || mime === SCRIPT_MIME_BACKEND;
+ return mime === SCRIPT_MIME_FRONTEND || mime === SCRIPT_MIME_BACKEND || mime === SCRIPT_MIME_JSX;
+}
+
+/** Frontend and JSX scripts share the browser runtime (frontend `api`, jQuery). */
+function isFrontendMime(mime: string): boolean {
+ return mime === SCRIPT_MIME_FRONTEND || mime === SCRIPT_MIME_JSX;
}
const SCRIPT_PATH = "/script.js";
-const API_DTS_PATH = "/trilium-api.d.ts";
+// TypeScript only parses JSX when the source file has a `.tsx`/`.jsx` extension,
+// so JSX notes get their own virtual path.
+const JSX_SCRIPT_PATH = "/script.tsx";
+/** Ambient file declaring the `api` global (a bridge for frontend, the curated stub for backend). */
+const API_GLOBALS_PATH = "/trilium-api.d.ts";
+/** The shared public API types module (frontend), injected verbatim from commons. */
+const API_TYPES_PATH = "/trilium-script-api.ts";
const JQUERY_DTS_PATH = "/jquery-globals.d.ts";
+const TRILIUM_MODULES_DTS_PATH = "/trilium-modules.d.ts";
+
+/** The virtual source-file path used for a given script MIME type. */
+function scriptPath(mime: string): string {
+ return mime === SCRIPT_MIME_JSX ? JSX_SCRIPT_PATH : SCRIPT_PATH;
+}
+
+// Shorthand ambient declarations for the bare-specifier imports a JSX render
+// note uses (`import { h } from "trilium:preact"`). A bodyless `declare module`
+// types every import from them as `any` — enough to silence "cannot find
+// module" (TS2307) without (yet) vendoring real Preact types.
+const triliumModulesDts = `declare module "trilium:preact";\ndeclare module "trilium:api";\n`;
const COMPILER_OPTIONS = {
// `target`/`lib` are filled in lazily once TypeScript is loaded (needs the ts enums).
@@ -57,27 +85,51 @@ async function createEnv(mime: string) {
// map so concurrent script notes (e.g. split view) don't clobber each
// other's source file.
const fsMap = new Map<string, string>(Object.entries(tsLibFiles));
- fsMap.set(API_DTS_PATH, mime === SCRIPT_MIME_BACKEND ? backendApiDts : frontendApiDts);
+ const path = scriptPath(mime);
// Seed with a space, never an empty string: `@typescript/vfs` treats an
// empty root file as "not found" (TS6053) at program creation. `tsSync`
// likewise pushes `doc || ' '`, so the script file is never empty at runtime.
- fsMap.set(SCRIPT_PATH, " ");
-
- const rootFiles = [SCRIPT_PATH, API_DTS_PATH];
-
- // Frontend scripts run in the browser with jQuery available as `$` / `jQuery`;
- // backend scripts run server-side and have neither. Inject the vendored jQuery
- // global declarations (lazily) only for frontend notes.
- if (mime === SCRIPT_MIME_FRONTEND) {
+ fsMap.set(path, " ");
+
+ const rootFiles = [path, API_GLOBALS_PATH];
+
+ if (isFrontendMime(mime)) {
+ // Frontend `api` types come from the shared, self-contained public surface
+ // in @triliumnext/commons (single source of truth, drift-guarded against the
+ // real implementation). Inject the module verbatim plus a bridge that exposes
+ // it as the `api` global. Relative `?raw` (not a bare specifier) so it lands
+ // in the lazy chunk and isn't gated by package `exports`.
+ const apiTypes = (await import("../../../commons/src/lib/script_api.ts?raw")).default;
+ fsMap.set(API_TYPES_PATH, apiTypes);
+ fsMap.set(API_GLOBALS_PATH, `import type { FrontendApi } from "./trilium-script-api";\ndeclare global {\n // eslint-disable-next-line no-var\n var api: FrontendApi;\n}\n`);
+ rootFiles.push(API_TYPES_PATH);
+
+ // Frontend scripts run in the browser with jQuery available as `$` / `jQuery`;
+ // backend scripts run server-side and have neither.
const { jqueryGlobals } = await import("./jquery_types.js");
fsMap.set(JQUERY_DTS_PATH, jqueryGlobals);
rootFiles.push(JQUERY_DTS_PATH);
+ } else {
+ // Backend still uses the curated stub (migrating to the shared module next).
+ fsMap.set(API_GLOBALS_PATH, backendApiDts);
+ }
+
+ if (mime === SCRIPT_MIME_JSX) {
+ // JSX notes import Preact/the api via bare specifiers (`trilium:preact`,
+ // `trilium:api`); declare them so those imports resolve.
+ fsMap.set(TRILIUM_MODULES_DTS_PATH, triliumModulesDts);
+ rootFiles.push(TRILIUM_MODULES_DTS_PATH);
}
const compilerOptions = {
...COMPILER_OPTIONS,
target: ts.ScriptTarget.ES2020,
- lib: ["es2020", "dom"]
+ lib: ["es2020", "dom"],
+ // `Preserve` type-checks JSX without requiring a factory symbol in scope.
+ // Intrinsic elements fall back to `any` (no `JSX.IntrinsicElements`), which
+ // `noImplicitAny: false` keeps quiet — so JSX parses without nagging until
+ // real Preact types are vendored.
+ ...(mime === SCRIPT_MIME_JSX ? { jsx: ts.JsxEmit.Preserve } : {})
};
const system = createSystem(fsMap);
@@ -109,7 +161,7 @@ export async function buildTypeCompletion(mime: string): Promise<TypeCompletion>
return {
extensions: [
- tsFacet.of({ env, path: SCRIPT_PATH }),
+ tsFacet.of({ env, path: scriptPath(mime) }),
tsSync(),
tsLinter({ diagnosticCodesToIgnore: ignoredDiagnosticCodes(mime) }),
tsHover()
@@ -133,6 +185,13 @@ const TS_TOP_LEVEL_AWAIT = 1375;
* frontend scripts but genuinely invalid in backend ones.
*/
function ignoredDiagnosticCodes(mime: string): number[] {
+ // JSX render notes are real modules (`import`/`export default`) transpiled by
+ // `buildJsx`, not wrapped in a function — so the function-body grammar
+ // exemptions below don't apply (top-level `return` is genuinely invalid, and
+ // top-level `await` is allowed natively in a module).
+ if (mime === SCRIPT_MIME_JSX) {
+ return [];
+ }
const codes = [TS_RETURN_OUTSIDE_FUNCTION];
if (mime === SCRIPT_MIME_FRONTEND) {
codes.push(TS_TOP_LEVEL_AWAIT);
@@ -150,10 +209,11 @@ function ignoredDiagnosticCodes(mime: string): number[] {
*/
export async function getScriptDiagnosticCodes(mime: string, code: string): Promise<number[]> {
const env = await createEnv(mime);
- env.updateFile(SCRIPT_PATH, code.length ? code : " ");
+ const path = scriptPath(mime);
+ env.updateFile(path, code.length ? code : " ");
const diagnostics = [
- ...env.languageService.getSyntacticDiagnostics(SCRIPT_PATH),
- ...env.languageService.getSemanticDiagnostics(SCRIPT_PATH)
+ ...env.languageService.getSyntacticDiagnostics(path),
+ ...env.languageService.getSemanticDiagnostics(path)
];
const ignored = ignoredDiagnosticCodes(mime);
return diagnostics
diff --git a/packages/commons/src/lib/script_api.ts b/packages/commons/src/lib/script_api.ts
new file mode 100644
index 0000000000..c1dcb6fa2d
--- /dev/null
+++ b/packages/commons/src/lib/script_api.ts
@@ -0,0 +1,224 @@
+/**
+ * Public type surface for Trilium **user scripts** — the shape of the `api`
+ * global available inside frontend/backend script notes.
+ *
+ * This is the single source of truth for script API types, consumed by:
+ * - the in-editor TypeScript language service (bundled into the script-note vfs),
+ * - the `script-deployer` app (script authoring/typechecking),
+ * and kept honest against the real implementations by member-presence drift
+ * guards (see `frontend_script_api.ts` / `backend_script_api.ts`).
+ *
+ * It is intentionally **self-contained** (no imports): the real `Api` interfaces
+ * drag in the whole client/server graph (froca, widgets, jQuery, Vite `?raw`
+ * imports) which can't be resolved by a browser-based language service. These
+ * are faithful, decoupled re-declarations of the public surface — heavy or
+ * advanced members (widget base classes, editor instances, the Preact API) are
+ * typed as `unknown` rather than pulling in their real types.
+ */
+
+/** A label or relation attached to a note. */
+export interface ScriptAttribute {
+ attributeId: string;
+ type: "label" | "relation";
+ name: string;
+ value: string;
+ isInheritable: boolean;
+ isOwned: boolean;
+}
+
+/** A note as seen by frontend scripts (subset of the client's `FNote`). */
+export interface ScriptFNote {
+ noteId: string;
+ title: string;
+ type: string;
+ mime: string;
+ isProtected: boolean;
+ attributes: string[];
+ parents: string[];
+ children: string[];
+
+ getParentNotes(): ScriptFNote[];
+ getChildNotes(): Promise<ScriptFNote[]>;
+ getParentNoteIds(): string[];
+ getChildNoteIds(): string[];
+
+ getAttributes(type?: string, name?: string): ScriptAttribute[];
+ getOwnedAttributes(type?: string, name?: string): ScriptAttribute[];
+ getAttribute(type: string, name: string): ScriptAttribute | null;
+ hasAttribute(type: string, name: string): boolean;
+ getLabels(name?: string): ScriptAttribute[];
+ getLabelValue(name: string): string | null;
+ hasLabel(name: string): boolean;
+ getRelations(name?: string): ScriptAttribute[];
+ getRelationValue(name: string): string | null;
+ getRelationTarget(name: string): Promise<ScriptFNote | null>;
+
+ getContent(): Promise<string | Uint8Array>;
+ getIcon(): string;
+ isRoot(): boolean;
+}
+
+/** A split/tab context as seen by frontend scripts (subset of `NoteContext`). */
+export interface ScriptNoteContext {
+ ntxId: string | null;
+ note: ScriptFNote | null;
+ notePath: string | null;
+ getCodeEditor(): Promise<unknown>;
+ getTextEditor(): Promise<unknown>;
+}
+
+/** Minimal day.js surface (the real API exposes the full day.js factory). */
+export type ScriptDayjs = (date?: string | number | Date) => {
+ format(template?: string): string;
+ add(value: number, unit: string): ReturnType<ScriptDayjs>;
+ subtract(value: number, unit: string): ReturnType<ScriptDayjs>;
+ toDate(): Date;
+};
+
+type Func = ((...args: unknown[]) => unknown) | string;
+
+/**
+ * The `api` global available inside **frontend** script notes
+ * (`application/javascript;env=frontend`).
+ */
+export interface FrontendApi {
+ /** Container of all the rendered script content (jQuery element). */
+ $container: unknown;
+ /** Note where the script started executing (the event entrypoint). */
+ startNote: ScriptFNote;
+ /** Note where the script is currently executing. */
+ currentNote: ScriptFNote;
+ /** Entity whose event triggered this execution (a note, or null). */
+ originEntity: unknown | null;
+ /** day.js library for date manipulation. See https://day.js.org */
+ dayjs: ScriptDayjs;
+
+ /** Base class for right-panel widgets. */
+ RightPanelWidget: unknown;
+ /** Base class for note-context-aware widgets. */
+ NoteContextAwareWidget: unknown;
+ /** Base class for basic widgets. */
+ BasicWidget: unknown;
+
+ /** Activates a note in the tree and in the note detail. */
+ activateNote(notePath: string): Promise<void>;
+ /** Activates a newly created note, ensuring the frontend has fully synced first. */
+ activateNewNote(notePath: string): Promise<void>;
+ /** Opens a note in a new tab. */
+ openTabWithNote(notePath: string, activate: boolean): Promise<void>;
+ /** Opens a note in a new split. */
+ openSplitWithNote(notePath: string, activate: boolean): Promise<void>;
+
+ /** Executes the given (synchronous) function on the backend. */
+ runOnBackend(func: Func, params?: unknown[]): Promise<unknown>;
+ /** Executes the given async function on the backend with manual transaction handling. */
+ runAsyncOnBackendWithManualTransactionHandling(func: Func, params?: unknown[]): Promise<unknown>;
+
+ /** Powerful attribute/value search, e.g. "#dateModified =* MONTH AND #log". */
+ searchForNotes(searchString: string): Promise<ScriptFNote[]>;
+ /** Returns the first note matching the search, or null. */
+ searchForNote(searchString: string): Promise<ScriptFNote | null>;
+ /** Returns a note by its ID (loading it into the cache if needed), or null. */
+ getNote(noteId: string): Promise<ScriptFNote | null>;
+ /** Returns multiple notes by their IDs (bulk-fills the cache). */
+ getNotes(noteIds: string[], silentNotFoundError?: boolean): Promise<ScriptFNote[]>;
+ /** Refreshes the given notes in the frontend cache from the backend. */
+ reloadNotes(noteIds: string[]): Promise<void>;
+ /** The name identifying this particular Trilium instance, or null. */
+ getInstanceName(): string | null;
+
+ /** Adds plain text at the active editor's cursor. */
+ addTextToActiveContextEditor(text: string): void;
+ /** The active note loaded into the center pane. */
+ getActiveContextNote(): ScriptFNote;
+ /** The currently active/focused split in the current tab. */
+ getActiveContext(): ScriptNoteContext;
+ /** The main (left-most) context of the current tab. */
+ getActiveMainContext(): ScriptNoteContext;
+ /** All note contexts (splits) across all tabs. */
+ getNoteContexts(): ScriptNoteContext[];
+ /** All main contexts (one per tab). */
+ getMainNoteContexts(): ScriptNoteContext[];
+ /** The CKEditor instance of the active text note, if any. */
+ getActiveContextTextEditor(): Promise<unknown>;
+ /** The CodeMirror instance of the active code note, if any. */
+ getActiveContextCodeEditor(): Promise<unknown>;
+ /** The widget handling the active note detail. */
+ getActiveNoteDetailWidget(): Promise<unknown>;
+ /** The note path of the active note, or null. */
+ getActiveContextNotePath(): string | null;
+ /** The component owning the given DOM element (nearest parent in the DOM tree). */
+ getComponentByEl(el: HTMLElement): unknown;
+
+ /** Shows an info toast message to the user. */
+ showMessage(message: string, delay?: number): void;
+ /** Shows an error toast message to the user. */
+ showError(message: string, delay?: number): void;
+ /** Shows an info dialog to the user. */
+ showInfoDialog(message: string): Promise<void>;
+ /** Shows a confirm dialog; resolves true if the user confirmed. */
+ showConfirmDialog(message: string): Promise<boolean>;
+ /** Shows a prompt dialog; resolves to the user's answer. */
+ showPromptDialog(props: { title?: string; message?: string; defaultValue?: string }): Promise<string | null>;
+
+ /** Creates a note link (jQuery element) for the given note path. */
+ createLink(notePath: string, params?: Record<string, unknown>): unknown;
+ /** @deprecated use createLink() instead */
+ createNoteLink(notePath: string, params?: Record<string, unknown>): unknown;
+
+ /** Triggers a Trilium command (low-level). */
+ triggerCommand(name: string, data?: Record<string, unknown>): Promise<unknown>;
+ /** Triggers a Trilium event (low-level). */
+ triggerEvent(name: string, data?: Record<string, unknown>): Promise<unknown>;
+ /** Sets up a tooltip on the given jQuery element. */
+ setupElementTooltip(el: unknown): void;
+ /** Protects/unprotects a note. */
+ protectNote(noteId: string, protect: boolean): Promise<void>;
+ /** Protects/unprotects a whole subtree. */
+ protectSubTree(noteId: string, protect: boolean): Promise<void>;
+
+ /** Returns (creating if needed) the date-note for today. */
+ getTodayNote(): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the day-note for the given "YYYY-MM-DD" date. */
+ getDayNote(date: string): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the week's first day-note for the given date. */
+ getWeekFirstDayNote(date: string): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the week-note for the given "YYYY-MM-DD" date. */
+ getWeekNote(date: string): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the month-note for the given "YYYY-MM" month. */
+ getMonthNote(month: string): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the quarter-note for the given date. */
+ getQuarterNote(date: string): Promise<ScriptFNote>;
+ /** Returns (creating if needed) the year-note for the given "YYYY" year. */
+ getYearNote(year: string): Promise<ScriptFNote>;
+
+ /** Hoists a note in the current tab ('root' effectively unhoists). */
+ setHoistedNoteId(noteId: string): void;
+ /** Binds a global keyboard shortcut (e.g. "ctrl+shift+a") to a handler. */
+ bindGlobalShortcut(keyboardShortcut: string, handler: () => void, namespace?: string): void;
+ /** Resolves once all backend → frontend synchronization is finished. */
+ waitUntilSynced(): Promise<unknown>;
+ /** Refreshes all open notes that include the given note. */
+ refreshIncludedNote(includedNoteId: string): void;
+
+ /** Returns a random (non-cryptographic) alphanumeric string of the given length. */
+ randomString(length: number): string;
+ /** Formats a size in bytes into a human-readable string. */
+ formatSize(size: number): string;
+ /** @deprecated use formatSize() */
+ formatNoteSize(size: number): string;
+ /** Formats a date as "YYYY-MM-DD". */
+ formatDateISO(date: Date): string;
+ /** Parses a date string into a Date. */
+ parseDate(str: string): Date;
+
+ /** Per-note log message buffers shown in the UI log pane. */
+ logMessages: Record<string, string[]>;
+ /** Per-note spaced-update handlers for the log pane. */
+ logSpacedUpdates: Record<string, unknown>;
+ /** Logs a message to the UI log pane (joins arguments like console.log). */
+ log(...args: unknown[]): void;
+
+ /** The Preact API surface (components, hooks) for render scripts. */
+ preact: unknown;
+}