@pairdraw/pen 0.17.0 → 0.19.0-beta.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/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import { SceneGraph } from "@pairdraw/scene-graph";
2
2
  import * as v from "valibot";
3
3
  import { Color } from "@pairdraw/scene-graph/primitives";
4
+ import { FontFamilyStyle } from "@pairdraw/scene-graph/font-style";
4
5
  //#region src/schema.d.ts
5
6
  /** Every property a node, or an override of one, can carry. */
6
7
  declare const nodeFields: {
@@ -286,7 +287,7 @@ declare const nodeFields: {
286
287
  layout: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
287
288
  gap: v.OptionalSchema<v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, undefined>;
288
289
  layoutIncludeStroke: v.OptionalSchema<v.BooleanSchema<undefined>, undefined>;
289
- padding: v.OptionalSchema<v.UnionSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.TupleSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>], undefined>, v.TupleSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>], undefined>], undefined>, undefined>;
290
+ padding: v.OptionalSchema<v.UnionSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.TupleSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>], undefined>, v.TupleSchema<[v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>, v.UnionSchema<[v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.StringSchema<undefined>], undefined>], undefined>], undefined>, undefined>;
290
291
  justifyContent: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
291
292
  alignItems: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
292
293
  clip: v.OptionalSchema<v.UnionSchema<[v.BooleanSchema<undefined>, v.StringSchema<undefined>], undefined>, undefined>;
@@ -345,8 +346,18 @@ interface PenNode extends PenOverride {
345
346
  type: string;
346
347
  id: string;
347
348
  }
349
+ /** A font file the document bundles, which its text names by `name` as a family. */
350
+ declare const fontSchema: v.LooseObjectSchema<{
351
+ readonly name: v.StringSchema<undefined>;
352
+ readonly url: v.StringSchema<undefined>;
353
+ }, undefined>;
348
354
  declare const penDocumentSchema: v.LooseObjectSchema<{
349
355
  readonly version: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
356
+ readonly name: v.OptionalSchema<v.StringSchema<undefined>, undefined>;
357
+ readonly fonts: v.OptionalSchema<v.ArraySchema<v.LooseObjectSchema<{
358
+ readonly name: v.StringSchema<undefined>;
359
+ readonly url: v.StringSchema<undefined>;
360
+ }, undefined>, undefined>, undefined>;
350
361
  readonly themes: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
351
362
  readonly imports: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
352
363
  readonly variables: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.LooseObjectSchema<{
@@ -359,6 +370,7 @@ declare const penDocumentSchema: v.LooseObjectSchema<{
359
370
  readonly children: v.ArraySchema<v.GenericSchema<unknown, PenNode>, undefined>;
360
371
  }, undefined>;
361
372
  type PenDocument = v.InferOutput<typeof penDocumentSchema>;
373
+ type PenFont = v.InferOutput<typeof fontSchema>;
362
374
  //#endregion
363
375
  //#region src/assets.d.ts
364
376
  /** An icon's name in its set. */
@@ -468,6 +480,12 @@ interface PenReadOptions {
468
480
  shaders?: ReadonlyMap<string, string>;
469
481
  /** Where icon glyphs come from; icons are empty frames without it. */
470
482
  icons?: PenIconSource;
483
+ /**
484
+ * The family and style each bundled font file names itself with, by its `name` in the
485
+ * document's `fonts`. pen.dev registers a bundled file under that name, such as
486
+ * `Geist-SemiBold`, and its text uses it as the family; the text takes the file's own names.
487
+ */
488
+ fonts?: ReadonlyMap<string, FontFamilyStyle>;
471
489
  /**
472
490
  * The documents the document imports, by alias, as `importedDocument` gives them. Their
473
491
  * variables join the document's as `<alias>:<name>`, and the components it uses, as
@@ -488,5 +506,5 @@ declare function penDocumentFromGraph(graph: SceneGraph): PenDocument;
488
506
  declare function stringifyPenDocument(document: PenDocument): string;
489
507
  declare function writePenDocument(source: PenDocument | SceneGraph): string;
490
508
  //#endregion
491
- export { PEN_PLUGIN_DATA_NAMESPACE, type PenAssets, type PenDocument, type PenIconRequest, type PenIconSource, type PenImport, type PenImports, type PenNode, type PenOverride, type PenReadOptions, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
509
+ export { PEN_PLUGIN_DATA_NAMESPACE, type PenAssets, type PenDocument, type PenFont, type PenIconRequest, type PenIconSource, type PenImport, type PenImports, type PenNode, type PenOverride, type PenReadOptions, buildPenGraph, iconName, iconOptions, importedDocument, isDataURL, isDocumentAssetPath, parseImportedImageURL, parsePenDocument, parsePenFile, penAssets, penDocumentFromGraph, readPenFile, stringifyPenDocument, withUsedImports, writePenDocument };
492
510
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/assets.ts","../src/imports.ts","../src/nodes.ts","../src/library.ts","../src/plugin-data.ts","../src/read.ts","../src/write.ts"],"mappings":";;;;;cAkJM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuFM,aAAa,EAAE,YAAY,EAAE,oBAAoB;;UAG5C,oBAAoB;EACnC;EACA;EACA,WAAW;EACX,cAAc,eAAe;GAC5B;;UAGc,gBAAgB;EAC/B;EACA;;cAuCI,mBAAiB,EAAA;;;;;;;;;;;;;KAQX,cAAc,EAAE,mBAAmB;;;;iBC1Q/B,SAAS,iBAAiB;;iBAM1B,YACd,iBACA,6BACC;;UAKc;EACf;EACA,UAAU;;;;;;iBAOI,oBAAoB;;iBAMpB,UAAU;;;;;iBAWV,sBAAsB;EAAgB;EAAe;;;UASpD;;EAEf,OAAO;;;;;EAKP;;;;;EAKA;;;;;;iBAsHc,UAAU,KAAK,cAAc;;;;UCrM5B;;EAEf;;EAEA,KAAK;;;KAIK,aAAa,oBAAoB;;;;;;;iBAqH7B,iBACd,eACA,cACA,KAAK,aACL,SAAS,aACR;;;;UCxGc;;;;;;EAMf,KACE,OAAO,YACP,iBACA,cACA,cACA,OAAO,OACP,UAAU;;;;;;;;;iBCgCE,gBAAgB,KAAK,aAAa,SAAS,aAAa;;;;;;;;cCtE3D;;;;UCOI;;;;;EAKf,QAAQ,OAAO;;EAEf,SAAS,oBAAoB;;;;;EAK7B,UAAU;;EAEV,QAAQ;;;;;;;EAOR,UAAU;;;iBAgDI,iBAAiB,eAAe;;iBAShC,cAAc,KAAK,aAAa,UAAS,iBAAsB;iBAiD/D,aAAa,cAAc,UAAS,iBAAsB;iBAIpD,YAAY,MAAM,MAAM,UAAU,iBAAiB,QAAQ;;;iBCuajE,qBAAqB,OAAO,aAAa;iBAqBzC,qBAAqB,UAAU;iBAI/B,iBAAiB,QAAQ,cAAc"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/schema.ts","../src/assets.ts","../src/imports.ts","../src/nodes.ts","../src/library.ts","../src/plugin-data.ts","../src/read.ts","../src/write.ts"],"mappings":";;;;;;cAoJM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuFM,aAAa,EAAE,YAAY,EAAE,oBAAoB;;UAG5C,oBAAoB;EACnC;EACA;EACA,WAAW;EACX,cAAc,eAAe;GAC5B;;UAGc,gBAAgB;EAC/B;EACA;;;cAwCI,YAAU,EAAA;;;;cAEV,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;KAWX,cAAc,EAAE,mBAAmB;KACnC,UAAU,EAAE,mBAAmB;;;;iBCnR3B,SAAS,iBAAiB;;iBAM1B,YACd,iBACA,6BACC;;UAKc;EACf;EACA,UAAU;;;;;;iBAOI,oBAAoB;;iBAMpB,UAAU;;;;;iBAWV,sBAAsB;EAAgB;EAAe;;;UASpD;;EAEf,OAAO;;;;;EAKP;;;;;EAKA;;;;;;iBAsHc,UAAU,KAAK,cAAc;;;;UCrM5B;;EAEf;;EAEA,KAAK;;;KAIK,aAAa,oBAAoB;;;;;;;iBAqH7B,iBACd,eACA,cACA,KAAK,aACL,SAAS,aACR;;;;UCtGc;;;;;;EAMf,KACE,OAAO,YACP,iBACA,cACA,cACA,OAAO,OACP,UAAU;;;;;;;;;iBC8BE,gBAAgB,KAAK,aAAa,SAAS,aAAa;;;;;;;;cCtE3D;;;;UCQI;;;;;EAKf,QAAQ,OAAO;;EAEf,SAAS,oBAAoB;;;;;EAK7B,UAAU;;EAEV,QAAQ;;;;;;EAMR,QAAQ,oBAAoB;;;;;;;EAO5B,UAAU;;;iBAgDI,iBAAiB,eAAe;;iBAShC,cAAc,KAAK,aAAa,UAAS,iBAAsB;iBAkD/D,aAAa,cAAc,UAAS,iBAAsB;iBAIpD,YAAY,MAAM,MAAM,UAAU,iBAAiB,QAAQ;;;iBC2bjE,qBAAqB,OAAO,aAAa;iBAqBzC,qBAAqB,UAAU;iBAI/B,iBAAiB,QAAQ,cAAc"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/pen",
3
- "version": "0.17.0",
3
+ "version": "0.19.0-beta.1",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
@@ -14,7 +14,7 @@
14
14
  "valibot": "^1.5.0"
15
15
  },
16
16
  "peerDependencies": {
17
- "@pairdraw/scene-graph": "^0.17.0"
17
+ "@pairdraw/scene-graph": "^0.19.0-beta.1"
18
18
  },
19
19
  "exports": {
20
20
  ".": {
package/src/geometry.ts CHANGED
@@ -69,3 +69,95 @@ export function lineNetwork(width: number, height: number): VectorNetwork {
69
69
  regions: []
70
70
  }
71
71
  }
72
+
73
+ function pathNumber(value: number): string {
74
+ return String(Object.is(value, -0) ? 0 : value)
75
+ }
76
+
77
+ function directedSegment(
78
+ network: VectorNetwork,
79
+ index: number,
80
+ forward: boolean
81
+ ): { command: string; end: number } {
82
+ const segment = network.segments[index]
83
+ const from = forward ? segment.start : segment.end
84
+ const to = forward ? segment.end : segment.start
85
+ const start = network.vertices[from]
86
+ const end = network.vertices[to]
87
+ const tangentStart = forward ? segment.tangentStart : segment.tangentEnd
88
+ const tangentEnd = forward ? segment.tangentEnd : segment.tangentStart
89
+ if (tangentStart.x === 0 && tangentStart.y === 0 && tangentEnd.x === 0 && tangentEnd.y === 0) {
90
+ return { command: `L${pathNumber(end.x)} ${pathNumber(end.y)}`, end: to }
91
+ }
92
+ return {
93
+ command: `C${pathNumber(start.x + tangentStart.x)} ${pathNumber(
94
+ start.y + tangentStart.y
95
+ )} ${pathNumber(end.x + tangentEnd.x)} ${pathNumber(end.y + tangentEnd.y)} ${pathNumber(
96
+ end.x
97
+ )} ${pathNumber(end.y)}`,
98
+ end: to
99
+ }
100
+ }
101
+
102
+ /**
103
+ * A vector network as SVG path data, the form pen keeps a path in (`geometry`). Region loops are
104
+ * closed subpaths; the segments outside them are walked as open chains so joins stay joins.
105
+ */
106
+ export function networkToSVGPath(network: VectorNetwork): string {
107
+ const parts: string[] = []
108
+ const inRegion = new Set<number>()
109
+ for (const region of network.regions) {
110
+ for (const loop of region.loops) {
111
+ if (loop.length === 0) continue
112
+ const first = network.segments[loop[0]]
113
+ let current: number
114
+ if (loop.length === 1) current = first.start
115
+ else {
116
+ const second = network.segments[loop[1]]
117
+ current = first.end === second.start || first.end === second.end ? first.start : first.end
118
+ }
119
+ const startVertex = network.vertices[current]
120
+ parts.push(`M${pathNumber(startVertex.x)} ${pathNumber(startVertex.y)}`)
121
+ for (const index of loop) {
122
+ const segment = network.segments[index]
123
+ const forward = segment.start === current
124
+ const drawn = directedSegment(network, index, forward)
125
+ parts.push(drawn.command)
126
+ current = drawn.end
127
+ inRegion.add(index)
128
+ }
129
+ parts.push('Z')
130
+ }
131
+ }
132
+ const used = new Set<number>(inRegion)
133
+ const degree = new Map<number, number[]>()
134
+ for (const [index, segment] of network.segments.entries()) {
135
+ if (inRegion.has(index)) continue
136
+ for (const vertex of [segment.start, segment.end]) {
137
+ const list = degree.get(vertex) ?? []
138
+ list.push(index)
139
+ degree.set(vertex, list)
140
+ }
141
+ }
142
+ let current: number
143
+ for (;;) {
144
+ const unused = [...degree.entries()].filter(([, indexes]) =>
145
+ indexes.some((index) => !used.has(index))
146
+ )
147
+ if (unused.length === 0) break
148
+ const start = (unused.find(([, indexes]) => indexes.length === 1) ?? unused[0])[0]
149
+ const vertex = network.vertices[start]
150
+ parts.push(`M${pathNumber(vertex.x)} ${pathNumber(vertex.y)}`)
151
+ current = start
152
+ for (;;) {
153
+ const next = (degree.get(current) ?? []).find((index) => !used.has(index))
154
+ if (next === undefined) break
155
+ const segment = network.segments[next]
156
+ used.add(next)
157
+ const drawn = directedSegment(network, next, segment.start === current)
158
+ parts.push(drawn.command)
159
+ current = drawn.end
160
+ }
161
+ }
162
+ return parts.join('')
163
+ }
package/src/icons.ts CHANGED
@@ -149,7 +149,7 @@ export function useIconComponent(node: SceneNode, pen: PenNode, build: Build): v
149
149
  graph.updateNode(node.id, { componentId })
150
150
  populateInstanceChildren(graph, node.id, componentId)
151
151
  } else if (instanceMainComponent(graph, node)?.id !== componentId) {
152
- swapInstanceComponent(graph, node.id, componentId, { keepName: true })
152
+ swapInstanceComponent(graph, node.id, componentId, { keepName: true, restoreOverrides: false })
153
153
  // The layer keeps its own name rather than the icon's, which a saved file keeps as an override.
154
154
  recordInstanceOverride(graph, node.id, ['name'])
155
155
  } else if (showsReplacedGlyph(graph, node, node.componentId)) {
package/src/index.ts CHANGED
@@ -19,5 +19,5 @@ export {
19
19
  readPenFile,
20
20
  type PenReadOptions
21
21
  } from './read'
22
- export type { PenDocument, PenNode, PenOverride } from './schema'
22
+ export type { PenDocument, PenFont, PenNode, PenOverride } from './schema'
23
23
  export { penDocumentFromGraph, stringifyPenDocument, writePenDocument } from './write'
package/src/instances.ts CHANGED
@@ -30,11 +30,17 @@ function sources(graph: SceneGraph, node: SceneNode): Set<string> {
30
30
  return found
31
31
  }
32
32
 
33
+ /** The pen.dev layer a layer was built from, which a component swap stops naming. */
34
+ function penLayerId(build: Build, node: SceneNode): string | undefined {
35
+ return build.effective.get(node.id)?.id
36
+ }
37
+
33
38
  /** The copy in `root`'s layers made from the pen.dev layer `sourceId`, at any depth. */
34
- function findCopy(graph: SceneGraph, root: SceneNode, sourceId: string): SceneNode | undefined {
39
+ function findCopy(build: Build, root: SceneNode, sourceId: string): SceneNode | undefined {
40
+ const { graph } = build
35
41
  const queue = graph.getChildren(root.id)
36
42
  for (const node of queue) {
37
- if (sources(graph, node).has(sourceId)) return node
43
+ if (penLayerId(build, node) === sourceId || sources(graph, node).has(sourceId)) return node
38
44
  queue.push(...graph.getChildren(node.id))
39
45
  }
40
46
  return undefined
@@ -44,10 +50,10 @@ function findCopy(graph: SceneGraph, root: SceneNode, sourceId: string): SceneNo
44
50
  * The layer an override's key names: pen.dev IDs separated by `/`, each one inside the copy of the
45
51
  * instance the one before it names.
46
52
  */
47
- function resolvePath(graph: SceneGraph, instance: SceneNode, path: string): SceneNode | undefined {
53
+ function resolvePath(build: Build, instance: SceneNode, path: string): SceneNode | undefined {
48
54
  let current: SceneNode | undefined = instance
49
55
  for (const id of path.split('/')) {
50
- current = current ? findCopy(graph, current, id) : undefined
56
+ current = current ? findCopy(build, current, id) : undefined
51
57
  }
52
58
  return current
53
59
  }
@@ -178,12 +184,13 @@ function overrideLayer(
178
184
  inAncestorThemes(build, target, () => {
179
185
  const leave = merged.theme ? ctx.enterTheme(merged.theme) : undefined
180
186
  try {
181
- applyPenProperties(target, merged, build)
187
+ // Children that replace the layer's own decide its size, as a fit_content(N) fallback holds
188
+ // only while the layer is empty, so the old ones go first.
189
+ if (children) for (const childId of target.childIds) graph.deleteNode(childId)
190
+ applyPenProperties(target, children ? { ...merged, children } : merged, build)
182
191
  recordChangedFields(graph, target, before, fields)
183
192
  if (children) {
184
193
  const fillsSlot = instance !== undefined && claimSlot(build, instance, target)
185
- const replaced = target.childIds
186
- for (const childId of replaced) graph.deleteNode(childId)
187
194
  for (const child of children) createSceneNode(child, target.id, build)
188
195
  if (!fillsSlot) build.replaced.add(target.id)
189
196
  }
@@ -217,7 +224,7 @@ function applyDescendants(
217
224
  populate: Populate
218
225
  ): void {
219
226
  for (const [path, override] of Object.entries(descendants ?? {})) {
220
- const target = resolvePath(build.graph, instance, path)
227
+ const target = resolvePath(build, instance, path)
221
228
  if (!target) continue
222
229
  if (override.type) replaceLayer(build, target, override, populate)
223
230
  else overrideLayer(build, target, override, instance)
@@ -263,6 +270,9 @@ export function populateInstances(build: Build): void {
263
270
  recordOwnFields(graph, instance, ref)
264
271
  inheritCopyFields(build, instance)
265
272
  applyDescendants(build, instance, ref.descendants, populate)
273
+ // pen.dev draws a ref's own children in place of its component's, whether or not the
274
+ // component declares a `slot`; like an override's children, they detach the instance.
275
+ if (ref.children) overrideLayer(build, instance, { children: ref.children })
266
276
  // Before anything copies this instance, so the copies are of what it became.
267
277
  detachReplacingInstances(build)
268
278
  }
package/src/nodes.ts CHANGED
@@ -6,7 +6,9 @@ import type {
6
6
  SceneGraph,
7
7
  SceneNode
8
8
  } from '@pairdraw/scene-graph'
9
+ import { normalizeEffects } from '@pairdraw/scene-graph/effects'
9
10
  import { CORNER_FIELDS } from '@pairdraw/scene-graph/fields'
11
+ import type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
10
12
  import { fillSizingFields } from '@pairdraw/scene-graph/layout'
11
13
  import type { Color } from '@pairdraw/scene-graph/primitives'
12
14
 
@@ -57,6 +59,8 @@ export interface Build {
57
59
  /** Shader files the document's paints and effects name, by URL, as their source. */
58
60
  shaders: PenShaderSources | undefined
59
61
  icons: PenIconSource | undefined
62
+ /** The family and style of each font the document bundles, by the name its text gives it. */
63
+ fonts: ReadonlyMap<string, FontFamilyStyle>
60
64
  /** Reusable nodes by their pen.dev ID. */
61
65
  components: Map<string, PenNode>
62
66
  /** The pen.dev fields each layer was built from, its instance's and overrides' merged in. */
@@ -145,6 +149,11 @@ function applyAutoLayout(
145
149
  node.primaryAxisSizing = own(widthSizing)
146
150
  node.counterAxisSizing = own(heightSizing)
147
151
  }
152
+ // pen.dev keeps `gap` between children under `space_between`, as CSS does; auto layout drops it.
153
+ // A hugging frame has no free space to spread, so packing it from the start lays it out the same.
154
+ if (node.primaryAxisAlign === 'SPACE_BETWEEN' && node.primaryAxisSizing === 'HUG') {
155
+ node.primaryAxisAlign = 'MIN'
156
+ }
148
157
  }
149
158
 
150
159
  const PLACEMENT_FIELDS = ['x', 'y', 'rotation', 'flipX', 'flipY'] as const
@@ -323,12 +332,12 @@ export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build):
323
332
  // A line layer has no inside or outside; its stroke is centred on it.
324
333
  if (node.type === 'LINE')
325
334
  node.strokes = node.strokes.map((paint) => ({ ...paint, align: 'CENTER' }))
326
- node.effects = convertEffects(pen.effect, ctx, build.shaders)
335
+ node.effects = normalizeEffects(convertEffects(pen.effect, ctx, build.shaders))
327
336
  applyCornerRadius(node, pen.cornerRadius, ctx)
328
337
  applyPadding(node, pen.padding, ctx)
329
338
 
330
339
  // Text without a width resizes to its content, which laying out the document measures.
331
- if (isTextLike) applyTextProps(node, pen, ctx)
340
+ if (isTextLike) applyTextProps(node, pen, ctx, build.fonts)
332
341
 
333
342
  if (pen.type === 'icon') drawIconLayer(node, pen, build)
334
343
  if (pen.type === 'ellipse') node.arcData = ellipseArc(pen, ctx)
package/src/read.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import * as v from 'valibot'
2
2
 
3
3
  import { SceneGraph } from '@pairdraw/scene-graph'
4
+ import type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
4
5
 
5
6
  import { lineNetwork, pathNetwork } from './geometry'
6
7
  import { removeUnusedIconComponents } from './icons'
@@ -29,6 +30,12 @@ export interface PenReadOptions {
29
30
  shaders?: ReadonlyMap<string, string>
30
31
  /** Where icon glyphs come from; icons are empty frames without it. */
31
32
  icons?: PenIconSource
33
+ /**
34
+ * The family and style each bundled font file names itself with, by its `name` in the
35
+ * document's `fonts`. pen.dev registers a bundled file under that name, such as
36
+ * `Geist-SemiBold`, and its text uses it as the family; the text takes the file's own names.
37
+ */
38
+ fonts?: ReadonlyMap<string, FontFamilyStyle>
32
39
  /**
33
40
  * The documents the document imports, by alias, as `importedDocument` gives them. Their
34
41
  * variables join the document's as `<alias>:<name>`, and the components it uses, as
@@ -106,6 +113,7 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
106
113
  images: createImageStore(graph, options.images),
107
114
  shaders: options.shaders,
108
115
  icons: options.icons,
116
+ fonts: options.fonts ?? new Map(),
109
117
  components: new Map(),
110
118
  effective: new Map(),
111
119
  instances: new Map(),
@@ -119,7 +127,7 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
119
127
  for (const imported of imports.values())
120
128
  collectComponents(imported.doc.children, build.components)
121
129
 
122
- const page = graph.addPage(doc.children[0]?.name ?? 'Page 1')
130
+ const page = graph.addPage(doc.name ?? doc.children[0]?.name ?? 'Page 1')
123
131
  for (const child of doc.children) createSceneNode(child, page.id, build)
124
132
  const libraryRoots = createLibraryRoots(doc, imports, build, createSceneNode)
125
133
  populateInstances(build)
package/src/schema.ts CHANGED
@@ -136,10 +136,12 @@ const effectSchema = v.looseObject({
136
136
  })
137
137
 
138
138
  const sizeSchema = numSchema
139
+ // A tuple takes a longer array and drops the rest, and a union keeps its first match: four values
140
+ // go first, or the two-value tuple reads [top, right] and loses the bottom and left.
139
141
  const paddingSchema = v.union([
140
142
  numSchema,
141
- v.tuple([numSchema, numSchema]),
142
- v.tuple([numSchema, numSchema, numSchema, numSchema])
143
+ v.tuple([numSchema, numSchema, numSchema, numSchema]),
144
+ v.tuple([numSchema, numSchema])
143
145
  ])
144
146
  const cornerRadiusSchema = v.union([numSchema, v.array(numSchema)])
145
147
 
@@ -283,8 +285,14 @@ const variableSchema = v.looseObject({
283
285
  ])
284
286
  })
285
287
 
288
+ /** A font file the document bundles, which its text names by `name` as a family. */
289
+ const fontSchema = v.looseObject({ name: strSchema, url: strSchema })
290
+
286
291
  const penDocumentSchema = v.looseObject({
287
292
  version: v.optional(strSchema),
293
+ // The page's name. The format is single-page, so it belongs to the document.
294
+ name: v.optional(strSchema),
295
+ fonts: v.optional(v.array(fontSchema)),
288
296
  themes: v.optional(v.record(strSchema, v.array(strSchema))),
289
297
  imports: v.optional(v.record(strSchema, strSchema)),
290
298
  variables: v.optional(v.record(strSchema, variableSchema)),
@@ -292,6 +300,7 @@ const penDocumentSchema = v.looseObject({
292
300
  })
293
301
 
294
302
  export type PenDocument = v.InferOutput<typeof penDocumentSchema>
303
+ export type PenFont = v.InferOutput<typeof fontSchema>
295
304
  export type PenVariable = v.InferOutput<typeof variableSchema>
296
305
  export type PenVariableScalar = v.InferOutput<typeof variableScalarSchema>
297
306
  export type PenPaint = v.InferOutput<typeof paintSchema>
package/src/text.ts CHANGED
@@ -1,4 +1,5 @@
1
1
  import type { SceneNode, StyleRun, TextAlignVertical, TextAutoResize } from '@pairdraw/scene-graph'
2
+ import { parseFontStyle, type FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
2
3
  import { percentLength, pixelLength } from '@pairdraw/scene-graph/text'
3
4
 
4
5
  import type { PenNode } from './schema'
@@ -55,7 +56,12 @@ const TEXT_GROWTH: Partial<Record<string, TextAutoResize>> = {
55
56
  * as pen.dev shows it. pen.dev 2.21 draws no underline, strikethrough, or text stroke, so those
56
57
  * are left out to match it. An `href` is kept as a link, drawn without an underline.
57
58
  */
58
- export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext): void {
59
+ export function applyTextProps(
60
+ node: SceneNode,
61
+ pen: PenNode,
62
+ ctx: VarContext,
63
+ fonts: ReadonlyMap<string, FontFamilyStyle>
64
+ ): void {
59
65
  const isIconFont = pen.type === 'icon_font'
60
66
  node.text = isIconFont ? (pen.iconFontName ?? '') : (pen.content ?? '')
61
67
  node.fontFamily = isIconFont
@@ -68,6 +74,20 @@ export function applyTextProps(node: SceneNode, pen: PenNode, ctx: VarContext):
68
74
  node.fontWeight = fontWeight(weight, ctx)
69
75
  bindIfVar(node, 'fontWeight', weight, ctx)
70
76
  node.italic = resolveString(pen.fontStyle, ctx)?.toLowerCase() === 'italic'
77
+ // A bundled font's name stands for one face of the family its file names.
78
+ const bundled = isIconFont ? undefined : fonts.get(node.fontFamily)
79
+ if (bundled) {
80
+ const { weight, italic } = parseFontStyle(bundled.style)
81
+ Object.assign(node, {
82
+ fontFamily: bundled.family,
83
+ fontStyle: bundled.style,
84
+ fontWeight: weight,
85
+ italic
86
+ })
87
+ // The bound name is the pen-only one no font is registered under, so a later reconcile
88
+ // would restore a family nothing draws with. The bundled face owns the family now.
89
+ delete node.boundVariables.fontFamily
90
+ }
71
91
  node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'
72
92
  node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'
73
93
  // pen.dev's line height multiplies the font size, so it follows the size as a percent.
package/src/write.ts CHANGED
@@ -20,6 +20,7 @@ import { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene
20
20
  import { layoutSizing } from '@pairdraw/scene-graph/layout'
21
21
  import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
22
22
 
23
+ import { networkToSVGPath } from './geometry'
23
24
  import { PEN_PLUGIN_DATA_NAMESPACE } from './plugin-data'
24
25
  import type {
25
26
  PenDocument,
@@ -502,6 +503,8 @@ function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode)
502
503
  result.rotation = rounded(node.flipX !== node.flipY ? node.rotation : -node.rotation)
503
504
  if (node.flipX) result.flipX = true
504
505
  if (node.flipY) result.flipY = true
506
+ const theme = themeFields(state, node)
507
+ if (theme) result.theme = theme
505
508
  const fill = paintsOf(state, node, 'fills', node.fills)
506
509
  if (fill !== undefined) result.fill = fill
507
510
  Object.assign(
@@ -512,6 +515,20 @@ function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode)
512
515
  textFields(state, node)
513
516
  )
514
517
  }
518
+ /**
519
+ * A layer's variable mode assignments, by the names pen writes: the collection's name and the
520
+ * mode's. A mode the document no longer holds is left out.
521
+ */
522
+ function themeFields(state: PenWriteState, node: SceneNode): Record<string, string> | undefined {
523
+ const theme: Record<string, string> = {}
524
+ for (const [collectionId, modeId] of Object.entries(node.variableModes)) {
525
+ const collection = state.collections.get(collectionId)
526
+ const mode = collection?.modes.find((candidate) => candidate.modeId === modeId)
527
+ if (collection && mode) theme[collection.name] = mode.name
528
+ }
529
+ return Object.keys(theme).length > 0 ? theme : undefined
530
+ }
531
+
515
532
  function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {
516
533
  if (
517
534
  node.type === 'TEXT' &&
@@ -537,6 +554,17 @@ function writeNode(state: PenWriteState, node: SceneNode): PenNode {
537
554
  const result: PenNode = { id: node.id, type: nodeType(node) }
538
555
  basicNodeFields(state, node, result)
539
556
  if (semanticNodeFields(state, node, result)) return result
557
+ // Written after the preserved pen fields, so a regenerated path wins over the source text.
558
+ if (node.type === 'VECTOR' && node.vectorNetwork && node.vectorNetwork.segments.length > 0) {
559
+ const geometry = networkToSVGPath(node.vectorNetwork)
560
+ if (geometry) {
561
+ result.geometry = geometry
562
+ // The written box is rounded; the view box names the same box, so the path maps onto it
563
+ // one to one rather than being scaled into a rounded height on the next read.
564
+ result.viewBox = [0, 0, rounded(node.width), rounded(node.height)]
565
+ if (node.vectorNetwork.regions[0]?.windingRule === 'EVENODD') result.fillRule = 'evenodd'
566
+ }
567
+ }
540
568
  const children =
541
569
  node.type === 'STICKY'
542
570
  ? []
@@ -581,7 +609,7 @@ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
581
609
  .filter((node) => !node.internalOnly)
582
610
  .map((node) => writeNode(state, node))
583
611
  )
584
- const document: PenDocument = { version: PEN_VERSION, children }
612
+ const document: PenDocument = { version: PEN_VERSION, name: graph.getPages()[0]?.name, children }
585
613
  const variablesValue = variablesOf(state)
586
614
  if (variablesValue) document.variables = variablesValue
587
615
  const themes = themesOf(state)