@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.
@@ -0,0 +1,128 @@
1
+ import type { SceneNode } from '@pairdraw/scene-graph'
2
+ import {
3
+ createSticky,
4
+ DEFAULT_STICKY_COLOR,
5
+ STICKY_COLORS,
6
+ STICKY_SIZE,
7
+ STICKY_WIDE_WIDTH,
8
+ stickyScale,
9
+ stickySublayers,
10
+ stickyWidth
11
+ } from '@pairdraw/scene-graph/generated'
12
+ import { recordInstanceOverride } from '@pairdraw/scene-graph/instances'
13
+ import { fillSizingFields } from '@pairdraw/scene-graph/layout'
14
+ import type { Color } from '@pairdraw/scene-graph/primitives'
15
+
16
+ import { parseSize } from './layout'
17
+ import type { Build } from './nodes'
18
+ import { applyPenPluginData } from './plugin-data'
19
+ import type { PenNode } from './schema'
20
+ import { bindIfVar, resolveBoolean, resolveNumber } from './variables'
21
+
22
+ /**
23
+ * pen.dev's text annotations: a `note`, a `prompt` for an agent, and a `context` note about the
24
+ * layers around it. Each becomes a sticky note holding its text, in the colour nearest the one
25
+ * pen.dev draws its card in; a prompt and a context note keep what they were as plugin data.
26
+ */
27
+ const ANNOTATION_COLORS: Readonly<Record<string, Color>> = {
28
+ note: STICKY_COLORS.yellow,
29
+ prompt: STICKY_COLORS.blue,
30
+ context: STICKY_COLORS.gray
31
+ }
32
+
33
+ export function isAnnotation(pen: Pick<PenNode, 'type'>): boolean {
34
+ return Object.hasOwn(ANNOTATION_COLORS, pen.type)
35
+ }
36
+
37
+ /** pen.dev cards smaller or larger than this stay readable as sticky notes at its bounds. */
38
+ const MIN_SCALE = 0.25
39
+ const MAX_SCALE = 4
40
+
41
+ /**
42
+ * The note's shape and scale: wide when the card is nearer FigJam's wide width than its square
43
+ * one, and its text scaled to the card's width. The card's box itself comes from `applyAnnotation`.
44
+ */
45
+ function stickyShape(pen: PenNode, build: Build): { wide: boolean; scale: number } {
46
+ const { value, sizing } = parseSize(pen.width, STICKY_SIZE, build.ctx)
47
+ const width = sizing === 'FIXED' && value > 0 ? value : STICKY_SIZE
48
+ const wide = width > (STICKY_SIZE + STICKY_WIDE_WIDTH) / 2
49
+ const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, width / stickyWidth(1, wide)))
50
+ return { wide, scale }
51
+ }
52
+
53
+ /**
54
+ * The sticky's size fields, so it takes the room in a layout pen.dev's card does: a fixed width
55
+ * and height keep the card's box, filling follows its parent's flow, and a card with no height or
56
+ * one that fits its content grows to its text as a sticky does.
57
+ */
58
+ function annotationSizeFields(
59
+ node: SceneNode,
60
+ pen: PenNode,
61
+ build: Build,
62
+ flowLayout: SceneNode['layoutMode']
63
+ ): Partial<SceneNode> {
64
+ const width = parseSize(pen.width, node.width, build.ctx)
65
+ const height = parseSize(pen.height, node.height, build.ctx)
66
+ const fixedHeight = pen.height !== undefined && height.sizing !== 'HUG'
67
+ const fields: Partial<SceneNode> = {
68
+ width: width.sizing === 'HUG' ? node.width : width.value,
69
+ height: fixedHeight ? height.value : node.height,
70
+ primaryAxisSizing: fixedHeight ? 'FIXED' : 'HUG',
71
+ minHeight: fixedHeight
72
+ ? null
73
+ : (height.fitContentFallback ??
74
+ STICKY_SIZE * stickyScale(stickySublayers(build.graph, node)?.author)),
75
+ layoutGrow: 0,
76
+ layoutAlignSelf: 'AUTO'
77
+ }
78
+ if (flowLayout === 'NONE') return fields
79
+ if (width.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'HORIZONTAL'))
80
+ if (height.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'VERTICAL'))
81
+ return fields
82
+ }
83
+
84
+ /** A sticky note for an annotation, with its sublayers; its fields come from `applyAnnotation`. */
85
+ export function createAnnotation(pen: PenNode, parentId: string, build: Build): SceneNode {
86
+ return createSticky(
87
+ build.graph,
88
+ parentId,
89
+ {
90
+ authorVisible: false,
91
+ color: ANNOTATION_COLORS[pen.type] ?? DEFAULT_STICKY_COLOR,
92
+ ...stickyShape(pen, build)
93
+ },
94
+ { id: pen.id }
95
+ )
96
+ }
97
+
98
+ /**
99
+ * Sets the fields a sticky note takes from an annotation: where it is, its box, whether it shows,
100
+ * and its text. A sticky note keeps its own style and upright placement, as FigJam draws one.
101
+ */
102
+ export function applyAnnotation(node: SceneNode, pen: PenNode, build: Build): void {
103
+ const { graph, ctx } = build
104
+ const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'
105
+ const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'
106
+ Object.assign(node, {
107
+ name: pen.name ?? pen.type,
108
+ x: pen.x ?? 0,
109
+ y: pen.y ?? 0,
110
+ visible: resolveBoolean(pen.enabled, ctx),
111
+ opacity: resolveNumber(pen.opacity, ctx, 1),
112
+ layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',
113
+ ...annotationSizeFields(node, pen, build, absolute ? 'NONE' : parentLayout)
114
+ } satisfies Partial<SceneNode>)
115
+ bindIfVar(node, 'width', pen.width, ctx)
116
+ bindIfVar(node, 'height', pen.height, ctx)
117
+ build.placements.delete(node.id)
118
+
119
+ const body = stickySublayers(graph, node)?.body
120
+ const text = pen.content ?? ''
121
+ if (body && body.text !== text) {
122
+ body.text = text
123
+ // A note inside an instance keeps the text an override gave it through the next sync.
124
+ recordInstanceOverride(graph, body.id, ['text'])
125
+ }
126
+ applyPenPluginData(node, pen)
127
+ build.effective.set(node.id, pen)
128
+ }
package/src/assets.ts ADDED
@@ -0,0 +1,224 @@
1
+ import type { PenDocument, PenNode, PenOverride, PenPaint, PenPaints } from './schema'
2
+ import { possibleValues } from './variables'
3
+
4
+ /**
5
+ * The icon set each of pen.dev's libraries is drawn from: Iconify's for Lucide, Feather, and
6
+ * Phosphor, which pen.dev draws at one weight, and Google's variable fonts for Material Symbols.
7
+ */
8
+ const ICON_SETS: Partial<Record<string, string>> = {
9
+ lucide: 'lucide',
10
+ feather: 'feather',
11
+ phosphor: 'ph',
12
+ 'Material Symbols Outlined': 'material-symbols-outlined',
13
+ 'Material Symbols Rounded': 'material-symbols-rounded',
14
+ 'Material Symbols Sharp': 'material-symbols-sharp'
15
+ }
16
+
17
+ /** The libraries pen.dev draws at an icon's `weight`: Material Symbols' variable fonts. */
18
+ const WEIGHTED_LIBRARIES = new Set([
19
+ 'Material Symbols Outlined',
20
+ 'Material Symbols Rounded',
21
+ 'Material Symbols Sharp'
22
+ ])
23
+
24
+ /** The weight pen.dev draws Material Symbols at when an icon sets none. */
25
+ const MATERIAL_SYMBOLS_WEIGHT = 200
26
+
27
+ /** An icon's name in its set. */
28
+ export function iconName(library: string, icon: string): string | null {
29
+ const set = ICON_SETS[library]
30
+ return set ? `${set}:${icon}` : null
31
+ }
32
+
33
+ /** How an icon from `library` is drawn at `weight`: its font's weight axis, for Material Symbols. */
34
+ export function iconOptions(
35
+ library: string,
36
+ weight: number | undefined
37
+ ): Record<string, number> | undefined {
38
+ return WEIGHTED_LIBRARIES.has(library) ? { wght: weight ?? MATERIAL_SYMBOLS_WEIGHT } : undefined
39
+ }
40
+
41
+ /** An icon a document draws: its name in its set and how it is drawn there. */
42
+ export interface PenIconRequest {
43
+ name: string
44
+ options?: Record<string, number>
45
+ }
46
+
47
+ /**
48
+ * Whether an image URL names a file in the document's folder: no scheme, no absolute path, and no
49
+ * `..` step out of it.
50
+ */
51
+ export function isDocumentAssetPath(url: string): boolean {
52
+ if (/^[a-z][a-z0-9+.-]*:/i.test(url) || url.startsWith('/') || url.startsWith('\\')) return false
53
+ return !url.split(/[/\\]/).includes('..')
54
+ }
55
+
56
+ /** Whether an image URL carries the image itself, for the host to decode as a URL. */
57
+ export function isDataURL(url: string): boolean {
58
+ return /^data:/i.test(url)
59
+ }
60
+
61
+ /** How an imported document's image files are named in the document importing it. */
62
+ export const IMPORTED_IMAGE_PREFIX = 'pen-import:'
63
+
64
+ /**
65
+ * An image URL `importedImageURL` gave an imported document's file, split into the alias of the
66
+ * import it came from and its URL there; null for any other URL.
67
+ */
68
+ export function parseImportedImageURL(url: string): { alias: string; url: string } | null {
69
+ if (!url.startsWith(IMPORTED_IMAGE_PREFIX)) return null
70
+ const rest = url.slice(IMPORTED_IMAGE_PREFIX.length)
71
+ const slash = rest.indexOf('/')
72
+ if (slash <= 0) return null
73
+ return { alias: rest.slice(0, slash), url: rest.slice(slash + 1) }
74
+ }
75
+
76
+ /** What a document draws from outside itself. */
77
+ export interface PenAssets {
78
+ /** Every icon, each way it is drawn. */
79
+ icons: PenIconRequest[]
80
+ /**
81
+ * Images to load: files relative to the document, data URLs, and files of the documents it
82
+ * imports, by the names `importedImageURL` gives them.
83
+ */
84
+ images: string[]
85
+ /**
86
+ * Shader files to read as text: files beside the document that a `shader` paint or effect names.
87
+ * `PenReadOptions.shaders` gives them back by these URLs.
88
+ */
89
+ shaders: string[]
90
+ }
91
+
92
+ function paintList(paints: PenPaints | undefined): PenPaint[] {
93
+ if (paints === undefined) return []
94
+ return Array.isArray(paints) ? paints : [paints]
95
+ }
96
+
97
+ /** Adds a shader file a paint or effect names, if it is one beside the document. */
98
+ function addShaderFile(url: string, shaders: Set<string>) {
99
+ if (isDocumentAssetPath(url)) shaders.add(url)
100
+ }
101
+
102
+ function paintShaders(paints: PenPaints | undefined, shaders: Set<string>) {
103
+ for (const paint of paintList(paints)) {
104
+ if (typeof paint === 'object' && paint.type === 'shader' && typeof paint.url === 'string') {
105
+ addShaderFile(paint.url, shaders)
106
+ }
107
+ }
108
+ }
109
+
110
+ function effectShaders(effect: PenOverride['effect'], shaders: Set<string>) {
111
+ const effects = effect === undefined ? [] : [effect].flat()
112
+ for (const item of effects) {
113
+ if (item.type === 'shader' && typeof item.url === 'string') addShaderFile(item.url, shaders)
114
+ }
115
+ }
116
+
117
+ function paintImages(paints: PenPaints | undefined, images: Set<string>) {
118
+ for (const paint of paintList(paints)) {
119
+ if (typeof paint === 'object' && paint.type === 'image' && typeof paint.url === 'string') {
120
+ const { url } = paint
121
+ if (isDocumentAssetPath(url) || isDataURL(url) || parseImportedImageURL(url)) images.add(url)
122
+ }
123
+ }
124
+ }
125
+
126
+ interface Found {
127
+ doc: PenDocument
128
+ /** Requests by their name and options, so each is listed once. */
129
+ icons: Map<string, PenIconRequest>
130
+ images: Set<string>
131
+ shaders: Set<string>
132
+ libraries: Set<string>
133
+ /** Icons an override names without its library, which comes from the layer it overrides. */
134
+ bareIcons: Set<string>
135
+ /** The weights icons are drawn at, for icons whose library an override leaves out. */
136
+ weights: Set<number | undefined>
137
+ }
138
+
139
+ /**
140
+ * Every weight a field can take, through the variables it names. A value that is no number, or a
141
+ * variable without one, leaves the weight unset, as drawing reads it.
142
+ */
143
+ function possibleWeights(weight: PenOverride['weight'], doc: PenDocument): (number | undefined)[] {
144
+ if (weight === undefined) return [undefined]
145
+ if (typeof weight === 'number') return [weight]
146
+ const values = possibleValues(weight, doc).map((value) => {
147
+ const parsed = Number(value)
148
+ return Number.isFinite(parsed) ? parsed : undefined
149
+ })
150
+ return values.length > 0 ? values : [undefined]
151
+ }
152
+
153
+ function addIcons(
154
+ libraries: readonly string[],
155
+ icons: readonly string[],
156
+ weights: readonly (number | undefined)[],
157
+ found: Found
158
+ ) {
159
+ for (const library of libraries) {
160
+ for (const icon of icons) {
161
+ // A variable without a name in some theme draws no icon there.
162
+ const name = icon ? iconName(library, icon) : null
163
+ if (!name) continue
164
+ for (const weight of weights) {
165
+ const options = iconOptions(library, weight)
166
+ found.icons.set(`${name}\0${JSON.stringify(options ?? null)}`, {
167
+ name,
168
+ options
169
+ })
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ /** Adds the icon a layer draws, if it draws one, and the libraries and weights it needs. */
176
+ function collectIcon(node: PenOverride, assets: Found) {
177
+ if (!node.icon || (node.type !== 'icon' && node.type !== undefined)) return
178
+ const icons = possibleValues(node.icon, assets.doc)
179
+ const weights = possibleWeights(node.weight, assets.doc)
180
+ for (const weight of weights) assets.weights.add(weight)
181
+ if (!node.library) {
182
+ for (const icon of icons) assets.bareIcons.add(icon)
183
+ return
184
+ }
185
+ const libraries = possibleValues(node.library, assets.doc)
186
+ for (const library of libraries) assets.libraries.add(library)
187
+ addIcons(libraries, icons, weights, assets)
188
+ }
189
+
190
+ function collect(node: PenOverride, assets: Found) {
191
+ collectIcon(node, assets)
192
+ paintImages(node.fill, assets.images)
193
+ paintShaders(node.fill, assets.shaders)
194
+ effectShaders(node.effect, assets.shaders)
195
+ if (!(typeof node.stroke === 'object' && 'thickness' in node.stroke)) {
196
+ paintImages(node.stroke, assets.images)
197
+ paintShaders(node.stroke, assets.shaders)
198
+ }
199
+ for (const child of node.children ?? []) collect(child, assets)
200
+ for (const override of Object.values(node.descendants ?? {})) collect(override, assets)
201
+ }
202
+
203
+ /**
204
+ * The icons and the image files a document draws, so a host can load them before reading it. An
205
+ * icon, library, or weight bound to a variable counts every value the variable has.
206
+ */
207
+ export function penAssets(doc: PenDocument): PenAssets {
208
+ const assets: Found = {
209
+ doc,
210
+ icons: new Map(),
211
+ images: new Set(),
212
+ shaders: new Set(),
213
+ libraries: new Set(),
214
+ bareIcons: new Set(),
215
+ weights: new Set()
216
+ }
217
+ for (const node of doc.children) collect(node satisfies PenNode, assets)
218
+ addIcons([...assets.libraries], [...assets.bareIcons], [...assets.weights], assets)
219
+ return {
220
+ icons: [...assets.icons.values()],
221
+ images: [...assets.images],
222
+ shaders: [...assets.shaders]
223
+ }
224
+ }
package/src/effects.ts ADDED
@@ -0,0 +1,62 @@
1
+ import type { Effect } from '@pairdraw/scene-graph'
2
+
3
+ import { mapBlendMode, type PenShaderSources } from './paints'
4
+ import type { PenEffect, PenNode } from './schema'
5
+ import { resolveBoolean, resolveColor, resolveNumber, type VarContext } from './variables'
6
+
7
+ const DEFAULT_SHADOW_COLOR = { r: 0, g: 0, b: 0, a: 0.25 }
8
+
9
+ function convertEffect(
10
+ effect: PenEffect,
11
+ ctx: VarContext,
12
+ shaders: PenShaderSources | undefined
13
+ ): Effect | null {
14
+ if (effect.type === 'shader') {
15
+ const source = effect.url ? shaders?.get(effect.url) : undefined
16
+ if (!source) return null
17
+ return {
18
+ type: 'SHADER',
19
+ source,
20
+ uniforms: {},
21
+ visible: resolveBoolean(effect.enabled, ctx),
22
+ blendMode: mapBlendMode(effect.blendMode) ?? 'NORMAL'
23
+ }
24
+ }
25
+ const base = {
26
+ visible: resolveBoolean(effect.enabled, ctx),
27
+ color: { ...DEFAULT_SHADOW_COLOR },
28
+ offset: { x: 0, y: 0 },
29
+ spread: 0,
30
+ blendMode: mapBlendMode(effect.blendMode) ?? 'NORMAL'
31
+ } satisfies Partial<Effect>
32
+ if (effect.type === 'blur' || effect.type === 'background_blur') {
33
+ return {
34
+ ...base,
35
+ type: effect.type === 'blur' ? 'LAYER_BLUR' : 'BACKGROUND_BLUR',
36
+ radius: resolveNumber(effect.radius, ctx)
37
+ }
38
+ }
39
+ if (effect.type !== 'shadow') return null
40
+ return {
41
+ ...base,
42
+ type: effect.shadowType === 'inner' ? 'INNER_SHADOW' : 'DROP_SHADOW',
43
+ color: effect.color ? resolveColor(effect.color, ctx) : base.color,
44
+ offset: {
45
+ x: resolveNumber(effect.offset?.x, ctx),
46
+ y: resolveNumber(effect.offset?.y, ctx)
47
+ },
48
+ radius: resolveNumber(effect.blur, ctx),
49
+ spread: resolveNumber(effect.spread, ctx)
50
+ }
51
+ }
52
+
53
+ /** A node's effects, including the shader effects their files give source. */
54
+ export function convertEffects(
55
+ effect: PenNode['effect'],
56
+ ctx: VarContext,
57
+ shaders?: PenShaderSources
58
+ ): Effect[] {
59
+ if (!effect) return []
60
+ const effects = Array.isArray(effect) ? effect : [effect]
61
+ return effects.flatMap((item) => convertEffect(item, ctx, shaders) ?? [])
62
+ }
@@ -0,0 +1,71 @@
1
+ import type { ArcData, VectorNetwork } from '@pairdraw/scene-graph'
2
+ import { parseSVGPath } from '@pairdraw/scene-graph/parse-path'
3
+
4
+ import type { PenNode } from './schema'
5
+ import { resolveNumber, type VarContext } from './variables'
6
+
7
+ const DEGREES = Math.PI / 180
8
+
9
+ /**
10
+ * An ellipse's arc. pen.dev measures `startAngle` counter-clockwise from the right and sweeps
11
+ * counter-clockwise for a positive `sweepAngle`; the scene graph measures clockwise.
12
+ */
13
+ export function ellipseArc(pen: PenNode, ctx: VarContext): ArcData | null {
14
+ if (pen.innerRadius === undefined && pen.startAngle === undefined && pen.sweepAngle === undefined)
15
+ return null
16
+ const start = resolveNumber(pen.startAngle, ctx)
17
+ const sweep = Math.max(-360, Math.min(360, resolveNumber(pen.sweepAngle, ctx, 360)))
18
+ return {
19
+ startingAngle: -start * DEGREES,
20
+ endingAngle: -(start + sweep) * DEGREES,
21
+ innerRadius: Math.max(0, Math.min(1, resolveNumber(pen.innerRadius, ctx)))
22
+ }
23
+ }
24
+
25
+ type ViewBox = [x: number, y: number, width: number, height: number]
26
+
27
+ function networkBounds(network: VectorNetwork): ViewBox {
28
+ let [minX, minY, maxX, maxY] = [Infinity, Infinity, -Infinity, -Infinity]
29
+ for (const { x, y } of network.vertices) {
30
+ minX = Math.min(minX, x)
31
+ minY = Math.min(minY, y)
32
+ maxX = Math.max(maxX, x)
33
+ maxY = Math.max(maxY, y)
34
+ }
35
+ return [minX, minY, maxX - minX, maxY - minY]
36
+ }
37
+
38
+ /**
39
+ * A path's geometry in its box. `viewBox` is the region of the path's coordinates that fills the
40
+ * box; without one, the geometry's own bounds do. An axis the geometry has no extent on is not
41
+ * scaled, so a straight line keeps its place.
42
+ */
43
+ export function pathNetwork(pen: PenNode, width: number, height: number): VectorNetwork | null {
44
+ if (!pen.geometry) return null
45
+ const network = parseSVGPath(pen.geometry, pen.fillRule === 'evenodd' ? 'EVENODD' : 'NONZERO')
46
+ if (network.vertices.length === 0) return network
47
+ const [vx, vy, vw, vh] = pen.viewBox ?? networkBounds(network)
48
+ const sx = vw > 0 ? width / vw : 1
49
+ const sy = vh > 0 ? height / vh : 1
50
+ for (const vertex of network.vertices) {
51
+ vertex.x = (vertex.x - vx) * sx
52
+ vertex.y = (vertex.y - vy) * sy
53
+ }
54
+ for (const segment of network.segments) {
55
+ segment.tangentStart = { x: segment.tangentStart.x * sx, y: segment.tangentStart.y * sy }
56
+ segment.tangentEnd = { x: segment.tangentEnd.x * sx, y: segment.tangentEnd.y * sy }
57
+ }
58
+ return network
59
+ }
60
+
61
+ /** A `line`'s geometry: from its box's top-left corner to its bottom-right, as pen.dev draws it. */
62
+ export function lineNetwork(width: number, height: number): VectorNetwork {
63
+ return {
64
+ vertices: [
65
+ { x: 0, y: 0 },
66
+ { x: width, y: height }
67
+ ],
68
+ segments: [{ start: 0, end: 1, tangentStart: { x: 0, y: 0 }, tangentEnd: { x: 0, y: 0 } }],
69
+ regions: []
70
+ }
71
+ }
package/src/icons.ts ADDED
@@ -0,0 +1,173 @@
1
+ import { pick } from 'es-toolkit/object'
2
+ import { isEqual } from 'es-toolkit/predicate'
3
+
4
+ import type { SceneGraph, SceneNode } from '@pairdraw/scene-graph'
5
+ import { BLACK } from '@pairdraw/scene-graph/constants'
6
+ import { readIconTint } from '@pairdraw/scene-graph/icons'
7
+ import {
8
+ getInstances,
9
+ INSTANCE_SYNC_PROPS,
10
+ instanceMainComponent,
11
+ populateInstanceChildren,
12
+ recordInstanceOverride,
13
+ swapInstanceComponent
14
+ } from '@pairdraw/scene-graph/instances'
15
+ import type { Color } from '@pairdraw/scene-graph/primitives'
16
+
17
+ import { iconName, iconOptions } from './assets'
18
+ import type { Build } from './nodes'
19
+ import type { PenNode } from './schema'
20
+ import { resolveOptionalNumber, resolveString } from './variables'
21
+
22
+ /** Space between the icon components on their page. */
23
+ const ICON_COMPONENT_GAP = 16
24
+
25
+ /**
26
+ * An icon draws its glyph in its fill colour, scaled to fit its box and centred, as pen.dev does;
27
+ * an icon the host could not load is an empty frame. Its library, name, and weight may be
28
+ * variables.
29
+ */
30
+ export function drawIcon(node: SceneNode, pen: PenNode, build: Build): void {
31
+ const { graph, ctx } = build
32
+ const color = node.fills.find((fill) => fill.type === 'SOLID')?.color ?? { ...BLACK }
33
+ node.fills = []
34
+ for (const childId of node.childIds) graph.deleteNode(childId)
35
+ const library = resolveString(pen.library, ctx)
36
+ const icon = resolveString(pen.icon, ctx)
37
+ const size = Math.min(node.width, node.height)
38
+ const name = library && icon ? iconName(library, icon) : null
39
+ if (!library || !name || size <= 0) return
40
+ const options = iconOptions(library, resolveOptionalNumber(pen.weight, ctx))
41
+ if (!build.icons?.draw(graph, node.id, name, size, color, options)) return
42
+ const dx = (node.width - size) / 2
43
+ const dy = (node.height - size) / 2
44
+ for (const glyph of graph.getChildren(node.id)) {
45
+ graph.updateNode(glyph.id, { x: glyph.x + dx, y: glyph.y + dy })
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Whether a layer built under `parentId` is part of a component. An instance cannot redraw the
51
+ * paths of a layer it copies, so an icon there is an instance of an icon component, which an
52
+ * instance of the enclosing component can swap, as Figma's icon sets work.
53
+ */
54
+ export function insideComponent(graph: SceneGraph, parentId: string): boolean {
55
+ for (let node = graph.getNode(parentId); node;) {
56
+ if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') return true
57
+ node = node.parentId ? graph.getNode(node.parentId) : undefined
58
+ }
59
+ return false
60
+ }
61
+
62
+ /**
63
+ * The component that draws an icon at a size, made on first use on an "Icons" page. Each size is
64
+ * its own component, so the glyph is drawn at that size, as pen.dev draws it, rather than scaled.
65
+ */
66
+ function iconComponent(build: Build, pen: PenNode, width: number, height: number): string {
67
+ const { graph, ctx } = build
68
+ const library = resolveString(pen.library, ctx) ?? ''
69
+ const icon = resolveString(pen.icon, ctx) ?? ''
70
+ const options = iconOptions(library, resolveOptionalNumber(pen.weight, ctx))
71
+ const key = `${library}/${icon}/${width}x${height}${options ? `/${JSON.stringify(options)}` : ''}`
72
+ const existing = build.iconComponents.get(key)
73
+ if (existing) return existing
74
+ build.iconPageId ??= graph.addPage('Icons').id
75
+ const placed = [...build.iconComponents.values()].map((id) => graph.getNode(id))
76
+ const x = placed.reduce((end, node) => Math.max(end, (node?.x ?? 0) + (node?.width ?? 0)), 0)
77
+ const component = graph.createNode('COMPONENT', build.iconPageId, {
78
+ name: key,
79
+ x: placed.length > 0 ? x + ICON_COMPONENT_GAP : 0,
80
+ width,
81
+ height,
82
+ fills: [{ type: 'SOLID', color: { ...BLACK }, opacity: 1, visible: true }]
83
+ })
84
+ drawIcon(component, pen, build)
85
+ build.iconComponents.set(key, component.id)
86
+ return component.id
87
+ }
88
+
89
+ /** Paints an icon's glyph `color` where it takes the icon's colour, as overrides of the instance. */
90
+ function recolorGlyph(graph: SceneGraph, instanceId: string, color: Color): void {
91
+ for (const glyph of graph.getChildren(instanceId)) {
92
+ const tint = readIconTint(glyph)
93
+ const fills = tint.includes('fill')
94
+ ? glyph.fills.map((fill) => ({ ...fill, color }))
95
+ : glyph.fills
96
+ const strokes = tint.includes('stroke')
97
+ ? glyph.strokes.map((stroke) => ({ ...stroke, color }))
98
+ : glyph.strokes
99
+ const changed = [
100
+ ...(isEqual(fills, glyph.fills) ? [] : ['fills']),
101
+ ...(isEqual(strokes, glyph.strokes) ? [] : ['strokes'])
102
+ ]
103
+ if (changed.length === 0) continue
104
+ graph.updateNode(glyph.id, { fills, strokes })
105
+ recordInstanceOverride(graph, glyph.id, changed)
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Keeps what the icon instance sets on itself, such as its opacity or effects, as overrides of it:
111
+ * the icon component is shared by every use of the glyph at that size, so linking to it would
112
+ * otherwise give the instance the component's values.
113
+ */
114
+ function keepOwnFields(
115
+ graph: SceneGraph,
116
+ instanceId: string,
117
+ own: Partial<SceneNode>,
118
+ componentId: string
119
+ ): void {
120
+ const component = graph.getNode(componentId)
121
+ const differing = INSTANCE_SYNC_PROPS.filter((field) => !isEqual(own[field], component?.[field]))
122
+ if (differing.length === 0) return
123
+ graph.updateNode(instanceId, pick(own, differing))
124
+ recordInstanceOverride(graph, instanceId, differing)
125
+ }
126
+
127
+ /**
128
+ * Whether a copy of an icon still shows the glyph its source showed when it was copied: drawing
129
+ * the source again at its laid-out size gives it a new glyph, which the copy does not follow.
130
+ */
131
+ function showsReplacedGlyph(graph: SceneGraph, copy: SceneNode, sourceId: string): boolean {
132
+ const sourceChildIds = graph.getNode(sourceId)?.childIds ?? []
133
+ return graph
134
+ .getChildren(copy.id)
135
+ .some((glyph) => !glyph.componentId || !sourceChildIds.includes(glyph.componentId))
136
+ }
137
+
138
+ /**
139
+ * Makes the icon instance `node` show its icon: the icon component for its glyph and size,
140
+ * swapped in when an override changed either, with the glyph in the icon's fill colour.
141
+ */
142
+ export function useIconComponent(node: SceneNode, pen: PenNode, build: Build): void {
143
+ const { graph } = build
144
+ const color = node.fills.find((fill) => fill.type === 'SOLID')?.color ?? { ...BLACK }
145
+ node.fills = []
146
+ const own = structuredClone(pick(node, INSTANCE_SYNC_PROPS))
147
+ const componentId = iconComponent(build, pen, node.width, node.height)
148
+ if (!node.componentId) {
149
+ graph.updateNode(node.id, { componentId })
150
+ populateInstanceChildren(graph, node.id, componentId)
151
+ } else if (instanceMainComponent(graph, node)?.id !== componentId) {
152
+ swapInstanceComponent(graph, node.id, componentId, { keepName: true })
153
+ // The layer keeps its own name rather than the icon's, which a saved file keeps as an override.
154
+ recordInstanceOverride(graph, node.id, ['name'])
155
+ } else if (showsReplacedGlyph(graph, node, node.componentId)) {
156
+ for (const childId of node.childIds) graph.deleteNode(childId)
157
+ populateInstanceChildren(graph, node.id, node.componentId)
158
+ }
159
+ keepOwnFields(graph, node.id, own, componentId)
160
+ recolorGlyph(graph, node.id, color)
161
+ }
162
+
163
+ /**
164
+ * Removes the icon components no icon shows any more: those for the sizes reading guessed before
165
+ * laying out gave the icons theirs.
166
+ */
167
+ export function removeUnusedIconComponents(build: Build): void {
168
+ for (const [key, id] of build.iconComponents) {
169
+ if (getInstances(build.graph, id).length > 0) continue
170
+ build.graph.deleteNode(id)
171
+ build.iconComponents.delete(key)
172
+ }
173
+ }