@pairdraw/pen 0.19.2 → 0.20.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/dist/index.d.ts CHANGED
@@ -359,6 +359,12 @@ declare const penDocumentSchema: v.LooseObjectSchema<{
359
359
  readonly url: v.StringSchema<undefined>;
360
360
  }, undefined>, undefined>, undefined>;
361
361
  readonly themes: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.ArraySchema<v.StringSchema<undefined>, undefined>, undefined>, undefined>;
362
+ /**
363
+ * The selector each mode applies in, by collection and mode name: `.dark` for a Dark mode a
364
+ * stylesheet writes. Pencil has no field for it, so it is an extension other clients ignore;
365
+ * without it a reopened document reads the stylesheet's dark block as a new mode.
366
+ */
367
+ readonly modeConditions: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>, undefined>;
362
368
  readonly imports: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
363
369
  readonly variables: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.LooseObjectSchema<{
364
370
  readonly type: v.StringSchema<undefined>;
@@ -366,7 +372,37 @@ declare const penDocumentSchema: v.LooseObjectSchema<{
366
372
  readonly value: v.UnionSchema<[v.StringSchema<undefined>, v.SchemaWithPipe<readonly [v.NumberSchema<undefined>, v.FiniteAction<number, undefined>]>, v.BooleanSchema<undefined>], undefined>;
367
373
  readonly theme: v.OptionalSchema<v.RecordSchema<v.StringSchema<undefined>, v.StringSchema<undefined>, undefined>, undefined>;
368
374
  }, undefined>, undefined>], undefined>;
375
+ /**
376
+ * The code that names the token, as Figma's variables carry it. Pencil has no field for it, so
377
+ * it is an extension other Pencil clients ignore; without it a reopened document cannot match a
378
+ * renamed variable to the token its stylesheet declares.
379
+ */
380
+ readonly codeSyntax: v.OptionalSchema<v.RecordSchema<v.PicklistSchema<readonly ["WEB", "ANDROID", "iOS"], undefined>, v.StringSchema<undefined>, undefined>, undefined>;
369
381
  }, undefined>, undefined>, undefined>;
382
+ /** The code the document's variables are linked to, as Core keeps it on the document node. */
383
+ readonly tokenSources: v.OptionalSchema<v.SchemaWithPipe<readonly [v.UnknownSchema, v.TransformAction<unknown, {
384
+ id: string;
385
+ kind: "css" | "folder" | "dtcg";
386
+ name: string;
387
+ path?: string | undefined;
388
+ syncedAt?: string | undefined;
389
+ snapshot: {
390
+ [x: string]: {
391
+ [x: string]: string;
392
+ };
393
+ };
394
+ names?: {
395
+ [x: string]: string;
396
+ } | undefined;
397
+ currentNames?: {
398
+ [x: string]: string;
399
+ } | undefined;
400
+ modes?: {
401
+ [x: string]: {
402
+ [x: string]: string;
403
+ };
404
+ } | undefined;
405
+ }[]>]>, undefined>;
370
406
  readonly children: v.ArraySchema<v.GenericSchema<unknown, PenNode>, undefined>;
371
407
  }, undefined>;
372
408
  type PenDocument = v.InferOutput<typeof penDocumentSchema>;
@@ -493,6 +529,10 @@ interface PenReadOptions {
493
529
  * component no import has reads as a placeholder.
494
530
  */
495
531
  imports?: PenImports;
532
+ /** Called with a variable a layer references that the document does not define. */
533
+ onUnknownVariable?(name: string): void;
534
+ /** Called with a node type the reader does not know, which reads as a placeholder frame. */
535
+ onUnknownNodeType?(type: string): void;
496
536
  }
497
537
  /** A `.pen` document's JSON, validated; throws for text that is not one. */
498
538
  declare function parsePenDocument(json: string): PenDocument;
@@ -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":";;;;;;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;;;iBC4bjE,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":";;;;;;cAsJM;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAuFM,aAAa,EAAE,YAAY,EAAE,oBAAoB;;UAG5C,oBAAoB;EACnC;EACA;EACA,WAAW;EACX,cAAc,eAAe;GAC5B;;UAGc,gBAAgB;EAC/B;EACA;;;cA8CI,YAAU,EAAA;;;;cAQV,mBAAiB,EAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;KAmBX,cAAc,EAAE,mBAAmB;KACnC,UAAU,EAAE,mBAAmB;;;;iBCzS3B,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;;;;UCSI;;;;;EAKf,QAAQ,OAAO;;EAEf,SAAS,oBAAoB;;;;;EAK7B,UAAU;;EAEV,QAAQ;;;;;;EAMR,QAAQ,oBAAoB;;;;;;;EAO5B,UAAU;;EAEV,mBAAmB;;EAEnB,mBAAmB;;;iBAgDL,iBAAiB,eAAe;;iBAShC,cAAc,KAAK,aAAa,UAAS,iBAAsB;iBA0D/D,aAAa,cAAc,UAAS,iBAAsB;iBAIpD,YAAY,MAAM,MAAM,UAAU,iBAAiB,QAAQ;;;iBC8bjE,qBAAqB,OAAO,aAAa;iBAgDzC,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.19.2",
3
+ "version": "0.20.0",
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.19.2"
17
+ "@pairdraw/scene-graph": "^0.20.0"
18
18
  },
19
19
  "exports": {
20
20
  ".": {
@@ -30,6 +30,9 @@ const ANNOTATION_COLORS: Readonly<Record<string, Color>> = {
30
30
  context: STICKY_COLORS.gray
31
31
  }
32
32
 
33
+ /** The annotation type names, which the reader knows even though they map to stickies. */
34
+ export const ANNOTATION_TYPES: readonly string[] = Object.keys(ANNOTATION_COLORS)
35
+
33
36
  export function isAnnotation(pen: Pick<PenNode, 'type'>): boolean {
34
37
  return Object.hasOwn(ANNOTATION_COLORS, pen.type)
35
38
  }
package/src/nodes.ts CHANGED
@@ -12,7 +12,7 @@ import type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
12
12
  import { fillSizingFields } from '@pairdraw/scene-graph/layout'
13
13
  import type { Color } from '@pairdraw/scene-graph/primitives'
14
14
 
15
- import { applyAnnotation, createAnnotation, isAnnotation } from './annotations'
15
+ import { ANNOTATION_TYPES, applyAnnotation, createAnnotation, isAnnotation } from './annotations'
16
16
  import { convertEffects } from './effects'
17
17
  import { ellipseArc } from './geometry'
18
18
  import { drawIcon, insideComponent, useIconComponent } from './icons'
@@ -71,6 +71,8 @@ export interface Build {
71
71
  placements: Map<string, PenPlacement>
72
72
  /** Groups in reading order. */
73
73
  groupIds: Set<string>
74
+ /** Called with a node type the reader does not know. */
75
+ onUnknownNodeType?: (type: string) => void
74
76
  /** The components icons in components are instances of, by glyph and size. */
75
77
  iconComponents: Map<string, string>
76
78
  /** The page those components are on, added with the first one. */
@@ -98,7 +100,25 @@ function isFlatLine(pen: PenNode, ctx: VarContext): boolean {
98
100
  return height.sizing === 'FIXED' && height.value === 0
99
101
  }
100
102
 
101
- function sceneType(pen: PenNode, ctx: VarContext): NodeType {
103
+ const KNOWN_PEN_TYPES = new Set([
104
+ 'frame',
105
+ 'line',
106
+ 'rectangle',
107
+ 'ellipse',
108
+ 'polygon',
109
+ 'group',
110
+ 'text',
111
+ 'icon_font',
112
+ 'path',
113
+ 'icon',
114
+ 'sticky',
115
+ 'ref',
116
+ // The annotation cards read as stickies; they are known types, not placeholders.
117
+ ...ANNOTATION_TYPES
118
+ ])
119
+
120
+ function sceneType(pen: PenNode, ctx: VarContext, warn?: (type: string) => void): NodeType {
121
+ if (!KNOWN_PEN_TYPES.has(pen.type)) warn?.(pen.type)
102
122
  if (pen.type === 'frame') return pen.reusable ? 'COMPONENT' : 'FRAME'
103
123
  if (pen.type === 'line') return isFlatLine(pen, ctx) ? 'LINE' : 'VECTOR'
104
124
  if (isAnnotation(pen)) return 'STICKY'
@@ -400,7 +420,10 @@ export function createSceneNode(pen: PenNode, parentId: string, build: Build): s
400
420
  const iconInstance = fields.type === 'icon' && insideComponent(build.graph, parentId)
401
421
  const leaveTheme = fields.theme ? build.ctx.enterTheme(fields.theme) : undefined
402
422
  try {
403
- const type = instanceOf || iconInstance ? 'INSTANCE' : sceneType(fields, build.ctx)
423
+ const type =
424
+ instanceOf || iconInstance
425
+ ? 'INSTANCE'
426
+ : sceneType(fields, build.ctx, build.onUnknownNodeType)
404
427
  // An ID a hand-edited file repeats gets a fresh one, so the layer does not replace the first
405
428
  // layer with it or become its own parent.
406
429
  const id = build.graph.getNode(pen.id) ? build.graph.entityIdMinter()() : pen.id
package/src/read.ts CHANGED
@@ -2,6 +2,7 @@ import * as v from 'valibot'
2
2
 
3
3
  import { SceneGraph } from '@pairdraw/scene-graph'
4
4
  import type { FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
5
+ import { rekeyTokenSources, tokenSourcesPluginData } from '@pairdraw/scene-graph/token-sources'
5
6
 
6
7
  import { lineNetwork, pathNetwork } from './geometry'
7
8
  import { removeUnusedIconComponents } from './icons'
@@ -43,6 +44,10 @@ export interface PenReadOptions {
43
44
  * component no import has reads as a placeholder.
44
45
  */
45
46
  imports?: PenImports
47
+ /** Called with a variable a layer references that the document does not define. */
48
+ onUnknownVariable?(name: string): void
49
+ /** Called with a node type the reader does not know, which reads as a placeholder frame. */
50
+ onUnknownNodeType?(type: string): void
46
51
  }
47
52
 
48
53
  function collectComponents(nodes: PenNode[], components: Map<string, PenNode>): void {
@@ -109,7 +114,9 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
109
114
  const imports: PenImports = options.imports ?? new Map()
110
115
  const build: Build = {
111
116
  graph,
112
- ctx: buildVarContext(graph, withImports(doc, imports)),
117
+ ctx: buildVarContext(graph, withImports(doc, imports), (name) =>
118
+ options.onUnknownVariable?.(name)
119
+ ),
113
120
  images: createImageStore(graph, options.images),
114
121
  shaders: options.shaders,
115
122
  icons: options.icons,
@@ -121,7 +128,8 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
121
128
  groupIds: new Set(),
122
129
  iconComponents: new Map(),
123
130
  iconPageId: null,
124
- replaced: new Set()
131
+ replaced: new Set(),
132
+ onUnknownNodeType: (type) => options.onUnknownNodeType?.(type)
125
133
  }
126
134
  collectComponents(doc.children, build.components)
127
135
  for (const imported of imports.values())
@@ -145,6 +153,11 @@ export function buildPenGraph(doc: PenDocument, options: PenReadOptions = {}): S
145
153
  if (graph.getPages(true).length === 0) {
146
154
  graph.addPage('Page 1')
147
155
  }
156
+ if (doc.tokenSources && doc.tokenSources.length > 0) {
157
+ graph.updateNode(graph.rootId, {
158
+ pluginData: tokenSourcesPluginData(graph, rekeyTokenSources(graph, doc.tokenSources))
159
+ })
160
+ }
148
161
 
149
162
  return graph
150
163
  }
package/src/schema.ts CHANGED
@@ -1,6 +1,8 @@
1
1
  import * as v from 'valibot'
2
2
 
3
+ import { CODE_SYNTAX_PLATFORMS } from '@pairdraw/scene-graph'
3
4
  import { finiteNumberSchema } from '@pairdraw/scene-graph/primitives'
5
+ import { tokenSourcesSchema } from '@pairdraw/scene-graph/token-sources'
4
6
 
5
7
  import { stripJSONComments } from './jsonc'
6
8
 
@@ -282,20 +284,40 @@ const variableSchema = v.looseObject({
282
284
  theme: v.optional(v.record(strSchema, strSchema))
283
285
  })
284
286
  )
285
- ])
287
+ ]),
288
+ /**
289
+ * The code that names the token, as Figma's variables carry it. Pencil has no field for it, so
290
+ * it is an extension other Pencil clients ignore; without it a reopened document cannot match a
291
+ * renamed variable to the token its stylesheet declares.
292
+ */
293
+ codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), strSchema))
286
294
  })
287
295
 
288
296
  /** A font file the document bundles, which its text names by `name` as a family. */
289
297
  const fontSchema = v.looseObject({ name: strSchema, url: strSchema })
290
298
 
299
+ /** A document whose links are a list this reader can use; any other value is no link at all. */
300
+ const penTokenSourcesSchema = v.pipe(
301
+ v.unknown(),
302
+ v.transform((value) => v.parse(tokenSourcesSchema, Array.isArray(value) ? value : []))
303
+ )
304
+
291
305
  const penDocumentSchema = v.looseObject({
292
306
  version: v.optional(strSchema),
293
307
  // The page's name. The format is single-page, so it belongs to the document.
294
308
  name: v.optional(strSchema),
295
309
  fonts: v.optional(v.array(fontSchema)),
296
310
  themes: v.optional(v.record(strSchema, v.array(strSchema))),
311
+ /**
312
+ * The selector each mode applies in, by collection and mode name: `.dark` for a Dark mode a
313
+ * stylesheet writes. Pencil has no field for it, so it is an extension other clients ignore;
314
+ * without it a reopened document reads the stylesheet's dark block as a new mode.
315
+ */
316
+ modeConditions: v.optional(v.record(strSchema, v.record(strSchema, strSchema))),
297
317
  imports: v.optional(v.record(strSchema, strSchema)),
298
318
  variables: v.optional(v.record(strSchema, variableSchema)),
319
+ /** The code the document's variables are linked to, as Core keeps it on the document node. */
320
+ tokenSources: v.optional(penTokenSourcesSchema),
299
321
  children: v.array(nodeSchema)
300
322
  })
301
323
 
package/src/text.ts CHANGED
@@ -1,3 +1,5 @@
1
+ import { omit } from 'es-toolkit'
2
+
1
3
  import type { SceneNode, StyleRun, TextAlignVertical, TextAutoResize } from '@pairdraw/scene-graph'
2
4
  import { parseFontStyle, type FontFamilyStyle } from '@pairdraw/scene-graph/font-style'
3
5
  import { percentLength, pixelLength } from '@pairdraw/scene-graph/text'
@@ -86,7 +88,7 @@ export function applyTextProps(
86
88
  })
87
89
  // The bound name is the pen-only one no font is registered under, so a later reconcile
88
90
  // would restore a family nothing draws with. The bundled face owns the family now.
89
- delete node.boundVariables.fontFamily
91
+ node.boundVariables = omit(node.boundVariables, ['fontFamily'])
90
92
  }
91
93
  node.textAlignHorizontal = TEXT_ALIGN[pen.textAlign ?? 'left'] ?? 'LEFT'
92
94
  node.textAlignVertical = TEXT_ALIGN_VERTICAL[pen.textAlignVertical ?? 'top'] ?? 'TOP'
package/src/variables.ts CHANGED
@@ -50,7 +50,7 @@ function varName(ref: string): string {
50
50
  export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {
51
51
  if (!isVarRef(val)) return
52
52
  const variable = ctx.byName.get(varName(val))
53
- if (variable) node.boundVariables[field] = variable.id
53
+ if (variable) node.boundVariables = { ...node.boundVariables, [field]: variable.id }
54
54
  }
55
55
 
56
56
  /** A number, or the value of the number variable it references. */
@@ -230,6 +230,23 @@ interface ThemeCollection {
230
230
  modeByTheme: Map<string, string>
231
231
  }
232
232
 
233
+ /** The selector each mode applies in, which Pencil itself does not record. */
234
+ function applyModeConditions(
235
+ graph: SceneGraph,
236
+ doc: PenDocument,
237
+ collections: readonly ThemeCollection[]
238
+ ) {
239
+ for (const created of collections) {
240
+ const collection = graph.variableCollections.get(created.id)
241
+ const conditions = collection && doc.modeConditions?.[collection.name]
242
+ if (!collection || !conditions) continue
243
+ for (const mode of collection.modes) {
244
+ const condition = conditions[mode.name]
245
+ if (condition) mode.condition = condition
246
+ }
247
+ }
248
+ }
249
+
233
250
  function addThemeCollection(graph: SceneGraph, axes: Axis[]): ThemeCollection {
234
251
  const themes = combinations(axes)
235
252
  const modes: VariableCollectionMode[] = themes.map((theme) => ({
@@ -250,13 +267,18 @@ function addThemeCollection(graph: SceneGraph, axes: Axis[]): ThemeCollection {
250
267
  return { id, axes, themes, modes, modeByTheme }
251
268
  }
252
269
 
253
- export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {
270
+ export function buildVarContext(
271
+ graph: SceneGraph,
272
+ doc: PenDocument,
273
+ onUnknownVariable?: (name: string) => void
274
+ ): VarContext {
254
275
  const axes = themeAxes(doc)
255
276
  const definitions = Object.entries(doc.variables ?? {})
256
277
  const collections = axisGroups(
257
278
  axes,
258
279
  definitions.map(([, definition]) => definition)
259
280
  ).map((group) => addThemeCollection(graph, group))
281
+ applyModeConditions(graph, doc, collections)
260
282
  const collectionOfAxis = new Map(
261
283
  collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection]))
262
284
  )
@@ -289,7 +311,8 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
289
311
  ])
290
312
  ),
291
313
  description: '',
292
- hiddenFromPublishing: false
314
+ hiddenFromPublishing: false,
315
+ ...(definition.codeSyntax ? { codeSyntax: definition.codeSyntax } : {})
293
316
  }
294
317
  graph.addVariable(variable)
295
318
  byName.set(name, variable)
@@ -303,6 +326,7 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
303
326
  /** A variable's value in the current theme, following aliases. */
304
327
  function resolve(ref: string): VariableValue | undefined {
305
328
  let variable = byName.get(varName(ref))
329
+ if (!variable) onUnknownVariable?.(varName(ref))
306
330
  for (let hops = 0; variable && hops <= byName.size; hops++) {
307
331
  const collection = collectionById.get(variable.collectionId)
308
332
  const value = collection ? variable.valuesByMode[modeIn(collection)] : undefined
package/src/write.ts CHANGED
@@ -19,6 +19,7 @@ import { stickySublayers } from '@pairdraw/scene-graph/generated'
19
19
  import { applyGradientTransform, invertGradientTransform } from '@pairdraw/scene-graph/gradient'
20
20
  import { layoutSizing } from '@pairdraw/scene-graph/layout'
21
21
  import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
22
+ import { readTokenSources, type TokenSource } from '@pairdraw/scene-graph/token-sources'
22
23
 
23
24
  import { networkToSVGPath } from './geometry'
24
25
  import { PEN_PLUGIN_DATA_NAMESPACE } from './plugin-data'
@@ -446,17 +447,20 @@ function penVariable(
446
447
  state: PenWriteState
447
448
  ): PenVariable {
448
449
  const modes = collection?.modes ?? []
450
+ const syntax = variable.codeSyntax ? { codeSyntax: variable.codeSyntax } : {}
449
451
  if (modes.length <= 1)
450
452
  return {
451
453
  type: variableType(variable.type),
452
- value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state)
454
+ value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state),
455
+ ...syntax
453
456
  }
454
457
  return {
455
458
  type: variableType(variable.type),
456
459
  value: modes.map((mode, index) => ({
457
460
  value: variableScalar(variable.valuesByMode[mode.modeId], state),
458
461
  ...(index === 0 ? {} : { theme: { [collection?.name ?? 'Mode']: mode.name } })
459
- }))
462
+ })),
463
+ ...syntax
460
464
  }
461
465
  }
462
466
 
@@ -481,6 +485,17 @@ function themesOf(state: PenWriteState): PenDocument['themes'] {
481
485
  )
482
486
  }
483
487
 
488
+ /** The selector each mode applies in, by collection and mode name; none when no mode names one. */
489
+ function modeConditionsOf(state: PenWriteState): PenDocument['modeConditions'] {
490
+ const entries = [...state.graph.variableCollections.values()].flatMap((collection) => {
491
+ const modes = collection.modes.flatMap((mode) =>
492
+ mode.condition ? [[mode.name, mode.condition] as const] : []
493
+ )
494
+ return modes.length > 0 ? [[collection.name, Object.fromEntries(modes)] as const] : []
495
+ })
496
+ return entries.length > 0 ? Object.fromEntries(entries) : undefined
497
+ }
498
+
484
499
  function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): void {
485
500
  if (node.name) result.name = node.name
486
501
  const placement = penCoordinates(node)
@@ -615,6 +630,33 @@ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
615
630
  if (variablesValue) document.variables = variablesValue
616
631
  const themes = themesOf(state)
617
632
  if (themes) document.themes = themes
633
+ const conditions = modeConditionsOf(state)
634
+ if (conditions) document.modeConditions = conditions
635
+ const tokenSources = readTokenSources(graph).map((source) => {
636
+ // The reopen gives variables new ids; these are the names the file holds for them. `names`
637
+ // stays as the last sync recorded it, where the token each variable stands for lives.
638
+ const currentNames = Object.fromEntries(
639
+ Object.keys(source.names ?? {}).flatMap((id) => {
640
+ const variable = variables.get(id)
641
+ const collection = variable ? collections.get(variable.collectionId) : undefined
642
+ return variable && collection ? [[id, `${collection.name}/${variable.name}`]] : []
643
+ })
644
+ )
645
+ const modes = {
646
+ ...source.modes,
647
+ ...Object.fromEntries(
648
+ [...collections.values()].map((collection) => [
649
+ collection.name,
650
+ Object.fromEntries(collection.modes.map((mode) => [mode.modeId, mode.name]))
651
+ ])
652
+ )
653
+ }
654
+ const refreshed: TokenSource = { ...source }
655
+ if (Object.keys(currentNames).length > 0) refreshed.currentNames = currentNames
656
+ if (Object.keys(modes).length > 0) refreshed.modes = modes
657
+ return refreshed
658
+ })
659
+ if (tokenSources.length > 0) document.tokenSources = tokenSources
618
660
  return document
619
661
  }
620
662