@pairdraw/dom-css 0.17.0 → 0.18.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/chunks/behaviours/states/layers.js +19 -0
- package/dist/chunks/behaviours/states/layers.js.map +1 -1
- package/dist/chunks/browser.js +3 -2
- package/dist/chunks/browser.js.map +1 -1
- package/dist/chunks/export/bundle.js +14 -14
- package/dist/chunks/export/bundle.js.map +1 -1
- package/dist/chunks/export/storybook/export.js +1 -1
- package/dist/chunks/export/storybook/export.js.map +1 -1
- package/dist/export.d.ts +0 -7
- package/package.json +3 -3
- package/src/export/bundle.ts +17 -21
- package/src/export/storybook/export.ts +1 -1
- package/src/import/scene-graph.ts +3 -2
- package/src/tokens/stylesheet.ts +33 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"bundle.js","names":[],"sources":["../../../src/export/bundle.ts"],"sourcesContent":["import type { CSSFontFaceRule } from '@acemir/cssom'\nimport { isValid, toUint8Array } from 'js-base64'\nimport { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { normalizeFontFamily } from '@pairdraw/scene-graph/font-style'\n\nimport { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { mergeClassNames, serializeHTML, splitWhitespace } from './html'\n\n/** A font face the exported text uses. */\nexport interface WebFontFaceRequest {\n family: string\n weight: number\n style?: 'normal' | 'italic'\n}\n\n/** A font file to ship next to the page, described as an `@font-face` rule. */\nexport interface WebFontFaceAsset {\n family: string\n weight: string | number | [number, number]\n style: string\n display?: string\n stretch?: string\n unicodeRange?: string[]\n format: 'woff2' | 'woff' | 'opentype' | 'truetype'\n path: string\n content: Uint8Array\n}\n\n/** Finds font files for the requested faces; paths start with `assetBasePath`. */\nexport type WebFontFaceResolver = (\n fonts: WebFontFaceRequest[],\n assetBasePath: string\n) => Promise<WebFontFaceAsset[]>\n\nexport interface ExportHTMLBundleOptions {\n html?: 'fragment' | 'standalone'\n style?: 'inline' | 'tailwind'\n assets?: 'inline' | 'external'\n /** Resolves font files to include with external assets; `none` includes no fonts. */\n fonts?: 'none' | WebFontFaceResolver\n assetBasePath?: string\n /**\n * Reads one of Tailwind's stylesheets, `tailwindcss/theme.css` or `tailwindcss/utilities.css`,\n * for a standalone Tailwind page. Browsers pass one; Node and Bun read the installed package.\n */\n loadTailwindStylesheet?: TailwindStylesheetLoader\n}\n\nexport type TailwindStylesheetLoader = (id: TailwindStylesheetId) => Promise<string>\nexport type TailwindStylesheetId = 'tailwindcss/theme.css' | 'tailwindcss/utilities.css'\n\nexport interface ExportHTMLFile {\n path: string\n content: string | Uint8Array\n}\n\nexport interface ExportHTMLBundle {\n entrypoint: string\n files: ExportHTMLFile[]\n}\n\ninterface StandaloneBounds {\n minX: number\n minY: number\n width: number\n height: number\n}\n\ntype ParseNode = DefaultTreeAdapterTypes.Node\ntype ParseParent = DefaultTreeAdapterTypes.ParentNode\ntype ParseElement = DefaultTreeAdapterTypes.Element\n\nconst RESET_CSS =\n '*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}'\n\nfunction styleToCSS(style: DesignStyleDeclaration): string {\n return Object.entries(style)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction cloneNode(node: DesignNode): DesignNode {\n if (node.type === 'text') return { ...node }\n return {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined,\n children: node.children.map(cloneNode)\n }\n}\n\nfunction standaloneStyleForNode(\n node: DesignElement,\n parent: DesignElement | undefined,\n origin: StandaloneBounds\n): DesignStyleDeclaration {\n const style = { ...node.inlineStyle }\n const source = node.sourceSceneNode\n if (!source) return style\n\n style.position = 'absolute'\n style.left = `${source.x - (parent ? 0 : origin.minX)}px`\n style.top = `${source.y - (parent ? 0 : origin.minY)}px`\n return style\n}\n\nfunction standaloneNode(\n node: DesignNode,\n origin: StandaloneBounds,\n parent?: DesignElement\n): DesignNode {\n if (node.type === 'text') return cloneNode(node)\n const standalone: DesignElement = {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: standaloneStyleForNode(node, parent, origin),\n children: []\n }\n standalone.children = node.children.map((child) => standaloneNode(child, origin, node))\n return standalone\n}\n\nfunction nodeBounds(node: DesignNode): StandaloneBounds | undefined {\n if (node.type === 'text' || !node.sourceSceneNode) return undefined\n return {\n minX: node.sourceSceneNode.x,\n minY: node.sourceSceneNode.y,\n width: node.sourceSceneNode.width,\n height: node.sourceSceneNode.height\n }\n}\n\nfunction standaloneSize(document: DesignDocument): StandaloneBounds {\n const bounds = document.children\n .map(nodeBounds)\n .filter((value): value is NonNullable<typeof value> => value !== undefined)\n const minX = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minX)) : 0\n const minY = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minY)) : 0\n const maxX = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minX + bound.width)) : 1\n const maxY = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minY + bound.height)) : 1\n return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) }\n}\n\nfunction standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument {\n return {\n ...document,\n children: document.children.map((node) => standaloneNode(node, size))\n }\n}\n\nfunction cssClassName(index: number): string {\n return `op-${index.toString(36)}`\n}\n\nfunction extractInlineStyles(\n node: DesignNode,\n rules: string[],\n nextIndex: { value: number }\n): DesignNode {\n if (node.type === 'text') return node\n const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex))\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children }\n\n const className = cssClassName(nextIndex.value)\n nextIndex.value += 1\n rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`)\n return {\n ...node,\n attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className },\n inlineStyle: undefined,\n children\n }\n}\n\nfunction isElement(node: ParseNode): node is ParseElement {\n return 'attrs' in node && 'tagName' in node\n}\n\nfunction walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void {\n if (isElement(node)) visit(node)\n if ('childNodes' in node) {\n for (const child of node.childNodes) walkParseTree(child, visit)\n }\n}\n\nfunction classNamesFromHTML(html: string): string[] {\n const fragment = parseFragment(html)\n const classes = new Set<string>()\n walkParseTree(fragment, (element) => {\n const classAttr = element.attrs.find((attr) => attr.name === 'class')\n if (!classAttr) return\n for (const className of splitWhitespace(classAttr.value)) classes.add(className)\n })\n return [...classes]\n}\n\n/**\n * The stylesheet for the tokens the document references, in the format the page needs: plain\n * custom properties for inline styles, `@theme` for Tailwind, so token utilities compile.\n */\nasync function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise<string> {\n const { tokens, sourceGraph } = document\n if (!tokens || !sourceGraph || tokens.used.size === 0) return ''\n const variables = tokens.stylesheetVariables()\n const { css } = await tokenStylesheet(sourceGraph, {\n format,\n include: (variable) => variables.has(variable.id)\n })\n return css\n}\n\nasync function readInstalledTailwindStylesheet(id: TailwindStylesheetId): Promise<string> {\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(new URL(import.meta.resolve(id)), 'utf8')\n}\n\nasync function compileTailwindClasses(\n classNames: string[],\n tokens: string,\n load: TailwindStylesheetLoader = readInstalledTailwindStylesheet\n): Promise<string> {\n if (classNames.length === 0) return ''\n const [{ compile }, themeCSS, utilitiesCSS] = await Promise.all([\n import('tailwindcss'),\n load('tailwindcss/theme.css'),\n load('tailwindcss/utilities.css')\n ])\n const compiler = await compile(`${themeCSS}\\n${tokens}\\n${utilitiesCSS}`)\n return compiler.build(classNames)\n}\n\nfunction collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {\n if (node.type === 'text') return\n const source = node.sourceSceneNode\n if (source?.type === 'TEXT') {\n const family = normalizeFontFamily(source.fontFamily)\n const style = source.italic ? 'italic' : 'normal'\n const key = `${family}|${source.fontWeight}|${style}`\n fonts.set(key, { family, weight: source.fontWeight, style })\n }\n for (const child of node.children) collectFontRequests(child, fonts)\n}\n\nfunction serializeFontWeight(weight: string | number | [number, number]): string {\n return Array.isArray(weight) ? weight.join(' ') : String(weight)\n}\n\n/**\n * A relative file path as a URL that points at it: each folder and file name percent-encoded,\n * so a page named `Card #1` finds `Card #1.assets/` rather than reading `#1` as a fragment.\n */\nfunction assetURL(path: string): string {\n return path.split('/').map(encodeURIComponent).join('/')\n}\n\nfunction fontSourceValue(asset: WebFontFaceAsset, from: string): string {\n // Relative to the stylesheet's folder, which the asset's path may start with.\n const path =\n from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path\n return [\n 'url(',\n JSON.stringify(assetURL(path)),\n ') format(',\n JSON.stringify(asset.format),\n ')'\n ].join('')\n}\n\ninterface FontFaceCSSOptions {\n /** The folder the stylesheet is in, which font paths are written relative to. */\n from: string\n /** `font-display` for every face, rather than each face's own. */\n display?: string\n}\n\nfunction fontFaceCSS(\n FontFaceRule: typeof CSSFontFaceRule,\n asset: WebFontFaceAsset,\n options: FontFaceCSSOptions\n): string {\n const rule = new FontFaceRule()\n rule.style.setProperty('font-family', JSON.stringify(asset.family))\n rule.style.setProperty('src', fontSourceValue(asset, options.from))\n rule.style.setProperty('font-weight', serializeFontWeight(asset.weight))\n rule.style.setProperty('font-style', asset.style)\n rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')\n if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)\n if (asset.unicodeRange && asset.unicodeRange.length > 0) {\n rule.style.setProperty('unicode-range', asset.unicodeRange.join(','))\n }\n return rule.cssText\n}\n\n/** Every font face a document's text uses, once each. */\nexport function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {\n const requests = new Map<string, WebFontFaceRequest>()\n for (const child of document.children) collectFontRequests(child, requests)\n return [...requests.values()]\n}\n\n/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */\nexport async function fontFaceStylesheet(\n assets: readonly WebFontFaceAsset[],\n options: FontFaceCSSOptions\n): Promise<string> {\n if (assets.length === 0) return ''\n // Loaded only when fonts ship as files; the CSS object model is not bundled for browsers.\n const cssom = await import('@acemir/cssom')\n return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')\n}\n\nasync function fontFaceAssets(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<{ css: string; files: ExportHTMLFile[] }> {\n if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }\n const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)\n // The page's stylesheet sits in the asset folder, beside the fonts' own folder.\n return {\n css: await fontFaceStylesheet(assets, { from: options.assetBasePath }),\n files: assets\n }\n}\n\nfunction dataImageParts(value: string): { mime: string; base64: string } | undefined {\n if (!value.startsWith('data:image/')) return undefined\n const marker = ';base64,'\n const markerIndex = value.indexOf(marker)\n if (markerIndex === -1) return undefined\n const base64 = value.slice(markerIndex + marker.length)\n // Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.\n if (!isValid(base64)) return undefined\n return { mime: value.slice('data:'.length, markerIndex), base64 }\n}\n\nfunction extensionForMime(mime: string): string {\n if (mime === 'image/jpeg') return 'jpg'\n if (mime === 'image/webp') return 'webp'\n if (mime === 'image/gif') return 'gif'\n if (mime === 'image/svg+xml') return 'svg'\n return 'png'\n}\n\n/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */\nexport function extractImageAssets(\n html: string,\n assetBasePath: string\n): { html: string; files: ExportHTMLFile[] } {\n const fragment = parseFragment(html)\n const files: ExportHTMLFile[] = []\n const sources = new Map<string, string>()\n walkParseTree(fragment, (element) => {\n const src = element.attrs.find((attr) => attr.name === 'src')\n if (!src) return\n const parts = dataImageParts(src.value)\n if (!parts) return\n const cachedPath = sources.get(src.value)\n if (cachedPath) {\n src.value = assetURL(cachedPath)\n return\n }\n const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`\n sources.set(src.value, path)\n files.push({ path, content: toUint8Array(parts.base64) })\n src.value = assetURL(path)\n })\n return { html: serialize(fragment), files }\n}\n\nfunction stylesheetLink(path: string): string {\n return `<link rel=\"stylesheet\" href=\"${assetURL(path)}\">`\n}\n\n/**\n * A `<style>` element holding `css`. The HTML parser ends the element at the first `</style`\n * in any letter case, whatever the CSS around it means, and style values can come from an\n * imported document, so each one is written `<\\/style`, which CSS strings and URLs read back\n * as `</style`.\n */\nfunction styleTag(css: string): string {\n return css ? `<style>${css.replace(/<\\/(?=style)/gi, '<\\\\/')}</style>` : ''\n}\n\ntype ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &\n Pick<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>\n\nasync function exportStandaloneHTML(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<ExportHTMLBundle> {\n const size = standaloneSize(document)\n const doc = standaloneDocument(document, size)\n const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`\n let body: string\n let css = `${RESET_CSS}${stageCSS}`\n\n if (options.style === 'tailwind') {\n body = serializeHTML(doc, { style: 'tailwind' })\n css += await compileTailwindClasses(\n classNamesFromHTML(body),\n await tokenCSS(document, 'tailwind'),\n options.loadTailwindStylesheet\n )\n } else {\n css += await tokenCSS(document, 'css')\n const rules: string[] = []\n const index = { value: 0 }\n const styledDocument: DesignDocument = {\n ...doc,\n children: doc.children.map((node) => extractInlineStyles(node, rules, index))\n }\n body = serializeHTML(styledDocument)\n css += rules.join('')\n }\n\n if (options.assets === 'external') {\n const [extracted, fonts] = await Promise.all([\n Promise.resolve(extractImageAssets(body, options.assetBasePath)),\n fontFaceAssets(document, options)\n ])\n body = extracted.html\n const cssPath = `${options.assetBasePath}/pairdraw.css`\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${stylesheetLink(cssPath)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return {\n entrypoint: 'index.html',\n files: [\n { path: 'index.html', content: html },\n { path: cssPath, content: `${fonts.css}${css}` },\n ...fonts.files,\n ...extracted.files\n ]\n }\n }\n\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${styleTag(css)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] }\n}\n\nexport async function exportHTMLBundle(\n document: DesignDocument,\n options: ExportHTMLBundleOptions = {}\n): Promise<ExportHTMLBundle> {\n const resolvedOptions: ResolvedBundleOptions = {\n html: options.html ?? 'fragment',\n style: options.style ?? 'inline',\n assets: options.assets ?? 'inline',\n fonts: options.fonts ?? 'none',\n assetBasePath: options.assetBasePath ?? 'assets',\n loadTailwindStylesheet: options.loadTailwindStylesheet\n }\n\n if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions)\n\n const fragment = serializeHTML(document, { style: resolvedOptions.style })\n if (resolvedOptions.assets !== 'external') {\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: fragment }] }\n }\n // A fragment has no stylesheet to declare fonts in, so only its images become files.\n const extracted = extractImageAssets(fragment, resolvedOptions.assetBasePath)\n return {\n entrypoint: 'index.html',\n files: [{ path: 'index.html', content: extracted.html }, ...extracted.files]\n }\n}\n"],"mappings":";;;;;;AA0EA,MAAM,YACJ;AAEF,SAAS,WAAW,OAAuC;CACzD,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,QAAQ,GAAG,WAAW,UAAU,EAAE,CAAC,CACnC,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,S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c,OAAO,qBAAqB,UAAU,eAAe;CAEhG,MAAM,WAAW,cAAc,UAAU,EAAE,OAAO,gBAAgB,MAAM,CAAC;CACzE,IAAI,gBAAgB,WAAW,YAC7B,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS;EAAS,CAAC;CAAE;CAGxF,MAAM,YAAY,mBAAmB,UAAU,gBAAgB,aAAa;CAC5E,OAAO;EACL,YAAY;EACZ,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,UAAU;EAAK,GAAG,GAAG,UAAU,KAAK;CAC7E;AACF"}
|
|
1
|
+
{"version":3,"file":"bundle.js","names":[],"sources":["../../../src/export/bundle.ts"],"sourcesContent":["import { isValid, toUint8Array } from 'js-base64'\nimport { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { normalizeFontFamily } from '@pairdraw/scene-graph/font-style'\n\nimport { tokenStylesheet, type TokenStylesheetFormat } from '../tokens/stylesheet'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { mergeClassNames, serializeHTML, splitWhitespace } from './html'\n\n/** A font face the exported text uses. */\nexport interface WebFontFaceRequest {\n family: string\n weight: number\n style?: 'normal' | 'italic'\n}\n\n/** A font file to ship next to the page, described as an `@font-face` rule. */\nexport interface WebFontFaceAsset {\n family: string\n weight: string | number | [number, number]\n style: string\n display?: string\n stretch?: string\n unicodeRange?: string[]\n format: 'woff2' | 'woff' | 'opentype' | 'truetype'\n path: string\n content: Uint8Array\n}\n\n/** Finds font files for the requested faces; paths start with `assetBasePath`. */\nexport type WebFontFaceResolver = (\n fonts: WebFontFaceRequest[],\n assetBasePath: string\n) => Promise<WebFontFaceAsset[]>\n\nexport interface ExportHTMLBundleOptions {\n html?: 'fragment' | 'standalone'\n style?: 'inline' | 'tailwind'\n assets?: 'inline' | 'external'\n /** Resolves font files to include with external assets; `none` includes no fonts. */\n fonts?: 'none' | WebFontFaceResolver\n assetBasePath?: string\n /**\n * Reads one of Tailwind's stylesheets, `tailwindcss/theme.css` or `tailwindcss/utilities.css`,\n * for a standalone Tailwind page. Browsers pass one; Node and Bun read the installed package.\n */\n loadTailwindStylesheet?: TailwindStylesheetLoader\n}\n\nexport type TailwindStylesheetLoader = (id: TailwindStylesheetId) => Promise<string>\nexport type TailwindStylesheetId = 'tailwindcss/theme.css' | 'tailwindcss/utilities.css'\n\nexport interface ExportHTMLFile {\n path: string\n content: string | Uint8Array\n}\n\nexport interface ExportHTMLBundle {\n entrypoint: string\n files: ExportHTMLFile[]\n}\n\ninterface StandaloneBounds {\n minX: number\n minY: number\n width: number\n height: number\n}\n\ntype ParseNode = DefaultTreeAdapterTypes.Node\ntype ParseParent = DefaultTreeAdapterTypes.ParentNode\ntype ParseElement = DefaultTreeAdapterTypes.Element\n\nconst RESET_CSS =\n '*,*::before,*::after{box-sizing:border-box}html,body{margin:0;padding:0}body{font-family:system-ui,sans-serif;background:#fff}'\n\nfunction styleToCSS(style: DesignStyleDeclaration): string {\n return Object.entries(style)\n .filter(([, value]) => value !== '')\n .map(([property, value]) => `${property}: ${value}`)\n .join('; ')\n}\n\nfunction cloneNode(node: DesignNode): DesignNode {\n if (node.type === 'text') return { ...node }\n return {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: node.inlineStyle ? { ...node.inlineStyle } : undefined,\n children: node.children.map(cloneNode)\n }\n}\n\nfunction standaloneStyleForNode(\n node: DesignElement,\n parent: DesignElement | undefined,\n origin: StandaloneBounds\n): DesignStyleDeclaration {\n const style = { ...node.inlineStyle }\n const source = node.sourceSceneNode\n if (!source) return style\n\n style.position = 'absolute'\n style.left = `${source.x - (parent ? 0 : origin.minX)}px`\n style.top = `${source.y - (parent ? 0 : origin.minY)}px`\n return style\n}\n\nfunction standaloneNode(\n node: DesignNode,\n origin: StandaloneBounds,\n parent?: DesignElement\n): DesignNode {\n if (node.type === 'text') return cloneNode(node)\n const standalone: DesignElement = {\n ...node,\n attrs: { ...node.attrs },\n inlineStyle: standaloneStyleForNode(node, parent, origin),\n children: []\n }\n standalone.children = node.children.map((child) => standaloneNode(child, origin, node))\n return standalone\n}\n\nfunction nodeBounds(node: DesignNode): StandaloneBounds | undefined {\n if (node.type === 'text' || !node.sourceSceneNode) return undefined\n return {\n minX: node.sourceSceneNode.x,\n minY: node.sourceSceneNode.y,\n width: node.sourceSceneNode.width,\n height: node.sourceSceneNode.height\n }\n}\n\nfunction standaloneSize(document: DesignDocument): StandaloneBounds {\n const bounds = document.children\n .map(nodeBounds)\n .filter((value): value is NonNullable<typeof value> => value !== undefined)\n const minX = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minX)) : 0\n const minY = bounds.length > 0 ? Math.min(...bounds.map((bound) => bound.minY)) : 0\n const maxX = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minX + bound.width)) : 1\n const maxY = bounds.length > 0 ? Math.max(...bounds.map((bound) => bound.minY + bound.height)) : 1\n return { minX, minY, width: Math.max(1, maxX - minX), height: Math.max(1, maxY - minY) }\n}\n\nfunction standaloneDocument(document: DesignDocument, size: StandaloneBounds): DesignDocument {\n return {\n ...document,\n children: document.children.map((node) => standaloneNode(node, size))\n }\n}\n\nfunction cssClassName(index: number): string {\n return `op-${index.toString(36)}`\n}\n\nfunction extractInlineStyles(\n node: DesignNode,\n rules: string[],\n nextIndex: { value: number }\n): DesignNode {\n if (node.type === 'text') return node\n const children = node.children.map((child) => extractInlineStyles(child, rules, nextIndex))\n if (!node.inlineStyle || Object.keys(node.inlineStyle).length === 0) return { ...node, children }\n\n const className = cssClassName(nextIndex.value)\n nextIndex.value += 1\n rules.push(`.${className}{${styleToCSS(node.inlineStyle)}}`)\n return {\n ...node,\n attrs: { ...node.attrs, class: mergeClassNames(node.attrs.class, className) ?? className },\n inlineStyle: undefined,\n children\n }\n}\n\nfunction isElement(node: ParseNode): node is ParseElement {\n return 'attrs' in node && 'tagName' in node\n}\n\nfunction walkParseTree(node: ParseNode | ParseParent, visit: (node: ParseElement) => void): void {\n if (isElement(node)) visit(node)\n if ('childNodes' in node) {\n for (const child of node.childNodes) walkParseTree(child, visit)\n }\n}\n\nfunction classNamesFromHTML(html: string): string[] {\n const fragment = parseFragment(html)\n const classes = new Set<string>()\n walkParseTree(fragment, (element) => {\n const classAttr = element.attrs.find((attr) => attr.name === 'class')\n if (!classAttr) return\n for (const className of splitWhitespace(classAttr.value)) classes.add(className)\n })\n return [...classes]\n}\n\n/**\n * The stylesheet for the tokens the document references, in the format the page needs: plain\n * custom properties for inline styles, `@theme` for Tailwind, so token utilities compile.\n */\nasync function tokenCSS(document: DesignDocument, format: TokenStylesheetFormat): Promise<string> {\n const { tokens, sourceGraph } = document\n if (!tokens || !sourceGraph || tokens.used.size === 0) return ''\n const variables = tokens.stylesheetVariables()\n const { css } = await tokenStylesheet(sourceGraph, {\n format,\n include: (variable) => variables.has(variable.id)\n })\n return css\n}\n\nasync function readInstalledTailwindStylesheet(id: TailwindStylesheetId): Promise<string> {\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(new URL(import.meta.resolve(id)), 'utf8')\n}\n\nasync function compileTailwindClasses(\n classNames: string[],\n tokens: string,\n load: TailwindStylesheetLoader = readInstalledTailwindStylesheet\n): Promise<string> {\n if (classNames.length === 0) return ''\n const [{ compile }, themeCSS, utilitiesCSS] = await Promise.all([\n import('tailwindcss'),\n load('tailwindcss/theme.css'),\n load('tailwindcss/utilities.css')\n ])\n const compiler = await compile(`${themeCSS}\\n${tokens}\\n${utilitiesCSS}`)\n return compiler.build(classNames)\n}\n\nfunction collectFontRequests(node: DesignNode, fonts: Map<string, WebFontFaceRequest>): void {\n if (node.type === 'text') return\n const source = node.sourceSceneNode\n if (source?.type === 'TEXT') {\n const family = normalizeFontFamily(source.fontFamily)\n const style = source.italic ? 'italic' : 'normal'\n const key = `${family}|${source.fontWeight}|${style}`\n fonts.set(key, { family, weight: source.fontWeight, style })\n }\n for (const child of node.children) collectFontRequests(child, fonts)\n}\n\nfunction serializeFontWeight(weight: string | number | [number, number]): string {\n return Array.isArray(weight) ? weight.join(' ') : String(weight)\n}\n\n/**\n * A relative file path as a URL that points at it: each folder and file name percent-encoded,\n * so a page named `Card #1` finds `Card #1.assets/` rather than reading `#1` as a fragment.\n */\nfunction assetURL(path: string): string {\n return path.split('/').map(encodeURIComponent).join('/')\n}\n\nfunction fontSourceValue(asset: WebFontFaceAsset, from: string): string {\n // Relative to the stylesheet's folder, which the asset's path may start with.\n const path =\n from && asset.path.startsWith(`${from}/`) ? asset.path.slice(from.length + 1) : asset.path\n return [\n 'url(',\n JSON.stringify(assetURL(path)),\n ') format(',\n JSON.stringify(asset.format),\n ')'\n ].join('')\n}\n\ninterface FontFaceCSSOptions {\n /** The folder the stylesheet is in, which font paths are written relative to. */\n from: string\n /** `font-display` for every face, rather than each face's own. */\n display?: string\n}\n\nfunction fontFaceCSS(asset: WebFontFaceAsset, options: FontFaceCSSOptions): string {\n const declarations: [property: string, value: string][] = [\n ['font-family', JSON.stringify(asset.family)],\n ['src', fontSourceValue(asset, options.from)],\n ['font-weight', serializeFontWeight(asset.weight)],\n ['font-style', asset.style],\n ['font-display', options.display ?? asset.display ?? 'swap']\n ]\n if (asset.stretch) declarations.push(['font-stretch', asset.stretch])\n if (asset.unicodeRange && asset.unicodeRange.length > 0) {\n declarations.push(['unicode-range', asset.unicodeRange.join(',')])\n }\n // Written out rather than serialized by a CSS object model, which a browser bundle cannot load.\n const body = declarations.map(([property, value]) => ` ${property}: ${value};`).join('\\n')\n return `@font-face {\\n${body}\\n}\\n`\n}\n\n/** Every font face a document's text uses, once each. */\nexport function designFontRequests(document: DesignDocument): WebFontFaceRequest[] {\n const requests = new Map<string, WebFontFaceRequest>()\n for (const child of document.children) collectFontRequests(child, requests)\n return [...requests.values()]\n}\n\n/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */\nexport function fontFaceStylesheet(\n assets: readonly WebFontFaceAsset[],\n options: FontFaceCSSOptions\n): string {\n if (assets.length === 0) return ''\n return assets.map((asset) => fontFaceCSS(asset, options)).join('')\n}\n\nasync function fontFaceAssets(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<{ css: string; files: ExportHTMLFile[] }> {\n if (options.fonts === 'none' || options.assets !== 'external') return { css: '', files: [] }\n const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)\n // The page's stylesheet sits in the asset folder, beside the fonts' own folder.\n return {\n css: fontFaceStylesheet(assets, { from: options.assetBasePath }),\n files: assets\n }\n}\n\nfunction dataImageParts(value: string): { mime: string; base64: string } | undefined {\n if (!value.startsWith('data:image/')) return undefined\n const marker = ';base64,'\n const markerIndex = value.indexOf(marker)\n if (markerIndex === -1) return undefined\n const base64 = value.slice(markerIndex + marker.length)\n // Documents can come from parsed HTML; an invalid payload stays inline rather than decoding to other bytes.\n if (!isValid(base64)) return undefined\n return { mime: value.slice('data:'.length, markerIndex), base64 }\n}\n\nfunction extensionForMime(mime: string): string {\n if (mime === 'image/jpeg') return 'jpg'\n if (mime === 'image/webp') return 'webp'\n if (mime === 'image/gif') return 'gif'\n if (mime === 'image/svg+xml') return 'svg'\n return 'png'\n}\n\n/** Inline images moved into files under `assetBasePath`, the HTML pointing at them. */\nexport function extractImageAssets(\n html: string,\n assetBasePath: string\n): { html: string; files: ExportHTMLFile[] } {\n const fragment = parseFragment(html)\n const files: ExportHTMLFile[] = []\n const sources = new Map<string, string>()\n walkParseTree(fragment, (element) => {\n const src = element.attrs.find((attr) => attr.name === 'src')\n if (!src) return\n const parts = dataImageParts(src.value)\n if (!parts) return\n const cachedPath = sources.get(src.value)\n if (cachedPath) {\n src.value = assetURL(cachedPath)\n return\n }\n const path = `${assetBasePath}/images/image-${sources.size + 1}.${extensionForMime(parts.mime)}`\n sources.set(src.value, path)\n files.push({ path, content: toUint8Array(parts.base64) })\n src.value = assetURL(path)\n })\n return { html: serialize(fragment), files }\n}\n\nfunction stylesheetLink(path: string): string {\n return `<link rel=\"stylesheet\" href=\"${assetURL(path)}\">`\n}\n\n/**\n * A `<style>` element holding `css`. The HTML parser ends the element at the first `</style`\n * in any letter case, whatever the CSS around it means, and style values can come from an\n * imported document, so each one is written `<\\/style`, which CSS strings and URLs read back\n * as `</style`.\n */\nfunction styleTag(css: string): string {\n return css ? `<style>${css.replace(/<\\/(?=style)/gi, '<\\\\/')}</style>` : ''\n}\n\ntype ResolvedBundleOptions = Required<Omit<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>> &\n Pick<ExportHTMLBundleOptions, 'loadTailwindStylesheet'>\n\nasync function exportStandaloneHTML(\n document: DesignDocument,\n options: ResolvedBundleOptions\n): Promise<ExportHTMLBundle> {\n const size = standaloneSize(document)\n const doc = standaloneDocument(document, size)\n const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`\n let body: string\n let css = `${RESET_CSS}${stageCSS}`\n\n if (options.style === 'tailwind') {\n body = serializeHTML(doc, { style: 'tailwind' })\n css += await compileTailwindClasses(\n classNamesFromHTML(body),\n await tokenCSS(document, 'tailwind'),\n options.loadTailwindStylesheet\n )\n } else {\n css += await tokenCSS(document, 'css')\n const rules: string[] = []\n const index = { value: 0 }\n const styledDocument: DesignDocument = {\n ...doc,\n children: doc.children.map((node) => extractInlineStyles(node, rules, index))\n }\n body = serializeHTML(styledDocument)\n css += rules.join('')\n }\n\n if (options.assets === 'external') {\n const [extracted, fonts] = await Promise.all([\n Promise.resolve(extractImageAssets(body, options.assetBasePath)),\n fontFaceAssets(document, options)\n ])\n body = extracted.html\n const cssPath = `${options.assetBasePath}/pairdraw.css`\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${stylesheetLink(cssPath)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return {\n entrypoint: 'index.html',\n files: [\n { path: 'index.html', content: html },\n { path: cssPath, content: `${fonts.css}${css}` },\n ...fonts.files,\n ...extracted.files\n ]\n }\n }\n\n const html = `<!doctype html><html><head><meta charset=\"utf-8\"><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">${styleTag(css)}</head><body><main data-pairdraw-html=\"standalone\" class=\"pairdraw-stage\">${body}</main></body></html>`\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: html }] }\n}\n\nexport async function exportHTMLBundle(\n document: DesignDocument,\n options: ExportHTMLBundleOptions = {}\n): Promise<ExportHTMLBundle> {\n const resolvedOptions: ResolvedBundleOptions = {\n html: options.html ?? 'fragment',\n style: options.style ?? 'inline',\n assets: options.assets ?? 'inline',\n fonts: options.fonts ?? 'none',\n assetBasePath: options.assetBasePath ?? 'assets',\n loadTailwindStylesheet: options.loadTailwindStylesheet\n }\n\n if (resolvedOptions.html === 'standalone') return exportStandaloneHTML(document, resolvedOptions)\n\n const fragment = serializeHTML(document, { style: resolvedOptions.style })\n if (resolvedOptions.assets !== 'external') {\n return { entrypoint: 'index.html', files: [{ path: 'index.html', content: fragment }] }\n }\n // A fragment has no stylesheet to declare fonts in, so only its images become files.\n const extracted = extractImageAssets(fragment, resolvedOptions.assetBasePath)\n return {\n entrypoint: 'index.html',\n files: [{ path: 'index.html', content: extracted.html }, ...extracted.files]\n }\n}\n"],"mappings":";;;;;;AAyEA,MAAM,YACJ;AAEF,SAAS,WAAW,OAAuC;CACzD,OAAO,OAAO,QAAQ,KAAK,CAAC,CACzB,QAAQ,GAAG,WAAW,UAAU,EAAE,CAAC,CACnC,KAAK,CAAC,UAAU,WAAW,GAAG,SAAS,IAAI,OAAO,CAAC,CACnD,KAAK,IAAI;AACd;AAEA,SAAS,UAAU,MAA8B;CAC/C,IAAI,KAAK,SAAS,QAAQ,OAAO,EAAE,GAAG,KAAK;CAC3C,OAAO;EACL,GAAG;EACH,OAAO,EAAE,GAAG,KAAK,MAAM;EACvB,aAAa,KAAK,cAAc,EAAE,GAAG,KAAK,YAAY,IAAI,KAAA;EAC1D,UAAU,KAAK,SAAS,IAAI,SAAS;CACvC;AAC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CAC5E,OAAO;EACL,YAAY;EACZ,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,UAAU;EAAK,GAAG,GAAG,UAAU,KAAK;CAC7E;AACF"}
|
|
@@ -319,7 +319,7 @@ async function storyFonts(graph, entries, options, folder) {
|
|
|
319
319
|
if (requests.size === 0) return [];
|
|
320
320
|
const assets = await options.fonts([...requests.values()], `${folder}/fonts`);
|
|
321
321
|
if (assets.length === 0) return [];
|
|
322
|
-
const css =
|
|
322
|
+
const css = fontFaceStylesheet(assets, {
|
|
323
323
|
from: folder,
|
|
324
324
|
display: "block"
|
|
325
325
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/export/storybook/groups.ts","../../../../src/export/storybook/export.ts"],"sourcesContent":["import { behaviourArgs } from '#dom-css/behaviours/args'\nimport { uniq } from 'es-toolkit/array'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { restingVariant } from '@pairdraw/scene-graph/components'\nimport { deriveSlashVariantProperties } from '@pairdraw/scene-graph/variant-properties'\n\nimport type { StoryProp } from './module'\nimport { claimName } from './names'\n\ninterface StoryVariant {\n values: string[]\n node: SceneNode\n}\n\n/** One story file: a component set, a standalone component, or slash-named siblings. */\nexport interface StoryGroup {\n page: SceneNode\n title: string\n name: string\n props: StoryProp[]\n variants: StoryVariant[]\n /** Layer the story file links to, when the group has a layer of its own. */\n linkNode?: string\n /**\n * The component set or standalone component the group shows, which may generate a component\n * of its own; slash-named components grouped together have none.\n */\n set?: SceneNode\n}\n\nfunction isExported(node: SceneNode): boolean {\n return node.visible && !node.internalOnly\n}\n\n/** Variants whose property values collide are told apart by layer name instead. */\nfunction distinctVariants(group: StoryGroup): StoryGroup {\n const keys = group.variants.map((variant) => JSON.stringify(variant.values))\n if (new Set(keys).size === keys.length) return group\n const taken = new Set<string>()\n return {\n ...group,\n variants: group.variants.map((variant) => ({\n ...variant,\n values: [claimName(variant.node.name, taken, { separator: ' ' })]\n })),\n props: [{ name: 'Variant', options: [...taken] }]\n }\n}\n\nfunction componentSetGroup(\n graph: SceneGraph,\n page: SceneNode,\n section: string,\n set: SceneNode\n): StoryGroup {\n const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')\n // The variant at its default values opens the file as its Default story.\n const first = restingVariant(graph, set)\n const components = graph\n .getChildren(set.id)\n .filter((child) => child.type === 'COMPONENT' && isExported(child))\n const variants = [\n ...components.filter((component) => component === first),\n ...components.filter((component) => component !== first)\n ].map((component) => ({\n values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),\n node: component\n }))\n const args = behaviourArgs(graph, set)\n const props = definitions.map((def, index): StoryProp => {\n const options = uniq([\n ...(def.variantOptions ?? []),\n ...variants.map((v) => v.values[index] ?? '')\n ])\n const boolean = args?.booleans.get(def.name)\n if (boolean) return { name: def.name, options, control: { type: 'boolean', ...boolean } }\n if (args?.states?.property === def.name)\n return {\n name: def.name,\n options,\n control: { type: 'state', rest: args.states.rest, disabled: args.states.disabled }\n }\n return { name: def.name, options }\n })\n return distinctVariants({\n page,\n title: `${section}/${set.name}`,\n name: set.name,\n props,\n variants,\n linkNode: set.name,\n set\n })\n}\n\nfunction componentGroup(page: SceneNode, section: string, component: SceneNode): StoryGroup {\n return {\n page,\n title: `${section}/${component.name}`,\n name: component.name,\n props: [],\n variants: [{ values: [], node: component }],\n linkNode: component.name,\n // A standalone component generates a component of its own too, as a set does.\n set: component\n }\n}\n\n/** `Button/Primary`, `Button/Secondary` → one `Button` group with a derived variant property. */\nfunction slashGroups(\n page: SceneNode,\n section: string,\n prefix: string,\n components: SceneNode[]\n): StoryGroup[] {\n const derived = deriveSlashVariantProperties(components, () => '')\n if (!derived) return components.map((component) => componentGroup(page, section, component))\n const props = derived.definitions.map((def) => ({\n name: def.name,\n options: def.variantOptions ?? []\n }))\n const variants = components.map((component) => {\n const values = derived.variants.get(component.id)?.componentPropertyValues ?? {}\n return { values: props.map((prop) => values[prop.name] ?? ''), node: component }\n })\n return [distinctVariants({ page, title: `${section}/${prefix}`, name: prefix, props, variants })]\n}\n\n/**\n * The story files a page produces, in layer order, titled under `section`, the page's name by\n * default. Instances are never exported.\n */\nexport function collectGroups(\n graph: SceneGraph,\n page: SceneNode,\n section = page.name\n): StoryGroup[] {\n const groups: StoryGroup[] = []\n const slashed = new Map<string, SceneNode[]>()\n const visit = (node: SceneNode) => {\n if (!isExported(node) || node.type === 'INSTANCE') return\n if (node.type === 'COMPONENT_SET') {\n const group = componentSetGroup(graph, page, section, node)\n if (group.variants.length > 0) groups.push(group)\n return\n }\n if (node.type === 'COMPONENT') {\n const [prefix, ...rest] = node.name.split('/')\n const name = prefix.trim()\n if (rest.length === 0 || !name) groups.push(componentGroup(page, section, node))\n else slashed.set(name, [...(slashed.get(name) ?? []), node])\n return\n }\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const child of graph.getChildren(page.id)) visit(child)\n for (const [prefix, components] of slashed)\n groups.push(...slashGroups(page, section, prefix, components))\n return groups\n}\n","import { PLACEMENT } from '#dom-css/behaviours/states/layers'\nimport { tokenStylesheet } from '#dom-css/tokens/stylesheet'\nimport type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'\nimport { compact } from 'es-toolkit/array'\nimport { omit } from 'es-toolkit/object'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport {\n designFontRequests,\n fontFaceStylesheet,\n type ExportHTMLFile,\n type WebFontFaceRequest,\n type WebFontFaceResolver\n} from '../bundle'\nimport { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'\nimport { reactComponent } from '../components/react'\nimport type { ComponentReferences } from '../components/references'\nimport type { ComponentStyling } from '../components/styling'\nimport { vueComponent } from '../components/vue'\nimport { serializeHTML, serializeNode } from '../html'\nimport { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'\nimport { printComponentStories } from './component'\nimport { collectGroups, type StoryGroup } from './groups'\nimport {\n printStoryModule,\n STORYBOOK_PACKAGES,\n type StoryDesign,\n type StorybookFramework\n} from './module'\nimport { claimName, fileTags, identifierName, storyId, VARIANT_TAG } from './names'\n\nexport { STORYBOOK_FRAMEWORKS, type StorybookFramework } from './module'\n\n/** Frameworks whose stories render generated components; HTML stories stay static. */\nconst GENERATORS: Partial<Record<StorybookFramework, ComponentGenerator>> = {\n vue: vueComponent,\n react: reactComponent\n}\n\nexport interface ExportStorybookOptions {\n framework?: StorybookFramework\n /**\n * How Vue and React components are styled: a stylesheet beside each, by default, or Tailwind\n * utilities in their markup, which needs Tailwind set up in the Storybook project.\n */\n styling?: ComponentStyling\n /** Limit the export to one page. Defaults to every page. */\n pageId?: string\n /**\n * The document's name, which titles its stories, such as `Pricing/Plan picker`, with each\n * page's name between when it has several. Without it, stories are titled by page.\n */\n document?: string\n /** Repository-relative `.fig`/`.pen` path; adds a `pairdraw://` design link to stories. */\n linkPath?: string\n /** Renders a variant to PNG; each story then shows it next to the link as its design. */\n renderDesignImage?: (nodeId: string) => Promise<Uint8Array>\n /** Draws vector layers as inline SVG, from the engine's SVG export. */\n vectorElement?: VectorElementRenderer\n /**\n * How each story file is written, which a caller decides, such as from rules a user wrote:\n * which stories it has and its title. Every file is written as `variants` by default.\n */\n plan?: (target: StoryTarget) => StoryPlan\n /**\n * Finds the font files the stories' text uses, which ship with them in `fonts/` and load\n * before a story shows, so its text draws in the document's fonts. Without it, text uses\n * whatever fonts Storybook's page has.\n */\n fonts?: WebFontFaceResolver\n /**\n * The folder a document's shared files go in, its fonts and design tokens, which must differ\n * for each document exported into the same place; `pairdraw/<document>` by default.\n */\n folder?: string\n}\n\n/** How a story file shows its component: every variant, Default alone, a gallery, or not. */\nexport const STORY_MODES = ['variants', 'single', 'gallery', 'none'] as const\nexport type StoryMode = (typeof STORY_MODES)[number]\n\n/** A story file the export would write, as a plan reads it. */\nexport interface StoryTarget {\n /** The document's name, when the export knows it. */\n document: string | undefined\n page: string\n /** The component set's or component's name, or a slash-named group's prefix. */\n name: string\n /** The title the file has unless the plan gives another. */\n title: string\n}\n\n/** What a plan says about a story file; anything it leaves out stays as it would be. */\nexport interface StoryPlan {\n stories?: StoryMode\n title?: string\n /**\n * Whether a Vue or React export generates a component for the file, as it does by default,\n * or keeps static stories of its variants.\n */\n generate?: boolean\n}\n\nexport interface StorybookFile extends ExportHTMLFile {\n /** Name of the page the file was generated from. */\n page: string\n}\n\n/** Layers whose name no other layer carries; the link scheme can only address those. */\nfunction uniqueLayerNames(graph: SceneGraph): Set<string> {\n const counts = new Map<string, number>()\n for (const node of graph.getAllNodes()) counts.set(node.name, (counts.get(node.name) ?? 0) + 1)\n return new Set([...counts].filter(([, count]) => count === 1).map(([name]) => name))\n}\n\ninterface ModuleContext {\n graph: SceneGraph\n framework: StorybookFramework\n linkPath?: string\n uniqueNames: Set<string>\n /** Export name of each story, by variant index. */\n storyNames: string[]\n /** Import path of each variant's design image, by variant index. */\n images: string[]\n vectorElement?: VectorElementRenderer\n mode: Exclude<StoryMode, 'none'>\n /** Stylesheets every story file imports, such as the fonts its text uses. */\n styles: string[]\n}\n\nfunction designLink(\n context: Pick<ModuleContext, 'linkPath' | 'uniqueNames'>,\n ...candidates: (string | undefined)[]\n): StoryDesign[] {\n const node = candidates.find((name) => name !== undefined && context.uniqueNames.has(name))\n if (!context.linkPath || !node) return []\n const url = `pairdraw://open?file=${encodeURIComponent(context.linkPath)}&node=${encodeURIComponent(node)}`\n return [{ type: 'link', url }]\n}\n\n/** Story export names, which also name the design images. */\nfunction storyNames(group: StoryGroup): string[] {\n // Named apart from the module's own types, `Story` and `Args`.\n const taken = new Set(['story', 'args'])\n const key = (name: string) => name.toLowerCase()\n return group.variants.map((variant, index) => {\n // The first variant, the one the design shows at rest, is the file's Default story.\n const text = index === 0 || group.props.length === 0 ? 'Default' : variant.values.join(' ')\n return claimName(identifierName(text, 'Variant'), taken, { key })\n })\n}\n\nfunction storyLabel(group: StoryGroup, values: string[], index: number): string {\n if (index === 0 || group.props.length === 0) return 'Default'\n return group.props.map((prop, i) => `${prop.name}=${values[i] ?? ''}`).join(', ')\n}\n\n/**\n * A variant drawn on its own, as a story shows it: its root, placed nowhere in particular, hugs\n * its content where the design gives it no width, rather than filling the story's canvas, and sizes include padding and\n * borders, which no page reset around the story says.\n */\nfunction standalone(document: DesignDocument): DesignDocument {\n const visit = (node: DesignNode, root: boolean) => {\n if (node.type !== 'element') return\n // A variant's root drops where the set places it, which is not where the story draws it,\n // and stays the containing block of the layers placed inside it.\n const placed = root && Object.hasOwn(node.inlineStyle ?? {}, 'position')\n const style: DesignStyleDeclaration = root\n ? { ...omit({ ...node.inlineStyle }, PLACEMENT), ...(placed ? { position: 'relative' } : {}) }\n : { ...node.inlineStyle }\n const has = (property: string) => Object.hasOwn(style, property)\n if ((has('width') || has('height')) && !has('box-sizing')) style['box-sizing'] = 'border-box'\n if (root && !has('width')) style.width = 'fit-content'\n node.inlineStyle = style\n for (const child of node.children) visit(child, false)\n }\n for (const child of document.children) visit(child, true)\n return document\n}\n\nfunction storyModule(group: StoryGroup, context: ModuleContext): string {\n return printStoryModule({\n framework: context.framework,\n title: group.title,\n tags: fileTags(group.page.name),\n styles: context.styles,\n name: group.name,\n props: group.props,\n variants: group.variants.map((variant) => ({\n values: variant.values,\n html: serializeHTML(\n standalone(\n sceneNodeToDesignDocument(context.graph, variant.node.id, {\n includeSourceIds: false,\n vectorElement: context.vectorElement\n })\n )\n )\n })),\n metaDesign: designLink(context, group.linkNode),\n images: context.images,\n gallery:\n context.mode === 'gallery'\n ? group.variants.map((variant) => ({\n values: variant.values,\n label: serializeNode({ type: 'text', text: variant.values.join(', ') || group.name })\n }))\n : null,\n stories: (context.mode === 'variants' ? group.variants : group.variants.slice(0, 1)).map(\n (variant, i) => ({\n exportName: context.storyNames[i] ?? '',\n label: storyLabel(group, variant.values, i),\n tags: i === 0 ? [] : [VARIANT_TAG],\n values: variant.values,\n design: [\n ...designLink(context, variant.node.name, group.linkNode),\n ...(context.images[i] ? [{ type: 'image' as const, variant: i }] : [])\n ]\n })\n )\n })\n}\n\n/** A story file to write: its group, the page it comes from, and its claimed file name. */\ninterface StoryEntry {\n page: SceneNode\n group: StoryGroup\n file: string\n mode: Exclude<StoryMode, 'none'>\n generate: boolean\n}\n\n/**\n * Every group's story file, with names claimed on every page so a one-page export picks the\n * same names as a full one, kept for the pages the export covers.\n */\nfunction storyEntries(\n graph: SceneGraph,\n { pageId, document, plan }: Pick<ExportStorybookOptions, 'pageId' | 'document' | 'plan'>\n): StoryEntry[] {\n const takenFiles = new Set<string>()\n const takenIds = new Set<string>()\n const entries: StoryEntry[] = []\n const pages = graph.getPages()\n // Pages without components, such as an empty first page, add no level to the titles.\n const storied = pages.filter((page) => collectGroups(graph, page).length > 0)\n const section = (page: SceneNode) => {\n if (document === undefined) return page.name\n return storied.length > 1 ? `${document}/${page.name}` : document\n }\n for (const page of pages) {\n for (const group of collectGroups(graph, page, section(page))) {\n const planned = plan?.({ document, page: page.name, name: group.name, title: group.title })\n const mode = planned?.stories ?? 'variants'\n if (mode === 'none') continue\n // Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.\n group.title = claimName(planned?.title ?? group.title, takenIds, {\n separator: ' ',\n key: storyId\n })\n // File names are compared ignoring case for case-insensitive file systems.\n const file = claimName(identifierName(group.name, 'Component'), takenFiles, {\n key: (name) => name.toLowerCase()\n })\n const generate = planned?.generate ?? true\n if (!pageId || page.id === pageId) entries.push({ page, group, file, mode, generate })\n }\n }\n return entries\n}\n\n/**\n * The component each entry's set generates, by set id, built twice: first alone, so each\n * knows its props, then knowing all the others, so an instance of one uses it rather than\n * drawing its layers.\n */\nfunction generatedModels(\n graph: SceneGraph,\n entries: readonly StoryEntry[],\n vectorElement: VectorElementRenderer | undefined\n): Map<string, ComponentModel> {\n // Components are imported by their files' names, so the two always match. A group's item\n // component gets a file of its own, named apart from every story file.\n const taken = new Set(entries.map((entry) => entry.file.toLowerCase()))\n const itemNames = new Map(\n entries.map((entry) => [\n entry.file,\n claimName(`${entry.file}Item`, taken, { key: (name) => name.toLowerCase() })\n ])\n )\n const model = (set: SceneNode, file: string, references?: ComponentReferences) =>\n componentModel(graph, set, {\n vectorElement,\n references,\n name: file,\n itemName: itemNames.get(file)\n })\n const alone = new Map<string, ComponentModel>()\n for (const { group, file, generate } of entries) {\n const component = generate && group.set && model(group.set, file)\n if (group.set && component) alone.set(group.set.id, component)\n }\n const models = new Map<string, ComponentModel>()\n for (const { group, file } of entries) {\n const component = group.set && alone.has(group.set.id) && model(group.set, file, alone)\n if (group.set && component) models.set(group.set.id, component)\n }\n return models\n}\n\n/** The folder a document's shared files go in, unless the caller names one. */\nfunction documentFolder(graph: SceneGraph, options: ExportStorybookOptions): string {\n if (options.folder) return options.folder\n const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined\n const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))\n return `pairdraw/${named.join('-')}`\n}\n\n/**\n * The font files the entries' text uses, and the stylesheet that loads them. Faces load\n * before text draws, so a story never shows a fallback font first.\n */\nasync function storyFonts(\n graph: SceneGraph,\n entries: readonly StoryEntry[],\n options: ExportStorybookOptions,\n folder: string\n): Promise<ExportHTMLFile[]> {\n if (!options.fonts) return []\n const requests = new Map<string, WebFontFaceRequest>()\n for (const { group } of entries)\n for (const variant of group.variants)\n for (const request of designFontRequests(\n sceneNodeToDesignDocument(graph, variant.node.id, { includeSourceIds: false })\n ))\n requests.set(`${request.family}|${request.weight}|${request.style ?? 'normal'}`, request)\n if (requests.size === 0) return []\n const assets = await options.fonts([...requests.values()], `${folder}/fonts`)\n if (assets.length === 0) return []\n const css = await fontFaceStylesheet(assets, { from: folder, display: 'block' })\n return [...assets, { path: `${folder}/fonts.css`, content: css }]\n}\n\n/**\n * The document's design tokens as custom properties, which stories' styles refer to as\n * `var(--…)` wherever the design binds a variable, so they resolve as the design draws them.\n */\nasync function storyTokens(graph: SceneGraph, folder: string): Promise<ExportHTMLFile[]> {\n if (graph.variables.size === 0) return []\n const { css } = await tokenStylesheet(graph, { format: 'css' })\n return css ? [{ path: `${folder}/tokens.css`, content: css }] : []\n}\n\n/**\n * Generate one CSF3 `.stories.ts` file per component or component set, plus a\n * `<Name>.design/` folder of variant images when `renderDesignImage` is given.\n */\nexport async function exportStorybook(\n graph: SceneGraph,\n options: ExportStorybookOptions = {}\n): Promise<StorybookFile[]> {\n const framework = options.framework ?? 'react'\n const uniqueNames = uniqueLayerNames(graph)\n const files: StorybookFile[] = []\n const add = (page: SceneNode, path: string, content: string | Uint8Array) =>\n files.push({ path, content, page: page.name })\n\n const entries = storyEntries(graph, options)\n const folder = documentFolder(graph, options)\n const shared = [\n ...(await storyFonts(graph, entries, options, folder)),\n ...(await storyTokens(graph, folder))\n ]\n const firstPage = entries.at(0)?.page\n if (firstPage) for (const file of shared) add(firstPage, file.path, file.content)\n // Every story file loads the document's fonts and tokens.\n const styles = shared.filter((file) => file.path.endsWith('.css')).map((file) => `./${file.path}`)\n const generate = GENERATORS[framework]\n const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()\n\n for (const { page, group, file, mode } of entries) {\n const component = group.set && models.get(group.set.id)\n if (generate && component) {\n const generated = await generate(component, { styling: options.styling })\n for (const item of generated.files) add(page, item.path, item.content)\n const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)\n add(\n page,\n `${file}.stories.ts`,\n printComponentStories({\n storybook: STORYBOOK_PACKAGES[framework],\n title: group.title,\n tags: fileTags(group.page.name),\n styles,\n component,\n generated,\n // A gallery lays out static variants; a generated component's stories are its states.\n single: mode === 'single',\n design: design.flatMap((entry) =>\n entry.type === 'link' ? [{ name: 'Pairdraw', type: 'link', url: entry.url }] : []\n )\n })\n )\n continue\n }\n\n // Only the stories a file keeps get design images; a gallery or Default alone keeps one.\n const names = storyNames(group).slice(0, mode === 'variants' ? undefined : 1)\n const render = options.renderDesignImage\n const images = render ? names.map((name) => `${file}.design/${name}.png`) : []\n if (render) {\n for (const [i, variant] of group.variants.slice(0, names.length).entries())\n add(page, images[i] ?? '', await render(variant.node.id))\n }\n const context = {\n ...options,\n graph,\n framework,\n uniqueNames,\n storyNames: names,\n images,\n mode,\n styles\n }\n add(page, `${file}.stories.ts`, storyModule(group, context))\n }\n return files\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,WAAW,CAAC,KAAK;AAC/B;;AAGA,SAAS,iBAAiB,OAA+B;CACvD,MAAM,OAAO,MAAM,SAAS,KAAK,YAAY,KAAK,UAAU,QAAQ,MAAM,CAAC;CAC3E,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAAQ,OAAO;CAC/C,MAAM,wBAAQ,IAAI,IAAY;CAC9B,OAAO;EACL,GAAG;EACH,UAAU,MAAM,SAAS,KAAK,aAAa;GACzC,GAAG;GACH,QAAQ,CAAC,UAAU,QAAQ,KAAK,MAAM,OAAO,EAAE,WAAW,IAAI,CAAC,CAAC;EAClE,EAAE;EACF,OAAO,CAAC;GAAE,MAAM;GAAW,SAAS,CAAC,GAAG,KAAK;EAAE,CAAC;CAClD;AACF;AAEA,SAAS,kBACP,OACA,MACA,SACA,KACY;CACZ,MAAM,cAAc,IAAI,6BAA6B,QAAQ,QAAQ,IAAI,SAAS,SAAS;CAE3F,MAAM,QAAQ,eAAe,OAAO,GAAG;CACvC,MAAM,aAAa,MAChB,YAAY,IAAI,EAAE,CAAC,CACnB,QAAQ,UAAU,MAAM,SAAS,eAAe,WAAW,KAAK,CAAC;CACpE,MAAM,WAAW,CACf,GAAG,WAAW,QAAQ,cAAc,cAAc,KAAK,GACvD,GAAG,WAAW,QAAQ,cAAc,cAAc,KAAK,CACzD,CAAC,CAAC,KAAK,eAAe;EACpB,QAAQ,YAAY,KAAK,QAAQ,UAAU,wBAAwB,IAAI,SAAS,EAAE;EAClF,MAAM;CACR,EAAE;CACF,MAAM,OAAO,cAAc,OAAO,GAAG;CACrC,MAAM,QAAQ,YAAY,KAAK,KAAK,UAAqB;EACvD,MAAM,U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AG,SAAS,aAAa,KAAA,IAAY,CAAC;EAC5E,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,SAAS,MAAM,KAAK,SAAS,GAAG,KAAK,UAAU,KAAK,KAAK,IAAI,CAAC;EAC7E,IAAI,QACF,KAAK,MAAM,CAAC,GAAG,YAAY,MAAM,SAAS,MAAM,GAAG,MAAM,MAAM,CAAC,CAAC,QAAQ,GACvE,IAAI,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,QAAQ,KAAK,EAAE,CAAC;EAE5D,MAAM,UAAU;GACd,GAAG;GACH;GACA;GACA;GACA,YAAY;GACZ;GACA;GACA;EACF;EACA,IAAI,MAAM,GAAG,KAAK,cAAc,YAAY,OAAO,OAAO,CAAC;CAC7D;CACA,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"export.js","names":[],"sources":["../../../../src/export/storybook/groups.ts","../../../../src/export/storybook/export.ts"],"sourcesContent":["import { behaviourArgs } from '#dom-css/behaviours/args'\nimport { uniq } from 'es-toolkit/array'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport { restingVariant } from '@pairdraw/scene-graph/components'\nimport { deriveSlashVariantProperties } from '@pairdraw/scene-graph/variant-properties'\n\nimport type { StoryProp } from './module'\nimport { claimName } from './names'\n\ninterface StoryVariant {\n values: string[]\n node: SceneNode\n}\n\n/** One story file: a component set, a standalone component, or slash-named siblings. */\nexport interface StoryGroup {\n page: SceneNode\n title: string\n name: string\n props: StoryProp[]\n variants: StoryVariant[]\n /** Layer the story file links to, when the group has a layer of its own. */\n linkNode?: string\n /**\n * The component set or standalone component the group shows, which may generate a component\n * of its own; slash-named components grouped together have none.\n */\n set?: SceneNode\n}\n\nfunction isExported(node: SceneNode): boolean {\n return node.visible && !node.internalOnly\n}\n\n/** Variants whose property values collide are told apart by layer name instead. */\nfunction distinctVariants(group: StoryGroup): StoryGroup {\n const keys = group.variants.map((variant) => JSON.stringify(variant.values))\n if (new Set(keys).size === keys.length) return group\n const taken = new Set<string>()\n return {\n ...group,\n variants: group.variants.map((variant) => ({\n ...variant,\n values: [claimName(variant.node.name, taken, { separator: ' ' })]\n })),\n props: [{ name: 'Variant', options: [...taken] }]\n }\n}\n\nfunction componentSetGroup(\n graph: SceneGraph,\n page: SceneNode,\n section: string,\n set: SceneNode\n): StoryGroup {\n const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')\n // The variant at its default values opens the file as its Default story.\n const first = restingVariant(graph, set)\n const components = graph\n .getChildren(set.id)\n .filter((child) => child.type === 'COMPONENT' && isExported(child))\n const variants = [\n ...components.filter((component) => component === first),\n ...components.filter((component) => component !== first)\n ].map((component) => ({\n values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),\n node: component\n }))\n const args = behaviourArgs(graph, set)\n const props = definitions.map((def, index): StoryProp => {\n const options = uniq([\n ...(def.variantOptions ?? []),\n ...variants.map((v) => v.values[index] ?? '')\n ])\n const boolean = args?.booleans.get(def.name)\n if (boolean) return { name: def.name, options, control: { type: 'boolean', ...boolean } }\n if (args?.states?.property === def.name)\n return {\n name: def.name,\n options,\n control: { type: 'state', rest: args.states.rest, disabled: args.states.disabled }\n }\n return { name: def.name, options }\n })\n return distinctVariants({\n page,\n title: `${section}/${set.name}`,\n name: set.name,\n props,\n variants,\n linkNode: set.name,\n set\n })\n}\n\nfunction componentGroup(page: SceneNode, section: string, component: SceneNode): StoryGroup {\n return {\n page,\n title: `${section}/${component.name}`,\n name: component.name,\n props: [],\n variants: [{ values: [], node: component }],\n linkNode: component.name,\n // A standalone component generates a component of its own too, as a set does.\n set: component\n }\n}\n\n/** `Button/Primary`, `Button/Secondary` → one `Button` group with a derived variant property. */\nfunction slashGroups(\n page: SceneNode,\n section: string,\n prefix: string,\n components: SceneNode[]\n): StoryGroup[] {\n const derived = deriveSlashVariantProperties(components, () => '')\n if (!derived) return components.map((component) => componentGroup(page, section, component))\n const props = derived.definitions.map((def) => ({\n name: def.name,\n options: def.variantOptions ?? []\n }))\n const variants = components.map((component) => {\n const values = derived.variants.get(component.id)?.componentPropertyValues ?? {}\n return { values: props.map((prop) => values[prop.name] ?? ''), node: component }\n })\n return [distinctVariants({ page, title: `${section}/${prefix}`, name: prefix, props, variants })]\n}\n\n/**\n * The story files a page produces, in layer order, titled under `section`, the page's name by\n * default. Instances are never exported.\n */\nexport function collectGroups(\n graph: SceneGraph,\n page: SceneNode,\n section = page.name\n): StoryGroup[] {\n const groups: StoryGroup[] = []\n const slashed = new Map<string, SceneNode[]>()\n const visit = (node: SceneNode) => {\n if (!isExported(node) || node.type === 'INSTANCE') return\n if (node.type === 'COMPONENT_SET') {\n const group = componentSetGroup(graph, page, section, node)\n if (group.variants.length > 0) groups.push(group)\n return\n }\n if (node.type === 'COMPONENT') {\n const [prefix, ...rest] = node.name.split('/')\n const name = prefix.trim()\n if (rest.length === 0 || !name) groups.push(componentGroup(page, section, node))\n else slashed.set(name, [...(slashed.get(name) ?? []), node])\n return\n }\n for (const child of graph.getChildren(node.id)) visit(child)\n }\n for (const child of graph.getChildren(page.id)) visit(child)\n for (const [prefix, components] of slashed)\n groups.push(...slashGroups(page, section, prefix, components))\n return groups\n}\n","import { PLACEMENT } from '#dom-css/behaviours/states/layers'\nimport { tokenStylesheet } from '#dom-css/tokens/stylesheet'\nimport type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'\nimport { compact } from 'es-toolkit/array'\nimport { omit } from 'es-toolkit/object'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\nimport {\n designFontRequests,\n fontFaceStylesheet,\n type ExportHTMLFile,\n type WebFontFaceRequest,\n type WebFontFaceResolver\n} from '../bundle'\nimport { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'\nimport { reactComponent } from '../components/react'\nimport type { ComponentReferences } from '../components/references'\nimport type { ComponentStyling } from '../components/styling'\nimport { vueComponent } from '../components/vue'\nimport { serializeHTML, serializeNode } from '../html'\nimport { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'\nimport { printComponentStories } from './component'\nimport { collectGroups, type StoryGroup } from './groups'\nimport {\n printStoryModule,\n STORYBOOK_PACKAGES,\n type StoryDesign,\n type StorybookFramework\n} from './module'\nimport { claimName, fileTags, identifierName, storyId, VARIANT_TAG } from './names'\n\nexport { STORYBOOK_FRAMEWORKS, type StorybookFramework } from './module'\n\n/** Frameworks whose stories render generated components; HTML stories stay static. */\nconst GENERATORS: Partial<Record<StorybookFramework, ComponentGenerator>> = {\n vue: vueComponent,\n react: reactComponent\n}\n\nexport interface ExportStorybookOptions {\n framework?: StorybookFramework\n /**\n * How Vue and React components are styled: a stylesheet beside each, by default, or Tailwind\n * utilities in their markup, which needs Tailwind set up in the Storybook project.\n */\n styling?: ComponentStyling\n /** Limit the export to one page. Defaults to every page. */\n pageId?: string\n /**\n * The document's name, which titles its stories, such as `Pricing/Plan picker`, with each\n * page's name between when it has several. Without it, stories are titled by page.\n */\n document?: string\n /** Repository-relative `.fig`/`.pen` path; adds a `pairdraw://` design link to stories. */\n linkPath?: string\n /** Renders a variant to PNG; each story then shows it next to the link as its design. */\n renderDesignImage?: (nodeId: string) => Promise<Uint8Array>\n /** Draws vector layers as inline SVG, from the engine's SVG export. */\n vectorElement?: VectorElementRenderer\n /**\n * How each story file is written, which a caller decides, such as from rules a user wrote:\n * which stories it has and its title. Every file is written as `variants` by default.\n */\n plan?: (target: StoryTarget) => StoryPlan\n /**\n * Finds the font files the stories' text uses, which ship with them in `fonts/` and load\n * before a story shows, so its text draws in the document's fonts. Without it, text uses\n * whatever fonts Storybook's page has.\n */\n fonts?: WebFontFaceResolver\n /**\n * The folder a document's shared files go in, its fonts and design tokens, which must differ\n * for each document exported into the same place; `pairdraw/<document>` by default.\n */\n folder?: string\n}\n\n/** How a story file shows its component: every variant, Default alone, a gallery, or not. */\nexport const STORY_MODES = ['variants', 'single', 'gallery', 'none'] as const\nexport type StoryMode = (typeof STORY_MODES)[number]\n\n/** A story file the export would write, as a plan reads it. */\nexport interface StoryTarget {\n /** The document's name, when the export knows it. */\n document: string | undefined\n page: string\n /** The component set's or component's name, or a slash-named group's prefix. */\n name: string\n /** The title the file has unless the plan gives another. */\n title: string\n}\n\n/** What a plan says about a story file; anything it leaves out stays as it would be. */\nexport interface StoryPlan {\n stories?: StoryMode\n title?: string\n /**\n * Whether a Vue or React export generates a component for the file, as it does by default,\n * or keeps static stories of its variants.\n */\n generate?: boolean\n}\n\nexport interface StorybookFile extends ExportHTMLFile {\n /** Name of the page the file was generated from. */\n page: string\n}\n\n/** Layers whose name no other layer carries; the link scheme can only address those. */\nfunction uniqueLayerNames(graph: SceneGraph): Set<string> {\n const counts = new Map<string, number>()\n for (const node of graph.getAllNodes()) counts.set(node.name, (counts.get(node.name) ?? 0) + 1)\n return new Set([...counts].filter(([, count]) => count === 1).map(([name]) => name))\n}\n\ninterface ModuleContext {\n graph: SceneGraph\n framework: StorybookFramework\n linkPath?: string\n uniqueNames: Set<string>\n /** Export name of each story, by variant index. */\n storyNames: string[]\n /** Import path of each variant's design image, by variant index. */\n images: string[]\n vectorElement?: VectorElementRenderer\n mode: Exclude<StoryMode, 'none'>\n /** Stylesheets every story file imports, such as the fonts its text uses. */\n styles: string[]\n}\n\nfunction designLink(\n context: Pick<ModuleContext, 'linkPath' | 'uniqueNames'>,\n ...candidates: (string | undefined)[]\n): StoryDesign[] {\n const node = candidates.find((name) => name !== undefined && context.uniqueNames.has(name))\n if (!context.linkPath || !node) return []\n const url = `pairdraw://open?file=${encodeURIComponent(context.linkPath)}&node=${encodeURIComponent(node)}`\n return [{ type: 'link', url }]\n}\n\n/** Story export names, which also name the design images. */\nfunction storyNames(group: StoryGroup): string[] {\n // Named apart from the module's own types, `Story` and `Args`.\n const taken = new Set(['story', 'args'])\n const key = (name: string) => name.toLowerCase()\n return group.variants.map((variant, index) => {\n // The first variant, the one the design shows at rest, is the file's Default story.\n const text = index === 0 || group.props.length === 0 ? 'Default' : variant.values.join(' ')\n return claimName(identifierName(text, 'Variant'), taken, { key })\n })\n}\n\nfunction storyLabel(group: StoryGroup, values: string[], index: number): string {\n if (index === 0 || group.props.length === 0) return 'Default'\n return group.props.map((prop, i) => `${prop.name}=${values[i] ?? ''}`).join(', ')\n}\n\n/**\n * A variant drawn on its own, as a story shows it: its root, placed nowhere in particular, hugs\n * its content where the design gives it no width, rather than filling the story's canvas, and sizes include padding and\n * borders, which no page reset around the story says.\n */\nfunction standalone(document: DesignDocument): DesignDocument {\n const visit = (node: DesignNode, root: boolean) => {\n if (node.type !== 'element') return\n // A variant's root drops where the set places it, which is not where the story draws it,\n // and stays the containing block of the layers placed inside it.\n const placed = root && Object.hasOwn(node.inlineStyle ?? {}, 'position')\n const style: DesignStyleDeclaration = root\n ? { ...omit({ ...node.inlineStyle }, PLACEMENT), ...(placed ? { position: 'relative' } : {}) }\n : { ...node.inlineStyle }\n const has = (property: string) => Object.hasOwn(style, property)\n if ((has('width') || has('height')) && !has('box-sizing')) style['box-sizing'] = 'border-box'\n if (root && !has('width')) style.width = 'fit-content'\n node.inlineStyle = style\n for (const child of node.children) visit(child, false)\n }\n for (const child of document.children) visit(child, true)\n return document\n}\n\nfunction storyModule(group: StoryGroup, context: ModuleContext): string {\n return printStoryModule({\n framework: context.framework,\n title: group.title,\n tags: fileTags(group.page.name),\n styles: context.styles,\n name: group.name,\n props: group.props,\n variants: group.variants.map((variant) => ({\n values: variant.values,\n html: serializeHTML(\n standalone(\n sceneNodeToDesignDocument(context.graph, variant.node.id, {\n includeSourceIds: false,\n vectorElement: context.vectorElement\n })\n )\n )\n })),\n metaDesign: designLink(context, group.linkNode),\n images: context.images,\n gallery:\n context.mode === 'gallery'\n ? group.variants.map((variant) => ({\n values: variant.values,\n label: serializeNode({ type: 'text', text: variant.values.join(', ') || group.name })\n }))\n : null,\n stories: (context.mode === 'variants' ? group.variants : group.variants.slice(0, 1)).map(\n (variant, i) => ({\n exportName: context.storyNames[i] ?? '',\n label: storyLabel(group, variant.values, i),\n tags: i === 0 ? [] : [VARIANT_TAG],\n values: variant.values,\n design: [\n ...designLink(context, variant.node.name, group.linkNode),\n ...(context.images[i] ? [{ type: 'image' as const, variant: i }] : [])\n ]\n })\n )\n })\n}\n\n/** A story file to write: its group, the page it comes from, and its claimed file name. */\ninterface StoryEntry {\n page: SceneNode\n group: StoryGroup\n file: string\n mode: Exclude<StoryMode, 'none'>\n generate: boolean\n}\n\n/**\n * Every group's story file, with names claimed on every page so a one-page export picks the\n * same names as a full one, kept for the pages the export covers.\n */\nfunction storyEntries(\n graph: SceneGraph,\n { pageId, document, plan }: Pick<ExportStorybookOptions, 'pageId' | 'document' | 'plan'>\n): StoryEntry[] {\n const takenFiles = new Set<string>()\n const takenIds = new Set<string>()\n const entries: StoryEntry[] = []\n const pages = graph.getPages()\n // Pages without components, such as an empty first page, add no level to the titles.\n const storied = pages.filter((page) => collectGroups(graph, page).length > 0)\n const section = (page: SceneNode) => {\n if (document === undefined) return page.name\n return storied.length > 1 ? `${document}/${page.name}` : document\n }\n for (const page of pages) {\n for (const group of collectGroups(graph, page, section(page))) {\n const planned = plan?.({ document, page: page.name, name: group.name, title: group.title })\n const mode = planned?.stories ?? 'variants'\n if (mode === 'none') continue\n // Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.\n group.title = claimName(planned?.title ?? group.title, takenIds, {\n separator: ' ',\n key: storyId\n })\n // File names are compared ignoring case for case-insensitive file systems.\n const file = claimName(identifierName(group.name, 'Component'), takenFiles, {\n key: (name) => name.toLowerCase()\n })\n const generate = planned?.generate ?? true\n if (!pageId || page.id === pageId) entries.push({ page, group, file, mode, generate })\n }\n }\n return entries\n}\n\n/**\n * The component each entry's set generates, by set id, built twice: first alone, so each\n * knows its props, then knowing all the others, so an instance of one uses it rather than\n * drawing its layers.\n */\nfunction generatedModels(\n graph: SceneGraph,\n entries: readonly StoryEntry[],\n vectorElement: VectorElementRenderer | undefined\n): Map<string, ComponentModel> {\n // Components are imported by their files' names, so the two always match. A group's item\n // component gets a file of its own, named apart from every story file.\n const taken = new Set(entries.map((entry) => entry.file.toLowerCase()))\n const itemNames = new Map(\n entries.map((entry) => [\n entry.file,\n claimName(`${entry.file}Item`, taken, { key: (name) => name.toLowerCase() })\n ])\n )\n const model = (set: SceneNode, file: string, references?: ComponentReferences) =>\n componentModel(graph, set, {\n vectorElement,\n references,\n name: file,\n itemName: itemNames.get(file)\n })\n const alone = new Map<string, ComponentModel>()\n for (const { group, file, generate } of entries) {\n const component = generate && group.set && model(group.set, file)\n if (group.set && component) alone.set(group.set.id, component)\n }\n const models = new Map<string, ComponentModel>()\n for (const { group, file } of entries) {\n const component = group.set && alone.has(group.set.id) && model(group.set, file, alone)\n if (group.set && component) models.set(group.set.id, component)\n }\n return models\n}\n\n/** The folder a document's shared files go in, unless the caller names one. */\nfunction documentFolder(graph: SceneGraph, options: ExportStorybookOptions): string {\n if (options.folder) return options.folder\n const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined\n const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))\n return `pairdraw/${named.join('-')}`\n}\n\n/**\n * The font files the entries' text uses, and the stylesheet that loads them. Faces load\n * before text draws, so a story never shows a fallback font first.\n */\nasync function storyFonts(\n graph: SceneGraph,\n entries: readonly StoryEntry[],\n options: ExportStorybookOptions,\n folder: string\n): Promise<ExportHTMLFile[]> {\n if (!options.fonts) return []\n const requests = new Map<string, WebFontFaceRequest>()\n for (const { group } of entries)\n for (const variant of group.variants)\n for (const request of designFontRequests(\n sceneNodeToDesignDocument(graph, variant.node.id, { includeSourceIds: false })\n ))\n requests.set(`${request.family}|${request.weight}|${request.style ?? 'normal'}`, request)\n if (requests.size === 0) return []\n const assets = await options.fonts([...requests.values()], `${folder}/fonts`)\n if (assets.length === 0) return []\n const css = fontFaceStylesheet(assets, { from: folder, display: 'block' })\n return [...assets, { path: `${folder}/fonts.css`, content: css }]\n}\n\n/**\n * The document's design tokens as custom properties, which stories' styles refer to as\n * `var(--…)` wherever the design binds a variable, so they resolve as the design draws them.\n */\nasync function storyTokens(graph: SceneGraph, folder: string): Promise<ExportHTMLFile[]> {\n if (graph.variables.size === 0) return []\n const { css } = await tokenStylesheet(graph, { format: 'css' })\n return css ? [{ path: `${folder}/tokens.css`, content: css }] : []\n}\n\n/**\n * Generate one CSF3 `.stories.ts` file per component or component set, plus a\n * `<Name>.design/` folder of variant images when `renderDesignImage` is given.\n */\nexport async function exportStorybook(\n graph: SceneGraph,\n options: ExportStorybookOptions = {}\n): Promise<StorybookFile[]> {\n const framework = options.framework ?? 'react'\n const uniqueNames = uniqueLayerNames(graph)\n const files: StorybookFile[] = []\n const add = (page: SceneNode, path: string, content: string | Uint8Array) =>\n files.push({ path, content, page: page.name })\n\n const entries = storyEntries(graph, options)\n const folder = documentFolder(graph, options)\n const shared = [\n ...(await storyFonts(graph, entries, options, folder)),\n ...(await storyTokens(graph, folder))\n ]\n const firstPage = entries.at(0)?.page\n if (firstPage) for (const file of shared) add(firstPage, file.path, file.content)\n // Every story file loads the document's fonts and tokens.\n const styles = shared.filter((file) => file.path.endsWith('.css')).map((file) => `./${file.path}`)\n const generate = GENERATORS[framework]\n const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()\n\n for (const { page, group, file, mode } of entries) {\n const component = group.set && models.get(group.set.id)\n if (generate && component) {\n const generated = await generate(component, { styling: options.styling })\n for (const item of generated.files) add(page, item.path, item.content)\n const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)\n add(\n page,\n `${file}.stories.ts`,\n printComponentStories({\n storybook: STORYBOOK_PACKAGES[framework],\n title: group.title,\n tags: fileTags(group.page.name),\n styles,\n component,\n generated,\n // A gallery lays out static variants; a generated component's stories are its states.\n single: mode === 'single',\n design: design.flatMap((entry) =>\n entry.type === 'link' ? [{ name: 'Pairdraw', type: 'link', url: entry.url }] : []\n )\n })\n )\n continue\n }\n\n // Only the stories a file keeps get design images; a gallery or Default alone keeps one.\n const names = storyNames(group).slice(0, mode === 'variants' ? undefined : 1)\n const render = options.renderDesignImage\n const images = render ? names.map((name) => `${file}.design/${name}.png`) : []\n if (render) {\n for (const [i, variant] of group.variants.slice(0, names.length).entries())\n add(page, images[i] ?? '', await render(variant.node.id))\n }\n const context = {\n ...options,\n graph,\n framework,\n uniqueNames,\n storyNames: names,\n images,\n mode,\n styles\n }\n add(page, `${file}.stories.ts`, storyModule(group, context))\n }\n return files\n}\n"],"mappings":";;;;;;;;;;;;AA+BA,SAAS,WAAW,MAA0B;CAC5C,OAAO,KAAK,WAAW,CAAC,KAAK;AAC/B;;AAGA,SAAS,iBAAiB,OAA+B;CACvD,MAAM,OAAO,MAAM,SAAS,KAAK,YAAY,KAAK,UAAU,QAAQ,MAAM,CAAC;CAC3E,IAAI,IAAI,IAAI,IAAI,CAAC,CAAC,SAAS,KAAK,QAAQ,OAAO;CAC/C,MAAM,wBAAQ,IAAI,IAAY;CAC9B,OAAO;EACL,GAAG;EACH,UAAU,MAAM,SAAS,KAAK,aAAa;GACzC,GAAG;GACH,QAAQ,CAAC,UAAU,QAAQ,KAAK,MAAM,OAAO,EAAE,WAAW,IAAI,CAAC,CAAC;EAClE,EAAE;EACF,OAAO,CAAC;GAAE,MAAM;GAAW,SAAS,CAAC,GAAG,KAAK;EAAE,CAAC;CAClD;AACF;AAEA,SAAS,kBACP,OACA,MACA,SACA,KACY;CACZ,MAAM,cAAc,IAAI,6BAA6B,QAAQ,QAAQ,IAAI,SAAS,SAAS;CAE3F,MAAM,QAAQ,eAAe,OAAO,GAAG;CACvC,MAAM,aAAa,MAChB,YAAY,IAAI,EAAE,CAAC,CACnB,QAAQ,UAAU,MAAM,SAAS,eAAe,WAAW,KAAK,CAAC;CACpE,MAAM,WAAW,CACf,GAAG,WAAW,QAAQ,cAAc,cAAc,KAAK,GACvD,GAAG,WAAW,QAAQ,cAAc,cAAc,KAAK,CACzD,CAAC,CAAC,KAAK,eAAe;EACpB,QAAQ,YAAY,KAAK,QAAQ,UAAU,wBAAwB,IAAI,SAAS,EAAE;EAClF,MAAM;CACR,EAAE;CACF,MAAM,OA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CAAC,CACH;GACA;EACF;EAGA,MAAM,QAAQ,WAAW,KAAK,CAAC,CAAC,MAAM,GAAG,SAAS,aAAa,KAAA,IAAY,CAAC;EAC5E,MAAM,SAAS,QAAQ;EACvB,MAAM,SAAS,SAAS,MAAM,KAAK,SAAS,GAAG,KAAK,UAAU,KAAK,KAAK,IAAI,CAAC;EAC7E,IAAI,QACF,KAAK,MAAM,CAAC,GAAG,YAAY,MAAM,SAAS,MAAM,GAAG,MAAM,MAAM,CAAC,CAAC,QAAQ,GACvE,IAAI,MAAM,OAAO,MAAM,IAAI,MAAM,OAAO,QAAQ,KAAK,EAAE,CAAC;EAE5D,MAAM,UAAU;GACd,GAAG;GACH;GACA;GACA;GACA,YAAY;GACZ;GACA;GACA;EACF;EACA,IAAI,MAAM,GAAG,KAAK,cAAc,YAAY,OAAO,OAAO,CAAC;CAC7D;CACA,OAAO;AACT"}
|
package/dist/export.d.ts
CHANGED
|
@@ -418,13 +418,6 @@ declare function modeAttribute(collection: VariableCollection, mode: VariableCol
|
|
|
418
418
|
};
|
|
419
419
|
/** The scope a mode applies in when it names none: `[data-theme="dark"]` for Theme / Dark. */
|
|
420
420
|
declare function defaultModeCondition(collection: VariableCollection, mode: VariableCollectionMode): string;
|
|
421
|
-
/**
|
|
422
|
-
* Variables as a stylesheet of custom properties. The default mode of every collection is the
|
|
423
|
-
* base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;
|
|
424
|
-
* every other mode overrides the values that differ, under its condition. Aliases stay `var()`
|
|
425
|
-
* references, and number formulas `calc()` over them; both are declared again in each mode that
|
|
426
|
-
* changes what they point to.
|
|
427
|
-
*/
|
|
428
421
|
declare function buildTokenStylesheet(source: TokenSource, { format, include }: TokenStylesheetOptions, validate: TokenValidator): TokenStylesheet;
|
|
429
422
|
/**
|
|
430
423
|
* Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@pairdraw/dom-css",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.18.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"files": [
|
|
6
6
|
"dist",
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"dependencies": {
|
|
13
13
|
"@acemir/cssom": "^0.9.31",
|
|
14
|
-
"@pairdraw/emit": "^0.
|
|
14
|
+
"@pairdraw/emit": "^0.18.0",
|
|
15
15
|
"css-tree": "^3.2.1",
|
|
16
16
|
"cssesc": "^3.0.0",
|
|
17
17
|
"dedent": "^1.7.2",
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
"twirlwind": "^0.4.1"
|
|
25
25
|
},
|
|
26
26
|
"peerDependencies": {
|
|
27
|
-
"@pairdraw/scene-graph": "^0.
|
|
27
|
+
"@pairdraw/scene-graph": "^0.18.0"
|
|
28
28
|
},
|
|
29
29
|
"exports": {
|
|
30
30
|
".": {
|
package/src/export/bundle.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import type { CSSFontFaceRule } from '@acemir/cssom'
|
|
2
1
|
import { isValid, toUint8Array } from 'js-base64'
|
|
3
2
|
import { parseFragment, serialize, type DefaultTreeAdapterTypes } from 'parse5'
|
|
4
3
|
|
|
@@ -276,22 +275,21 @@ interface FontFaceCSSOptions {
|
|
|
276
275
|
display?: string
|
|
277
276
|
}
|
|
278
277
|
|
|
279
|
-
function fontFaceCSS(
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
)
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
rule.style.setProperty('font-style', asset.style)
|
|
289
|
-
rule.style.setProperty('font-display', options.display ?? asset.display ?? 'swap')
|
|
290
|
-
if (asset.stretch) rule.style.setProperty('font-stretch', asset.stretch)
|
|
278
|
+
function fontFaceCSS(asset: WebFontFaceAsset, options: FontFaceCSSOptions): string {
|
|
279
|
+
const declarations: [property: string, value: string][] = [
|
|
280
|
+
['font-family', JSON.stringify(asset.family)],
|
|
281
|
+
['src', fontSourceValue(asset, options.from)],
|
|
282
|
+
['font-weight', serializeFontWeight(asset.weight)],
|
|
283
|
+
['font-style', asset.style],
|
|
284
|
+
['font-display', options.display ?? asset.display ?? 'swap']
|
|
285
|
+
]
|
|
286
|
+
if (asset.stretch) declarations.push(['font-stretch', asset.stretch])
|
|
291
287
|
if (asset.unicodeRange && asset.unicodeRange.length > 0) {
|
|
292
|
-
|
|
288
|
+
declarations.push(['unicode-range', asset.unicodeRange.join(',')])
|
|
293
289
|
}
|
|
294
|
-
|
|
290
|
+
// Written out rather than serialized by a CSS object model, which a browser bundle cannot load.
|
|
291
|
+
const body = declarations.map(([property, value]) => ` ${property}: ${value};`).join('\n')
|
|
292
|
+
return `@font-face {\n${body}\n}\n`
|
|
295
293
|
}
|
|
296
294
|
|
|
297
295
|
/** Every font face a document's text uses, once each. */
|
|
@@ -302,14 +300,12 @@ export function designFontRequests(document: DesignDocument): WebFontFaceRequest
|
|
|
302
300
|
}
|
|
303
301
|
|
|
304
302
|
/** `@font-face` rules for font files, as a stylesheet in the folder `options.from`. */
|
|
305
|
-
export
|
|
303
|
+
export function fontFaceStylesheet(
|
|
306
304
|
assets: readonly WebFontFaceAsset[],
|
|
307
305
|
options: FontFaceCSSOptions
|
|
308
|
-
):
|
|
306
|
+
): string {
|
|
309
307
|
if (assets.length === 0) return ''
|
|
310
|
-
|
|
311
|
-
const cssom = await import('@acemir/cssom')
|
|
312
|
-
return assets.map((asset) => fontFaceCSS(cssom.CSSFontFaceRule, asset, options)).join('')
|
|
308
|
+
return assets.map((asset) => fontFaceCSS(asset, options)).join('')
|
|
313
309
|
}
|
|
314
310
|
|
|
315
311
|
async function fontFaceAssets(
|
|
@@ -320,7 +316,7 @@ async function fontFaceAssets(
|
|
|
320
316
|
const assets = await options.fonts(designFontRequests(document), `${options.assetBasePath}/fonts`)
|
|
321
317
|
// The page's stylesheet sits in the asset folder, beside the fonts' own folder.
|
|
322
318
|
return {
|
|
323
|
-
css:
|
|
319
|
+
css: fontFaceStylesheet(assets, { from: options.assetBasePath }),
|
|
324
320
|
files: assets
|
|
325
321
|
}
|
|
326
322
|
}
|
|
@@ -339,7 +339,7 @@ async function storyFonts(
|
|
|
339
339
|
if (requests.size === 0) return []
|
|
340
340
|
const assets = await options.fonts([...requests.values()], `${folder}/fonts`)
|
|
341
341
|
if (assets.length === 0) return []
|
|
342
|
-
const css =
|
|
342
|
+
const css = fontFaceStylesheet(assets, { from: folder, display: 'block' })
|
|
343
343
|
return [...assets, { path: `${folder}/fonts.css`, content: css }]
|
|
344
344
|
}
|
|
345
345
|
|
|
@@ -10,6 +10,7 @@ import {
|
|
|
10
10
|
} from '@pairdraw/scene-graph'
|
|
11
11
|
import { TRANSPARENT } from '@pairdraw/scene-graph/constants'
|
|
12
12
|
import { parseCSSAlignSelf, parseCSSNumber, parseCSSShadows } from '@pairdraw/scene-graph/css'
|
|
13
|
+
import { normalizeEffects } from '@pairdraw/scene-graph/effects'
|
|
13
14
|
import { computeImageHash } from '@pairdraw/scene-graph/images'
|
|
14
15
|
|
|
15
16
|
import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
|
|
@@ -328,7 +329,7 @@ function applyElementStyle(
|
|
|
328
329
|
}
|
|
329
330
|
|
|
330
331
|
const effects = parseCSSShadows(pickStyle(style, 'box-shadow'))
|
|
331
|
-
if (effects.length > 0) node.effects = effects
|
|
332
|
+
if (effects.length > 0) node.effects = normalizeEffects(effects)
|
|
332
333
|
|
|
333
334
|
const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
|
|
334
335
|
if (opacity !== null) node.opacity = opacity
|
|
@@ -368,7 +369,7 @@ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
|
|
|
368
369
|
if (opacity !== null) node.opacity = opacity
|
|
369
370
|
|
|
370
371
|
const effects = parseCSSShadows(pickStyle(style, 'text-shadow'))
|
|
371
|
-
if (effects.length > 0) node.effects = effects
|
|
372
|
+
if (effects.length > 0) node.effects = normalizeEffects(effects)
|
|
372
373
|
|
|
373
374
|
const textAlign = pickStyle(style, 'text-align')?.toUpperCase()
|
|
374
375
|
if (textAlign === 'CENTER' || textAlign === 'RIGHT' || textAlign === 'JUSTIFIED') {
|
package/src/tokens/stylesheet.ts
CHANGED
|
@@ -9,7 +9,14 @@ import { variableValueReferences } from '@pairdraw/scene-graph/variables'
|
|
|
9
9
|
|
|
10
10
|
import { cssColor } from '../export/css'
|
|
11
11
|
import { formulaToCSS } from './formula'
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
collectionVariables,
|
|
14
|
+
deriveCSSName,
|
|
15
|
+
explicitCSSName,
|
|
16
|
+
tokenSlug,
|
|
17
|
+
variableCSSNames,
|
|
18
|
+
variableNamespace
|
|
19
|
+
} from './names'
|
|
13
20
|
import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
|
|
14
21
|
import { tokenNumberToCSS, variableUnit } from './values'
|
|
15
22
|
|
|
@@ -170,6 +177,29 @@ function variantNames(scopes: ModeScope[]): string[] {
|
|
|
170
177
|
* references, and number formulas `calc()` over them; both are declared again in each mode that
|
|
171
178
|
* changes what they point to.
|
|
172
179
|
*/
|
|
180
|
+
/**
|
|
181
|
+
* A name that took a numeric suffix is an alias nobody can read back from the stylesheet, so it
|
|
182
|
+
* is reported rather than left as a silent second spelling of another token.
|
|
183
|
+
*/
|
|
184
|
+
function numberedNameIssues(
|
|
185
|
+
variables: readonly Variable[],
|
|
186
|
+
names: Map<string, string>,
|
|
187
|
+
modeOf: (variable: Variable) => string
|
|
188
|
+
): TokenStylesheetIssue[] {
|
|
189
|
+
const issues: TokenStylesheetIssue[] = []
|
|
190
|
+
for (const variable of variables) {
|
|
191
|
+
const name = names.get(variable.id)
|
|
192
|
+
const base = deriveCSSName(variable)
|
|
193
|
+
if (!name || explicitCSSName(variable) || name === base) continue
|
|
194
|
+
issues.push({
|
|
195
|
+
message: `"${variable.name}" is written --${name}: --${base} is taken`,
|
|
196
|
+
variableId: variable.id,
|
|
197
|
+
modeId: modeOf(variable)
|
|
198
|
+
})
|
|
199
|
+
}
|
|
200
|
+
return issues
|
|
201
|
+
}
|
|
202
|
+
|
|
173
203
|
export function buildTokenStylesheet(
|
|
174
204
|
source: TokenSource,
|
|
175
205
|
{ format, include = () => true }: TokenStylesheetOptions,
|
|
@@ -205,6 +235,8 @@ export function buildTokenStylesheet(
|
|
|
205
235
|
return { name, value: css }
|
|
206
236
|
}
|
|
207
237
|
|
|
238
|
+
issues.push(...numberedNameIssues(variables, names, defaultModeOf))
|
|
239
|
+
|
|
208
240
|
const defaults = new Map<string, Declaration>()
|
|
209
241
|
const theme: Declaration[] = []
|
|
210
242
|
const root: Declaration[] = []
|