@pairdraw/pen 0.0.0-stage → 0.16.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.
package/src/paints.ts ADDED
@@ -0,0 +1,417 @@
1
+ import * as v from 'valibot'
2
+
3
+ import type {
4
+ BlendMode,
5
+ Fill,
6
+ FillType,
7
+ GradientStop,
8
+ MeshGradientPoint,
9
+ SceneNode,
10
+ Stroke,
11
+ StrokeCap,
12
+ StrokeJoin
13
+ } from '@pairdraw/scene-graph'
14
+ import { TRANSPARENT } from '@pairdraw/scene-graph/constants'
15
+ import {
16
+ ellipticalGradientTransform,
17
+ isMeshFill,
18
+ linearGradientTransformFromAxes,
19
+ meshPointCount
20
+ } from '@pairdraw/scene-graph/gradient'
21
+ import type { Vector } from '@pairdraw/scene-graph/primitives'
22
+ import {
23
+ createShaderSourcePaint,
24
+ withShaderPaints,
25
+ type ShaderPaint
26
+ } from '@pairdraw/scene-graph/shaders'
27
+
28
+ import { imagePaint, type PenImages } from './images'
29
+ import { meshPaintSchema } from './schema'
30
+ import type {
31
+ PenGradientPaint,
32
+ PenImagePaint,
33
+ PenMeshPaint,
34
+ PenLegacyStroke,
35
+ PenNode,
36
+ PenOverride,
37
+ PenPaint,
38
+ PenPaints,
39
+ PenShaderPaint,
40
+ PenSides
41
+ } from './schema'
42
+ import {
43
+ bindIfVar,
44
+ resolveBoolean,
45
+ resolveColor,
46
+ resolveNumber,
47
+ type VarContext
48
+ } from './variables'
49
+
50
+ type PaintField = 'fills' | 'strokes'
51
+
52
+ /** Shader files a document's paints and effects name, by URL, as their source text. */
53
+ export type PenShaderSources = ReadonlyMap<string, string>
54
+
55
+ /** Where a shader file's source comes from, and the shader entries converted so far. */
56
+ interface PenShaderRead {
57
+ sources: PenShaderSources | undefined
58
+ /** Each shader paint converted, for the node's plugin data. */
59
+ out: ShaderPaint[]
60
+ }
61
+
62
+ /**
63
+ * pen.dev blend modes by name. Linear burn and linear dodge have no counterpart in the scene
64
+ * graph, so they draw as normal.
65
+ */
66
+ const BLEND_MODES: Partial<Record<string, BlendMode>> = {
67
+ normal: 'NORMAL',
68
+ darken: 'DARKEN',
69
+ multiply: 'MULTIPLY',
70
+ colorBurn: 'COLOR_BURN',
71
+ light: 'LIGHTEN',
72
+ screen: 'SCREEN',
73
+ colorDodge: 'COLOR_DODGE',
74
+ overlay: 'OVERLAY',
75
+ softLight: 'SOFT_LIGHT',
76
+ hardLight: 'HARD_LIGHT',
77
+ difference: 'DIFFERENCE',
78
+ exclusion: 'EXCLUSION',
79
+ hue: 'HUE',
80
+ saturation: 'SATURATION',
81
+ color: 'COLOR',
82
+ luminosity: 'LUMINOSITY'
83
+ }
84
+
85
+ export function mapBlendMode(value: string | undefined): BlendMode | undefined {
86
+ return value === undefined ? undefined : BLEND_MODES[value]
87
+ }
88
+
89
+ const GRADIENT_TYPES: Partial<Record<string, FillType>> = {
90
+ linear: 'GRADIENT_LINEAR',
91
+ radial: 'GRADIENT_RADIAL',
92
+ angular: 'GRADIENT_ANGULAR',
93
+ diamond: 'GRADIENT_DIAMOND'
94
+ }
95
+
96
+ /**
97
+ * pen.dev places a gradient in the layer's unit square: `center` defaults to the middle, a linear
98
+ * gradient runs `size.height` long from bottom to top, and radial, diamond, and angular ones are
99
+ * ellipses of diameter `size`. `rotation` turns all of it counter-clockwise in that square. An
100
+ * angular gradient starts at the top and turns clockwise. Measured against pen.dev 2.21 renders.
101
+ * A diamond gradient uses the same ellipse as a radial one.
102
+ */
103
+ function gradientTransform(paint: PenGradientPaint, type: FillType, ctx: VarContext) {
104
+ const center = { x: paint.center?.x ?? 0.5, y: paint.center?.y ?? 0.5 }
105
+ const width = resolveNumber(paint.size?.width, ctx, 1)
106
+ const height = resolveNumber(paint.size?.height, ctx, 1)
107
+ const angle = (resolveNumber(paint.rotation, ctx) * Math.PI) / 180
108
+ // Up, and right, after turning counter-clockwise on a y-down canvas.
109
+ const up = { x: -Math.sin(angle), y: -Math.cos(angle) }
110
+ const right = { x: Math.cos(angle), y: -Math.sin(angle) }
111
+ const along = (direction: Vector, length: number): Vector => ({
112
+ x: center.x + direction.x * length,
113
+ y: center.y + direction.y * length
114
+ })
115
+ if (type === 'GRADIENT_LINEAR') {
116
+ return linearGradientTransformFromAxes(along(up, -height / 2), along(up, height / 2), {
117
+ x: right.x * height,
118
+ y: right.y * height
119
+ })
120
+ }
121
+ if (type === 'GRADIENT_ANGULAR') {
122
+ return ellipticalGradientTransform(center, along(up, height / 2), along(right, width / 2))
123
+ }
124
+ // Radial and diamond gradients share this ellipse.
125
+ return ellipticalGradientTransform(center, along(right, width / 2), {
126
+ x: center.x - up.x * (height / 2),
127
+ y: center.y - up.y * (height / 2)
128
+ })
129
+ }
130
+
131
+ function gradientStops(paint: PenGradientPaint, ctx: VarContext): GradientStop[] {
132
+ return (paint.colors ?? []).map((stop) => ({
133
+ color: resolveColor(stop.color, ctx),
134
+ position: resolveNumber(stop.position, ctx)
135
+ }))
136
+ }
137
+
138
+ function convertPaint(
139
+ paint: PenPaint,
140
+ index: number,
141
+ field: PaintField,
142
+ ctx: VarContext,
143
+ node: SceneNode | undefined,
144
+ images: PenImages | undefined,
145
+ shaders?: PenShaderRead
146
+ ): Fill | null {
147
+ if (typeof paint === 'string' || paint.type === 'color') {
148
+ const raw = typeof paint === 'string' ? paint : paint.color
149
+ if (typeof raw !== 'string') return null
150
+ const color = resolveColor(raw, ctx)
151
+ if (node) bindIfVar(node, `${field}/${index}/color`, raw, ctx)
152
+ return {
153
+ type: 'SOLID',
154
+ color,
155
+ opacity: color.a,
156
+ visible: typeof paint === 'string' || resolveBoolean(paint.enabled, ctx),
157
+ blendMode: typeof paint === 'string' ? undefined : mapBlendMode(paint.blendMode)
158
+ }
159
+ }
160
+ if (paint.type === 'gradient') {
161
+ const gradient = paint as PenGradientPaint
162
+ const type = GRADIENT_TYPES[gradient.gradientType ?? 'linear']
163
+ if (!type) return null
164
+ return {
165
+ type,
166
+ color: { ...TRANSPARENT },
167
+ opacity: resolveNumber(gradient.opacity, ctx, 1),
168
+ visible: resolveBoolean(gradient.enabled, ctx),
169
+ blendMode: mapBlendMode(gradient.blendMode),
170
+ gradientStops: gradientStops(gradient, ctx),
171
+ gradientTransform: gradientTransform(gradient, type, ctx)
172
+ }
173
+ }
174
+ if (paint.type === 'image') return convertImagePaint(paint as PenImagePaint, ctx, node, images)
175
+ if (paint.type === 'mesh_gradient') return convertMeshPaint(paint, ctx)
176
+ if (paint.type === 'shader') return convertShaderPaint(paint as PenShaderPaint, ctx, shaders)
177
+ return null
178
+ }
179
+
180
+ /** A pen.dev image paint as the `IMAGE` fill that draws the image its URL names. */
181
+ function convertImagePaint(
182
+ paint: PenImagePaint,
183
+ ctx: VarContext,
184
+ node: SceneNode | undefined,
185
+ images: PenImages | undefined
186
+ ): Fill | null {
187
+ const image = paint.url ? images?.get(paint.url) : undefined
188
+ if (!image) return null
189
+ const box = { width: node?.width ?? 0, height: node?.height ?? 0 }
190
+ return {
191
+ ...imagePaint(paint, image, box, resolveNumber(paint.opacity, ctx, 1)),
192
+ visible: resolveBoolean(paint.enabled, ctx),
193
+ blendMode: mapBlendMode(paint.blendMode)
194
+ }
195
+ }
196
+
197
+ /**
198
+ * A pen.dev shader paint as the shader paint it draws: its source comes from the file `url` names,
199
+ * which the host read as `PenReadOptions.shaders`. One whose source is missing draws nothing, as a
200
+ * shader pen.dev cannot compile shows an empty frame.
201
+ */
202
+ function convertShaderPaint(
203
+ paint: PenShaderPaint,
204
+ ctx: VarContext,
205
+ shaders: PenShaderRead | undefined
206
+ ): Fill | null {
207
+ const source = paint.url === undefined ? undefined : shaders?.sources?.get(paint.url)
208
+ if (!source || !shaders) return null
209
+ const { paint: fill, shader } = createShaderSourcePaint(source)
210
+ shaders.out.push(shader)
211
+ return {
212
+ ...fill,
213
+ opacity: resolveNumber(paint.opacity, ctx, 1),
214
+ visible: resolveBoolean(paint.enabled, ctx),
215
+ blendMode: mapBlendMode(paint.blendMode)
216
+ }
217
+ }
218
+
219
+ /**
220
+ * A pen.dev mesh paint as a `MESH` fill. `columns` and `rows` count points per side, so the grid
221
+ * between them is one smaller each way; a file that counts cells instead still matches when its
222
+ * grid is one larger. Anything else is not a mesh this reader draws, so it is skipped.
223
+ */
224
+ function convertMeshPaint(raw: unknown, ctx: VarContext): Fill | null {
225
+ const parsed = v.safeParse(meshPaintSchema, raw)
226
+ if (!parsed.success) return null
227
+ const paint: PenMeshPaint = parsed.output
228
+ const columns = Math.max(1, Math.floor(resolveNumber(paint.columns, ctx, 1)))
229
+ const rows = Math.max(1, Math.floor(resolveNumber(paint.rows, ctx, 1)))
230
+ const points = meshPoints(paint.colors ?? [], paint.points ?? [], ctx)
231
+ if (!points) return null
232
+ let meshColumns = columns
233
+ let meshRows = rows
234
+ if (points.length !== meshPointCount(meshColumns, meshRows)) {
235
+ if (columns > 1 && rows > 1 && points.length === columns * rows) {
236
+ meshColumns = columns - 1
237
+ meshRows = rows - 1
238
+ } else {
239
+ return null
240
+ }
241
+ }
242
+ const fill: Fill = {
243
+ type: 'MESH',
244
+ color: { ...TRANSPARENT },
245
+ opacity: resolveNumber(paint.opacity, ctx, 1),
246
+ visible: resolveBoolean(paint.enabled, ctx),
247
+ blendMode: mapBlendMode(paint.blendMode),
248
+ meshColumns,
249
+ meshRows,
250
+ meshPoints: points
251
+ }
252
+ return isMeshFill(fill) ? fill : null
253
+ }
254
+
255
+ /** One mesh point per vertex: a color with the point's position. */
256
+ function meshPoints(
257
+ colors: readonly unknown[],
258
+ positions: readonly unknown[],
259
+ ctx: VarContext
260
+ ): MeshGradientPoint[] | null {
261
+ if (colors.length === 0 || colors.length !== positions.length) return null
262
+ const points: MeshGradientPoint[] = []
263
+ for (let index = 0; index < colors.length; index++) {
264
+ const rawColor = colors[index]
265
+ const rawPosition = positions[index]
266
+ if (typeof rawColor !== 'string') return null
267
+ let position: unknown = rawPosition
268
+ if (typeof rawPosition === 'object' && rawPosition !== null && 'position' in rawPosition) {
269
+ position = rawPosition.position
270
+ }
271
+ if (!Array.isArray(position) || position.length < 2) return null
272
+ const [x, y] = position
273
+ if (typeof x !== 'number' || typeof y !== 'number') return null
274
+ points.push({
275
+ position: { x: resolveNumber(x, ctx), y: resolveNumber(y, ctx) },
276
+ color: resolveColor(rawColor, ctx)
277
+ })
278
+ }
279
+ return points
280
+ }
281
+
282
+ /** A node's fills, or its strokes' paints, in pen.dev's order: the last one draws on top. */
283
+ export function convertPaints(
284
+ paints: PenPaints | undefined,
285
+ field: PaintField,
286
+ ctx: VarContext,
287
+ node?: SceneNode,
288
+ images?: PenImages,
289
+ shaders?: PenShaderSources
290
+ ): Fill[] {
291
+ if (paints === undefined) return []
292
+ const list = Array.isArray(paints) ? paints : [paints]
293
+ const result: Fill[] = []
294
+ const read: PenShaderRead = { sources: shaders, out: [] }
295
+ for (const paint of list) {
296
+ const converted = convertPaint(paint, result.length, field, ctx, node, images, read)
297
+ if (converted) result.push(converted)
298
+ }
299
+ if (node && read.out.length > 0) {
300
+ const other = field === 'fills' ? node.strokes : node.fills
301
+ node.pluginData = withShaderPaints(node, [...result, ...other], read.out)
302
+ }
303
+ return result
304
+ }
305
+
306
+ const ALIGNMENTS: Partial<Record<string, Stroke['align']>> = {
307
+ inner: 'INSIDE',
308
+ inside: 'INSIDE',
309
+ center: 'CENTER',
310
+ outer: 'OUTSIDE',
311
+ outside: 'OUTSIDE'
312
+ }
313
+
314
+ const JOINS: Partial<Record<string, StrokeJoin>> = {
315
+ miter: 'MITER',
316
+ bevel: 'BEVEL',
317
+ round: 'ROUND'
318
+ }
319
+ const CAPS: Partial<Record<string, StrokeCap>> = {
320
+ butt: 'NONE',
321
+ round: 'ROUND',
322
+ square: 'SQUARE'
323
+ }
324
+
325
+ /** The stroke fields of a node, with the 2.8 object form spread into the current ones. */
326
+ export interface PenStrokeFields {
327
+ paints: PenPaints | undefined
328
+ width: PenNode['strokeWidth']
329
+ alignment: string | undefined
330
+ cap: string | undefined
331
+ join: string | undefined
332
+ }
333
+
334
+ function isLegacyStroke(stroke: PenNode['stroke']): stroke is PenLegacyStroke {
335
+ return typeof stroke === 'object' && !Array.isArray(stroke) && 'thickness' in stroke
336
+ }
337
+
338
+ /** A node's stroke fields; an instance's own fields replace its component's one by one. */
339
+ export function strokeFields(pen: PenOverride, base?: PenStrokeFields): PenStrokeFields {
340
+ if (isLegacyStroke(pen.stroke)) {
341
+ return {
342
+ paints: pen.stroke.fill,
343
+ width: pen.stroke.thickness,
344
+ alignment: pen.stroke.align,
345
+ cap: pen.stroke.cap,
346
+ join: pen.stroke.join
347
+ }
348
+ }
349
+ return {
350
+ paints: pen.stroke ?? base?.paints,
351
+ width: pen.strokeWidth ?? base?.width,
352
+ alignment: pen.strokeAlignment ?? base?.alignment,
353
+ cap: pen.strokeLinecap ?? base?.cap,
354
+ join: pen.strokeLinejoin ?? base?.join
355
+ }
356
+ }
357
+
358
+ const STROKE_SIDE_FIELDS = [
359
+ ['top', 'borderTopWeight'],
360
+ ['right', 'borderRightWeight'],
361
+ ['bottom', 'borderBottomWeight'],
362
+ ['left', 'borderLeftWeight']
363
+ ] as const
364
+
365
+ /** A per-side width, with a `$name` on a side kept as that side's binding. */
366
+ function applySideWidths(node: SceneNode, sides: PenSides, ctx: VarContext): number {
367
+ node.independentStrokeWeights = true
368
+ let weight = 0
369
+ for (const [side, field] of STROKE_SIDE_FIELDS) {
370
+ const value = resolveNumber(sides[side], ctx)
371
+ node[field] = value
372
+ bindIfVar(node, field, sides[side], ctx)
373
+ if (value > weight) weight = value
374
+ }
375
+ return weight
376
+ }
377
+
378
+ /**
379
+ * Sets a node's strokes. pen.dev draws a stroke only with both paints and a width: a missing side
380
+ * of a per-side width is zero, and the alignment defaults to centred.
381
+ */
382
+ export function applyStroke(
383
+ node: SceneNode,
384
+ fields: PenStrokeFields,
385
+ ctx: VarContext,
386
+ images?: PenImages,
387
+ shaders?: PenShaderSources
388
+ ): void {
389
+ node.strokes = []
390
+ node.independentStrokeWeights = false
391
+ if (fields.paints === undefined || fields.width === undefined) return
392
+
393
+ let weight: number
394
+ if (typeof fields.width === 'object') {
395
+ weight = applySideWidths(node, fields.width, ctx)
396
+ } else {
397
+ weight = resolveNumber(fields.width, ctx)
398
+ bindIfVar(node, 'strokeWeight', fields.width, ctx)
399
+ }
400
+ if (weight <= 0) return
401
+
402
+ const align = ALIGNMENTS[fields.alignment ?? 'center'] ?? 'CENTER'
403
+ const cap = CAPS[fields.cap ?? 'butt'] ?? 'NONE'
404
+ const join = JOINS[fields.join ?? 'miter'] ?? 'MITER'
405
+ node.strokeCap = cap
406
+ node.strokeJoin = join
407
+ node.strokes = convertPaints(fields.paints, 'strokes', ctx, node, images, shaders).map(
408
+ (paint) => ({
409
+ ...paint,
410
+ weight,
411
+ align,
412
+ cap,
413
+ join,
414
+ dashPattern: []
415
+ })
416
+ )
417
+ }
@@ -0,0 +1,86 @@
1
+ import type { SceneNode } from '@pairdraw/scene-graph'
2
+ import type { Color } from '@pairdraw/scene-graph/primitives'
3
+
4
+ import { unresolvedRef } from './plugin-data'
5
+ import type { PenNode } from './schema'
6
+
7
+ /**
8
+ * Layers pen.dev draws that this reader cannot: a `script` node's generated layers, a `browser`
9
+ * node's live page, and a `ref` to a component that could not be found, such as one from a library
10
+ * the host could not read. Each reads as a frame in its box, filled and outlined with a dashed line
11
+ * where pen.dev gives it neither, and labelled with what it stands for when it has no layers.
12
+ */
13
+ const EMBED_TYPES: ReadonlySet<string> = new Set(['script', 'browser'])
14
+
15
+ const PLACEHOLDER_FILL: Color = { r: 0.96, g: 0.96, b: 0.96, a: 1 }
16
+ const PLACEHOLDER_OUTLINE: Color = { r: 0.62, g: 0.62, b: 0.62, a: 1 }
17
+ const PLACEHOLDER_DASH = [4, 4]
18
+ /** Room around the label, inside the outline. */
19
+ const PLACEHOLDER_INSET = 8
20
+ const LABEL_SIZE = 12
21
+ const LABEL_COLOR = '#737373'
22
+
23
+ /** Whether a layer reads as a placeholder. */
24
+ export function isPlaceholder(pen: PenNode): boolean {
25
+ return EMBED_TYPES.has(pen.type) || unresolvedRef(pen) !== undefined
26
+ }
27
+
28
+ /**
29
+ * Fills and outlines a placeholder where pen.dev gives it no paint of its own, insets an auto
30
+ * layout's content, and clips a script or browser frame to its box, as pen.dev shows them.
31
+ */
32
+ export function applyPlaceholderLook(node: SceneNode, pen: PenNode): void {
33
+ if (pen.fill === undefined) {
34
+ node.fills = [{ type: 'SOLID', color: { ...PLACEHOLDER_FILL }, opacity: 1, visible: true }]
35
+ }
36
+ if (node.strokes.length === 0) {
37
+ node.strokes = [
38
+ {
39
+ type: 'SOLID',
40
+ color: { ...PLACEHOLDER_OUTLINE },
41
+ opacity: 1,
42
+ visible: true,
43
+ weight: 1,
44
+ align: 'INSIDE',
45
+ dashPattern: [...PLACEHOLDER_DASH]
46
+ }
47
+ ]
48
+ }
49
+ if (pen.padding === undefined && node.layoutMode !== 'NONE') {
50
+ node.paddingTop = PLACEHOLDER_INSET
51
+ node.paddingRight = PLACEHOLDER_INSET
52
+ node.paddingBottom = PLACEHOLDER_INSET
53
+ node.paddingLeft = PLACEHOLDER_INSET
54
+ }
55
+ if (EMBED_TYPES.has(pen.type) && pen.clip === undefined) node.clipsContent = true
56
+ }
57
+
58
+ /** What a placeholder stands for: its file, its page, or the component it names. */
59
+ function labelText(pen: PenNode): string {
60
+ const missing = unresolvedRef(pen)
61
+ if (missing !== undefined) return missing || (pen.name ?? 'ref')
62
+ if (pen.type === 'script' && pen.scriptUri) return pen.scriptUri
63
+ if (pen.type === 'browser' && pen.url) return pen.url
64
+ return pen.name ?? pen.type
65
+ }
66
+
67
+ /**
68
+ * The label a placeholder without layers of its own shows, as a text layer; none for one with
69
+ * layers, such as a script node pen.dev saved with what it generated. The label says it was
70
+ * generated, so a writer can leave it out.
71
+ */
72
+ export function placeholderLabel(pen: PenNode, nodeId: string): PenNode | undefined {
73
+ if (!isPlaceholder(pen) || (pen.children?.length ?? 0) > 0) return undefined
74
+ const text = labelText(pen)
75
+ return {
76
+ id: `${nodeId}#label`,
77
+ type: 'text',
78
+ name: text,
79
+ content: text,
80
+ fontSize: LABEL_SIZE,
81
+ fill: LABEL_COLOR,
82
+ x: PLACEHOLDER_INSET,
83
+ y: PLACEHOLDER_INSET,
84
+ generated: 'placeholder'
85
+ }
86
+ }
@@ -0,0 +1,84 @@
1
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
2
+ import { localTransformFromWorld } from '@pairdraw/scene-graph/coordinate'
3
+ import { fitEnclosingGroups } from '@pairdraw/scene-graph/group-bounds'
4
+ import Matrix from '@pairdraw/scene-graph/matrix'
5
+ import type { Vector } from '@pairdraw/scene-graph/primitives'
6
+
7
+ /**
8
+ * Where pen.dev puts a layer: at `x`, `y` in its parent, turned `rotation` degrees
9
+ * counter-clockwise and then mirrored, both about that corner. The scene graph turns clockwise and
10
+ * mirrors about a layer's centre, so a layer's position depends on its final size and is set after
11
+ * layout. Measured against pen.dev 2.21 renders of turned, mirrored, and grouped layers.
12
+ */
13
+ export interface PenPlacement {
14
+ x: number
15
+ y: number
16
+ rotation: number
17
+ flipX: boolean
18
+ flipY: boolean
19
+ }
20
+
21
+ export function isPlain(placement: PenPlacement): boolean {
22
+ return placement.rotation === 0 && !placement.flipX && !placement.flipY
23
+ }
24
+
25
+ function inFlow(graph: SceneGraph, node: SceneNode): boolean {
26
+ const parent = node.parentId ? graph.getNode(node.parentId) : undefined
27
+ return !!parent && parent.layoutMode !== 'NONE' && node.layoutPositioning !== 'ABSOLUTE'
28
+ }
29
+
30
+ /** Sets a layer's position and turn so it lands where pen.dev draws it; `offset` is where its box starts in pen.dev's. */
31
+ function place(
32
+ graph: SceneGraph,
33
+ node: SceneNode,
34
+ placement: PenPlacement,
35
+ offset: Vector = { x: 0, y: 0 }
36
+ ) {
37
+ const world = Matrix.multiply(
38
+ Matrix.translated(placement.x, placement.y),
39
+ Matrix.rotated((-placement.rotation * Math.PI) / 180),
40
+ Matrix.scaled(placement.flipX ? -1 : 1, placement.flipY ? -1 : 1),
41
+ Matrix.translated(offset.x, offset.y)
42
+ )
43
+ const local = localTransformFromWorld(
44
+ { ...node, flipX: placement.flipX },
45
+ world,
46
+ Matrix.identity()
47
+ )
48
+ if (!local) return
49
+ // Auto layout places the layers in its flow; only their turn and mirroring carry over.
50
+ if (inFlow(graph, node)) graph.updateNode(node.id, { ...local, x: node.x, y: node.y })
51
+ else graph.updateNode(node.id, local)
52
+ }
53
+
54
+ /**
55
+ * Places every turned or mirrored layer, which the reader builds upright. Then each group, inner
56
+ * ones first, is fitted to its placed layers and placed itself; its box starts at its layers'
57
+ * bounds, wherever pen.dev's starts. `groupIds` is in reading order.
58
+ */
59
+ export function placeLayers(
60
+ graph: SceneGraph,
61
+ placements: ReadonlyMap<string, PenPlacement>,
62
+ groupIds: readonly string[]
63
+ ): void {
64
+ const groups = new Set(groupIds)
65
+ for (const [id, placement] of placements) {
66
+ const node = graph.getNode(id)
67
+ if (node && !groups.has(id) && !isPlain(placement)) place(graph, node, placement)
68
+ }
69
+
70
+ const origins = new Map<string, Vector>()
71
+ for (const id of groupIds) {
72
+ const group = graph.getNode(id)
73
+ if (group) origins.set(id, { x: group.x, y: group.y })
74
+ }
75
+ // Reading order lists a group before the groups inside it, so reversed it is innermost first.
76
+ for (const id of groupIds.toReversed()) {
77
+ fitEnclosingGroups(graph, [id])
78
+ const node = graph.getNode(id)
79
+ const origin = origins.get(id)
80
+ const placement = placements.get(id)
81
+ if (!node || !origin || !placement || isPlain(placement)) continue
82
+ place(graph, node, placement, { x: node.x - origin.x, y: node.y - origin.y })
83
+ }
84
+ }
@@ -0,0 +1,86 @@
1
+ import type { PluginDataEntry, SceneNode } from '@pairdraw/scene-graph'
2
+
3
+ import type { PenNode, PenOverride } from './schema'
4
+
5
+ /**
6
+ * The shared plugin data namespace that keeps the pen.dev fields a layer has no field for, so
7
+ * agents can read them with `getSharedPluginData('pen', key)` and a `.pen` writer can write them
8
+ * back. Each value is its field's JSON.
9
+ */
10
+ export const PEN_PLUGIN_DATA_NAMESPACE = 'pen'
11
+
12
+ /**
13
+ * The pen.dev fields kept as plugin data: notes for agents (`context`, `metadata`), the frame an
14
+ * agent is working on (`placeholder`), the components suggested for a slot (`slot`), and what a
15
+ * `prompt` or `context` node was, with the model a prompt asks. A `script` or `browser` node, which
16
+ * reads as a placeholder frame, keeps its file and inputs or its page and view; a `ref` whose
17
+ * component could not be found keeps the ID it names; and a label a placeholder was given says so.
18
+ */
19
+ const PEN_PLUGIN_DATA_KEYS = [
20
+ 'type',
21
+ 'ref',
22
+ 'context',
23
+ 'metadata',
24
+ 'placeholder',
25
+ 'slot',
26
+ 'model',
27
+ 'scriptUri',
28
+ 'inputs',
29
+ 'url',
30
+ 'deviceId',
31
+ 'zoom',
32
+ 'scrollX',
33
+ 'scrollY',
34
+ 'generated'
35
+ ] as const
36
+
37
+ type PenPluginDataKey = (typeof PEN_PLUGIN_DATA_KEYS)[number]
38
+
39
+ /** Node types kept as plugin data on the layer they become. */
40
+ const KEPT_TYPES: ReadonlySet<string> = new Set(['prompt', 'context', 'script', 'browser'])
41
+
42
+ /**
43
+ * The field a `ref` whose component is missing reads with, holding the ID it names: the layer is a
44
+ * placeholder frame, and keeps being a `ref` as plugin data.
45
+ */
46
+ export const UNRESOLVED_REF = 'unresolvedRef'
47
+
48
+ /** The ID a placeholder for a missing component names, or undefined for any other layer. */
49
+ export function unresolvedRef(pen: PenOverride): string | undefined {
50
+ const ref = pen[UNRESOLVED_REF]
51
+ return typeof ref === 'string' ? ref : undefined
52
+ }
53
+
54
+ /** As `setSharedPluginData` stores an entry, so the Figma API reads and replaces it. */
55
+ function entry(key: PenPluginDataKey, value: unknown): PluginDataEntry {
56
+ return {
57
+ pluginId: PEN_PLUGIN_DATA_NAMESPACE,
58
+ key: `${PEN_PLUGIN_DATA_NAMESPACE}/${key}`,
59
+ value: JSON.stringify(value)
60
+ }
61
+ }
62
+
63
+ function penEntries(pen: PenNode): PluginDataEntry[] {
64
+ const missing = unresolvedRef(pen)
65
+ return PEN_PLUGIN_DATA_KEYS.flatMap((key) => {
66
+ if (key === 'type') {
67
+ if (missing !== undefined) return [entry(key, 'ref')]
68
+ return KEPT_TYPES.has(pen.type) ? [entry(key, pen.type)] : []
69
+ }
70
+ // A resolved `ref` is an instance, which says what it shows itself.
71
+ if (key === 'ref') return missing === undefined ? [] : [entry(key, missing)]
72
+ const value = pen[key]
73
+ return value === undefined ? [] : [entry(key, value)]
74
+ })
75
+ }
76
+
77
+ /**
78
+ * Replaces the layer's pen.dev plugin data with the fields `pen` carries, keeping every other
79
+ * entry, so applying a layer's fields again with an override's merged in leaves one of each.
80
+ */
81
+ export function applyPenPluginData(node: SceneNode, pen: PenNode): void {
82
+ const others = node.pluginData.filter((item) => item.pluginId !== PEN_PLUGIN_DATA_NAMESPACE)
83
+ const own = penEntries(pen)
84
+ if (own.length === 0 && others.length === node.pluginData.length) return
85
+ node.pluginData = [...others, ...own]
86
+ }