@pairdraw/dom-css 0.21.0 → 0.22.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 (38) hide show
  1. package/dist/chunks/behaviours/states/layers.js +100 -15
  2. package/dist/chunks/behaviours/states/layers.js.map +1 -1
  3. package/dist/chunks/browser.js +373 -37
  4. package/dist/chunks/browser.js.map +1 -1
  5. package/dist/chunks/import/html.js +66 -11
  6. package/dist/chunks/import/html.js.map +1 -1
  7. package/dist/chunks/import/jsx/source/ast.js +207 -0
  8. package/dist/chunks/import/jsx/source/ast.js.map +1 -0
  9. package/dist/chunks/import/jsx/source/candidates.js +74 -0
  10. package/dist/chunks/import/jsx/source/candidates.js.map +1 -0
  11. package/dist/chunks/import/jsx/source/evaluate.js +213 -0
  12. package/dist/chunks/import/jsx/source/evaluate.js.map +1 -0
  13. package/dist/chunks/import/jsx/source/index.js +448 -0
  14. package/dist/chunks/import/jsx/source/index.js.map +1 -0
  15. package/dist/export.d.ts +16 -3
  16. package/dist/export.js +2 -2
  17. package/dist/index.d.ts +66 -1
  18. package/dist/index.js +5 -2
  19. package/dist/styling.d.ts +9 -2
  20. package/package.json +5 -3
  21. package/src/cssom/browser.ts +63 -0
  22. package/src/export/css.ts +28 -1
  23. package/src/export/index.ts +3 -0
  24. package/src/export/projection.ts +97 -13
  25. package/src/import/flow.ts +127 -6
  26. package/src/import/jsx/source/ast.ts +267 -0
  27. package/src/import/jsx/source/candidates.ts +72 -0
  28. package/src/import/jsx/source/evaluate.ts +300 -0
  29. package/src/import/jsx/source/index.ts +36 -0
  30. package/src/import/jsx/source/render.ts +543 -0
  31. package/src/import/jsx/source/report.ts +49 -0
  32. package/src/import/scene-graph.ts +19 -7
  33. package/src/index.ts +10 -0
  34. package/src/runtime/browser/runtime.ts +13 -5
  35. package/src/runtime/browser/sandbox.ts +176 -27
  36. package/src/runtime/css/scan.ts +45 -0
  37. package/src/runtime/css/url.ts +92 -0
  38. package/src/runtime/headless/styles.ts +71 -15
@@ -212,21 +212,76 @@ function classList(element) {
212
212
  function elementId(element) {
213
213
  return "id" in element.attrs ? element.attrs.id : void 0;
214
214
  }
215
+ /** Reads a CSS identifier from `start`, where a backslash makes the next character a literal. */
216
+ function readIdentifier(selector, start) {
217
+ let value = "";
218
+ let index = start;
219
+ while (index < selector.length) {
220
+ const character = selector[index];
221
+ if (character === "\\") {
222
+ value += selector[index + 1] ?? "";
223
+ index += 2;
224
+ continue;
225
+ }
226
+ if (/[\w-]/.test(character)) {
227
+ value += character;
228
+ index += 1;
229
+ continue;
230
+ }
231
+ break;
232
+ }
233
+ return {
234
+ value,
235
+ end: index
236
+ };
237
+ }
238
+ /** One compound selector, such as `div.card#main` or `w-\[1024px\]`, as its parts. */
239
+ function readCompound(selector) {
240
+ const compound = {
241
+ tag: "",
242
+ classes: [],
243
+ unsupported: false
244
+ };
245
+ let index = 0;
246
+ while (index < selector.length) {
247
+ const character = selector[index];
248
+ if (character === "." || character === "#") {
249
+ const identifier = readIdentifier(selector, index + 1);
250
+ if (!identifier.value) {
251
+ compound.unsupported = true;
252
+ return compound;
253
+ }
254
+ if (character === ".") compound.classes.push(identifier.value);
255
+ else compound.id = identifier.value;
256
+ index = identifier.end;
257
+ continue;
258
+ }
259
+ if (character === "*") {
260
+ index += 1;
261
+ continue;
262
+ }
263
+ if (/[A-Za-z]/.test(character)) {
264
+ const identifier = readIdentifier(selector, index);
265
+ compound.tag = identifier.value;
266
+ index = identifier.end;
267
+ continue;
268
+ }
269
+ compound.unsupported = true;
270
+ return compound;
271
+ }
272
+ return compound;
273
+ }
215
274
  function selectorSpecificity(selector) {
216
- const idCount = selector.match(/#[\w-]+/g)?.length ?? 0;
217
- const classCount = selector.match(/\.[\w-]+/g)?.length ?? 0;
218
- const tagCount = selector.split(/[\s>]+/).filter((part) => /^[a-z]/iu.test(part)).length;
219
- return idCount * 100 + classCount * 10 + tagCount;
275
+ const compound = readCompound(selector);
276
+ return (compound.id ? 100 : 0) + compound.classes.length * 10 + (compound.tag ? 1 : 0);
220
277
  }
221
278
  function matchesSimpleSelector(element, selector) {
222
- if (selector.includes(":") || selector.includes("[")) return false;
223
- const idMatch = selector.match(/#([\w-]+)/);
224
- if (idMatch?.[1] && elementId(element) !== idMatch[1]) return false;
225
- const classes = selector.match(/\.[\w-]+/g) ?? [];
279
+ const compound = readCompound(selector);
280
+ if (compound.unsupported) return false;
281
+ if (compound.id && elementId(element) !== compound.id) return false;
226
282
  const elementClasses = classList(element);
227
- if (!classes.every((name) => elementClasses.has(name.slice(1)))) return false;
228
- const tag = selector.replace(/#[\w-]+/g, "").replace(/\.[\w-]+/g, "");
229
- return tag.length === 0 || tag === "*" || element.tagName.toLowerCase() === tag.toLowerCase();
283
+ if (!compound.classes.every((name) => elementClasses.has(name))) return false;
284
+ return compound.tag === "" || element.tagName.toLowerCase() === compound.tag.toLowerCase();
230
285
  }
231
286
  /** A complex selector as its compounds, rightmost last; `null` when a combinator lacks a side. */
232
287
  function selectorSteps(selector) {
@@ -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'\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 tailwindHTM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AM,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\n/** A compound selector read with its escapes, as Tailwind escapes arbitrary values. */\ninterface CompoundSelector {\n tag: string\n id?: string\n classes: string[]\n /** A selector this runtime cannot match, such as an attribute or pseudo-class one. */\n unsupported: boolean\n}\n\n/** Reads a CSS identifier from `start`, where a backslash makes the next character a literal. */\nfunction readIdentifier(selector: string, start: number): { value: string; end: number } {\n let value = ''\n let index = start\n while (index < selector.length) {\n const character = selector[index]\n if (character === '\\\\') {\n value += selector[index + 1] ?? ''\n index += 2\n continue\n }\n if (/[\\w-]/.test(character)) {\n value += character\n index += 1\n continue\n }\n break\n }\n return { value, end: index }\n}\n\n/** One compound selector, such as `div.card#main` or `w-\\[1024px\\]`, as its parts. */\nfunction readCompound(selector: string): CompoundSelector {\n const compound: CompoundSelector = { tag: '', classes: [], unsupported: false }\n let index = 0\n while (index < selector.length) {\n const character = selector[index]\n if (character === '.' || character === '#') {\n const identifier = readIdentifier(selector, index + 1)\n if (!identifier.value) {\n compound.unsupported = true\n return compound\n }\n if (character === '.') compound.classes.push(identifier.value)\n else compound.id = identifier.value\n index = identifier.end\n continue\n }\n if (character === '*') {\n index += 1\n continue\n }\n if (/[A-Za-z]/.test(character)) {\n const identifier = readIdentifier(selector, index)\n compound.tag = identifier.value\n index = identifier.end\n continue\n }\n // A pseudo-class, attribute selector, or namespace this runtime does not match.\n compound.unsupported = true\n return compound\n }\n return compound\n}\n\nfunction selectorSpecificity(selector: string): number {\n const compound = readCompound(selector)\n // A tag counts once per compound; the universal selector, alone or as in `*.card`, counts zero.\n return (compound.id ? 100 : 0) + compound.classes.length * 10 + (compound.tag ? 1 : 0)\n}\n\nfunction matchesSimpleSelector(element: DesignElement, selector: string): boolean {\n const compound = readCompound(selector)\n if (compound.unsupported) return false\n if (compound.id && elementId(element) !== compound.id) return false\n const elementClasses = classList(element)\n if (!compound.classes.every((name) => elementClasses.has(name))) return false\n return compound.tag === '' || element.tagName.toLowerCase() === compound.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 tail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AG,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"}
@@ -0,0 +1,207 @@
1
+ import { compact } from "es-toolkit/array";
2
+ import { parse } from "acorn";
3
+ import { transform } from "sucrase";
4
+ //#region src/import/jsx/source/report.ts
5
+ /** Pasted source that a reader cannot turn into layers. */
6
+ var CodeSourceError = class extends Error {
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "CodeSourceError";
10
+ }
11
+ };
12
+ /** The most layers one paste may draw, so a pathological source cannot stall a document. */
13
+ const MAX_CODE_ELEMENTS = 2e3;
14
+ /** Pasted source that draws more than a document should take, which a paste refuses by size. */
15
+ var CodeTooLargeError = class extends CodeSourceError {
16
+ constructor(message) {
17
+ super(message);
18
+ this.name = "CodeTooLargeError";
19
+ }
20
+ };
21
+ function emptyReport() {
22
+ return {
23
+ placeholders: 0,
24
+ componentsAsFrames: 0,
25
+ droppedProps: 0,
26
+ approximations: 0,
27
+ imagesAsPlaceholders: 0
28
+ };
29
+ }
30
+ //#endregion
31
+ //#region src/import/jsx/source/ast.ts
32
+ /** Whether a value is a function the paste defines, rather than an object it describes. */
33
+ function isLiteralFunction(value) {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value) && "kind" in value;
35
+ }
36
+ /**
37
+ * A name a paste cannot know, such as a prop the caller passes or a hook's result. It shadows a
38
+ * module binding of the same name, the way a parameter shadows one in JavaScript.
39
+ */
40
+ const UNKNOWN = Symbol("unknown");
41
+ const TRANSFORM_OPTIONS = {
42
+ transforms: ["typescript", "jsx"],
43
+ jsxPragma: "__h",
44
+ jsxFragmentPragma: "__fragment",
45
+ production: true
46
+ };
47
+ /** The program a pasted source stands for, after TypeScript and JSX turn into plain JavaScript. */
48
+ function parseSource(source) {
49
+ const trimmed = source.trim();
50
+ if (!trimmed) throw new CodeSourceError("Nothing to paste");
51
+ let code;
52
+ try {
53
+ code = transform(trimmed, TRANSFORM_OPTIONS).code;
54
+ } catch (error) {
55
+ throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`);
56
+ }
57
+ try {
58
+ return parse(code, {
59
+ ecmaVersion: "latest",
60
+ sourceType: "module",
61
+ allowReturnOutsideFunction: true
62
+ });
63
+ } catch (error) {
64
+ throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`);
65
+ }
66
+ }
67
+ function errorMessage(error) {
68
+ return error instanceof Error ? error.message : String(error);
69
+ }
70
+ /** Whether a call builds an element, which is what makes a function a component here. */
71
+ function isElementCall(node) {
72
+ return node?.type === "CallExpression" && calleeName(node) === "__h";
73
+ }
74
+ function calleeName(node) {
75
+ return node.callee.type === "Identifier" ? node.callee.name : void 0;
76
+ }
77
+ function memberName(node) {
78
+ if (node.object.type !== "Identifier") return void 0;
79
+ const object = node.object.name;
80
+ if (!node.computed && node.property.type === "Identifier") return `${object}.${node.property.name}`;
81
+ return object;
82
+ }
83
+ function propertyKey(property) {
84
+ if (property.computed) return null;
85
+ if (property.key.type === "Identifier") return property.key.name;
86
+ return typeof property.key.value === "string" ? String(property.key.value) : null;
87
+ }
88
+ function functionNode(node) {
89
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression" || node.type === "ArrowFunctionExpression") return node;
90
+ return null;
91
+ }
92
+ function declarationOf(node) {
93
+ if (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") return node.declaration ?? null;
94
+ return node;
95
+ }
96
+ /** `h1` reads as `H1` and `my-widget` as `MyWidget`, so a layer is named after its tag. */
97
+ function pascalCase(value) {
98
+ return compact(value.split(/[^a-zA-Z0-9]+/).map((part) => part ? part[0].toUpperCase() + part.slice(1) : "")).join("");
99
+ }
100
+ /** Whether a function's body builds an element anywhere in its own statements. */
101
+ function drawsElements(node) {
102
+ if (isElementCall(node)) return true;
103
+ return childNodes(node).some((child) => drawsElements(child));
104
+ }
105
+ /** Children of each node kind, read through the fields acorn's own interfaces declare. */
106
+ const CHILD_READERS = {
107
+ Program: (node) => node.body,
108
+ BlockStatement: (node) => node.body,
109
+ ExportNamedDeclaration: (node) => nodesIn(node.declaration),
110
+ ExportDefaultDeclaration: (node) => nodesIn(node.declaration),
111
+ ExpressionStatement: (node) => [node.expression],
112
+ ReturnStatement: (node) => nodesIn(node.argument),
113
+ IfStatement: (node) => {
114
+ const statement = node;
115
+ return [
116
+ statement.test,
117
+ statement.consequent,
118
+ ...nodesIn(statement.alternate)
119
+ ];
120
+ },
121
+ VariableDeclaration: (node) => node.declarations,
122
+ VariableDeclarator: (node) => nodesIn(node.init),
123
+ FunctionDeclaration: (node) => functionChildren(node),
124
+ FunctionExpression: (node) => functionChildren(node),
125
+ ArrowFunctionExpression: (node) => functionChildren(node),
126
+ CallExpression: (node) => {
127
+ const call = node;
128
+ return [call.callee, ...call.arguments];
129
+ },
130
+ MemberExpression: (node) => {
131
+ const member = node;
132
+ return [member.object, member.property];
133
+ },
134
+ ObjectExpression: (node) => node.properties,
135
+ Property: (node) => {
136
+ const property = node;
137
+ return [property.key, property.value];
138
+ },
139
+ ArrayExpression: (node) => nodesIn(node.elements),
140
+ SpreadElement: (node) => nodesIn(node.argument),
141
+ TemplateLiteral: (node) => node.expressions,
142
+ UnaryExpression: (node) => [node.argument],
143
+ BinaryExpression: (node) => {
144
+ const operation = node;
145
+ return [operation.left, operation.right];
146
+ },
147
+ LogicalExpression: (node) => {
148
+ const operation = node;
149
+ return [operation.left, operation.right];
150
+ },
151
+ ConditionalExpression: (node) => {
152
+ const conditional = node;
153
+ return [
154
+ conditional.test,
155
+ conditional.consequent,
156
+ conditional.alternate
157
+ ];
158
+ },
159
+ AssignmentPattern: (node) => {
160
+ const pattern = node;
161
+ return [pattern.left, pattern.right];
162
+ },
163
+ ObjectPattern: (node) => node.properties,
164
+ RestElement: (node) => nodesIn(node.argument)
165
+ };
166
+ function functionChildren(node) {
167
+ return [...node.params, node.body];
168
+ }
169
+ /** The nodes a node holds, so a walk reads children rather than every property of a node. */
170
+ function childNodes(node) {
171
+ return CHILD_READERS[node.type]?.(node) ?? [];
172
+ }
173
+ function nodesIn(value) {
174
+ if (Array.isArray(value)) return value.filter(isNode);
175
+ return isNode(value) ? [value] : [];
176
+ }
177
+ function isNode(value) {
178
+ return typeof value === "object" && value !== null && "type" in value && "start" in value;
179
+ }
180
+ /** The source an expression names, for the text a placeholder shows. */
181
+ function expressionText(node) {
182
+ switch (node.type) {
183
+ case "Identifier": return node.name;
184
+ case "Literal": {
185
+ const value = node.value;
186
+ return typeof value === "string" ? JSON.stringify(value) : String(value);
187
+ }
188
+ case "MemberExpression": {
189
+ const member = node;
190
+ const object = expressionText(member.object);
191
+ if (!member.computed && member.property.type === "Identifier") return `${object}.${member.property.name}`;
192
+ return `${object}[${expressionText(member.property)}]`;
193
+ }
194
+ case "CallExpression": {
195
+ const call = node;
196
+ const argumentsText = call.arguments.map((argument) => expressionText(argument)).join(", ");
197
+ return `${expressionText(call.callee)}(${argumentsText})`;
198
+ }
199
+ case "ConditionalExpression": return `${expressionText(node.test)} ? …`;
200
+ case "TemplateLiteral": return "`…`";
201
+ default: return "…";
202
+ }
203
+ }
204
+ //#endregion
205
+ export { CodeSourceError, CodeTooLargeError, MAX_CODE_ELEMENTS, UNKNOWN, calleeName, declarationOf, drawsElements, emptyReport, expressionText, functionNode, isElementCall, isLiteralFunction, memberName, parseSource, pascalCase, propertyKey };
206
+
207
+ //# sourceMappingURL=ast.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ast.js","names":[],"sources":["../../../../../src/import/jsx/source/report.ts","../../../../../src/import/jsx/source/ast.ts"],"sourcesContent":["import type { DesignNode } from '#dom-css/types'\n\n/** Pasted source that a reader cannot turn into layers. */\nexport class CodeSourceError extends Error {\n constructor(message: string) {\n super(message)\n this.name = 'CodeSourceError'\n }\n}\n\n/** The most layers one paste may draw, so a pathological source cannot stall a document. */\nexport const MAX_CODE_ELEMENTS = 2_000\n\n/** Pasted source that draws more than a document should take, which a paste refuses by size. */\nexport class CodeTooLargeError extends CodeSourceError {\n constructor(message: string) {\n super(message)\n this.name = 'CodeTooLargeError'\n }\n}\n\n/** What a paste could not keep, so the caller can tell the user in one toast. */\nexport interface CodeReport {\n /** Expressions rendered as their own source text. */\n placeholders: number\n /** Components with no definition in the paste, drawn as frames under their name. */\n componentsAsFrames: number\n /** Attributes an element has no layer property for, and props no component could take. */\n droppedProps: number\n /** Branches and values read from one possibility rather than known exactly. */\n approximations: number\n /** Images whose source a paste cannot load, drawn at their box size. */\n imagesAsPlaceholders: number\n}\n\nexport interface CodeTree {\n children: DesignNode[]\n report: CodeReport\n}\n\nexport function emptyReport(): CodeReport {\n return {\n placeholders: 0,\n componentsAsFrames: 0,\n droppedProps: 0,\n approximations: 0,\n imagesAsPlaceholders: 0\n }\n}\n","import { parse } from 'acorn'\nimport type {\n ArrowFunctionExpression,\n ArrayExpression,\n AssignmentPattern,\n AssignmentProperty,\n BinaryExpression,\n BlockStatement,\n CallExpression,\n ConditionalExpression,\n ExportDefaultDeclaration,\n ExportNamedDeclaration,\n ExpressionStatement,\n FunctionDeclaration,\n FunctionExpression,\n Identifier,\n IfStatement,\n LogicalExpression,\n MemberExpression,\n ModuleDeclaration,\n Node,\n ObjectExpression,\n ObjectPattern,\n Program,\n Property,\n RestElement,\n ReturnStatement,\n SpreadElement,\n Statement,\n TemplateLiteral,\n UnaryExpression,\n VariableDeclaration,\n VariableDeclarator\n} from 'acorn'\nimport { compact } from 'es-toolkit/array'\nimport { transform } from 'sucrase'\n\nimport { CodeSourceError } from './report'\n\n/** A value the reader could work out without running anything. */\nexport type LiteralValue =\n | string\n | number\n | boolean\n | LiteralFunction\n | LiteralValue[]\n | LiteralObject\n\nexport interface LiteralObject {\n [key: string]: LiteralValue\n}\n\n/** Whether a value is a function the paste defines, rather than an object it describes. */\nexport function isLiteralFunction(value: unknown): value is LiteralFunction {\n return typeof value === 'object' && value !== null && !Array.isArray(value) && 'kind' in value\n}\n\nexport interface LiteralFunction {\n kind: 'function'\n node: FunctionDeclaration | FunctionExpression | ArrowFunctionExpression\n env: Env\n name?: string\n}\n\n/**\n * A name a paste cannot know, such as a prop the caller passes or a hook's result. It shadows a\n * module binding of the same name, the way a parameter shadows one in JavaScript.\n */\nexport const UNKNOWN = Symbol('unknown')\n\nexport type Env = Map<string, LiteralValue | typeof UNKNOWN>\n\nconst TRANSFORM_OPTIONS = {\n transforms: ['typescript', 'jsx'] as Array<'typescript' | 'jsx'>,\n jsxPragma: '__h',\n jsxFragmentPragma: '__fragment',\n production: true\n}\n\n/** The program a pasted source stands for, after TypeScript and JSX turn into plain JavaScript. */\nexport function parseSource(source: string): Program {\n const trimmed = source.trim()\n if (!trimmed) throw new CodeSourceError('Nothing to paste')\n let code: string\n try {\n code = transform(trimmed, TRANSFORM_OPTIONS).code\n } catch (error) {\n throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`)\n }\n try {\n return parse(code, {\n ecmaVersion: 'latest',\n sourceType: 'module',\n allowReturnOutsideFunction: true\n })\n } catch (error) {\n throw new CodeSourceError(`Not readable as JSX or HTML: ${errorMessage(error)}`)\n }\n}\n\nfunction errorMessage(error: unknown): string {\n return error instanceof Error ? error.message : String(error)\n}\n\n/** Whether a call builds an element, which is what makes a function a component here. */\nexport function isElementCall(node: Node | null | undefined): boolean {\n return node?.type === 'CallExpression' && calleeName(node as CallExpression) === '__h'\n}\n\nexport function calleeName(node: CallExpression): string | undefined {\n return node.callee.type === 'Identifier' ? node.callee.name : undefined\n}\n\nexport function memberName(node: MemberExpression): string | undefined {\n if (node.object.type !== 'Identifier') return undefined\n const object = node.object.name\n if (!node.computed && node.property.type === 'Identifier') {\n return `${object}.${node.property.name}`\n }\n return object\n}\n\nexport function propertyKey(property: Property | AssignmentProperty): string | null {\n if (property.computed) return null\n if (property.key.type === 'Identifier') return property.key.name\n return typeof (property.key as { value?: unknown }).value === 'string'\n ? String((property.key as { value?: unknown }).value)\n : null\n}\n\nexport function functionNode(\n node: Node\n): FunctionDeclaration | FunctionExpression | ArrowFunctionExpression | null {\n if (\n node.type === 'FunctionDeclaration' ||\n node.type === 'FunctionExpression' ||\n node.type === 'ArrowFunctionExpression'\n ) {\n return node as FunctionDeclaration | FunctionExpression | ArrowFunctionExpression\n }\n return null\n}\n\nexport function declarationOf(node: Statement | ModuleDeclaration): Node | null {\n if (node.type === 'ExportNamedDeclaration' || node.type === 'ExportDefaultDeclaration') {\n return node.declaration ?? null\n }\n return node\n}\n\n/** `h1` reads as `H1` and `my-widget` as `MyWidget`, so a layer is named after its tag. */\nexport function pascalCase(value: string): string {\n return compact(\n value.split(/[^a-zA-Z0-9]+/).map((part) => (part ? part[0].toUpperCase() + part.slice(1) : ''))\n ).join('')\n}\n\n/** Whether a function's body builds an element anywhere in its own statements. */\nexport function drawsElements(node: Node): boolean {\n if (isElementCall(node)) return true\n return childNodes(node).some((child) => drawsElements(child))\n}\n\n/** Children of each node kind, read through the fields acorn's own interfaces declare. */\nconst CHILD_READERS: Partial<Record<string, (node: Node) => Node[]>> = {\n Program: (node) => (node as Program).body,\n BlockStatement: (node) => (node as BlockStatement).body,\n ExportNamedDeclaration: (node) => nodesIn((node as ExportNamedDeclaration).declaration),\n ExportDefaultDeclaration: (node) => nodesIn((node as ExportDefaultDeclaration).declaration),\n ExpressionStatement: (node) => [(node as ExpressionStatement).expression],\n ReturnStatement: (node) => nodesIn((node as ReturnStatement).argument),\n IfStatement: (node) => {\n const statement = node as IfStatement\n return [statement.test, statement.consequent, ...nodesIn(statement.alternate)]\n },\n VariableDeclaration: (node) => (node as VariableDeclaration).declarations,\n VariableDeclarator: (node) => nodesIn((node as VariableDeclarator).init),\n FunctionDeclaration: (node) => functionChildren(node as FunctionDeclaration),\n FunctionExpression: (node) => functionChildren(node as FunctionExpression),\n ArrowFunctionExpression: (node) => functionChildren(node as ArrowFunctionExpression),\n CallExpression: (node) => {\n const call = node as CallExpression\n return [call.callee, ...call.arguments]\n },\n MemberExpression: (node) => {\n const member = node as MemberExpression\n return [member.object, member.property]\n },\n ObjectExpression: (node) => (node as ObjectExpression).properties,\n Property: (node) => {\n const property = node as Property\n return [property.key, property.value]\n },\n ArrayExpression: (node) => nodesIn((node as ArrayExpression).elements),\n SpreadElement: (node) => nodesIn((node as SpreadElement).argument),\n TemplateLiteral: (node) => (node as TemplateLiteral).expressions,\n UnaryExpression: (node) => [(node as UnaryExpression).argument],\n BinaryExpression: (node) => {\n const operation = node as BinaryExpression\n return [operation.left, operation.right]\n },\n LogicalExpression: (node) => {\n const operation = node as LogicalExpression\n return [operation.left, operation.right]\n },\n ConditionalExpression: (node) => {\n const conditional = node as ConditionalExpression\n return [conditional.test, conditional.consequent, conditional.alternate]\n },\n AssignmentPattern: (node) => {\n const pattern = node as AssignmentPattern\n return [pattern.left, pattern.right]\n },\n ObjectPattern: (node) => (node as ObjectPattern).properties,\n RestElement: (node) => nodesIn((node as RestElement).argument)\n}\n\nfunction functionChildren(\n node: FunctionDeclaration | FunctionExpression | ArrowFunctionExpression\n): Node[] {\n return [...node.params, node.body]\n}\n\n/** The nodes a node holds, so a walk reads children rather than every property of a node. */\nexport function childNodes(node: Node): Node[] {\n return CHILD_READERS[node.type]?.(node) ?? []\n}\n\nfunction nodesIn(value: unknown): Node[] {\n if (Array.isArray(value)) return value.filter(isNode)\n return isNode(value) ? [value] : []\n}\n\nfunction isNode(value: unknown): value is Node {\n return typeof value === 'object' && value !== null && 'type' in value && 'start' in value\n}\n\n/** The source an expression names, for the text a placeholder shows. */\nexport function expressionText(node: Node): string {\n switch (node.type) {\n case 'Identifier':\n return (node as Identifier).name\n case 'Literal': {\n const value = (node as { value?: unknown }).value\n return typeof value === 'string' ? JSON.stringify(value) : String(value)\n }\n case 'MemberExpression': {\n const member = node as MemberExpression\n const object = expressionText(member.object)\n if (!member.computed && member.property.type === 'Identifier') {\n return `${object}.${member.property.name}`\n }\n return `${object}[${expressionText(member.property)}]`\n }\n case 'CallExpression': {\n const call = node as CallExpression\n const argumentsText = call.arguments.map((argument) => expressionText(argument)).join(', ')\n return `${expressionText(call.callee)}(${argumentsText})`\n }\n case 'ConditionalExpression':\n return `${expressionText((node as ConditionalExpression).test)} ? …`\n case 'TemplateLiteral':\n return '`…`'\n default:\n return '…'\n }\n}\n"],"mappings":";;;;;AAGA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;;AAGA,MAAa,oBAAoB;;AAGjC,IAAa,oBAAb,cAAuC,gBAAgB;CACrD,YAAY,SAAiB;EAC3B,MAAM,OAAO;EACb,KAAK,OAAO;CACd;AACF;AAqBA,SAAgB,cAA0B;CACxC,OAAO;EACL,cAAc;EACd,oBAAoB;EACpB,cAAc;EACd,gBAAgB;EAChB,sBAAsB;CACxB;AACF;;;;ACKA,SAAgB,kBAAkB,OAA0C;CAC1E,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK,KAAK,UAA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,KAAK,WAAW;GACd,MAAM,QAAS,KAA6B;GAC5C,OAAO,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI,OAAO,KAAK;EACzE;EACA,KAAK,oBAAoB;GACvB,MAAM,SAAS;GACf,MAAM,SAAS,eAAe,OAAO,MAAM;GAC3C,IAAI,CAAC,OAAO,YAAY,OAAO,SAAS,SAAS,cAC/C,OAAO,GAAG,OAAO,GAAG,OAAO,SAAS;GAEtC,OAAO,GAAG,OAAO,GAAG,eAAe,OAAO,QAAQ,EAAE;EACtD;EACA,KAAK,kBAAkB;GACrB,MAAM,OAAO;GACb,MAAM,gBAAgB,KAAK,UAAU,KAAK,aAAa,eAAe,QAAQ,CAAC,CAAC,CAAC,KAAK,IAAI;GAC1F,OAAO,GAAG,eAAe,KAAK,MAAM,EAAE,GAAG,cAAc;EACzD;EACA,KAAK,yBACH,OAAO,GAAG,eAAgB,KAA+B,IAAI,EAAE;EACjE,KAAK,mBACH,OAAO;EACT,SACE,OAAO;CACX;AACF"}
@@ -0,0 +1,74 @@
1
+ //#region src/import/jsx/source/candidates.ts
2
+ /** Variants whose utility draws nothing in a layer, so the whole class goes. */
3
+ const LAYERLESS_VARIANTS = /* @__PURE__ */ new Set([
4
+ "before",
5
+ "after",
6
+ "placeholder",
7
+ "file",
8
+ "marker",
9
+ "selection"
10
+ ]);
11
+ /** The utilities a class list names, with one base utility per class and its variant count. */
12
+ function tailwindUtilities(classes) {
13
+ const candidates = /* @__PURE__ */ new Set();
14
+ let variantsStripped = 0;
15
+ for (const token of classes) {
16
+ if (!token) continue;
17
+ const base = baseUtility(token);
18
+ if (base === null) continue;
19
+ if (base.variant) variantsStripped += 1;
20
+ candidates.add(base.name);
21
+ }
22
+ return {
23
+ candidates: [...candidates],
24
+ variantsStripped
25
+ };
26
+ }
27
+ /** `md:hover:bg-slate-50` → `bg-slate-50`; `before:content-['*']` → nothing. */
28
+ function baseUtility(token) {
29
+ const variants = [];
30
+ let depth = 0;
31
+ let start = 0;
32
+ for (let index = 0; index < token.length; index++) {
33
+ const character = token[index];
34
+ if (character === "[") depth++;
35
+ else if (character === "]") depth = Math.max(0, depth - 1);
36
+ else if (character === ":" && depth === 0) {
37
+ variants.push(token.slice(start, index));
38
+ start = index + 1;
39
+ }
40
+ }
41
+ const utility = token.slice(start);
42
+ if (variants.length === 0) return {
43
+ name: token,
44
+ variant: false
45
+ };
46
+ if (variants.some((variant) => LAYERLESS_VARIANTS.has(variant))) return null;
47
+ if (!utility || utility.startsWith("[")) return null;
48
+ return {
49
+ name: utility,
50
+ variant: true
51
+ };
52
+ }
53
+ /** The classes an element names; an element with no classes names none. */
54
+ function classText(attrs) {
55
+ return attrs.class ?? "";
56
+ }
57
+ /**
58
+ * The Tailwind utilities pasted markup names, with the base utility kept from every variant
59
+ * (`md:flex-row` asks for `flex-row` here), so a paste styles the same at any canvas width.
60
+ */
61
+ function tailwindCandidates(nodes) {
62
+ const classes = [];
63
+ const visit = (node) => {
64
+ if (node.type !== "element") return;
65
+ classes.push(...classText(node.attrs).split(/\s+/));
66
+ for (const child of node.children) visit(child);
67
+ };
68
+ for (const node of nodes) visit(node);
69
+ return tailwindUtilities(classes);
70
+ }
71
+ //#endregion
72
+ export { tailwindCandidates, tailwindUtilities };
73
+
74
+ //# sourceMappingURL=candidates.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"candidates.js","names":[],"sources":["../../../../../src/import/jsx/source/candidates.ts"],"sourcesContent":["import type { DesignNode } from '#dom-css/types'\n\n/** Variants whose utility draws nothing in a layer, so the whole class goes. */\nconst LAYERLESS_VARIANTS = new Set([\n 'before',\n 'after',\n 'placeholder',\n 'file',\n 'marker',\n 'selection'\n])\n\n/** The utilities a class list names, with one base utility per class and its variant count. */\nexport function tailwindUtilities(classes: Iterable<string>): {\n candidates: string[]\n variantsStripped: number\n} {\n const candidates = new Set<string>()\n let variantsStripped = 0\n for (const token of classes) {\n if (!token) continue\n const base = baseUtility(token)\n if (base === null) continue\n if (base.variant) variantsStripped += 1\n candidates.add(base.name)\n }\n return { candidates: [...candidates], variantsStripped }\n}\n\n/** `md:hover:bg-slate-50` → `bg-slate-50`; `before:content-['*']` → nothing. */\nexport function baseUtility(token: string): { name: string; variant: boolean } | null {\n const variants: string[] = []\n let depth = 0\n let start = 0\n for (let index = 0; index < token.length; index++) {\n const character = token[index]\n if (character === '[') depth++\n else if (character === ']') depth = Math.max(0, depth - 1)\n else if (character === ':' && depth === 0) {\n variants.push(token.slice(start, index))\n start = index + 1\n }\n }\n const utility = token.slice(start)\n if (variants.length === 0) return { name: token, variant: false }\n if (variants.some((variant) => LAYERLESS_VARIANTS.has(variant))) return null\n if (!utility || utility.startsWith('[')) return null\n return { name: utility, variant: true }\n}\n\n/** The classes an element names; an element with no classes names none. */\nfunction classText(attrs: Record<string, string | undefined>): string {\n return attrs.class ?? ''\n}\n\n/**\n * The Tailwind utilities pasted markup names, with the base utility kept from every variant\n * (`md:flex-row` asks for `flex-row` here), so a paste styles the same at any canvas width.\n */\nexport function tailwindCandidates(nodes: readonly DesignNode[]): {\n candidates: string[]\n variantsStripped: number\n} {\n const classes: string[] = []\n const visit = (node: DesignNode): void => {\n if (node.type !== 'element') return\n classes.push(...classText(node.attrs).split(/\\s+/))\n for (const child of node.children) visit(child)\n }\n for (const node of nodes) visit(node)\n return tailwindUtilities(classes)\n}\n"],"mappings":";;AAGA,MAAM,qCAAqB,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;AAGD,SAAgB,kBAAkB,SAGhC;CACA,MAAM,6BAAa,IAAI,IAAY;CACnC,IAAI,mBAAmB;CACvB,KAAK,MAAM,SAAS,SAAS;EAC3B,IAAI,CAAC,OAAO;EACZ,MAAM,OAAO,YAAY,KAAK;EAC9B,IAAI,SAAS,MAAM;EACnB,IAAI,KAAK,SAAS,oBAAoB;EACtC,WAAW,IAAI,KAAK,IAAI;CAC1B;CACA,OAAO;EAAE,YAAY,CAAC,GAAG,UAAU;EAAG;CAAiB;A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