Skip to content

Build your personal knowledge base with Trilium Notes

feat(codemirror/autocomplete): basic Preact API types

Elian Dorana5eccb82da10
diff --git a/packages/codemirror/src/type_completion/index.spec.ts b/packages/codemirror/src/type_completion/index.spec.ts
index 790bc798b8..b511f4cd25 100644
--- a/packages/codemirror/src/type_completion/index.spec.ts
+++ b/packages/codemirror/src/type_completion/index.spec.ts
@@ -4,6 +4,10 @@ import { getScriptDiagnosticCodes, SCRIPT_MIME_BACKEND, SCRIPT_MIME_FRONTEND, SC
/** "Property 'x' does not exist on type 'y'." */
const TS_UNKNOWN_PROPERTY = 2339;
+/** "Argument of type 'x' is not assignable to parameter of type 'y'." */
+const TS_ARGUMENT_NOT_ASSIGNABLE = 2345;
+/** "Type 'x' is not assignable to type 'y'." */
+const TS_TYPE_NOT_ASSIGNABLE = 2322;
/** "'await' expressions are only allowed at the top level of a file when that file is a module…" */
const TS_TOP_LEVEL_AWAIT = 1375;
/** "Cannot find name '$'. Do you need to install type definitions for jQuery?…" */
@@ -112,6 +116,35 @@ describe("script note diagnostics", () => {
expect(codes).toEqual([]);
}, TIMEOUT);
+ it("provides real Preact hook types from trilium:preact (type inference)", async () => {
+ // Correct usage: `useState(0)` infers a number setter.
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { useState } from \"trilium:preact\";\nconst [count, setCount] = useState(0);\nsetCount(count + 1);"
+ );
+ expect(codes).toEqual([]);
+ }, TIMEOUT);
+
+ it("type-checks Preact hook arguments (real types, not any)", async () => {
+ // `useState(0)` → setter takes a number; passing a string must error,
+ // proving the hooks resolve to real types rather than `any`.
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "import { useState } from \"trilium:preact\";\nconst [count, setCount] = useState(0);\nsetCount(\"not a number\");"
+ );
+ expect(codes).toContain(TS_ARGUMENT_NOT_ASSIGNABLE);
+ }, TIMEOUT);
+
+ it("type-checks JSX intrinsic element attributes (real JSX.IntrinsicElements)", async () => {
+ // `tabIndex` is typed as a number on Preact's HTMLAttributes; a string
+ // value must error, proving intrinsic-element typing is wired (not `any`).
+ const codes = await getScriptDiagnosticCodes(
+ SCRIPT_MIME_JSX,
+ "const el = <div tabIndex=\"oops\">hi</div>;"
+ );
+ expect(codes).toContain(TS_TYPE_NOT_ASSIGNABLE);
+ }, TIMEOUT);
+
it("provides jQuery to JSX render notes (browser runtime, like frontend)", async () => {
const codes = await getScriptDiagnosticCodes(
SCRIPT_MIME_JSX,
diff --git a/packages/codemirror/src/type_completion/index.ts b/packages/codemirror/src/type_completion/index.ts
index 6bc1a90f58..29196dabab 100644
--- a/packages/codemirror/src/type_completion/index.ts
+++ b/packages/codemirror/src/type_completion/index.ts
@@ -51,12 +51,6 @@ 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).
allowJs: true,
@@ -116,7 +110,12 @@ async function createEnv(mime: string) {
if (mime === SCRIPT_MIME_JSX) {
// JSX notes import Preact/the api via bare specifiers (`trilium:preact`,
- // `trilium:api`); declare them so those imports resolve.
+ // `trilium:api`). Inject the real Preact .d.ts under `/node_modules/preact`
+ // so those modules — and the `JSX.IntrinsicElements` namespace — resolve.
+ const { preactVfsFiles, triliumModulesDts } = await import("./preact_types.js");
+ for (const [filePath, content] of Object.entries(preactVfsFiles)) {
+ fsMap.set(filePath, content);
+ }
fsMap.set(TRILIUM_MODULES_DTS_PATH, triliumModulesDts);
rootFiles.push(TRILIUM_MODULES_DTS_PATH);
}
@@ -125,11 +124,13 @@ async function createEnv(mime: string) {
...COMPILER_OPTIONS,
target: ts.ScriptTarget.ES2020,
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 } : {})
+ // The runtime uses the classic `h` transform, but we only type-check (never
+ // emit), so the automatic runtime is cleaner: it pulls `JSX.IntrinsicElements`
+ // from `preact/jsx-runtime`, giving real element/attribute typing without a
+ // factory symbol in scope.
+ ...(mime === SCRIPT_MIME_JSX
+ ? { jsx: ts.JsxEmit.ReactJSX, jsxImportSource: "preact" }
+ : {})
};
const system = createSystem(fsMap);
diff --git a/packages/codemirror/src/type_completion/preact_types.ts b/packages/codemirror/src/type_completion/preact_types.ts
new file mode 100644
index 0000000000..68bab5adb5
--- /dev/null
+++ b/packages/codemirror/src/type_completion/preact_types.ts
@@ -0,0 +1,107 @@
+// Real Preact type declarations injected into the JSX script-note vfs so the
+// `trilium:preact` import (and JSX intrinsic elements) resolve to actual types
+// rather than `any`.
+//
+// JSX render notes run Preact's classic `h`/`Fragment` transform at runtime
+// (see `buildJsx` in `packages/trilium-core/src/services/script.ts`), but the
+// language service only *type-checks* — it never emits. So for checking we use
+// the modern automatic runtime (`jsx: ReactJSX`, `jsxImportSource: "preact"`),
+// which resolves the full `JSX.IntrinsicElements` namespace from
+// `preact/jsx-runtime`. This avoids hand-authoring every HTML element's props.
+//
+// Like `jquery_types.ts`, the .d.ts text is read with relative `?raw` imports at
+// build time, so it tracks the installed `preact` version with no vendored
+// snapshot and lands in the lazy script-editor chunk (loaded only when a JSX
+// note opens).
+import hooksIndex from "../../../../node_modules/preact/hooks/src/index.d.ts?raw";
+import jsxRuntime from "../../../../node_modules/preact/jsx-runtime/src/index.d.ts?raw";
+import preactDom from "../../../../node_modules/preact/src/dom.d.ts?raw";
+import preactIndex from "../../../../node_modules/preact/src/index.d.ts?raw";
+import preactJsx from "../../../../node_modules/preact/src/jsx.d.ts?raw";
+
+/**
+ * Minimal `package.json` shims so the vfs's node10 module resolution finds each
+ * subpath's `types` entry (`exports` maps are ignored under node10). The four
+ * `.d.ts` files reference each other via the bare `preact` / `preact/...`
+ * specifiers and relative paths, so the directory layout must match the real
+ * package.
+ */
+function typesPackageJson(): string {
+ return JSON.stringify({ types: "src/index.d.ts" });
+}
+
+/**
+ * Virtual files placed under `/node_modules/preact` so `import … from "preact"`,
+ * `"preact/hooks"` and `"preact/jsx-runtime"` resolve. Keyed by absolute vfs
+ * path. Merge into the JSX env's file map.
+ */
+export const preactVfsFiles: Record<string, string> = {
+ "/node_modules/preact/package.json": typesPackageJson(),
+ "/node_modules/preact/src/index.d.ts": preactIndex,
+ "/node_modules/preact/src/jsx.d.ts": preactJsx,
+ "/node_modules/preact/src/dom.d.ts": preactDom,
+ "/node_modules/preact/hooks/package.json": typesPackageJson(),
+ "/node_modules/preact/hooks/src/index.d.ts": hooksIndex,
+ "/node_modules/preact/jsx-runtime/package.json": typesPackageJson(),
+ "/node_modules/preact/jsx-runtime/src/index.d.ts": jsxRuntime
+};
+
+/**
+ * Ambient declarations for the bare-specifier imports a JSX render note uses.
+ *
+ * - `trilium:preact` mirrors the runtime `api.preact` surface: it re-exports
+ * Preact core + all hooks, plus Trilium's `defineWidget`/`defineLauncherWidget`
+ * and the bundled UI components. The heavy components drag in the whole client
+ * widget graph, so (matching `script_api.ts`'s philosophy) they're typed as a
+ * loose `ComponentType<any>` rather than their real prop types.
+ * - `trilium:api` exposes the same object as the `api` global.
+ */
+export const triliumModulesDts = `
+declare module "trilium:preact" {
+ import type { ComponentType, VNode } from "preact";
+ export * from "preact";
+ export * from "preact/hooks";
+
+ export interface WidgetDefinition {
+ parent: "right-pane";
+ render: () => VNode;
+ position?: number;
+ }
+ export function defineWidget(definition: WidgetDefinition): WidgetDefinition & { type: "preact-widget" };
+ export function defineLauncherWidget(definition: { render: () => VNode }): { type: "preact-launcher-widget"; render: () => VNode };
+
+ export const ActionButton: ComponentType<any>;
+ export const Admonition: ComponentType<any>;
+ export const Button: ComponentType<any>;
+ export const CKEditor: ComponentType<any>;
+ export const Collapsible: ComponentType<any>;
+ export const Dropdown: ComponentType<any>;
+ export const FormCheckbox: ComponentType<any>;
+ export const FormDropdownList: ComponentType<any>;
+ export const FormFileUploadButton: ComponentType<any>;
+ export const FormFileUploadActionButton: ComponentType<any>;
+ export const FormGroup: ComponentType<any>;
+ export const FormListItem: ComponentType<any>;
+ export const FormDropdownDivider: ComponentType<any>;
+ export const FormDropdownSubmenu: ComponentType<any>;
+ export const FormRadioGroup: ComponentType<any>;
+ export const FormText: ComponentType<any>;
+ export const FormTextArea: ComponentType<any>;
+ export const FormTextBox: ComponentType<any>;
+ export const FormToggle: ComponentType<any>;
+ export const Icon: ComponentType<any>;
+ export const LinkButton: ComponentType<any>;
+ export const LoadingSpinner: ComponentType<any>;
+ export const Modal: ComponentType<any>;
+ export const NoteAutocomplete: ComponentType<any>;
+ export const NoteLink: ComponentType<any>;
+ export const RawHtml: ComponentType<any>;
+ export const Slider: ComponentType<any>;
+ export const RightPanelWidget: ComponentType<any>;
+}
+
+declare module "trilium:api" {
+ const api: typeof globalThis.api;
+ export default api;
+}
+`;