@pairdraw/dom-css 0.0.0-stage → 0.16.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.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/browser.d.ts +29 -0
  4. package/dist/browser.js +2 -0
  5. package/dist/chunks/behaviours/args.js +59 -0
  6. package/dist/chunks/behaviours/args.js.map +1 -0
  7. package/dist/chunks/behaviours/controls.js +109 -0
  8. package/dist/chunks/behaviours/controls.js.map +1 -0
  9. package/dist/chunks/behaviours/reset.js +40 -0
  10. package/dist/chunks/behaviours/reset.js.map +1 -0
  11. package/dist/chunks/behaviours/roles.js +51 -0
  12. package/dist/chunks/behaviours/roles.js.map +1 -0
  13. package/dist/chunks/behaviours/states/conditions.js +103 -0
  14. package/dist/chunks/behaviours/states/conditions.js.map +1 -0
  15. package/dist/chunks/behaviours/states/css.js +172 -0
  16. package/dist/chunks/behaviours/states/css.js.map +1 -0
  17. package/dist/chunks/behaviours/states/layers.js +1736 -0
  18. package/dist/chunks/behaviours/states/layers.js.map +1 -0
  19. package/dist/chunks/behaviours/states/model.js +144 -0
  20. package/dist/chunks/behaviours/states/model.js.map +1 -0
  21. package/dist/chunks/behaviours/states/tailwind.js +198 -0
  22. package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
  23. package/dist/chunks/browser.js +1352 -0
  24. package/dist/chunks/browser.js.map +1 -0
  25. package/dist/chunks/export/bundle.js +337 -0
  26. package/dist/chunks/export/bundle.js.map +1 -0
  27. package/dist/chunks/export/components/drawn.js +60 -0
  28. package/dist/chunks/export/components/drawn.js.map +1 -0
  29. package/dist/chunks/export/components/fields.js +178 -0
  30. package/dist/chunks/export/components/fields.js.map +1 -0
  31. package/dist/chunks/export/components/groups.js +297 -0
  32. package/dist/chunks/export/components/groups.js.map +1 -0
  33. package/dist/chunks/export/components/icons.js +260 -0
  34. package/dist/chunks/export/components/icons.js.map +1 -0
  35. package/dist/chunks/export/components/layers.js +1594 -0
  36. package/dist/chunks/export/components/layers.js.map +1 -0
  37. package/dist/chunks/export/index.js +477 -0
  38. package/dist/chunks/export/index.js.map +1 -0
  39. package/dist/chunks/export/storybook/component.js +448 -0
  40. package/dist/chunks/export/storybook/component.js.map +1 -0
  41. package/dist/chunks/export/storybook/export.js +410 -0
  42. package/dist/chunks/export/storybook/export.js.map +1 -0
  43. package/dist/chunks/import/html.js +406 -0
  44. package/dist/chunks/import/html.js.map +1 -0
  45. package/dist/chunks/import/jsx/dev-runtime.js +37 -0
  46. package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
  47. package/dist/chunks/tokens/cssom-validator.js +10 -0
  48. package/dist/chunks/tokens/cssom-validator.js.map +1 -0
  49. package/dist/export.d.ts +594 -0
  50. package/dist/export.js +13 -0
  51. package/dist/index.d.ts +115 -0
  52. package/dist/index.js +7 -0
  53. package/dist/jsx-dev-runtime.d.ts +8 -0
  54. package/dist/jsx-dev-runtime.js +3 -0
  55. package/dist/jsx-runtime.d.ts +20 -0
  56. package/dist/jsx-runtime.js +3 -0
  57. package/dist/rolldown-runtime.js +13 -0
  58. package/dist/runtime.d.ts +10 -0
  59. package/dist/scene-graph.d.ts +2 -0
  60. package/dist/scene-graph.js +2 -0
  61. package/dist/scene-graph2.d.ts +10 -0
  62. package/dist/styling.d.ts +93 -0
  63. package/dist/tailwind.d.ts +39 -0
  64. package/dist/types.d.ts +89 -0
  65. package/package.json +73 -4
  66. package/src/behaviours/args.ts +85 -0
  67. package/src/behaviours/controls.ts +195 -0
  68. package/src/behaviours/index.ts +11 -0
  69. package/src/behaviours/reset.ts +37 -0
  70. package/src/behaviours/roles.ts +44 -0
  71. package/src/behaviours/states/conditions.ts +105 -0
  72. package/src/behaviours/states/css.ts +123 -0
  73. package/src/behaviours/states/index.ts +4 -0
  74. package/src/behaviours/states/layers.ts +205 -0
  75. package/src/behaviours/states/model.ts +175 -0
  76. package/src/behaviours/states/names.ts +39 -0
  77. package/src/behaviours/states/tailwind.ts +148 -0
  78. package/src/behaviours/states/types.ts +56 -0
  79. package/src/browser.ts +146 -0
  80. package/src/cssom.d.ts +38 -0
  81. package/src/export/bundle.ts +461 -0
  82. package/src/export/components/drawn.ts +73 -0
  83. package/src/export/components/fields.ts +178 -0
  84. package/src/export/components/groups.ts +78 -0
  85. package/src/export/components/icons.ts +230 -0
  86. package/src/export/components/layers.ts +121 -0
  87. package/src/export/components/model.ts +544 -0
  88. package/src/export/components/properties.ts +167 -0
  89. package/src/export/components/react/fields.ts +129 -0
  90. package/src/export/components/react/index.ts +606 -0
  91. package/src/export/components/react/shared.ts +76 -0
  92. package/src/export/components/references.ts +212 -0
  93. package/src/export/components/repeats.ts +128 -0
  94. package/src/export/components/shaders.ts +125 -0
  95. package/src/export/components/styling.ts +31 -0
  96. package/src/export/components/tree.ts +72 -0
  97. package/src/export/components/vue.ts +517 -0
  98. package/src/export/css.ts +57 -0
  99. package/src/export/grid.ts +42 -0
  100. package/src/export/html.ts +163 -0
  101. package/src/export/index.ts +44 -0
  102. package/src/export/projection.ts +581 -0
  103. package/src/export/storybook/component.ts +334 -0
  104. package/src/export/storybook/export.ts +430 -0
  105. package/src/export/storybook/groups.ts +161 -0
  106. package/src/export/storybook/module.ts +319 -0
  107. package/src/export/storybook/names.ts +51 -0
  108. package/src/export/tailwind-jsx.ts +156 -0
  109. package/src/export/text.ts +415 -0
  110. package/src/import/css-text.ts +4 -0
  111. package/src/import/css-values.ts +31 -0
  112. package/src/import/flow.ts +248 -0
  113. package/src/import/html.ts +88 -0
  114. package/src/import/jsx/core.ts +130 -0
  115. package/src/import/jsx/dev-runtime.ts +8 -0
  116. package/src/import/jsx/runtime.ts +76 -0
  117. package/src/import/scene-graph.ts +582 -0
  118. package/src/import/style-attribute.ts +25 -0
  119. package/src/import/tailwind.ts +54 -0
  120. package/src/import/text.ts +518 -0
  121. package/src/index.ts +51 -0
  122. package/src/runtime/browser/runtime.ts +301 -0
  123. package/src/runtime/headless/runtime.ts +99 -0
  124. package/src/runtime/headless/styles.ts +330 -0
  125. package/src/runtime/index.ts +11 -0
  126. package/src/tokens/conditions.ts +66 -0
  127. package/src/tokens/cssom-validator.ts +8 -0
  128. package/src/tokens/custom-properties.ts +331 -0
  129. package/src/tokens/expression.ts +128 -0
  130. package/src/tokens/formula.ts +140 -0
  131. package/src/tokens/index.ts +43 -0
  132. package/src/tokens/names.ts +161 -0
  133. package/src/tokens/references.ts +201 -0
  134. package/src/tokens/stylesheet.ts +304 -0
  135. package/src/tokens/validate.ts +86 -0
  136. package/src/tokens/values.ts +44 -0
  137. package/src/types.ts +59 -0
@@ -0,0 +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,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;EAAK,GAAG,GAAG,UAAU,KAAK;CAC7E;AACF"}
@@ -0,0 +1,60 @@
1
+ import { isEqual } from "es-toolkit/predicate";
2
+ //#region src/export/components/drawn.ts
3
+ /** What a layer draws, which an instance can change without a property. */
4
+ const DRAWN = [
5
+ "fills",
6
+ "strokes",
7
+ "effects",
8
+ "opacity",
9
+ "cornerRadius",
10
+ "fontFamily",
11
+ "fontSize",
12
+ "fontWeight",
13
+ "italic"
14
+ ];
15
+ /** How a layer lays out what it holds, which an instance can change without a property. */
16
+ const LAYOUT = [
17
+ "layoutMode",
18
+ "itemSpacing",
19
+ "paddingTop",
20
+ "paddingRight",
21
+ "paddingBottom",
22
+ "paddingLeft",
23
+ "primaryAxisAlign",
24
+ "counterAxisAlign"
25
+ ];
26
+ const same = (a, b, fields) => fields.every((field) => isEqual(a[field], b[field]));
27
+ const bound = (node, field) => node.componentPropertyReferences.some((reference) => reference.field === field);
28
+ function childrenMatch(graph, drawn, main) {
29
+ const children = graph.getChildren(drawn.id);
30
+ const mains = graph.getChildren(main.id);
31
+ return children.length === mains.length && children.every((child, index) => {
32
+ const counterpart = mains.at(index);
33
+ return counterpart !== void 0 && layerMatches(graph, child, counterpart);
34
+ });
35
+ }
36
+ /**
37
+ * Whether a layer of an instance draws as its main component's does, apart from what a
38
+ * property of the component sets: the text a text property shows and what a boolean property
39
+ * shows or hides, which the component's props pass on.
40
+ */
41
+ function layerMatches(graph, drawn, main) {
42
+ if (drawn.type !== main.type) return false;
43
+ if (!bound(main, "VISIBLE") && drawn.visible !== main.visible) return false;
44
+ if (drawn.type === "TEXT" && !bound(main, "TEXT") && drawn.text !== main.text) return false;
45
+ if (drawn.type === "INSTANCE" && drawn.componentId !== main.componentId) return false;
46
+ return same(drawn, main, DRAWN) && same(drawn, main, LAYOUT) && childrenMatch(graph, drawn, main);
47
+ }
48
+ /**
49
+ * Whether an instance draws exactly as the variant it shows, so a generated component given
50
+ * its property values draws it: the same look, layout, words, and nested components, apart
51
+ * from where its parent places and sizes it. An instance with any other change, such as edited
52
+ * text no property sets or a fill of its own, draws its own layers instead.
53
+ */
54
+ function drawsAsMain(graph, instance, main) {
55
+ return same(instance, main, DRAWN) && same(instance, main, LAYOUT) && childrenMatch(graph, instance, main);
56
+ }
57
+ //#endregion
58
+ export { drawsAsMain };
59
+
60
+ //# sourceMappingURL=drawn.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"drawn.js","names":[],"sources":["../../../../src/export/components/drawn.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { ComponentPropertyReferenceField, SceneGraph, SceneNode } from '@pairdraw/scene-graph'\n\n/** What a layer draws, which an instance can change without a property. */\nconst DRAWN = [\n 'fills',\n 'strokes',\n 'effects',\n 'opacity',\n 'cornerRadius',\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'italic'\n] as const satisfies readonly (keyof SceneNode)[]\n\n/** How a layer lays out what it holds, which an instance can change without a property. */\nconst LAYOUT = [\n 'layoutMode',\n 'itemSpacing',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'primaryAxisAlign',\n 'counterAxisAlign'\n] as const satisfies readonly (keyof SceneNode)[]\n\nconst same = (a: SceneNode, b: SceneNode, fields: readonly (keyof SceneNode)[]) =>\n fields.every((field) => isEqual(a[field], b[field]))\n\nconst bound = (node: SceneNode, field: ComponentPropertyReferenceField) =>\n node.componentPropertyReferences.some((reference) => reference.field === field)\n\nfunction childrenMatch(graph: SceneGraph, drawn: SceneNode, main: SceneNode): boolean {\n const children = graph.getChildren(drawn.id)\n const mains = graph.getChildren(main.id)\n return (\n children.length === mains.length &&\n children.every((child, index) => {\n const counterpart = mains.at(index)\n return counterpart !== undefined && layerMatches(graph, child, counterpart)\n })\n )\n}\n\n/**\n * Whether a layer of an instance draws as its main component's does, apart from what a\n * property of the component sets: the text a text property shows and what a boolean property\n * shows or hides, which the component's props pass on.\n */\nfunction layerMatches(graph: SceneGraph, drawn: SceneNode, main: SceneNode): boolean {\n if (drawn.type !== main.type) return false\n if (!bound(main, 'VISIBLE') && drawn.visible !== main.visible) return false\n if (drawn.type === 'TEXT' && !bound(main, 'TEXT') && drawn.text !== main.text) return false\n if (drawn.type === 'INSTANCE' && drawn.componentId !== main.componentId) return false\n return same(drawn, main, DRAWN) && same(drawn, main, LAYOUT) && childrenMatch(graph, drawn, main)\n}\n\n/**\n * Whether an instance draws exactly as the variant it shows, so a generated component given\n * its property values draws it: the same look, layout, words, and nested components, apart\n * from where its parent places and sizes it. An instance with any other change, such as edited\n * text no property sets or a fill of its own, draws its own layers instead.\n */\nexport function drawsAsMain(graph: SceneGraph, instance: SceneNode, main: SceneNode): boolean {\n return (\n same(instance, main, DRAWN) &&\n same(instance, main, LAYOUT) &&\n childrenMatch(graph, instance, main)\n )\n}\n"],"mappings":";;;AAKA,MAAM,QAAQ;CACZ;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAGA,MAAM,SAAS;CACb;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,MAAM,QAAQ,GAAc,GAAc,WACxC,OAAO,OAAO,UAAU,QAAQ,EAAE,QAAQ,EAAE,MAAM,CAAC;AAErD,MAAM,SAAS,MAAiB,UAC9B,KAAK,4BAA4B,MAAM,cAAc,UAAU,UAAU,KAAK;AAEhF,SAAS,cAAc,OAAmB,OAAkB,MAA0B;CACpF,MAAM,WAAW,MAAM,YAAY,MAAM,EAAE;CAC3C,MAAM,QAAQ,MAAM,YAAY,KAAK,EAAE;CACvC,OACE,SAAS,WAAW,MAAM,UAC1B,SAAS,OAAO,OAAO,UAAU;EAC/B,MAAM,cAAc,MAAM,GAAG,KAAK;EAClC,OAAO,gBAAgB,KAAA,KAAa,aAAa,OAAO,OAAO,WAAW;CAC5E,CAAC;AAEL;;;;;;AAOA,SAAS,aAAa,OAAmB,OAAkB,MAA0B;CACnF,IAAI,MAAM,SAAS,KAAK,MAAM,OAAO;CACrC,IAAI,CAAC,MAAM,MAAM,SAAS,KAAK,MAAM,YAAY,KAAK,SAAS,OAAO;CACtE,IAAI,MAAM,SAAS,UAAU,CAAC,MAAM,MAAM,MAAM,KAAK,MAAM,SAAS,KAAK,MAAM,OAAO;CACtF,IAAI,MAAM,SAAS,cAAc,MAAM,gBAAgB,KAAK,aAAa,OAAO;CAChF,OAAO,KAAK,OAAO,MAAM,KAAK,KAAK,KAAK,OAAO,MAAM,MAAM,KAAK,cAAc,OAAO,OAAO,IAAI;AAClG;;;;;;;AAQA,SAAgB,YAAY,OAAmB,UAAqB,MAA0B;CAC5F,OACE,KAAK,UAAU,MAAM,KAAK,KAC1B,KAAK,UAAU,MAAM,MAAM,KAC3B,cAAc,OAAO,UAAU,IAAI;AAEvC"}
@@ -0,0 +1,178 @@
1
+ import { INPUT_RESET } from "../../behaviours/reset.js";
2
+ import { isEmptyObject } from "es-toolkit/predicate";
3
+ import { omit, pick } from "es-toolkit/object";
4
+ import { DEFAULT_NUMBER_SETTINGS, numberSettings } from "@pairdraw/scene-graph/behaviours";
5
+ import { es } from "@pairdraw/emit";
6
+ //#region src/export/components/fields.ts
7
+ /** Kinds that hold a number in a range. */
8
+ const RANGED = /* @__PURE__ */ new Set([
9
+ "slider",
10
+ "progress",
11
+ "numberField"
12
+ ]);
13
+ /** Kinds whose text layer is an input, and the text value that layer shows. */
14
+ const INPUT_VALUES = {
15
+ textField: "value",
16
+ textarea: "value",
17
+ numberField: "text"
18
+ };
19
+ /** The text value whose bound layer a kind draws as its input, if it has one. */
20
+ const inputValue = (kind) => INPUT_VALUES[kind];
21
+ /** The number a ranged kind binds, starting where the design's behaviour does. */
22
+ function rangeModel(kind, behaviour) {
23
+ if (!RANGED.has(kind)) return null;
24
+ return { ...numberSettings(behaviour, "value") ?? DEFAULT_NUMBER_SETTINGS };
25
+ }
26
+ /**
27
+ * The text a text field or textarea binds. When the design draws it filled and empty, the
28
+ * empty field shows its text property's words as a placeholder and starts empty; otherwise it
29
+ * starts with them.
30
+ */
31
+ function textModel(kind, definition, args) {
32
+ if (kind !== "textField" && kind !== "textarea") return null;
33
+ const words = typeof definition?.defaultValue === "string" ? definition.defaultValue : "";
34
+ return args.filled ? {
35
+ default: "",
36
+ placeholder: words
37
+ } : {
38
+ default: words,
39
+ placeholder: null
40
+ };
41
+ }
42
+ /** What a text layer's look is, as opposed to where it sits. */
43
+ const TEXT_LOOK = [
44
+ "color",
45
+ "opacity",
46
+ "font-family",
47
+ "font-size",
48
+ "font-style",
49
+ "font-weight",
50
+ "letter-spacing",
51
+ "line-height",
52
+ "text-decoration",
53
+ "text-transform"
54
+ ];
55
+ /**
56
+ * The input among a field's bound text layers: the one shown at rest. A layer reading other
57
+ * words is the same layer in another state; drawn while filled, its look is the typed text's,
58
+ * and the resting look becomes the placeholder's.
59
+ */
60
+ function inputLayers(bound) {
61
+ const element = bound.find((layer) => layer.base.display !== "none") ?? bound.at(0);
62
+ if (!element) return null;
63
+ const replaced = bound.filter((layer) => layer !== element);
64
+ const filled = replaced.find((layer) => layer.rules.some((rule) => rule.conditions.some((condition) => condition.type === "filled")));
65
+ if (filled) {
66
+ const typed = pick(omit(filled.base, ["display"]), TEXT_LOOK);
67
+ element.rules.push({
68
+ conditions: [],
69
+ pseudo: "placeholder",
70
+ style: pick(element.base, TEXT_LOOK)
71
+ });
72
+ element.base = {
73
+ ...element.base,
74
+ ...typed
75
+ };
76
+ element.rules = element.rules.filter((rule) => !rule.style.display);
77
+ }
78
+ element.base = {
79
+ ...INPUT_RESET,
80
+ ...omit(element.base, ["display", "white-space"])
81
+ };
82
+ return {
83
+ element,
84
+ replaced
85
+ };
86
+ }
87
+ /** What the library sets on a part it places itself, which the design's drawn place gives way to. */
88
+ const PLACED = {
89
+ slider: {
90
+ range: [
91
+ "left",
92
+ "right",
93
+ "width"
94
+ ],
95
+ thumb: [
96
+ "left",
97
+ "right",
98
+ "transform"
99
+ ]
100
+ },
101
+ progress: { indicator: ["width"] }
102
+ };
103
+ /**
104
+ * Gives a number field's input, which the design draws as words that hug their value, room
105
+ * for its longest value rather than an input's default width, and no spinner of the browser's
106
+ * own, since the design draws its steppers.
107
+ */
108
+ function numberInput(input, range) {
109
+ if (!input || !range) return;
110
+ const { element } = input;
111
+ element.base = {
112
+ ...element.base,
113
+ appearance: "textfield"
114
+ };
115
+ element.rules.push({
116
+ conditions: [],
117
+ pseudo: "-webkit-inner-spin-button",
118
+ style: {
119
+ appearance: "none",
120
+ margin: "0"
121
+ }
122
+ });
123
+ if (Object.hasOwn(element.base, "width")) return;
124
+ const digits = Math.max(String(range.min).length, String(range.max).length);
125
+ element.base = {
126
+ ...element.base,
127
+ width: `${digits + 1}ch`
128
+ };
129
+ }
130
+ /** Kinds whose root Reka and Radix render as a span, which a size alone does not lay out. */
131
+ const SPAN_ROOTS = /* @__PURE__ */ new Set(["slider"]);
132
+ /** Lays a span root out as the block the design draws, unless the design says otherwise. */
133
+ function blockRoot(kind, root) {
134
+ if (SPAN_ROOTS.has(kind) && !Object.hasOwn(root.base, "display")) root.base = {
135
+ ...root.base,
136
+ display: "block"
137
+ };
138
+ }
139
+ /** Drops the place a slider or progress bar draws its moving parts at, which the value sets. */
140
+ function freePlacedParts(kind, parts) {
141
+ for (const [element, part] of parts) {
142
+ const placed = PLACED[kind]?.[part];
143
+ if (!placed) continue;
144
+ element.base = omit(element.base, placed);
145
+ element.rules = element.rules.map((rule) => ({
146
+ ...rule,
147
+ style: omit(rule.style, placed)
148
+ })).filter((rule) => !isEmptyObject(rule.style));
149
+ }
150
+ }
151
+ const PERCENT = es.parseExpression(`({ width: \`\${$share}%\` })`);
152
+ /**
153
+ * A progress bar's indicator style, reaching the value's share of its range, the value held
154
+ * within it: the value itself for a range of 0 to 100. Null for an empty range, which has no
155
+ * share.
156
+ */
157
+ function progressWidth(range, value) {
158
+ const span = range.max - range.min;
159
+ if (span <= 0) return null;
160
+ const clamped = es.fill(es.parseExpression("Math.min($max, Math.max($min, $value))"), {
161
+ $value: value,
162
+ $min: es.number(range.min),
163
+ $max: es.number(range.max)
164
+ });
165
+ const offset = range.min === 0 ? clamped : es.fill(es.parseExpression("$value - $min"), {
166
+ $value: clamped,
167
+ $min: es.number(range.min)
168
+ });
169
+ const share = span === 100 ? offset : es.fill(es.parseExpression("(($offset) / $span) * 100"), {
170
+ $offset: offset,
171
+ $span: es.number(span)
172
+ });
173
+ return es.fill(PERCENT, { $share: share });
174
+ }
175
+ //#endregion
176
+ export { blockRoot, freePlacedParts, inputLayers, inputValue, numberInput, progressWidth, rangeModel, textModel };
177
+
178
+ //# sourceMappingURL=fields.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fields.js","names":[],"sources":["../../../../src/export/components/fields.ts"],"sourcesContent":["import type { BehaviourArgs } from '#dom-css/behaviours/args'\nimport { INPUT_RESET } from '#dom-css/behaviours/reset'\nimport type { StateElement } from '#dom-css/behaviours/states/types'\nimport { omit, pick } from 'es-toolkit/object'\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport { es } from '@pairdraw/emit'\nimport type { ComponentPropertyDefinition } from '@pairdraw/scene-graph'\nimport {\n DEFAULT_NUMBER_SETTINGS,\n numberSettings,\n type Behaviour\n} from '@pairdraw/scene-graph/behaviours'\n\nimport type { GeneratedKind, RangeModel, TextModel } from './model'\n\n/** Kinds that hold a number in a range. */\nconst RANGED: ReadonlySet<GeneratedKind> = new Set(['slider', 'progress', 'numberField'])\n\n/** Kinds whose text layer is an input, and the text value that layer shows. */\nconst INPUT_VALUES: Partial<Record<GeneratedKind, string>> = {\n textField: 'value',\n textarea: 'value',\n numberField: 'text'\n}\n\n/** The text value whose bound layer a kind draws as its input, if it has one. */\nexport const inputValue = (kind: GeneratedKind): string | undefined => INPUT_VALUES[kind]\n\n/** The number a ranged kind binds, starting where the design's behaviour does. */\nexport function rangeModel(kind: GeneratedKind, behaviour: Behaviour): RangeModel | null {\n if (!RANGED.has(kind)) return null\n return { ...(numberSettings(behaviour, 'value') ?? DEFAULT_NUMBER_SETTINGS) }\n}\n\n/**\n * The text a text field or textarea binds. When the design draws it filled and empty, the\n * empty field shows its text property's words as a placeholder and starts empty; otherwise it\n * starts with them.\n */\nexport function textModel(\n kind: GeneratedKind,\n definition: ComponentPropertyDefinition | undefined,\n args: BehaviourArgs\n): TextModel | null {\n if (kind !== 'textField' && kind !== 'textarea') return null\n const words = typeof definition?.defaultValue === 'string' ? definition.defaultValue : ''\n return args.filled ? { default: '', placeholder: words } : { default: words, placeholder: null }\n}\n\n/** A field's text layer drawn as its input, and the same layer in other words, which it replaces. */\nexport interface InputLayers {\n element: StateElement\n replaced: StateElement[]\n}\n\n/** What a text layer's look is, as opposed to where it sits. */\nconst TEXT_LOOK = [\n 'color',\n 'opacity',\n 'font-family',\n 'font-size',\n 'font-style',\n 'font-weight',\n 'letter-spacing',\n 'line-height',\n 'text-decoration',\n 'text-transform'\n]\n\n/**\n * The input among a field's bound text layers: the one shown at rest. A layer reading other\n * words is the same layer in another state; drawn while filled, its look is the typed text's,\n * and the resting look becomes the placeholder's.\n */\nexport function inputLayers(bound: readonly StateElement[]): InputLayers | null {\n const element = bound.find((layer) => layer.base.display !== 'none') ?? bound.at(0)\n if (!element) return null\n const replaced = bound.filter((layer) => layer !== element)\n const filled = replaced.find((layer) =>\n layer.rules.some((rule) => rule.conditions.some((condition) => condition.type === 'filled'))\n )\n if (filled) {\n const typed = pick(omit(filled.base, ['display']), TEXT_LOOK)\n element.rules.push({\n conditions: [],\n pseudo: 'placeholder',\n style: pick(element.base, TEXT_LOOK)\n })\n element.base = { ...element.base, ...typed }\n // The layer shows in every state now, so states that hid or showed it no longer do.\n element.rules = element.rules.filter((rule) => !rule.style.display)\n }\n element.base = { ...INPUT_RESET, ...omit(element.base, ['display', 'white-space']) }\n return { element, replaced }\n}\n\n/** What the library sets on a part it places itself, which the design's drawn place gives way to. */\nconst PLACED: Partial<Record<GeneratedKind, Record<string, readonly string[]>>> = {\n slider: { range: ['left', 'right', 'width'], thumb: ['left', 'right', 'transform'] },\n progress: { indicator: ['width'] }\n}\n\n/**\n * Gives a number field's input, which the design draws as words that hug their value, room\n * for its longest value rather than an input's default width, and no spinner of the browser's\n * own, since the design draws its steppers.\n */\nexport function numberInput(input: InputLayers | null, range: RangeModel | null): void {\n if (!input || !range) return\n const { element } = input\n element.base = { ...element.base, appearance: 'textfield' }\n element.rules.push({\n conditions: [],\n pseudo: '-webkit-inner-spin-button',\n style: { appearance: 'none', margin: '0' }\n })\n if (Object.hasOwn(element.base, 'width')) return\n const digits = Math.max(String(range.min).length, String(range.max).length)\n element.base = { ...element.base, width: `${digits + 1}ch` }\n}\n\n/** Kinds whose root Reka and Radix render as a span, which a size alone does not lay out. */\nconst SPAN_ROOTS: ReadonlySet<GeneratedKind> = new Set(['slider'])\n\n/** Lays a span root out as the block the design draws, unless the design says otherwise. */\nexport function blockRoot(kind: GeneratedKind, root: StateElement): void {\n if (SPAN_ROOTS.has(kind) && !Object.hasOwn(root.base, 'display'))\n root.base = { ...root.base, display: 'block' }\n}\n\n/** Drops the place a slider or progress bar draws its moving parts at, which the value sets. */\nexport function freePlacedParts(\n kind: GeneratedKind,\n parts: ReadonlyMap<StateElement, string>\n): void {\n for (const [element, part] of parts) {\n const placed = PLACED[kind]?.[part]\n if (!placed) continue\n element.base = omit(element.base, placed)\n element.rules = element.rules\n .map((rule) => ({ ...rule, style: omit(rule.style, placed) }))\n .filter((rule) => !isEmptyObject(rule.style))\n }\n}\n\nconst PERCENT = es.parseExpression(`({ width: \\`\\${$share}%\\` })`)\n\n/**\n * A progress bar's indicator style, reaching the value's share of its range, the value held\n * within it: the value itself for a range of 0 to 100. Null for an empty range, which has no\n * share.\n */\nexport function progressWidth(range: RangeModel, value: es.SyntaxNode): es.SyntaxNode | null {\n const span = range.max - range.min\n if (span <= 0) return null\n // A value outside the range fills the indicator no further than its ends.\n const clamped = es.fill(es.parseExpression('Math.min($max, Math.max($min, $value))'), {\n $value: value,\n $min: es.number(range.min),\n $max: es.number(range.max)\n })\n const offset =\n range.min === 0\n ? clamped\n : es.fill(es.parseExpression('$value - $min'), {\n $value: clamped,\n $min: es.number(range.min)\n })\n const share =\n span === 100\n ? offset\n : es.fill(es.parseExpression('(($offset) / $span) * 100'), {\n $offset: offset,\n $span: es.number(span)\n })\n return es.fill(PERCENT, { $share: share })\n}\n"],"mappings":";;;;;;;AAiBA,MAAM,yBAAqC,IAAI,IAAI;CAAC;CAAU;CAAY;AAAa,CAAC;;AAGxF,MAAM,eAAuD;CAC3D,WAAW;CACX,UAAU;CACV,aAAa;AACf;;AAGA,MAAa,cAAc,SAA4C,aAAa;;AAGpF,SAAgB,WAAW,MAAqB,WAAyC;CACvF,IAAI,CAAC,OAAO,IAAI,IAAI,GAAG,OAAO;CAC9B,OAAO,EAAE,GAAI,eAAe,WAAW,OAAO,KAAK,wBAAyB;AAC9E;;;;;;AAOA,SAAgB,UACd,MACA,YACA,MACkB;CAClB,IAAI,SAAS,eAAe,SAAS,YAAY,OAAO;CACxD,MAAM,QAAQ,OAAO,YAAY,iBAAiB,WAAW,WAAW,eAAe;CACvF,OAAO,KAAK,SAAS;EAAE,SAAS;EAAI,aAAa;CAAM,IAAI;EAAE,SAAS;EAAO,aAAa;CAAK;AACjG;;AASA,MAAM,YAAY;CAChB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;;;;;AAOA,SAAgB,YAAY,OAAoD;CAC9E,MAAM,UAAU,MAAM,MAAM,UAAU,MAAM,KAAK,YAAY,MAAM,KAAK,MAAM,GAAG,CAAC;CAClF,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,WAAW,MAAM,QAAQ,UAAU,UAAU,OAAO;CAC1D,MAAM,SAAS,SAAS,MAAM,UAC5B,MAAM,MAAM,MAAM,SAAS,KAAK,WAAW,MAAM,cAAc,UAAU,SAAS,QAAQ,CAAC,CAC7F;CACA,IAAI,QAAQ;EACV,MAAM,QAAQ,KAAK,KAAK,OAAO,MAAM,CAAC,SAAS,CAAC,GAAG,SAAS;EAC5D,QAAQ,MAAM,KAAK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;;AAGA,SAAgB,gBACd,MACA,OACM;CACN,KAAK,MAAM,CAAC,SAAS,SAAS,OAAO;EACnC,MAAM,SAAS,OAAO,KAAK,GAAG;EAC9B,IAAI,CAAC,QAAQ;EACb,QAAQ,OAAO,KAAK,QAAQ,MAAM,MAAM;EACxC,QAAQ,QAAQ,QAAQ,MACrB,KAAK,UAAU;GAAE,GAAG;GAAM,OAAO,KAAK,KAAK,OAAO,MAAM;EAAE,EAAE,CAAC,CAC7D,QAAQ,SAAS,CAAC,cAAc,KAAK,KAAK,CAAC;CAChD;AACF;AAEA,MAAM,UAAU,GAAG,gBAAgB,8BAA8B;;;;;;AAOjE,SAAgB,cAAc,OAAmB,OAA4C;CAC3F,MAAM,OAAO,MAAM,MAAM,MAAM;CAC/B,IAAI,QAAQ,GAAG,OAAO;CAEtB,MAAM,UAAU,GAAG,KAAK,GAAG,gBAAgB,wCAAwC,GAAG;EACpF,QAAQ;EACR,MAAM,GAAG,OAAO,MAAM,GAAG;EACzB,MAAM,GAAG,OAAO,MAAM,GAAG;CAC3B,CAAC;CACD,MAAM,SACJ,MAAM,QAAQ,IACV,UACA,GAAG,KAAK,GAAG,gBAAgB,eAAe,GAAG;EAC3C,QAAQ;EACR,MAAM,GAAG,OAAO,MAAM,GAAG;CAC3B,CAAC;CACP,MAAM,QACJ,SAAS,MACL,SACA,GAAG,KAAK,GAAG,gBAAgB,2BAA2B,GAAG;EACvD,SAAS;EACT,OAAO,GAAG,OAAO,IAAI;CACvB,CAAC;CACP,OAAO,GAAG,KAAK,SAAS,EAAE,QAAQ,MAAM,CAAC;AAC3C"}
@@ -0,0 +1,297 @@
1
+ import { layerKind } from "../../behaviours/states/layers.js";
2
+ import { difference } from "../../behaviours/states/model.js";
3
+ import { claimName } from "../../behaviours/states/css.js";
4
+ import { drawsAsMain } from "./drawn.js";
5
+ import { isIconModified, isNamedIcon, readIcon } from "@pairdraw/scene-graph/icons";
6
+ import { isEmptyObject } from "es-toolkit/predicate";
7
+ import { behaviourOwner, findLayerByPath } from "@pairdraw/scene-graph/behaviours";
8
+ import { instanceMainComponent } from "@pairdraw/scene-graph/instances";
9
+ import { findComponentPropertyTargets } from "@pairdraw/scene-graph/components";
10
+ import { kebabCase } from "es-toolkit/string";
11
+ //#region src/export/components/references.ts
12
+ /**
13
+ * How a parent places a layer, as opposed to how the layer looks. A component used in place of
14
+ * a layer keeps its own look and state styles; the parent only places it.
15
+ */
16
+ const PLACEMENT = /^(position|inset|left|top|right|bottom|(min-|max-)?(width|height)|margin(-.+)?|flex(-(grow|shrink|basis))?|align-self|justify-self|order|grid-(area|column|row)(-.+)?|transform(-origin)?|rotate|translate|scale|z-index)$/;
17
+ /** Whether a declaration places a layer rather than drawing it. */
18
+ const isPlacement = (property) => PLACEMENT.test(property);
19
+ /** Whether a declaration hides or shows a layer by state, which the parent decides too. */
20
+ const isVisibility = (property, value) => property === "display" && (value === "none" || value === "revert");
21
+ /** Keeps only where the parent places a layer, and whether a state shows it. */
22
+ function placementOnly(element) {
23
+ const placement = (style) => Object.fromEntries(Object.entries(style).filter(([property, value]) => isPlacement(property) || isVisibility(property, value)));
24
+ element.base = placement(element.base);
25
+ element.rules = element.rules.map((rule) => ({
26
+ ...rule,
27
+ style: placement(rule.style)
28
+ })).filter((rule) => !isEmptyObject(rule.style));
29
+ }
30
+ /** The set a component belongs to, or the component itself when it stands alone. */
31
+ function ownerId(graph, component) {
32
+ const parent = component.parentId ? graph.getNode(component.parentId) : void 0;
33
+ return parent?.type === "COMPONENT_SET" ? parent.id : component.id;
34
+ }
35
+ /**
36
+ * The words an instance shows for a text property: an assignment that overrides the default,
37
+ * else what its bound text layer reads, which a direct edit changes, else the assignment.
38
+ */
39
+ function shownText(graph, instance, propertyId) {
40
+ const assigned = instance.componentPropertyAssignments[propertyId];
41
+ const main = instanceMainComponent(graph, instance);
42
+ const definition = (main && behaviourOwner(graph, main))?.componentPropertyDefinitions.find((item) => item.id === propertyId);
43
+ if (typeof assigned === "string" && assigned !== definition?.defaultValue) return assigned;
44
+ return findComponentPropertyTargets(graph, instance, propertyId).find((item) => item.field === "TEXT" && item.node.type === "TEXT")?.node.text ?? (typeof assigned === "string" ? assigned : void 0);
45
+ }
46
+ /**
47
+ * What `instance` sets on `component`: the values it is drawn with that differ from defaults,
48
+ * and whether it is drawn on: its model, or for a group's item the value that marks it chosen.
49
+ */
50
+ function referenceValues(graph, instance, component) {
51
+ const values = instanceMainComponent(graph, instance)?.componentPropertyValues ?? {};
52
+ const props = [];
53
+ let model = null;
54
+ for (const [property, arg] of component.args.booleans) {
55
+ if (values[property] !== arg.on) continue;
56
+ if (arg.name === component.model || component.valueProp && arg.name !== "disabled") model = arg.name;
57
+ else props.push({
58
+ name: arg.name,
59
+ value: true
60
+ });
61
+ }
62
+ const states = component.args.states;
63
+ if (states?.disabled && values[states.property] === states.disabled) props.push({
64
+ name: "disabled",
65
+ value: true
66
+ });
67
+ for (const prop of component.props) {
68
+ const value = values[prop.property];
69
+ if (Object.hasOwn(values, prop.property) && value !== prop.default) props.push({
70
+ name: prop.name,
71
+ value
72
+ });
73
+ }
74
+ for (const text of component.texts) {
75
+ const value = shownText(graph, instance, text.id);
76
+ if (value !== void 0 && value !== text.default) props.push({
77
+ name: text.name,
78
+ value
79
+ });
80
+ }
81
+ for (const prop of component.booleans) {
82
+ const assignments = instance.componentPropertyAssignments;
83
+ const value = Object.hasOwn(assignments, prop.id) ? assignments[prop.id] === "true" : prop.default;
84
+ if (value !== prop.default) props.push({
85
+ name: prop.name,
86
+ value
87
+ });
88
+ }
89
+ return {
90
+ props,
91
+ model
92
+ };
93
+ }
94
+ /**
95
+ * What the layer at `element` uses in place of drawing itself, if anything, read from the first
96
+ * variant that draws it as that element: the rest state, or the one that shows it, such as open
97
+ * content.
98
+ */
99
+ function usedLayer(graph, variantIds, element, references) {
100
+ const path = element.key.split("\0")[0] ?? "";
101
+ const node = variantIds.map((id) => findLayerByPath(graph, id, path)).find((found) => found !== void 0 && layerKind(graph, found) === element.kind);
102
+ if (!node) return null;
103
+ const main = node.type === "INSTANCE" ? instanceMainComponent(graph, node) : void 0;
104
+ const component = main && drawsAsMain(graph, node, main) ? references.get(ownerId(graph, main)) : void 0;
105
+ if (component) return {
106
+ type: "reference",
107
+ component: component.name,
108
+ ...referenceValues(graph, node, component)
109
+ };
110
+ const icon = readIcon(node);
111
+ return icon && isNamedIcon(icon) && !isIconModified(graph, node) ? {
112
+ type: "icon",
113
+ icon: icon.name
114
+ } : null;
115
+ }
116
+ /**
117
+ * The layers of a set's merged markup that are used rather than drawn: instances of other
118
+ * generated components, and icons from a set, read from the variants in order, the rest state
119
+ * first. Their own layers are dropped from the markup and the styles, which belong to the
120
+ * component or the icon.
121
+ */
122
+ function referencedLayers(graph, root, variantIds, references, taken = /* @__PURE__ */ new Map()) {
123
+ const used = /* @__PURE__ */ new Map();
124
+ const visit = (element) => {
125
+ for (const child of element.children) {
126
+ if (child.type !== "element" || taken.has(child)) continue;
127
+ const layer = usedLayer(graph, variantIds, child, references);
128
+ if (!layer) {
129
+ visit(child);
130
+ continue;
131
+ }
132
+ used.set(child, layer);
133
+ child.children = [];
134
+ if (layer.type === "reference") placementOnly(child);
135
+ }
136
+ };
137
+ visit(root);
138
+ return used;
139
+ }
140
+ //#endregion
141
+ //#region src/export/components/repeats.ts
142
+ /** The words a layer reads, joined across its text. */
143
+ function textOf(node) {
144
+ if (node.type === "text") return node.text;
145
+ return node.children.map(textOf).join(" ");
146
+ }
147
+ const elementsOf = (element) => (element?.children ?? []).filter((child) => child.type === "element");
148
+ /**
149
+ * The value each label stands for: the label as a slug, such as `account`, apart from the
150
+ * others, or its position when it has no words.
151
+ */
152
+ function slugValues(labels) {
153
+ const taken = /* @__PURE__ */ new Set();
154
+ return labels.map((label, index) => claimName(kebabCase(label) || String(index), taken));
155
+ }
156
+ /**
157
+ * Tabs' triggers, the layers in its list, and its panels, the layers in its panels slot, each
158
+ * with the value of the tab it belongs to, matched by position. The tabs start on the first.
159
+ */
160
+ function tabParts(parts) {
161
+ const partElement = (id) => [...parts].find(([, part]) => part === id)?.[0];
162
+ const triggers = elementsOf(partElement("list"));
163
+ const values = slugValues(triggers.map(textOf));
164
+ const repeated = /* @__PURE__ */ new Map();
165
+ for (const [index, trigger] of triggers.entries()) repeated.set(trigger, {
166
+ part: "trigger",
167
+ value: values[index] ?? String(index)
168
+ });
169
+ for (const [index, panel] of elementsOf(partElement("panels")).entries()) {
170
+ const value = values.at(index);
171
+ if (value !== void 0) repeated.set(panel, {
172
+ part: "content",
173
+ value
174
+ });
175
+ }
176
+ const first = values.at(0);
177
+ return {
178
+ repeated,
179
+ choice: first === void 0 ? null : {
180
+ options: values,
181
+ default: first
182
+ }
183
+ };
184
+ }
185
+ /** How `drawn` looks different from `base`, leaving out where each is placed. */
186
+ function lookChange(base, drawn) {
187
+ const changed = Object.entries(difference(base, drawn));
188
+ return Object.fromEntries(changed.filter(([property]) => !isPlacement(property)));
189
+ }
190
+ /** `base` with `change` applied, where `unset` drops a declaration. */
191
+ function applied(base, change) {
192
+ return Object.fromEntries([...Object.entries(base).filter(([property]) => change[property] !== "unset"), ...Object.entries(change).filter(([, value]) => value !== "unset")]);
193
+ }
194
+ /** The layer of `into` where `from` has `child`: the same name, and the same one of that name. */
195
+ function counterpart(child, from, into) {
196
+ const named = (element) => elementsOf(element).filter((item) => item.name === child.name);
197
+ return named(into).at(named(from).indexOf(child));
198
+ }
199
+ /**
200
+ * Tabs draw the first trigger chosen and the others not. Every trigger rests with the look of
201
+ * the others and takes the first one's, layer by layer, while Reka or Radix marks it active;
202
+ * each keeps its own place. A layer is matched across triggers by name, and one without a
203
+ * counterpart keeps its own styles.
204
+ */
205
+ function activeTriggers(repeated) {
206
+ const triggers = [...repeated].filter(([, item]) => item.part === "trigger").map(([el]) => el);
207
+ const first = triggers.at(0);
208
+ const second = triggers.at(1);
209
+ if (!first || !second) return;
210
+ const [active, inactive] = structuredClone([first, second]);
211
+ for (const trigger of triggers) {
212
+ const visit = (layer, drawn, other) => {
213
+ if (trigger === first) layer.base = applied(layer.base, lookChange(drawn.base, other.base));
214
+ const look = lookChange(layer.base, drawn.base);
215
+ if (!isEmptyObject(look)) layer.rules.push({
216
+ conditions: [{
217
+ type: "state",
218
+ value: "active"
219
+ }],
220
+ on: trigger,
221
+ style: look
222
+ });
223
+ for (const child of elementsOf(layer)) {
224
+ const drawnChild = counterpart(child, layer, drawn);
225
+ const otherChild = counterpart(child, layer, other);
226
+ if (drawnChild && otherChild) visit(child, drawnChild, otherChild);
227
+ }
228
+ };
229
+ visit(trigger, active, inactive);
230
+ }
231
+ }
232
+ //#endregion
233
+ //#region src/export/components/groups.ts
234
+ /** Groups whose items are their own primitive inside the group, as Reka and Radix have them. */
235
+ const GROUP_ITEMS = {
236
+ radioGroup: "radioGroupItem",
237
+ toggleGroup: "toggleGroupItem",
238
+ accordion: "accordionItem"
239
+ };
240
+ const isGroup = (kind) => Object.hasOwn(GROUP_ITEMS, kind);
241
+ /**
242
+ * A group's items: the component they share, generated as the group's item primitive, and
243
+ * each item in the items slot as a use of it with the value it stands for. The group chooses
244
+ * among those values, starting on the item the design draws on, or none.
245
+ */
246
+ function groupItems(graph, variantIds, itemsElement, build) {
247
+ const elements = (itemsElement?.children ?? []).filter((child) => child.type === "element");
248
+ const instances = elements.map((element) => {
249
+ const path = element.key.split("\0")[0] ?? "";
250
+ const node = variantIds.map((id) => findLayerByPath(graph, id, path)).find((found) => found?.type === "INSTANCE");
251
+ const main = node && instanceMainComponent(graph, node);
252
+ return node && main ? {
253
+ node,
254
+ owner: behaviourOwner(graph, main)
255
+ } : null;
256
+ });
257
+ const owner = instances.find((instance) => instance?.owner)?.owner;
258
+ const item = owner && build(owner);
259
+ if (!owner || !item) return null;
260
+ const label = item.texts.at(0);
261
+ const values = slugValues(elements.map((element, index) => {
262
+ const node = instances[index]?.node;
263
+ return label && node && shownText(graph, node, label.id) || textOf(element);
264
+ }));
265
+ const used = /* @__PURE__ */ new Map();
266
+ let chosen = null;
267
+ for (const [index, element] of elements.entries()) {
268
+ const instance = instances[index];
269
+ const value = values.at(index);
270
+ if (instance?.owner?.id !== owner.id || value === void 0) continue;
271
+ const { props, model } = referenceValues(graph, instance.node, item);
272
+ if (model) chosen ??= value;
273
+ used.set(element, {
274
+ type: "reference",
275
+ component: item.name,
276
+ props: [{
277
+ name: "value",
278
+ value
279
+ }, ...props],
280
+ model: null
281
+ });
282
+ element.children = [];
283
+ placementOnly(element);
284
+ }
285
+ return {
286
+ item,
287
+ used,
288
+ choice: {
289
+ options: values,
290
+ default: chosen
291
+ }
292
+ };
293
+ }
294
+ //#endregion
295
+ export { GROUP_ITEMS, activeTriggers, groupItems, isGroup, referencedLayers, tabParts };
296
+
297
+ //# sourceMappingURL=groups.js.map