AI-native design editor. Open-source Figma alternative.
feat: export components as Storybook stories (#751)
Marc Went802091b05174
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 1ca97ab89..6dab280a5 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,16 +10,19 @@### Added+- Export components to Storybook with `openpencil export -f storybook`: one CSF3 story file per component set or component for React, Vue, or HTML, with a story and `select` controls per variant, 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 (#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.- Choose PPTX in the Export panel's format list, alongside PNG, JPG, WEBP, SVG, and PDF.### Changed+- `openpencil://` and web `?node=` links select the layer on another page when the current page has none, switching to that page.- Generate Tailwind JSX with the same class mapping as Tailwind HTML export, so both describe a design the same way, and write opaque colors as hex in HTML, CSS, and Tailwind output. `openpencil export -f jsx --style tailwind` now exports a whole page when no `--node` is given.- Show download progress with a percentage and transferred size while installing a desktop update, instead of an indeterminate message that lasted until the restart.### Fixed+- Size auto-width text from `.pen` files to its content in CLI exports, instead of a 10000px placeholder that stretched hugging frames in HTML and Storybook output, and keep narrow widths a `.pen` file sets explicitly instead of widening multi-character text.- Keep grid layouts, rotation, inner shadows, every shadow of a layer, layer and background blur, flex grow, right-to-left direction, and sections in HTML export, which previously turned grids into columns and dropped the rest.- Show what to update instead of a blank window when the browser or system WebView is too old, naming the detected macOS, Safari, Chrome, Edge, Firefox, WebKitGTK, or WebView2 version and linking a prefilled bug report, and explain a failed start the same way (#744).- Start on macOS 13 with WebKit older than Safari 17.4, which previously failed with `Promise.withResolvers is not a function` (#744).diff --git a/README.md b/README.mdindex c7344474f..a9ee77c87 100644--- a/README.md+++ b/README.md@@ -80,7 +80,7 @@ openpencil query design.fig "//SECTION//TEXT" # Text insid### Export-Render to PNG, JPG, WEBP, SVG, PDF, PPTX, HTML, JSX, or `.fig` — or export selections/pages as `.fig` and convert whole documents between supported formats:+Render to PNG, JPG, WEBP, SVG, PDF, PPTX, HTML, JSX, Storybook stories, or `.fig` — or export selections/pages as `.fig` and convert whole documents between supported formats:```shopenpencil export design.fig # PNG@@ -89,6 +89,7 @@ openpencil export design.fig -f fig --page "Page 1" # Export a page as .figopenpencil export design.fig -f jsx --style tailwind # Tailwind JSXopenpencil export design.fig -f html --css tailwind # Tailwind HTML fragmentopenpencil export design.fig -f html --html standalone --assets external # HTML + assets+openpencil export design.fig -f storybook --framework vue # Storybook stories per componentopenpencil convert design.pen output.fig # Convert between document formatsopenpencil import page.html --css styles.css -o page.fig # HTML/CSS → editable .fig```diff --git a/bun.lock b/bun.lockindex a265bba25..a4b2ed59f 100644--- a/bun.lock+++ b/bun.lock@@ -175,6 +175,7 @@"canvaskit-wasm": "^0.41.1","citty": "^0.1.6","js-base64": "^3.9.3",+ "valibot": "^1.4.2",},"devDependencies": {"@types/bun": "^1.3.14",@@ -250,6 +251,10 @@"version": "0.15.1","dependencies": {"@acemir/cssom": "^0.9.31",+ "@sveltejs/acorn-typescript": "^1.0.13",+ "acorn": "^8.18.0",+ "dedent": "^1.7.2",+ "es-toolkit": "^1.51.0","esrap": "^2.3.11","js-base64": "^3.9.3","parse5": "^8.0.1",@@ -1773,6 +1778,8 @@"@supabase/supabase-js": ["@supabase/[email protected]", "", { "dependencies": { "@supabase/auth-js": "2.112.3", "@supabase/functions-js": "2.112.3", "@supabase/postgrest-js": "2.112.3", "@supabase/realtime-js": "2.112.3", "@supabase/storage-js": "2.112.3" }, "peerDependencies": { "@opentelemetry/api": ">=1.0.0" }, "optionalPeers": ["@opentelemetry/api"] }, "sha512-Jv1bxVQmEJNkjvPEhFaKjPzsh+Ozyew6lWGD+SoYcsclDEP1z7yEvKvfUQfzy0DkxRIQnZNxmmWtAzw5XLTQoA=="],+ "@sveltejs/acorn-typescript": ["@sveltejs/[email protected]", "", { "peerDependencies": { "acorn": "^8.9.0" } }, "sha512-wgKggnhZVL9Bfx1OaKKTrYY9BFRk6C8UAkQNUcIv1+llzYrIqy+RZm5HPKzn0NpEBvTVhTqB4kQyllZywsRBRQ=="],+"@svgdotjs/svg.js": ["@svgdotjs/[email protected]", "", {}, "sha512-NUdbI/7FDdqGpzKmqr09IQoy9MUcrAC/3bC8gLgXi6OfJuyri450zMLvJekFUhuq3iN5gpdPjoSoStNl9Eijfg=="],"@swc/helpers": ["@swc/[email protected]", "", { "dependencies": { "tslib": "^2.8.0" } }, "sha512-5lSsMOTXURePglDfvuAQUqkGek9Hg2kksOYay2m0+XR++b2NWYL/4sWyuvVBIs8oKnJaxkdi9whaL/sqN13afw=="],diff --git a/packages/cli/package.json b/packages/cli/package.jsonindex ac1694f3f..022292635 100644--- a/packages/cli/package.json+++ b/packages/cli/package.json@@ -43,7 +43,8 @@"agentfmt": "^0.1.3","canvaskit-wasm": "^0.41.1","citty": "^0.1.6",- "js-base64": "^3.9.3"+ "js-base64": "^3.9.3",+ "valibot": "^1.4.2"},"devDependencies": {"@types/bun": "^1.3.14"diff --git a/packages/cli/src/export-font-policy.ts b/packages/cli/src/commands/export/font-policy.tssimilarity index 100%rename from packages/cli/src/export-font-policy.tsrename to packages/cli/src/commands/export/font-policy.tsdiff --git a/packages/cli/src/commands/export.ts b/packages/cli/src/commands/export/index.tssimilarity index 88%rename from packages/cli/src/commands/export.tsrename to packages/cli/src/commands/export/index.tsindex 12ecabdc2..5adcc2553 100644--- a/packages/cli/src/commands/export.ts+++ b/packages/cli/src/commands/export/index.ts@@ -8,12 +8,20 @@ import { BUILTIN_IO_FORMATS, IORegistry, type ExportResult } from '@open-pencil/import { isAppMode, requireFile, rpc } from '#cli/app-client'import { appTargetOptions, appTargetRPCArgs } from '#cli/app-target'-import { applyExportFontPolicy, exportFontRoots, FONT_POLICIES } from '#cli/export-font-policy'import { ok, printError } from '#cli/format'-import { loadDocument, populateDocumentPage, populateWholeDocument } from '#cli/headless'+import {+ loadDocument,+ populateDocumentPage,+ populateWholeDocument,+ requirePage+} from '#cli/headless'++import { applyExportFontPolicy, exportFontRoots, FONT_POLICIES } from './font-policy'+import { exportStorybookFromFile } from './storybook'const io = new IORegistry(BUILTIN_IO_FORMATS)-const FORMAT_IDS = io.listExportFormats('node').map((format) => format.id)+// Storybook writes a folder of stories, so it stays a CLI command beside the IO formats.+const FORMAT_IDS = [...io.listExportFormats('node').map((format) => format.id), 'storybook']const ALL_FORMATS = new Set(FORMAT_IDS.map((id) => id.toUpperCase()))const FORMAT_LIST = `${FORMAT_IDS.slice(0, -1).join(', ')}, or ${FORMAT_IDS.at(-1)}`@@ -26,7 +34,7 @@ const HTML_MODES = new Set(['fragment', 'standalone'])const HTML_ASSETS = new Set(['inline', 'external'])const HTML_FONTS = new Set(['assets', 'none'])-interface ExportArgs {+export interface ExportArgs {file?: stringoutput?: stringformat: string@@ -39,6 +47,9 @@ interface ExportArgs {css: stringassets: stringfonts: string+ framework: string+ 'design-images': boolean+ watch?: boolean'font-policy': stringthumbnail?: booleanwidth: string@@ -84,7 +95,13 @@ async function exportViaApp(format: string, args: ExportArgs) {return}- if (format === 'JSX' || format === 'HTML' || format === 'FIG' || format === 'PPTX') {+ if (+ format === 'JSX' ||+ format === 'HTML' ||+ format === 'FIG' ||+ format === 'PPTX' ||+ format === 'STORYBOOK'+ ) {printError(`${format} export is only available in file mode right now.`)process.exit(1)}@@ -167,18 +184,8 @@ function exportOptions(format: string, args: ExportArgs): unknown {async function exportFromFile(format: string, args: ExportArgs) {const file = requireFile(args.file)const graph = await loadDocument(file)-const pages = graph.getPages()- const page = args.page ? pages.find((p) => p.name === args.page) : pages[0]- if (!page) {- const available = pages.map((p) => `"${p.name}"`).join(', ')- printError(- args.page- ? `Page "${args.page}" not found. Available pages: ${available || 'none'}.`- : 'Document has no pages.'- )- process.exit(1)- }+ const page = requirePage(graph, args.page)const defaultName = basename(file, extname(file))@@ -238,7 +245,8 @@ export default defineCommand({output: {type: 'string',alias: 'o',- description: 'Output file path (default: <name>.<format>)',+ description:+ 'Output file path (default: <name>.<format>); for storybook, a directory (default: <name>-stories)',required: false},format: {@@ -256,7 +264,8 @@ export default defineCommand({},page: {type: 'string',- description: 'Export a specific page by name (FIG defaults to the whole document)',+ description:+ 'Export a specific page by name (FIG, PPTX, and Storybook default to the whole document)',required: false},node: {@@ -289,6 +298,20 @@ export default defineCommand({description: 'HTML font output: assets or none (default: none)',default: 'none'},+ framework: {+ type: 'string',+ description: 'Storybook framework: react, vue, or html (default: react)',+ default: 'react'+ },+ 'design-images': {+ type: 'boolean',+ description: 'Storybook: render each variant to PNG for the Design panel (default: true)',+ default: true+ },+ watch: {+ type: 'boolean',+ description: 'Storybook: re-export whenever the document changes'+ },'font-policy': {type: 'string',description: 'Raster/PDF font policy: warn, strict, or allow (default: warn)',@@ -338,6 +361,8 @@ export default defineCommand({if (isAppMode(args.file)) {await exportViaApp(format, args)+ } else if (format === 'STORYBOOK') {+ await exportStorybookFromFile(args)} else {await exportFromFile(format, args)}diff --git a/packages/cli/src/commands/export/storybook/index.ts b/packages/cli/src/commands/export/storybook/index.tsnew file mode 100644index 000000000..b288893e6--- /dev/null+++ b/packages/cli/src/commands/export/storybook/index.ts@@ -0,0 +1,239 @@+import { existsSync, watch } from 'node:fs'+import { lstat, mkdir, mkdtemp, rename, rm, rmdir, writeFile } from 'node:fs/promises'+import {+ basename,+ dirname,+ extname,+ isAbsolute,+ join,+ posix,+ relative,+ resolve,+ sep+} from 'node:path'++import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'+import {+ exportStorybook,+ STORYBOOK_FRAMEWORKS,+ type StorybookFile,+ type StorybookFramework+} from '@open-pencil/dom-css'++import { requireFile } from '#cli/app-client'+import { applyExportFontPolicy } from '#cli/commands/export/font-policy'+import { ok, printError } from '#cli/format'+import { loadDocument, populateWholeDocument, requirePage } from '#cli/headless'++import { readManifest, writeManifest, type StoryManifest, type StoryOwner } from './manifest'++interface StorybookArgs {+ file?: string+ output?: string+ page?: string+ node?: string+ framework: string+ 'design-images': boolean+ 'font-policy': string+ watch?: boolean+}++const io = new IORegistry(BUILTIN_IO_FORMATS)++function isStorybookFramework(value: string): value is StorybookFramework {+ return STORYBOOK_FRAMEWORKS.some((framework) => framework === value)+}++function toPosix(path: string): string {+ return path.split(sep).join(posix.sep)+}++/** Repository-relative path for `openpencil://` links, when the file sits under the cwd. */+function linkPath(file: string): string | undefined {+ const path = toPosix(relative(process.cwd(), resolve(file)))+ return path.startsWith('../') || isAbsolute(path) ? undefined : path+}++/** What an export replaces: every page of `source`, or only `page` for a one-page export. */+interface ExportScope {+ source: string+ page?: string+}++function owns(scope: ExportScope, owner: StoryOwner): boolean {+ return owner.source === scope.source && (scope.page === undefined || owner.page === scope.page)+}++function conflict(outputDir: string, path: string, manifest: StoryManifest, scope: ExportScope) {+ const target = join(outputDir, path)+ const elsewhere = `; export ${scope.source} to another --output directory.`+ if (!Object.hasOwn(manifest.files, path))+ return new Error(`${target} was not generated by this export${elsewhere}`)+ const owner = manifest.files[path]+ if (owner.source === scope.source)+ return new Error(+ `${target} holds page ${owner.page} of ${scope.source}; export the whole document to renumber its stories.`+ )+ return new Error(`${target} was generated from ${owner.source}, page ${owner.page}${elsewhere}`)+}++function isErrorCode(error: unknown, ...codes: string[]): boolean {+ return error instanceof Error && 'code' in error && codes.includes(String(error.code))+}++/**+ * Refuses a path whose `.design` folder is a symbolic link: removing or writing an image+ * through it would reach outside the output directory.+ */+async function refuseLinkedFolder(outputDir: string, path: string): Promise<void> {+ const folder = dirname(path)+ if (folder === '.') return+ const stats = await lstat(join(outputDir, folder)).catch((error: unknown) => {+ if (isErrorCode(error, 'ENOENT')) return null+ throw error+ })+ if (stats && !stats.isDirectory())+ throw new Error(`${join(outputDir, folder)} is not a folder; remove it and export again.`)+}++/**+ * Removes the files the manifest says a previous export of this scope generated, so a+ * component deleted or renamed in the document does not linger, and returns the manifest+ * for the new files. Refuses before removing anything when the export would overwrite a+ * file it did not generate: a hand-written story, another document's, or someone's image.+ */+async function replaceGeneratedFiles(+ outputDir: string,+ scope: ExportScope,+ files: StorybookFile[]+): Promise<StoryManifest> {+ const manifest = await readManifest(outputDir)+ const owned = new Set(+ Object.entries(manifest.files)+ .filter(([, owner]) => owns(scope, owner))+ .map(([path]) => path)+ )+ const paths = files.map((file) => file.path)++ for (const path of new Set([...paths, ...owned])) await refuseLinkedFolder(outputDir, path)+ for (const path of paths) {+ if (owned.has(path) || !existsSync(join(outputDir, path))) continue+ throw conflict(outputDir, path, manifest, scope)+ }+ for (const path of owned) await rm(join(outputDir, path), { force: true })+ for (const folder of new Set([...owned].map(dirname))) {+ if (folder === '.') continue+ // Only a folder the removal emptied goes; anything else someone put there stays.+ await rmdir(join(outputDir, folder)).catch((error: unknown) => {+ if (!isErrorCode(error, 'ENOTEMPTY', 'ENOENT', 'EEXIST')) throw error+ })+ }++ const kept = Object.entries(manifest.files).filter(([path]) => !owned.has(path))+ const added = files.map((file) => [file.path, { source: scope.source, page: file.page }])+ return { version: 1, files: Object.fromEntries([...kept, ...added]) }+}++async function writeStories(+ args: StorybookArgs,+ file: string,+ framework: StorybookFramework,+ outputDir: string+): Promise<number> {+ const graph = await loadDocument(file)+ const pageId = args.page ? requirePage(graph, args.page).id : undefined+ populateWholeDocument(graph)+ if (args['design-images']) {+ const pageIds = pageId ? [pageId] : graph.getPages().map((page) => page.id)+ await applyExportFontPolicy(graph, pageIds, 'PNG', args['font-policy'])+ }+ const files = await exportStorybook(graph, {+ framework,+ pageId,+ linkPath: linkPath(file),+ renderDesignImage: args['design-images']+ ? async (nodeId) => {+ const result = await io.exportContent(+ 'png',+ { graph, target: { scope: 'node', nodeId } },+ { format: 'PNG', scale: 2 }+ )+ if (!(result.data instanceof Uint8Array)) throw new Error('PNG export returned text.')+ return result.data+ }+ : undefined+ })+ if (files.length === 0)+ 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 }+ 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.+ const staging = await mkdtemp(join(outputDir, '.openpencil-export-'))+ try {+ for (const story of files) {+ await mkdir(dirname(join(staging, story.path)), { recursive: true })+ await writeFile(join(staging, story.path), story.content)+ }+ const manifest = await replaceGeneratedFiles(outputDir, scope, files)+ for (const { path } of files) {+ await mkdir(dirname(join(outputDir, path)), { recursive: true })+ await rename(join(staging, path), join(outputDir, path))+ }+ await writeManifest(outputDir, manifest)+ } finally {+ await rm(staging, { recursive: true, force: true })+ }+ return files.filter((story) => story.path.endsWith('.stories.ts')).length+}++/** Re-exports on every save; editors that save by rename are why the folder is watched. */+function watchDocument(file: string, onChange: () => Promise<void>): void {+ let timer: ReturnType<typeof setTimeout> | undefined+ let running = Promise.resolve()+ watch(dirname(resolve(file)), (_event, name) => {+ if (name !== basename(file)) return+ clearTimeout(timer)+ timer = setTimeout(() => {+ running = running.then(onChange)+ }, 200)+ })+}++export async function exportStorybookFromFile(args: StorybookArgs): Promise<void> {+ if (args.node) {+ printError('--node is not supported for Storybook export. Use --page to limit it to one page.')+ process.exit(1)+ }+ const framework = args.framework+ if (!isStorybookFramework(framework)) {+ printError(+ `Invalid Storybook framework "${framework}". Use ${STORYBOOK_FRAMEWORKS.join(', ')}.`+ )+ process.exit(1)+ }+ const file = requireFile(args.file)+ const outputDir = resolve(args.output ?? `${basename(file, extname(file))}-stories`)+ const run = async () => {+ const count = await writeStories(args, file, framework, outputDir)+ console.log(ok(`Exported ${count} story files to ${outputDir}`))+ }++ try {+ await run()+ } catch (error) {+ printError(error instanceof Error ? error.message : String(error))+ process.exit(1)+ }+ if (!args.watch) return++ // A save can land mid-write or break the document; report it and keep watching.+ watchDocument(file, () =>+ run().catch((error: unknown) =>+ printError(error instanceof Error ? error.message : String(error))+ )+ )+ console.log(ok(`Watching ${file} for changes`))+}diff --git a/packages/cli/src/commands/export/storybook/manifest.ts b/packages/cli/src/commands/export/storybook/manifest.tsnew file mode 100644index 000000000..11ecc30f2--- /dev/null+++ b/packages/cli/src/commands/export/storybook/manifest.ts@@ -0,0 +1,65 @@+import { readFile, rename, writeFile } from 'node:fs/promises'+import { isAbsolute, join, posix } from 'node:path'++import * as v from 'valibot'++/**+ * Records which document and page generated each file in a Storybook output folder, so a+ * re-export replaces its own stories and leaves every other file alone.+ */+export const MANIFEST_FILE = '.openpencil-stories.json'++/**+ * A story file or a design image directly under the output folder. The manifest is read+ * from disk and may have been edited, so nothing it lists may point anywhere else.+ */+export function isGeneratedPath(path: string): boolean {+ if (isAbsolute(path) || posix.normalize(path) !== path || path.startsWith('..')) return false+ const folder = posix.dirname(path)+ if (folder === '.') return path.endsWith('.stories.ts')+ return posix.dirname(folder) === '.' && folder.endsWith('.design') && path.endsWith('.png')+}++const StoryOwnerSchema = v.object({ source: v.string(), page: v.string() })++const ManifestSchema = v.object({+ version: v.literal(1),+ files: v.record(+ v.pipe(v.string(), v.check(isGeneratedPath, 'Expected a story or design image path.')),+ StoryOwnerSchema+ )+})++export type StoryOwner = v.InferOutput<typeof StoryOwnerSchema>+export type StoryManifest = v.InferOutput<typeof ManifestSchema>++export async function readManifest(outputDir: string): Promise<StoryManifest> {+ const path = join(outputDir, MANIFEST_FILE)+ let text: string+ try {+ text = await readFile(path, 'utf8')+ } catch (error) {+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')+ return { version: 1, files: {} }+ throw error+ }+ let data: unknown+ try {+ data = JSON.parse(text)+ } catch {+ data = undefined+ }+ const result = v.safeParse(ManifestSchema, data)+ if (!result.success)+ throw new Error(+ `${path} is not a valid OpenPencil stories manifest; remove it together with the stories it listed, then export again.`+ )+ return result.output+}++/** Written beside the stories and renamed into place, so a failed write keeps the old one. */+export async function writeManifest(outputDir: string, manifest: StoryManifest): Promise<void> {+ const path = join(outputDir, MANIFEST_FILE)+ await writeFile(`${path}.tmp`, `${JSON.stringify(manifest, null, 2)}\n`)+ await rename(`${path}.tmp`, path)+}diff --git a/packages/cli/src/headless.ts b/packages/cli/src/headless.tsindex 379cbc7c5..a0f529539 100644--- a/packages/cli/src/headless.ts+++ b/packages/cli/src/headless.ts@@ -5,6 +5,8 @@ import { populateAllLazyFigImportRoots, populateLazyFigImportRoots } from '@openimport { computeAllLayouts } from '@open-pencil/core/layout'import type { SceneGraph } from '@open-pencil/scene-graph'+import { printError } from '#cli/format'+export { initCanvasKit }const io = new IORegistry(BUILTIN_IO_FORMATS)@@ -54,3 +56,18 @@ export function prepareDocumentForRPC(graph: SceneGraph, command: string, args?:}populateWholeDocument(graph)}++export function requirePage(graph: SceneGraph, pageName?: string) {+ const pages = graph.getPages()+ const page = pageName ? pages.find((p) => p.name === pageName) : pages[0]+ if (!page) {+ const available = pages.map((p) => `"${p.name}"`).join(', ')+ printError(+ pageName+ ? `Page "${pageName}" not found. Available pages: ${available || 'none'}.`+ : 'Document has no pages.'+ )+ process.exit(1)+ }+ return page+}diff --git a/packages/core/src/editor/pages.ts b/packages/core/src/editor/pages.tsindex 1fb1e8e41..c7a69aa6d 100644--- a/packages/core/src/editor/pages.ts+++ b/packages/core/src/editor/pages.ts@@ -51,9 +51,10 @@ export function createPageActions(ctx: EditorContext) {return populationWorkerInstance}+ /** `switchGeneration` is null for a lookup, which no page switch can supersede. */async function populatePage(pageId: string,- switchGeneration: number,+ switchGeneration: number | null,signal?: AbortSignal): Promise<boolean | null> {throwIfAborted(signal)@@ -63,7 +64,7 @@ export function createPageActions(ctx: EditorContext) {throwIfAborted(signal)if (workerGeneration !== populationWorkerGeneration ||- switchGeneration !== pageSwitchGeneration+ (switchGeneration !== null && switchGeneration !== pageSwitchGeneration)) {return null}@@ -179,6 +180,14 @@ export function createPageActions(ctx: EditorContext) {return true}+ /**+ * Loads a page's layers so they can be searched, without fonts, layout, or switching to+ * it — and without superseding a page switch the user has in progress.+ */+ async function loadPageNodes(pageId: string): Promise<void> {+ if (ctx.graph.getNode(pageId)?.type === 'CANVAS') await populatePage(pageId, null)+ }+async function switchPage(pageId: string, options: SwitchPageOptions = {}): Promise<void> {const prepared = await preparePage(pageId, options)if (prepared) commitPageSwitch(prepared)@@ -233,7 +242,14 @@ export function createPageActions(ctx: EditorContext) {ctx.requestRender()}+ /** Advances whenever a page switch starts, so a caller can tell it was overtaken. */+ function pageSwitchCount(): number {+ return pageSwitchGeneration+ }+return {+ loadPageNodes,+ pageSwitchCount,preparePage,commitPageSwitch,switchPage,diff --git a/packages/docs/programmable/cli/exporting.md b/packages/docs/programmable/cli/exporting.mdindex 50830d789..6d3d3c731 100644--- a/packages/docs/programmable/cli/exporting.md+++ b/packages/docs/programmable/cli/exporting.md@@ -1,11 +1,11 @@---title: Exporting-description: Export document content to images, PDF, PowerPoint, `.fig`, JSX, or HTML, with font-substitution policies for raster and PDF output.+description: Export document content to images, PDF, PowerPoint, `.fig`, JSX, HTML, or Storybook stories, with font-substitution policies for raster and PDF output.---# Exporting-Export designs from the terminal — raster images, vectors, PDF, editable PowerPoint, `.fig` subsets, JSX code, or HTML.+Export designs from the terminal — raster images, vectors, PDF, editable PowerPoint, `.fig` subsets, JSX code, HTML, or Storybook stories.## Image Export@@ -23,7 +23,7 @@ openpencil export design.fig -f html --css tailwind # export an HTML fragmentOptions:-- `-f` — format: `png`, `jpg`, `webp`, `svg`, `pdf`, `pptx`, `jsx`, `html`, `fig`+- `-f` — format: `png`, `jpg`, `webp`, `svg`, `pdf`, `pptx`, `jsx`, `html`, `fig`, `storybook`- `-s` — export scale (default: `1`)- `-q` — quality: `0`–`100` (JPG/WEBP only)- `-o` — output path@@ -88,6 +88,28 @@ Standalone Tailwind output is compiled during export; it does not depend on theHTML export is available in file mode.+## Storybook Export++Generate one CSF3 `.stories.ts` file per component set or component:++```sh+openpencil export design.fig -f storybook # React stories in ./design-stories/+openpencil export design.fig -f storybook --framework vue -o src/stories+openpencil export design.fig -f storybook --framework html --page "Components"+openpencil export design.pen -f storybook -o src/stories --watch # re-export on every save+```++Each variant of a component set becomes a story, and its variant properties become `select` controls, so switching a control shows the matching variant. 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. Text, boolean, and instance-swap properties are not exported yet.++Stories carry `parameters.design` entries for [`@storybook/addon-designs`](https://github.com/storybookjs/addon-designs):++- **OpenPencil** — when the document path is inside the current directory, an [`openpencil://` link](../index#url-scheme) that opens the document in the desktop app and selects the variant, or its component set when another layer shares the variant's name. The scheme addresses layers by name, so a story whose variant and component names are both shared by other layers gets no link.+- **Design** — a 2× PNG of the variant, written to `<Name>.design/` next to the story and referenced with `new URL(…, import.meta.url)`, so Vite bundles it. Copy the parameter onto the story of your own component to compare the implementation with the design. `--no-design-images` skips rendering; font substitution follows `--font-policy` as in raster export.++`-o` names the output directory. A `.openpencil-stories.json` manifest there records which document, as a path relative to the output directory, and which page generated each story and design image; commit it with the stories. An export replaces the files that a previous export of the same document generated there, including those of components since deleted or renamed; with `--page`, only that page's. It refuses, before changing anything, to overwrite any other file — a hand-written story, another document's, or a stray image. A one-page export whose file names shifted onto another page's stories asks for a full export instead. Without the manifest, existing stories count as someone else's, so remove them before exporting again. `--watch` keeps the command running and re-exports whenever the document is saved, so Storybook's hot reload follows the design; a save that cannot be read is reported and the watch continues. A missing `--page` or a `--font-policy strict` substitution still ends the command.+## Live App ModeOmit the file to export from the running app:@@ -96,4 +118,4 @@ Omit the file to export from the running app:openpencil export -f png # export from the current document```-Live app mode supports PNG, JPG, WEBP, SVG, and PDF. PowerPoint, JSX, HTML, and `.fig` exports require a file argument. File-mode thumbnail export is not currently supported.+Live app mode supports PNG, JPG, WEBP, SVG, and PDF. PowerPoint, JSX, HTML, Storybook, and `.fig` exports require a file argument. File-mode thumbnail export is not currently supported.diff --git a/packages/docs/programmable/index.md b/packages/docs/programmable/index.mdindex 815db4935..72eb1de52 100644--- a/packages/docs/programmable/index.md+++ b/packages/docs/programmable/index.md@@ -70,7 +70,7 @@ openpencil://open?file=web/design/hikyo.pen&node=Button/Large/DefaultThe app matches `file` against the paths of the open tabs as a whole trailing segment sequence, and focuses that tab without re-reading the document, so a file that moved or turned unreadable since it opened still gets its layer selected. The first open tab whose path ends with the requested path wins, which matters when two checkouts have the same file open. Segments are compared the way the platform's filesystem does: ASCII-case-insensitively on macOS and Windows, exactly on Linux, so `Web/Design/hikyo.pen` and `web/design/hikyo.pen` are the same file on a Mac and two different ones on Linux. If no open tab matches, a file picker asks for the file once; the picked file must end with the same relative path, otherwise the link is cancelled. No path is joined onto a root and no filesystem access is granted beyond what the picker returns. A file the link actually opens — the picked one — joins the recent-files list like any other file you open; focusing a tab that was already open does not touch the list, because nothing was opened.-With a node name, the app selects every layer carrying that exact name on the current page and zooms the view to the whole selection. An unknown name shows a notice and leaves the document open. Opening a file and selecting layers is all the scheme can do.+With a node name, the app selects every layer carrying that exact name on the current page and zooms the view to the whole selection. When the current page has none, it switches to the first page that does, loading pages as needed. An unknown name shows a notice and leaves the document open. Opening a file and selecting layers is all the scheme can do.The web app takes the same link from its own address bar:diff --git a/packages/docs/reference/cli.md b/packages/docs/reference/cli.mdindex 80c5f5abe..1d57809de 100644--- a/packages/docs/reference/cli.md+++ b/packages/docs/reference/cli.md@@ -90,7 +90,7 @@ openpencil variables [file] [options]## export-Export to PNG, JPG, WEBP, SVG, JSX, HTML, or `.fig`.+Export to PNG, JPG, WEBP, SVG, JSX, HTML, `.fig`, or Storybook stories.```shopenpencil export [file] [options]@@ -98,17 +98,20 @@ openpencil export [file] [options]| Option | Alias | Description ||--------|-------|-------------|-| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `pdf`, `pptx`, `jsx`, `tailwind-jsx`, `html`, `fig` |-| `--output` | `-o` | Output file path (default: `<name>.<format>`) |+| `--format` | `-f` | `png` (default), `jpg`, `webp`, `svg`, `pdf`, `pptx`, `jsx`, `tailwind-jsx`, `html`, `fig`, `storybook` |+| `--output` | `-o` | Output file path (default: `<name>.<format>`); a directory for `storybook` (default: `<name>-stories`) || `--scale` | `-s` | Export scale (default: 1) || `--quality` | `-q` | Quality 0–100, JPG/WEBP only (default: 90) |-| `--page` | | Page name (default: first page) |+| `--page` | | Page name (default: first page; `fig`, `pptx`, and `storybook` default to every page) || `--node` | | Node ID to export (default: all top-level nodes) || `--style` | | JSX style: `openpencil` (default), `tailwind` (same as `-f tailwind-jsx`) || `--html` | | HTML mode: `fragment` (default), `standalone` || `--css` | | HTML CSS output: `inline` (default), `tailwind` || `--assets` | | Standalone HTML assets: `inline` (default), `external` || `--fonts` | | Standalone HTML font output: `assets`, `none` (default) |+| `--framework` | | Storybook framework: `react` (default), `vue`, `html` |+| `--design-images` | | Storybook: render a PNG per variant for the Design panel (default: on; `--no-design-images` to skip) |+| `--watch` | | Storybook: re-export whenever the document is saved || `--thumbnail` | | Export page thumbnail instead of full render || `--width` | | Thumbnail width (default: 1920) || `--height` | | Thumbnail height (default: 1080) |diff --git a/packages/dom-css/package.json b/packages/dom-css/package.jsonindex c25fab703..cafae83ab 100644--- a/packages/dom-css/package.json+++ b/packages/dom-css/package.json@@ -77,6 +77,10 @@},"dependencies": {"@acemir/cssom": "^0.9.31",+ "@sveltejs/acorn-typescript": "^1.0.13",+ "acorn": "^8.18.0",+ "dedent": "^1.7.2",+ "es-toolkit": "^1.51.0","esrap": "^2.3.11","js-base64": "^3.9.3","parse5": "^8.0.1",diff --git a/packages/dom-css/src/index.ts b/packages/dom-css/src/index.tsindex b0c5eab1b..be535a33a 100644--- a/packages/dom-css/src/index.ts+++ b/packages/dom-css/src/index.ts@@ -1,6 +1,7 @@import type * as DesignTypes from './types'export { exportHTMLBundle } from './html-export'+export { exportStorybook, STORYBOOK_FRAMEWORKS } from './storybook/export'export { serializeHTML, serializeNode } from './serialize'export { createBrowserCSSRuntime, createCSSRuntime, createHeadlessCSSRuntime } from './runtime'export {@@ -71,6 +72,7 @@ export type {WebFontFaceRequest,WebFontFaceResolver} from './html-export'+export type { ExportStorybookOptions, StorybookFile, StorybookFramework } from './storybook/export'export type { SerializeHTMLOptions } from './serialize'export type { ToSceneGraphOptions } from './to-scene-graph'export type CSSComputeOptions = DesignTypes.CSSComputeOptionsdiff --git a/packages/dom-css/src/storybook/estree.ts b/packages/dom-css/src/storybook/estree.tsnew file mode 100644index 000000000..942f84c36--- /dev/null+++ b/packages/dom-css/src/storybook/estree.ts@@ -0,0 +1,134 @@+import { tsPlugin } from '@sveltejs/acorn-typescript'+import { Parser } from 'acorn'+import { print } from 'esrap'+import ts from 'esrap/languages/ts'++/** An ESTree or TS-ESTree node, as acorn parses it and esrap prints it. */+export interface SyntaxNode {+ type: string+ [key: string]: unknown+}++const TSParser = Parser.extend(tsPlugin())++function isNode(value: unknown): value is SyntaxNode {+ return typeof value === 'object' && value !== null && 'type' in value+}++/** The node under `key`, or undefined when it is absent or not a node. */+export function child(node: SyntaxNode | undefined, key: string): SyntaxNode | undefined {+ const value = node?.[key]+ return isNode(value) ? value : undefined+}++export function children(node: SyntaxNode | undefined, key: string): SyntaxNode[] {+ const value = node?.[key]+ return Array.isArray(value) ? value.filter(isNode) : []+}++export function parseModule(source: string): SyntaxNode & { body: SyntaxNode[] } {+ const program: unknown = TSParser.parse(source, { ecmaVersion: 'latest', sourceType: 'module' })+ if (!isNode(program)) throw new Error('Expected a module')+ return { ...program, body: children(program, 'body') }+}++export function parseExpression(source: string): SyntaxNode {+ const expression = child(parseModule(`(${source})`).body.at(0), 'expression')+ if (!expression) throw new Error(`Expected an expression: ${source}`)+ return expression+}++export function parseType(source: string): SyntaxNode {+ const type = child(parseModule(`type T = ${source}`).body.at(0), 'typeAnnotation')+ if (!type) throw new Error(`Expected a type: ${source}`)+ return type+}++/** A hole value that removes the object property holding it. */+export const OMIT = Symbol('omit')++/**+ * Replace `$name` placeholders — identifiers, type references, and string literals — with+ * nodes. A property whose value is filled with `OMIT` is removed.+ */+export function fill<T extends SyntaxNode>(+ template: T,+ holes: Record<string, SyntaxNode | typeof OMIT>+): T {+ const hole = (name: unknown) => (typeof name === 'string' ? holes[name] : undefined)+ const holeOf = (node: SyntaxNode) => {+ if (node.type === 'Identifier') return hole(node.name)+ if (node.type === 'Literal') return hole(node.value)+ if (node.type === 'TSTypeReference') return hole(child(node, 'typeName')?.name)+ return undefined+ }+ const omitted = (node: unknown) =>+ isNode(node) && node.type === 'Property' && hole(child(node, 'value')?.name) === OMIT+ const replacement = (node: SyntaxNode): SyntaxNode | undefined => {+ const value = holeOf(node)+ if (!value || value === OMIT) return undefined+ // `$name: Story` keeps its annotation when the identifier is filled.+ return node.typeAnnotation ? { ...value, typeAnnotation: node.typeAnnotation } : value+ }+ const visit = (node: SyntaxNode): SyntaxNode => {+ const filled = replacement(node)+ if (filled) return structuredClone(filled)+ const copy: SyntaxNode = { ...node }+ for (const [key, value] of Object.entries(node)) {+ if (Array.isArray(value))+ copy[key] = value+ .filter((item) => !omitted(item))+ .map((item) => (isNode(item) ? visit(item) : item))+ else if (isNode(value)) copy[key] = visit(value)+ }+ return copy+ }+ return visit(template) as T+}++export function printModule(program: SyntaxNode): string {+ return print(program, ts(), { indent: ' ' }).code+}++export const identifier = (name: string): SyntaxNode => ({ type: 'Identifier', name })++export const string = (value: string): SyntaxNode => ({ type: 'Literal', value })++const propertyKey = (key: string) =>+ /^[A-Za-z_$][\w$]*$/.test(key) ? identifier(key) : string(key)++export function object(entries: (readonly [string, SyntaxNode])[]): SyntaxNode {+ return {+ type: 'ObjectExpression',+ properties: entries.map(([key, value]) => ({+ type: 'Property',+ kind: 'init',+ key: propertyKey(key),+ value,+ computed: false,+ method: false,+ shorthand: false+ }))+ }+}++export const array = (elements: SyntaxNode[]): SyntaxNode => ({ type: 'ArrayExpression', elements })++export function stringUnionType(values: string[]): SyntaxNode {+ const literals = values.map((value) => ({ type: 'TSLiteralType', literal: string(value) }))+ return literals.length === 1 && literals[0]+ ? literals[0]+ : { type: 'TSUnionType', types: literals }+}++export function objectType(entries: [string, SyntaxNode][]): SyntaxNode {+ return {+ type: 'TSTypeLiteral',+ members: entries.map(([key, typeAnnotation]) => ({+ type: 'TSPropertySignature',+ key: propertyKey(key),+ computed: false,+ typeAnnotation: { type: 'TSTypeAnnotation', typeAnnotation }+ }))+ }+}diff --git a/packages/dom-css/src/storybook/export.ts b/packages/dom-css/src/storybook/export.tsnew file mode 100644index 000000000..c916b6317--- /dev/null+++ b/packages/dom-css/src/storybook/export.ts@@ -0,0 +1,130 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'++import { sceneNodeToDesignDocument } from '../from-scene-graph'+import type { ExportHTMLFile } from '../html-export'+import { serializeHTML } from '../serialize'+import { collectGroups, type StoryGroup } from './groups'+import { printStoryModule, type StoryDesign, type StorybookFramework } from './module'+import { claimName, identifierName, storyId } from './names'++export { STORYBOOK_FRAMEWORKS, type StorybookFramework } from './module'++export interface ExportStorybookOptions {+ framework?: StorybookFramework+ /** Limit the export to one page. Defaults to every page. */+ pageId?: string+ /** Repository-relative `.fig`/`.pen` path; adds an `openpencil://` design link to stories. */+ linkPath?: string+ /** Renders a variant to PNG; each story then shows it next to the link as its design. */+ renderDesignImage?: (nodeId: string) => Promise<Uint8Array>+}++export interface StorybookFile extends ExportHTMLFile {+ /** Name of the page the file was generated from. */+ page: string+}++/** Layers whose name no other layer carries; the link scheme can only address those. */+function uniqueLayerNames(graph: SceneGraph): Set<string> {+ const counts = new Map<string, number>()+ for (const node of graph.getAllNodes()) counts.set(node.name, (counts.get(node.name) ?? 0) + 1)+ return new Set([...counts].filter(([, count]) => count === 1).map(([name]) => name))+}++interface ModuleContext {+ graph: SceneGraph+ framework: StorybookFramework+ linkPath?: string+ uniqueNames: Set<string>+ /** Export name of each story, by variant index. */+ storyNames: string[]+ /** Import path of each variant's design image, by variant index. */+ images: string[]+}++function designLink(context: ModuleContext, ...candidates: (string | undefined)[]): StoryDesign[] {+ const node = candidates.find((name) => name !== undefined && context.uniqueNames.has(name))+ if (!context.linkPath || !node) return []+ const url = `openpencil://open?file=${encodeURIComponent(context.linkPath)}&node=${encodeURIComponent(node)}`+ return [{ type: 'link', url }]+}++/** Story export names, which also name the design images. */+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 claimName(identifierName(text, 'Variant'), taken, { key })+ })+}++function storyLabel(group: StoryGroup, values: string[]): string {+ if (group.props.length === 0) return 'Default'+ return group.props.map((prop, i) => `${prop.name}=${values[i] ?? ''}`).join(', ')+}++function storyModule(group: StoryGroup, context: ModuleContext): string {+ return printStoryModule({+ framework: context.framework,+ title: group.title,+ name: group.name,+ props: group.props,+ variants: group.variants.map((variant) => ({+ values: variant.values,+ html: serializeHTML(sceneNodeToDesignDocument(context.graph, variant.node.id, false))+ })),+ 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 }] : [])+ ]+ }))+ })+}++/**+ * Generate one CSF3 `.stories.ts` file per component or component set, plus a+ * `<Name>.design/` folder of variant images when `renderDesignImage` is given.+ */+export async function exportStorybook(+ graph: SceneGraph,+ options: ExportStorybookOptions = {}+): Promise<StorybookFile[]> {+ const framework = options.framework ?? 'react'+ const uniqueNames = uniqueLayerNames(graph)+ const takenFiles = new Set<string>()+ const takenIds = new Set<string>()+ const files: StorybookFile[] = []+ const add = (page: SceneNode, path: string, content: string | Uint8Array) =>+ files.push({ path, content, page: page.name })++ // Names are claimed on every page, so a one-page export picks the same names as a full one.+ for (const page of graph.getPages()) {+ for (const group of collectGroups(graph, page)) {+ // Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.+ group.title = claimName(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 (options.pageId && page.id !== options.pageId) continue++ const names = storyNames(group)+ const render = options.renderDesignImage+ const images = render ? names.map((name) => `${file}.design/${name}.png`) : []+ if (render) {+ for (const [i, variant] of group.variants.entries())+ add(page, images[i] ?? '', await render(variant.node.id))+ }+ const context = { ...options, graph, framework, uniqueNames, storyNames: names, images }+ add(page, `${file}.stories.ts`, storyModule(group, context))+ }+ }+ return files+}diff --git a/packages/dom-css/src/storybook/groups.ts b/packages/dom-css/src/storybook/groups.tsnew file mode 100644index 000000000..a60f19406--- /dev/null+++ b/packages/dom-css/src/storybook/groups.ts@@ -0,0 +1,117 @@+import type { SceneGraph, SceneNode } from '@open-pencil/scene-graph'+import { deriveSlashVariantProperties } from '@open-pencil/scene-graph/variant-properties'++import { claimName } from './names'++export interface StoryVariant {+ values: string[]+ node: SceneNode+}++/** One story file: a component set, a standalone component, or slash-named siblings. */+export interface StoryGroup {+ page: SceneNode+ title: string+ name: string+ props: { name: string; options: string[] }[]+ variants: StoryVariant[]+ /** Layer the story file links to, when the group has a layer of its own. */+ linkNode?: string+}++function isExported(node: SceneNode): boolean {+ return node.visible && !node.internalOnly+}++/** Variants whose property values collide are told apart by layer name instead. */+function distinctVariants(group: StoryGroup): StoryGroup {+ const keys = group.variants.map((variant) => JSON.stringify(variant.values))+ if (new Set(keys).size === keys.length) return group+ const taken = new Set<string>()+ return {+ ...group,+ variants: group.variants.map((variant) => ({+ ...variant,+ values: [claimName(variant.node.name, taken, { separator: ' ' })]+ })),+ props: [{ name: 'Variant', options: [...taken] }]+ }+}++function componentSetGroup(graph: SceneGraph, page: SceneNode, set: SceneNode): StoryGroup {+ const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')+ const variants = graph+ .getChildren(set.id)+ .filter((child) => child.type === 'COMPONENT' && isExported(child))+ .map((component) => ({+ values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),+ node: component+ }))+ const props = definitions.map((def, index) => ({+ name: def.name,+ options: [+ ...new Set([...(def.variantOptions ?? []), ...variants.map((v) => v.values[index] ?? '')])+ ]+ }))+ return distinctVariants({+ page,+ title: `${page.name}/${set.name}`,+ name: set.name,+ props,+ variants,+ linkNode: set.name+ })+}++function componentGroup(page: SceneNode, component: SceneNode): StoryGroup {+ return {+ page,+ title: `${page.name}/${component.name}`,+ name: component.name,+ props: [],+ variants: [{ values: [], node: component }],+ linkNode: component.name+ }+}++/** `Button/Primary`, `Button/Secondary` → one `Button` group with a derived variant property. */+function slashGroups(page: SceneNode, prefix: string, components: SceneNode[]): StoryGroup[] {+ const derived = deriveSlashVariantProperties(components, () => '')+ if (!derived) return components.map((component) => componentGroup(page, component))+ const props = derived.definitions.map((def) => ({+ name: def.name,+ options: def.variantOptions ?? []+ }))+ const variants = components.map((component) => {+ const values = derived.variants.get(component.id)?.componentPropertyValues ?? {}+ return { values: props.map((prop) => values[prop.name] ?? ''), node: component }+ })+ return [+ distinctVariants({ page, title: `${page.name}/${prefix}`, name: prefix, props, variants })+ ]+}++/** The story files a page produces, in layer order. Instances are never exported. */+export function collectGroups(graph: SceneGraph, page: SceneNode): StoryGroup[] {+ const groups: StoryGroup[] = []+ const slashed = new Map<string, SceneNode[]>()+ const visit = (node: SceneNode) => {+ if (!isExported(node) || node.type === 'INSTANCE') return+ if (node.type === 'COMPONENT_SET') {+ const group = componentSetGroup(graph, page, node)+ if (group.variants.length > 0) groups.push(group)+ return+ }+ if (node.type === 'COMPONENT') {+ const [prefix, ...rest] = node.name.split('/')+ const name = prefix.trim()+ if (rest.length === 0 || !name) groups.push(componentGroup(page, node))+ else slashed.set(name, [...(slashed.get(name) ?? []), node])+ return+ }+ for (const child of graph.getChildren(node.id)) visit(child)+ }+ for (const child of graph.getChildren(page.id)) visit(child)+ for (const [prefix, components] of slashed) groups.push(...slashGroups(page, prefix, components))+ return groups+}diff --git a/packages/dom-css/src/storybook/module.ts b/packages/dom-css/src/storybook/module.tsnew file mode 100644index 000000000..6c99af90b--- /dev/null+++ b/packages/dom-css/src/storybook/module.ts@@ -0,0 +1,166 @@+import dedent from 'dedent'++import * as es from './estree'++export const STORYBOOK_FRAMEWORKS = ['react', 'vue', 'html'] as const+export type StorybookFramework = (typeof STORYBOOK_FRAMEWORKS)[number]++/** Tells readers the file is generated; nothing parses it. */+const HEADER = '// Generated by OpenPencil. Re-export to update; edits are overwritten.'++/** Everything a story module varies by; the TypeScript around it is a fixed template. */+export interface StoryModuleData {+ framework: StorybookFramework+ title: string+ /** Group name used in the missing-variant error. */+ name: string+ props: { name: string; options: string[] }[]+ variants: { values: string[]; html: string }[]+ metaDesign: StoryDesign[]+ /** Import path of each design image, by variant index. */+ images: string[]+ stories: { exportName: string; label: string; values: string[]; design: StoryDesign[] }[]+}++export type StoryDesign =+ | { type: 'link'; url: string }+ /** Refers to the design image of the variant with this index. */+ | { type: 'image'; variant: number }++const MODULE = es.parseModule(dedent`+ import type { Meta, StoryObj } from '$storybook'++ type Args = $Args++ const variants: Record<string, string> = $variants++ function variantHTML(args: Args): string {+ const key = JSON.stringify($key)+ const html = variants[key]+ if (html === undefined) throw new Error($missing + key)+ return html+ }++ const meta = {+ title: $title,+ parameters: $parameters,+ args: $args,+ argTypes: $argTypes,+ render: (args) => $render+ } satisfies Meta<Args>++ export default meta+ type Story = StoryObj<Args>+`)++const IMAGE = es.parseModule(`const $name = new URL($path, import.meta.url).href`)+const STORY = es.parseModule(`export const $name: Story = $story`)++const FRAMEWORKS: Record<+ StorybookFramework,+ { storybook: string; imports: es.SyntaxNode[]; render: es.SyntaxNode }+> = {+ react: {+ storybook: '@storybook/react-vite',+ imports: es.parseModule(`import { createElement } from 'react'`).body,+ render: es.parseExpression(+ `createElement('div', { dangerouslySetInnerHTML: { __html: variantHTML(args) } })`+ )+ },+ vue: {+ storybook: '@storybook/vue3-vite',+ imports: es.parseModule(`import { h } from 'vue'`).body,+ render: es.parseExpression(`{ setup: () => () => h('div', { innerHTML: variantHTML(args) }) }`)+ },+ html: {+ storybook: '@storybook/html-vite',+ imports: [],+ render: es.parseExpression('variantHTML(args)')+ }+}++const imageName = (variant: number) => `design${variant}`++function argsObject(data: StoryModuleData, values: string[]): es.SyntaxNode {+ return es.object(data.props.map((prop, i) => [prop.name, es.string(values[i] ?? '')]))+}++function parameters(design: StoryDesign[]): es.SyntaxNode {+ const entries = design.map((entry) =>+ entry.type === 'link'+ ? es.object([+ ['name', es.string('OpenPencil')],+ ['type', es.string('link')],+ ['url', es.string(entry.url)]+ ])+ : es.object([+ ['name', es.string('Design')],+ ['type', es.string('image')],+ ['url', es.identifier(imageName(entry.variant))]+ ])+ )+ return es.object([['design', es.array(entries)]])+}++const NO_ARGS = es.parseType('Record<string, never>')++function argsType(data: StoryModuleData): es.SyntaxNode {+ if (data.props.length === 0) return NO_ARGS+ return es.objectType(data.props.map((prop) => [prop.name, es.stringUnionType(prop.options)]))+}++/** Print a CSF3 story module for one component or component set. */+export function printStoryModule(data: StoryModuleData): string {+ const framework = FRAMEWORKS[data.framework]+ const [storybookImport, ...body] = es.fill(MODULE, {+ $storybook: es.string(framework.storybook),+ $Args: argsType(data),+ $variants: es.object(+ data.variants.map((variant) => [JSON.stringify(variant.values), es.string(variant.html)])+ ),+ $key: es.array(+ data.props.map((prop) => ({+ type: 'MemberExpression',+ object: es.identifier('args'),+ property: es.string(prop.name),+ computed: true,+ optional: false+ }))+ ),+ $missing: es.string(`${data.name} has no variant `),+ $title: es.string(data.title),+ $parameters: data.metaDesign.length > 0 ? parameters(data.metaDesign) : es.OMIT,+ $args: argsObject(data, data.variants[0]?.values ?? []),+ $argTypes: es.object(+ data.props.map((prop) => [+ prop.name,+ es.object([+ ['control', es.string('select')],+ ['options', es.array(prop.options.map(es.string))]+ ])+ ])+ ),+ $render: framework.render+ }).body+ const images = data.images.flatMap(+ (path, i) =>+ es.fill(IMAGE, { $name: es.identifier(imageName(i)), $path: es.string(`./${path}`) }).body+ )+ const stories = data.stories.flatMap(+ (story) =>+ es.fill(STORY, {+ $name: es.identifier(story.exportName),+ $story: es.object([+ ['name', es.string(story.label)],+ ...(story.design.length > 0 ? [['parameters', parameters(story.design)] as const] : []),+ ['args', argsObject(data, story.values)]+ ])+ }).body+ )+ const module = es.printModule({+ type: 'Program',+ sourceType: 'module',+ body: [storybookImport, ...framework.imports, ...images, ...body, ...stories]+ })+ return `${HEADER}\n${module}\n`+}diff --git a/packages/dom-css/src/storybook/names.ts b/packages/dom-css/src/storybook/names.tsnew file mode 100644index 000000000..751f593c5--- /dev/null+++ b/packages/dom-css/src/storybook/names.ts@@ -0,0 +1,39 @@+import { pascalCase } from 'es-toolkit/string'++/**+ * Claim `base`, or the first free `base<separator><n>` from 2 on. `key` decides which+ * names collide, e.g. ignoring case for file names on case-insensitive file systems.+ */+export function claimName(+ base: string,+ taken: Set<string>,+ { separator = '', key = (name: string) => name } = {}+): string {+ let name = base+ for (let n = 2; taken.has(key(name)); n++) name = `${base}${separator}${n}`+ taken.add(key(name))+ return name+}++const NOT_IDENTIFIER_PART = /[^\p{ID_Continue}]/gu+const IDENTIFIER_START = /^\p{ID_Start}/u++/** A PascalCase JavaScript identifier for `text`, prefixed with `fallback` when it cannot start one. */+export function identifierName(text: string, fallback: string): string {+ const name = pascalCase(text).replace(NOT_IDENTIFIER_PART, '')+ return IDENTIFIER_START.test(name) ? name : `${fallback}${name}`+}++/**+ * Storybook's `sanitize` from `src/csf/csf-utils.ts`, which turns titles into story ids.+ * It is only exported from `storybook/internal/csf`, so it is copied here; a test keeps+ * the copy equal to the installed Storybook.+ */+export function storyId(title: string): string {+ return title+ .toLowerCase()+ .replace(/[ ’–—―′¿'`~!@#$%^&*()_|+\-=?;:'",.<>{}[\]\\/]/gi, '-')+ .replace(/-+/g, '-')+ .replace(/^-+/, '')+ .replace(/-+$/, '')+}diff --git a/packages/dom-css/tests/storybook/export.test.ts b/packages/dom-css/tests/storybook/export.test.tsnew file mode 100644index 000000000..fede493e4--- /dev/null+++ b/packages/dom-css/tests/storybook/export.test.ts@@ -0,0 +1,214 @@+import { describe, expect, it } from 'bun:test'+import { mkdtemp, writeFile } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { exportStorybook } from '#dom-css/index'++import { SceneGraph } from '@open-pencil/scene-graph'++function buttonGraph() {+ const graph = new SceneGraph()+ const page = graph.addPage('Library')+ const set = graph.createNode('COMPONENT_SET', page.id, {+ name: 'Button',+ componentPropertyDefinitions: [+ {+ id: 'size',+ name: 'Size',+ type: 'VARIANT',+ defaultValue: 'Small',+ variantOptions: ['Small', 'Large']+ }+ ]+ })+ for (const [size, width] of [+ ['Small', 80],+ ['Large', 160]+ ] as const) {+ const variant = graph.createNode('COMPONENT', set.id, {+ name: `Size=${size}`,+ width,+ height: 40,+ componentPropertyValues: { Size: size }+ })+ graph.createNode('TEXT', variant.id, { name: 'Label', text: `<b>${size}</b>` })+ }+ return { graph, page }+}++interface Story {+ name: string+ args: Record<string, string>+ parameters?: { design: { name: string; type: string; url: string }[] }+}++interface StoryModule {+ default: {+ title: string+ args: Record<string, string>+ argTypes: Record<string, unknown>+ render: (args: object) => string+ }+ [story: string]: unknown+}++function storyExport(module: StoryModule, name: string): Story {+ return module[name] as Story+}++async function importStory(content: string): Promise<StoryModule> {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-'))+ const path = join(dir, 'story.ts')+ await writeFile(path, content)+ return import(path)+}++describe('exportStorybook', () => {+ it('turns a component set into a story per variant with select controls', async () => {+ const { graph } = buttonGraph()+ const files = await exportStorybook(graph, { framework: 'html', linkPath: 'design/ui kit.fig' })++ expect(files.map((file) => file.path)).toEqual(['Button.stories.ts'])+ const content = String(files[0]?.content)+ expect(content).toContain('openpencil://open?file=design%2Fui%20kit.fig&node=Button')+ // Variant layers named `Size=Small` are unique here, so each story links to its own.+ expect(content).toContain('openpencil://open?file=design%2Fui%20kit.fig&node=Size%3DLarge')++ const story = await importStory(content)+ expect(story.default.title).toBe('Library/Button')+ expect(story.default.argTypes).toEqual({+ Size: { control: 'select', options: ['Small', 'Large'] }+ })+ expect(story.default.args).toEqual({ Size: 'Small' })+ expect(content.indexOf('export const Small')).toBeLessThan(+ content.indexOf('export const Large')+ )+ expect(story.Large).toMatchObject({ name: 'Size=Large', args: { Size: 'Large' } })++ const large = story.default.render({ Size: 'Large' })+ expect(large).toContain('width: 160px')+ expect(large).toContain('<b>Large</b>')+ expect(() => story.default.render({ Size: 'Huge' })).toThrow('Button has no variant ["Huge"]')+ })++ it('groups slash-named components and keeps standalone ones apart', async () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Icons')+ graph.createNode('COMPONENT', page.id, { name: 'Icon/Arrow', width: 16, height: 16 })+ graph.createNode('COMPONENT', page.id, { name: 'Icon/Check', width: 24, height: 24 })+ graph.createNode('COMPONENT', page.id, { name: 'Badge', width: 32, height: 16 })++ const files = await exportStorybook(graph, { framework: 'html', pageId: page.id })+ expect(files.map((file) => file.path)).toEqual(['Badge.stories.ts', 'Icon.stories.ts'])++ const icon = await importStory(String(files[1]?.content))+ expect(icon.default.title).toBe('Icons/Icon')+ expect(icon.default.render({ Variant: 'Check' })).toContain('width: 24px')+ const badge = await importStory(String(files[0]?.content))+ expect(badge.default.render({})).toContain('width: 32px')+ })++ it('keys variants by layer name when their property values collide', async () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Library')+ const set = graph.createNode('COMPONENT_SET', page.id, { name: 'Chip' })+ graph.createNode('COMPONENT', set.id, { name: 'Chip', width: 40, height: 20 })+ graph.createNode('COMPONENT', set.id, { name: 'Chip', width: 60, height: 20 })++ const story = await importStory(+ String((await exportStorybook(graph, { framework: 'html' }))[0]?.content)+ )+ expect(story.default.args).toEqual({ Variant: 'Chip' })+ expect(story.default.render({ Variant: 'Chip 2' })).toContain('width: 60px')+ })++ it('emits framework-specific render wrappers', async () => {+ const { graph } = buttonGraph()+ const react = String((await exportStorybook(graph, { framework: 'react' }))[0]?.content)+ const vue = String((await exportStorybook(graph, { framework: 'vue' }))[0]?.content)++ expect(react).toContain("from '@storybook/react-vite'")+ expect(react).toContain('dangerouslySetInnerHTML')+ expect(react).not.toContain('openpencil://')+ expect(vue).toContain("from '@storybook/vue3-vite'")+ expect(vue).toContain("h('div', { innerHTML: variantHTML(args) })")+ })++ it('writes a design image per variant and links stories to it', async () => {+ const { graph } = buttonGraph()+ graph.createNode('FRAME', graph.getPages()[0]?.id ?? '', { name: 'Size=Large' })+ const rendered: string[] = []+ const files = await exportStorybook(graph, {+ framework: 'html',+ linkPath: 'ui.pen',+ renderDesignImage: async (nodeId) => {+ rendered.push(nodeId)+ return new Uint8Array([nodeId.length])+ }+ })++ expect(files.map((file) => file.path)).toEqual([+ 'Button.design/Small.png',+ 'Button.design/Large.png',+ 'Button.stories.ts'+ ])+ expect(rendered).toHaveLength(2)+ const story = await importStory(String(files[2]?.content))+ const [link, image] = storyExport(story, 'Large').parameters?.design ?? []+ expect(image).toMatchObject({ name: 'Design', type: 'image' })+ expect(image?.url).toEndWith('/Button.design/Large.png')+ // A second `Size=Large` layer makes that name ambiguous, so the story links to the set.+ expect(link?.url).toEndWith('node=Button')+ })++ it('gives same-named components on a page distinct titles', async () => {+ const graph = new SceneGraph()+ const page = graph.addPage('Library')+ graph.createNode('COMPONENT', page.id, { name: 'Card', width: 10, height: 10 })+ graph.createNode('COMPONENT', page.id, { name: 'Card', width: 20, height: 10 })++ const files = await exportStorybook(graph, { framework: 'html' })+ expect(files.map((file) => file.path)).toEqual(['Card.stories.ts', 'Card2.stories.ts'])+ expect((await importStory(String(files[1]?.content))).default.title).toBe('Library/Card 2')++ // Storybook ids ignore case, so `library/Card` would collide with `Library/Card`.+ const lower = graph.addPage('library')+ graph.createNode('COMPONENT', lower.id, { name: 'Card', width: 5, height: 5 })+ const withLower = await exportStorybook(graph, { framework: 'html' })+ expect((await importStory(String(withLower[2]?.content))).default.title).toBe('library/Card 3')++ // A one-page export names its files as the full export does.+ const other = graph.addPage('Other')+ graph.createNode('COMPONENT', other.id, { name: 'Card', width: 30, height: 10 })+ const pageFiles = await exportStorybook(graph, { framework: 'html', pageId: other.id })+ expect(pageFiles.map((file) => file.path)).toEqual(['Card4.stories.ts'])+ })++ it('tags every file with the page it was generated from', async () => {+ const { graph } = buttonGraph()+ graph.createNode('COMPONENT', graph.addPage('Icons').id, { name: 'Star', width: 8, height: 8 })++ const files = await exportStorybook(graph, { framework: 'html' })+ expect(files.map(({ path, page }) => [path, page])).toEqual([+ ['Button.stories.ts', 'Library'],+ ['Star.stories.ts', 'Icons']+ ])+ expect(String(files[0]?.content).split('\n', 1)).toEqual([+ '// Generated by OpenPencil. Re-export to update; edits are overwritten.'+ ])+ })++ it('omits the link when neither the variant nor its set has a unique name', async () => {+ const { graph } = buttonGraph()+ const other = graph.addPage('Other')+ graph.createNode('FRAME', other.id, { name: 'Button' })+ graph.createNode('FRAME', other.id, { name: 'Size=Small' })++ const [story] = await exportStorybook(graph, { framework: 'html', linkPath: 'ui.fig' })+ const content = String(story?.content)+ expect(content).toContain('node=Size%3DLarge')+ expect(content).not.toContain('node=Button')+ expect(content).not.toContain('node=Size%3DSmall')+ })+})diff --git a/packages/dom-css/tests/storybook/names.test.ts b/packages/dom-css/tests/storybook/names.test.tsnew file mode 100644index 000000000..ffb08eb2a--- /dev/null+++ b/packages/dom-css/tests/storybook/names.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from 'bun:test'++import { claimName, identifierName, storyId } from '#dom-css/storybook/names'+import { sanitize } from 'storybook/internal/csf'++describe('storyId', () => {+ it('matches the installed Storybook', () => {+ for (const title of [+ 'Library/Card',+ 'library/card',+ 'Library/Card 2',+ 'Lib `x` "q"/Button\'s "set"',+ 'Größe/Knopf',+ 'A§B',+ 'A-B',+ 'Emoji 🙂/Face',+ '—/?'+ ])+ expect(storyId(title)).toBe(sanitize(title))+ })+})++describe('identifierName', () => {+ it('builds PascalCase identifiers from layer and variant names', () => {+ expect(identifierName('Size=Small, Kind=a"b', 'Variant')).toBe('SizeSmallKindAB')+ expect(identifierName('Größe', 'Variant')).toBe('Größe')+ expect(identifierName('Kind=🙂 smile', 'Variant')).toBe('KindSmile')+ expect(identifierName('2xl', 'Variant')).toBe('Variant2Xl')+ expect(identifierName('🙂', 'Variant')).toBe('Variant')+ })+})++describe('claimName', () => {+ it('numbers names that are already taken under the given key', () => {+ const taken = new Set<string>()+ const key = (name: string) => name.toLowerCase()+ expect(['Card', 'card', 'CARD'].map((name) => claimName(name, taken, { key }))).toEqual([+ 'Card',+ 'card2',+ 'CARD3'+ ])+ expect(claimName('Chip', new Set(['Chip']), { separator: ' ' })).toBe('Chip 2')+ })+})diff --git a/packages/pen/src/read.ts b/packages/pen/src/read.tsindex e5a353353..c869d6989 100644--- a/packages/pen/src/read.ts+++ b/packages/pen/src/read.ts@@ -126,7 +126,7 @@ function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {function resolveSizing(pen: PenNode, ctx: VarContext) {const isTextLike = pen.type === 'text' || pen.type === 'icon_font'const defaultSize = isTextLike ? 20 : 100- const defaultW = isTextLike && pen.width === undefined ? 10_000 : defaultSize+ const defaultW = isTextLike && pen.width === undefined ? 0 : defaultSizeconst w = parseSize(pen.width, defaultW, ctx)const h = parseSize(pen.height, defaultSize, ctx)const layout = mapLayoutMode(pen)@@ -258,8 +258,11 @@ function createSceneNode(applyTextProps(node, pen, ctx)if (parentLayout === 'NONE' && pen.width === undefined && !pen.textGrowth) {node.textAutoResize = 'NONE'- node.width = node.text.length * node.fontSize * 0.65+ node.width = estimateTextWidth(node)node.height = node.fontSize * (node.lineHeight ? node.lineHeight / node.fontSize : 1.2)+ } else if (pen.width === undefined) {+ // Headless layout keeps stored sizes, so an omitted width starts from the content.+ node.width = estimateTextWidth(node)}}@@ -475,12 +478,8 @@ function fixInstanceWidths(graph: SceneGraph): void {}}-function fixTextWidths(graph: SceneGraph): void {- for (const node of graph.getAllNodes()) {- if (node.type !== 'TEXT' || !node.text || node.text.length <= 1) continue- if (node.width >= node.fontSize * 2) continue- node.width = node.text.length * node.fontSize * 0.65- }+function estimateTextWidth(node: SceneNode): number {+ return node.text.length * node.fontSize * 0.65}export function parsePenFile(json: string): SceneGraph {@@ -508,7 +507,6 @@ export function parsePenFile(json: string): SceneGraph {populateInstances(graph)resolveThemeVariables(doc.children, graph, ctx)fixInstanceWidths(graph)- fixTextWidths(graph)if (graph.getPages(true).length === 0) {graph.addPage('Page 1')diff --git a/skills/open-pencil/SKILL.md b/skills/open-pencil/SKILL.mdindex 42f539dcc..0e1978ac0 100644--- a/skills/open-pencil/SKILL.md+++ b/skills/open-pencil/SKILL.md@@ -105,6 +105,7 @@ openpencil export design.fig -f pdf -o page.pdfopenpencil export design.fig -f fig -o roundtrip.figopenpencil export design.fig -f jsx -o component.jsxopenpencil export design.fig -f jsx --style tailwind -o component.tsx+openpencil export design.pen -f storybook -o src/stories --watch # stories + design images per component, re-exported on saveopenpencil export design.fig --thumbnail --width 1920 --height 1080openpencil export --page "Components" -o components.pngdiff --git a/src/app/document/io/deep-link.ts b/src/app/document/io/deep-link.tsindex 8f9f7e2fa..cb1ea1060 100644--- a/src/app/document/io/deep-link.ts+++ b/src/app/document/io/deep-link.ts@@ -21,7 +21,7 @@ export interface DeepLinkActions {/** Absolute paths of the documents currently open in tabs. */openPaths: () => string[]/** Selects the node and zooms to it. False when no node carries that name. */- selectByName: (name: string) => boolean+ selectByName: (name: string) => boolean | Promise<boolean>notify: (message: string) => void}@@ -30,6 +30,21 @@ export function clamp(value: string): string {return value.length > 120 ? `${value.slice(0, 119)}…` : value}+/**+ * Runs a link's layer search. Searching can load other pages after the file opened, so a+ * failure is reported as an error rather than as a layer the document does not carry.+ */+export async function searchLinkedNode(+ selectByName: (name: string) => boolean | Promise<boolean>,+ name: string+): Promise<{ found: boolean } | { error: string }> {+ try {+ return { found: await selectByName(name) }+ } catch (error) {+ return { error: clamp(error instanceof Error ? error.message : String(error)) }+ }+}+/*** Whether `candidate` ends with `relative` as whole path segments, decided by the* `path_matches_suffix` Tauri command: it canonicalizes the candidate and compares@@ -99,9 +114,11 @@ export async function openDeepLink(}await io.openPath(picked)}- if (target.node && !actions.selectByName(target.node)) {+ if (!target.node) return+ const search = await searchLinkedNode(actions.selectByName, target.node)+ if ('error' in search) actions.notify(messages.operationFailed(search))+ else if (!search.found)actions.notify(messages.deepLinkNodeNotFound({ node: clamp(target.node), file: clamp(target.path) }))- }}diff --git a/src/app/document/io/web-link.ts b/src/app/document/io/web-link.tsindex cd16a2097..03cc23e60 100644--- a/src/app/document/io/web-link.ts+++ b/src/app/document/io/web-link.ts@@ -5,7 +5,7 @@// redirect. Nothing else is reachable: no `http:`, no `file:`, no other extension.import { omit } from 'es-toolkit'-import { clamp } from '@/app/document/io/deep-link'+import { clamp, searchLinkedNode } from '@/app/document/io/deep-link'import { notificationMessages } from '@/app/i18n/notifications'import { openBrowserFileFromURL } from '@/app/shell/menu/files'@@ -16,7 +16,7 @@ export interface WebOpenParams {export interface WebLinkActions {/** Selects the node and zooms to it. False when no node carries that name. */- selectByName: (name: string) => boolean+ selectByName: (name: string) => boolean | Promise<boolean>notify: (message: string, level: 'info' | 'error') => void}@@ -76,12 +76,14 @@ export async function openWebLink()return}- if (target.node && !actions.selectByName(target.node)) {+ if (!target.node) return+ const search = await searchLinkedNode(actions.selectByName, target.node)+ if ('error' in search) actions.notify(messages.operationFailed(search), 'error')+ else if (!search.found)actions.notify(messages.deepLinkNodeNotFound({ node: clamp(target.node), file: clamp(target.file.host) }),'info')- }}/**diff --git a/src/app/editor/selection/focus.ts b/src/app/editor/selection/focus.tsindex c6372b613..8c6bf46e2 100644--- a/src/app/editor/selection/focus.ts+++ b/src/app/editor/selection/focus.ts@@ -2,10 +2,14 @@ import type { SceneGraph } from '@open-pencil/scene-graph'/** What focusing needs from the editor, so a caller can drive it without a whole store. */export interface FocusStore {- graph: Pick<SceneGraph, 'getChildren' | 'getNode'>+ graph: Pick<SceneGraph, 'getChildren' | 'getNode' | 'getPages'>state: { currentPageId: string }select: (ids: string[]) => voidzoomToSelection: () => void+ /** Loads a page's layers without showing it; imported pages load them on first visit. */+ loadPageNodes: (pageId: string) => Promise<void>+ switchPage: (pageId: string) => Promise<void>+ pageSwitchCount: () => number}/**@@ -42,7 +46,34 @@ export function focusNodes(store: FocusStore, ids: readonly string[]): boolean {return true}-/** Focuses every node with that exact name on the current page. */-export function focusNodesByName(store: FocusStore, name: string): boolean {- return focusNodes(store, findNodesByName(store.graph, store.state.currentPageId, name))+/** `superseded` when the user switched pages while other pages were being searched. */+export type FocusByNameResult = 'found' | 'missing' | 'superseded'++/**+ * Focuses every node with that exact name on the current page, or else on the first+ * other page that carries it, switching to that page. Other pages are loaded without+ * being shown, so a miss leaves the view where it was, and a page switch the user starts+ * meanwhile wins over the search.+ */+export async function focusNodesByName(+ store: FocusStore,+ name: string+): Promise<FocusByNameResult> {+ const startPageId = store.state.currentPageId+ const here = findNodesByName(store.graph, startPageId, name)+ if (here.length > 0) return focusNodes(store, here) ? 'found' : 'missing'+ const switches = store.pageSwitchCount()+ for (const page of store.graph.getPages()) {+ if (page.id === startPageId) continue+ await store.loadPageNodes(page.id)+ if (store.pageSwitchCount() !== switches) return 'superseded'+ const ids = findNodesByName(store.graph, page.id, name)+ if (ids.length === 0) continue+ await store.switchPage(page.id)+ // A switch the user started meanwhile can keep this one from committing.+ if (store.pageSwitchCount() !== switches + 1 || store.state.currentPageId !== page.id)+ return 'superseded'+ return focusNodes(store, ids) ? 'found' : 'missing'+ }+ return 'missing'}diff --git a/src/views/WorkspaceView.vue b/src/views/WorkspaceView.vueindex 4c944f2a6..04b15a951 100644--- a/src/views/WorkspaceView.vue+++ b/src/views/WorkspaceView.vue@@ -108,8 +108,9 @@ function stripWebLinkParams(): void {}/** The action both link handlers take; see `focusNodesByName`. */-function selectNodeByName(name: string): boolean {- return focusNodesByName(getActiveStore(), name)+async function selectNodeByName(name: string): Promise<boolean> {+ // A search the user overtook by switching pages is not a missing layer.+ return (await focusNodesByName(getActiveStore(), name)) !== 'missing'}async function openPendingAssociatedFiles(): Promise<void> {diff --git a/tests/engine/app/document/io/deep-link.test.ts b/tests/engine/app/document/io/deep-link.test.tsindex 511fbea9e..b4a36d971 100644--- a/tests/engine/app/document/io/deep-link.test.ts+++ b/tests/engine/app/document/io/deep-link.test.ts@@ -163,6 +163,25 @@ describe('openDeepLink', () => {expect(notices[0]).toContain('Nope')})+ test('reports a failed layer search as an error, not a missing layer', async () => {+ const notices: string[] = []++ await openDeepLink(+ { path: 'web/design/hikyo.pen', node: 'Button' },+ {+ openPaths: () => ['/r/hikyo/web/design/hikyo.pen'],+ selectByName: async () => {+ throw new Error('page failed to load')+ },+ notify: (message) => notices.push(message)+ },+ io()+ )++ expect(notices).toHaveLength(1)+ expect(notices[0]).toContain('page failed to load')+ })+test('reports a dismissed picker as nothing chosen, not a wrong file', async () => {const deps = io({ choosePaths: mock(async () => []) })const notices: string[] = []diff --git a/tests/engine/app/document/io/web-link.test.ts b/tests/engine/app/document/io/web-link.test.tsindex 53863f618..a101c5cd5 100644--- a/tests/engine/app/document/io/web-link.test.ts+++ b/tests/engine/app/document/io/web-link.test.ts@@ -113,6 +113,26 @@ describe('openWebLink', () => {expect(notices[0]).toContain('raw.githubusercontent.com')})+ test('reports a failed layer search as an error, not a missing layer', async () => {+ const open = mock(async (): Promise<void> => undefined)+ const notices: [string, string][] = []++ await openWebLink(+ target,+ {+ selectByName: async () => {+ throw new Error('page failed to load')+ },+ notify: (m, level) => notices.push([m, level])+ },+ { open }+ )++ expect(notices).toHaveLength(1)+ expect(notices[0]?.[0]).toContain('page failed to load')+ expect(notices[0]?.[1]).toBe('error')+ })+test('notifies when the node is missing', async () => {const open = mock(async (): Promise<void> => undefined)const notices: string[] = []diff --git a/tests/engine/app/editor/selection/focus.test.ts b/tests/engine/app/editor/selection/focus.test.tsindex fe2843557..033ed7e0a 100644--- a/tests/engine/app/editor/selection/focus.test.ts+++ b/tests/engine/app/editor/selection/focus.test.ts@@ -13,18 +13,27 @@ function harness() {const graph = makeSceneGraph()const pageId = firstPageId(graph)const selected: string[][] = []+ const prepared: string[] = []let zooms = 0+ let switches = 0const store: FocusStore = {graph,state: { currentPageId: pageId },select: (ids) => void selected.push(ids),- zoomToSelection: () => void zooms+++ zoomToSelection: () => void zooms++,+ loadPageNodes: async (id) => void prepared.push(id),+ switchPage: async (id) => {+ switches+++ store.state.currentPageId = id+ },+ pageSwitchCount: () => switches}return {graph,pageId,store,selected,+ prepared,get zooms() {return zooms}@@ -51,21 +60,74 @@ test('walks nested groups rather than only the first level', () => {expect(findNodesByName(graph, pageId, 'Deep')).toEqual([leaf.id])})-test('focuses every match by name and zooms once', () => {+test('focuses every match by name and zooms once', async () => {const { graph, pageId, store, selected } = harness()const frame = graph.createNode('FRAME', pageId, { name: 'Card' })const first = graph.createNode('RECTANGLE', frame.id, { name: 'Button' })const second = graph.createNode('RECTANGLE', frame.id, { name: 'Button' })- expect(focusNodesByName(store, 'Button')).toBe(true)+ expect(await focusNodesByName(store, 'Button')).toBe('found')expect(selected).toEqual([[first.id, second.id]])})-test('does nothing for a name the page does not carry', () => {- const { store, selected } = harness()+test('prefers the current page and otherwise switches to the first page carrying the name', async () => {+ const { graph, pageId, store, selected, prepared } = harness()+ const second = graph.addPage('Components')+ const third = graph.addPage('More')+ const here = graph.createNode('RECTANGLE', pageId, { name: 'Shared' })+ graph.createNode('RECTANGLE', second.id, { name: 'Shared' })+ const button = graph.createNode('COMPONENT', third.id, { name: 'Button' })- expect(focusNodesByName(store, 'Missing')).toBe(false)+ expect(await focusNodesByName(store, 'Shared')).toBe('found')+ expect(selected).toEqual([[here.id]])+ expect(prepared).toEqual([])++ expect(await focusNodesByName(store, 'Button')).toBe('found')+ expect(prepared).not.toContain(pageId)+ expect(prepared.slice(-2)).toEqual([second.id, third.id])+ expect(store.state.currentPageId).toBe(third.id)+ expect(selected.at(-1)).toEqual([button.id])+})++test('yields to a page switch the user starts while other pages load', async () => {+ const { graph, pageId, store, selected } = harness()+ const other = graph.addPage('Other')+ const mine = graph.addPage('Mine')+ graph.createNode('COMPONENT', other.id, { name: 'Button' })+ store.loadPageNodes = async () => {+ await store.switchPage(mine.id)+ }++ expect(await focusNodesByName(store, 'Button')).toBe('superseded')+ expect(store.state.currentPageId).toBe(mine.id)+ expect(selected).toEqual([])+ expect(pageId).not.toBe(mine.id)+})++test('does not focus a page while another switch is still pending', async () => {+ const { graph, store, selected } = harness()+ const other = graph.addPage('Other')+ graph.createNode('COMPONENT', other.id, { name: 'Button' })+ // The user's switch starts during the search's own and has not committed yet.+ const { switchPage, pageSwitchCount } = store+ let pending = 0+ store.pageSwitchCount = () => pageSwitchCount() + pending+ store.switchPage = async (id) => {+ await switchPage(id)+ pending+++ }++ expect(await focusNodesByName(store, 'Button')).toBe('superseded')+ expect(store.state.currentPageId).toBe(other.id)+ expect(selected).toEqual([])+})++test('does nothing for a name no page carries', async () => {+ const { pageId, store, selected } = harness()++ expect(await focusNodesByName(store, 'Missing')).toBe('missing')expect(selected).toEqual([])+ expect(store.state.currentPageId).toBe(pageId)})test('ignores ids that are no longer in the document', () => {diff --git a/tests/engine/cli/export-font-policy.test.ts b/tests/engine/cli/export/font-policy.test.tssimilarity index 90%rename from tests/engine/cli/export-font-policy.test.tsrename to tests/engine/cli/export/font-policy.test.tsindex 88af4045c..c22c2dac1 100644--- a/tests/engine/cli/export-font-policy.test.ts+++ b/tests/engine/cli/export/font-policy.test.ts@@ -2,7 +2,11 @@ import { expect, test } from 'bun:test'import { SceneGraph } from '@open-pencil/scene-graph'-import { FONT_POLICIES, applyExportFontPolicy, exportFontRoots } from '#cli/export-font-policy'+import {+ FONT_POLICIES,+ applyExportFontPolicy,+ exportFontRoots+} from '#cli/commands/export/font-policy'function graphWithMissingFont(): { graph: SceneGraph; pageId: string } {const graph = new SceneGraph()diff --git a/tests/engine/cli/export.test.ts b/tests/engine/cli/export/index.test.tssimilarity index 100%rename from tests/engine/cli/export.test.tsrename to tests/engine/cli/export/index.test.tsdiff --git a/tests/engine/cli/export/storybook.test.ts b/tests/engine/cli/export/storybook.test.tsnew file mode 100644index 000000000..c93867ce0--- /dev/null+++ b/tests/engine/cli/export/storybook.test.ts@@ -0,0 +1,359 @@+import { expect, setDefaultTimeout, test } from 'bun:test'+import { mkdir, mkdtemp, readdir, rm, symlink } from 'node:fs/promises'+import { tmpdir } from 'node:os'+import { join } from 'node:path'++import { BUILTIN_IO_FORMATS, IORegistry } from '@open-pencil/core/io'++import { runOpenPencilCLI } from '#tests/helpers/cli'+import { cliSourcePath } from '#tests/helpers/paths'+import { makeSceneGraph } from '#tests/helpers/scene'++setDefaultTimeout(30_000)++const io = new IORegistry(BUILTIN_IO_FORMATS)+const MANIFEST = '.openpencil-stories.json'++/** Entries a user sees in the output folder; the manifest is a dot file. */+async function outputEntries(output: string): Promise<string[]> {+ return (await readdir(output)).filter((entry) => !entry.startsWith('.')).sort()+}++async function writeComponentFixture(dir: string, names: string[], file = 'library.fig') {+ const figPath = join(dir, file)+ const graph = makeSceneGraph()+ const page = graph.addPage('Library')+ for (const name of names) graph.createNode('COMPONENT', page.id, { name, width: 32, height: 16 })+ const result = await io.writeDocument('fig', graph)+ await Bun.write(figPath, result.data as Uint8Array)+ return figPath+}++test('export CLI writes Storybook stories with design images', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = await writeComponentFixture(dir, ['Badge'])+ const output = join(dir, 'stories')++ const { stdout, stderr, exitCode } = await runOpenPencilCLI([+ 'export',+ figPath,+ '--format',+ 'storybook',+ '--framework',+ 'vue',+ '--font-policy',+ 'allow',+ '--output',+ output+ ])++ expect(stderr).toBe('')+ expect(exitCode).toBe(0)+ expect(stdout).toContain('Exported 1 story files')+ const story = await Bun.file(join(output, 'Badge.stories.ts')).text()+ expect(story).toContain("from '@storybook/vue3-vite'")+ expect(story).toContain("title: 'Library/Badge'")+ const manifest: unknown = JSON.parse(await Bun.file(join(output, MANIFEST)).text())+ expect(manifest).toEqual({+ version: 1,+ files: {+ 'Badge.design/Default.png': { source: '../library.fig', page: 'Library' },+ 'Badge.stories.ts': { source: '../library.fig', page: 'Library' }+ }+ })+ const png = new Uint8Array(await Bun.file(join(output, 'Badge.design/Default.png')).arrayBuffer())+ expect(new TextDecoder().decode(png.slice(1, 4))).toBe('PNG')+})++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 setup = await runOpenPencilCLI([+ 'export',+ await writeComponentFixture(dir, ['Old']),+ ...args+ ])+ expect(setup.exitCode).toBe(0)+ await Bun.write(join(output, 'Mine.stories.ts'), 'export default {}\n')++ const { exitCode } = await runOpenPencilCLI([+ 'export',+ await writeComponentFixture(dir, ['New']),+ ...args+ ])++ expect(exitCode).toBe(0)+ expect(await Bun.file(join(output, 'Old.stories.ts')).exists()).toBe(false)+ expect(await Bun.file(join(output, 'New.stories.ts')).exists()).toBe(true)+ expect((await outputEntries(output)).some((entry) => entry.endsWith('.design'))).toBe(false)+ expect(await Bun.file(join(output, 'Mine.stories.ts')).text()).toBe('export default {}\n')+})++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]+ for (const [names, file] of [+ [['Card'], 'library.fig'],+ [['Chip'], 'b.fig']+ ] as const) {+ const setup = await runOpenPencilCLI([+ 'export',+ await writeComponentFixture(dir, [...names], file),+ ...args+ ])+ expect(setup.exitCode).toBe(0)+ }+ expect(await Bun.file(join(output, 'Card.stories.ts')).exists()).toBe(true)+ expect(await Bun.file(join(output, 'Chip.stories.ts')).exists()).toBe(true)++ await Bun.write(join(output, 'Mine.stories.ts'), 'export default {}\n')+ const { stderr, exitCode } = await runOpenPencilCLI([+ 'export',+ await writeComponentFixture(dir, ['Card', 'Mine']),+ ...args+ ])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('Mine.stories.ts was not generated by this export')+ expect(await Bun.file(join(output, 'Mine.stories.ts')).text()).toBe('export default {}\n')+ expect(await Bun.file(join(output, 'Card.stories.ts')).exists()).toBe(true)+})++test('export CLI --page replaces that page and keeps the stories of other pages', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = join(dir, 'library.fig')+ const writeDocument = async (second: string) => {+ const graph = makeSceneGraph()+ graph.createNode('COMPONENT', graph.addPage('One').id, { name: 'Kept', width: 8, height: 8 })+ graph.createNode('COMPONENT', graph.addPage('Two').id, { name: second, width: 8, height: 8 })+ const result = await io.writeDocument('fig', graph)+ await Bun.write(figPath, result.data as Uint8Array)+ }+ const output = join(dir, 'stories')+ const args = ['--format', 'storybook', '--no-design-images', '--output', output]+ await writeDocument('Old')+ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)++ await writeDocument('New')+ const { exitCode } = await runOpenPencilCLI(['export', figPath, '--page', 'Two', ...args])++ expect(exitCode).toBe(0)+ expect(await Bun.file(join(output, 'Kept.stories.ts')).exists()).toBe(true)+ expect(await Bun.file(join(output, 'New.stories.ts')).exists()).toBe(true)+})++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]+ for (const [folder, name] of [+ ['a', 'Card'],+ ['b', 'Chip']+ ]) {+ await mkdir(join(dir, folder))+ const figPath = await writeComponentFixture(join(dir, folder), [name])+ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)+ }++ expect(await Bun.file(join(output, 'Card.stories.ts')).exists()).toBe(true)+ expect(await Bun.file(join(output, 'Chip.stories.ts')).exists()).toBe(true)+})++test('export CLI --page refuses to renumber stories of other pages', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = join(dir, 'library.fig')+ const writeDocument = async (first: string) => {+ const graph = makeSceneGraph()+ graph.createNode('COMPONENT', graph.addPage('One').id, { name: first, width: 8, height: 8 })+ graph.createNode('COMPONENT', graph.addPage('Two').id, { name: 'Card', width: 8, height: 8 })+ const result = await io.writeDocument('fig', graph)+ await Bun.write(figPath, result.data as Uint8Array)+ }+ const output = join(dir, 'stories')+ const args = ['--format', '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'])++ // Renaming page One's Card renumbers page Two's story onto page One's Card.stories.ts.+ await writeDocument('Badge')+ const pageExport = await runOpenPencilCLI(['export', figPath, '--page', 'Two', ...args])+ expect(pageExport.exitCode).toBe(1)+ expect(pageExport.stderr).toContain('holds page One of')+ expect(await outputEntries(output)).toEqual(['Card.stories.ts', 'Card2.stories.ts'])++ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)+ expect(await outputEntries(output)).toEqual(['Badge.stories.ts', 'Card.stories.ts'])+})++test('export CLI refuses to overwrite a design image it did not generate', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = await writeComponentFixture(dir, ['Badge'])+ const output = join(dir, 'stories')+ await mkdir(join(output, 'Badge.design'), { recursive: true })+ await Bun.write(join(output, 'Badge.design/Default.png'), 'mine')++ const { stderr, exitCode } = await runOpenPencilCLI([+ 'export',+ figPath,+ '--format',+ 'storybook',+ '--font-policy',+ 'allow',+ '--output',+ output+ ])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('Default.png was not generated by this export')+ expect(await Bun.file(join(output, 'Badge.design/Default.png')).text()).toBe('mine')+})++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]+ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)+ await Bun.write(join(output, 'Badge.design/notes.txt'), 'mine')++ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)++ expect((await readdir(join(output, 'Badge.design'))).sort()).toEqual(['Default.png', 'notes.txt'])+})++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 badge = await writeComponentFixture(dir, ['Badge'])+ expect((await runOpenPencilCLI(['export', badge, ...args])).exitCode).toBe(0)++ const chip = await writeComponentFixture(dir, ['Chip'])+ expect((await runOpenPencilCLI(['export', chip, ...args])).exitCode).toBe(0)++ expect(await outputEntries(output)).toEqual(['Chip.design', 'Chip.stories.ts'])+})++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]+ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)+ const outside = join(dir, 'outside')+ await mkdir(outside)+ await Bun.write(join(outside, 'Default.png'), 'keep')+ await rm(join(output, 'Badge.design'), { recursive: true })+ await symlink(outside, join(output, 'Badge.design'))++ const { stderr, exitCode } = await runOpenPencilCLI(['export', figPath, ...args])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('Badge.design is not a folder')+ expect(await Bun.file(join(outside, 'Default.png')).text()).toBe('keep')+ expect(await Bun.file(join(output, 'Badge.stories.ts')).exists()).toBe(true)+})++test('export CLI --watch re-exports stories when the document changes', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = await writeComponentFixture(dir, ['First'])+ const output = join(dir, 'stories')+ const proc = Bun.spawn(+ [+ process.execPath,+ cliSourcePath('index.ts'),+ 'export',+ figPath,+ '--format',+ 'storybook',+ '--no-design-images',+ '--watch',+ '--output',+ output+ ],+ { stdout: 'pipe', stderr: 'pipe' }+ )+ try {+ const reader = proc.stdout.getReader()+ let seen = ''+ const waitFor = async (text: string) => {+ while (!seen.includes(text)) {+ const { value, done } = await reader.read()+ if (done) throw new Error(`CLI exited before printing "${text}": ${seen}`)+ seen += new TextDecoder().decode(value)+ }+ }+ await waitFor('Watching')+ await writeComponentFixture(dir, ['Second'])+ const until = Date.now() + 10_000+ while (!(await Bun.file(join(output, 'Second.stories.ts')).exists())) {+ if (Date.now() > until) throw new Error(`No re-export after the change: ${seen}`)+ await Bun.sleep(50)+ }+ expect(await Bun.file(join(output, 'First.stories.ts')).exists()).toBe(false)+ } finally {+ proc.kill()+ }+})++test('export CLI rejects Storybook export of a document without components', async () => {+ const dir = await mkdtemp(join(tmpdir(), 'open-pencil-storybook-cli-'))+ const figPath = await writeComponentFixture(dir, [])++ const { stderr, exitCode } = await runOpenPencilCLI([+ 'export',+ figPath,+ '--format',+ 'storybook',+ '--output',+ join(dir, 'stories')+ ])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('No components found in the document.')+})++test('export CLI refuses a manifest that lists files 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')+ await Bun.write(join(dir, 'outside.png'), 'keep')+ await Bun.write(+ join(output, MANIFEST),+ JSON.stringify({+ version: 1,+ files: { '../outside.png': { source: '../library.fig', page: 'Library' } }+ })+ )++ const { stderr, exitCode } = await runOpenPencilCLI([+ 'export',+ figPath,+ '--format',+ 'storybook',+ '--no-design-images',+ '--output',+ output+ ])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('is not a valid OpenPencil stories manifest')+ expect(await Bun.file(join(dir, 'outside.png')).text()).toBe('keep')+})++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]+ expect((await runOpenPencilCLI(['export', figPath, ...args])).exitCode).toBe(0)+ await rm(join(output, MANIFEST))++ const { stderr, exitCode } = await runOpenPencilCLI(['export', figPath, ...args])++ expect(exitCode).toBe(1)+ expect(stderr).toContain('Badge.stories.ts was not generated by this export')+})diff --git a/tests/engine/editor/pages/loading.test.ts b/tests/engine/editor/pages/loading.test.tsindex de25d7dda..296753f68 100644--- a/tests/engine/editor/pages/loading.test.ts+++ b/tests/engine/editor/pages/loading.test.ts@@ -136,3 +136,32 @@ test('page viewport cleanup remains independent from app preparation state', ()expect(() => editor.clearPageViewports()).not.toThrow()})++test('loading page nodes for a lookup does not supersede a page switch in progress', async () => {+ const graph = new SceneGraph()+ const firstPage = graph.getPages()[0]+ if (!firstPage) throw new Error('Expected default page')+ const target = graph.addPage('Target')+ const searched = graph.addPage('Searched')+ graph.createNode('TEXT', target.id, { text: 'Loading', fontFamily: 'Loader Test' })+ let release: (() => void) | null = null+ const fontReady = new Promise<void>((resolve) => {+ release = resolve+ })+ const editor = createEditor({+ graph,+ skipInitialGraphSetup: true,+ loadFont: async () => {+ await fontReady+ return null+ }+ })++ const switching = editor.switchPage(target.id)+ await Promise.resolve()+ await editor.loadPageNodes(searched.id)+ release?.()+ await switching++ expect(editor.state.currentPageId).toBe(target.id)+})diff --git a/tests/engine/pen/layout.test.ts b/tests/engine/pen/layout.test.tsindex 5b9412387..585cc4af3 100644--- a/tests/engine/pen/layout.test.ts+++ b/tests/engine/pen/layout.test.ts@@ -151,3 +151,88 @@ describe('parseSize — Pen sizing fallbacks (#564)', () => {})})++describe('parsePenFile — text without a width', () => {+ function hugButton(text: PenNode) {+ const graph = parseLayoutDocument([+ { id: 'button', name: 'button', type: 'frame', padding: [12, 24], children: [text] }+ ])+ const nodes = graph.getAllNodes()+ return {+ button: nodes.find((node) => node.type === 'FRAME' && node.name === 'button'),+ label: nodes.find((node) => node.type === 'TEXT')+ }+ }++ test('sizes auto-width text from its content instead of a placeholder', () => {+ const { button, label } = hugButton({+ id: 'label',+ name: 'label',+ type: 'text',+ content: 'Button',+ fontSize: 18+ })++ expect(label?.width).toBeGreaterThan(0)+ expect(label?.width).toBeLessThan(200)+ expect(button?.width).toBeLessThan(250)+ })++ test('gives fixed-width text, even a single glyph, a non-zero width', () => {+ for (const content of ['A', 'Label']) {+ const { label } = hugButton({+ id: 'label',+ name: 'label',+ type: 'text',+ content,+ fontSize: 18,+ textGrowth: 'fixed-width'+ })+ expect(label?.width).toBeGreaterThan(0)+ expect(label?.width).toBeLessThan(200)+ }+ })++ test('keeps empty text without a width at zero', () => {+ const { label } = hugButton({ id: 'label', name: 'label', type: 'text', content: '' })+ expect(label?.width).toBe(0)+ })++ test('keeps an explicit narrow width on multi-character text', () => {+ const graph = parsePenFile(+ JSON.stringify({+ version: '2.17',+ children: [+ {+ id: 'label',+ name: 'label',+ type: 'text',+ content: 'Label',+ width: 0,+ textGrowth: 'fixed-width'+ }+ ]+ } satisfies PenDocument)+ )+ expect(graph.getAllNodes().find((node) => node.type === 'TEXT')?.width).toBe(0)+ })++ test('keeps an explicit zero width', () => {+ const graph = parsePenFile(+ JSON.stringify({+ version: '2.17',+ children: [+ {+ id: 'label',+ name: 'label',+ type: 'text',+ content: 'A',+ width: 0,+ textGrowth: 'fixed-width'+ }+ ]+ } satisfies PenDocument)+ )+ expect(graph.getAllNodes().find((node) => node.type === 'TEXT')?.width).toBe(0)+ })+})