@pairdraw/design-jsx 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 (109) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +48 -2
  3. package/dist/chunks/attributes.js +32 -0
  4. package/dist/chunks/attributes.js.map +1 -0
  5. package/dist/chunks/behaviours/elements.js +321 -0
  6. package/dist/chunks/behaviours/elements.js.map +1 -0
  7. package/dist/chunks/behaviours/render.js +368 -0
  8. package/dist/chunks/behaviours/render.js.map +1 -0
  9. package/dist/chunks/component-properties.js +809 -0
  10. package/dist/chunks/component-properties.js.map +1 -0
  11. package/dist/chunks/components.js +78 -0
  12. package/dist/chunks/components.js.map +1 -0
  13. package/dist/chunks/connectors.js +290 -0
  14. package/dist/chunks/connectors.js.map +1 -0
  15. package/dist/chunks/effects.js +57 -0
  16. package/dist/chunks/effects.js.map +1 -0
  17. package/dist/chunks/elements.js +618 -0
  18. package/dist/chunks/elements.js.map +1 -0
  19. package/dist/chunks/export/behaviours.js +113 -0
  20. package/dist/chunks/export/behaviours.js.map +1 -0
  21. package/dist/chunks/export/bindings.js +273 -0
  22. package/dist/chunks/export/bindings.js.map +1 -0
  23. package/dist/chunks/export/decoration.js +96 -0
  24. package/dist/chunks/export/decoration.js.map +1 -0
  25. package/dist/chunks/export/font.js +17 -0
  26. package/dist/chunks/export/font.js.map +1 -0
  27. package/dist/chunks/export/icons.js +34 -0
  28. package/dist/chunks/export/icons.js.map +1 -0
  29. package/dist/chunks/export/index.js +1390 -0
  30. package/dist/chunks/export/index.js.map +1 -0
  31. package/dist/chunks/fields.js +1065 -0
  32. package/dist/chunks/fields.js.map +1 -0
  33. package/dist/chunks/index.js +438 -0
  34. package/dist/chunks/index.js.map +1 -0
  35. package/dist/chunks/jsx-dev-runtime.js +16 -0
  36. package/dist/chunks/jsx-dev-runtime.js.map +1 -0
  37. package/dist/index.d.ts +543 -0
  38. package/dist/index.d.ts.map +1 -0
  39. package/dist/index.js +11 -0
  40. package/dist/jsx-dev-runtime.d.ts +2 -0
  41. package/dist/jsx-dev-runtime.js +2 -0
  42. package/dist/jsx-runtime.d.ts +44 -0
  43. package/dist/jsx-runtime.d.ts.map +1 -0
  44. package/dist/jsx-runtime.js +2 -0
  45. package/dist/tree.d.ts +261 -0
  46. package/dist/tree.d.ts.map +1 -0
  47. package/package.json +54 -4
  48. package/src/attributes.ts +30 -0
  49. package/src/behaviours/elements.ts +47 -0
  50. package/src/behaviours/index.ts +253 -0
  51. package/src/behaviours/render.ts +144 -0
  52. package/src/component-properties.ts +428 -0
  53. package/src/components.ts +109 -0
  54. package/src/connectors.ts +316 -0
  55. package/src/definitions.ts +277 -0
  56. package/src/effects.ts +80 -0
  57. package/src/elements.ts +321 -0
  58. package/src/enums.ts +182 -0
  59. package/src/export/behaviours.ts +143 -0
  60. package/src/export/bindings.ts +155 -0
  61. package/src/export/decoration.ts +39 -0
  62. package/src/export/font.ts +25 -0
  63. package/src/export/helpers.ts +75 -0
  64. package/src/export/icons.ts +42 -0
  65. package/src/export/index.ts +297 -0
  66. package/src/export/paint.ts +276 -0
  67. package/src/export/props.ts +369 -0
  68. package/src/export/state.ts +52 -0
  69. package/src/export/text.ts +155 -0
  70. package/src/export/value.ts +99 -0
  71. package/src/export/variables.ts +393 -0
  72. package/src/fields.ts +39 -0
  73. package/src/figjam-text.ts +37 -0
  74. package/src/global.d.ts +4 -0
  75. package/src/helpers.ts +135 -0
  76. package/src/index.ts +155 -0
  77. package/src/jsx-dev-runtime.ts +1 -0
  78. package/src/jsx-runtime.ts +51 -0
  79. package/src/mini-react.ts +23 -0
  80. package/src/overrides/effects.ts +39 -0
  81. package/src/overrides/fills.ts +56 -0
  82. package/src/overrides/state.ts +55 -0
  83. package/src/overrides/strokes.ts +109 -0
  84. package/src/overrides/text.ts +116 -0
  85. package/src/overrides/vector.ts +122 -0
  86. package/src/paints.ts +230 -0
  87. package/src/props-overrides.ts +481 -0
  88. package/src/reconcile.ts +134 -0
  89. package/src/reference/authoring.md +76 -0
  90. package/src/reference/examples.ts +49 -0
  91. package/src/reference.ts +19 -0
  92. package/src/refs.ts +48 -0
  93. package/src/render.ts +147 -0
  94. package/src/renderer.ts +598 -0
  95. package/src/scalar-bindings.ts +36 -0
  96. package/src/schema.ts +213 -0
  97. package/src/services.ts +36 -0
  98. package/src/shapes-with-text.ts +73 -0
  99. package/src/stickies.ts +72 -0
  100. package/src/streaming/index.ts +47 -0
  101. package/src/streaming/literals.ts +82 -0
  102. package/src/streaming/projection.ts +189 -0
  103. package/src/text-content.ts +233 -0
  104. package/src/transform.ts +78 -0
  105. package/src/tree.ts +285 -0
  106. package/src/types.ts +13 -0
  107. package/src/variables/graph.ts +265 -0
  108. package/src/variables/index.ts +124 -0
  109. package/src/variables/props.ts +77 -0
@@ -0,0 +1,481 @@
1
+ import type { Fill, SceneNode, ArcData, NodeType } from '@pairdraw/scene-graph'
2
+ import { colorToFill } from '@pairdraw/scene-graph/color'
3
+ import { parseCSSGridTracks, parseCSSNumber } from '@pairdraw/scene-graph/css'
4
+ import {
5
+ autoLayoutSizingFields,
6
+ fillSizingFields,
7
+ parseAutoLayoutDirection,
8
+ parseCounterAxisAlign,
9
+ parsePrimaryAxisAlign
10
+ } from '@pairdraw/scene-graph/layout'
11
+ import type { Color, JSONObject } from '@pairdraw/scene-graph/primitives'
12
+ import { withShaderPaints, type ShaderPaint } from '@pairdraw/scene-graph/shaders'
13
+
14
+ import { DESIGN_JSX_STYLE_KEYS, designJSXProp } from './definitions'
15
+ import {
16
+ BLEND_MODE,
17
+ TEXT_ALIGN,
18
+ TEXT_ALIGN_VERTICAL,
19
+ TEXT_AUTO_RESIZE,
20
+ TEXT_CASE,
21
+ TEXT_DECORATION,
22
+ TEXT_DIRECTION
23
+ } from './enums'
24
+ import { applyEffectOverrides } from './overrides/effects'
25
+ import { fillFromValue, isColor, isFillValue } from './overrides/fills'
26
+ import { applyStateOverrides } from './overrides/state'
27
+ import { applyStrokeOverrides } from './overrides/strokes'
28
+ import { applyTextDetailOverrides, AUTO, textLengthProp } from './overrides/text'
29
+ import { isShaderFill } from './paints'
30
+
31
+ const WEIGHT_MAP: Record<string, number> = {
32
+ normal: 400,
33
+ medium: 500,
34
+ bold: 700
35
+ }
36
+
37
+ function parseDirection(value: unknown): SceneNode['textDirection'] | undefined {
38
+ if (typeof value !== 'string') return undefined
39
+ return TEXT_DIRECTION.parse(value) ?? 'AUTO'
40
+ }
41
+
42
+ function numberFromPx(value: unknown): number | undefined {
43
+ if (typeof value === 'number') return value
44
+ return typeof value === 'string' ? (parseCSSNumber(value) ?? undefined) : undefined
45
+ }
46
+
47
+ /** `props` with the sizes and styles its `style` object gives, where the props leave them unset. */
48
+ export function normalizeStyleProps(props: Record<string, unknown>): Record<string, unknown> {
49
+ const style = props.style
50
+ if (style === null || typeof style !== 'object' || Array.isArray(style)) return props
51
+
52
+ const source = style as JSONObject
53
+ const normalized = { ...props }
54
+ for (const [name, keys] of Object.entries(DESIGN_JSX_STYLE_KEYS)) {
55
+ if (designJSXProp(normalized, name) !== undefined) continue
56
+ const found = keys.find(({ key }) => source[key] !== undefined)
57
+ if (found) normalized[name] = found.px ? numberFromPx(source[found.key]) : source[found.key]
58
+ }
59
+ return normalized
60
+ }
61
+
62
+ export function applySizeOverrides(
63
+ props: Record<string, unknown>,
64
+ o: Partial<SceneNode>,
65
+ parentLayout: SceneNode['layoutMode']
66
+ ): { w: unknown; h: unknown } {
67
+ const w = designJSXProp(props, 'w')
68
+ const h = designJSXProp(props, 'h')
69
+ if (typeof w === 'number') o.width = w
70
+ if (typeof h === 'number') o.height = h
71
+
72
+ if (w === 'fill') Object.assign(o, fillSizingFields(parentLayout, 'HORIZONTAL'))
73
+ if (h === 'fill') Object.assign(o, fillSizingFields(parentLayout, 'VERTICAL'))
74
+
75
+ if (props.x !== undefined) o.x = props.x as number
76
+ if (props.y !== undefined) o.y = props.y as number
77
+ if (props.top !== undefined) o.y = props.top as number
78
+ if (props.left !== undefined) o.x = props.left as number
79
+
80
+ if (props.position === 'absolute') o.layoutPositioning = 'ABSOLUTE'
81
+ const hasExplicitPosition =
82
+ props.x !== undefined ||
83
+ props.y !== undefined ||
84
+ props.top !== undefined ||
85
+ props.left !== undefined
86
+ if (hasExplicitPosition && parentLayout !== 'NONE') {
87
+ o.layoutPositioning = 'ABSOLUTE'
88
+ }
89
+
90
+ return { w, h }
91
+ }
92
+
93
+ /**
94
+ * Sets the layer's fills, moving each shader paint's preset into the layer's plugin data,
95
+ * where a shader paint keeps it.
96
+ */
97
+ function setFills(values: (string | Color | Fill)[], o: Partial<SceneNode>): void {
98
+ const shaders: ShaderPaint[] = []
99
+ const fills = values.map((value) => {
100
+ const fill = fillFromValue(value)
101
+ if (!isShaderFill(fill)) return fill
102
+ const { shader, ...paint } = fill
103
+ if (paint.imageHash) shaders.push(shader)
104
+ return paint
105
+ })
106
+ if (fills.length === 0) return
107
+ o.fills = fills
108
+ if (shaders.length > 0)
109
+ o.pluginData = withShaderPaints({ pluginData: o.pluginData ?? [] }, fills, shaders)
110
+ }
111
+
112
+ function applyFillOverride(props: Record<string, unknown>, o: Partial<SceneNode>): void {
113
+ // `fills={[]}` paints nothing, which a text, painted black by default, has to say.
114
+ if (Array.isArray(props.fills) && props.fills.length === 0) {
115
+ o.fills = []
116
+ return
117
+ }
118
+ if (Array.isArray(props.fills)) {
119
+ setFills(props.fills.filter(isFillValue), o)
120
+ return
121
+ }
122
+
123
+ const bg = designJSXProp(props, 'bg')
124
+ if (isFillValue(bg)) setFills([bg], o)
125
+ }
126
+
127
+ function applyCornerOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
128
+ const rounded = designJSXProp(props, 'rounded')
129
+ if (typeof rounded === 'number') o.cornerRadius = rounded
130
+
131
+ if (
132
+ props.roundedTL !== undefined ||
133
+ props.roundedTR !== undefined ||
134
+ props.roundedBL !== undefined ||
135
+ props.roundedBR !== undefined
136
+ ) {
137
+ o.independentCorners = true
138
+ if (props.roundedTL !== undefined) o.topLeftRadius = props.roundedTL as number
139
+ if (props.roundedTR !== undefined) o.topRightRadius = props.roundedTR as number
140
+ if (props.roundedBL !== undefined) o.bottomLeftRadius = props.roundedBL as number
141
+ if (props.roundedBR !== undefined) o.bottomRightRadius = props.roundedBR as number
142
+ }
143
+
144
+ if (props.cornerSmoothing !== undefined) o.cornerSmoothing = props.cornerSmoothing as number
145
+ }
146
+
147
+ function applyVisualOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
148
+ applyFillOverride(props, o)
149
+ applyStrokeOverrides(props, o)
150
+ applyCornerOverrides(props, o)
151
+
152
+ if (props.opacity !== undefined) o.opacity = props.opacity as number
153
+ applyTransformOverrides(props, o)
154
+ const blendMode = BLEND_MODE.parse(props.blendMode)
155
+ if (blendMode) o.blendMode = blendMode
156
+ if (props.overflow === 'hidden') o.clipsContent = true
157
+ }
158
+
159
+ function applyTransformOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
160
+ const rotation = designJSXProp(props, 'rotate')
161
+ if (rotation !== undefined) o.rotation = rotation as number
162
+ if (props.flipX !== undefined) o.flipX = props.flipX === true
163
+ if (props.flipY !== undefined) o.flipY = props.flipY === true
164
+ }
165
+
166
+ function applyPaddingOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
167
+ const p = designJSXProp(props, 'p')
168
+ if (typeof p === 'number') {
169
+ o.paddingTop = p
170
+ o.paddingRight = p
171
+ o.paddingBottom = p
172
+ o.paddingLeft = p
173
+ }
174
+ const px = props.px as number | undefined
175
+ const py = props.py as number | undefined
176
+ if (px !== undefined) {
177
+ o.paddingLeft = px
178
+ o.paddingRight = px
179
+ }
180
+ if (py !== undefined) {
181
+ o.paddingTop = py
182
+ o.paddingBottom = py
183
+ }
184
+ if (props.pt !== undefined) o.paddingTop = props.pt as number
185
+ if (props.pr !== undefined) o.paddingRight = props.pr as number
186
+ if (props.pb !== undefined) o.paddingBottom = props.pb as number
187
+ if (props.pl !== undefined) o.paddingLeft = props.pl as number
188
+ }
189
+
190
+ const PADDING_KEYS = ['p', 'padding', 'px', 'py', 'pt', 'pr', 'pb', 'pl'] as const
191
+ const AUTO_LAYOUT_TRIGGER_KEYS = [
192
+ ...PADDING_KEYS,
193
+ 'justify',
194
+ 'justifyContent',
195
+ 'items',
196
+ 'align',
197
+ 'alignItems'
198
+ ] as const
199
+
200
+ function hasAutoLayoutTriggerProps(props: Record<string, unknown>): boolean {
201
+ return AUTO_LAYOUT_TRIGGER_KEYS.some((k) => props[k] !== undefined)
202
+ }
203
+
204
+ function applyGridOverrides(
205
+ props: Record<string, unknown>,
206
+ o: Partial<SceneNode>,
207
+ w: unknown,
208
+ h: unknown
209
+ ): void {
210
+ o.layoutMode = 'GRID'
211
+
212
+ if (typeof w === 'number') o.width = w
213
+ if (typeof h === 'number') o.height = h
214
+
215
+ if (typeof props.columns === 'string') {
216
+ o.gridTemplateColumns = parseCSSGridTracks(props.columns)
217
+ } else if (typeof props.columns === 'number') {
218
+ o.gridTemplateColumns = Array.from({ length: props.columns }, () => ({
219
+ sizing: 'FR' as const,
220
+ value: 1
221
+ }))
222
+ }
223
+
224
+ if (typeof props.rows === 'string') {
225
+ o.gridTemplateRows = parseCSSGridTracks(props.rows)
226
+ } else if (typeof props.rows === 'number') {
227
+ o.gridTemplateRows = Array.from({ length: props.rows }, () => ({
228
+ sizing: 'FR' as const,
229
+ value: 1
230
+ }))
231
+ }
232
+
233
+ if (typeof props.columnGap === 'number') o.gridColumnGap = props.columnGap
234
+ if (typeof props.rowGap === 'number') o.gridRowGap = props.rowGap
235
+ if (typeof props.gap === 'number') {
236
+ o.gridColumnGap = props.gap
237
+ o.gridRowGap = props.gap
238
+ }
239
+
240
+ if (props.rows === undefined && typeof h !== 'number') {
241
+ o.height = 0
242
+ }
243
+ }
244
+
245
+ function applyGridChildOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
246
+ const col = designJSXProp(props, 'colStart')
247
+ const row = designJSXProp(props, 'rowStart')
248
+ const colSpan = (props.colSpan as number | undefined) ?? 1
249
+ const rowSpan = (props.rowSpan as number | undefined) ?? 1
250
+
251
+ if (col !== undefined || row !== undefined) {
252
+ o.gridPosition = {
253
+ column: (col as number | undefined) ?? 0,
254
+ row: (row as number | undefined) ?? 0,
255
+ columnSpan: colSpan,
256
+ rowSpan: rowSpan
257
+ }
258
+ }
259
+ }
260
+
261
+ function applyAutoLayoutSizing(
262
+ o: Partial<SceneNode>,
263
+ props: Record<string, unknown>,
264
+ w: unknown,
265
+ h: unknown
266
+ ): void {
267
+ const flex = typeof props.flex === 'string' ? props.flex : 'col'
268
+ o.layoutMode = parseAutoLayoutDirection(flex) ?? 'HORIZONTAL'
269
+ const own = (dim: unknown) => (typeof dim === 'number' ? 'FIXED' : 'HUG')
270
+ Object.assign(o, autoLayoutSizingFields(o.layoutMode, own(w), own(h)))
271
+ }
272
+
273
+ function applyLayoutAlignmentOverrides(
274
+ props: Record<string, unknown>,
275
+ o: Partial<SceneNode>
276
+ ): void {
277
+ const justify = designJSXProp(props, 'justify')
278
+ if (typeof justify === 'string' && justify) {
279
+ o.primaryAxisAlign = parsePrimaryAxisAlign(justify) ?? 'MIN'
280
+ }
281
+ const items = designJSXProp(props, 'items')
282
+ if (typeof items === 'string' && items) {
283
+ o.counterAxisAlign = parseCounterAxisAlign(items) ?? 'MIN'
284
+ }
285
+ }
286
+
287
+ function shouldEnableAutoLayout(props: Record<string, unknown>, isText: boolean): boolean {
288
+ if (props.flex !== undefined) return true
289
+ if (!isText && hasAutoLayoutTriggerProps(props)) return true
290
+ return false
291
+ }
292
+
293
+ function applyLayoutOverrides(
294
+ props: Record<string, unknown>,
295
+ o: Partial<SceneNode>,
296
+ w: unknown,
297
+ h: unknown,
298
+ isText: boolean,
299
+ parentLayout: SceneNode['layoutMode']
300
+ ): void {
301
+ if (props.grid) {
302
+ applyGridOverrides(props, o, w, h)
303
+ applyPaddingOverrides(props, o)
304
+ if (props.grow !== undefined) o.layoutGrow = props.grow as number
305
+ return
306
+ }
307
+
308
+ if (parentLayout === 'GRID') {
309
+ applyGridChildOverrides(props, o)
310
+ }
311
+
312
+ if (shouldEnableAutoLayout(props, isText)) {
313
+ applyAutoLayoutSizing(o, props, w, h)
314
+ }
315
+
316
+ o.layoutDirection =
317
+ parseDirection(props.flow ?? (!isText ? props.dir : undefined)) ?? o.layoutDirection
318
+
319
+ if (props.gap !== undefined) o.itemSpacing = props.gap as number
320
+
321
+ if (props.wrap) {
322
+ o.layoutWrap = 'WRAP'
323
+ if (props.rowGap !== undefined) o.counterAxisSpacing = props.rowGap as number
324
+ }
325
+
326
+ applyLayoutAlignmentOverrides(props, o)
327
+
328
+ applyPaddingOverrides(props, o)
329
+
330
+ if (props.grow !== undefined) o.layoutGrow = props.grow as number
331
+ }
332
+
333
+ function applyTextStyleOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
334
+ const fontSize = designJSXProp(props, 'size')
335
+ if (typeof fontSize === 'number') o.fontSize = fontSize
336
+
337
+ const fontFamily = designJSXProp(props, 'font')
338
+ if (typeof fontFamily === 'string') o.fontFamily = fontFamily
339
+
340
+ const weight = designJSXProp(props, 'weight')
341
+ if (typeof props.italic === 'boolean') o.italic = props.italic
342
+
343
+ if (typeof weight === 'number') {
344
+ o.fontWeight = weight
345
+ } else if (typeof weight === 'string') {
346
+ o.fontWeight = WEIGHT_MAP[weight] ?? 400
347
+ }
348
+
349
+ if (typeof props.color === 'string' || isColor(props.color)) {
350
+ o.fills = [colorToFill(props.color)]
351
+ }
352
+
353
+ // A value it cannot read is left out, so the text keeps its own.
354
+ const lineHeight = props.lineHeight === AUTO ? null : textLengthProp(props.lineHeight)
355
+ if (lineHeight !== undefined) o.lineHeight = lineHeight
356
+ const letterSpacing = textLengthProp(props.letterSpacing)
357
+ if (letterSpacing) o.letterSpacing = letterSpacing
358
+ const textDecoration = TEXT_DECORATION.parse(props.textDecoration)
359
+ if (textDecoration) o.textDecoration = textDecoration
360
+ applyTextDetailOverrides(props, o)
361
+ const textCase = TEXT_CASE.parse(props.textCase)
362
+ if (textCase) o.textCase = textCase
363
+ if (props.maxLines !== undefined) {
364
+ o.maxLines = props.maxLines as number
365
+ o.textTruncation = 'ENDING'
366
+ }
367
+ if (props.truncate) {
368
+ o.textTruncation = 'ENDING'
369
+ }
370
+
371
+ applyTextAlignmentOverrides(props, o)
372
+ }
373
+
374
+ function applyTextAlignmentOverrides(props: Record<string, unknown>, o: Partial<SceneNode>): void {
375
+ const textAlign = designJSXProp(props, 'textAlign')
376
+ if (typeof textAlign === 'string') {
377
+ o.textAlignHorizontal = TEXT_ALIGN.parse(textAlign) ?? 'LEFT'
378
+ }
379
+
380
+ const textAlignVertical = designJSXProp(props, 'textAlignVertical')
381
+ if (typeof textAlignVertical === 'string') {
382
+ o.textAlignVertical = TEXT_ALIGN_VERTICAL.parse(textAlignVertical) ?? 'TOP'
383
+ }
384
+ }
385
+
386
+ function applyTextAutoResize(
387
+ props: Record<string, unknown>,
388
+ o: Partial<SceneNode>,
389
+ parentLayout: SceneNode['layoutMode']
390
+ ): void {
391
+ const w = designJSXProp(props, 'w')
392
+ const hasExplicitWidth = w !== undefined
393
+ const fillsParent = w === 'fill' || (props.grow as number) > 0
394
+ const isInsideAutoLayout = parentLayout !== 'NONE'
395
+
396
+ // DO NOT CHANGE these defaults without testing headless layout (no CanvasKit).
397
+ // WIDTH_AND_HEIGHT relies on MeasureFunc — without it, text keeps the 100×100
398
+ // default SceneNode size and blows up every HUG container. layout.ts has a
399
+ // fallback estimator, but changing this logic can silently break all JSX rendering.
400
+ if (props.textAutoResize) {
401
+ o.textAutoResize = TEXT_AUTO_RESIZE.parse(props.textAutoResize) ?? 'NONE'
402
+ } else if (hasExplicitWidth || (isInsideAutoLayout && fillsParent)) {
403
+ o.textAutoResize = 'HEIGHT'
404
+ } else {
405
+ o.textAutoResize = 'WIDTH_AND_HEIGHT'
406
+ }
407
+ }
408
+
409
+ function applyTextOverrides(
410
+ props: Record<string, unknown>,
411
+ o: Partial<SceneNode>,
412
+ parentLayout: SceneNode['layoutMode']
413
+ ): void {
414
+ applyTextStyleOverrides(props, o)
415
+ o.textDirection = parseDirection(props.dir) ?? o.textDirection
416
+ applyTextAutoResize(props, o, parentLayout)
417
+ }
418
+
419
+ const FULL_TURN_DEGREES = 360
420
+
421
+ function numberProp(value: unknown): number | undefined {
422
+ return typeof value === 'number' ? value : undefined
423
+ }
424
+
425
+ /**
426
+ * An `<Ellipse>`'s arc from its props: angles in degrees, clockwise from three o'clock, as the
427
+ * canvas draws arcs, and the hole as a share of the ellipse. Null when none is set.
428
+ */
429
+ function arcOverride(props: Record<string, unknown>): ArcData | null {
430
+ const start = numberProp(props.startAngle)
431
+ const end = numberProp(props.endAngle)
432
+ const innerRadius = numberProp(props.innerRadius)
433
+ if (start === undefined && end === undefined && innerRadius === undefined) return null
434
+ const startDegrees = start ?? 0
435
+ return {
436
+ startingAngle: (startDegrees * Math.PI) / 180,
437
+ endingAngle: ((end ?? startDegrees + FULL_TURN_DEGREES) * Math.PI) / 180,
438
+ innerRadius: innerRadius ?? 0
439
+ }
440
+ }
441
+
442
+ /** The fields a shape element's own props set, by the layer it makes. */
443
+ export function shapeOverrides(
444
+ nodeType: NodeType,
445
+ props: Record<string, unknown>
446
+ ): Partial<SceneNode> {
447
+ const o: Partial<SceneNode> = {}
448
+ if (nodeType === 'STAR' || nodeType === 'POLYGON') {
449
+ const points = numberProp(props.pointCount) ?? numberProp(props.points)
450
+ if (points !== undefined) o.pointCount = points
451
+ }
452
+ if (nodeType === 'STAR') {
453
+ const innerRadius = numberProp(props.innerRadius)
454
+ if (innerRadius !== undefined) o.starInnerRadius = innerRadius
455
+ }
456
+ if (nodeType === 'ELLIPSE') {
457
+ const arc = arcOverride(props)
458
+ if (arc) o.arcData = arc
459
+ }
460
+ return o
461
+ }
462
+
463
+ export function propsToOverrides(
464
+ props: Record<string, unknown>,
465
+ isText: boolean,
466
+ parentLayout: SceneNode['layoutMode']
467
+ ): Partial<SceneNode> {
468
+ props = normalizeStyleProps(props)
469
+ const o: Partial<SceneNode> = {}
470
+
471
+ if (props.name) o.name = props.name as string
472
+
473
+ const { w, h } = applySizeOverrides(props, o, parentLayout)
474
+ applyVisualOverrides(props, o)
475
+ applyLayoutOverrides(props, o, w, h, isText, parentLayout)
476
+ if (isText) applyTextOverrides(props, o, parentLayout)
477
+ applyEffectOverrides(props, o)
478
+ applyStateOverrides(props, o)
479
+
480
+ return o
481
+ }
@@ -0,0 +1,134 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ /**
4
+ * Fields a layer keeps when its code is rendered again: its place in the tree and the identity
5
+ * that other layers, libraries and files refer to.
6
+ */
7
+ const IDENTITY_FIELDS = new Set<keyof SceneNode>([
8
+ 'id',
9
+ 'type',
10
+ 'parentId',
11
+ 'childIds',
12
+ 'source',
13
+ 'componentKey',
14
+ 'sourceLibraryKey',
15
+ 'publishId',
16
+ 'overrideKey'
17
+ ])
18
+
19
+ /**
20
+ * Types rebuilt as a whole: instance overrides are keyed by the ids of their sublayers, and icon
21
+ * and SVG artwork is drawn again from its paths.
22
+ */
23
+ const REPLACED_TYPES = new Set<SceneNode['type']>(['INSTANCE', 'VECTOR', 'BOOLEAN_OPERATION'])
24
+
25
+ function updatesInPlace(existing: SceneNode, rendered: SceneNode): boolean {
26
+ return existing.type === rendered.type && !REPLACED_TYPES.has(existing.type)
27
+ }
28
+
29
+ /** Pairs rendered children with existing ones: same type and name first, then same type in order. */
30
+ function matchChildren(
31
+ existing: readonly SceneNode[],
32
+ rendered: readonly SceneNode[]
33
+ ): Map<SceneNode, SceneNode> {
34
+ const pairs = new Map<SceneNode, SceneNode>()
35
+ const free = new Set(existing)
36
+ const take = (node: SceneNode, test: (candidate: SceneNode) => boolean) => {
37
+ for (const candidate of free) {
38
+ if (!test(candidate)) continue
39
+ free.delete(candidate)
40
+ pairs.set(node, candidate)
41
+ return
42
+ }
43
+ }
44
+ for (const node of rendered) {
45
+ take(node, (candidate) => candidate.type === node.type && candidate.name === node.name)
46
+ }
47
+ for (const node of rendered) {
48
+ if (!pairs.has(node)) take(node, (candidate) => candidate.type === node.type)
49
+ }
50
+ return pairs
51
+ }
52
+
53
+ function authoredChanges(existing: SceneNode, rendered: SceneNode): Partial<SceneNode> {
54
+ const changes: Partial<SceneNode> = {}
55
+ for (const key of Object.keys(rendered) as (keyof SceneNode)[]) {
56
+ if (IDENTITY_FIELDS.has(key)) continue
57
+ const next = rendered[key]
58
+ if (JSON.stringify(existing[key]) === JSON.stringify(next)) continue
59
+ Object.assign(changes, { [key]: structuredClone(next) })
60
+ }
61
+ return changes
62
+ }
63
+
64
+ class Reconciler {
65
+ /** Rendered layer id → the id it has once reconciled: the existing layer's, or its own. */
66
+ readonly ids = new Map<string, string>()
67
+
68
+ constructor(private readonly graph: SceneGraph) {}
69
+
70
+ keepRendered(node: SceneNode) {
71
+ this.ids.set(node.id, node.id)
72
+ for (const child of this.graph.getChildren(node.id)) this.keepRendered(child)
73
+ }
74
+
75
+ /** Makes `existing` match `rendered` and returns the id the pair ends up with. */
76
+ pair(existing: SceneNode, rendered: SceneNode): string {
77
+ if (!updatesInPlace(existing, rendered)) {
78
+ const parentId = existing.parentId
79
+ const parent = parentId ? this.graph.getNode(parentId) : undefined
80
+ if (parent && parentId) {
81
+ this.graph.insertChildAt(rendered.id, parentId, parent.childIds.indexOf(existing.id))
82
+ }
83
+ this.graph.deleteNode(existing.id)
84
+ this.keepRendered(rendered)
85
+ return rendered.id
86
+ }
87
+ const changes = authoredChanges(existing, rendered)
88
+ if (Object.keys(changes).length > 0) this.graph.updateNode(existing.id, changes)
89
+ this.ids.set(rendered.id, existing.id)
90
+ this.children(existing.id, rendered.id)
91
+ this.graph.deleteNode(rendered.id)
92
+ return existing.id
93
+ }
94
+
95
+ private children(existingId: string, renderedId: string) {
96
+ const renderedChildren = this.graph.getChildren(renderedId)
97
+ const pairs = matchChildren(this.graph.getChildren(existingId), renderedChildren)
98
+ const order = renderedChildren.map((child) => {
99
+ const match = pairs.get(child)
100
+ return match ? this.pair(match, child) : child.id
101
+ })
102
+ for (const child of renderedChildren) if (!pairs.has(child)) this.keepRendered(child)
103
+ const kept = new Set(order)
104
+ for (const child of this.graph.getChildren(existingId)) {
105
+ if (!kept.has(child.id)) this.graph.deleteNode(child.id)
106
+ }
107
+ for (const [index, id] of order.entries()) this.graph.insertChildAt(id, existingId, index)
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Folds freshly rendered layers into the layers they replace, so code edits update layers in
113
+ * place: matched layers keep their ids, and only the properties that differ change. Roots pair
114
+ * by position; extra rendered roots stay, extra existing roots are deleted. Returns the id each
115
+ * rendered layer ends up with.
116
+ */
117
+ export function reconcileRenderedLayers(
118
+ graph: SceneGraph,
119
+ existingRootIds: readonly string[],
120
+ renderedRootIds: readonly string[]
121
+ ): { rootIds: string[]; ids: Map<string, string> } {
122
+ const reconciler = new Reconciler(graph)
123
+ const rootIds = renderedRootIds.flatMap((renderedId, index) => {
124
+ const rendered = graph.getNode(renderedId)
125
+ if (!rendered) return []
126
+ const existingId = existingRootIds.at(index)
127
+ const existing = existingId ? graph.getNode(existingId) : undefined
128
+ if (existing) return [reconciler.pair(existing, rendered)]
129
+ reconciler.keepRendered(rendered)
130
+ return [rendered.id]
131
+ })
132
+ for (const id of existingRootIds.slice(renderedRootIds.length)) graph.deleteNode(id)
133
+ return { rootIds, ids: reconciler.ids }
134
+ }