@pairdraw/pen 0.20.0 → 0.21.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/write.ts CHANGED
@@ -1,5 +1,9 @@
1
+ import { isEqual } from 'es-toolkit'
2
+ import { fromUint8Array } from 'js-base64'
3
+
1
4
  import type {
2
5
  BlendMode,
6
+ EnabledLibraryBinding,
3
7
  Fill,
4
8
  GradientTransform,
5
9
  LayoutAlign,
@@ -15,17 +19,25 @@ import type {
15
19
  import { SceneGraph as SceneGraphValue } from '@pairdraw/scene-graph'
16
20
  import { colorToHex, colorToHex8 } from '@pairdraw/scene-graph/color'
17
21
  import { getNodeLocalMatrix } from '@pairdraw/scene-graph/coordinate'
22
+ import { readDesignMemory } from '@pairdraw/scene-graph/design-memory'
18
23
  import { stickySublayers } from '@pairdraw/scene-graph/generated'
19
24
  import { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene-graph/gradient'
25
+ import { imageMimeType } from '@pairdraw/scene-graph/images'
20
26
  import { layoutSizing } from '@pairdraw/scene-graph/layout'
21
27
  import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
28
+ import { readStoredStatusWorkflow } from '@pairdraw/scene-graph/statuses'
22
29
  import { readTokenSources, type TokenSource } from '@pairdraw/scene-graph/token-sources'
23
30
 
31
+ import { readPenImports, readSourceLibraryPublication } from './document-libraries'
24
32
  import { networkToSVGPath } from './geometry'
25
- import { PEN_PLUGIN_DATA_NAMESPACE } from './plugin-data'
33
+ import { penCropTransform } from './images'
34
+ import { importedComponentIds } from './library'
35
+ import { PEN_PLUGIN_DATA_NAMESPACE, readIconOrigin } from './plugin-data'
26
36
  import type {
27
37
  PenDocument,
28
38
  PenEffect,
39
+ PenOverride,
40
+ PenImagePaint,
29
41
  PenNode,
30
42
  PenNumber,
31
43
  PenPaint,
@@ -60,7 +72,75 @@ type PenWriteState = {
60
72
  collections: ReadonlyMap<string, VariableCollection>
61
73
  /** Nodes the document will contain, so an instance refs only a component that is written. */
62
74
  writtenIds: ReadonlySet<string>
75
+ /** Components the file resolves through its `imports`, which a ref may name without writing them. */
76
+ importedIds: ReadonlySet<string>
77
+ /** What the file cannot hold, reported once writing leaves it out. */
78
+ warnings: string[]
79
+ /** The same facts as kinds, for a host that shows them in its own language. */
80
+ details: PenWriteWarning[]
81
+ drops: {
82
+ images: number
83
+ effects: number
84
+ filters: number
85
+ scroll: number
86
+ fontFeatures: number
87
+ }
88
+ }
89
+
90
+ /**
91
+ * What a written `.pen` file could not hold, as facts rather than a sentence: the app shows these
92
+ * in the reader's language, while the CLI and MCP print `penWriteWarningText` of each.
93
+ */
94
+ export type PenWriteWarning =
95
+ | { kind: 'merged-pages'; pages: number; name: string }
96
+ | { kind: 'display-p3-colors' }
97
+ | { kind: 'library-definitions'; count: number }
98
+ | { kind: 'missing-image-fills'; count: number }
99
+ | { kind: 'dropped-effects'; count: number }
100
+ | { kind: 'dropped-filters'; count: number }
101
+ | { kind: 'dropped-scroll'; count: number }
102
+ | { kind: 'dropped-font-features'; count: number }
103
+
104
+ /** The English sentence a write warning has always been reported as. */
105
+ export function penWriteWarningText(warning: PenWriteWarning): string {
106
+ switch (warning.kind) {
107
+ case 'merged-pages':
108
+ return `Pencil.dev files hold one page; ${warning.pages} pages were merged into “${warning.name}”.`
109
+ case 'display-p3-colors':
110
+ return 'Colors are written as sRGB hex, the only form a Pencil.dev file holds; a Display P3 color outside sRGB comes out as the nearest sRGB color.'
111
+ case 'library-definitions':
112
+ return `Library components came from ${warning.count} enabled ${warning.count === 1 ? 'library' : 'libraries'}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`
113
+ case 'missing-image-fills':
114
+ return `Image fills with missing image data were left out (${warning.count}); Pencil.dev files cannot hold a paint without its image.`
115
+ case 'dropped-effects':
116
+ return `Noise and texture effects were left out (${warning.count}); Pencil.dev files have no form for them.`
117
+ case 'dropped-filters':
118
+ return `Image adjustment filters were left out (${warning.count}); Pencil.dev files have no form for them.`
119
+ case 'dropped-scroll':
120
+ return `Scroll overflow was left out (${warning.count}); Pencil.dev files have no form for it.`
121
+ case 'dropped-font-features':
122
+ return `OpenType font features were left out (${warning.count}); Pencil.dev files have no form for them.`
123
+ default: {
124
+ const unhandled: never = warning
125
+ throw new Error(`Unhandled pen write warning: ${String(unhandled)}`)
126
+ }
127
+ }
128
+ }
129
+
130
+ /** Records a warning as its sentence and its kind, in the order it was found. */
131
+ function emit(state: PenWriteState, warning: PenWriteWarning): void {
132
+ state.details.push(warning)
133
+ state.warnings.push(penWriteWarningText(warning))
134
+ }
135
+
136
+ /** What a caller learns about content a written `.pen` file cannot hold. */
137
+ export interface PenWriteOptions {
138
+ /** Collects one sentence per kind of content left out, in place of silently losing it. */
139
+ warnings?: string[]
140
+ /** Collects the same facts as kinds, for a host that shows them in its own language. */
141
+ warningDetails?: PenWriteWarning[]
63
142
  }
143
+
64
144
  /** Snaps matrix values that are within floating-point noise of an integer. */
65
145
  function snapCoordinate(value: number): number {
66
146
  return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value
@@ -174,8 +254,31 @@ function gradientPaint(fill: Fill): PenPaint {
174
254
  }
175
255
  }
176
256
 
177
- function imagePaint(fill: Fill): PenPaint {
178
- return { type: 'image', ...paintBase(fill), url: fill.imageHash }
257
+ /**
258
+ * An image fill as a pen.dev paint whose image travels with the file: Pencil.dev opens a data URL
259
+ * and the scene graph keeps the bytes, so the fill is written whole instead of pointing at a hash
260
+ * no reader can resolve. A paint whose bytes are gone is left out and reported, never written as a
261
+ * dead URL.
262
+ */
263
+ function imagePaint(state: PenWriteState, fill: Fill): PenPaint | null {
264
+ const bytes = fill.imageHash ? state.graph.images.get(fill.imageHash) : undefined
265
+ if (!bytes) {
266
+ state.drops.images++
267
+ return null
268
+ }
269
+ if (fill.filters) state.drops.filters++
270
+ const paint: PenImagePaint = {
271
+ type: 'image',
272
+ ...paintBase(fill),
273
+ url: `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`
274
+ }
275
+ if (fill.imageScaleMode === 'FIT') paint.mode = 'contain'
276
+ if (fill.imageScaleMode === 'CROP') {
277
+ paint.mode = 'stretch'
278
+ const transform = fill.imageTransform && penCropTransform(fill.imageTransform)
279
+ if (transform) paint.transform = transform
280
+ }
281
+ return paint
179
282
  }
180
283
 
181
284
  function penPaint(
@@ -184,13 +287,13 @@ function penPaint(
184
287
  field: 'fills' | 'strokes',
185
288
  fill: Fill,
186
289
  index: number
187
- ): PenPaint {
290
+ ): PenPaint | null {
188
291
  if (fill.type === 'SOLID') {
189
292
  const binding = variableReference(state, node.boundVariables[`${field}/${index}/color`])
190
293
  return { type: 'color', color: binding ?? colorValue(fill.color), ...paintBase(fill) }
191
294
  }
192
295
  if (fill.type.startsWith('GRADIENT_')) return gradientPaint(fill)
193
- if (fill.type === 'IMAGE') return imagePaint(fill)
296
+ if (fill.type === 'IMAGE') return imagePaint(state, fill)
194
297
  return { type: fill.type.toLowerCase(), ...paintBase(fill) }
195
298
  }
196
299
 
@@ -201,7 +304,10 @@ function paintsOf(
201
304
  paints: readonly Fill[]
202
305
  ): PenPaints | undefined {
203
306
  if (paints.length === 0) return undefined
204
- const result = paints.map((paint, index) => penPaint(state, node, field, paint, index))
307
+ const result = paints
308
+ .map((paint, index) => penPaint(state, node, field, paint, index))
309
+ .filter((paint): paint is PenPaint => paint !== null)
310
+ if (result.length === 0) return undefined
205
311
  return result.length === 1 ? result[0] : result
206
312
  }
207
313
 
@@ -465,9 +571,9 @@ function penVariable(
465
571
  }
466
572
 
467
573
  function variablesOf(state: PenWriteState): Record<string, PenVariable> | undefined {
468
- if (state.graph.variables.size === 0) return undefined
574
+ if (state.variables.size === 0) return undefined
469
575
  return Object.fromEntries(
470
- [...state.graph.variables.values()]
576
+ [...state.variables.values()]
471
577
  .sort((left, right) => left.name.localeCompare(right.name))
472
578
  .map((variable) => [
473
579
  variable.name,
@@ -477,9 +583,9 @@ function variablesOf(state: PenWriteState): Record<string, PenVariable> | undefi
477
583
  }
478
584
 
479
585
  function themesOf(state: PenWriteState): PenDocument['themes'] {
480
- if (state.graph.variableCollections.size === 0) return undefined
586
+ if (state.collections.size === 0) return undefined
481
587
  return Object.fromEntries(
482
- [...state.graph.variableCollections.values()]
588
+ [...state.collections.values()]
483
589
  .sort((left, right) => left.name.localeCompare(right.name))
484
590
  .map((collection) => [collection.name, collection.modes.map((mode) => mode.name)])
485
591
  )
@@ -487,7 +593,7 @@ function themesOf(state: PenWriteState): PenDocument['themes'] {
487
593
 
488
594
  /** The selector each mode applies in, by collection and mode name; none when no mode names one. */
489
595
  function modeConditionsOf(state: PenWriteState): PenDocument['modeConditions'] {
490
- const entries = [...state.graph.variableCollections.values()].flatMap((collection) => {
596
+ const entries = [...state.collections.values()].flatMap((collection) => {
491
597
  const modes = collection.modes.flatMap((mode) =>
492
598
  mode.condition ? [[mode.name, mode.condition] as const] : []
493
599
  )
@@ -545,6 +651,125 @@ function themeFields(state: PenWriteState, node: SceneNode): Record<string, stri
545
651
  return Object.keys(theme).length > 0 ? theme : undefined
546
652
  }
547
653
 
654
+ /**
655
+ * The pen fields an instance override writes: what it changes on a layer, not the placement and
656
+ * layout a reopen recalculates from the component and the boxes around it.
657
+ */
658
+ const OVERRIDABLE_FIELDS: ReadonlySet<string> = new Set([
659
+ 'content',
660
+ 'fill',
661
+ 'stroke',
662
+ 'strokeWidth',
663
+ 'cornerRadius',
664
+ 'effect',
665
+ 'opacity',
666
+ 'enabled',
667
+ 'fontFamily',
668
+ 'fontSize',
669
+ 'fontWeight',
670
+ 'fontStyle',
671
+ 'textAlign',
672
+ 'textAlignVertical',
673
+ 'lineHeight',
674
+ 'letterSpacing',
675
+ 'href'
676
+ ])
677
+
678
+ /**
679
+ * The path a copy sits at in its component, from the instance down: the ids of the layers it
680
+ * copies, as pen names a `descendants` override. A copy that swapped its component copies `swapOf`
681
+ * instead of the component it draws.
682
+ */
683
+ function overridePath(
684
+ graph: SceneGraph,
685
+ instanceId: string,
686
+ copyId: string,
687
+ swapOf?: string
688
+ ): string | null {
689
+ const parts: string[] = []
690
+ let current = graph.getNode(copyId)
691
+ while (current && current.id !== instanceId) {
692
+ const id = current.id === copyId && swapOf ? swapOf : current.componentId
693
+ if (!id) return null
694
+ parts.unshift(id)
695
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
696
+ }
697
+ return current ? parts.join('/') : null
698
+ }
699
+
700
+ /**
701
+ * The fields a swap override names an icon by: pen carries the glyph, not the component drawn.
702
+ */
703
+ function iconOverride(graph: SceneGraph, componentId: string | null): PenOverride | undefined {
704
+ const origin = readIconOrigin(componentId ? graph.getNode(componentId) : undefined)
705
+ if (!origin) return undefined
706
+ const override: PenOverride = { icon: origin.icon }
707
+ if (origin.library) override.library = origin.library
708
+ if (origin.weight !== undefined) override.weight = origin.weight
709
+ return override
710
+ }
711
+
712
+ /**
713
+ * The overrides an instance writes, and whether one of them is a swap the file cannot name. A
714
+ * layer that swapped its component draws another component than the one it copies, which pen holds
715
+ * as a glyph for an icon; any other swap is what the instance shows, not what it links to.
716
+ */
717
+ function instanceDescendants(
718
+ state: PenWriteState,
719
+ node: SceneNode
720
+ ): { descendants?: Record<string, PenOverride>; unrepresentable: boolean } {
721
+ const overridden = [...node.instanceOverrides.descendants.keys()]
722
+ if (overridden.length === 0) return { unrepresentable: false }
723
+ // Comparing writes fields the moment a document writes them, but their drops are counted once.
724
+ const probe: PenWriteState = {
725
+ ...state,
726
+ drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }
727
+ }
728
+ const descendants: Record<string, PenOverride> = {}
729
+ let unrepresentable = false
730
+ for (const copyId of overridden) {
731
+ const overrides = node.instanceOverrides.descendants.get(copyId)
732
+ const swapped = overrides?.has('componentId') === true
733
+ const swapOf = swapped ? overrides.get('sourceComponentId') : undefined
734
+ const path = overridePath(
735
+ state.graph,
736
+ node.id,
737
+ copyId,
738
+ typeof swapOf === 'string' ? swapOf : undefined
739
+ )
740
+ const copy = state.graph.getNode(copyId)
741
+ if (!path || !copy) {
742
+ unrepresentable = true
743
+ continue
744
+ }
745
+ if (swapped) {
746
+ const icon = iconOverride(state.graph, copy.componentId)
747
+ if (!icon) {
748
+ unrepresentable = true
749
+ continue
750
+ }
751
+ descendants[path] = icon
752
+ continue
753
+ }
754
+ const master = copy.componentId ? state.graph.getNode(copy.componentId) : undefined
755
+ if (!master) {
756
+ unrepresentable = true
757
+ continue
758
+ }
759
+ const own = writeNode(probe, copy)
760
+ const base = writeNode(probe, master)
761
+ const override: PenOverride = {}
762
+ for (const field of OVERRIDABLE_FIELDS) {
763
+ if (!isEqual(own[field], base[field])) override[field] = own[field]
764
+ }
765
+ if (Object.keys(override).length > 0) descendants[path] = override
766
+ }
767
+ return {
768
+ descendants: Object.keys(descendants).length > 0 ? descendants : undefined,
769
+ unrepresentable
770
+ }
771
+ }
772
+
548
773
  function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {
549
774
  if (
550
775
  node.type === 'TEXT' &&
@@ -554,20 +779,37 @@ function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNo
554
779
  result.width = 'fit_content'
555
780
  if (node.type === 'STICKY') result.content = stickySublayers(state.graph, node)?.body.text ?? ''
556
781
  penPluginFields(node, result)
557
- // Shader effects have no pen.dev form yet; dropping them keeps the file loadable.
558
- const effects = node.effects.filter((effect): effect is ShadowEffect => effect.type !== 'SHADER')
782
+ // Shader, noise, and texture effects have no pen.dev form; dropping them keeps the file loadable.
783
+ const effects = node.effects.filter((effect): effect is ShadowEffect => {
784
+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') return true
785
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') return true
786
+ if (effect.type === 'NOISE' || effect.type === 'TEXTURE') state.drops.effects++
787
+ return false
788
+ })
559
789
  if (effects.length > 0)
560
790
  result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf)
561
791
  if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') result.reusable = true
562
- if (node.type === 'INSTANCE' && node.componentId && state.writtenIds.has(node.componentId)) {
792
+ if (
793
+ node.type === 'INSTANCE' &&
794
+ node.componentId &&
795
+ (state.writtenIds.has(node.componentId) || state.importedIds.has(node.componentId))
796
+ ) {
797
+ const overrides = instanceDescendants(state, node)
798
+ // The file names a swap through the library it imports; one it cannot name is written as the
799
+ // layers the instance draws, which keeps what it shows, as before the library work.
800
+ if (overrides.unrepresentable && !state.writtenIds.has(node.componentId)) return false
563
801
  result.type = 'ref'
564
802
  result.ref = node.componentId
803
+ if (overrides.descendants) result.descendants = overrides.descendants
565
804
  return true
566
805
  }
567
806
  return false
568
807
  }
569
808
  function writeNode(state: PenWriteState, node: SceneNode): PenNode {
809
+ if (node.overflowDirection !== 'NONE') state.drops.scroll++
810
+ if (node.fontFeatures.length > 0) state.drops.fontFeatures++
570
811
  const result: PenNode = { id: node.id, type: nodeType(node) }
812
+ if (node.status !== null) result.status = node.status
571
813
  basicNodeFields(state, node, result)
572
814
  if (semanticNodeFields(state, node, result)) return result
573
815
  // Written after the preserved pen fields, so a regenerated path wins over the source text.
@@ -612,20 +854,35 @@ function sortKeys(value: unknown): unknown {
612
854
  return value
613
855
  }
614
856
 
615
- export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
857
+ export function penDocumentFromGraph(
858
+ graph: SceneGraph,
859
+ options: PenWriteOptions = {}
860
+ ): PenDocument {
861
+ // A deleted variable has no state `.pen` can hold, so layers bound to it write its value.
616
862
  const variables = new Map<string, Variable>()
617
- for (const variable of graph.variables.values()) variables.set(variable.id, variable)
863
+ for (const variable of graph.getLiveVariables()) variables.set(variable.id, variable)
618
864
  const collections = new Map<string, VariableCollection>()
619
- for (const collection of graph.variableCollections.values())
620
- collections.set(collection.id, collection)
621
- const state: PenWriteState = { graph, variables, collections, writtenIds: writtenNodeIds(graph) }
622
- const children = graph.getPages().flatMap((page) =>
865
+ for (const collection of graph.getLiveCollections()) collections.set(collection.id, collection)
866
+ // The file declares its imports, so a ref to a component one of them defines resolves on reopen.
867
+ const imports = readPenImports(graph)
868
+ const state: PenWriteState = {
869
+ graph,
870
+ variables,
871
+ collections,
872
+ writtenIds: writtenNodeIds(graph),
873
+ importedIds: importedComponentIds(graph, imports ?? {}),
874
+ warnings: options.warnings ?? [],
875
+ details: [],
876
+ drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }
877
+ }
878
+ const pages = graph.getPages()
879
+ const children = pages.flatMap((page) =>
623
880
  graph
624
881
  .getChildren(page.id)
625
882
  .filter((node) => !node.internalOnly)
626
883
  .map((node) => writeNode(state, node))
627
884
  )
628
- const document: PenDocument = { version: PEN_VERSION, name: graph.getPages()[0]?.name, children }
885
+ const document: PenDocument = { version: PEN_VERSION, name: pages[0]?.name, children }
629
886
  const variablesValue = variablesOf(state)
630
887
  if (variablesValue) document.variables = variablesValue
631
888
  const themes = themesOf(state)
@@ -657,14 +914,63 @@ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
657
914
  return refreshed
658
915
  })
659
916
  if (tokenSources.length > 0) document.tokenSources = tokenSources
917
+ const designMemory = readDesignMemory(graph)
918
+ if (designMemory) document.designMemory = designMemory
919
+ // Only a document that chose its statuses writes them: the default falls back on read.
920
+ const statuses = readStoredStatusWorkflow(graph)
921
+ if (statuses) document.statuses = statuses
922
+ if (imports) document.imports = imports
923
+ const enabledLibraries = enabledLibrariesOf(graph, state)
924
+ if (enabledLibraries) document.enabledLibraries = enabledLibraries
925
+ const publication = readSourceLibraryPublication(graph)
926
+ if (publication) document.sourceLibraryPublication = publication
927
+ if (pages.length > 1) {
928
+ const name = document.name ?? 'Page 1'
929
+ emit(state, { kind: 'merged-pages', pages: pages.length, name })
930
+ }
931
+ if (graph.documentColorSpace === 'display-p3') {
932
+ emit(state, { kind: 'display-p3-colors' })
933
+ }
934
+ reportDrops(state)
935
+ options.warningDetails?.push(...state.details)
660
936
  return document
661
937
  }
662
938
 
939
+ /**
940
+ * The library bindings a `.pen` file records, or null when the document has none. The definitions
941
+ * live on the hidden page, which a Pencil.dev file cannot hold, so the file records the bindings
942
+ * and says that the components it was built from come back as placeholders.
943
+ */
944
+ function enabledLibrariesOf(
945
+ graph: SceneGraph,
946
+ state: PenWriteState
947
+ ): EnabledLibraryBinding[] | null {
948
+ const bindings = [...graph.enabledLibraries.values()]
949
+ if (bindings.length === 0) return null
950
+ const enabled = bindings.filter((binding) => binding.enabled).length
951
+ if (enabled > 0) emit(state, { kind: 'library-definitions', count: enabled })
952
+ return bindings
953
+ }
954
+
955
+ /** Adds one sentence for each kind of content the written file had to leave out. */
956
+ function reportDrops(state: PenWriteState): void {
957
+ const { images, effects, filters, scroll, fontFeatures } = state.drops
958
+ if (images > 0) emit(state, { kind: 'missing-image-fills', count: images })
959
+ if (effects > 0) emit(state, { kind: 'dropped-effects', count: effects })
960
+ if (filters > 0) emit(state, { kind: 'dropped-filters', count: filters })
961
+ if (scroll > 0) emit(state, { kind: 'dropped-scroll', count: scroll })
962
+ if (fontFeatures > 0) emit(state, { kind: 'dropped-font-features', count: fontFeatures })
963
+ }
964
+
663
965
  export function stringifyPenDocument(document: PenDocument): string {
664
966
  return `${JSON.stringify(sortKeys(document), null, 2)}\n`
665
967
  }
666
968
 
667
- export function writePenDocument(source: PenDocument | SceneGraph): string {
668
- const document = source instanceof SceneGraphValue ? penDocumentFromGraph(source) : source
969
+ export function writePenDocument(
970
+ source: PenDocument | SceneGraph,
971
+ options: PenWriteOptions = {}
972
+ ): string {
973
+ const document =
974
+ source instanceof SceneGraphValue ? penDocumentFromGraph(source, options) : source
669
975
  return stringifyPenDocument(document)
670
976
  }