@pairdraw/dom-css 0.17.0 → 0.19.0-beta.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.
package/src/export/css.ts CHANGED
@@ -1,6 +1,16 @@
1
- import type { Effect, Fill, ShadowEffect, Stroke, TextLength } from '@pairdraw/scene-graph'
1
+ import type {
2
+ Effect,
3
+ Fill,
4
+ GradientStop,
5
+ SceneNode,
6
+ ShadowEffect,
7
+ Stroke,
8
+ TextLength
9
+ } from '@pairdraw/scene-graph'
2
10
  import { colorToCSS, colorToHex } from '@pairdraw/scene-graph/color'
3
- import type { Color } from '@pairdraw/scene-graph/primitives'
11
+ import { blurSigma } from '@pairdraw/scene-graph/geometry'
12
+ import { gradientPoint } from '@pairdraw/scene-graph/gradient'
13
+ import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
4
14
 
5
15
  import type { DesignStyleDeclaration } from '../types'
6
16
 
@@ -14,35 +24,177 @@ export function fillToCSS(fill: Fill | undefined): string | undefined {
14
24
  return cssColor({ ...fill.color, a: fill.opacity })
15
25
  }
16
26
 
27
+ /** A number CSS reads the same back: six decimals, no trailing zeros or negative zero. */
28
+ function cssNumber(value: number): string {
29
+ const rounded = Number(value.toFixed(6))
30
+ return String(rounded === 0 ? 0 : rounded)
31
+ }
32
+
33
+ function stopToCSS(stop: GradientStop, opacity: number): string {
34
+ const color = cssColor({ ...stop.color, a: stop.color.a * opacity })
35
+ return `${color} ${cssNumber(stop.position * 100)}%`
36
+ }
37
+
38
+ /** The unit-square point as a CSS position pair, percentages of the box's width and height. */
39
+ function positionToCSS(point: Vector): string {
40
+ return `${cssNumber(point.x * 100)}% ${cssNumber(point.y * 100)}%`
41
+ }
42
+
43
+ /**
44
+ * A gradient paint as the CSS gradient that draws it in a `width` × `height` box. The transform
45
+ * maps the box's unit square onto gradient space; its inverse gives the line's ends, the
46
+ * ellipse's centre and radii, or the sweep's start ray. Diamond gradients have no CSS spelling.
47
+ */
48
+ export function gradientFillToCSS(fill: Fill, width: number, height: number): string | undefined {
49
+ const transform = fill.gradientTransform
50
+ const stops = fill.gradientStops
51
+ if (!fill.visible || !transform || !stops || stops.length === 0 || width <= 0 || height <= 0) {
52
+ return undefined
53
+ }
54
+ const painted = stops.map((stop) => stopToCSS(stop, fill.opacity)).join(', ')
55
+ if (fill.type === 'GRADIENT_LINEAR') {
56
+ const start = gradientPoint(transform, { x: 0, y: 0.5 })
57
+ const end = gradientPoint(transform, { x: 1, y: 0.5 })
58
+ const dx = (end.x - start.x) * width
59
+ const dy = (end.y - start.y) * height
60
+ if (dx === 0 && dy === 0) return undefined
61
+ // CSS angles point up at 0deg and turn clockwise; screen y grows downward.
62
+ const degrees = (Math.atan2(dx, -dy) * 180) / Math.PI
63
+ return `linear-gradient(${cssNumber(degrees)}deg, ${painted})`
64
+ }
65
+ if (fill.type !== 'GRADIENT_RADIAL' && fill.type !== 'GRADIENT_ANGULAR') return undefined
66
+ const center = gradientPoint(transform, { x: 0.5, y: 0.5 })
67
+ const edgeX = gradientPoint(transform, { x: 1, y: 0.5 })
68
+ const edgeY = gradientPoint(transform, { x: 0.5, y: 1 })
69
+ const rx = Math.hypot((edgeX.x - center.x) * width, (edgeX.y - center.y) * height)
70
+ const ry = Math.hypot((edgeY.x - center.x) * width, (edgeY.y - center.y) * height)
71
+ if (rx <= 0 || ry <= 0) return undefined
72
+ const at = `at ${positionToCSS(center)}`
73
+ if (fill.type === 'GRADIENT_RADIAL') {
74
+ const shape =
75
+ Math.abs(rx - ry) < 1e-6
76
+ ? `circle ${cssNumber(rx)}px`
77
+ : `ellipse ${cssNumber(rx)}px ${cssNumber(ry)}px`
78
+ return `radial-gradient(${shape} ${at}, ${painted})`
79
+ }
80
+ const degrees =
81
+ (Math.atan2((edgeX.y - center.y) * height, (edgeX.x - center.x) * width) * 180) / Math.PI + 90
82
+ return `conic-gradient(from ${cssNumber(degrees)}deg ${at}, ${painted})`
83
+ }
84
+
85
+ /**
86
+ * The paint stack as `background-image`, top layer first as CSS paints it. Solid paints stay
87
+ * out; the bottom one becomes `background-color`, and a solid above another paint has no CSS
88
+ * spelling here. Image paints export through the element's own source, not this list.
89
+ */
90
+ export function gradientFillsToCSS(
91
+ fills: Fill[],
92
+ width: number,
93
+ height: number
94
+ ): string | undefined {
95
+ const layers: string[] = []
96
+ for (let index = fills.length - 1; index >= 0; index--) {
97
+ const css = gradientFillToCSS(fills[index], width, height)
98
+ if (css) layers.push(css)
99
+ }
100
+ return layers.length > 0 ? layers.join(', ') : undefined
101
+ }
102
+
103
+ export type BorderSide = 'top' | 'right' | 'bottom' | 'left'
104
+
105
+ /**
106
+ * The width of each side of the border a layer's first stroke projects as, zero without one. A
107
+ * border insets the box its absolutely positioned children are placed in, where a stroke does not.
108
+ */
109
+ export function borderWidths(node: SceneNode): Record<BorderSide, number> {
110
+ if (!strokeColorToCSS(node.strokes.at(0))) return { top: 0, right: 0, bottom: 0, left: 0 }
111
+ if (!node.independentStrokeWeights) {
112
+ const weight = node.strokes[0]?.weight ?? 0
113
+ return { top: weight, right: weight, bottom: weight, left: weight }
114
+ }
115
+ return {
116
+ top: node.borderTopWeight,
117
+ right: node.borderRightWeight,
118
+ bottom: node.borderBottomWeight,
119
+ left: node.borderLeftWeight
120
+ }
121
+ }
122
+
17
123
  export function strokeColorToCSS(stroke: Stroke | undefined): string | undefined {
18
124
  if (!stroke?.visible) return undefined
19
125
  return cssColor({ ...stroke.color, a: stroke.opacity })
20
126
  }
21
127
 
22
- function shadowToCSS(effect: ShadowEffect): string {
128
+ function px(value: number): string {
129
+ return `${Number(value.toFixed(3))}px`
130
+ }
131
+
132
+ /**
133
+ * A shadow as `box-shadow` writes it, or as `text-shadow` does without its spread. CSS blurs a
134
+ * shadow by half its blur length, so the length is twice the sigma the canvas blurs it by.
135
+ */
136
+ function shadowToCSS(effect: ShadowEffect, spread = true): string {
23
137
  const inset = effect.type === 'INNER_SHADOW' ? 'inset ' : ''
24
- return `${inset}${effect.offset.x}px ${effect.offset.y}px ${effect.radius}px ${effect.spread}px ${cssColor(effect.color)}`
138
+ const parts = [
139
+ `${inset}${px(effect.offset.x)}`,
140
+ px(effect.offset.y),
141
+ px(2 * blurSigma(effect.radius))
142
+ ]
143
+ if (spread) parts.push(px(effect.spread))
144
+ parts.push(cssColor(effect.color))
145
+ return parts.join(' ')
25
146
  }
26
147
 
27
- export function dropShadowToCSS(effect: Effect | undefined): string | undefined {
28
- if (effect?.type !== 'DROP_SHADOW' || !effect.visible) return undefined
29
- return shadowToCSS(effect)
148
+ const isShadow = (effect: Effect): effect is ShadowEffect =>
149
+ effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
150
+
151
+ /**
152
+ * The blurs as the canvas draws them: the first visible layer blur as `filter`, and every
153
+ * background blur in turn as `backdrop-filter`.
154
+ */
155
+ const isLayerBlur = (effect: Effect): effect is ShadowEffect =>
156
+ effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR'
157
+ const isBackgroundBlur = (effect: Effect): effect is ShadowEffect =>
158
+ effect.type === 'BACKGROUND_BLUR'
159
+ const isDropShadow = (effect: Effect): effect is ShadowEffect => effect.type === 'DROP_SHADOW'
160
+
161
+ function addBlurs(style: DesignStyleDeclaration, visible: Effect[]): void {
162
+ const layer = visible.find(isLayerBlur)
163
+ if (layer) style.filter = `blur(${px(blurSigma(layer.radius))})`
164
+ const backdrop = visible.filter(isBackgroundBlur)
165
+ if (backdrop.length > 0) {
166
+ style['backdrop-filter'] = backdrop
167
+ .map((effect) => `blur(${px(blurSigma(effect.radius))})`)
168
+ .join(' ')
169
+ }
30
170
  }
31
171
 
32
- /** Every visible shadow, in order, plus layer and background blur. */
172
+ /**
173
+ * Every visible shadow, in order, plus layer and background blur, blurred as the canvas draws
174
+ * them: CSS's `blur()` takes the Gaussian sigma itself.
175
+ */
33
176
  export function effectsToCSS(effects: Effect[]): DesignStyleDeclaration {
34
177
  const style: DesignStyleDeclaration = {}
35
178
  const visible = effects.filter((effect) => effect.visible)
36
- const shadows = visible.filter(
37
- (effect): effect is ShadowEffect =>
38
- effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW'
39
- )
40
- if (shadows.length > 0) style['box-shadow'] = shadows.map(shadowToCSS).join(', ')
41
- for (const effect of visible) {
42
- if (effect.type === 'LAYER_BLUR' || effect.type === 'FOREGROUND_BLUR')
43
- style.filter = `blur(${effect.radius}px)`
44
- if (effect.type === 'BACKGROUND_BLUR') style['backdrop-filter'] = `blur(${effect.radius}px)`
179
+ const shadows = visible.filter(isShadow)
180
+ if (shadows.length > 0)
181
+ style['box-shadow'] = shadows.map((effect) => shadowToCSS(effect)).join(', ')
182
+ addBlurs(style, visible)
183
+ return style
184
+ }
185
+
186
+ /**
187
+ * Text's effects: each visible drop shadow as `text-shadow`, which has no spread and shadows the
188
+ * glyphs, and its layer and background blurs. An inner shadow has no form CSS gives text.
189
+ */
190
+ export function textEffectsToCSS(effects: Effect[]): DesignStyleDeclaration {
191
+ const style: DesignStyleDeclaration = {}
192
+ const visible = effects.filter((effect) => effect.visible)
193
+ const shadows = visible.filter(isDropShadow)
194
+ if (shadows.length > 0) {
195
+ style['text-shadow'] = shadows.map((effect) => shadowToCSS(effect, false)).join(', ')
45
196
  }
197
+ addBlurs(style, visible)
46
198
  return style
47
199
  }
48
200
 
@@ -55,3 +207,25 @@ export function lineHeightToCSS(length: TextLength): string {
55
207
  export function letterSpacingToCSS(length: TextLength): string {
56
208
  return length.unit === 'PIXELS' ? `${length.value}px` : `${length.value / 100}em`
57
209
  }
210
+
211
+ /**
212
+ * Room for the spacing CSS puts after a line's last letter. A layer fits and aligns its lines by
213
+ * their glyphs, without that spacing, so a spaced text's box is one spacing wider than its own
214
+ * width and a negative margin takes the spacing back: lines break and align as on the canvas, and
215
+ * the text takes the room it does there. Browsers put the spacing on a glyph's right in either
216
+ * direction, so the margin is on the right. `spacing` is the CSS the text's letter spacing is
217
+ * written as, which may refer to a token.
218
+ */
219
+ export function letterSpacingRoomCSS(
220
+ length: TextLength,
221
+ spacing: string,
222
+ width: string | undefined
223
+ ): DesignStyleDeclaration {
224
+ const literal = spacing === letterSpacingToCSS(length)
225
+ return {
226
+ ...(width !== undefined && { width: `calc(${width} + ${spacing})` }),
227
+ 'margin-right': literal
228
+ ? letterSpacingToCSS({ ...length, value: -length.value })
229
+ : `calc(-1 * ${spacing})`
230
+ }
231
+ }
@@ -2,6 +2,7 @@
2
2
  export {
3
3
  sceneGraphToDesignDocument,
4
4
  sceneNodeToDesignDocument,
5
+ sceneNodesToDesignDocument,
5
6
  type SceneGraphToDesignOptions,
6
7
  type VectorElementRenderer
7
8
  } from './projection'
@@ -0,0 +1,111 @@
1
+ import type { ConstraintType, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import type { DesignStyleDeclaration } from '../types'
4
+ import { borderWidths } from './css'
5
+
6
+ const AXES = {
7
+ width: { constraint: 'horizontalConstraint', start: 'left', end: 'right', at: 'x' },
8
+ height: { constraint: 'verticalConstraint', start: 'top', end: 'bottom', at: 'y' }
9
+ } as const
10
+
11
+ type Axis = keyof typeof AXES
12
+
13
+ const length = (value: number) => `${Number(value.toFixed(3))}px`
14
+ const percent = (value: number) => `${Number((value * 100).toFixed(4))}%`
15
+
16
+ /** A percentage of the containing block moved by a length, as `calc()` when it moves. */
17
+ function shifted(base: string, by: number): string {
18
+ if (Number(by.toFixed(3)) === 0) return base
19
+ return `calc(${base} ${by < 0 ? '-' : '+'} ${length(Math.abs(by))})`
20
+ }
21
+
22
+ /**
23
+ * A placed layer along one axis, measured in the box CSS places it in: inside the parent's
24
+ * border, which a stroke on the canvas does not take from its children. A parent with no size
25
+ * on the axis leaves its box to the page, so its children keep their start and size there.
26
+ */
27
+ function placedAxis(node: SceneNode, parent: SceneNode | undefined, axis: Axis) {
28
+ const { constraint, start, end, at } = AXES[axis]
29
+ const border = parent ? borderWidths(parent) : undefined
30
+ const inset = border?.[start] ?? 0
31
+ const room = (parent?.[axis] ?? 0) - inset - (border?.[end] ?? 0)
32
+ const kind: ConstraintType = parent && room > 0 ? node[constraint] : 'MIN'
33
+ const before = node[at] - inset
34
+ return { kind, room, before, after: room - before - node[axis] }
35
+ }
36
+
37
+ /**
38
+ * Whether a placed layer's constraint sizes it along an axis: Left and Right and Scale both size
39
+ * it from the parent, so it takes no fixed size.
40
+ */
41
+ export function constraintSizes(
42
+ node: SceneNode,
43
+ parent: SceneNode | undefined,
44
+ axis: Axis
45
+ ): boolean {
46
+ const { kind } = placedAxis(node, parent, axis)
47
+ return kind === 'STRETCH' || kind === 'SCALE'
48
+ }
49
+
50
+ /**
51
+ * Whether a layer's parent leaves it to its coordinates: it is absolutely positioned, or its
52
+ * parent frame has no auto layout. The parent it is placed in is the one its constraints follow.
53
+ */
54
+ export function placement(
55
+ node: SceneNode,
56
+ parent: SceneNode | undefined
57
+ ): { parent: SceneNode | undefined } | null {
58
+ const frame = parent?.type === 'CANVAS' ? undefined : parent
59
+ if (node.layoutPositioning === 'ABSOLUTE' || frame?.layoutMode === 'NONE')
60
+ return { parent: frame }
61
+ return null
62
+ }
63
+
64
+ /**
65
+ * Place a layer by its constraints when its parent does not lay it out. A frame without auto
66
+ * layout becomes the containing block of the children it places.
67
+ */
68
+ export function addPositioning(
69
+ style: DesignStyleDeclaration,
70
+ node: SceneNode,
71
+ parent: SceneNode | undefined
72
+ ): void {
73
+ const placed = placement(node, parent)
74
+ if (placed) {
75
+ style.position = 'absolute'
76
+ addConstrainedPlacement(style, node, placed.parent)
77
+ } else if (node.layoutMode === 'NONE' && node.type !== 'TEXT' && node.childIds.length > 0) {
78
+ style.position = 'relative'
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Place a layer by its constraints, so it follows the parent when the page resizes it as the
84
+ * canvas does (`resize.ts` in `@pairdraw/scene-graph`): Left and Top keep the start edge,
85
+ * Right and Bottom the end edge, Center the offset from the centre, Left and Right both edges,
86
+ * and Scale its share of the parent. A stretched size is written out rather than left to both
87
+ * edges, which an image would not fill.
88
+ */
89
+ function addConstrainedPlacement(
90
+ style: DesignStyleDeclaration,
91
+ node: SceneNode,
92
+ parent: SceneNode | undefined
93
+ ): void {
94
+ for (const axis of ['width', 'height'] as const) {
95
+ const { start, end } = AXES[axis]
96
+ const { kind, room, before, after } = placedAxis(node, parent, axis)
97
+ if (kind === 'MAX') {
98
+ style[end] = length(after)
99
+ } else if (kind === 'CENTER') {
100
+ style[start] = shifted('50%', before - room / 2)
101
+ } else if (kind === 'STRETCH') {
102
+ style[start] = length(before)
103
+ style[axis] = shifted('100%', node[axis] - room)
104
+ } else if (kind === 'SCALE') {
105
+ style[start] = percent(before / room)
106
+ style[axis] = percent(node[axis] / room)
107
+ } else {
108
+ style[start] = length(before)
109
+ }
110
+ }
111
+ }
@@ -1,3 +1,4 @@
1
+ import { isEqual } from 'es-toolkit/predicate'
1
2
  import { fromUint8Array } from 'js-base64'
2
3
 
3
4
  import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
@@ -12,15 +13,18 @@ import { DesignTokens, type CSSModes } from '../tokens/references'
12
13
  import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
13
14
  import {
14
15
  cssColor,
15
- dropShadowToCSS,
16
16
  effectsToCSS,
17
17
  fillToCSS,
18
+ gradientFillsToCSS,
19
+ letterSpacingRoomCSS,
18
20
  letterSpacingToCSS,
19
21
  lineHeightToCSS,
20
- strokeColorToCSS
22
+ strokeColorToCSS,
23
+ textEffectsToCSS
21
24
  } from './css'
22
25
  import { addGridContainer, addGridPlacement } from './grid'
23
- import { textCaseToCSS, textElementContent } from './text'
26
+ import { addPositioning, constraintSizes, placement } from './position'
27
+ import { textCaseToCSS, textElementContent, uniformLetterSpacing } from './text'
24
28
 
25
29
  const DOM_CSS_PLUGIN_ID = 'pairdraw-dom-css'
26
30
  const IMAGE_SOURCE_URL_KEY = 'image-source-url'
@@ -108,8 +112,12 @@ function addSize(
108
112
  parent: SceneNode | undefined,
109
113
  css: FieldCSS
110
114
  ): void {
115
+ const placed = placement(node, parent)
111
116
  const sized = (axis: 'width' | 'height') =>
112
- node[axis] > 0 && !hugs(node, axis) && !stretches(node, parent, axis)
117
+ node[axis] > 0 &&
118
+ !hugs(node, axis) &&
119
+ !stretches(node, parent, axis) &&
120
+ !(placed && constraintSizes(node, placed.parent, axis))
113
121
  if (sized('width')) style.width = css('width', px(node.width))
114
122
  if (sized('height')) style.height = css('height', px(node.height))
115
123
  }
@@ -131,28 +139,6 @@ function stretches(
131
139
  return axis !== mainAxis
132
140
  }
133
141
 
134
- /**
135
- * Place a layer at its coordinates when its parent does not lay it out: it is absolutely
136
- * positioned, or its parent frame has no auto layout. A frame without auto layout becomes the
137
- * containing block of the children it places.
138
- */
139
- function addPositioning(
140
- style: DesignStyleDeclaration,
141
- node: SceneNode,
142
- parent: SceneNode | undefined
143
- ): void {
144
- const placed =
145
- node.layoutPositioning === 'ABSOLUTE' ||
146
- (parent !== undefined && parent.type !== 'CANVAS' && parent.layoutMode === 'NONE')
147
- if (placed) {
148
- style.position = 'absolute'
149
- style.left = `${node.x}px`
150
- style.top = `${node.y}px`
151
- } else if (node.layoutMode === 'NONE' && node.type !== 'TEXT' && node.childIds.length > 0) {
152
- style.position = 'relative'
153
- }
154
- }
155
-
156
142
  function addSizeConstraints(style: DesignStyleDeclaration, node: SceneNode, css: FieldCSS): void {
157
143
  if (node.minWidth !== null) style['min-width'] = css('minWidth', px(node.minWidth))
158
144
  if (node.maxWidth !== null) style['max-width'] = css('maxWidth', px(node.maxWidth))
@@ -321,6 +307,8 @@ function styleFromSceneNode(
321
307
  addSizeConstraints(style, node, css)
322
308
  const fill = fillToCSS(node.fills.at(0))
323
309
  if (fill) style['background-color'] = css('fills/0/color', fill)
310
+ const gradients = gradientFillsToCSS(node.fills, node.width, node.height)
311
+ if (gradients) style['background-image'] = gradients
324
312
  addImageStyle(style, node)
325
313
  addStroke(style, node, css)
326
314
  Object.assign(style, effectsToCSS(node.effects))
@@ -372,14 +360,18 @@ function styleFromTextNode(
372
360
  if (node.lineHeight !== null) {
373
361
  style['line-height'] = css('lineHeight', lineHeightToCSS(node.lineHeight))
374
362
  }
375
- if (node.letterSpacing.value !== 0) {
376
- style['letter-spacing'] = css('letterSpacing', letterSpacingToCSS(node.letterSpacing))
363
+ const spacing = css('letterSpacing', letterSpacingToCSS(node.letterSpacing))
364
+ if (node.letterSpacing.value !== 0) style['letter-spacing'] = spacing
365
+ // The spacing after a line's last letter needs room only when one spacing ends every line.
366
+ const ending = uniformLetterSpacing(node)
367
+ if (ending && ending.value !== 0) {
368
+ const written = isEqual(ending, node.letterSpacing) ? spacing : letterSpacingToCSS(ending)
369
+ Object.assign(style, letterSpacingRoomCSS(ending, written, style.width))
377
370
  }
378
371
  if (node.textAlignHorizontal !== 'LEFT')
379
372
  style['text-align'] = node.textAlignHorizontal.toLowerCase()
380
373
  if (node.opacity < 1) style.opacity = css('opacity', String(node.opacity))
381
- const shadow = dropShadowToCSS(node.effects[0])
382
- if (shadow) style['text-shadow'] = shadow
374
+ Object.assign(style, textEffectsToCSS(node.effects))
383
375
  if (node.textDecoration !== 'NONE') {
384
376
  style['text-decoration-line'] =
385
377
  node.textDecoration === 'UNDERLINE' ? 'underline' : 'line-through'
@@ -568,14 +560,25 @@ export function sceneNodeToDesignDocument(
568
560
  nodeId: string,
569
561
  options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}
570
562
  ): DesignDocument {
571
- const node = graph.getNode(nodeId)
563
+ return sceneNodesToDesignDocument(graph, [nodeId], options)
564
+ }
565
+
566
+ /**
567
+ * Project several nodes, including each own box, through one token collector: the document then
568
+ * declares the tokens every root references, not only those of the last one.
569
+ */
570
+ export function sceneNodesToDesignDocument(
571
+ graph: SceneGraph,
572
+ nodeIds: readonly string[],
573
+ options: Omit<SceneGraphToDesignOptions, 'rootId'> = {}
574
+ ): DesignDocument {
572
575
  const context = projectionContext(graph, options)
573
576
  const modes = context.tokens?.defaultModes() ?? new Map<string, string>()
574
- const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null
575
- return {
576
- type: 'document',
577
- sourceGraph: graph,
578
- tokens: context.tokens,
579
- children: projected ? [projected] : []
577
+ const children: DesignNode[] = []
578
+ for (const nodeId of nodeIds) {
579
+ const node = graph.getNode(nodeId)
580
+ const projected = node ? sceneNodeToDesignNode(context, node, modes, true) : null
581
+ if (projected) children.push(projected)
580
582
  }
583
+ return { type: 'document', sourceGraph: graph, tokens: context.tokens, children }
581
584
  }
@@ -37,6 +37,8 @@ const IMPORT_NAMED = es.parseModule(`import { $Component } from '$path'`)
37
37
 
38
38
  const STORY = es.parseModule(`export const $name: Story = $story`)
39
39
 
40
+ const IMAGE = es.parseModule(`const $name = new URL($path, import.meta.url).href`)
41
+
40
42
  /**
41
43
  * What clicking a control does, as Reka marks it: the role to find it by, the element that
42
44
  * changes, and the `data-state` it ends in.
@@ -133,8 +135,13 @@ export interface ComponentStoriesData {
133
135
  generated: Pick<GeneratedComponent, 'entry' | 'valueArg' | 'valueList'>
134
136
  /** Design links for the whole file, as `parameters.design` entries. */
135
137
  design: { name: string; type: string; url: string }[]
138
+ /** Design image per story, by story name: the path relative to the story file. */
139
+ designs?: Map<string, string>
136
140
  }
137
141
 
142
+ /** The prop values a story sets over the component's rest values. */
143
+ export type StoryValues = Record<string, string | number | boolean>
144
+
138
145
  const FALSE = es.parseExpression('false')
139
146
  const TRUE = es.parseExpression('true')
140
147
 
@@ -217,20 +224,26 @@ function argTypes(component: ComponentModel, model: string | null, list: boolean
217
224
  }
218
225
 
219
226
  /** A story per state worth seeing: at rest, each boolean on, disabled, and each prop value. */
220
- function stories(
227
+ export function componentStories(
221
228
  component: ComponentModel,
222
229
  model: string | null,
223
230
  list: boolean
224
- ): { name: string; story: es.SyntaxNode }[] {
231
+ ): { name: string; values: StoryValues; story: es.SyntaxNode }[] {
225
232
  // Stories are named apart from the component the file imports and the module's own names.
226
233
  const taken = new Set([component.name, 'meta', 'Story'])
227
234
  let first = true
228
- const story = (label: string, args: [string, es.SyntaxNode][], play?: es.SyntaxNode) => {
235
+ const story = (
236
+ label: string,
237
+ values: StoryValues,
238
+ args: [string, es.SyntaxNode][],
239
+ play?: es.SyntaxNode
240
+ ) => {
229
241
  // Every story after the first, Default, is another state, tagged so Storybook can hide it.
230
242
  const variant = !first
231
243
  first = false
232
244
  return {
233
245
  name: claimName(identifierName(label, 'Story'), taken),
246
+ values,
234
247
  story: es.object([
235
248
  ...(variant
236
249
  ? [['tags', es.array([es.string(VARIANT_TAG)])] as [string, es.SyntaxNode]]
@@ -243,8 +256,10 @@ function stories(
243
256
  const { range } = component
244
257
  const boolean = !component.choice && !range && !component.text
245
258
  return [
246
- story('Default', [], playOf(component)),
247
- ...(component.model && model && boolean ? [story(component.model, [[model, TRUE]])] : []),
259
+ story('Default', {}, [], playOf(component)),
260
+ ...(component.model && model && boolean
261
+ ? [story(component.model, { [model]: true }, [[model, TRUE]])]
262
+ : []),
248
263
  // A range gets a story at each end it does not start at.
249
264
  ...(range && model
250
265
  ? (
@@ -254,23 +269,25 @@ function stories(
254
269
  ] as const
255
270
  )
256
271
  .filter(([, value]) => value !== range.default)
257
- .map(([label, value]) => story(label, [[model, numberArg(value, list)]]))
272
+ .map(([label, value]) =>
273
+ story(label, { [model]: value }, [[model, numberArg(value, list)]])
274
+ )
258
275
  : []),
259
276
  // A choice gets a story per option it does not start on, such as each other tab.
260
277
  ...(component.choice && model
261
278
  ? component.choice.options
262
279
  .filter((option) => option !== component.choice?.default)
263
- .map((option) => story(option, [[model, es.string(option)]]))
280
+ .map((option) => story(option, { [model]: option }, [[model, es.string(option)]]))
264
281
  : []),
265
- ...(component.disabled ? [story('Disabled', [['disabled', TRUE]])] : []),
282
+ ...(component.disabled ? [story('Disabled', { disabled: true }, [['disabled', TRUE]])] : []),
266
283
  ...component.props.flatMap((prop) =>
267
284
  prop.options
268
285
  .filter((option) => option !== prop.default)
269
- .map((option) => story(option, [[prop.name, es.string(option)]]))
286
+ .map((option) => story(option, { [prop.name]: option }, [[prop.name, es.string(option)]]))
270
287
  ),
271
288
  // A boolean gets a story drawn the other way, such as an icon shown that is hidden at rest.
272
289
  ...component.booleans.map((prop) =>
273
- story(`${prop.property} ${prop.default ? 'off' : 'on'}`, [
290
+ story(`${prop.property} ${prop.default ? 'off' : 'on'}`, { [prop.name]: !prop.default }, [
274
291
  [prop.name, prop.default ? FALSE : TRUE]
275
292
  ])
276
293
  )
@@ -312,10 +329,47 @@ export function printComponentStories(data: ComponentStoriesData): string {
312
329
  $Component: es.identifier(component.name),
313
330
  $path: es.string(entry.path)
314
331
  }).body
315
- const all = stories(component, model, list)
316
- const exported = (data.single ? all.slice(0, 1) : all).flatMap(
317
- (item) => es.fill(STORY, { $name: es.identifier(item.name), $story: item.story }).body
318
- )
332
+ const all = componentStories(component, model, list)
333
+ const kept = data.single ? all.slice(0, 1) : all
334
+ // Each story's design image is a URL const, so Vite bundles the file it points at.
335
+ const images = kept.flatMap((item, index) => {
336
+ const path = data.designs?.get(item.name)
337
+ return path
338
+ ? es.fill(IMAGE, { $name: es.identifier(`design${index}`), $path: es.string(path) }).body
339
+ : []
340
+ })
341
+ const exported = kept.flatMap((item, index) => {
342
+ const parameters = es.object([
343
+ [
344
+ 'design',
345
+ es.array([
346
+ es.object([
347
+ ['name', es.string('Design')],
348
+ ['type', es.string('image')],
349
+ ['url', es.identifier(`design${index}`)]
350
+ ])
351
+ ])
352
+ ]
353
+ ])
354
+ const story = data.designs?.has(item.name)
355
+ ? {
356
+ ...item.story,
357
+ properties: [
358
+ ...es.children(item.story, 'properties'),
359
+ {
360
+ type: 'Property',
361
+ kind: 'init',
362
+ key: es.identifier('parameters'),
363
+ value: parameters,
364
+ computed: false,
365
+ method: false,
366
+ shorthand: false
367
+ }
368
+ ]
369
+ }
370
+ : item.story
371
+ return es.fill(STORY, { $name: es.identifier(item.name), $story: story }).body
372
+ })
319
373
  // Only a control with a play function uses `expect`.
320
374
  const [types, expectImport, ...rest] = body
321
375
  const imports = playOf(component) ? [types, expectImport] : [types]
@@ -327,6 +381,7 @@ export function printComponentStories(data: ComponentStoriesData): string {
327
381
  ...stylesheets(data.styles),
328
382
  ...componentImport,
329
383
  ...rest,
384
+ ...images,
330
385
  ...exported
331
386
  ])
332
387
  })