@pairdraw/dom-css 0.20.0 → 0.21.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"layers.js","names":["px","#graph","#chain","#drawsResolved","px"],"sources":["../../../../src/tokens/names.ts","../../../../src/export/css.ts","../../../../src/tokens/values.ts","../../../../src/tokens/formula.ts","../../../../src/tokens/validate.ts","../../../../src/tokens/stylesheet.ts","../../../../src/tokens/references.ts","../../../../src/export/grid.ts","../../../../src/export/position.ts","../../../../src/export/text.ts","../../../../src/export/projection.ts","../../../../src/behaviours/states/layers.ts"],"sourcesContent":["import { compact } from 'es-toolkit/array'\nimport valueParser from 'postcss-value-parser'\nimport { themeNamespaces, type ThemeNamespace } from 'twirlwind'\n\nimport type { SceneGraph, Variable, VariableScope } from '@pairdraw/scene-graph'\n\n/** Every variable, collection by collection, in each collection's own order. */\nexport function collectionVariables(\n source: Pick<SceneGraph, 'variables' | 'variableCollections'>\n): Variable[] {\n return compact(\n [...source.variableCollections.values()].flatMap((collection) =>\n collection.variableIds.map((id) => source.variables.get(id))\n )\n )\n}\n\nconst SCOPE_NAMESPACES: Partial<Record<VariableScope, ThemeNamespace>> = {\n CORNER_RADIUS: 'radius',\n GAP: 'spacing',\n WIDTH_HEIGHT: 'spacing',\n FONT_SIZE: 'text',\n LINE_HEIGHT: 'leading',\n LETTER_SPACING: 'tracking',\n FONT_FAMILY: 'font',\n FONT_STYLE: 'font-weight',\n EFFECT_FLOAT: 'blur'\n}\n\n/** Leading name segments that already say the namespace, so `Color/primary` is not `--color-color-primary`. */\nconst NAMESPACE_WORDS: Record<string, ThemeNamespace> = {\n ...Object.fromEntries(themeNamespaces.map((namespace) => [namespace, namespace])),\n colors: 'color',\n colour: 'color',\n colours: 'color',\n space: 'spacing',\n radii: 'radius',\n rounded: 'radius',\n corner: 'radius',\n corners: 'radius',\n 'font-size': 'text',\n 'line-height': 'leading',\n 'letter-spacing': 'tracking',\n fonts: 'font',\n 'font-family': 'font',\n weight: 'font-weight',\n shadows: 'shadow'\n}\n\n/**\n * Lowercase words joined by `-`, keeping digits on their word, as Tailwind keys do: `Text/2xl`\n * is `text-2xl`, `Heading/H1` is `heading-h1`, `brandPrimary` is `brand-primary`. es-toolkit's\n * `kebabCase` splits digits off (`text-2-xl`), which no design system writes.\n */\nexport function tokenSlug(text: string): string {\n const words = text\n .normalize('NFKC')\n .replaceAll(/(\\p{Ll})(\\p{Lu})/gu, '$1 $2')\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n return compact(words).join('-')\n}\n\n/** The Tailwind namespace a token belongs to, from its type, its scopes, then its leading name segment. */\nexport function variableNamespace(variable: Variable): ThemeNamespace | undefined {\n if (variable.type === 'COLOR') return 'color'\n const fromScopes = new Set((variable.scopes ?? []).map((scope) => SCOPE_NAMESPACES[scope]))\n const [only] = fromScopes\n if (fromScopes.size === 1 && only) return only\n return NAMESPACE_WORDS[tokenSlug(variable.name.split('/')[0] ?? '')]\n}\n\n/**\n * The custom property a code snippet names, without `--`: `var(--brand)`, `var(--brand, red)`\n * and `--brand` all name `brand`. A snippet that is anything else, such as a Tailwind class,\n * names none.\n */\nexport function parseCSSName(snippet: string | undefined): string | undefined {\n const nodes = valueParser(snippet ?? '').nodes.filter((node) => node.type !== 'space')\n const [node] = nodes\n if (nodes.length !== 1) return undefined\n const word =\n node.type === 'function' && node.value === 'var' && 'nodes' in node\n ? node.nodes.find((child) => child.type !== 'space')\n : node\n return word?.type === 'word' && word.value.startsWith('--') && word.value.length > 2\n ? word.value.slice(2)\n : undefined\n}\n\n/** The name `codeSyntax.WEB` gives the token, if it gives one. */\nexport function explicitCSSName(variable: Variable): string | undefined {\n return parseCSSName(variable.codeSyntax?.WEB)\n}\n\n/**\n * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. A group the next segment\n * repeats is said once, so `Gap/gap-1` is `gap-1`, as kits that mirror Tailwind classes name them. Two tokens can derive\n * the same name, so stylesheet output takes names from `variableCSSNames`, which makes them unique.\n */\nexport function deriveCSSName(variable: Variable): string {\n const namespace = variableNamespace(variable)\n const segments = compact(variable.name.split('/').map(tokenSlug))\n if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ''] === namespace) {\n segments.shift()\n }\n const body =\n segments\n .filter((segment, index) => {\n const next = segments.at(index + 1)\n return next === undefined || (next !== segment && !next.startsWith(`${segment}-`))\n })\n .join('-') || 'token'\n if (!namespace || body === namespace || body.startsWith(`${namespace}-`)) return body\n return `${namespace}-${body}`\n}\n\n/**\n * Document-wide custom property names, without `--`. The first token whose `WEB` snippet claims\n * a name keeps it; later claimants, which Figma files do contain, and derived names that collide\n * take a derived name with a numeric suffix, in iteration order.\n */\nexport function variableCSSNames(variables: Iterable<Variable>): Map<string, string> {\n const list = [...variables]\n const names = new Map<string, string>()\n const taken = new Set<string>()\n for (const variable of list) {\n const name = explicitCSSName(variable)\n if (!name || taken.has(name)) continue\n names.set(variable.id, name)\n taken.add(name)\n }\n for (const variable of list) {\n if (names.has(variable.id)) continue\n const base = deriveCSSName(variable)\n let name = base\n for (let n = 2; taken.has(name); n++) name = `${base}-${n}`\n names.set(variable.id, name)\n taken.add(name)\n }\n return names\n}\n\n/** The `WEB` snippet that names a token in Figma's Dev Mode and here. */\nexport function cssNameCodeSyntax(name: string): string {\n return `var(--${name})`\n}\n\n/** Namespaces longest first, so `font-weight-bold` reads as `font-weight`, not `font`. */\nconst NAMESPACES_BY_LENGTH = [...themeNamespaces].sort((a, b) => b.length - a.length)\n\n/**\n * The variable name a custom property reads as: a Tailwind namespace becomes the group, so\n * `color-gray-50` is `color/gray-50` and `radius-md` is `radius/md`; any other name stays as it\n * is. Variables made this way keep the property in their `WEB` code syntax, so the stylesheet\n * writes the same name back.\n */\nexport function cssNameVariableName(name: string): string {\n const namespace = NAMESPACES_BY_LENGTH.find((candidate) => name.startsWith(`${candidate}-`))\n return namespace ? `${namespace}/${name.slice(namespace.length + 1)}` : name\n}\n","import type {\n Effect,\n Fill,\n GradientStop,\n SceneNode,\n ShadowEffect,\n Stroke,\n TextLength\n} from '@pairdraw/scene-graph'\nimport { colorToCSS, colorToHex } from '@pairdraw/scene-graph/color'\nimport { blurSigma } from '@pairdraw/scene-graph/geometry'\nimport { gradientPoint } from '@pairdraw/scene-graph/gradient'\nimport type { Color, Vector } from '@pairdraw/scene-graph/primitives'\n\nimport type { DesignStyleDeclaration } from '../types'\n\n/** Opaque colors as hex, which Tailwind matches to its palette; translucent ones as `rgba()`. */\nexport function cssColor(color: Color): string {\n return color.a >= 1 ? colorToHex(color) : colorToCSS(color)\n}\n\nexport function fillToCSS(fill: Fill | undefined): string | undefined {\n if (fill?.type !== 'SOLID' || !fill.visible) return undefined\n return cssColor({ ...fill.color, a: fill.opacity })\n}\n\n/** A number CSS reads the same back: six decimals, no trailing zeros or negative zero. */\nfunction cssNumber(value: number): string {\n const rounded = Number(value.toFixed(6))\n return String(rounded === 0 ? 0 : rounded)\n}\n\nfunction stopToCSS(stop: GradientStop, opacity: number): string {\n const color = cssColor({ ...stop.color, a: stop.color.a * opacity })\n return `${color} ${cssNumber(stop.position * 100)}%`\n}\n\n/** The unit-square point as a CSS position pair, percentages of the box's width and height. */\nfunction positionToCSS(point: Vector): string {\n return `${cssNumber(point.x * 100)}% ${cssNumber(point.y * 100)}%`\n}\n\n/**\n * A gradient paint as the CSS gradient that draws it in a `width` × `height` box. The transform\n * maps the box's unit square onto gradient space; its inverse gives the line's ends, the\n * ellipse's centre and radii, or the sweep's start ray. Diamond gradients have no CSS spelling.\n */\nexport function gradientFillToCSS(fill: Fill, width: number, height: number): string | undefined {\n const transform = fill.gradientTransform\n const stops = fill.gradientStops\n if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) {\n return undefined\n }\n const painted = stops.map((stop) => stopToCSS(stop, fill.opacity)).join(', ')\n if (fill.type === 'GRADIENT_LINEAR') {\n const start = gradientPoint(transform, { x: 0, y: 0.5 })\n const end = gradientPoint(transform, { x: 1, y: 0.5 })\n const dx = (end.x - start.x) * width\n const dy = (end.y - start.y) * height\n if (dx === 0 && dy === 0) return undefined\n // CSS angles point up at 0deg and turn clockwise; screen y grows downward.\n const degrees = (Math.atan2(dx, -dy) * 180) / Math.PI\n return `linear-gradient(${cssNumber(degrees)}deg, ${painted})`\n }\n if (fill.type !== 'GRADIENT_RADIAL' && fill.type !== 'GRADIENT_ANGULAR') return undefined\n const center = gradientPoint(transform, { x: 0.5, y: 0.5 })\n const edgeX = gradientPoint(transform, { x: 1, y: 0.5 })\n const edgeY = gradientPoint(transform, { x: 0.5, y: 1 })\n const rx = Math.hypot((edgeX.x - center.x) * width, (edgeX.y - center.y) * height)\n const ry = Math.hypot((edgeY.x - center.x) * width, (edgeY.y - center.y) * height)\n if (rx <= 0 || ry <= 0) return undefined\n const at = `at ${positionToCSS(center)}`\n if (fill.type === 'GRADIENT_RADIAL') {\n const shape =\n Math.abs(rx - ry) < 1e-6\n ? `circle ${cssNumber(rx)}px`\n : `ellipse ${cssNumber(rx)}px ${cssNumber(ry)}px`\n return `radial-gradient(${shape} ${at}, ${painted})`\n }\n const degrees =\n (Math.atan2((edgeX.y - center.y) * height, (edgeX.x - center.x) * width) * 180) / Math.PI + 90\n return `conic-gradient(from ${cssNumber(degrees)}deg ${at}, ${painted})`\n}\n\n/**\n * The paint stack as `background-image`, top layer first as CSS paints it. Solid paints stay\n * out; the bottom one becomes `background-color`, and a solid above another paint has no CSS\n * spelling here. Image paints export through the element's own source, not this list.\n */\nexport function gradientFillsToCSS(\n fills: Fill[],\n width: number,\n height: number\n): string | undefined {\n const layers: string[] = []\n for (let index = fills.length - 1; index >= 0; index--) {\n const css = gradientFillToCSS(fills[index], width, height)\n if (css) layers.push(css)\n }\n return layers.length > 0 ? layers.join(', ') : undefined\n}\n\nexport type BorderSide = 'top' | 'right' | 'bottom' | 'left'\n\n/**\n * The width of each side of the border a layer's first stroke projects as, zero without one. A\n * border insets the box its absolutely positioned children are placed in, where a stroke does not.\n */\nexport function borderWidths(node: SceneNode): Record<BorderSide, number> {\n const stroke = node.strokes.find((item) => item.visible)\n if (!strokeColorToCSS(stroke)) return { top: 0, right: 0, bottom: 0, left: 0 }\n if (!node.independentStrokeWeights) {\n const weight = stroke?.weight ?? 0\n return { top: weight, right: weight, bottom: weight, left: weight }\n }\n return {\n top: node.borderTopWeight,\n right: node.borderRightWeight,\n bottom: node.borderBottomWeight,\n left: node.borderLeftWeight\n }\n}\n\nexport function strokeColorToCSS(stroke: Stroke | undefined): string | undefined {\n if (!stroke?.visible) return undefined\n return cssColor({ ...stroke.color, a: stroke.opacity })\n}\n\nfunction px(value: number): string {\n return `${Number(value.toFixed(3))}px`\n}\n\n/**\n * A shadow as `box-shadow` writes it, or as `text-shadow` does without its spread. CSS blurs a\n * shadow by half its blur length, so the length is twice the sigma the canvas blurs it by.\n */\nfunction shadowToCSS(effect: ShadowEffect, spread = true): string {\n const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''\n const parts = [\n `${inset}${px(effect.offset.x)}`,\n px(effect.offset.y),\n px(2 * blurSigma(effect.radius))\n ]\n if (spread) parts.push(px(effect.spread))\n parts.push(cssColor(effect.color))\n return parts.join(' ')\n}\n\nconst isShadow = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'\n\n/**\n * The blurs as the canvas draws them: the first visible layer blur as `filter`, and every\n * background blur in turn as `backdrop-filter`.\n */\nconst isLayerBlur = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR'\nconst isBackgroundBlur = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'BACKGROUND_BLUR'\nconst isDropShadow = (effect: Effect): effect is ShadowEffect => effect.type === 'DROP_SHADOW'\n\nfunction addBlurs(style: DesignStyleDeclaration, visible: Effect[]): void {\n const layer = visible.find(isLayerBlur)\n if (layer) style.filter = `blur(${px(blurSigma(layer.radius))})`\n const backdrop = visible.filter(isBackgroundBlur)\n if (backdrop.length > 0) {\n style['backdrop-filter'] = backdrop\n .map((effect) => `blur(${px(blurSigma(effect.radius))})`)\n .join(' ')\n }\n}\n\n/**\n * Every visible shadow, in order, plus layer and background blur, blurred as the canvas draws\n * them: CSS's `blur()` takes the Gaussian sigma itself.\n */\nexport function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n const visible = effects.filter((effect) => effect.visible)\n const shadows = visible.filter(isShadow)\n if (shadows.length > 0)\n style['box-shadow'] = shadows.map((effect) => shadowToCSS(effect)).join(', ')\n addBlurs(style, visible)\n return style\n}\n\n/**\n * Text's effects: each visible drop shadow as `text-shadow`, which has no spread and shadows the\n * glyphs, and its layer and background blurs. An inner shadow has no form CSS gives text.\n */\nexport function textEffectsToCSS(effects: Effect[]): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n const visible = effects.filter((effect) => effect.visible)\n const shadows = visible.filter(isDropShadow)\n if (shadows.length > 0) {\n style['text-shadow'] = shadows.map((effect) => shadowToCSS(effect, false)).join(', ')\n }\n addBlurs(style, visible)\n return style\n}\n\n/** A line height as CSS writes it: a percent as the unitless multiple that follows the font size. */\nexport function lineHeightToCSS(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : String(length.value / 100)\n}\n\n/** A letter spacing as CSS writes it: a percent of the font size in `em`. */\nexport function letterSpacingToCSS(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`\n}\n\n/**\n * Room for the spacing CSS puts after a line's last letter. A layer fits and aligns its lines by\n * their glyphs, without that spacing, so a spaced text's box is one spacing wider than its own\n * width and a negative margin takes the spacing back: lines break and align as on the canvas, and\n * the text takes the room it does there. Browsers put the spacing on a glyph's right in either\n * direction, so the margin is on the right. `spacing` is the CSS the text's letter spacing is\n * written as, which may refer to a token.\n */\nexport function letterSpacingRoomCSS(\n length: TextLength,\n spacing: string,\n width: string | undefined\n): DesignStyleDeclaration {\n const literal = spacing === letterSpacingToCSS(length)\n return {\n ...(width !== undefined && { width: `calc(${width} + ${spacing})` }),\n 'margin-right': literal\n ? letterSpacingToCSS({ ...length, value: -length.value })\n : `calc(-1 * ${spacing})`\n }\n}\n","import type { TokenUnit, Variable, VariableScope } from '@pairdraw/scene-graph'\nimport { tokenNumberInUnit } from '@pairdraw/scene-graph/variables'\n\nimport { variableNamespace } from './names'\n\nconst UNITLESS_SCOPES = new Set<VariableScope>(['OPACITY', 'FONT_STYLE', 'FONT_VARIATIONS'])\n\n/**\n * A property that takes values in each token unit, where a browser checks or computes a CSS\n * expression written for the token: `scale` takes any plain number, `width` any length.\n */\nexport const TOKEN_UNIT_PROPERTY: Record<TokenUnit, string> = {\n none: 'scale',\n px: 'width',\n rem: 'width',\n '%': 'width',\n ms: 'transition-duration',\n s: 'transition-duration',\n deg: 'rotate'\n}\n\n/**\n * The unit a FLOAT token is written in. An explicit unit wins; opacity and font weights are\n * unitless; every other number is a pixel length, which is what the canvas draws.\n */\nexport function variableUnit(variable: Variable): TokenUnit {\n if (variable.type !== 'FLOAT') return 'none'\n if (variable.unit) return variable.unit\n const scopes = variable.scopes ?? []\n if (scopes.length > 0 && scopes.every((scope) => UNITLESS_SCOPES.has(scope))) return 'none'\n return variableNamespace(variable) === 'font-weight' ? 'none' : 'px'\n}\n\n/** Six decimals keep `rem` exact for every pixel step down to 1/1024px (0.5px is 0.03125rem). */\nfunction trimNumber(value: number): string {\n return String(Number(value.toFixed(6)))\n}\n\n/** A stored number written in its unit: 24 as `rem` is `1.5rem`, 150 as `ms` is `150ms`. */\nexport function tokenNumberToCSS(value: number, unit: TokenUnit): string {\n const number = trimNumber(tokenNumberInUnit(value, unit))\n if (unit === 'none' || number === '0') return number\n return `${number}${unit}`\n}\n","import type { Variable, VariableFormulaNode } from '@pairdraw/scene-graph'\nimport { foldFormula } from '@pairdraw/scene-graph/variables'\n\nimport { tokenNumberToCSS, variableUnit } from './values'\n\n/**\n * A number formula as `calc()`, with each reference a `var()`. CSS adds only like with like and\n * multiplies a length only by a plain number, so a literal takes the unit of what it is added\n * to, and a formula CSS cannot type, such as a length times a length, has no CSS form.\n */\ntype Term =\n | { kind: 'literal'; value: number }\n | { kind: 'css'; text: string; precedence: number; dimension: boolean }\n\nconst OPERATORS = {\n add: { symbol: '+', precedence: 1 },\n subtract: { symbol: '-', precedence: 1 },\n multiply: { symbol: '*', precedence: 2 },\n divide: { symbol: '/', precedence: 2 }\n} as const\ntype Arithmetic = keyof typeof OPERATORS\nconst ATOM = 3\n\nclass UnsupportedFormulaError extends Error {\n override name = 'UnsupportedFormulaError'\n}\n\ninterface FormulaContext {\n variables: ReadonlyMap<string, Variable>\n names: ReadonlyMap<string, string>\n /** A literal written as a length, in the exported token's unit. */\n length: (value: number) => string\n}\n\nexport function formulaToCSS(\n node: VariableFormulaNode,\n variable: Variable,\n variables: ReadonlyMap<string, Variable>,\n names: ReadonlyMap<string, string>\n): string | { issue: string } {\n const unit = variableUnit(variable)\n const context = { variables, names, length: (value: number) => tokenNumberToCSS(value, unit) }\n try {\n const result = convert(node, context)\n const dimension = unit !== 'none'\n if (result.kind === 'literal') return write(result, dimension, context)\n if (result.dimension !== dimension)\n return { issue: dimension ? 'has a formula without a unit' : 'has a formula with a unit' }\n return `calc(${result.text})`\n } catch (error) {\n if (error instanceof UnsupportedFormulaError) return { issue: error.message }\n throw error\n }\n}\n\nfunction convert(node: VariableFormulaNode, context: FormulaContext): Term {\n return foldFormula<Term>(node, {\n literal: (value) => {\n if (typeof value === 'number') return { kind: 'literal', value }\n if (typeof value === 'boolean')\n throw new UnsupportedFormulaError('mixes true/false into a number')\n throw new UnsupportedFormulaError('mixes text or a color into a number')\n },\n reference: (id) => reference(id, context),\n operation: ({ operator }, operands) => {\n const [a, b] = operands\n if (operator === 'negate' && operands.length === 1) return negate(a, context)\n if (operands.length !== 2 || !isArithmetic(operator))\n throw new UnsupportedFormulaError('uses logic that CSS has no form for')\n if (a.kind === 'literal' && b.kind === 'literal')\n return { kind: 'literal', value: fold(operator, a.value, b.value) }\n return binary(operator, a, b, context)\n }\n })\n}\n\nfunction reference(id: string, { variables, names }: FormulaContext): Term {\n const target = variables.get(id)\n const name = names.get(id)\n if (!target || !name)\n throw new UnsupportedFormulaError('refers to a variable that does not exist')\n if (target.type !== 'FLOAT')\n throw new UnsupportedFormulaError('uses a variable that is not a number')\n const dimension = variableUnit(target) !== 'none'\n return { kind: 'css', text: `var(--${name})`, precedence: ATOM, dimension }\n}\n\nfunction negate(term: Term, context: FormulaContext): Term {\n if (term.kind === 'literal') return { kind: 'literal', value: -term.value }\n const text = `-1 * ${grouped(term, false, OPERATORS.multiply.precedence, context)}`\n return { kind: 'css', text, precedence: OPERATORS.multiply.precedence, dimension: term.dimension }\n}\n\nfunction binary(operator: Arithmetic, a: Term, b: Term, context: FormulaContext): Term {\n const { symbol, precedence } = OPERATORS[operator]\n // The right side of - and / keeps its parentheses even at equal precedence.\n const rightBelow = operator === 'subtract' || operator === 'divide' ? precedence + 1 : precedence\n const aDimension = a.kind === 'css' && a.dimension\n const bDimension = b.kind === 'css' && b.dimension\n if (precedence === 1) {\n if (a.kind === 'css' && b.kind === 'css' && aDimension !== bDimension)\n throw new UnsupportedFormulaError('adds a length to a plain number')\n const dimension = aDimension || bDimension\n const left = grouped(a, dimension, precedence, context)\n const right = grouped(b, dimension, rightBelow, context)\n return { kind: 'css', text: `${left} ${symbol} ${right}`, precedence, dimension }\n }\n if (bDimension && operator === 'divide') throw new UnsupportedFormulaError('divides by a length')\n if (aDimension && bDimension) throw new UnsupportedFormulaError('multiplies two lengths')\n const left = grouped(a, false, precedence, context)\n const right = grouped(b, false, rightBelow, context)\n return {\n kind: 'css',\n text: `${left} ${symbol} ${right}`,\n precedence,\n dimension: aDimension || bDimension\n }\n}\n\nfunction write(term: Term, dimension: boolean, context: FormulaContext) {\n if (term.kind === 'css') return term.text\n return dimension ? context.length(term.value) : String(Number(term.value.toFixed(6)))\n}\n\nfunction grouped(term: Term, dimension: boolean, below: number, context: FormulaContext) {\n return term.kind === 'css' && term.precedence < below\n ? `(${term.text})`\n : write(term, dimension, context)\n}\n\nfunction isArithmetic(operator: string): operator is Arithmetic {\n return Object.hasOwn(OPERATORS, operator)\n}\n\nfunction fold(operator: Arithmetic, a: number, b: number) {\n if (operator === 'add') return a + b\n if (operator === 'subtract') return a - b\n if (operator === 'multiply') return a * b\n return a / b\n}\n","import valueParser from 'postcss-value-parser'\n\nimport type { CSSStyleSheetLike } from '../cssom/types'\n\ntype Parse = (cssText: string) => CSSStyleSheetLike\n\nconst AT_RULES = ['@media', '@supports', '@container'] as const\n\n/** What a rule looks like to the checks below; the object model's own types are wider. */\ntype ParsedRule = {\n cssRules?: unknown[]\n selectorText?: string\n style?: { length: number; getPropertyValue(property: string): string }\n}\n\nfunction rules(sheet: CSSStyleSheetLike): ParsedRule[] {\n return sheet.cssRules.filter(\n (rule): rule is ParsedRule => typeof rule === 'object' && rule !== null\n )\n}\n\n/**\n * Token strings come from documents, so each one is parsed in place before it is written. A value\n * or condition that closes its rule early parses to a different number of rules and fails.\n */\nexport function createTokenValidator(parse: Parse) {\n /** `--name: value` is one declaration whose value reads back unchanged. */\n function declaration(name: string, value: string): boolean {\n const parsed = rules(parse(`:root{--${name}:${value}}`))\n const [rule] = parsed\n return (\n parsed.length === 1 &&\n rule.style?.length === 1 &&\n rule.style.getPropertyValue(`--${name}`).trim() === value.trim() &&\n (rule.cssRules?.length ?? 0) === 0\n )\n }\n\n return {\n declaration,\n\n /**\n * A custom property name without its `--`: one word to the CSS value tokenizer, which splits\n * on spaces, colons, commas and slashes, and one declaration to the parser. It starts with a\n * letter, digit or underscore, so `--` is never doubled into `----`.\n */\n name(name: string): boolean {\n const { nodes } = valueParser(`--${name}`)\n return (\n /^\\w/.test(name) &&\n nodes.length === 1 &&\n nodes[0]?.type === 'word' &&\n declaration(name, '0')\n )\n },\n\n /** A selector, or a `@media`, `@supports` or `@container` prelude, that wraps exactly one rule. */\n condition(condition: string): boolean {\n const trimmed = condition.trim()\n if (trimmed.startsWith('@')) {\n if (\n !AT_RULES.some((rule) => trimmed.startsWith(`${rule} `) || trimmed.startsWith(`${rule}(`))\n )\n return false\n const parsed = rules(parse(`${trimmed}{:root{--t:0}}`))\n return parsed.length === 1 && parsed[0]?.cssRules?.length === 1\n }\n const parsed = rules(parse(`${trimmed}{--t:0}`))\n const [rule] = parsed\n return (\n parsed.length === 1 &&\n typeof rule.selectorText === 'string' &&\n rule.style?.length === 1 &&\n (rule.cssRules?.length ?? 0) === 0\n )\n }\n }\n}\n\nexport type TokenValidator = ReturnType<typeof createTokenValidator>\n\n/** The browser's own CSS parser, through a constructable stylesheet. */\nexport function parseWithBrowser(cssText: string): CSSStyleSheetLike {\n const sheet = new CSSStyleSheet()\n sheet.replaceSync(cssText)\n return { cssRules: [...sheet.cssRules] }\n}\n","import type {\n SceneGraph,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport { cssColor } from '../export/css'\nimport { formulaToCSS } from './formula'\nimport {\n collectionVariables,\n deriveCSSName,\n explicitCSSName,\n tokenSlug,\n variableCSSNames,\n variableNamespace\n} from './names'\nimport { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'\nimport { tokenNumberToCSS, variableUnit } from './values'\n\nexport type TokenStylesheetFormat = 'css' | 'tailwind'\n\nexport type TokenStylesheetIssue = {\n message: string\n variableId?: string\n collectionId?: string\n modeId?: string\n}\n\nexport type TokenStylesheetOptions = {\n format: TokenStylesheetFormat\n /** Write only these tokens. Names still come from every token, so aliases outside resolve. */\n include?: (variable: Variable) => boolean\n}\n\nexport type TokenStylesheet = {\n css: string\n issues: TokenStylesheetIssue[]\n}\n\ntype Declaration = { name: string; value: string }\n\ntype ModeScope = {\n collection: VariableCollection\n mode: VariableCollectionMode\n condition: string\n declarations: Declaration[]\n}\n\ntype TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections'>\n\nfunction isAtRuleCondition(condition: string): boolean {\n return condition.trim().startsWith('@')\n}\n\n/**\n * A mode's name as an identifier. A name with no letters or digits falls back to its id, slugged\n * too: Figma ids such as `1:2` are not valid in a selector value or a variant name as they are.\n * Names that slug alike in one collection, such as `Dark` and `dark!`, are numbered in mode\n * order, so each mode keeps its own selector and variant.\n */\nfunction modeSlug(collection: VariableCollection, mode: VariableCollectionMode): string {\n const plainSlug = ({ name, modeId }: VariableCollectionMode) =>\n tokenSlug(name) || `mode-${tokenSlug(modeId) || 'unnamed'}`\n const taken = new Set<string>()\n for (const candidate of collection.modes) {\n const base = plainSlug(candidate)\n let slug = base\n for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`\n if (candidate.modeId === mode.modeId) return slug\n taken.add(slug)\n }\n return plainSlug(mode)\n}\n\n/** The attribute a collection's manual modes are switched by, unless it names its own. */\nexport function defaultModeAttributeName(collection: VariableCollection): string {\n return `data-${tokenSlug(collection.name) || 'mode'}`\n}\n\n/** The attribute that puts an element in a mode with no condition of its own: `data-theme`. */\nexport function modeAttribute(\n collection: VariableCollection,\n mode: VariableCollectionMode\n): { name: string; value: string } {\n return {\n name: collection.modeAttribute ?? defaultModeAttributeName(collection),\n value: modeSlug(collection, mode)\n }\n}\n\n/** The scope a mode applies in when it names none: `[data-theme=\"dark\"]` for Theme / Dark. */\nexport function defaultModeCondition(\n collection: VariableCollection,\n mode: VariableCollectionMode\n): string {\n const { name, value } = modeAttribute(collection, mode)\n return `[${name}=\"${value}\"]`\n}\n\nfunction quoteString(value: string): string {\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\a ')}\"`\n}\n\n/** One mode's value as CSS, or why it has none. */\nfunction modeValue(\n variable: Variable,\n value: VariableValue | undefined,\n modeId: string,\n names: ReadonlyMap<string, string>,\n variables: ReadonlyMap<string, Variable>\n): string | { issue: string } {\n const expression = variable.expressions?.[modeId]\n if (expression) return expression.css\n if (value === undefined) return { issue: 'has no value in this mode' }\n if (typeof value === 'object' && 'expression' in value) {\n if (value.expression === 'FORMULA' && variable.type === 'FLOAT')\n return formulaToCSS(value.value, variable, variables, names)\n if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }\n return { issue: 'uses an expression that CSS token export does not support' }\n }\n if (typeof value === 'object' && 'aliasId' in value) {\n const target = names.get(value.aliasId)\n return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }\n }\n if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value)\n if (variable.type === 'FLOAT' && typeof value === 'number')\n return tokenNumberToCSS(value, variableUnit(variable))\n if (variable.type === 'STRING' && typeof value === 'string')\n return variableNamespace(variable) === 'font' ? value : quoteString(value)\n if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }\n return { issue: 'has a value that does not match its type' }\n}\n\nfunction block(selector: string, declarations: Declaration[], indent = ''): string {\n const body = declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join('\\n')\n return `${indent}${selector} {\\n${body}\\n${indent}}`\n}\n\n/**\n * A comment naming `text`. Collection and mode names are the person's own text, so a `*` before\n * a `/` in them is spaced apart, which keeps a name from ending the comment and writing rules.\n */\nfunction cssComment(text: string): string {\n return `/* ${text.replaceAll('*/', '* /')} */`\n}\n\nfunction modeBlock(scope: ModeScope): string {\n const comment = cssComment(`${scope.collection.name}: ${scope.mode.name}`)\n if (!isAtRuleCondition(scope.condition))\n return `${comment}\\n${block(scope.condition, scope.declarations)}`\n return `${comment}\\n${scope.condition} {\\n${block(':root', scope.declarations, ' ')}\\n}`\n}\n\n/** `@custom-variant dark (&:where([data-theme=\"dark\"], [data-theme=\"dark\"] *));` */\nfunction customVariant(name: string, condition: string): string {\n const body = isAtRuleCondition(condition) ? condition : `&:where(${condition}, ${condition} *)`\n return `@custom-variant ${name} (${body});`\n}\n\n/** Variants are named after their mode, prefixed with the collection where two modes share a name. */\nfunction variantNames(scopes: ModeScope[]): string[] {\n const plain = scopes.map(({ collection, mode }) => modeSlug(collection, mode))\n return plain.map((name, index) => {\n const shared = plain.filter((other) => other === name).length > 1\n const collection = scopes[index]?.collection.name ?? ''\n return shared ? `${tokenSlug(collection)}-${name}` : name\n })\n}\n\n/**\n * Variables as a stylesheet of custom properties. The default mode of every collection is the\n * base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;\n * every other mode overrides the values that differ, under its condition. Aliases stay `var()`\n * references, and number formulas `calc()` over them; both are declared again in each mode that\n * changes what they point to.\n */\n/**\n * A name that took a numeric suffix is an alias nobody can read back from the stylesheet, so it\n * is reported rather than left as a silent second spelling of another token.\n */\nfunction numberedNameIssues(\n variables: readonly Variable[],\n names: Map<string, string>,\n modeOf: (variable: Variable) => string\n): TokenStylesheetIssue[] {\n const issues: TokenStylesheetIssue[] = []\n for (const variable of variables) {\n const name = names.get(variable.id)\n const base = deriveCSSName(variable)\n if (!name || explicitCSSName(variable) || name === base) continue\n issues.push({\n message: `\"${variable.name}\" is written --${name}: --${base} is taken`,\n variableId: variable.id,\n modeId: modeOf(variable)\n })\n }\n return issues\n}\n\nexport function buildTokenStylesheet(\n source: TokenSource,\n { format, include = () => true }: TokenStylesheetOptions,\n validate: TokenValidator\n): TokenStylesheet {\n const issues: TokenStylesheetIssue[] = []\n const collections = [...source.variableCollections.values()]\n const all = collectionVariables(source)\n const names = variableCSSNames(all)\n const variables = all.filter(include)\n const defaultModeOf = (variable: Variable) =>\n source.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n\n function declare(\n variable: Variable,\n modeId: string,\n value: VariableValue | undefined\n ): Declaration | undefined {\n const name = names.get(variable.id) ?? variable.id\n const css = modeValue(variable, value, modeId, names, source.variables)\n if (typeof css !== 'string') {\n issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })\n return undefined\n }\n if (!validate.declaration(name, css)) {\n issues.push({\n message: `${variable.name} is not a valid CSS declaration: --${name}: ${css}`,\n variableId: variable.id,\n modeId\n })\n return undefined\n }\n return { name, value: css }\n }\n\n issues.push(...numberedNameIssues(variables, names, defaultModeOf))\n\n const defaults = new Map<string, Declaration>()\n const theme: Declaration[] = []\n const root: Declaration[] = []\n for (const variable of variables) {\n const modeId = defaultModeOf(variable)\n const declaration = declare(variable, modeId, variable.valuesByMode[modeId])\n if (!declaration) continue\n defaults.set(variable.id, declaration)\n if (format === 'tailwind' && variableNamespace(variable) !== undefined) theme.push(declaration)\n else root.push(declaration)\n }\n\n /**\n * What a mode's scope declares: the collection's values that differ from its default, and every\n * alias or formula, in any collection, whose chain reaches one of them. Custom properties inherit as\n * computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue\n * unless it is declared again where `--blue` changes.\n */\n function modeDeclarations(\n collection: VariableCollection,\n mode: VariableCollectionMode\n ): Declaration[] {\n const own = (variable: Variable) => variable.collectionId === collection.id\n const valueIn = (variable: Variable) =>\n own(variable)\n ? (variable.valuesByMode[mode.modeId] ?? variable.valuesByMode[collection.defaultModeId])\n : variable.valuesByMode[defaultModeOf(variable)]\n const inMode = new Map<string, Declaration>()\n const scoped = new Map<string, Declaration>()\n for (const variable of variables.filter(own)) {\n const declaration = declare(variable, mode.modeId, valueIn(variable))\n if (!declaration) continue\n inMode.set(variable.id, declaration)\n if (declaration.value !== defaults.get(variable.id)?.value)\n scoped.set(variable.id, declaration)\n }\n for (let grew = true; grew;) {\n grew = false\n for (const variable of variables) {\n const references = variableValueReferences(valueIn(variable))\n if (scoped.has(variable.id) || !references.some((target) => scoped.has(target))) continue\n const declaration = inMode.get(variable.id) ?? defaults.get(variable.id)\n if (!declaration) continue\n scoped.set(variable.id, declaration)\n grew = true\n }\n }\n return variables.flatMap((variable) => {\n const declaration = scoped.get(variable.id)\n return declaration ? [declaration] : []\n })\n }\n\n const scopes: ModeScope[] = []\n for (const collection of collections) {\n for (const mode of collection.modes) {\n if (mode.modeId === collection.defaultModeId) continue\n const condition = mode.condition ?? defaultModeCondition(collection, mode)\n if (!validate.condition(condition)) {\n issues.push({\n message: `${collection.name}: ${mode.name} has a condition that is not a selector or a @media, @supports or @container query: ${condition}`,\n collectionId: collection.id,\n modeId: mode.modeId\n })\n continue\n }\n const declarations = modeDeclarations(collection, mode)\n if (declarations.length > 0) scopes.push({ collection, mode, condition, declarations })\n }\n }\n\n const sections: string[] = []\n if (theme.length > 0) sections.push(block('@theme', theme))\n if (root.length > 0) sections.push(block(':root', root))\n sections.push(...scopes.map(modeBlock))\n if (format === 'tailwind' && scopes.length > 0) {\n const variants = variantNames(scopes)\n sections.push(\n scopes\n .map((scope, index) =>\n customVariant(variants[index] ?? modeSlug(scope.collection, scope.mode), scope.condition)\n )\n .join('\\n')\n )\n }\n return { css: sections.length > 0 ? `${sections.join('\\n\\n')}\\n` : '', issues }\n}\n\n/**\n * Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS\n * object model package loads on first use; its browser build exports nothing, so it is never\n * the browser path.\n */\nexport async function loadTokenValidator(): Promise<TokenValidator> {\n if (typeof CSSStyleSheet === 'function') return createTokenValidator(parseWithBrowser)\n const headless = await import('./cssom-validator')\n return headless.tokenValidator\n}\n\nexport async function tokenStylesheet(\n source: TokenSource,\n options: TokenStylesheetOptions\n): Promise<TokenStylesheet> {\n return buildTokenStylesheet(source, options, await loadTokenValidator())\n}\n","import type { SceneGraph, SceneNode, Variable } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { collectionVariables, variableCSSNames, variableNamespace } from './names'\nimport { modeAttribute } from './stylesheet'\nimport { variableUnit } from './values'\n\n/** The mode CSS applies for each collection, by collection id. */\nexport type CSSModes = ReadonlyMap<string, string>\n\n/** Bound fields drawn as a length; any other numeric binding is unitless or not exported. */\nconst LENGTH_FIELDS = new Set([\n 'width',\n 'height',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'cornerRadius',\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomLeftRadius',\n 'bottomRightRadius',\n 'strokeWeight',\n 'borderTopWeight',\n 'borderBottomWeight',\n 'borderLeftWeight',\n 'borderRightWeight',\n 'fontSize',\n 'letterSpacing',\n 'lineHeight',\n 'paddingLeft',\n 'paddingRight',\n 'paddingTop',\n 'paddingBottom',\n 'itemSpacing',\n 'counterAxisSpacing',\n 'gridRowGap',\n 'gridColumnGap'\n])\n\nconst LENGTH_UNITS = new Set(['px', 'rem'])\n\n/** Color channels are stored as floats; a bound paint copies them, so this only absorbs rounding. */\nconst CHANNEL_TOLERANCE = 1 / 512\n\nconst CHANNELS = ['r', 'g', 'b', 'a'] as const\n\nfunction sameColor(a: Color, b: Color): boolean {\n return CHANNELS.every((channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE)\n}\n\nfunction isColor(value: unknown): value is Color {\n return typeof value === 'object' && value !== null && 'r' in value && 'a' in value\n}\n\n/**\n * A field's value as the number a token gives it. A text's letter spacing and line height are\n * lengths: in pixels they match by their value, while a percent of the font size, or automatic\n * line height, has no length token to match and stays literal.\n */\nfunction drawnNumber(node: SceneNode, field: string): number | undefined {\n if (field === 'letterSpacing' || field === 'lineHeight') {\n const length = node[field]\n return length?.unit === 'PIXELS' ? length.value : undefined\n }\n const value: unknown = Reflect.get(node, field)\n return typeof value === 'number' ? value : undefined\n}\n\n/** Where an alias chain ends in the modes the canvas draws: a value, or a CSS expression. */\ntype TokenChain = {\n ids: string[]\n value: Variable['valuesByMode'][string] | undefined\n end: Variable\n expression: boolean\n}\n\n/** The paint a `fills/0/color` or `strokes/1/color` binding names. */\nfunction boundPaint(node: SceneNode, field: string) {\n const [list, index] = field.split('/')\n if (list === 'fills') return node.fills[Number(index)]\n if (list === 'strokes') return node.strokes[Number(index)]\n return undefined\n}\n\n/**\n * Variable references for design-to-code. A bound field becomes `var(--name)` only when the\n * stylesheet resolves it to what the canvas draws: the element sits in the same modes, and the\n * token's CSS value is a length for a length, a bare number for opacity, or the paint's color.\n * Anything else keeps its literal value.\n */\nexport class DesignTokens {\n readonly names: ReadonlyMap<string, string>\n /** Tokens the output references, with every variable their aliases reach. */\n readonly used = new Set<string>()\n readonly #graph: SceneGraph\n\n constructor(graph: SceneGraph) {\n this.#graph = graph\n this.names = variableCSSNames(collectionVariables(graph))\n }\n\n /** The modes CSS applies outside the exported nodes: every collection's default. */\n defaultModes(): CSSModes {\n return new Map(\n [...this.#graph.variableCollections.values()].map((collection) => [\n collection.id,\n collection.defaultModeId\n ])\n )\n }\n\n /**\n * Attributes that put an element in the modes the canvas draws it in, and the modes CSS then\n * applies to it. An exported root takes the editor's active modes; below it, a node changes\n * modes only where it sets one. Only a mode without its own condition can be set this way.\n */\n enter(\n node: SceneNode,\n inherited: CSSModes,\n root: boolean\n ): { attrs: Record<string, string>; modes: CSSModes } {\n const attrs: Record<string, string> = {}\n const modes = new Map(inherited)\n for (const collection of this.#graph.variableCollections.values()) {\n if (!root && !node.variableModes[collection.id]) continue\n const modeId = this.#graph.getNodeVariableModeId(node.id, collection.id)\n const mode = collection.modes.find((candidate) => candidate.modeId === modeId)\n if (!mode || modeId === inherited.get(collection.id)) continue\n if (modeId === collection.defaultModeId || mode.condition) continue\n const { name, value } = modeAttribute(collection, mode)\n attrs[name] = value\n modes.set(collection.id, modeId)\n }\n return { attrs, modes }\n }\n\n /** `var(--name)` for a bound field, or `undefined` where the literal value must stay. */\n reference(node: SceneNode, field: string, modes: CSSModes): string | undefined {\n const variableId = node.boundVariables[field]\n const variable = variableId ? this.#graph.variables.get(variableId) : undefined\n const name = variable && this.names.get(variable.id)\n if (!variable || !name) return undefined\n const chain = this.#chain(node, variable, modes)\n if (!chain || !this.#drawsResolved(node, field, chain)) return undefined\n for (const id of chain.ids) this.used.add(id)\n return `var(--${name})`\n }\n\n /**\n * Follow aliases in the modes the canvas draws the node in, stopping at a value or at a CSS\n * expression, which is what the stylesheet writes for that mode. Fails where CSS would resolve\n * any link in another mode.\n */\n #chain(node: SceneNode, start: Variable, modes: CSSModes): TokenChain | undefined {\n const ids: string[] = []\n let variable: Variable | undefined = start\n while (variable && !ids.includes(variable.id)) {\n ids.push(variable.id)\n const modeId = this.#graph.getNodeVariableModeId(node.id, variable.collectionId)\n const collection = this.#graph.variableCollections.get(variable.collectionId)\n const cssModeId = modes.get(variable.collectionId) ?? collection?.defaultModeId\n if (modeId !== cssModeId) return undefined\n const value =\n variable.valuesByMode[modeId] ??\n (collection ? variable.valuesByMode[collection.defaultModeId] : undefined)\n if (variable.expressions?.[modeId]) return { ids, value, end: variable, expression: true }\n if (typeof value === 'object' && 'aliasId' in value) {\n variable = this.#graph.variables.get(value.aliasId)\n continue\n }\n return { ids, value, end: variable, expression: false }\n }\n return undefined\n }\n\n #drawsResolved(node: SceneNode, field: string, { value, end, expression }: TokenChain): boolean {\n if (field.endsWith('/color')) {\n const paint = boundPaint(node, field)\n if (!paint?.visible || paint.type !== 'SOLID' || !isColor(value)) return false\n return sameColor({ ...paint.color, a: paint.opacity }, value)\n }\n const drawn = drawnNumber(node, field)\n if (drawn === undefined || typeof value !== 'number') return false\n if (Math.fround(drawn) !== Math.fround(value)) return false\n // An expression is the author's CSS for the value, whatever unit the token stores.\n if (field === 'opacity') return expression || variableUnit(end) === 'none'\n return LENGTH_FIELDS.has(field) && (expression || LENGTH_UNITS.has(variableUnit(end)))\n }\n\n /**\n * The variables a stylesheet for this output declares: the referenced ones and every variable\n * their aliases reach in any mode, since each mode's scope declares its own alias targets.\n */\n stylesheetVariables(): Set<string> {\n const ids = new Set<string>()\n const pending = [...this.used]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (ids.has(id)) continue\n ids.add(id)\n for (const value of Object.values(this.#graph.variables.get(id)?.valuesByMode ?? {}))\n if (typeof value === 'object' && 'aliasId' in value) pending.push(value.aliasId)\n }\n return ids\n }\n\n /** Custom properties the Tailwind stylesheet declares in `@theme`, which name utilities. */\n themeVariables(): string[] {\n return [...this.names].flatMap(([id, name]) => {\n const variable = this.#graph.variables.get(id)\n return variable && variableNamespace(variable) !== undefined ? [`--${name}`] : []\n })\n }\n}\n","import type { GridTrack, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction trackToCSS(track: GridTrack): string {\n if (track.sizing === 'FR') return `${track.value}fr`\n if (track.sizing === 'FIXED') return `${track.value}px`\n return 'auto'\n}\n\n/** Equal `1fr` tracks use Tailwind's `grid-cols-N` form, which keeps them from overflowing. */\nfunction tracksToCSS(tracks: GridTrack[]): string {\n if (tracks.every((track) => track.sizing === 'FR' && track.value === 1))\n return `repeat(${tracks.length}, minmax(0, 1fr))`\n return tracks.map(trackToCSS).join(' ')\n}\n\nexport function addGridContainer(\n style: DesignStyleDeclaration,\n node: SceneNode,\n css: (field: string, literal: string) => string\n): void {\n style.display = 'grid'\n if (node.gridTemplateColumns.length > 0)\n style['grid-template-columns'] = tracksToCSS(node.gridTemplateColumns)\n if (node.gridTemplateRows.length > 0)\n style['grid-template-rows'] = tracksToCSS(node.gridTemplateRows)\n if (node.gridColumnGap > 0) style['column-gap'] = css('gridColumnGap', `${node.gridColumnGap}px`)\n if (node.gridRowGap > 0) style['row-gap'] = css('gridRowGap', `${node.gridRowGap}px`)\n}\n\n/** A span sets the whole placement, so the start follows it. */\nexport function addGridPlacement(style: DesignStyleDeclaration, node: SceneNode): void {\n const position = node.gridPosition\n if (!position) return\n if (position.columnSpan > 1)\n style['grid-column'] = `span ${position.columnSpan} / span ${position.columnSpan}`\n if (position.column > 0) style['grid-column-start'] = String(position.column)\n if (position.rowSpan > 1)\n style['grid-row'] = `span ${position.rowSpan} / span ${position.rowSpan}`\n if (position.row > 0) style['grid-row-start'] = String(position.row)\n}\n","import type { ConstraintType, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { DesignStyleDeclaration } from '../types'\nimport { borderWidths } from './css'\n\nconst AXES = {\n width: { constraint: 'horizontalConstraint', start: 'left', end: 'right', at: 'x' },\n height: { constraint: 'verticalConstraint', start: 'top', end: 'bottom', at: 'y' }\n} as const\n\ntype Axis = keyof typeof AXES\n\nconst length = (value: number) => `${Number(value.toFixed(3))}px`\nconst percent = (value: number) => `${Number((value * 100).toFixed(4))}%`\n\n/** A percentage of the containing block moved by a length, as `calc()` when it moves. */\nfunction shifted(base: string, by: number): string {\n if (Number(by.toFixed(3)) === 0) return base\n return `calc(${base} ${by < 0 ? '-' : '+'} ${length(Math.abs(by))})`\n}\n\n/**\n * A placed layer along one axis, measured in the box CSS places it in: inside the parent's\n * border, which a stroke on the canvas does not take from its children. A parent with no size\n * on the axis leaves its box to the page, so its children keep their start and size there.\n */\nfunction placedAxis(node: SceneNode, parent: SceneNode | undefined, axis: Axis) {\n const { constraint, start, end, at } = AXES[axis]\n const border = parent ? borderWidths(parent) : undefined\n const inset = border?.[start] ?? 0\n const room = (parent?.[axis] ?? 0) - inset - (border?.[end] ?? 0)\n const kind: ConstraintType = parent && room > 0 ? node[constraint] : 'MIN'\n const before = node[at] - inset\n return { kind, room, before, after: room - before - node[axis] }\n}\n\n/**\n * Whether a placed layer's constraint sizes it along an axis: Left and Right and Scale both size\n * it from the parent, so it takes no fixed size.\n */\nexport function constraintSizes(\n node: SceneNode,\n parent: SceneNode | undefined,\n axis: Axis\n): boolean {\n const { kind } = placedAxis(node, parent, axis)\n return kind === 'STRETCH' || kind === 'SCALE'\n}\n\n/**\n * Whether a layer's parent leaves it to its coordinates: it is absolutely positioned, or its\n * parent frame has no auto layout. The parent it is placed in is the one its constraints follow.\n */\nexport function placement(\n node: SceneNode,\n parent: SceneNode | undefined\n): { parent: SceneNode | undefined } | null {\n const frame = parent?.type === 'CANVAS' ? undefined : parent\n if (node.layoutPositioning === 'ABSOLUTE' || frame?.layoutMode === 'NONE')\n return { parent: frame }\n return null\n}\n\n/**\n * Place a layer by its constraints when its parent does not lay it out. A frame without auto\n * layout becomes the containing block of the children it places.\n */\nexport function addPositioning(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n const placed = placement(node, parent)\n if (placed) {\n style.position = 'absolute'\n addConstrainedPlacement(style, node, placed.parent)\n } else if (node.layoutMode === 'NONE' && node.type !== 'TEXT' && node.childIds.length > 0) {\n style.position = 'relative'\n }\n}\n\n/**\n * Place a layer by its constraints, so it follows the parent when the page resizes it as the\n * canvas does (`resize.ts` in `@pairdraw/scene-graph`): Left and Top keep the start edge,\n * Right and Bottom the end edge, Center the offset from the centre, Left and Right both edges,\n * and Scale its share of the parent. A stretched size is written out rather than left to both\n * edges, which an image would not fill.\n */\nfunction addConstrainedPlacement(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n for (const axis of ['width', 'height'] as const) {\n const { start, end } = AXES[axis]\n const { kind, room, before, after } = placedAxis(node, parent, axis)\n if (kind === 'MAX') {\n style[end] = length(after)\n } else if (kind === 'CENTER') {\n style[start] = shifted('50%', before - room / 2)\n } else if (kind === 'STRETCH') {\n style[start] = length(before)\n style[axis] = shifted('100%', node[axis] - room)\n } else if (kind === 'SCALE') {\n style[start] = percent(before / room)\n style[axis] = percent(node[axis] / room)\n } else {\n style[start] = length(before)\n }\n }\n}\n","import { uniq } from 'es-toolkit/array'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport type {\n CharacterStyleOverride,\n HyperlinkTarget,\n SceneNode,\n TextLength\n} from '@pairdraw/scene-graph'\nimport {\n hasTextList,\n listNumberFormat,\n paragraphSpacingAt,\n paragraphStyleAt,\n pixelLength,\n textLengthPixels,\n textListItems,\n textParagraphRanges,\n type TextListItem,\n type TextParagraphRange\n} from '@pairdraw/scene-graph/text'\n\nimport type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { fillToCSS, letterSpacingToCSS, lineHeightToCSS } from './css'\n\n/** The character styles CSS writes, as a text layer and its runs hold them. */\ntype CharacterStyle = Pick<\n SceneNode,\n | 'fontFamily'\n | 'fontSize'\n | 'fontWeight'\n | 'italic'\n | 'letterSpacing'\n | 'lineHeight'\n | 'fills'\n | 'textDecoration'\n | 'textDecorationStyle'\n | 'textDecorationThickness'\n | 'textDecorationFills'\n | 'textDecorationSkipInk'\n | 'textUnderlineOffset'\n | 'textCase'\n>\n\ntype CharacterStyleKey = keyof CharacterStyle\n\nconst CHARACTER_STYLE_KEYS: readonly CharacterStyleKey[] = [\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'italic',\n 'letterSpacing',\n 'lineHeight',\n 'fills',\n 'textDecoration',\n 'textDecorationStyle',\n 'textDecorationThickness',\n 'textDecorationFills',\n 'textDecorationSkipInk',\n 'textUnderlineOffset',\n 'textCase'\n]\n\n/** A list's indent per level, in ems of its first character, as the canvas lays lists out. */\nconst LIST_INDENT_EMS = 1.5\n\nconst DECORATION_PROPERTIES = new Set([\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-color',\n 'text-decoration-thickness',\n 'text-underline-offset',\n 'text-decoration-skip-ink'\n])\n\nconst px = (value: number) => `${value}px`\n\n/** Characters `[start, end)`, the run style over them, and where they link to. */\ninterface StyledRange {\n start: number\n end: number\n style: CharacterStyle\n href: string | null\n}\n\n/** Links a page can follow: to the web, to mail, or to a phone; others are left out. */\nconst LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:'])\n\n/** A link as an `href`, for a link to a URL a page can follow. */\nfunction linkHref(link: HyperlinkTarget | null | undefined): string | null {\n if (link?.type !== 'URL') return null\n try {\n return LINK_PROTOCOLS.has(new URL(link.value).protocol) ? link.value : null\n } catch {\n // Not an absolute URL, which a page could not follow from anywhere it is placed.\n return null\n }\n}\n\nexport function textCaseToCSS(value: SceneNode['textCase']): string | undefined {\n if (value === 'UPPER') return 'uppercase'\n if (value === 'LOWER') return 'lowercase'\n if (value === 'TITLE') return 'capitalize'\n return undefined\n}\n\n/**\n * The letter spacing every character of a text has, from its run or the layer, or `undefined`\n * when characters differ or there are none: then no one spacing ends every line. Characters\n * spaced and sized as the layer is give the layer's own spacing; otherwise each spacing is\n * resolved at its characters' font size, as CSS resolves `em` where a run sets its own size.\n */\nexport function uniformLetterSpacing(node: SceneNode): TextLength | undefined {\n const spacings = styledRanges(node).map(({ style }) => ({\n length: style.letterSpacing,\n fontSize: style.fontSize\n }))\n if (spacings.length === 0) return undefined\n const asLayer = spacings.every(\n ({ length, fontSize }) =>\n isEqual(length, node.letterSpacing) &&\n (length.unit === 'PIXELS' || fontSize === node.fontSize)\n )\n if (asLayer) return node.letterSpacing\n const pixels = uniq(spacings.map(({ length, fontSize }) => textLengthPixels(length, fontSize)))\n return pixels.length === 1 ? pixelLength(pixels[0]) : undefined\n}\n\nfunction characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {\n const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]))\n for (const key of CHARACTER_STYLE_KEYS) {\n const value = override[key]\n if (value !== undefined) style[key] = value\n }\n return style as CharacterStyle\n}\n\n/** The text in ranges of one style each: the runs, and the layer's own style between them. */\nfunction styledRanges(node: SceneNode): StyledRange[] {\n const ranges: StyledRange[] = []\n const base = characterStyle(node)\n let at = 0\n for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {\n const start = Math.max(at, run.start)\n const end = Math.min(node.text.length, run.start + run.length)\n if (start > at) ranges.push({ start: at, end: start, style: base, href: null })\n if (end > start) {\n const href = linkHref(run.style.hyperlink)\n ranges.push({ start, end, style: characterStyle(node, run.style), href })\n }\n at = Math.max(at, end)\n }\n if (at < node.text.length) {\n ranges.push({ start: at, end: node.text.length, style: base, href: null })\n }\n return ranges\n}\n\n/** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */\nfunction decorationCSS(style: CharacterStyle): DesignStyleDeclaration {\n if (style.textDecoration === 'NONE') return {}\n const underline = style.textDecoration === 'UNDERLINE'\n const css: DesignStyleDeclaration = {\n 'text-decoration-line': underline ? 'underline' : 'line-through'\n }\n if (style.textDecorationStyle !== 'SOLID') {\n css['text-decoration-style'] = style.textDecorationStyle.toLowerCase()\n }\n const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible))\n if (color) css['text-decoration-color'] = color\n if (style.textDecorationThickness !== null) {\n css['text-decoration-thickness'] = px(style.textDecorationThickness)\n }\n if (underline && style.textUnderlineOffset !== null) {\n css['text-underline-offset'] = px(style.textUnderlineOffset)\n }\n if (underline && !style.textDecorationSkipInk) css['text-decoration-skip-ink'] = 'none'\n return css\n}\n\nfunction characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDeclaration {\n return {\n color: fillToCSS(style.fills.at(0)) ?? '',\n 'font-family': style.fontFamily,\n 'font-size': px(style.fontSize),\n 'font-weight': String(style.fontWeight),\n 'font-style': style.italic ? 'italic' : 'normal',\n 'letter-spacing': letterSpacingToCSS(style.letterSpacing),\n 'line-height': style.lineHeight === null ? 'normal' : lineHeightToCSS(style.lineHeight),\n 'text-transform': textCaseToCSS(style.textCase) ?? 'none',\n ...(decorated ? decorationCSS(style) : {})\n }\n}\n\n/**\n * What a run's span sets beyond the text's own style. A percent letter spacing is written again\n * where the span changes the font size: CSS inherits spacing already resolved at the text's size,\n * while the canvas spaces each run by its own size.\n */\nfunction spanCSS(\n style: CharacterStyle,\n decorated: boolean,\n base: DesignStyleDeclaration\n): DesignStyleDeclaration {\n const own = characterCSS(style, decorated)\n const css = differing(own, base)\n const { unit, value } = style.letterSpacing\n if (unit === 'PERCENT' && value !== 0 && 'font-size' in css) {\n css['letter-spacing'] = own['letter-spacing']\n }\n return css\n}\n\n/** What `css` sets differently from `base`. */\nfunction differing(\n css: DesignStyleDeclaration,\n base: DesignStyleDeclaration\n): DesignStyleDeclaration {\n return Object.fromEntries(\n Object.entries(css).filter(([property, value]) => value !== '' && base[property] !== value)\n )\n}\n\n/**\n * Whether the text decorates every character alike. CSS draws an element's decoration through\n * its descendants, which cannot take it off, so mixed decorations go on the spans instead.\n */\nfunction uniformDecoration(node: SceneNode, ranges: readonly StyledRange[]): boolean {\n const decorations = ranges\n .filter((range) => node.text.slice(range.start, range.end).replaceAll('\\n', '') !== '')\n .map((range) => decorationCSS(range.style))\n return decorations.every((decoration) => isEqual(decoration, decorations[0]))\n}\n\ninterface TextProjection {\n node: SceneNode\n ranges: StyledRange[]\n base: DesignStyleDeclaration\n decorated: boolean\n}\n\nfunction textNode(text: string): DesignNode {\n return { type: 'text', text }\n}\n\nfunction element(\n tagName: string,\n inlineStyle: DesignStyleDeclaration,\n children: DesignNode[]\n): DesignElement {\n return { type: 'element', tagName, attrs: {}, inlineStyle, children }\n}\n\n/**\n * A link styled as the text around it: a link draws in the text's colour and with only the\n * decoration its characters have, as in Figma, not in a browser's link style.\n */\nfunction linkElement(href: string, css: DesignStyleDeclaration, text: string): DesignElement {\n const style = { color: 'inherit', 'text-decoration-line': 'none', ...css }\n return { ...element('a', style, [textNode(text)]), attrs: { href } }\n}\n\n/**\n * `text[start, end)` as text and spans, each span setting only what differs from the layer;\n * linked characters are a link instead.\n */\nfunction inlineContent(projection: TextProjection, start: number, end: number): DesignNode[] {\n const { node, ranges, base, decorated } = projection\n const pieces: { css: DesignStyleDeclaration; text: string; href: string | null }[] = []\n for (const range of ranges) {\n const from = Math.max(start, range.start)\n const to = Math.min(end, range.end)\n if (to <= from) continue\n const css = spanCSS(range.style, !decorated, base)\n const text = node.text.slice(from, to)\n const previous = pieces.at(-1)\n if (previous && previous.href === range.href && isEqual(previous.css, css)) {\n previous.text += text\n } else pieces.push({ css, text, href: range.href })\n }\n return pieces.map(({ css, text, href }) => {\n if (href) return linkElement(href, css, text)\n return Object.keys(css).length === 0 ? textNode(text) : element('span', css, [textNode(text)])\n })\n}\n\n/** A paragraph's content; an empty one holds a line break, which gives it a line's height. */\nfunction paragraphContent(projection: TextProjection, range: TextParagraphRange): DesignNode[] {\n if (range.end === range.start) return [element('br', {}, [])]\n return inlineContent(projection, range.start, range.end)\n}\n\n/** Text that CSS lays out in one element: no lists, and no spacing or indent between lines. */\nfunction needsBlocks(node: SceneNode): boolean {\n if (hasTextList(node)) return true\n const paragraphs = textParagraphRanges(node.text)\n return paragraphs.some(\n (_, index) =>\n paragraphSpacingAt(node, index, 'paragraphIndent') > 0 ||\n (index < paragraphs.length - 1 && paragraphSpacingAt(node, index, 'paragraphSpacing') > 0)\n )\n}\n\n/** The space after paragraph `index`: list spacing between two items, paragraph spacing else. */\nfunction spaceAfter(node: SceneNode, index: number, count: number): number {\n if (index >= count - 1) return 0\n const betweenItems =\n paragraphStyleAt(node.textParagraphs, index).listType !== 'NONE' &&\n paragraphStyleAt(node.textParagraphs, index + 1).listType !== 'NONE'\n return paragraphSpacingAt(node, index, betweenItems ? 'listSpacing' : 'paragraphSpacing')\n}\n\nfunction listStyleType(item: TextListItem): string {\n if (item.listType === 'UNORDERED') return 'disc'\n const format = listNumberFormat(item.level)\n if (format === 'LOWER_ALPHA') return 'lower-alpha'\n if (format === 'LOWER_ROMAN') return 'lower-roman'\n return 'decimal'\n}\n\n/** A list in the text, open at one level, with the item that nested lists go into. */\ninterface OpenList {\n level: number\n listType: TextListItem['listType']\n element: DesignElement\n item: DesignElement | undefined\n}\n\n/** Where the next list item goes: closes lists deeper than it, or of another kind at its level. */\nfunction closeListsFor(open: OpenList[], item: TextListItem): void {\n while ((open.at(-1)?.level ?? 0) > item.level) open.pop()\n const top = open.at(-1)\n if (top?.level === item.level && (top.listType !== item.listType || item.startsList)) open.pop()\n}\n\n/**\n * Opens a list one level below the innermost open one, inside its last item; a level an item\n * skips gets an item without a marker to hold it.\n */\nfunction openList(\n open: OpenList[],\n blocks: DesignNode[],\n item: TextListItem,\n indent: number\n): void {\n const parent = open.at(-1)\n const level = (parent?.level ?? 0) + 1\n const list = element(\n item.listType === 'ORDERED' ? 'ol' : 'ul',\n {\n ...blockMargins(0, 0),\n 'padding-inline-start': px(indent),\n 'list-style-type': level === item.level ? listStyleType(item) : 'none'\n },\n []\n )\n if (parent) {\n parent.item ??= appendTo(parent.element, element('li', { 'list-style-type': 'none' }, []))\n // The space after the item the list nests in stands above the list.\n const spacing = parent.item.inlineStyle?.['margin-bottom']\n if (spacing && parent.item.inlineStyle && list.inlineStyle) {\n delete parent.item.inlineStyle['margin-bottom']\n list.inlineStyle['margin-top'] = spacing\n }\n parent.item.children.push(list)\n } else blocks.push(list)\n open.push({ level, listType: item.listType, element: list, item: undefined })\n}\n\nfunction plainParagraph(\n projection: TextProjection,\n index: number,\n range: TextParagraphRange,\n after: number\n): DesignElement {\n const style = blockMargins(0, after)\n const indent = paragraphSpacingAt(projection.node, index, 'paragraphIndent')\n if (indent > 0) style['text-indent'] = px(indent)\n return element('p', style, paragraphContent(projection, range))\n}\n\n/**\n * The text as blocks, as Figma lays it out: a paragraph per plain one, lists nested by level\n * with Figma's markers (bullets at every level, numbers counting 1, a, i as they nest), and the\n * space after each paragraph as a margin on what ends it.\n */\nfunction blockContent(projection: TextProjection): DesignNode[] {\n const { node } = projection\n const paragraphs = textParagraphRanges(node.text)\n const items = new Map(\n textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])\n )\n const blocks: DesignNode[] = []\n const open: OpenList[] = []\n for (const [index, range] of paragraphs.entries()) {\n const after = spaceAfter(node, index, paragraphs.length)\n const item = items.get(index)\n if (!item) {\n open.length = 0\n blocks.push(plainParagraph(projection, index, range, after))\n continue\n }\n const unit = groupEm(projection, paragraphs, item) * LIST_INDENT_EMS\n closeListsFor(open, item)\n while ((open.at(-1)?.level ?? 0) < item.level) {\n // A hanging list's markers stand outside the text, so its first level has no indent.\n const first = open.length === 0\n openList(open, blocks, item, first && node.hangingList ? 0 : unit)\n }\n const list = open.at(-1)\n if (!list) continue\n const style: DesignStyleDeclaration = after > 0 ? { 'margin-bottom': px(after) } : {}\n list.item = appendTo(list.element, element('li', style, paragraphContent(projection, range)))\n }\n return blocks\n}\n\n/** Margins above and below a block, written out: paragraphs and lists have their own in CSS. */\nfunction blockMargins(top: number, bottom: number): DesignStyleDeclaration {\n return { 'margin-top': px(top), 'margin-bottom': px(bottom) }\n}\n\nfunction appendTo(parent: DesignElement, child: DesignElement): DesignElement {\n parent.children.push(child)\n return child\n}\n\n/** The size of a list's first character, which its indents are measured in. */\nfunction groupEm(\n projection: TextProjection,\n paragraphs: readonly TextParagraphRange[],\n item: TextListItem\n): number {\n const at = paragraphs[item.groupStart]?.start ?? item.start\n const range = projection.ranges.find((candidate) => at >= candidate.start && at < candidate.end)\n return range?.style.fontSize ?? projection.node.fontSize\n}\n\n/**\n * A text layer's element: its tag, its style with the decoration the whole text shares, and\n * its content. Runs of characters styled apart become spans; text with lists, paragraph\n * spacing, or a first-line indent becomes blocks, which a `<div>` holds.\n */\nexport function textElementContent(\n node: SceneNode,\n layerStyle: DesignStyleDeclaration\n): { tagName: string; style: DesignStyleDeclaration; children: DesignNode[] } {\n const ranges = styledRanges(node)\n const decorated = uniformDecoration(node, ranges)\n const style = Object.fromEntries(\n Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property))\n )\n if (decorated) Object.assign(style, decorationCSS(characterStyle(node)))\n const projection: TextProjection = {\n node,\n ranges,\n base: characterCSS(characterStyle(node), decorated),\n decorated\n }\n if (!needsBlocks(node)) {\n return { tagName: 'span', style, children: inlineContent(projection, 0, node.text.length) }\n }\n return { tagName: 'div', style, children: blockContent(projection) }\n}\n","import { isEqual } from 'es-toolkit/predicate'\nimport { fromUint8Array } from 'js-base64'\n\nimport type { SceneGraph, SceneNode, Stroke } from '@pairdraw/scene-graph'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport { readIcon } from '@pairdraw/scene-graph/icons'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport { layoutSizingInParent } from '@pairdraw/scene-graph/layout'\nimport { isShaderPresetPaint, shaderOfPaint } from '@pairdraw/scene-graph/shaders'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport { DesignTokens, type CSSModes } from '../tokens/references'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport {\n cssColor,\n effectsToCSS,\n fillToCSS,\n gradientFillsToCSS,\n letterSpacingRoomCSS,\n letterSpacingToCSS,\n lineHeightToCSS,\n strokeColorToCSS,\n textEffectsToCSS\n} from './css'\nimport { addGridContainer, addGridPlacement } from './grid'\nimport { addPositioning, constraintSizes, placement } from './position'\nimport { textCaseToCSS, textElementContent, uniformLetterSpacing } from './text'\n\nconst DOM_CSS_PLUGIN_ID = 'pairdraw-dom-css'\nconst IMAGE_SOURCE_URL_KEY = 'image-source-url'\n\n/**\n * Draws a vector-shaped layer as an inline `<svg>` element sized to the layer, from the\n * engine's own SVG export. dom-css cannot depend on that engine, so it comes in as an option.\n */\nexport type VectorElementRenderer = (graph: SceneGraph, node: SceneNode) => DesignElement | null\n\nexport interface SceneGraphToDesignOptions {\n rootId?: string\n /** Write each layer's ID as `data-pairdraw-node-id`. Default true. */\n includeSourceIds?: boolean\n /** Write each layer's own name as `data-name`, as the Tailwind JSX export does. Default false. */\n includeLayerNames?: boolean\n /** Write variable-bound values as `var(--name)` where CSS resolves them as drawn. Default true. */\n tokens?: boolean\n /** Vector, boolean, star, polygon, and icon layers as inline SVG; without it they project as boxes. */\n vectorElement?: VectorElementRenderer\n /** Hidden layers to project as shown, such as the tab panels a component reveals itself. */\n shown?: ReadonlySet<string>\n}\n\n/** Layers whose shape only paths describe, which CSS boxes cannot draw. */\nconst VECTOR_SHAPES = new Set<SceneNode['type']>(['VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON'])\n\n/** What a box draws itself, which the SVG of a vector layer draws instead. */\nconst BOX_PAINT = /^(background|border|box-shadow|outline|filter)/\n\n/** A field's CSS: its token reference where one is faithful, otherwise the literal value. */\ntype FieldCSS = (field: string, literal: string) => string\n\nconst px = (value: number) => `${value}px`\n\nfunction nodeChildren(graph: SceneGraph, node: SceneNode): SceneNode[] {\n return node.childIds\n .map((id) => graph.getNode(id))\n .filter((child): child is SceneNode => child !== undefined)\n}\n\nfunction justifyContentToCSS(value: SceneNode['primaryAxisAlign']): string | undefined {\n if (value === 'CENTER') return 'center'\n if (value === 'MAX') return 'flex-end'\n if (value === 'SPACE_BETWEEN') return 'space-between'\n if (value === 'SPACE_AROUND') return 'space-around'\n return undefined\n}\n\n/**\n * Cross-axis alignment of a container's children, or of one child. Auto layout starts children\n * at the start while flexbox stretches them, so start is written out: a child that hugs its\n * content keeps its own size.\n */\nfunction alignToCSS(\n value: SceneNode['counterAxisAlign'] | SceneNode['layoutAlignSelf']\n): string | undefined {\n if (value === 'MIN') return 'flex-start'\n if (value === 'CENTER') return 'center'\n if (value === 'MAX') return 'flex-end'\n if (value === 'STRETCH') return 'stretch'\n if (value === 'BASELINE') return 'baseline'\n return undefined\n}\n\n/** Whether a layer sizes itself to its content along an axis, so CSS should too. */\nfunction hugs(node: SceneNode, axis: 'width' | 'height'): boolean {\n if (node.type === 'TEXT')\n return (\n node.textAutoResize === 'WIDTH_AND_HEIGHT' ||\n (axis === 'height' && node.textAutoResize === 'HEIGHT')\n )\n if (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL') return false\n const primary = (node.layoutMode === 'HORIZONTAL') === (axis === 'width')\n return (primary ? node.primaryAxisSizing : node.counterAxisSizing) === 'HUG'\n}\n\n/**\n * A layer's size: fixed on the axes the design fixes, and left to the content where the layer\n * hugs it (an auto layout frame set to Hug, or auto-sizing text), so the page grows with it.\n */\nfunction addSize(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS\n): void {\n const placed = placement(node, parent)\n const sized = (axis: 'width' | 'height') =>\n node[axis] > 0 &&\n !hugs(node, axis) &&\n !stretches(node, parent, axis) &&\n !(placed && constraintSizes(node, placed.parent, axis))\n if (sized('width')) style.width = css('width', px(node.width))\n if (sized('height')) style.height = css('height', px(node.height))\n}\n\n/**\n * Whether a layer fills an axis by stretching, which a fixed CSS size would prevent: across a\n * flex parent, or either axis of a grid cell. Along a flex parent, fill is `flex-grow`, and the\n * size stays as its basis.\n */\nfunction stretches(\n node: SceneNode,\n parent: SceneNode | undefined,\n axis: 'width' | 'height'\n): boolean {\n const sizing = layoutSizingInParent(parent, node, axis === 'width' ? 'HORIZONTAL' : 'VERTICAL')\n if (sizing !== 'FILL' || !parent) return false\n if (parent.layoutMode === 'GRID') return true\n const mainAxis = parent.layoutMode === 'HORIZONTAL' ? 'width' : 'height'\n return axis !== mainAxis\n}\n\nfunction addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.minWidth !== null) style['min-width'] = css('minWidth', px(node.minWidth))\n if (node.maxWidth !== null) style['max-width'] = css('maxWidth', px(node.maxWidth))\n if (node.minHeight !== null) style['min-height'] = css('minHeight', px(node.minHeight))\n if (node.maxHeight !== null) style['max-height'] = css('maxHeight', px(node.maxHeight))\n}\n\nfunction addCornerRadii(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.type === 'ELLIPSE') {\n style['border-radius'] = '50%'\n return\n }\n if (node.independentCorners) {\n const corners = [\n ['border-top-left-radius', 'topLeftRadius', node.topLeftRadius],\n ['border-top-right-radius', 'topRightRadius', node.topRightRadius],\n ['border-bottom-right-radius', 'bottomRightRadius', node.bottomRightRadius],\n ['border-bottom-left-radius', 'bottomLeftRadius', node.bottomLeftRadius]\n ] as const\n for (const [property, field, radius] of corners)\n if (radius > 0) style[property] = css(field, px(radius))\n return\n }\n\n if (node.cornerRadius > 0) style['border-radius'] = css('cornerRadius', px(node.cornerRadius))\n}\n\nfunction addStroke(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n const stroke = node.strokes.find((item) => item.visible)\n const literalColor = strokeColorToCSS(stroke)\n if (!literalColor || !stroke) return\n const color = css('strokes/0/color', literalColor)\n const borderStyle = node.dashPattern.length > 0 ? 'dashed' : 'solid'\n if (!node.independentStrokeWeights) {\n style.border = `${css('strokeWeight', px(stroke.weight))} solid ${color}`\n if (borderStyle !== 'solid') style['border-style'] = borderStyle\n return\n }\n\n style['border-style'] = borderStyle\n style['border-color'] = color\n style['border-top-width'] = css('borderTopWeight', px(node.borderTopWeight))\n style['border-right-width'] = css('borderRightWeight', px(node.borderRightWeight))\n style['border-bottom-width'] = css('borderBottomWeight', px(node.borderBottomWeight))\n style['border-left-width'] = css('borderLeftWeight', px(node.borderLeftWeight))\n}\n\n/**\n * CSS gives an element one border, so the visible strokes after the first become rings in\n * `box-shadow`, in layer order. An outside ring grows from the border's outer edge, an inside one\n * from its inner edge, and a centred stroke gets a ring on each side of the border. Rings cannot\n * dash or take per-side weights, and outer and inner rings paint in separate CSS layers, so a\n * stroke order that alternates them is approximated.\n */\nfunction extraStrokeShadows(strokes: Stroke[], first: Stroke): string[] {\n const outer: string[] = []\n const inner: string[] = []\n let outside = 0\n let inside = first.weight\n for (const stroke of strokes) {\n if (!stroke.visible) continue\n const color = strokeColorToCSS(stroke)\n if (!color) continue\n if (stroke.align !== 'OUTSIDE') {\n inside += stroke.align === 'CENTER' ? stroke.weight / 2 : stroke.weight\n inner.push(`inset 0 0 0 ${px(inside)} ${color}`)\n }\n if (stroke.align !== 'INSIDE') {\n outside += stroke.align === 'CENTER' ? stroke.weight / 2 : stroke.weight\n outer.push(`0 0 0 ${px(outside)} ${color}`)\n }\n }\n // The first ring listed paints on top, so each group stays nearest first.\n return [...outer, ...inner]\n}\n\nconst PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'] as const\n\n/** Sides compare by their CSS, so a token and a literal of the same size stay separate. */\nfunction addPadding(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n const [top, right, bottom, left] = PADDING_FIELDS.map((field) => css(field, px(node[field])))\n const zero = px(0)\n if ([top, right, bottom, left].every((value) => value === zero)) return\n\n if (top === right && right === bottom && bottom === left) {\n style.padding = top\n return\n }\n\n if (top === bottom && right === left) {\n if (top !== zero) style['padding-block'] = top\n if (right !== zero) style['padding-inline'] = right\n return\n }\n\n if (top !== zero) style['padding-top'] = top\n if (right !== zero) style['padding-right'] = right\n if (bottom !== zero) style['padding-bottom'] = bottom\n if (left !== zero) style['padding-left'] = left\n}\n\nfunction addFlexGap(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.itemSpacing <= 0 && node.counterAxisSpacing <= 0) return\n const item = css('itemSpacing', px(node.itemSpacing))\n if (node.counterAxisSpacing <= 0) {\n style.gap = item\n return\n }\n\n const counter = css('counterAxisSpacing', px(node.counterAxisSpacing))\n if (node.layoutMode === 'HORIZONTAL') {\n if (node.itemSpacing > 0) style['column-gap'] = item\n style['row-gap'] = counter\n return\n }\n\n if (node.itemSpacing > 0) style['row-gap'] = item\n style['column-gap'] = counter\n}\n\n/** Image bytes as a data URL of the type they are encoded in. */\nfunction imageDataURL(bytes: Uint8Array): string {\n return `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`\n}\n\n/**\n * The shader a layer's fill draws, which the projection keeps as the shader rather than the\n * image of its still frame: the shader of its first fill, as the projection reads one fill.\n */\nfunction layerShader(graph: SceneGraph, node: SceneNode): DesignElement['shader'] {\n const fill = node.fills.at(0)\n const shader = fill?.visible ? shaderOfPaint(node, fill) : null\n if (!shader || !isShaderPresetPaint(shader)) return undefined\n const bytes = graph.images.get(shader.image)\n const frame = bytes ? imageDataURL(bytes) : undefined\n return { preset: shader.preset, frame }\n}\n\nconst POSITIONED = new Set(['relative', 'absolute', 'fixed', 'sticky'])\n\n/** Whether a `position` value makes an element the containing block of what it places. */\nexport function isPositioned(position: unknown): boolean {\n return typeof position === 'string' && POSITIONED.has(position)\n}\n\n/** A shader layer contains what plays behind its content, beneath everything it holds. */\nfunction addShaderLayerStyle(style: DesignStyleDeclaration): void {\n if (!isPositioned(style.position)) style.position = 'relative'\n style.isolation = 'isolate'\n}\n\nfunction addImageStyle(style: DesignStyleDeclaration, node: SceneNode): void {\n const fill = node.fills.at(0)\n if (fill?.type !== 'IMAGE' || !fill.visible || shaderOfPaint(node, fill)) return\n if (node.width > 0 && node.height > 0) style['aspect-ratio'] = `${node.width} / ${node.height}`\n if (fill.imageScaleMode === 'FIT') style['object-fit'] = 'contain'\n if (fill.imageScaleMode === 'FILL') style['object-fit'] = 'cover'\n}\n\n/** Styles a node takes from its parent's layout, and its own rotation. */\nfunction addLayoutChild(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n if (parent?.layoutMode === 'GRID') addGridPlacement(style, node)\n else if (parent && parent.layoutMode !== 'NONE' && node.layoutGrow > 0) style['flex-grow'] = '1'\n if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`\n}\n\nconst SIZE_PROPERTIES = ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height']\n\n/**\n * A layer's size includes its padding and stroke, as auto layout measures it. CSS sizes the\n * content box unless told otherwise, so a sized box with padding or a border says so.\n */\nfunction addBoxSizing(style: DesignStyleDeclaration): void {\n const sized = SIZE_PROPERTIES.some((property) => Object.hasOwn(style, property))\n const boxed = Object.keys(style).some(\n (property) =>\n property.startsWith('padding') ||\n (property.startsWith('border') && !property.endsWith('radius'))\n )\n if (sized && boxed) style['box-sizing'] = 'border-box'\n}\n\n/**\n * The CSS keyword for a blend mode, where one paints the same mode. Linear burn would need\n * `plus-darker`, which Chrome, Edge, and Firefox do not implement, so it gains no keyword and\n * exports flat. A normal layer or an unscoped pass-through needs none either.\n */\nconst CSS_BLEND_MODES: Partial<Record<SceneNode['blendMode'], string>> = {\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'color-burn',\n LIGHTEN: 'lighten',\n SCREEN: 'screen',\n LINEAR_DODGE: 'plus-lighter',\n COLOR_DODGE: 'color-dodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'soft-light',\n HARD_LIGHT: 'hard-light',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\n\nfunction styleFromSceneNode(\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n addSize(style, node, parent, css)\n addPositioning(style, node, parent)\n addSizeConstraints(style, node, css)\n const fill = fillToCSS(node.fills.at(0))\n if (fill) style['background-color'] = css('fills/0/color', fill)\n const gradients = gradientFillsToCSS(node.fills, node.width, node.height)\n if (gradients) style['background-image'] = gradients\n addImageStyle(style, node)\n addStroke(style, node, css)\n Object.assign(style, effectsToCSS(node.effects))\n const visibleStrokes = node.strokes.filter((stroke) => stroke.visible)\n if (visibleStrokes.length > 1) {\n const rings = extraStrokeShadows(visibleStrokes.slice(1), visibleStrokes[0])\n if (rings.length > 0) {\n style['box-shadow'] = [rings.join(', '), style['box-shadow']]\n .filter((shadow): shadow is string => Boolean(shadow))\n .join(', ')\n }\n }\n if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))\n const blend = CSS_BLEND_MODES[node.blendMode]\n if (blend) style['mix-blend-mode'] = blend\n addCornerRadii(style, node, css)\n if (node.clipsContent) style.overflow = 'hidden'\n const alignSelf = alignToCSS(node.layoutAlignSelf)\n if (alignSelf) style['align-self'] = alignSelf\n\n addLayoutChild(style, node, parent)\n if (node.layoutDirection === 'RTL') style.direction = 'rtl'\n\n if (node.layoutMode === 'GRID') {\n addGridContainer(style, node, css)\n addPadding(style, node, css)\n } else if (node.layoutMode !== 'NONE') {\n style.display = 'flex'\n // Row is the flexbox default.\n if (node.layoutMode === 'VERTICAL') style['flex-direction'] = 'column'\n const justifyContent = justifyContentToCSS(node.primaryAxisAlign)\n const alignItems = alignToCSS(node.counterAxisAlign)\n if (justifyContent) style['justify-content'] = justifyContent\n if (alignItems) style['align-items'] = alignItems\n if (node.layoutWrap === 'WRAP') style['flex-wrap'] = 'wrap'\n addFlexGap(style, node, css)\n addPadding(style, node, css)\n }\n\n addBoxSizing(style)\n return style\n}\n\nfunction styleFromTextNode(\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n addSize(style, node, parent, css)\n addPositioning(style, node, parent)\n addLayoutChild(style, node, parent)\n if (resolveNodeTextDirection(node) === 'RTL') style.direction = 'rtl'\n const color = fillToCSS(node.fills.at(0))\n style.color = color ? css('fills/0/color', color) : cssColor(BLACK)\n style['font-family'] = node.fontFamily\n style['font-size'] = css('fontSize', px(node.fontSize))\n style['font-weight'] = String(node.fontWeight)\n if (node.italic) style['font-style'] = 'italic'\n if (node.lineHeight !== null) {\n style['line-height'] = css('lineHeight', lineHeightToCSS(node.lineHeight))\n }\n const spacing = css('letterSpacing', letterSpacingToCSS(node.letterSpacing))\n if (node.letterSpacing.value !== 0) style['letter-spacing'] = spacing\n // The spacing after a line's last letter needs room only when one spacing ends every line.\n const ending = uniformLetterSpacing(node)\n if (ending && ending.value !== 0) {\n const written = isEqual(ending, node.letterSpacing) ? spacing : letterSpacingToCSS(ending)\n Object.assign(style, letterSpacingRoomCSS(ending, written, style.width))\n }\n if (node.textAlignHorizontal !== 'LEFT')\n style['text-align'] = node.textAlignHorizontal.toLowerCase()\n if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))\n Object.assign(style, textEffectsToCSS(node.effects))\n if (node.textDecoration !== 'NONE') {\n style['text-decoration-line'] =\n node.textDecoration === 'UNDERLINE' ? 'underline' : 'line-through'\n }\n const textTransform = textCaseToCSS(node.textCase)\n if (textTransform) style['text-transform'] = textTransform\n style['white-space'] = node.maxLines === 1 ? 'nowrap' : 'pre-wrap'\n return style\n}\n\nfunction imageSourceURL(node: SceneNode): string | undefined {\n return node.pluginData.find(\n (entry) => entry.pluginId === DOM_CSS_PLUGIN_ID && entry.key === IMAGE_SOURCE_URL_KEY\n )?.value\n}\n\n/** A layer's name, unless it only repeats the layer's type. */\nexport function ownLayerName(node: SceneNode): string | undefined {\n return node.name && node.name !== node.type ? node.name : undefined\n}\n\nfunction attrsForNode(\n graph: SceneGraph,\n node: SceneNode,\n {\n includeSourceIds,\n includeLayerNames\n }: Pick<ProjectionContext, 'includeSourceIds' | 'includeLayerNames'>\n): Record<string, string> {\n const attrs: Record<string, string> = {}\n const name = includeLayerNames ? ownLayerName(node) : undefined\n if (name) attrs['data-name'] = name\n if (includeSourceIds) attrs['data-pairdraw-node-id'] = node.id\n const sourceURL = imageSourceURL(node)\n if (sourceURL) attrs.src = sourceURL\n const fill = node.fills.at(0)\n if (fill?.type !== 'IMAGE' || !fill.imageHash || shaderOfPaint(node, fill)) return attrs\n const bytes = graph.images.get(fill.imageHash)\n if (!bytes) return attrs\n return { ...attrs, src: imageDataURL(bytes) }\n}\n\nfunction tagNameForNode(node: SceneNode): string {\n if (node.type === 'SECTION') return 'section'\n const fill = node.fills.at(0)\n const image = fill?.type === 'IMAGE' && !shaderOfPaint(node, fill)\n if ((image || imageSourceURL(node)) && node.childIds.length === 0) return 'img'\n return 'div'\n}\n\ninterface ProjectionContext {\n graph: SceneGraph\n includeSourceIds: boolean\n includeLayerNames: boolean\n tokens: DesignTokens | undefined\n vectorElement: VectorElementRenderer | undefined\n shown: ReadonlySet<string> | undefined\n}\n\n/**\n * A vector layer as the renderer's `<svg>`, placed where the layer's box would be: its\n * position, size, opacity, and transform stay, and its paint is the SVG's, not the box's.\n */\nfunction vectorDesignNode(\n context: ProjectionContext,\n node: SceneNode,\n attrs: Record<string, string>,\n style: DesignStyleDeclaration\n): DesignElement | null {\n const drawn = context.vectorElement?.(context.graph, node)\n if (!drawn) return null\n const placement = Object.fromEntries(\n Object.entries(style).filter(([property]) => !BOX_PAINT.test(property))\n )\n return {\n ...drawn,\n attrs: { ...drawn.attrs, ...attrs },\n inlineStyle: { ...drawn.inlineStyle, ...placement },\n sourceSceneNodeId: node.id,\n sourceSceneNode: node\n }\n}\n\n/** The outline a vector mask clips siblings to, in the sibling's own box; null where CSS cannot. */\nfunction vectorMaskClip(mask: SceneNode, sibling: SceneNode): string | null {\n // The renderer clips to the rotated outline; a polygon built from the unrotated box would\n // cut a different region, so a rotated mask stays unclipped as the export documents.\n if (mask.maskType !== 'VECTOR' || mask.childIds.length > 0 || mask.rotation !== 0) return null\n const left = mask.x - sibling.x\n const top = mask.y - sibling.y\n if (mask.type === 'RECTANGLE') {\n const right = left + mask.width\n const bottom = top + mask.height\n return `polygon(${px(left)} ${px(top)}, ${px(right)} ${px(top)}, ${px(right)} ${px(bottom)}, ${px(left)} ${px(bottom)})`\n }\n if (mask.type === 'ELLIPSE') {\n const rx = mask.width / 2\n const ry = mask.height / 2\n return `ellipse(${px(rx)} ${px(ry)} at ${px(left + rx)} ${px(top + ry)})`\n }\n return null\n}\n\n/**\n * Projects a parent's children as the canvas draws them: a mask layer is never a layer of its\n * own, and one vector mask clips the siblings after it. Alpha and luminance masks have no\n * faithful CSS form over several elements, and two masks combine, so those stay unclipped.\n */\nfunction projectChildren(\n context: ProjectionContext,\n parent: SceneNode,\n modes: CSSModes,\n root: boolean\n): DesignNode[] {\n const projected: DesignNode[] = []\n let masks: SceneNode[] = []\n let afterMask = false\n for (const child of nodeChildren(context.graph, parent)) {\n if (child.visible && child.isMask) {\n masks = afterMask ? [...masks, child] : [child]\n afterMask = true\n continue\n }\n afterMask = false\n const node = sceneNodeToDesignNode(context, child, modes, root)\n if (!node) continue\n const mask = masks.length === 1 ? masks[0] : null\n if (mask && node.type === 'element') {\n const clip = vectorMaskClip(mask, child)\n if (clip) node.inlineStyle = { ...node.inlineStyle, 'clip-path': clip }\n }\n projected.push(node)\n }\n return projected\n}\n\nfunction sceneNodeToDesignNode(\n context: ProjectionContext,\n node: SceneNode,\n inherited: CSSModes,\n root: boolean\n): DesignNode | null {\n if ((!node.visible && !context.shown?.has(node.id)) || node.internalOnly) return null\n const { graph, tokens } = context\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const entered = tokens?.enter(node, inherited, root)\n const modes = entered?.modes ?? inherited\n const attrs = { ...attrsForNode(graph, node, context), ...entered?.attrs }\n const css: FieldCSS = (field, literal) => tokens?.reference(node, field, modes) ?? literal\n\n if (node.type === 'TEXT') {\n const content = textElementContent(node, styleFromTextNode(node, parent, css))\n return {\n type: 'element',\n tagName: content.tagName,\n attrs,\n inlineStyle: content.style,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children: content.children\n }\n }\n\n // An icon is one drawing, however many paths it has.\n if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {\n const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css))\n if (vector) return vector\n }\n\n const children = projectChildren(context, node, modes, false)\n\n if (node.type === 'CANVAS') {\n return {\n type: 'element',\n tagName: 'main',\n attrs,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children\n }\n }\n\n const style = styleFromSceneNode(node, parent, css)\n const shader = layerShader(graph, node)\n if (shader) addShaderLayerStyle(style)\n return {\n type: 'element',\n tagName: tagNameForNode(node),\n attrs,\n inlineStyle: style,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children,\n shader\n }\n}\n\nfunction projectionContext(\n graph: SceneGraph,\n {\n includeSourceIds = true,\n includeLayerNames = false,\n tokens = true,\n vectorElement,\n shown\n }: SceneGraphToDesignOptions\n): ProjectionContext {\n return {\n graph,\n includeSourceIds,\n includeLayerNames,\n tokens: tokens ? new DesignTokens(graph) : undefined,\n vectorElement,\n shown\n }\n}\n\nexport function sceneGraphToDesignDocument(\n graph: SceneGraph,\n options: SceneGraphToDesignOptions = {}\n): DesignDocument {\n const root = graph.getNode(options.rootId ?? graph.rootId)\n const context = projectionContext(graph, options)\n const modes = context.tokens?.defaultModes() ?? new Map<string, string>()\n const children = root ? projectChildren(context, root, modes, true) : []\n\n return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }\n}\n\n/** Project one node, including its own box, instead of the children of a root. */\nexport function sceneNodeToDesignDocument(\n graph: SceneGraph,\n nodeId: string,\n options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}\n): DesignDocument {\n return sceneNodesToDesignDocument(graph, [nodeId], options)\n}\n\n/**\n * Project several nodes, including each own box, through one token collector: the document then\n * declares the tokens every root references, not only those of the last one.\n */\nexport function sceneNodesToDesignDocument(\n graph: SceneGraph,\n nodeIds: readonly string[],\n options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}\n): DesignDocument {\n const context = projectionContext(graph, options)\n const modes = context.tokens?.defaultModes() ?? new Map<string, string>()\n const children: DesignNode[] = []\n for (const nodeId of nodeIds) {\n const node = graph.getNode(nodeId)\n const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null\n if (projected) children.push(projected)\n }\n return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }\n}\n","import {\n sceneNodeToDesignDocument,\n type SceneGraphToDesignOptions\n} from '#dom-css/export/projection'\nimport type { DesignElement, DesignNode, DesignText } from '#dom-css/types'\nimport { omit } from 'es-toolkit/object'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n behaviourOwner,\n layerPath,\n partBinding,\n readBehaviour\n} from '@pairdraw/scene-graph/behaviours'\nimport { readIcon } from '@pairdraw/scene-graph/icons'\nimport { instanceMainComponent } from '@pairdraw/scene-graph/instances'\nimport { instanceSlotFrames, slotPropertyId } from '@pairdraw/scene-graph/slots'\n\nimport type { StateElement } from './types'\n\n/** A variant's projected layer, keyed so the same layer matches across variants. */\nexport interface VariantLayer {\n type: 'element'\n key: string\n kind: string | undefined\n name: string\n element: DesignElement\n children: Array<VariantLayer | DesignText>\n}\n\n/** Where the set places a variant, which is not the component's own style. */\nexport const PLACEMENT = ['position', 'left', 'top', 'right', 'bottom', 'inset']\n\nfunction textContent(element: DesignElement): string | null {\n const texts = element.children.filter((child): child is DesignText => child.type === 'text')\n return texts.length > 0 ? texts.map((text) => text.text).join('') : null\n}\n\n/**\n * What a layer draws other than its own box: an instance of a component (of any of its set's\n * variants), or an icon. Undefined for any other layer.\n */\nexport function layerKind(graph: SceneGraph, node: SceneNode | undefined): string | undefined {\n if (!node) return undefined\n if (node.type === 'INSTANCE') {\n const main = instanceMainComponent(graph, node)\n const owner = main && behaviourOwner(graph, main)\n return `instance ${owner?.id ?? ''}`\n }\n const icon = readIcon(node)\n return icon ? `icon ${icon.name}` : undefined\n}\n\nfunction variantLayer(\n graph: SceneGraph,\n variant: SceneNode,\n node: DesignNode,\n parentKey: string,\n index: number\n): VariantLayer | DesignText {\n if (node.type === 'text') return node\n const source = node.sourceSceneNodeId\n const path = source ? layerPath(graph, variant.id, source) : `${parentKey}/~${index}`\n const text = textContent(node)\n const kind = layerKind(graph, node.sourceSceneNode)\n // A label that reads differently in a variant is a different layer, shown by its state, and\n // so is a layer drawn as another component or icon, or as one instead of its own box.\n const key = [path, ...(kind ? [kind] : []), ...(text === null ? [] : [text])].join('\\0')\n return {\n type: 'element',\n key,\n kind,\n name: node.sourceSceneNode?.name ?? node.tagName,\n element: node,\n children: node.children.map((child, i) => variantLayer(graph, variant, child, key, i))\n }\n}\n\n/**\n * The tab panels a variant draws hidden behind the first. The generated tabs show each when its\n * tab is chosen, so they are projected as drawn.\n */\nfunction tabPanels(graph: SceneGraph, variant: SceneNode): Set<string> {\n const owner = behaviourOwner(graph, variant)\n const behaviour = owner && readBehaviour(owner)\n const propertyId = behaviour?.kind === 'tabs' ? partBinding(behaviour, 'panels') : undefined\n const panels = propertyId\n ? instanceSlotFrames(graph, variant).find((frame) => slotPropertyId(frame) === propertyId)\n : undefined\n return new Set(panels?.childIds)\n}\n\n/**\n * The layers of a variant a boolean property shows or hides, which are projected however the\n * variant draws them, since the generated component shows them from its prop.\n */\nfunction visibilityBound(graph: SceneGraph, variant: SceneNode): Set<string> {\n const bound = new Set<string>()\n const visit = (node: SceneNode) => {\n for (const child of graph.getChildren(node.id)) {\n if (child.componentPropertyReferences.some((item) => item.field === 'VISIBLE'))\n bound.add(child.id)\n if (child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(variant)\n return bound\n}\n\n/** A variant projected to DOM, without where the set places it. */\nexport function projectVariant(\n graph: SceneGraph,\n variant: SceneNode,\n { vectorElement }: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}\n): VariantLayer | null {\n const document = sceneNodeToDesignDocument(graph, variant.id, {\n includeSourceIds: false,\n vectorElement,\n shown: new Set([...tabPanels(graph, variant), ...visibilityBound(graph, variant)])\n })\n const root = document.children.at(0)\n if (root?.type !== 'element') return null\n const style = root.inlineStyle ?? {}\n // Absolutely placed layers inside still need the root as their containing block.\n root.inlineStyle = {\n ...omit(style, PLACEMENT),\n ...(style.position ? { position: 'relative' } : {})\n }\n return {\n type: 'element',\n key: '',\n kind: undefined,\n name: variant.name,\n element: root,\n children: root.children.map((child, i) => variantLayer(graph, variant, child, '', i))\n }\n}\n\n/** Every layer of a projected variant by key. */\nexport function layersByKey(\n root: VariantLayer,\n into = new Map<string, VariantLayer>()\n): Map<string, VariantLayer> {\n into.set(root.key, root)\n for (const child of root.children) if (child.type === 'element') layersByKey(child, into)\n return into\n}\n\n/** A merged layer starting from a variant's layer, with that layer's style as its base. */\nexport function stateElement(layer: VariantLayer): StateElement {\n return {\n type: 'element',\n key: layer.key,\n kind: layer.kind,\n name: layer.name,\n tagName: layer.element.tagName,\n attrs: { ...layer.element.attrs },\n base: { ...layer.element.inlineStyle },\n rules: [],\n shader: layer.element.shader,\n children: layer.children.map((child) => (child.type === 'text' ? child : stateElement(child)))\n }\n}\n\nfunction hideAtRest(element: StateElement, hidden: Set<StateElement>): void {\n element.base = { ...element.base, display: 'none' }\n hidden.add(element)\n for (const child of element.children) if (child.type === 'element') hideAtRest(child, hidden)\n}\n\n/**\n * Adds the layers only `variant` draws to the merged tree, after the sibling they follow\n * there. Each keeps the style this variant draws it with, hidden at rest, and is recorded in\n * `hidden` so the variants that draw it show it again.\n */\nexport function mergeVariant(\n into: StateElement,\n variant: VariantLayer,\n hidden: Set<StateElement>\n): void {\n let previous = -1\n for (const child of variant.children) {\n if (child.type === 'text') continue\n const index = into.children.findIndex(\n (item) => item.type === 'element' && item.key === child.key\n )\n const existing = into.children.at(index)\n if (index !== -1 && existing?.type === 'element') {\n mergeVariant(existing, child, hidden)\n previous = index\n continue\n }\n const added = stateElement(child)\n hideAtRest(added, hidden)\n previous += 1\n into.children.splice(previous, 0, added)\n }\n}\n\n/** Every element of the merged tree, root first. */\nexport function allElements(root: StateElement, into: StateElement[] = []): StateElement[] {\n into.push(root)\n for (const child of root.children) if (child.type === 'element') allElements(child, into)\n return into\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAOA,SAAgB,oBACd,QACY;CACZ,OAAO,QACL,CAAC,GAAG,OAAO,oBAAoB,OAAO,CAAC,CAAC,CAAC,SAAS,eAChD,WAAW,YAAY,KAAK,OAAO,OAAO,UAAU,IAAI,EAAE,CAAC,CAC7D,CACF;AACF;AAEA,MAAM,mBAAmE;CACvE,eAAe;CACf,KAAK;CACL,cAAc;CACd,WAAW;CACX,aAAa;CACb,gBAAgB;CAChB,aAAa;CACb,YAAY;CACZ,cAAc;AAChB;;AAGA,MAAM,kBAAkD;CACtD,GAAG,OAAO,YAAY,gBAAgB,KAAK,cAAc,CAAC,WAAW,SAAS,CAAC,CAAC;CAChF,QAAQ;CACR,QAAQ;CACR,SAAS;CACT,OAAO;CACP,OAAO;CACP,SAAS;CACT,QAAQ;CACR,SAAS;CACT,aAAa;CACb,eAAe;CACf,kBAAkB;CAClB,OAAO;CACP,eAAe;CACf,QAAQ;CACR,SAAS;AACX;;;;;;AAOA,SAAgB,UAAU,MAAsB;CAC9C,MAAM,QAAQ,KACX,UAAU,MAAM,CAAC,CACjB,WAAW,sBAAsB,OAAO,CAAC,CACzC,YAAY,CAAC,CACb,MAAM,iBAAiB;CAC1B,OAAO,QAAQ,KAAK,CAAC,CAAC,KAAK,GAAG;AAChC;;AAGA,SAAgB,kBAAkB,UAAgD;CAChF,IAAI,SAAS,SAAS,SAAS,OAAO;CACtC,MAAM,aAAa,IAAI,KAAK,SAAS,UAAU,CAAC,EAAA,CAAG,KAAK,UAAU,iBAAiB,MAAM,CAAC;CAC1F,MAAM,CAAC,QAAQ;CACf,IAAI,WAAW,SAAS,KAAK,MAAM,OAAO;CAC1C,OAAO,gBAAgB,UAAU,SAAS,K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,OAAO;AACT"}
1
+ {"version":3,"file":"layers.js","names":["px","#graph","#chain","#drawsResolved","px"],"sources":["../../../../src/tokens/names.ts","../../../../src/export/css.ts","../../../../src/tokens/values.ts","../../../../src/tokens/formula.ts","../../../../src/tokens/validate.ts","../../../../src/tokens/stylesheet.ts","../../../../src/tokens/references.ts","../../../../src/export/grid.ts","../../../../src/export/position.ts","../../../../src/export/text.ts","../../../../src/export/projection.ts","../../../../src/behaviours/states/layers.ts"],"sourcesContent":["import { compact } from 'es-toolkit/array'\nimport valueParser from 'postcss-value-parser'\nimport { themeNamespaces, type ThemeNamespace } from 'twirlwind'\n\nimport type { SceneGraph, Variable, VariableScope } from '@pairdraw/scene-graph'\n\n/** Every variable, collection by collection, in each collection's own order. */\nexport function collectionVariables(\n source: Pick<SceneGraph, 'variables' | 'variableCollections'>\n): Variable[] {\n return compact(\n [...source.variableCollections.values()]\n .filter((collection) => !collection.deleted)\n .flatMap((collection) => collection.variableIds.map((id) => source.variables.get(id)))\n )\n}\n\nconst SCOPE_NAMESPACES: Partial<Record<VariableScope, ThemeNamespace>> = {\n CORNER_RADIUS: 'radius',\n GAP: 'spacing',\n WIDTH_HEIGHT: 'spacing',\n FONT_SIZE: 'text',\n LINE_HEIGHT: 'leading',\n LETTER_SPACING: 'tracking',\n FONT_FAMILY: 'font',\n FONT_STYLE: 'font-weight',\n EFFECT_FLOAT: 'blur'\n}\n\n/** Leading name segments that already say the namespace, so `Color/primary` is not `--color-color-primary`. */\nconst NAMESPACE_WORDS: Record<string, ThemeNamespace> = {\n ...Object.fromEntries(themeNamespaces.map((namespace) => [namespace, namespace])),\n colors: 'color',\n colour: 'color',\n colours: 'color',\n space: 'spacing',\n radii: 'radius',\n rounded: 'radius',\n corner: 'radius',\n corners: 'radius',\n 'font-size': 'text',\n 'line-height': 'leading',\n 'letter-spacing': 'tracking',\n fonts: 'font',\n 'font-family': 'font',\n weight: 'font-weight',\n shadows: 'shadow'\n}\n\n/**\n * Lowercase words joined by `-`, keeping digits on their word, as Tailwind keys do: `Text/2xl`\n * is `text-2xl`, `Heading/H1` is `heading-h1`, `brandPrimary` is `brand-primary`. es-toolkit's\n * `kebabCase` splits digits off (`text-2-xl`), which no design system writes.\n */\nexport function tokenSlug(text: string): string {\n const words = text\n .normalize('NFKC')\n .replaceAll(/(\\p{Ll})(\\p{Lu})/gu, '$1 $2')\n .toLowerCase()\n .split(/[^\\p{L}\\p{N}]+/u)\n return compact(words).join('-')\n}\n\n/** The Tailwind namespace a token belongs to, from its type, its scopes, then its leading name segment. */\nexport function variableNamespace(variable: Variable): ThemeNamespace | undefined {\n if (variable.type === 'COLOR') return 'color'\n const fromScopes = new Set((variable.scopes ?? []).map((scope) => SCOPE_NAMESPACES[scope]))\n const [only] = fromScopes\n if (fromScopes.size === 1 && only) return only\n return NAMESPACE_WORDS[tokenSlug(variable.name.split('/')[0] ?? '')]\n}\n\n/**\n * The custom property a code snippet names, without `--`: `var(--brand)`, `var(--brand, red)`\n * and `--brand` all name `brand`. A snippet that is anything else, such as a Tailwind class,\n * names none.\n */\nexport function parseCSSName(snippet: string | undefined): string | undefined {\n const nodes = valueParser(snippet ?? '').nodes.filter((node) => node.type !== 'space')\n const [node] = nodes\n if (nodes.length !== 1) return undefined\n const word =\n node.type === 'function' && node.value === 'var' && 'nodes' in node\n ? node.nodes.find((child) => child.type !== 'space')\n : node\n return word?.type === 'word' && word.value.startsWith('--') && word.value.length > 2\n ? word.value.slice(2)\n : undefined\n}\n\n/** The name `codeSyntax.WEB` gives the token, if it gives one. */\nexport function explicitCSSName(variable: Variable): string | undefined {\n return parseCSSName(variable.codeSyntax?.WEB)\n}\n\n/**\n * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. A group the next segment\n * repeats is said once, so `Gap/gap-1` is `gap-1`, as kits that mirror Tailwind classes name them. Two tokens can derive\n * the same name, so stylesheet output takes names from `variableCSSNames`, which makes them unique.\n */\nexport function deriveCSSName(variable: Variable): string {\n const namespace = variableNamespace(variable)\n const segments = compact(variable.name.split('/').map(tokenSlug))\n if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ''] === namespace) {\n segments.shift()\n }\n const body =\n segments\n .filter((segment, index) => {\n const next = segments.at(index + 1)\n return next === undefined || (next !== segment && !next.startsWith(`${segment}-`))\n })\n .join('-') || 'token'\n if (!namespace || body === namespace || body.startsWith(`${namespace}-`)) return body\n return `${namespace}-${body}`\n}\n\n/**\n * Document-wide custom property names, without `--`. The first token whose `WEB` snippet claims\n * a name keeps it; later claimants, which Figma files do contain, and derived names that collide\n * take a derived name with a numeric suffix, in iteration order.\n */\nexport function variableCSSNames(variables: Iterable<Variable>): Map<string, string> {\n const list = [...variables]\n const names = new Map<string, string>()\n const taken = new Set<string>()\n for (const variable of list) {\n const name = explicitCSSName(variable)\n if (!name || taken.has(name)) continue\n names.set(variable.id, name)\n taken.add(name)\n }\n for (const variable of list) {\n if (names.has(variable.id)) continue\n const base = deriveCSSName(variable)\n let name = base\n for (let n = 2; taken.has(name); n++) name = `${base}-${n}`\n names.set(variable.id, name)\n taken.add(name)\n }\n return names\n}\n\n/** The `WEB` snippet that names a token in Figma's Dev Mode and here. */\nexport function cssNameCodeSyntax(name: string): string {\n return `var(--${name})`\n}\n\n/** Namespaces longest first, so `font-weight-bold` reads as `font-weight`, not `font`. */\nconst NAMESPACES_BY_LENGTH = [...themeNamespaces].sort((a, b) => b.length - a.length)\n\n/**\n * The variable name a custom property reads as: a Tailwind namespace becomes the group, so\n * `color-gray-50` is `color/gray-50` and `radius-md` is `radius/md`; any other name stays as it\n * is. Variables made this way keep the property in their `WEB` code syntax, so the stylesheet\n * writes the same name back.\n */\nexport function cssNameVariableName(name: string): string {\n const namespace = NAMESPACES_BY_LENGTH.find((candidate) => name.startsWith(`${candidate}-`))\n return namespace ? `${namespace}/${name.slice(namespace.length + 1)}` : name\n}\n","import type {\n ColorProfile,\n Effect,\n Fill,\n GradientStop,\n SceneNode,\n ShadowEffect,\n Stroke,\n TextLength\n} from '@pairdraw/scene-graph'\nimport { colorToDocumentCSS } from '@pairdraw/scene-graph/color'\nimport { blurSigma } from '@pairdraw/scene-graph/geometry'\nimport { gradientPoint } from '@pairdraw/scene-graph/gradient'\nimport type { Color, Vector } from '@pairdraw/scene-graph/primitives'\n\nimport type { DesignStyleDeclaration } from '../types'\n\n/** A color as CSS in the document's profile, so a Display P3 color keeps its gamut. */\nexport function cssColor(color: Color, profile: ColorProfile = 'srgb'): string {\n return colorToDocumentCSS(color, profile)\n}\n\nexport function fillToCSS(fill: Fill | undefined, profile: ColorProfile = 'srgb') {\n if (fill?.type !== 'SOLID' || !fill.visible) return undefined\n return cssColor({ ...fill.color, a: fill.opacity }, profile)\n}\n\n/** A number CSS reads the same back: six decimals, no trailing zeros or negative zero. */\nfunction cssNumber(value: number): string {\n const rounded = Number(value.toFixed(6))\n return String(rounded === 0 ? 0 : rounded)\n}\n\nfunction stopToCSS(stop: GradientStop, opacity: number, profile: ColorProfile): string {\n const color = cssColor({ ...stop.color, a: stop.color.a * opacity }, profile)\n return `${color} ${cssNumber(stop.position * 100)}%`\n}\n\n/** The unit-square point as a CSS position pair, percentages of the box's width and height. */\nfunction positionToCSS(point: Vector): string {\n return `${cssNumber(point.x * 100)}% ${cssNumber(point.y * 100)}%`\n}\n\n/**\n * A gradient paint as the CSS gradient that draws it in a `width` × `height` box. The transform\n * maps the box's unit square onto gradient space; its inverse gives the line's ends, the\n * ellipse's centre and radii, or the sweep's start ray. Diamond gradients have no CSS spelling.\n */\nexport function gradientFillToCSS(\n fill: Fill,\n width: number,\n height: number,\n profile: ColorProfile = 'srgb'\n): string | undefined {\n const transform = fill.gradientTransform\n const stops = fill.gradientStops\n if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) {\n return undefined\n }\n const painted = stops.map((stop) => stopToCSS(stop, fill.opacity, profile)).join(', ')\n if (fill.type === 'GRADIENT_LINEAR') {\n const start = gradientPoint(transform, { x: 0, y: 0.5 })\n const end = gradientPoint(transform, { x: 1, y: 0.5 })\n const dx = (end.x - start.x) * width\n const dy = (end.y - start.y) * height\n if (dx === 0 && dy === 0) return undefined\n // CSS angles point up at 0deg and turn clockwise; screen y grows downward.\n const degrees = (Math.atan2(dx, -dy) * 180) / Math.PI\n return `linear-gradient(${cssNumber(degrees)}deg, ${painted})`\n }\n if (fill.type !== 'GRADIENT_RADIAL' && fill.type !== 'GRADIENT_ANGULAR') return undefined\n const center = gradientPoint(transform, { x: 0.5, y: 0.5 })\n const edgeX = gradientPoint(transform, { x: 1, y: 0.5 })\n const edgeY = gradientPoint(transform, { x: 0.5, y: 1 })\n const rx = Math.hypot((edgeX.x - center.x) * width, (edgeX.y - center.y) * height)\n const ry = Math.hypot((edgeY.x - center.x) * width, (edgeY.y - center.y) * height)\n if (rx <= 0 || ry <= 0) return undefined\n const at = `at ${positionToCSS(center)}`\n if (fill.type === 'GRADIENT_RADIAL') {\n const shape =\n Math.abs(rx - ry) < 1e-6\n ? `circle ${cssNumber(rx)}px`\n : `ellipse ${cssNumber(rx)}px ${cssNumber(ry)}px`\n return `radial-gradient(${shape} ${at}, ${painted})`\n }\n const degrees =\n (Math.atan2((edgeX.y - center.y) * height, (edgeX.x - center.x) * width) * 180) / Math.PI + 90\n return `conic-gradient(from ${cssNumber(degrees)}deg ${at}, ${painted})`\n}\n\n/**\n * The paint stack as `background-image`, top layer first as CSS paints it. Solid paints stay\n * out; the bottom one becomes `background-color`, and a solid above another paint has no CSS\n * spelling here. Image paints export through the element's own source, not this list.\n */\nexport function gradientFillsToCSS(\n fills: Fill[],\n width: number,\n height: number,\n profile: ColorProfile = 'srgb'\n): string | undefined {\n const layers: string[] = []\n for (let index = fills.length - 1; index >= 0; index--) {\n const css = gradientFillToCSS(fills[index], width, height, profile)\n if (css) layers.push(css)\n }\n return layers.length > 0 ? layers.join(', ') : undefined\n}\n\nexport type BorderSide = 'top' | 'right' | 'bottom' | 'left'\n\n/**\n * The width of each side of the border a layer's first stroke projects as, zero without one. A\n * border insets the box its absolutely positioned children are placed in, where a stroke does not.\n */\nexport function borderWidths(node: SceneNode): Record<BorderSide, number> {\n const stroke = node.strokes.find((item) => item.visible)\n if (!strokeColorToCSS(stroke)) return { top: 0, right: 0, bottom: 0, left: 0 }\n if (!node.independentStrokeWeights) {\n const weight = stroke?.weight ?? 0\n return { top: weight, right: weight, bottom: weight, left: weight }\n }\n return {\n top: node.borderTopWeight,\n right: node.borderRightWeight,\n bottom: node.borderBottomWeight,\n left: node.borderLeftWeight\n }\n}\n\nexport function strokeColorToCSS(\n stroke: Stroke | undefined,\n profile: ColorProfile = 'srgb'\n): string | undefined {\n if (!stroke?.visible) return undefined\n return cssColor({ ...stroke.color, a: stroke.opacity }, profile)\n}\n\nfunction px(value: number): string {\n return `${Number(value.toFixed(3))}px`\n}\n\n/**\n * A shadow as `box-shadow` writes it, or as `text-shadow` does without its spread. CSS blurs a\n * shadow by half its blur length, so the length is twice the sigma the canvas blurs it by.\n */\nfunction shadowToCSS(effect: ShadowEffect, spread = true, profile: ColorProfile = 'srgb'): string {\n const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''\n const parts = [\n `${inset}${px(effect.offset.x)}`,\n px(effect.offset.y),\n px(2 * blurSigma(effect.radius))\n ]\n if (spread) parts.push(px(effect.spread))\n parts.push(cssColor(effect.color, profile))\n return parts.join(' ')\n}\n\nconst isShadow = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'\n\n/**\n * The blurs as the canvas draws them: the first visible layer blur as `filter`, and every\n * background blur in turn as `backdrop-filter`.\n */\nconst isLayerBlur = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR'\nconst isBackgroundBlur = (effect: Effect): effect is ShadowEffect =>\n effect.type === 'BACKGROUND_BLUR'\nconst isDropShadow = (effect: Effect): effect is ShadowEffect => effect.type === 'DROP_SHADOW'\n\nfunction addBlurs(style: DesignStyleDeclaration, visible: Effect[]): void {\n const layer = visible.find(isLayerBlur)\n if (layer) style.filter = `blur(${px(blurSigma(layer.radius))})`\n const backdrop = visible.filter(isBackgroundBlur)\n if (backdrop.length > 0) {\n style['backdrop-filter'] = backdrop\n .map((effect) => `blur(${px(blurSigma(effect.radius))})`)\n .join(' ')\n }\n}\n\n/**\n * Every visible shadow, in order, plus layer and background blur, blurred as the canvas draws\n * them: CSS's `blur()` takes the Gaussian sigma itself.\n */\nexport function effectsToCSS(\n effects: Effect[],\n profile: ColorProfile = 'srgb'\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n const visible = effects.filter((effect) => effect.visible)\n const shadows = visible.filter(isShadow)\n if (shadows.length > 0)\n style['box-shadow'] = shadows.map((effect) => shadowToCSS(effect, true, profile)).join(', ')\n addBlurs(style, visible)\n return style\n}\n\n/**\n * Text's effects: each visible drop shadow as `text-shadow`, which has no spread and shadows the\n * glyphs, and its layer and background blurs. An inner shadow has no form CSS gives text.\n */\nexport function textEffectsToCSS(\n effects: Effect[],\n profile: ColorProfile = 'srgb'\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n const visible = effects.filter((effect) => effect.visible)\n const shadows = visible.filter(isDropShadow)\n if (shadows.length > 0) {\n style['text-shadow'] = shadows.map((effect) => shadowToCSS(effect, false, profile)).join(', ')\n }\n addBlurs(style, visible)\n return style\n}\n\n/** A line height as CSS writes it: a percent as the unitless multiple that follows the font size. */\nexport function lineHeightToCSS(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : String(length.value / 100)\n}\n\n/** A letter spacing as CSS writes it: a percent of the font size in `em`. */\nexport function letterSpacingToCSS(length: TextLength): string {\n return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`\n}\n\n/**\n * Room for the spacing CSS puts after a line's last letter. A layer fits and aligns its lines by\n * their glyphs, without that spacing, so a spaced text's box is one spacing wider than its own\n * width and a negative margin takes the spacing back: lines break and align as on the canvas, and\n * the text takes the room it does there. Browsers put the spacing on a glyph's right in either\n * direction, so the margin is on the right. `spacing` is the CSS the text's letter spacing is\n * written as, which may refer to a token.\n */\nexport function letterSpacingRoomCSS(\n length: TextLength,\n spacing: string,\n width: string | undefined\n): DesignStyleDeclaration {\n const literal = spacing === letterSpacingToCSS(length)\n return {\n ...(width !== undefined && { width: `calc(${width} + ${spacing})` }),\n 'margin-right': literal\n ? letterSpacingToCSS({ ...length, value: -length.value })\n : `calc(-1 * ${spacing})`\n }\n}\n","import type { TokenUnit, Variable, VariableScope } from '@pairdraw/scene-graph'\nimport { tokenNumberInUnit } from '@pairdraw/scene-graph/variables'\n\nimport { variableNamespace } from './names'\n\nconst UNITLESS_SCOPES = new Set<VariableScope>(['OPACITY', 'FONT_STYLE', 'FONT_VARIATIONS'])\n\n/**\n * A property that takes values in each token unit, where a browser checks or computes a CSS\n * expression written for the token: `scale` takes any plain number, `width` any length.\n */\nexport const TOKEN_UNIT_PROPERTY: Record<TokenUnit, string> = {\n none: 'scale',\n px: 'width',\n rem: 'width',\n '%': 'width',\n ms: 'transition-duration',\n s: 'transition-duration',\n deg: 'rotate'\n}\n\n/**\n * The unit a FLOAT token is written in. An explicit unit wins; opacity and font weights are\n * unitless; every other number is a pixel length, which is what the canvas draws.\n */\nexport function variableUnit(variable: Variable): TokenUnit {\n if (variable.type !== 'FLOAT') return 'none'\n if (variable.unit) return variable.unit\n const scopes = variable.scopes ?? []\n if (scopes.length > 0 && scopes.every((scope) => UNITLESS_SCOPES.has(scope))) return 'none'\n return variableNamespace(variable) === 'font-weight' ? 'none' : 'px'\n}\n\n/** Six decimals keep `rem` exact for every pixel step down to 1/1024px (0.5px is 0.03125rem). */\nfunction trimNumber(value: number): string {\n return String(Number(value.toFixed(6)))\n}\n\n/** A stored number written in its unit: 24 as `rem` is `1.5rem`, 150 as `ms` is `150ms`. */\nexport function tokenNumberToCSS(value: number, unit: TokenUnit): string {\n const number = trimNumber(tokenNumberInUnit(value, unit))\n if (unit === 'none' || number === '0') return number\n return `${number}${unit}`\n}\n","import type { Variable, VariableFormulaNode } from '@pairdraw/scene-graph'\nimport { foldFormula } from '@pairdraw/scene-graph/variables'\n\nimport { tokenNumberToCSS, variableUnit } from './values'\n\n/**\n * A number formula as `calc()`, with each reference a `var()`. CSS adds only like with like and\n * multiplies a length only by a plain number, so a literal takes the unit of what it is added\n * to, and a formula CSS cannot type, such as a length times a length, has no CSS form.\n */\ntype Term =\n | { kind: 'literal'; value: number }\n | { kind: 'css'; text: string; precedence: number; dimension: boolean }\n\nconst OPERATORS = {\n add: { symbol: '+', precedence: 1 },\n subtract: { symbol: '-', precedence: 1 },\n multiply: { symbol: '*', precedence: 2 },\n divide: { symbol: '/', precedence: 2 }\n} as const\ntype Arithmetic = keyof typeof OPERATORS\nconst ATOM = 3\n\nclass UnsupportedFormulaError extends Error {\n override name = 'UnsupportedFormulaError'\n}\n\ninterface FormulaContext {\n variables: ReadonlyMap<string, Variable>\n names: ReadonlyMap<string, string>\n /** A literal written as a length, in the exported token's unit. */\n length: (value: number) => string\n}\n\nexport function formulaToCSS(\n node: VariableFormulaNode,\n variable: Variable,\n variables: ReadonlyMap<string, Variable>,\n names: ReadonlyMap<string, string>\n): string | { issue: string } {\n const unit = variableUnit(variable)\n const context = { variables, names, length: (value: number) => tokenNumberToCSS(value, unit) }\n try {\n const result = convert(node, context)\n const dimension = unit !== 'none'\n if (result.kind === 'literal') return write(result, dimension, context)\n if (result.dimension !== dimension)\n return { issue: dimension ? 'has a formula without a unit' : 'has a formula with a unit' }\n return `calc(${result.text})`\n } catch (error) {\n if (error instanceof UnsupportedFormulaError) return { issue: error.message }\n throw error\n }\n}\n\nfunction convert(node: VariableFormulaNode, context: FormulaContext): Term {\n return foldFormula<Term>(node, {\n literal: (value) => {\n if (typeof value === 'number') return { kind: 'literal', value }\n if (typeof value === 'boolean')\n throw new UnsupportedFormulaError('mixes true/false into a number')\n throw new UnsupportedFormulaError('mixes text or a color into a number')\n },\n reference: (id) => reference(id, context),\n operation: ({ operator }, operands) => {\n const [a, b] = operands\n if (operator === 'negate' && operands.length === 1) return negate(a, context)\n if (operands.length !== 2 || !isArithmetic(operator))\n throw new UnsupportedFormulaError('uses logic that CSS has no form for')\n if (a.kind === 'literal' && b.kind === 'literal')\n return { kind: 'literal', value: fold(operator, a.value, b.value) }\n return binary(operator, a, b, context)\n }\n })\n}\n\nfunction reference(id: string, { variables, names }: FormulaContext): Term {\n const target = variables.get(id)\n const name = names.get(id)\n if (!target || !name)\n throw new UnsupportedFormulaError('refers to a variable that does not exist')\n if (target.type !== 'FLOAT')\n throw new UnsupportedFormulaError('uses a variable that is not a number')\n const dimension = variableUnit(target) !== 'none'\n return { kind: 'css', text: `var(--${name})`, precedence: ATOM, dimension }\n}\n\nfunction negate(term: Term, context: FormulaContext): Term {\n if (term.kind === 'literal') return { kind: 'literal', value: -term.value }\n const text = `-1 * ${grouped(term, false, OPERATORS.multiply.precedence, context)}`\n return { kind: 'css', text, precedence: OPERATORS.multiply.precedence, dimension: term.dimension }\n}\n\nfunction binary(operator: Arithmetic, a: Term, b: Term, context: FormulaContext): Term {\n const { symbol, precedence } = OPERATORS[operator]\n // The right side of - and / keeps its parentheses even at equal precedence.\n const rightBelow = operator === 'subtract' || operator === 'divide' ? precedence + 1 : precedence\n const aDimension = a.kind === 'css' && a.dimension\n const bDimension = b.kind === 'css' && b.dimension\n if (precedence === 1) {\n if (a.kind === 'css' && b.kind === 'css' && aDimension !== bDimension)\n throw new UnsupportedFormulaError('adds a length to a plain number')\n const dimension = aDimension || bDimension\n const left = grouped(a, dimension, precedence, context)\n const right = grouped(b, dimension, rightBelow, context)\n return { kind: 'css', text: `${left} ${symbol} ${right}`, precedence, dimension }\n }\n if (bDimension && operator === 'divide') throw new UnsupportedFormulaError('divides by a length')\n if (aDimension && bDimension) throw new UnsupportedFormulaError('multiplies two lengths')\n const left = grouped(a, false, precedence, context)\n const right = grouped(b, false, rightBelow, context)\n return {\n kind: 'css',\n text: `${left} ${symbol} ${right}`,\n precedence,\n dimension: aDimension || bDimension\n }\n}\n\nfunction write(term: Term, dimension: boolean, context: FormulaContext) {\n if (term.kind === 'css') return term.text\n return dimension ? context.length(term.value) : String(Number(term.value.toFixed(6)))\n}\n\nfunction grouped(term: Term, dimension: boolean, below: number, context: FormulaContext) {\n return term.kind === 'css' && term.precedence < below\n ? `(${term.text})`\n : write(term, dimension, context)\n}\n\nfunction isArithmetic(operator: string): operator is Arithmetic {\n return Object.hasOwn(OPERATORS, operator)\n}\n\nfunction fold(operator: Arithmetic, a: number, b: number) {\n if (operator === 'add') return a + b\n if (operator === 'subtract') return a - b\n if (operator === 'multiply') return a * b\n return a / b\n}\n","import valueParser from 'postcss-value-parser'\n\nimport type { CSSStyleSheetLike } from '../cssom/types'\n\ntype Parse = (cssText: string) => CSSStyleSheetLike\n\nconst AT_RULES = ['@media', '@supports', '@container'] as const\n\n/** What a rule looks like to the checks below; the object model's own types are wider. */\ntype ParsedRule = {\n cssRules?: unknown[]\n selectorText?: string\n style?: { length: number; getPropertyValue(property: string): string }\n}\n\nfunction rules(sheet: CSSStyleSheetLike): ParsedRule[] {\n return sheet.cssRules.filter(\n (rule): rule is ParsedRule => typeof rule === 'object' && rule !== null\n )\n}\n\n/**\n * Token strings come from documents, so each one is parsed in place before it is written. A value\n * or condition that closes its rule early parses to a different number of rules and fails.\n */\nexport function createTokenValidator(parse: Parse) {\n /** `--name: value` is one declaration whose value reads back unchanged. */\n function declaration(name: string, value: string): boolean {\n const parsed = rules(parse(`:root{--${name}:${value}}`))\n const [rule] = parsed\n return (\n parsed.length === 1 &&\n rule.style?.length === 1 &&\n rule.style.getPropertyValue(`--${name}`).trim() === value.trim() &&\n (rule.cssRules?.length ?? 0) === 0\n )\n }\n\n return {\n declaration,\n\n /**\n * A custom property name without its `--`: one word to the CSS value tokenizer, which splits\n * on spaces, colons, commas and slashes, and one declaration to the parser. It starts with a\n * letter, digit or underscore, so `--` is never doubled into `----`.\n */\n name(name: string): boolean {\n const { nodes } = valueParser(`--${name}`)\n return (\n /^\\w/.test(name) &&\n nodes.length === 1 &&\n nodes[0]?.type === 'word' &&\n declaration(name, '0')\n )\n },\n\n /** A selector, or a `@media`, `@supports` or `@container` prelude, that wraps exactly one rule. */\n condition(condition: string): boolean {\n const trimmed = condition.trim()\n if (trimmed.startsWith('@')) {\n if (\n !AT_RULES.some((rule) => trimmed.startsWith(`${rule} `) || trimmed.startsWith(`${rule}(`))\n )\n return false\n const parsed = rules(parse(`${trimmed}{:root{--t:0}}`))\n return parsed.length === 1 && parsed[0]?.cssRules?.length === 1\n }\n const parsed = rules(parse(`${trimmed}{--t:0}`))\n const [rule] = parsed\n return (\n parsed.length === 1 &&\n typeof rule.selectorText === 'string' &&\n rule.style?.length === 1 &&\n (rule.cssRules?.length ?? 0) === 0\n )\n }\n }\n}\n\nexport type TokenValidator = ReturnType<typeof createTokenValidator>\n\n/** The browser's own CSS parser, through a constructable stylesheet. */\nexport function parseWithBrowser(cssText: string): CSSStyleSheetLike {\n const sheet = new CSSStyleSheet()\n sheet.replaceSync(cssText)\n return { cssRules: [...sheet.cssRules] }\n}\n","import type {\n ColorProfile,\n SceneGraph,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableValue\n} from '@pairdraw/scene-graph'\nimport { variableValueReferences } from '@pairdraw/scene-graph/variables'\n\nimport { cssColor } from '../export/css'\nimport { formulaToCSS } from './formula'\nimport {\n collectionVariables,\n deriveCSSName,\n explicitCSSName,\n tokenSlug,\n variableCSSNames,\n variableNamespace\n} from './names'\nimport { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'\nimport { tokenNumberToCSS, variableUnit } from './values'\n\nexport type TokenStylesheetFormat = 'css' | 'tailwind'\n\nexport type TokenStylesheetIssue = {\n message: string\n variableId?: string\n collectionId?: string\n modeId?: string\n}\n\nexport type TokenStylesheetOptions = {\n format: TokenStylesheetFormat\n /** Write only these tokens. Names still come from every token, so aliases outside resolve. */\n include?: (variable: Variable) => boolean\n}\n\nexport type TokenStylesheet = {\n css: string\n issues: TokenStylesheetIssue[]\n}\n\ntype Declaration = { name: string; value: string }\n\ntype ModeScope = {\n collection: VariableCollection\n mode: VariableCollectionMode\n condition: string\n declarations: Declaration[]\n}\n\ntype TokenSource = Pick<SceneGraph, 'variables' | 'variableCollections' | 'documentColorSpace'>\n\nfunction isAtRuleCondition(condition: string): boolean {\n return condition.trim().startsWith('@')\n}\n\n/**\n * A mode's name as an identifier. A name with no letters or digits falls back to its id, slugged\n * too: Figma ids such as `1:2` are not valid in a selector value or a variant name as they are.\n * Names that slug alike in one collection, such as `Dark` and `dark!`, are numbered in mode\n * order, so each mode keeps its own selector and variant.\n */\nfunction modeSlug(collection: VariableCollection, mode: VariableCollectionMode): string {\n const plainSlug = ({ name, modeId }: VariableCollectionMode) =>\n tokenSlug(name) || `mode-${tokenSlug(modeId) || 'unnamed'}`\n const taken = new Set<string>()\n for (const candidate of collection.modes) {\n const base = plainSlug(candidate)\n let slug = base\n for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`\n if (candidate.modeId === mode.modeId) return slug\n taken.add(slug)\n }\n return plainSlug(mode)\n}\n\n/** The attribute a collection's manual modes are switched by, unless it names its own. */\nexport function defaultModeAttributeName(collection: VariableCollection): string {\n return `data-${tokenSlug(collection.name) || 'mode'}`\n}\n\n/** The attribute that puts an element in a mode with no condition of its own: `data-theme`. */\nexport function modeAttribute(\n collection: VariableCollection,\n mode: VariableCollectionMode\n): { name: string; value: string } {\n return {\n name: collection.modeAttribute ?? defaultModeAttributeName(collection),\n value: modeSlug(collection, mode)\n }\n}\n\n/** The scope a mode applies in when it names none: `[data-theme=\"dark\"]` for Theme / Dark. */\nexport function defaultModeCondition(\n collection: VariableCollection,\n mode: VariableCollectionMode\n): string {\n const { name, value } = modeAttribute(collection, mode)\n return `[${name}=\"${value}\"]`\n}\n\nfunction quoteString(value: string): string {\n return `\"${value.replaceAll('\\\\', '\\\\\\\\').replaceAll('\"', '\\\\\"').replaceAll('\\n', '\\\\a ')}\"`\n}\n\n/** One mode's value as CSS, or why it has none. */\nfunction modeValue(\n variable: Variable,\n value: VariableValue | undefined,\n modeId: string,\n names: ReadonlyMap<string, string>,\n variables: ReadonlyMap<string, Variable>,\n profile: ColorProfile\n): string | { issue: string } {\n const expression = variable.expressions?.[modeId]\n if (expression) return expression.css\n if (value === undefined) return { issue: 'has no value in this mode' }\n if (typeof value === 'object' && 'expression' in value) {\n if (value.expression === 'FORMULA' && variable.type === 'FLOAT')\n return formulaToCSS(value.value, variable, variables, names)\n if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }\n return { issue: 'uses an expression that CSS token export does not support' }\n }\n if (typeof value === 'object' && 'aliasId' in value) {\n const target = names.get(value.aliasId)\n return target ? `var(--${target})` : { issue: 'aliases a variable that does not exist' }\n }\n if (variable.type === 'COLOR' && typeof value === 'object') return cssColor(value, profile)\n if (variable.type === 'FLOAT' && typeof value === 'number')\n return tokenNumberToCSS(value, variableUnit(variable))\n if (variable.type === 'STRING' && typeof value === 'string')\n return variableNamespace(variable) === 'font' ? value : quoteString(value)\n if (variable.type === 'BOOLEAN') return { issue: 'is a boolean, which CSS has no value for' }\n return { issue: 'has a value that does not match its type' }\n}\n\nfunction block(selector: string, declarations: Declaration[], indent = ''): string {\n const body = declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join('\\n')\n return `${indent}${selector} {\\n${body}\\n${indent}}`\n}\n\n/**\n * A comment naming `text`. Collection and mode names are the person's own text, so a `*` before\n * a `/` in them is spaced apart, which keeps a name from ending the comment and writing rules.\n */\nfunction cssComment(text: string): string {\n return `/* ${text.replaceAll('*/', '* /')} */`\n}\n\nfunction modeBlock(scope: ModeScope): string {\n const comment = cssComment(`${scope.collection.name}: ${scope.mode.name}`)\n if (!isAtRuleCondition(scope.condition))\n return `${comment}\\n${block(scope.condition, scope.declarations)}`\n return `${comment}\\n${scope.condition} {\\n${block(':root', scope.declarations, ' ')}\\n}`\n}\n\n/** `@custom-variant dark (&:where([data-theme=\"dark\"], [data-theme=\"dark\"] *));` */\nfunction customVariant(name: string, condition: string): string {\n const body = isAtRuleCondition(condition) ? condition : `&:where(${condition}, ${condition} *)`\n return `@custom-variant ${name} (${body});`\n}\n\n/** Variants are named after their mode, prefixed with the collection where two modes share a name. */\nfunction variantNames(scopes: ModeScope[]): string[] {\n const plain = scopes.map(({ collection, mode }) => modeSlug(collection, mode))\n return plain.map((name, index) => {\n const shared = plain.filter((other) => other === name).length > 1\n const collection = scopes[index]?.collection.name ?? ''\n return shared ? `${tokenSlug(collection)}-${name}` : name\n })\n}\n\n/**\n * Variables as a stylesheet of custom properties. The default mode of every collection is the\n * base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;\n * every other mode overrides the values that differ, under its condition. Aliases stay `var()`\n * references, and number formulas `calc()` over them; both are declared again in each mode that\n * changes what they point to.\n */\n/**\n * A name that took a numeric suffix is an alias nobody can read back from the stylesheet, so it\n * is reported rather than left as a silent second spelling of another token.\n */\nfunction numberedNameIssues(\n variables: readonly Variable[],\n names: Map<string, string>,\n modeOf: (variable: Variable) => string\n): TokenStylesheetIssue[] {\n const issues: TokenStylesheetIssue[] = []\n for (const variable of variables) {\n const name = names.get(variable.id)\n const base = deriveCSSName(variable)\n if (!name || explicitCSSName(variable) || name === base) continue\n issues.push({\n message: `\"${variable.name}\" is written --${name}: --${base} is taken`,\n variableId: variable.id,\n modeId: modeOf(variable)\n })\n }\n return issues\n}\n\nexport function buildTokenStylesheet(\n source: TokenSource,\n { format, include = () => true }: TokenStylesheetOptions,\n validate: TokenValidator\n): TokenStylesheet {\n const issues: TokenStylesheetIssue[] = []\n const collections = [...source.variableCollections.values()]\n const all = collectionVariables(source)\n const names = variableCSSNames(all)\n const variables = all.filter(include)\n const defaultModeOf = (variable: Variable) =>\n source.variableCollections.get(variable.collectionId)?.defaultModeId ?? ''\n\n function declare(\n variable: Variable,\n modeId: string,\n value: VariableValue | undefined\n ): Declaration | undefined {\n const name = names.get(variable.id) ?? variable.id\n const css = modeValue(\n variable,\n value,\n modeId,\n names,\n source.variables,\n source.documentColorSpace\n )\n if (typeof css !== 'string') {\n issues.push({ message: `${variable.name} ${css.issue}`, variableId: variable.id, modeId })\n return undefined\n }\n if (!validate.declaration(name, css)) {\n issues.push({\n message: `${variable.name} is not a valid CSS declaration: --${name}: ${css}`,\n variableId: variable.id,\n modeId\n })\n return undefined\n }\n return { name, value: css }\n }\n\n issues.push(...numberedNameIssues(variables, names, defaultModeOf))\n\n const defaults = new Map<string, Declaration>()\n const theme: Declaration[] = []\n const root: Declaration[] = []\n for (const variable of variables) {\n const modeId = defaultModeOf(variable)\n const declaration = declare(variable, modeId, variable.valuesByMode[modeId])\n if (!declaration) continue\n defaults.set(variable.id, declaration)\n if (format === 'tailwind' && variableNamespace(variable) !== undefined) theme.push(declaration)\n else root.push(declaration)\n }\n\n /**\n * What a mode's scope declares: the collection's values that differ from its default, and every\n * alias or formula, in any collection, whose chain reaches one of them. Custom properties inherit as\n * computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue\n * unless it is declared again where `--blue` changes.\n */\n function modeDeclarations(\n collection: VariableCollection,\n mode: VariableCollectionMode\n ): Declaration[] {\n const own = (variable: Variable) => variable.collectionId === collection.id\n const valueIn = (variable: Variable) =>\n own(variable)\n ? (variable.valuesByMode[mode.modeId] ?? variable.valuesByMode[collection.defaultModeId])\n : variable.valuesByMode[defaultModeOf(variable)]\n const inMode = new Map<string, Declaration>()\n const scoped = new Map<string, Declaration>()\n for (const variable of variables.filter(own)) {\n const declaration = declare(variable, mode.modeId, valueIn(variable))\n if (!declaration) continue\n inMode.set(variable.id, declaration)\n if (declaration.value !== defaults.get(variable.id)?.value)\n scoped.set(variable.id, declaration)\n }\n for (let grew = true; grew;) {\n grew = false\n for (const variable of variables) {\n const references = variableValueReferences(valueIn(variable))\n if (scoped.has(variable.id) || !references.some((target) => scoped.has(target))) continue\n const declaration = inMode.get(variable.id) ?? defaults.get(variable.id)\n if (!declaration) continue\n scoped.set(variable.id, declaration)\n grew = true\n }\n }\n return variables.flatMap((variable) => {\n const declaration = scoped.get(variable.id)\n return declaration ? [declaration] : []\n })\n }\n\n const scopes: ModeScope[] = []\n for (const collection of collections) {\n for (const mode of collection.modes) {\n if (mode.modeId === collection.defaultModeId) continue\n const condition = mode.condition ?? defaultModeCondition(collection, mode)\n if (!validate.condition(condition)) {\n issues.push({\n message: `${collection.name}: ${mode.name} has a condition that is not a selector or a @media, @supports or @container query: ${condition}`,\n collectionId: collection.id,\n modeId: mode.modeId\n })\n continue\n }\n const declarations = modeDeclarations(collection, mode)\n if (declarations.length > 0) scopes.push({ collection, mode, condition, declarations })\n }\n }\n\n const sections: string[] = []\n if (theme.length > 0) sections.push(block('@theme', theme))\n if (root.length > 0) sections.push(block(':root', root))\n sections.push(...scopes.map(modeBlock))\n if (format === 'tailwind' && scopes.length > 0) {\n const variants = variantNames(scopes)\n sections.push(\n scopes\n .map((scope, index) =>\n customVariant(variants[index] ?? modeSlug(scope.collection, scope.mode), scope.condition)\n )\n .join('\\n')\n )\n }\n return { css: sections.length > 0 ? `${sections.join('\\n\\n')}\\n` : '', issues }\n}\n\n/**\n * Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS\n * object model package loads on first use; its browser build exports nothing, so it is never\n * the browser path.\n */\nexport async function loadTokenValidator(): Promise<TokenValidator> {\n if (typeof CSSStyleSheet === 'function') return createTokenValidator(parseWithBrowser)\n const headless = await import('./cssom-validator')\n return headless.tokenValidator\n}\n\nexport async function tokenStylesheet(\n source: TokenSource,\n options: TokenStylesheetOptions\n): Promise<TokenStylesheet> {\n return buildTokenStylesheet(source, options, await loadTokenValidator())\n}\n","import type { SceneGraph, SceneNode, Variable } from '@pairdraw/scene-graph'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { collectionVariables, variableCSSNames, variableNamespace } from './names'\nimport { modeAttribute } from './stylesheet'\nimport { variableUnit } from './values'\n\n/** The mode CSS applies for each collection, by collection id. */\nexport type CSSModes = ReadonlyMap<string, string>\n\n/** Bound fields drawn as a length; any other numeric binding is unitless or not exported. */\nconst LENGTH_FIELDS = new Set([\n 'width',\n 'height',\n 'minWidth',\n 'maxWidth',\n 'minHeight',\n 'maxHeight',\n 'cornerRadius',\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomLeftRadius',\n 'bottomRightRadius',\n 'strokeWeight',\n 'borderTopWeight',\n 'borderBottomWeight',\n 'borderLeftWeight',\n 'borderRightWeight',\n 'fontSize',\n 'letterSpacing',\n 'lineHeight',\n 'paddingLeft',\n 'paddingRight',\n 'paddingTop',\n 'paddingBottom',\n 'itemSpacing',\n 'counterAxisSpacing',\n 'gridRowGap',\n 'gridColumnGap'\n])\n\nconst LENGTH_UNITS = new Set(['px', 'rem'])\n\n/** Color channels are stored as floats; a bound paint copies them, so this only absorbs rounding. */\nconst CHANNEL_TOLERANCE = 1 / 512\n\nconst CHANNELS = ['r', 'g', 'b', 'a'] as const\n\nfunction sameColor(a: Color, b: Color): boolean {\n return CHANNELS.every((channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE)\n}\n\nfunction isColor(value: unknown): value is Color {\n return typeof value === 'object' && value !== null && 'r' in value && 'a' in value\n}\n\n/**\n * A field's value as the number a token gives it. A text's letter spacing and line height are\n * lengths: in pixels they match by their value, while a percent of the font size, or automatic\n * line height, has no length token to match and stays literal.\n */\nfunction drawnNumber(node: SceneNode, field: string): number | undefined {\n if (field === 'letterSpacing' || field === 'lineHeight') {\n const length = node[field]\n return length?.unit === 'PIXELS' ? length.value : undefined\n }\n const value: unknown = Reflect.get(node, field)\n return typeof value === 'number' ? value : undefined\n}\n\n/** Where an alias chain ends in the modes the canvas draws: a value, or a CSS expression. */\ntype TokenChain = {\n ids: string[]\n value: Variable['valuesByMode'][string] | undefined\n end: Variable\n expression: boolean\n}\n\n/** The paint a `fills/0/color` or `strokes/1/color` binding names. */\nfunction boundPaint(node: SceneNode, field: string) {\n const [list, index] = field.split('/')\n if (list === 'fills') return node.fills[Number(index)]\n if (list === 'strokes') return node.strokes[Number(index)]\n return undefined\n}\n\n/**\n * Variable references for design-to-code. A bound field becomes `var(--name)` only when the\n * stylesheet resolves it to what the canvas draws: the element sits in the same modes, and the\n * token's CSS value is a length for a length, a bare number for opacity, or the paint's color.\n * Anything else keeps its literal value.\n */\nexport class DesignTokens {\n readonly names: ReadonlyMap<string, string>\n /** Tokens the output references, with every variable their aliases reach. */\n readonly used = new Set<string>()\n readonly #graph: SceneGraph\n\n constructor(graph: SceneGraph) {\n this.#graph = graph\n this.names = variableCSSNames(collectionVariables(graph))\n }\n\n /** The modes CSS applies outside the exported nodes: every collection's default. */\n defaultModes(): CSSModes {\n return new Map(\n [...this.#graph.variableCollections.values()].map((collection) => [\n collection.id,\n collection.defaultModeId\n ])\n )\n }\n\n /**\n * Attributes that put an element in the modes the canvas draws it in, and the modes CSS then\n * applies to it. An exported root takes the editor's active modes; below it, a node changes\n * modes only where it sets one. Only a mode without its own condition can be set this way.\n */\n enter(\n node: SceneNode,\n inherited: CSSModes,\n root: boolean\n ): { attrs: Record<string, string>; modes: CSSModes } {\n const attrs: Record<string, string> = {}\n const modes = new Map(inherited)\n for (const collection of this.#graph.variableCollections.values()) {\n if (!root && !node.variableModes[collection.id]) continue\n const modeId = this.#graph.getNodeVariableModeId(node.id, collection.id)\n const mode = collection.modes.find((candidate) => candidate.modeId === modeId)\n if (!mode || modeId === inherited.get(collection.id)) continue\n if (modeId === collection.defaultModeId || mode.condition) continue\n const { name, value } = modeAttribute(collection, mode)\n attrs[name] = value\n modes.set(collection.id, modeId)\n }\n return { attrs, modes }\n }\n\n /** `var(--name)` for a bound field, or `undefined` where the literal value must stay. */\n reference(node: SceneNode, field: string, modes: CSSModes): string | undefined {\n const variableId = node.boundVariables[field]\n const variable = variableId ? this.#graph.variables.get(variableId) : undefined\n const name = variable && this.names.get(variable.id)\n if (!variable || !name) return undefined\n const chain = this.#chain(node, variable, modes)\n if (!chain || !this.#drawsResolved(node, field, chain)) return undefined\n for (const id of chain.ids) this.used.add(id)\n return `var(--${name})`\n }\n\n /**\n * Follow aliases in the modes the canvas draws the node in, stopping at a value or at a CSS\n * expression, which is what the stylesheet writes for that mode. Fails where CSS would resolve\n * any link in another mode.\n */\n #chain(node: SceneNode, start: Variable, modes: CSSModes): TokenChain | undefined {\n const ids: string[] = []\n let variable: Variable | undefined = start\n while (variable && !ids.includes(variable.id)) {\n ids.push(variable.id)\n const modeId = this.#graph.getNodeVariableModeId(node.id, variable.collectionId)\n const collection = this.#graph.variableCollections.get(variable.collectionId)\n const cssModeId = modes.get(variable.collectionId) ?? collection?.defaultModeId\n if (modeId !== cssModeId) return undefined\n const value =\n variable.valuesByMode[modeId] ??\n (collection ? variable.valuesByMode[collection.defaultModeId] : undefined)\n if (variable.expressions?.[modeId]) return { ids, value, end: variable, expression: true }\n if (typeof value === 'object' && 'aliasId' in value) {\n variable = this.#graph.variables.get(value.aliasId)\n continue\n }\n return { ids, value, end: variable, expression: false }\n }\n return undefined\n }\n\n #drawsResolved(node: SceneNode, field: string, { value, end, expression }: TokenChain): boolean {\n if (field.endsWith('/color')) {\n const paint = boundPaint(node, field)\n if (!paint?.visible || paint.type !== 'SOLID' || !isColor(value)) return false\n return sameColor({ ...paint.color, a: paint.opacity }, value)\n }\n const drawn = drawnNumber(node, field)\n if (drawn === undefined || typeof value !== 'number') return false\n if (Math.fround(drawn) !== Math.fround(value)) return false\n // An expression is the author's CSS for the value, whatever unit the token stores.\n if (field === 'opacity') return expression || variableUnit(end) === 'none'\n return LENGTH_FIELDS.has(field) && (expression || LENGTH_UNITS.has(variableUnit(end)))\n }\n\n /**\n * The variables a stylesheet for this output declares: the referenced ones and every variable\n * their aliases reach in any mode, since each mode's scope declares its own alias targets.\n */\n stylesheetVariables(): Set<string> {\n const ids = new Set<string>()\n const pending = [...this.used]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (ids.has(id)) continue\n ids.add(id)\n for (const value of Object.values(this.#graph.variables.get(id)?.valuesByMode ?? {}))\n if (typeof value === 'object' && 'aliasId' in value) pending.push(value.aliasId)\n }\n return ids\n }\n\n /** Custom properties the Tailwind stylesheet declares in `@theme`, which name utilities. */\n themeVariables(): string[] {\n return [...this.names].flatMap(([id, name]) => {\n const variable = this.#graph.variables.get(id)\n return variable && variableNamespace(variable) !== undefined ? [`--${name}`] : []\n })\n }\n}\n","import type { GridTrack, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { DesignStyleDeclaration } from '../types'\n\nfunction trackToCSS(track: GridTrack): string {\n if (track.sizing === 'FR') return `${track.value}fr`\n if (track.sizing === 'FIXED') return `${track.value}px`\n return 'auto'\n}\n\n/** Equal `1fr` tracks use Tailwind's `grid-cols-N` form, which keeps them from overflowing. */\nfunction tracksToCSS(tracks: GridTrack[]): string {\n if (tracks.every((track) => track.sizing === 'FR' && track.value === 1))\n return `repeat(${tracks.length}, minmax(0, 1fr))`\n return tracks.map(trackToCSS).join(' ')\n}\n\nexport function addGridContainer(\n style: DesignStyleDeclaration,\n node: SceneNode,\n css: (field: string, literal: string) => string\n): void {\n style.display = 'grid'\n if (node.gridTemplateColumns.length > 0)\n style['grid-template-columns'] = tracksToCSS(node.gridTemplateColumns)\n if (node.gridTemplateRows.length > 0)\n style['grid-template-rows'] = tracksToCSS(node.gridTemplateRows)\n if (node.gridColumnGap > 0) style['column-gap'] = css('gridColumnGap', `${node.gridColumnGap}px`)\n if (node.gridRowGap > 0) style['row-gap'] = css('gridRowGap', `${node.gridRowGap}px`)\n}\n\n/** A span sets the whole placement, so the start follows it. */\nexport function addGridPlacement(style: DesignStyleDeclaration, node: SceneNode): void {\n const position = node.gridPosition\n if (!position) return\n if (position.columnSpan > 1)\n style['grid-column'] = `span ${position.columnSpan} / span ${position.columnSpan}`\n if (position.column > 0) style['grid-column-start'] = String(position.column)\n if (position.rowSpan > 1)\n style['grid-row'] = `span ${position.rowSpan} / span ${position.rowSpan}`\n if (position.row > 0) style['grid-row-start'] = String(position.row)\n}\n","import type { ConstraintType, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { DesignStyleDeclaration } from '../types'\nimport { borderWidths } from './css'\n\nconst AXES = {\n width: { constraint: 'horizontalConstraint', start: 'left', end: 'right', at: 'x' },\n height: { constraint: 'verticalConstraint', start: 'top', end: 'bottom', at: 'y' }\n} as const\n\ntype Axis = keyof typeof AXES\n\nconst length = (value: number) => `${Number(value.toFixed(3))}px`\nconst percent = (value: number) => `${Number((value * 100).toFixed(4))}%`\n\n/** A percentage of the containing block moved by a length, as `calc()` when it moves. */\nfunction shifted(base: string, by: number): string {\n if (Number(by.toFixed(3)) === 0) return base\n return `calc(${base} ${by < 0 ? '-' : '+'} ${length(Math.abs(by))})`\n}\n\n/**\n * A placed layer along one axis, measured in the box CSS places it in: inside the parent's\n * border, which a stroke on the canvas does not take from its children. A parent with no size\n * on the axis leaves its box to the page, so its children keep their start and size there.\n */\nfunction placedAxis(node: SceneNode, parent: SceneNode | undefined, axis: Axis) {\n const { constraint, start, end, at } = AXES[axis]\n const border = parent ? borderWidths(parent) : undefined\n const inset = border?.[start] ?? 0\n const room = (parent?.[axis] ?? 0) - inset - (border?.[end] ?? 0)\n const kind: ConstraintType = parent && room > 0 ? node[constraint] : 'MIN'\n const before = node[at] - inset\n return { kind, room, before, after: room - before - node[axis] }\n}\n\n/**\n * Whether a placed layer's constraint sizes it along an axis: Left and Right and Scale both size\n * it from the parent, so it takes no fixed size.\n */\nexport function constraintSizes(\n node: SceneNode,\n parent: SceneNode | undefined,\n axis: Axis\n): boolean {\n const { kind } = placedAxis(node, parent, axis)\n return kind === 'STRETCH' || kind === 'SCALE'\n}\n\n/**\n * Whether a layer's parent leaves it to its coordinates: it is absolutely positioned, or its\n * parent frame has no auto layout. The parent it is placed in is the one its constraints follow.\n */\nexport function placement(\n node: SceneNode,\n parent: SceneNode | undefined\n): { parent: SceneNode | undefined } | null {\n const frame = parent?.type === 'CANVAS' ? undefined : parent\n if (node.layoutPositioning === 'ABSOLUTE' || frame?.layoutMode === 'NONE')\n return { parent: frame }\n return null\n}\n\n/**\n * Place a layer by its constraints when its parent does not lay it out. A frame without auto\n * layout becomes the containing block of the children it places.\n */\nexport function addPositioning(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n const placed = placement(node, parent)\n if (placed) {\n style.position = 'absolute'\n addConstrainedPlacement(style, node, placed.parent)\n } else if (node.layoutMode === 'NONE' && node.type !== 'TEXT' && node.childIds.length > 0) {\n style.position = 'relative'\n }\n}\n\n/**\n * Place a layer by its constraints, so it follows the parent when the page resizes it as the\n * canvas does (`resize.ts` in `@pairdraw/scene-graph`): Left and Top keep the start edge,\n * Right and Bottom the end edge, Center the offset from the centre, Left and Right both edges,\n * and Scale its share of the parent. A stretched size is written out rather than left to both\n * edges, which an image would not fill.\n */\nfunction addConstrainedPlacement(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n for (const axis of ['width', 'height'] as const) {\n const { start, end } = AXES[axis]\n const { kind, room, before, after } = placedAxis(node, parent, axis)\n if (kind === 'MAX') {\n style[end] = length(after)\n } else if (kind === 'CENTER') {\n style[start] = shifted('50%', before - room / 2)\n } else if (kind === 'STRETCH') {\n style[start] = length(before)\n style[axis] = shifted('100%', node[axis] - room)\n } else if (kind === 'SCALE') {\n style[start] = percent(before / room)\n style[axis] = percent(node[axis] / room)\n } else {\n style[start] = length(before)\n }\n }\n}\n","import { uniq } from 'es-toolkit/array'\nimport { isEqual } from 'es-toolkit/predicate'\n\nimport type {\n CharacterStyleOverride,\n ColorProfile,\n HyperlinkTarget,\n SceneNode,\n TextLength\n} from '@pairdraw/scene-graph'\nimport {\n hasTextList,\n listNumberFormat,\n paragraphSpacingAt,\n paragraphStyleAt,\n pixelLength,\n textLengthPixels,\n textListItems,\n textParagraphRanges,\n type TextListItem,\n type TextParagraphRange\n} from '@pairdraw/scene-graph/text'\n\nimport type { DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport { fillToCSS, letterSpacingToCSS, lineHeightToCSS } from './css'\n\n/** The character styles CSS writes, as a text layer and its runs hold them. */\ntype CharacterStyle = Pick<\n SceneNode,\n | 'fontFamily'\n | 'fontSize'\n | 'fontWeight'\n | 'italic'\n | 'letterSpacing'\n | 'lineHeight'\n | 'fills'\n | 'textDecoration'\n | 'textDecorationStyle'\n | 'textDecorationThickness'\n | 'textDecorationFills'\n | 'textDecorationSkipInk'\n | 'textUnderlineOffset'\n | 'textCase'\n>\n\ntype CharacterStyleKey = keyof CharacterStyle\n\nconst CHARACTER_STYLE_KEYS: readonly CharacterStyleKey[] = [\n 'fontFamily',\n 'fontSize',\n 'fontWeight',\n 'italic',\n 'letterSpacing',\n 'lineHeight',\n 'fills',\n 'textDecoration',\n 'textDecorationStyle',\n 'textDecorationThickness',\n 'textDecorationFills',\n 'textDecorationSkipInk',\n 'textUnderlineOffset',\n 'textCase'\n]\n\n/** A list's indent per level, in ems of its first character, as the canvas lays lists out. */\nconst LIST_INDENT_EMS = 1.5\n\nconst DECORATION_PROPERTIES = new Set([\n 'text-decoration-line',\n 'text-decoration-style',\n 'text-decoration-color',\n 'text-decoration-thickness',\n 'text-underline-offset',\n 'text-decoration-skip-ink'\n])\n\nconst px = (value: number) => `${value}px`\n\n/** Characters `[start, end)`, the run style over them, and where they link to. */\ninterface StyledRange {\n start: number\n end: number\n style: CharacterStyle\n href: string | null\n}\n\n/** Links a page can follow: to the web, to mail, or to a phone; others are left out. */\nconst LINK_PROTOCOLS = new Set(['http:', 'https:', 'mailto:', 'tel:'])\n\n/** A link as an `href`, for a link to a URL a page can follow. */\nfunction linkHref(link: HyperlinkTarget | null | undefined): string | null {\n if (link?.type !== 'URL') return null\n try {\n return LINK_PROTOCOLS.has(new URL(link.value).protocol) ? link.value : null\n } catch {\n // Not an absolute URL, which a page could not follow from anywhere it is placed.\n return null\n }\n}\n\nexport function textCaseToCSS(value: SceneNode['textCase']): string | undefined {\n if (value === 'UPPER') return 'uppercase'\n if (value === 'LOWER') return 'lowercase'\n if (value === 'TITLE') return 'capitalize'\n return undefined\n}\n\n/**\n * The letter spacing every character of a text has, from its run or the layer, or `undefined`\n * when characters differ or there are none: then no one spacing ends every line. Characters\n * spaced and sized as the layer is give the layer's own spacing; otherwise each spacing is\n * resolved at its characters' font size, as CSS resolves `em` where a run sets its own size.\n */\nexport function uniformLetterSpacing(node: SceneNode): TextLength | undefined {\n const spacings = styledRanges(node).map(({ style }) => ({\n length: style.letterSpacing,\n fontSize: style.fontSize\n }))\n if (spacings.length === 0) return undefined\n const asLayer = spacings.every(\n ({ length, fontSize }) =>\n isEqual(length, node.letterSpacing) &&\n (length.unit === 'PIXELS' || fontSize === node.fontSize)\n )\n if (asLayer) return node.letterSpacing\n const pixels = uniq(spacings.map(({ length, fontSize }) => textLengthPixels(length, fontSize)))\n return pixels.length === 1 ? pixelLength(pixels[0]) : undefined\n}\n\nfunction characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {\n const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]))\n for (const key of CHARACTER_STYLE_KEYS) {\n const value = override[key]\n if (value !== undefined) style[key] = value\n }\n return style as CharacterStyle\n}\n\n/** The text in ranges of one style each: the runs, and the layer's own style between them. */\nfunction styledRanges(node: SceneNode): StyledRange[] {\n const ranges: StyledRange[] = []\n const base = characterStyle(node)\n let at = 0\n for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {\n const start = Math.max(at, run.start)\n const end = Math.min(node.text.length, run.start + run.length)\n if (start > at) ranges.push({ start: at, end: start, style: base, href: null })\n if (end > start) {\n const href = linkHref(run.style.hyperlink)\n ranges.push({ start, end, style: characterStyle(node, run.style), href })\n }\n at = Math.max(at, end)\n }\n if (at < node.text.length) {\n ranges.push({ start: at, end: node.text.length, style: base, href: null })\n }\n return ranges\n}\n\n/** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */\nfunction decorationCSS(style: CharacterStyle, profile: ColorProfile): DesignStyleDeclaration {\n if (style.textDecoration === 'NONE') return {}\n const underline = style.textDecoration === 'UNDERLINE'\n const css: DesignStyleDeclaration = {\n 'text-decoration-line': underline ? 'underline' : 'line-through'\n }\n if (style.textDecorationStyle !== 'SOLID') {\n css['text-decoration-style'] = style.textDecorationStyle.toLowerCase()\n }\n const color = fillToCSS(\n style.textDecorationFills.find((fill) => fill.visible),\n profile\n )\n if (color) css['text-decoration-color'] = color\n if (style.textDecorationThickness !== null) {\n css['text-decoration-thickness'] = px(style.textDecorationThickness)\n }\n if (underline && style.textUnderlineOffset !== null) {\n css['text-underline-offset'] = px(style.textUnderlineOffset)\n }\n if (underline && !style.textDecorationSkipInk) css['text-decoration-skip-ink'] = 'none'\n return css\n}\n\nfunction characterCSS(\n style: CharacterStyle,\n decorated: boolean,\n profile: ColorProfile\n): DesignStyleDeclaration {\n return {\n color: fillToCSS(style.fills.at(0), profile) ?? '',\n 'font-family': style.fontFamily,\n 'font-size': px(style.fontSize),\n 'font-weight': String(style.fontWeight),\n 'font-style': style.italic ? 'italic' : 'normal',\n 'letter-spacing': letterSpacingToCSS(style.letterSpacing),\n 'line-height': style.lineHeight === null ? 'normal' : lineHeightToCSS(style.lineHeight),\n 'text-transform': textCaseToCSS(style.textCase) ?? 'none',\n ...(decorated ? decorationCSS(style, profile) : {})\n }\n}\n\n/**\n * What a run's span sets beyond the text's own style. A percent letter spacing is written again\n * where the span changes the font size: CSS inherits spacing already resolved at the text's size,\n * while the canvas spaces each run by its own size.\n */\nfunction spanCSS(\n style: CharacterStyle,\n decorated: boolean,\n base: DesignStyleDeclaration,\n profile: ColorProfile\n): DesignStyleDeclaration {\n const own = characterCSS(style, decorated, profile)\n const css = differing(own, base)\n const { unit, value } = style.letterSpacing\n if (unit === 'PERCENT' && value !== 0 && 'font-size' in css) {\n css['letter-spacing'] = own['letter-spacing']\n }\n return css\n}\n\n/** What `css` sets differently from `base`. */\nfunction differing(\n css: DesignStyleDeclaration,\n base: DesignStyleDeclaration\n): DesignStyleDeclaration {\n return Object.fromEntries(\n Object.entries(css).filter(([property, value]) => value !== '' && base[property] !== value)\n )\n}\n\n/**\n * Whether the text decorates every character alike. CSS draws an element's decoration through\n * its descendants, which cannot take it off, so mixed decorations go on the spans instead.\n */\nfunction uniformDecoration(\n node: SceneNode,\n ranges: readonly StyledRange[],\n profile: ColorProfile\n): boolean {\n const decorations = ranges\n .filter((range) => node.text.slice(range.start, range.end).replaceAll('\\n', '') !== '')\n .map((range) => decorationCSS(range.style, profile))\n return decorations.every((decoration) => isEqual(decoration, decorations[0]))\n}\n\ninterface TextProjection {\n node: SceneNode\n ranges: StyledRange[]\n base: DesignStyleDeclaration\n decorated: boolean\n profile: ColorProfile\n}\n\nfunction textNode(text: string): DesignNode {\n return { type: 'text', text }\n}\n\nfunction element(\n tagName: string,\n inlineStyle: DesignStyleDeclaration,\n children: DesignNode[]\n): DesignElement {\n return { type: 'element', tagName, attrs: {}, inlineStyle, children }\n}\n\n/**\n * A link styled as the text around it: a link draws in the text's colour and with only the\n * decoration its characters have, as in Figma, not in a browser's link style.\n */\nfunction linkElement(href: string, css: DesignStyleDeclaration, text: string): DesignElement {\n const style = { color: 'inherit', 'text-decoration-line': 'none', ...css }\n return { ...element('a', style, [textNode(text)]), attrs: { href } }\n}\n\n/**\n * `text[start, end)` as text and spans, each span setting only what differs from the layer;\n * linked characters are a link instead.\n */\nfunction inlineContent(projection: TextProjection, start: number, end: number): DesignNode[] {\n const { node, ranges, base, decorated, profile } = projection\n const pieces: { css: DesignStyleDeclaration; text: string; href: string | null }[] = []\n for (const range of ranges) {\n const from = Math.max(start, range.start)\n const to = Math.min(end, range.end)\n if (to <= from) continue\n const css = spanCSS(range.style, !decorated, base, profile)\n const text = node.text.slice(from, to)\n const previous = pieces.at(-1)\n if (previous && previous.href === range.href && isEqual(previous.css, css)) {\n previous.text += text\n } else pieces.push({ css, text, href: range.href })\n }\n return pieces.map(({ css, text, href }) => {\n if (href) return linkElement(href, css, text)\n return Object.keys(css).length === 0 ? textNode(text) : element('span', css, [textNode(text)])\n })\n}\n\n/** A paragraph's content; an empty one holds a line break, which gives it a line's height. */\nfunction paragraphContent(projection: TextProjection, range: TextParagraphRange): DesignNode[] {\n if (range.end === range.start) return [element('br', {}, [])]\n return inlineContent(projection, range.start, range.end)\n}\n\n/** Text that CSS lays out in one element: no lists, and no spacing or indent between lines. */\nfunction needsBlocks(node: SceneNode): boolean {\n if (hasTextList(node)) return true\n const paragraphs = textParagraphRanges(node.text)\n return paragraphs.some(\n (_, index) =>\n paragraphSpacingAt(node, index, 'paragraphIndent') > 0 ||\n (index < paragraphs.length - 1 && paragraphSpacingAt(node, index, 'paragraphSpacing') > 0)\n )\n}\n\n/** The space after paragraph `index`: list spacing between two items, paragraph spacing else. */\nfunction spaceAfter(node: SceneNode, index: number, count: number): number {\n if (index >= count - 1) return 0\n const betweenItems =\n paragraphStyleAt(node.textParagraphs, index).listType !== 'NONE' &&\n paragraphStyleAt(node.textParagraphs, index + 1).listType !== 'NONE'\n return paragraphSpacingAt(node, index, betweenItems ? 'listSpacing' : 'paragraphSpacing')\n}\n\nfunction listStyleType(item: TextListItem): string {\n if (item.listType === 'UNORDERED') return 'disc'\n const format = listNumberFormat(item.level)\n if (format === 'LOWER_ALPHA') return 'lower-alpha'\n if (format === 'LOWER_ROMAN') return 'lower-roman'\n return 'decimal'\n}\n\n/** A list in the text, open at one level, with the item that nested lists go into. */\ninterface OpenList {\n level: number\n listType: TextListItem['listType']\n element: DesignElement\n item: DesignElement | undefined\n}\n\n/** Where the next list item goes: closes lists deeper than it, or of another kind at its level. */\nfunction closeListsFor(open: OpenList[], item: TextListItem): void {\n while ((open.at(-1)?.level ?? 0) > item.level) open.pop()\n const top = open.at(-1)\n if (top?.level === item.level && (top.listType !== item.listType || item.startsList)) open.pop()\n}\n\n/**\n * Opens a list one level below the innermost open one, inside its last item; a level an item\n * skips gets an item without a marker to hold it.\n */\nfunction openList(\n open: OpenList[],\n blocks: DesignNode[],\n item: TextListItem,\n indent: number\n): void {\n const parent = open.at(-1)\n const level = (parent?.level ?? 0) + 1\n const list = element(\n item.listType === 'ORDERED' ? 'ol' : 'ul',\n {\n ...blockMargins(0, 0),\n 'padding-inline-start': px(indent),\n 'list-style-type': level === item.level ? listStyleType(item) : 'none'\n },\n []\n )\n if (parent) {\n parent.item ??= appendTo(parent.element, element('li', { 'list-style-type': 'none' }, []))\n // The space after the item the list nests in stands above the list.\n const spacing = parent.item.inlineStyle?.['margin-bottom']\n if (spacing && parent.item.inlineStyle && list.inlineStyle) {\n delete parent.item.inlineStyle['margin-bottom']\n list.inlineStyle['margin-top'] = spacing\n }\n parent.item.children.push(list)\n } else blocks.push(list)\n open.push({ level, listType: item.listType, element: list, item: undefined })\n}\n\nfunction plainParagraph(\n projection: TextProjection,\n index: number,\n range: TextParagraphRange,\n after: number\n): DesignElement {\n const style = blockMargins(0, after)\n const indent = paragraphSpacingAt(projection.node, index, 'paragraphIndent')\n if (indent > 0) style['text-indent'] = px(indent)\n return element('p', style, paragraphContent(projection, range))\n}\n\n/**\n * The text as blocks, as Figma lays it out: a paragraph per plain one, lists nested by level\n * with Figma's markers (bullets at every level, numbers counting 1, a, i as they nest), and the\n * space after each paragraph as a margin on what ends it.\n */\nfunction blockContent(projection: TextProjection): DesignNode[] {\n const { node } = projection\n const paragraphs = textParagraphRanges(node.text)\n const items = new Map(\n textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item])\n )\n const blocks: DesignNode[] = []\n const open: OpenList[] = []\n for (const [index, range] of paragraphs.entries()) {\n const after = spaceAfter(node, index, paragraphs.length)\n const item = items.get(index)\n if (!item) {\n open.length = 0\n blocks.push(plainParagraph(projection, index, range, after))\n continue\n }\n const unit = groupEm(projection, paragraphs, item) * LIST_INDENT_EMS\n closeListsFor(open, item)\n while ((open.at(-1)?.level ?? 0) < item.level) {\n // A hanging list's markers stand outside the text, so its first level has no indent.\n const first = open.length === 0\n openList(open, blocks, item, first && node.hangingList ? 0 : unit)\n }\n const list = open.at(-1)\n if (!list) continue\n const style: DesignStyleDeclaration = after > 0 ? { 'margin-bottom': px(after) } : {}\n list.item = appendTo(list.element, element('li', style, paragraphContent(projection, range)))\n }\n return blocks\n}\n\n/** Margins above and below a block, written out: paragraphs and lists have their own in CSS. */\nfunction blockMargins(top: number, bottom: number): DesignStyleDeclaration {\n return { 'margin-top': px(top), 'margin-bottom': px(bottom) }\n}\n\nfunction appendTo(parent: DesignElement, child: DesignElement): DesignElement {\n parent.children.push(child)\n return child\n}\n\n/** The size of a list's first character, which its indents are measured in. */\nfunction groupEm(\n projection: TextProjection,\n paragraphs: readonly TextParagraphRange[],\n item: TextListItem\n): number {\n const at = paragraphs[item.groupStart]?.start ?? item.start\n const range = projection.ranges.find((candidate) => at >= candidate.start && at < candidate.end)\n return range?.style.fontSize ?? projection.node.fontSize\n}\n\n/**\n * A text layer's element: its tag, its style with the decoration the whole text shares, and\n * its content. Runs of characters styled apart become spans; text with lists, paragraph\n * spacing, or a first-line indent becomes blocks, which a `<div>` holds.\n */\nexport function textElementContent(\n node: SceneNode,\n layerStyle: DesignStyleDeclaration,\n profile: ColorProfile = 'srgb'\n): { tagName: string; style: DesignStyleDeclaration; children: DesignNode[] } {\n const ranges = styledRanges(node)\n const decorated = uniformDecoration(node, ranges, profile)\n const style = Object.fromEntries(\n Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property))\n )\n if (decorated) Object.assign(style, decorationCSS(characterStyle(node), profile))\n const projection: TextProjection = {\n node,\n ranges,\n base: characterCSS(characterStyle(node), decorated, profile),\n decorated,\n profile\n }\n if (!needsBlocks(node)) {\n return { tagName: 'span', style, children: inlineContent(projection, 0, node.text.length) }\n }\n return { tagName: 'div', style, children: blockContent(projection) }\n}\n","import { isEqual } from 'es-toolkit/predicate'\nimport { fromUint8Array } from 'js-base64'\n\nimport type { ColorProfile, SceneGraph, SceneNode, Stroke } from '@pairdraw/scene-graph'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport { readIcon } from '@pairdraw/scene-graph/icons'\nimport { imageMimeType } from '@pairdraw/scene-graph/images'\nimport { layoutSizingInParent } from '@pairdraw/scene-graph/layout'\nimport { isShaderPresetPaint, shaderOfPaint } from '@pairdraw/scene-graph/shaders'\nimport { resolveNodeTextDirection } from '@pairdraw/scene-graph/text/direction'\n\nimport { DesignTokens, type CSSModes } from '../tokens/references'\nimport type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'\nimport {\n cssColor,\n effectsToCSS,\n fillToCSS,\n gradientFillsToCSS,\n letterSpacingRoomCSS,\n letterSpacingToCSS,\n lineHeightToCSS,\n strokeColorToCSS,\n textEffectsToCSS\n} from './css'\nimport { addGridContainer, addGridPlacement } from './grid'\nimport { addPositioning, constraintSizes, placement } from './position'\nimport { textCaseToCSS, textElementContent, uniformLetterSpacing } from './text'\n\nconst DOM_CSS_PLUGIN_ID = 'pairdraw-dom-css'\nconst IMAGE_SOURCE_URL_KEY = 'image-source-url'\n\n/**\n * Draws a vector-shaped layer as an inline `<svg>` element sized to the layer, from the\n * engine's own SVG export. dom-css cannot depend on that engine, so it comes in as an option.\n */\nexport type VectorElementRenderer = (graph: SceneGraph, node: SceneNode) => DesignElement | null\n\nexport interface SceneGraphToDesignOptions {\n rootId?: string\n /** Write each layer's ID as `data-pairdraw-node-id`. Default true. */\n includeSourceIds?: boolean\n /** Write each layer's own name as `data-name`, as the Tailwind JSX export does. Default false. */\n includeLayerNames?: boolean\n /** Write variable-bound values as `var(--name)` where CSS resolves them as drawn. Default true. */\n tokens?: boolean\n /** Vector, boolean, star, polygon, and icon layers as inline SVG; without it they project as boxes. */\n vectorElement?: VectorElementRenderer\n /** Hidden layers to project as shown, such as the tab panels a component reveals itself. */\n shown?: ReadonlySet<string>\n}\n\n/** Layers whose shape only paths describe, which CSS boxes cannot draw. */\nconst VECTOR_SHAPES = new Set<SceneNode['type']>(['VECTOR', 'BOOLEAN_OPERATION', 'STAR', 'POLYGON'])\n\n/** What a vector's own SVG draws, so the placement wrapper leaves it out; a backdrop stays on the wrapper. */\nconst VECTOR_WRAPPER_PAINT = /^(background|border|box-shadow|outline|filter)/\n\n/** Every CSS property that paints a layer, wherever its paint is written. */\nexport const PAINT_PROPERTY =\n /^(background|backdrop-filter|border|box-shadow|outline|filter|color|fill|stroke|text-shadow)/\n\n/** Whether a projected style paints; a radius or a placement property on its own does not. */\nexport function paintsSomething(style: DesignStyleDeclaration): boolean {\n return Object.keys(style).some(\n (property) => PAINT_PROPERTY.test(property) && !property.endsWith('radius')\n )\n}\n\n/**\n * Whether a projected layer paints or writes text. A frame with no paint and no children projects\n * to a bare element with only its size, so a selection of such layers draws nothing.\n */\nexport function designNodeDraws(node: DesignNode): boolean {\n if (node.type === 'text') return node.text.trim().length > 0\n if (node.shader?.frame) return true\n if (node.tagName === 'svg' || node.tagName === 'img' || node.tagName === 'canvas') return true\n return (\n paintsSomething({ ...node.computedStyle, ...node.inlineStyle }) ||\n node.children.some(designNodeDraws)\n )\n}\n\n/** A field's CSS: its token reference where one is faithful, otherwise the literal value. */\ntype FieldCSS = (field: string, literal: string) => string\n\nconst px = (value: number) => `${value}px`\n\nfunction nodeChildren(graph: SceneGraph, node: SceneNode): SceneNode[] {\n return node.childIds\n .map((id) => graph.getNode(id))\n .filter((child): child is SceneNode => child !== undefined)\n}\n\nfunction justifyContentToCSS(value: SceneNode['primaryAxisAlign']): string | undefined {\n if (value === 'CENTER') return 'center'\n if (value === 'MAX') return 'flex-end'\n if (value === 'SPACE_BETWEEN') return 'space-between'\n if (value === 'SPACE_AROUND') return 'space-around'\n return undefined\n}\n\n/**\n * Cross-axis alignment of a container's children, or of one child. Auto layout starts children\n * at the start while flexbox stretches them, so start is written out: a child that hugs its\n * content keeps its own size.\n */\nfunction alignToCSS(\n value: SceneNode['counterAxisAlign'] | SceneNode['layoutAlignSelf']\n): string | undefined {\n if (value === 'MIN') return 'flex-start'\n if (value === 'CENTER') return 'center'\n if (value === 'MAX') return 'flex-end'\n if (value === 'STRETCH') return 'stretch'\n if (value === 'BASELINE') return 'baseline'\n return undefined\n}\n\n/** Whether a layer sizes itself to its content along an axis, so CSS should too. */\nfunction hugs(node: SceneNode, axis: 'width' | 'height'): boolean {\n if (node.type === 'TEXT')\n return (\n node.textAutoResize === 'WIDTH_AND_HEIGHT' ||\n (axis === 'height' && node.textAutoResize === 'HEIGHT')\n )\n if (node.layoutMode !== 'HORIZONTAL' && node.layoutMode !== 'VERTICAL') return false\n const primary = (node.layoutMode === 'HORIZONTAL') === (axis === 'width')\n return (primary ? node.primaryAxisSizing : node.counterAxisSizing) === 'HUG'\n}\n\n/**\n * A layer's size: fixed on the axes the design fixes, and left to the content where the layer\n * hugs it (an auto layout frame set to Hug, or auto-sizing text), so the page grows with it.\n */\nfunction addSize(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS\n): void {\n const placed = placement(node, parent)\n const sized = (axis: 'width' | 'height') =>\n node[axis] > 0 &&\n !hugs(node, axis) &&\n !stretches(node, parent, axis) &&\n !(placed && constraintSizes(node, placed.parent, axis))\n if (sized('width')) style.width = css('width', px(node.width))\n if (sized('height')) style.height = css('height', px(node.height))\n}\n\n/**\n * Whether a layer fills an axis by stretching, which a fixed CSS size would prevent: across a\n * flex parent, or either axis of a grid cell. Along a flex parent, fill is `flex-grow`, and the\n * size stays as its basis.\n */\nfunction stretches(\n node: SceneNode,\n parent: SceneNode | undefined,\n axis: 'width' | 'height'\n): boolean {\n const sizing = layoutSizingInParent(parent, node, axis === 'width' ? 'HORIZONTAL' : 'VERTICAL')\n if (sizing !== 'FILL' || !parent) return false\n if (parent.layoutMode === 'GRID') return true\n const mainAxis = parent.layoutMode === 'HORIZONTAL' ? 'width' : 'height'\n return axis !== mainAxis\n}\n\nfunction addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.minWidth !== null) style['min-width'] = css('minWidth', px(node.minWidth))\n if (node.maxWidth !== null) style['max-width'] = css('maxWidth', px(node.maxWidth))\n if (node.minHeight !== null) style['min-height'] = css('minHeight', px(node.minHeight))\n if (node.maxHeight !== null) style['max-height'] = css('maxHeight', px(node.maxHeight))\n}\n\nfunction addCornerRadii(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.type === 'ELLIPSE') {\n style['border-radius'] = '50%'\n return\n }\n if (node.independentCorners) {\n const corners = [\n ['border-top-left-radius', 'topLeftRadius', node.topLeftRadius],\n ['border-top-right-radius', 'topRightRadius', node.topRightRadius],\n ['border-bottom-right-radius', 'bottomRightRadius', node.bottomRightRadius],\n ['border-bottom-left-radius', 'bottomLeftRadius', node.bottomLeftRadius]\n ] as const\n for (const [property, field, radius] of corners)\n if (radius > 0) style[property] = css(field, px(radius))\n return\n }\n\n if (node.cornerRadius > 0) style['border-radius'] = css('cornerRadius', px(node.cornerRadius))\n}\n\nfunction addStroke(\n style: DesignStyleDeclaration,\n node: SceneNode,\n css: FieldCSS,\n profile: ColorProfile\n): void {\n const stroke = node.strokes.find((item) => item.visible)\n const literalColor = strokeColorToCSS(stroke, profile)\n if (!literalColor || !stroke) return\n const color = css('strokes/0/color', literalColor)\n const borderStyle = node.dashPattern.length > 0 ? 'dashed' : 'solid'\n if (!node.independentStrokeWeights) {\n style.border = `${css('strokeWeight', px(stroke.weight))} solid ${color}`\n if (borderStyle !== 'solid') style['border-style'] = borderStyle\n return\n }\n\n style['border-style'] = borderStyle\n style['border-color'] = color\n style['border-top-width'] = css('borderTopWeight', px(node.borderTopWeight))\n style['border-right-width'] = css('borderRightWeight', px(node.borderRightWeight))\n style['border-bottom-width'] = css('borderBottomWeight', px(node.borderBottomWeight))\n style['border-left-width'] = css('borderLeftWeight', px(node.borderLeftWeight))\n}\n\n/**\n * CSS gives an element one border, so the visible strokes after the first become rings in\n * `box-shadow`, in layer order. An outside ring grows from the border's outer edge, an inside one\n * from its inner edge, and a centred stroke gets a ring on each side of the border. Rings cannot\n * dash or take per-side weights, and outer and inner rings paint in separate CSS layers, so a\n * stroke order that alternates them is approximated.\n */\nfunction extraStrokeShadows(strokes: Stroke[], first: Stroke, profile: ColorProfile): string[] {\n const outer: string[] = []\n const inner: string[] = []\n let outside = 0\n let inside = first.weight\n for (const stroke of strokes) {\n if (!stroke.visible) continue\n const color = strokeColorToCSS(stroke, profile)\n if (!color) continue\n if (stroke.align !== 'OUTSIDE') {\n inside += stroke.align === 'CENTER' ? stroke.weight / 2 : stroke.weight\n inner.push(`inset 0 0 0 ${px(inside)} ${color}`)\n }\n if (stroke.align !== 'INSIDE') {\n outside += stroke.align === 'CENTER' ? stroke.weight / 2 : stroke.weight\n outer.push(`0 0 0 ${px(outside)} ${color}`)\n }\n }\n // The first ring listed paints on top, so each group stays nearest first.\n return [...outer, ...inner]\n}\n\nconst PADDING_FIELDS = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'] as const\n\n/** Sides compare by their CSS, so a token and a literal of the same size stay separate. */\nfunction addPadding(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n const [top, right, bottom, left] = PADDING_FIELDS.map((field) => css(field, px(node[field])))\n const zero = px(0)\n if ([top, right, bottom, left].every((value) => value === zero)) return\n\n if (top === right && right === bottom && bottom === left) {\n style.padding = top\n return\n }\n\n if (top === bottom && right === left) {\n if (top !== zero) style['padding-block'] = top\n if (right !== zero) style['padding-inline'] = right\n return\n }\n\n if (top !== zero) style['padding-top'] = top\n if (right !== zero) style['padding-right'] = right\n if (bottom !== zero) style['padding-bottom'] = bottom\n if (left !== zero) style['padding-left'] = left\n}\n\nfunction addFlexGap(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {\n if (node.itemSpacing <= 0 && node.counterAxisSpacing <= 0) return\n const item = css('itemSpacing', px(node.itemSpacing))\n if (node.counterAxisSpacing <= 0) {\n style.gap = item\n return\n }\n\n const counter = css('counterAxisSpacing', px(node.counterAxisSpacing))\n if (node.layoutMode === 'HORIZONTAL') {\n if (node.itemSpacing > 0) style['column-gap'] = item\n style['row-gap'] = counter\n return\n }\n\n if (node.itemSpacing > 0) style['row-gap'] = item\n style['column-gap'] = counter\n}\n\n/** Image bytes as a data URL of the type they are encoded in. */\nfunction imageDataURL(bytes: Uint8Array): string {\n return `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`\n}\n\n/**\n * The shader a layer's fill draws, which the projection keeps as the shader rather than the\n * image of its still frame: the shader of its first fill, as the projection reads one fill.\n */\nfunction layerShader(graph: SceneGraph, node: SceneNode): DesignElement['shader'] {\n const fill = node.fills.at(0)\n const shader = fill?.visible ? shaderOfPaint(node, fill) : null\n if (!shader || !isShaderPresetPaint(shader)) return undefined\n const bytes = graph.images.get(shader.image)\n const frame = bytes ? imageDataURL(bytes) : undefined\n return { preset: shader.preset, frame }\n}\n\nconst POSITIONED = new Set(['relative', 'absolute', 'fixed', 'sticky'])\n\n/** Whether a `position` value makes an element the containing block of what it places. */\nexport function isPositioned(position: unknown): boolean {\n return typeof position === 'string' && POSITIONED.has(position)\n}\n\n/** A shader layer contains what plays behind its content, beneath everything it holds. */\nfunction addShaderLayerStyle(style: DesignStyleDeclaration): void {\n if (!isPositioned(style.position)) style.position = 'relative'\n style.isolation = 'isolate'\n}\n\nfunction addImageStyle(style: DesignStyleDeclaration, node: SceneNode): void {\n const fill = node.fills.at(0)\n if (fill?.type !== 'IMAGE' || !fill.visible || shaderOfPaint(node, fill)) return\n if (node.width > 0 && node.height > 0) style['aspect-ratio'] = `${node.width} / ${node.height}`\n if (fill.imageScaleMode === 'FIT') style['object-fit'] = 'contain'\n if (fill.imageScaleMode === 'FILL') style['object-fit'] = 'cover'\n}\n\n/** Styles a node takes from its parent's layout, and its own rotation. */\nfunction addLayoutChild(\n style: DesignStyleDeclaration,\n node: SceneNode,\n parent: SceneNode | undefined\n): void {\n if (parent?.layoutMode === 'GRID') addGridPlacement(style, node)\n else if (parent && parent.layoutMode !== 'NONE' && node.layoutGrow > 0) style['flex-grow'] = '1'\n if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`\n}\n\nconst SIZE_PROPERTIES = ['width', 'height', 'min-width', 'max-width', 'min-height', 'max-height']\n\n/**\n * A layer's size includes its padding and stroke, as auto layout measures it. CSS sizes the\n * content box unless told otherwise, so a sized box with padding or a border says so.\n */\nfunction addBoxSizing(style: DesignStyleDeclaration): void {\n const sized = SIZE_PROPERTIES.some((property) => Object.hasOwn(style, property))\n const boxed = Object.keys(style).some(\n (property) =>\n property.startsWith('padding') ||\n (property.startsWith('border') && !property.endsWith('radius'))\n )\n if (sized && boxed) style['box-sizing'] = 'border-box'\n}\n\n/**\n * The CSS keyword for a blend mode, where one paints the same mode. Linear burn would need\n * `plus-darker`, which Chrome, Edge, and Firefox do not implement, so it gains no keyword and\n * exports flat. A normal layer or an unscoped pass-through needs none either.\n */\nconst CSS_BLEND_MODES: Partial<Record<SceneNode['blendMode'], string>> = {\n DARKEN: 'darken',\n MULTIPLY: 'multiply',\n COLOR_BURN: 'color-burn',\n LIGHTEN: 'lighten',\n SCREEN: 'screen',\n LINEAR_DODGE: 'plus-lighter',\n COLOR_DODGE: 'color-dodge',\n OVERLAY: 'overlay',\n SOFT_LIGHT: 'soft-light',\n HARD_LIGHT: 'hard-light',\n DIFFERENCE: 'difference',\n EXCLUSION: 'exclusion',\n HUE: 'hue',\n SATURATION: 'saturation',\n COLOR: 'color',\n LUMINOSITY: 'luminosity'\n}\n\nfunction styleFromSceneNode(\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS,\n profile: ColorProfile\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n addSize(style, node, parent, css)\n addPositioning(style, node, parent)\n addSizeConstraints(style, node, css)\n const fill = fillToCSS(node.fills.at(0), profile)\n if (fill) style['background-color'] = css('fills/0/color', fill)\n const gradients = gradientFillsToCSS(node.fills, node.width, node.height, profile)\n if (gradients) style['background-image'] = gradients\n addImageStyle(style, node)\n addStroke(style, node, css, profile)\n Object.assign(style, effectsToCSS(node.effects, profile))\n const visibleStrokes = node.strokes.filter((stroke) => stroke.visible)\n if (visibleStrokes.length > 1) {\n const rings = extraStrokeShadows(visibleStrokes.slice(1), visibleStrokes[0], profile)\n if (rings.length > 0) {\n style['box-shadow'] = [rings.join(', '), style['box-shadow']]\n .filter((shadow): shadow is string => Boolean(shadow))\n .join(', ')\n }\n }\n if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))\n const blend = CSS_BLEND_MODES[node.blendMode]\n if (blend) style['mix-blend-mode'] = blend\n addCornerRadii(style, node, css)\n if (node.clipsContent) style.overflow = 'hidden'\n const alignSelf = alignToCSS(node.layoutAlignSelf)\n if (alignSelf) style['align-self'] = alignSelf\n\n addLayoutChild(style, node, parent)\n if (node.layoutDirection === 'RTL') style.direction = 'rtl'\n\n if (node.layoutMode === 'GRID') {\n addGridContainer(style, node, css)\n addPadding(style, node, css)\n } else if (node.layoutMode !== 'NONE') {\n style.display = 'flex'\n // Row is the flexbox default.\n if (node.layoutMode === 'VERTICAL') style['flex-direction'] = 'column'\n const justifyContent = justifyContentToCSS(node.primaryAxisAlign)\n const alignItems = alignToCSS(node.counterAxisAlign)\n if (justifyContent) style['justify-content'] = justifyContent\n if (alignItems) style['align-items'] = alignItems\n if (node.layoutWrap === 'WRAP') style['flex-wrap'] = 'wrap'\n addFlexGap(style, node, css)\n addPadding(style, node, css)\n }\n\n addBoxSizing(style)\n return style\n}\n\nfunction styleFromTextNode(\n node: SceneNode,\n parent: SceneNode | undefined,\n css: FieldCSS,\n profile: ColorProfile\n): DesignStyleDeclaration {\n const style: DesignStyleDeclaration = {}\n addSize(style, node, parent, css)\n addPositioning(style, node, parent)\n addLayoutChild(style, node, parent)\n if (resolveNodeTextDirection(node) === 'RTL') style.direction = 'rtl'\n const color = fillToCSS(node.fills.at(0), profile)\n style.color = color ? css('fills/0/color', color) : cssColor(BLACK, profile)\n style['font-family'] = node.fontFamily\n style['font-size'] = css('fontSize', px(node.fontSize))\n style['font-weight'] = String(node.fontWeight)\n if (node.italic) style['font-style'] = 'italic'\n if (node.lineHeight !== null) {\n style['line-height'] = css('lineHeight', lineHeightToCSS(node.lineHeight))\n }\n const spacing = css('letterSpacing', letterSpacingToCSS(node.letterSpacing))\n if (node.letterSpacing.value !== 0) style['letter-spacing'] = spacing\n // The spacing after a line's last letter needs room only when one spacing ends every line.\n const ending = uniformLetterSpacing(node)\n if (ending && ending.value !== 0) {\n const written = isEqual(ending, node.letterSpacing) ? spacing : letterSpacingToCSS(ending)\n Object.assign(style, letterSpacingRoomCSS(ending, written, style.width))\n }\n if (node.textAlignHorizontal !== 'LEFT')\n style['text-align'] = node.textAlignHorizontal.toLowerCase()\n if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))\n Object.assign(style, textEffectsToCSS(node.effects, profile))\n if (node.textDecoration !== 'NONE') {\n style['text-decoration-line'] =\n node.textDecoration === 'UNDERLINE' ? 'underline' : 'line-through'\n }\n const textTransform = textCaseToCSS(node.textCase)\n if (textTransform) style['text-transform'] = textTransform\n style['white-space'] = node.maxLines === 1 ? 'nowrap' : 'pre-wrap'\n return style\n}\n\nfunction imageSourceURL(node: SceneNode): string | undefined {\n return node.pluginData.find(\n (entry) => entry.pluginId === DOM_CSS_PLUGIN_ID && entry.key === IMAGE_SOURCE_URL_KEY\n )?.value\n}\n\n/** A layer's name, unless it only repeats the layer's type. */\nexport function ownLayerName(node: SceneNode): string | undefined {\n return node.name && node.name !== node.type ? node.name : undefined\n}\n\nfunction attrsForNode(\n graph: SceneGraph,\n node: SceneNode,\n {\n includeSourceIds,\n includeLayerNames\n }: Pick<ProjectionContext, 'includeSourceIds' | 'includeLayerNames'>\n): Record<string, string> {\n const attrs: Record<string, string> = {}\n const name = includeLayerNames ? ownLayerName(node) : undefined\n if (name) attrs['data-name'] = name\n if (includeSourceIds) attrs['data-pairdraw-node-id'] = node.id\n const sourceURL = imageSourceURL(node)\n if (sourceURL) attrs.src = sourceURL\n const fill = node.fills.at(0)\n if (fill?.type !== 'IMAGE' || !fill.imageHash || shaderOfPaint(node, fill)) return attrs\n const bytes = graph.images.get(fill.imageHash)\n if (!bytes) return attrs\n return { ...attrs, src: imageDataURL(bytes) }\n}\n\nfunction tagNameForNode(node: SceneNode): string {\n if (node.type === 'SECTION') return 'section'\n const fill = node.fills.at(0)\n const image = fill?.type === 'IMAGE' && !shaderOfPaint(node, fill)\n if ((image || imageSourceURL(node)) && node.childIds.length === 0) return 'img'\n return 'div'\n}\n\ninterface ProjectionContext {\n graph: SceneGraph\n includeSourceIds: boolean\n includeLayerNames: boolean\n tokens: DesignTokens | undefined\n vectorElement: VectorElementRenderer | undefined\n shown: ReadonlySet<string> | undefined\n}\n\n/**\n * A vector layer as the renderer's `<svg>`, placed where the layer's box would be: its\n * position, size, opacity, and transform stay, and its paint is the SVG's, not the box's.\n */\nfunction vectorDesignNode(\n context: ProjectionContext,\n node: SceneNode,\n attrs: Record<string, string>,\n style: DesignStyleDeclaration\n): DesignElement | null {\n const drawn = context.vectorElement?.(context.graph, node)\n if (!drawn) return null\n const placement = Object.fromEntries(\n Object.entries(style).filter(([property]) => !VECTOR_WRAPPER_PAINT.test(property))\n )\n return {\n ...drawn,\n attrs: { ...drawn.attrs, ...attrs },\n inlineStyle: { ...drawn.inlineStyle, ...placement },\n sourceSceneNodeId: node.id,\n sourceSceneNode: node\n }\n}\n\n/** The outline a vector mask clips siblings to, in the sibling's own box; null where CSS cannot. */\nfunction vectorMaskClip(mask: SceneNode, sibling: SceneNode): string | null {\n // The renderer clips to the rotated outline; a polygon built from the unrotated box would\n // cut a different region, so a rotated mask stays unclipped as the export documents.\n if (mask.maskType !== 'VECTOR' || mask.childIds.length > 0 || mask.rotation !== 0) return null\n const left = mask.x - sibling.x\n const top = mask.y - sibling.y\n if (mask.type === 'RECTANGLE') {\n const right = left + mask.width\n const bottom = top + mask.height\n return `polygon(${px(left)} ${px(top)}, ${px(right)} ${px(top)}, ${px(right)} ${px(bottom)}, ${px(left)} ${px(bottom)})`\n }\n if (mask.type === 'ELLIPSE') {\n const rx = mask.width / 2\n const ry = mask.height / 2\n return `ellipse(${px(rx)} ${px(ry)} at ${px(left + rx)} ${px(top + ry)})`\n }\n return null\n}\n\n/**\n * Projects a parent's children as the canvas draws them: a mask layer is never a layer of its\n * own, and one vector mask clips the siblings after it. Alpha and luminance masks have no\n * faithful CSS form over several elements, and two masks combine, so those stay unclipped.\n */\nfunction projectChildren(\n context: ProjectionContext,\n parent: SceneNode,\n modes: CSSModes,\n root: boolean\n): DesignNode[] {\n const projected: DesignNode[] = []\n let masks: SceneNode[] = []\n let afterMask = false\n for (const child of nodeChildren(context.graph, parent)) {\n if (child.visible && child.isMask) {\n masks = afterMask ? [...masks, child] : [child]\n afterMask = true\n continue\n }\n afterMask = false\n const node = sceneNodeToDesignNode(context, child, modes, root)\n if (!node) continue\n const mask = masks.length === 1 ? masks[0] : null\n if (mask && node.type === 'element') {\n const clip = vectorMaskClip(mask, child)\n if (clip) node.inlineStyle = { ...node.inlineStyle, 'clip-path': clip }\n }\n projected.push(node)\n }\n return projected\n}\n\nfunction sceneNodeToDesignNode(\n context: ProjectionContext,\n node: SceneNode,\n inherited: CSSModes,\n root: boolean\n): DesignNode | null {\n if ((!node.visible && !context.shown?.has(node.id)) || node.internalOnly) return null\n const { graph, tokens } = context\n const parent = node.parentId ? graph.getNode(node.parentId) : undefined\n const entered = tokens?.enter(node, inherited, root)\n const modes = entered?.modes ?? inherited\n const attrs = { ...attrsForNode(graph, node, context), ...entered?.attrs }\n const css: FieldCSS = (field, literal) => tokens?.reference(node, field, modes) ?? literal\n\n if (node.type === 'TEXT') {\n const content = textElementContent(\n node,\n styleFromTextNode(node, parent, css, graph.documentColorSpace),\n graph.documentColorSpace\n )\n return {\n type: 'element',\n tagName: content.tagName,\n attrs,\n inlineStyle: content.style,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children: content.children\n }\n }\n\n // An icon is one drawing, however many paths it has.\n if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {\n const vector = vectorDesignNode(\n context,\n node,\n attrs,\n styleFromSceneNode(node, parent, css, graph.documentColorSpace)\n )\n if (vector) return vector\n }\n\n const children = projectChildren(context, node, modes, false)\n\n if (node.type === 'CANVAS') {\n return {\n type: 'element',\n tagName: 'main',\n attrs,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children\n }\n }\n\n const style = styleFromSceneNode(node, parent, css, graph.documentColorSpace)\n const shader = layerShader(graph, node)\n if (shader) addShaderLayerStyle(style)\n return {\n type: 'element',\n tagName: tagNameForNode(node),\n attrs,\n inlineStyle: style,\n sourceSceneNodeId: node.id,\n sourceSceneNode: node,\n children,\n shader\n }\n}\n\nfunction projectionContext(\n graph: SceneGraph,\n {\n includeSourceIds = true,\n includeLayerNames = false,\n tokens = true,\n vectorElement,\n shown\n }: SceneGraphToDesignOptions\n): ProjectionContext {\n return {\n graph,\n includeSourceIds,\n includeLayerNames,\n tokens: tokens ? new DesignTokens(graph) : undefined,\n vectorElement,\n shown\n }\n}\n\nexport function sceneGraphToDesignDocument(\n graph: SceneGraph,\n options: SceneGraphToDesignOptions = {}\n): DesignDocument {\n const root = graph.getNode(options.rootId ?? graph.rootId)\n const context = projectionContext(graph, options)\n const modes = context.tokens?.defaultModes() ?? new Map<string, string>()\n const children = root ? projectChildren(context, root, modes, true) : []\n\n return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }\n}\n\n/** Project one node, including its own box, instead of the children of a root. */\nexport function sceneNodeToDesignDocument(\n graph: SceneGraph,\n nodeId: string,\n options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}\n): DesignDocument {\n return sceneNodesToDesignDocument(graph, [nodeId], options)\n}\n\n/**\n * Project several nodes, including each own box, through one token collector: the document then\n * declares the tokens every root references, not only those of the last one.\n */\nexport function sceneNodesToDesignDocument(\n graph: SceneGraph,\n nodeIds: readonly string[],\n options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}\n): DesignDocument {\n const context = projectionContext(graph, options)\n const modes = context.tokens?.defaultModes() ?? new Map<string, string>()\n const children: DesignNode[] = []\n for (const nodeId of nodeIds) {\n const node = graph.getNode(nodeId)\n const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null\n if (projected) children.push(projected)\n }\n return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }\n}\n","import {\n sceneNodeToDesignDocument,\n type SceneGraphToDesignOptions\n} from '#dom-css/export/projection'\nimport type { DesignElement, DesignNode, DesignText } from '#dom-css/types'\nimport { omit } from 'es-toolkit/object'\n\nimport type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'\nimport {\n behaviourOwner,\n layerPath,\n partBinding,\n readBehaviour\n} from '@pairdraw/scene-graph/behaviours'\nimport { readIcon } from '@pairdraw/scene-graph/icons'\nimport { instanceMainComponent } from '@pairdraw/scene-graph/instances'\nimport { instanceSlotFrames, slotPropertyId } from '@pairdraw/scene-graph/slots'\n\nimport type { StateElement } from './types'\n\n/** A variant's projected layer, keyed so the same layer matches across variants. */\nexport interface VariantLayer {\n type: 'element'\n key: string\n kind: string | undefined\n name: string\n element: DesignElement\n children: Array<VariantLayer | DesignText>\n}\n\n/** Where the set places a variant, which is not the component's own style. */\nexport const PLACEMENT = ['position', 'left', 'top', 'right', 'bottom', 'inset']\n\nfunction textContent(element: DesignElement): string | null {\n const texts = element.children.filter((child): child is DesignText => child.type === 'text')\n return texts.length > 0 ? texts.map((text) => text.text).join('') : null\n}\n\n/**\n * What a layer draws other than its own box: an instance of a component (of any of its set's\n * variants), or an icon. Undefined for any other layer.\n */\nexport function layerKind(graph: SceneGraph, node: SceneNode | undefined): string | undefined {\n if (!node) return undefined\n if (node.type === 'INSTANCE') {\n const main = instanceMainComponent(graph, node)\n const owner = main && behaviourOwner(graph, main)\n return `instance ${owner?.id ?? ''}`\n }\n const icon = readIcon(node)\n return icon ? `icon ${icon.name}` : undefined\n}\n\nfunction variantLayer(\n graph: SceneGraph,\n variant: SceneNode,\n node: DesignNode,\n parentKey: string,\n index: number\n): VariantLayer | DesignText {\n if (node.type === 'text') return node\n const source = node.sourceSceneNodeId\n const path = source ? layerPath(graph, variant.id, source) : `${parentKey}/~${index}`\n const text = textContent(node)\n const kind = layerKind(graph, node.sourceSceneNode)\n // A label that reads differently in a variant is a different layer, shown by its state, and\n // so is a layer drawn as another component or icon, or as one instead of its own box.\n const key = [path, ...(kind ? [kind] : []), ...(text === null ? [] : [text])].join('\\0')\n return {\n type: 'element',\n key,\n kind,\n name: node.sourceSceneNode?.name ?? node.tagName,\n element: node,\n children: node.children.map((child, i) => variantLayer(graph, variant, child, key, i))\n }\n}\n\n/**\n * The tab panels a variant draws hidden behind the first. The generated tabs show each when its\n * tab is chosen, so they are projected as drawn.\n */\nfunction tabPanels(graph: SceneGraph, variant: SceneNode): Set<string> {\n const owner = behaviourOwner(graph, variant)\n const behaviour = owner && readBehaviour(owner)\n const propertyId = behaviour?.kind === 'tabs' ? partBinding(behaviour, 'panels') : undefined\n const panels = propertyId\n ? instanceSlotFrames(graph, variant).find((frame) => slotPropertyId(frame) === propertyId)\n : undefined\n return new Set(panels?.childIds)\n}\n\n/**\n * The layers of a variant a boolean property shows or hides, which are projected however the\n * variant draws them, since the generated component shows them from its prop.\n */\nfunction visibilityBound(graph: SceneGraph, variant: SceneNode): Set<string> {\n const bound = new Set<string>()\n const visit = (node: SceneNode) => {\n for (const child of graph.getChildren(node.id)) {\n if (child.componentPropertyReferences.some((item) => item.field === 'VISIBLE'))\n bound.add(child.id)\n if (child.type !== 'INSTANCE') visit(child)\n }\n }\n visit(variant)\n return bound\n}\n\n/** A variant projected to DOM, without where the set places it. */\nexport function projectVariant(\n graph: SceneGraph,\n variant: SceneNode,\n { vectorElement }: Pick<SceneGraphToDesignOptions, 'vectorElement'> = {}\n): VariantLayer | null {\n const document = sceneNodeToDesignDocument(graph, variant.id, {\n includeSourceIds: false,\n vectorElement,\n shown: new Set([...tabPanels(graph, variant), ...visibilityBound(graph, variant)])\n })\n const root = document.children.at(0)\n if (root?.type !== 'element') return null\n const style = root.inlineStyle ?? {}\n // Absolutely placed layers inside still need the root as their containing block.\n root.inlineStyle = {\n ...omit(style, PLACEMENT),\n ...(style.position ? { position: 'relative' } : {})\n }\n return {\n type: 'element',\n key: '',\n kind: undefined,\n name: variant.name,\n element: root,\n children: root.children.map((child, i) => variantLayer(graph, variant, child, '', i))\n }\n}\n\n/** Every layer of a projected variant by key. */\nexport function layersByKey(\n root: VariantLayer,\n into = new Map<string, VariantLayer>()\n): Map<string, VariantLayer> {\n into.set(root.key, root)\n for (const child of root.children) if (child.type === 'element') layersByKey(child, into)\n return into\n}\n\n/** A merged layer starting from a variant's layer, with that layer's style as its base. */\nexport function stateElement(layer: VariantLayer): StateElement {\n return {\n type: 'element',\n key: layer.key,\n kind: layer.kind,\n name: layer.name,\n tagName: layer.element.tagName,\n attrs: { ...layer.element.attrs },\n base: { ...layer.element.inlineStyle },\n rules: [],\n shader: layer.element.shader,\n children: layer.children.map((child) => (child.type === 'text' ? child : stateElement(child)))\n }\n}\n\nfunction hideAtRest(element: StateElement, hidden: Set<StateElement>): void {\n element.base = { ...element.base, display: 'none' }\n hidden.add(element)\n for (const child of element.children) if (child.type === 'element') hideAtRest(child, hidden)\n}\n\n/**\n * Adds the layers only `variant` draws to the merged tree, after the sibling they follow\n * there. Each keeps the style this variant draws it with, hidden at rest, and is recorded in\n * `hidden` so the variants that draw it show it again.\n */\nexport function mergeVariant(\n into: StateElement,\n variant: VariantLayer,\n hidden: Set<StateElement>\n): void {\n let previous = -1\n for (const child of variant.children) {\n if (child.type === 'text') continue\n const index = into.children.findIndex(\n (item) => item.type === 'element' && item.key === child.key\n )\n const existing = into.children.at(index)\n if (index !== -1 && existing?.type === 'element') {\n mergeVariant(existing, child, hidden)\n previous = index\n continue\n }\n const added = stateElement(child)\n hideAtRest(added, hidden)\n previous += 1\n into.children.splice(previous, 0, added)\n }\n}\n\n/** Every element of the merged tree, root first. */\nexport function allElements(root: StateElement, into: StateElement[] = []): StateElement[] {\n into.push(root)\n for (const child of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