@pairdraw/dom-css 0.0.0-stage → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (137) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +219 -2
  3. package/dist/browser.d.ts +29 -0
  4. package/dist/browser.js +2 -0
  5. package/dist/chunks/behaviours/args.js +59 -0
  6. package/dist/chunks/behaviours/args.js.map +1 -0
  7. package/dist/chunks/behaviours/controls.js +109 -0
  8. package/dist/chunks/behaviours/controls.js.map +1 -0
  9. package/dist/chunks/behaviours/reset.js +40 -0
  10. package/dist/chunks/behaviours/reset.js.map +1 -0
  11. package/dist/chunks/behaviours/roles.js +51 -0
  12. package/dist/chunks/behaviours/roles.js.map +1 -0
  13. package/dist/chunks/behaviours/states/conditions.js +103 -0
  14. package/dist/chunks/behaviours/states/conditions.js.map +1 -0
  15. package/dist/chunks/behaviours/states/css.js +172 -0
  16. package/dist/chunks/behaviours/states/css.js.map +1 -0
  17. package/dist/chunks/behaviours/states/layers.js +1736 -0
  18. package/dist/chunks/behaviours/states/layers.js.map +1 -0
  19. package/dist/chunks/behaviours/states/model.js +144 -0
  20. package/dist/chunks/behaviours/states/model.js.map +1 -0
  21. package/dist/chunks/behaviours/states/tailwind.js +198 -0
  22. package/dist/chunks/behaviours/states/tailwind.js.map +1 -0
  23. package/dist/chunks/browser.js +1352 -0
  24. package/dist/chunks/browser.js.map +1 -0
  25. package/dist/chunks/export/bundle.js +337 -0
  26. package/dist/chunks/export/bundle.js.map +1 -0
  27. package/dist/chunks/export/components/drawn.js +60 -0
  28. package/dist/chunks/export/components/drawn.js.map +1 -0
  29. package/dist/chunks/export/components/fields.js +178 -0
  30. package/dist/chunks/export/components/fields.js.map +1 -0
  31. package/dist/chunks/export/components/groups.js +297 -0
  32. package/dist/chunks/export/components/groups.js.map +1 -0
  33. package/dist/chunks/export/components/icons.js +260 -0
  34. package/dist/chunks/export/components/icons.js.map +1 -0
  35. package/dist/chunks/export/components/layers.js +1594 -0
  36. package/dist/chunks/export/components/layers.js.map +1 -0
  37. package/dist/chunks/export/index.js +477 -0
  38. package/dist/chunks/export/index.js.map +1 -0
  39. package/dist/chunks/export/storybook/component.js +448 -0
  40. package/dist/chunks/export/storybook/component.js.map +1 -0
  41. package/dist/chunks/export/storybook/export.js +410 -0
  42. package/dist/chunks/export/storybook/export.js.map +1 -0
  43. package/dist/chunks/import/html.js +406 -0
  44. package/dist/chunks/import/html.js.map +1 -0
  45. package/dist/chunks/import/jsx/dev-runtime.js +37 -0
  46. package/dist/chunks/import/jsx/dev-runtime.js.map +1 -0
  47. package/dist/chunks/tokens/cssom-validator.js +10 -0
  48. package/dist/chunks/tokens/cssom-validator.js.map +1 -0
  49. package/dist/export.d.ts +594 -0
  50. package/dist/export.js +13 -0
  51. package/dist/index.d.ts +115 -0
  52. package/dist/index.js +7 -0
  53. package/dist/jsx-dev-runtime.d.ts +8 -0
  54. package/dist/jsx-dev-runtime.js +3 -0
  55. package/dist/jsx-runtime.d.ts +20 -0
  56. package/dist/jsx-runtime.js +3 -0
  57. package/dist/rolldown-runtime.js +13 -0
  58. package/dist/runtime.d.ts +10 -0
  59. package/dist/scene-graph.d.ts +2 -0
  60. package/dist/scene-graph.js +2 -0
  61. package/dist/scene-graph2.d.ts +10 -0
  62. package/dist/styling.d.ts +93 -0
  63. package/dist/tailwind.d.ts +39 -0
  64. package/dist/types.d.ts +89 -0
  65. package/package.json +73 -4
  66. package/src/behaviours/args.ts +85 -0
  67. package/src/behaviours/controls.ts +195 -0
  68. package/src/behaviours/index.ts +11 -0
  69. package/src/behaviours/reset.ts +37 -0
  70. package/src/behaviours/roles.ts +44 -0
  71. package/src/behaviours/states/conditions.ts +105 -0
  72. package/src/behaviours/states/css.ts +123 -0
  73. package/src/behaviours/states/index.ts +4 -0
  74. package/src/behaviours/states/layers.ts +205 -0
  75. package/src/behaviours/states/model.ts +175 -0
  76. package/src/behaviours/states/names.ts +39 -0
  77. package/src/behaviours/states/tailwind.ts +148 -0
  78. package/src/behaviours/states/types.ts +56 -0
  79. package/src/browser.ts +146 -0
  80. package/src/cssom.d.ts +38 -0
  81. package/src/export/bundle.ts +461 -0
  82. package/src/export/components/drawn.ts +73 -0
  83. package/src/export/components/fields.ts +178 -0
  84. package/src/export/components/groups.ts +78 -0
  85. package/src/export/components/icons.ts +230 -0
  86. package/src/export/components/layers.ts +121 -0
  87. package/src/export/components/model.ts +544 -0
  88. package/src/export/components/properties.ts +167 -0
  89. package/src/export/components/react/fields.ts +129 -0
  90. package/src/export/components/react/index.ts +606 -0
  91. package/src/export/components/react/shared.ts +76 -0
  92. package/src/export/components/references.ts +212 -0
  93. package/src/export/components/repeats.ts +128 -0
  94. package/src/export/components/shaders.ts +125 -0
  95. package/src/export/components/styling.ts +31 -0
  96. package/src/export/components/tree.ts +72 -0
  97. package/src/export/components/vue.ts +517 -0
  98. package/src/export/css.ts +57 -0
  99. package/src/export/grid.ts +42 -0
  100. package/src/export/html.ts +163 -0
  101. package/src/export/index.ts +44 -0
  102. package/src/export/projection.ts +581 -0
  103. package/src/export/storybook/component.ts +334 -0
  104. package/src/export/storybook/export.ts +430 -0
  105. package/src/export/storybook/groups.ts +161 -0
  106. package/src/export/storybook/module.ts +319 -0
  107. package/src/export/storybook/names.ts +51 -0
  108. package/src/export/tailwind-jsx.ts +156 -0
  109. package/src/export/text.ts +415 -0
  110. package/src/import/css-text.ts +4 -0
  111. package/src/import/css-values.ts +31 -0
  112. package/src/import/flow.ts +248 -0
  113. package/src/import/html.ts +88 -0
  114. package/src/import/jsx/core.ts +130 -0
  115. package/src/import/jsx/dev-runtime.ts +8 -0
  116. package/src/import/jsx/runtime.ts +76 -0
  117. package/src/import/scene-graph.ts +582 -0
  118. package/src/import/style-attribute.ts +25 -0
  119. package/src/import/tailwind.ts +54 -0
  120. package/src/import/text.ts +518 -0
  121. package/src/index.ts +51 -0
  122. package/src/runtime/browser/runtime.ts +301 -0
  123. package/src/runtime/headless/runtime.ts +99 -0
  124. package/src/runtime/headless/styles.ts +330 -0
  125. package/src/runtime/index.ts +11 -0
  126. package/src/tokens/conditions.ts +66 -0
  127. package/src/tokens/cssom-validator.ts +8 -0
  128. package/src/tokens/custom-properties.ts +331 -0
  129. package/src/tokens/expression.ts +128 -0
  130. package/src/tokens/formula.ts +140 -0
  131. package/src/tokens/index.ts +43 -0
  132. package/src/tokens/names.ts +161 -0
  133. package/src/tokens/references.ts +201 -0
  134. package/src/tokens/stylesheet.ts +304 -0
  135. package/src/tokens/validate.ts +86 -0
  136. package/src/tokens/values.ts +44 -0
  137. package/src/types.ts +59 -0
@@ -0,0 +1,430 @@
1
+ import { PLACEMENT } from '#dom-css/behaviours/states/layers'
2
+ import { tokenStylesheet } from '#dom-css/tokens/stylesheet'
3
+ import type { DesignDocument, DesignNode, DesignStyleDeclaration } from '#dom-css/types'
4
+ import { compact } from 'es-toolkit/array'
5
+ import { omit } from 'es-toolkit/object'
6
+
7
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
8
+
9
+ import {
10
+ designFontRequests,
11
+ fontFaceStylesheet,
12
+ type ExportHTMLFile,
13
+ type WebFontFaceRequest,
14
+ type WebFontFaceResolver
15
+ } from '../bundle'
16
+ import { componentModel, type ComponentGenerator, type ComponentModel } from '../components/model'
17
+ import { reactComponent } from '../components/react'
18
+ import type { ComponentReferences } from '../components/references'
19
+ import type { ComponentStyling } from '../components/styling'
20
+ import { vueComponent } from '../components/vue'
21
+ import { serializeHTML, serializeNode } from '../html'
22
+ import { sceneNodeToDesignDocument, type VectorElementRenderer } from '../projection'
23
+ import { printComponentStories } from './component'
24
+ import { collectGroups, type StoryGroup } from './groups'
25
+ import {
26
+ printStoryModule,
27
+ STORYBOOK_PACKAGES,
28
+ type StoryDesign,
29
+ type StorybookFramework
30
+ } from './module'
31
+ import { claimName, fileTags, identifierName, storyId, VARIANT_TAG } from './names'
32
+
33
+ export { STORYBOOK_FRAMEWORKS, type StorybookFramework } from './module'
34
+
35
+ /** Frameworks whose stories render generated components; HTML stories stay static. */
36
+ const GENERATORS: Partial<Record<StorybookFramework, ComponentGenerator>> = {
37
+ vue: vueComponent,
38
+ react: reactComponent
39
+ }
40
+
41
+ export interface ExportStorybookOptions {
42
+ framework?: StorybookFramework
43
+ /**
44
+ * How Vue and React components are styled: a stylesheet beside each, by default, or Tailwind
45
+ * utilities in their markup, which needs Tailwind set up in the Storybook project.
46
+ */
47
+ styling?: ComponentStyling
48
+ /** Limit the export to one page. Defaults to every page. */
49
+ pageId?: string
50
+ /**
51
+ * The document's name, which titles its stories, such as `Pricing/Plan picker`, with each
52
+ * page's name between when it has several. Without it, stories are titled by page.
53
+ */
54
+ document?: string
55
+ /** Repository-relative `.fig`/`.pen` path; adds a `pairdraw://` design link to stories. */
56
+ linkPath?: string
57
+ /** Renders a variant to PNG; each story then shows it next to the link as its design. */
58
+ renderDesignImage?: (nodeId: string) => Promise<Uint8Array>
59
+ /** Draws vector layers as inline SVG, from the engine's SVG export. */
60
+ vectorElement?: VectorElementRenderer
61
+ /**
62
+ * How each story file is written, which a caller decides, such as from rules a user wrote:
63
+ * which stories it has and its title. Every file is written as `variants` by default.
64
+ */
65
+ plan?: (target: StoryTarget) => StoryPlan
66
+ /**
67
+ * Finds the font files the stories' text uses, which ship with them in `fonts/` and load
68
+ * before a story shows, so its text draws in the document's fonts. Without it, text uses
69
+ * whatever fonts Storybook's page has.
70
+ */
71
+ fonts?: WebFontFaceResolver
72
+ /**
73
+ * The folder a document's shared files go in, its fonts and design tokens, which must differ
74
+ * for each document exported into the same place; `pairdraw/<document>` by default.
75
+ */
76
+ folder?: string
77
+ }
78
+
79
+ /** How a story file shows its component: every variant, Default alone, a gallery, or not. */
80
+ export const STORY_MODES = ['variants', 'single', 'gallery', 'none'] as const
81
+ export type StoryMode = (typeof STORY_MODES)[number]
82
+
83
+ /** A story file the export would write, as a plan reads it. */
84
+ export interface StoryTarget {
85
+ /** The document's name, when the export knows it. */
86
+ document: string | undefined
87
+ page: string
88
+ /** The component set's or component's name, or a slash-named group's prefix. */
89
+ name: string
90
+ /** The title the file has unless the plan gives another. */
91
+ title: string
92
+ }
93
+
94
+ /** What a plan says about a story file; anything it leaves out stays as it would be. */
95
+ export interface StoryPlan {
96
+ stories?: StoryMode
97
+ title?: string
98
+ /**
99
+ * Whether a Vue or React export generates a component for the file, as it does by default,
100
+ * or keeps static stories of its variants.
101
+ */
102
+ generate?: boolean
103
+ }
104
+
105
+ export interface StorybookFile extends ExportHTMLFile {
106
+ /** Name of the page the file was generated from. */
107
+ page: string
108
+ }
109
+
110
+ /** Layers whose name no other layer carries; the link scheme can only address those. */
111
+ function uniqueLayerNames(graph: SceneGraph): Set<string> {
112
+ const counts = new Map<string, number>()
113
+ for (const node of graph.getAllNodes()) counts.set(node.name, (counts.get(node.name) ?? 0) + 1)
114
+ return new Set([...counts].filter(([, count]) => count === 1).map(([name]) => name))
115
+ }
116
+
117
+ interface ModuleContext {
118
+ graph: SceneGraph
119
+ framework: StorybookFramework
120
+ linkPath?: string
121
+ uniqueNames: Set<string>
122
+ /** Export name of each story, by variant index. */
123
+ storyNames: string[]
124
+ /** Import path of each variant's design image, by variant index. */
125
+ images: string[]
126
+ vectorElement?: VectorElementRenderer
127
+ mode: Exclude<StoryMode, 'none'>
128
+ /** Stylesheets every story file imports, such as the fonts its text uses. */
129
+ styles: string[]
130
+ }
131
+
132
+ function designLink(
133
+ context: Pick<ModuleContext, 'linkPath' | 'uniqueNames'>,
134
+ ...candidates: (string | undefined)[]
135
+ ): StoryDesign[] {
136
+ const node = candidates.find((name) => name !== undefined && context.uniqueNames.has(name))
137
+ if (!context.linkPath || !node) return []
138
+ const url = `pairdraw://open?file=${encodeURIComponent(context.linkPath)}&node=${encodeURIComponent(node)}`
139
+ return [{ type: 'link', url }]
140
+ }
141
+
142
+ /** Story export names, which also name the design images. */
143
+ function storyNames(group: StoryGroup): string[] {
144
+ // Named apart from the module's own types, `Story` and `Args`.
145
+ const taken = new Set(['story', 'args'])
146
+ const key = (name: string) => name.toLowerCase()
147
+ return group.variants.map((variant, index) => {
148
+ // The first variant, the one the design shows at rest, is the file's Default story.
149
+ const text = index === 0 || group.props.length === 0 ? 'Default' : variant.values.join(' ')
150
+ return claimName(identifierName(text, 'Variant'), taken, { key })
151
+ })
152
+ }
153
+
154
+ function storyLabel(group: StoryGroup, values: string[], index: number): string {
155
+ if (index === 0 || group.props.length === 0) return 'Default'
156
+ return group.props.map((prop, i) => `${prop.name}=${values[i] ?? ''}`).join(', ')
157
+ }
158
+
159
+ /**
160
+ * A variant drawn on its own, as a story shows it: its root, placed nowhere in particular, hugs
161
+ * its content where the design gives it no width, rather than filling the story's canvas, and sizes include padding and
162
+ * borders, which no page reset around the story says.
163
+ */
164
+ function standalone(document: DesignDocument): DesignDocument {
165
+ const visit = (node: DesignNode, root: boolean) => {
166
+ if (node.type !== 'element') return
167
+ // A variant's root drops where the set places it, which is not where the story draws it,
168
+ // and stays the containing block of the layers placed inside it.
169
+ const placed = root && Object.hasOwn(node.inlineStyle ?? {}, 'position')
170
+ const style: DesignStyleDeclaration = root
171
+ ? { ...omit({ ...node.inlineStyle }, PLACEMENT), ...(placed ? { position: 'relative' } : {}) }
172
+ : { ...node.inlineStyle }
173
+ const has = (property: string) => Object.hasOwn(style, property)
174
+ if ((has('width') || has('height')) && !has('box-sizing')) style['box-sizing'] = 'border-box'
175
+ if (root && !has('width')) style.width = 'fit-content'
176
+ node.inlineStyle = style
177
+ for (const child of node.children) visit(child, false)
178
+ }
179
+ for (const child of document.children) visit(child, true)
180
+ return document
181
+ }
182
+
183
+ function storyModule(group: StoryGroup, context: ModuleContext): string {
184
+ return printStoryModule({
185
+ framework: context.framework,
186
+ title: group.title,
187
+ tags: fileTags(group.page.name),
188
+ styles: context.styles,
189
+ name: group.name,
190
+ props: group.props,
191
+ variants: group.variants.map((variant) => ({
192
+ values: variant.values,
193
+ html: serializeHTML(
194
+ standalone(
195
+ sceneNodeToDesignDocument(context.graph, variant.node.id, {
196
+ includeSourceIds: false,
197
+ vectorElement: context.vectorElement
198
+ })
199
+ )
200
+ )
201
+ })),
202
+ metaDesign: designLink(context, group.linkNode),
203
+ images: context.images,
204
+ gallery:
205
+ context.mode === 'gallery'
206
+ ? group.variants.map((variant) => ({
207
+ values: variant.values,
208
+ label: serializeNode({ type: 'text', text: variant.values.join(', ') || group.name })
209
+ }))
210
+ : null,
211
+ stories: (context.mode === 'variants' ? group.variants : group.variants.slice(0, 1)).map(
212
+ (variant, i) => ({
213
+ exportName: context.storyNames[i] ?? '',
214
+ label: storyLabel(group, variant.values, i),
215
+ tags: i === 0 ? [] : [VARIANT_TAG],
216
+ values: variant.values,
217
+ design: [
218
+ ...designLink(context, variant.node.name, group.linkNode),
219
+ ...(context.images[i] ? [{ type: 'image' as const, variant: i }] : [])
220
+ ]
221
+ })
222
+ )
223
+ })
224
+ }
225
+
226
+ /** A story file to write: its group, the page it comes from, and its claimed file name. */
227
+ interface StoryEntry {
228
+ page: SceneNode
229
+ group: StoryGroup
230
+ file: string
231
+ mode: Exclude<StoryMode, 'none'>
232
+ generate: boolean
233
+ }
234
+
235
+ /**
236
+ * Every group's story file, with names claimed on every page so a one-page export picks the
237
+ * same names as a full one, kept for the pages the export covers.
238
+ */
239
+ function storyEntries(
240
+ graph: SceneGraph,
241
+ { pageId, document, plan }: Pick<ExportStorybookOptions, 'pageId' | 'document' | 'plan'>
242
+ ): StoryEntry[] {
243
+ const takenFiles = new Set<string>()
244
+ const takenIds = new Set<string>()
245
+ const entries: StoryEntry[] = []
246
+ const pages = graph.getPages()
247
+ // Pages without components, such as an empty first page, add no level to the titles.
248
+ const storied = pages.filter((page) => collectGroups(graph, page).length > 0)
249
+ const section = (page: SceneNode) => {
250
+ if (document === undefined) return page.name
251
+ return storied.length > 1 ? `${document}/${page.name}` : document
252
+ }
253
+ for (const page of pages) {
254
+ for (const group of collectGroups(graph, page, section(page))) {
255
+ const planned = plan?.({ document, page: page.name, name: group.name, title: group.title })
256
+ const mode = planned?.stories ?? 'variants'
257
+ if (mode === 'none') continue
258
+ // Storybook ids ignore case and punctuation, so `Library/Card` and `library/card` collide.
259
+ group.title = claimName(planned?.title ?? group.title, takenIds, {
260
+ separator: ' ',
261
+ key: storyId
262
+ })
263
+ // File names are compared ignoring case for case-insensitive file systems.
264
+ const file = claimName(identifierName(group.name, 'Component'), takenFiles, {
265
+ key: (name) => name.toLowerCase()
266
+ })
267
+ const generate = planned?.generate ?? true
268
+ if (!pageId || page.id === pageId) entries.push({ page, group, file, mode, generate })
269
+ }
270
+ }
271
+ return entries
272
+ }
273
+
274
+ /**
275
+ * The component each entry's set generates, by set id, built twice: first alone, so each
276
+ * knows its props, then knowing all the others, so an instance of one uses it rather than
277
+ * drawing its layers.
278
+ */
279
+ function generatedModels(
280
+ graph: SceneGraph,
281
+ entries: readonly StoryEntry[],
282
+ vectorElement: VectorElementRenderer | undefined
283
+ ): Map<string, ComponentModel> {
284
+ // Components are imported by their files' names, so the two always match. A group's item
285
+ // component gets a file of its own, named apart from every story file.
286
+ const taken = new Set(entries.map((entry) => entry.file.toLowerCase()))
287
+ const itemNames = new Map(
288
+ entries.map((entry) => [
289
+ entry.file,
290
+ claimName(`${entry.file}Item`, taken, { key: (name) => name.toLowerCase() })
291
+ ])
292
+ )
293
+ const model = (set: SceneNode, file: string, references?: ComponentReferences) =>
294
+ componentModel(graph, set, {
295
+ vectorElement,
296
+ references,
297
+ name: file,
298
+ itemName: itemNames.get(file)
299
+ })
300
+ const alone = new Map<string, ComponentModel>()
301
+ for (const { group, file, generate } of entries) {
302
+ const component = generate && group.set && model(group.set, file)
303
+ if (group.set && component) alone.set(group.set.id, component)
304
+ }
305
+ const models = new Map<string, ComponentModel>()
306
+ for (const { group, file } of entries) {
307
+ const component = group.set && alone.has(group.set.id) && model(group.set, file, alone)
308
+ if (group.set && component) models.set(group.set.id, component)
309
+ }
310
+ return models
311
+ }
312
+
313
+ /** The folder a document's shared files go in, unless the caller names one. */
314
+ function documentFolder(graph: SceneGraph, options: ExportStorybookOptions): string {
315
+ if (options.folder) return options.folder
316
+ const page = options.pageId ? graph.getNode(options.pageId)?.name : undefined
317
+ const named = compact([options.document ?? 'document', page]).map((name) => storyId(name))
318
+ return `pairdraw/${named.join('-')}`
319
+ }
320
+
321
+ /**
322
+ * The font files the entries' text uses, and the stylesheet that loads them. Faces load
323
+ * before text draws, so a story never shows a fallback font first.
324
+ */
325
+ async function storyFonts(
326
+ graph: SceneGraph,
327
+ entries: readonly StoryEntry[],
328
+ options: ExportStorybookOptions,
329
+ folder: string
330
+ ): Promise<ExportHTMLFile[]> {
331
+ if (!options.fonts) return []
332
+ const requests = new Map<string, WebFontFaceRequest>()
333
+ for (const { group } of entries)
334
+ for (const variant of group.variants)
335
+ for (const request of designFontRequests(
336
+ sceneNodeToDesignDocument(graph, variant.node.id, { includeSourceIds: false })
337
+ ))
338
+ requests.set(`${request.family}|${request.weight}|${request.style ?? 'normal'}`, request)
339
+ if (requests.size === 0) return []
340
+ const assets = await options.fonts([...requests.values()], `${folder}/fonts`)
341
+ if (assets.length === 0) return []
342
+ const css = await fontFaceStylesheet(assets, { from: folder, display: 'block' })
343
+ return [...assets, { path: `${folder}/fonts.css`, content: css }]
344
+ }
345
+
346
+ /**
347
+ * The document's design tokens as custom properties, which stories' styles refer to as
348
+ * `var(--…)` wherever the design binds a variable, so they resolve as the design draws them.
349
+ */
350
+ async function storyTokens(graph: SceneGraph, folder: string): Promise<ExportHTMLFile[]> {
351
+ if (graph.variables.size === 0) return []
352
+ const { css } = await tokenStylesheet(graph, { format: 'css' })
353
+ return css ? [{ path: `${folder}/tokens.css`, content: css }] : []
354
+ }
355
+
356
+ /**
357
+ * Generate one CSF3 `.stories.ts` file per component or component set, plus a
358
+ * `<Name>.design/` folder of variant images when `renderDesignImage` is given.
359
+ */
360
+ export async function exportStorybook(
361
+ graph: SceneGraph,
362
+ options: ExportStorybookOptions = {}
363
+ ): Promise<StorybookFile[]> {
364
+ const framework = options.framework ?? 'react'
365
+ const uniqueNames = uniqueLayerNames(graph)
366
+ const files: StorybookFile[] = []
367
+ const add = (page: SceneNode, path: string, content: string | Uint8Array) =>
368
+ files.push({ path, content, page: page.name })
369
+
370
+ const entries = storyEntries(graph, options)
371
+ const folder = documentFolder(graph, options)
372
+ const shared = [
373
+ ...(await storyFonts(graph, entries, options, folder)),
374
+ ...(await storyTokens(graph, folder))
375
+ ]
376
+ const firstPage = entries.at(0)?.page
377
+ if (firstPage) for (const file of shared) add(firstPage, file.path, file.content)
378
+ // Every story file loads the document's fonts and tokens.
379
+ const styles = shared.filter((file) => file.path.endsWith('.css')).map((file) => `./${file.path}`)
380
+ const generate = GENERATORS[framework]
381
+ const models = generate ? generatedModels(graph, entries, options.vectorElement) : new Map()
382
+
383
+ for (const { page, group, file, mode } of entries) {
384
+ const component = group.set && models.get(group.set.id)
385
+ 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
+ )
406
+ continue
407
+ }
408
+
409
+ // Only the stories a file keeps get design images; a gallery or Default alone keeps one.
410
+ const names = storyNames(group).slice(0, mode === 'variants' ? undefined : 1)
411
+ const render = options.renderDesignImage
412
+ const images = render ? names.map((name) => `${file}.design/${name}.png`) : []
413
+ if (render) {
414
+ for (const [i, variant] of group.variants.slice(0, names.length).entries())
415
+ add(page, images[i] ?? '', await render(variant.node.id))
416
+ }
417
+ const context = {
418
+ ...options,
419
+ graph,
420
+ framework,
421
+ uniqueNames,
422
+ storyNames: names,
423
+ images,
424
+ mode,
425
+ styles
426
+ }
427
+ add(page, `${file}.stories.ts`, storyModule(group, context))
428
+ }
429
+ return files
430
+ }
@@ -0,0 +1,161 @@
1
+ import { behaviourArgs } from '#dom-css/behaviours/args'
2
+ import { uniq } from 'es-toolkit/array'
3
+
4
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
5
+ import { restingVariant } from '@pairdraw/scene-graph/components'
6
+ import { deriveSlashVariantProperties } from '@pairdraw/scene-graph/variant-properties'
7
+
8
+ import type { StoryProp } from './module'
9
+ import { claimName } from './names'
10
+
11
+ interface StoryVariant {
12
+ values: string[]
13
+ node: SceneNode
14
+ }
15
+
16
+ /** One story file: a component set, a standalone component, or slash-named siblings. */
17
+ export interface StoryGroup {
18
+ page: SceneNode
19
+ title: string
20
+ name: string
21
+ props: StoryProp[]
22
+ variants: StoryVariant[]
23
+ /** Layer the story file links to, when the group has a layer of its own. */
24
+ linkNode?: string
25
+ /**
26
+ * The component set or standalone component the group shows, which may generate a component
27
+ * of its own; slash-named components grouped together have none.
28
+ */
29
+ set?: SceneNode
30
+ }
31
+
32
+ function isExported(node: SceneNode): boolean {
33
+ return node.visible && !node.internalOnly
34
+ }
35
+
36
+ /** Variants whose property values collide are told apart by layer name instead. */
37
+ function distinctVariants(group: StoryGroup): StoryGroup {
38
+ const keys = group.variants.map((variant) => JSON.stringify(variant.values))
39
+ if (new Set(keys).size === keys.length) return group
40
+ const taken = new Set<string>()
41
+ return {
42
+ ...group,
43
+ variants: group.variants.map((variant) => ({
44
+ ...variant,
45
+ values: [claimName(variant.node.name, taken, { separator: ' ' })]
46
+ })),
47
+ props: [{ name: 'Variant', options: [...taken] }]
48
+ }
49
+ }
50
+
51
+ function componentSetGroup(
52
+ graph: SceneGraph,
53
+ page: SceneNode,
54
+ section: string,
55
+ set: SceneNode
56
+ ): StoryGroup {
57
+ const definitions = set.componentPropertyDefinitions.filter((def) => def.type === 'VARIANT')
58
+ // The variant at its default values opens the file as its Default story.
59
+ const first = restingVariant(graph, set)
60
+ const components = graph
61
+ .getChildren(set.id)
62
+ .filter((child) => child.type === 'COMPONENT' && isExported(child))
63
+ const variants = [
64
+ ...components.filter((component) => component === first),
65
+ ...components.filter((component) => component !== first)
66
+ ].map((component) => ({
67
+ values: definitions.map((def) => component.componentPropertyValues[def.name] ?? ''),
68
+ node: component
69
+ }))
70
+ const args = behaviourArgs(graph, set)
71
+ const props = definitions.map((def, index): StoryProp => {
72
+ const options = uniq([
73
+ ...(def.variantOptions ?? []),
74
+ ...variants.map((v) => v.values[index] ?? '')
75
+ ])
76
+ const boolean = args?.booleans.get(def.name)
77
+ if (boolean) return { name: def.name, options, control: { type: 'boolean', ...boolean } }
78
+ if (args?.states?.property === def.name)
79
+ return {
80
+ name: def.name,
81
+ options,
82
+ control: { type: 'state', rest: args.states.rest, disabled: args.states.disabled }
83
+ }
84
+ return { name: def.name, options }
85
+ })
86
+ return distinctVariants({
87
+ page,
88
+ title: `${section}/${set.name}`,
89
+ name: set.name,
90
+ props,
91
+ variants,
92
+ linkNode: set.name,
93
+ set
94
+ })
95
+ }
96
+
97
+ function componentGroup(page: SceneNode, section: string, component: SceneNode): StoryGroup {
98
+ return {
99
+ page,
100
+ title: `${section}/${component.name}`,
101
+ name: component.name,
102
+ props: [],
103
+ variants: [{ values: [], node: component }],
104
+ linkNode: component.name,
105
+ // A standalone component generates a component of its own too, as a set does.
106
+ set: component
107
+ }
108
+ }
109
+
110
+ /** `Button/Primary`, `Button/Secondary` → one `Button` group with a derived variant property. */
111
+ function slashGroups(
112
+ page: SceneNode,
113
+ section: string,
114
+ prefix: string,
115
+ components: SceneNode[]
116
+ ): StoryGroup[] {
117
+ const derived = deriveSlashVariantProperties(components, () => '')
118
+ if (!derived) return components.map((component) => componentGroup(page, section, component))
119
+ const props = derived.definitions.map((def) => ({
120
+ name: def.name,
121
+ options: def.variantOptions ?? []
122
+ }))
123
+ const variants = components.map((component) => {
124
+ const values = derived.variants.get(component.id)?.componentPropertyValues ?? {}
125
+ return { values: props.map((prop) => values[prop.name] ?? ''), node: component }
126
+ })
127
+ return [distinctVariants({ page, title: `${section}/${prefix}`, name: prefix, props, variants })]
128
+ }
129
+
130
+ /**
131
+ * The story files a page produces, in layer order, titled under `section`, the page's name by
132
+ * default. Instances are never exported.
133
+ */
134
+ export function collectGroups(
135
+ graph: SceneGraph,
136
+ page: SceneNode,
137
+ section = page.name
138
+ ): StoryGroup[] {
139
+ const groups: StoryGroup[] = []
140
+ const slashed = new Map<string, SceneNode[]>()
141
+ const visit = (node: SceneNode) => {
142
+ if (!isExported(node) || node.type === 'INSTANCE') return
143
+ if (node.type === 'COMPONENT_SET') {
144
+ const group = componentSetGroup(graph, page, section, node)
145
+ if (group.variants.length > 0) groups.push(group)
146
+ return
147
+ }
148
+ if (node.type === 'COMPONENT') {
149
+ const [prefix, ...rest] = node.name.split('/')
150
+ const name = prefix.trim()
151
+ if (rest.length === 0 || !name) groups.push(componentGroup(page, section, node))
152
+ else slashed.set(name, [...(slashed.get(name) ?? []), node])
153
+ return
154
+ }
155
+ for (const child of graph.getChildren(node.id)) visit(child)
156
+ }
157
+ for (const child of graph.getChildren(page.id)) visit(child)
158
+ for (const [prefix, components] of slashed)
159
+ groups.push(...slashGroups(page, section, prefix, components))
160
+ return groups
161
+ }