@pairdraw/dom-css 0.18.0 → 0.19.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.
@@ -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
  })
@@ -20,7 +20,7 @@ import type { ComponentStyling } from '../components/styling'
20
20
  import { vueComponent } from '../components/vue'
21
21
  import { serializeHTML, serializeNode } from '../html'
22
22
  import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'
23
- import { printComponentStories } from './component'
23
+ import { componentStories, printComponentStories, type StoryValues } from './component'
24
24
  import { collectGroups, type StoryGroup } from './groups'
25
25
  import {
26
26
  printStoryModule,
@@ -271,6 +271,40 @@ function storyEntries(
271
271
  return entries
272
272
  }
273
273
 
274
+ /**
275
+ * The variant a generated component's story draws: the one whose variant property values match
276
+ * the story's args over the component's rest values. A state no single variant draws, such as
277
+ * a text field's words, has none.
278
+ */
279
+ function variantForStory(
280
+ group: StoryGroup,
281
+ component: ComponentModel,
282
+ values: StoryValues
283
+ ): StoryGroup['variants'][number] | undefined {
284
+ const args = component.args
285
+ // The variant property values the component shows at rest, and with the story's args set.
286
+ const shown = (story: StoryValues): Record<string, string> => {
287
+ const record: Record<string, string> = {}
288
+ for (const prop of component.props)
289
+ record[prop.property] = String(story[prop.name] ?? prop.default)
290
+ for (const [property, boolean] of args.booleans)
291
+ record[property] = (story[boolean.name] ?? false) ? boolean.on : boolean.off
292
+ if (args.states)
293
+ record[args.states.property] =
294
+ story['disabled'] === true && args.states.disabled !== undefined
295
+ ? args.states.disabled
296
+ : args.states.rest
297
+ if (args.filled) record[args.filled.property] = args.filled.off
298
+ return record
299
+ }
300
+ const target = shown(values)
301
+ return group.variants.find((variant) =>
302
+ Object.entries(target).every(
303
+ ([property, value]) => variant.node.componentPropertyValues[property] === value
304
+ )
305
+ )
306
+ }
307
+
274
308
  /**
275
309
  * The component each entry's set generates, by set id, built twice: first alone, so each
276
310
  * knows its props, then knowing all the others, so an instance of one uses it rather than
@@ -353,6 +387,63 @@ async function storyTokens(graph: SceneGraph, folder: string): Promise<ExportHTM
353
387
  return css ? [{ path: `${folder}/tokens.css`, content: css }] : []
354
388
  }
355
389
 
390
+ /** What writing one generated component's stories needs from the export around it. */
391
+ interface GeneratedContext {
392
+ options: ExportStorybookOptions
393
+ framework: StorybookFramework
394
+ uniqueNames: Set<string>
395
+ styles: string[]
396
+ add: (page: SceneNode, path: string, content: string | Uint8Array) => void
397
+ entry: StoryEntry
398
+ }
399
+
400
+ /** A generated component's files: its component, design images, and state stories. */
401
+ async function addGeneratedStories(
402
+ component: ComponentModel,
403
+ generate: ComponentGenerator,
404
+ { options, framework, uniqueNames, styles, add, entry }: GeneratedContext
405
+ ): Promise<void> {
406
+ const { page, group, file, mode } = entry
407
+ const generated = await generate(component, { styling: options.styling })
408
+ for (const item of generated.files) add(page, item.path, item.content)
409
+ const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)
410
+ // Each state story shows the variant that draws it, as static stories show their own.
411
+ const states = componentStories(
412
+ component,
413
+ generated.valueArg,
414
+ generated.valueList ?? false
415
+ ).slice(0, mode === 'single' ? 1 : undefined)
416
+ const designs = new Map<string, string>()
417
+ const render = options.renderDesignImage
418
+ if (render) {
419
+ for (const state of states) {
420
+ const variant = variantForStory(group, component, state.values)
421
+ if (!variant) continue
422
+ const path = `${file}.design/${state.name}.png`
423
+ add(page, path, await render(variant.node.id))
424
+ designs.set(state.name, `./${path}`)
425
+ }
426
+ }
427
+ add(
428
+ page,
429
+ `${file}.stories.ts`,
430
+ printComponentStories({
431
+ storybook: STORYBOOK_PACKAGES[framework],
432
+ title: group.title,
433
+ tags: fileTags(group.page.name),
434
+ styles,
435
+ component,
436
+ generated,
437
+ // A gallery lays out static variants; a generated component's stories are its states.
438
+ single: mode === 'single',
439
+ design: design.flatMap((link) =>
440
+ link.type === 'link' ? [{ name: 'Pairdraw', type: 'link', url: link.url }] : []
441
+ ),
442
+ designs
443
+ })
444
+ )
445
+ }
446
+
356
447
  /**
357
448
  * Generate one CSF3 `.stories.ts` file per component or component set, plus a
358
449
  * `<Name>.design/` folder of variant images when `renderDesignImage` is given.
@@ -380,29 +471,19 @@ export async function exportStorybook(
380
471
  const generate = GENERATORS[framework]
381
472
  const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()
382
473
 
383
- for (const { page, group, file, mode } of entries) {
474
+ for (const entry of entries) {
475
+ const { page, group, file, mode } = entry
384
476
  const component = group.set && models.get(group.set.id)
385
477
  if (generate && component) {
386
- const generated = await generate(component, { styling: options.styling })
387
- for (const item of generated.files) add(page, item.path, item.content)
388
- const design = designLink({ linkPath: options.linkPath, uniqueNames }, group.linkNode)
389
- add(
390
- page,
391
- `${file}.stories.ts`,
392
- printComponentStories({
393
- storybook: STORYBOOK_PACKAGES[framework],
394
- title: group.title,
395
- tags: fileTags(group.page.name),
396
- styles,
397
- component,
398
- generated,
399
- // A gallery lays out static variants; a generated component's stories are its states.
400
- single: mode === 'single',
401
- design: design.flatMap((entry) =>
402
- entry.type === 'link' ? [{ name: 'Pairdraw', type: 'link', url: entry.url }] : []
403
- )
404
- })
405
- )
478
+ const context: GeneratedContext = {
479
+ options,
480
+ framework,
481
+ uniqueNames,
482
+ styles,
483
+ add,
484
+ entry
485
+ }
486
+ await addGeneratedStories(component, generate, context)
406
487
  continue
407
488
  }
408
489
 
@@ -1,11 +1,19 @@
1
+ import { uniq } from 'es-toolkit/array'
1
2
  import { isEqual } from 'es-toolkit/predicate'
2
3
 
3
- import type { CharacterStyleOverride, HyperlinkTarget, SceneNode } from '@pairdraw/scene-graph'
4
+ import type {
5
+ CharacterStyleOverride,
6
+ HyperlinkTarget,
7
+ SceneNode,
8
+ TextLength
9
+ } from '@pairdraw/scene-graph'
4
10
  import {
5
11
  hasTextList,
6
12
  listNumberFormat,
7
13
  paragraphSpacingAt,
8
14
  paragraphStyleAt,
15
+ pixelLength,
16
+ textLengthPixels,
9
17
  textListItems,
10
18
  textParagraphRanges,
11
19
  type TextListItem,
@@ -96,6 +104,28 @@ export function textCaseToCSS(value: SceneNode['textCase']): string | undefined
96
104
  return undefined
97
105
  }
98
106
 
107
+ /**
108
+ * The letter spacing every character of a text has, from its run or the layer, or `undefined`
109
+ * when characters differ or there are none: then no one spacing ends every line. Characters
110
+ * spaced and sized as the layer is give the layer's own spacing; otherwise each spacing is
111
+ * resolved at its characters' font size, as CSS resolves `em` where a run sets its own size.
112
+ */
113
+ export function uniformLetterSpacing(node: SceneNode): TextLength | undefined {
114
+ const spacings = styledRanges(node).map(({ style }) => ({
115
+ length: style.letterSpacing,
116
+ fontSize: style.fontSize
117
+ }))
118
+ if (spacings.length === 0) return undefined
119
+ const asLayer = spacings.every(
120
+ ({ length, fontSize }) =>
121
+ isEqual(length, node.letterSpacing) &&
122
+ (length.unit === 'PIXELS' || fontSize === node.fontSize)
123
+ )
124
+ if (asLayer) return node.letterSpacing
125
+ const pixels = uniq(spacings.map(({ length, fontSize }) => textLengthPixels(length, fontSize)))
126
+ return pixels.length === 1 ? pixelLength(pixels[0]) : undefined
127
+ }
128
+
99
129
  function characterStyle(node: SceneNode, override: CharacterStyleOverride = {}): CharacterStyle {
100
130
  const style = Object.fromEntries(CHARACTER_STYLE_KEYS.map((key) => [key, node[key]]))
101
131
  for (const key of CHARACTER_STYLE_KEYS) {
@@ -162,6 +192,25 @@ function characterCSS(style: CharacterStyle, decorated: boolean): DesignStyleDec
162
192
  }
163
193
  }
164
194
 
195
+ /**
196
+ * What a run's span sets beyond the text's own style. A percent letter spacing is written again
197
+ * where the span changes the font size: CSS inherits spacing already resolved at the text's size,
198
+ * while the canvas spaces each run by its own size.
199
+ */
200
+ function spanCSS(
201
+ style: CharacterStyle,
202
+ decorated: boolean,
203
+ base: DesignStyleDeclaration
204
+ ): DesignStyleDeclaration {
205
+ const own = characterCSS(style, decorated)
206
+ const css = differing(own, base)
207
+ const { unit, value } = style.letterSpacing
208
+ if (unit === 'PERCENT' && value !== 0 && 'font-size' in css) {
209
+ css['letter-spacing'] = own['letter-spacing']
210
+ }
211
+ return css
212
+ }
213
+
165
214
  /** What `css` sets differently from `base`. */
166
215
  function differing(
167
216
  css: DesignStyleDeclaration,
@@ -222,7 +271,7 @@ function inlineContent(projection: TextProjection, start: number, end: number):
222
271
  const from = Math.max(start, range.start)
223
272
  const to = Math.min(end, range.end)
224
273
  if (to <= from) continue
225
- const css = differing(characterCSS(range.style, !decorated), base)
274
+ const css = spanCSS(range.style, !decorated, base)
226
275
  const text = node.text.slice(from, to)
227
276
  const previous = pieces.at(-1)
228
277
  if (previous && previous.href === range.href && isEqual(previous.css, css)) {