@pairdraw/pen 0.20.0 → 0.21.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.
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,25 @@ 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
+ drops: {
80
+ images: number
81
+ effects: number
82
+ filters: number
83
+ scroll: number
84
+ fontFeatures: number
85
+ }
86
+ }
87
+
88
+ /** What a caller learns about content a written `.pen` file cannot hold. */
89
+ export interface PenWriteOptions {
90
+ /** Collects one sentence per kind of content left out, in place of silently losing it. */
91
+ warnings?: string[]
63
92
  }
93
+
64
94
  /** Snaps matrix values that are within floating-point noise of an integer. */
65
95
  function snapCoordinate(value: number): number {
66
96
  return Math.abs(value - Math.round(value)) < 1e-9 ? Math.round(value) : value
@@ -174,8 +204,31 @@ function gradientPaint(fill: Fill): PenPaint {
174
204
  }
175
205
  }
176
206
 
177
- function imagePaint(fill: Fill): PenPaint {
178
- return { type: 'image', ...paintBase(fill), url: fill.imageHash }
207
+ /**
208
+ * An image fill as a pen.dev paint whose image travels with the file: Pencil.dev opens a data URL
209
+ * and the scene graph keeps the bytes, so the fill is written whole instead of pointing at a hash
210
+ * no reader can resolve. A paint whose bytes are gone is left out and reported, never written as a
211
+ * dead URL.
212
+ */
213
+ function imagePaint(state: PenWriteState, fill: Fill): PenPaint | null {
214
+ const bytes = fill.imageHash ? state.graph.images.get(fill.imageHash) : undefined
215
+ if (!bytes) {
216
+ state.drops.images++
217
+ return null
218
+ }
219
+ if (fill.filters) state.drops.filters++
220
+ const paint: PenImagePaint = {
221
+ type: 'image',
222
+ ...paintBase(fill),
223
+ url: `data:${imageMimeType(bytes)};base64,${fromUint8Array(bytes)}`
224
+ }
225
+ if (fill.imageScaleMode === 'FIT') paint.mode = 'contain'
226
+ if (fill.imageScaleMode === 'CROP') {
227
+ paint.mode = 'stretch'
228
+ const transform = fill.imageTransform && penCropTransform(fill.imageTransform)
229
+ if (transform) paint.transform = transform
230
+ }
231
+ return paint
179
232
  }
180
233
 
181
234
  function penPaint(
@@ -184,13 +237,13 @@ function penPaint(
184
237
  field: 'fills' | 'strokes',
185
238
  fill: Fill,
186
239
  index: number
187
- ): PenPaint {
240
+ ): PenPaint | null {
188
241
  if (fill.type === 'SOLID') {
189
242
  const binding = variableReference(state, node.boundVariables[`${field}/${index}/color`])
190
243
  return { type: 'color', color: binding ?? colorValue(fill.color), ...paintBase(fill) }
191
244
  }
192
245
  if (fill.type.startsWith('GRADIENT_')) return gradientPaint(fill)
193
- if (fill.type === 'IMAGE') return imagePaint(fill)
246
+ if (fill.type === 'IMAGE') return imagePaint(state, fill)
194
247
  return { type: fill.type.toLowerCase(), ...paintBase(fill) }
195
248
  }
196
249
 
@@ -201,7 +254,10 @@ function paintsOf(
201
254
  paints: readonly Fill[]
202
255
  ): PenPaints | undefined {
203
256
  if (paints.length === 0) return undefined
204
- const result = paints.map((paint, index) => penPaint(state, node, field, paint, index))
257
+ const result = paints
258
+ .map((paint, index) => penPaint(state, node, field, paint, index))
259
+ .filter((paint): paint is PenPaint => paint !== null)
260
+ if (result.length === 0) return undefined
205
261
  return result.length === 1 ? result[0] : result
206
262
  }
207
263
 
@@ -465,9 +521,9 @@ function penVariable(
465
521
  }
466
522
 
467
523
  function variablesOf(state: PenWriteState): Record<string, PenVariable> | undefined {
468
- if (state.graph.variables.size === 0) return undefined
524
+ if (state.variables.size === 0) return undefined
469
525
  return Object.fromEntries(
470
- [...state.graph.variables.values()]
526
+ [...state.variables.values()]
471
527
  .sort((left, right) => left.name.localeCompare(right.name))
472
528
  .map((variable) => [
473
529
  variable.name,
@@ -477,9 +533,9 @@ function variablesOf(state: PenWriteState): Record<string, PenVariable> | undefi
477
533
  }
478
534
 
479
535
  function themesOf(state: PenWriteState): PenDocument['themes'] {
480
- if (state.graph.variableCollections.size === 0) return undefined
536
+ if (state.collections.size === 0) return undefined
481
537
  return Object.fromEntries(
482
- [...state.graph.variableCollections.values()]
538
+ [...state.collections.values()]
483
539
  .sort((left, right) => left.name.localeCompare(right.name))
484
540
  .map((collection) => [collection.name, collection.modes.map((mode) => mode.name)])
485
541
  )
@@ -487,7 +543,7 @@ function themesOf(state: PenWriteState): PenDocument['themes'] {
487
543
 
488
544
  /** The selector each mode applies in, by collection and mode name; none when no mode names one. */
489
545
  function modeConditionsOf(state: PenWriteState): PenDocument['modeConditions'] {
490
- const entries = [...state.graph.variableCollections.values()].flatMap((collection) => {
546
+ const entries = [...state.collections.values()].flatMap((collection) => {
491
547
  const modes = collection.modes.flatMap((mode) =>
492
548
  mode.condition ? [[mode.name, mode.condition] as const] : []
493
549
  )
@@ -545,6 +601,125 @@ function themeFields(state: PenWriteState, node: SceneNode): Record<string, stri
545
601
  return Object.keys(theme).length > 0 ? theme : undefined
546
602
  }
547
603
 
604
+ /**
605
+ * The pen fields an instance override writes: what it changes on a layer, not the placement and
606
+ * layout a reopen recalculates from the component and the boxes around it.
607
+ */
608
+ const OVERRIDABLE_FIELDS: ReadonlySet<string> = new Set([
609
+ 'content',
610
+ 'fill',
611
+ 'stroke',
612
+ 'strokeWidth',
613
+ 'cornerRadius',
614
+ 'effect',
615
+ 'opacity',
616
+ 'enabled',
617
+ 'fontFamily',
618
+ 'fontSize',
619
+ 'fontWeight',
620
+ 'fontStyle',
621
+ 'textAlign',
622
+ 'textAlignVertical',
623
+ 'lineHeight',
624
+ 'letterSpacing',
625
+ 'href'
626
+ ])
627
+
628
+ /**
629
+ * The path a copy sits at in its component, from the instance down: the ids of the layers it
630
+ * copies, as pen names a `descendants` override. A copy that swapped its component copies `swapOf`
631
+ * instead of the component it draws.
632
+ */
633
+ function overridePath(
634
+ graph: SceneGraph,
635
+ instanceId: string,
636
+ copyId: string,
637
+ swapOf?: string
638
+ ): string | null {
639
+ const parts: string[] = []
640
+ let current = graph.getNode(copyId)
641
+ while (current && current.id !== instanceId) {
642
+ const id = current.id === copyId && swapOf ? swapOf : current.componentId
643
+ if (!id) return null
644
+ parts.unshift(id)
645
+ current = current.parentId ? graph.getNode(current.parentId) : undefined
646
+ }
647
+ return current ? parts.join('/') : null
648
+ }
649
+
650
+ /**
651
+ * The fields a swap override names an icon by: pen carries the glyph, not the component drawn.
652
+ */
653
+ function iconOverride(graph: SceneGraph, componentId: string | null): PenOverride | undefined {
654
+ const origin = readIconOrigin(componentId ? graph.getNode(componentId) : undefined)
655
+ if (!origin) return undefined
656
+ const override: PenOverride = { icon: origin.icon }
657
+ if (origin.library) override.library = origin.library
658
+ if (origin.weight !== undefined) override.weight = origin.weight
659
+ return override
660
+ }
661
+
662
+ /**
663
+ * The overrides an instance writes, and whether one of them is a swap the file cannot name. A
664
+ * layer that swapped its component draws another component than the one it copies, which pen holds
665
+ * as a glyph for an icon; any other swap is what the instance shows, not what it links to.
666
+ */
667
+ function instanceDescendants(
668
+ state: PenWriteState,
669
+ node: SceneNode
670
+ ): { descendants?: Record<string, PenOverride>; unrepresentable: boolean } {
671
+ const overridden = [...node.instanceOverrides.descendants.keys()]
672
+ if (overridden.length === 0) return { unrepresentable: false }
673
+ // Comparing writes fields the moment a document writes them, but their drops are counted once.
674
+ const probe: PenWriteState = {
675
+ ...state,
676
+ drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }
677
+ }
678
+ const descendants: Record<string, PenOverride> = {}
679
+ let unrepresentable = false
680
+ for (const copyId of overridden) {
681
+ const overrides = node.instanceOverrides.descendants.get(copyId)
682
+ const swapped = overrides?.has('componentId') === true
683
+ const swapOf = swapped ? overrides.get('sourceComponentId') : undefined
684
+ const path = overridePath(
685
+ state.graph,
686
+ node.id,
687
+ copyId,
688
+ typeof swapOf === 'string' ? swapOf : undefined
689
+ )
690
+ const copy = state.graph.getNode(copyId)
691
+ if (!path || !copy) {
692
+ unrepresentable = true
693
+ continue
694
+ }
695
+ if (swapped) {
696
+ const icon = iconOverride(state.graph, copy.componentId)
697
+ if (!icon) {
698
+ unrepresentable = true
699
+ continue
700
+ }
701
+ descendants[path] = icon
702
+ continue
703
+ }
704
+ const master = copy.componentId ? state.graph.getNode(copy.componentId) : undefined
705
+ if (!master) {
706
+ unrepresentable = true
707
+ continue
708
+ }
709
+ const own = writeNode(probe, copy)
710
+ const base = writeNode(probe, master)
711
+ const override: PenOverride = {}
712
+ for (const field of OVERRIDABLE_FIELDS) {
713
+ if (!isEqual(own[field], base[field])) override[field] = own[field]
714
+ }
715
+ if (Object.keys(override).length > 0) descendants[path] = override
716
+ }
717
+ return {
718
+ descendants: Object.keys(descendants).length > 0 ? descendants : undefined,
719
+ unrepresentable
720
+ }
721
+ }
722
+
548
723
  function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): boolean {
549
724
  if (
550
725
  node.type === 'TEXT' &&
@@ -554,20 +729,37 @@ function semanticNodeFields(state: PenWriteState, node: SceneNode, result: PenNo
554
729
  result.width = 'fit_content'
555
730
  if (node.type === 'STICKY') result.content = stickySublayers(state.graph, node)?.body.text ?? ''
556
731
  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')
732
+ // Shader, noise, and texture effects have no pen.dev form; dropping them keeps the file loadable.
733
+ const effects = node.effects.filter((effect): effect is ShadowEffect => {
734
+ if (effect.type === 'DROP_SHADOW' || effect.type === 'INNER_SHADOW') return true
735
+ if (effect.type === 'LAYER_BLUR' || effect.type === 'BACKGROUND_BLUR') return true
736
+ if (effect.type === 'NOISE' || effect.type === 'TEXTURE') state.drops.effects++
737
+ return false
738
+ })
559
739
  if (effects.length > 0)
560
740
  result.effect = effects.length === 1 ? effectOf(effects[0]) : effects.map(effectOf)
561
741
  if (node.type === 'COMPONENT' || node.type === 'COMPONENT_SET') result.reusable = true
562
- if (node.type === 'INSTANCE' && node.componentId && state.writtenIds.has(node.componentId)) {
742
+ if (
743
+ node.type === 'INSTANCE' &&
744
+ node.componentId &&
745
+ (state.writtenIds.has(node.componentId) || state.importedIds.has(node.componentId))
746
+ ) {
747
+ const overrides = instanceDescendants(state, node)
748
+ // The file names a swap through the library it imports; one it cannot name is written as the
749
+ // layers the instance draws, which keeps what it shows, as before the library work.
750
+ if (overrides.unrepresentable && !state.writtenIds.has(node.componentId)) return false
563
751
  result.type = 'ref'
564
752
  result.ref = node.componentId
753
+ if (overrides.descendants) result.descendants = overrides.descendants
565
754
  return true
566
755
  }
567
756
  return false
568
757
  }
569
758
  function writeNode(state: PenWriteState, node: SceneNode): PenNode {
759
+ if (node.overflowDirection !== 'NONE') state.drops.scroll++
760
+ if (node.fontFeatures.length > 0) state.drops.fontFeatures++
570
761
  const result: PenNode = { id: node.id, type: nodeType(node) }
762
+ if (node.status !== null) result.status = node.status
571
763
  basicNodeFields(state, node, result)
572
764
  if (semanticNodeFields(state, node, result)) return result
573
765
  // Written after the preserved pen fields, so a regenerated path wins over the source text.
@@ -612,20 +804,34 @@ function sortKeys(value: unknown): unknown {
612
804
  return value
613
805
  }
614
806
 
615
- export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
807
+ export function penDocumentFromGraph(
808
+ graph: SceneGraph,
809
+ options: PenWriteOptions = {}
810
+ ): PenDocument {
811
+ // A deleted variable has no state `.pen` can hold, so layers bound to it write its value.
616
812
  const variables = new Map<string, Variable>()
617
- for (const variable of graph.variables.values()) variables.set(variable.id, variable)
813
+ for (const variable of graph.getLiveVariables()) variables.set(variable.id, variable)
618
814
  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) =>
815
+ for (const collection of graph.getLiveCollections()) collections.set(collection.id, collection)
816
+ // The file declares its imports, so a ref to a component one of them defines resolves on reopen.
817
+ const imports = readPenImports(graph)
818
+ const state: PenWriteState = {
819
+ graph,
820
+ variables,
821
+ collections,
822
+ writtenIds: writtenNodeIds(graph),
823
+ importedIds: importedComponentIds(graph, imports ?? {}),
824
+ warnings: options.warnings ?? [],
825
+ drops: { images: 0, effects: 0, filters: 0, scroll: 0, fontFeatures: 0 }
826
+ }
827
+ const pages = graph.getPages()
828
+ const children = pages.flatMap((page) =>
623
829
  graph
624
830
  .getChildren(page.id)
625
831
  .filter((node) => !node.internalOnly)
626
832
  .map((node) => writeNode(state, node))
627
833
  )
628
- const document: PenDocument = { version: PEN_VERSION, name: graph.getPages()[0]?.name, children }
834
+ const document: PenDocument = { version: PEN_VERSION, name: pages[0]?.name, children }
629
835
  const variablesValue = variablesOf(state)
630
836
  if (variablesValue) document.variables = variablesValue
631
837
  const themes = themesOf(state)
@@ -657,14 +863,84 @@ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
657
863
  return refreshed
658
864
  })
659
865
  if (tokenSources.length > 0) document.tokenSources = tokenSources
866
+ const designMemory = readDesignMemory(graph)
867
+ if (designMemory) document.designMemory = designMemory
868
+ // Only a document that chose its statuses writes them: the default falls back on read.
869
+ const statuses = readStoredStatusWorkflow(graph)
870
+ if (statuses) document.statuses = statuses
871
+ if (imports) document.imports = imports
872
+ const enabledLibraries = enabledLibrariesOf(graph, state)
873
+ if (enabledLibraries) document.enabledLibraries = enabledLibraries
874
+ const publication = readSourceLibraryPublication(graph)
875
+ if (publication) document.sourceLibraryPublication = publication
876
+ if (pages.length > 1) {
877
+ const name = document.name ?? 'Page 1'
878
+ state.warnings.push(
879
+ `Pencil.dev files hold one page; ${pages.length} pages were merged into “${name}”.`
880
+ )
881
+ }
882
+ if (graph.documentColorSpace === 'display-p3') {
883
+ state.warnings.push(
884
+ '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.'
885
+ )
886
+ }
887
+ reportDrops(state)
660
888
  return document
661
889
  }
662
890
 
891
+ /**
892
+ * The library bindings a `.pen` file records, or null when the document has none. The definitions
893
+ * live on the hidden page, which a Pencil.dev file cannot hold, so the file records the bindings
894
+ * and says that the components it was built from come back as placeholders.
895
+ */
896
+ function enabledLibrariesOf(
897
+ graph: SceneGraph,
898
+ state: PenWriteState
899
+ ): EnabledLibraryBinding[] | null {
900
+ const bindings = [...graph.enabledLibraries.values()]
901
+ if (bindings.length === 0) return null
902
+ const enabled = bindings.filter((binding) => binding.enabled).length
903
+ if (enabled > 0)
904
+ state.warnings.push(
905
+ `Library components came from ${enabled} enabled ${enabled === 1 ? 'library' : 'libraries'}, whose definitions Pencil.dev files do not hold; re-enable those libraries after reopening to restore them.`
906
+ )
907
+ return bindings
908
+ }
909
+
910
+ /** Adds one sentence for each kind of content the written file had to leave out. */
911
+ function reportDrops(state: PenWriteState): void {
912
+ const { images, effects, filters, scroll, fontFeatures } = state.drops
913
+ if (images > 0)
914
+ state.warnings.push(
915
+ `Image fills with missing image data were left out (${images}); Pencil.dev files cannot hold a paint without its image.`
916
+ )
917
+ if (effects > 0)
918
+ state.warnings.push(
919
+ `Noise and texture effects were left out (${effects}); Pencil.dev files have no form for them.`
920
+ )
921
+ if (filters > 0)
922
+ state.warnings.push(
923
+ `Image adjustment filters were left out (${filters}); Pencil.dev files have no form for them.`
924
+ )
925
+ if (scroll > 0)
926
+ state.warnings.push(
927
+ `Scroll overflow was left out (${scroll}); Pencil.dev files have no form for it.`
928
+ )
929
+ if (fontFeatures > 0)
930
+ state.warnings.push(
931
+ `OpenType font features were left out (${fontFeatures}); Pencil.dev files have no form for them.`
932
+ )
933
+ }
934
+
663
935
  export function stringifyPenDocument(document: PenDocument): string {
664
936
  return `${JSON.stringify(sortKeys(document), null, 2)}\n`
665
937
  }
666
938
 
667
- export function writePenDocument(source: PenDocument | SceneGraph): string {
668
- const document = source instanceof SceneGraphValue ? penDocumentFromGraph(source) : source
939
+ export function writePenDocument(
940
+ source: PenDocument | SceneGraph,
941
+ options: PenWriteOptions = {}
942
+ ): string {
943
+ const document =
944
+ source instanceof SceneGraphValue ? penDocumentFromGraph(source, options) : source
669
945
  return stringifyPenDocument(document)
670
946
  }