AI-native design editor. Open-source Figma alternative.
feat(storybook): tag stories and decide them per component by rules (#1034)
Danila Poyarkovb3d0770555ed
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 03a301c1b..957716abf 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -88,7 +88,7 @@- Import SVG markup with `figma.createNodeFromSvg(svg)` in the plugin API, as in Figma: it builds the same layers as pasting the SVG, on the current page at its origin.- Detach an instance from its component with `detachInstance()` in the plugin API, as in Figma, from scripts run through `eval`.- Run scripts written for Figma's dynamic-page mode that call `figma.getNodeByIdAsync()` or `getMainComponentAsync()`; both resolve to the same nodes as their synchronous forms.-- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, titled by the document and, when several have components, its page, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, and an `openpencil://` link that opens the variant in OpenPencil. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).+- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, titled by the document and, when several have components, its page, with a story and `select` controls per variant (a component with a behaviour gets boolean `checked`, `pressed`, `open`, and `disabled` controls instead, and each interaction state stays a story; with `--framework vue` or `--framework react`, a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a Reka UI or Radix UI component whose variants are compiled into state styles and whose text properties are string props with a text control, tabs and groups choosing a value named after each tab's or item's label, sliders, progress bars, and number fields binding a number within their range, text fields and textareas binding their text as a native input or textarea with the design's placeholder and filled look (React's number field is a native number input with its steppers wired, since Radix has none), each tab's trigger drawn with the chosen tab's look while it is active, and groups writing an item component they use once per item with the words each item shows; inside it, an instance of another generated component uses that component, also where a state draws it in place of another layer, operable from the value the design draws, and an icon is an `@iconify/vue` or `@iconify/react` component; with stories whose play function operates it), a design image per variant, an `openpencil://` link that opens the variant in OpenPencil, and the document's fonts as files every story file loads, warning about families no web font provider has (`--fonts none` leaves them out); each file opens with a `Default` story and tags its other stories `variant` and itself with its page, so Storybook's tag filter can show one story per component or hide a page; a rules file (`openpencil.stories.json`, or `--rules`) leaves components out, keeps `Default` alone, lays a set out as a gallery, or renames titles, matched by page and component name. `--watch` re-exports on every save and removes stories of deleted components, and `--beside` writes each document's stories next to it, for many documents at once (#727).- Export HTML and Tailwind JSX from the app's export options and through the IO registry, and export Tailwind JSX from the CLI with `-f tailwind-jsx` (`-f jsx --style tailwind` still works). HTML export of a single layer now includes the layer itself, as other formats do. Vector shapes, booleans, stars, and polygons export as inline SVG with their fills, gradients, strokes, and shadows, in HTML, Tailwind JSX, and Storybook stories.- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.- Let AI and MCP agents verify and replay their edits with diff tools: `diff_visual` returns a pixel diff of two rendered nodes with the changed region, and `diff_apply` applies a `diff_create` or `diff_show` patch, including moved, added, and removed children, only when every node still matches it. The built-in AI chat enables `diff_create`, `diff_jsx`, and `diff_visual` by default.diff --git a/packages/cli/src/commands/export/index.ts b/packages/cli/src/commands/export/index.tsindex 01068f8a7..0725cfb5f 100644--- a/packages/cli/src/commands/export/index.ts+++ b/packages/cli/src/commands/export/index.ts@@ -47,7 +47,7 @@ export interface ExportArgs {html: stringcss: stringassets: string- fonts: string+ fonts?: stringframework: string'design-images': booleanwatch?: boolean@@ -203,7 +203,7 @@ async function executeFileExport(function exportOptions(format: string, args: ExportArgs): unknown {if (format === 'FIG') return { renderThumbnail: true }if (format === 'HTML')- return { html: args.html, style: args.css, assets: args.assets, fonts: args.fonts }+ return { html: args.html, style: args.css, assets: args.assets, fonts: args.fonts ?? 'none' }if (formatSupportsScale(format))return {format,@@ -328,8 +328,8 @@ export default defineCommand({},fonts: {type: 'string',- description: 'HTML font output: assets or none (default: none)',- default: 'none'+ description:+ 'HTML and Storybook font files: assets or none (default: none for HTML, assets for Storybook)'},framework: {type: 'string',@@ -349,6 +349,11 @@ export default defineCommand({type: 'boolean',description: "Storybook: write each document's stories into the document's own folder"},+ rules: {+ type: 'string',+ description:+ 'Storybook: rules file for which stories each component gets and its title (default: openpencil.stories.json when present)'+ },'font-policy': {type: 'string',description: 'Raster/PDF font policy: warn, strict, or allow (default: warn)',@@ -386,8 +391,8 @@ export default defineCommand({process.exit(1)}- if (format === 'HTML' && !HTML_FONTS.has(args.fonts)) {- printError(`Invalid HTML font output "${args.fonts}". Use assets or none.`)+ if (args.fonts && !HTML_FONTS.has(args.fonts)) {+ printError(`Invalid font output "${args.fonts}". Use assets or none.`)process.exit(1)}diff --git a/packages/cli/src/commands/export/storybook/fonts.ts b/packages/cli/src/commands/export/storybook/fonts.tsnew file mode 100644index 000000000..c67e7504f--- /dev/null+++ b/packages/cli/src/commands/export/storybook/fonts.ts@@ -0,0 +1,36 @@+import { uniq } from 'es-toolkit/array'++import { exportWebFontFaceAssets } from '@open-pencil/core/text/web-font/assets'+import type { WebFontFaceResolver } from '@open-pencil/dom-css'++import { warn } from '#cli/format'++/**+ * The font files stories' text uses, from the web font providers the editor uses. A family no+ * provider has falls back to the browser's fonts, which the export warns about rather than+ * failing, since the stories still work.+ */+export const storyFonts: WebFontFaceResolver = async (fonts, assetBasePath) => {+ const { assets } = await exportWebFontFaceAssets({ fonts, assetBasePath })+ const found = new Set(assets.map((asset) => asset.family))+ const missing = uniq(fonts.map((font) => font.family).filter((family) => !found.has(family)))+ if (missing.length > 0)+ console.error(+ warn(`No font files found for ${missing.join(', ')}; stories use the browser's fonts.`)+ )+ return assets+}++/**+ * The folder a document's font files go in, named by its path relative to the output, such as+ * `fonts/kit-design` for `../kit/design.fig`, so documents exported into one folder, even ones+ * with the same name, never share one; a one-page export adds the page.+ */+export function fontFolder(source: string, page: string | undefined): string {+ const name = [source.replace(/\.[^./]*$/, ''), page ?? '']+ .join('-')+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ return `fonts/${name || 'document'}`+}diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.tsindex e2d054298..f673a571e 100644--- a/packages/cli/src/commands/export/storybook/index.ts+++ b/packages/cli/src/commands/export/storybook/index.ts@@ -25,7 +25,9 @@ import { applyExportFontPolicy } from '#cli/commands/export/font-policy'import { ok, printError } from '#cli/format'import { loadDocument, populateWholeDocument, requirePage } from '#cli/headless'+import { fontFolder, storyFonts } from './fonts'import { readManifest, writeManifest, type StoryManifest, type StoryOwner } from './manifest'+import { readStoryRules, storyPlan } from './rules'interface StorybookArgs {file?: string@@ -39,6 +41,10 @@ interface StorybookArgs {'design-images': boolean'font-policy': stringwatch?: boolean+ /** A rules file for which stories each component gets and its title. */+ rules?: string+ /** `none` ships no font files with the stories. */+ fonts?: string}const io = new IORegistry(BUILTIN_IO_FORMATS)@@ -150,9 +156,16 @@ async function writeStories(const pageIds = pageId ? [pageId] : graph.getPages().map((page) => page.id)await applyExportFontPolicy(graph, pageIds, 'PNG', args['font-policy'])}+ // Read on every export, so a watch picks up edited rules with the next save.+ const rules = await readStoryRules(args.rules)+ // Relative to the output, the document's path tells apart documents exported there together.+ const source = toPosix(relative(outputDir, resolve(file)))const files = await exportStorybook(graph, {framework,pageId,+ plan: rules ? storyPlan(rules) : undefined,+ fonts: args.fonts === 'none' ? undefined : storyFonts,+ fontFolder: fontFolder(source, args.page),// Titled by the document, so stories of documents exported together stay apart.document: basename(file, extname(file)),linkPath: linkPath(file),@@ -173,7 +186,7 @@ async function writeStories(throw new Error(`No components found in ${args.page ? `page "${args.page}"` : 'the document'}.`)// Relative to the output, the document's path is the same on every machine and cwd.- const scope = { source: toPosix(relative(outputDir, resolve(file))), page: args.page }+ const scope = { source, page: args.page }await mkdir(outputDir, { recursive: true })// Staged next to the output so a failed write leaves the previous export in place,// and in a dot folder, which Storybook's story globs skip.diff --git a/packages/cli/src/commands/export/storybook/rules.ts b/packages/cli/src/commands/export/storybook/rules.tsnew file mode 100644index 000000000..12665d24d--- /dev/null+++ b/packages/cli/src/commands/export/storybook/rules.ts@@ -0,0 +1,72 @@+import { existsSync } from 'node:fs'+import { readFile } from 'node:fs/promises'+import { matchesGlob } from 'node:path'++import * as v from 'valibot'++import { STORY_MODES, type StoryPlan, type StoryTarget } from '@open-pencil/dom-css'++/** The rules file a Storybook export reads from the working directory when it is there. */+export const RULES_FILE = 'openpencil.stories.json'++/**+ * A rule for the story files whose `<page>/<name>` path matches its glob: which stories they+ * have, and a title template with `{document}`, `{page}`, `{name}`, and `{path}`, the title+ * they would have.+ */+const StoryRule = v.object({+ match: v.pipe(v.string(), v.minLength(1)),+ stories: v.optional(v.picklist(STORY_MODES)),+ title: v.optional(v.pipe(v.string(), v.minLength(1)))+})++const StoryRules = v.object({ rules: v.array(StoryRule) })++export type StoryRules = v.InferOutput<typeof StoryRules>++/**+ * The rules in `path`, or in {@link RULES_FILE} when no path is given and the working+ * directory has one; null when there are none to read.+ */+export async function readStoryRules(path: string | undefined): Promise<StoryRules | null> {+ const file = path ?? RULES_FILE+ if (path === undefined && !existsSync(file)) return null+ const parsed = v.safeParse(+ v.pipe(v.string(), v.parseJson(), StoryRules),+ await readFile(file, 'utf8')+ )+ if (!parsed.success) throw new Error(`Invalid rules in ${file}: ${v.summarize(parsed.issues)}`)+ return parsed.output+}++const PLACEHOLDER = /\{(document|page|name|path)\}/g++function fillTitle(template: string, target: StoryTarget): string {+ const values: Record<string, string> = {+ document: target.document ?? '',+ page: target.page,+ name: target.name,+ path: target.title+ }+ return template.replace(PLACEHOLDER, (placeholder: string, key: string) =>+ Object.hasOwn(values, key) ? (values[key] ?? placeholder) : placeholder+ )+}++/**+ * How each story file is written under `rules`: every rule whose glob matches the file's+ * original `<page>/<name>` path applies in order, so a later one overrides an earlier one, each+ * field on its own. Renaming never changes which rules match.+ */+export function storyPlan(rules: StoryRules): (target: StoryTarget) => StoryPlan {+ return (target) => {+ const path = `${target.page}/${target.name}`+ const plan: StoryPlan = {}+ for (const rule of rules.rules) {+ if (!matchesGlob(path, rule.match)) continue+ if (rule.stories) plan.stories = rule.stories+ if (rule.title) plan.title = fillTitle(rule.title, target)+ }+ return plan+ }+}diff --git a/packages/cli/tests/commands/export/storybook/fonts.test.ts b/packages/cli/tests/commands/export/storybook/fonts.test.tsnew file mode 100644index 000000000..23688d016--- /dev/null+++ b/packages/cli/tests/commands/export/storybook/fonts.test.ts@@ -0,0 +1,12 @@+import { describe, expect, test } from 'bun:test'++import { fontFolder } from '#cli/commands/export/storybook/fonts'++describe('Storybook font folders', () => {+ test('differ for documents of the same name exported into one folder', () => {+ expect(fontFolder('../kit/design.fig', undefined)).toBe('fonts/kit-design')+ expect(fontFolder('../app/design.fig', undefined)).toBe('fonts/app-design')+ // A one-page export keeps its page's fonts apart from the others'.+ expect(fontFolder('design.fig', 'Icons')).toBe('fonts/design-icons')+ })+})diff --git a/packages/cli/tests/commands/export/storybook/rules.test.ts b/packages/cli/tests/commands/export/storybook/rules.test.tsnew file mode 100644index 000000000..1881b8750--- /dev/null+++ b/packages/cli/tests/commands/export/storybook/rules.test.ts@@ -0,0 +1,60 @@+import { describe, expect, test } from 'bun:test'+import { mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { readStoryRules, storyPlan } from '#cli/commands/export/storybook/rules'++const target = (page: string, name: string) => ({+ document: 'Kit',+ page,+ name,+ title: `Kit/${page}/${name}`+})++describe('Storybook export rules', () => {+ test('apply every matching rule in order, each field on its own', () => {+ const plan = storyPlan({+ rules: [+ { match: '**', title: 'Design system/{page}/{name}' },+ { match: 'Icons/**', stories: 'gallery' },+ { match: 'Icons/legacy', stories: 'none' }+ ]+ })+ expect(plan(target('Icons', 'icon'))).toEqual({+ stories: 'gallery',+ title: 'Design system/Icons/icon'+ })+ expect(plan(target('Icons', 'legacy')).stories).toBe('none')+ // A file no rule names keeps everything it would have.+ expect(storyPlan({ rules: [{ match: 'Icons/**', stories: 'single' }] })(target('Forms', 'input'))).toEqual({})+ })++ test('fill titles from the file, its default title included', () => {+ const plan = storyPlan({ rules: [{ match: '**', title: '{path} ({document})' }] })+ expect(plan(target('Forms', 'input')).title).toBe('Kit/Forms/input (Kit)')+ })++ test('match the original names, so a renamed title never changes which rules apply', () => {+ const plan = storyPlan({+ rules: [+ { match: 'Forms/**', title: 'Inputs/{name}' },+ { match: 'Inputs/**', stories: 'none' }+ ]+ })+ expect(plan(target('Forms', 'input'))).toEqual({ title: 'Inputs/input' })+ })++ test('read a rules file, and reject one that is not valid JSON or not rules', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-rules-'))+ const good = join(dir, 'good.json')+ await writeFile(good, JSON.stringify({ rules: [{ match: '**', stories: 'single' }] }))+ expect(await readStoryRules(good)).toEqual({ rules: [{ match: '**', stories: 'single' }] })++ const bad = join(dir, 'bad.json')+ await writeFile(bad, JSON.stringify({ rules: [{ match: '**', stories: 'some' }] }))+ await expect(readStoryRules(bad)).rejects.toThrow(/Invalid rules/)+ await writeFile(bad, '{ not json')+ await expect(readStoryRules(bad)).rejects.toThrow(/Invalid rules/)+ })+})diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex f0b2bf101..d87b2e8ab 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -150,8 +150,39 @@ openpencil export design.fig -f storybook --framework vue -o src/storiesopenpencil export design.fig -f storybook --framework html --page "Components"openpencil export design.pen -f storybook -o src/stories --watch # re-export on every saveopenpencil export 'src/**/*.pen' -f storybook --beside --watch # stories next to each design+openpencil export design.fig -f storybook --rules stories.json # stories and titles by rule```+### Fewer stories in the sidebar++Each story file opens with a `Default` story, the variant the design shows at rest, with every control. Every other variant or state story is tagged `variant`, and each file is tagged `openpencil` and `page:<page>`, such as `page:icons`. Storybook's sidebar filter selects by these tags, and `.storybook/main.ts` can set what it shows by default, such as one story per component and no icons page:++```ts+const config: StorybookConfig = {+ // …+ tags: {+ variant: { defaultFilterSelection: 'exclude' },+ 'page:icons': { excludeFromSidebar: true }+ }+}+```++### Stories and titles by rule++What the tags can't do, such as leaving components out or laying an icon set out as a gallery, a rules file decides. The export reads `openpencil.stories.json` from the working directory when it is there, or the file `--rules` names, again on every export when watching:++```json+{+ "rules": [+ { "match": "**", "title": "Design system/{page}/{name}" },+ { "match": "Icons/**", "stories": "gallery" },+ { "match": "**/_*", "stories": "none" }+ ]+}+```++A rule applies to every story file whose `<page>/<name>` path matches its glob, by the names in the document: the page's, and the component set's or component's, or the prefix of slash-named components, such as `Icons/icon`. Every matching rule applies in order, so a later rule overrides an earlier one, each field on its own. `stories` is `variants`, a story per variant or state, as without rules; `single`, the `Default` story alone; `gallery`, `Default` and a `Gallery` story laying every variant out with its name, for static stories; or `none`, which leaves the file out. `title` is the file's title, with `{document}`, `{page}`, `{name}`, and `{path}`, the title it would have, filled in; titles that end up the same are kept apart as titles always are. Rules match the document's names, never a renamed title, so renaming a file never changes which rules apply to it.+### Designs next to their storiesKeep each component's design file in the component's folder and export with `--beside`: each document's stories, design images, and `.openpencil-stories.json` manifest go into that document's own folder, next to the component's code. A Storybook `stories` glob such as `../src/**/*.stories.ts` in `.storybook/main.ts` then picks them up without further configuration.@@ -160,7 +191,7 @@ Pass several documents, or a quoted glob such as `'src/**/*.pen'` that OpenPenciStories are titled by the document's file name, and then the page when more than one page has components: `pricing.fig` gives `pricing/Plan picker`, so documents exported together keep their stories apart. Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. A set with a behaviour gets the control's own props instead: a Switch or Checkbox has a `checked` boolean, a Toggle `pressed`, a Collapsible `open`, and `disabled` when the set draws a disabled state; hover, pressed, and focus stay stories of their own. Standalone components named with slashes, such as `Button/Primary` and `Button/Secondary`, are grouped into one `Button` file with a `Variant` control. A combination the design has no variant for throws a named error in Storybook rather than showing a different variant.-Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families, which Storybook has to load itself. Static stories don't export text, boolean, or instance-swap properties yet.+Stories render the component as HTML with inline styles, like `-f html`, so they need no OpenPencil runtime; `--framework` (`react`, `vue`, or `html`) only changes the wrapper and the `Meta`/`StoryObj` import from `@storybook/react-vite`, `@storybook/vue3-vite`, or `@storybook/html-vite`. Text uses the document's font families: the export fetches their files from the web font providers the editor uses into `fonts/<document>/` with a `fonts.css` every story file imports, so stories draw in those fonts, never in a fallback first. A family no provider has, such as Menlo, falls back to the browser's fonts, which the export warns about; `--fonts none` ships no font files. Static stories don't export text, boolean, or instance-swap properties yet.With `--framework vue` or `--framework react`, a component set or component whose behaviour is a Button, Switch, Checkbox, Toggle, Collapsible, Tabs, Radio group, Toggle group, Accordion, Slider, Progress, Number field, Text field, or Textarea becomes a real component instead: `<Name>.vue` built on Reka UI, or `<Name>.tsx` with a `<Name>.module.css` built on Radix UI's `radix-ui` package. Its variants are compiled into a stylesheet keyed on the states Reka and Radix set (`data-state`, `data-disabled`, hover, and focus), and every other variant property is a prop the component sets as a `data-*` attribute. In Vue its value is a `v-model` such as `checked` or `open`; in React the component takes the Radix root's props, such as `checked`, `defaultChecked`, and `onCheckedChange`. Its text properties are string props, defaulting to the design's words, which the layers bound to them draw, with a text control in its stories.diff --git a/packages/dom-css/src/export/bundle.ts b/packages/dom-css/src/export/bundle.tsindex 066b27512..12b588ef8 100644--- a/packages/dom-css/src/export/bundle.ts+++ b/packages/dom-css/src/export/bundle.ts@@ -248,21 +248,35 @@ function serializeFontWeight(weight: string | number | [number, number]): stringreturn Array.isArray(weight) ? weight.join(' ') : String(weight)}-function fontSourceValue(asset: WebFontFaceAsset): string {- const url = new URL(asset.path, 'file:///')+function fontSourceValue(asset: WebFontFaceAsset, from: string): string {+ // Relative to the stylesheet's folder, which the asset's path may start with.+ const path =+ from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path+ const url = new URL(path, 'file:///')const escapedPath = url.pathname.slice(1)return ['url(', JSON.stringify(escapedPath), ') format(', JSON.stringify(asset.format), ')'].join('')}-function fontFaceCSS(FontFaceRule: typeof CSSFontFaceRule, asset: WebFontFaceAsset): string {+interface FontFaceCSSOptions {+ /** The folder the stylesheet is in, which font paths are written relative to. */+ from: string+ /** `font-display` for every face, rather than each face's own. */+ display?: string+}++function fontFaceCSS(+ FontFaceRule: typeof CSSFontFaceRule,+ asset: WebFontFaceAsset,+ options: FontFaceCSSOptions+): string {const rule = new FontFaceRule()rule.style.setProperty('font-family', JSON.stringify(asset.family))- rule.style.setProperty('src', fontSourceValue(asset))+ rule.style.setProperty('src', fontSourceValue(asset, options.from))rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))rule.style.setProperty('font-style', asset.style)- rule.style.setProperty('font-display', asset.display ?? 'swap')+ rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)if (asset.unicodeRange && asset.unicodeRange.length > 0) {rule.style.setProperty('unicode-range', asset.unicodeRange.join(','))@@ -270,22 +284,32 @@ function fontFaceCSS(FontFaceRule: typeof CSSFontFaceRule, asset: WebFontFaceAssreturn rule.cssText}+/** Every font face a document's text uses, once each. */+export function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {+ const requests = new Map<string, WebFontFaceRequest>()+ for (const child of document.children) collectFontRequests(child, requests)+ return [...requests.values()]+}++/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */+export async function fontFaceStylesheet(+ assets: readonly WebFontFaceAsset[],+ options: FontFaceCSSOptions+): Promise<string> {+ if (assets.length === 0) return ''+ // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.+ const cssom = await import('@acemir/cssom')+ return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')+}+async function fontFaceAssets(document: DesignDocument,options: Required<ExportHTMLBundleOptions>): Promise<{ css: string; files: ExportHTMLFile[] }> {if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }- const requests = new Map<string, WebFontFaceRequest>()- for (const child of document.children) collectFontRequests(child, requests)- // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.- const [assets, cssom] = await Promise.all([- options.fonts([...requests.values()], `${options.assetBasePath}/fonts`),- import('@acemir/cssom')- ])- return {- css: assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset)).join(''),- files: assets- }+ const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)+ // The page's stylesheet sits at the top, so font paths stay as they are.+ return { css: await fontFaceStylesheet(assets, { from: '' }), files: assets }}function dataImageParts(value: string): { mime: string; base64: string } | undefined {diff --git a/packages/dom-css/src/export/storybook/component.ts b/packages/dom-css/src/export/storybook/component.tsindex 70863aa5c..0c33d98a2 100644--- a/packages/dom-css/src/export/storybook/component.ts+++ b/packages/dom-css/src/export/storybook/component.ts@@ -9,7 +9,8 @@ import type {GeneratedComponent,GeneratedKind} from '../components/model'-import { claimName, identifierName } from './names'+import { stylesheets } from './module'+import { claimName, identifierName, VARIANT_TAG } from './names'/** Tells readers the file is generated; nothing parses it. */const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.'@@ -20,6 +21,7 @@ const MODULE = es.parseModule(dedent`const meta = {title: $title,+ tags: $tags,component: $Component,parameters: $parameters,args: $args,@@ -121,6 +123,12 @@ export interface ComponentStoriesData {/** The Storybook renderer package the stories import their types from. */storybook: stringtitle: string+ /** Tags on the whole file, which its stories inherit. */+ tags: string[]+ /** Stylesheets the file imports, such as the fonts its text uses. */+ styles: string[]+ /** Only the Default story, as a plan can ask for. */+ single?: booleancomponent: ComponentModelgenerated: Pick<GeneratedComponent, 'entry' | 'valueArg' | 'valueList'>/** Design links for the whole file, as `parameters.design` entries. */@@ -210,13 +218,20 @@ function stories(list: boolean): { name: string; story: es.SyntaxNode }[] {const taken = new Set<string>()- const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => ({- name: claimName(identifierName(label, 'Story'), taken),- story: es.object([- ...(args.length > 0 ? [['args', es.object(args)] as [string, es.SyntaxNode]] : []),- ...(play ? [['play', play] as [string, es.SyntaxNode]] : [])- ])- })+ const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => {+ // Every story after the first, Default, is another state, tagged so Storybook can hide it.+ const variant = taken.size > 0+ return {+ name: claimName(identifierName(label, 'Story'), taken),+ story: es.object([+ ...(variant+ ? [['tags', es.array([es.string(VARIANT_TAG)])] as [string, es.SyntaxNode]]+ : []),+ ...(args.length > 0 ? [['args', es.object(args)] as [string, es.SyntaxNode]] : []),+ ...(play ? [['play', play] as [string, es.SyntaxNode]] : [])+ ])+ }+ }const { range } = componentconst boolean = !component.choice && !range && !component.textreturn [@@ -274,6 +289,7 @@ export function printComponentStories(data: ComponentStoriesData): string {$storybook: es.string(data.storybook),$Component: es.identifier(component.name),$title: es.string(data.title),+ $tags: es.array(data.tags.map(es.string)),$parameters: parameters,$args: es.object(restArgs(component, model, list)),$argTypes: argTypes(component, model, list)@@ -282,7 +298,8 @@ export function printComponentStories(data: ComponentStoriesData): string {$Component: es.identifier(component.name),$path: es.string(entry.path)}).body- const exported = stories(component, model, list).flatMap(+ const all = stories(component, model, list)+ const exported = (data.single ? all.slice(0, 1) : all).flatMap((item) => es.fill(STORY, { $name: es.identifier(item.name), $story: item.story }).body)// Only a control with a play function uses `expect`.@@ -291,7 +308,13 @@ export function printComponentStories(data: ComponentStoriesData): string {const module = es.printModule({type: 'Program',sourceType: 'module',- body: compact([...imports, ...componentImport, ...rest, ...exported])+ body: compact([+ ...imports,+ ...stylesheets(data.styles),+ ...componentImport,+ ...rest,+ ...exported+ ])})return `${HEADER}\n${module}\n`}diff --git a/packages/dom-css/src/export/storybook/export.ts b/packages/dom-css/src/export/storybook/export.tsindex fd964c399..fb0d36648 100644--- a/packages/dom-css/src/export/storybook/export.ts+++ b/packages/dom-css/src/export/storybook/export.ts@@ -1,11 +1,20 @@+import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'+import { compact } from 'es-toolkit/array'+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'-import type { ExportHTMLFile } from '../bundle'+import {+ designFontRequests,+ fontFaceStylesheet,+ type ExportHTMLFile,+ type WebFontFaceRequest,+ type WebFontFaceResolver+} from '../bundle'import { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'import { reactComponent } from '../components/react'import type { ComponentReferences } from '../components/references'import { vueComponent } from '../components/vue'-import { serializeHTML } from '../html'+import { serializeHTML, serializeNode } from '../html'import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'import { printComponentStories } from './component'import { collectGroups, type StoryGroup } from './groups'@@ -15,7 +24,7 @@ import {type StoryDesign,type StorybookFramework} from './module'-import { claimName, identifierName, storyId } from './names'+import { claimName, fileTags, identifierName, storyId, VARIANT_TAG } from './names'export { STORYBOOK_FRAMEWORKS, type StorybookFramework } from './module'@@ -40,6 +49,43 @@ export interface ExportStorybookOptions {renderDesignImage?: (nodeId: string) => Promise<Uint8Array>/** Draws vector layers as inline SVG, from the engine's SVG export. */vectorElement?: VectorElementRenderer+ /**+ * How each story file is written, which a caller decides, such as from rules a user wrote:+ * which stories it has and its title. Every file is written as `variants` by default.+ */+ plan?: (target: StoryTarget) => StoryPlan+ /**+ * Finds the font files the stories' text uses, which ship with them in `fonts/` and load+ * before a story shows, so its text draws in the document's fonts. Without it, text uses+ * whatever fonts Storybook's page has.+ */+ fonts?: WebFontFaceResolver+ /**+ * The folder the font files go in, which must differ for each document exported into the+ * same place; `fonts/<document>` by default.+ */+ fontFolder?: string+}++/** How a story file shows its component: every variant, Default alone, a gallery, or not. */+export const STORY_MODES = ['variants', 'single', 'gallery', 'none'] as const+export type StoryMode = (typeof STORY_MODES)[number]++/** A story file the export would write, as a plan reads it. */+export interface StoryTarget {+ /** The document's name, when the export knows it. */+ document: string | undefined+ page: string+ /** The component set's or component's name, or a slash-named group's prefix. */+ name: string+ /** The title the file has unless the plan gives another. */+ title: string+}++/** What a plan says about a story file; anything it leaves out stays as it would be. */+export interface StoryPlan {+ stories?: StoryMode+ title?: string}export interface StorybookFile extends ExportHTMLFile {@@ -64,6 +110,9 @@ interface ModuleContext {/** Import path of each variant's design image, by variant index. */images: string[]vectorElement?: VectorElementRenderer+ mode: Exclude<StoryMode, 'none'>+ /** Stylesheets every story file imports, such as the fonts its text uses. */+ styles: string[]}function designLink(@@ -80,43 +129,77 @@ function designLink(function storyNames(group: StoryGroup): string[] {const taken = new Set<string>()const key = (name: string) => name.toLowerCase()- return group.variants.map((variant) => {- const text = group.props.length === 0 ? 'Default' : variant.values.join(' ')+ return group.variants.map((variant, index) => {+ // The first variant, the one the design shows at rest, is the file's Default story.+ const text = index === 0 || group.props.length === 0 ? 'Default' : variant.values.join(' ')return claimName(identifierName(text, 'Variant'), taken, { key })})}-function storyLabel(group: StoryGroup, values: string[]): string {- if (group.props.length === 0) return 'Default'+function storyLabel(group: StoryGroup, values: string[], index: number): string {+ if (index === 0 || group.props.length === 0) return 'Default'return group.props.map((prop, i) => `${prop.name}=${values[i] ?? ''}`).join(', ')}+/**+ * A variant drawn on its own, as a story shows it: its root hugs its content where the design+ * gives it no width, rather than filling the story's canvas, and sizes include padding and+ * borders, which no page reset around the story says.+ */+function standalone(document: DesignDocument): DesignDocument {+ const visit = (node: DesignNode, root: boolean) => {+ if (node.type !== 'element') return+ const style: DesignStyleDeclaration = { ...node.inlineStyle }+ const has = (property: string) => Object.hasOwn(style, property)+ if ((has('width') || has('height')) && !has('box-sizing')) style['box-sizing'] = 'border-box'+ if (root && !has('width')) style.width = 'fit-content'+ node.inlineStyle = style+ for (const child of node.children) visit(child, false)+ }+ for (const child of document.children) visit(child, true)+ return document+}+function storyModule(group: StoryGroup, context: ModuleContext): string {return printStoryModule({framework: context.framework,title: group.title,+ tags: fileTags(group.page.name),+ styles: context.styles,name: group.name,props: group.props,variants: group.variants.map((variant) => ({values: variant.values,html: serializeHTML(- sceneNodeToDesignDocument(context.graph, variant.node.id, {- includeSourceIds: false,- vectorElement: context.vectorElement- })+ standalone(+ sceneNodeToDesignDocument(context.graph, variant.node.id, {+ includeSourceIds: false,+ vectorElement: context.vectorElement+ })+ ))})),metaDesign: designLink(context, group.linkNode),images: context.images,- stories: group.variants.map((variant, i) => ({- exportName: context.storyNames[i] ?? '',- label: storyLabel(group, variant.values),- values: variant.values,- design: [- ...designLink(context, variant.node.name, group.linkNode),- ...(context.images[i] ? [{ type: 'image' as const, variant: i }] : [])- ]- }))+ gallery:+ context.mode === 'gallery'+ ? group.variants.map((variant) => ({+ values: variant.values,+ label: serializeNode({ type: 'text', text: variant.values.join(', ') || group.name })+ }))+ : null,+ stories: (context.mode === 'variants' ? group.variants : group.variants.slice(0, 1)).map(+ (variant, i) => ({+ exportName: context.storyNames[i] ?? '',+ label: storyLabel(group, variant.values, i),+ tags: i === 0 ? [] : [VARIANT_TAG],+ values: variant.values,+ design: [+ ...designLink(context, variant.node.name, group.linkNode),+ ...(context.images[i] ? [{ type: 'image' as const, variant: i }] : [])+ ]+ })+ )})}@@ -125,6 +208,7 @@ interface StoryEntry {page: SceneNodegroup: StoryGroupfile: string+ mode: Exclude<StoryMode, 'none'>}/**@@ -133,8 +217,7 @@ interface StoryEntry {*/function storyEntries(graph: SceneGraph,- pageId: string | undefined,- document: string | undefined+ { pageId, document, plan }: Pick<ExportStorybookOptions, 'pageId' | 'document' | 'plan'>): StoryEntry[] {const takenFiles = new Set<string>()const takenIds = new Set<string>()@@ -148,13 +231,19 @@ function storyEntries(}for (const page of pages) {for (const group of collectGroups(graph, page, section(page))) {+ const planned = plan?.({ document, page: page.name, name: group.name, title: group.title })+ const mode = planned?.stories ?? 'variants'+ if (mode === 'none') continue// Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.- group.title = claimName(group.title, takenIds, { separator: ' ', key: storyId })+ group.title = claimName(planned?.title ?? group.title, takenIds, {+ separator: ' ',+ key: storyId+ })// File names are compared ignoring case for case-insensitive file systems.const file = claimName(identifierName(group.name, 'Component'), takenFiles, {key: (name) => name.toLowerCase()})- if (!pageId || page.id === pageId) entries.push({ page, group, file })+ if (!pageId || page.id === pageId) entries.push({ page, group, file, mode })}}return entries@@ -199,6 +288,35 @@ function generatedModels(return models}+/**+ * The font files the entries' text uses, in a folder of the document's own so documents+ * exported side by side keep theirs apart, and the stylesheet that loads them. Faces load+ * before text draws, so a story never shows a fallback font first.+ */+async function storyFonts(+ graph: SceneGraph,+ entries: readonly StoryEntry[],+ options: ExportStorybookOptions+): Promise<{ stylesheet: string; files: ExportHTMLFile[] } | null> {+ if (!options.fonts) return null+ const requests = new Map<string, WebFontFaceRequest>()+ for (const { group } of entries)+ for (const variant of group.variants)+ for (const request of designFontRequests(+ sceneNodeToDesignDocument(graph, variant.node.id, { includeSourceIds: false })+ ))+ requests.set(`${request.family}|${request.weight}|${request.style ?? 'normal'}`, request)+ if (requests.size === 0) return null+ const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined+ const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))+ const folder = options.fontFolder ?? `fonts/${named.join('-')}`+ const assets = await options.fonts([...requests.values()], folder)+ if (assets.length === 0) return null+ const css = await fontFaceStylesheet(assets, { from: folder, display: 'block' })+ const stylesheet = `${folder}/fonts.css`+ return { stylesheet, files: [...assets, { path: stylesheet, content: css }] }+}+/*** Generate one CSF3 `.stories.ts` file per component or component set, plus a* `<Name>.design/` folder of variant images when `renderDesignImage` is given.@@ -213,11 +331,15 @@ export async function exportStorybook(const add = (page: SceneNode, path: string, content: string | Uint8Array) =>files.push({ path, content, page: page.name })- const entries = storyEntries(graph, options.pageId, options.document)+ const entries = storyEntries(graph, options)+ const fonts = await storyFonts(graph, entries, options)+ const firstPage = entries.at(0)?.page+ if (fonts && firstPage) for (const file of fonts.files) add(firstPage, file.path, file.content)+ const styles = fonts ? [`./${fonts.stylesheet}`] : []const generate = GENERATORS[framework]const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()- for (const { page, group, file } of entries) {+ for (const { page, group, file, mode } of entries) {const component = group.set && models.get(group.set.id)if (generate && component) {const generated = await generate(component)@@ -229,8 +351,12 @@ export async function exportStorybook(printComponentStories({storybook: STORYBOOK_PACKAGES[framework],title: group.title,+ tags: fileTags(group.page.name),+ styles,component,generated,+ // A gallery lays out static variants; a generated component's stories are its states.+ single: mode === 'single',design: design.flatMap((entry) =>entry.type === 'link' ? [{ name: 'OpenPencil', type: 'link', url: entry.url }] : [])@@ -239,14 +365,24 @@ export async function exportStorybook(continue}- const names = storyNames(group)+ // Only the stories a file keeps get design images; a gallery or Default alone keeps one.+ const names = storyNames(group).slice(0, mode === 'variants' ? undefined : 1)const render = options.renderDesignImageconst images = render ? names.map((name) => `${file}.design/${name}.png`) : []if (render) {- for (const [i, variant] of group.variants.entries())+ for (const [i, variant] of group.variants.slice(0, names.length).entries())add(page, images[i] ?? '', await render(variant.node.id))}- const context = { ...options, graph, framework, uniqueNames, storyNames: names, images }+ const context = {+ ...options,+ graph,+ framework,+ uniqueNames,+ storyNames: names,+ images,+ mode,+ styles+ }add(page, `${file}.stories.ts`, storyModule(group, context))}return filesdiff --git a/packages/dom-css/src/export/storybook/module.ts b/packages/dom-css/src/export/storybook/module.tsindex 462657eac..295c7a573 100644--- a/packages/dom-css/src/export/storybook/module.ts+++ b/packages/dom-css/src/export/storybook/module.ts@@ -27,6 +27,10 @@ export interface StoryProp {export interface StoryModuleData {framework: StorybookFrameworktitle: string+ /** Tags on the whole file, which its stories inherit. */+ tags: string[]+ /** Stylesheets the file imports, such as the fonts its text uses. */+ styles: string[]/** Group name used in the missing-variant error. */name: stringprops: StoryProp[]@@ -34,7 +38,15 @@ export interface StoryModuleData {metaDesign: StoryDesign[]/** Import path of each design image, by variant index. */images: string[]- stories: { exportName: string; label: string; values: string[]; design: StoryDesign[] }[]+ /** Every variant laid out in one story, each with its label as escaped HTML, if a gallery. */+ gallery: { values: string[]; label: string }[] | null+ stories: {+ exportName: string+ label: string+ values: string[]+ design: StoryDesign[]+ tags: string[]+ }[]}export type StoryDesign =@@ -58,6 +70,7 @@ const MODULE = es.parseModule(dedent`const meta = {title: $title,+ tags: $tags,parameters: $parameters,args: $args,argTypes: $argTypes,@@ -68,8 +81,31 @@ const MODULE = es.parseModule(dedent`type Story = StoryObj<Args>`)+const GALLERY = es.parseModule(dedent`+ const labels: [string, string][] = $labels++ function galleryHTML(): string {+ const items = labels.map(+ ([key, label]) =>+ '<figure style="margin: 0; display: flex; flex-direction: column; align-items: center; gap: 8px">' ++ (variants[key] ?? '') ++ '<figcaption style="font: 12px system-ui, sans-serif; color: #6b7280">' ++ label ++ '</figcaption></figure>'+ )+ return (+ '<div style="display: flex; flex-wrap: wrap; align-items: flex-end; gap: 24px">' ++ items.join('') ++ '</div>'+ )+ }++ export const Gallery: Story = { name: 'Gallery', render: () => $render }+`)+const IMAGE = es.parseModule(`const $name = new URL($path, import.meta.url).href`)const STORY = es.parseModule(`export const $name: Story = $story`)+const STYLESHEET = es.parseModule(`import '$path'`)/** The Storybook renderer package each framework's stories import their types from. */export const STORYBOOK_PACKAGES: Record<StorybookFramework, string> = {@@ -78,26 +114,28 @@ export const STORYBOOK_PACKAGES: Record<StorybookFramework, string> = {html: '@storybook/html-vite'}+/** How each framework renders a string of HTML, `$html`, as a story. */const FRAMEWORKS: Record<StorybookFramework, { imports: es.SyntaxNode[]; render: es.SyntaxNode }> ={react: {imports: es.parseModule(`import { createElement } from 'react'`).body,render: es.parseExpression(- `createElement('div', { dangerouslySetInnerHTML: { __html: variantHTML(args) } })`+ `createElement('div', { dangerouslySetInnerHTML: { __html: $html } })`)},vue: {imports: es.parseModule(`import { h } from 'vue'`).body,- render: es.parseExpression(- `{ setup: () => () => h('div', { innerHTML: variantHTML(args) }) }`- )+ render: es.parseExpression(`{ setup: () => () => h('div', { innerHTML: $html }) }`)},html: {imports: [],- render: es.parseExpression('variantHTML(args)')+ render: es.parseExpression('$html')}}+const rendered = (framework: StorybookFramework, html: string) =>+ es.fill(FRAMEWORKS[framework].render, { $html: es.parseExpression(html) })+const imageName = (variant: number) => `design${variant}`const BOOLEAN = es.parseType('boolean')@@ -214,6 +252,10 @@ function argsType(data: StoryModuleData): es.SyntaxNode {return es.objectType(entries)}+/** `import './fonts/kit/fonts.css'` for each stylesheet, which the bundler loads with the stories. */+export const stylesheets = (paths: readonly string[]) =>+ paths.flatMap((path) => es.fill(STYLESHEET, { $path: es.string(path) }).body)+/** Print a CSF3 story module for one component or component set. */export function printStoryModule(data: StoryModuleData): string {const framework = FRAMEWORKS[data.framework]@@ -226,10 +268,11 @@ export function printStoryModule(data: StoryModuleData): string {$key: es.array(data.props.map((prop) => propValue(data, prop))),$missing: es.string(`${data.name} has no variant `),$title: es.string(data.title),+ $tags: es.array(data.tags.map(es.string)),$parameters: data.metaDesign.length > 0 ? parameters(data.metaDesign) : es.OMIT,$args: argsObject(data, data.variants[0]?.values ?? []),$argTypes: argTypes(data),- $render: framework.render+ $render: rendered(data.framework, 'variantHTML(args)')}).bodyconst images = data.images.flatMap((path, i) =>@@ -241,15 +284,36 @@ export function printStoryModule(data: StoryModuleData): string {$name: es.identifier(story.exportName),$story: es.object([['name', es.string(story.label)],+ ...(story.tags.length > 0+ ? [['tags', es.array(story.tags.map(es.string))] as const]+ : []),...(story.design.length > 0 ? [['parameters', parameters(story.design)] as const] : []),['args', argsObject(data, story.values)]])}).body)+ const gallery = data.gallery+ ? es.fill(GALLERY, {+ $labels: es.array(+ data.gallery.map((item) =>+ es.array([es.string(JSON.stringify(item.values)), es.string(item.label)])+ )+ ),+ $render: rendered(data.framework, 'galleryHTML()')+ }).body+ : []const module = es.printModule({type: 'Program',sourceType: 'module',- body: [storybookImport, ...framework.imports, ...images, ...body, ...stories]+ body: [+ storybookImport,+ ...framework.imports,+ ...stylesheets(data.styles),+ ...images,+ ...body,+ ...stories,+ ...gallery+ ]})return `${HEADER}\n${module}\n`}diff --git a/packages/dom-css/src/export/storybook/names.ts b/packages/dom-css/src/export/storybook/names.tsindex 751f593c5..cd53a1b3d 100644--- a/packages/dom-css/src/export/storybook/names.ts+++ b/packages/dom-css/src/export/storybook/names.ts@@ -37,3 +37,15 @@ export function storyId(title: string): string {.replace(/^-+/, '').replace(/-+$/, '')}++/**+ * Tags a story file carries, which Storybook's sidebar filter and `main.ts` `tags` options+ * select by: every exported file, and the page it comes from.+ */+export const fileTags = (page: string) => ['openpencil', `page:${storyId(page)}`]++/**+ * The tag every story but a file's first carries: each other variant or state. Excluding it+ * in Storybook leaves one story per component, the one the design shows at rest.+ */+export const VARIANT_TAG = 'variant'diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.tsindex 1713235d8..2c5fefb58 100644--- a/packages/dom-css/src/index.ts+++ b/packages/dom-css/src/index.ts@@ -1,7 +1,7 @@import type * as DesignTypes from './types'export { exportHTMLBundle } from './export/bundle'-export { exportStorybook, STORYBOOK_FRAMEWORKS } from './export/storybook/export'+export { exportStorybook, STORY_MODES, STORYBOOK_FRAMEWORKS } from './export/storybook/export'export { serializeHTML, serializeNode } from './export/html'export { createBrowserCSSRuntime, createCSSRuntime, createHeadlessCSSRuntime } from './runtime'export {@@ -80,7 +80,10 @@ export type {export type {ExportStorybookOptions,StorybookFile,- StorybookFramework+ StorybookFramework,+ StoryMode,+ StoryPlan,+ StoryTarget} from './export/storybook/export'export type { SerializeHTMLOptions } from './export/html'export type { ToSceneGraphOptions } from './import/scene-graph'diff --git a/packages/dom-css/tests/export/components/vue.test.ts b/packages/dom-css/tests/export/components/vue.test.tsindex 08aa1f04d..249fa954f 100644--- a/packages/dom-css/tests/export/components/vue.test.ts+++ b/packages/dom-css/tests/export/components/vue.test.ts@@ -295,4 +295,13 @@ describe('generated Vue stories', () => {expect(stories.Checked?.args).toEqual({ checked: true })expect(typeof stories.Default?.play).toBe('function')})++ test('tag every state after Default, so Storybook can show one story per component', async () => {+ const { stories } = await generate(switchSet())+ const tags = (name: string) => (stories[name] as { tags?: string[] } | undefined)?.tags+ expect((stories.default as { tags: string[] }).tags).toContain('openpencil')+ expect(tags('Default')).toBeUndefined()+ expect(tags('Checked')).toEqual(['variant'])+ expect(tags('Disabled')).toEqual(['variant'])+ })})diff --git a/packages/dom-css/tests/export/storybook/export.test.ts b/packages/dom-css/tests/export/storybook/export.test.tsindex d22e1a51d..ea1e573d1 100644--- a/packages/dom-css/tests/export/storybook/export.test.ts+++ b/packages/dom-css/tests/export/storybook/export.test.ts@@ -5,6 +5,7 @@ import { join } from 'node:path'import { exportStorybook } from '#dom-css/index'+import { es } from '@open-pencil/emit'import { emptyBehaviour, SceneGraph, withBehaviour } from '@open-pencil/scene-graph'function buttonGraph() {@@ -39,6 +40,7 @@ function buttonGraph() {interface Story {name: string+ tags?: string[]args: Record<string, string | boolean>parameters?: { design: { name: string; type: string; url: string }[] }}@@ -46,6 +48,7 @@ interface Story {interface StoryModule {default: {title: string+ tags: string[]args: Record<string, string | boolean>argTypes: Record<string, unknown>render: (args: object) => string@@ -57,6 +60,14 @@ function storyExport(module: StoryModule, name: string): Story {return module[name] as Story}+/** The modules a story file imports, read from its syntax rather than its text. */+function importSources(content: string): string[] {+ return es+ .children(es.parseModule(content), 'body')+ .filter((node) => node.type === 'ImportDeclaration')+ .map((node) => String(es.child(node, 'source')?.value))+}+async function importStory(content: string): Promise<StoryModule> {const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-'))const path = join(dir, 'story.ts')@@ -92,6 +103,112 @@ describe('exportStorybook', () => {expect(() => story.default.render({ Size: 'Huge' })).toThrow('Button has no variant ["Huge"]')})+ it('tags its stories so Storybook can show one per component, or hide a page', async () => {+ const { graph } = buttonGraph()+ const [file] = await exportStorybook(graph, { framework: 'html' })+ const story = await importStory(String(file?.content))+ expect(story.default.tags).toEqual(['openpencil', 'page:library'])+ // The variant the design shows at rest is the Default story; each other one is a variant.+ expect(storyExport(story, 'Default')).toMatchObject({+ name: 'Default',+ args: { Size: 'Small' }+ })+ expect(storyExport(story, 'Default').tags).toBeUndefined()+ expect(storyExport(story, 'Large').tags).toEqual(['variant'])+ })++ it('writes each file as its plan says: renamed, Default alone, a gallery, or not at all', async () => {+ const { graph, page } = buttonGraph()+ graph.createNode('COMPONENT', page.id, { name: 'Badge', width: 10, height: 10 })+ graph.createNode('COMPONENT', page.id, { name: 'Internal', width: 10, height: 10 })+ const files = await exportStorybook(graph, {+ framework: 'html',+ renderDesignImage: () => Promise.resolve(new Uint8Array([1])),+ plan: ({ name }) => {+ if (name === 'Internal') return { stories: 'none' }+ if (name === 'Badge') return { stories: 'single', title: 'Kit/Button' }+ return { stories: 'gallery', title: 'Kit/Button' }+ }+ })+ // Only the Default story each file keeps gets a design image.+ expect(files.map((file) => file.path)).toEqual([+ 'Button.design/Default.png',+ 'Button.stories.ts',+ 'Badge.design/Default.png',+ 'Badge.stories.ts'+ ])+ const button = await importStory(String(files[1]?.content))+ // A gallery keeps Default, with its controls, and lays every variant out in one story.+ expect(+ Object.keys(button)+ .filter((key) => key !== 'default')+ .sort()+ ).toEqual(['Default', 'Gallery'])+ const gallery = button.Gallery as { render: () => string }+ expect(gallery.render()).toContain('<b>Small</b>')+ expect(gallery.render().match(/<figure/g)).toHaveLength(2)+ expect(gallery.render()).toContain(+ '<figcaption style="font: 12px system-ui, sans-serif; color: #6b7280">Large</figcaption>'+ )+ // Renamed titles stay apart, as titles that collide always do.+ const badge = await importStory(String(files[3]?.content))+ expect([button.default.title, badge.default.title]).toEqual(['Kit/Button', 'Kit/Button 2'])+ expect(Object.keys(badge).filter((key) => key !== 'default')).toEqual(['Default'])+ })++ it("ships the fonts its text uses in the document's folder, loaded before text draws", async () => {+ const { graph } = buttonGraph()+ const requested: { family: string; weight: number }[] = []+ const files = await exportStorybook(graph, {+ framework: 'html',+ document: 'Kit',+ fonts: (fonts, folder) => {+ requested.push(...fonts)+ return Promise.resolve(+ fonts.map((font) => ({+ ...font,+ style: font.style ?? 'normal',+ format: 'woff2' as const,+ path: `${folder}/${font.family.toLowerCase()}-${font.weight}.woff2`,+ content: new Uint8Array([1])+ }))+ )+ }+ })+ expect(requested.map((font) => font.family)).toEqual(['Inter'])+ const css = String(files.find((file) => file.path === 'fonts/kit/fonts.css')?.content)+ expect(files.map((file) => file.path)).toContain('fonts/kit/inter-400.woff2')+ expect(css).toContain('url("inter-400.woff2")')+ expect(css).toContain('font-display: block')+ const story = String(files.find((file) => file.path === 'Button.stories.ts')?.content)+ expect(importSources(story)).toContain('./fonts/kit/fonts.css')++ // A caller exporting several documents into one place names each one's folder.+ const named = await exportStorybook(graph, {+ framework: 'html',+ fontFolder: 'fonts/kit-design',+ fonts: (fonts, folder) =>+ Promise.resolve(+ fonts.map((font) => ({+ ...font,+ style: 'normal',+ format: 'woff2' as const,+ path: `${folder}/face.woff2`,+ content: new Uint8Array([1])+ }))+ )+ })+ expect(named.map((file) => file.path)).toContain('fonts/kit-design/fonts.css')++ // With no font files found, nothing is written and stories import nothing.+ const without = await exportStorybook(graph, {+ framework: 'html',+ fonts: () => Promise.resolve([])+ })+ expect(without.map((file) => file.path)).toEqual(['Button.stories.ts'])+ expect(importSources(String(without[0]?.content))).not.toContain('./fonts/kit/fonts.css')+ })+it('gives a component with a behaviour its own props instead of variant selects', async () => {const graph = new SceneGraph()const page = graph.addPage('Library')@@ -160,6 +277,41 @@ describe('exportStorybook', () => {})})+ it('draws a variant as it stands alone: hugging its content, sized with its borders', async () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Library')+ const tag = graph.createNode('COMPONENT', page.id, {+ name: 'Tag',+ layoutMode: 'HORIZONTAL',+ primaryAxisSizing: 'HUG',+ counterAxisSizing: 'HUG',+ paddingLeft: 8,+ paddingRight: 8+ })+ graph.createNode('FRAME', tag.id, {+ name: 'Dot',+ width: 20,+ height: 20,+ strokes: [+ {+ type: 'SOLID',+ color: { r: 0, g: 0, b: 0, a: 1 },+ weight: 2,+ opacity: 1,+ visible: true,+ align: 'INSIDE'+ }+ ]+ })+ const [file] = await exportStorybook(graph, { framework: 'html' })+ const html = (await importStory(String(file?.content))).default.render({})+ // The design hugs the tag, where a block would fill the story's canvas.+ expect(html).toMatch(/^<div style="[^"]*width: fit-content/)+ // The dot is 20px with its border, as the design draws it.+ const dot = /<div style="([^"]*width: 20px[^"]*)">/.exec(html)?.[1] ?? ''+ expect(dot).toContain('box-sizing: border-box')+ })+it('groups slash-named components and keeps standalone ones apart', async () => {const graph = new SceneGraph()const page = graph.addPage('Icons')@@ -217,7 +369,7 @@ describe('exportStorybook', () => {})expect(files.map((file) => file.path)).toEqual([- 'Button.design/Small.png',+ 'Button.design/Default.png','Button.design/Large.png','Button.stories.ts'])diff --git a/tests/engine/cli/export/storybook.test.ts b/tests/engine/cli/export/storybook.test.tsindex 821a29945..6d35fb5ae 100644--- a/tests/engine/cli/export/storybook.test.ts+++ b/tests/engine/cli/export/storybook.test.ts@@ -9,6 +9,9 @@ import { runOpenPencilCLI } from '#tests/helpers/cli'import { cliSourcePath } from '#tests/helpers/paths'import { makeSceneGraph } from '#tests/helpers/scene'+/** A Storybook export without font files, which come from the network these tests leave out. */+const STORYBOOK = ['--format', 'storybook', '--fonts', 'none']+setDefaultTimeout(30_000)const io = new IORegistry(BUILTIN_IO_FORMATS)@@ -37,8 +40,7 @@ test('export CLI writes Storybook stories with design images', async () => {const { stdout, stderr, exitCode } = await runOpenPencilCLI(['export',figPath,- '--format',- 'storybook',+ ...STORYBOOK,'--framework','vue','--font-policy',@@ -69,7 +71,7 @@ test('export CLI writes Storybook stories with design images', async () => {test('export CLI replaces stale generated stories and keeps hand-written ones', async () => {const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]const setup = await runOpenPencilCLI(['export',await writeComponentFixture(dir, ['Old']),@@ -94,7 +96,7 @@ test('export CLI replaces stale generated stories and keeps hand-written ones',test('export CLI keeps stories of other documents and refuses to overwrite them', async () => {const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]for (const [names, file] of [[['Card'], 'library.fig'],[['Chip'], 'b.fig']@@ -133,7 +135,7 @@ test('export CLI --page replaces that page and keeps the stories of other pages'await Bun.write(figPath, result.data as Uint8Array)}const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]await writeDocument('Old')expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)@@ -148,7 +150,7 @@ test('export CLI --page replaces that page and keeps the stories of other pages'test('export CLI tells apart documents that share a file name', async () => {const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]for (const [folder, name] of [['a', 'Card'],['b', 'Chip']@@ -173,7 +175,7 @@ test('export CLI --page refuses to renumber stories of other pages', async () =>await Bun.write(figPath, result.data as Uint8Array)}const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]await writeDocument('Card')expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)expect(await outputEntries(output)).toEqual(['Card.stories.ts', 'Card2.stories.ts'])@@ -199,8 +201,7 @@ test('export CLI refuses to overwrite a design image it did not generate', asyncconst { stderr, exitCode } = await runOpenPencilCLI(['export',figPath,- '--format',- 'storybook',+ ...STORYBOOK,'--font-policy','allow','--output',@@ -216,7 +217,7 @@ test('export CLI keeps files it did not generate in a design folder', async () =const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const figPath = await writeComponentFixture(dir, ['Badge'])const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--font-policy', 'allow', '--output', output]+ const args = [...STORYBOOK, '--font-policy', 'allow', '--output', output]expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)await Bun.write(join(output, 'Badge.design/notes.txt'), 'mine')@@ -228,7 +229,7 @@ test('export CLI keeps files it did not generate in a design folder', async () =test('export CLI removes the design folder of a deleted component', async () => {const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--font-policy', 'allow', '--output', output]+ const args = [...STORYBOOK, '--font-policy', 'allow', '--output', output]const badge = await writeComponentFixture(dir, ['Badge'])expect((await runOpenPencilCLI(['export', badge, ...args])).exitCode).toBe(0)@@ -242,7 +243,7 @@ test('export CLI refuses a design folder that links outside the output', async (const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const figPath = await writeComponentFixture(dir, ['Badge'])const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--font-policy', 'allow', '--output', output]+ const args = [...STORYBOOK, '--font-policy', 'allow', '--output', output]expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)const outside = join(dir, 'outside')await mkdir(outside)@@ -268,8 +269,7 @@ test('export CLI --beside writes the stories of every matched document next to iconst { stdout, stderr, exitCode } = await runOpenPencilCLI(['export',join(dir, '**/*.fig'),- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--beside'])@@ -295,8 +295,7 @@ test('export CLI expands an extglob pattern', async () => {const { stderr, exitCode } = await runOpenPencilCLI(['export',join(dir, '+(card|chip).fig'),- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--beside'])@@ -320,8 +319,7 @@ test('export CLI opens a document whose name contains glob syntax', async () =>const { stderr, exitCode } = await runOpenPencilCLI(['export',file,- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--beside'])@@ -345,8 +343,7 @@ test('export CLI --beside records documents that share a folder in one manifest''export',card,chip,- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--beside'])@@ -367,7 +364,7 @@ test('export CLI needs an output choice and one document for --page', async () =await writeComponentFixture(dir, ['Card'], 'card.fig')await writeComponentFixture(dir, ['Chip'], 'chip.fig')const pattern = join(dir, '*.fig')- const storybook = ['--format', 'storybook', '--no-design-images']+ const storybook = [...STORYBOOK, '--no-design-images']const noOutput = await runOpenPencilCLI(['export', pattern, ...storybook])expect(noOutput.exitCode).toBe(1)@@ -399,8 +396,7 @@ test('export CLI exports the other documents when one fails, then exits 1', asynconst { stderr, exitCode } = await runOpenPencilCLI(['export',join(dir, '*.fig'),- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--beside'])@@ -459,8 +455,7 @@ test('export CLI rejects Storybook export of a document without components', asyconst { stderr, exitCode } = await runOpenPencilCLI(['export',figPath,- '--format',- 'storybook',+ ...STORYBOOK,'--output',join(dir, 'stories')])@@ -485,8 +480,7 @@ test('export CLI refuses a manifest that lists files outside the output', asyncconst { stderr, exitCode } = await runOpenPencilCLI(['export',figPath,- '--format',- 'storybook',+ ...STORYBOOK,'--no-design-images','--output',output@@ -501,7 +495,7 @@ test('export CLI treats stories as foreign once the manifest is gone', async ()const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))const figPath = await writeComponentFixture(dir, ['Badge'])const output = join(dir, 'stories')- const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ const args = [...STORYBOOK, '--no-design-images', '--output', output]expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)await rm(join(output, MANIFEST))