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(client): let a widget note return several widgets
BeatLink176695e0cdfc
diff --git a/apps/client/src/services/bundle.spec.ts b/apps/client/src/services/bundle.spec.tsindex 544a6c41b1..34177d53b4 100644--- a/apps/client/src/services/bundle.spec.ts+++ b/apps/client/src/services/bundle.spec.ts@@ -292,6 +292,71 @@ describe("getWidgetBundlesByParent (default export)", () => {expect(result.getLegacyWidgets("left-pane")).toEqual([]);});+ it("registers every widget when a bundle returns an array", async () => {+ const id = buildNote({ title: "Multi-widget note" }).noteId;+ const bundle: Bundle = {+ script: `return [+ { parentWidget: "left-pane" },+ { type: "preact-widget", parent: "right-pane", render: () => null },+ null+ ];`,+ html: "",+ noteId: id,+ allNoteIds: [id]+ };+ server.get = vi.fn(async (url: string) => {+ if (url === "script/widgets") return [bundle];+ return [];+ }) as unknown as typeof server.get;++ const result = await bundleService.getWidgetBundlesByParent();+ const legacy = result.getLegacyWidgets("left-pane");+ const preact = result.getPreactWidgets("right-pane");+ expect(legacy).toHaveLength(1);+ expect(preact).toHaveLength(1);+ // Every widget of the note is tagged with the note it came from, and the falsy entry is dropped.+ expect((legacy[0] as any)._noteId).toBe(id);+ expect(preact[0]._noteId).toBe(id);+ });++ it("reports the parentless widget of an array without dropping its siblings", async () => {+ const id = buildNote({ title: "Partly broken widget note" }).noteId;+ const errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);+ const bundle: Bundle = {+ script: `return [{ parentWidget: "left-pane" }, { render: () => null }];`,+ html: "",+ noteId: id,+ allNoteIds: [id]+ };+ server.get = vi.fn(async (url: string) => {+ if (url === "script/widgets") return [bundle];+ return [];+ }) as unknown as typeof server.get;++ const result = await bundleService.getWidgetBundlesByParent();+ expect(result.getLegacyWidgets("left-pane")).toHaveLength(1);+ expect(errorSpy).toHaveBeenCalledTimes(1);+ expect(errorSpy.mock.calls[0][0]).toBe(id);+ errorSpy.mockRestore();+ });++ it("ignores a bundle that returns an empty array", async () => {+ const id = buildNote({ title: "No widgets note" }).noteId;+ const bundle: Bundle = {+ script: `return [];`,+ html: "",+ noteId: id,+ allNoteIds: [id]+ };+ server.get = vi.fn(async (url: string) => {+ if (url === "script/widgets") return [bundle];+ return [];+ }) as unknown as typeof server.get;++ const result = await bundleService.getWidgetBundlesByParent();+ expect(result.getLegacyWidgets("left-pane")).toEqual([]);+ });+it("reports a per-bundle error when executing a single bundle throws", async () => {const id = buildNote({ title: "Bad widget note" }).noteId;const errorSpy = vi.spyOn(toast, "showErrorForScriptNote").mockReturnValue(undefined);diff --git a/apps/client/src/services/bundle.ts b/apps/client/src/services/bundle.tsindex 6ef3bf62d2..e122dfa7fb 100644--- a/apps/client/src/services/bundle.ts+++ b/apps/client/src/services/bundle.ts@@ -29,6 +29,9 @@ type WithNoteId<T> = T & {};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,@@ -150,11 +153,10 @@ async function getWidgetBundlesByParent() {const scriptBundles = await server.get<Bundle[]>("script/widgets");for (const bundle of scriptBundles) {- let widget;-try {- widget = await executeBundle(bundle);- if (widget) {+ const result = await executeBundle(bundle);++ for (const widget of asWidgetList(result)) {widget._noteId = bundle.noteId;widgetsByParent.add(widget);}@@ -185,6 +187,18 @@ export default {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.diff --git a/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md b/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.mdindex 7f84f54219..27f2274e75 100644--- a/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md+++ b/docs/User Guide/User Guide/Scripting/Frontend Basics/Custom Widgets.md@@ -108,6 +108,45 @@ A widget can be placed in one of the following sections of the applications:To position the widget somewhere else, just change the value passed to `get parentWidget()` for legacy widgets or the `parent` field for Preact. Do note that some positions such as `note-detail-pane` and `right-pane` have special requirements that need to be accounted for (see the table above).+## Multiple widgets in a single note++A widget note usually returns one widget, but it can also return an array of them. This is useful when several widgets share code or state, since they can all live in the same note instead of being split across notes that need a shared module.++Each widget of the array is registered on its own, so they can have different parents and positions. A widget that is missing its `parentWidget` (or `parent` for Preact) is reported as an error without affecting the other widgets of the note.++### Legacy version (jQuery)++```+class TreeWidget extends api.BasicWidget {+ get parentWidget() { return "left-pane"; }+ doRender() { this.$widget = $("<span>Left pane</span>"); }+}++class SidebarWidget extends api.BasicWidget {+ get parentWidget() { return "right-pane"; }+ doRender() { this.$widget = $("<span>Right pane</span>"); }+}++module.exports = [ new TreeWidget(), new SidebarWidget() ];+```++### Preact version++```+import { defineWidget } from "trilium:preact";++export default [+ defineWidget({+ parent: "left-pane",+ render: () => <span>Left pane from Preact.</span>+ }),+ defineWidget({+ parent: "right-pane",+ render: () => <span>Right pane from Preact.</span>+ })+];+```+## Launch bar widgetsLaunch bar widgets are similar to _Custom widgets_ but are specific to the <a class="reference-link" href="../../Basic%20Concepts%20and%20Features/UI%20Elements/Launch%20Bar.md">Launch Bar</a>. See <a class="reference-link" href="Launch%20Bar%20Widgets.md">Launch Bar Widgets</a> for more information.