#!/usr/bin/env bun // Writes each framework adapter (src/react, src/solid, src/vue): one module // per element and per declaration child, from the registry in // src/elements/index.ts, and an index that re-exports them. // // Naming is by convention, and the compiler checks it: element `switch` has // `switchElement`, `defineSwitch`, `SwitchSpec` and `SwitchElement`; // declaration `tab` has `tabDeclaration` and `TabAttributes`. // // bun run scripts/generate-adapters.ts write the files // bun run scripts/generate-adapters.ts --check fail if one is stale (CI) import { readdirSync, unlinkSync } from "node:fs"; import { join } from "node:path"; import { elements } from "../src/elements"; import { camel, declarationModules, elementDeprecations, elementModules, kebab, pascal } from "./element-modules"; /** The package name the generated adapters import: mtrl, material, … */ const pkg = (await Bun.file(join(import.meta.dir, "..", "package.json")).json()) as { name: string }; interface Framework { dir: string; /** The exported component name for an element or declaration name. */ component: (name: string) => string; header: string; /** Extra line at the top, such as a directive. */ directive?: string; exports: string; } const frameworks: Framework[] = [ { dir: "react", component: pascal, directive: '"use client";', header: "React components for the elements. Each renders its `` tag, registers\n * it on first mount and loads its CSS.", exports: `export { configure } from "./create"; export type { ComponentProps, DeclarationProps, EventProps, DefaultProps, FormProps, MComponent, MDeclaration } from "./create";`, }, { dir: "solid", component: pascal, header: "Solid components for the elements. Each renders its `` tag, registers\n * it on mount and loads its CSS.", exports: `export { configure } from "./create"; export type { SolidProps, DeclarationProps, EventProps, DefaultProps, FormProps, MComponent, MDeclaration } from "./create";`, }, { dir: "vue", component: (name) => `M${pascal(name)}`, header: "Vue components for the elements. Each renders its `` tag, registers\n * it on mount and loads its CSS. `v-model` binds the element's live state.", exports: `export { configure } from "./create"; export type { VueProps, VueEmits, VueSlots, ModelProps, Exposed, MComponent, MDeclaration } from "./create";`, }, ]; // A component's own module: its element's CSS and element module // only, so importing one component ships that component and nothing else. // The index re-exports them, and the calls are pure, so a bundler drops what // the app does not name. const module = (framework: Framework, name: string, body: string, imports: string[]): string => `// src/${framework.dir}/${kebab(name)}.ts // Generated by scripts/generate-adapters.ts from src/elements. Do not edit. ${framework.directive ? `${framework.directive}\n` : ""}${imports.join("\n")} ${body} `; const elementModule = (framework: Framework, { name, module: from, styles }: (typeof elementModules)[number]): string => { const P = pascal(name); const C = framework.component(name); const note = elementDeprecations[name]?.(framework.component("toolbar")); const body = `${note ? `/** @deprecated ${note} */\n` : ""}export const ${C}: MComponent<${P}Spec, ${P}Element> = /*#__PURE__*/ createComponent(${camel(name)}Element.spec, define${P}, "${C}");`; return module(framework, name, body, [ ...styles.map((style) => `import "${pkg.name}/elements/css/${style}";`), `import { ${camel(name)}Element, define${P}, type ${P}Spec, type ${P}Element } from "../elements/${from}";`, `import { createComponent, type MComponent } from "./create";`, ]); }; const declarationModule = (framework: Framework, { name, module: from }: (typeof declarationModules)[number]): string => { const P = pascal(name); const C = framework.component(name); return module(framework, name, `export const ${C}: MDeclaration<${P}Attributes> = /*#__PURE__*/ createDeclaration(${name}Declaration, "${C}");`, [ `import { ${name}Declaration, type ${P}Attributes } from "../elements/${from}";`, `import { createDeclaration, type MDeclaration } from "./create";`, ]); }; const index = (framework: Framework): string => `// src/${framework.dir}/index.ts // Generated by scripts/generate-adapters.ts from src/elements. Do not edit. ${framework.directive ? `${framework.directive}\n` : ""}/** * ${framework.header} * * @module ${framework.dir} */ ${framework.exports} ${[...elementModules, ...declarationModules].map(({ name }) => `export { ${framework.component(name)} } from "./${kebab(name)}";`).join("\n")} `; // The bare tags in the framework's JSX, an opt-in types entry: // `material/react/jsx` and `material/solid/jsx`. Augmenting from material/elements would // break type-checking for an app without React or Solid. const tags = [ ...elementModules.map(({ name, module: from }) => ({ tag: `m-${kebab(name)}`, spec: `import("../elements/${from}").${pascal(name)}Spec`, element: `import("../elements/${from}").${pascal(name)}Element`, deprecated: elementDeprecations[name]?.(pascal("toolbar")) })), ...declarationModules.map(({ name, module: from }) => ({ tag: `m-${kebab(name)}`, spec: `typeof import("../elements/${from}").${name}Declaration`, element: "HTMLElement", deprecated: undefined })), ]; /** Each live property and element event name, with the specs that have it: Solid's `prop:` and `on:` are global. */ const byName = (key: "properties" | "events"): Map => { const names = new Map(); for (const { name, module: from } of elementModules) { const spec = elements[name as keyof typeof elements].spec as { properties?: object; events?: object }; for (const property of Object.keys(spec[key] ?? {})) { names.set(property, [...(names.get(property) ?? []), `import("../elements/${from}").${pascal(name)}Spec`]); } } return names; }; const jsx = (framework: Framework): string | null => { if (framework.dir === "vue") return null; const react = framework.dir === "react"; const header = `// src/${framework.dir}/jsx.ts // Generated by scripts/generate-adapters.ts from src/elements. Do not edit. ${framework.directive ? `${framework.directive}\n` : ""}/** * Types the bare \`m-*\` tags in ${react ? "React" : "Solid"}'s JSX, for the elements used directly * rather than through the components. Types only, opt in once: \`import type {} from "${pkg.name}/${framework.dir}/jsx";\` * * @module ${framework.dir}/jsx */ `; const entries = tags.map(({ tag, spec, element, deprecated }) => `${deprecated ? ` /** @deprecated ${deprecated} */\n` : ""} "${tag}": Tag<${spec}, ${element}>;`).join("\n"); if (react) { return `${header}import type * as React from "react"; import type { ElementEvents, ElementMarkup } from "../elements"; import type { ReactHostAttributes } from "./create"; /** * The element's events as React 19 listens to them on a custom element: an * \`on\` prop in lower case gets the element's own event * (\`onchange={(e) => e.detail.value}\`). \`onChange\` stays React's synthetic * event, which has no \`detail\`; React 18 sets no event props on a custom element. */ type Events = { [K in keyof ElementEvents & string as \`on\${Lowercase}\`]?: (event: ElementEvents[K]) => void; }; /** A tag's props: its attributes as markup writes them, its events, and any HTML attribute. */ type Tag = Omit< React.DetailedHTMLProps, E>, keyof ElementMarkup | keyof Events > & ElementMarkup & Events; declare module "react" { // eslint-disable-next-line @typescript-eslint/no-namespace -- JSX is a namespace; this merges into it namespace JSX { interface IntrinsicElements { ${entries} } } } `; } const specUnion = elementModules.map(({ name, module: from }) => `import("../elements/${from}").${pascal(name)}Spec`).join(" | "); const list = (names: Map, fn: string): string => [...names.keys()].map((name) => ` "${name}": ${fn}<"${name}">;`).join("\n"); return `${header}import type { ElementEvents, ElementMarkup, ElementProperties } from "../elements"; import type { SolidHostAttributes } from "./create"; /** A tag's props: its attributes as markup writes them, and any HTML attribute. */ type Tag = Omit, keyof ElementMarkup> & ElementMarkup; type Spec = ${specUnion}; type Prop = S extends unknown ? K extends keyof ElementProperties ? NonNullable[K]> : never : never; type Ev = S extends unknown ? K extends keyof ElementEvents ? ElementEvents[K] : never : never; declare module "solid-js" { // eslint-disable-next-line @typescript-eslint/no-namespace -- JSX is a namespace; this merges into it namespace JSX { interface IntrinsicElements { ${entries} } /** \`prop:checked\`, \`prop:value\`: the elements' live properties. */ interface ExplicitProperties { ${list(byName("properties"), "Prop")} } /** \`on:change\` and the other element events. */ interface CustomEvents { ${list(byName("events"), "Ev")} } } } `; }; // The hook is installed only by material/ssr/vue. No server import reaches Vue's // client graph. The string is empty in the browser, so hydration does not look // for a template the HTML parser has already consumed. const vueShadow = `// src/vue/shadow.ts // Generated by scripts/generate-adapters.ts. Do not edit. import type { VNode } from "vue"; import { getPrefix, isBrowser } from "../elements/adapter"; type Renderer = ( tag: string, props: Record, children: () => VNode[], prefix: string, ) => string | Promise; /** * Inner HTML for one host during SSR: the declarative template followed by its * light DOM, or "" in the browser and when no renderer is registered. Async * children resolve to that same string. */ export const shadow = (tag: string, props: Record, children: () => VNode[]): string | Promise => { if (isBrowser) return ""; const render = (globalThis as unknown as Record)[Symbol.for("mtrl.ssr")]?.vue; if (!render) return ""; return render(tag, props, children, getPrefix()); }; `; // The hook is installed only by material/ssr/react. No server import reaches React's // client graph; the HTML parser consumes this child before hydration. const reactShadow = `// src/react/shadow.ts // Generated by scripts/generate-adapters.ts. Do not edit. "use client"; import * as React from "react"; import { getPrefix, isBrowser } from "../elements/adapter"; type Renderer = (tag: string, props: Record, children: React.ReactNode, prefix: string) => string | undefined; export const shadow = (tag: string, props: Record, children: React.ReactNode): React.ReactNode => { if (isBrowser) return null; const render = (globalThis as unknown as Record)[Symbol.for("mtrl.ssr")]?.react; const html = render?.(tag, props, children, getPrefix()); return html === undefined ? null : React.createElement("template", { shadowrootmode: "open", shadowrootdelegatesfocus: "", dangerouslySetInnerHTML: { __html: html }, }); }; `; // The hook is installed only by material/ssr/solid. No server import reaches Solid's // client graph. The browser keeps the original children: the parser has already // consumed the declarative shadow template. const solidShadow = `// src/solid/shadow.ts // Generated by scripts/generate-adapters.ts. Do not edit. import type { JSX } from "solid-js"; import { isServer } from "solid-js/web"; import { getPrefix } from "../elements/adapter"; type Renderer = ( tag: string, props: Record, children: JSX.Element, prefix: string, ) => JSX.Element; /** Host children with a declarative shadow template when the server renderer is registered. */ export const shadow = (tag: string, props: Record, children: JSX.Element): JSX.Element => { if (!isServer) return children; const render = (globalThis as unknown as Record)[Symbol.for("mtrl.ssr")]?.solid; if (!render) return children; return render(tag, props, children, getPrefix()); }; `; /** Every file the generator owns, by path. */ const files = (framework: Framework): Map => new Map([ [`src/${framework.dir}/index.ts`, index(framework)], ...(framework.dir === "react" ? [["src/react/shadow.ts", reactShadow] as const] : []), ...(framework.dir === "vue" ? [["src/vue/shadow.ts", vueShadow] as const] : []), ...(framework.dir === "solid" ? [["src/solid/shadow.ts", solidShadow] as const] : []), ...elementModules.map((element) => [`src/${framework.dir}/${kebab(element.name)}.ts`, elementModule(framework, element)] as const), ...declarationModules.map((declaration) => [`src/${framework.dir}/${kebab(declaration.name)}.ts`, declarationModule(framework, declaration)] as const), ...(jsx(framework) === null ? [] : [[`src/${framework.dir}/jsx.ts`, jsx(framework) as string] as const]), ]); /** Hand-written files in an adapter folder; anything else there is generated. */ const OWN = new Set(["create.ts", "css.d.ts"]); const check = process.argv.includes("--check"); let stale = false; for (const framework of frameworks) { const expected = files(framework); const present = readdirSync(`src/${framework.dir}`).filter((file) => !OWN.has(file)).map((file) => `src/${framework.dir}/${file}`); for (const target of present.filter((file) => !expected.has(file))) { if (check) { console.error(`${target} is not generated any more: run bun run adapters:generate`); stale = true; } else { unlinkSync(target); console.log(`removed ${target}`); } } for (const [target, source] of expected) { if (check) { const current = await Bun.file(target).text().catch(() => ""); if (current !== source) { console.error(`${target} is stale: run bun run adapters:generate`); stale = true; } } else { await Bun.write(target, source); } } if (!check) console.log(`wrote src/${framework.dir}: ${expected.size} files`); } if (stale) process.exit(1); if (check) console.log("adapter modules are up to date");