Skip to content

Build your personal knowledge base with Trilium Notes

fix(scripting): load `preact/compat` for frontend scripts

Elian Doran9ca7b1df6fee
diff --git a/apps/client/src/services/frontend_script_api_preact.spec.ts b/apps/client/src/services/frontend_script_api_preact.spec.ts
index 6ffed4f2ee..1280112273 100644
--- a/apps/client/src/services/frontend_script_api_preact.spec.ts
+++ b/apps/client/src/services/frontend_script_api_preact.spec.ts
@@ -1,4 +1,4 @@
-import { Fragment, h } from "preact";
+import { Fragment, h, render as renderPreact } from "preact";
import { describe, expect, it } from "vitest";
import { preactAPI } from "./frontend_script_api_preact.js";
@@ -21,6 +21,21 @@ describe("preactAPI", () => {
expect(typeof (preactAPI as Record<string, unknown>).useEffect).toBe("function");
});
+ it("applies compat's `defaultProps` and `px` units to what scripts render through `h`", () => {
+ function Greeting({ name }: { name?: string }) {
+ return preactAPI.h("span", { style: { width: 10 } }, name);
+ }
+ Greeting.defaultProps = { name: "world" };
+
+ const host = document.createElement("div");
+ renderPreact(preactAPI.h(Greeting, null), host);
+
+ const span = host.querySelector("span");
+ expect(span).not.toBeNull();
+ expect(span?.textContent).toBe("world");
+ expect(span?.style.width).toBe("10px");
+ });
+
it("defineWidget tags the definition with the preact-widget type and preserves fields", () => {
const render = () => h(Fragment, null);
const result = preactAPI.defineWidget({ parent: "right-pane", render, position: 42 });
diff --git a/apps/client/src/services/frontend_script_api_preact.ts b/apps/client/src/services/frontend_script_api_preact.ts
index f080c93b03..0a999d84e5 100644
--- a/apps/client/src/services/frontend_script_api_preact.ts
+++ b/apps/client/src/services/frontend_script_api_preact.ts
@@ -1,3 +1,7 @@
+// Scripts build their vnodes with core's `h`, so compat's `options.vnode` hook is what gives their
+// components `defaultProps` and their numeric styles a `px` unit.
+import "preact/compat";
+
import { createContext, Fragment, h, VNode } from "preact";
import * as hooks from "preact/hooks";