@pairdraw/dom-css 0.18.0 → 0.19.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.
@@ -1 +1 @@
1
- {"version":3,"file":"html.js","names":["parse","parse"],"sources":["../../../src/import/style-attribute.ts","../../../src/runtime/headless/styles.ts","../../../src/runtime/headless/runtime.ts","../../../src/runtime/index.ts","../../../src/import/tailwind.ts","../../../src/import/html.ts"],"sourcesContent":["import { parse } from '@acemir/cssom'\nimport type { CSSStyleRuleLike } from '@acemir/cssom'\n\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction firstStyleRule(cssText: string): CSSStyleRuleLike | null {\n const [rule] = parse(cssText).cssRules\n if (!rule || typeof rule !== 'object' || !('style' in rule)) return null\n return rule as CSSStyleRuleLike\n}\n\nexport function parseStyleAttribute(value: string | undefined): DesignStyleDeclaration | undefined {\n if (!value) return undefined\n\n const rule = firstStyleRule(`*{${value}}`)\n if (!rule) return undefined\n\n const style: DesignStyleDeclaration = {}\n for (const property of Array.from(rule.style)) {\n const propertyValue = rule.style.getPropertyValue(property)\n if (propertyValue) style[property] = propertyValue\n }\n\n return Object.keys(style).length > 0 ? style : undefined\n}\n","import type {\n DesignDocument,\n DesignElement,\n DesignNode,\n DesignStyleDeclaration\n} from '#dom-css/types'\nimport {\n parse,\n type CSSGroupingRuleLike,\n type CSSStyleDeclarationLike,\n type CSSStyleRuleLike\n} from '@acemir/cssom'\n\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber, splitCSSValue } from '@pairdraw/scene-graph/css'\n\ninterface HeadlessCSSRule {\n selector: string\n specificity: number\n order: number\n /** Declared values with `var()` unresolved, so each element resolves them in its own scope. */\n declarations: DesignStyleDeclaration\n}\n\ninterface ParsedHeadlessCSS {\n rules: HeadlessCSSRule[]\n customProperties: DesignStyleDeclaration\n}\n\ninterface AncestorContext {\n element: DesignElement\n parent: AncestorContext | null\n}\n\nconst INHERITED_PROPERTIES = new Set([\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'line-height'\n])\n\n/** Declared values as written, before custom properties and shorthands are resolved. */\nfunction declarationsOf(style: CSSStyleDeclarationLike): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {\n const value = style.getPropertyValue(property).trim()\n if (property && value) result[property] = value\n }\n return result\n}\n\nfunction resolveDeclarations(\n declarations: DesignStyleDeclaration,\n customProperties: DesignStyleDeclaration\n): DesignStyleDeclaration {\n const resolved: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(declarations)) {\n const resolvedValue = resolveCSSValue(value, customProperties)\n if (resolvedValue) resolved[property] = resolvedValue\n }\n return expandStyleShorthands(resolved)\n}\n\n/** Adds the custom properties a declaration block sets, resolved against those already in scope. */\nfunction declareCustomProperties(\n scope: DesignStyleDeclaration,\n declarations: DesignStyleDeclaration\n): void {\n for (const [name, value] of Object.entries(declarations)) {\n if (!name.startsWith('--')) continue\n const resolved = resolveCSSValue(value, scope)\n if (resolved) scope[name] = resolved\n }\n}\n\nfunction isStyleRule(rule: unknown): rule is CSSStyleRuleLike {\n return (\n typeof rule === 'object' &&\n rule !== null &&\n 'selectorText' in rule &&\n 'style' in rule &&\n typeof rule.selectorText === 'string'\n )\n}\n\nfunction isGroupingRule(rule: unknown): rule is CSSGroupingRuleLike {\n return (\n typeof rule === 'object' && rule !== null && 'cssRules' in rule && Array.isArray(rule.cssRules)\n )\n}\n\nfunction collectStyleRules(rules: unknown[]): CSSStyleRuleLike[] {\n return rules.flatMap((rule) => {\n if (isStyleRule(rule)) return [rule]\n if (isGroupingRule(rule)) return collectStyleRules(rule.cssRules)\n return []\n })\n}\n\nfunction parseRules(cssText: string): ParsedHeadlessCSS {\n let order = 0\n const sheet = parse(cssText)\n const styleRules = collectStyleRules(sheet.cssRules)\n const customProperties = collectCustomProperties(styleRules)\n const rules = styleRules.flatMap((rule) => {\n const declarations = declarationsOf(rule.style)\n return rule.selectorText\n .split(',')\n .map((selector) => selector.trim())\n .filter((selector) => selector.length > 0)\n .map((selector) => ({\n selector,\n specificity: selectorSpecificity(selector),\n order: order++,\n declarations\n }))\n })\n return { rules, customProperties }\n}\n\nfunction collectCustomProperties(rules: CSSStyleRuleLike[]): DesignStyleDeclaration {\n const customProperties: DesignStyleDeclaration = {}\n for (const rule of rules) {\n if (!rule.selectorText.split(',').some((selector) => selector.trim() === ':root')) continue\n declareCustomProperties(customProperties, declarationsOf(rule.style))\n }\n return customProperties\n}\n\nfunction resolveCSSValue(value: string, customProperties: DesignStyleDeclaration): string {\n return resolveSimpleCalc(resolveVariables(value, customProperties))\n}\n\nconst CUSTOM_PROPERTY_NAME = /^--[\\w-]+$/\n\n/** `var()` references as their values; a fallback can hold parentheses and other `var()`s. */\nfunction resolveVariables(value: string, customProperties: DesignStyleDeclaration): string {\n let result = ''\n let index = 0\n for (;;) {\n const start = value.indexOf('var(', index)\n const end = start === -1 ? -1 : closingParenthesis(value, start + 3)\n if (end === -1) return result + value.slice(index)\n const inner = value.slice(start + 4, end)\n const comma = inner.indexOf(',')\n const name = (comma === -1 ? inner : inner.slice(0, comma)).trim()\n const declared: string | undefined = Object.hasOwn(customProperties, name)\n ? customProperties[name]\n : undefined\n const fallback = comma === -1 ? '' : inner.slice(comma + 1).trim()\n result += value.slice(index, start)\n result += CUSTOM_PROPERTY_NAME.test(name)\n ? (declared ?? resolveVariables(fallback, customProperties))\n : value.slice(start, end + 1)\n index = end + 1\n }\n}\n\n/** The index of the `)` closing the `(` at `open`, or -1 when it is never closed. */\nfunction closingParenthesis(value: string, open: number): number {\n let depth = 0\n for (let index = open; index < value.length; index++) {\n if (value[index] === '(') depth++\n else if (value[index] === ')' && --depth === 0) return index\n }\n return -1\n}\n\n/** `calc()` of a product, with the length on either side, as pixels. */\nfunction resolveSimpleCalc(value: string): string {\n const calc = /^calc\\(\\s*([-\\d.]+)(rem|px)?\\s*\\*\\s*([-\\d.]+)(rem|px)?\\s*\\)$/.exec(value)\n if (!calc?.[1] || !calc[3] || (calc[2] && calc[4])) return value\n\n const left = Number.parseFloat(calc[1])\n const right = Number.parseFloat(calc[3])\n // An unmatched group is undefined at run time, though the match array types it as a string.\n const unit = calc[2] || calc[4] || 'px'\n if (!Number.isFinite(left) || !Number.isFinite(right)) return value\n return `${unit === 'rem' ? left * right * 16 : left * right}px`\n}\n\nconst BORDER_STYLES = new Set([\n 'none',\n 'hidden',\n 'dotted',\n 'dashed',\n 'solid',\n 'double',\n 'groove',\n 'ridge',\n 'inset',\n 'outset'\n])\n\n/**\n * Shorthands as the longhands they set, in declaration order, so a later declaration wins over\n * an earlier one whether it is a shorthand, a logical side, or a single side, as in CSS.\n */\nfunction expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(style)) {\n result[property] = value\n Object.assign(result, longhandsOf(property, value))\n }\n return result\n}\n\nfunction longhandsOf(property: string, value: string): DesignStyleDeclaration {\n if (property === 'margin' || property === 'padding') return boxSides(property, value)\n const logical = /^(margin|padding)-(inline|block)$/u.exec(property)\n if (logical) return logicalSides(property, value, logical[2] === 'inline')\n if (property === 'border') return borderLonghands(value)\n if (property === 'background') {\n const color = splitCSSValue(value).find(isColor)\n return color ? { 'background-color': color } : {}\n }\n return {}\n}\n\nfunction boxSides(property: string, value: string): DesignStyleDeclaration {\n const [top, right = top, bottom = top, left = right] = splitCSSValue(value)\n if (!top || !right || !bottom || !left) return {}\n return {\n [`${property}-top`]: top,\n [`${property}-right`]: right,\n [`${property}-bottom`]: bottom,\n [`${property}-left`]: left\n }\n}\n\n/** `padding-inline` and `padding-block` as the sides they set in left-to-right, horizontal text. */\nfunction logicalSides(property: string, value: string, inline: boolean): DesignStyleDeclaration {\n const box = property.slice(0, property.lastIndexOf('-'))\n const [first, second = first] = splitCSSValue(value)\n if (!first || !second) return {}\n const [start, end] = inline ? ['left', 'right'] : ['top', 'bottom']\n return { [`${box}-${start}`]: first, [`${box}-${end}`]: second }\n}\n\nfunction borderLonghands(value: string): DesignStyleDeclaration {\n const parts = splitCSSValue(value)\n const longhands: DesignStyleDeclaration = {}\n const color = parts.find(isColor)\n const width = parts.find((part) => parseCSSNumber(part) !== null)\n const style = parts.find((part) => BORDER_STYLES.has(part.toLowerCase()))\n if (color) longhands['border-color'] = color\n if (width) longhands['border-width'] = width\n if (style) longhands['border-style'] = style.toLowerCase()\n return longhands\n}\n\n/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */\nfunction isColor(value: string): boolean {\n return tryParseColor(value) !== null\n}\n\nfunction classList(element: DesignElement): Set<string> {\n const className = 'class' in element.attrs ? element.attrs.class : ''\n return new Set(className.split(/\\s+/).filter((name) => name.length > 0))\n}\n\nfunction elementId(element: DesignElement): string | undefined {\n return 'id' in element.attrs ? element.attrs.id : undefined\n}\n\nfunction selectorSpecificity(selector: string): number {\n const idCount = selector.match(/#[\\w-]+/g)?.length ?? 0\n const classCount = selector.match(/\\.[\\w-]+/g)?.length ?? 0\n // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.\n const tagCount = selector.split(/[\\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length\n return idCount * 100 + classCount * 10 + tagCount\n}\n\nfunction matchesSimpleSelector(element: DesignElement, selector: string): boolean {\n if (selector.includes(':') || selector.includes('[')) return false\n\n const idMatch = selector.match(/#([\\w-]+)/)\n if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false\n\n const classes = selector.match(/\\.[\\w-]+/g) ?? []\n const elementClasses = classList(element)\n if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false\n\n const tag = selector.replace(/#[\\w-]+/g, '').replace(/\\.[\\w-]+/g, '')\n // The universal selector, as Tailwind's preflight uses for `box-sizing`, matches any element.\n return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()\n}\n\ninterface SelectorStep {\n compound: string\n /** How this compound relates to the one after it: `>` for a parent, ` ` for any ancestor. */\n combinator: '>' | ' '\n}\n\n/** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */\nfunction selectorSteps(selector: string): SelectorStep[] | null {\n const tokens = selector\n .replaceAll('>', ' > ')\n .split(/\\s+/)\n .filter((token) => token.length > 0)\n const steps: SelectorStep[] = []\n let pending: '>' | null = null\n for (const token of tokens) {\n if (token === '>') {\n if (pending || steps.length === 0) return null\n pending = '>'\n continue\n }\n const previous = steps.at(-1)\n if (previous) previous.combinator = pending ?? ' '\n steps.push({ compound: token, combinator: ' ' })\n pending = null\n }\n return pending ? null : steps\n}\n\nfunction matchesSelector(\n element: DesignElement,\n selector: string,\n parent: AncestorContext | null\n): boolean {\n const steps = selectorSteps(selector)\n return steps !== null && matchesSteps(element, steps, steps.length - 1, parent)\n}\n\n/** Whether the element matches the compound at `index` and some ancestors match those before. */\nfunction matchesSteps(\n element: DesignElement,\n steps: SelectorStep[],\n index: number,\n parent: AncestorContext | null\n): boolean {\n const step = steps.at(index)\n if (!step || !matchesSimpleSelector(element, step.compound)) return false\n if (index === 0) return true\n const previous = steps.at(index - 1)\n if (!previous) return false\n if (previous.combinator === '>') {\n return parent !== null && matchesSteps(parent.element, steps, index - 1, parent.parent)\n }\n for (let ancestor = parent; ancestor; ancestor = ancestor.parent) {\n if (matchesSteps(ancestor.element, steps, index - 1, ancestor.parent)) return true\n }\n return false\n}\n\nfunction applyComputedStyles(\n node: DesignNode,\n rules: HeadlessCSSRule[],\n parent: AncestorContext | null,\n inheritedStyle: DesignStyleDeclaration,\n inheritedCustomProperties: DesignStyleDeclaration\n): DesignNode {\n if (node.type === 'text') return node\n\n const computedStyle: DesignStyleDeclaration = pickInheritedStyle(inheritedStyle)\n const matchingRules = rules\n .filter((rule) => matchesSelector(node, rule.selector, parent))\n .sort((left, right) => left.specificity - right.specificity || left.order - right.order)\n\n // Custom properties cascade and inherit like any property, so `var()` resolves per element.\n const customProperties = { ...inheritedCustomProperties }\n for (const rule of matchingRules) declareCustomProperties(customProperties, rule.declarations)\n declareCustomProperties(customProperties, node.inlineStyle ?? {})\n\n for (const rule of matchingRules) {\n Object.assign(computedStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n Object.assign(computedStyle, resolveDeclarations(node.inlineStyle ?? {}, customProperties))\n\n const context = { element: node, parent }\n return {\n ...node,\n computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,\n children: node.children.map((child) =>\n applyComputedStyles(child, rules, context, computedStyle, customProperties)\n )\n }\n}\n\nfunction pickInheritedStyle(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const inherited: DesignStyleDeclaration = {}\n for (const property of INHERITED_PROPERTIES) {\n const value = style[property]\n if (value) inherited[property] = value\n }\n return inherited\n}\n\nexport function computeHeadlessStyles(document: DesignDocument, cssText = ''): DesignDocument {\n const stylesheetText = [document.stylesheets?.map((sheet) => sheet.cssText).join('\\n'), cssText]\n .filter((text): text is string => !!text)\n .join('\\n')\n const { rules, customProperties } = parseRules(stylesheetText)\n // A fragment has no document element, so `:root` reaches its elements through inheritance only.\n const rootStyle: DesignStyleDeclaration = {}\n for (const rule of rules.filter(({ selector }) => selector === ':root')) {\n Object.assign(rootStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n\n return {\n ...document,\n children: document.children.map((child) =>\n applyComputedStyles(child, rules, null, rootStyle, customProperties)\n )\n }\n}\n","import { serializeHTML } from '#dom-css/export/html'\nimport { INLINE_TAGS } from '#dom-css/import/flow'\nimport { parseStyleAttribute } from '#dom-css/import/style-attribute'\nimport type { CSSRuntime, DesignDocument, DesignElement, DesignNode } from '#dom-css/types'\nimport { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { computeHeadlessStyles } from './styles'\n\nfunction attrsToRecord(attrs: DefaultTreeAdapterTypes.Element['attrs']): Record<string, string> {\n const result: Record<string, string> = {}\n for (const attr of attrs) result[attr.name] = attr.value\n return result\n}\n\nfunction isTextNode(\n node: DefaultTreeAdapterTypes.ChildNode\n): node is DefaultTreeAdapterTypes.TextNode {\n return node.nodeName === '#text'\n}\n\nconst NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])\n\nfunction isInlineElement(node: DefaultTreeAdapterTypes.ChildNode | undefined): boolean {\n return node !== undefined && 'tagName' in node && INLINE_TAGS.has(node.tagName.toLowerCase())\n}\n\n/**\n * Text, and the spaces in or beside inline elements, which CSS draws among their words; spaces\n * between blocks lay nothing out, so they are left out.\n */\nfunction keepsText(\n node: DefaultTreeAdapterTypes.TextNode,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n index: number,\n inInline: boolean\n): boolean {\n if (node.value.trim().length > 0) return true\n return (\n node.value.length > 0 &&\n (inInline || isInlineElement(siblings[index - 1]) || isInlineElement(siblings[index + 1]))\n )\n}\n\nfunction childrenToDesignNodes(\n nodes: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode[] {\n return nodes\n .map((node, index) => childToDesignNode(node, index, nodes, inInline))\n .filter((child): child is DesignNode => child !== null)\n}\n\nfunction childToDesignNode(\n node: DefaultTreeAdapterTypes.ChildNode,\n index: number,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode | null {\n if (isTextNode(node)) {\n return keepsText(node, siblings, index, inInline) ? { type: 'text', text: node.value } : null\n }\n\n if (!('tagName' in node)) return null\n if (NON_RENDERED_TAGS.has(node.tagName.toLowerCase())) return null\n\n const attrs = attrsToRecord(node.attrs)\n const element: DesignElement = {\n type: 'element',\n tagName: node.tagName.toLowerCase(),\n attrs,\n children: childrenToDesignNodes(node.childNodes, isInlineElement(node))\n }\n\n const inlineStyle = parseStyleAttribute(attrs.style)\n if (inlineStyle) element.inlineStyle = inlineStyle\n\n return element\n}\n\nfunction parseHTML(html: string): DesignDocument {\n const fragment = parseFragment(html)\n return {\n type: 'document',\n children: childrenToDesignNodes(fragment.childNodes, false)\n }\n}\n\nexport function createHeadlessCSSRuntime(): CSSRuntime {\n return {\n kind: 'headless',\n parseHTML,\n serializeHTML(document: DesignDocument) {\n return serializeHTML(document)\n },\n async computeStyles(document: DesignDocument, cssText = '') {\n return computeHeadlessStyles(document, cssText)\n }\n }\n}\n","import type { CSSRuntime } from '../types'\nimport { createBrowserCSSRuntime } from './browser/runtime'\nimport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport { createBrowserCSSRuntime } from './browser/runtime'\nexport type { BrowserCSSRuntimeOptions } from './browser/runtime'\nexport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport function createCSSRuntime(): CSSRuntime {\n return typeof document !== 'undefined' ? createBrowserCSSRuntime() : createHeadlessCSSRuntime()\n}\n","import { compile } from 'tailwindcss'\n\nexport interface CompileTailwindCSSOptions {\n css?: string\n base?: string\n loadStylesheet?: (id: string, base: string) => Promise<string>\n}\n\nconst DEFAULT_TAILWIND_CSS = '@import \"tailwindcss\";'\n\nexport async function compileTailwindCSS(\n classes: string | Iterable<string>,\n options: CompileTailwindCSSOptions = {}\n): Promise<string> {\n const compiler = await compile(tailwindCompilerCSS(options.css), {\n base: options.base,\n loadStylesheet: async (id, base) => {\n const content = options.loadStylesheet\n ? await options.loadStylesheet(id, base)\n : await loadTailwindStylesheet(id)\n return { path: id, base, content }\n }\n })\n return compiler.build(normalizeClasses(classes))\n}\n\nfunction tailwindCompilerCSS(css: string | undefined): string {\n const trimmed = css?.trim()\n if (!trimmed) return DEFAULT_TAILWIND_CSS\n if (containsTailwindImport(trimmed)) return trimmed\n return `${DEFAULT_TAILWIND_CSS}\\n${trimmed}`\n}\n\nfunction containsTailwindImport(css: string): boolean {\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n return /^\\s*@import\\s+(?:\"tailwindcss(?:\\/[^\"]*)?\"|'tailwindcss(?:\\/[^']*)?')/m.test(\n withoutComments\n )\n}\n\nfunction normalizeClasses(classes: string | Iterable<string>): string[] {\n const classNames = typeof classes === 'string' ? [classes] : Array.from(classes)\n return classNames\n .flatMap((className) => className.split(/\\s+/))\n .map((className) => className.trim())\n .filter((className) => className.length > 0)\n}\n\nasync function loadTailwindStylesheet(id: string): Promise<string> {\n const stylesheet = id === 'tailwindcss' ? 'tailwindcss/index.css' : id\n const url = new URL(import.meta.resolve(stylesheet))\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(url, 'utf8')\n}\n","import { parse, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { createCSSRuntime } from '../runtime'\nimport type { CSSComputeOptions, CSSRuntime, DesignDocument } from '../types'\nimport { mergeCSSText } from './css-text'\nimport { designDocumentToSceneGraph, type ToSceneGraphOptions } from './scene-graph'\nimport { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'\n\nexport interface HTMLToDesignDocumentOptions {\n cssText?: string\n runtime?: CSSRuntime\n compute?: CSSComputeOptions\n}\n\nexport interface HTMLToSceneGraphOptions extends HTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nexport interface TailwindHTMLToDesignDocumentOptions\n extends Omit<HTMLToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}\n\nexport interface TailwindHTMLToSceneGraphOptions\n extends TailwindHTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nfunction runtimeForOptions(runtime: CSSRuntime | undefined) {\n return runtime ?? createCSSRuntime()\n}\n\nfunction getChildNodes(node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.ChildNode[] {\n return 'childNodes' in node ? node.childNodes : []\n}\n\nfunction textContent(node: DefaultTreeAdapterTypes.Node): string {\n if (node.nodeName === '#text' && 'value' in node) return node.value\n return getChildNodes(node).map(textContent).join('')\n}\n\nfunction collectStyleText(node: DefaultTreeAdapterTypes.Node, styles: string[]): void {\n if ('tagName' in node && node.tagName.toLowerCase() === 'style') {\n const css = textContent(node).trim()\n if (css) styles.push(css)\n return\n }\n\n for (const child of getChildNodes(node)) collectStyleText(child, styles)\n}\n\nfunction extractEmbeddedCSSText(html: string): string | undefined {\n const styles: string[] = []\n collectStyleText(parse(html), styles)\n return styles.length > 0 ? styles.join('\\n') : undefined\n}\n\nexport async function htmlToDesignDocument(\n html: string,\n options: HTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const runtime = runtimeForOptions(options.runtime)\n const document = runtime.parseHTML(html)\n const cssText = mergeCSSText(extractEmbeddedCSSText(html), options.cssText)\n return runtime.computeStyles(document, cssText, options.compute)\n}\n\nexport async function htmlToSceneGraph(\n html: string,\n options: HTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await htmlToDesignDocument(html, options)\n return designDocumentToSceneGraph(document, options)\n}\n\nexport async function tailwindHTMLToDesignDocument(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const cssText = await compileTailwindCSS(candidates, options)\n return htmlToDesignDocument(html, { ...options, cssText })\n}\n\nexport async function tailwindHTMLToSceneGraph(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await tailwindHTMLToDesignDocument(html, candidates, options)\n return designDocumentToSceneGraph(document, options)\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,eAAe,SAA0C;CAChE,MAAM,CAAC,QAAQA,QAAM,OAAO,CAAC,CAAC;CAC9B,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,EAAE,WAAW,OAAO,OAAO;CACpE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAA+D;CACjG,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAAO,eAAe,KAAK,MAAM,EAAE;CACzC,IAAI,CAAC,MAAM,OAAO,KAAA;CAElB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,YAAY,MAAM,KAAK,KAAK,KAAK,GAAG;EAC7C,MAAM,gBAAgB,KAAK,MAAM,iBAAiB,QAAQ;EAC1D,IAAI,eAAe,MAAM,YAAY;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CAC1B,iBAAiB,MAAM,IAAI,GAAG,MAAM;CACpC,OAAO,OAAO,SAAS,IAAI,OAAO,KAAK,IAAI,IAAI,KAAA;AACjD;AAEA,eAAsB,qBACpB,MACA,UAAuC,CAAC,GACf;CACzB,MAAM,UAAU,kBAAkB,QAAQ,OAAO;CACjD,MAAM,WAAW,QAAQ,UAAU,IAAI;CACvC,MAAM,UAAU,aAAa,uBAAuB,IAAI,GAAG,QAAQ,OAAO;CAC1E,OAAO,QAAQ,cAAc,UAAU,SAAS,QAAQ,OAAO;AACjE;AAEA,eAAsB,iBACpB,MACA,UAAmC,CAAC,GACf;CACrB,MAAM,WAAW,MAAM,qBAAqB,MAAM,OAAO;CACzD,OAAO,2BAA2B,UAAU,OAAO;AACrD;AAEA,eAAsB,6BACpB,MACA,YACA,UAA+C,CAAC,GACvB;CACzB,MAAM,UAAU,MAAM,mBAAmB,YAAY,OAAO;CAC5D,OAAO,qBAAqB,MAAM;EAAE,GAAG;EAAS;CAAQ,CAAC;AAC3D;AAEA,eAAsB,yBACpB,MACA,YACA,UAA2C,CAAC,GACvB;CACrB,MAAM,WAAW,MAAM,6BAA6B,MAAM,YAAY,OAAO;CAC7E,OAAO,2BAA2B,UAAU,OAAO;AACrD"}
1
+ {"version":3,"file":"html.js","names":["parse","parse"],"sources":["../../../src/import/style-attribute.ts","../../../src/runtime/headless/styles.ts","../../../src/runtime/headless/runtime.ts","../../../src/runtime/index.ts","../../../src/import/tailwind.ts","../../../src/import/html.ts"],"sourcesContent":["import { parse } from '@acemir/cssom'\n\nimport type { CSSStyleRuleLike } from '../cssom/types'\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction firstStyleRule(cssText: string): CSSStyleRuleLike | null {\n const [rule] = parse(cssText).cssRules\n if (!rule || typeof rule !== 'object' || !('style' in rule)) return null\n return rule as CSSStyleRuleLike\n}\n\nexport function parseStyleAttribute(value: string | undefined): DesignStyleDeclaration | undefined {\n if (!value) return undefined\n\n const rule = firstStyleRule(`*{${value}}`)\n if (!rule) return undefined\n\n const style: DesignStyleDeclaration = {}\n for (const property of Array.from(rule.style)) {\n const propertyValue = rule.style.getPropertyValue(property)\n if (propertyValue) style[property] = propertyValue\n }\n\n return Object.keys(style).length > 0 ? style : undefined\n}\n","import type {\n CSSGroupingRuleLike,\n CSSStyleDeclarationLike,\n CSSStyleRuleLike\n} from '#dom-css/cssom/types'\nimport type {\n DesignDocument,\n DesignElement,\n DesignNode,\n DesignStyleDeclaration\n} from '#dom-css/types'\nimport { parse } from '@acemir/cssom'\n\nimport { tryParseColor } from '@pairdraw/scene-graph/color'\nimport { parseCSSNumber, splitCSSValue } from '@pairdraw/scene-graph/css'\n\ninterface HeadlessCSSRule {\n selector: string\n specificity: number\n order: number\n /** Declared values with `var()` unresolved, so each element resolves them in its own scope. */\n declarations: DesignStyleDeclaration\n}\n\ninterface ParsedHeadlessCSS {\n rules: HeadlessCSSRule[]\n customProperties: DesignStyleDeclaration\n}\n\ninterface AncestorContext {\n element: DesignElement\n parent: AncestorContext | null\n}\n\nconst INHERITED_PROPERTIES = new Set([\n 'color',\n 'font-family',\n 'font-size',\n 'font-weight',\n 'line-height'\n])\n\n/** Declared values as written, before custom properties and shorthands are resolved. */\nfunction declarationsOf(style: CSSStyleDeclarationLike): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const property of Array.from({ length: style.length }, (_, index) => style[index])) {\n const value = style.getPropertyValue(property).trim()\n if (property && value) result[property] = value\n }\n return result\n}\n\nfunction resolveDeclarations(\n declarations: DesignStyleDeclaration,\n customProperties: DesignStyleDeclaration\n): DesignStyleDeclaration {\n const resolved: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(declarations)) {\n const resolvedValue = resolveCSSValue(value, customProperties)\n if (resolvedValue) resolved[property] = resolvedValue\n }\n return expandStyleShorthands(resolved)\n}\n\n/** Adds the custom properties a declaration block sets, resolved against those already in scope. */\nfunction declareCustomProperties(\n scope: DesignStyleDeclaration,\n declarations: DesignStyleDeclaration\n): void {\n for (const [name, value] of Object.entries(declarations)) {\n if (!name.startsWith('--')) continue\n const resolved = resolveCSSValue(value, scope)\n if (resolved) scope[name] = resolved\n }\n}\n\nfunction isStyleRule(rule: unknown): rule is CSSStyleRuleLike {\n return (\n typeof rule === 'object' &&\n rule !== null &&\n 'selectorText' in rule &&\n 'style' in rule &&\n typeof rule.selectorText === 'string'\n )\n}\n\nfunction isGroupingRule(rule: unknown): rule is CSSGroupingRuleLike {\n return (\n typeof rule === 'object' && rule !== null && 'cssRules' in rule && Array.isArray(rule.cssRules)\n )\n}\n\nfunction collectStyleRules(rules: unknown[]): CSSStyleRuleLike[] {\n return rules.flatMap((rule) => {\n if (isStyleRule(rule)) return [rule]\n if (isGroupingRule(rule)) return collectStyleRules(rule.cssRules)\n return []\n })\n}\n\nfunction parseRules(cssText: string): ParsedHeadlessCSS {\n let order = 0\n const sheet = parse(cssText)\n const styleRules = collectStyleRules(sheet.cssRules)\n const customProperties = collectCustomProperties(styleRules)\n const rules = styleRules.flatMap((rule) => {\n const declarations = declarationsOf(rule.style)\n return rule.selectorText\n .split(',')\n .map((selector) => selector.trim())\n .filter((selector) => selector.length > 0)\n .map((selector) => ({\n selector,\n specificity: selectorSpecificity(selector),\n order: order++,\n declarations\n }))\n })\n return { rules, customProperties }\n}\n\nfunction collectCustomProperties(rules: CSSStyleRuleLike[]): DesignStyleDeclaration {\n const customProperties: DesignStyleDeclaration = {}\n for (const rule of rules) {\n if (!rule.selectorText.split(',').some((selector) => selector.trim() === ':root')) continue\n declareCustomProperties(customProperties, declarationsOf(rule.style))\n }\n return customProperties\n}\n\nfunction resolveCSSValue(value: string, customProperties: DesignStyleDeclaration): string {\n return resolveSimpleCalc(resolveVariables(value, customProperties))\n}\n\nconst CUSTOM_PROPERTY_NAME = /^--[\\w-]+$/\n\n/** `var()` references as their values; a fallback can hold parentheses and other `var()`s. */\nfunction resolveVariables(value: string, customProperties: DesignStyleDeclaration): string {\n let result = ''\n let index = 0\n for (;;) {\n const start = value.indexOf('var(', index)\n const end = start === -1 ? -1 : closingParenthesis(value, start + 3)\n if (end === -1) return result + value.slice(index)\n const inner = value.slice(start + 4, end)\n const comma = inner.indexOf(',')\n const name = (comma === -1 ? inner : inner.slice(0, comma)).trim()\n const declared: string | undefined = Object.hasOwn(customProperties, name)\n ? customProperties[name]\n : undefined\n const fallback = comma === -1 ? '' : inner.slice(comma + 1).trim()\n result += value.slice(index, start)\n result += CUSTOM_PROPERTY_NAME.test(name)\n ? (declared ?? resolveVariables(fallback, customProperties))\n : value.slice(start, end + 1)\n index = end + 1\n }\n}\n\n/** The index of the `)` closing the `(` at `open`, or -1 when it is never closed. */\nfunction closingParenthesis(value: string, open: number): number {\n let depth = 0\n for (let index = open; index < value.length; index++) {\n if (value[index] === '(') depth++\n else if (value[index] === ')' && --depth === 0) return index\n }\n return -1\n}\n\n/** `calc()` of a product, with the length on either side, as pixels. */\nfunction resolveSimpleCalc(value: string): string {\n const calc = /^calc\\(\\s*([-\\d.]+)(rem|px)?\\s*\\*\\s*([-\\d.]+)(rem|px)?\\s*\\)$/.exec(value)\n if (!calc?.[1] || !calc[3] || (calc[2] && calc[4])) return value\n\n const left = Number.parseFloat(calc[1])\n const right = Number.parseFloat(calc[3])\n // An unmatched group is undefined at run time, though the match array types it as a string.\n const unit = calc[2] || calc[4] || 'px'\n if (!Number.isFinite(left) || !Number.isFinite(right)) return value\n return `${unit === 'rem' ? left * right * 16 : left * right}px`\n}\n\nconst BORDER_STYLES = new Set([\n 'none',\n 'hidden',\n 'dotted',\n 'dashed',\n 'solid',\n 'double',\n 'groove',\n 'ridge',\n 'inset',\n 'outset'\n])\n\n/**\n * Shorthands as the longhands they set, in declaration order, so a later declaration wins over\n * an earlier one whether it is a shorthand, a logical side, or a single side, as in CSS.\n */\nfunction expandStyleShorthands(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const result: DesignStyleDeclaration = {}\n for (const [property, value] of Object.entries(style)) {\n result[property] = value\n Object.assign(result, longhandsOf(property, value))\n }\n return result\n}\n\nfunction longhandsOf(property: string, value: string): DesignStyleDeclaration {\n if (property === 'margin' || property === 'padding') return boxSides(property, value)\n const logical = /^(margin|padding)-(inline|block)$/u.exec(property)\n if (logical) return logicalSides(property, value, logical[2] === 'inline')\n if (property === 'border') return borderLonghands(value)\n if (property === 'background') {\n const color = splitCSSValue(value).find(isColor)\n return color ? { 'background-color': color } : {}\n }\n return {}\n}\n\nfunction boxSides(property: string, value: string): DesignStyleDeclaration {\n const [top, right = top, bottom = top, left = right] = splitCSSValue(value)\n if (!top || !right || !bottom || !left) return {}\n return {\n [`${property}-top`]: top,\n [`${property}-right`]: right,\n [`${property}-bottom`]: bottom,\n [`${property}-left`]: left\n }\n}\n\n/** `padding-inline` and `padding-block` as the sides they set in left-to-right, horizontal text. */\nfunction logicalSides(property: string, value: string, inline: boolean): DesignStyleDeclaration {\n const box = property.slice(0, property.lastIndexOf('-'))\n const [first, second = first] = splitCSSValue(value)\n if (!first || !second) return {}\n const [start, end] = inline ? ['left', 'right'] : ['top', 'bottom']\n return { [`${box}-${start}`]: first, [`${box}-${end}`]: second }\n}\n\nfunction borderLonghands(value: string): DesignStyleDeclaration {\n const parts = splitCSSValue(value)\n const longhands: DesignStyleDeclaration = {}\n const color = parts.find(isColor)\n const width = parts.find((part) => parseCSSNumber(part) !== null)\n const style = parts.find((part) => BORDER_STYLES.has(part.toLowerCase()))\n if (color) longhands['border-color'] = color\n if (width) longhands['border-width'] = width\n if (style) longhands['border-style'] = style.toLowerCase()\n return longhands\n}\n\n/** Any CSS color, including `transparent`, which a shorthand may set on purpose. */\nfunction isColor(value: string): boolean {\n return tryParseColor(value) !== null\n}\n\nfunction classList(element: DesignElement): Set<string> {\n const className = 'class' in element.attrs ? element.attrs.class : ''\n return new Set(className.split(/\\s+/).filter((name) => name.length > 0))\n}\n\nfunction elementId(element: DesignElement): string | undefined {\n return 'id' in element.attrs ? element.attrs.id : undefined\n}\n\nfunction selectorSpecificity(selector: string): number {\n const idCount = selector.match(/#[\\w-]+/g)?.length ?? 0\n const classCount = selector.match(/\\.[\\w-]+/g)?.length ?? 0\n // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.\n const tagCount = selector.split(/[\\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length\n return idCount * 100 + classCount * 10 + tagCount\n}\n\nfunction matchesSimpleSelector(element: DesignElement, selector: string): boolean {\n if (selector.includes(':') || selector.includes('[')) return false\n\n const idMatch = selector.match(/#([\\w-]+)/)\n if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false\n\n const classes = selector.match(/\\.[\\w-]+/g) ?? []\n const elementClasses = classList(element)\n if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false\n\n const tag = selector.replace(/#[\\w-]+/g, '').replace(/\\.[\\w-]+/g, '')\n // The universal selector, as Tailwind's preflight uses for `box-sizing`, matches any element.\n return tag.length === 0 || tag === '*' || element.tagName.toLowerCase() === tag.toLowerCase()\n}\n\ninterface SelectorStep {\n compound: string\n /** How this compound relates to the one after it: `>` for a parent, ` ` for any ancestor. */\n combinator: '>' | ' '\n}\n\n/** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */\nfunction selectorSteps(selector: string): SelectorStep[] | null {\n const tokens = selector\n .replaceAll('>', ' > ')\n .split(/\\s+/)\n .filter((token) => token.length > 0)\n const steps: SelectorStep[] = []\n let pending: '>' | null = null\n for (const token of tokens) {\n if (token === '>') {\n if (pending || steps.length === 0) return null\n pending = '>'\n continue\n }\n const previous = steps.at(-1)\n if (previous) previous.combinator = pending ?? ' '\n steps.push({ compound: token, combinator: ' ' })\n pending = null\n }\n return pending ? null : steps\n}\n\nfunction matchesSelector(\n element: DesignElement,\n selector: string,\n parent: AncestorContext | null\n): boolean {\n const steps = selectorSteps(selector)\n return steps !== null && matchesSteps(element, steps, steps.length - 1, parent)\n}\n\n/** Whether the element matches the compound at `index` and some ancestors match those before. */\nfunction matchesSteps(\n element: DesignElement,\n steps: SelectorStep[],\n index: number,\n parent: AncestorContext | null\n): boolean {\n const step = steps.at(index)\n if (!step || !matchesSimpleSelector(element, step.compound)) return false\n if (index === 0) return true\n const previous = steps.at(index - 1)\n if (!previous) return false\n if (previous.combinator === '>') {\n return parent !== null && matchesSteps(parent.element, steps, index - 1, parent.parent)\n }\n for (let ancestor = parent; ancestor; ancestor = ancestor.parent) {\n if (matchesSteps(ancestor.element, steps, index - 1, ancestor.parent)) return true\n }\n return false\n}\n\nfunction applyComputedStyles(\n node: DesignNode,\n rules: HeadlessCSSRule[],\n parent: AncestorContext | null,\n inheritedStyle: DesignStyleDeclaration,\n inheritedCustomProperties: DesignStyleDeclaration\n): DesignNode {\n if (node.type === 'text') return node\n\n const computedStyle: DesignStyleDeclaration = pickInheritedStyle(inheritedStyle)\n const matchingRules = rules\n .filter((rule) => matchesSelector(node, rule.selector, parent))\n .sort((left, right) => left.specificity - right.specificity || left.order - right.order)\n\n // Custom properties cascade and inherit like any property, so `var()` resolves per element.\n const customProperties = { ...inheritedCustomProperties }\n for (const rule of matchingRules) declareCustomProperties(customProperties, rule.declarations)\n declareCustomProperties(customProperties, node.inlineStyle ?? {})\n\n for (const rule of matchingRules) {\n Object.assign(computedStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n Object.assign(computedStyle, resolveDeclarations(node.inlineStyle ?? {}, customProperties))\n\n const context = { element: node, parent }\n return {\n ...node,\n computedStyle: Object.keys(computedStyle).length > 0 ? computedStyle : undefined,\n children: node.children.map((child) =>\n applyComputedStyles(child, rules, context, computedStyle, customProperties)\n )\n }\n}\n\nfunction pickInheritedStyle(style: DesignStyleDeclaration): DesignStyleDeclaration {\n const inherited: DesignStyleDeclaration = {}\n for (const property of INHERITED_PROPERTIES) {\n const value = style[property]\n if (value) inherited[property] = value\n }\n return inherited\n}\n\nexport function computeHeadlessStyles(document: DesignDocument, cssText = ''): DesignDocument {\n const stylesheetText = [document.stylesheets?.map((sheet) => sheet.cssText).join('\\n'), cssText]\n .filter((text): text is string => !!text)\n .join('\\n')\n const { rules, customProperties } = parseRules(stylesheetText)\n // A fragment has no document element, so `:root` reaches its elements through inheritance only.\n const rootStyle: DesignStyleDeclaration = {}\n for (const rule of rules.filter(({ selector }) => selector === ':root')) {\n Object.assign(rootStyle, resolveDeclarations(rule.declarations, customProperties))\n }\n\n return {\n ...document,\n children: document.children.map((child) =>\n applyComputedStyles(child, rules, null, rootStyle, customProperties)\n )\n }\n}\n","import { serializeHTML } from '#dom-css/export/html'\nimport { INLINE_TAGS } from '#dom-css/import/flow'\nimport { parseStyleAttribute } from '#dom-css/import/style-attribute'\nimport type { CSSRuntime, DesignDocument, DesignElement, DesignNode } from '#dom-css/types'\nimport { parseFragment, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport { computeHeadlessStyles } from './styles'\n\nfunction attrsToRecord(attrs: DefaultTreeAdapterTypes.Element['attrs']): Record<string, string> {\n const result: Record<string, string> = {}\n for (const attr of attrs) result[attr.name] = attr.value\n return result\n}\n\nfunction isTextNode(\n node: DefaultTreeAdapterTypes.ChildNode\n): node is DefaultTreeAdapterTypes.TextNode {\n return node.nodeName === '#text'\n}\n\nconst NON_RENDERED_TAGS = new Set(['head', 'link', 'meta', 'script', 'style', 'template', 'title'])\n\nfunction isInlineElement(node: DefaultTreeAdapterTypes.ChildNode | undefined): boolean {\n return node !== undefined && 'tagName' in node && INLINE_TAGS.has(node.tagName.toLowerCase())\n}\n\n/**\n * Text, and the spaces in or beside inline elements, which CSS draws among their words; spaces\n * between blocks lay nothing out, so they are left out.\n */\nfunction keepsText(\n node: DefaultTreeAdapterTypes.TextNode,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n index: number,\n inInline: boolean\n): boolean {\n if (node.value.trim().length > 0) return true\n return (\n node.value.length > 0 &&\n (inInline || isInlineElement(siblings[index - 1]) || isInlineElement(siblings[index + 1]))\n )\n}\n\nfunction childrenToDesignNodes(\n nodes: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode[] {\n return nodes\n .map((node, index) => childToDesignNode(node, index, nodes, inInline))\n .filter((child): child is DesignNode => child !== null)\n}\n\nfunction childToDesignNode(\n node: DefaultTreeAdapterTypes.ChildNode,\n index: number,\n siblings: readonly DefaultTreeAdapterTypes.ChildNode[],\n inInline: boolean\n): DesignNode | null {\n if (isTextNode(node)) {\n return keepsText(node, siblings, index, inInline) ? { type: 'text', text: node.value } : null\n }\n\n if (!('tagName' in node)) return null\n if (NON_RENDERED_TAGS.has(node.tagName.toLowerCase())) return null\n\n const attrs = attrsToRecord(node.attrs)\n const element: DesignElement = {\n type: 'element',\n tagName: node.tagName.toLowerCase(),\n attrs,\n children: childrenToDesignNodes(node.childNodes, isInlineElement(node))\n }\n\n const inlineStyle = parseStyleAttribute(attrs.style)\n if (inlineStyle) element.inlineStyle = inlineStyle\n\n return element\n}\n\nfunction parseHTML(html: string): DesignDocument {\n const fragment = parseFragment(html)\n return {\n type: 'document',\n children: childrenToDesignNodes(fragment.childNodes, false)\n }\n}\n\nexport function createHeadlessCSSRuntime(): CSSRuntime {\n return {\n kind: 'headless',\n parseHTML,\n serializeHTML(document: DesignDocument) {\n return serializeHTML(document)\n },\n async computeStyles(document: DesignDocument, cssText = '') {\n return computeHeadlessStyles(document, cssText)\n }\n }\n}\n","import type { CSSRuntime } from '../types'\nimport { createBrowserCSSRuntime } from './browser/runtime'\nimport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport { createBrowserCSSRuntime } from './browser/runtime'\nexport type { BrowserCSSRuntimeOptions } from './browser/runtime'\nexport { createHeadlessCSSRuntime } from './headless/runtime'\n\nexport function createCSSRuntime(): CSSRuntime {\n return typeof document !== 'undefined' ? createBrowserCSSRuntime() : createHeadlessCSSRuntime()\n}\n","import { compile } from 'tailwindcss'\n\nexport interface CompileTailwindCSSOptions {\n css?: string\n base?: string\n loadStylesheet?: (id: string, base: string) => Promise<string>\n}\n\nconst DEFAULT_TAILWIND_CSS = '@import \"tailwindcss\";'\n\nexport async function compileTailwindCSS(\n classes: string | Iterable<string>,\n options: CompileTailwindCSSOptions = {}\n): Promise<string> {\n const compiler = await compile(tailwindCompilerCSS(options.css), {\n base: options.base,\n loadStylesheet: async (id, base) => {\n const content = options.loadStylesheet\n ? await options.loadStylesheet(id, base)\n : await loadTailwindStylesheet(id)\n return { path: id, base, content }\n }\n })\n return compiler.build(normalizeClasses(classes))\n}\n\nfunction tailwindCompilerCSS(css: string | undefined): string {\n const trimmed = css?.trim()\n if (!trimmed) return DEFAULT_TAILWIND_CSS\n if (containsTailwindImport(trimmed)) return trimmed\n return `${DEFAULT_TAILWIND_CSS}\\n${trimmed}`\n}\n\nfunction containsTailwindImport(css: string): boolean {\n const withoutComments = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, '')\n return /^\\s*@import\\s+(?:\"tailwindcss(?:\\/[^\"]*)?\"|'tailwindcss(?:\\/[^']*)?')/m.test(\n withoutComments\n )\n}\n\nfunction normalizeClasses(classes: string | Iterable<string>): string[] {\n const classNames = typeof classes === 'string' ? [classes] : Array.from(classes)\n return classNames\n .flatMap((className) => className.split(/\\s+/))\n .map((className) => className.trim())\n .filter((className) => className.length > 0)\n}\n\nasync function loadTailwindStylesheet(id: string): Promise<string> {\n const stylesheet = id === 'tailwindcss' ? 'tailwindcss/index.css' : id\n const url = new URL(import.meta.resolve(stylesheet))\n const { readFile } = await import(/* @vite-ignore */ 'node:fs/promises')\n return readFile(url, 'utf8')\n}\n","import { parse, type DefaultTreeAdapterTypes } from 'parse5'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { createCSSRuntime } from '../runtime'\nimport type { CSSComputeOptions, CSSRuntime, DesignDocument } from '../types'\nimport { mergeCSSText } from './css-text'\nimport { designDocumentToSceneGraph, type ToSceneGraphOptions } from './scene-graph'\nimport { compileTailwindCSS, type CompileTailwindCSSOptions } from './tailwind'\n\nexport interface HTMLToDesignDocumentOptions {\n cssText?: string\n runtime?: CSSRuntime\n compute?: CSSComputeOptions\n}\n\nexport interface HTMLToSceneGraphOptions extends HTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nexport interface TailwindHTMLToDesignDocumentOptions\n extends Omit<HTMLToDesignDocumentOptions, 'cssText'>, CompileTailwindCSSOptions {}\n\nexport interface TailwindHTMLToSceneGraphOptions\n extends TailwindHTMLToDesignDocumentOptions, ToSceneGraphOptions {}\n\nfunction runtimeForOptions(runtime: CSSRuntime | undefined) {\n return runtime ?? createCSSRuntime()\n}\n\nfunction getChildNodes(node: DefaultTreeAdapterTypes.Node): DefaultTreeAdapterTypes.ChildNode[] {\n return 'childNodes' in node ? node.childNodes : []\n}\n\nfunction textContent(node: DefaultTreeAdapterTypes.Node): string {\n if (node.nodeName === '#text' && 'value' in node) return node.value\n return getChildNodes(node).map(textContent).join('')\n}\n\nfunction collectStyleText(node: DefaultTreeAdapterTypes.Node, styles: string[]): void {\n if ('tagName' in node && node.tagName.toLowerCase() === 'style') {\n const css = textContent(node).trim()\n if (css) styles.push(css)\n return\n }\n\n for (const child of getChildNodes(node)) collectStyleText(child, styles)\n}\n\nfunction extractEmbeddedCSSText(html: string): string | undefined {\n const styles: string[] = []\n collectStyleText(parse(html), styles)\n return styles.length > 0 ? styles.join('\\n') : undefined\n}\n\nexport async function htmlToDesignDocument(\n html: string,\n options: HTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const runtime = runtimeForOptions(options.runtime)\n const document = runtime.parseHTML(html)\n const cssText = mergeCSSText(extractEmbeddedCSSText(html), options.cssText)\n return runtime.computeStyles(document, cssText, options.compute)\n}\n\nexport async function htmlToSceneGraph(\n html: string,\n options: HTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await htmlToDesignDocument(html, options)\n return designDocumentToSceneGraph(document, options)\n}\n\nexport async function tailwindHTMLToDesignDocument(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToDesignDocumentOptions = {}\n): Promise<DesignDocument> {\n const cssText = await compileTailwindCSS(candidates, options)\n return htmlToDesignDocument(html, { ...options, cssText })\n}\n\nexport async function tailwindHTMLToSceneGraph(\n html: string,\n candidates: string | Iterable<string>,\n options: TailwindHTMLToSceneGraphOptions = {}\n): Promise<SceneGraph> {\n const document = await tailwindHTMLToDesignDocument(html, candidates, options)\n return designDocumentToSceneGraph(document, options)\n}\n"],"mappings":";;;;;;;;;AAKA,SAAS,eAAe,SAA0C;CAChE,MAAM,CAAC,QAAQA,QAAM,OAAO,CAAC,CAAC;CAC9B,IAAI,CAAC,QAAQ,OAAO,SAAS,YAAY,EAAE,WAAW,OAAO,OAAO;CACpE,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAA+D;CACjG,IAAI,CAAC,OAAO,OAAO,KAAA;CAEnB,MAAM,OAAO,eAAe,KAAK,MAAM,EAAE;CACzC,IAAI,CAAC,MAAM,OAAO,KAAA;CAElB,MAAM,QAAgC,CAAC;CACvC,KAAK,MAAM,YAAY,MAAM,KAAK,KAAK,KAAK,GAAG;EAC7C,MAAM,gBAAgB,KAAK,MAAM,iBAAiB,QAAQ;EAC1D,IAAI,eAAe,MAAM,YAAY;CACvC;CAEA,OAAO,OAAO,KAAK,KAAK,CAAC,CAAC,SAAS,IAAI,QAAQ,KAAA;AACjD;;;ACUA,MAAM,uCAAuB,IAAI,IAAI;CACnC;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAS,eAAe,OAAwD;CAC9E,MAAM,SAAiC,CAAC;CACxC,KAAK,MAAM,YAAY,MAAM,KAAK,EAAE,QAAQ,MAAM,OAAO,IAAI,GAAG,UAAU,MAAM,MAAM,GAAG;EACvF,MAAM,QAAQ,MAAM,iBAAiB,QAAQ,CAAC,CAAC,KAAK;EACpD,IAAI,YAAY,OAAO,OAAO,YAAY;CAC5C;CACA,OAAO;AACT;AAEA,SAAS,oBACP,cACA,kBACwB;CACxB,MAAM,WAAmC,CAAC;CAC1C,KAAK,MAAM,CAAC,UAAU,UAAU,OAAO,QAAQ,YAAY,GAAG;EAC5D,MAAM,gBAAgB,gBAAgB,OAAO,g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,qBAAqB,MAAM;EAAE,GAAG;EAAS;CAAQ,CAAC;AAC3D;AAEA,eAAsB,yBACpB,MACA,YACA,UAA2C,CAAC,GACvB;CACrB,MAAM,WAAW,MAAM,6BAA6B,MAAM,YAAY,OAAO;CAC7E,OAAO,2BAA2B,UAAU,OAAO;AACrD"}
package/dist/export.d.ts CHANGED
@@ -1,9 +1,8 @@
1
1
  import { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration, DesignText } from "./types.js";
2
- import { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, exportHTMLBundle, sceneGraphToDesignDocument, sceneNodeToDesignDocument, serializeHTML } from "./styling.js";
2
+ import { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, exportHTMLBundle, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, serializeHTML } from "./styling.js";
3
3
  import { ThemeNamespace } from "twirlwind";
4
4
  import { Behaviour } from "@pairdraw/scene-graph/behaviours";
5
5
  import { es } from "@pairdraw/emit";
6
- import { CSSStyleSheetLike } from "@acemir/cssom";
7
6
  import { ComponentPropertyDefinition, SceneGraph, SceneNode, TokenUnit, Variable, VariableCollection, VariableCollectionMode } from "@pairdraw/scene-graph";
8
7
  //#region src/export/tailwind-jsx.d.ts
9
8
  /** Engine services the projection takes, such as drawing vector layers as SVG. */
@@ -289,6 +288,11 @@ declare function readCustomProperties(css: string): CustomPropertySheet;
289
288
  */
290
289
  declare function modeConditionKey(condition: string): string;
291
290
  //#endregion
291
+ //#region src/cssom/types.d.ts
292
+ interface CSSStyleSheetLike {
293
+ cssRules: unknown[];
294
+ }
295
+ //#endregion
292
296
  //#region src/tokens/validate.d.ts
293
297
  type Parse = (cssText: string) => CSSStyleSheetLike;
294
298
  /**
@@ -583,5 +587,5 @@ declare function stateTailwindClasses(styles: StateStyles, options?: StateTailwi
583
587
  /** The state styles as Tailwind utilities on each element of the merged markup. */
584
588
  declare function stateStylesToTailwind(styles: StateStyles, options?: StateTailwindOptions): DesignDocument;
585
589
  //#endregion
586
- export { BUTTON_RESET, type BehaviourArgs, type BooleanArg, type BooleanModel, COMPONENT_STYLINGS, type CSSExpressionProblem, type CSSValueToken, type CSSValueTokenKind, type ComponentStyling, type ControlModel, type ControlRole, type CustomPropertyDeclaration, type CustomPropertyScope, type CustomPropertySheet, type DesignDocument, type DesignElement, type DesignNode, type ExportHTMLBundle, type ExportHTMLBundleOptions, type ExportHTMLFile, type FeatureCondition, ICON_PACKAGES, INPUT_RESET, type IconFramework, type IconPackage, LAYER_COMPONENT_FRAMEWORKS, type LayerComponent, type LayerComponentFramework, type LayerMarkup, type SceneGraphToDesignOptions, type StateCondition, type StateElement, type StateNode, type StateRule, type StateStyles, type StateStylesheet, type StateTailwindOptions, type StatesModel, TOKEN_UNIT_PROPERTY, type TailwindJSXWithLayers, type TailwindStylesheetId, type TailwindStylesheetLoader, type TokenStylesheet, type TokenStylesheetFormat, type TokenStylesheetIssue, type TokenStylesheetOptions, type TokenValidator, type VectorElementRenderer, type WebFontFaceAsset, type WebFontFaceRequest, type WebFontFaceResolver, behaviourArgs, behaviourControls, booleanOf, buildTokenStylesheet, collectionVariables, conditionSelector, controlRoles, createTokenValidator, cssExpressionProblem, cssNameCodeSyntax, cssNameVariableName, cssTokenProperty, cssValueTokens, defaultModeAttributeName, defaultModeCondition, deriveCSSName, designDocumentToTailwindJSX, explicitCSSName, exportHTMLBundle, featureConditionCSS, groupOf, iconPackagesFor, isIconPackage, layerComponents, layerMarkup, loadTokenValidator, modeAttribute, modeConditionKey, modeConditionName, parseCSSName, parseFeatureCondition, readCustomProperties, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers, serializeHTML, stateStyles, stateStylesToCSS, stateStylesToTailwind, stateTailwindClasses, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit };
590
+ export { BUTTON_RESET, type BehaviourArgs, type BooleanArg, type BooleanModel, COMPONENT_STYLINGS, type CSSExpressionProblem, type CSSValueToken, type CSSValueTokenKind, type ComponentStyling, type ControlModel, type ControlRole, type CustomPropertyDeclaration, type CustomPropertyScope, type CustomPropertySheet, type DesignDocument, type DesignElement, type DesignNode, type ExportHTMLBundle, type ExportHTMLBundleOptions, type ExportHTMLFile, type FeatureCondition, ICON_PACKAGES, INPUT_RESET, type IconFramework, type IconPackage, LAYER_COMPONENT_FRAMEWORKS, type LayerComponent, type LayerComponentFramework, type LayerMarkup, type SceneGraphToDesignOptions, type StateCondition, type StateElement, type StateNode, type StateRule, type StateStyles, type StateStylesheet, type StateTailwindOptions, type StatesModel, TOKEN_UNIT_PROPERTY, type TailwindJSXWithLayers, type TailwindStylesheetId, type TailwindStylesheetLoader, type TokenStylesheet, type TokenStylesheetFormat, type TokenStylesheetIssue, type TokenStylesheetOptions, type TokenValidator, type VectorElementRenderer, type WebFontFaceAsset, type WebFontFaceRequest, type WebFontFaceResolver, behaviourArgs, behaviourControls, booleanOf, buildTokenStylesheet, collectionVariables, conditionSelector, controlRoles, createTokenValidator, cssExpressionProblem, cssNameCodeSyntax, cssNameVariableName, cssTokenProperty, cssValueTokens, defaultModeAttributeName, defaultModeCondition, deriveCSSName, designDocumentToTailwindJSX, explicitCSSName, exportHTMLBundle, featureConditionCSS, groupOf, iconPackagesFor, isIconPackage, layerComponents, layerMarkup, loadTokenValidator, modeAttribute, modeConditionKey, modeConditionName, parseCSSName, parseFeatureCondition, readCustomProperties, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers, serializeHTML, stateStyles, stateStylesToCSS, stateStylesToTailwind, stateTailwindClasses, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit };
587
591
  //# sourceMappingURL=export.d.ts.map
package/dist/export.js CHANGED
@@ -1,4 +1,4 @@
1
- import { TOKEN_UNIT_PROPERTY, buildTokenStylesheet, collectionVariables, createTokenValidator, cssNameCodeSyntax, cssNameVariableName, defaultModeAttributeName, defaultModeCondition, deriveCSSName, explicitCSSName, loadTokenValidator, modeAttribute, parseCSSName, sceneGraphToDesignDocument, sceneNodeToDesignDocument, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit } from "./chunks/behaviours/states/layers.js";
1
+ import { TOKEN_UNIT_PROPERTY, buildTokenStylesheet, collectionVariables, createTokenValidator, cssNameCodeSyntax, cssNameVariableName, defaultModeAttributeName, defaultModeCondition, deriveCSSName, explicitCSSName, loadTokenValidator, modeAttribute, parseCSSName, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit } from "./chunks/behaviours/states/layers.js";
2
2
  import { serializeHTML, stateStylesToTailwind, stateTailwindClasses } from "./chunks/behaviours/states/tailwind.js";
3
3
  import { exportHTMLBundle } from "./chunks/export/bundle.js";
4
4
  import { behaviourArgs } from "./chunks/behaviours/args.js";
@@ -10,4 +10,4 @@ import { ICON_PACKAGES, iconPackagesFor, isIconPackage } from "./chunks/export/c
10
10
  import { cssExpressionProblem, cssTokenProperty, cssValueTokens, designDocumentToTailwindJSX, featureConditionCSS, modeConditionKey, modeConditionName, parseFeatureCondition, readCustomProperties, sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers } from "./chunks/export/index.js";
11
11
  import { behaviourControls, booleanOf } from "./chunks/behaviours/controls.js";
12
12
  import { controlRoles, groupOf } from "./chunks/behaviours/roles.js";
13
- export { BUTTON_RESET, COMPONENT_STYLINGS, ICON_PACKAGES, INPUT_RESET, LAYER_COMPONENT_FRAMEWORKS, TOKEN_UNIT_PROPERTY, behaviourArgs, behaviourControls, booleanOf, buildTokenStylesheet, collectionVariables, conditionSelector, controlRoles, createTokenValidator, cssExpressionProblem, cssNameCodeSyntax, cssNameVariableName, cssTokenProperty, cssValueTokens, defaultModeAttributeName, defaultModeCondition, deriveCSSName, designDocumentToTailwindJSX, explicitCSSName, exportHTMLBundle, featureConditionCSS, groupOf, iconPackagesFor, isIconPackage, layerComponents, layerMarkup, loadTokenValidator, modeAttribute, modeConditionKey, modeConditionName, parseCSSName, parseFeatureCondition, readCustomProperties, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers, serializeHTML, stateStyles, stateStylesToCSS, stateStylesToTailwind, stateTailwindClasses, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit };
13
+ export { BUTTON_RESET, COMPONENT_STYLINGS, ICON_PACKAGES, INPUT_RESET, LAYER_COMPONENT_FRAMEWORKS, TOKEN_UNIT_PROPERTY, behaviourArgs, behaviourControls, booleanOf, buildTokenStylesheet, collectionVariables, conditionSelector, controlRoles, createTokenValidator, cssExpressionProblem, cssNameCodeSyntax, cssNameVariableName, cssTokenProperty, cssValueTokens, defaultModeAttributeName, defaultModeCondition, deriveCSSName, designDocumentToTailwindJSX, explicitCSSName, exportHTMLBundle, featureConditionCSS, groupOf, iconPackagesFor, isIconPackage, layerComponents, layerMarkup, loadTokenValidator, modeAttribute, modeConditionKey, modeConditionName, parseCSSName, parseFeatureCondition, readCustomProperties, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, sceneNodesToTailwindJSX, sceneNodesToTailwindJSXWithLayers, serializeHTML, stateStyles, stateStylesToCSS, stateStylesToTailwind, stateTailwindClasses, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit };
package/dist/styling.d.ts CHANGED
@@ -22,6 +22,11 @@ interface SceneGraphToDesignOptions {
22
22
  declare function sceneGraphToDesignDocument(graph: SceneGraph, options?: SceneGraphToDesignOptions): DesignDocument;
23
23
  /** Project one node, including its own box, instead of the children of a root. */
24
24
  declare function sceneNodeToDesignDocument(graph: SceneGraph, nodeId: string, options?: Omit<SceneGraphToDesignOptions, 'rootId'>): DesignDocument;
25
+ /**
26
+ * Project several nodes, including each own box, through one token collector: the document then
27
+ * declares the tokens every root references, not only those of the last one.
28
+ */
29
+ declare function sceneNodesToDesignDocument(graph: SceneGraph, nodeIds: readonly string[], options?: Omit<SceneGraphToDesignOptions, 'rootId'>): DesignDocument;
25
30
  //#endregion
26
31
  //#region src/export/bundle.d.ts
27
32
  /** A font face the exported text uses. */
@@ -89,5 +94,5 @@ declare function serializeHTML(document: DesignDocument, options?: SerializeHTML
89
94
  declare const COMPONENT_STYLINGS: readonly ["css", "tailwind"];
90
95
  type ComponentStyling = (typeof COMPONENT_STYLINGS)[number];
91
96
  //#endregion
92
- export { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, SerializeHTMLOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, exportHTMLBundle, sceneGraphToDesignDocument, sceneNodeToDesignDocument, serializeHTML, serializeNode };
97
+ export { COMPONENT_STYLINGS, ComponentStyling, ExportHTMLBundle, ExportHTMLBundleOptions, ExportHTMLFile, SceneGraphToDesignOptions, SerializeHTMLOptions, TailwindStylesheetId, TailwindStylesheetLoader, VectorElementRenderer, WebFontFaceAsset, WebFontFaceRequest, WebFontFaceResolver, exportHTMLBundle, sceneGraphToDesignDocument, sceneNodeToDesignDocument, sceneNodesToDesignDocument, serializeHTML, serializeNode };
93
98
  //# sourceMappingURL=styling.d.ts.map
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/dom-css",
3
- "version": "0.18.0",
3
+ "version": "0.19.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -11,7 +11,7 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "dependencies": {
13
13
  "@acemir/cssom": "^0.9.31",
14
- "@pairdraw/emit": "^0.18.0",
14
+ "@pairdraw/emit": "^0.19.0",
15
15
  "css-tree": "^3.2.1",
16
16
  "cssesc": "^3.0.0",
17
17
  "dedent": "^1.7.2",
@@ -24,7 +24,7 @@
24
24
  "twirlwind": "^0.4.1"
25
25
  },
26
26
  "peerDependencies": {
27
- "@pairdraw/scene-graph": "^0.18.0"
27
+ "@pairdraw/scene-graph": "^0.19.0"
28
28
  },
29
29
  "exports": {
30
30
  ".": {
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The CSS object model shapes this package reads, its own so a consumer never needs the types of
3
+ * the CSS parser it loads at runtime: the browser's, or `@acemir/cssom` where there is none.
4
+ */
5
+ export interface CSSStyleDeclarationLike {
6
+ readonly length: number
7
+ readonly [index: number]: string
8
+ getPropertyValue(property: string): string
9
+ }
10
+
11
+ export interface CSSStyleRuleLike {
12
+ selectorText: string
13
+ style: CSSStyleDeclarationLike
14
+ }
15
+
16
+ export interface CSSGroupingRuleLike {
17
+ cssRules: unknown[]
18
+ }
19
+
20
+ export interface CSSStyleSheetLike {
21
+ cssRules: unknown[]
22
+ }
package/src/export/css.ts CHANGED
@@ -1,6 +1,16 @@
1
- import type { Effect, Fill, ShadowEffect, Stroke, TextLength } from '@pairdraw/scene-graph'
1
+ import type {
2
+ Effect,
3
+ Fill,
4
+ GradientStop,
5
+ SceneNode,
6
+ ShadowEffect,
7
+ Stroke,
8
+ TextLength
9
+ } from '@pairdraw/scene-graph'
2
10
  import { colorToCSS, colorToHex } from '@pairdraw/scene-graph/color'
3
- import type { Color } from '@pairdraw/scene-graph/primitives'
11
+ import { blurSigma } from '@pairdraw/scene-graph/geometry'
12
+ import { gradientPoint } from '@pairdraw/scene-graph/gradient'
13
+ import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
4
14
 
5
15
  import type { DesignStyleDeclaration } from '../types'
6
16
 
@@ -14,35 +24,177 @@ export function fillToCSS(fill: Fill | undefined): string | undefined {
14
24
  return cssColor({ ...fill.color, a: fill.opacity })
15
25
  }
16
26
 
27
+ /** A number CSS reads the same back: six decimals, no trailing zeros or negative zero. */
28
+ function cssNumber(value: number): string {
29
+ const rounded = Number(value.toFixed(6))
30
+ return String(rounded === 0 ? 0 : rounded)
31
+ }
32
+
33
+ function stopToCSS(stop: GradientStop, opacity: number): string {
34
+ const color = cssColor({ ...stop.color, a: stop.color.a * opacity })
35
+ return `${color} ${cssNumber(stop.position * 100)}%`
36
+ }
37
+
38
+ /** The unit-square point as a CSS position pair, percentages of the box's width and height. */
39
+ function positionToCSS(point: Vector): string {
40
+ return `${cssNumber(point.x * 100)}% ${cssNumber(point.y * 100)}%`
41
+ }
42
+
43
+ /**
44
+ * A gradient paint as the CSS gradient that draws it in a `width` × `height` box. The transform
45
+ * maps the box's unit square onto gradient space; its inverse gives the line's ends, the
46
+ * ellipse's centre and radii, or the sweep's start ray. Diamond gradients have no CSS spelling.
47
+ */
48
+ export function gradientFillToCSS(fill: Fill, width: number, height: number): string | undefined {
49
+ const transform = fill.gradientTransform
50
+ const stops = fill.gradientStops
51
+ if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) {
52
+ return undefined
53
+ }
54
+ const painted = stops.map((stop) => stopToCSS(stop, fill.opacity)).join(', ')
55
+ if (fill.type === 'GRADIENT_LINEAR') {
56
+ const start = gradientPoint(transform, { x: 0, y: 0.5 })
57
+ const end = gradientPoint(transform, { x: 1, y: 0.5 })
58
+ const dx = (end.x - start.x) * width
59
+ const dy = (end.y - start.y) * height
60
+ if (dx === 0 && dy === 0) return undefined
61
+ // CSS angles point up at 0deg and turn clockwise; screen y grows downward.
62
+ const degrees = (Math.atan2(dx, -dy) * 180) / Math.PI
63
+ return `linear-gradient(${cssNumber(degrees)}deg, ${painted})`
64
+ }
65
+ if (fill.type !== 'GRADIENT_RADIAL' && fill.type !== 'GRADIENT_ANGULAR') return undefined
66
+ const center = gradientPoint(transform, { x: 0.5, y: 0.5 })
67
+ const edgeX = gradientPoint(transform, { x: 1, y: 0.5 })
68
+ const edgeY = gradientPoint(transform, { x: 0.5, y: 1 })
69
+ const rx = Math.hypot((edgeX.x - center.x) * width, (edgeX.y - center.y) * height)
70
+ const ry = Math.hypot((edgeY.x - center.x) * width, (edgeY.y - center.y) * height)
71
+ if (rx <= 0 || ry <= 0) return undefined
72
+ const at = `at ${positionToCSS(center)}`
73
+ if (fill.type === 'GRADIENT_RADIAL') {
74
+ const shape =
75
+ Math.abs(rx - ry) < 1e-6
76
+ ? `circle ${cssNumber(rx)}px`
77
+ : `ellipse ${cssNumber(rx)}px ${cssNumber(ry)}px`
78
+ return `radial-gradient(${shape} ${at}, ${painted})`
79
+ }
80
+ const degrees =
81
+ (Math.atan2((edgeX.y - center.y) * height, (edgeX.x - center.x) * width) * 180) / Math.PI + 90
82
+ return `conic-gradient(from ${cssNumber(degrees)}deg ${at}, ${painted})`
83
+ }
84
+
85
+ /**
86
+ * The paint stack as `background-image`, top layer first as CSS paints it. Solid paints stay
87
+ * out; the bottom one becomes `background-color`, and a solid above another paint has no CSS
88
+ * spelling here. Image paints export through the element's own source, not this list.
89
+ */
90
+ export function gradientFillsToCSS(
91
+ fills: Fill[],
92
+ width: number,
93
+ height: number
94
+ ): string | undefined {
95
+ const layers: string[] = []
96
+ for (let index = fills.length - 1; index >= 0; index--) {
97
+ const css = gradientFillToCSS(fills[index], width, height)
98
+ if (css) layers.push(css)
99
+ }
100
+ return layers.length > 0 ? layers.join(', ') : undefined
101
+ }
102
+
103
+ export type BorderSide = 'top' | 'right' | 'bottom' | 'left'
104
+
105
+ /**
106
+ * The width of each side of the border a layer's first stroke projects as, zero without one. A
107
+ * border insets the box its absolutely positioned children are placed in, where a stroke does not.
108
+ */
109
+ export function borderWidths(node: SceneNode): Record<BorderSide, number> {
110
+ if (!strokeColorToCSS(node.strokes.at(0))) return { top: 0, right: 0, bottom: 0, left: 0 }
111
+ if (!node.independentStrokeWeights) {
112
+ const weight = node.strokes[0]?.weight ?? 0
113
+ return { top: weight, right: weight, bottom: weight, left: weight }
114
+ }
115
+ return {
116
+ top: node.borderTopWeight,
117
+ right: node.borderRightWeight,
118
+ bottom: node.borderBottomWeight,
119
+ left: node.borderLeftWeight
120
+ }
121
+ }
122
+
17
123
  export function strokeColorToCSS(stroke: Stroke | undefined): string | undefined {
18
124
  if (!stroke?.visible) return undefined
19
125
  return cssColor({ ...stroke.color, a: stroke.opacity })
20
126
  }
21
127
 
22
- function shadowToCSS(effect: ShadowEffect): string {
128
+ function px(value: number): string {
129
+ return `${Number(value.toFixed(3))}px`
130
+ }
131
+
132
+ /**
133
+ * A shadow as `box-shadow` writes it, or as `text-shadow` does without its spread. CSS blurs a
134
+ * shadow by half its blur length, so the length is twice the sigma the canvas blurs it by.
135
+ */
136
+ function shadowToCSS(effect: ShadowEffect, spread = true): string {
23
137
  const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''
24
- return `${inset}${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${cssColor(effect.color)}`
138
+ const parts = [
139
+ `${inset}${px(effect.offset.x)}`,
140
+ px(effect.offset.y),
141
+ px(2 * blurSigma(effect.radius))
142
+ ]
143
+ if (spread) parts.push(px(effect.spread))
144
+ parts.push(cssColor(effect.color))
145
+ return parts.join(' ')
25
146
  }
26
147
 
27
- export function dropShadowToCSS(effect: Effect | undefined): string | undefined {
28
- if (effect?.type !== 'DROP_SHADOW' || !effect.visible) return undefined
29
- return shadowToCSS(effect)
148
+ const isShadow = (effect: Effect): effect is ShadowEffect =>
149
+ effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
150
+
151
+ /**
152
+ * The blurs as the canvas draws them: the first visible layer blur as `filter`, and every
153
+ * background blur in turn as `backdrop-filter`.
154
+ */
155
+ const isLayerBlur = (effect: Effect): effect is ShadowEffect =>
156
+ effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR'
157
+ const isBackgroundBlur = (effect: Effect): effect is ShadowEffect =>
158
+ effect.type === 'BACKGROUND_BLUR'
159
+ const isDropShadow = (effect: Effect): effect is ShadowEffect => effect.type === 'DROP_SHADOW'
160
+
161
+ function addBlurs(style: DesignStyleDeclaration, visible: Effect[]): void {
162
+ const layer = visible.find(isLayerBlur)
163
+ if (layer) style.filter = `blur(${px(blurSigma(layer.radius))})`
164
+ const backdrop = visible.filter(isBackgroundBlur)
165
+ if (backdrop.length > 0) {
166
+ style['backdrop-filter'] = backdrop
167
+ .map((effect) => `blur(${px(blurSigma(effect.radius))})`)
168
+ .join(' ')
169
+ }
30
170
  }
31
171
 
32
- /** Every visible shadow, in order, plus layer and background blur. */
172
+ /**
173
+ * Every visible shadow, in order, plus layer and background blur, blurred as the canvas draws
174
+ * them: CSS's `blur()` takes the Gaussian sigma itself.
175
+ */
33
176
  export function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {
34
177
  const style: DesignStyleDeclaration = {}
35
178
  const visible = effects.filter((effect) => effect.visible)
36
- const shadows = visible.filter(
37
- (effect): effect is ShadowEffect =>
38
- effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
39
- )
40
- if (shadows.length > 0) style['box-shadow'] = shadows.map(shadowToCSS).join(', ')
41
- for (const effect of visible) {
42
- if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR')
43
- style.filter = `blur(${effect.radius}px)`
44
- if (effect.type === 'BACKGROUND_BLUR') style['backdrop-filter'] = `blur(${effect.radius}px)`
179
+ const shadows = visible.filter(isShadow)
180
+ if (shadows.length > 0)
181
+ style['box-shadow'] = shadows.map((effect) => shadowToCSS(effect)).join(', ')
182
+ addBlurs(style, visible)
183
+ return style
184
+ }
185
+
186
+ /**
187
+ * Text's effects: each visible drop shadow as `text-shadow`, which has no spread and shadows the
188
+ * glyphs, and its layer and background blurs. An inner shadow has no form CSS gives text.
189
+ */
190
+ export function textEffectsToCSS(effects: Effect[]): DesignStyleDeclaration {
191
+ const style: DesignStyleDeclaration = {}
192
+ const visible = effects.filter((effect) => effect.visible)
193
+ const shadows = visible.filter(isDropShadow)
194
+ if (shadows.length > 0) {
195
+ style['text-shadow'] = shadows.map((effect) => shadowToCSS(effect, false)).join(', ')
45
196
  }
197
+ addBlurs(style, visible)
46
198
  return style
47
199
  }
48
200
 
@@ -55,3 +207,25 @@ export function lineHeightToCSS(length: TextLength): string {
55
207
  export function letterSpacingToCSS(length: TextLength): string {
56
208
  return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`
57
209
  }
210
+
211
+ /**
212
+ * Room for the spacing CSS puts after a line's last letter. A layer fits and aligns its lines by
213
+ * their glyphs, without that spacing, so a spaced text's box is one spacing wider than its own
214
+ * width and a negative margin takes the spacing back: lines break and align as on the canvas, and
215
+ * the text takes the room it does there. Browsers put the spacing on a glyph's right in either
216
+ * direction, so the margin is on the right. `spacing` is the CSS the text's letter spacing is
217
+ * written as, which may refer to a token.
218
+ */
219
+ export function letterSpacingRoomCSS(
220
+ length: TextLength,
221
+ spacing: string,
222
+ width: string | undefined
223
+ ): DesignStyleDeclaration {
224
+ const literal = spacing === letterSpacingToCSS(length)
225
+ return {
226
+ ...(width !== undefined && { width: `calc(${width} + ${spacing})` }),
227
+ 'margin-right': literal
228
+ ? letterSpacingToCSS({ ...length, value: -length.value })
229
+ : `calc(-1 * ${spacing})`
230
+ }
231
+ }
@@ -2,6 +2,7 @@
2
2
  export {
3
3
  sceneGraphToDesignDocument,
4
4
  sceneNodeToDesignDocument,
5
+ sceneNodesToDesignDocument,
5
6
  type SceneGraphToDesignOptions,
6
7
  type VectorElementRenderer
7
8
  } from './projection'