@pairdraw/dom-css 0.16.0 → 0.16.1
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/export/bundle.js +3 -3
- package/dist/chunks/export/bundle.js.map +1 -1
- package/dist/chunks/export/components/layers.js +136 -131
- package/dist/chunks/export/components/layers.js.map +1 -1
- package/package.json +18 -3
- package/src/export/bundle.ts +3 -3
- package/src/export/components/react/index.ts +5 -199
- package/src/export/components/react/props.ts +151 -0
- package/src/export/components/react/radix.ts +52 -0
|
@@ -259,7 +259,7 @@ function styleTag(css) {
|
|
|
259
259
|
async function exportStandaloneHTML(document, options) {
|
|
260
260
|
const size = standaloneSize(document);
|
|
261
261
|
const doc = standaloneDocument(document, size);
|
|
262
|
-
const stageCSS = `.
|
|
262
|
+
const stageCSS = `.pairdraw-stage{position:relative;width:${size.width}px;height:${size.height}px;overflow:hidden;background:transparent}`;
|
|
263
263
|
let body;
|
|
264
264
|
let css = `${RESET_CSS}${stageCSS}`;
|
|
265
265
|
if (options.style === "tailwind") {
|
|
@@ -285,7 +285,7 @@ async function exportStandaloneHTML(document, options) {
|
|
|
285
285
|
files: [
|
|
286
286
|
{
|
|
287
287
|
path: "index.html",
|
|
288
|
-
content: `<!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="
|
|
288
|
+
content: `<!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>`
|
|
289
289
|
},
|
|
290
290
|
{
|
|
291
291
|
path: cssPath,
|
|
@@ -300,7 +300,7 @@ async function exportStandaloneHTML(document, options) {
|
|
|
300
300
|
entrypoint: "index.html",
|
|
301
301
|
files: [{
|
|
302
302
|
path: "index.html",
|
|
303
|
-
content: `<!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="
|
|
303
|
+
content: `<!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>`
|
|
304
304
|
}]
|
|
305
305
|
};
|
|
306
306
|
}
|
|
@@ -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\nfunction styleTag(css: string): string {\n return css ? `<style>${css}</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 = `.op-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=\"op-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=\"op-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,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;AACF;AAEA,SAAS,uBACP,MACA,QACA,QACwB;CACxB,MAAM,QAAQ,EAAE,GAAG,KAAK,YAAY;CACpC,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,WAAW;CACjB,MAAM,OAAO,G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ontFaceRule } 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\nfunction styleTag(css: string): string {\n return css ? `<style>${css}</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,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;AACF;AAEA,SAAS,uBACP,MACA,QACA,QACwB;CACxB,MAAM,QAAQ,EAAE,GAAG,KAAK,YAAY;CACpC,MAAM,SAAS,KAAK;CACpB,IAAI,CAAC,QAAQ,OAAO;CAEpB,MAAM,WAAW;CACjB,MAAM,OAAO,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACtD,MAAM,MAAM,GAAG,OAAO,KAAK,SAAS,IAAI,OAAO,MAAM;CACrD,OAAO;AACT;AAEA,SAAS,eACP,MACA,QACA,QACY;CACZ,IAAI,KAAK,SAAS,QAAQ,OAAO,UAAU,IAAI;CAC/C,MAAM,aAA4B;EAChC,GAAG;EACH,OAAO,EAAE,GAAG,KAAK,MAAM;EACvB,aAAa,uBAAuB,MAAM,QAAQ,MAAM;EACxD,UAAU,CAAC;CACb;CACA,WAA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;IAAM;IAC/C,GAAG,MAAM;IACT,GAAG,UAAU;GACf;EACF;CACF;CAGA,OAAO;EAAE,YAAY;EAAc,OAAO,CAAC;GAAE,MAAM;GAAc,SAAS,wHAD2D,SAAS,GAAG,EAAE,4EAA4E,KAAK;EACrJ,CAAC;CAAE;AACpF;AAEA,eAAsB,iBACpB,UACA,UAAmC,CAAC,GACT;CAC3B,MAAM,kBAAyC;EAC7C,MAAM,QAAQ,QAAQ;EACtB,OAAO,QAAQ,SAAS;EACxB,QAAQ,QAAQ,UAAU;EAC1B,OAAO,QAAQ,SAAS;EACxB,eAAe,QAAQ,iBAAiB;EACxC,wBAAwB,QAAQ;CAClC;CAEA,IAAI,gBAAgB,SAAS,cAAc,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"}
|
|
@@ -628,7 +628,7 @@ function prepend(declaration, statements) {
|
|
|
628
628
|
body.body = [...statements, ...es.children(body, "body")];
|
|
629
629
|
}
|
|
630
630
|
//#endregion
|
|
631
|
-
//#region src/export/components/react/
|
|
631
|
+
//#region src/export/components/react/radix.ts
|
|
632
632
|
/**
|
|
633
633
|
* The Radix primitive a kind renders, from the unified `radix-ui` package, and the component
|
|
634
634
|
* of it each part uses. Its root takes the value two ways (`checked` and `onCheckedChange`,
|
|
@@ -723,12 +723,146 @@ const RADIX = {
|
|
|
723
723
|
textarea: null,
|
|
724
724
|
plain: null
|
|
725
725
|
};
|
|
726
|
+
/** The local name a Radix namespace is imported as, such as `SwitchPrimitive`. */
|
|
727
|
+
const PRIMITIVE = (namespace) => `${namespace}Primitive`;
|
|
728
|
+
/** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */
|
|
729
|
+
const defaultOf = (model) => `default${upperFirst(model)}`;
|
|
730
|
+
//#endregion
|
|
731
|
+
//#region src/export/components/react/props.ts
|
|
732
|
+
/**
|
|
733
|
+
* The props of a group that fixes one choice at a time, without the `type` it fixes. The
|
|
734
|
+
* root's own props join the single and multiple choice, which a single value can't satisfy.
|
|
735
|
+
*/
|
|
736
|
+
const SINGLE_PROPS = {
|
|
737
|
+
toggleGroup: "ToggleGroupSingleProps",
|
|
738
|
+
accordion: "AccordionSingleProps"
|
|
739
|
+
};
|
|
740
|
+
const qualified = (namespace, name) => ({
|
|
741
|
+
type: "TSQualifiedName",
|
|
742
|
+
left: es.identifier(PRIMITIVE(namespace)),
|
|
743
|
+
right: es.identifier(name)
|
|
744
|
+
});
|
|
745
|
+
/** Props a kind declares itself, where no Radix root has them. */
|
|
746
|
+
const OWN_PROPS = {
|
|
747
|
+
progress: "Omit<ComponentProps<typeof ProgressPrimitive.Root>, 'value'> & { value?: number }",
|
|
748
|
+
numberField: "Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & { defaultValue?: number; onValueChange?: (value: number) => void; disabled?: boolean }",
|
|
749
|
+
textField: "ComponentProps<'input'>",
|
|
750
|
+
textarea: "ComponentProps<'textarea'>"
|
|
751
|
+
};
|
|
752
|
+
/** The root's own props, or a single choice group's. */
|
|
753
|
+
function rootPropsType(kind, tag) {
|
|
754
|
+
const own = OWN_PROPS[kind];
|
|
755
|
+
if (own) return es.parseType(own);
|
|
756
|
+
if (kind === "plain") return es.parseType(`ComponentProps<'${tag}'>`);
|
|
757
|
+
const radix = RADIX[kind];
|
|
758
|
+
if (!radix) return es.parseType("ComponentProps<'button'>");
|
|
759
|
+
const single = SINGLE_PROPS[kind];
|
|
760
|
+
if (single) return es.fill(es.parseType("Omit<$Props, 'type'>"), { $Props: qualified(radix.namespace, single) });
|
|
761
|
+
return es.fill(es.parseType("ComponentProps<typeof $Root>"), { $Root: qualified(radix.namespace, radix.parts.root) });
|
|
762
|
+
}
|
|
763
|
+
/** The root's own props, extended with the component's variant props when it has any. */
|
|
764
|
+
function propsType$1(component) {
|
|
765
|
+
const base = rootPropsType(component.kind, component.tree.tag);
|
|
766
|
+
if ([
|
|
767
|
+
component.props,
|
|
768
|
+
component.texts,
|
|
769
|
+
component.booleans,
|
|
770
|
+
component.slots
|
|
771
|
+
].every((list) => list.length === 0)) return base;
|
|
772
|
+
return {
|
|
773
|
+
type: "TSIntersectionType",
|
|
774
|
+
types: [base, es.objectType([
|
|
775
|
+
...component.props.map((prop) => [
|
|
776
|
+
prop.name,
|
|
777
|
+
es.stringUnionType(prop.options),
|
|
778
|
+
true
|
|
779
|
+
]),
|
|
780
|
+
...component.texts.map((text) => [
|
|
781
|
+
text.name,
|
|
782
|
+
es.parseType("string"),
|
|
783
|
+
true
|
|
784
|
+
]),
|
|
785
|
+
...component.booleans.map((prop) => [
|
|
786
|
+
prop.name,
|
|
787
|
+
es.parseType("boolean"),
|
|
788
|
+
true
|
|
789
|
+
]),
|
|
790
|
+
...component.slots.map((slot) => [
|
|
791
|
+
slot.name,
|
|
792
|
+
es.parseType("ReactNode"),
|
|
793
|
+
true
|
|
794
|
+
])
|
|
795
|
+
])]
|
|
796
|
+
};
|
|
797
|
+
}
|
|
798
|
+
/**
|
|
799
|
+
* `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
|
|
800
|
+
* kept off the root, and the rest passed on.
|
|
801
|
+
*/
|
|
802
|
+
function parameters(component) {
|
|
803
|
+
const own = [
|
|
804
|
+
...kindParameters(component),
|
|
805
|
+
...[...component.props, ...component.texts].map((prop) => ({
|
|
806
|
+
name: prop.name,
|
|
807
|
+
default: es.string(prop.default)
|
|
808
|
+
})),
|
|
809
|
+
...component.booleans.map((prop) => ({
|
|
810
|
+
name: prop.name,
|
|
811
|
+
default: es.parseExpression(String(prop.default))
|
|
812
|
+
})),
|
|
813
|
+
...component.slots.map((slot) => ({ name: slot.name }))
|
|
814
|
+
];
|
|
815
|
+
if (own.length === 0) return es.identifier("props");
|
|
816
|
+
return {
|
|
817
|
+
type: "ObjectPattern",
|
|
818
|
+
properties: [...own.map((prop) => ({
|
|
819
|
+
type: "Property",
|
|
820
|
+
kind: "init",
|
|
821
|
+
key: es.identifier(prop.name),
|
|
822
|
+
value: prop.default ? {
|
|
823
|
+
type: "AssignmentPattern",
|
|
824
|
+
left: es.identifier(prop.name),
|
|
825
|
+
right: prop.default
|
|
826
|
+
} : es.identifier(prop.name),
|
|
827
|
+
computed: false,
|
|
828
|
+
method: false,
|
|
829
|
+
shorthand: true
|
|
830
|
+
})), {
|
|
831
|
+
type: "RestElement",
|
|
832
|
+
argument: es.identifier("props")
|
|
833
|
+
}]
|
|
834
|
+
};
|
|
835
|
+
}
|
|
836
|
+
/**
|
|
837
|
+
* `import { useState, type ComponentProps, type ReactNode } from 'react'` with only what the
|
|
838
|
+
* component uses: a number field's state, its root's props, and its slots' content.
|
|
839
|
+
*/
|
|
840
|
+
function reactImport(uses) {
|
|
841
|
+
const types = [...uses.props ? ["ComponentProps"] : [], ...uses.slots ? ["ReactNode"] : []];
|
|
842
|
+
if (!uses.state && types.length === 0) return [];
|
|
843
|
+
const specifiers = uses.state ? ["useState", ...types.map((name) => `type ${name}`)].join(", ") : types.join(", ");
|
|
844
|
+
return es.parseModule(`import ${uses.state ? "" : "type "}{ ${specifiers} } from 'react'`).body;
|
|
845
|
+
}
|
|
846
|
+
/**
|
|
847
|
+
* The prop a story sets the value with: Radix's uncontrolled value, so a story's control and
|
|
848
|
+
* its play function can both change it, which a slider takes as a list; a progress bar's own
|
|
849
|
+
* value, which nothing else changes.
|
|
850
|
+
*/
|
|
851
|
+
function valueArg(kind, model) {
|
|
852
|
+
if (!model) return { valueArg: null };
|
|
853
|
+
if (kind === "progress") return { valueArg: "value" };
|
|
854
|
+
return {
|
|
855
|
+
valueArg: defaultOf(model),
|
|
856
|
+
...kind === "slider" ? { valueList: true } : {}
|
|
857
|
+
};
|
|
858
|
+
}
|
|
859
|
+
//#endregion
|
|
860
|
+
//#region src/export/components/react/index.ts
|
|
726
861
|
/** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
|
|
727
862
|
const ROOT_ATTRIBUTES$1 = {
|
|
728
863
|
toggleGroup: [jsx.attribute("type", jsx.stringValue("single"))],
|
|
729
864
|
accordion: [jsx.attribute("type", jsx.stringValue("single")), jsx.attribute("collapsible", null)]
|
|
730
865
|
};
|
|
731
|
-
const PRIMITIVE = (namespace) => `${namespace}Primitive`;
|
|
732
866
|
const HEADING_STYLE$1 = jsx.container(es.object(Object.entries(HEADING_RESET).map(([property, value]) => [camelCase(property), es.string(value)])));
|
|
733
867
|
/** Several classes on one element, skipping a caller's that is absent. */
|
|
734
868
|
const CLASS_NAMES = es.parseExpression("$classes.filter(Boolean).join(' ')");
|
|
@@ -758,8 +892,6 @@ function iconElement$1(node, uses, depth) {
|
|
|
758
892
|
if (drawn.type === "component") return jsx.element(drawn.import.local, [className], [], depth);
|
|
759
893
|
return jsx.element(drawn.component.local, [jsx.attribute("icon", jsx.container(es.identifier(drawn.import.local))), className], [], depth);
|
|
760
894
|
}
|
|
761
|
-
/** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */
|
|
762
|
-
const defaultOf = (model) => `default${upperFirst(model)}`;
|
|
763
895
|
/** A reference's prop value: a bare name for true, `{false}`, or a string. */
|
|
764
896
|
function referenceValue(value) {
|
|
765
897
|
if (value === true) return null;
|
|
@@ -890,133 +1022,6 @@ const RADIX_IMPORT = es.parseModule(`import { $Namespace as $Primitive } from 'r
|
|
|
890
1022
|
const ICONIFY_IMPORT = es.parseModule(`import { Icon as ${ICONIFY$1} } from '@iconify/react'`).body;
|
|
891
1023
|
const IMPORT_COMPONENT$1 = es.parseModule(`import { $Component } from '$path'`);
|
|
892
1024
|
/**
|
|
893
|
-
* The props of a group that fixes one choice at a time, without the `type` it fixes. The
|
|
894
|
-
* root's own props join the single and multiple choice, which a single value can't satisfy.
|
|
895
|
-
*/
|
|
896
|
-
const SINGLE_PROPS = {
|
|
897
|
-
toggleGroup: "ToggleGroupSingleProps",
|
|
898
|
-
accordion: "AccordionSingleProps"
|
|
899
|
-
};
|
|
900
|
-
const qualified = (namespace, name) => ({
|
|
901
|
-
type: "TSQualifiedName",
|
|
902
|
-
left: es.identifier(PRIMITIVE(namespace)),
|
|
903
|
-
right: es.identifier(name)
|
|
904
|
-
});
|
|
905
|
-
/** Props a kind declares itself, where no Radix root has them. */
|
|
906
|
-
const OWN_PROPS = {
|
|
907
|
-
progress: "Omit<ComponentProps<typeof ProgressPrimitive.Root>, 'value'> & { value?: number }",
|
|
908
|
-
numberField: "Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & { defaultValue?: number; onValueChange?: (value: number) => void; disabled?: boolean }",
|
|
909
|
-
textField: "ComponentProps<'input'>",
|
|
910
|
-
textarea: "ComponentProps<'textarea'>"
|
|
911
|
-
};
|
|
912
|
-
/** The root's own props, or a single choice group's. */
|
|
913
|
-
function rootPropsType(kind, tag) {
|
|
914
|
-
const own = OWN_PROPS[kind];
|
|
915
|
-
if (own) return es.parseType(own);
|
|
916
|
-
if (kind === "plain") return es.parseType(`ComponentProps<'${tag}'>`);
|
|
917
|
-
const radix = RADIX[kind];
|
|
918
|
-
if (!radix) return es.parseType("ComponentProps<'button'>");
|
|
919
|
-
const single = SINGLE_PROPS[kind];
|
|
920
|
-
if (single) return es.fill(es.parseType("Omit<$Props, 'type'>"), { $Props: qualified(radix.namespace, single) });
|
|
921
|
-
return es.fill(es.parseType("ComponentProps<typeof $Root>"), { $Root: qualified(radix.namespace, radix.parts.root) });
|
|
922
|
-
}
|
|
923
|
-
/** The root's own props, extended with the component's variant props when it has any. */
|
|
924
|
-
function propsType$1(component) {
|
|
925
|
-
const base = rootPropsType(component.kind, component.tree.tag);
|
|
926
|
-
if ([
|
|
927
|
-
component.props,
|
|
928
|
-
component.texts,
|
|
929
|
-
component.booleans,
|
|
930
|
-
component.slots
|
|
931
|
-
].every((list) => list.length === 0)) return base;
|
|
932
|
-
return {
|
|
933
|
-
type: "TSIntersectionType",
|
|
934
|
-
types: [base, es.objectType([
|
|
935
|
-
...component.props.map((prop) => [
|
|
936
|
-
prop.name,
|
|
937
|
-
es.stringUnionType(prop.options),
|
|
938
|
-
true
|
|
939
|
-
]),
|
|
940
|
-
...component.texts.map((text) => [
|
|
941
|
-
text.name,
|
|
942
|
-
es.parseType("string"),
|
|
943
|
-
true
|
|
944
|
-
]),
|
|
945
|
-
...component.booleans.map((prop) => [
|
|
946
|
-
prop.name,
|
|
947
|
-
es.parseType("boolean"),
|
|
948
|
-
true
|
|
949
|
-
]),
|
|
950
|
-
...component.slots.map((slot) => [
|
|
951
|
-
slot.name,
|
|
952
|
-
es.parseType("ReactNode"),
|
|
953
|
-
true
|
|
954
|
-
])
|
|
955
|
-
])]
|
|
956
|
-
};
|
|
957
|
-
}
|
|
958
|
-
/**
|
|
959
|
-
* `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
|
|
960
|
-
* kept off the root, and the rest passed on.
|
|
961
|
-
*/
|
|
962
|
-
function parameters(component) {
|
|
963
|
-
const own = [
|
|
964
|
-
...kindParameters(component),
|
|
965
|
-
...[...component.props, ...component.texts].map((prop) => ({
|
|
966
|
-
name: prop.name,
|
|
967
|
-
default: es.string(prop.default)
|
|
968
|
-
})),
|
|
969
|
-
...component.booleans.map((prop) => ({
|
|
970
|
-
name: prop.name,
|
|
971
|
-
default: es.parseExpression(String(prop.default))
|
|
972
|
-
})),
|
|
973
|
-
...component.slots.map((slot) => ({ name: slot.name }))
|
|
974
|
-
];
|
|
975
|
-
if (own.length === 0) return es.identifier("props");
|
|
976
|
-
return {
|
|
977
|
-
type: "ObjectPattern",
|
|
978
|
-
properties: [...own.map((prop) => ({
|
|
979
|
-
type: "Property",
|
|
980
|
-
kind: "init",
|
|
981
|
-
key: es.identifier(prop.name),
|
|
982
|
-
value: prop.default ? {
|
|
983
|
-
type: "AssignmentPattern",
|
|
984
|
-
left: es.identifier(prop.name),
|
|
985
|
-
right: prop.default
|
|
986
|
-
} : es.identifier(prop.name),
|
|
987
|
-
computed: false,
|
|
988
|
-
method: false,
|
|
989
|
-
shorthand: true
|
|
990
|
-
})), {
|
|
991
|
-
type: "RestElement",
|
|
992
|
-
argument: es.identifier("props")
|
|
993
|
-
}]
|
|
994
|
-
};
|
|
995
|
-
}
|
|
996
|
-
/**
|
|
997
|
-
* `import { useState, type ComponentProps, type ReactNode } from 'react'` with only what the
|
|
998
|
-
* component uses: a number field's state, its root's props, and its slots' content.
|
|
999
|
-
*/
|
|
1000
|
-
function reactImport(uses) {
|
|
1001
|
-
const types = [...uses.props ? ["ComponentProps"] : [], ...uses.slots ? ["ReactNode"] : []];
|
|
1002
|
-
if (!uses.state && types.length === 0) return [];
|
|
1003
|
-
const specifiers = uses.state ? ["useState", ...types.map((name) => `type ${name}`)].join(", ") : types.join(", ");
|
|
1004
|
-
return es.parseModule(`import ${uses.state ? "" : "type "}{ ${specifiers} } from 'react'`).body;
|
|
1005
|
-
}
|
|
1006
|
-
/**
|
|
1007
|
-
* The prop a story sets the value with: Radix's uncontrolled value, so a story's control and
|
|
1008
|
-
* its play function can both change it, which a slider takes as a list; a progress bar's own
|
|
1009
|
-
* value, which nothing else changes.
|
|
1010
|
-
*/
|
|
1011
|
-
function valueArg(kind, model) {
|
|
1012
|
-
if (!model) return { valueArg: null };
|
|
1013
|
-
if (kind === "progress") return { valueArg: "value" };
|
|
1014
|
-
return {
|
|
1015
|
-
valueArg: defaultOf(model),
|
|
1016
|
-
...kind === "slider" ? { valueList: true } : {}
|
|
1017
|
-
};
|
|
1018
|
-
}
|
|
1019
|
-
/**
|
|
1020
1025
|
* A component as a React component on Radix UI: its parts as Radix primitives from the
|
|
1021
1026
|
* `radix-ui` package, its variants' state styles in a CSS module, and props that extend the
|
|
1022
1027
|
* Radix root's with its other variant properties.
|