@pairdraw/dom-css 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/browser.d.ts +29 -0
  4. package/dist/browser.js +2 -0
  5. package/dist/chunks/behaviours/args.js +59 -0
  6. package/dist/chunks/behaviours/args.js.map +1 -0
  7. package/dist/chunks/behaviours/controls.js +109 -0
  8. package/dist/chunks/behaviours/controls.js.map +1 -0
  9. package/dist/chunks/behaviours/reset.js +40 -0
  10. package/dist/chunks/behaviours/reset.js.map +1 -0
  11. package/dist/chunks/behaviours/roles.js +51 -0
  12. package/dist/chunks/behaviours/roles.js.map +1 -0
  13. package/dist/chunks/behaviours/states/conditions.js +103 -0
  14. package/dist/chunks/behaviours/states/conditions.js.map +1 -0
  15. package/dist/chunks/behaviours/states/css.js +172 -0
  16. package/dist/chunks/behaviours/states/css.js.map +1 -0
  17. package/dist/chunks/behaviours/states/layers.js +1736 -0
  18. package/dist/chunks/behaviours/states/layers.js.map +1 -0
  19. package/dist/chunks/behaviours/states/model.js +144 -0
  20. package/dist/chunks/behaviours/states/model.js.map +1 -0
  21. package/dist/chunks/behaviours/states/tailwind.js +198 -0
  22. package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
  23. package/dist/chunks/browser.js +1352 -0
  24. package/dist/chunks/browser.js.map +1 -0
  25. package/dist/chunks/export/bundle.js +337 -0
  26. package/dist/chunks/export/bundle.js.map +1 -0
  27. package/dist/chunks/export/components/drawn.js +60 -0
  28. package/dist/chunks/export/components/drawn.js.map +1 -0
  29. package/dist/chunks/export/components/fields.js +178 -0
  30. package/dist/chunks/export/components/fields.js.map +1 -0
  31. package/dist/chunks/export/components/groups.js +297 -0
  32. package/dist/chunks/export/components/groups.js.map +1 -0
  33. package/dist/chunks/export/components/icons.js +260 -0
  34. package/dist/chunks/export/components/icons.js.map +1 -0
  35. package/dist/chunks/export/components/layers.js +1594 -0
  36. package/dist/chunks/export/components/layers.js.map +1 -0
  37. package/dist/chunks/export/index.js +477 -0
  38. package/dist/chunks/export/index.js.map +1 -0
  39. package/dist/chunks/export/storybook/component.js +448 -0
  40. package/dist/chunks/export/storybook/component.js.map +1 -0
  41. package/dist/chunks/export/storybook/export.js +410 -0
  42. package/dist/chunks/export/storybook/export.js.map +1 -0
  43. package/dist/chunks/import/html.js +406 -0
  44. package/dist/chunks/import/html.js.map +1 -0
  45. package/dist/chunks/import/jsx/dev-runtime.js +37 -0
  46. package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
  47. package/dist/chunks/tokens/cssom-validator.js +10 -0
  48. package/dist/chunks/tokens/cssom-validator.js.map +1 -0
  49. package/dist/export.d.ts +594 -0
  50. package/dist/export.js +13 -0
  51. package/dist/index.d.ts +115 -0
  52. package/dist/index.js +7 -0
  53. package/dist/jsx-dev-runtime.d.ts +8 -0
  54. package/dist/jsx-dev-runtime.js +3 -0
  55. package/dist/jsx-runtime.d.ts +20 -0
  56. package/dist/jsx-runtime.js +3 -0
  57. package/dist/rolldown-runtime.js +13 -0
  58. package/dist/runtime.d.ts +10 -0
  59. package/dist/scene-graph.d.ts +2 -0
  60. package/dist/scene-graph.js +2 -0
  61. package/dist/scene-graph2.d.ts +10 -0
  62. package/dist/styling.d.ts +93 -0
  63. package/dist/tailwind.d.ts +39 -0
  64. package/dist/types.d.ts +89 -0
  65. package/package.json +73 -4
  66. package/src/behaviours/args.ts +85 -0
  67. package/src/behaviours/controls.ts +195 -0
  68. package/src/behaviours/index.ts +11 -0
  69. package/src/behaviours/reset.ts +37 -0
  70. package/src/behaviours/roles.ts +44 -0
  71. package/src/behaviours/states/conditions.ts +105 -0
  72. package/src/behaviours/states/css.ts +123 -0
  73. package/src/behaviours/states/index.ts +4 -0
  74. package/src/behaviours/states/layers.ts +205 -0
  75. package/src/behaviours/states/model.ts +175 -0
  76. package/src/behaviours/states/names.ts +39 -0
  77. package/src/behaviours/states/tailwind.ts +148 -0
  78. package/src/behaviours/states/types.ts +56 -0
  79. package/src/browser.ts +146 -0
  80. package/src/cssom.d.ts +38 -0
  81. package/src/export/bundle.ts +461 -0
  82. package/src/export/components/drawn.ts +73 -0
  83. package/src/export/components/fields.ts +178 -0
  84. package/src/export/components/groups.ts +78 -0
  85. package/src/export/components/icons.ts +230 -0
  86. package/src/export/components/layers.ts +121 -0
  87. package/src/export/components/model.ts +544 -0
  88. package/src/export/components/properties.ts +167 -0
  89. package/src/export/components/react/fields.ts +129 -0
  90. package/src/export/components/react/index.ts +606 -0
  91. package/src/export/components/react/shared.ts +76 -0
  92. package/src/export/components/references.ts +212 -0
  93. package/src/export/components/repeats.ts +128 -0
  94. package/src/export/components/shaders.ts +125 -0
  95. package/src/export/components/styling.ts +31 -0
  96. package/src/export/components/tree.ts +72 -0
  97. package/src/export/components/vue.ts +517 -0
  98. package/src/export/css.ts +57 -0
  99. package/src/export/grid.ts +42 -0
  100. package/src/export/html.ts +163 -0
  101. package/src/export/index.ts +44 -0
  102. package/src/export/projection.ts +581 -0
  103. package/src/export/storybook/component.ts +334 -0
  104. package/src/export/storybook/export.ts +430 -0
  105. package/src/export/storybook/groups.ts +161 -0
  106. package/src/export/storybook/module.ts +319 -0
  107. package/src/export/storybook/names.ts +51 -0
  108. package/src/export/tailwind-jsx.ts +156 -0
  109. package/src/export/text.ts +415 -0
  110. package/src/import/css-text.ts +4 -0
  111. package/src/import/css-values.ts +31 -0
  112. package/src/import/flow.ts +248 -0
  113. package/src/import/html.ts +88 -0
  114. package/src/import/jsx/core.ts +130 -0
  115. package/src/import/jsx/dev-runtime.ts +8 -0
  116. package/src/import/jsx/runtime.ts +76 -0
  117. package/src/import/scene-graph.ts +582 -0
  118. package/src/import/style-attribute.ts +25 -0
  119. package/src/import/tailwind.ts +54 -0
  120. package/src/import/text.ts +518 -0
  121. package/src/index.ts +51 -0
  122. package/src/runtime/browser/runtime.ts +301 -0
  123. package/src/runtime/headless/runtime.ts +99 -0
  124. package/src/runtime/headless/styles.ts +330 -0
  125. package/src/runtime/index.ts +11 -0
  126. package/src/tokens/conditions.ts +66 -0
  127. package/src/tokens/cssom-validator.ts +8 -0
  128. package/src/tokens/custom-properties.ts +331 -0
  129. package/src/tokens/expression.ts +128 -0
  130. package/src/tokens/formula.ts +140 -0
  131. package/src/tokens/index.ts +43 -0
  132. package/src/tokens/names.ts +161 -0
  133. package/src/tokens/references.ts +201 -0
  134. package/src/tokens/stylesheet.ts +304 -0
  135. package/src/tokens/validate.ts +86 -0
  136. package/src/tokens/values.ts +44 -0
  137. package/src/types.ts +59 -0
@@ -0,0 +1,1736 @@
1
+ import { fromUint8Array } from "js-base64";
2
+ import { BLACK } from "@pairdraw/scene-graph/constants";
3
+ import { readIcon } from "@pairdraw/scene-graph/icons";
4
+ import { imageMimeType } from "@pairdraw/scene-graph/images";
5
+ import { layoutSizingInParent } from "@pairdraw/scene-graph/layout";
6
+ import { isShaderPresetPaint, shaderOfPaint } from "@pairdraw/scene-graph/shaders";
7
+ import { resolveNodeTextDirection } from "@pairdraw/scene-graph/text/direction";
8
+ import { compact } from "es-toolkit/array";
9
+ import valueParser from "postcss-value-parser";
10
+ import { themeNamespaces } from "twirlwind";
11
+ import { foldFormula, tokenNumberInUnit, variableValueReferences } from "@pairdraw/scene-graph/variables";
12
+ import { colorToCSS, colorToHex } from "@pairdraw/scene-graph/color";
13
+ import { isEqual } from "es-toolkit/predicate";
14
+ import { hasTextList, listNumberFormat, paragraphSpacingAt, paragraphStyleAt, textListItems, textParagraphRanges } from "@pairdraw/scene-graph/text";
15
+ import { omit } from "es-toolkit/object";
16
+ import { behaviourOwner, layerPath, partBinding, readBehaviour } from "@pairdraw/scene-graph/behaviours";
17
+ import { instanceMainComponent } from "@pairdraw/scene-graph/instances";
18
+ import { instanceSlotFrames, slotPropertyId } from "@pairdraw/scene-graph/slots";
19
+ //#region src/tokens/names.ts
20
+ /** Every variable, collection by collection, in each collection's own order. */
21
+ function collectionVariables(source) {
22
+ return compact([...source.variableCollections.values()].flatMap((collection) => collection.variableIds.map((id) => source.variables.get(id))));
23
+ }
24
+ const SCOPE_NAMESPACES = {
25
+ CORNER_RADIUS: "radius",
26
+ GAP: "spacing",
27
+ WIDTH_HEIGHT: "spacing",
28
+ FONT_SIZE: "text",
29
+ LINE_HEIGHT: "leading",
30
+ LETTER_SPACING: "tracking",
31
+ FONT_FAMILY: "font",
32
+ FONT_STYLE: "font-weight",
33
+ EFFECT_FLOAT: "blur"
34
+ };
35
+ /** Leading name segments that already say the namespace, so `Color/primary` is not `--color-color-primary`. */
36
+ const NAMESPACE_WORDS = {
37
+ ...Object.fromEntries(themeNamespaces.map((namespace) => [namespace, namespace])),
38
+ colors: "color",
39
+ colour: "color",
40
+ colours: "color",
41
+ space: "spacing",
42
+ radii: "radius",
43
+ rounded: "radius",
44
+ corner: "radius",
45
+ corners: "radius",
46
+ "font-size": "text",
47
+ "line-height": "leading",
48
+ "letter-spacing": "tracking",
49
+ fonts: "font",
50
+ "font-family": "font",
51
+ weight: "font-weight",
52
+ shadows: "shadow"
53
+ };
54
+ /**
55
+ * Lowercase words joined by `-`, keeping digits on their word, as Tailwind keys do: `Text/2xl`
56
+ * is `text-2xl`, `Heading/H1` is `heading-h1`, `brandPrimary` is `brand-primary`. es-toolkit's
57
+ * `kebabCase` splits digits off (`text-2-xl`), which no design system writes.
58
+ */
59
+ function tokenSlug(text) {
60
+ const words = text.normalize("NFKC").replaceAll(/(\p{Ll})(\p{Lu})/gu, "$1 $2").toLowerCase().split(/[^\p{L}\p{N}]+/u);
61
+ return compact(words).join("-");
62
+ }
63
+ /** The Tailwind namespace a token belongs to, from its type, its scopes, then its leading name segment. */
64
+ function variableNamespace(variable) {
65
+ if (variable.type === "COLOR") return "color";
66
+ const fromScopes = new Set((variable.scopes ?? []).map((scope) => SCOPE_NAMESPACES[scope]));
67
+ const [only] = fromScopes;
68
+ if (fromScopes.size === 1 && only) return only;
69
+ return NAMESPACE_WORDS[tokenSlug(variable.name.split("/")[0] ?? "")];
70
+ }
71
+ /**
72
+ * The custom property a code snippet names, without `--`: `var(--brand)`, `var(--brand, red)`
73
+ * and `--brand` all name `brand`. A snippet that is anything else, such as a Tailwind class,
74
+ * names none.
75
+ */
76
+ function parseCSSName(snippet) {
77
+ const nodes = valueParser(snippet ?? "").nodes.filter((node) => node.type !== "space");
78
+ const [node] = nodes;
79
+ if (nodes.length !== 1) return void 0;
80
+ const word = node.type === "function" && node.value === "var" && "nodes" in node ? node.nodes.find((child) => child.type !== "space") : node;
81
+ return word?.type === "word" && word.value.startsWith("--") && word.value.length > 2 ? word.value.slice(2) : void 0;
82
+ }
83
+ /** The name `codeSyntax.WEB` gives the token, if it gives one. */
84
+ function explicitCSSName(variable) {
85
+ return parseCSSName(variable.codeSyntax?.WEB);
86
+ }
87
+ /**
88
+ * `Gray/50` as COLOR is `color-gray-50`; `Space/small` is `spacing-small`. A group the next segment
89
+ * repeats is said once, so `Gap/gap-1` is `gap-1`, as kits that mirror Tailwind classes name them. Two tokens can derive
90
+ * the same name, so stylesheet output takes names from `variableCSSNames`, which makes them unique.
91
+ */
92
+ function deriveCSSName(variable) {
93
+ const namespace = variableNamespace(variable);
94
+ const segments = compact(variable.name.split("/").map(tokenSlug));
95
+ if (segments.length > 1 && namespace && NAMESPACE_WORDS[segments[0] ?? ""] === namespace) segments.shift();
96
+ const body = segments.filter((segment, index) => {
97
+ const next = segments.at(index + 1);
98
+ return next === void 0 || next !== segment && !next.startsWith(`${segment}-`);
99
+ }).join("-") || "token";
100
+ if (!namespace || body === namespace || body.startsWith(`${namespace}-`)) return body;
101
+ return `${namespace}-${body}`;
102
+ }
103
+ /**
104
+ * Document-wide custom property names, without `--`. The first token whose `WEB` snippet claims
105
+ * a name keeps it; later claimants, which Figma files do contain, and derived names that collide
106
+ * take a derived name with a numeric suffix, in iteration order.
107
+ */
108
+ function variableCSSNames(variables) {
109
+ const list = [...variables];
110
+ const names = /* @__PURE__ */ new Map();
111
+ const taken = /* @__PURE__ */ new Set();
112
+ for (const variable of list) {
113
+ const name = explicitCSSName(variable);
114
+ if (!name || taken.has(name)) continue;
115
+ names.set(variable.id, name);
116
+ taken.add(name);
117
+ }
118
+ for (const variable of list) {
119
+ if (names.has(variable.id)) continue;
120
+ const base = deriveCSSName(variable);
121
+ let name = base;
122
+ for (let n = 2; taken.has(name); n++) name = `${base}-${n}`;
123
+ names.set(variable.id, name);
124
+ taken.add(name);
125
+ }
126
+ return names;
127
+ }
128
+ /** The `WEB` snippet that names a token in Figma's Dev Mode and here. */
129
+ function cssNameCodeSyntax(name) {
130
+ return `var(--${name})`;
131
+ }
132
+ /** Namespaces longest first, so `font-weight-bold` reads as `font-weight`, not `font`. */
133
+ const NAMESPACES_BY_LENGTH = [...themeNamespaces].sort((a, b) => b.length - a.length);
134
+ /**
135
+ * The variable name a custom property reads as: a Tailwind namespace becomes the group, so
136
+ * `color-gray-50` is `color/gray-50` and `radius-md` is `radius/md`; any other name stays as it
137
+ * is. Variables made this way keep the property in their `WEB` code syntax, so the stylesheet
138
+ * writes the same name back.
139
+ */
140
+ function cssNameVariableName(name) {
141
+ const namespace = NAMESPACES_BY_LENGTH.find((candidate) => name.startsWith(`${candidate}-`));
142
+ return namespace ? `${namespace}/${name.slice(namespace.length + 1)}` : name;
143
+ }
144
+ //#endregion
145
+ //#region src/export/css.ts
146
+ /** Opaque colors as hex, which Tailwind matches to its palette; translucent ones as `rgba()`. */
147
+ function cssColor(color) {
148
+ return color.a >= 1 ? colorToHex(color) : colorToCSS(color);
149
+ }
150
+ function fillToCSS(fill) {
151
+ if (fill?.type !== "SOLID" || !fill.visible) return void 0;
152
+ return cssColor({
153
+ ...fill.color,
154
+ a: fill.opacity
155
+ });
156
+ }
157
+ function strokeColorToCSS(stroke) {
158
+ if (!stroke?.visible) return void 0;
159
+ return cssColor({
160
+ ...stroke.color,
161
+ a: stroke.opacity
162
+ });
163
+ }
164
+ function shadowToCSS(effect) {
165
+ return `${effect.type === "INNER_SHADOW" ? "inset " : ""}${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${cssColor(effect.color)}`;
166
+ }
167
+ function dropShadowToCSS(effect) {
168
+ if (effect?.type !== "DROP_SHADOW" || !effect.visible) return void 0;
169
+ return shadowToCSS(effect);
170
+ }
171
+ /** Every visible shadow, in order, plus layer and background blur. */
172
+ function effectsToCSS(effects) {
173
+ const style = {};
174
+ const visible = effects.filter((effect) => effect.visible);
175
+ const shadows = visible.filter((effect) => effect.type === "DROP_SHADOW" || effect.type === "INNER_SHADOW");
176
+ if (shadows.length > 0) style["box-shadow"] = shadows.map(shadowToCSS).join(", ");
177
+ for (const effect of visible) {
178
+ if (effect.type === "LAYER_BLUR" || effect.type === "FOREGROUND_BLUR") style.filter = `blur(${effect.radius}px)`;
179
+ if (effect.type === "BACKGROUND_BLUR") style["backdrop-filter"] = `blur(${effect.radius}px)`;
180
+ }
181
+ return style;
182
+ }
183
+ /** A line height as CSS writes it: a percent as the unitless multiple that follows the font size. */
184
+ function lineHeightToCSS(length) {
185
+ return length.unit === "PIXELS" ? `${length.value}px` : String(length.value / 100);
186
+ }
187
+ /** A letter spacing as CSS writes it: a percent of the font size in `em`. */
188
+ function letterSpacingToCSS(length) {
189
+ return length.unit === "PIXELS" ? `${length.value}px` : `${length.value / 100}em`;
190
+ }
191
+ //#endregion
192
+ //#region src/tokens/values.ts
193
+ const UNITLESS_SCOPES = /* @__PURE__ */ new Set([
194
+ "OPACITY",
195
+ "FONT_STYLE",
196
+ "FONT_VARIATIONS"
197
+ ]);
198
+ /**
199
+ * A property that takes values in each token unit, where a browser checks or computes a CSS
200
+ * expression written for the token: `scale` takes any plain number, `width` any length.
201
+ */
202
+ const TOKEN_UNIT_PROPERTY = {
203
+ none: "scale",
204
+ px: "width",
205
+ rem: "width",
206
+ "%": "width",
207
+ ms: "transition-duration",
208
+ s: "transition-duration",
209
+ deg: "rotate"
210
+ };
211
+ /**
212
+ * The unit a FLOAT token is written in. An explicit unit wins; opacity and font weights are
213
+ * unitless; every other number is a pixel length, which is what the canvas draws.
214
+ */
215
+ function variableUnit(variable) {
216
+ if (variable.type !== "FLOAT") return "none";
217
+ if (variable.unit) return variable.unit;
218
+ const scopes = variable.scopes ?? [];
219
+ if (scopes.length > 0 && scopes.every((scope) => UNITLESS_SCOPES.has(scope))) return "none";
220
+ return variableNamespace(variable) === "font-weight" ? "none" : "px";
221
+ }
222
+ /** Six decimals keep `rem` exact for every pixel step down to 1/1024px (0.5px is 0.03125rem). */
223
+ function trimNumber(value) {
224
+ return String(Number(value.toFixed(6)));
225
+ }
226
+ /** A stored number written in its unit: 24 as `rem` is `1.5rem`, 150 as `ms` is `150ms`. */
227
+ function tokenNumberToCSS(value, unit) {
228
+ const number = trimNumber(tokenNumberInUnit(value, unit));
229
+ if (unit === "none" || number === "0") return number;
230
+ return `${number}${unit}`;
231
+ }
232
+ //#endregion
233
+ //#region src/tokens/formula.ts
234
+ const OPERATORS = {
235
+ add: {
236
+ symbol: "+",
237
+ precedence: 1
238
+ },
239
+ subtract: {
240
+ symbol: "-",
241
+ precedence: 1
242
+ },
243
+ multiply: {
244
+ symbol: "*",
245
+ precedence: 2
246
+ },
247
+ divide: {
248
+ symbol: "/",
249
+ precedence: 2
250
+ }
251
+ };
252
+ const ATOM = 3;
253
+ var UnsupportedFormulaError = class extends Error {
254
+ name = "UnsupportedFormulaError";
255
+ };
256
+ function formulaToCSS(node, variable, variables, names) {
257
+ const unit = variableUnit(variable);
258
+ const context = {
259
+ variables,
260
+ names,
261
+ length: (value) => tokenNumberToCSS(value, unit)
262
+ };
263
+ try {
264
+ const result = convert(node, context);
265
+ const dimension = unit !== "none";
266
+ if (result.kind === "literal") return write(result, dimension, context);
267
+ if (result.dimension !== dimension) return { issue: dimension ? "has a formula without a unit" : "has a formula with a unit" };
268
+ return `calc(${result.text})`;
269
+ } catch (error) {
270
+ if (error instanceof UnsupportedFormulaError) return { issue: error.message };
271
+ throw error;
272
+ }
273
+ }
274
+ function convert(node, context) {
275
+ return foldFormula(node, {
276
+ literal: (value) => {
277
+ if (typeof value === "number") return {
278
+ kind: "literal",
279
+ value
280
+ };
281
+ if (typeof value === "boolean") throw new UnsupportedFormulaError("mixes true/false into a number");
282
+ throw new UnsupportedFormulaError("mixes text or a color into a number");
283
+ },
284
+ reference: (id) => reference(id, context),
285
+ operation: ({ operator }, operands) => {
286
+ const [a, b] = operands;
287
+ if (operator === "negate" && operands.length === 1) return negate(a, context);
288
+ if (operands.length !== 2 || !isArithmetic(operator)) throw new UnsupportedFormulaError("uses logic that CSS has no form for");
289
+ if (a.kind === "literal" && b.kind === "literal") return {
290
+ kind: "literal",
291
+ value: fold(operator, a.value, b.value)
292
+ };
293
+ return binary(operator, a, b, context);
294
+ }
295
+ });
296
+ }
297
+ function reference(id, { variables, names }) {
298
+ const target = variables.get(id);
299
+ const name = names.get(id);
300
+ if (!target || !name) throw new UnsupportedFormulaError("refers to a variable that does not exist");
301
+ if (target.type !== "FLOAT") throw new UnsupportedFormulaError("uses a variable that is not a number");
302
+ const dimension = variableUnit(target) !== "none";
303
+ return {
304
+ kind: "css",
305
+ text: `var(--${name})`,
306
+ precedence: ATOM,
307
+ dimension
308
+ };
309
+ }
310
+ function negate(term, context) {
311
+ if (term.kind === "literal") return {
312
+ kind: "literal",
313
+ value: -term.value
314
+ };
315
+ return {
316
+ kind: "css",
317
+ text: `-1 * ${grouped(term, false, OPERATORS.multiply.precedence, context)}`,
318
+ precedence: OPERATORS.multiply.precedence,
319
+ dimension: term.dimension
320
+ };
321
+ }
322
+ function binary(operator, a, b, context) {
323
+ const { symbol, precedence } = OPERATORS[operator];
324
+ const rightBelow = operator === "subtract" || operator === "divide" ? precedence + 1 : precedence;
325
+ const aDimension = a.kind === "css" && a.dimension;
326
+ const bDimension = b.kind === "css" && b.dimension;
327
+ if (precedence === 1) {
328
+ if (a.kind === "css" && b.kind === "css" && aDimension !== bDimension) throw new UnsupportedFormulaError("adds a length to a plain number");
329
+ const dimension = aDimension || bDimension;
330
+ return {
331
+ kind: "css",
332
+ text: `${grouped(a, dimension, precedence, context)} ${symbol} ${grouped(b, dimension, rightBelow, context)}`,
333
+ precedence,
334
+ dimension
335
+ };
336
+ }
337
+ if (bDimension && operator === "divide") throw new UnsupportedFormulaError("divides by a length");
338
+ if (aDimension && bDimension) throw new UnsupportedFormulaError("multiplies two lengths");
339
+ return {
340
+ kind: "css",
341
+ text: `${grouped(a, false, precedence, context)} ${symbol} ${grouped(b, false, rightBelow, context)}`,
342
+ precedence,
343
+ dimension: aDimension || bDimension
344
+ };
345
+ }
346
+ function write(term, dimension, context) {
347
+ if (term.kind === "css") return term.text;
348
+ return dimension ? context.length(term.value) : String(Number(term.value.toFixed(6)));
349
+ }
350
+ function grouped(term, dimension, below, context) {
351
+ return term.kind === "css" && term.precedence < below ? `(${term.text})` : write(term, dimension, context);
352
+ }
353
+ function isArithmetic(operator) {
354
+ return Object.hasOwn(OPERATORS, operator);
355
+ }
356
+ function fold(operator, a, b) {
357
+ if (operator === "add") return a + b;
358
+ if (operator === "subtract") return a - b;
359
+ if (operator === "multiply") return a * b;
360
+ return a / b;
361
+ }
362
+ //#endregion
363
+ //#region src/tokens/validate.ts
364
+ const AT_RULES = [
365
+ "@media",
366
+ "@supports",
367
+ "@container"
368
+ ];
369
+ function rules(sheet) {
370
+ return sheet.cssRules.filter((rule) => typeof rule === "object" && rule !== null);
371
+ }
372
+ /**
373
+ * Token strings come from documents, so each one is parsed in place before it is written. A value
374
+ * or condition that closes its rule early parses to a different number of rules and fails.
375
+ */
376
+ function createTokenValidator(parse) {
377
+ /** `--name: value` is one declaration whose value reads back unchanged. */
378
+ function declaration(name, value) {
379
+ const parsed = rules(parse(`:root{--${name}:${value}}`));
380
+ const [rule] = parsed;
381
+ return parsed.length === 1 && rule.style?.length === 1 && rule.style.getPropertyValue(`--${name}`).trim() === value.trim() && (rule.cssRules?.length ?? 0) === 0;
382
+ }
383
+ return {
384
+ declaration,
385
+ /**
386
+ * A custom property name without its `--`: one word to the CSS value tokenizer, which splits
387
+ * on spaces, colons, commas and slashes, and one declaration to the parser. It starts with a
388
+ * letter, digit or underscore, so `--` is never doubled into `----`.
389
+ */
390
+ name(name) {
391
+ const { nodes } = valueParser(`--${name}`);
392
+ return /^\w/.test(name) && nodes.length === 1 && nodes[0]?.type === "word" && declaration(name, "0");
393
+ },
394
+ /** A selector, or a `@media`, `@supports` or `@container` prelude, that wraps exactly one rule. */
395
+ condition(condition) {
396
+ const trimmed = condition.trim();
397
+ if (trimmed.startsWith("@")) {
398
+ if (!AT_RULES.some((rule) => trimmed.startsWith(`${rule} `) || trimmed.startsWith(`${rule}(`))) return false;
399
+ const parsed = rules(parse(`${trimmed}{:root{--t:0}}`));
400
+ return parsed.length === 1 && parsed[0]?.cssRules?.length === 1;
401
+ }
402
+ const parsed = rules(parse(`${trimmed}{--t:0}`));
403
+ const [rule] = parsed;
404
+ return parsed.length === 1 && typeof rule.selectorText === "string" && rule.style?.length === 1 && (rule.cssRules?.length ?? 0) === 0;
405
+ }
406
+ };
407
+ }
408
+ /** The browser's own CSS parser, through a constructable stylesheet. */
409
+ function parseWithBrowser(cssText) {
410
+ const sheet = new CSSStyleSheet();
411
+ sheet.replaceSync(cssText);
412
+ return { cssRules: [...sheet.cssRules] };
413
+ }
414
+ //#endregion
415
+ //#region src/tokens/stylesheet.ts
416
+ function isAtRuleCondition(condition) {
417
+ return condition.trim().startsWith("@");
418
+ }
419
+ /**
420
+ * A mode's name as an identifier. A name with no letters or digits falls back to its id, slugged
421
+ * too: Figma ids such as `1:2` are not valid in a selector value or a variant name as they are.
422
+ * Names that slug alike in one collection, such as `Dark` and `dark!`, are numbered in mode
423
+ * order, so each mode keeps its own selector and variant.
424
+ */
425
+ function modeSlug(collection, mode) {
426
+ const plainSlug = ({ name, modeId }) => tokenSlug(name) || `mode-${tokenSlug(modeId) || "unnamed"}`;
427
+ const taken = /* @__PURE__ */ new Set();
428
+ for (const candidate of collection.modes) {
429
+ const base = plainSlug(candidate);
430
+ let slug = base;
431
+ for (let n = 2; taken.has(slug); n++) slug = `${base}-${n}`;
432
+ if (candidate.modeId === mode.modeId) return slug;
433
+ taken.add(slug);
434
+ }
435
+ return plainSlug(mode);
436
+ }
437
+ /** The attribute a collection's manual modes are switched by, unless it names its own. */
438
+ function defaultModeAttributeName(collection) {
439
+ return `data-${tokenSlug(collection.name) || "mode"}`;
440
+ }
441
+ /** The attribute that puts an element in a mode with no condition of its own: `data-theme`. */
442
+ function modeAttribute(collection, mode) {
443
+ return {
444
+ name: collection.modeAttribute ?? defaultModeAttributeName(collection),
445
+ value: modeSlug(collection, mode)
446
+ };
447
+ }
448
+ /** The scope a mode applies in when it names none: `[data-theme="dark"]` for Theme / Dark. */
449
+ function defaultModeCondition(collection, mode) {
450
+ const { name, value } = modeAttribute(collection, mode);
451
+ return `[${name}="${value}"]`;
452
+ }
453
+ function quoteString(value) {
454
+ return `"${value.replaceAll("\\", "\\\\").replaceAll("\"", "\\\"").replaceAll("\n", "\\a ")}"`;
455
+ }
456
+ /** One mode's value as CSS, or why it has none. */
457
+ function modeValue(variable, value, modeId, names, variables) {
458
+ const expression = variable.expressions?.[modeId];
459
+ if (expression) return expression.css;
460
+ if (value === void 0) return { issue: "has no value in this mode" };
461
+ if (typeof value === "object" && "expression" in value) {
462
+ if (value.expression === "FORMULA" && variable.type === "FLOAT") return formulaToCSS(value.value, variable, variables, names);
463
+ if (variable.type === "BOOLEAN") return { issue: "is a boolean, which CSS has no value for" };
464
+ return { issue: "uses an expression that CSS token export does not support" };
465
+ }
466
+ if (typeof value === "object" && "aliasId" in value) {
467
+ const target = names.get(value.aliasId);
468
+ return target ? `var(--${target})` : { issue: "aliases a variable that does not exist" };
469
+ }
470
+ if (variable.type === "COLOR" && typeof value === "object") return cssColor(value);
471
+ if (variable.type === "FLOAT" && typeof value === "number") return tokenNumberToCSS(value, variableUnit(variable));
472
+ if (variable.type === "STRING" && typeof value === "string") return variableNamespace(variable) === "font" ? value : quoteString(value);
473
+ if (variable.type === "BOOLEAN") return { issue: "is a boolean, which CSS has no value for" };
474
+ return { issue: "has a value that does not match its type" };
475
+ }
476
+ function block(selector, declarations, indent = "") {
477
+ return `${indent}${selector} {\n${declarations.map(({ name, value }) => `${indent} --${name}: ${value};`).join("\n")}\n${indent}}`;
478
+ }
479
+ function modeBlock(scope) {
480
+ const comment = `/* ${scope.collection.name}: ${scope.mode.name} */`;
481
+ if (!isAtRuleCondition(scope.condition)) return `${comment}\n${block(scope.condition, scope.declarations)}`;
482
+ return `${comment}\n${scope.condition} {\n${block(":root", scope.declarations, " ")}\n}`;
483
+ }
484
+ /** `@custom-variant dark (&:where([data-theme="dark"], [data-theme="dark"] *));` */
485
+ function customVariant(name, condition) {
486
+ return `@custom-variant ${name} (${isAtRuleCondition(condition) ? condition : `&:where(${condition}, ${condition} *)`});`;
487
+ }
488
+ /** Variants are named after their mode, prefixed with the collection where two modes share a name. */
489
+ function variantNames(scopes) {
490
+ const plain = scopes.map(({ collection, mode }) => modeSlug(collection, mode));
491
+ return plain.map((name, index) => {
492
+ const shared = plain.filter((other) => other === name).length > 1;
493
+ const collection = scopes[index]?.collection.name ?? "";
494
+ return shared ? `${tokenSlug(collection)}-${name}` : name;
495
+ });
496
+ }
497
+ /**
498
+ * Variables as a stylesheet of custom properties. The default mode of every collection is the
499
+ * base set, in `:root` or, for Tailwind, in `@theme` when the token has a Tailwind namespace;
500
+ * every other mode overrides the values that differ, under its condition. Aliases stay `var()`
501
+ * references, and number formulas `calc()` over them; both are declared again in each mode that
502
+ * changes what they point to.
503
+ */
504
+ function buildTokenStylesheet(source, { format, include = () => true }, validate) {
505
+ const issues = [];
506
+ const collections = [...source.variableCollections.values()];
507
+ const all = collectionVariables(source);
508
+ const names = variableCSSNames(all);
509
+ const variables = all.filter(include);
510
+ const defaultModeOf = (variable) => source.variableCollections.get(variable.collectionId)?.defaultModeId ?? "";
511
+ function declare(variable, modeId, value) {
512
+ const name = names.get(variable.id) ?? variable.id;
513
+ const css = modeValue(variable, value, modeId, names, source.variables);
514
+ if (typeof css !== "string") {
515
+ issues.push({
516
+ message: `${variable.name} ${css.issue}`,
517
+ variableId: variable.id,
518
+ modeId
519
+ });
520
+ return;
521
+ }
522
+ if (!validate.declaration(name, css)) {
523
+ issues.push({
524
+ message: `${variable.name} is not a valid CSS declaration: --${name}: ${css}`,
525
+ variableId: variable.id,
526
+ modeId
527
+ });
528
+ return;
529
+ }
530
+ return {
531
+ name,
532
+ value: css
533
+ };
534
+ }
535
+ const defaults = /* @__PURE__ */ new Map();
536
+ const theme = [];
537
+ const root = [];
538
+ for (const variable of variables) {
539
+ const modeId = defaultModeOf(variable);
540
+ const declaration = declare(variable, modeId, variable.valuesByMode[modeId]);
541
+ if (!declaration) continue;
542
+ defaults.set(variable.id, declaration);
543
+ if (format === "tailwind" && variableNamespace(variable) !== void 0) theme.push(declaration);
544
+ else root.push(declaration);
545
+ }
546
+ /**
547
+ * What a mode's scope declares: the collection's values that differ from its default, and every
548
+ * alias or formula, in any collection, whose chain reaches one of them. Custom properties inherit as
549
+ * computed values, so `--primary: var(--blue)` resolved at `:root` would keep the old blue
550
+ * unless it is declared again where `--blue` changes.
551
+ */
552
+ function modeDeclarations(collection, mode) {
553
+ const own = (variable) => variable.collectionId === collection.id;
554
+ const valueIn = (variable) => own(variable) ? variable.valuesByMode[mode.modeId] ?? variable.valuesByMode[collection.defaultModeId] : variable.valuesByMode[defaultModeOf(variable)];
555
+ const inMode = /* @__PURE__ */ new Map();
556
+ const scoped = /* @__PURE__ */ new Map();
557
+ for (const variable of variables.filter(own)) {
558
+ const declaration = declare(variable, mode.modeId, valueIn(variable));
559
+ if (!declaration) continue;
560
+ inMode.set(variable.id, declaration);
561
+ if (declaration.value !== defaults.get(variable.id)?.value) scoped.set(variable.id, declaration);
562
+ }
563
+ for (let grew = true; grew;) {
564
+ grew = false;
565
+ for (const variable of variables) {
566
+ const references = variableValueReferences(valueIn(variable));
567
+ if (scoped.has(variable.id) || !references.some((target) => scoped.has(target))) continue;
568
+ const declaration = inMode.get(variable.id) ?? defaults.get(variable.id);
569
+ if (!declaration) continue;
570
+ scoped.set(variable.id, declaration);
571
+ grew = true;
572
+ }
573
+ }
574
+ return variables.flatMap((variable) => {
575
+ const declaration = scoped.get(variable.id);
576
+ return declaration ? [declaration] : [];
577
+ });
578
+ }
579
+ const scopes = [];
580
+ for (const collection of collections) for (const mode of collection.modes) {
581
+ if (mode.modeId === collection.defaultModeId) continue;
582
+ const condition = mode.condition ?? defaultModeCondition(collection, mode);
583
+ if (!validate.condition(condition)) {
584
+ issues.push({
585
+ message: `${collection.name}: ${mode.name} has a condition that is not a selector or a @media, @supports or @container query: ${condition}`,
586
+ collectionId: collection.id,
587
+ modeId: mode.modeId
588
+ });
589
+ continue;
590
+ }
591
+ const declarations = modeDeclarations(collection, mode);
592
+ if (declarations.length > 0) scopes.push({
593
+ collection,
594
+ mode,
595
+ condition,
596
+ declarations
597
+ });
598
+ }
599
+ const sections = [];
600
+ if (theme.length > 0) sections.push(block("@theme", theme));
601
+ if (root.length > 0) sections.push(block(":root", root));
602
+ sections.push(...scopes.map(modeBlock));
603
+ if (format === "tailwind" && scopes.length > 0) {
604
+ const variants = variantNames(scopes);
605
+ sections.push(scopes.map((scope, index) => customVariant(variants[index] ?? modeSlug(scope.collection, scope.mode), scope.condition)).join("\n"));
606
+ }
607
+ return {
608
+ css: sections.length > 0 ? `${sections.join("\n\n")}\n` : "",
609
+ issues
610
+ };
611
+ }
612
+ /**
613
+ * Browsers check token strings with their own CSS parser. Elsewhere, in the CLI and MCP, the CSS
614
+ * object model package loads on first use; its browser build exports nothing, so it is never
615
+ * the browser path.
616
+ */
617
+ async function loadTokenValidator() {
618
+ if (typeof CSSStyleSheet === "function") return createTokenValidator(parseWithBrowser);
619
+ return (await import("../../tokens/cssom-validator.js").then((n) => n.cssom_validator_exports)).tokenValidator;
620
+ }
621
+ async function tokenStylesheet(source, options) {
622
+ return buildTokenStylesheet(source, options, await loadTokenValidator());
623
+ }
624
+ //#endregion
625
+ //#region src/tokens/references.ts
626
+ /** Bound fields drawn as a length; any other numeric binding is unitless or not exported. */
627
+ const LENGTH_FIELDS = /* @__PURE__ */ new Set([
628
+ "width",
629
+ "height",
630
+ "minWidth",
631
+ "maxWidth",
632
+ "minHeight",
633
+ "maxHeight",
634
+ "cornerRadius",
635
+ "topLeftRadius",
636
+ "topRightRadius",
637
+ "bottomLeftRadius",
638
+ "bottomRightRadius",
639
+ "strokeWeight",
640
+ "borderTopWeight",
641
+ "borderBottomWeight",
642
+ "borderLeftWeight",
643
+ "borderRightWeight",
644
+ "fontSize",
645
+ "letterSpacing",
646
+ "lineHeight",
647
+ "paddingLeft",
648
+ "paddingRight",
649
+ "paddingTop",
650
+ "paddingBottom",
651
+ "itemSpacing",
652
+ "counterAxisSpacing",
653
+ "gridRowGap",
654
+ "gridColumnGap"
655
+ ]);
656
+ const LENGTH_UNITS = /* @__PURE__ */ new Set(["px", "rem"]);
657
+ /** Color channels are stored as floats; a bound paint copies them, so this only absorbs rounding. */
658
+ const CHANNEL_TOLERANCE = 1 / 512;
659
+ const CHANNELS = [
660
+ "r",
661
+ "g",
662
+ "b",
663
+ "a"
664
+ ];
665
+ function sameColor(a, b) {
666
+ return CHANNELS.every((channel) => Math.abs(a[channel] - b[channel]) <= CHANNEL_TOLERANCE);
667
+ }
668
+ function isColor(value) {
669
+ return typeof value === "object" && value !== null && "r" in value && "a" in value;
670
+ }
671
+ /** The paint a `fills/0/color` or `strokes/1/color` binding names. */
672
+ function boundPaint(node, field) {
673
+ const [list, index] = field.split("/");
674
+ if (list === "fills") return node.fills[Number(index)];
675
+ if (list === "strokes") return node.strokes[Number(index)];
676
+ }
677
+ /**
678
+ * Variable references for design-to-code. A bound field becomes `var(--name)` only when the
679
+ * stylesheet resolves it to what the canvas draws: the element sits in the same modes, and the
680
+ * token's CSS value is a length for a length, a bare number for opacity, or the paint's color.
681
+ * Anything else keeps its literal value.
682
+ */
683
+ var DesignTokens = class {
684
+ names;
685
+ /** Tokens the output references, with every variable their aliases reach. */
686
+ used = /* @__PURE__ */ new Set();
687
+ #graph;
688
+ constructor(graph) {
689
+ this.#graph = graph;
690
+ this.names = variableCSSNames(collectionVariables(graph));
691
+ }
692
+ /** The modes CSS applies outside the exported nodes: every collection's default. */
693
+ defaultModes() {
694
+ return new Map([...this.#graph.variableCollections.values()].map((collection) => [collection.id, collection.defaultModeId]));
695
+ }
696
+ /**
697
+ * Attributes that put an element in the modes the canvas draws it in, and the modes CSS then
698
+ * applies to it. An exported root takes the editor's active modes; below it, a node changes
699
+ * modes only where it sets one. Only a mode without its own condition can be set this way.
700
+ */
701
+ enter(node, inherited, root) {
702
+ const attrs = {};
703
+ const modes = new Map(inherited);
704
+ for (const collection of this.#graph.variableCollections.values()) {
705
+ if (!root && !node.variableModes[collection.id]) continue;
706
+ const modeId = this.#graph.getNodeVariableModeId(node.id, collection.id);
707
+ const mode = collection.modes.find((candidate) => candidate.modeId === modeId);
708
+ if (!mode || modeId === inherited.get(collection.id)) continue;
709
+ if (modeId === collection.defaultModeId || mode.condition) continue;
710
+ const { name, value } = modeAttribute(collection, mode);
711
+ attrs[name] = value;
712
+ modes.set(collection.id, modeId);
713
+ }
714
+ return {
715
+ attrs,
716
+ modes
717
+ };
718
+ }
719
+ /** `var(--name)` for a bound field, or `undefined` where the literal value must stay. */
720
+ reference(node, field, modes) {
721
+ const variableId = node.boundVariables[field];
722
+ const variable = variableId ? this.#graph.variables.get(variableId) : void 0;
723
+ const name = variable && this.names.get(variable.id);
724
+ if (!variable || !name) return void 0;
725
+ const chain = this.#chain(node, variable, modes);
726
+ if (!chain || !this.#drawsResolved(node, field, chain)) return void 0;
727
+ for (const id of chain.ids) this.used.add(id);
728
+ return `var(--${name})`;
729
+ }
730
+ /**
731
+ * Follow aliases in the modes the canvas draws the node in, stopping at a value or at a CSS
732
+ * expression, which is what the stylesheet writes for that mode. Fails where CSS would resolve
733
+ * any link in another mode.
734
+ */
735
+ #chain(node, start, modes) {
736
+ const ids = [];
737
+ let variable = start;
738
+ while (variable && !ids.includes(variable.id)) {
739
+ ids.push(variable.id);
740
+ const modeId = this.#graph.getNodeVariableModeId(node.id, variable.collectionId);
741
+ const collection = this.#graph.variableCollections.get(variable.collectionId);
742
+ if (modeId !== (modes.get(variable.collectionId) ?? collection?.defaultModeId)) return void 0;
743
+ const value = variable.valuesByMode[modeId] ?? (collection ? variable.valuesByMode[collection.defaultModeId] : void 0);
744
+ if (variable.expressions?.[modeId]) return {
745
+ ids,
746
+ value,
747
+ end: variable,
748
+ expression: true
749
+ };
750
+ if (typeof value === "object" && "aliasId" in value) {
751
+ variable = this.#graph.variables.get(value.aliasId);
752
+ continue;
753
+ }
754
+ return {
755
+ ids,
756
+ value,
757
+ end: variable,
758
+ expression: false
759
+ };
760
+ }
761
+ }
762
+ #drawsResolved(node, field, { value, end, expression }) {
763
+ if (field.endsWith("/color")) {
764
+ const paint = boundPaint(node, field);
765
+ if (!paint?.visible || paint.type !== "SOLID" || !isColor(value)) return false;
766
+ return sameColor({
767
+ ...paint.color,
768
+ a: paint.opacity
769
+ }, value);
770
+ }
771
+ const drawn = Reflect.get(node, field);
772
+ if (typeof drawn !== "number" || typeof value !== "number") return false;
773
+ if (Math.fround(drawn) !== Math.fround(value)) return false;
774
+ if (field === "opacity") return expression || variableUnit(end) === "none";
775
+ return LENGTH_FIELDS.has(field) && (expression || LENGTH_UNITS.has(variableUnit(end)));
776
+ }
777
+ /**
778
+ * The variables a stylesheet for this output declares: the referenced ones and every variable
779
+ * their aliases reach in any mode, since each mode's scope declares its own alias targets.
780
+ */
781
+ stylesheetVariables() {
782
+ const ids = /* @__PURE__ */ new Set();
783
+ const pending = [...this.used];
784
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
785
+ if (ids.has(id)) continue;
786
+ ids.add(id);
787
+ for (const value of Object.values(this.#graph.variables.get(id)?.valuesByMode ?? {})) if (typeof value === "object" && "aliasId" in value) pending.push(value.aliasId);
788
+ }
789
+ return ids;
790
+ }
791
+ /** Custom properties the Tailwind stylesheet declares in `@theme`, which name utilities. */
792
+ themeVariables() {
793
+ return [...this.names].flatMap(([id, name]) => {
794
+ const variable = this.#graph.variables.get(id);
795
+ return variable && variableNamespace(variable) !== void 0 ? [`--${name}`] : [];
796
+ });
797
+ }
798
+ };
799
+ //#endregion
800
+ //#region src/export/grid.ts
801
+ function trackToCSS(track) {
802
+ if (track.sizing === "FR") return `${track.value}fr`;
803
+ if (track.sizing === "FIXED") return `${track.value}px`;
804
+ return "auto";
805
+ }
806
+ /** Equal `1fr` tracks use Tailwind's `grid-cols-N` form, which keeps them from overflowing. */
807
+ function tracksToCSS(tracks) {
808
+ if (tracks.every((track) => track.sizing === "FR" && track.value === 1)) return `repeat(${tracks.length}, minmax(0, 1fr))`;
809
+ return tracks.map(trackToCSS).join(" ");
810
+ }
811
+ function addGridContainer(style, node, css) {
812
+ style.display = "grid";
813
+ if (node.gridTemplateColumns.length > 0) style["grid-template-columns"] = tracksToCSS(node.gridTemplateColumns);
814
+ if (node.gridTemplateRows.length > 0) style["grid-template-rows"] = tracksToCSS(node.gridTemplateRows);
815
+ if (node.gridColumnGap > 0) style["column-gap"] = css("gridColumnGap", `${node.gridColumnGap}px`);
816
+ if (node.gridRowGap > 0) style["row-gap"] = css("gridRowGap", `${node.gridRowGap}px`);
817
+ }
818
+ /** A span sets the whole placement, so the start follows it. */
819
+ function addGridPlacement(style, node) {
820
+ const position = node.gridPosition;
821
+ if (!position) return;
822
+ if (position.columnSpan > 1) style["grid-column"] = `span ${position.columnSpan} / span ${position.columnSpan}`;
823
+ if (position.column > 0) style["grid-column-start"] = String(position.column);
824
+ if (position.rowSpan > 1) style["grid-row"] = `span ${position.rowSpan} / span ${position.rowSpan}`;
825
+ if (position.row > 0) style["grid-row-start"] = String(position.row);
826
+ }
827
+ //#endregion
828
+ //#region src/export/text.ts
829
+ const CHARACTER_STYLE_KEYS = [
830
+ "fontFamily",
831
+ "fontSize",
832
+ "fontWeight",
833
+ "italic",
834
+ "letterSpacing",
835
+ "lineHeight",
836
+ "fills",
837
+ "textDecoration",
838
+ "textDecorationStyle",
839
+ "textDecorationThickness",
840
+ "textDecorationFills",
841
+ "textDecorationSkipInk",
842
+ "textUnderlineOffset",
843
+ "textCase"
844
+ ];
845
+ /** A list's indent per level, in ems of its first character, as the canvas lays lists out. */
846
+ const LIST_INDENT_EMS = 1.5;
847
+ const DECORATION_PROPERTIES = /* @__PURE__ */ new Set([
848
+ "text-decoration-line",
849
+ "text-decoration-style",
850
+ "text-decoration-color",
851
+ "text-decoration-thickness",
852
+ "text-underline-offset",
853
+ "text-decoration-skip-ink"
854
+ ]);
855
+ const px$1 = (value) => `${value}px`;
856
+ /** Links a page can follow: to the web, to mail, or to a phone; others are left out. */
857
+ const LINK_PROTOCOLS = /* @__PURE__ */ new Set([
858
+ "http:",
859
+ "https:",
860
+ "mailto:",
861
+ "tel:"
862
+ ]);
863
+ /** A link as an `href`, for a link to a URL a page can follow. */
864
+ function linkHref(link) {
865
+ if (link?.type !== "URL") return null;
866
+ try {
867
+ return LINK_PROTOCOLS.has(new URL(link.value).protocol) ? link.value : null;
868
+ } catch {
869
+ return null;
870
+ }
871
+ }
872
+ function textCaseToCSS(value) {
873
+ if (value === "UPPER") return "uppercase";
874
+ if (value === "LOWER") return "lowercase";
875
+ if (value === "TITLE") return "capitalize";
876
+ }
877
+ function characterStyle(node, override = {}) {
878
+ const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]));
879
+ for (const key of CHARACTER_STYLE_KEYS) {
880
+ const value = override[key];
881
+ if (value !== void 0) style[key] = value;
882
+ }
883
+ return style;
884
+ }
885
+ /** The text in ranges of one style each: the runs, and the layer's own style between them. */
886
+ function styledRanges(node) {
887
+ const ranges = [];
888
+ const base = characterStyle(node);
889
+ let at = 0;
890
+ for (const run of node.styleRuns.toSorted((a, b) => a.start - b.start)) {
891
+ const start = Math.max(at, run.start);
892
+ const end = Math.min(node.text.length, run.start + run.length);
893
+ if (start > at) ranges.push({
894
+ start: at,
895
+ end: start,
896
+ style: base,
897
+ href: null
898
+ });
899
+ if (end > start) {
900
+ const href = linkHref(run.style.hyperlink);
901
+ ranges.push({
902
+ start,
903
+ end,
904
+ style: characterStyle(node, run.style),
905
+ href
906
+ });
907
+ }
908
+ at = Math.max(at, end);
909
+ }
910
+ if (at < node.text.length) ranges.push({
911
+ start: at,
912
+ end: node.text.length,
913
+ style: base,
914
+ href: null
915
+ });
916
+ return ranges;
917
+ }
918
+ /** Underline or strikethrough as CSS writes it: Figma's offset is CSS's, from the baseline. */
919
+ function decorationCSS(style) {
920
+ if (style.textDecoration === "NONE") return {};
921
+ const underline = style.textDecoration === "UNDERLINE";
922
+ const css = { "text-decoration-line": underline ? "underline" : "line-through" };
923
+ if (style.textDecorationStyle !== "SOLID") css["text-decoration-style"] = style.textDecorationStyle.toLowerCase();
924
+ const color = fillToCSS(style.textDecorationFills.find((fill) => fill.visible));
925
+ if (color) css["text-decoration-color"] = color;
926
+ if (style.textDecorationThickness !== null) css["text-decoration-thickness"] = px$1(style.textDecorationThickness);
927
+ if (underline && style.textUnderlineOffset !== null) css["text-underline-offset"] = px$1(style.textUnderlineOffset);
928
+ if (underline && !style.textDecorationSkipInk) css["text-decoration-skip-ink"] = "none";
929
+ return css;
930
+ }
931
+ function characterCSS(style, decorated) {
932
+ return {
933
+ color: fillToCSS(style.fills.at(0)) ?? "",
934
+ "font-family": style.fontFamily,
935
+ "font-size": px$1(style.fontSize),
936
+ "font-weight": String(style.fontWeight),
937
+ "font-style": style.italic ? "italic" : "normal",
938
+ "letter-spacing": letterSpacingToCSS(style.letterSpacing),
939
+ "line-height": style.lineHeight === null ? "normal" : lineHeightToCSS(style.lineHeight),
940
+ "text-transform": textCaseToCSS(style.textCase) ?? "none",
941
+ ...decorated ? decorationCSS(style) : {}
942
+ };
943
+ }
944
+ /** What `css` sets differently from `base`. */
945
+ function differing(css, base) {
946
+ return Object.fromEntries(Object.entries(css).filter(([property, value]) => value !== "" && base[property] !== value));
947
+ }
948
+ /**
949
+ * Whether the text decorates every character alike. CSS draws an element's decoration through
950
+ * its descendants, which cannot take it off, so mixed decorations go on the spans instead.
951
+ */
952
+ function uniformDecoration(node, ranges) {
953
+ const decorations = ranges.filter((range) => node.text.slice(range.start, range.end).replaceAll("\n", "") !== "").map((range) => decorationCSS(range.style));
954
+ return decorations.every((decoration) => isEqual(decoration, decorations[0]));
955
+ }
956
+ function textNode(text) {
957
+ return {
958
+ type: "text",
959
+ text
960
+ };
961
+ }
962
+ function element(tagName, inlineStyle, children) {
963
+ return {
964
+ type: "element",
965
+ tagName,
966
+ attrs: {},
967
+ inlineStyle,
968
+ children
969
+ };
970
+ }
971
+ /**
972
+ * A link styled as the text around it: a link draws in the text's colour and with only the
973
+ * decoration its characters have, as in Figma, not in a browser's link style.
974
+ */
975
+ function linkElement(href, css, text) {
976
+ return {
977
+ ...element("a", {
978
+ color: "inherit",
979
+ "text-decoration-line": "none",
980
+ ...css
981
+ }, [textNode(text)]),
982
+ attrs: { href }
983
+ };
984
+ }
985
+ /**
986
+ * `text[start, end)` as text and spans, each span setting only what differs from the layer;
987
+ * linked characters are a link instead.
988
+ */
989
+ function inlineContent(projection, start, end) {
990
+ const { node, ranges, base, decorated } = projection;
991
+ const pieces = [];
992
+ for (const range of ranges) {
993
+ const from = Math.max(start, range.start);
994
+ const to = Math.min(end, range.end);
995
+ if (to <= from) continue;
996
+ const css = differing(characterCSS(range.style, !decorated), base);
997
+ const text = node.text.slice(from, to);
998
+ const previous = pieces.at(-1);
999
+ if (previous && previous.href === range.href && isEqual(previous.css, css)) previous.text += text;
1000
+ else pieces.push({
1001
+ css,
1002
+ text,
1003
+ href: range.href
1004
+ });
1005
+ }
1006
+ return pieces.map(({ css, text, href }) => {
1007
+ if (href) return linkElement(href, css, text);
1008
+ return Object.keys(css).length === 0 ? textNode(text) : element("span", css, [textNode(text)]);
1009
+ });
1010
+ }
1011
+ /** A paragraph's content; an empty one holds a line break, which gives it a line's height. */
1012
+ function paragraphContent(projection, range) {
1013
+ if (range.end === range.start) return [element("br", {}, [])];
1014
+ return inlineContent(projection, range.start, range.end);
1015
+ }
1016
+ /** Text that CSS lays out in one element: no lists, and no spacing or indent between lines. */
1017
+ function needsBlocks(node) {
1018
+ if (hasTextList(node)) return true;
1019
+ const paragraphs = textParagraphRanges(node.text);
1020
+ return paragraphs.some((_, index) => paragraphSpacingAt(node, index, "paragraphIndent") > 0 || index < paragraphs.length - 1 && paragraphSpacingAt(node, index, "paragraphSpacing") > 0);
1021
+ }
1022
+ /** The space after paragraph `index`: list spacing between two items, paragraph spacing else. */
1023
+ function spaceAfter(node, index, count) {
1024
+ if (index >= count - 1) return 0;
1025
+ const betweenItems = paragraphStyleAt(node.textParagraphs, index).listType !== "NONE" && paragraphStyleAt(node.textParagraphs, index + 1).listType !== "NONE";
1026
+ return paragraphSpacingAt(node, index, betweenItems ? "listSpacing" : "paragraphSpacing");
1027
+ }
1028
+ function listStyleType(item) {
1029
+ if (item.listType === "UNORDERED") return "disc";
1030
+ const format = listNumberFormat(item.level);
1031
+ if (format === "LOWER_ALPHA") return "lower-alpha";
1032
+ if (format === "LOWER_ROMAN") return "lower-roman";
1033
+ return "decimal";
1034
+ }
1035
+ /** Where the next list item goes: closes lists deeper than it, or of another kind at its level. */
1036
+ function closeListsFor(open, item) {
1037
+ while ((open.at(-1)?.level ?? 0) > item.level) open.pop();
1038
+ const top = open.at(-1);
1039
+ if (top?.level === item.level && (top.listType !== item.listType || item.startsList)) open.pop();
1040
+ }
1041
+ /**
1042
+ * Opens a list one level below the innermost open one, inside its last item; a level an item
1043
+ * skips gets an item without a marker to hold it.
1044
+ */
1045
+ function openList(open, blocks, item, indent) {
1046
+ const parent = open.at(-1);
1047
+ const level = (parent?.level ?? 0) + 1;
1048
+ const list = element(item.listType === "ORDERED" ? "ol" : "ul", {
1049
+ ...blockMargins(0, 0),
1050
+ "padding-inline-start": px$1(indent),
1051
+ "list-style-type": level === item.level ? listStyleType(item) : "none"
1052
+ }, []);
1053
+ if (parent) {
1054
+ parent.item ??= appendTo(parent.element, element("li", { "list-style-type": "none" }, []));
1055
+ const spacing = parent.item.inlineStyle?.["margin-bottom"];
1056
+ if (spacing && parent.item.inlineStyle && list.inlineStyle) {
1057
+ delete parent.item.inlineStyle["margin-bottom"];
1058
+ list.inlineStyle["margin-top"] = spacing;
1059
+ }
1060
+ parent.item.children.push(list);
1061
+ } else blocks.push(list);
1062
+ open.push({
1063
+ level,
1064
+ listType: item.listType,
1065
+ element: list,
1066
+ item: void 0
1067
+ });
1068
+ }
1069
+ function plainParagraph(projection, index, range, after) {
1070
+ const style = blockMargins(0, after);
1071
+ const indent = paragraphSpacingAt(projection.node, index, "paragraphIndent");
1072
+ if (indent > 0) style["text-indent"] = px$1(indent);
1073
+ return element("p", style, paragraphContent(projection, range));
1074
+ }
1075
+ /**
1076
+ * The text as blocks, as Figma lays it out: a paragraph per plain one, lists nested by level
1077
+ * with Figma's markers (bullets at every level, numbers counting 1, a, i as they nest), and the
1078
+ * space after each paragraph as a margin on what ends it.
1079
+ */
1080
+ function blockContent(projection) {
1081
+ const { node } = projection;
1082
+ const paragraphs = textParagraphRanges(node.text);
1083
+ const items = new Map(textListItems(node.text, node.textParagraphs).map((item) => [item.paragraph, item]));
1084
+ const blocks = [];
1085
+ const open = [];
1086
+ for (const [index, range] of paragraphs.entries()) {
1087
+ const after = spaceAfter(node, index, paragraphs.length);
1088
+ const item = items.get(index);
1089
+ if (!item) {
1090
+ open.length = 0;
1091
+ blocks.push(plainParagraph(projection, index, range, after));
1092
+ continue;
1093
+ }
1094
+ const unit = groupEm(projection, paragraphs, item) * LIST_INDENT_EMS;
1095
+ closeListsFor(open, item);
1096
+ while ((open.at(-1)?.level ?? 0) < item.level) openList(open, blocks, item, open.length === 0 && node.hangingList ? 0 : unit);
1097
+ const list = open.at(-1);
1098
+ if (!list) continue;
1099
+ const style = after > 0 ? { "margin-bottom": px$1(after) } : {};
1100
+ list.item = appendTo(list.element, element("li", style, paragraphContent(projection, range)));
1101
+ }
1102
+ return blocks;
1103
+ }
1104
+ /** Margins above and below a block, written out: paragraphs and lists have their own in CSS. */
1105
+ function blockMargins(top, bottom) {
1106
+ return {
1107
+ "margin-top": px$1(top),
1108
+ "margin-bottom": px$1(bottom)
1109
+ };
1110
+ }
1111
+ function appendTo(parent, child) {
1112
+ parent.children.push(child);
1113
+ return child;
1114
+ }
1115
+ /** The size of a list's first character, which its indents are measured in. */
1116
+ function groupEm(projection, paragraphs, item) {
1117
+ const at = paragraphs[item.groupStart]?.start ?? item.start;
1118
+ return projection.ranges.find((candidate) => at >= candidate.start && at < candidate.end)?.style.fontSize ?? projection.node.fontSize;
1119
+ }
1120
+ /**
1121
+ * A text layer's element: its tag, its style with the decoration the whole text shares, and
1122
+ * its content. Runs of characters styled apart become spans; text with lists, paragraph
1123
+ * spacing, or a first-line indent becomes blocks, which a `<div>` holds.
1124
+ */
1125
+ function textElementContent(node, layerStyle) {
1126
+ const ranges = styledRanges(node);
1127
+ const decorated = uniformDecoration(node, ranges);
1128
+ const style = Object.fromEntries(Object.entries(layerStyle).filter(([property]) => !DECORATION_PROPERTIES.has(property)));
1129
+ if (decorated) Object.assign(style, decorationCSS(characterStyle(node)));
1130
+ const projection = {
1131
+ node,
1132
+ ranges,
1133
+ base: characterCSS(characterStyle(node), decorated),
1134
+ decorated
1135
+ };
1136
+ if (!needsBlocks(node)) return {
1137
+ tagName: "span",
1138
+ style,
1139
+ children: inlineContent(projection, 0, node.text.length)
1140
+ };
1141
+ return {
1142
+ tagName: "div",
1143
+ style,
1144
+ children: blockContent(projection)
1145
+ };
1146
+ }
1147
+ //#endregion
1148
+ //#region src/export/projection.ts
1149
+ const DOM_CSS_PLUGIN_ID = "pairdraw-dom-css";
1150
+ const IMAGE_SOURCE_URL_KEY = "image-source-url";
1151
+ /** Layers whose shape only paths describe, which CSS boxes cannot draw. */
1152
+ const VECTOR_SHAPES = /* @__PURE__ */ new Set([
1153
+ "VECTOR",
1154
+ "BOOLEAN_OPERATION",
1155
+ "STAR",
1156
+ "POLYGON"
1157
+ ]);
1158
+ /** What a box draws itself, which the SVG of a vector layer draws instead. */
1159
+ const BOX_PAINT = /^(background|border|box-shadow|outline|filter)/;
1160
+ const px = (value) => `${value}px`;
1161
+ function nodeChildren(graph, node) {
1162
+ return node.childIds.map((id) => graph.getNode(id)).filter((child) => child !== void 0);
1163
+ }
1164
+ function justifyContentToCSS(value) {
1165
+ if (value === "CENTER") return "center";
1166
+ if (value === "MAX") return "flex-end";
1167
+ if (value === "SPACE_BETWEEN") return "space-between";
1168
+ if (value === "SPACE_AROUND") return "space-around";
1169
+ }
1170
+ /**
1171
+ * Cross-axis alignment of a container's children, or of one child. Auto layout starts children
1172
+ * at the start while flexbox stretches them, so start is written out: a child that hugs its
1173
+ * content keeps its own size.
1174
+ */
1175
+ function alignToCSS(value) {
1176
+ if (value === "MIN") return "flex-start";
1177
+ if (value === "CENTER") return "center";
1178
+ if (value === "MAX") return "flex-end";
1179
+ if (value === "STRETCH") return "stretch";
1180
+ if (value === "BASELINE") return "baseline";
1181
+ }
1182
+ /** Whether a layer sizes itself to its content along an axis, so CSS should too. */
1183
+ function hugs(node, axis) {
1184
+ if (node.type === "TEXT") return node.textAutoResize === "WIDTH_AND_HEIGHT" || axis === "height" && node.textAutoResize === "HEIGHT";
1185
+ if (node.layoutMode !== "HORIZONTAL" && node.layoutMode !== "VERTICAL") return false;
1186
+ return (node.layoutMode === "HORIZONTAL" === (axis === "width") ? node.primaryAxisSizing : node.counterAxisSizing) === "HUG";
1187
+ }
1188
+ /**
1189
+ * A layer's size: fixed on the axes the design fixes, and left to the content where the layer
1190
+ * hugs it (an auto layout frame set to Hug, or auto-sizing text), so the page grows with it.
1191
+ */
1192
+ function addSize(style, node, parent, css) {
1193
+ const sized = (axis) => node[axis] > 0 && !hugs(node, axis) && !stretches(node, parent, axis);
1194
+ if (sized("width")) style.width = css("width", px(node.width));
1195
+ if (sized("height")) style.height = css("height", px(node.height));
1196
+ }
1197
+ /**
1198
+ * Whether a layer fills an axis by stretching, which a fixed CSS size would prevent: across a
1199
+ * flex parent, or either axis of a grid cell. Along a flex parent, fill is `flex-grow`, and the
1200
+ * size stays as its basis.
1201
+ */
1202
+ function stretches(node, parent, axis) {
1203
+ if (layoutSizingInParent(parent, node, axis === "width" ? "HORIZONTAL" : "VERTICAL") !== "FILL" || !parent) return false;
1204
+ if (parent.layoutMode === "GRID") return true;
1205
+ return axis !== (parent.layoutMode === "HORIZONTAL" ? "width" : "height");
1206
+ }
1207
+ /**
1208
+ * Place a layer at its coordinates when its parent does not lay it out: it is absolutely
1209
+ * positioned, or its parent frame has no auto layout. A frame without auto layout becomes the
1210
+ * containing block of the children it places.
1211
+ */
1212
+ function addPositioning(style, node, parent) {
1213
+ if (node.layoutPositioning === "ABSOLUTE" || parent !== void 0 && parent.type !== "CANVAS" && parent.layoutMode === "NONE") {
1214
+ style.position = "absolute";
1215
+ style.left = `${node.x}px`;
1216
+ style.top = `${node.y}px`;
1217
+ } else if (node.layoutMode === "NONE" && node.type !== "TEXT" && node.childIds.length > 0) style.position = "relative";
1218
+ }
1219
+ function addSizeConstraints(style, node, css) {
1220
+ if (node.minWidth !== null) style["min-width"] = css("minWidth", px(node.minWidth));
1221
+ if (node.maxWidth !== null) style["max-width"] = css("maxWidth", px(node.maxWidth));
1222
+ if (node.minHeight !== null) style["min-height"] = css("minHeight", px(node.minHeight));
1223
+ if (node.maxHeight !== null) style["max-height"] = css("maxHeight", px(node.maxHeight));
1224
+ }
1225
+ function addCornerRadii(style, node, css) {
1226
+ if (node.type === "ELLIPSE") {
1227
+ style["border-radius"] = "50%";
1228
+ return;
1229
+ }
1230
+ if (node.independentCorners) {
1231
+ const corners = [
1232
+ [
1233
+ "border-top-left-radius",
1234
+ "topLeftRadius",
1235
+ node.topLeftRadius
1236
+ ],
1237
+ [
1238
+ "border-top-right-radius",
1239
+ "topRightRadius",
1240
+ node.topRightRadius
1241
+ ],
1242
+ [
1243
+ "border-bottom-right-radius",
1244
+ "bottomRightRadius",
1245
+ node.bottomRightRadius
1246
+ ],
1247
+ [
1248
+ "border-bottom-left-radius",
1249
+ "bottomLeftRadius",
1250
+ node.bottomLeftRadius
1251
+ ]
1252
+ ];
1253
+ for (const [property, field, radius] of corners) if (radius > 0) style[property] = css(field, px(radius));
1254
+ return;
1255
+ }
1256
+ if (node.cornerRadius > 0) style["border-radius"] = css("cornerRadius", px(node.cornerRadius));
1257
+ }
1258
+ function addStroke(style, node, css) {
1259
+ const stroke = node.strokes.at(0);
1260
+ const literalColor = strokeColorToCSS(stroke);
1261
+ if (!literalColor || !stroke) return;
1262
+ const color = css("strokes/0/color", literalColor);
1263
+ const borderStyle = node.dashPattern.length > 0 ? "dashed" : "solid";
1264
+ if (!node.independentStrokeWeights) {
1265
+ style.border = `${css("strokeWeight", px(stroke.weight))} solid ${color}`;
1266
+ if (borderStyle !== "solid") style["border-style"] = borderStyle;
1267
+ return;
1268
+ }
1269
+ style["border-style"] = borderStyle;
1270
+ style["border-color"] = color;
1271
+ style["border-top-width"] = css("borderTopWeight", px(node.borderTopWeight));
1272
+ style["border-right-width"] = css("borderRightWeight", px(node.borderRightWeight));
1273
+ style["border-bottom-width"] = css("borderBottomWeight", px(node.borderBottomWeight));
1274
+ style["border-left-width"] = css("borderLeftWeight", px(node.borderLeftWeight));
1275
+ }
1276
+ const PADDING_FIELDS = [
1277
+ "paddingTop",
1278
+ "paddingRight",
1279
+ "paddingBottom",
1280
+ "paddingLeft"
1281
+ ];
1282
+ /** Sides compare by their CSS, so a token and a literal of the same size stay separate. */
1283
+ function addPadding(style, node, css) {
1284
+ const [top, right, bottom, left] = PADDING_FIELDS.map((field) => css(field, px(node[field])));
1285
+ const zero = px(0);
1286
+ if ([
1287
+ top,
1288
+ right,
1289
+ bottom,
1290
+ left
1291
+ ].every((value) => value === zero)) return;
1292
+ if (top === right && right === bottom && bottom === left) {
1293
+ style.padding = top;
1294
+ return;
1295
+ }
1296
+ if (top === bottom && right === left) {
1297
+ if (top !== zero) style["padding-block"] = top;
1298
+ if (right !== zero) style["padding-inline"] = right;
1299
+ return;
1300
+ }
1301
+ if (top !== zero) style["padding-top"] = top;
1302
+ if (right !== zero) style["padding-right"] = right;
1303
+ if (bottom !== zero) style["padding-bottom"] = bottom;
1304
+ if (left !== zero) style["padding-left"] = left;
1305
+ }
1306
+ function addFlexGap(style, node, css) {
1307
+ if (node.itemSpacing <= 0 && node.counterAxisSpacing <= 0) return;
1308
+ const item = css("itemSpacing", px(node.itemSpacing));
1309
+ if (node.counterAxisSpacing <= 0) {
1310
+ style.gap = item;
1311
+ return;
1312
+ }
1313
+ const counter = css("counterAxisSpacing", px(node.counterAxisSpacing));
1314
+ if (node.layoutMode === "HORIZONTAL") {
1315
+ if (node.itemSpacing > 0) style["column-gap"] = item;
1316
+ style["row-gap"] = counter;
1317
+ return;
1318
+ }
1319
+ if (node.itemSpacing > 0) style["row-gap"] = item;
1320
+ style["column-gap"] = counter;
1321
+ }
1322
+ /** Image bytes as a data URL of the type they are encoded in. */
1323
+ function imageDataURL(bytes) {
1324
+ return `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`;
1325
+ }
1326
+ /**
1327
+ * The shader a layer's fill draws, which the projection keeps as the shader rather than the
1328
+ * image of its still frame: the shader of its first fill, as the projection reads one fill.
1329
+ */
1330
+ function layerShader(graph, node) {
1331
+ const fill = node.fills.at(0);
1332
+ const shader = fill?.visible ? shaderOfPaint(node, fill) : null;
1333
+ if (!shader || !isShaderPresetPaint(shader)) return void 0;
1334
+ const bytes = graph.images.get(shader.image);
1335
+ const frame = bytes ? imageDataURL(bytes) : void 0;
1336
+ return {
1337
+ preset: shader.preset,
1338
+ frame
1339
+ };
1340
+ }
1341
+ const POSITIONED = /* @__PURE__ */ new Set([
1342
+ "relative",
1343
+ "absolute",
1344
+ "fixed",
1345
+ "sticky"
1346
+ ]);
1347
+ /** Whether a `position` value makes an element the containing block of what it places. */
1348
+ function isPositioned(position) {
1349
+ return typeof position === "string" && POSITIONED.has(position);
1350
+ }
1351
+ /** A shader layer contains what plays behind its content, beneath everything it holds. */
1352
+ function addShaderLayerStyle(style) {
1353
+ if (!isPositioned(style.position)) style.position = "relative";
1354
+ style.isolation = "isolate";
1355
+ }
1356
+ function addImageStyle(style, node) {
1357
+ const fill = node.fills.at(0);
1358
+ if (fill?.type !== "IMAGE" || !fill.visible || shaderOfPaint(node, fill)) return;
1359
+ if (node.width > 0 && node.height > 0) style["aspect-ratio"] = `${node.width} / ${node.height}`;
1360
+ if (fill.imageScaleMode === "FIT") style["object-fit"] = "contain";
1361
+ if (fill.imageScaleMode === "FILL") style["object-fit"] = "cover";
1362
+ }
1363
+ /** Styles a node takes from its parent's layout, and its own rotation. */
1364
+ function addLayoutChild(style, node, parent) {
1365
+ if (parent?.layoutMode === "GRID") addGridPlacement(style, node);
1366
+ else if (parent && parent.layoutMode !== "NONE" && node.layoutGrow > 0) style["flex-grow"] = "1";
1367
+ if (node.rotation !== 0) style.transform = `rotate(${node.rotation}deg)`;
1368
+ }
1369
+ const SIZE_PROPERTIES = [
1370
+ "width",
1371
+ "height",
1372
+ "min-width",
1373
+ "max-width",
1374
+ "min-height",
1375
+ "max-height"
1376
+ ];
1377
+ /**
1378
+ * A layer's size includes its padding and stroke, as auto layout measures it. CSS sizes the
1379
+ * content box unless told otherwise, so a sized box with padding or a border says so.
1380
+ */
1381
+ function addBoxSizing(style) {
1382
+ const sized = SIZE_PROPERTIES.some((property) => Object.hasOwn(style, property));
1383
+ const boxed = Object.keys(style).some((property) => property.startsWith("padding") || property.startsWith("border") && !property.endsWith("radius"));
1384
+ if (sized && boxed) style["box-sizing"] = "border-box";
1385
+ }
1386
+ function styleFromSceneNode(node, parent, css) {
1387
+ const style = {};
1388
+ addSize(style, node, parent, css);
1389
+ addPositioning(style, node, parent);
1390
+ addSizeConstraints(style, node, css);
1391
+ const fill = fillToCSS(node.fills.at(0));
1392
+ if (fill) style["background-color"] = css("fills/0/color", fill);
1393
+ addImageStyle(style, node);
1394
+ addStroke(style, node, css);
1395
+ Object.assign(style, effectsToCSS(node.effects));
1396
+ if (node.opacity < 1) style.opacity = css("opacity", String(node.opacity));
1397
+ addCornerRadii(style, node, css);
1398
+ if (node.clipsContent) style.overflow = "hidden";
1399
+ const alignSelf = alignToCSS(node.layoutAlignSelf);
1400
+ if (alignSelf) style["align-self"] = alignSelf;
1401
+ addLayoutChild(style, node, parent);
1402
+ if (node.layoutDirection === "RTL") style.direction = "rtl";
1403
+ if (node.layoutMode === "GRID") {
1404
+ addGridContainer(style, node, css);
1405
+ addPadding(style, node, css);
1406
+ } else if (node.layoutMode !== "NONE") {
1407
+ style.display = "flex";
1408
+ if (node.layoutMode === "VERTICAL") style["flex-direction"] = "column";
1409
+ const justifyContent = justifyContentToCSS(node.primaryAxisAlign);
1410
+ const alignItems = alignToCSS(node.counterAxisAlign);
1411
+ if (justifyContent) style["justify-content"] = justifyContent;
1412
+ if (alignItems) style["align-items"] = alignItems;
1413
+ if (node.layoutWrap === "WRAP") style["flex-wrap"] = "wrap";
1414
+ addFlexGap(style, node, css);
1415
+ addPadding(style, node, css);
1416
+ }
1417
+ addBoxSizing(style);
1418
+ return style;
1419
+ }
1420
+ function styleFromTextNode(node, parent, css) {
1421
+ const style = {};
1422
+ addSize(style, node, parent, css);
1423
+ addPositioning(style, node, parent);
1424
+ addLayoutChild(style, node, parent);
1425
+ if (resolveNodeTextDirection(node) === "RTL") style.direction = "rtl";
1426
+ const color = fillToCSS(node.fills.at(0));
1427
+ style.color = color ? css("fills/0/color", color) : cssColor(BLACK);
1428
+ style["font-family"] = node.fontFamily;
1429
+ style["font-size"] = css("fontSize", px(node.fontSize));
1430
+ style["font-weight"] = String(node.fontWeight);
1431
+ if (node.italic) style["font-style"] = "italic";
1432
+ if (node.lineHeight !== null) style["line-height"] = css("lineHeight", lineHeightToCSS(node.lineHeight));
1433
+ if (node.letterSpacing.value !== 0) style["letter-spacing"] = css("letterSpacing", letterSpacingToCSS(node.letterSpacing));
1434
+ if (node.textAlignHorizontal !== "LEFT") style["text-align"] = node.textAlignHorizontal.toLowerCase();
1435
+ if (node.opacity < 1) style.opacity = css("opacity", String(node.opacity));
1436
+ const shadow = dropShadowToCSS(node.effects[0]);
1437
+ if (shadow) style["text-shadow"] = shadow;
1438
+ if (node.textDecoration !== "NONE") style["text-decoration-line"] = node.textDecoration === "UNDERLINE" ? "underline" : "line-through";
1439
+ const textTransform = textCaseToCSS(node.textCase);
1440
+ if (textTransform) style["text-transform"] = textTransform;
1441
+ style["white-space"] = node.maxLines === 1 ? "nowrap" : "pre-wrap";
1442
+ return style;
1443
+ }
1444
+ function imageSourceURL(node) {
1445
+ return node.pluginData.find((entry) => entry.pluginId === DOM_CSS_PLUGIN_ID && entry.key === IMAGE_SOURCE_URL_KEY)?.value;
1446
+ }
1447
+ /** A layer's name, unless it only repeats the layer's type. */
1448
+ function ownLayerName(node) {
1449
+ return node.name && node.name !== node.type ? node.name : void 0;
1450
+ }
1451
+ function attrsForNode(graph, node, { includeSourceIds, includeLayerNames }) {
1452
+ const attrs = {};
1453
+ const name = includeLayerNames ? ownLayerName(node) : void 0;
1454
+ if (name) attrs["data-name"] = name;
1455
+ if (includeSourceIds) attrs["data-pairdraw-node-id"] = node.id;
1456
+ const sourceURL = imageSourceURL(node);
1457
+ if (sourceURL) attrs.src = sourceURL;
1458
+ const fill = node.fills.at(0);
1459
+ if (fill?.type !== "IMAGE" || !fill.imageHash || shaderOfPaint(node, fill)) return attrs;
1460
+ const bytes = graph.images.get(fill.imageHash);
1461
+ if (!bytes) return attrs;
1462
+ return {
1463
+ ...attrs,
1464
+ src: imageDataURL(bytes)
1465
+ };
1466
+ }
1467
+ function tagNameForNode(node) {
1468
+ if (node.type === "SECTION") return "section";
1469
+ const fill = node.fills.at(0);
1470
+ if ((fill?.type === "IMAGE" && !shaderOfPaint(node, fill) || imageSourceURL(node)) && node.childIds.length === 0) return "img";
1471
+ return "div";
1472
+ }
1473
+ /**
1474
+ * A vector layer as the renderer's `<svg>`, placed where the layer's box would be: its
1475
+ * position, size, opacity, and transform stay, and its paint is the SVG's, not the box's.
1476
+ */
1477
+ function vectorDesignNode(context, node, attrs, style) {
1478
+ const drawn = context.vectorElement?.(context.graph, node);
1479
+ if (!drawn) return null;
1480
+ const placement = Object.fromEntries(Object.entries(style).filter(([property]) => !BOX_PAINT.test(property)));
1481
+ return {
1482
+ ...drawn,
1483
+ attrs: {
1484
+ ...drawn.attrs,
1485
+ ...attrs
1486
+ },
1487
+ inlineStyle: {
1488
+ ...drawn.inlineStyle,
1489
+ ...placement
1490
+ },
1491
+ sourceSceneNodeId: node.id,
1492
+ sourceSceneNode: node
1493
+ };
1494
+ }
1495
+ function sceneNodeToDesignNode(context, node, inherited, root) {
1496
+ if (!node.visible && !context.shown?.has(node.id) || node.internalOnly) return null;
1497
+ const { graph, tokens } = context;
1498
+ const parent = node.parentId ? graph.getNode(node.parentId) : void 0;
1499
+ const entered = tokens?.enter(node, inherited, root);
1500
+ const modes = entered?.modes ?? inherited;
1501
+ const attrs = {
1502
+ ...attrsForNode(graph, node, context),
1503
+ ...entered?.attrs
1504
+ };
1505
+ const css = (field, literal) => tokens?.reference(node, field, modes) ?? literal;
1506
+ if (node.type === "TEXT") {
1507
+ const content = textElementContent(node, styleFromTextNode(node, parent, css));
1508
+ return {
1509
+ type: "element",
1510
+ tagName: content.tagName,
1511
+ attrs,
1512
+ inlineStyle: content.style,
1513
+ sourceSceneNodeId: node.id,
1514
+ sourceSceneNode: node,
1515
+ children: content.children
1516
+ };
1517
+ }
1518
+ if (VECTOR_SHAPES.has(node.type) || readIcon(node)) {
1519
+ const vector = vectorDesignNode(context, node, attrs, styleFromSceneNode(node, parent, css));
1520
+ if (vector) return vector;
1521
+ }
1522
+ const children = nodeChildren(graph, node).map((child) => sceneNodeToDesignNode(context, child, modes, false)).filter((child) => child !== null);
1523
+ if (node.type === "CANVAS") return {
1524
+ type: "element",
1525
+ tagName: "main",
1526
+ attrs,
1527
+ sourceSceneNodeId: node.id,
1528
+ sourceSceneNode: node,
1529
+ children
1530
+ };
1531
+ const style = styleFromSceneNode(node, parent, css);
1532
+ const shader = layerShader(graph, node);
1533
+ if (shader) addShaderLayerStyle(style);
1534
+ return {
1535
+ type: "element",
1536
+ tagName: tagNameForNode(node),
1537
+ attrs,
1538
+ inlineStyle: style,
1539
+ sourceSceneNodeId: node.id,
1540
+ sourceSceneNode: node,
1541
+ children,
1542
+ shader
1543
+ };
1544
+ }
1545
+ function projectionContext(graph, { includeSourceIds = true, includeLayerNames = false, tokens = true, vectorElement, shown }) {
1546
+ return {
1547
+ graph,
1548
+ includeSourceIds,
1549
+ includeLayerNames,
1550
+ tokens: tokens ? new DesignTokens(graph) : void 0,
1551
+ vectorElement,
1552
+ shown
1553
+ };
1554
+ }
1555
+ function sceneGraphToDesignDocument(graph, options = {}) {
1556
+ const root = graph.getNode(options.rootId ?? graph.rootId);
1557
+ const context = projectionContext(graph, options);
1558
+ const modes = context.tokens?.defaultModes() ?? /* @__PURE__ */ new Map();
1559
+ const children = root ? nodeChildren(graph, root).map((child) => sceneNodeToDesignNode(context, child, modes, true)).filter((child) => child !== null) : [];
1560
+ return {
1561
+ type: "document",
1562
+ sourceGraph: graph,
1563
+ tokens: context.tokens,
1564
+ children
1565
+ };
1566
+ }
1567
+ /** Project one node, including its own box, instead of the children of a root. */
1568
+ function sceneNodeToDesignDocument(graph, nodeId, options = {}) {
1569
+ const node = graph.getNode(nodeId);
1570
+ const context = projectionContext(graph, options);
1571
+ const modes = context.tokens?.defaultModes() ?? /* @__PURE__ */ new Map();
1572
+ const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null;
1573
+ return {
1574
+ type: "document",
1575
+ sourceGraph: graph,
1576
+ tokens: context.tokens,
1577
+ children: projected ? [projected] : []
1578
+ };
1579
+ }
1580
+ //#endregion
1581
+ //#region src/behaviours/states/layers.ts
1582
+ /** Where the set places a variant, which is not the component's own style. */
1583
+ const PLACEMENT = [
1584
+ "position",
1585
+ "left",
1586
+ "top",
1587
+ "right",
1588
+ "bottom",
1589
+ "inset"
1590
+ ];
1591
+ function textContent(element) {
1592
+ const texts = element.children.filter((child) => child.type === "text");
1593
+ return texts.length > 0 ? texts.map((text) => text.text).join("") : null;
1594
+ }
1595
+ /**
1596
+ * What a layer draws other than its own box: an instance of a component (of any of its set's
1597
+ * variants), or an icon. Undefined for any other layer.
1598
+ */
1599
+ function layerKind(graph, node) {
1600
+ if (!node) return void 0;
1601
+ if (node.type === "INSTANCE") {
1602
+ const main = instanceMainComponent(graph, node);
1603
+ return `instance ${(main && behaviourOwner(graph, main))?.id ?? ""}`;
1604
+ }
1605
+ const icon = readIcon(node);
1606
+ return icon ? `icon ${icon.name}` : void 0;
1607
+ }
1608
+ function variantLayer(graph, variant, node, parentKey, index) {
1609
+ if (node.type === "text") return node;
1610
+ const source = node.sourceSceneNodeId;
1611
+ const path = source ? layerPath(graph, variant.id, source) : `${parentKey}/~${index}`;
1612
+ const text = textContent(node);
1613
+ const kind = layerKind(graph, node.sourceSceneNode);
1614
+ const key = [
1615
+ path,
1616
+ ...kind ? [kind] : [],
1617
+ ...text === null ? [] : [text]
1618
+ ].join("\0");
1619
+ return {
1620
+ type: "element",
1621
+ key,
1622
+ kind,
1623
+ name: node.sourceSceneNode?.name ?? node.tagName,
1624
+ element: node,
1625
+ children: node.children.map((child, i) => variantLayer(graph, variant, child, key, i))
1626
+ };
1627
+ }
1628
+ /**
1629
+ * The tab panels a variant draws hidden behind the first. The generated tabs show each when its
1630
+ * tab is chosen, so they are projected as drawn.
1631
+ */
1632
+ function tabPanels(graph, variant) {
1633
+ const owner = behaviourOwner(graph, variant);
1634
+ const behaviour = owner && readBehaviour(owner);
1635
+ const propertyId = behaviour?.kind === "tabs" ? partBinding(behaviour, "panels") : void 0;
1636
+ const panels = propertyId ? instanceSlotFrames(graph, variant).find((frame) => slotPropertyId(frame) === propertyId) : void 0;
1637
+ return new Set(panels?.childIds);
1638
+ }
1639
+ /**
1640
+ * The layers of a variant a boolean property shows or hides, which are projected however the
1641
+ * variant draws them, since the generated component shows them from its prop.
1642
+ */
1643
+ function visibilityBound(graph, variant) {
1644
+ const bound = /* @__PURE__ */ new Set();
1645
+ const visit = (node) => {
1646
+ for (const child of graph.getChildren(node.id)) {
1647
+ if (child.componentPropertyReferences.some((item) => item.field === "VISIBLE")) bound.add(child.id);
1648
+ if (child.type !== "INSTANCE") visit(child);
1649
+ }
1650
+ };
1651
+ visit(variant);
1652
+ return bound;
1653
+ }
1654
+ /** A variant projected to DOM, without where the set places it. */
1655
+ function projectVariant(graph, variant, { vectorElement } = {}) {
1656
+ const root = sceneNodeToDesignDocument(graph, variant.id, {
1657
+ includeSourceIds: false,
1658
+ vectorElement,
1659
+ shown: /* @__PURE__ */ new Set([...tabPanels(graph, variant), ...visibilityBound(graph, variant)])
1660
+ }).children.at(0);
1661
+ if (root?.type !== "element") return null;
1662
+ const style = root.inlineStyle ?? {};
1663
+ root.inlineStyle = {
1664
+ ...omit(style, PLACEMENT),
1665
+ ...style.position ? { position: "relative" } : {}
1666
+ };
1667
+ return {
1668
+ type: "element",
1669
+ key: "",
1670
+ kind: void 0,
1671
+ name: variant.name,
1672
+ element: root,
1673
+ children: root.children.map((child, i) => variantLayer(graph, variant, child, "", i))
1674
+ };
1675
+ }
1676
+ /** Every layer of a projected variant by key. */
1677
+ function layersByKey(root, into = /* @__PURE__ */ new Map()) {
1678
+ into.set(root.key, root);
1679
+ for (const child of root.children) if (child.type === "element") layersByKey(child, into);
1680
+ return into;
1681
+ }
1682
+ /** A merged layer starting from a variant's layer, with that layer's style as its base. */
1683
+ function stateElement(layer) {
1684
+ return {
1685
+ type: "element",
1686
+ key: layer.key,
1687
+ kind: layer.kind,
1688
+ name: layer.name,
1689
+ tagName: layer.element.tagName,
1690
+ attrs: { ...layer.element.attrs },
1691
+ base: { ...layer.element.inlineStyle },
1692
+ rules: [],
1693
+ shader: layer.element.shader,
1694
+ children: layer.children.map((child) => child.type === "text" ? child : stateElement(child))
1695
+ };
1696
+ }
1697
+ function hideAtRest(element, hidden) {
1698
+ element.base = {
1699
+ ...element.base,
1700
+ display: "none"
1701
+ };
1702
+ hidden.add(element);
1703
+ for (const child of element.children) if (child.type === "element") hideAtRest(child, hidden);
1704
+ }
1705
+ /**
1706
+ * Adds the layers only `variant` draws to the merged tree, after the sibling they follow
1707
+ * there. Each keeps the style this variant draws it with, hidden at rest, and is recorded in
1708
+ * `hidden` so the variants that draw it show it again.
1709
+ */
1710
+ function mergeVariant(into, variant, hidden) {
1711
+ let previous = -1;
1712
+ for (const child of variant.children) {
1713
+ if (child.type === "text") continue;
1714
+ const index = into.children.findIndex((item) => item.type === "element" && item.key === child.key);
1715
+ const existing = into.children.at(index);
1716
+ if (index !== -1 && existing?.type === "element") {
1717
+ mergeVariant(existing, child, hidden);
1718
+ previous = index;
1719
+ continue;
1720
+ }
1721
+ const added = stateElement(child);
1722
+ hideAtRest(added, hidden);
1723
+ previous += 1;
1724
+ into.children.splice(previous, 0, added);
1725
+ }
1726
+ }
1727
+ /** Every element of the merged tree, root first. */
1728
+ function allElements(root, into = []) {
1729
+ into.push(root);
1730
+ for (const child of root.children) if (child.type === "element") allElements(child, into);
1731
+ return into;
1732
+ }
1733
+ //#endregion
1734
+ export { PLACEMENT, TOKEN_UNIT_PROPERTY, allElements, buildTokenStylesheet, collectionVariables, createTokenValidator, cssNameCodeSyntax, cssNameVariableName, defaultModeAttributeName, defaultModeCondition, deriveCSSName, explicitCSSName, isPositioned, layerKind, layersByKey, loadTokenValidator, mergeVariant, modeAttribute, ownLayerName, parseCSSName, projectVariant, sceneGraphToDesignDocument, sceneNodeToDesignDocument, stateElement, tokenNumberToCSS, tokenSlug, tokenStylesheet, variableCSSNames, variableNamespace, variableUnit };
1735
+
1736
+ //# sourceMappingURL=layers.js.map