@pairdraw/dom-css 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (139) 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 +1599 -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 +88 -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 +412 -0
  91. package/src/export/components/react/props.ts +151 -0
  92. package/src/export/components/react/radix.ts +52 -0
  93. package/src/export/components/react/shared.ts +76 -0
  94. package/src/export/components/references.ts +212 -0
  95. package/src/export/components/repeats.ts +128 -0
  96. package/src/export/components/shaders.ts +125 -0
  97. package/src/export/components/styling.ts +31 -0
  98. package/src/export/components/tree.ts +72 -0
  99. package/src/export/components/vue.ts +517 -0
  100. package/src/export/css.ts +57 -0
  101. package/src/export/grid.ts +42 -0
  102. package/src/export/html.ts +163 -0
  103. package/src/export/index.ts +44 -0
  104. package/src/export/projection.ts +581 -0
  105. package/src/export/storybook/component.ts +334 -0
  106. package/src/export/storybook/export.ts +430 -0
  107. package/src/export/storybook/groups.ts +161 -0
  108. package/src/export/storybook/module.ts +319 -0
  109. package/src/export/storybook/names.ts +51 -0
  110. package/src/export/tailwind-jsx.ts +156 -0
  111. package/src/export/text.ts +415 -0
  112. package/src/import/css-text.ts +4 -0
  113. package/src/import/css-values.ts +31 -0
  114. package/src/import/flow.ts +248 -0
  115. package/src/import/html.ts +88 -0
  116. package/src/import/jsx/core.ts +130 -0
  117. package/src/import/jsx/dev-runtime.ts +8 -0
  118. package/src/import/jsx/runtime.ts +76 -0
  119. package/src/import/scene-graph.ts +582 -0
  120. package/src/import/style-attribute.ts +25 -0
  121. package/src/import/tailwind.ts +54 -0
  122. package/src/import/text.ts +518 -0
  123. package/src/index.ts +51 -0
  124. package/src/runtime/browser/runtime.ts +301 -0
  125. package/src/runtime/headless/runtime.ts +99 -0
  126. package/src/runtime/headless/styles.ts +330 -0
  127. package/src/runtime/index.ts +11 -0
  128. package/src/tokens/conditions.ts +66 -0
  129. package/src/tokens/cssom-validator.ts +8 -0
  130. package/src/tokens/custom-properties.ts +331 -0
  131. package/src/tokens/expression.ts +128 -0
  132. package/src/tokens/formula.ts +140 -0
  133. package/src/tokens/index.ts +43 -0
  134. package/src/tokens/names.ts +161 -0
  135. package/src/tokens/references.ts +201 -0
  136. package/src/tokens/stylesheet.ts +304 -0
  137. package/src/tokens/validate.ts +86 -0
  138. package/src/tokens/values.ts +44 -0
  139. package/src/types.ts +59 -0
@@ -0,0 +1,412 @@
1
+ import { HEADING_RESET } from '#dom-css/behaviours/reset'
2
+ import { stateStylesToCSS } from '#dom-css/behaviours/states/css'
3
+ import dedent from 'dedent'
4
+ import { compact } from 'es-toolkit/array'
5
+ import { omit } from 'es-toolkit/object'
6
+ import { camelCase } from 'es-toolkit/string'
7
+
8
+ import { es, jsx } from '@pairdraw/emit'
9
+ import type { ShaderComponent } from '@pairdraw/scene-graph/shaders'
10
+
11
+ import { drawingImports, iconDrawing, iconImportDeclarations, iconNamer } from '../icons'
12
+ import type { ComponentElement, ComponentGenerator, ComponentNode, GeneratedKind } from '../model'
13
+ import type { ComponentReference, IconReference } from '../references'
14
+ import {
15
+ drawnEffects,
16
+ SHADER_CANVAS,
17
+ shaderCSS,
18
+ shaderEffectAttributes,
19
+ shaderEffectName,
20
+ shaderImport,
21
+ type ShaderLayer
22
+ } from '../shaders'
23
+ import { componentClasses } from '../styling'
24
+ import {
25
+ INPUT_PROPS,
26
+ inputElement,
27
+ NUMBER_STATE,
28
+ partAttributes,
29
+ prepend,
30
+ STEPPERS
31
+ } from './fields'
32
+ import { parameters, propsType, reactImport, SINGLE_PROPS, valueArg } from './props'
33
+ import { defaultOf, PRIMITIVE, RADIX } from './radix'
34
+ import { classValue, drawing, elementLayers, moduleClass, numeric, type MarkupUses } from './shared'
35
+
36
+ /** What a group's root fixes: one item chosen at a time, and an accordion that can all close. */
37
+ const ROOT_ATTRIBUTES: Partial<Record<GeneratedKind, es.SyntaxNode[]>> = {
38
+ toggleGroup: [jsx.attribute('type', jsx.stringValue('single'))],
39
+ accordion: [jsx.attribute('type', jsx.stringValue('single')), jsx.attribute('collapsible', null)]
40
+ }
41
+
42
+ const HEADING_STYLE = jsx.container(
43
+ es.object(
44
+ Object.entries(HEADING_RESET).map(
45
+ ([property, value]) => [camelCase(property), es.string(value)] as const
46
+ )
47
+ )
48
+ )
49
+
50
+ /** Several classes on one element, skipping a caller's that is absent. */
51
+ const CLASS_NAMES = es.parseExpression("$classes.filter(Boolean).join(' ')")
52
+
53
+ /** Whether a layer renders as a native button: a button's root, or a number field's stepper. */
54
+ const isNativeButton = (node: ComponentElement, kind: GeneratedKind) =>
55
+ (kind === 'button' && node.part === 'root') ||
56
+ (kind === 'numberField' && node.part !== null && Object.hasOwn(STEPPERS, node.part))
57
+
58
+ /** A Radix primitive's part, a native button, or the design's tag. */
59
+ function tagOf(node: ComponentElement, kind: GeneratedKind): string {
60
+ const radix = RADIX[kind]
61
+ const part = node.part ? radix?.parts[node.part] : undefined
62
+ if (radix && part) return `${PRIMITIVE(radix.namespace)}.${part}`
63
+ return isNativeButton(node, kind) ? 'button' : node.tag
64
+ }
65
+
66
+ /** `disabled || undefined`, so a native root sets `data-disabled` only while disabled. */
67
+ const disabledFlag = (kind: GeneratedKind) =>
68
+ es.parseExpression(
69
+ kind === 'numberField' ? 'disabled || undefined' : 'props.disabled || undefined'
70
+ )
71
+
72
+ /** The Iconify component, named apart from any component the design calls `Icon`. */
73
+ const ICONIFY = 'IconifyIcon'
74
+
75
+ /** An icon: its package's own component where it has the icon, Iconify's otherwise. */
76
+ function iconElement(node: IconReference, uses: MarkupUses, depth: number): es.SyntaxNode {
77
+ const className = jsx.attribute('className', classValue(uses.classOf(node.className)))
78
+ const found = iconDrawing(node.icon, uses.iconPackage, 'react')
79
+ const drawn = found && uses.nameIcon(found)
80
+ if (!drawn) {
81
+ uses.icons = true
82
+ return jsx.element(
83
+ ICONIFY,
84
+ [jsx.attribute('icon', jsx.stringValue(node.icon)), className],
85
+ [],
86
+ depth
87
+ )
88
+ }
89
+ uses.iconImports.push(...drawingImports(drawn))
90
+ if (drawn.type === 'component') return jsx.element(drawn.import.local, [className], [], depth)
91
+ return jsx.element(
92
+ drawn.component.local,
93
+ [jsx.attribute('icon', jsx.container(es.identifier(drawn.import.local))), className],
94
+ [],
95
+ depth
96
+ )
97
+ }
98
+
99
+ /** A reference's prop value: a bare name for true, `{false}`, or a string. */
100
+ function referenceValue(value: string | boolean): es.SyntaxNode | null {
101
+ if (value === true) return null
102
+ if (value === false) return jsx.container(jsx.literal(false))
103
+ return jsx.stringValue(value)
104
+ }
105
+
106
+ function reference(node: ComponentReference, uses: MarkupUses, depth: number): es.SyntaxNode {
107
+ uses.components.add(node.component)
108
+ return drawing(
109
+ jsx.element(
110
+ node.component,
111
+ [
112
+ jsx.attribute('className', classValue(uses.classOf(node.className))),
113
+ ...node.props.map((prop) => jsx.attribute(prop.name, referenceValue(prop.value))),
114
+ ...(node.model ? [jsx.attribute(defaultOf(node.model), null)] : [])
115
+ ],
116
+ [],
117
+ depth
118
+ ),
119
+ node.layerId,
120
+ uses
121
+ )
122
+ }
123
+
124
+ function element(node: ComponentNode, uses: MarkupUses, depth: number): es.SyntaxNode {
125
+ if (node.type === 'text') return jsx.text(node.value)
126
+ if (node.type === 'textProp') return jsx.container(es.identifier(node.name))
127
+ if (node.type === 'reference') return reference(node, uses, depth)
128
+ if (node.type === 'input')
129
+ return drawing(inputElement(node.className, uses, depth), node.layerId, uses)
130
+ if (node.type === 'icon') return drawing(iconElement(node, uses, depth), node.layerId, uses)
131
+ return designElement(node, uses, depth)
132
+ }
133
+
134
+ /**
135
+ * The design's own classes, the state styles' module class, and on the root the caller's,
136
+ * which the spread would otherwise lose to the generated one.
137
+ */
138
+ function classNameOf(node: ComponentElement, root: boolean, uses: MarkupUses): es.SyntaxNode {
139
+ const classes = [
140
+ ...(node.attrs.class ? [es.string(node.attrs.class)] : []),
141
+ uses.classOf(node.className),
142
+ ...(root ? [es.parseExpression('props.className')] : [])
143
+ ]
144
+ const only = classes.length === 1 ? classes.at(0) : undefined
145
+ return only ?? es.fill(CLASS_NAMES, { $classes: es.array(classes) })
146
+ }
147
+
148
+ /**
149
+ * What a root fixes before the caller's props: a group's single choice and its start, and a
150
+ * slider's or progress bar's range and the value it starts at.
151
+ */
152
+ function rootAttributes(uses: MarkupUses): es.SyntaxNode[] {
153
+ const { component } = uses
154
+ const start = uses.choice?.default
155
+ const { range } = component
156
+ return [
157
+ ...(ROOT_ATTRIBUTES[uses.kind] ?? []),
158
+ // A choice starts on the design's option, which the caller's props can change.
159
+ ...(start ? [jsx.attribute('defaultValue', jsx.stringValue(start))] : []),
160
+ ...(range && uses.kind === 'slider'
161
+ ? [
162
+ jsx.attribute('defaultValue', jsx.container(es.array([es.number(range.default)]))),
163
+ numeric('min', range.min),
164
+ numeric('max', range.max),
165
+ numeric('step', range.step)
166
+ ]
167
+ : []),
168
+ ...(range && uses.kind === 'progress'
169
+ ? [
170
+ // Radix takes a value within its range, as the indicator draws one.
171
+ jsx.attribute(
172
+ 'value',
173
+ jsx.container(
174
+ es.fill(es.parseExpression('Math.min($max, Math.max($min, value))'), {
175
+ $min: es.number(range.min),
176
+ $max: es.number(range.max)
177
+ })
178
+ )
179
+ ),
180
+ numeric('max', range.max)
181
+ ]
182
+ : [])
183
+ ]
184
+ }
185
+
186
+ function bindingAttributes(
187
+ node: ComponentElement,
188
+ kind: GeneratedKind,
189
+ native: boolean
190
+ ): es.SyntaxNode[] {
191
+ return node.bindings.flatMap((binding) => {
192
+ if (binding.type === 'prop')
193
+ return [jsx.attribute(binding.attribute, jsx.container(es.identifier(binding.prop.name)))]
194
+ // Radix sets `data-disabled` on its own roots; a native root needs it for the styles.
195
+ if (binding.type === 'disabled' && native)
196
+ return [jsx.attribute('data-disabled', jsx.container(disabledFlag(kind)))]
197
+ return []
198
+ })
199
+ }
200
+
201
+ /** A shader playing behind its layer's content, with telemetry off, as every export has it. */
202
+ function shaderCanvas(shader: ShaderLayer, uses: MarkupUses, depth: number): es.SyntaxNode {
203
+ const effect =
204
+ (at: number) =>
205
+ (component: ShaderComponent): es.SyntaxNode => {
206
+ uses.shaders.add(component.type)
207
+ const children = drawnEffects(component.children).map(effect(at + 1))
208
+ return jsx.element(
209
+ shaderEffectName(component.type),
210
+ shaderEffectAttributes(component),
211
+ children,
212
+ at
213
+ )
214
+ }
215
+ return jsx.element(
216
+ SHADER_CANVAS,
217
+ [
218
+ jsx.attribute('className', classValue(uses.classOf(shader.className))),
219
+ jsx.attribute('disableTelemetry', null)
220
+ ],
221
+ drawnEffects(shader.preset.components).map(effect(depth + 1)),
222
+ depth
223
+ )
224
+ }
225
+
226
+ /** Words alone stay on the element's line, where a line break would add a space. */
227
+ function wordsOnly(node: ComponentElement): boolean {
228
+ const only = node.children.length === 1 ? node.children[0]?.type : undefined
229
+ return !node.slot && !node.shader && (only === 'text' || only === 'textProp')
230
+ }
231
+
232
+ function designElement(node: ComponentElement, uses: MarkupUses, depth: number): es.SyntaxNode {
233
+ const kind = uses.kind
234
+ const root = node.part === 'root'
235
+ const native = root && !(node.part && RADIX[kind]?.parts[node.part])
236
+ const attributes = [
237
+ ...(isNativeButton(node, kind) ? [jsx.attribute('type', jsx.stringValue('button'))] : []),
238
+ ...(root ? rootAttributes(uses) : []),
239
+ // The root passes the caller's props on, such as `checked` or `onClick`, unless its input
240
+ // takes them.
241
+ ...(root && !INPUT_PROPS[kind] ? [jsx.spread(es.identifier('props'))] : []),
242
+ ...(node.value === undefined ? [] : [jsx.attribute('value', jsx.stringValue(node.value))]),
243
+ ...Object.entries(omit(node.attrs, ['class'])).map(([name, value]) =>
244
+ jsx.attribute(name, jsx.stringValue(value))
245
+ ),
246
+ ...partAttributes(node, uses),
247
+ jsx.attribute('className', classValue(classNameOf(node, root, uses))),
248
+ ...bindingAttributes(node, kind, native)
249
+ ]
250
+ const inline = wordsOnly(node)
251
+ // Radix puts an accordion item's trigger in a header, which carries the heading level.
252
+ const header = kind === 'accordionItem' && node.part === 'trigger'
253
+ const childDepth = depth + (header ? 2 : 1)
254
+ const content = node.children.map((child) => element(child, uses, childDepth))
255
+ const shader = node.shader ? [shaderCanvas(node.shader, uses, childDepth)] : []
256
+ const drawn = drawing(
257
+ jsx.element(
258
+ tagOf(node, kind),
259
+ attributes,
260
+ [...shader, ...(node.slot ? [slotContent(node.slot, content, childDepth)] : content)],
261
+ depth + (header ? 1 : 0),
262
+ inline
263
+ ),
264
+ node.layerId,
265
+ uses
266
+ )
267
+ const shown = header
268
+ ? jsx.element(
269
+ `${PRIMITIVE('Accordion')}.Header`,
270
+ [jsx.attribute('style', HEADING_STYLE)],
271
+ [drawn],
272
+ depth
273
+ )
274
+ : drawn
275
+ return node.shownBy ? whenShown(node.shownBy, shown) : shown
276
+ }
277
+
278
+ const LOGICAL = (operator: '&&' | '??', left: es.SyntaxNode, right: es.SyntaxNode) => ({
279
+ type: 'LogicalExpression',
280
+ operator,
281
+ left,
282
+ right
283
+ })
284
+
285
+ /** `{content ?? <>…</>}`: what the caller passes for a slot, or the design's content. */
286
+ function slotContent(slot: string, children: es.SyntaxNode[], depth: number): es.SyntaxNode {
287
+ return jsx.container(LOGICAL('??', es.identifier(slot), jsx.fragment(children, depth)))
288
+ }
289
+
290
+ /** `{showIcon && <…/>}`: a layer a boolean prop shows. */
291
+ function whenShown(prop: string, drawn: es.SyntaxNode): es.SyntaxNode {
292
+ return jsx.container(LOGICAL('&&', es.identifier(prop), drawn))
293
+ }
294
+
295
+ const MODULE = es.parseModule(dedent`
296
+ import type { ComponentProps } from 'react'
297
+
298
+ import styles from '$styles'
299
+
300
+ export type $Props = $Type
301
+
302
+ export function $Name($params: $Props) {
303
+ return $body
304
+ }
305
+ `)
306
+
307
+ const RADIX_IMPORT = es.parseModule(`import { $Namespace as $Primitive } from 'radix-ui'`)
308
+ const ICONIFY_IMPORT = es.parseModule(`import { Icon as ${ICONIFY} } from '@iconify/react'`).body
309
+ const IMPORT_COMPONENT = es.parseModule(`import { $Component } from '$path'`)
310
+
311
+ /**
312
+ * A component as a React component on Radix UI: its parts as Radix primitives from the
313
+ * `radix-ui` package, its variants' state styles in a CSS module, and props that extend the
314
+ * Radix root's with its other variant properties.
315
+ */
316
+ export const reactComponent: ComponentGenerator = async (component, options = {}) => {
317
+ const styling = options.styling ?? 'css'
318
+ const radix = RADIX[component.kind]
319
+ const stylesPath = `${component.name}.module.css`
320
+ const classOf = componentClasses(component, styling)
321
+ const uses: MarkupUses = {
322
+ component,
323
+ // Styled with Tailwind, a layer's utilities are written out; otherwise its module class.
324
+ classOf: (className) =>
325
+ styling === 'css' ? moduleClass(className) : es.string(classOf(className)),
326
+ kind: component.kind,
327
+ choice: component.choice,
328
+ components: new Set(),
329
+ layers: new WeakMap(),
330
+ icons: false,
331
+ iconPackage: options.icons ?? 'iconify',
332
+ iconImports: [],
333
+ nameIcon: iconNamer(component, [
334
+ ICONIFY,
335
+ 'styles',
336
+ `${component.name}Props`,
337
+ ...(radix ? [radix.namespace, PRIMITIVE(radix.namespace)] : [])
338
+ ]),
339
+ shaders: new Set()
340
+ }
341
+ const body = element(component.tree, uses, 1)
342
+ const imports = [
343
+ ...(uses.icons ? ICONIFY_IMPORT : []),
344
+ ...iconImportDeclarations(uses.iconImports),
345
+ ...(uses.shaders.size > 0 ? [shaderImport('shaders/react', uses.shaders)] : []),
346
+ ...(radix
347
+ ? es.fill(RADIX_IMPORT, {
348
+ $Namespace: es.identifier(radix.namespace),
349
+ $Primitive: es.identifier(PRIMITIVE(radix.namespace))
350
+ }).body
351
+ : []),
352
+ ...[...uses.components].sort().flatMap(
353
+ (name) =>
354
+ es.fill(IMPORT_COMPONENT, {
355
+ $Component: es.identifier(name),
356
+ $path: es.string(`./${name}`)
357
+ }).body
358
+ )
359
+ ]
360
+ const [, stylesImport, ...rest] = es.fill(MODULE, {
361
+ $styles: es.string(`./${stylesPath}`),
362
+ $Props: es.identifier(`${component.name}Props`),
363
+ $Type: propsType(component),
364
+ $Name: es.identifier(component.name),
365
+ $params: parameters(component),
366
+ $body: body
367
+ }).body
368
+ const state =
369
+ component.kind === 'numberField' && component.range ? NUMBER_STATE(component.range) : []
370
+ prepend(rest.at(-1), state)
371
+ const react = reactImport({
372
+ state: state.length > 0,
373
+ // A single choice group's props come from Radix's own type, not `ComponentProps`.
374
+ props: !SINGLE_PROPS[component.kind],
375
+ slots: component.slots.length > 0
376
+ })
377
+ const program = {
378
+ type: 'Program',
379
+ sourceType: 'module',
380
+ body: [...react, ...imports, ...(styling === 'css' ? [stylesImport] : []), ...rest]
381
+ }
382
+ // Tailwind styles the markup itself; a CSS module is written beside it otherwise.
383
+ const stylesheet =
384
+ styling === 'css'
385
+ ? [
386
+ {
387
+ path: stylesPath,
388
+ content: compact([
389
+ (await stateStylesToCSS(component.styles)).css,
390
+ shaderCSS(component.tree)
391
+ ]).join('\n')
392
+ }
393
+ ]
394
+ : []
395
+ const model = component.model
396
+ // A group's items are their own component, which the group's markup uses.
397
+ const item = component.item ? await reactComponent(component.item, options) : null
398
+ return {
399
+ files: [
400
+ ...(item?.files ?? []),
401
+ {
402
+ path: `${component.name}.tsx`,
403
+ content: `${jsx.printModule(program)}\n`,
404
+ // The template is filled with copies, so the body, which holds all the JSX, is read.
405
+ layerIds: elementLayers(body, uses.layers)
406
+ },
407
+ ...stylesheet
408
+ ],
409
+ entry: { path: `./${component.name}`, named: true },
410
+ ...valueArg(component.kind, model)
411
+ }
412
+ }
@@ -0,0 +1,151 @@
1
+ import { es } from '@pairdraw/emit'
2
+
3
+ import type { ComponentModel, GeneratedComponent, GeneratedKind } from '../model'
4
+ import { kindParameters, type Parameter } from './fields'
5
+ import { defaultOf, PRIMITIVE, RADIX } from './radix'
6
+
7
+ /**
8
+ * The props of a group that fixes one choice at a time, without the `type` it fixes. The
9
+ * root's own props join the single and multiple choice, which a single value can't satisfy.
10
+ */
11
+ export const SINGLE_PROPS: Partial<Record<GeneratedKind, string>> = {
12
+ toggleGroup: 'ToggleGroupSingleProps',
13
+ accordion: 'AccordionSingleProps'
14
+ }
15
+
16
+ const qualified = (namespace: string, name: string) => ({
17
+ type: 'TSQualifiedName',
18
+ left: es.identifier(PRIMITIVE(namespace)),
19
+ right: es.identifier(name)
20
+ })
21
+
22
+ /** Props a kind declares itself, where no Radix root has them. */
23
+ const OWN_PROPS: Partial<Record<GeneratedKind, string>> = {
24
+ progress: "Omit<ComponentProps<typeof ProgressPrimitive.Root>, 'value'> & { value?: number }",
25
+ numberField:
26
+ "Omit<ComponentProps<'div'>, 'defaultValue' | 'onChange'> & { defaultValue?: number; onValueChange?: (value: number) => void; disabled?: boolean }",
27
+ textField: "ComponentProps<'input'>",
28
+ textarea: "ComponentProps<'textarea'>"
29
+ }
30
+
31
+ /** The root's own props, or a single choice group's. */
32
+ function rootPropsType(kind: GeneratedKind, tag: string): es.SyntaxNode {
33
+ const own = OWN_PROPS[kind]
34
+ if (own) return es.parseType(own)
35
+ // A component without a behaviour takes its root element's props.
36
+ if (kind === 'plain') return es.parseType(`ComponentProps<'${tag}'>`)
37
+ const radix = RADIX[kind]
38
+ if (!radix) return es.parseType("ComponentProps<'button'>")
39
+ const single = SINGLE_PROPS[kind]
40
+ if (single)
41
+ return es.fill(es.parseType("Omit<$Props, 'type'>"), {
42
+ $Props: qualified(radix.namespace, single)
43
+ })
44
+ return es.fill(es.parseType('ComponentProps<typeof $Root>'), {
45
+ $Root: qualified(radix.namespace, radix.parts.root)
46
+ })
47
+ }
48
+
49
+ /** The root's own props, extended with the component's variant props when it has any. */
50
+ export function propsType(component: ComponentModel): es.SyntaxNode {
51
+ const base = rootPropsType(component.kind, component.tree.tag)
52
+ const own = [component.props, component.texts, component.booleans, component.slots]
53
+ if (own.every((list) => list.length === 0)) return base
54
+ return {
55
+ type: 'TSIntersectionType',
56
+ types: [
57
+ base,
58
+ es.objectType([
59
+ ...component.props.map((prop): [string, es.SyntaxNode, boolean] => [
60
+ prop.name,
61
+ es.stringUnionType(prop.options),
62
+ true
63
+ ]),
64
+ ...component.texts.map((text): [string, es.SyntaxNode, boolean] => [
65
+ text.name,
66
+ es.parseType('string'),
67
+ true
68
+ ]),
69
+ ...component.booleans.map((prop): [string, es.SyntaxNode, boolean] => [
70
+ prop.name,
71
+ es.parseType('boolean'),
72
+ true
73
+ ]),
74
+ ...component.slots.map((slot): [string, es.SyntaxNode, boolean] => [
75
+ slot.name,
76
+ es.parseType('ReactNode'),
77
+ true
78
+ ])
79
+ ])
80
+ ]
81
+ }
82
+ }
83
+
84
+ /**
85
+ * `{ size = 'Small', label = 'Save', ...props }`: variant and text props with their defaults,
86
+ * kept off the root, and the rest passed on.
87
+ */
88
+ export function parameters(component: ComponentModel): es.SyntaxNode {
89
+ const own: Parameter[] = [
90
+ ...kindParameters(component),
91
+ ...[...component.props, ...component.texts].map((prop) => ({
92
+ name: prop.name,
93
+ default: es.string(prop.default)
94
+ })),
95
+ ...component.booleans.map((prop) => ({
96
+ name: prop.name,
97
+ default: es.parseExpression(String(prop.default))
98
+ })),
99
+ // Slots are kept off the root too, which would otherwise get them as attributes.
100
+ ...component.slots.map((slot) => ({ name: slot.name }))
101
+ ]
102
+ if (own.length === 0) return es.identifier('props')
103
+ return {
104
+ type: 'ObjectPattern',
105
+ properties: [
106
+ ...own.map((prop) => ({
107
+ type: 'Property',
108
+ kind: 'init',
109
+ key: es.identifier(prop.name),
110
+ value: prop.default
111
+ ? { type: 'AssignmentPattern', left: es.identifier(prop.name), right: prop.default }
112
+ : es.identifier(prop.name),
113
+ computed: false,
114
+ method: false,
115
+ shorthand: true
116
+ })),
117
+ { type: 'RestElement', argument: es.identifier('props') }
118
+ ]
119
+ }
120
+ }
121
+
122
+ /**
123
+ * `import { useState, type ComponentProps, type ReactNode } from 'react'` with only what the
124
+ * component uses: a number field's state, its root's props, and its slots' content.
125
+ */
126
+ export function reactImport(uses: {
127
+ state: boolean
128
+ props: boolean
129
+ slots: boolean
130
+ }): es.SyntaxNode[] {
131
+ const types = [...(uses.props ? ['ComponentProps'] : []), ...(uses.slots ? ['ReactNode'] : [])]
132
+ if (!uses.state && types.length === 0) return []
133
+ const specifiers = uses.state
134
+ ? ['useState', ...types.map((name) => `type ${name}`)].join(', ')
135
+ : types.join(', ')
136
+ return es.parseModule(`import ${uses.state ? '' : 'type '}{ ${specifiers} } from 'react'`).body
137
+ }
138
+
139
+ /**
140
+ * The prop a story sets the value with: Radix's uncontrolled value, so a story's control and
141
+ * its play function can both change it, which a slider takes as a list; a progress bar's own
142
+ * value, which nothing else changes.
143
+ */
144
+ export function valueArg(
145
+ kind: GeneratedKind,
146
+ model: string | null
147
+ ): Pick<GeneratedComponent, 'valueArg' | 'valueList'> {
148
+ if (!model) return { valueArg: null }
149
+ if (kind === 'progress') return { valueArg: 'value' }
150
+ return { valueArg: defaultOf(model), ...(kind === 'slider' ? { valueList: true } : {}) }
151
+ }
@@ -0,0 +1,52 @@
1
+ import { upperFirst } from 'es-toolkit/string'
2
+
3
+ import type { GeneratedKind } from '../model'
4
+
5
+ /**
6
+ * The Radix primitive a kind renders, from the unified `radix-ui` package, and the component
7
+ * of it each part uses. Its root takes the value two ways (`checked` and `onCheckedChange`,
8
+ * `pressed`, `open`) and `disabled` itself, so the generated props extend the root's.
9
+ */
10
+ export const RADIX: Record<
11
+ GeneratedKind,
12
+ { namespace: string; parts: Record<string, string> } | null
13
+ > = {
14
+ button: null,
15
+ switch: { namespace: 'Switch', parts: { root: 'Root', thumb: 'Thumb' } },
16
+ checkbox: { namespace: 'Checkbox', parts: { root: 'Root', indicator: 'Indicator' } },
17
+ toggle: { namespace: 'Toggle', parts: { root: 'Root' } },
18
+ collapsible: {
19
+ namespace: 'Collapsible',
20
+ parts: { root: 'Root', trigger: 'Trigger', content: 'Content' }
21
+ },
22
+ tabs: {
23
+ namespace: 'Tabs',
24
+ parts: { root: 'Root', list: 'List', trigger: 'Trigger', content: 'Content' }
25
+ },
26
+ radioGroup: { namespace: 'RadioGroup', parts: { root: 'Root' } },
27
+ toggleGroup: { namespace: 'ToggleGroup', parts: { root: 'Root' } },
28
+ accordion: { namespace: 'Accordion', parts: { root: 'Root' } },
29
+ radioGroupItem: { namespace: 'RadioGroup', parts: { root: 'Item', indicator: 'Indicator' } },
30
+ toggleGroupItem: { namespace: 'ToggleGroup', parts: { root: 'Item' } },
31
+ accordionItem: {
32
+ namespace: 'Accordion',
33
+ parts: { root: 'Item', trigger: 'Trigger', content: 'Content' }
34
+ },
35
+ slider: {
36
+ namespace: 'Slider',
37
+ parts: { root: 'Root', track: 'Track', range: 'Range', thumb: 'Thumb' }
38
+ },
39
+ progress: { namespace: 'Progress', parts: { root: 'Root', indicator: 'Indicator' } },
40
+ // Radix has no number or text field; these are native inputs in the design's own elements.
41
+ numberField: null,
42
+ textField: null,
43
+ textarea: null,
44
+ // A component without a behaviour is the design's own elements.
45
+ plain: null
46
+ }
47
+
48
+ /** The local name a Radix namespace is imported as, such as `SwitchPrimitive`. */
49
+ export const PRIMITIVE = (namespace: string) => `${namespace}Primitive`
50
+
51
+ /** `defaultChecked`: Radix's uncontrolled value, which a nested control starts from. */
52
+ export const defaultOf = (model: string) => `default${upperFirst(model)}`
@@ -0,0 +1,76 @@
1
+ import { es, jsx } from '@pairdraw/emit'
2
+
3
+ import type { IconDrawing, IconImport, IconPackage } from '../icons'
4
+ import type { ComponentModel, GeneratedKind } from '../model'
5
+
6
+ /** `styles.thumb`, or `styles['switch-thumb']` for a class that isn't an identifier. */
7
+ export function moduleClass(className: string): es.SyntaxNode {
8
+ return {
9
+ type: 'MemberExpression',
10
+ object: es.identifier('styles'),
11
+ property: es.isIdentifierName(className) ? es.identifier(className) : es.string(className),
12
+ computed: !es.isIdentifierName(className),
13
+ optional: false
14
+ }
15
+ }
16
+
17
+ /** What a component's markup uses, which its module imports. */
18
+ export interface MarkupUses {
19
+ component: ComponentModel
20
+ kind: GeneratedKind
21
+ choice: ComponentModel['choice']
22
+ /** Other generated components. */
23
+ components: Set<string>
24
+ /** Whether an icon is drawn by Iconify. */
25
+ icons: boolean
26
+ /** The package icons come from, and what the icons drawn from it import. */
27
+ iconPackage: IconPackage
28
+ iconImports: IconImport[]
29
+ /** Names an icon's imports apart from the component's other names. */
30
+ nameIcon: (drawing: IconDrawing) => IconDrawing
31
+ /** A layer's class as the component is styled: its CSS module class, or its utilities. */
32
+ classOf: (className: string) => es.SyntaxNode
33
+ /** The layer each JSX element draws, which code links back to. */
34
+ layers: WeakMap<es.SyntaxNode, string>
35
+ /** Effects of the `shaders` library its layers fill with. */
36
+ shaders: Set<string>
37
+ }
38
+
39
+ export const numeric = (name: string, value: number) =>
40
+ jsx.attribute(name, jsx.container(es.number(value)))
41
+
42
+ /** A `className` value: a plain string as an attribute string, anything else in braces. */
43
+ export function classValue(value: es.SyntaxNode): es.SyntaxNode {
44
+ return value.type === 'Literal' && typeof value.value === 'string'
45
+ ? jsx.stringValue(value.value)
46
+ : jsx.container(value)
47
+ }
48
+
49
+ /** `element`, recorded as drawing `layerId`, so code can link back to that layer. */
50
+ export function drawing(
51
+ element: es.SyntaxNode,
52
+ layerId: string | undefined,
53
+ uses: MarkupUses
54
+ ): es.SyntaxNode {
55
+ if (layerId) uses.layers.set(element, layerId)
56
+ return element
57
+ }
58
+
59
+ /** The layer of each JSX element in `program`, in the order the elements open. */
60
+ export function elementLayers(
61
+ program: es.SyntaxNode,
62
+ layers: WeakMap<es.SyntaxNode, string>
63
+ ): (string | null)[] {
64
+ const found: (string | null)[] = []
65
+ const visit = (value: unknown) => {
66
+ if (Array.isArray(value)) {
67
+ for (const item of value) visit(item)
68
+ return
69
+ }
70
+ if (!es.isNode(value)) return
71
+ if (value.type === 'JSXElement') found.push(layers.get(value) ?? null)
72
+ for (const item of Object.values(value)) visit(item)
73
+ }
74
+ visit(program)
75
+ return found
76
+ }