@pairdraw/pen 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.
package/src/write.ts ADDED
@@ -0,0 +1,594 @@
1
+ import type {
2
+ BlendMode,
3
+ Fill,
4
+ GradientTransform,
5
+ LayoutAlign,
6
+ LayoutCounterAlign,
7
+ SceneGraph,
8
+ SceneNode,
9
+ ShadowEffect,
10
+ Stroke,
11
+ Variable,
12
+ VariableCollection,
13
+ VariableValue
14
+ } from '@pairdraw/scene-graph'
15
+ import { SceneGraph as SceneGraphValue } from '@pairdraw/scene-graph'
16
+ import { colorToHex, colorToHex8 } from '@pairdraw/scene-graph/color'
17
+ import { getNodeLocalMatrix } from '@pairdraw/scene-graph/coordinate'
18
+ import { stickySublayers } from '@pairdraw/scene-graph/generated'
19
+ import { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene-graph/gradient'
20
+ import { layoutSizing } from '@pairdraw/scene-graph/layout'
21
+ import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
22
+
23
+ import { PEN_PLUGIN_DATA_NAMESPACE } from './plugin-data'
24
+ import type {
25
+ PenDocument,
26
+ PenEffect,
27
+ PenNode,
28
+ PenNumber,
29
+ PenPaint,
30
+ PenPaints,
31
+ PenSides,
32
+ PenVariable,
33
+ PenVariableScalar
34
+ } from './schema'
35
+ const PEN_VERSION = '2.21'
36
+ const PEN_PLUGIN_FIELDS: Readonly<Partial<Record<string, string>>> = {
37
+ 'pen/type': 'type',
38
+ 'pen/ref': 'ref',
39
+ 'pen/generated': 'generated',
40
+ 'pen/context': 'context',
41
+ 'pen/placeholder': 'placeholder',
42
+ 'pen/slot': 'slot',
43
+ 'pen/model': 'model',
44
+ 'pen/scriptUri': 'scriptUri',
45
+ 'pen/inputs': 'inputs',
46
+ 'pen/url': 'url',
47
+ 'pen/deviceId': 'deviceId',
48
+ 'pen/zoom': 'zoom',
49
+ 'pen/scrollX': 'scrollX',
50
+ 'pen/scrollY': 'scrollY'
51
+ }
52
+
53
+ type PenWriteState = {
54
+ graph: SceneGraph
55
+ variables: ReadonlyMap<string, Variable>
56
+ collections: ReadonlyMap<string, VariableCollection>
57
+ }
58
+ /** Snaps matrix values that are within floating-point noise of an integer. */
59
+ function snapCoordinate(value: number): number {
60
+ return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value
61
+ }
62
+ function rounded(value: number): number {
63
+ return Number(value.toFixed(3))
64
+ }
65
+ function colorValue(value: Color): string {
66
+ return value.a === 1 ? colorToHex(value) : colorToHex8(value)
67
+ }
68
+ function variableReference(state: PenWriteState, id: string | undefined): string | undefined {
69
+ const variable = id === undefined ? undefined : state.variables.get(id)
70
+ return variable === undefined ? undefined : `$${variable.name}`
71
+ }
72
+ function variableOr<T>(state: PenWriteState, node: SceneNode, field: string, value: T): T | string {
73
+ return variableReference(state, node.boundVariables[field]) ?? value
74
+ }
75
+
76
+ /** Matches the pen corner convention of placing x/y after undoing the node's rotation or flip. */
77
+ function penCoordinates(node: SceneNode): Vector {
78
+ if (node.rotation === 0 && !node.flipX && !node.flipY) return { x: node.x, y: node.y }
79
+ const matrix = getNodeLocalMatrix({ ...node, x: 0, y: 0 })
80
+ return { x: snapCoordinate(node.x + matrix[2]), y: snapCoordinate(node.y + matrix[5]) }
81
+ }
82
+
83
+ /** pen.dev's names for the scene graph's blend modes, inverse of the reader's `BLEND_MODES`. */
84
+ const BLEND_MODE_NAMES: Partial<Record<BlendMode, string>> = {
85
+ NORMAL: 'normal',
86
+ DARKEN: 'darken',
87
+ MULTIPLY: 'multiply',
88
+ COLOR_BURN: 'colorBurn',
89
+ LIGHTEN: 'light',
90
+ SCREEN: 'screen',
91
+ COLOR_DODGE: 'colorDodge',
92
+ OVERLAY: 'overlay',
93
+ SOFT_LIGHT: 'softLight',
94
+ HARD_LIGHT: 'hardLight',
95
+ DIFFERENCE: 'difference',
96
+ EXCLUSION: 'exclusion',
97
+ HUE: 'hue',
98
+ SATURATION: 'saturation',
99
+ COLOR: 'color',
100
+ LUMINOSITY: 'luminosity'
101
+ }
102
+ function paintBase(fill: Fill): Record<string, unknown> {
103
+ const result: Record<string, unknown> = {}
104
+ if (!fill.visible) result.enabled = false
105
+ if (fill.opacity !== 1) result.opacity = rounded(fill.opacity)
106
+ const blendMode = (fill.blendMode && BLEND_MODE_NAMES[fill.blendMode]) ?? undefined
107
+ if (blendMode && blendMode !== 'normal') result.blendMode = blendMode
108
+ return result
109
+ }
110
+
111
+ function gradientName(type: Fill['type']): 'linear' | 'radial' | 'angular' | 'diamond' {
112
+ if (type === 'GRADIENT_RADIAL') return 'radial'
113
+ if (type === 'GRADIENT_ANGULAR') return 'angular'
114
+ if (type === 'GRADIENT_DIAMOND') return 'diamond'
115
+ return 'linear'
116
+ }
117
+
118
+ function gradientPoint(inverse: GradientTransform | undefined, point: Vector): Vector {
119
+ return inverse === undefined ? point : applyGradientTransform(inverse, point)
120
+ }
121
+ function gradientAxis(
122
+ fill: Fill,
123
+ inverse: GradientTransform | undefined,
124
+ center: Vector,
125
+ first: Vector,
126
+ second: Vector
127
+ ): { rotation: number; width: number; height: number } {
128
+ const firstLength = 2 * Math.hypot(first.x - center.x, first.y - center.y)
129
+ const secondLength = 2 * Math.hypot(second.x - center.x, second.y - center.y)
130
+ const rotationOf = (axis: Vector, offset: number): number =>
131
+ offset - (Math.atan2(axis.x, -axis.y) * 180) / Math.PI
132
+ if (fill.type === 'GRADIENT_LINEAR') {
133
+ const axis =
134
+ inverse === undefined
135
+ ? { x: 0, y: -1 }
136
+ : {
137
+ x: applyGradientTransform(inverse, { x: 1, y: 0.5 }).x - center.x,
138
+ y: applyGradientTransform(inverse, { x: 1, y: 0.5 }).y - center.y
139
+ }
140
+ return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }
141
+ }
142
+ if (fill.type === 'GRADIENT_RADIAL' || fill.type === 'GRADIENT_DIAMOND') {
143
+ const axis = { x: second.x - center.x, y: second.y - center.y }
144
+ return { rotation: rotationOf(axis, 180), width: firstLength, height: secondLength }
145
+ }
146
+ const axis = { x: first.x - center.x, y: first.y - center.y }
147
+ return { rotation: rotationOf(axis, 0), width: secondLength, height: firstLength }
148
+ }
149
+ function gradientPaint(fill: Fill): PenPaint {
150
+ const transform = fill.gradientTransform
151
+ const inverse = transform === undefined ? undefined : invertGradientTransform(transform)
152
+ const center = gradientPoint(inverse, { x: 0.5, y: 0.5 })
153
+ const first = gradientPoint(inverse, { x: 1, y: 0.5 })
154
+ const second = gradientPoint(inverse, { x: 0.5, y: 1 })
155
+ const axis = gradientAxis(fill, inverse, center, first, second)
156
+ return {
157
+ type: 'gradient',
158
+ gradientType: gradientName(fill.type),
159
+ ...paintBase(fill),
160
+ center: { x: rounded(center.x), y: rounded(center.y) },
161
+ size: { width: rounded(axis.width), height: rounded(axis.height) },
162
+ rotation: rounded(axis.rotation),
163
+ colors: (fill.gradientStops ?? []).map((stop) => ({
164
+ color: colorValue(stop.color),
165
+ position: rounded(stop.position)
166
+ }))
167
+ }
168
+ }
169
+
170
+ function imagePaint(fill: Fill): PenPaint {
171
+ return { type: 'image', ...paintBase(fill), url: fill.imageHash }
172
+ }
173
+
174
+ function penPaint(
175
+ state: PenWriteState,
176
+ node: SceneNode,
177
+ field: 'fills' | 'strokes',
178
+ fill: Fill,
179
+ index: number
180
+ ): PenPaint {
181
+ if (fill.type === 'SOLID') {
182
+ const binding = variableReference(state, node.boundVariables[`${field}/${index}/color`])
183
+ return { type: 'color', color: binding ?? colorValue(fill.color), ...paintBase(fill) }
184
+ }
185
+ if (fill.type.startsWith('GRADIENT_')) return gradientPaint(fill)
186
+ if (fill.type === 'IMAGE') return imagePaint(fill)
187
+ return { type: fill.type.toLowerCase(), ...paintBase(fill) }
188
+ }
189
+
190
+ function paintsOf(
191
+ state: PenWriteState,
192
+ node: SceneNode,
193
+ field: 'fills' | 'strokes',
194
+ paints: readonly Fill[]
195
+ ): PenPaints | undefined {
196
+ if (paints.length === 0) return undefined
197
+ const result = paints.map((paint, index) => penPaint(state, node, field, paint, index))
198
+ return result.length === 1 ? result[0] : result
199
+ }
200
+
201
+ function strokesOf(
202
+ state: PenWriteState,
203
+ node: SceneNode
204
+ ): Pick<
205
+ PenNode,
206
+ 'stroke' | 'strokeWidth' | 'strokeAlignment' | 'strokeLinecap' | 'strokeLinejoin'
207
+ > {
208
+ if (node.strokes.length === 0) return {}
209
+ const paints = paintsOf(state, node, 'strokes', node.strokes)
210
+ if (paints === undefined) return {}
211
+ const first = node.strokes[0]
212
+ const strokeWidth: PenNumber | PenSides = node.independentStrokeWeights
213
+ ? {
214
+ top: variableOr(state, node, 'borderTopWeight', rounded(node.borderTopWeight)),
215
+ right: variableOr(state, node, 'borderRightWeight', rounded(node.borderRightWeight)),
216
+ bottom: variableOr(state, node, 'borderBottomWeight', rounded(node.borderBottomWeight)),
217
+ left: variableOr(state, node, 'borderLeftWeight', rounded(node.borderLeftWeight))
218
+ }
219
+ : variableOr(state, node, 'strokeWeight', rounded(first.weight))
220
+ const caps: Record<NonNullable<Stroke['cap']>, string> = {
221
+ NONE: 'butt',
222
+ ROUND: 'round',
223
+ SQUARE: 'square',
224
+ ARROW_LINES: 'butt',
225
+ ARROW_EQUILATERAL: 'butt',
226
+ TRIANGLE_FILLED: 'butt',
227
+ DIAMOND_FILLED: 'butt',
228
+ CIRCLE_FILLED: 'butt'
229
+ }
230
+ const joins: Record<NonNullable<Stroke['join']>, string> = {
231
+ MITER: 'miter',
232
+ BEVEL: 'bevel',
233
+ ROUND: 'round'
234
+ }
235
+ const linecap = first.cap === undefined ? undefined : caps[first.cap]
236
+ const linejoin = first.join === undefined ? undefined : joins[first.join]
237
+ return {
238
+ stroke: paints,
239
+ strokeWidth,
240
+ strokeAlignment: first.align.toLowerCase(),
241
+ strokeLinecap: linecap === 'butt' ? undefined : linecap,
242
+ strokeLinejoin: linejoin === 'miter' ? undefined : linejoin
243
+ }
244
+ }
245
+
246
+ function effectOf(effect: ShadowEffect): PenEffect {
247
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') {
248
+ return {
249
+ type: effect.type === 'LAYER_BLUR' ? 'blur' : 'background_blur',
250
+ radius: rounded(effect.radius),
251
+ enabled: effect.visible
252
+ }
253
+ }
254
+ return {
255
+ type: 'shadow',
256
+ shadowType: effect.type === 'INNER_SHADOW' ? 'inner' : undefined,
257
+ color: colorValue(effect.color),
258
+ offset: { x: rounded(effect.offset.x), y: rounded(effect.offset.y) },
259
+ blur: rounded(effect.radius),
260
+ spread: rounded(effect.spread),
261
+ enabled: effect.visible
262
+ }
263
+ }
264
+
265
+ function variableType(type: Variable['type']): PenVariable['type'] {
266
+ if (type === 'COLOR') return 'color'
267
+ if (type === 'FLOAT') return 'number'
268
+ if (type === 'BOOLEAN') return 'boolean'
269
+ return 'string'
270
+ }
271
+
272
+ function layoutFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
273
+ if (node.layoutMode === 'NONE')
274
+ return node.type === 'FRAME' || node.type === 'COMPONENT' ? { layout: 'none' } : {}
275
+ const justify: Partial<Record<LayoutAlign, string>> = {
276
+ CENTER: 'center',
277
+ MAX: 'end',
278
+ SPACE_BETWEEN: 'space_between',
279
+ SPACE_AROUND: 'space_around'
280
+ }
281
+ const align: Partial<Record<LayoutCounterAlign, string>> = {
282
+ CENTER: 'center',
283
+ MAX: 'end',
284
+ STRETCH: 'stretch',
285
+ BASELINE: 'baseline'
286
+ }
287
+ const fields: Partial<PenNode> = {
288
+ layout: node.layoutMode === 'HORIZONTAL' ? 'horizontal' : 'vertical'
289
+ }
290
+ const gapBinding = variableReference(state, node.boundVariables['itemSpacing'])
291
+ if (gapBinding !== undefined) fields.gap = gapBinding
292
+ else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing)
293
+ if (node.primaryAxisAlign !== 'MIN') fields.justifyContent = justify[node.primaryAxisAlign]
294
+ if (node.counterAxisAlign !== 'MIN') fields.alignItems = align[node.counterAxisAlign]
295
+ const padding: [number, number, number, number] = [
296
+ node.paddingTop,
297
+ node.paddingRight,
298
+ node.paddingBottom,
299
+ node.paddingLeft
300
+ ]
301
+ if (padding.some((value) => value !== 0)) fields.padding = padding
302
+ if (node.clipsContent) fields.clip = true
303
+ if (node.strokesIncludedInLayout) fields.layoutIncludeStroke = true
304
+ return fields
305
+ }
306
+
307
+ function sizing(
308
+ state: PenWriteState,
309
+ node: SceneNode,
310
+ axis: 'HORIZONTAL' | 'VERTICAL'
311
+ ): PenNumber | undefined {
312
+ const mode = layoutSizing(state.graph, node, axis)
313
+ if (mode === 'FILL') return 'fill_container'
314
+ if (mode === 'HUG') return 'fit_content'
315
+ return undefined
316
+ }
317
+
318
+ function penPluginFields(node: SceneNode, result: PenNode): void {
319
+ for (const entry of node.pluginData) {
320
+ if (entry.pluginId !== PEN_PLUGIN_DATA_NAMESPACE) continue
321
+ const field = PEN_PLUGIN_FIELDS[entry.key]
322
+ if (field === undefined) continue
323
+ let value: unknown
324
+ try {
325
+ value = JSON.parse(entry.value)
326
+ } catch {
327
+ console.warn(`Skipping corrupt pen plugin field ${field}`)
328
+ continue
329
+ }
330
+ result[field] = value
331
+ }
332
+ }
333
+
334
+ function nodeType(node: SceneNode): string {
335
+ switch (node.type) {
336
+ case 'COMPONENT':
337
+ case 'COMPONENT_SET':
338
+ case 'FRAME':
339
+ case 'SECTION':
340
+ return 'frame'
341
+ case 'RECTANGLE':
342
+ case 'ROUNDED_RECTANGLE':
343
+ return 'rectangle'
344
+ case 'ELLIPSE':
345
+ return 'ellipse'
346
+ case 'POLYGON':
347
+ case 'STAR':
348
+ return 'polygon'
349
+ case 'GROUP':
350
+ case 'BOOLEAN_OPERATION':
351
+ return 'group'
352
+ case 'TEXT':
353
+ return 'text'
354
+ case 'VECTOR':
355
+ return 'path'
356
+ case 'LINE':
357
+ return 'line'
358
+ case 'STICKY':
359
+ return 'note'
360
+ default:
361
+ return 'frame'
362
+ }
363
+ }
364
+
365
+ /** A line height as the multiple of the font size pen.dev stores; undefined when it has none. */
366
+ function lineHeightMultiple(node: SceneNode): number | undefined {
367
+ const lineHeight = node.lineHeight
368
+ if (!lineHeight) return undefined
369
+ if (lineHeight.unit !== 'PIXELS') return rounded(lineHeight.value / 100)
370
+ return node.fontSize > 0 ? rounded(lineHeight.value / node.fontSize) : undefined
371
+ }
372
+
373
+ /** Letter spacing in the pixels pen.dev stores, a percent following the font size. */
374
+ function letterSpacingPixels(node: SceneNode): number {
375
+ const spacing = node.letterSpacing
376
+ return spacing.unit === 'PIXELS' ? spacing.value : (spacing.value / 100) * node.fontSize
377
+ }
378
+
379
+ function textFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
380
+ if (node.type !== 'TEXT') return {}
381
+ const fields: Partial<PenNode> = { content: node.text }
382
+ if (node.fontFamily !== 'Inter')
383
+ fields.fontFamily = variableOr(state, node, 'fontFamily', node.fontFamily)
384
+ if (node.fontSize !== 14)
385
+ fields.fontSize = variableOr(state, node, 'fontSize', rounded(node.fontSize))
386
+ const fontWeight = variableOr(state, node, 'fontWeight', node.fontWeight)
387
+ if (typeof fontWeight === 'string' || node.fontWeight !== 400) fields.fontWeight = fontWeight
388
+ if (node.italic) fields.fontStyle = 'italic'
389
+ const textAlign: Partial<Record<SceneNode['textAlignHorizontal'], string>> = {
390
+ CENTER: 'center',
391
+ RIGHT: 'right',
392
+ JUSTIFIED: 'justify'
393
+ }
394
+ const textAlignVertical: Partial<Record<SceneNode['textAlignVertical'], string>> = {
395
+ CENTER: 'middle',
396
+ BOTTOM: 'bottom'
397
+ }
398
+ if (node.textAlignHorizontal !== 'LEFT') fields.textAlign = textAlign[node.textAlignHorizontal]
399
+ if (node.textAlignVertical !== 'TOP')
400
+ fields.textAlignVertical = textAlignVertical[node.textAlignVertical]
401
+ const lineHeight = lineHeightMultiple(node)
402
+ if (lineHeight !== undefined) fields.lineHeight = lineHeight
403
+ if (node.letterSpacing.value !== 0) fields.letterSpacing = rounded(letterSpacingPixels(node))
404
+ if (node.textAutoResize === 'HEIGHT') fields.textGrowth = 'fixed-width'
405
+ if (node.textAutoResize === 'NONE' || node.textAutoResize === 'TRUNCATE')
406
+ fields.textGrowth = 'fixed-width-height'
407
+ const link = node.styleRuns.find((run) => run.style.hyperlink?.type === 'URL')
408
+ if (link?.style.hyperlink?.type === 'URL') fields.href = link.style.hyperlink.value
409
+ return fields
410
+ }
411
+
412
+ function cornerFields(node: SceneNode): Partial<PenNode> {
413
+ if (node.independentCorners) {
414
+ return {
415
+ cornerRadius: [
416
+ node.topLeftRadius,
417
+ node.topRightRadius,
418
+ node.bottomRightRadius,
419
+ node.bottomLeftRadius
420
+ ]
421
+ }
422
+ }
423
+ if (node.cornerRadius !== 0) return { cornerRadius: rounded(node.cornerRadius) }
424
+ return {}
425
+ }
426
+
427
+ function variableScalar(value: VariableValue | undefined, state: PenWriteState): PenVariableScalar {
428
+ if (value === undefined) return ''
429
+ if (typeof value === 'object' && 'aliasId' in value) {
430
+ const variable = state.variables.get(value.aliasId)
431
+ return variable === undefined ? '' : `$${variable.name}`
432
+ }
433
+ if (typeof value === 'object') return 'r' in value ? colorValue(value) : ''
434
+ return value
435
+ }
436
+ function penVariable(
437
+ variable: Variable,
438
+ collection: VariableCollection | undefined,
439
+ state: PenWriteState
440
+ ): PenVariable {
441
+ const modes = collection?.modes ?? []
442
+ if (modes.length <= 1)
443
+ return {
444
+ type: variableType(variable.type),
445
+ value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state)
446
+ }
447
+ return {
448
+ type: variableType(variable.type),
449
+ value: modes.map((mode, index) => ({
450
+ value: variableScalar(variable.valuesByMode[mode.modeId], state),
451
+ ...(index === 0 ? {} : { theme: { [collection?.name ?? 'Mode']: mode.name } })
452
+ }))
453
+ }
454
+ }
455
+
456
+ function variablesOf(state: PenWriteState): Record<string, PenVariable> | undefined {
457
+ if (state.graph.variables.size === 0) return undefined
458
+ return Object.fromEntries(
459
+ [...state.graph.variables.values()]
460
+ .sort((left, right) => left.name.localeCompare(right.name))
461
+ .map((variable) => [
462
+ variable.name,
463
+ penVariable(variable, state.collections.get(variable.collectionId), state)
464
+ ])
465
+ )
466
+ }
467
+
468
+ function themesOf(state: PenWriteState): PenDocument['themes'] {
469
+ if (state.graph.variableCollections.size === 0) return undefined
470
+ return Object.fromEntries(
471
+ [...state.graph.variableCollections.values()]
472
+ .sort((left, right) => left.name.localeCompare(right.name))
473
+ .map((collection) => [collection.name, collection.modes.map((mode) => mode.name)])
474
+ )
475
+ }
476
+
477
+ function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): void {
478
+ if (node.name) result.name = node.name
479
+ const placement = penCoordinates(node)
480
+ if (placement.x !== 0) result.x = rounded(placement.x)
481
+ if (placement.y !== 0) result.y = rounded(placement.y)
482
+ result.width = variableOr(
483
+ state,
484
+ node,
485
+ 'width',
486
+ sizing(state, node, 'HORIZONTAL') ?? rounded(node.width)
487
+ )
488
+ result.height = variableOr(
489
+ state,
490
+ node,
491
+ 'height',
492
+ sizing(state, node, 'VERTICAL') ?? rounded(node.height)
493
+ )
494
+ if (!node.visible) result.enabled = false
495
+ if (node.opacity !== 1) result.opacity = rounded(node.opacity)
496
+ if (node.rotation !== 0)
497
+ result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation)
498
+ if (node.flipX) result.flipX = true
499
+ if (node.flipY) result.flipY = true
500
+ const fill = paintsOf(state, node, 'fills', node.fills)
501
+ if (fill !== undefined) result.fill = fill
502
+ Object.assign(
503
+ result,
504
+ strokesOf(state, node),
505
+ layoutFields(state, node),
506
+ cornerFields(node),
507
+ textFields(state, node)
508
+ )
509
+ }
510
+ function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {
511
+ if (
512
+ node.type === 'TEXT' &&
513
+ node.textAutoResize === 'WIDTH_AND_HEIGHT' &&
514
+ layoutSizing(state.graph, node, 'HORIZONTAL') === 'HUG'
515
+ )
516
+ result.width = 'fit_content'
517
+ if (node.type === 'STICKY') result.content = stickySublayers(state.graph, node)?.body.text ?? ''
518
+ penPluginFields(node, result)
519
+ // Shader effects have no pen.dev form yet; dropping them keeps the file loadable.
520
+ const effects = node.effects.filter((effect): effect is ShadowEffect => effect.type !== 'SHADER')
521
+ if (effects.length > 0)
522
+ result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf)
523
+ if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') result.reusable = true
524
+ if (node.type === 'INSTANCE' && node.componentId) {
525
+ result.type = 'ref'
526
+ result.ref = node.componentId
527
+ return true
528
+ }
529
+ return false
530
+ }
531
+ function writeNode(state: PenWriteState, node: SceneNode): PenNode {
532
+ const result: PenNode = { id: node.id, type: nodeType(node) }
533
+ basicNodeFields(state, node, result)
534
+ if (semanticNodeFields(state, node, result)) return result
535
+ const children =
536
+ node.type === 'STICKY'
537
+ ? []
538
+ : state.graph
539
+ .getChildren(node.id)
540
+ .filter((child) => !child.internalOnly)
541
+ .map((child) => writeNode(state, child))
542
+ if (children.length > 0) result.children = children
543
+ return result
544
+ }
545
+
546
+ /** Code-point order, so the canonical text does not depend on the runtime locale. */
547
+ function compareCodePoints(left: string, right: string): number {
548
+ if (left < right) return -1
549
+ if (left > right) return 1
550
+ return 0
551
+ }
552
+
553
+ function sortKeys(value: unknown): unknown {
554
+ if (Array.isArray(value)) return value.map(sortKeys)
555
+ if (value !== null && typeof value === 'object') {
556
+ const entries = Object.entries(value as { [key: string]: unknown })
557
+ return Object.fromEntries(
558
+ entries
559
+ .sort(([left], [right]) => compareCodePoints(left, right))
560
+ .map(([key, entry]) => [key, sortKeys(entry)])
561
+ )
562
+ }
563
+ return value
564
+ }
565
+
566
+ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
567
+ const variables = new Map<string, Variable>()
568
+ for (const variable of graph.variables.values()) variables.set(variable.id, variable)
569
+ const collections = new Map<string, VariableCollection>()
570
+ for (const collection of graph.variableCollections.values())
571
+ collections.set(collection.id, collection)
572
+ const state: PenWriteState = { graph, variables, collections }
573
+ const children = graph.getPages().flatMap((page) =>
574
+ graph
575
+ .getChildren(page.id)
576
+ .filter((node) => !node.internalOnly)
577
+ .map((node) => writeNode(state, node))
578
+ )
579
+ const document: PenDocument = { version: PEN_VERSION, children }
580
+ const variablesValue = variablesOf(state)
581
+ if (variablesValue) document.variables = variablesValue
582
+ const themes = themesOf(state)
583
+ if (themes) document.themes = themes
584
+ return document
585
+ }
586
+
587
+ export function stringifyPenDocument(document: PenDocument): string {
588
+ return `${JSON.stringify(sortKeys(document), null, 2)}\n`
589
+ }
590
+
591
+ export function writePenDocument(source: PenDocument | SceneGraph): string {
592
+ const document = source instanceof SceneGraphValue ? penDocumentFromGraph(source) : source
593
+ return stringifyPenDocument(document)
594
+ }