@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/read.ts ADDED
@@ -0,0 +1,150 @@
1
+ import * as v from 'valibot'
2
+
3
+ import { SceneGraph } from '@pairdraw/scene-graph'
4
+
5
+ import { lineNetwork, pathNetwork } from './geometry'
6
+ import { removeUnusedIconComponents } from './icons'
7
+ import { createImageStore } from './images'
8
+ import { withImports, type PenImports } from './imports'
9
+ import { inAncestorThemes, populateInstances } from './instances'
10
+ import { createLibraryRoots, markLibraryRoots } from './library'
11
+ import { createSceneNode, redrawIconAtLaidOutSize, type Build, type PenIconSource } from './nodes'
12
+ import { placeLayers } from './placement'
13
+ import { penFileSchema, type PenDocument, type PenNode } from './schema'
14
+ import { buildVarContext } from './variables'
15
+
16
+ /** Options for reading a document. */
17
+ export interface PenReadOptions {
18
+ /**
19
+ * Lays out the graph's auto layout and text, as `layoutAuthoredNodes` in Core does. Turned and
20
+ * mirrored layers are placed after it, since where they land depends on their final size.
21
+ */
22
+ layout?(graph: SceneGraph): void
23
+ /** The image files the document's paints name, by their URL in it; see `penAssets`. */
24
+ images?: ReadonlyMap<string, Uint8Array>
25
+ /**
26
+ * The shader files the document's paints and effects name, by their URL in it, as their source
27
+ * text; see `penAssets`. A shader whose file is missing draws nothing.
28
+ */
29
+ shaders?: ReadonlyMap<string, string>
30
+ /** Where icon glyphs come from; icons are empty frames without it. */
31
+ icons?: PenIconSource
32
+ /**
33
+ * The documents the document imports, by alias, as `importedDocument` gives them. Their
34
+ * variables join the document's as `<alias>:<name>`, and the components it uses, as
35
+ * `<alias>:<id>`, go on the hidden library page as read-only library definitions. A `ref` to a
36
+ * component no import has reads as a placeholder.
37
+ */
38
+ imports?: PenImports
39
+ }
40
+
41
+ function collectComponents(nodes: PenNode[], components: Map<string, PenNode>): void {
42
+ for (const node of nodes) {
43
+ if (node.reusable) components.set(node.id, node)
44
+ if (node.children) collectComponents(node.children, components)
45
+ }
46
+ }
47
+
48
+ /** Whether a group sits in an auto layout's flow, where fitting it changes the layout. */
49
+ function groupsInFlow(graph: SceneGraph, groupIds: Iterable<string>): boolean {
50
+ for (const id of groupIds) {
51
+ const group = graph.getNode(id)
52
+ const parent = group?.parentId ? graph.getNode(group.parentId) : undefined
53
+ if (parent && parent.layoutMode !== 'NONE') return true
54
+ }
55
+ return false
56
+ }
57
+
58
+ /**
59
+ * Draws each path and slanted line in its box once boxes have their final size, which fill and
60
+ * fit sizing only give once laid out, and redraws each icon laying out sized.
61
+ */
62
+ function drawAtFinalSize(build: Build, laidOut: boolean): void {
63
+ for (const [id, pen] of build.effective) {
64
+ const node = build.graph.getNode(id)
65
+ if (!node) continue
66
+ if (pen.type === 'path') {
67
+ const network = pathNetwork(pen, node.width, node.height)
68
+ if (network) node.vectorNetwork = network
69
+ } else if (pen.type === 'line' && node.type === 'VECTOR') {
70
+ node.vectorNetwork = lineNetwork(node.width, node.height)
71
+ } else if (pen.type === 'icon' && laidOut) {
72
+ // In the themes the icon was read in, which its colour and glyph may take variables from.
73
+ inAncestorThemes(build, node, () => {
74
+ const leave = pen.theme ? build.ctx.enterTheme(pen.theme) : undefined
75
+ try {
76
+ redrawIconAtLaidOutSize(node, pen, build)
77
+ } finally {
78
+ leave?.()
79
+ }
80
+ })
81
+ }
82
+ }
83
+ }
84
+
85
+ /** A `.pen` document's JSON, validated; throws for text that is not one. */
86
+ export function parsePenDocument(json: string): PenDocument {
87
+ const parsed = v.safeParse(penFileSchema, json)
88
+ if (!parsed.success) {
89
+ throw new Error(`Not a .pen document: ${v.summarize(parsed.issues)}`)
90
+ }
91
+ return parsed.output
92
+ }
93
+
94
+ /** Builds the scene graph of a document `parsePenDocument` read. */
95
+ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): SceneGraph {
96
+ const graph = new SceneGraph()
97
+
98
+ for (const page of graph.getPages(true)) {
99
+ graph.deleteNode(page.id)
100
+ }
101
+
102
+ const imports: PenImports = options.imports ?? new Map()
103
+ const build: Build = {
104
+ graph,
105
+ ctx: buildVarContext(graph, withImports(doc, imports)),
106
+ images: createImageStore(graph, options.images),
107
+ shaders: options.shaders,
108
+ icons: options.icons,
109
+ components: new Map(),
110
+ effective: new Map(),
111
+ instances: new Map(),
112
+ placements: new Map(),
113
+ groupIds: new Set(),
114
+ iconComponents: new Map(),
115
+ iconPageId: null,
116
+ replaced: new Set()
117
+ }
118
+ collectComponents(doc.children, build.components)
119
+ for (const imported of imports.values())
120
+ collectComponents(imported.doc.children, build.components)
121
+
122
+ const page = graph.addPage(doc.children[0]?.name ?? 'Page 1')
123
+ for (const child of doc.children) createSceneNode(child, page.id, build)
124
+ const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode)
125
+ populateInstances(build)
126
+
127
+ options.layout?.(graph)
128
+ drawAtFinalSize(build, options.layout !== undefined)
129
+ placeLayers(graph, build.placements, [...build.groupIds])
130
+ if (options.layout && groupsInFlow(graph, build.groupIds)) {
131
+ options.layout(graph)
132
+ drawAtFinalSize(build, true)
133
+ }
134
+ removeUnusedIconComponents(build)
135
+ markLibraryRoots(graph, libraryRoots)
136
+
137
+ if (graph.getPages(true).length === 0) {
138
+ graph.addPage('Page 1')
139
+ }
140
+
141
+ return graph
142
+ }
143
+
144
+ export function parsePenFile(json: string, options: PenReadOptions = {}): SceneGraph {
145
+ return buildPenGraph(parsePenDocument(json), options)
146
+ }
147
+
148
+ export async function readPenFile(file: File, options?: PenReadOptions): Promise<SceneGraph> {
149
+ return parsePenFile(await file.text(), options)
150
+ }
package/src/schema.ts ADDED
@@ -0,0 +1,299 @@
1
+ import * as v from 'valibot'
2
+
3
+ import { stripJSONComments } from './jsonc'
4
+
5
+ /**
6
+ * The `.pen` document as pen.dev writes it (schema 2.21), plus the older forms still found in
7
+ * files: the object `stroke` of 2.8 and `icon_font` nodes. Properties typed `…OrVariable` hold a
8
+ * `$name` reference in place of the value. Enumerated values stay strings so a value this reader
9
+ * does not know falls back to the default instead of rejecting the document.
10
+ */
11
+
12
+ const numSchema = v.union([v.number(), v.string()])
13
+ const boolSchema = v.union([v.boolean(), v.string()])
14
+ const strSchema = v.string()
15
+ const sidesSchema = v.looseObject({
16
+ top: v.optional(numSchema),
17
+ right: v.optional(numSchema),
18
+ bottom: v.optional(numSchema),
19
+ left: v.optional(numSchema)
20
+ })
21
+
22
+ const paintBase = {
23
+ enabled: v.optional(boolSchema),
24
+ blendMode: v.optional(strSchema)
25
+ }
26
+
27
+ const colorPaintSchema = v.looseObject({
28
+ type: v.literal('color'),
29
+ ...paintBase,
30
+ color: strSchema
31
+ })
32
+
33
+ const gradientPaintSchema = v.looseObject({
34
+ type: v.literal('gradient'),
35
+ ...paintBase,
36
+ gradientType: v.optional(strSchema),
37
+ opacity: v.optional(numSchema),
38
+ center: v.optional(v.looseObject({ x: v.optional(v.number()), y: v.optional(v.number()) })),
39
+ size: v.optional(
40
+ v.looseObject({
41
+ width: v.optional(numSchema),
42
+ height: v.optional(numSchema)
43
+ })
44
+ ),
45
+ rotation: v.optional(numSchema),
46
+ colors: v.optional(v.array(v.looseObject({ color: strSchema, position: numSchema })))
47
+ })
48
+
49
+ const imagePaintSchema = v.looseObject({
50
+ type: v.literal('image'),
51
+ ...paintBase,
52
+ opacity: v.optional(numSchema),
53
+ url: v.optional(strSchema),
54
+ mode: v.optional(strSchema),
55
+ transform: v.optional(
56
+ v.tuple([v.number(), v.number(), v.number(), v.number(), v.number(), v.number()])
57
+ )
58
+ })
59
+
60
+ /**
61
+ * A `mesh_gradient` paint, as the `.pen` reference documents it: one color per vertex and one
62
+ * point per vertex in [0,1], `columns * rows` of them. Bezier handles ride on the points and do
63
+ * not change the grid this reader draws, so they pass through as unknowns.
64
+ */
65
+ export const meshPaintSchema = v.looseObject({
66
+ type: v.literal('mesh_gradient'),
67
+ ...paintBase,
68
+ opacity: v.optional(numSchema),
69
+ columns: v.optional(numSchema),
70
+ rows: v.optional(numSchema),
71
+ colors: v.optional(v.array(v.unknown())),
72
+ points: v.optional(v.array(v.unknown()))
73
+ })
74
+
75
+ /**
76
+ * A `shader` paint: `url` names the shader file beside the document, whose source `PenReadOptions`
77
+ * gives by that URL. One whose source the host did not read draws nothing, as pen.dev shows a
78
+ * shader it cannot compile.
79
+ */
80
+ const shaderPaintSchema = v.looseObject({
81
+ type: v.literal('shader'),
82
+ ...paintBase,
83
+ opacity: v.optional(numSchema),
84
+ url: v.optional(strSchema)
85
+ })
86
+
87
+ /** Paint types this reader does not draw. */
88
+ const otherPaintSchema = v.looseObject({ type: strSchema, ...paintBase })
89
+
90
+ const paintSchema = v.union([
91
+ strSchema,
92
+ colorPaintSchema,
93
+ gradientPaintSchema,
94
+ imagePaintSchema,
95
+ meshPaintSchema,
96
+ shaderPaintSchema,
97
+ otherPaintSchema
98
+ ])
99
+ const paintsSchema = v.union([paintSchema, v.array(paintSchema)])
100
+
101
+ /** The 2.8 stroke: one colour with its weight and placement in one object. */
102
+ const legacyStrokeSchema = v.looseObject({
103
+ thickness: v.union([numSchema, sidesSchema]),
104
+ fill: v.optional(strSchema),
105
+ align: v.optional(strSchema),
106
+ join: v.optional(strSchema),
107
+ cap: v.optional(strSchema)
108
+ })
109
+
110
+ const effectSchema = v.looseObject({
111
+ type: strSchema,
112
+ enabled: v.optional(boolSchema),
113
+ radius: v.optional(numSchema),
114
+ shadowType: v.optional(strSchema),
115
+ offset: v.optional(v.looseObject({ x: numSchema, y: numSchema })),
116
+ blur: v.optional(numSchema),
117
+ /** Written by older files; current pen.dev shadows have no spread. */
118
+ spread: v.optional(numSchema),
119
+ color: v.optional(strSchema),
120
+ blendMode: v.optional(strSchema),
121
+ /** The shader file a `shader` effect names, read by `PenReadOptions.shaders`. */
122
+ url: v.optional(strSchema)
123
+ })
124
+
125
+ const sizeSchema = numSchema
126
+ const paddingSchema = v.union([
127
+ numSchema,
128
+ v.tuple([numSchema, numSchema]),
129
+ v.tuple([numSchema, numSchema, numSchema, numSchema])
130
+ ])
131
+ const cornerRadiusSchema = v.union([numSchema, v.array(numSchema)])
132
+
133
+ /** Every property a node, or an override of one, can carry. */
134
+ const nodeFields = {
135
+ name: v.optional(strSchema),
136
+ context: v.optional(strSchema),
137
+ /**
138
+ * What a layer is, for agents: pen.dev writes a `type` and any fields of its own. It is only kept
139
+ * as plugin data, so any value is read as it is rather than rejecting the document.
140
+ */
141
+ metadata: v.optional(v.unknown()),
142
+ x: v.optional(v.number()),
143
+ y: v.optional(v.number()),
144
+ width: v.optional(sizeSchema),
145
+ height: v.optional(sizeSchema),
146
+ reusable: v.optional(v.boolean()),
147
+ theme: v.optional(v.record(strSchema, strSchema)),
148
+ enabled: v.optional(boolSchema),
149
+ opacity: v.optional(numSchema),
150
+ flipX: v.optional(boolSchema),
151
+ flipY: v.optional(boolSchema),
152
+ layoutPosition: v.optional(strSchema),
153
+ rotation: v.optional(numSchema),
154
+
155
+ fill: v.optional(paintsSchema),
156
+ stroke: v.optional(v.union([paintsSchema, legacyStrokeSchema])),
157
+ strokeWidth: v.optional(v.union([numSchema, sidesSchema])),
158
+ strokeLinecap: v.optional(strSchema),
159
+ strokeLinejoin: v.optional(strSchema),
160
+ strokeAlignment: v.optional(strSchema),
161
+ effect: v.optional(v.union([effectSchema, v.array(effectSchema)])),
162
+ cornerRadius: v.optional(cornerRadiusSchema),
163
+
164
+ layout: v.optional(strSchema),
165
+ gap: v.optional(numSchema),
166
+ layoutIncludeStroke: v.optional(v.boolean()),
167
+ padding: v.optional(paddingSchema),
168
+ justifyContent: v.optional(strSchema),
169
+ alignItems: v.optional(strSchema),
170
+ clip: v.optional(boolSchema),
171
+ placeholder: v.optional(v.boolean()),
172
+ slot: v.optional(v.union([v.literal(false), v.array(strSchema)])),
173
+
174
+ innerRadius: v.optional(numSchema),
175
+ startAngle: v.optional(numSchema),
176
+ sweepAngle: v.optional(numSchema),
177
+ polygonCount: v.optional(numSchema),
178
+ geometry: v.optional(strSchema),
179
+ fillRule: v.optional(strSchema),
180
+ viewBox: v.optional(v.tuple([v.number(), v.number(), v.number(), v.number()])),
181
+
182
+ content: v.optional(strSchema),
183
+ textGrowth: v.optional(strSchema),
184
+ fontFamily: v.optional(strSchema),
185
+ fontSize: v.optional(numSchema),
186
+ fontWeight: v.optional(numSchema),
187
+ fontStyle: v.optional(strSchema),
188
+ letterSpacing: v.optional(numSchema),
189
+ lineHeight: v.optional(numSchema),
190
+ textAlign: v.optional(strSchema),
191
+ textAlignVertical: v.optional(strSchema),
192
+ underline: v.optional(boolSchema),
193
+ strikethrough: v.optional(boolSchema),
194
+ href: v.optional(v.nullable(strSchema)),
195
+
196
+ library: v.optional(strSchema),
197
+ icon: v.optional(strSchema),
198
+ weight: v.optional(numSchema),
199
+ iconFontName: v.optional(strSchema),
200
+ iconFontFamily: v.optional(strSchema),
201
+
202
+ ref: v.optional(strSchema),
203
+ /** The model a `prompt` node asks. */
204
+ model: v.optional(strSchema),
205
+
206
+ /** A `script` node's JavaScript file, relative to the document. */
207
+ scriptUri: v.optional(strSchema),
208
+ /** A `script` node's input values by name. */
209
+ inputs: v.optional(v.record(strSchema, v.unknown())),
210
+ /** The page a `browser` node shows; empty asks for one. */
211
+ url: v.optional(strSchema),
212
+ /** The device a `browser` node emulates; responsive without one. */
213
+ deviceId: v.optional(strSchema),
214
+ zoom: v.optional(numSchema),
215
+ scrollX: v.optional(numSchema),
216
+ scrollY: v.optional(numSchema)
217
+ }
218
+
219
+ export type NodeFields = v.InferOutput<v.ObjectSchema<typeof nodeFields, undefined>>
220
+
221
+ /** Properties an instance sets on one of its component's descendants, or a node replacing it. */
222
+ export interface PenOverride extends NodeFields {
223
+ type?: string
224
+ id?: string
225
+ children?: PenNode[]
226
+ descendants?: Record<string, PenOverride>
227
+ [key: string]: unknown
228
+ }
229
+
230
+ export interface PenNode extends PenOverride {
231
+ type: string
232
+ id: string
233
+ }
234
+
235
+ const overrideSchema: v.GenericSchema<unknown, PenOverride> = v.looseObject({
236
+ ...nodeFields,
237
+ type: v.optional(strSchema),
238
+ id: v.optional(strSchema),
239
+ children: v.optional(v.array(v.lazy(() => nodeSchema))),
240
+ descendants: v.optional(
241
+ v.record(
242
+ strSchema,
243
+ v.lazy(() => overrideSchema)
244
+ )
245
+ )
246
+ })
247
+
248
+ const nodeSchema: v.GenericSchema<unknown, PenNode> = v.looseObject({
249
+ ...nodeFields,
250
+ type: strSchema,
251
+ id: strSchema,
252
+ children: v.optional(v.array(v.lazy(() => nodeSchema))),
253
+ descendants: v.optional(v.record(strSchema, overrideSchema))
254
+ })
255
+
256
+ const variableScalarSchema = v.union([v.string(), v.number(), v.boolean()])
257
+
258
+ const variableSchema = v.looseObject({
259
+ type: strSchema,
260
+ value: v.union([
261
+ variableScalarSchema,
262
+ v.array(
263
+ v.looseObject({
264
+ value: variableScalarSchema,
265
+ theme: v.optional(v.record(strSchema, strSchema))
266
+ })
267
+ )
268
+ ])
269
+ })
270
+
271
+ const penDocumentSchema = v.looseObject({
272
+ version: v.optional(strSchema),
273
+ themes: v.optional(v.record(strSchema, v.array(strSchema))),
274
+ imports: v.optional(v.record(strSchema, strSchema)),
275
+ variables: v.optional(v.record(strSchema, variableSchema)),
276
+ children: v.array(nodeSchema)
277
+ })
278
+
279
+ export type PenDocument = v.InferOutput<typeof penDocumentSchema>
280
+ export type PenVariable = v.InferOutput<typeof variableSchema>
281
+ export type PenVariableScalar = v.InferOutput<typeof variableScalarSchema>
282
+ export type PenPaint = v.InferOutput<typeof paintSchema>
283
+ export type PenPaints = v.InferOutput<typeof paintsSchema>
284
+ export type PenGradientPaint = v.InferOutput<typeof gradientPaintSchema>
285
+ export type PenImagePaint = v.InferOutput<typeof imagePaintSchema>
286
+ export type PenShaderPaint = v.InferOutput<typeof shaderPaintSchema>
287
+ export type PenMeshPaint = v.InferOutput<typeof meshPaintSchema>
288
+ export type PenLegacyStroke = v.InferOutput<typeof legacyStrokeSchema>
289
+ export type PenEffect = v.InferOutput<typeof effectSchema>
290
+ export type PenSides = v.InferOutput<typeof sidesSchema>
291
+ export type PenNumber = v.InferOutput<typeof numSchema>
292
+
293
+ /** A `.pen` file's text, which may hold comments, as its document. */
294
+ export const penFileSchema = v.pipe(
295
+ v.string(),
296
+ v.transform(stripJSONComments),
297
+ v.parseJson(),
298
+ penDocumentSchema
299
+ )
package/src/slots.ts ADDED
@@ -0,0 +1,41 @@
1
+ import type { SceneNode } from '@pairdraw/scene-graph'
2
+ import { createComponentPropertyId } from '@pairdraw/scene-graph/components'
3
+ import {
4
+ canCreateSlot,
5
+ claimSlotContent,
6
+ createSlotProperty,
7
+ slotOwner,
8
+ slotScope,
9
+ updateSlotProperty
10
+ } from '@pairdraw/scene-graph/slots'
11
+
12
+ import type { Build } from './nodes'
13
+ import type { PenNode } from './schema'
14
+
15
+ /**
16
+ * Makes a frame pen.dev marks with `slot` a slot of the component it is in, suggesting the
17
+ * components it lists that the document defines. A frame outside a component has no slot to be.
18
+ */
19
+ export function createPenSlot(node: SceneNode, pen: PenNode, build: Build): void {
20
+ const { graph, components } = build
21
+ if (!Array.isArray(pen.slot) || !canCreateSlot(graph, node)) return
22
+ const definition = createSlotProperty(graph, node.id, createComponentPropertyId())
23
+ const owner = slotOwner(graph, node)
24
+ if (!definition || !owner) return
25
+ const preferredValues = pen.slot.filter((id) => components.get(id)?.type === 'frame')
26
+ if (preferredValues.length > 0)
27
+ updateSlotProperty(graph, owner.id, definition.id, { preferredValues })
28
+ }
29
+
30
+ /**
31
+ * Lets `instance` own the content of the slot frame `target`, which an override of its is about
32
+ * to fill, as filling a slot in pen.dev keeps the instance. Returns false when `target` is not a
33
+ * slot of that very instance, whose layers the override must then replace.
34
+ */
35
+ export function claimSlot(build: Build, instance: SceneNode, target: SceneNode): boolean {
36
+ const scope = slotScope(build.graph, target.id)
37
+ if (scope.kind !== 'slot' || scope.frame.id !== target.id || scope.instance.id !== instance.id)
38
+ return false
39
+ claimSlotContent(build.graph, scope)
40
+ return true
41
+ }
package/src/text.ts ADDED
@@ -0,0 +1,92 @@
1
+ import type { SceneNode, StyleRun, TextAlignVertical, TextAutoResize } from '@pairdraw/scene-graph'
2
+ import { percentLength, pixelLength } from '@pairdraw/scene-graph/text'
3
+
4
+ import type { PenNode } from './schema'
5
+ import { bindIfVar, isVarRef, resolveNumber, resolveString, type VarContext } from './variables'
6
+
7
+ const FONT_WEIGHTS: Partial<Record<string, number>> = {
8
+ thin: 100,
9
+ extralight: 200,
10
+ light: 300,
11
+ normal: 400,
12
+ regular: 400,
13
+ medium: 500,
14
+ semibold: 600,
15
+ bold: 700,
16
+ extrabold: 800,
17
+ black: 900
18
+ }
19
+
20
+ /** pen.dev writes weights as numbers in strings, such as "700"; older files use names. */
21
+ function fontWeight(value: PenNode['fontWeight'], ctx: VarContext): number {
22
+ if (value === undefined) return 400
23
+ if (typeof value === 'number') return value
24
+ const named = isVarRef(value) ? ctx.resolveString(value) || ctx.resolveNumber(value) : value
25
+ const numeric = Number(named)
26
+ if (Number.isFinite(numeric) && numeric > 0) return numeric
27
+ return FONT_WEIGHTS[String(named).toLowerCase()] ?? 400
28
+ }
29
+
30
+ const TEXT_ALIGN: Partial<Record<string, SceneNode['textAlignHorizontal']>> = {
31
+ left: 'LEFT',
32
+ center: 'CENTER',
33
+ right: 'RIGHT',
34
+ justify: 'JUSTIFIED'
35
+ }
36
+
37
+ const TEXT_ALIGN_VERTICAL: Partial<Record<string, TextAlignVertical>> = {
38
+ top: 'TOP',
39
+ middle: 'CENTER',
40
+ bottom: 'BOTTOM'
41
+ }
42
+
43
+ /**
44
+ * `auto` grows on one line, `fixed-width` wraps and grows down, and `fixed-width-height` wraps in
45
+ * a fixed box its text may overflow.
46
+ */
47
+ const TEXT_GROWTH: Partial<Record<string, TextAutoResize>> = {
48
+ auto: 'WIDTH_AND_HEIGHT',
49
+ 'fixed-width': 'HEIGHT',
50
+ 'fixed-width-height': 'NONE'
51
+ }
52
+
53
+ /**
54
+ * A text layer's content and style. Content that reads like a variable reference stays as written,
55
+ * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those
56
+ * are left out to match it. An `href` is kept as a link, drawn without an underline.
57
+ */
58
+ export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {
59
+ const isIconFont = pen.type === 'icon_font'
60
+ node.text = isIconFont ? (pen.iconFontName ?? '') : (pen.content ?? '')
61
+ node.fontFamily = isIconFont
62
+ ? (pen.iconFontFamily ?? 'Material Symbols Sharp')
63
+ : (resolveString(pen.fontFamily, ctx) ?? 'Inter')
64
+ bindIfVar(node, 'fontFamily', pen.fontFamily, ctx)
65
+ node.fontSize = resolveNumber(pen.fontSize, ctx, 14)
66
+ bindIfVar(node, 'fontSize', pen.fontSize, ctx)
67
+ const weight = pen.fontWeight ?? (isIconFont ? pen.weight : undefined)
68
+ node.fontWeight = fontWeight(weight, ctx)
69
+ bindIfVar(node, 'fontWeight', weight, ctx)
70
+ node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === 'italic'
71
+ node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'
72
+ node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'
73
+ // pen.dev's line height multiplies the font size, so it follows the size as a percent.
74
+ if (pen.lineHeight !== undefined) {
75
+ node.lineHeight = percentLength(resolveNumber(pen.lineHeight, ctx) * 100)
76
+ }
77
+ if (pen.letterSpacing !== undefined) {
78
+ node.letterSpacing = pixelLength(resolveNumber(pen.letterSpacing, ctx))
79
+ }
80
+ node.textAutoResize = TEXT_GROWTH[pen.textGrowth ?? 'auto'] ?? 'WIDTH_AND_HEIGHT'
81
+ // pen.dev draws every font at its default optical size, whatever the text's size.
82
+ node.opticalSizeFromFontSize = false
83
+ node.strokes = []
84
+ node.styleRuns = textLink(pen, node.text, ctx)
85
+ }
86
+
87
+ /** A text's `href` links all of its characters, as one run. */
88
+ function textLink(pen: PenNode, text: string, ctx: VarContext): StyleRun[] {
89
+ const href = pen.type === 'text' ? resolveString(pen.href ?? undefined, ctx)?.trim() : undefined
90
+ if (!href || text.length === 0) return []
91
+ return [{ start: 0, length: text.length, style: { hyperlink: { type: 'URL', value: href } } }]
92
+ }