@pairdraw/pen 0.0.0-stage → 0.16.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,284 @@
1
+ import {
2
+ generateId,
3
+ type SceneGraph,
4
+ type SceneNode,
5
+ type Variable,
6
+ type VariableCollectionMode,
7
+ type VariableType,
8
+ type VariableValue
9
+ } from '@pairdraw/scene-graph'
10
+ import { parseColor } from '@pairdraw/scene-graph/color'
11
+ import { BLACK } from '@pairdraw/scene-graph/constants'
12
+ import type { Color } from '@pairdraw/scene-graph/primitives'
13
+
14
+ import type { PenDocument, PenNumber, PenVariable, PenVariableScalar } from './schema'
15
+
16
+ type Theme = Record<string, string>
17
+
18
+ /**
19
+ * A document's variables, resolved in the theme of the layer being read. pen.dev themes are axes,
20
+ * such as `mode` and `density`, each with its values; every combination of one value per axis is
21
+ * one mode of a single collection, since a variable can depend on several axes at once.
22
+ */
23
+ export interface VarContext {
24
+ /** The collection the document's variables and themes make, or `null` when it has neither. */
25
+ collectionId: string | null
26
+ byName: Map<string, Variable>
27
+ resolveColor(ref: string): Color
28
+ resolveNumber(ref: string): number
29
+ /** The number the variable holds, or nothing when it holds none. */
30
+ numberValue(ref: string): number | undefined
31
+ resolveString(ref: string): string
32
+ resolveBoolean(ref: string): boolean
33
+ /** Merges a layer's theme over its parent's until the returned function is called. */
34
+ enterTheme(theme: Theme): () => void
35
+ /** The mode of the theme being read. */
36
+ modeId(): string
37
+ }
38
+
39
+ export function isVarRef(val: unknown): val is `$${string}` {
40
+ return typeof val === 'string' && val.startsWith('$') && val.length > 1
41
+ }
42
+
43
+ function varName(ref: string): string {
44
+ return ref.slice(1)
45
+ }
46
+
47
+ export function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {
48
+ if (!isVarRef(val)) return
49
+ const variable = ctx.byName.get(varName(val))
50
+ if (variable) node.boundVariables[field] = variable.id
51
+ }
52
+
53
+ /** A number, or the value of the number variable it references. */
54
+ export function resolveNumber(value: PenNumber | undefined, ctx: VarContext, fallback = 0): number {
55
+ if (value === undefined) return fallback
56
+ if (typeof value === 'number') return value
57
+ if (isVarRef(value)) return ctx.resolveNumber(value)
58
+ const parsed = Number(value)
59
+ return Number.isFinite(parsed) ? parsed : fallback
60
+ }
61
+
62
+ /** A number, or the value of the number variable it references; nothing where there is none. */
63
+ export function resolveOptionalNumber(
64
+ value: PenNumber | undefined,
65
+ ctx: VarContext
66
+ ): number | undefined {
67
+ if (value === undefined) return undefined
68
+ if (typeof value === 'number') return value
69
+ if (isVarRef(value)) return ctx.numberValue(value)
70
+ const parsed = Number(value)
71
+ return Number.isFinite(parsed) ? parsed : undefined
72
+ }
73
+
74
+ /** A boolean, or the value of the variable it references. */
75
+ export function resolveBoolean(
76
+ value: boolean | string | undefined,
77
+ ctx: VarContext,
78
+ fallback = true
79
+ ): boolean {
80
+ if (value === undefined) return fallback
81
+ if (typeof value === 'boolean') return value
82
+ return isVarRef(value) ? ctx.resolveBoolean(value) : value !== 'false'
83
+ }
84
+
85
+ /** A string, or the value of the string variable it references. */
86
+ export function resolveString(value: string | undefined, ctx: VarContext): string | undefined {
87
+ return value !== undefined && isVarRef(value) ? ctx.resolveString(value) : value
88
+ }
89
+
90
+ /**
91
+ * Every value a field can take: the value itself, or the value its variable has in each theme,
92
+ * through aliases, with the empty value where a theme has none, as reading resolves it. For
93
+ * loading what a document may draw before it is read in a theme.
94
+ */
95
+ export function possibleValues(value: string | undefined, doc: PenDocument): string[] {
96
+ const themes = combinations(themeAxes(doc))
97
+ const found = new Set<string>()
98
+ const seen = new Set<string>()
99
+ const visit = (raw: PenVariableScalar | undefined) => {
100
+ if (raw === undefined) return
101
+ if (!isVarRef(raw)) {
102
+ found.add(String(raw))
103
+ return
104
+ }
105
+ const name = varName(raw)
106
+ const definition = doc.variables?.[name]
107
+ if (!definition || seen.has(name)) return
108
+ seen.add(name)
109
+ const empty = emptyValue(sceneType(definition.type))
110
+ for (const theme of themes) {
111
+ const themed = rawValue(definition, theme)
112
+ if (themed !== undefined) visit(themed)
113
+ else if (typeof empty !== 'object') found.add(String(empty))
114
+ }
115
+ }
116
+ visit(value)
117
+ return [...found]
118
+ }
119
+
120
+ /** A colour, or the value of the colour variable it references. */
121
+ export function resolveColor(value: string, ctx: VarContext): Color {
122
+ return isVarRef(value) ? ctx.resolveColor(value) : parseColor(value)
123
+ }
124
+
125
+ function sceneType(type: string): VariableType {
126
+ if (type === 'color') return 'COLOR'
127
+ if (type === 'number') return 'FLOAT'
128
+ if (type === 'boolean') return 'BOOLEAN'
129
+ return 'STRING'
130
+ }
131
+
132
+ /** pen.dev leaves a variable without a value in a theme no entry matches: black, zero, or empty. */
133
+ function emptyValue(type: VariableType): VariableValue {
134
+ if (type === 'COLOR') return { ...BLACK }
135
+ if (type === 'FLOAT') return 0
136
+ if (type === 'BOOLEAN') return false
137
+ return ''
138
+ }
139
+
140
+ type Axis = [name: string, values: string[]]
141
+
142
+ /** The document's theme axes that have values. */
143
+ function themeAxes(doc: PenDocument): Axis[] {
144
+ return Object.entries(doc.themes ?? {}).filter(([, values]) => values.length > 0)
145
+ }
146
+
147
+ /** Every combination of one value per axis, the first values first. */
148
+ function combinations(axes: Axis[]): Theme[] {
149
+ return axes.reduce<Theme[]>(
150
+ (themes, [axis, values]) =>
151
+ themes.flatMap((theme) => values.map((value) => ({ ...theme, [axis]: value }))),
152
+ [{}]
153
+ )
154
+ }
155
+
156
+ /**
157
+ * A variable's raw value in a full theme. An entry applies when each of its axes has its value in
158
+ * the theme, and a later one replaces an earlier one, as pen.dev 2.21 resolves them.
159
+ */
160
+ function rawValue(definition: PenVariable, theme: Theme): PenVariableScalar | undefined {
161
+ if (!Array.isArray(definition.value)) return definition.value
162
+ let found: PenVariableScalar | undefined
163
+ for (const entry of definition.value) {
164
+ const entryTheme = Object.entries(entry.theme ?? {})
165
+ if (entryTheme.every(([axis, value]) => theme[axis] === value)) found = entry.value
166
+ }
167
+ return found
168
+ }
169
+
170
+ function sceneValue(
171
+ raw: PenVariableScalar | undefined,
172
+ type: VariableType,
173
+ ids: ReadonlyMap<string, string>
174
+ ): VariableValue {
175
+ if (raw === undefined) return emptyValue(type)
176
+ if (isVarRef(raw)) {
177
+ const aliasId = ids.get(varName(raw))
178
+ return aliasId ? { aliasId } : emptyValue(type)
179
+ }
180
+ if (type === 'COLOR') return typeof raw === 'string' ? parseColor(raw) : emptyValue(type)
181
+ if (type === 'FLOAT') return typeof raw === 'number' ? raw : Number(raw) || 0
182
+ if (type === 'BOOLEAN') return typeof raw === 'boolean' ? raw : raw === 'true'
183
+ return String(raw)
184
+ }
185
+
186
+ function themeKey(theme: Theme, axes: Axis[]): string {
187
+ return axes.map(([axis]) => theme[axis]).join('\u0000')
188
+ }
189
+
190
+ export function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {
191
+ const axes = themeAxes(doc)
192
+ const themes = combinations(axes)
193
+ const modes: VariableCollectionMode[] = themes.map((theme) => ({
194
+ modeId: generateId(),
195
+ name: axes.length === 0 ? 'Default' : axes.map(([axis]) => theme[axis]).join(' / ')
196
+ }))
197
+ const modeByTheme = new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index]]))
198
+ const definitions = Object.entries(doc.variables ?? {})
199
+ const collectionId = generateId()
200
+ // A document with neither variables nor themes, such as a new one, gets no empty collection.
201
+ const hasCollection = definitions.length > 0 || axes.length > 0
202
+ if (hasCollection) {
203
+ graph.addCollection({
204
+ id: collectionId,
205
+ name: axes.length === 1 ? axes[0][0] : 'Theme',
206
+ modes,
207
+ defaultModeId: modes[0].modeId,
208
+ variableIds: []
209
+ })
210
+ }
211
+
212
+ const ids = new Map(definitions.map(([name]) => [name, generateId()]))
213
+ const byName = new Map<string, Variable>()
214
+ const byId = new Map<string, Variable>()
215
+ for (const [name, definition] of definitions) {
216
+ const type = sceneType(definition.type)
217
+ const variable: Variable = {
218
+ id: ids.get(name) ?? generateId(),
219
+ name,
220
+ type,
221
+ collectionId,
222
+ valuesByMode: Object.fromEntries(
223
+ themes.map((theme, index) => [
224
+ modes[index].modeId,
225
+ sceneValue(rawValue(definition, theme), type, ids)
226
+ ])
227
+ ),
228
+ description: '',
229
+ hiddenFromPublishing: false
230
+ }
231
+ graph.addVariable(variable)
232
+ byName.set(name, variable)
233
+ byId.set(variable.id, variable)
234
+ }
235
+
236
+ let current: Theme = themes[0]
237
+ const modeId = () => modeByTheme.get(themeKey(current, axes))?.modeId ?? modes[0].modeId
238
+
239
+ /** A variable's value in the current theme, following aliases. */
240
+ function resolve(ref: string): VariableValue | undefined {
241
+ let variable = byName.get(varName(ref))
242
+ for (let hops = 0; variable && hops <= byName.size; hops++) {
243
+ const value = variable.valuesByMode[modeId()]
244
+ if (typeof value !== 'object' || !('aliasId' in value)) return value
245
+ variable = byId.get(value.aliasId)
246
+ }
247
+ return undefined
248
+ }
249
+
250
+ return {
251
+ collectionId: hasCollection ? collectionId : null,
252
+ byName,
253
+ resolveColor(ref) {
254
+ const value = resolve(ref)
255
+ return typeof value === 'object' && 'r' in value ? value : { ...BLACK }
256
+ },
257
+ resolveNumber(ref) {
258
+ return this.numberValue(ref) ?? 0
259
+ },
260
+ numberValue(ref) {
261
+ const value = resolve(ref)
262
+ return typeof value === 'number' ? value : undefined
263
+ },
264
+ resolveString(ref) {
265
+ const value = resolve(ref)
266
+ return typeof value === 'string' ? value : ''
267
+ },
268
+ resolveBoolean(ref) {
269
+ const value = resolve(ref)
270
+ return typeof value === 'boolean' ? value : value !== undefined && value !== 'false'
271
+ },
272
+ enterTheme(theme) {
273
+ const outer = current
274
+ const known = Object.entries(theme).filter(([axis, value]) =>
275
+ axes.some(([name, values]) => name === axis && values.includes(value))
276
+ )
277
+ current = { ...outer, ...Object.fromEntries(known) }
278
+ return () => {
279
+ current = outer
280
+ }
281
+ },
282
+ modeId
283
+ }
284
+ }