@pairdraw/pen 0.19.1 → 0.19.2

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/nodes.ts CHANGED
@@ -308,7 +308,7 @@ export function applyPenProperties(node: SceneNode, pen: PenNode, build: Build):
308
308
  layoutGrow: 0,
309
309
  layoutAlignSelf: 'AUTO',
310
310
  boundVariables: {},
311
- variableModes: pen.theme && ctx.collectionId ? { [ctx.collectionId]: ctx.modeId() } : {}
311
+ variableModes: pen.theme ? ctx.variableModes(pen.theme) : {}
312
312
  } satisfies Partial<SceneNode>)
313
313
  bindIfVar(node, 'visible', pen.enabled, ctx)
314
314
  bindIfVar(node, 'opacity', pen.opacity, ctx)
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
- /** The mode of the theme being read. */
36
- modeId(): string
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}` {
@@ -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 themes = combinations(themeAxes(doc))
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
- for (const theme of themes) {
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,41 +198,93 @@ function themeKey(theme: Theme, axes: Axis[]): string {
194
198
  return axes.map(([axis]) => theme[axis]).join('\u0000')
195
199
  }
196
200
 
197
- export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {
198
- const axes = themeAxes(doc)
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
+ function addThemeCollection(graph: SceneGraph, axes: Axis[]): ThemeCollection {
199
234
  const themes = combinations(axes)
200
235
  const modes: VariableCollectionMode[] = themes.map((theme) => ({
201
236
  modeId: generateId(),
202
237
  name: axes.length === 0 ? 'Default' : axes.map(([axis]) => theme[axis]).join(' / ')
203
238
  }))
204
- const modeByTheme = new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index]]))
239
+ const id = generateId()
240
+ graph.addCollection({
241
+ id,
242
+ name: axes.length === 0 ? 'Variables' : axes.map(([axis]) => axis).join(' / '),
243
+ modes,
244
+ defaultModeId: modes[0].modeId,
245
+ variableIds: []
246
+ })
247
+ const modeByTheme = new Map(
248
+ themes.map((theme, index) => [themeKey(theme, axes), modes[index].modeId])
249
+ )
250
+ return { id, axes, themes, modes, modeByTheme }
251
+ }
252
+
253
+ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {
254
+ const axes = themeAxes(doc)
205
255
  const definitions = Object.entries(doc.variables ?? {})
206
- const collectionId = generateId()
207
- // A document with neither variables nor themes, such as a new one, gets no empty collection.
208
- const hasCollection = definitions.length > 0 || axes.length > 0
209
- if (hasCollection) {
210
- graph.addCollection({
211
- id: collectionId,
212
- name: axes.length === 1 ? axes[0][0] : 'Theme',
213
- modes,
214
- defaultModeId: modes[0].modeId,
215
- variableIds: []
216
- })
256
+ const collections = axisGroups(
257
+ axes,
258
+ definitions.map(([, definition]) => definition)
259
+ ).map((group) => addThemeCollection(graph, group))
260
+ const collectionOfAxis = new Map(
261
+ collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection]))
262
+ )
263
+ // A variable no axis decides goes with the first axes, where it holds one value in every mode. A
264
+ // document with neither variables nor themes, such as a new one, gets no empty collection.
265
+ const fallback = collections[0] ?? (definitions.length > 0 ? addThemeCollection(graph, []) : null)
266
+ const collectionFor = (definition: PenVariable): ThemeCollection | null => {
267
+ const first = axesOf(definition, axes).at(0)
268
+ return (first && collectionOfAxis.get(first[0])) || fallback
217
269
  }
218
270
 
219
271
  const ids = new Map(definitions.map(([name]) => [name, generateId()]))
220
272
  const byName = new Map<string, Variable>()
221
273
  const byId = new Map<string, Variable>()
274
+ const collectionById = new Map<string, ThemeCollection>()
222
275
  for (const [name, definition] of definitions) {
223
276
  const type = sceneType(definition.type)
277
+ const collection = collectionFor(definition)
278
+ if (!collection) continue
279
+ collectionById.set(collection.id, collection)
224
280
  const variable: Variable = {
225
281
  id: ids.get(name) ?? generateId(),
226
282
  name,
227
283
  type,
228
- collectionId,
284
+ collectionId: collection.id,
229
285
  valuesByMode: Object.fromEntries(
230
- themes.map((theme, index) => [
231
- modes[index].modeId,
286
+ collection.themes.map((theme, index) => [
287
+ collection.modes[index].modeId,
232
288
  sceneValue(rawValue(definition, theme), type, ids)
233
289
  ])
234
290
  ),
@@ -240,14 +296,16 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
240
296
  byId.set(variable.id, variable)
241
297
  }
242
298
 
243
- let current: Theme = themes[0]
244
- const modeId = () => modeByTheme.get(themeKey(current, axes))?.modeId ?? modes[0].modeId
299
+ let current: Theme = Object.fromEntries(axes.map(([axis, values]) => [axis, values[0]]))
300
+ const modeIn = (collection: ThemeCollection) =>
301
+ collection.modeByTheme.get(themeKey(current, collection.axes)) ?? collection.modes[0].modeId
245
302
 
246
303
  /** A variable's value in the current theme, following aliases. */
247
304
  function resolve(ref: string): VariableValue | undefined {
248
305
  let variable = byName.get(varName(ref))
249
306
  for (let hops = 0; variable && hops <= byName.size; hops++) {
250
- const value = variable.valuesByMode[modeId()]
307
+ const collection = collectionById.get(variable.collectionId)
308
+ const value = collection ? variable.valuesByMode[modeIn(collection)] : undefined
251
309
  if (typeof value !== 'object' || !('aliasId' in value)) return value
252
310
  variable = byId.get(value.aliasId)
253
311
  }
@@ -255,7 +313,6 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
255
313
  }
256
314
 
257
315
  return {
258
- collectionId: hasCollection ? collectionId : null,
259
316
  byName,
260
317
  resolveColor(ref) {
261
318
  const value = resolve(ref)
@@ -286,6 +343,9 @@ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext
286
343
  current = outer
287
344
  }
288
345
  },
289
- modeId
346
+ variableModes(theme) {
347
+ const touched = uniq(Object.keys(theme).flatMap((axis) => collectionOfAxis.get(axis) ?? []))
348
+ return Object.fromEntries(touched.map((collection) => [collection.id, modeIn(collection)]))
349
+ }
290
350
  }
291
351
  }
package/src/write.ts CHANGED
@@ -298,11 +298,12 @@ function layoutFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
298
298
  else if (node.itemSpacing !== 0) fields.gap = rounded(node.itemSpacing)
299
299
  if (node.primaryAxisAlign !== 'MIN') fields.justifyContent = justify[node.primaryAxisAlign]
300
300
  if (node.counterAxisAlign !== 'MIN') fields.alignItems = align[node.counterAxisAlign]
301
- const padding: [number, number, number, number] = [
302
- node.paddingTop,
303
- node.paddingRight,
304
- node.paddingBottom,
305
- node.paddingLeft
301
+ // A padding bound to a variable is written as its reference, as the reader binds it again.
302
+ const padding: [PenNumber, PenNumber, PenNumber, PenNumber] = [
303
+ variableOr(state, node, 'paddingTop', node.paddingTop),
304
+ variableOr(state, node, 'paddingRight', node.paddingRight),
305
+ variableOr(state, node, 'paddingBottom', node.paddingBottom),
306
+ variableOr(state, node, 'paddingLeft', node.paddingLeft)
306
307
  ]
307
308
  if (padding.some((value) => value !== 0)) fields.padding = padding
308
309
  if (node.clipsContent) fields.clip = true
@@ -415,19 +416,19 @@ function textFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
415
416
  return fields
416
417
  }
417
418
 
418
- function cornerFields(node: SceneNode): Partial<PenNode> {
419
+ function cornerFields(state: PenWriteState, node: SceneNode): Partial<PenNode> {
419
420
  if (node.independentCorners) {
420
421
  return {
421
422
  cornerRadius: [
422
- node.topLeftRadius,
423
- node.topRightRadius,
424
- node.bottomRightRadius,
425
- node.bottomLeftRadius
423
+ variableOr(state, node, 'topLeftRadius', rounded(node.topLeftRadius)),
424
+ variableOr(state, node, 'topRightRadius', rounded(node.topRightRadius)),
425
+ variableOr(state, node, 'bottomRightRadius', rounded(node.bottomRightRadius)),
426
+ variableOr(state, node, 'bottomLeftRadius', rounded(node.bottomLeftRadius))
426
427
  ]
427
428
  }
428
429
  }
429
- if (node.cornerRadius !== 0) return { cornerRadius: rounded(node.cornerRadius) }
430
- return {}
430
+ const radius = variableOr(state, node, 'cornerRadius', rounded(node.cornerRadius))
431
+ return radius === 0 ? {} : { cornerRadius: radius }
431
432
  }
432
433
 
433
434
  function variableScalar(value: VariableValue | undefined, state: PenWriteState): PenVariableScalar {
@@ -511,7 +512,7 @@ function basicNodeFields(state: PenWriteState, node: SceneNode, result: PenNode)
511
512
  result,
512
513
  strokesOf(state, node),
513
514
  layoutFields(state, node),
514
- cornerFields(node),
515
+ cornerFields(state, node),
515
516
  textFields(state, node)
516
517
  )
517
518
  }