@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,1594 @@
1
+ import { allElements, isPositioned } from "../../behaviours/states/layers.js";
2
+ import { serializeHTML, serializedElements, stateStylesToTailwind, stateTailwindClasses } from "../../behaviours/states/tailwind.js";
3
+ import { extractImageAssets } from "../bundle.js";
4
+ import { behaviourArgs } from "../../behaviours/args.js";
5
+ import { BUTTON_RESET, HEADING_RESET } from "../../behaviours/reset.js";
6
+ import { ownerVariants, restLayerOf, stateStyles } from "../../behaviours/states/model.js";
7
+ import { claimName, identifierName, layerClassNames, propAttribute, stateStylesToCSS } from "../../behaviours/states/css.js";
8
+ import { blockRoot, freePlacedParts, inputLayers, inputValue, numberInput, progressWidth, rangeModel, textModel } from "./fields.js";
9
+ import { GROUP_ITEMS, activeTriggers, groupItems, isGroup, referencedLayers, tabParts } from "./groups.js";
10
+ import { drawingImports, iconDrawing, iconImportDeclarations, iconNamer } from "./icons.js";
11
+ import { isShaderPresetPaint, shaderOfPaint } from "@pairdraw/scene-graph/shaders";
12
+ import { compact, uniq, zip } from "es-toolkit/array";
13
+ import { omit } from "es-toolkit/object";
14
+ import { behaviourContract, behaviourProperties, findLayerByPath, layerPath, readBehaviour, textBinding } from "@pairdraw/scene-graph/behaviours";
15
+ import { slotPropertyId } from "@pairdraw/scene-graph/slots";
16
+ import { variantDefaultValue } from "@pairdraw/scene-graph/components";
17
+ import { camelCase, kebabCase, upperFirst } from "es-toolkit/string";
18
+ import { es, jsx, vue } from "@pairdraw/emit";
19
+ import dedent from "dedent";
20
+ //#region src/export/components/properties.ts
21
+ /**
22
+ * The layers bound to a property through `field`, each with the prop it draws. A layer is
23
+ * bound when it is in any variant, found by the path every variant shares.
24
+ */
25
+ function boundLayers(graph, set, elements, field, props) {
26
+ const variants = ownerVariants(graph, set);
27
+ const bound = /* @__PURE__ */ new Map();
28
+ for (const element of elements) {
29
+ const path = element.key.split("\0")[0] ?? "";
30
+ for (const variant of variants) {
31
+ const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find((item) => item.field === field);
32
+ const prop = reference && props.get(reference.propertyId);
33
+ if (prop) {
34
+ bound.set(element, prop);
35
+ break;
36
+ }
37
+ }
38
+ }
39
+ return bound;
40
+ }
41
+ const propName = (property, taken, fallback) => claimName(camelCase(identifierName(property, fallback)), taken);
42
+ /** The set's boolean properties as props, and the layers each shows while it is on. */
43
+ function booleanProps(graph, set, elements, taken) {
44
+ const booleans = behaviourProperties(graph, set).filter((definition) => definition.type === "BOOLEAN").map((definition) => ({
45
+ name: propName(definition.name, taken, "Shown"),
46
+ id: definition.id,
47
+ property: definition.name,
48
+ default: definition.defaultValue === "true"
49
+ }));
50
+ return {
51
+ booleans,
52
+ shownBy: boundLayers(graph, set, elements, "VISIBLE", new Map(booleans.map((prop) => [prop.id, prop.name])))
53
+ };
54
+ }
55
+ /**
56
+ * The set's slot properties as props, and the frame each fills, except frames a behaviour
57
+ * draws its parts in, such as a switch's thumb, which stay its parts.
58
+ */
59
+ function slotProps(graph, set, elements, taken, parts) {
60
+ const definitions = behaviourProperties(graph, set).filter((definition) => definition.type === "SLOT");
61
+ const frames = elements.filter((element) => !parts.has(element));
62
+ const slots = definitions.map((definition) => ({
63
+ name: propName(definition.name, taken, "Content"),
64
+ id: definition.id,
65
+ property: definition.name
66
+ }));
67
+ const slotOf = boundLayers(graph, set, frames, "SLOT_CONTENT", new Map(slots.map((prop) => [prop.id, prop.name])));
68
+ const drawn = new Set(slotOf.values());
69
+ return {
70
+ slots: slots.filter((slot) => drawn.has(slot.name)),
71
+ slotOf
72
+ };
73
+ }
74
+ /**
75
+ * The set's text properties as props, and the layers bound to each. A layer is bound when it
76
+ * is in any variant, found by the path every variant shares.
77
+ */
78
+ function textProps(graph, set, elements, taken, input) {
79
+ const definitions = behaviourProperties(graph, set).filter((item) => item.type === "TEXT" && item.id !== input);
80
+ const texts = definitions.map((definition) => ({
81
+ name: claimName(camelCase(identifierName(definition.name, "Text")), taken),
82
+ id: definition.id,
83
+ property: definition.name,
84
+ default: definition.defaultValue
85
+ }));
86
+ const byId = new Map(definitions.map((definition, i) => [definition.id, texts[i]]));
87
+ const variants = ownerVariants(graph, set);
88
+ const bound = /* @__PURE__ */ new Map();
89
+ const inputs = [];
90
+ for (const element of elements) {
91
+ const path = element.key.split("\0")[0] ?? "";
92
+ for (const variant of variants) {
93
+ const reference = findLayerByPath(graph, variant.id, path)?.componentPropertyReferences.find((item) => item.field === "TEXT");
94
+ if (reference && reference.propertyId === input) {
95
+ inputs.push(element);
96
+ break;
97
+ }
98
+ const prop = reference && byId.get(reference.propertyId);
99
+ if (prop) {
100
+ bound.set(element, prop.name);
101
+ break;
102
+ }
103
+ }
104
+ }
105
+ return {
106
+ texts,
107
+ bound,
108
+ input: inputs
109
+ };
110
+ }
111
+ //#endregion
112
+ //#region src/export/components/shaders.ts
113
+ function shaderLayer(node, className, preset) {
114
+ if (!preset) return void 0;
115
+ const position = node.base.position;
116
+ return {
117
+ preset,
118
+ className: `${className}-shader`,
119
+ positioned: isPositioned(position)
120
+ };
121
+ }
122
+ /**
123
+ * The shader each element's layer fills with in the rest variant: the topmost visible shader
124
+ * fill, which the component plays behind the layer's content.
125
+ */
126
+ function shaderLayers(graph, restId, elements) {
127
+ const shaders = /* @__PURE__ */ new Map();
128
+ for (const element of elements) {
129
+ const layer = findLayerByPath(graph, restId, element.key.split("\0")[0] ?? "");
130
+ if (!layer) continue;
131
+ const shader = layer.fills.filter((fill) => fill.visible).map((fill) => shaderOfPaint(layer, fill)).findLast((found) => found !== null && isShaderPresetPaint(found));
132
+ if (shader) shaders.set(element, shader.preset);
133
+ }
134
+ return shaders;
135
+ }
136
+ /** Whether an effect's name can be imported, as every effect the library has can. */
137
+ const isEffectName = (type) => es.isIdentifierName(type);
138
+ /** The effects of `components` a generated component draws: those it can import by name. */
139
+ const drawnEffects = (components) => (components ?? []).filter((component) => isEffectName(component.type));
140
+ /**
141
+ * `import { Shader as ShaderCanvas, Aurora as ShaderAurora } from 'shaders/vue'`: the canvas and
142
+ * effects a component draws, under names apart from its own.
143
+ */
144
+ function shaderImport(source, effects) {
145
+ return {
146
+ type: "ImportDeclaration",
147
+ importKind: "value",
148
+ specifiers: ["Shader", ...[...effects].sort()].map((name) => ({
149
+ type: "ImportSpecifier",
150
+ imported: es.identifier(name),
151
+ local: es.identifier(name === "Shader" ? SHADER_CANVAS : shaderEffectName(name))
152
+ })),
153
+ source: es.string(source)
154
+ };
155
+ }
156
+ /** The local name a generated component imports effect `type` as, apart from its own names. */
157
+ const shaderEffectName = (type) => `Shader${type}`;
158
+ /** An effect's props as JSX attributes: strings as they are, anything else as JSON. */
159
+ function shaderEffectAttributes(component) {
160
+ return Object.entries(component.props ?? {}).map(([key, value]) => jsx.attribute(key, typeof value === "string" ? jsx.stringValue(value) : jsx.container(es.json(value))));
161
+ }
162
+ /** The local name of the library's `Shader` canvas. */
163
+ const SHADER_CANVAS = "ShaderCanvas";
164
+ /** The elements of a component's tree that fill with a shader. */
165
+ function shaderElements(node) {
166
+ if (node.type !== "element") return [];
167
+ return [...node.shader ? [node] : [], ...node.children.flatMap(shaderElements)];
168
+ }
169
+ /**
170
+ * The style that puts each shader behind its layer's content: the layer becomes its own
171
+ * stacking context, positioned if it is not already, and the shader fills it beneath
172
+ * everything it holds, clipped to its corners.
173
+ */
174
+ function shaderCSS(tree) {
175
+ return shaderElements(tree).flatMap(({ className, shader }) => shader ? [`.${className} { isolation: isolate;${shader.positioned ? "" : " position: relative;"} }`, `.${shader.className} { position: absolute; inset: 0; z-index: -1; border-radius: inherit; overflow: hidden; pointer-events: none; }`] : []).join("\n");
176
+ }
177
+ //#endregion
178
+ //#region src/export/components/tree.ts
179
+ function componentTree(node, labels, bindings) {
180
+ const repeated = labels.repeated.get(node);
181
+ const layerId = labels.layerOf(node);
182
+ const part = repeated?.part ?? labels.parts.get(node) ?? null;
183
+ const text = labels.texts.get(node);
184
+ const className = labels.classes.get(node) ?? "";
185
+ return {
186
+ type: "element",
187
+ part,
188
+ ...repeated ? { value: repeated.value } : {},
189
+ tag: node.tagName,
190
+ className,
191
+ layerId,
192
+ attrs: node.attrs,
193
+ bindings: part === "root" ? bindings : [],
194
+ shownBy: labels.shownBy.get(node),
195
+ slot: labels.slotOf.get(node),
196
+ shader: shaderLayer(node, className, labels.shaders.get(node)),
197
+ children: text ? [{
198
+ type: "textProp",
199
+ name: text
200
+ }] : node.children.flatMap((child) => child.type === "text" ? [{
201
+ type: "text",
202
+ value: child.text
203
+ }] : childNode(child, labels))
204
+ };
205
+ }
206
+ function childNode(element, labels) {
207
+ const className = labels.classes.get(element) ?? "";
208
+ const layerId = labels.layerOf(element);
209
+ if (labels.input?.element === element) return [{
210
+ type: "input",
211
+ className,
212
+ layerId
213
+ }];
214
+ if (labels.input?.replaced.includes(element)) return [];
215
+ const used = labels.used.get(element);
216
+ if (!used) return [componentTree(element, labels, [])];
217
+ return [{
218
+ ...used,
219
+ className,
220
+ layerId
221
+ }];
222
+ }
223
+ //#endregion
224
+ //#region src/export/components/model.ts
225
+ /** Kinds generated as components so far; the rest keep static stories. */
226
+ const GENERATED_KINDS = [
227
+ "button",
228
+ "switch",
229
+ "checkbox",
230
+ "toggle",
231
+ "collapsible",
232
+ "tabs",
233
+ "radioGroup",
234
+ "toggleGroup",
235
+ "accordion",
236
+ "slider",
237
+ "progress",
238
+ "numberField",
239
+ "textField",
240
+ "textarea"
241
+ ];
242
+ /** Parts each kind renders as a native button, which the reset clears for the design. */
243
+ const BUTTON_PARTS = {
244
+ button: ["root"],
245
+ switch: ["root"],
246
+ checkbox: ["root"],
247
+ toggle: ["root"],
248
+ collapsible: ["trigger"],
249
+ tabs: ["trigger"],
250
+ radioGroup: [],
251
+ toggleGroup: [],
252
+ accordion: [],
253
+ slider: [],
254
+ progress: [],
255
+ numberField: ["increment", "decrement"],
256
+ textField: [],
257
+ textarea: [],
258
+ plain: [],
259
+ radioGroupItem: ["root"],
260
+ toggleGroupItem: ["root"],
261
+ accordionItem: ["trigger"]
262
+ };
263
+ const isGenerated = (kind) => GENERATED_KINDS.includes(kind);
264
+ /** What an owner generates as: a group's item when it is one, its own kind, or nothing. */
265
+ function generatedKind(kind, itemOf) {
266
+ if (itemOf) return GROUP_ITEMS[itemOf];
267
+ return isGenerated(kind) ? kind : null;
268
+ }
269
+ /** Layer paths of the slot frames that draw each part, the same in every variant. */
270
+ function partPaths(graph, set, behaviour) {
271
+ const partOfSlot = new Map(Object.entries(behaviour.parts).map(([part, slot]) => [slot, part]));
272
+ const paths = /* @__PURE__ */ new Map();
273
+ const visit = (variant, node) => {
274
+ const part = partOfSlot.get(slotPropertyId(node) ?? "");
275
+ if (part) paths.set(layerPath(graph, variant.id, node.id), part);
276
+ for (const child of graph.getChildren(node.id)) visit(variant, child);
277
+ };
278
+ for (const variant of ownerVariants(graph, set)) for (const child of graph.getChildren(variant.id)) visit(variant, child);
279
+ return paths;
280
+ }
281
+ /** Each layer's behaviour part: the root, and the slot frames that draw the others. */
282
+ function behaviourParts(graph, set, behaviour, root) {
283
+ const paths = partPaths(graph, set, behaviour);
284
+ const contract = behaviourContract(behaviour.kind).parts;
285
+ const parts = /* @__PURE__ */ new Map([[root, "root"]]);
286
+ for (const element of allElements(root)) {
287
+ const part = paths.get(element.key);
288
+ if (part && contract.some((item) => item.id === part)) parts.set(element, part);
289
+ }
290
+ return parts;
291
+ }
292
+ /** Clears the native button look from the parts a kind renders as buttons. */
293
+ function resetButtons(kind, parts, repeated) {
294
+ const all = [...parts, ...[...repeated].map(([element, item]) => [element, item.part])];
295
+ for (const [element, part] of all) if (BUTTON_PARTS[kind].includes(part)) element.base = {
296
+ ...BUTTON_RESET,
297
+ ...element.base
298
+ };
299
+ }
300
+ /** The variant properties that are not values or states, as props set as `data-*`. */
301
+ function variantProps(graph, set, args, taken) {
302
+ const bound = /* @__PURE__ */ new Set([
303
+ ...args.booleans.keys(),
304
+ args.states?.property,
305
+ args.filled?.property
306
+ ]);
307
+ return behaviourProperties(graph, set).filter((definition) => definition.type === "VARIANT" && !bound.has(definition.name)).map((definition) => ({
308
+ name: claimName(camelCase(identifierName(definition.name, "Prop")), taken),
309
+ property: definition.name,
310
+ options: uniq([...definition.variantOptions ?? [], ...ownerVariants(graph, set).map((variant) => variant.componentPropertyValues[definition.name] ?? "")]).filter((option) => option !== ""),
311
+ default: variantDefaultValue(graph, set, definition)
312
+ }));
313
+ }
314
+ /** What the root binds: its model, an item's value, `disabled`, and its variant props. */
315
+ function rootBindings(model, item, disabled, props) {
316
+ return [
317
+ ...model ? [{
318
+ type: "model",
319
+ name: model
320
+ }] : [],
321
+ ...item ? [{ type: "value" }] : [],
322
+ ...disabled ? [{ type: "disabled" }] : [],
323
+ ...props.map((prop) => ({
324
+ type: "prop",
325
+ prop,
326
+ attribute: propAttribute(prop.property)
327
+ }))
328
+ ];
329
+ }
330
+ /**
331
+ * A group's items, built as the group's item component; null for other owners and for a
332
+ * group's item itself.
333
+ */
334
+ function itemsOf(graph, behaviour, variantIds, parts, options, build) {
335
+ if (options.itemOf || !isGroup(behaviour.kind)) return null;
336
+ const itemsElement = [...parts].find(([, part]) => part === "items")?.[0];
337
+ return groupItems(graph, variantIds, itemsElement, build(behaviour.kind));
338
+ }
339
+ /**
340
+ * The value the component binds two ways: `value` when it chooses among options or holds a
341
+ * number or text, its boolean such as `checked`, or none for a group's item, which its group
342
+ * chooses.
343
+ */
344
+ function modelName(args, item, valued) {
345
+ if (valued) return "value";
346
+ if (item) return null;
347
+ return [...args.booleans.values()].find((arg) => arg.name !== "disabled")?.name ?? null;
348
+ }
349
+ /** Whether the set draws a disabled look, as a boolean or an interaction state. */
350
+ const drawsDisabled = (args) => [...args.booleans.values()].some((arg) => arg.name === "disabled") || args.states?.disabled !== void 0;
351
+ /** The layers used rather than drawn: a group's items, then other generated components. */
352
+ function usedLayers(graph, root, variantIds, items, references) {
353
+ const used = new Map(items);
354
+ if (references) for (const [element, layer] of referencedLayers(graph, root, variantIds, references, used)) used.set(element, layer);
355
+ return used;
356
+ }
357
+ /**
358
+ * Sizes the design gives include a layer's padding and border, which a component's own
359
+ * stylesheet has to say, since no page reset around it does. A root without a width hugs its
360
+ * content, as the design draws it.
361
+ */
362
+ function borderBoxes(root) {
363
+ if (!Object.hasOwn(root.base, "width")) root.base = {
364
+ ...root.base,
365
+ width: "fit-content"
366
+ };
367
+ for (const element of allElements(root)) {
368
+ const has = (property) => Object.hasOwn(element.base, property);
369
+ if ((has("width") || has("height")) && !has("box-sizing")) element.base = {
370
+ "box-sizing": "border-box",
371
+ ...element.base
372
+ };
373
+ }
374
+ }
375
+ /**
376
+ * Each layer's part, and tabs' triggers and panels, with the styles the generated parts need:
377
+ * native buttons cleared, the chosen tab's look, and moving parts free of their drawn place.
378
+ */
379
+ function drawnParts(graph, set, behaviour, kind, root) {
380
+ const parts = behaviour ? behaviourParts(graph, set, behaviour, root) : /* @__PURE__ */ new Map([[root, "root"]]);
381
+ const tabs = behaviour?.kind === "tabs" ? tabParts(parts) : null;
382
+ const repeated = tabs?.repeated ?? /* @__PURE__ */ new Map();
383
+ activeTriggers(repeated);
384
+ resetButtons(kind, parts, repeated);
385
+ freePlacedParts(kind, parts);
386
+ blockRoot(kind, root);
387
+ borderBoxes(root);
388
+ return {
389
+ parts,
390
+ tabs,
391
+ repeated
392
+ };
393
+ }
394
+ /** The number or text the component holds, and the text property a field's input shows. */
395
+ function valueModels(graph, set, kind, behaviour, args) {
396
+ if (!behaviour) return {
397
+ range: null,
398
+ text: null,
399
+ inputProperty: void 0
400
+ };
401
+ const valueText = inputValue(kind);
402
+ const inputProperty = valueText && textBinding(behaviour, valueText);
403
+ const definition = behaviourProperties(graph, set).find((item) => item.id === inputProperty);
404
+ return {
405
+ range: rangeModel(kind, behaviour),
406
+ text: textModel(kind, definition, args),
407
+ inputProperty
408
+ };
409
+ }
410
+ function componentModel(graph, set, options = {}) {
411
+ const behaviour = readBehaviour(set);
412
+ const kind = behaviour ? generatedKind(behaviour.kind, options.itemOf) : "plain";
413
+ const styles = kind ? stateStyles(graph, set, options) : null;
414
+ const args = behaviourArgs(graph, set) ?? { booleans: /* @__PURE__ */ new Map() };
415
+ if (!kind || !styles) return null;
416
+ const name = options.name ?? identifierName(set.name, "Component");
417
+ const { parts, tabs, repeated } = drawnParts(graph, set, behaviour, kind, styles.root);
418
+ const variantIds = [styles.restId, ...ownerVariants(graph, set).map((variant) => variant.id)];
419
+ const items = behaviour && itemsOf(graph, behaviour, variantIds, parts, options, (itemOf) => (owner) => componentModel(graph, owner, {
420
+ ...options,
421
+ name: options.itemName ?? `${name}Item`,
422
+ itemName: void 0,
423
+ itemOf
424
+ }));
425
+ const choice = tabs?.choice ?? items?.choice ?? null;
426
+ const { range, text, inputProperty } = valueModels(graph, set, kind, behaviour, args);
427
+ const model = modelName(args, !!options.itemOf, !!(choice ?? range ?? text));
428
+ const taken = /* @__PURE__ */ new Set([
429
+ ...model ? [model] : [],
430
+ "disabled",
431
+ "value"
432
+ ]);
433
+ const props = variantProps(graph, set, args, taken);
434
+ const disabled = drawsDisabled(args);
435
+ const used = usedLayers(graph, styles.root, variantIds, items?.used, options.references);
436
+ const elements = allElements(styles.root);
437
+ const texts = textProps(graph, set, elements, taken, inputProperty);
438
+ const input = inputLayers(texts.input);
439
+ numberInput(input, range);
440
+ const { booleans, shownBy } = booleanProps(graph, set, elements, taken);
441
+ const { slots, slotOf } = slotProps(graph, set, elements, taken, parts);
442
+ return {
443
+ name,
444
+ kind,
445
+ styles,
446
+ tree: componentTree(styles.root, {
447
+ parts,
448
+ classes: layerClassNames(styles),
449
+ texts: texts.bound,
450
+ used,
451
+ repeated,
452
+ input,
453
+ shownBy,
454
+ slotOf,
455
+ shaders: shaderLayers(graph, styles.restId, elements),
456
+ layerOf: (element) => restLayerOf(graph, styles, element)
457
+ }, rootBindings(model, !!options.itemOf, disabled, props)),
458
+ model,
459
+ choice,
460
+ range,
461
+ text,
462
+ valueProp: !!options.itemOf,
463
+ item: items?.item ?? null,
464
+ disabled,
465
+ props,
466
+ texts: texts.texts,
467
+ booleans,
468
+ slots,
469
+ args
470
+ };
471
+ }
472
+ //#endregion
473
+ //#region src/export/components/styling.ts
474
+ /** How a generated component is styled: a stylesheet, or Tailwind utilities in its markup. */
475
+ const COMPONENT_STYLINGS = ["css", "tailwind"];
476
+ /** Where a layer's shader plays: filling the layer, beneath its content, inside its corners. */
477
+ const SHADER_UTILITIES = "pointer-events-none absolute inset-0 -z-10 rounded-[inherit]";
478
+ /**
479
+ * The class each of a component's readable class names stands for. Styled with a stylesheet, a
480
+ * class is itself; with Tailwind it is the layer's utilities, its states behind their variants,
481
+ * and a shader canvas's placement.
482
+ */
483
+ function componentClasses(component, styling) {
484
+ if (styling === "css") return (className) => className;
485
+ const readable = layerClassNames(component.styles);
486
+ const utilities = stateTailwindClasses(component.styles);
487
+ const byClass = /* @__PURE__ */ new Map();
488
+ for (const [element, className] of readable) byClass.set(className, utilities.get(element) ?? "");
489
+ for (const { shader } of shaderElements(component.tree)) if (shader) byClass.set(shader.className, SHADER_UTILITIES);
490
+ return (className) => byClass.get(className) ?? className;
491
+ }
492
+ //#endregion
493
+ //#region src/export/components/react/shared.ts
494
+ /** `styles.thumb`, or `styles['switch-thumb']` for a class that isn't an identifier. */
495
+ function moduleClass(className) {
496
+ return {
497
+ type: "MemberExpression",
498
+ object: es.identifier("styles"),
499
+ property: es.isIdentifierName(className) ? es.identifier(className) : es.string(className),
500
+ computed: !es.isIdentifierName(className),
501
+ optional: false
502
+ };
503
+ }
504
+ const numeric = (name, value) => jsx.attribute(name, jsx.container(es.number(value)));
505
+ /** A `className` value: a plain string as an attribute string, anything else in braces. */
506
+ function classValue(value) {
507
+ return value.type === "Literal" && typeof value.value === "string" ? jsx.stringValue(value.value) : jsx.container(value);
508
+ }
509
+ /** `element`, recorded as drawing `layerId`, so code can link back to that layer. */
510
+ function drawing$1(element, layerId, uses) {
511
+ if (layerId) uses.layers.set(element, layerId);
512
+ return element;
513
+ }
514
+ /** The layer of each JSX element in `program`, in the order the elements open. */
515
+ function elementLayers(program, layers) {
516
+ const found = [];
517
+ const visit = (value) => {
518
+ if (Array.isArray(value)) {
519
+ for (const item of value) visit(item);
520
+ return;
521
+ }
522
+ if (!es.isNode(value)) return;
523
+ if (value.type === "JSXElement") found.push(layers.get(value) ?? null);
524
+ for (const item of Object.values(value)) visit(item);
525
+ };
526
+ visit(program);
527
+ return found;
528
+ }
529
+ //#endregion
530
+ //#region src/export/components/react/fields.ts
531
+ /** Kinds whose native input takes the caller's props, rather than their root. */
532
+ const INPUT_PROPS = {
533
+ textField: "input",
534
+ textarea: "textarea"
535
+ };
536
+ /** A number field's stepper parts, which change its value by a step. */
537
+ const STEPPERS = {
538
+ increment: {
539
+ label: "Increase",
540
+ sign: "+"
541
+ },
542
+ decrement: {
543
+ label: "Decrease",
544
+ sign: "-"
545
+ }
546
+ };
547
+ /** What a part of a native or measured control needs: a stepper's step, an indicator's width. */
548
+ function partAttributes(node, uses) {
549
+ const { range } = uses.component;
550
+ if (!range || !node.part) return [];
551
+ if (uses.kind === "progress" && node.part === "indicator") {
552
+ const style = progressWidth(range, es.identifier("value"));
553
+ return style ? [jsx.attribute("style", jsx.container(style))] : [];
554
+ }
555
+ const stepper = uses.kind === "numberField" ? STEPPERS[node.part] : void 0;
556
+ if (!stepper) return [];
557
+ return [
558
+ jsx.attribute("aria-label", jsx.stringValue(stepper.label)),
559
+ jsx.attribute("disabled", jsx.container(es.identifier("disabled"))),
560
+ jsx.attribute("onClick", jsx.container(es.parseExpression(`() => commit(value ${stepper.sign} ${String(range.step)})`)))
561
+ ];
562
+ }
563
+ const NUMBER_INPUT = [
564
+ ["type", jsx.stringValue("number")],
565
+ ["value", jsx.container(es.parseExpression("Number.isNaN(value) ? '' : value"))],
566
+ ["onChange", jsx.container(es.parseExpression("(event) => setValue(event.target.valueAsNumber)"))],
567
+ ["onBlur", jsx.container(es.parseExpression("() => commit(value)"))]
568
+ ];
569
+ /** A field's input: a number input that commits within its range, or the input or textarea. */
570
+ function inputElement(className, uses, depth) {
571
+ const { component } = uses;
572
+ const classAttribute = jsx.attribute("className", classValue(uses.classOf(className)));
573
+ const { range } = component;
574
+ if (range) return jsx.element("input", [
575
+ ...NUMBER_INPUT.map(([name, value]) => jsx.attribute(name, value)),
576
+ numeric("min", range.min),
577
+ numeric("max", range.max),
578
+ numeric("step", range.step),
579
+ jsx.attribute("disabled", jsx.container(es.identifier("disabled"))),
580
+ classAttribute
581
+ ], [], depth);
582
+ const start = component.text?.default;
583
+ const placeholder = component.text?.placeholder;
584
+ return jsx.element(INPUT_PROPS[uses.kind] ?? "input", [
585
+ ...placeholder ? [jsx.attribute("placeholder", jsx.stringValue(placeholder))] : [],
586
+ ...start ? [jsx.attribute("defaultValue", jsx.stringValue(start))] : [],
587
+ jsx.spread(es.identifier("props")),
588
+ classAttribute
589
+ ], [], depth);
590
+ }
591
+ /** Props a kind reads itself: a progress bar's value, a number field's start and changes. */
592
+ function kindParameters(component) {
593
+ const { range } = component;
594
+ if (component.kind === "progress" && range) return [{
595
+ name: "value",
596
+ default: es.number(range.default)
597
+ }];
598
+ if (component.kind === "numberField" && range) return [
599
+ {
600
+ name: "defaultValue",
601
+ default: es.number(range.default)
602
+ },
603
+ { name: "onValueChange" },
604
+ { name: "disabled" }
605
+ ];
606
+ return [];
607
+ }
608
+ /**
609
+ * A number field's value: typed freely, and settled within its range when it loses focus or a
610
+ * stepper moves it, which is when the caller hears of it.
611
+ */
612
+ const NUMBER_STATE = (range) => es.fill(es.parseModule(dedent`
613
+ const [value, setValue] = useState(defaultValue)
614
+ const commit = (next: number) => {
615
+ const settled = Number.isNaN(next) ? $min : Math.min($max, Math.max($min, next))
616
+ setValue(settled)
617
+ onValueChange?.(settled)
618
+ }
619
+ `), {
620
+ $min: es.number(range.min),
621
+ $max: es.number(range.max)
622
+ }).body;
623
+ /** The component function's statements before it returns, such as a number field's state. */
624
+ function prepend(declaration, statements) {
625
+ const fn = es.child(declaration, "declaration");
626
+ const body = es.child(fn, "body");
627
+ if (!body || statements.length === 0) return;
628
+ body.body = [...statements, ...es.children(body, "body")];
629
+ }
630
+ //#endregion
631
+ //#region src/export/components/react/index.ts
632
+ /**
633
+ * The Radix primitive a kind renders, from the unified `radix-ui` package, and the component
634
+ * of it each part uses. Its root takes the value two ways (`checked` and `onCheckedChange`,
635
+ * `pressed`, `open`) and `disabled` itself, so the generated props extend the root's.
636
+ */
637
+ const RADIX = {
638
+ button: null,
639
+ switch: {
640
+ namespace: "Switch",
641
+ parts: {
642
+ root: "Root",
643
+ thumb: "Thumb"
644
+ }
645
+ },
646
+ checkbox: {
647
+ namespace: "Checkbox",
648
+ parts: {
649
+ root: "Root",
650
+ indicator: "Indicator"
651
+ }
652
+ },
653
+ toggle: {
654
+ namespace: "Toggle",
655
+ parts: { root: "Root" }
656
+ },
657
+ collapsible: {
658
+ namespace: "Collapsible",
659
+ parts: {
660
+ root: "Root",
661
+ trigger: "Trigger",
662
+ content: "Content"
663
+ }
664
+ },
665
+ tabs: {
666
+ namespace: "Tabs",
667
+ parts: {
668
+ root: "Root",
669
+ list: "List",
670
+ trigger: "Trigger",
671
+ content: "Content"
672
+ }
673
+ },
674
+ radioGroup: {
675
+ namespace: "RadioGroup",
676
+ parts: { root: "Root" }
677
+ },
678
+ toggleGroup: {
679
+ namespace: "ToggleGroup",
680
+ parts: { root: "Root" }
681
+ },
682
+ accordion: {
683
+ namespace: "Accordion",
684
+ parts: { root: "Root" }
685
+ },
686
+ radioGroupItem: {
687
+ namespace: "RadioGroup",
688
+ parts: {
689
+ root: "Item",
690
+ indicator: "Indicator"
691
+ }
692
+ },
693
+ toggleGroupItem: {
694
+ namespace: "ToggleGroup",
695
+ parts: { root: "Item" }
696
+ },
697
+ accordionItem: {
698
+ namespace: "Accordion",
699
+ parts: {
700
+ root: "Item",
701
+ trigger: "Trigger",
702
+ content: "Content"
703
+ }
704
+ },
705
+ slider: {
706
+ namespace: "Slider",
707
+ parts: {
708
+ root: "Root",
709
+ track: "Track",
710
+ range: "Range",
711
+ thumb: "Thumb"
712
+ }
713
+ },
714
+ progress: {
715
+ namespace: "Progress",
716
+ parts: {
717
+ root: "Root",
718
+ indicator: "Indicator"
719
+ }
720
+ },
721
+ numberField: null,
722
+ textField: null,
723
+ textarea: null,
724
+ plain: null
725
+ };
726
+ /** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
727
+ const ROOT_ATTRIBUTES$1 = {
728
+ toggleGroup: [jsx.attribute("type", jsx.stringValue("single"))],
729
+ accordion: [jsx.attribute("type", jsx.stringValue("single")), jsx.attribute("collapsible", null)]
730
+ };
731
+ const PRIMITIVE = (namespace) => `${namespace}Primitive`;
732
+ const HEADING_STYLE$1 = jsx.container(es.object(Object.entries(HEADING_RESET).map(([property, value]) => [camelCase(property), es.string(value)])));
733
+ /** Several classes on one element, skipping a caller's that is absent. */
734
+ const CLASS_NAMES = es.parseExpression("$classes.filter(Boolean).join(' ')");
735
+ /** Whether a layer renders as a native button: a button's root, or a number field's stepper. */
736
+ const isNativeButton = (node, kind) => kind === "button" && node.part === "root" || kind === "numberField" && node.part !== null && Object.hasOwn(STEPPERS, node.part);
737
+ /** A Radix primitive's part, a native button, or the design's tag. */
738
+ function tagOf(node, kind) {
739
+ const radix = RADIX[kind];
740
+ const part = node.part ? radix?.parts[node.part] : void 0;
741
+ if (radix && part) return `${PRIMITIVE(radix.namespace)}.${part}`;
742
+ return isNativeButton(node, kind) ? "button" : node.tag;
743
+ }
744
+ /** `disabled || undefined`, so a native root sets `data-disabled` only while disabled. */
745
+ const disabledFlag = (kind) => es.parseExpression(kind === "numberField" ? "disabled || undefined" : "props.disabled || undefined");
746
+ /** The Iconify component, named apart from any component the design calls `Icon`. */
747
+ const ICONIFY$1 = "IconifyIcon";
748
+ /** An icon: its package's own component where it has the icon, Iconify's otherwise. */
749
+ function iconElement$1(node, uses, depth) {
750
+ const className = jsx.attribute("className", classValue(uses.classOf(node.className)));
751
+ const found = iconDrawing(node.icon, uses.iconPackage, "react");
752
+ const drawn = found && uses.nameIcon(found);
753
+ if (!drawn) {
754
+ uses.icons = true;
755
+ return jsx.element(ICONIFY$1, [jsx.attribute("icon", jsx.stringValue(node.icon)), className], [], depth);
756
+ }
757
+ uses.iconImports.push(...drawingImports(drawn));
758
+ if (drawn.type === "component") return jsx.element(drawn.import.local, [className], [], depth);
759
+ return jsx.element(drawn.component.local, [jsx.attribute("icon", jsx.container(es.identifier(drawn.import.local))), className], [], depth);
760
+ }
761
+ /** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */
762
+ const defaultOf = (model) => `default${upperFirst(model)}`;
763
+ /** A reference's prop value: a bare name for true, `{false}`, or a string. */
764
+ function referenceValue(value) {
765
+ if (value === true) return null;
766
+ if (value === false) return jsx.container(jsx.literal(false));
767
+ return jsx.stringValue(value);
768
+ }
769
+ function reference$1(node, uses, depth) {
770
+ uses.components.add(node.component);
771
+ return drawing$1(jsx.element(node.component, [
772
+ jsx.attribute("className", classValue(uses.classOf(node.className))),
773
+ ...node.props.map((prop) => jsx.attribute(prop.name, referenceValue(prop.value))),
774
+ ...node.model ? [jsx.attribute(defaultOf(node.model), null)] : []
775
+ ], [], depth), node.layerId, uses);
776
+ }
777
+ function element(node, uses, depth) {
778
+ if (node.type === "text") return jsx.text(node.value);
779
+ if (node.type === "textProp") return jsx.container(es.identifier(node.name));
780
+ if (node.type === "reference") return reference$1(node, uses, depth);
781
+ if (node.type === "input") return drawing$1(inputElement(node.className, uses, depth), node.layerId, uses);
782
+ if (node.type === "icon") return drawing$1(iconElement$1(node, uses, depth), node.layerId, uses);
783
+ return designElement$1(node, uses, depth);
784
+ }
785
+ /**
786
+ * The design's own classes, the state styles' module class, and on the root the caller's,
787
+ * which the spread would otherwise lose to the generated one.
788
+ */
789
+ function classNameOf(node, root, uses) {
790
+ const classes = [
791
+ ...node.attrs.class ? [es.string(node.attrs.class)] : [],
792
+ uses.classOf(node.className),
793
+ ...root ? [es.parseExpression("props.className")] : []
794
+ ];
795
+ return (classes.length === 1 ? classes.at(0) : void 0) ?? es.fill(CLASS_NAMES, { $classes: es.array(classes) });
796
+ }
797
+ /**
798
+ * What a root fixes before the caller's props: a group's single choice and its start, and a
799
+ * slider's or progress bar's range and the value it starts at.
800
+ */
801
+ function rootAttributes(uses) {
802
+ const { component } = uses;
803
+ const start = uses.choice?.default;
804
+ const { range } = component;
805
+ return [
806
+ ...ROOT_ATTRIBUTES$1[uses.kind] ?? [],
807
+ ...start ? [jsx.attribute("defaultValue", jsx.stringValue(start))] : [],
808
+ ...range && uses.kind === "slider" ? [
809
+ jsx.attribute("defaultValue", jsx.container(es.array([es.number(range.default)]))),
810
+ numeric("min", range.min),
811
+ numeric("max", range.max),
812
+ numeric("step", range.step)
813
+ ] : [],
814
+ ...range && uses.kind === "progress" ? [jsx.attribute("value", jsx.container(es.fill(es.parseExpression("Math.min($max, Math.max($min, value))"), {
815
+ $min: es.number(range.min),
816
+ $max: es.number(range.max)
817
+ }))), numeric("max", range.max)] : []
818
+ ];
819
+ }
820
+ function bindingAttributes$1(node, kind, native) {
821
+ return node.bindings.flatMap((binding) => {
822
+ if (binding.type === "prop") return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))];
823
+ if (binding.type === "disabled" && native) return [jsx.attribute("data-disabled", jsx.container(disabledFlag(kind)))];
824
+ return [];
825
+ });
826
+ }
827
+ /** A shader playing behind its layer's content, with telemetry off, as every export has it. */
828
+ function shaderCanvas$1(shader, uses, depth) {
829
+ const effect = (at) => (component) => {
830
+ uses.shaders.add(component.type);
831
+ const children = drawnEffects(component.children).map(effect(at + 1));
832
+ return jsx.element(shaderEffectName(component.type), shaderEffectAttributes(component), children, at);
833
+ };
834
+ return jsx.element(SHADER_CANVAS, [jsx.attribute("className", classValue(uses.classOf(shader.className))), jsx.attribute("disableTelemetry", null)], drawnEffects(shader.preset.components).map(effect(depth + 1)), depth);
835
+ }
836
+ /** Words alone stay on the element's line, where a line break would add a space. */
837
+ function wordsOnly(node) {
838
+ const only = node.children.length === 1 ? node.children[0]?.type : void 0;
839
+ return !node.slot && !node.shader && (only === "text" || only === "textProp");
840
+ }
841
+ function designElement$1(node, uses, depth) {
842
+ const kind = uses.kind;
843
+ const root = node.part === "root";
844
+ const native = root && !(node.part && RADIX[kind]?.parts[node.part]);
845
+ const attributes = [
846
+ ...isNativeButton(node, kind) ? [jsx.attribute("type", jsx.stringValue("button"))] : [],
847
+ ...root ? rootAttributes(uses) : [],
848
+ ...root && !INPUT_PROPS[kind] ? [jsx.spread(es.identifier("props"))] : [],
849
+ ...node.value === void 0 ? [] : [jsx.attribute("value", jsx.stringValue(node.value))],
850
+ ...Object.entries(omit(node.attrs, ["class"])).map(([name, value]) => jsx.attribute(name, jsx.stringValue(value))),
851
+ ...partAttributes(node, uses),
852
+ jsx.attribute("className", classValue(classNameOf(node, root, uses))),
853
+ ...bindingAttributes$1(node, kind, native)
854
+ ];
855
+ const inline = wordsOnly(node);
856
+ const header = kind === "accordionItem" && node.part === "trigger";
857
+ const childDepth = depth + (header ? 2 : 1);
858
+ const content = node.children.map((child) => element(child, uses, childDepth));
859
+ const shader = node.shader ? [shaderCanvas$1(node.shader, uses, childDepth)] : [];
860
+ const drawn = drawing$1(jsx.element(tagOf(node, kind), attributes, [...shader, ...node.slot ? [slotContent(node.slot, content, childDepth)] : content], depth + (header ? 1 : 0), inline), node.layerId, uses);
861
+ const shown = header ? jsx.element(`${PRIMITIVE("Accordion")}.Header`, [jsx.attribute("style", HEADING_STYLE$1)], [drawn], depth) : drawn;
862
+ return node.shownBy ? whenShown(node.shownBy, shown) : shown;
863
+ }
864
+ const LOGICAL = (operator, left, right) => ({
865
+ type: "LogicalExpression",
866
+ operator,
867
+ left,
868
+ right
869
+ });
870
+ /** `{content ?? <>…</>}`: what the caller passes for a slot, or the design's content. */
871
+ function slotContent(slot, children, depth) {
872
+ return jsx.container(LOGICAL("??", es.identifier(slot), jsx.fragment(children, depth)));
873
+ }
874
+ /** `{showIcon && <…/>}`: a layer a boolean prop shows. */
875
+ function whenShown(prop, drawn) {
876
+ return jsx.container(LOGICAL("&&", es.identifier(prop), drawn));
877
+ }
878
+ const MODULE = es.parseModule(dedent`
879
+ import type { ComponentProps } from 'react'
880
+
881
+ import styles from '$styles'
882
+
883
+ export type $Props = $Type
884
+
885
+ export function $Name($params: $Props) {
886
+ return $body
887
+ }
888
+ `);
889
+ const RADIX_IMPORT = es.parseModule(`import { $Namespace as $Primitive } from 'radix-ui'`);
890
+ const ICONIFY_IMPORT = es.parseModule(`import { Icon as ${ICONIFY$1} } from '@iconify/react'`).body;
891
+ const IMPORT_COMPONENT$1 = es.parseModule(`import { $Component } from '$path'`);
892
+ /**
893
+ * The props of a group that fixes one choice at a time, without the `type` it fixes. The
894
+ * root's own props join the single and multiple choice, which a single value can't satisfy.
895
+ */
896
+ const SINGLE_PROPS = {
897
+ toggleGroup: "ToggleGroupSingleProps",
898
+ accordion: "AccordionSingleProps"
899
+ };
900
+ const qualified = (namespace, name) => ({
901
+ type: "TSQualifiedName",
902
+ left: es.identifier(PRIMITIVE(namespace)),
903
+ right: es.identifier(name)
904
+ });
905
+ /** Props a kind declares itself, where no Radix root has them. */
906
+ const OWN_PROPS = {
907
+ progress: "Omit<ComponentProps<typeof ProgressPrimitive.Root>, 'value'> & { value?: number }",
908
+ numberField: "Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & { defaultValue?: number; onValueChange?: (value: number) => void; disabled?: boolean }",
909
+ textField: "ComponentProps<'input'>",
910
+ textarea: "ComponentProps<'textarea'>"
911
+ };
912
+ /** The root's own props, or a single choice group's. */
913
+ function rootPropsType(kind, tag) {
914
+ const own = OWN_PROPS[kind];
915
+ if (own) return es.parseType(own);
916
+ if (kind === "plain") return es.parseType(`ComponentProps<'${tag}'>`);
917
+ const radix = RADIX[kind];
918
+ if (!radix) return es.parseType("ComponentProps<'button'>");
919
+ const single = SINGLE_PROPS[kind];
920
+ if (single) return es.fill(es.parseType("Omit<$Props, 'type'>"), { $Props: qualified(radix.namespace, single) });
921
+ return es.fill(es.parseType("ComponentProps<typeof $Root>"), { $Root: qualified(radix.namespace, radix.parts.root) });
922
+ }
923
+ /** The root's own props, extended with the component's variant props when it has any. */
924
+ function propsType$1(component) {
925
+ const base = rootPropsType(component.kind, component.tree.tag);
926
+ if ([
927
+ component.props,
928
+ component.texts,
929
+ component.booleans,
930
+ component.slots
931
+ ].every((list) => list.length === 0)) return base;
932
+ return {
933
+ type: "TSIntersectionType",
934
+ types: [base, es.objectType([
935
+ ...component.props.map((prop) => [
936
+ prop.name,
937
+ es.stringUnionType(prop.options),
938
+ true
939
+ ]),
940
+ ...component.texts.map((text) => [
941
+ text.name,
942
+ es.parseType("string"),
943
+ true
944
+ ]),
945
+ ...component.booleans.map((prop) => [
946
+ prop.name,
947
+ es.parseType("boolean"),
948
+ true
949
+ ]),
950
+ ...component.slots.map((slot) => [
951
+ slot.name,
952
+ es.parseType("ReactNode"),
953
+ true
954
+ ])
955
+ ])]
956
+ };
957
+ }
958
+ /**
959
+ * `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
960
+ * kept off the root, and the rest passed on.
961
+ */
962
+ function parameters(component) {
963
+ const own = [
964
+ ...kindParameters(component),
965
+ ...[...component.props, ...component.texts].map((prop) => ({
966
+ name: prop.name,
967
+ default: es.string(prop.default)
968
+ })),
969
+ ...component.booleans.map((prop) => ({
970
+ name: prop.name,
971
+ default: es.parseExpression(String(prop.default))
972
+ })),
973
+ ...component.slots.map((slot) => ({ name: slot.name }))
974
+ ];
975
+ if (own.length === 0) return es.identifier("props");
976
+ return {
977
+ type: "ObjectPattern",
978
+ properties: [...own.map((prop) => ({
979
+ type: "Property",
980
+ kind: "init",
981
+ key: es.identifier(prop.name),
982
+ value: prop.default ? {
983
+ type: "AssignmentPattern",
984
+ left: es.identifier(prop.name),
985
+ right: prop.default
986
+ } : es.identifier(prop.name),
987
+ computed: false,
988
+ method: false,
989
+ shorthand: true
990
+ })), {
991
+ type: "RestElement",
992
+ argument: es.identifier("props")
993
+ }]
994
+ };
995
+ }
996
+ /**
997
+ * `import { useState, type ComponentProps, type ReactNode } from 'react'` with only what the
998
+ * component uses: a number field's state, its root's props, and its slots' content.
999
+ */
1000
+ function reactImport(uses) {
1001
+ const types = [...uses.props ? ["ComponentProps"] : [], ...uses.slots ? ["ReactNode"] : []];
1002
+ if (!uses.state && types.length === 0) return [];
1003
+ const specifiers = uses.state ? ["useState", ...types.map((name) => `type ${name}`)].join(", ") : types.join(", ");
1004
+ return es.parseModule(`import ${uses.state ? "" : "type "}{ ${specifiers} } from 'react'`).body;
1005
+ }
1006
+ /**
1007
+ * The prop a story sets the value with: Radix's uncontrolled value, so a story's control and
1008
+ * its play function can both change it, which a slider takes as a list; a progress bar's own
1009
+ * value, which nothing else changes.
1010
+ */
1011
+ function valueArg(kind, model) {
1012
+ if (!model) return { valueArg: null };
1013
+ if (kind === "progress") return { valueArg: "value" };
1014
+ return {
1015
+ valueArg: defaultOf(model),
1016
+ ...kind === "slider" ? { valueList: true } : {}
1017
+ };
1018
+ }
1019
+ /**
1020
+ * A component as a React component on Radix UI: its parts as Radix primitives from the
1021
+ * `radix-ui` package, its variants' state styles in a CSS module, and props that extend the
1022
+ * Radix root's with its other variant properties.
1023
+ */
1024
+ const reactComponent = async (component, options = {}) => {
1025
+ const styling = options.styling ?? "css";
1026
+ const radix = RADIX[component.kind];
1027
+ const stylesPath = `${component.name}.module.css`;
1028
+ const classOf = componentClasses(component, styling);
1029
+ const uses = {
1030
+ component,
1031
+ classOf: (className) => styling === "css" ? moduleClass(className) : es.string(classOf(className)),
1032
+ kind: component.kind,
1033
+ choice: component.choice,
1034
+ components: /* @__PURE__ */ new Set(),
1035
+ layers: /* @__PURE__ */ new WeakMap(),
1036
+ icons: false,
1037
+ iconPackage: options.icons ?? "iconify",
1038
+ iconImports: [],
1039
+ nameIcon: iconNamer(component, [
1040
+ ICONIFY$1,
1041
+ "styles",
1042
+ `${component.name}Props`,
1043
+ ...radix ? [radix.namespace, PRIMITIVE(radix.namespace)] : []
1044
+ ]),
1045
+ shaders: /* @__PURE__ */ new Set()
1046
+ };
1047
+ const body = element(component.tree, uses, 1);
1048
+ const imports = [
1049
+ ...uses.icons ? ICONIFY_IMPORT : [],
1050
+ ...iconImportDeclarations(uses.iconImports),
1051
+ ...uses.shaders.size > 0 ? [shaderImport("shaders/react", uses.shaders)] : [],
1052
+ ...radix ? es.fill(RADIX_IMPORT, {
1053
+ $Namespace: es.identifier(radix.namespace),
1054
+ $Primitive: es.identifier(PRIMITIVE(radix.namespace))
1055
+ }).body : [],
1056
+ ...[...uses.components].sort().flatMap((name) => es.fill(IMPORT_COMPONENT$1, {
1057
+ $Component: es.identifier(name),
1058
+ $path: es.string(`./${name}`)
1059
+ }).body)
1060
+ ];
1061
+ const [, stylesImport, ...rest] = es.fill(MODULE, {
1062
+ $styles: es.string(`./${stylesPath}`),
1063
+ $Props: es.identifier(`${component.name}Props`),
1064
+ $Type: propsType$1(component),
1065
+ $Name: es.identifier(component.name),
1066
+ $params: parameters(component),
1067
+ $body: body
1068
+ }).body;
1069
+ const state = component.kind === "numberField" && component.range ? NUMBER_STATE(component.range) : [];
1070
+ prepend(rest.at(-1), state);
1071
+ const program = {
1072
+ type: "Program",
1073
+ sourceType: "module",
1074
+ body: [
1075
+ ...reactImport({
1076
+ state: state.length > 0,
1077
+ props: !SINGLE_PROPS[component.kind],
1078
+ slots: component.slots.length > 0
1079
+ }),
1080
+ ...imports,
1081
+ ...styling === "css" ? [stylesImport] : [],
1082
+ ...rest
1083
+ ]
1084
+ };
1085
+ const stylesheet = styling === "css" ? [{
1086
+ path: stylesPath,
1087
+ content: compact([(await stateStylesToCSS(component.styles)).css, shaderCSS(component.tree)]).join("\n")
1088
+ }] : [];
1089
+ const model = component.model;
1090
+ return {
1091
+ files: [
1092
+ ...(component.item ? await reactComponent(component.item, options) : null)?.files ?? [],
1093
+ {
1094
+ path: `${component.name}.tsx`,
1095
+ content: `${jsx.printModule(program)}\n`,
1096
+ layerIds: elementLayers(body, uses.layers)
1097
+ },
1098
+ ...stylesheet
1099
+ ],
1100
+ entry: {
1101
+ path: `./${component.name}`,
1102
+ named: true
1103
+ },
1104
+ ...valueArg(component.kind, model)
1105
+ };
1106
+ };
1107
+ //#endregion
1108
+ //#region src/export/components/vue.ts
1109
+ /** The Reka UI components a kind renders, by part, and the prop its model binds. */
1110
+ const REKA = {
1111
+ button: { parts: {} },
1112
+ switch: {
1113
+ parts: {
1114
+ root: "SwitchRoot",
1115
+ thumb: "SwitchThumb"
1116
+ },
1117
+ model: "modelValue"
1118
+ },
1119
+ checkbox: {
1120
+ parts: {
1121
+ root: "CheckboxRoot",
1122
+ indicator: "CheckboxIndicator"
1123
+ },
1124
+ model: "modelValue"
1125
+ },
1126
+ toggle: {
1127
+ parts: { root: "Toggle" },
1128
+ model: "modelValue"
1129
+ },
1130
+ collapsible: {
1131
+ parts: {
1132
+ root: "CollapsibleRoot",
1133
+ trigger: "CollapsibleTrigger",
1134
+ content: "CollapsibleContent"
1135
+ },
1136
+ model: "open"
1137
+ },
1138
+ tabs: {
1139
+ parts: {
1140
+ root: "TabsRoot",
1141
+ list: "TabsList",
1142
+ trigger: "TabsTrigger",
1143
+ content: "TabsContent"
1144
+ },
1145
+ model: "modelValue"
1146
+ },
1147
+ radioGroup: {
1148
+ parts: { root: "RadioGroupRoot" },
1149
+ model: "modelValue"
1150
+ },
1151
+ toggleGroup: {
1152
+ parts: { root: "ToggleGroupRoot" },
1153
+ model: "modelValue"
1154
+ },
1155
+ accordion: {
1156
+ parts: { root: "AccordionRoot" },
1157
+ model: "modelValue"
1158
+ },
1159
+ radioGroupItem: { parts: {
1160
+ root: "RadioGroupItem",
1161
+ indicator: "RadioGroupIndicator"
1162
+ } },
1163
+ toggleGroupItem: { parts: { root: "ToggleGroupItem" } },
1164
+ accordionItem: { parts: {
1165
+ root: "AccordionItem",
1166
+ trigger: "AccordionTrigger",
1167
+ content: "AccordionContent"
1168
+ } },
1169
+ slider: {
1170
+ parts: {
1171
+ root: "SliderRoot",
1172
+ track: "SliderTrack",
1173
+ range: "SliderRange",
1174
+ thumb: "SliderThumb"
1175
+ },
1176
+ model: "modelValue"
1177
+ },
1178
+ progress: {
1179
+ parts: {
1180
+ root: "ProgressRoot",
1181
+ indicator: "ProgressIndicator"
1182
+ },
1183
+ model: "modelValue"
1184
+ },
1185
+ numberField: {
1186
+ parts: {
1187
+ root: "NumberFieldRoot",
1188
+ increment: "NumberFieldIncrement",
1189
+ decrement: "NumberFieldDecrement"
1190
+ },
1191
+ model: "modelValue"
1192
+ },
1193
+ textField: { parts: {} },
1194
+ textarea: { parts: {} },
1195
+ plain: { parts: {} }
1196
+ };
1197
+ /** Kinds whose two-way value is their input's, which binds it rather than the root. */
1198
+ const INPUT_MODEL = /* @__PURE__ */ new Set(["textField", "textarea"]);
1199
+ /** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
1200
+ const ROOT_ATTRIBUTES = {
1201
+ toggleGroup: [vue.attribute("type", "single")],
1202
+ accordion: [vue.attribute("type", "single"), vue.bound("collapsible", es.parseExpression("true"))]
1203
+ };
1204
+ const identifier = (name) => es.identifier(name);
1205
+ const HEADING_STYLE = Object.entries(HEADING_RESET).map(([property, value]) => `${property}: ${value}`).join("; ");
1206
+ /** `disabled || undefined`, so a native button sets `data-disabled` only while disabled. */
1207
+ const DISABLED_FLAG = es.parseExpression("disabled || undefined");
1208
+ function bindingAttributes(binding, uses, native) {
1209
+ const { kind } = uses;
1210
+ if (binding.type === "model") {
1211
+ if (INPUT_MODEL.has(kind)) return [];
1212
+ const bound = uses.sliderValues ?? binding.name;
1213
+ return [vue.model(identifier(bound), REKA[kind].model === "open" ? "open" : void 0)];
1214
+ }
1215
+ if (binding.type === "prop") return [vue.bound(binding.attribute, identifier(binding.prop.name))];
1216
+ if (binding.type === "value") return [vue.bound("value", identifier("value"))];
1217
+ return [...native && kind !== "button" ? [] : [vue.bound("disabled", identifier("disabled"))], ...native ? [vue.bound("data-disabled", DISABLED_FLAG)] : []];
1218
+ }
1219
+ /** The number range a slider, progress bar, or number field's root is given. */
1220
+ function rangeAttributes(component) {
1221
+ const { range } = component;
1222
+ if (!range) return [];
1223
+ const bound = (name) => vue.bound(name, es.number(range[name]));
1224
+ return component.kind === "progress" ? [bound("max")] : [
1225
+ bound("min"),
1226
+ bound("max"),
1227
+ bound("step")
1228
+ ];
1229
+ }
1230
+ function progressStyle(component) {
1231
+ const { range, model } = component;
1232
+ const style = range && model ? progressWidth(range, identifier(model)) : null;
1233
+ return style ? [vue.bound("style", style)] : [];
1234
+ }
1235
+ /** `element`, recorded as drawing `layerId`, so code can link back to that layer. */
1236
+ function drawing(element, layerId, uses) {
1237
+ if (layerId) uses.layers.set(element, layerId);
1238
+ return element;
1239
+ }
1240
+ /** A field's input: Reka's for a number field, else a native input or textarea. */
1241
+ function inputNode(className, uses) {
1242
+ const { component } = uses;
1243
+ if (component.kind === "numberField") {
1244
+ uses.reka.add("NumberFieldInput");
1245
+ return vue.element("NumberFieldInput", [vue.attribute("class", uses.classOf(className))]);
1246
+ }
1247
+ const placeholder = component.text?.placeholder;
1248
+ return vue.element(component.kind === "textarea" ? "textarea" : "input", [
1249
+ vue.attribute("class", uses.classOf(className)),
1250
+ ...component.model ? [vue.model(identifier(component.model))] : [],
1251
+ ...placeholder ? [vue.attribute("placeholder", placeholder)] : [],
1252
+ ...component.disabled ? [vue.bound("disabled", identifier("disabled"))] : []
1253
+ ]);
1254
+ }
1255
+ /** The Iconify component, named apart from any component the design calls `Icon`. */
1256
+ const ICONIFY = "IconifyIcon";
1257
+ /** An icon: its package's own component where it has the icon, Iconify's otherwise. */
1258
+ function iconElement(node, uses) {
1259
+ const className = vue.attribute("class", uses.classOf(node.className));
1260
+ const found = iconDrawing(node.icon, uses.iconPackage, "vue");
1261
+ const drawn = found && uses.nameIcon(found);
1262
+ if (!drawn) {
1263
+ uses.icons = true;
1264
+ return vue.element(ICONIFY, [vue.attribute("icon", node.icon), className]);
1265
+ }
1266
+ uses.iconImports.push(...drawingImports(drawn));
1267
+ if (drawn.type === "component") return vue.element(drawn.import.local, [className]);
1268
+ return vue.element(drawn.component.local, [vue.bound("icon", identifier(drawn.import.local)), className]);
1269
+ }
1270
+ function reference(node, uses) {
1271
+ uses.components.add(node.component);
1272
+ const model = node.model ? claimName(`${camelCase(node.component)}${upperFirst(node.model)}`, uses.taken) : null;
1273
+ if (model) uses.models.push({ name: model });
1274
+ return vue.element(node.component, [
1275
+ vue.attribute("class", uses.classOf(node.className)),
1276
+ ...node.props.map((prop) => typeof prop.value === "boolean" ? vue.bound(prop.name, es.parseExpression(String(prop.value))) : vue.attribute(prop.name, prop.value)),
1277
+ ...model && node.model ? [vue.model(identifier(model), node.model)] : []
1278
+ ]);
1279
+ }
1280
+ /** A design element's attributes: what shows it, its part's own, the design's, and bindings. */
1281
+ function elementAttributes(node, uses, { native, button }) {
1282
+ const root = node.part === "root";
1283
+ return [
1284
+ ...node.shownBy ? [vue.renderIf(identifier(node.shownBy))] : [],
1285
+ ...button ? [vue.attribute("type", "button")] : [],
1286
+ ...root ? [...ROOT_ATTRIBUTES[uses.kind] ?? [], ...rangeAttributes(uses.component)] : [],
1287
+ ...uses.kind === "progress" && node.part === "indicator" ? progressStyle(uses.component) : [],
1288
+ ...Object.entries(omit(node.attrs, ["class"])).map(([name, value]) => vue.attribute(name, value)),
1289
+ vue.attribute("class", compact([node.attrs.class, uses.classOf(node.className)]).join(" ")),
1290
+ ...node.value === void 0 ? [] : [vue.attribute("value", node.value)],
1291
+ ...node.bindings.flatMap((binding) => bindingAttributes(binding, uses, native))
1292
+ ];
1293
+ }
1294
+ /** A shader playing behind its layer's content, with telemetry off, as every export has it. */
1295
+ function shaderCanvas(shader, uses) {
1296
+ const effect = (component) => {
1297
+ uses.shaders.add(component.type);
1298
+ return vue.element(shaderEffectName(component.type), Object.entries(component.props ?? {}).map(([key, value]) => typeof value === "string" ? vue.attribute(kebabCase(key), value) : vue.bound(kebabCase(key), es.json(value))), drawnEffects(component.children).map(effect));
1299
+ };
1300
+ return vue.element(SHADER_CANVAS, [vue.attribute("class", uses.classOf(shader.className)), vue.bound("disable-telemetry", es.json(true))], drawnEffects(shader.preset.components).map(effect));
1301
+ }
1302
+ function designElement(node, uses) {
1303
+ const reka = node.part ? REKA[uses.kind].parts[node.part] : void 0;
1304
+ if (reka) uses.reka.add(reka);
1305
+ const native = node.part === "root" && !reka;
1306
+ const button = native && uses.kind === "button";
1307
+ const content = node.children.map((child) => templateNode(child, uses));
1308
+ const children = node.shader ? [shaderCanvas(node.shader, uses), ...content] : content;
1309
+ const element = drawing(vue.element(reka ?? (button ? "button" : node.tag), elementAttributes(node, uses, {
1310
+ native,
1311
+ button
1312
+ }), node.slot ? [...node.shader ? [shaderCanvas(node.shader, uses)] : [], vue.element("slot", [vue.attribute("name", node.slot)], content)] : children), node.layerId, uses);
1313
+ if (uses.kind !== "accordionItem" || node.part !== "trigger") return element;
1314
+ uses.reka.add("AccordionHeader");
1315
+ return vue.element("AccordionHeader", [vue.attribute("style", HEADING_STYLE)], [element]);
1316
+ }
1317
+ function templateNode(node, uses) {
1318
+ if (node.type === "text") return vue.text(node.value);
1319
+ if (node.type === "textProp") return vue.interpolation(identifier(node.name));
1320
+ if (node.type === "reference") return drawing(reference(node, uses), node.layerId, uses);
1321
+ if (node.type === "input") return drawing(inputNode(node.className, uses), node.layerId, uses);
1322
+ if (node.type === "icon") return drawing(iconElement(node, uses), node.layerId, uses);
1323
+ return designElement(node, uses);
1324
+ }
1325
+ function propsType(component) {
1326
+ const members = component.props.map((prop) => [
1327
+ prop.name,
1328
+ es.stringUnionType(prop.options),
1329
+ true
1330
+ ]);
1331
+ if (component.disabled) members.unshift([
1332
+ "disabled",
1333
+ es.parseType("boolean"),
1334
+ true
1335
+ ]);
1336
+ if (component.valueProp) members.unshift([
1337
+ "value",
1338
+ es.parseType("string"),
1339
+ false
1340
+ ]);
1341
+ for (const text of component.texts) members.push([
1342
+ text.name,
1343
+ es.parseType("string"),
1344
+ true
1345
+ ]);
1346
+ for (const prop of component.booleans) members.push([
1347
+ prop.name,
1348
+ es.parseType("boolean"),
1349
+ true
1350
+ ]);
1351
+ return es.objectType(members);
1352
+ }
1353
+ /** `defineProps`, with `withDefaults` when any prop has a default to give. */
1354
+ /** Whether any prop has a default to give: `disabled`, a variant, a text, or a boolean. */
1355
+ const hasDefaults = (component) => component.disabled || component.props.length > 0 || component.texts.length > 0 || component.booleans.length > 0;
1356
+ function propsDeclaration(component) {
1357
+ return hasDefaults(component) ? es.fill(PROPS, {
1358
+ $Props: propsType(component),
1359
+ $defaults: propsDefaults(component)
1360
+ }).body : es.fill(REQUIRED_PROPS, { $Props: propsType(component) }).body;
1361
+ }
1362
+ function propsDefaults(component) {
1363
+ return es.object([
1364
+ ...component.disabled ? [["disabled", es.parseExpression("false")]] : [],
1365
+ ...component.props.map((prop) => [prop.name, es.string(prop.default)]),
1366
+ ...component.texts.map((text) => [text.name, es.string(text.default)]),
1367
+ ...component.booleans.map((prop) => [prop.name, es.parseExpression(String(prop.default))])
1368
+ ]);
1369
+ }
1370
+ const PROPS = es.parseModule("withDefaults(defineProps<$Props>(), $defaults)");
1371
+ const REQUIRED_PROPS = es.parseModule("defineProps<$Props>()");
1372
+ const MODEL = es.parseModule("const $model = defineModel<boolean>($name, { default: false })");
1373
+ const CHOICE_MODEL = es.parseModule("const $model = defineModel<$Type>($name, { default: $default })");
1374
+ const OPEN_CHOICE_MODEL = es.parseModule("const $model = defineModel<$Type>($name)");
1375
+ const VALUE_MODEL = es.parseModule("const $model = defineModel<$Type>($name, { default: $default })");
1376
+ const SLIDER_VALUES = es.parseModule(dedent`
1377
+ const $values = computed({
1378
+ get: () => [$model.value],
1379
+ set: (next: number[] | undefined) => {
1380
+ $model.value = next?.[0] ?? $model.value
1381
+ }
1382
+ })
1383
+ `);
1384
+ function namedImport(names, source, local = (name) => name) {
1385
+ return {
1386
+ type: "ImportDeclaration",
1387
+ importKind: "value",
1388
+ specifiers: names.map((name) => ({
1389
+ type: "ImportSpecifier",
1390
+ imported: identifier(name),
1391
+ local: identifier(local(name))
1392
+ })),
1393
+ source: es.string(source)
1394
+ };
1395
+ }
1396
+ const IMPORT_COMPONENT = es.parseModule(`import $Component from '$path'`);
1397
+ const MODEL_REF = es.parseModule("const $name = ref(true)");
1398
+ /** What the script imports: Vue's helpers, Iconify, Reka, and other generated components. */
1399
+ function scriptImports(uses) {
1400
+ const helpers = compact([uses.sliderValues && "computed", uses.models.length > 0 && "ref"]);
1401
+ return [
1402
+ ...helpers.length > 0 ? [namedImport(helpers, "vue")] : [],
1403
+ ...uses.icons ? [namedImport(["Icon"], "@iconify/vue", () => ICONIFY)] : [],
1404
+ ...iconImportDeclarations(uses.iconImports),
1405
+ ...uses.reka.size > 0 ? [namedImport([...uses.reka].sort(), "reka-ui")] : [],
1406
+ ...uses.shaders.size > 0 ? [shaderImport("shaders/vue", uses.shaders)] : [],
1407
+ ...[...uses.components].sort().flatMap((name) => es.fill(IMPORT_COMPONENT, {
1408
+ $Component: identifier(name),
1409
+ $path: es.string(`./${name}.vue`)
1410
+ }).body)
1411
+ ];
1412
+ }
1413
+ /** The model's declaration: a choice, a number or text, or a boolean, and a slider's list. */
1414
+ function modelDeclaration(component, uses) {
1415
+ const name = component.model;
1416
+ if (!name) return [];
1417
+ const { choice, range, text } = component;
1418
+ const base = {
1419
+ $model: identifier(name),
1420
+ $name: es.string(name)
1421
+ };
1422
+ if (choice) return es.fill(choice.default === null ? OPEN_CHOICE_MODEL : CHOICE_MODEL, {
1423
+ ...base,
1424
+ $Type: es.stringUnionType(choice.options),
1425
+ $default: choice.default === null ? es.OMIT : es.string(choice.default)
1426
+ }).body;
1427
+ if (!range && !text) return es.fill(MODEL, base).body;
1428
+ const model = es.fill(VALUE_MODEL, {
1429
+ ...base,
1430
+ $Type: es.parseType(range ? "number" : "string"),
1431
+ $default: range ? es.number(range.default) : es.string(text?.default ?? "")
1432
+ }).body;
1433
+ const values = uses.sliderValues ? es.fill(SLIDER_VALUES, {
1434
+ $values: identifier(uses.sliderValues),
1435
+ $model: identifier(name)
1436
+ }).body : [];
1437
+ return [...model, ...values];
1438
+ }
1439
+ function script(component, uses) {
1440
+ const props = component.valueProp || hasDefaults(component) ? propsDeclaration(component) : [];
1441
+ const refs = uses.models.flatMap((item) => es.fill(MODEL_REF, { $name: identifier(item.name) }).body);
1442
+ return {
1443
+ type: "Program",
1444
+ sourceType: "module",
1445
+ body: [
1446
+ ...scriptImports(uses),
1447
+ ...props,
1448
+ ...modelDeclaration(component, uses),
1449
+ ...refs
1450
+ ]
1451
+ };
1452
+ }
1453
+ /**
1454
+ * A component as a Vue single-file component on Reka UI: its variants' state styles in a
1455
+ * scoped stylesheet, its parts as Reka components, and its props from the behaviour and its
1456
+ * other variant properties.
1457
+ */
1458
+ const vueComponent = async (component, options = {}) => {
1459
+ const styling = options.styling ?? "css";
1460
+ const taken = /* @__PURE__ */ new Set([
1461
+ ...component.props.map((prop) => prop.name),
1462
+ ...component.texts.map((text) => text.name),
1463
+ ...component.booleans.map((prop) => prop.name),
1464
+ ...component.slots.map((slot) => slot.name),
1465
+ ...component.model ? [component.model] : [],
1466
+ "disabled"
1467
+ ]);
1468
+ const uses = {
1469
+ component,
1470
+ classOf: componentClasses(component, styling),
1471
+ layers: /* @__PURE__ */ new WeakMap(),
1472
+ kind: component.kind,
1473
+ sliderValues: component.kind === "slider" && component.model ? claimName("values", taken) : null,
1474
+ reka: /* @__PURE__ */ new Set(),
1475
+ components: /* @__PURE__ */ new Set(),
1476
+ icons: false,
1477
+ iconPackage: options.icons ?? "iconify",
1478
+ iconImports: [],
1479
+ nameIcon: iconNamer(component, [ICONIFY, ...taken]),
1480
+ shaders: /* @__PURE__ */ new Set(),
1481
+ models: [],
1482
+ taken
1483
+ };
1484
+ const template = templateNode(component.tree, uses);
1485
+ const style = styling === "css" ? compact([(await stateStylesToCSS(component.styles)).css, shaderCSS(component.tree)]).join("\n") : void 0;
1486
+ const path = `${component.name}.vue`;
1487
+ const item = component.item ? await vueComponent(component.item, options) : null;
1488
+ const sfc = {
1489
+ script: script(component, uses),
1490
+ template,
1491
+ style
1492
+ };
1493
+ return {
1494
+ files: [...item?.files ?? [], {
1495
+ path,
1496
+ content: vue.printComponent(sfc),
1497
+ layerIds: vue.componentElements(sfc).map((element) => (element && uses.layers.get(element)) ?? null)
1498
+ }],
1499
+ entry: {
1500
+ path: `./${path}`,
1501
+ named: false
1502
+ },
1503
+ valueArg: component.model
1504
+ };
1505
+ };
1506
+ //#endregion
1507
+ //#region src/export/components/layers.ts
1508
+ /** The frameworks a layer can be generated as a component for. */
1509
+ const LAYER_COMPONENT_FRAMEWORKS = ["vue", "react"];
1510
+ /**
1511
+ * Each layer as a Vue or React component, as the Storybook export generates a component set's:
1512
+ * a component set with its variants as props and its behaviour's parts, and any other layer as
1513
+ * a plain component of the elements it draws. Names stay distinct across the layers.
1514
+ */
1515
+ async function layerComponents(graph, layerIds, framework, options = {}) {
1516
+ const generate = framework === "vue" ? vueComponent : reactComponent;
1517
+ const taken = /* @__PURE__ */ new Set();
1518
+ const components = [];
1519
+ for (const layerId of layerIds) {
1520
+ const layer = graph.getNode(layerId);
1521
+ if (!layer) continue;
1522
+ const name = claimName(identifierName(layer.name, "Component"), taken);
1523
+ const model = componentModel(graph, layer, {
1524
+ ...options,
1525
+ name,
1526
+ references: /* @__PURE__ */ new Map()
1527
+ });
1528
+ if (!model) continue;
1529
+ const { files } = await generate(model, {
1530
+ styling: options.styling,
1531
+ icons: options.icons
1532
+ });
1533
+ components.push({
1534
+ name,
1535
+ layerId,
1536
+ files
1537
+ });
1538
+ }
1539
+ return components;
1540
+ }
1541
+ /** The state element each element of markup built from it draws, which it builds one for one. */
1542
+ function drawnBy(state, design, found) {
1543
+ if (state.type === "text" || design.type === "text") return;
1544
+ found.set(design, state);
1545
+ for (const [child, built] of zip(state.children, design.children)) drawnBy(child, built, found);
1546
+ }
1547
+ /** The layer of each element `serializeHTML` writes for the document, in the order they open. */
1548
+ function markupLayers(graph, styles, document) {
1549
+ const states = /* @__PURE__ */ new Map();
1550
+ for (const root of document.children) drawnBy(styles.root, root, states);
1551
+ return serializedElements(document).map((element) => {
1552
+ const state = element && states.get(element);
1553
+ return (state && restLayerOf(graph, styles, state)) ?? null;
1554
+ });
1555
+ }
1556
+ /**
1557
+ * Layers as indented HTML with a readable class per layer and one stylesheet, as the generated
1558
+ * components draw them, or with Tailwind utilities in place of the classes and no stylesheet.
1559
+ * Images are files under `assetBasePath` rather than inlined.
1560
+ */
1561
+ async function layerMarkup(graph, layerIds, options = {}) {
1562
+ const taken = /* @__PURE__ */ new Set();
1563
+ const html = [];
1564
+ const layers = [];
1565
+ const css = [];
1566
+ for (const layerId of layerIds) {
1567
+ const layer = graph.getNode(layerId);
1568
+ const styles = layer && stateStyles(graph, layer, options);
1569
+ if (!layer || !styles) continue;
1570
+ const name = claimName(styles.name, taken, { separator: " " });
1571
+ const named = {
1572
+ ...styles,
1573
+ name
1574
+ };
1575
+ const sheet = options.styling === "tailwind" ? {
1576
+ document: stateStylesToTailwind(named),
1577
+ css: ""
1578
+ } : await stateStylesToCSS(named);
1579
+ html.push(serializeHTML(sheet.document, { indent: true }));
1580
+ layers.push(...markupLayers(graph, named, sheet.document));
1581
+ if (sheet.css) css.push(sheet.css);
1582
+ }
1583
+ const { html: page, files } = extractImageAssets(html.join("\n\n"), options.assetBasePath ?? "assets");
1584
+ return {
1585
+ html: page,
1586
+ layerIds: layers,
1587
+ css: css.join("\n"),
1588
+ images: files
1589
+ };
1590
+ }
1591
+ //#endregion
1592
+ export { COMPONENT_STYLINGS, LAYER_COMPONENT_FRAMEWORKS, SHADER_UTILITIES, componentModel, layerComponents, layerMarkup, reactComponent, shaderEffectAttributes, vueComponent };
1593
+
1594
+ //# sourceMappingURL=layers.js.map