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
import { ScriptParams } from "@triliumnext/commons";
import { h, VNode } from "preact";
import FNote from "../entities/fnote.js";
import BasicWidget, { ReactWrappedWidget } from "../widgets/basic_widget.js";
import RightPanelWidget from "../widgets/right_panel_widget.js";
import { BackendScriptingDisabledError } from "./backend_scripting.js";
import type { Entity } from "./frontend_script_api.js";
import { WidgetDefinitionWithType } from "./frontend_script_api_preact.js";
import { t } from "./i18n.js";
import ScriptContext from "./script_context.js";
import server from "./server.js";
import toastService, { showErrorForScriptNote } from "./toast.js";
import utils, { causeChain, getErrorMessage, rootCauseMessage } from "./utils.js";
// TODO: Deduplicate with server.
export interface Bundle {
script: string;
html: string;
noteId: string;
allNoteIds: string[];
}
type LegacyWidget = (BasicWidget | RightPanelWidget) & {
parentWidget?: string;
};
type WithNoteId<T> = T & {
_noteId: string;
};
export type Widget = WithNoteId<(LegacyWidget | WidgetDefinitionWithType)>;
/** What a `#widget` note's script is allowed to return: one widget, or several. */
export type WidgetBundleResult = Widget | Widget[] | null | undefined;
async function getAndExecuteBundle(noteId: string, originEntity: FNote | null = null, script: string | null = null, params: ScriptParams | null = null, opts?: ExecuteBundleOpts) {
const bundle = await server.post<Bundle>(`script/bundle/${noteId}`, {
script,
params
});
return await executeBundle(bundle, originEntity, undefined, opts);
}
export type ParentName = WidgetDefinitionWithType["parent"];
export async function executeBundleWithoutErrorHandling(bundle: Bundle, originEntity?: Entity | null, $container?: JQuery<HTMLElement>) {
const apiContext = await ScriptContext(bundle.noteId, bundle.allNoteIds, originEntity, $container);
return await function () {
return eval(`const apiContext = this; (async function() { ${bundle.script}\r\n})()`);
}.call(apiContext);
}
export interface ExecuteBundleOpts {
/**
* When `true`, the caught error is re-thrown after being reported, so the caller can tell the
* bundle failed (e.g. to avoid claiming success). Defaults to `false` — errors are swallowed,
* which is what widget/startup callers rely on.
*/
rethrow?: boolean;
}
export async function executeBundle(bundle: Bundle, originEntity?: Entity | null, $container?: JQuery<HTMLElement>, opts?: ExecuteBundleOpts) {
try {
return await executeBundleWithoutErrorHandling(bundle, originEntity, $container);
} catch (e: unknown) {
if (!isBackendScriptingDisabled(e)) {
showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });
logError("Widget initialization failed: ", e);
}
if (opts?.rethrow) {
throw e;
}
}
}
async function executeStartupBundles() {
const isMobile = utils.isMobile();
const scriptBundles = await server.get<Bundle[]>(`script/startup${ isMobile ? "?mobile=true" : ""}`);
for (const bundle of scriptBundles) {
await executeBundle(bundle);
}
}
export class WidgetsByParent {
private legacyWidgets: Record<string, WithNoteId<LegacyWidget>[]>;
private preactWidgets: Record<string, WithNoteId<WidgetDefinitionWithType>[]>;
constructor() {
this.legacyWidgets = {};
this.preactWidgets = {};
}
add(widget: Widget) {
let hasParentWidget = false;
let isPreact = false;
if ("type" in widget && widget.type === "preact-widget") {
// React-based script.
const reactWidget = widget as WithNoteId<WidgetDefinitionWithType>;
this.preactWidgets[reactWidget.parent] = this.preactWidgets[reactWidget.parent] || [];
this.preactWidgets[reactWidget.parent].push(reactWidget);
isPreact = true;
hasParentWidget = !!reactWidget.parent;
} else if ("parentWidget" in widget && widget.parentWidget) {
this.legacyWidgets[widget.parentWidget] = this.legacyWidgets[widget.parentWidget] || [];
this.legacyWidgets[widget.parentWidget].push(widget);
hasParentWidget = !!widget.parentWidget;
}
if (!hasParentWidget) {
showErrorForScriptNote(widget._noteId, t("toast.widget-missing-parent", {
property: isPreact ? "parent" : "parentWidget"
}));
}
}
get(parentName: ParentName) {
const widgets: (BasicWidget | VNode)[] = this.getLegacyWidgets(parentName);
for (const preactWidget of this.getPreactWidgets(parentName)) {
const el = h(preactWidget.render, {});
const widget = new ReactWrappedWidget(el);
widget.contentSized();
if (preactWidget.position) {
widget.position = preactWidget.position;
}
widgets.push(widget);
}
return widgets;
}
getLegacyWidgets(parentName: ParentName): (BasicWidget | RightPanelWidget)[] {
if (!this.legacyWidgets[parentName]) return [];
return (
this.legacyWidgets[parentName]
// previously, custom widgets were provided as a single instance, but that has the disadvantage
// for splits where we actually need multiple instaces and thus having a class to instantiate is better
// https://github.com/zadam/trilium/issues/4274
.map((w: any) => (w.prototype ? new w() : w))
);
}
getPreactWidgets(parentName: ParentName) {
return this.preactWidgets[parentName] ?? [];
}
}
async function getWidgetBundlesByParent() {
const widgetsByParent = new WidgetsByParent();
try {
const scriptBundles = await server.get<Bundle[]>("script/widgets");
for (const bundle of scriptBundles) {
try {
const result = await executeBundle(bundle);
for (const widget of asWidgetList(result)) {
widget._noteId = bundle.noteId;
widgetsByParent.add(widget);
}
} catch (e: any) {
if (!isBackendScriptingDisabled(e)) {
showErrorForScriptNote(bundle.noteId, rootCauseMessage(e), { monospace: true });
logError("Widget initialization failed: ", e);
}
continue;
}
}
} catch (e) {
toastService.showPersistent({
id: `custom-widget-list-failure`,
title: t("toast.widget-list-error.title"),
message: getErrorMessage(e),
icon: "bx bx-error-circle"
});
}
return widgetsByParent;
}
export default {
executeBundle,
getAndExecuteBundle,
executeStartupBundles,
getWidgetBundlesByParent
};
/**
* Normalizes what a widget bundle returned into a list, so a single `#widget` note can contribute
* several widgets. Falsy entries are dropped: a script that renders nothing returns `undefined`.
*/
function asWidgetList(result: WidgetBundleResult): Widget[] {
if (!result) {
return [];
}
return (Array.isArray(result) ? result : [result]).filter((widget) => !!widget);
}
/**
* Whether the failure was a disabled backend script (anywhere in its cause chain). Those already
* raise a single consolidated toast in `runOnBackend`, so the per-note toast here is redundant.
*/
export function isBackendScriptingDisabled(e: unknown): boolean {
for (const error of causeChain(e)) {
if (error instanceof BackendScriptingDisabledError) {
return true;
}
}
return false;
}