@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.
@@ -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
@@ -339,7 +373,7 @@ async function storyFonts(
339
373
  if (requests.size === 0) return []
340
374
  const assets = await options.fonts([...requests.values()], `${folder}/fonts`)
341
375
  if (assets.length === 0) return []
342
- const css = await fontFaceStylesheet(assets, { from: folder, display: 'block' })
376
+ const css = fontFaceStylesheet(assets, { from: folder, display: 'block' })
343
377
  return [...assets, { path: `${folder}/fonts.css`, content: css }]
344
378
  }
345
379
 
@@ -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)) {
@@ -9,8 +9,16 @@ import {
9
9
  type Stroke
10
10
  } from '@pairdraw/scene-graph'
11
11
  import { TRANSPARENT } from '@pairdraw/scene-graph/constants'
12
- import { parseCSSAlignSelf, parseCSSNumber, parseCSSShadows } from '@pairdraw/scene-graph/css'
12
+ import {
13
+ parseCSSAlignSelf,
14
+ parseCSSBackgroundImages,
15
+ parseCSSNumber,
16
+ parseCSSShadows
17
+ } from '@pairdraw/scene-graph/css'
18
+ import { normalizeEffects } from '@pairdraw/scene-graph/effects'
19
+ import { blurRadiusForSigma } from '@pairdraw/scene-graph/geometry'
13
20
  import { computeImageHash } from '@pairdraw/scene-graph/images'
21
+ import { textLayerName } from '@pairdraw/scene-graph/node-defaults'
14
22
 
15
23
  import type { DesignDocument, DesignElement, DesignNode, DesignStyleDeclaration } from '../types'
16
24
  import { colorToFillFromCSS, colorToStrokeFromCSS, mergedStyle, pickStyle } from './css-values'
@@ -36,6 +44,16 @@ import {
36
44
  const DOM_CSS_PLUGIN_ID = 'pairdraw-dom-css'
37
45
  const IMAGE_SOURCE_URL_KEY = 'image-source-url'
38
46
 
47
+ /**
48
+ * CSS shadows as the layer's effects, each blurred as the browser blurs it: CSS blurs a shadow
49
+ * by half its blur length, which the canvas draws from the radius that gives that sigma.
50
+ */
51
+ function cssShadows(value: string | undefined) {
52
+ return parseCSSShadows(value).map((effect) =>
53
+ effect.type === 'SHADER' ? effect : { ...effect, radius: blurRadiusForSigma(effect.radius / 2) }
54
+ )
55
+ }
56
+
39
57
  export interface DesignDocumentToSceneGraphOptions {
40
58
  pageName?: string
41
59
  }
@@ -75,6 +93,43 @@ function fillsFromStyle(style: DesignStyleDeclaration, property: string): Fill[]
75
93
  return colorToFillFromCSS(pickStyle(style, property))
76
94
  }
77
95
 
96
+ /**
97
+ * The `background-image` layers as fills, bottom-first as Pairdraw paints them: CSS paints the
98
+ * first layer on top, so the list reverses. A `url()` layer becomes an image fill when its
99
+ * bytes are inline; a remote address is skipped, as an unfetchable background paints nothing.
100
+ */
101
+ function backgroundFills(
102
+ graph: SceneGraph,
103
+ node: SceneNode,
104
+ style: DesignStyleDeclaration
105
+ ): Fill[] {
106
+ const layers = parseCSSBackgroundImages(
107
+ pickStyle(style, 'background-image'),
108
+ node.width,
109
+ node.height
110
+ )
111
+ const fills: Fill[] = []
112
+ for (const layer of layers) {
113
+ if (layer.kind === 'gradient') {
114
+ fills.push(layer.fill)
115
+ continue
116
+ }
117
+ const bytes = bytesFromDataURL(layer.url)
118
+ if (!bytes) continue
119
+ const imageHash = computeImageHash(bytes)
120
+ graph.images.set(imageHash, bytes)
121
+ fills.push({
122
+ type: 'IMAGE',
123
+ imageHash,
124
+ imageScaleMode: 'FILL',
125
+ color: { ...TRANSPARENT },
126
+ opacity: 1,
127
+ visible: true
128
+ })
129
+ }
130
+ return fills.reverse()
131
+ }
132
+
78
133
  function aspectRatioFromCSS(value: string | undefined): number | null {
79
134
  if (!value || value === 'auto') return null
80
135
  const parts = value
@@ -310,7 +365,8 @@ function applyElementStyle(
310
365
  applyPadding(node, style)
311
366
 
312
367
  const fills = fillsFromStyle(style, 'background-color')
313
- if (fills.length > 0) node.fills = fills
368
+ const background = backgroundFills(graph, node, style)
369
+ if (fills.length > 0 || background.length > 0) node.fills = [...fills, ...background]
314
370
  applyImageFill(graph, node, element, style)
315
371
 
316
372
  const strokes = colorToStrokeFromCSS(
@@ -327,8 +383,8 @@ function applyElementStyle(
327
383
  setBorderWeights(node, style, strokes[0])
328
384
  }
329
385
 
330
- const effects = parseCSSShadows(pickStyle(style, 'box-shadow'))
331
- if (effects.length > 0) node.effects = effects
386
+ const effects = cssShadows(pickStyle(style, 'box-shadow'))
387
+ if (effects.length > 0) node.effects = normalizeEffects(effects)
332
388
 
333
389
  const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
334
390
  if (opacity !== null) node.opacity = opacity
@@ -367,8 +423,8 @@ function applyTextStyle(node: SceneNode, style: DesignStyleDeclaration): void {
367
423
  const opacity = parseCSSNumber(pickStyle(style, 'opacity'))
368
424
  if (opacity !== null) node.opacity = opacity
369
425
 
370
- const effects = parseCSSShadows(pickStyle(style, 'text-shadow'))
371
- if (effects.length > 0) node.effects = effects
426
+ const effects = cssShadows(pickStyle(style, 'text-shadow'))
427
+ if (effects.length > 0) node.effects = normalizeEffects(effects)
372
428
 
373
429
  const textAlign = pickStyle(style, 'text-align')?.toUpperCase()
374
430
  if (textAlign === 'CENTER' || textAlign === 'RIGHT' || textAlign === 'JUSTIFIED') {
@@ -396,7 +452,7 @@ function createRichTextNode(
396
452
  const base = pick(node, CHARACTER_FIELDS)
397
453
  const rich = blocks ? blockRichText(element, style, base) : inlineRichText(element, style, base)
398
454
  node.text = rich.text
399
- node.name = rich.text.slice(0, 32) || 'Text'
455
+ node.name = textLayerName('TEXT', rich.text)
400
456
  node.styleRuns = rich.styleRuns
401
457
  if (blocks) applyParagraphs(node, rich)
402
458
  applyFlowSizing(graph, node, style, display, parentFlow)
@@ -428,7 +484,7 @@ function createTextNode(
428
484
  display: string,
429
485
  parentFlow: ParentFlow
430
486
  ) {
431
- const node = graph.createNode('TEXT', parentId, { name: text.slice(0, 32) || 'Text', text })
487
+ const node = graph.createNode('TEXT', parentId, { name: textLayerName('TEXT', text), text })
432
488
  applyTextStyle(node, style)
433
489
  applyFlowSizing(graph, node, style, display, parentFlow)
434
490
  return node
@@ -1,6 +1,6 @@
1
1
  import { parse } from '@acemir/cssom'
2
- import type { CSSStyleRuleLike } from '@acemir/cssom'
3
2
 
3
+ import type { CSSStyleRuleLike } from '../cssom/types'
4
4
  import type { DesignStyleDeclaration } from '../types'
5
5
 
6
6
  function firstStyleRule(cssText: string): CSSStyleRuleLike | null {
@@ -255,7 +255,9 @@ async function computeStylesInIframe(
255
255
  content.innerHTML = serializeHTML(designDocument)
256
256
  iframeDocument.body.append(content)
257
257
 
258
- await requestFrame(iframeDocument)
258
+ // The sandbox sits offscreen, where WebKit never runs an animation frame of its own; the
259
+ // page's frame lays the iframe out too, and the page is visible whenever a person pastes.
260
+ await requestFrame(browserDocument)
259
261
  return copyComputedStyles(designDocument, content, options)
260
262
  } finally {
261
263
  iframe.remove()
@@ -1,15 +1,15 @@
1
+ import type {
2
+ CSSGroupingRuleLike,
3
+ CSSStyleDeclarationLike,
4
+ CSSStyleRuleLike
5
+ } from '#dom-css/cssom/types'
1
6
  import type {
2
7
  DesignDocument,
3
8
  DesignElement,
4
9
  DesignNode,
5
10
  DesignStyleDeclaration
6
11
  } from '#dom-css/types'
7
- import {
8
- parse,
9
- type CSSGroupingRuleLike,
10
- type CSSStyleDeclarationLike,
11
- type CSSStyleRuleLike
12
- } from '@acemir/cssom'
12
+ import { parse } from '@acemir/cssom'
13
13
 
14
14
  import { tryParseColor } from '@pairdraw/scene-graph/color'
15
15
  import { parseCSSNumber, splitCSSValue } from '@pairdraw/scene-graph/css'
@@ -54,6 +54,20 @@ function isColor(value: unknown): value is Color {
54
54
  return typeof value === 'object' && value !== null && 'r' in value && 'a' in value
55
55
  }
56
56
 
57
+ /**
58
+ * A field's value as the number a token gives it. A text's letter spacing and line height are
59
+ * lengths: in pixels they match by their value, while a percent of the font size, or automatic
60
+ * line height, has no length token to match and stays literal.
61
+ */
62
+ function drawnNumber(node: SceneNode, field: string): number | undefined {
63
+ if (field === 'letterSpacing' || field === 'lineHeight') {
64
+ const length = node[field]
65
+ return length?.unit === 'PIXELS' ? length.value : undefined
66
+ }
67
+ const value: unknown = Reflect.get(node, field)
68
+ return typeof value === 'number' ? value : undefined
69
+ }
70
+
57
71
  /** Where an alias chain ends in the modes the canvas draws: a value, or a CSS expression. */
58
72
  type TokenChain = {
59
73
  ids: string[]
@@ -167,8 +181,8 @@ export class DesignTokens {
167
181
  if (!paint?.visible || paint.type !== 'SOLID' || !isColor(value)) return false
168
182
  return sameColor({ ...paint.color, a: paint.opacity }, value)
169
183
  }
170
- const drawn: unknown = Reflect.get(node, field)
171
- if (typeof drawn !== 'number' || typeof value !== 'number') return false
184
+ const drawn = drawnNumber(node, field)
185
+ if (drawn === undefined || typeof value !== 'number') return false
172
186
  if (Math.fround(drawn) !== Math.fround(value)) return false
173
187
  // An expression is the author's CSS for the value, whatever unit the token stores.
174
188
  if (field === 'opacity') return expression || variableUnit(end) === 'none'
@@ -9,7 +9,14 @@ import { variableValueReferences } from '@pairdraw/scene-graph/variables'
9
9
 
10
10
  import { cssColor } from '../export/css'
11
11
  import { formulaToCSS } from './formula'
12
- import { collectionVariables, tokenSlug, variableCSSNames, variableNamespace } from './names'
12
+ import {
13
+ collectionVariables,
14
+ deriveCSSName,
15
+ explicitCSSName,
16
+ tokenSlug,
17
+ variableCSSNames,
18
+ variableNamespace
19
+ } from './names'
13
20
  import { createTokenValidator, parseWithBrowser, type TokenValidator } from './validate'
14
21
  import { tokenNumberToCSS, variableUnit } from './values'
15
22
 
@@ -170,6 +177,29 @@ function variantNames(scopes: ModeScope[]): string[] {
170
177
  * references, and number formulas `calc()` over them; both are declared again in each mode that
171
178
  * changes what they point to.
172
179
  */
180
+ /**
181
+ * A name that took a numeric suffix is an alias nobody can read back from the stylesheet, so it
182
+ * is reported rather than left as a silent second spelling of another token.
183
+ */
184
+ function numberedNameIssues(
185
+ variables: readonly Variable[],
186
+ names: Map<string, string>,
187
+ modeOf: (variable: Variable) => string
188
+ ): TokenStylesheetIssue[] {
189
+ const issues: TokenStylesheetIssue[] = []
190
+ for (const variable of variables) {
191
+ const name = names.get(variable.id)
192
+ const base = deriveCSSName(variable)
193
+ if (!name || explicitCSSName(variable) || name === base) continue
194
+ issues.push({
195
+ message: `"${variable.name}" is written --${name}: --${base} is taken`,
196
+ variableId: variable.id,
197
+ modeId: modeOf(variable)
198
+ })
199
+ }
200
+ return issues
201
+ }
202
+
173
203
  export function buildTokenStylesheet(
174
204
  source: TokenSource,
175
205
  { format, include = () => true }: TokenStylesheetOptions,
@@ -205,6 +235,8 @@ export function buildTokenStylesheet(
205
235
  return { name, value: css }
206
236
  }
207
237
 
238
+ issues.push(...numberedNameIssues(variables, names, defaultModeOf))
239
+
208
240
  const defaults = new Map<string, Declaration>()
209
241
  const theme: Declaration[] = []
210
242
  const root: Declaration[] = []
@@ -1,6 +1,7 @@
1
- import type { CSSStyleSheetLike } from '@acemir/cssom'
2
1
  import valueParser from 'postcss-value-parser'
3
2
 
3
+ import type { CSSStyleSheetLike } from '../cssom/types'
4
+
4
5
  type Parse = (cssText: string) => CSSStyleSheetLike
5
6
 
6
7
  const AT_RULES = ['@media', '@supports', '@container'] as const