@pairdraw/pen 0.19.1 → 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/chunks/annotations.js +84 -21
- package/dist/chunks/annotations.js.map +1 -1
- package/dist/chunks/effects.js +19 -1
- package/dist/chunks/effects.js.map +1 -1
- package/dist/chunks/index.js +70 -21
- package/dist/chunks/index.js.map +1 -1
- package/dist/index.d.ts +40 -0
- package/dist/index.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/annotations.ts +3 -0
- package/src/nodes.ts +27 -4
- package/src/read.ts +15 -2
- package/src/schema.ts +23 -1
- package/src/text.ts +3 -1
- package/src/variables.ts +114 -30
- package/src/write.ts +58 -15
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;
|
package/dist/index.d.ts.map
CHANGED
|
@@ -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":";;;;;;
|
|
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.
|
|
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.
|
|
17
|
+
"@pairdraw/scene-graph": "^0.20.0"
|
|
18
18
|
},
|
|
19
19
|
"exports": {
|
|
20
20
|
".": {
|
package/src/annotations.ts
CHANGED
|
@@ -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
|
-
|
|
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'
|
|
@@ -308,7 +328,7 @@ export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build):
|
|
|
308
328
|
layoutGrow: 0,
|
|
309
329
|
layoutAlignSelf: 'AUTO',
|
|
310
330
|
boundVariables: {},
|
|
311
|
-
variableModes: pen.theme
|
|
331
|
+
variableModes: pen.theme ? ctx.variableModes(pen.theme) : {}
|
|
312
332
|
} satisfies Partial<SceneNode>)
|
|
313
333
|
bindIfVar(node, 'visible', pen.enabled, ctx)
|
|
314
334
|
bindIfVar(node, 'opacity', pen.opacity, ctx)
|
|
@@ -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 =
|
|
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
|
-
|
|
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
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
import { groupBy, uniq } from 'es-toolkit/array'
|
|
2
|
+
|
|
1
3
|
import {
|
|
2
4
|
generateId,
|
|
3
5
|
type SceneGraph,
|
|
@@ -21,8 +23,6 @@ type Theme = Record<string, string>
|
|
|
21
23
|
* one mode of a single collection, since a variable can depend on several axes at once.
|
|
22
24
|
*/
|
|
23
25
|
export interface VarContext {
|
|
24
|
-
/** The collection the document's variables and themes make, or `null` when it has neither. */
|
|
25
|
-
collectionId: string | null
|
|
26
26
|
byName: Map<string, Variable>
|
|
27
27
|
resolveColor(ref: string): Color
|
|
28
28
|
resolveNumber(ref: string): number
|
|
@@ -32,8 +32,11 @@ export interface VarContext {
|
|
|
32
32
|
resolveBoolean(ref: string): boolean
|
|
33
33
|
/** Merges a layer's theme over its parent's until the returned function is called. */
|
|
34
34
|
enterTheme(theme: Theme): () => void
|
|
35
|
-
/**
|
|
36
|
-
|
|
35
|
+
/**
|
|
36
|
+
* The modes a layer setting `theme` takes: in each collection holding one of its axes, the mode
|
|
37
|
+
* of the theme being read.
|
|
38
|
+
*/
|
|
39
|
+
variableModes(theme: Theme): Record<string, string>
|
|
37
40
|
}
|
|
38
41
|
|
|
39
42
|
export function isVarRef(val: unknown): val is `$${string}` {
|
|
@@ -47,7 +50,7 @@ function varName(ref: string): string {
|
|
|
47
50
|
export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {
|
|
48
51
|
if (!isVarRef(val)) return
|
|
49
52
|
const variable = ctx.byName.get(varName(val))
|
|
50
|
-
if (variable) node.boundVariables[field]
|
|
53
|
+
if (variable) node.boundVariables = { ...node.boundVariables, [field]: variable.id }
|
|
51
54
|
}
|
|
52
55
|
|
|
53
56
|
/** A number, or the value of the number variable it references. */
|
|
@@ -97,7 +100,7 @@ export function resolveString(value: string | undefined, ctx: VarContext): strin
|
|
|
97
100
|
* loading what a document may draw before it is read in a theme.
|
|
98
101
|
*/
|
|
99
102
|
export function possibleValues(value: string | undefined, doc: PenDocument): string[] {
|
|
100
|
-
const
|
|
103
|
+
const axes = themeAxes(doc)
|
|
101
104
|
const found = new Set<string>()
|
|
102
105
|
const seen = new Set<string>()
|
|
103
106
|
const visit = (raw: PenVariableScalar | undefined) => {
|
|
@@ -111,7 +114,8 @@ export function possibleValues(value: string | undefined, doc: PenDocument): str
|
|
|
111
114
|
if (!definition || seen.has(name)) return
|
|
112
115
|
seen.add(name)
|
|
113
116
|
const empty = emptyValue(sceneType(definition.type))
|
|
114
|
-
|
|
117
|
+
// Only the axes its values name decide which applies.
|
|
118
|
+
for (const theme of combinations(axesOf(definition, axes))) {
|
|
115
119
|
const themed = rawValue(definition, theme)
|
|
116
120
|
if (themed !== undefined) visit(themed)
|
|
117
121
|
else if (typeof empty !== 'object') found.add(String(empty))
|
|
@@ -194,60 +198,138 @@ function themeKey(theme: Theme, axes: Axis[]): string {
|
|
|
194
198
|
return axes.map(([axis]) => theme[axis]).join('\u0000')
|
|
195
199
|
}
|
|
196
200
|
|
|
197
|
-
|
|
198
|
-
|
|
201
|
+
/** The document's axes a variable's values name, in the document's order. */
|
|
202
|
+
function axesOf(definition: PenVariable, axes: Axis[]): Axis[] {
|
|
203
|
+
if (!Array.isArray(definition.value)) return []
|
|
204
|
+
const named = new Set(definition.value.flatMap((entry) => Object.keys(entry.theme ?? {})))
|
|
205
|
+
return axes.filter(([axis]) => named.has(axis))
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/** The axes in groups, each joining the axes some variable's values combine, through any chain. */
|
|
209
|
+
function axisGroups(axes: Axis[], definitions: PenVariable[]): Axis[][] {
|
|
210
|
+
const parent = new Map(axes.map(([axis]) => [axis, axis]))
|
|
211
|
+
const root = (axis: string): string => {
|
|
212
|
+
const next = parent.get(axis) ?? axis
|
|
213
|
+
return next === axis ? axis : root(next)
|
|
214
|
+
}
|
|
215
|
+
for (const definition of definitions) {
|
|
216
|
+
const named = axesOf(definition, axes)
|
|
217
|
+
const first = named.at(0)
|
|
218
|
+
if (!first) continue
|
|
219
|
+
for (const [axis] of named.slice(1)) parent.set(root(axis), root(first[0]))
|
|
220
|
+
}
|
|
221
|
+
return Object.values(groupBy(axes, ([axis]) => root(axis)))
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/** A collection for a group of axes: one mode for each combination of their values. */
|
|
225
|
+
interface ThemeCollection {
|
|
226
|
+
id: string
|
|
227
|
+
axes: Axis[]
|
|
228
|
+
themes: Theme[]
|
|
229
|
+
modes: VariableCollectionMode[]
|
|
230
|
+
modeByTheme: Map<string, string>
|
|
231
|
+
}
|
|
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
|
+
|
|
250
|
+
function addThemeCollection(graph: SceneGraph, axes: Axis[]): ThemeCollection {
|
|
199
251
|
const themes = combinations(axes)
|
|
200
252
|
const modes: VariableCollectionMode[] = themes.map((theme) => ({
|
|
201
253
|
modeId: generateId(),
|
|
202
254
|
name: axes.length === 0 ? 'Default' : axes.map(([axis]) => theme[axis]).join(' / ')
|
|
203
255
|
}))
|
|
204
|
-
const
|
|
256
|
+
const id = generateId()
|
|
257
|
+
graph.addCollection({
|
|
258
|
+
id,
|
|
259
|
+
name: axes.length === 0 ? 'Variables' : axes.map(([axis]) => axis).join(' / '),
|
|
260
|
+
modes,
|
|
261
|
+
defaultModeId: modes[0].modeId,
|
|
262
|
+
variableIds: []
|
|
263
|
+
})
|
|
264
|
+
const modeByTheme = new Map(
|
|
265
|
+
themes.map((theme, index) => [themeKey(theme, axes), modes[index].modeId])
|
|
266
|
+
)
|
|
267
|
+
return { id, axes, themes, modes, modeByTheme }
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
export function buildVarContext(
|
|
271
|
+
graph: SceneGraph,
|
|
272
|
+
doc: PenDocument,
|
|
273
|
+
onUnknownVariable?: (name: string) => void
|
|
274
|
+
): VarContext {
|
|
275
|
+
const axes = themeAxes(doc)
|
|
205
276
|
const definitions = Object.entries(doc.variables ?? {})
|
|
206
|
-
const
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
277
|
+
const collections = axisGroups(
|
|
278
|
+
axes,
|
|
279
|
+
definitions.map(([, definition]) => definition)
|
|
280
|
+
).map((group) => addThemeCollection(graph, group))
|
|
281
|
+
applyModeConditions(graph, doc, collections)
|
|
282
|
+
const collectionOfAxis = new Map(
|
|
283
|
+
collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection]))
|
|
284
|
+
)
|
|
285
|
+
// A variable no axis decides goes with the first axes, where it holds one value in every mode. A
|
|
286
|
+
// document with neither variables nor themes, such as a new one, gets no empty collection.
|
|
287
|
+
const fallback = collections[0] ?? (definitions.length > 0 ? addThemeCollection(graph, []) : null)
|
|
288
|
+
const collectionFor = (definition: PenVariable): ThemeCollection | null => {
|
|
289
|
+
const first = axesOf(definition, axes).at(0)
|
|
290
|
+
return (first && collectionOfAxis.get(first[0])) || fallback
|
|
217
291
|
}
|
|
218
292
|
|
|
219
293
|
const ids = new Map(definitions.map(([name]) => [name, generateId()]))
|
|
220
294
|
const byName = new Map<string, Variable>()
|
|
221
295
|
const byId = new Map<string, Variable>()
|
|
296
|
+
const collectionById = new Map<string, ThemeCollection>()
|
|
222
297
|
for (const [name, definition] of definitions) {
|
|
223
298
|
const type = sceneType(definition.type)
|
|
299
|
+
const collection = collectionFor(definition)
|
|
300
|
+
if (!collection) continue
|
|
301
|
+
collectionById.set(collection.id, collection)
|
|
224
302
|
const variable: Variable = {
|
|
225
303
|
id: ids.get(name) ?? generateId(),
|
|
226
304
|
name,
|
|
227
305
|
type,
|
|
228
|
-
collectionId,
|
|
306
|
+
collectionId: collection.id,
|
|
229
307
|
valuesByMode: Object.fromEntries(
|
|
230
|
-
themes.map((theme, index) => [
|
|
231
|
-
modes[index].modeId,
|
|
308
|
+
collection.themes.map((theme, index) => [
|
|
309
|
+
collection.modes[index].modeId,
|
|
232
310
|
sceneValue(rawValue(definition, theme), type, ids)
|
|
233
311
|
])
|
|
234
312
|
),
|
|
235
313
|
description: '',
|
|
236
|
-
hiddenFromPublishing: false
|
|
314
|
+
hiddenFromPublishing: false,
|
|
315
|
+
...(definition.codeSyntax ? { codeSyntax: definition.codeSyntax } : {})
|
|
237
316
|
}
|
|
238
317
|
graph.addVariable(variable)
|
|
239
318
|
byName.set(name, variable)
|
|
240
319
|
byId.set(variable.id, variable)
|
|
241
320
|
}
|
|
242
321
|
|
|
243
|
-
let current: Theme =
|
|
244
|
-
const
|
|
322
|
+
let current: Theme = Object.fromEntries(axes.map(([axis, values]) => [axis, values[0]]))
|
|
323
|
+
const modeIn = (collection: ThemeCollection) =>
|
|
324
|
+
collection.modeByTheme.get(themeKey(current, collection.axes)) ?? collection.modes[0].modeId
|
|
245
325
|
|
|
246
326
|
/** A variable's value in the current theme, following aliases. */
|
|
247
327
|
function resolve(ref: string): VariableValue | undefined {
|
|
248
328
|
let variable = byName.get(varName(ref))
|
|
329
|
+
if (!variable) onUnknownVariable?.(varName(ref))
|
|
249
330
|
for (let hops = 0; variable && hops <= byName.size; hops++) {
|
|
250
|
-
const
|
|
331
|
+
const collection = collectionById.get(variable.collectionId)
|
|
332
|
+
const value = collection ? variable.valuesByMode[modeIn(collection)] : undefined
|
|
251
333
|
if (typeof value !== 'object' || !('aliasId' in value)) return value
|
|
252
334
|
variable = byId.get(value.aliasId)
|
|
253
335
|
}
|
|
@@ -255,7 +337,6 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
|
|
|
255
337
|
}
|
|
256
338
|
|
|
257
339
|
return {
|
|
258
|
-
collectionId: hasCollection ? collectionId : null,
|
|
259
340
|
byName,
|
|
260
341
|
resolveColor(ref) {
|
|
261
342
|
const value = resolve(ref)
|
|
@@ -286,6 +367,9 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
|
|
|
286
367
|
current = outer
|
|
287
368
|
}
|
|
288
369
|
},
|
|
289
|
-
|
|
370
|
+
variableModes(theme) {
|
|
371
|
+
const touched = uniq(Object.keys(theme).flatMap((axis) => collectionOfAxis.get(axis) ?? []))
|
|
372
|
+
return Object.fromEntries(touched.map((collection) => [collection.id, modeIn(collection)]))
|
|
373
|
+
}
|
|
290
374
|
}
|
|
291
375
|
}
|
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'
|
|
@@ -298,11 +299,12 @@ function layoutFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
|
|
|
298
299
|
else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing)
|
|
299
300
|
if (node.primaryAxisAlign !== 'MIN') fields.justifyContent = justify[node.primaryAxisAlign]
|
|
300
301
|
if (node.counterAxisAlign !== 'MIN') fields.alignItems = align[node.counterAxisAlign]
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
node.
|
|
304
|
-
node.
|
|
305
|
-
node.
|
|
302
|
+
// A padding bound to a variable is written as its reference, as the reader binds it again.
|
|
303
|
+
const padding: [PenNumber, PenNumber, PenNumber, PenNumber] = [
|
|
304
|
+
variableOr(state, node, 'paddingTop', node.paddingTop),
|
|
305
|
+
variableOr(state, node, 'paddingRight', node.paddingRight),
|
|
306
|
+
variableOr(state, node, 'paddingBottom', node.paddingBottom),
|
|
307
|
+
variableOr(state, node, 'paddingLeft', node.paddingLeft)
|
|
306
308
|
]
|
|
307
309
|
if (padding.some((value) => value !== 0)) fields.padding = padding
|
|
308
310
|
if (node.clipsContent) fields.clip = true
|
|
@@ -415,19 +417,19 @@ function textFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
|
|
|
415
417
|
return fields
|
|
416
418
|
}
|
|
417
419
|
|
|
418
|
-
function cornerFields(node: SceneNode): Partial<PenNode> {
|
|
420
|
+
function cornerFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
|
|
419
421
|
if (node.independentCorners) {
|
|
420
422
|
return {
|
|
421
423
|
cornerRadius: [
|
|
422
|
-
node.topLeftRadius,
|
|
423
|
-
node.topRightRadius,
|
|
424
|
-
node.bottomRightRadius,
|
|
425
|
-
node.bottomLeftRadius
|
|
424
|
+
variableOr(state, node, 'topLeftRadius', rounded(node.topLeftRadius)),
|
|
425
|
+
variableOr(state, node, 'topRightRadius', rounded(node.topRightRadius)),
|
|
426
|
+
variableOr(state, node, 'bottomRightRadius', rounded(node.bottomRightRadius)),
|
|
427
|
+
variableOr(state, node, 'bottomLeftRadius', rounded(node.bottomLeftRadius))
|
|
426
428
|
]
|
|
427
429
|
}
|
|
428
430
|
}
|
|
429
|
-
|
|
430
|
-
return {}
|
|
431
|
+
const radius = variableOr(state, node, 'cornerRadius', rounded(node.cornerRadius))
|
|
432
|
+
return radius === 0 ? {} : { cornerRadius: radius }
|
|
431
433
|
}
|
|
432
434
|
|
|
433
435
|
function variableScalar(value: VariableValue | undefined, state: PenWriteState): PenVariableScalar {
|
|
@@ -445,17 +447,20 @@ function penVariable(
|
|
|
445
447
|
state: PenWriteState
|
|
446
448
|
): PenVariable {
|
|
447
449
|
const modes = collection?.modes ?? []
|
|
450
|
+
const syntax = variable.codeSyntax ? { codeSyntax: variable.codeSyntax } : {}
|
|
448
451
|
if (modes.length <= 1)
|
|
449
452
|
return {
|
|
450
453
|
type: variableType(variable.type),
|
|
451
|
-
value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state)
|
|
454
|
+
value: variableScalar(variable.valuesByMode[modes[0]?.modeId ?? ''], state),
|
|
455
|
+
...syntax
|
|
452
456
|
}
|
|
453
457
|
return {
|
|
454
458
|
type: variableType(variable.type),
|
|
455
459
|
value: modes.map((mode, index) => ({
|
|
456
460
|
value: variableScalar(variable.valuesByMode[mode.modeId], state),
|
|
457
461
|
...(index === 0 ? {} : { theme: { [collection?.name ?? 'Mode']: mode.name } })
|
|
458
|
-
}))
|
|
462
|
+
})),
|
|
463
|
+
...syntax
|
|
459
464
|
}
|
|
460
465
|
}
|
|
461
466
|
|
|
@@ -480,6 +485,17 @@ function themesOf(state: PenWriteState): PenDocument['themes'] {
|
|
|
480
485
|
)
|
|
481
486
|
}
|
|
482
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
|
+
|
|
483
499
|
function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode): void {
|
|
484
500
|
if (node.name) result.name = node.name
|
|
485
501
|
const placement = penCoordinates(node)
|
|
@@ -511,7 +527,7 @@ function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode)
|
|
|
511
527
|
result,
|
|
512
528
|
strokesOf(state, node),
|
|
513
529
|
layoutFields(state, node),
|
|
514
|
-
cornerFields(node),
|
|
530
|
+
cornerFields(state, node),
|
|
515
531
|
textFields(state, node)
|
|
516
532
|
)
|
|
517
533
|
}
|
|
@@ -614,6 +630,33 @@ export function penDocumentFromGraph(graph: SceneGraph): PenDocument {
|
|
|
614
630
|
if (variablesValue) document.variables = variablesValue
|
|
615
631
|
const themes = themesOf(state)
|
|
616
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
|
|
617
660
|
return document
|
|
618
661
|
}
|
|
619
662
|
|