@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.
@@ -1,3 +1,4 @@
1
+ import { groupBy, uniq } from "es-toolkit/array";
1
2
  import { generateId } from "@pairdraw/scene-graph";
2
3
  import { parseColor } from "@pairdraw/scene-graph/color";
3
4
  import { BLACK } from "@pairdraw/scene-graph/constants";
@@ -14,7 +15,10 @@ function varName(ref) {
14
15
  function bindIfVar(node, field, val, ctx) {
15
16
  if (!isVarRef(val)) return;
16
17
  const variable = ctx.byName.get(varName(val));
17
- if (variable) node.boundVariables[field] = variable.id;
18
+ if (variable) node.boundVariables = {
19
+ ...node.boundVariables,
20
+ [field]: variable.id
21
+ };
18
22
  }
19
23
  /** A number, or the value of the number variable it references. */
20
24
  function resolveNumber(value, ctx, fallback = 0) {
@@ -50,7 +54,7 @@ function resolveString(value, ctx) {
50
54
  * loading what a document may draw before it is read in a theme.
51
55
  */
52
56
  function possibleValues(value, doc) {
53
- const themes = combinations(themeAxes(doc));
57
+ const axes = themeAxes(doc);
54
58
  const found = /* @__PURE__ */ new Set();
55
59
  const seen = /* @__PURE__ */ new Set();
56
60
  const visit = (raw) => {
@@ -64,7 +68,7 @@ function possibleValues(value, doc) {
64
68
  if (!definition || seen.has(name)) return;
65
69
  seen.add(name);
66
70
  const empty = emptyValue(sceneType(definition.type));
67
- for (const theme of themes) {
71
+ for (const theme of combinations(axesOf(definition, axes))) {
68
72
  const themed = rawValue(definition, theme);
69
73
  if (themed !== void 0) visit(themed);
70
74
  else if (typeof empty !== "object") found.add(String(empty));
@@ -128,55 +132,109 @@ function sceneValue(raw, type, ids) {
128
132
  function themeKey(theme, axes) {
129
133
  return axes.map(([axis]) => theme[axis]).join("\0");
130
134
  }
131
- function buildVarContext(graph, doc) {
132
- const axes = themeAxes(doc);
135
+ /** The document's axes a variable's values name, in the document's order. */
136
+ function axesOf(definition, axes) {
137
+ if (!Array.isArray(definition.value)) return [];
138
+ const named = new Set(definition.value.flatMap((entry) => Object.keys(entry.theme ?? {})));
139
+ return axes.filter(([axis]) => named.has(axis));
140
+ }
141
+ /** The axes in groups, each joining the axes some variable's values combine, through any chain. */
142
+ function axisGroups(axes, definitions) {
143
+ const parent = new Map(axes.map(([axis]) => [axis, axis]));
144
+ const root = (axis) => {
145
+ const next = parent.get(axis) ?? axis;
146
+ return next === axis ? axis : root(next);
147
+ };
148
+ for (const definition of definitions) {
149
+ const named = axesOf(definition, axes);
150
+ const first = named.at(0);
151
+ if (!first) continue;
152
+ for (const [axis] of named.slice(1)) parent.set(root(axis), root(first[0]));
153
+ }
154
+ return Object.values(groupBy(axes, ([axis]) => root(axis)));
155
+ }
156
+ /** The selector each mode applies in, which Pencil itself does not record. */
157
+ function applyModeConditions(graph, doc, collections) {
158
+ for (const created of collections) {
159
+ const collection = graph.variableCollections.get(created.id);
160
+ const conditions = collection && doc.modeConditions?.[collection.name];
161
+ if (!collection || !conditions) continue;
162
+ for (const mode of collection.modes) {
163
+ const condition = conditions[mode.name];
164
+ if (condition) mode.condition = condition;
165
+ }
166
+ }
167
+ }
168
+ function addThemeCollection(graph, axes) {
133
169
  const themes = combinations(axes);
134
170
  const modes = themes.map((theme) => ({
135
171
  modeId: generateId(),
136
172
  name: axes.length === 0 ? "Default" : axes.map(([axis]) => theme[axis]).join(" / ")
137
173
  }));
138
- const modeByTheme = new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index]]));
139
- const definitions = Object.entries(doc.variables ?? {});
140
- const collectionId = generateId();
141
- const hasCollection = definitions.length > 0 || axes.length > 0;
142
- if (hasCollection) graph.addCollection({
143
- id: collectionId,
144
- name: axes.length === 1 ? axes[0][0] : "Theme",
174
+ const id = generateId();
175
+ graph.addCollection({
176
+ id,
177
+ name: axes.length === 0 ? "Variables" : axes.map(([axis]) => axis).join(" / "),
145
178
  modes,
146
179
  defaultModeId: modes[0].modeId,
147
180
  variableIds: []
148
181
  });
182
+ return {
183
+ id,
184
+ axes,
185
+ themes,
186
+ modes,
187
+ modeByTheme: new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index].modeId]))
188
+ };
189
+ }
190
+ function buildVarContext(graph, doc, onUnknownVariable) {
191
+ const axes = themeAxes(doc);
192
+ const definitions = Object.entries(doc.variables ?? {});
193
+ const collections = axisGroups(axes, definitions.map(([, definition]) => definition)).map((group) => addThemeCollection(graph, group));
194
+ applyModeConditions(graph, doc, collections);
195
+ const collectionOfAxis = new Map(collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection])));
196
+ const fallback = collections[0] ?? (definitions.length > 0 ? addThemeCollection(graph, []) : null);
197
+ const collectionFor = (definition) => {
198
+ const first = axesOf(definition, axes).at(0);
199
+ return first && collectionOfAxis.get(first[0]) || fallback;
200
+ };
149
201
  const ids = new Map(definitions.map(([name]) => [name, generateId()]));
150
202
  const byName = /* @__PURE__ */ new Map();
151
203
  const byId = /* @__PURE__ */ new Map();
204
+ const collectionById = /* @__PURE__ */ new Map();
152
205
  for (const [name, definition] of definitions) {
153
206
  const type = sceneType(definition.type);
207
+ const collection = collectionFor(definition);
208
+ if (!collection) continue;
209
+ collectionById.set(collection.id, collection);
154
210
  const variable = {
155
211
  id: ids.get(name) ?? generateId(),
156
212
  name,
157
213
  type,
158
- collectionId,
159
- valuesByMode: Object.fromEntries(themes.map((theme, index) => [modes[index].modeId, sceneValue(rawValue(definition, theme), type, ids)])),
214
+ collectionId: collection.id,
215
+ valuesByMode: Object.fromEntries(collection.themes.map((theme, index) => [collection.modes[index].modeId, sceneValue(rawValue(definition, theme), type, ids)])),
160
216
  description: "",
161
- hiddenFromPublishing: false
217
+ hiddenFromPublishing: false,
218
+ ...definition.codeSyntax ? { codeSyntax: definition.codeSyntax } : {}
162
219
  };
163
220
  graph.addVariable(variable);
164
221
  byName.set(name, variable);
165
222
  byId.set(variable.id, variable);
166
223
  }
167
- let current = themes[0];
168
- const modeId = () => modeByTheme.get(themeKey(current, axes))?.modeId ?? modes[0].modeId;
224
+ let current = Object.fromEntries(axes.map(([axis, values]) => [axis, values[0]]));
225
+ const modeIn = (collection) => collection.modeByTheme.get(themeKey(current, collection.axes)) ?? collection.modes[0].modeId;
169
226
  /** A variable's value in the current theme, following aliases. */
170
227
  function resolve(ref) {
171
228
  let variable = byName.get(varName(ref));
229
+ if (!variable) onUnknownVariable?.(varName(ref));
172
230
  for (let hops = 0; variable && hops <= byName.size; hops++) {
173
- const value = variable.valuesByMode[modeId()];
231
+ const collection = collectionById.get(variable.collectionId);
232
+ const value = collection ? variable.valuesByMode[modeIn(collection)] : void 0;
174
233
  if (typeof value !== "object" || !("aliasId" in value)) return value;
175
234
  variable = byId.get(value.aliasId);
176
235
  }
177
236
  }
178
237
  return {
179
- collectionId: hasCollection ? collectionId : null,
180
238
  byName,
181
239
  resolveColor(ref) {
182
240
  const value = resolve(ref);
@@ -208,7 +266,10 @@ function buildVarContext(graph, doc) {
208
266
  current = outer;
209
267
  };
210
268
  },
211
- modeId
269
+ variableModes(theme) {
270
+ const touched = uniq(Object.keys(theme).flatMap((axis) => collectionOfAxis.get(axis) ?? []));
271
+ return Object.fromEntries(touched.map((collection) => [collection.id, modeIn(collection)]));
272
+ }
212
273
  };
213
274
  }
214
275
  //#endregion
@@ -431,6 +492,8 @@ const ANNOTATION_COLORS = {
431
492
  prompt: STICKY_COLORS.blue,
432
493
  context: STICKY_COLORS.gray
433
494
  };
495
+ /** The annotation type names, which the reader knows even though they map to stickies. */
496
+ const ANNOTATION_TYPES = Object.keys(ANNOTATION_COLORS);
434
497
  function isAnnotation(pen) {
435
498
  return Object.hasOwn(ANNOTATION_COLORS, pen.type);
436
499
  }
@@ -510,6 +573,6 @@ function applyAnnotation(node, pen, build) {
510
573
  build.effective.set(node.id, pen);
511
574
  }
512
575
  //#endregion
513
- export { PEN_PLUGIN_DATA_NAMESPACE, UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, possibleValues, resolveBoolean, resolveColor, resolveNumber, resolveOptionalNumber, resolveString, unresolvedRef };
576
+ export { ANNOTATION_TYPES, PEN_PLUGIN_DATA_NAMESPACE, UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, possibleValues, resolveBoolean, resolveColor, resolveNumber, resolveOptionalNumber, resolveString, unresolvedRef };
514
577
 
515
578
  //# sourceMappingURL=annotations.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"annotations.js","names":[],"sources":["../../src/variables.ts","../../src/plugin-data.ts","../../src/layout.ts","../../src/annotations.ts"],"sourcesContent":["import {\n generateId,\n type SceneGraph,\n type SceneNode,\n type Variable,\n type VariableCollectionMode,\n type VariableType,\n type VariableValue\n} from '@pairdraw/scene-graph'\nimport { parseColor } from '@pairdraw/scene-graph/color'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { PenDocument, PenNumber, PenVariable, PenVariableScalar } from './schema'\n\ntype Theme = Record<string, string>\n\n/**\n * A document's variables, resolved in the theme of the layer being read. pen.dev themes are axes,\n * such as `mode` and `density`, each with its values; every combination of one value per axis is\n * one mode of a single collection, since a variable can depend on several axes at once.\n */\nexport interface VarContext {\n /** The collection the document's variables and themes make, or `null` when it has neither. */\n collectionId: string | null\n byName: Map<string, Variable>\n resolveColor(ref: string): Color\n resolveNumber(ref: string): number\n /** The number the variable holds, or nothing when it holds none. */\n numberValue(ref: string): number | undefined\n resolveString(ref: string): string\n resolveBoolean(ref: string): boolean\n /** Merges a layer's theme over its parent's until the returned function is called. */\n enterTheme(theme: Theme): () => void\n /** The mode of the theme being read. */\n modeId(): string\n}\n\nexport function isVarRef(val: unknown): val is `$${string}` {\n return typeof val === 'string' && val.startsWith('$') && val.length > 1\n}\n\nfunction varName(ref: string): string {\n return ref.slice(1)\n}\n\nexport function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {\n if (!isVarRef(val)) return\n const variable = ctx.byName.get(varName(val))\n if (variable) node.boundVariables[field] = variable.id\n}\n\n/** A number, or the value of the number variable it references. */\nexport function resolveNumber(value: PenNumber | undefined, ctx: VarContext, fallback = 0): number {\n if (value === undefined) return fallback\n if (typeof value === 'number') return value\n if (isVarRef(value)) return ctx.resolveNumber(value)\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : fallback\n}\n\n/** A number, or the value of the number variable it references; nothing where there is none. */\nexport function resolveOptionalNumber(\n value: PenNumber | undefined,\n ctx: VarContext\n): number | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'number') return value\n if (isVarRef(value)) return ctx.numberValue(value)\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/** A boolean, or the value of the variable it references. */\nexport function resolveBoolean(\n value: boolean | string | undefined,\n ctx: VarContext,\n fallback = true\n): boolean {\n if (value === undefined) return fallback\n if (typeof value === 'boolean') return value\n if (isVarRef(value)) return ctx.resolveBoolean(value)\n // Text other than true or false, such as `no` or `0`, reads as the default, as a missing\n // value does.\n const text = value.toLowerCase()\n return text === 'true' || text === 'false' ? text === 'true' : fallback\n}\n\n/** A string, or the value of the string variable it references. */\nexport function resolveString(value: string | undefined, ctx: VarContext): string | undefined {\n return value !== undefined && isVarRef(value) ? ctx.resolveString(value) : value\n}\n\n/**\n * Every value a field can take: the value itself, or the value its variable has in each theme,\n * through aliases, with the empty value where a theme has none, as reading resolves it. For\n * loading what a document may draw before it is read in a theme.\n */\nexport function possibleValues(value: string | undefined, doc: PenDocument): string[] {\n const themes = combinations(themeAxes(doc))\n const found = new Set<string>()\n const seen = new Set<string>()\n const visit = (raw: PenVariableScalar | undefined) => {\n if (raw === undefined) return\n if (!isVarRef(raw)) {\n found.add(String(raw))\n return\n }\n const name = varName(raw)\n const definition = doc.variables?.[name]\n if (!definition || seen.has(name)) return\n seen.add(name)\n const empty = emptyValue(sceneType(definition.type))\n for (const theme of themes) {\n const themed = rawValue(definition, theme)\n if (themed !== undefined) visit(themed)\n else if (typeof empty !== 'object') found.add(String(empty))\n }\n }\n visit(value)\n return [...found]\n}\n\n/** A colour, or the value of the colour variable it references. */\nexport function resolveColor(value: string, ctx: VarContext): Color {\n return isVarRef(value) ? ctx.resolveColor(value) : parseColor(value)\n}\n\nfunction sceneType(type: string): VariableType {\n if (type === 'color') return 'COLOR'\n if (type === 'number') return 'FLOAT'\n if (type === 'boolean') return 'BOOLEAN'\n return 'STRING'\n}\n\n/** pen.dev leaves a variable without a value in a theme no entry matches: black, zero, or empty. */\nfunction emptyValue(type: VariableType): VariableValue {\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\ntype Axis = [name: string, values: string[]]\n\n/** The document's theme axes that have values. */\nfunction themeAxes(doc: PenDocument): Axis[] {\n return Object.entries(doc.themes ?? {}).filter(([, values]) => values.length > 0)\n}\n\n/** Every combination of one value per axis, the first values first. */\nfunction combinations(axes: Axis[]): Theme[] {\n return axes.reduce<Theme[]>(\n (themes, [axis, values]) =>\n themes.flatMap((theme) => values.map((value) => ({ ...theme, [axis]: value }))),\n [{}]\n )\n}\n\n/**\n * A variable's raw value in a full theme. An entry applies when each of its axes has its value in\n * the theme, and a later one replaces an earlier one, as pen.dev 2.21 resolves them.\n */\nfunction rawValue(definition: PenVariable, theme: Theme): PenVariableScalar | undefined {\n if (!Array.isArray(definition.value)) return definition.value\n let found: PenVariableScalar | undefined\n for (const entry of definition.value) {\n const entryTheme = Object.entries(entry.theme ?? {})\n if (entryTheme.every(([axis, value]) => theme[axis] === value)) found = entry.value\n }\n return found\n}\n\nfunction sceneValue(\n raw: PenVariableScalar | undefined,\n type: VariableType,\n ids: ReadonlyMap<string, string>\n): VariableValue {\n if (raw === undefined) return emptyValue(type)\n if (isVarRef(raw)) {\n const aliasId = ids.get(varName(raw))\n return aliasId ? { aliasId } : emptyValue(type)\n }\n if (type === 'COLOR') return typeof raw === 'string' ? parseColor(raw) : emptyValue(type)\n if (type === 'FLOAT') {\n const value = Number(raw)\n return Number.isFinite(value) ? value : 0\n }\n if (type === 'BOOLEAN') return typeof raw === 'boolean' ? raw : raw === 'true'\n return String(raw)\n}\n\nfunction themeKey(theme: Theme, axes: Axis[]): string {\n return axes.map(([axis]) => theme[axis]).join('\\u0000')\n}\n\nexport function buildVarContext(graph: SceneGraph, doc: PenDocument): VarContext {\n const axes = themeAxes(doc)\n const themes = combinations(axes)\n const modes: VariableCollectionMode[] = themes.map((theme) => ({\n modeId: generateId(),\n name: axes.length === 0 ? 'Default' : axes.map(([axis]) => theme[axis]).join(' / ')\n }))\n const modeByTheme = new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index]]))\n const definitions = Object.entries(doc.variables ?? {})\n const collectionId = generateId()\n // A document with neither variables nor themes, such as a new one, gets no empty collection.\n const hasCollection = definitions.length > 0 || axes.length > 0\n if (hasCollection) {\n graph.addCollection({\n id: collectionId,\n name: axes.length === 1 ? axes[0][0] : 'Theme',\n modes,\n defaultModeId: modes[0].modeId,\n variableIds: []\n })\n }\n\n const ids = new Map(definitions.map(([name]) => [name, generateId()]))\n const byName = new Map<string, Variable>()\n const byId = new Map<string, Variable>()\n for (const [name, definition] of definitions) {\n const type = sceneType(definition.type)\n const variable: Variable = {\n id: ids.get(name) ?? generateId(),\n name,\n type,\n collectionId,\n valuesByMode: Object.fromEntries(\n themes.map((theme, index) => [\n modes[index].modeId,\n sceneValue(rawValue(definition, theme), type, ids)\n ])\n ),\n description: '',\n hiddenFromPublishing: false\n }\n graph.addVariable(variable)\n byName.set(name, variable)\n byId.set(variable.id, variable)\n }\n\n let current: Theme = themes[0]\n const modeId = () => modeByTheme.get(themeKey(current, axes))?.modeId ?? modes[0].modeId\n\n /** A variable's value in the current theme, following aliases. */\n function resolve(ref: string): VariableValue | undefined {\n let variable = byName.get(varName(ref))\n for (let hops = 0; variable && hops <= byName.size; hops++) {\n const value = variable.valuesByMode[modeId()]\n if (typeof value !== 'object' || !('aliasId' in value)) return value\n variable = byId.get(value.aliasId)\n }\n return undefined\n }\n\n return {\n collectionId: hasCollection ? collectionId : null,\n byName,\n resolveColor(ref) {\n const value = resolve(ref)\n return typeof value === 'object' && 'r' in value ? value : { ...BLACK }\n },\n resolveNumber(ref) {\n return this.numberValue(ref) ?? 0\n },\n numberValue(ref) {\n const value = resolve(ref)\n return typeof value === 'number' ? value : undefined\n },\n resolveString(ref) {\n const value = resolve(ref)\n return typeof value === 'string' ? value : ''\n },\n resolveBoolean(ref) {\n const value = resolve(ref)\n return typeof value === 'boolean' ? value : value !== undefined && value !== 'false'\n },\n enterTheme(theme) {\n const outer = current\n const known = Object.entries(theme).filter(([axis, value]) =>\n axes.some(([name, values]) => name === axis && values.includes(value))\n )\n current = { ...outer, ...Object.fromEntries(known) }\n return () => {\n current = outer\n }\n },\n modeId\n }\n}\n","import type { PluginDataEntry, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { PenNode, PenOverride } from './schema'\n\n/**\n * The shared plugin data namespace that keeps the pen.dev fields a layer has no field for, so\n * agents can read them with `getSharedPluginData('pen', key)` and a `.pen` writer can write them\n * back. Each value is its field's JSON.\n */\nexport const PEN_PLUGIN_DATA_NAMESPACE = 'pen'\n\n/**\n * The pen.dev fields kept as plugin data: notes for agents (`context`, `metadata`), the frame an\n * agent is working on (`placeholder`), the components suggested for a slot (`slot`), and what a\n * `prompt` or `context` node was, with the model a prompt asks. A `script` or `browser` node, which\n * reads as a placeholder frame, keeps its file and inputs or its page and view; a `ref` whose\n * component could not be found keeps the ID it names; and a label a placeholder was given says so.\n */\nconst PEN_PLUGIN_DATA_KEYS = [\n 'type',\n 'ref',\n 'context',\n 'metadata',\n 'placeholder',\n 'slot',\n 'model',\n 'scriptUri',\n 'inputs',\n 'url',\n 'deviceId',\n 'zoom',\n 'scrollX',\n 'scrollY',\n 'generated'\n] as const\n\ntype PenPluginDataKey = (typeof PEN_PLUGIN_DATA_KEYS)[number]\n\n/** Node types kept as plugin data on the layer they become. */\nconst KEPT_TYPES: ReadonlySet<string> = new Set(['prompt', 'context', 'script', 'browser'])\n\n/**\n * The field a `ref` whose component is missing reads with, holding the ID it names: the layer is a\n * placeholder frame, and keeps being a `ref` as plugin data.\n */\nexport const UNRESOLVED_REF = 'unresolvedRef'\n\n/** The ID a placeholder for a missing component names, or undefined for any other layer. */\nexport function unresolvedRef(pen: PenOverride): string | undefined {\n const ref = pen[UNRESOLVED_REF]\n return typeof ref === 'string' ? ref : undefined\n}\n\n/** As `setSharedPluginData` stores an entry, so the Figma API reads and replaces it. */\nfunction entry(key: PenPluginDataKey, value: unknown): PluginDataEntry {\n return {\n pluginId: PEN_PLUGIN_DATA_NAMESPACE,\n key: `${PEN_PLUGIN_DATA_NAMESPACE}/${key}`,\n value: JSON.stringify(value)\n }\n}\n\nfunction penEntries(pen: PenNode): PluginDataEntry[] {\n const missing = unresolvedRef(pen)\n return PEN_PLUGIN_DATA_KEYS.flatMap((key) => {\n if (key === 'type') {\n if (missing !== undefined) return [entry(key, 'ref')]\n return KEPT_TYPES.has(pen.type) ? [entry(key, pen.type)] : []\n }\n // A resolved `ref` is an instance, which says what it shows itself.\n if (key === 'ref') return missing === undefined ? [] : [entry(key, missing)]\n const value = pen[key]\n return value === undefined ? [] : [entry(key, value)]\n })\n}\n\n/**\n * Replaces the layer's pen.dev plugin data with the fields `pen` carries, keeping every other\n * entry, so applying a layer's fields again with an override's merged in leaves one of each.\n */\nexport function applyPenPluginData(node: SceneNode, pen: PenNode): void {\n const others = node.pluginData.filter((item) => item.pluginId !== PEN_PLUGIN_DATA_NAMESPACE)\n const own = penEntries(pen)\n if (own.length === 0 && others.length === node.pluginData.length) return\n node.pluginData = [...others, ...own]\n}\n","import type {\n LayoutAlign,\n LayoutCounterAlign,\n LayoutMode,\n LayoutSizing,\n SceneNode\n} from '@pairdraw/scene-graph'\nimport { parseAutoLayoutDirection } from '@pairdraw/scene-graph/layout'\n\nimport type { PenNode, PenNumber } from './schema'\nimport { bindIfVar, isVarRef, resolveNumber, type VarContext } from './variables'\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\nconst PADDING = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'] as const\n\nexport function applyCornerRadius(\n node: SceneNode,\n radius: PenNode['cornerRadius'],\n ctx: VarContext\n): void {\n if (radius === undefined) return\n if (Array.isArray(radius)) {\n node.independentCorners = true\n for (const [index, field] of CORNERS.entries()) {\n node[field] = resolveNumber(radius[index], ctx)\n bindIfVar(node, field, radius[index], ctx)\n }\n return\n }\n node.cornerRadius = resolveNumber(radius, ctx)\n bindIfVar(node, 'cornerRadius', radius, ctx)\n}\n\n/** pen.dev padding: one value, vertical and horizontal, or top, right, bottom, and left. */\nfunction paddingSides(padding: NonNullable<PenNode['padding']>): PenNumber[] {\n if (!Array.isArray(padding)) return [padding, padding, padding, padding]\n if (padding.length === 2) return [padding[0], padding[1], padding[0], padding[1]]\n return padding\n}\n\nexport function applyPadding(node: SceneNode, padding: PenNode['padding'], ctx: VarContext): void {\n if (padding === undefined) return\n const sides = paddingSides(padding)\n for (const [index, field] of PADDING.entries()) {\n node[field] = resolveNumber(sides[index], ctx)\n bindIfVar(node, field, sides[index], ctx)\n }\n}\n\ninterface ParsedSize {\n value: number\n sizing: LayoutSizing\n /** Fallback used only when fit_content(N) has no children. */\n fitContentFallback?: number\n}\n\nfunction parseParameterizedFallback(value: string, behavior: string): number | undefined {\n const prefix = `${behavior}(`\n if (!value.startsWith(prefix) || !value.endsWith(')')) return undefined\n\n const rawFallback = value.slice(prefix.length, -1).trim()\n if (rawFallback === '') return undefined\n\n const parsedFallback = Number(rawFallback)\n return Number.isFinite(parsedFallback) ? parsedFallback : undefined\n}\n\nfunction parseSizingBehavior(value: string, fallback: number): ParsedSize | undefined {\n if (value === 'fill_container') return { value: fallback, sizing: 'FILL' }\n if (value === 'fit_content') return { value: fallback, sizing: 'HUG' }\n\n // Older generated .pen files used hug_content as an alias for fit_content.\n if (value === 'hug_content') return { value: fallback, sizing: 'HUG' }\n\n const fillFallback = parseParameterizedFallback(value, 'fill_container')\n if (fillFallback !== undefined) return { value: fillFallback, sizing: 'FILL' }\n\n const fitFallback =\n parseParameterizedFallback(value, 'fit_content') ??\n parseParameterizedFallback(value, 'hug_content')\n if (fitFallback !== undefined) {\n return { value: fitFallback, sizing: 'HUG', fitContentFallback: fitFallback }\n }\n return undefined\n}\n\nexport function parseSize(\n value: number | string | undefined,\n fallback: number,\n ctx?: VarContext\n): ParsedSize {\n if (value === undefined) return { value: fallback, sizing: 'FIXED' }\n if (typeof value === 'number') return { value, sizing: 'FIXED' }\n\n const behavior = parseSizingBehavior(value, fallback)\n if (behavior) return behavior\n\n if (isVarRef(value) && ctx) return { value: ctx.resolveNumber(value), sizing: 'FIXED' }\n const parsed = Number(value)\n return { value: Number.isFinite(parsed) ? parsed : fallback, sizing: 'FIXED' }\n}\n\nexport function mapLayoutMode(pen: PenNode): LayoutMode {\n const direction = parseAutoLayoutDirection(pen.layout)\n if (direction) return direction\n return pen.type === 'frame' && pen.layout === undefined ? 'HORIZONTAL' : 'NONE'\n}\n\n/** pen.dev's main axis alignments. */\nconst JUSTIFY_CONTENT: Partial<Record<string, LayoutAlign>> = {\n start: 'MIN',\n center: 'CENTER',\n end: 'MAX',\n space_between: 'SPACE_BETWEEN',\n space_around: 'SPACE_AROUND'\n}\n\nconst ALIGN_ITEMS: Partial<Record<string, LayoutCounterAlign>> = {\n start: 'MIN',\n center: 'CENTER',\n end: 'MAX'\n}\n\nexport function mapJustifyContent(value: string | undefined): LayoutAlign {\n return JUSTIFY_CONTENT[value ?? 'start'] ?? 'MIN'\n}\n\nexport function mapAlignItems(value: string | undefined): LayoutCounterAlign {\n return ALIGN_ITEMS[value ?? 'start'] ?? 'MIN'\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport {\n createSticky,\n DEFAULT_STICKY_COLOR,\n STICKY_COLORS,\n STICKY_SIZE,\n STICKY_WIDE_WIDTH,\n stickyScale,\n stickySublayers,\n stickyWidth\n} from '@pairdraw/scene-graph/generated'\nimport { recordInstanceOverride } from '@pairdraw/scene-graph/instances'\nimport { fillSizingFields } from '@pairdraw/scene-graph/layout'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSize } from './layout'\nimport type { Build } from './nodes'\nimport { applyPenPluginData } from './plugin-data'\nimport type { PenNode } from './schema'\nimport { bindIfVar, resolveBoolean, resolveNumber } from './variables'\n\n/**\n * pen.dev's text annotations: a `note`, a `prompt` for an agent, and a `context` note about the\n * layers around it. Each becomes a sticky note holding its text, in the colour nearest the one\n * pen.dev draws its card in; a prompt and a context note keep what they were as plugin data.\n */\nconst ANNOTATION_COLORS: Readonly<Record<string, Color>> = {\n note: STICKY_COLORS.yellow,\n prompt: STICKY_COLORS.blue,\n context: STICKY_COLORS.gray\n}\n\nexport function isAnnotation(pen: Pick<PenNode, 'type'>): boolean {\n return Object.hasOwn(ANNOTATION_COLORS, pen.type)\n}\n\n/** pen.dev cards smaller or larger than this stay readable as sticky notes at its bounds. */\nconst MIN_SCALE = 0.25\nconst MAX_SCALE = 4\n\n/**\n * The note's shape and scale: wide when the card is nearer FigJam's wide width than its square\n * one, and its text scaled to the card's width. The card's box itself comes from `applyAnnotation`.\n */\nfunction stickyShape(pen: PenNode, build: Build): { wide: boolean; scale: number } {\n const { value, sizing } = parseSize(pen.width, STICKY_SIZE, build.ctx)\n const width = sizing === 'FIXED' && value > 0 ? value : STICKY_SIZE\n const wide = width > (STICKY_SIZE + STICKY_WIDE_WIDTH) / 2\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, width / stickyWidth(1, wide)))\n return { wide, scale }\n}\n\n/**\n * The sticky's size fields, so it takes the room in a layout pen.dev's card does: a fixed width\n * and height keep the card's box, filling follows its parent's flow, and a card with no height or\n * one that fits its content grows to its text as a sticky does.\n */\nfunction annotationSizeFields(\n node: SceneNode,\n pen: PenNode,\n build: Build,\n flowLayout: SceneNode['layoutMode']\n): Partial<SceneNode> {\n const width = parseSize(pen.width, node.width, build.ctx)\n const height = parseSize(pen.height, node.height, build.ctx)\n const fixedHeight = pen.height !== undefined && height.sizing !== 'HUG'\n const fields: Partial<SceneNode> = {\n width: width.sizing === 'HUG' ? node.width : width.value,\n height: fixedHeight ? height.value : node.height,\n primaryAxisSizing: fixedHeight ? 'FIXED' : 'HUG',\n minHeight: fixedHeight\n ? null\n : (height.fitContentFallback ??\n STICKY_SIZE * stickyScale(stickySublayers(build.graph, node)?.author)),\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO'\n }\n if (flowLayout === 'NONE') return fields\n if (width.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'HORIZONTAL'))\n if (height.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'VERTICAL'))\n return fields\n}\n\n/** A sticky note for an annotation, with its sublayers; its fields come from `applyAnnotation`. */\nexport function createAnnotation(pen: PenNode, parentId: string, build: Build): SceneNode {\n return createSticky(\n build.graph,\n parentId,\n {\n authorVisible: false,\n color: ANNOTATION_COLORS[pen.type] ?? DEFAULT_STICKY_COLOR,\n ...stickyShape(pen, build)\n },\n { id: pen.id }\n )\n}\n\n/**\n * Sets the fields a sticky note takes from an annotation: where it is, its box, whether it shows,\n * and its text. A sticky note keeps its own style and upright placement, as FigJam draws one.\n */\nexport function applyAnnotation(node: SceneNode, pen: PenNode, build: Build): void {\n const { graph, ctx } = build\n const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'\n const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'\n Object.assign(node, {\n name: pen.name ?? pen.type,\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n visible: resolveBoolean(pen.enabled, ctx),\n opacity: resolveNumber(pen.opacity, ctx, 1),\n layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',\n ...annotationSizeFields(node, pen, build, absolute ? 'NONE' : parentLayout)\n } satisfies Partial<SceneNode>)\n bindIfVar(node, 'width', pen.width, ctx)\n bindIfVar(node, 'height', pen.height, ctx)\n build.placements.delete(node.id)\n\n const body = stickySublayers(graph, node)?.body\n const text = pen.content ?? ''\n if (body && body.text !== text) {\n body.text = text\n // A note inside an instance keeps the text an override gave it through the next sync.\n recordInstanceOverride(graph, body.id, ['text'])\n }\n applyPenPluginData(node, pen)\n build.effective.set(node.id, pen)\n}\n"],"mappings":";;;;;;;AAsCA,SAAgB,SAAS,KAAmC;CAC1D,OAAO,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS;AACxE;AAEA,SAAS,QAAQ,KAAqB;CACpC,OAAO,IAAI,MAAM,CAAC;AACpB;AAEA,SAAgB,UAAU,MAAiB,OAAe,KAAc,KAAuB;CAC7F,IAAI,CAAC,SAAS,GAAG,GAAG;CACpB,MAAM,WAAW,IAAI,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC5C,IAAI,UAAU,KAAK,eAAe,SAAS,SAAS;AACtD;;AAGA,SAAgB,cAAc,OAA8B,KAAiB,WAAW,GAAW;CACjG,IAAI,UAAU,KAAA,GAAW,OAAO;CAChC,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,SAAS,KAAK,GAAG,OAAO,IAAI,cAAc,KAAK;CACnD,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,SAAS,MAAM,IAAI,SAAS;AAC5C;;AAGA,SAAgB,sBACd,OACA,KACoB;CACpB,IAAI,UAAU,KAAA,GAAW,OAAO,KAAA;CAChC,IAAI,OAAO,UAAU,UAAU,OAAO;CACtC,IAAI,SAAS,KAAK,GAAG,OAAO,IAAI,YAAY,KAAK;CACjD,MAAM,SAAS,OAAO,KAAK;CAC3B,OAAO,OAAO,SAAS,MAAM,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AO,IAAI,WAAW;CAC5B,IAAI,QAAQ,KAAK,SAAS,MAAM;EAC9B,KAAK,OAAO;EAEZ,uBAAuB,OAAO,KAAK,IAAI,CAAC,MAAM,CAAC;CACjD;CACA,mBAAmB,MAAM,GAAG;CAC5B,MAAM,UAAU,IAAI,KAAK,IAAI,GAAG;AAClC"}
1
+ {"version":3,"file":"annotations.js","names":[],"sources":["../../src/variables.ts","../../src/plugin-data.ts","../../src/layout.ts","../../src/annotations.ts"],"sourcesContent":["import { groupBy, uniq } from 'es-toolkit/array'\n\nimport {\n generateId,\n type SceneGraph,\n type SceneNode,\n type Variable,\n type VariableCollectionMode,\n type VariableType,\n type VariableValue\n} from '@pairdraw/scene-graph'\nimport { parseColor } from '@pairdraw/scene-graph/color'\nimport { BLACK } from '@pairdraw/scene-graph/constants'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport type { PenDocument, PenNumber, PenVariable, PenVariableScalar } from './schema'\n\ntype Theme = Record<string, string>\n\n/**\n * A document's variables, resolved in the theme of the layer being read. pen.dev themes are axes,\n * such as `mode` and `density`, each with its values; every combination of one value per axis is\n * one mode of a single collection, since a variable can depend on several axes at once.\n */\nexport interface VarContext {\n byName: Map<string, Variable>\n resolveColor(ref: string): Color\n resolveNumber(ref: string): number\n /** The number the variable holds, or nothing when it holds none. */\n numberValue(ref: string): number | undefined\n resolveString(ref: string): string\n resolveBoolean(ref: string): boolean\n /** Merges a layer's theme over its parent's until the returned function is called. */\n enterTheme(theme: Theme): () => void\n /**\n * The modes a layer setting `theme` takes: in each collection holding one of its axes, the mode\n * of the theme being read.\n */\n variableModes(theme: Theme): Record<string, string>\n}\n\nexport function isVarRef(val: unknown): val is `$${string}` {\n return typeof val === 'string' && val.startsWith('$') && val.length > 1\n}\n\nfunction varName(ref: string): string {\n return ref.slice(1)\n}\n\nexport function bindIfVar(node: SceneNode, field: string, val: unknown, ctx: VarContext): void {\n if (!isVarRef(val)) return\n const variable = ctx.byName.get(varName(val))\n if (variable) node.boundVariables = { ...node.boundVariables, [field]: variable.id }\n}\n\n/** A number, or the value of the number variable it references. */\nexport function resolveNumber(value: PenNumber | undefined, ctx: VarContext, fallback = 0): number {\n if (value === undefined) return fallback\n if (typeof value === 'number') return value\n if (isVarRef(value)) return ctx.resolveNumber(value)\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : fallback\n}\n\n/** A number, or the value of the number variable it references; nothing where there is none. */\nexport function resolveOptionalNumber(\n value: PenNumber | undefined,\n ctx: VarContext\n): number | undefined {\n if (value === undefined) return undefined\n if (typeof value === 'number') return value\n if (isVarRef(value)) return ctx.numberValue(value)\n const parsed = Number(value)\n return Number.isFinite(parsed) ? parsed : undefined\n}\n\n/** A boolean, or the value of the variable it references. */\nexport function resolveBoolean(\n value: boolean | string | undefined,\n ctx: VarContext,\n fallback = true\n): boolean {\n if (value === undefined) return fallback\n if (typeof value === 'boolean') return value\n if (isVarRef(value)) return ctx.resolveBoolean(value)\n // Text other than true or false, such as `no` or `0`, reads as the default, as a missing\n // value does.\n const text = value.toLowerCase()\n return text === 'true' || text === 'false' ? text === 'true' : fallback\n}\n\n/** A string, or the value of the string variable it references. */\nexport function resolveString(value: string | undefined, ctx: VarContext): string | undefined {\n return value !== undefined && isVarRef(value) ? ctx.resolveString(value) : value\n}\n\n/**\n * Every value a field can take: the value itself, or the value its variable has in each theme,\n * through aliases, with the empty value where a theme has none, as reading resolves it. For\n * loading what a document may draw before it is read in a theme.\n */\nexport function possibleValues(value: string | undefined, doc: PenDocument): string[] {\n const axes = themeAxes(doc)\n const found = new Set<string>()\n const seen = new Set<string>()\n const visit = (raw: PenVariableScalar | undefined) => {\n if (raw === undefined) return\n if (!isVarRef(raw)) {\n found.add(String(raw))\n return\n }\n const name = varName(raw)\n const definition = doc.variables?.[name]\n if (!definition || seen.has(name)) return\n seen.add(name)\n const empty = emptyValue(sceneType(definition.type))\n // Only the axes its values name decide which applies.\n for (const theme of combinations(axesOf(definition, axes))) {\n const themed = rawValue(definition, theme)\n if (themed !== undefined) visit(themed)\n else if (typeof empty !== 'object') found.add(String(empty))\n }\n }\n visit(value)\n return [...found]\n}\n\n/** A colour, or the value of the colour variable it references. */\nexport function resolveColor(value: string, ctx: VarContext): Color {\n return isVarRef(value) ? ctx.resolveColor(value) : parseColor(value)\n}\n\nfunction sceneType(type: string): VariableType {\n if (type === 'color') return 'COLOR'\n if (type === 'number') return 'FLOAT'\n if (type === 'boolean') return 'BOOLEAN'\n return 'STRING'\n}\n\n/** pen.dev leaves a variable without a value in a theme no entry matches: black, zero, or empty. */\nfunction emptyValue(type: VariableType): VariableValue {\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\ntype Axis = [name: string, values: string[]]\n\n/** The document's theme axes that have values. */\nfunction themeAxes(doc: PenDocument): Axis[] {\n return Object.entries(doc.themes ?? {}).filter(([, values]) => values.length > 0)\n}\n\n/** Every combination of one value per axis, the first values first. */\nfunction combinations(axes: Axis[]): Theme[] {\n return axes.reduce<Theme[]>(\n (themes, [axis, values]) =>\n themes.flatMap((theme) => values.map((value) => ({ ...theme, [axis]: value }))),\n [{}]\n )\n}\n\n/**\n * A variable's raw value in a full theme. An entry applies when each of its axes has its value in\n * the theme, and a later one replaces an earlier one, as pen.dev 2.21 resolves them.\n */\nfunction rawValue(definition: PenVariable, theme: Theme): PenVariableScalar | undefined {\n if (!Array.isArray(definition.value)) return definition.value\n let found: PenVariableScalar | undefined\n for (const entry of definition.value) {\n const entryTheme = Object.entries(entry.theme ?? {})\n if (entryTheme.every(([axis, value]) => theme[axis] === value)) found = entry.value\n }\n return found\n}\n\nfunction sceneValue(\n raw: PenVariableScalar | undefined,\n type: VariableType,\n ids: ReadonlyMap<string, string>\n): VariableValue {\n if (raw === undefined) return emptyValue(type)\n if (isVarRef(raw)) {\n const aliasId = ids.get(varName(raw))\n return aliasId ? { aliasId } : emptyValue(type)\n }\n if (type === 'COLOR') return typeof raw === 'string' ? parseColor(raw) : emptyValue(type)\n if (type === 'FLOAT') {\n const value = Number(raw)\n return Number.isFinite(value) ? value : 0\n }\n if (type === 'BOOLEAN') return typeof raw === 'boolean' ? raw : raw === 'true'\n return String(raw)\n}\n\nfunction themeKey(theme: Theme, axes: Axis[]): string {\n return axes.map(([axis]) => theme[axis]).join('\\u0000')\n}\n\n/** The document's axes a variable's values name, in the document's order. */\nfunction axesOf(definition: PenVariable, axes: Axis[]): Axis[] {\n if (!Array.isArray(definition.value)) return []\n const named = new Set(definition.value.flatMap((entry) => Object.keys(entry.theme ?? {})))\n return axes.filter(([axis]) => named.has(axis))\n}\n\n/** The axes in groups, each joining the axes some variable's values combine, through any chain. */\nfunction axisGroups(axes: Axis[], definitions: PenVariable[]): Axis[][] {\n const parent = new Map(axes.map(([axis]) => [axis, axis]))\n const root = (axis: string): string => {\n const next = parent.get(axis) ?? axis\n return next === axis ? axis : root(next)\n }\n for (const definition of definitions) {\n const named = axesOf(definition, axes)\n const first = named.at(0)\n if (!first) continue\n for (const [axis] of named.slice(1)) parent.set(root(axis), root(first[0]))\n }\n return Object.values(groupBy(axes, ([axis]) => root(axis)))\n}\n\n/** A collection for a group of axes: one mode for each combination of their values. */\ninterface ThemeCollection {\n id: string\n axes: Axis[]\n themes: Theme[]\n modes: VariableCollectionMode[]\n modeByTheme: Map<string, string>\n}\n\n/** The selector each mode applies in, which Pencil itself does not record. */\nfunction applyModeConditions(\n graph: SceneGraph,\n doc: PenDocument,\n collections: readonly ThemeCollection[]\n) {\n for (const created of collections) {\n const collection = graph.variableCollections.get(created.id)\n const conditions = collection && doc.modeConditions?.[collection.name]\n if (!collection || !conditions) continue\n for (const mode of collection.modes) {\n const condition = conditions[mode.name]\n if (condition) mode.condition = condition\n }\n }\n}\n\nfunction addThemeCollection(graph: SceneGraph, axes: Axis[]): ThemeCollection {\n const themes = combinations(axes)\n const modes: VariableCollectionMode[] = themes.map((theme) => ({\n modeId: generateId(),\n name: axes.length === 0 ? 'Default' : axes.map(([axis]) => theme[axis]).join(' / ')\n }))\n const id = generateId()\n graph.addCollection({\n id,\n name: axes.length === 0 ? 'Variables' : axes.map(([axis]) => axis).join(' / '),\n modes,\n defaultModeId: modes[0].modeId,\n variableIds: []\n })\n const modeByTheme = new Map(\n themes.map((theme, index) => [themeKey(theme, axes), modes[index].modeId])\n )\n return { id, axes, themes, modes, modeByTheme }\n}\n\nexport function buildVarContext(\n graph: SceneGraph,\n doc: PenDocument,\n onUnknownVariable?: (name: string) => void\n): VarContext {\n const axes = themeAxes(doc)\n const definitions = Object.entries(doc.variables ?? {})\n const collections = axisGroups(\n axes,\n definitions.map(([, definition]) => definition)\n ).map((group) => addThemeCollection(graph, group))\n applyModeConditions(graph, doc, collections)\n const collectionOfAxis = new Map(\n collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection]))\n )\n // A variable no axis decides goes with the first axes, where it holds one value in every mode. A\n // document with neither variables nor themes, such as a new one, gets no empty collection.\n const fallback = collections[0] ?? (definitions.length > 0 ? addThemeCollection(graph, []) : null)\n const collectionFor = (definition: PenVariable): ThemeCollection | null => {\n const first = axesOf(definition, axes).at(0)\n return (first && collectionOfAxis.get(first[0])) || fallback\n }\n\n const ids = new Map(definitions.map(([name]) => [name, generateId()]))\n const byName = new Map<string, Variable>()\n const byId = new Map<string, Variable>()\n const collectionById = new Map<string, ThemeCollection>()\n for (const [name, definition] of definitions) {\n const type = sceneType(definition.type)\n const collection = collectionFor(definition)\n if (!collection) continue\n collectionById.set(collection.id, collection)\n const variable: Variable = {\n id: ids.get(name) ?? generateId(),\n name,\n type,\n collectionId: collection.id,\n valuesByMode: Object.fromEntries(\n collection.themes.map((theme, index) => [\n collection.modes[index].modeId,\n sceneValue(rawValue(definition, theme), type, ids)\n ])\n ),\n description: '',\n hiddenFromPublishing: false,\n ...(definition.codeSyntax ? { codeSyntax: definition.codeSyntax } : {})\n }\n graph.addVariable(variable)\n byName.set(name, variable)\n byId.set(variable.id, variable)\n }\n\n let current: Theme = Object.fromEntries(axes.map(([axis, values]) => [axis, values[0]]))\n const modeIn = (collection: ThemeCollection) =>\n collection.modeByTheme.get(themeKey(current, collection.axes)) ?? collection.modes[0].modeId\n\n /** A variable's value in the current theme, following aliases. */\n function resolve(ref: string): VariableValue | undefined {\n let variable = byName.get(varName(ref))\n if (!variable) onUnknownVariable?.(varName(ref))\n for (let hops = 0; variable && hops <= byName.size; hops++) {\n const collection = collectionById.get(variable.collectionId)\n const value = collection ? variable.valuesByMode[modeIn(collection)] : undefined\n if (typeof value !== 'object' || !('aliasId' in value)) return value\n variable = byId.get(value.aliasId)\n }\n return undefined\n }\n\n return {\n byName,\n resolveColor(ref) {\n const value = resolve(ref)\n return typeof value === 'object' && 'r' in value ? value : { ...BLACK }\n },\n resolveNumber(ref) {\n return this.numberValue(ref) ?? 0\n },\n numberValue(ref) {\n const value = resolve(ref)\n return typeof value === 'number' ? value : undefined\n },\n resolveString(ref) {\n const value = resolve(ref)\n return typeof value === 'string' ? value : ''\n },\n resolveBoolean(ref) {\n const value = resolve(ref)\n return typeof value === 'boolean' ? value : value !== undefined && value !== 'false'\n },\n enterTheme(theme) {\n const outer = current\n const known = Object.entries(theme).filter(([axis, value]) =>\n axes.some(([name, values]) => name === axis && values.includes(value))\n )\n current = { ...outer, ...Object.fromEntries(known) }\n return () => {\n current = outer\n }\n },\n variableModes(theme) {\n const touched = uniq(Object.keys(theme).flatMap((axis) => collectionOfAxis.get(axis) ?? []))\n return Object.fromEntries(touched.map((collection) => [collection.id, modeIn(collection)]))\n }\n }\n}\n","import type { PluginDataEntry, SceneNode } from '@pairdraw/scene-graph'\n\nimport type { PenNode, PenOverride } from './schema'\n\n/**\n * The shared plugin data namespace that keeps the pen.dev fields a layer has no field for, so\n * agents can read them with `getSharedPluginData('pen', key)` and a `.pen` writer can write them\n * back. Each value is its field's JSON.\n */\nexport const PEN_PLUGIN_DATA_NAMESPACE = 'pen'\n\n/**\n * The pen.dev fields kept as plugin data: notes for agents (`context`, `metadata`), the frame an\n * agent is working on (`placeholder`), the components suggested for a slot (`slot`), and what a\n * `prompt` or `context` node was, with the model a prompt asks. A `script` or `browser` node, which\n * reads as a placeholder frame, keeps its file and inputs or its page and view; a `ref` whose\n * component could not be found keeps the ID it names; and a label a placeholder was given says so.\n */\nconst PEN_PLUGIN_DATA_KEYS = [\n 'type',\n 'ref',\n 'context',\n 'metadata',\n 'placeholder',\n 'slot',\n 'model',\n 'scriptUri',\n 'inputs',\n 'url',\n 'deviceId',\n 'zoom',\n 'scrollX',\n 'scrollY',\n 'generated'\n] as const\n\ntype PenPluginDataKey = (typeof PEN_PLUGIN_DATA_KEYS)[number]\n\n/** Node types kept as plugin data on the layer they become. */\nconst KEPT_TYPES: ReadonlySet<string> = new Set(['prompt', 'context', 'script', 'browser'])\n\n/**\n * The field a `ref` whose component is missing reads with, holding the ID it names: the layer is a\n * placeholder frame, and keeps being a `ref` as plugin data.\n */\nexport const UNRESOLVED_REF = 'unresolvedRef'\n\n/** The ID a placeholder for a missing component names, or undefined for any other layer. */\nexport function unresolvedRef(pen: PenOverride): string | undefined {\n const ref = pen[UNRESOLVED_REF]\n return typeof ref === 'string' ? ref : undefined\n}\n\n/** As `setSharedPluginData` stores an entry, so the Figma API reads and replaces it. */\nfunction entry(key: PenPluginDataKey, value: unknown): PluginDataEntry {\n return {\n pluginId: PEN_PLUGIN_DATA_NAMESPACE,\n key: `${PEN_PLUGIN_DATA_NAMESPACE}/${key}`,\n value: JSON.stringify(value)\n }\n}\n\nfunction penEntries(pen: PenNode): PluginDataEntry[] {\n const missing = unresolvedRef(pen)\n return PEN_PLUGIN_DATA_KEYS.flatMap((key) => {\n if (key === 'type') {\n if (missing !== undefined) return [entry(key, 'ref')]\n return KEPT_TYPES.has(pen.type) ? [entry(key, pen.type)] : []\n }\n // A resolved `ref` is an instance, which says what it shows itself.\n if (key === 'ref') return missing === undefined ? [] : [entry(key, missing)]\n const value = pen[key]\n return value === undefined ? [] : [entry(key, value)]\n })\n}\n\n/**\n * Replaces the layer's pen.dev plugin data with the fields `pen` carries, keeping every other\n * entry, so applying a layer's fields again with an override's merged in leaves one of each.\n */\nexport function applyPenPluginData(node: SceneNode, pen: PenNode): void {\n const others = node.pluginData.filter((item) => item.pluginId !== PEN_PLUGIN_DATA_NAMESPACE)\n const own = penEntries(pen)\n if (own.length === 0 && others.length === node.pluginData.length) return\n node.pluginData = [...others, ...own]\n}\n","import type {\n LayoutAlign,\n LayoutCounterAlign,\n LayoutMode,\n LayoutSizing,\n SceneNode\n} from '@pairdraw/scene-graph'\nimport { parseAutoLayoutDirection } from '@pairdraw/scene-graph/layout'\n\nimport type { PenNode, PenNumber } from './schema'\nimport { bindIfVar, isVarRef, resolveNumber, type VarContext } from './variables'\n\nconst CORNERS = [\n 'topLeftRadius',\n 'topRightRadius',\n 'bottomRightRadius',\n 'bottomLeftRadius'\n] as const\nconst PADDING = ['paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft'] as const\n\nexport function applyCornerRadius(\n node: SceneNode,\n radius: PenNode['cornerRadius'],\n ctx: VarContext\n): void {\n if (radius === undefined) return\n if (Array.isArray(radius)) {\n node.independentCorners = true\n for (const [index, field] of CORNERS.entries()) {\n node[field] = resolveNumber(radius[index], ctx)\n bindIfVar(node, field, radius[index], ctx)\n }\n return\n }\n node.cornerRadius = resolveNumber(radius, ctx)\n bindIfVar(node, 'cornerRadius', radius, ctx)\n}\n\n/** pen.dev padding: one value, vertical and horizontal, or top, right, bottom, and left. */\nfunction paddingSides(padding: NonNullable<PenNode['padding']>): PenNumber[] {\n if (!Array.isArray(padding)) return [padding, padding, padding, padding]\n if (padding.length === 2) return [padding[0], padding[1], padding[0], padding[1]]\n return padding\n}\n\nexport function applyPadding(node: SceneNode, padding: PenNode['padding'], ctx: VarContext): void {\n if (padding === undefined) return\n const sides = paddingSides(padding)\n for (const [index, field] of PADDING.entries()) {\n node[field] = resolveNumber(sides[index], ctx)\n bindIfVar(node, field, sides[index], ctx)\n }\n}\n\ninterface ParsedSize {\n value: number\n sizing: LayoutSizing\n /** Fallback used only when fit_content(N) has no children. */\n fitContentFallback?: number\n}\n\nfunction parseParameterizedFallback(value: string, behavior: string): number | undefined {\n const prefix = `${behavior}(`\n if (!value.startsWith(prefix) || !value.endsWith(')')) return undefined\n\n const rawFallback = value.slice(prefix.length, -1).trim()\n if (rawFallback === '') return undefined\n\n const parsedFallback = Number(rawFallback)\n return Number.isFinite(parsedFallback) ? parsedFallback : undefined\n}\n\nfunction parseSizingBehavior(value: string, fallback: number): ParsedSize | undefined {\n if (value === 'fill_container') return { value: fallback, sizing: 'FILL' }\n if (value === 'fit_content') return { value: fallback, sizing: 'HUG' }\n\n // Older generated .pen files used hug_content as an alias for fit_content.\n if (value === 'hug_content') return { value: fallback, sizing: 'HUG' }\n\n const fillFallback = parseParameterizedFallback(value, 'fill_container')\n if (fillFallback !== undefined) return { value: fillFallback, sizing: 'FILL' }\n\n const fitFallback =\n parseParameterizedFallback(value, 'fit_content') ??\n parseParameterizedFallback(value, 'hug_content')\n if (fitFallback !== undefined) {\n return { value: fitFallback, sizing: 'HUG', fitContentFallback: fitFallback }\n }\n return undefined\n}\n\nexport function parseSize(\n value: number | string | undefined,\n fallback: number,\n ctx?: VarContext\n): ParsedSize {\n if (value === undefined) return { value: fallback, sizing: 'FIXED' }\n if (typeof value === 'number') return { value, sizing: 'FIXED' }\n\n const behavior = parseSizingBehavior(value, fallback)\n if (behavior) return behavior\n\n if (isVarRef(value) && ctx) return { value: ctx.resolveNumber(value), sizing: 'FIXED' }\n const parsed = Number(value)\n return { value: Number.isFinite(parsed) ? parsed : fallback, sizing: 'FIXED' }\n}\n\nexport function mapLayoutMode(pen: PenNode): LayoutMode {\n const direction = parseAutoLayoutDirection(pen.layout)\n if (direction) return direction\n return pen.type === 'frame' && pen.layout === undefined ? 'HORIZONTAL' : 'NONE'\n}\n\n/** pen.dev's main axis alignments. */\nconst JUSTIFY_CONTENT: Partial<Record<string, LayoutAlign>> = {\n start: 'MIN',\n center: 'CENTER',\n end: 'MAX',\n space_between: 'SPACE_BETWEEN',\n space_around: 'SPACE_AROUND'\n}\n\nconst ALIGN_ITEMS: Partial<Record<string, LayoutCounterAlign>> = {\n start: 'MIN',\n center: 'CENTER',\n end: 'MAX'\n}\n\nexport function mapJustifyContent(value: string | undefined): LayoutAlign {\n return JUSTIFY_CONTENT[value ?? 'start'] ?? 'MIN'\n}\n\nexport function mapAlignItems(value: string | undefined): LayoutCounterAlign {\n return ALIGN_ITEMS[value ?? 'start'] ?? 'MIN'\n}\n","import type { SceneNode } from '@pairdraw/scene-graph'\nimport {\n createSticky,\n DEFAULT_STICKY_COLOR,\n STICKY_COLORS,\n STICKY_SIZE,\n STICKY_WIDE_WIDTH,\n stickyScale,\n stickySublayers,\n stickyWidth\n} from '@pairdraw/scene-graph/generated'\nimport { recordInstanceOverride } from '@pairdraw/scene-graph/instances'\nimport { fillSizingFields } from '@pairdraw/scene-graph/layout'\nimport type { Color } from '@pairdraw/scene-graph/primitives'\n\nimport { parseSize } from './layout'\nimport type { Build } from './nodes'\nimport { applyPenPluginData } from './plugin-data'\nimport type { PenNode } from './schema'\nimport { bindIfVar, resolveBoolean, resolveNumber } from './variables'\n\n/**\n * pen.dev's text annotations: a `note`, a `prompt` for an agent, and a `context` note about the\n * layers around it. Each becomes a sticky note holding its text, in the colour nearest the one\n * pen.dev draws its card in; a prompt and a context note keep what they were as plugin data.\n */\nconst ANNOTATION_COLORS: Readonly<Record<string, Color>> = {\n note: STICKY_COLORS.yellow,\n prompt: STICKY_COLORS.blue,\n context: STICKY_COLORS.gray\n}\n\n/** The annotation type names, which the reader knows even though they map to stickies. */\nexport const ANNOTATION_TYPES: readonly string[] = Object.keys(ANNOTATION_COLORS)\n\nexport function isAnnotation(pen: Pick<PenNode, 'type'>): boolean {\n return Object.hasOwn(ANNOTATION_COLORS, pen.type)\n}\n\n/** pen.dev cards smaller or larger than this stay readable as sticky notes at its bounds. */\nconst MIN_SCALE = 0.25\nconst MAX_SCALE = 4\n\n/**\n * The note's shape and scale: wide when the card is nearer FigJam's wide width than its square\n * one, and its text scaled to the card's width. The card's box itself comes from `applyAnnotation`.\n */\nfunction stickyShape(pen: PenNode, build: Build): { wide: boolean; scale: number } {\n const { value, sizing } = parseSize(pen.width, STICKY_SIZE, build.ctx)\n const width = sizing === 'FIXED' && value > 0 ? value : STICKY_SIZE\n const wide = width > (STICKY_SIZE + STICKY_WIDE_WIDTH) / 2\n const scale = Math.min(MAX_SCALE, Math.max(MIN_SCALE, width / stickyWidth(1, wide)))\n return { wide, scale }\n}\n\n/**\n * The sticky's size fields, so it takes the room in a layout pen.dev's card does: a fixed width\n * and height keep the card's box, filling follows its parent's flow, and a card with no height or\n * one that fits its content grows to its text as a sticky does.\n */\nfunction annotationSizeFields(\n node: SceneNode,\n pen: PenNode,\n build: Build,\n flowLayout: SceneNode['layoutMode']\n): Partial<SceneNode> {\n const width = parseSize(pen.width, node.width, build.ctx)\n const height = parseSize(pen.height, node.height, build.ctx)\n const fixedHeight = pen.height !== undefined && height.sizing !== 'HUG'\n const fields: Partial<SceneNode> = {\n width: width.sizing === 'HUG' ? node.width : width.value,\n height: fixedHeight ? height.value : node.height,\n primaryAxisSizing: fixedHeight ? 'FIXED' : 'HUG',\n minHeight: fixedHeight\n ? null\n : (height.fitContentFallback ??\n STICKY_SIZE * stickyScale(stickySublayers(build.graph, node)?.author)),\n layoutGrow: 0,\n layoutAlignSelf: 'AUTO'\n }\n if (flowLayout === 'NONE') return fields\n if (width.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'HORIZONTAL'))\n if (height.sizing === 'FILL') Object.assign(fields, fillSizingFields(flowLayout, 'VERTICAL'))\n return fields\n}\n\n/** A sticky note for an annotation, with its sublayers; its fields come from `applyAnnotation`. */\nexport function createAnnotation(pen: PenNode, parentId: string, build: Build): SceneNode {\n return createSticky(\n build.graph,\n parentId,\n {\n authorVisible: false,\n color: ANNOTATION_COLORS[pen.type] ?? DEFAULT_STICKY_COLOR,\n ...stickyShape(pen, build)\n },\n { id: pen.id }\n )\n}\n\n/**\n * Sets the fields a sticky note takes from an annotation: where it is, its box, whether it shows,\n * and its text. A sticky note keeps its own style and upright placement, as FigJam draws one.\n */\nexport function applyAnnotation(node: SceneNode, pen: PenNode, build: Build): void {\n const { graph, ctx } = build\n const parentLayout = (node.parentId && graph.getNode(node.parentId)?.layoutMode) || 'NONE'\n const absolute = pen.layoutPosition === 'absolute' && parentLayout !== 'NONE'\n Object.assign(node, {\n name: pen.name ?? pen.type,\n x: pen.x ?? 0,\n y: pen.y ?? 0,\n visible: resolveBoolean(pen.enabled, ctx),\n opacity: resolveNumber(pen.opacity, ctx, 1),\n layoutPositioning: absolute ? 'ABSOLUTE' : 'AUTO',\n ...annotationSizeFields(node, pen, build, absolute ? 'NONE' : parentLayout)\n } satisfies Partial<SceneNode>)\n bindIfVar(node, 'width', pen.width, ctx)\n bindIfVar(node, 'height', pen.height, ctx)\n build.placements.delete(node.id)\n\n const body = stickySublayers(graph, node)?.body\n const text = pen.content ?? ''\n if (body && body.text !== text) {\n body.text = text\n // A note inside an instance keeps the text an override gave it through the next sync.\n recordInstanceOverride(graph, body.id, ['text'])\n }\n applyPenPluginData(node, pen)\n build.effective.set(node.id, pen)\n}\n"],"mappings":";;;;;;;;AAyCA,SAAgB,SAAS,KAAmC;CAC1D,OAAO,OAAO,QAAQ,YAAY,IAAI,WAAW,GAAG,KAAK,IAAI,SAAS;AACxE;AAEA,SAAS,QAAQ,KAAqB;CACpC,OAAO,IAAI,MAAM,CAAC;AACpB;AAEA,SAAgB,UAAU,MAAiB,OAAe,KAAc,KAAuB;CAC7F,IAAI,CAAC,SAAS,GAAG,GAAG;CACpB,MAAM,WAAW,IAAI,OAAO,IAAI,QAAQ,GAAG,CAAC;CAC5C,IAAI,UAAU,KAAK,iBAAiB;EAAE,GAAG,KAAK;GAAiB,QAAQ,SAAS;CAAG;AACrF;;AAGA,SAAgB,cAAc,OAA8B,KAAiB,WAAW,GAAW;CACj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cAAc,IAAI,SAAS,KAAK,CAAC;EAC1C,mBAAmB,WAAW,aAAa;EAC3C,GAAG,qBAAqB,MAAM,KAAK,OAAO,WAAW,SAAS,YAAY;CAC5E,CAA8B;CAC9B,UAAU,MAAM,SAAS,IAAI,OAAO,GAAG;CACvC,UAAU,MAAM,UAAU,IAAI,QAAQ,GAAG;CACzC,MAAM,WAAW,OAAO,KAAK,EAAE;CAE/B,MAAM,OAAO,gBAAgB,OAAO,IAAI,CAAC,EAAE;CAC3C,MAAM,OAAO,IAAI,WAAW;CAC5B,IAAI,QAAQ,KAAK,SAAS,MAAM;EAC9B,KAAK,OAAO;EAEZ,uBAAuB,OAAO,KAAK,IAAI,CAAC,MAAM,CAAC;CACjD;CACA,mBAAmB,MAAM,GAAG;CAC5B,MAAM,UAAU,IAAI,KAAK,IAAI,GAAG;AAClC"}
@@ -1,6 +1,8 @@
1
1
  import { bindIfVar, resolveBoolean, resolveColor, resolveNumber } from "./annotations.js";
2
+ import { CODE_SYNTAX_PLATFORMS } from "@pairdraw/scene-graph";
2
3
  import { BLACK, TRANSPARENT } from "@pairdraw/scene-graph/constants";
3
4
  import * as v from "valibot";
5
+ import { tokenSourcesSchema } from "@pairdraw/scene-graph/token-sources";
4
6
  import { computeImageHash, coverImageTransform, imageSize } from "@pairdraw/scene-graph/images";
5
7
  import { ellipticalGradientTransform, isMeshFill, linearGradientTransformFromAxes, meshPointCount } from "@pairdraw/scene-graph/gradient";
6
8
  import { createShaderSourcePaint, withShaderPaints } from "@pairdraw/scene-graph/shaders";
@@ -410,20 +412,36 @@ const variableSchema = v.looseObject({
410
412
  value: v.union([variableScalarSchema, v.array(v.looseObject({
411
413
  value: variableScalarSchema,
412
414
  theme: v.optional(v.record(strSchema, strSchema))
413
- }))])
415
+ }))]),
416
+ /**
417
+ * The code that names the token, as Figma's variables carry it. Pencil has no field for it, so
418
+ * it is an extension other Pencil clients ignore; without it a reopened document cannot match a
419
+ * renamed variable to the token its stylesheet declares.
420
+ */
421
+ codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), strSchema))
414
422
  });
415
423
  /** A font file the document bundles, which its text names by `name` as a family. */
416
424
  const fontSchema = v.looseObject({
417
425
  name: strSchema,
418
426
  url: strSchema
419
427
  });
428
+ /** A document whose links are a list this reader can use; any other value is no link at all. */
429
+ const penTokenSourcesSchema = v.pipe(v.unknown(), v.transform((value) => v.parse(tokenSourcesSchema, Array.isArray(value) ? value : [])));
420
430
  const penDocumentSchema = v.looseObject({
421
431
  version: v.optional(strSchema),
422
432
  name: v.optional(strSchema),
423
433
  fonts: v.optional(v.array(fontSchema)),
424
434
  themes: v.optional(v.record(strSchema, v.array(strSchema))),
435
+ /**
436
+ * The selector each mode applies in, by collection and mode name: `.dark` for a Dark mode a
437
+ * stylesheet writes. Pencil has no field for it, so it is an extension other clients ignore;
438
+ * without it a reopened document reads the stylesheet's dark block as a new mode.
439
+ */
440
+ modeConditions: v.optional(v.record(strSchema, v.record(strSchema, strSchema))),
425
441
  imports: v.optional(v.record(strSchema, strSchema)),
426
442
  variables: v.optional(v.record(strSchema, variableSchema)),
443
+ /** The code the document's variables are linked to, as Core keeps it on the document node. */
444
+ tokenSources: v.optional(penTokenSourcesSchema),
427
445
  children: v.array(nodeSchema)
428
446
  });
429
447
  /** A `.pen` file's text, which may hold comments, as its document. */