@pairdraw/pen 0.19.2 → 0.21.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.
@@ -2,6 +2,7 @@ import { groupBy, uniq } from "es-toolkit/array";
2
2
  import { generateId } from "@pairdraw/scene-graph";
3
3
  import { parseColor } from "@pairdraw/scene-graph/color";
4
4
  import { BLACK } from "@pairdraw/scene-graph/constants";
5
+ import * as v from "valibot";
5
6
  import { recordInstanceOverride } from "@pairdraw/scene-graph/instances";
6
7
  import { fillSizingFields, parseAutoLayoutDirection } from "@pairdraw/scene-graph/layout";
7
8
  import { DEFAULT_STICKY_COLOR, STICKY_COLORS, STICKY_SIZE, STICKY_WIDE_WIDTH, createSticky, stickyScale, stickySublayers, stickyWidth } from "@pairdraw/scene-graph/generated";
@@ -15,7 +16,10 @@ function varName(ref) {
15
16
  function bindIfVar(node, field, val, ctx) {
16
17
  if (!isVarRef(val)) return;
17
18
  const variable = ctx.byName.get(varName(val));
18
- if (variable) node.boundVariables[field] = variable.id;
19
+ if (variable) node.boundVariables = {
20
+ ...node.boundVariables,
21
+ [field]: variable.id
22
+ };
19
23
  }
20
24
  /** A number, or the value of the number variable it references. */
21
25
  function resolveNumber(value, ctx, fallback = 0) {
@@ -150,6 +154,18 @@ function axisGroups(axes, definitions) {
150
154
  }
151
155
  return Object.values(groupBy(axes, ([axis]) => root(axis)));
152
156
  }
157
+ /** The selector each mode applies in, which Pencil itself does not record. */
158
+ function applyModeConditions(graph, doc, collections) {
159
+ for (const created of collections) {
160
+ const collection = graph.variableCollections.get(created.id);
161
+ const conditions = collection && doc.modeConditions?.[collection.name];
162
+ if (!collection || !conditions) continue;
163
+ for (const mode of collection.modes) {
164
+ const condition = conditions[mode.name];
165
+ if (condition) mode.condition = condition;
166
+ }
167
+ }
168
+ }
153
169
  function addThemeCollection(graph, axes) {
154
170
  const themes = combinations(axes);
155
171
  const modes = themes.map((theme) => ({
@@ -172,10 +188,11 @@ function addThemeCollection(graph, axes) {
172
188
  modeByTheme: new Map(themes.map((theme, index) => [themeKey(theme, axes), modes[index].modeId]))
173
189
  };
174
190
  }
175
- function buildVarContext(graph, doc) {
191
+ function buildVarContext(graph, doc, onUnknownVariable) {
176
192
  const axes = themeAxes(doc);
177
193
  const definitions = Object.entries(doc.variables ?? {});
178
194
  const collections = axisGroups(axes, definitions.map(([, definition]) => definition)).map((group) => addThemeCollection(graph, group));
195
+ applyModeConditions(graph, doc, collections);
179
196
  const collectionOfAxis = new Map(collections.flatMap((collection) => collection.axes.map(([axis]) => [axis, collection])));
180
197
  const fallback = collections[0] ?? (definitions.length > 0 ? addThemeCollection(graph, []) : null);
181
198
  const collectionFor = (definition) => {
@@ -198,7 +215,8 @@ function buildVarContext(graph, doc) {
198
215
  collectionId: collection.id,
199
216
  valuesByMode: Object.fromEntries(collection.themes.map((theme, index) => [collection.modes[index].modeId, sceneValue(rawValue(definition, theme), type, ids)])),
200
217
  description: "",
201
- hiddenFromPublishing: false
218
+ hiddenFromPublishing: false,
219
+ ...definition.codeSyntax ? { codeSyntax: definition.codeSyntax } : {}
202
220
  };
203
221
  graph.addVariable(variable);
204
222
  byName.set(name, variable);
@@ -209,6 +227,7 @@ function buildVarContext(graph, doc) {
209
227
  /** A variable's value in the current theme, following aliases. */
210
228
  function resolve(ref) {
211
229
  let variable = byName.get(varName(ref));
230
+ if (!variable) onUnknownVariable?.(varName(ref));
212
231
  for (let hops = 0; variable && hops <= byName.size; hops++) {
213
232
  const collection = collectionById.get(variable.collectionId);
214
233
  const value = collection ? variable.valuesByMode[modeIn(collection)] : void 0;
@@ -303,6 +322,35 @@ function unresolvedRef(pen) {
303
322
  const ref = pen[UNRESOLVED_REF];
304
323
  return typeof ref === "string" ? ref : void 0;
305
324
  }
325
+ /**
326
+ * The pen fields the component for an icon was drawn from, kept on it: a layer inside a component
327
+ * that swaps its glyph names the icon in the override, not the component, so a save needs them
328
+ * back to write the swap. Other pen clients ignore the entry.
329
+ */
330
+ const ICON_ORIGIN_KEY = "pen/iconOrigin";
331
+ const iconOriginSchema = v.object({
332
+ library: v.optional(v.pipe(v.string(), v.nonEmpty())),
333
+ icon: v.pipe(v.string(), v.nonEmpty()),
334
+ weight: v.optional(v.number())
335
+ });
336
+ /** Keeps the fields an icon component was drawn from on it. */
337
+ function writeIconOrigin(node, origin) {
338
+ const key = `pen/${ICON_ORIGIN_KEY}`;
339
+ const originEntry = {
340
+ pluginId: "pen",
341
+ key,
342
+ value: JSON.stringify(origin)
343
+ };
344
+ node.pluginData = [...node.pluginData.filter((item) => item.key !== key), originEntry];
345
+ }
346
+ /** The fields the component `node` draws as an icon is, or undefined for any other component. */
347
+ function readIconOrigin(node) {
348
+ const key = `pen/${ICON_ORIGIN_KEY}`;
349
+ const stored = node?.pluginData.find((item) => item.pluginId === "pen" && item.key === key);
350
+ if (!stored) return void 0;
351
+ const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), iconOriginSchema), stored.value);
352
+ return parsed.success ? parsed.output : void 0;
353
+ }
306
354
  /** As `setSharedPluginData` stores an entry, so the Figma API reads and replaces it. */
307
355
  function entry(key, value) {
308
356
  return {
@@ -474,6 +522,8 @@ const ANNOTATION_COLORS = {
474
522
  prompt: STICKY_COLORS.blue,
475
523
  context: STICKY_COLORS.gray
476
524
  };
525
+ /** The annotation type names, which the reader knows even though they map to stickies. */
526
+ const ANNOTATION_TYPES = Object.keys(ANNOTATION_COLORS);
477
527
  function isAnnotation(pen) {
478
528
  return Object.hasOwn(ANNOTATION_COLORS, pen.type);
479
529
  }
@@ -553,6 +603,6 @@ function applyAnnotation(node, pen, build) {
553
603
  build.effective.set(node.id, pen);
554
604
  }
555
605
  //#endregion
556
- 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 };
606
+ export { ANNOTATION_TYPES, PEN_PLUGIN_DATA_NAMESPACE, UNRESOLVED_REF, applyAnnotation, applyCornerRadius, applyPadding, applyPenPluginData, bindIfVar, buildVarContext, createAnnotation, isAnnotation, isVarRef, mapAlignItems, mapJustifyContent, mapLayoutMode, parseSize, possibleValues, readIconOrigin, resolveBoolean, resolveColor, resolveNumber, resolveOptionalNumber, resolveString, unresolvedRef, writeIconOrigin };
557
607
 
558
608
  //# 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 { 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[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\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(graph: SceneGraph, doc: PenDocument): 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 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 }\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 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\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,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,MAA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;AACF;;;;;AAMA,SAAgB,gBAAgB,MAAiB,KAAc,OAAoB;CACjF,MAAM,EAAE,OAAO,QAAQ;CACvB,MAAM,eAAgB,KAAK,YAAY,MAAM,QAAQ,KAAK,QAAQ,CAAC,EAAE,cAAe;CACpF,MAAM,WAAW,IAAI,mBAAmB,cAAc,iBAAiB;CACvE,OAAO,OAAO,MAAM;EAClB,MAAM,IAAI,QAAQ,IAAI;EACtB,GAAG,IAAI,KAAK;EACZ,GAAG,IAAI,KAAK;EACZ,SAAS,eAAe,IAAI,SAAS,GAAG;EACxC,SAAS,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
+ {"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 * as v from 'valibot'\n\nimport 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/**\n * The pen fields the component for an icon was drawn from, kept on it: a layer inside a component\n * that swaps its glyph names the icon in the override, not the component, so a save needs them\n * back to write the swap. Other pen clients ignore the entry.\n */\nconst ICON_ORIGIN_KEY = 'pen/iconOrigin'\n\nconst iconOriginSchema = v.object({\n library: v.optional(v.pipe(v.string(), v.nonEmpty())),\n icon: v.pipe(v.string(), v.nonEmpty()),\n weight: v.optional(v.number())\n})\n\n/** The pen fields an icon component was drawn from. */\nexport type PenIconOrigin = v.InferOutput<typeof iconOriginSchema>\n\n/** Keeps the fields an icon component was drawn from on it. */\nexport function writeIconOrigin(node: SceneNode, origin: PenIconOrigin): void {\n const key = `${PEN_PLUGIN_DATA_NAMESPACE}/${ICON_ORIGIN_KEY}`\n const originEntry: PluginDataEntry = {\n pluginId: PEN_PLUGIN_DATA_NAMESPACE,\n key,\n value: JSON.stringify(origin)\n }\n node.pluginData = [...node.pluginData.filter((item) => item.key !== key), originEntry]\n}\n\n/** The fields the component `node` draws as an icon is, or undefined for any other component. */\nexport function readIconOrigin(node: SceneNode | undefined): PenIconOrigin | undefined {\n const key = `${PEN_PLUGIN_DATA_NAMESPACE}/${ICON_ORIGIN_KEY}`\n const stored = node?.pluginData.find(\n (item) => item.pluginId === PEN_PLUGIN_DATA_NAMESPACE && item.key === key\n )\n if (!stored) return undefined\n const parsed = v.safeParse(v.pipe(v.string(), v.parseJson(), iconOriginSchema), stored.value)\n return parsed.success ? parsed.output : 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,WA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AAa;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"}
@@ -0,0 +1,35 @@
1
+ import { PAIRDRAW_PLUGIN_DATA, readPluginData, withPluginData } from "@pairdraw/scene-graph/plugin-data";
2
+ //#region src/document-libraries.ts
3
+ const { penImports: penImportsField, sourceLibraryPublication: publicationField } = PAIRDRAW_PLUGIN_DATA;
4
+ /**
5
+ * The `.pen` documents a graph imports, by the alias its file names each one with. The reader
6
+ * stores them beside the design memory, so a save writes the same `imports` back.
7
+ */
8
+ function readPenImports(graph) {
9
+ const root = graph.getNode(graph.rootId);
10
+ const imports = readPluginData(root?.pluginData, penImportsField);
11
+ return imports && Object.keys(imports).length > 0 ? imports : void 0;
12
+ }
13
+ /** The library this document publishes as, or null when it publishes none. */
14
+ function readSourceLibraryPublication(graph) {
15
+ const root = graph.getNode(graph.rootId);
16
+ return readPluginData(root?.pluginData, publicationField) ?? null;
17
+ }
18
+ /**
19
+ * Keeps the library links a `.pen` file carries on the graph it reads into: the documents it
20
+ * imports (their paths, which resolve their components and variables on a reopen), the libraries
21
+ * it switched on, and the library it publishes as.
22
+ */
23
+ function writeLibraryLinks(graph, doc) {
24
+ const root = graph.getNode(graph.rootId);
25
+ if (!root) return;
26
+ let pluginData = root.pluginData;
27
+ if (doc.imports && Object.keys(doc.imports).length > 0) pluginData = withPluginData(pluginData, penImportsField, doc.imports);
28
+ if (doc.sourceLibraryPublication) pluginData = withPluginData(pluginData, publicationField, doc.sourceLibraryPublication);
29
+ if (pluginData !== root.pluginData) graph.updateNode(root.id, { pluginData });
30
+ if (doc.enabledLibraries) graph.enabledLibraries = new Map(doc.enabledLibraries.map((binding) => [binding.libraryId, binding]));
31
+ }
32
+ //#endregion
33
+ export { readPenImports, readSourceLibraryPublication, writeLibraryLinks };
34
+
35
+ //# sourceMappingURL=document-libraries.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"document-libraries.js","names":[],"sources":["../../src/document-libraries.ts"],"sourcesContent":["import type { SceneGraph, SourceLibraryPublication } from '@pairdraw/scene-graph'\nimport {\n PAIRDRAW_PLUGIN_DATA,\n readPluginData,\n withPluginData\n} from '@pairdraw/scene-graph/plugin-data'\n\nimport type { PenDocument } from './schema'\n\nconst { penImports: penImportsField, sourceLibraryPublication: publicationField } =\n PAIRDRAW_PLUGIN_DATA\n\ntype LibraryLinks = Pick<PenDocument, 'imports' | 'enabledLibraries' | 'sourceLibraryPublication'>\n\n/**\n * The `.pen` documents a graph imports, by the alias its file names each one with. The reader\n * stores them beside the design memory, so a save writes the same `imports` back.\n */\nexport function readPenImports(graph: SceneGraph): Record<string, string> | undefined {\n const root = graph.getNode(graph.rootId)\n const imports = readPluginData(root?.pluginData, penImportsField)\n return imports && Object.keys(imports).length > 0 ? imports : undefined\n}\n\n/** The library this document publishes as, or null when it publishes none. */\nexport function readSourceLibraryPublication(graph: SceneGraph): SourceLibraryPublication | null {\n const root = graph.getNode(graph.rootId)\n return readPluginData(root?.pluginData, publicationField) ?? null\n}\n\n/**\n * Keeps the library links a `.pen` file carries on the graph it reads into: the documents it\n * imports (their paths, which resolve their components and variables on a reopen), the libraries\n * it switched on, and the library it publishes as.\n */\nexport function writeLibraryLinks(graph: SceneGraph, doc: LibraryLinks): void {\n const root = graph.getNode(graph.rootId)\n if (!root) return\n let pluginData = root.pluginData\n if (doc.imports && Object.keys(doc.imports).length > 0) {\n pluginData = withPluginData(pluginData, penImportsField, doc.imports)\n }\n if (doc.sourceLibraryPublication) {\n pluginData = withPluginData(pluginData, publicationField, doc.sourceLibraryPublication)\n }\n if (pluginData !== root.pluginData) graph.updateNode(root.id, { pluginData })\n if (doc.enabledLibraries) {\n graph.enabledLibraries = new Map(\n doc.enabledLibraries.map((binding) => [binding.libraryId, binding])\n )\n }\n}\n"],"mappings":";;AASA,MAAM,EAAE,YAAY,iBAAiB,0BAA0B,qBAC7D;;;;;AAQF,SAAgB,eAAe,OAAuD;CACpF,MAAM,OAAO,MAAM,QAAQ,MAAM,MAAM;CACvC,MAAM,UAAU,eAAe,MAAM,YAAY,eAAe;CAChE,OAAO,WAAW,OAAO,KAAK,OAAO,CAAC,CAAC,SAAS,IAAI,UAAU,KAAA;AAChE;;AAGA,SAAgB,6BAA6B,OAAoD;CAC/F,MAAM,OAAO,MAAM,QAAQ,MAAM,MAAM;CACvC,OAAO,eAAe,MAAM,YAAY,gBAAgB,KAAK;AAC/D;;;;;;AAOA,SAAgB,kBAAkB,OAAmB,KAAyB;CAC5E,MAAM,OAAO,MAAM,QAAQ,MAAM,MAAM;CACvC,IAAI,CAAC,MAAM;CACX,IAAI,aAAa,KAAK;CACtB,IAAI,IAAI,WAAW,OAAO,KAAK,IAAI,OAAO,CAAC,CAAC,SAAS,GACnD,aAAa,eAAe,YAAY,iBAAiB,IAAI,OAAO;CAEtE,IAAI,IAAI,0BACN,aAAa,eAAe,YAAY,kBAAkB,IAAI,wBAAwB;CAExF,IAAI,eAAe,KAAK,YAAY,MAAM,WAAW,KAAK,IAAI,EAAE,WAAW,CAAC;CAC5E,IAAI,IAAI,kBACN,MAAM,mBAAmB,IAAI,IAC3B,IAAI,iBAAiB,KAAK,YAAY,CAAC,QAAQ,WAAW,OAAO,CAAC,CACpE;AAEJ"}
@@ -1,6 +1,11 @@
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 { designMemorySchema } from "@pairdraw/scene-graph/design-memory";
6
+ import { nodeStatusSchema, statusWorkflowSchema } from "@pairdraw/scene-graph/statuses";
7
+ import { tokenSourcesSchema } from "@pairdraw/scene-graph/token-sources";
8
+ import { enabledLibrariesSchema, sourceLibraryPublicationSchema } from "@pairdraw/scene-graph/plugin-data";
4
9
  import { computeImageHash, coverImageTransform, imageSize } from "@pairdraw/scene-graph/images";
5
10
  import { ellipticalGradientTransform, isMeshFill, linearGradientTransformFromAxes, meshPointCount } from "@pairdraw/scene-graph/gradient";
6
11
  import { createShaderSourcePaint, withShaderPaints } from "@pairdraw/scene-graph/shaders";
@@ -39,6 +44,29 @@ function invertAffine([a, b, c, d, tx, ty]) {
39
44
  m12: (b * tx - a * ty) / det
40
45
  };
41
46
  }
47
+ /**
48
+ * A crop's image-space window as pen.dev's affine, which maps the crop back onto the image so a
49
+ * reader inverts it into the same window. The tuple is `[a, b, c, d, tx, ty]`: columns first.
50
+ */
51
+ function penCropTransform(crop) {
52
+ const inverse = invertAffine([
53
+ crop.m00,
54
+ crop.m10,
55
+ crop.m01,
56
+ crop.m11,
57
+ crop.m02,
58
+ crop.m12
59
+ ]);
60
+ if (!inverse) return null;
61
+ return [
62
+ inverse.m00,
63
+ inverse.m10,
64
+ inverse.m01,
65
+ inverse.m11,
66
+ inverse.m02,
67
+ inverse.m12
68
+ ];
69
+ }
42
70
  function compose(outer, inner) {
43
71
  return {
44
72
  m00: outer.m00 * inner.m00 + outer.m01 * inner.m10,
@@ -303,11 +331,24 @@ const paddingSchema = v.union([
303
331
  v.tuple([numSchema, numSchema])
304
332
  ]);
305
333
  const cornerRadiusSchema = v.union([numSchema, v.array(numSchema)]);
334
+ /**
335
+ * A layer's status, or none when the value is not an id this reader can use: a document stays
336
+ * readable because of one unreadable field.
337
+ */
338
+ const penNodeStatusSchema = v.pipe(v.unknown(), v.transform((value) => {
339
+ const parsed = v.safeParse(nodeStatusSchema, value);
340
+ return parsed.success ? parsed.output : void 0;
341
+ }));
306
342
  /** Every property a node, or an override of one, can carry. */
307
343
  const nodeFields = {
308
344
  name: v.optional(strSchema),
309
345
  context: v.optional(strSchema),
310
346
  /**
347
+ * The layer's status, an id in the document's status workflow, as Core keeps it on the layer.
348
+ * Pencil has no field for it, so it is an extension other Pencil clients ignore.
349
+ */
350
+ status: v.optional(penNodeStatusSchema),
351
+ /**
311
352
  * What a layer is, for agents: pen.dev writes a `type` and any fields of its own. It is only kept
312
353
  * as plugin data, so any value is read as it is rather than rejecting the document.
313
354
  */
@@ -410,20 +451,92 @@ const variableSchema = v.looseObject({
410
451
  value: v.union([variableScalarSchema, v.array(v.looseObject({
411
452
  value: variableScalarSchema,
412
453
  theme: v.optional(v.record(strSchema, strSchema))
413
- }))])
454
+ }))]),
455
+ /**
456
+ * The code that names the token, as Figma's variables carry it. Pencil has no field for it, so
457
+ * it is an extension other Pencil clients ignore; without it a reopened document cannot match a
458
+ * renamed variable to the token its stylesheet declares.
459
+ */
460
+ codeSyntax: v.optional(v.record(v.picklist(CODE_SYNTAX_PLATFORMS), strSchema))
414
461
  });
415
462
  /** A font file the document bundles, which its text names by `name` as a family. */
416
463
  const fontSchema = v.looseObject({
417
464
  name: strSchema,
418
465
  url: strSchema
419
466
  });
467
+ /** A document whose links are a list this reader can use; any other value is no link at all. */
468
+ const penTokenSourcesSchema = v.pipe(v.unknown(), v.transform((value) => v.parse(tokenSourcesSchema, Array.isArray(value) ? value : [])));
469
+ /**
470
+ * The memory a file holds, or none when an older client wrote something this reader cannot use:
471
+ * a document stays readable because of one unreadable field.
472
+ */
473
+ const penDesignMemorySchema = v.pipe(v.unknown(), v.transform((value) => {
474
+ const parsed = v.safeParse(designMemorySchema, value);
475
+ return parsed.success ? parsed.output : void 0;
476
+ }));
477
+ /**
478
+ * The status workflow the file holds, or none when an older client wrote something this reader
479
+ * cannot use: a document stays readable because of one unreadable field.
480
+ */
481
+ const penStatusWorkflowSchema = v.pipe(v.unknown(), v.transform((value) => {
482
+ const parsed = v.safeParse(statusWorkflowSchema, value);
483
+ return parsed.success ? parsed.output : void 0;
484
+ }));
485
+ /**
486
+ * The libraries the file switched on, or none when an older client wrote something this reader
487
+ * cannot use: a document stays readable because of one unreadable field.
488
+ */
489
+ const penEnabledLibrariesSchema = v.pipe(v.unknown(), v.transform((value) => {
490
+ const parsed = v.safeParse(enabledLibrariesSchema, value);
491
+ return parsed.success && parsed.output.length > 0 ? parsed.output : void 0;
492
+ }));
493
+ /**
494
+ * The library the file publishes as, or none when an older client wrote something this reader
495
+ * cannot use: a document stays readable because of one unreadable field.
496
+ */
497
+ const penSourceLibraryPublicationSchema = v.pipe(v.unknown(), v.transform((value) => {
498
+ const parsed = v.safeParse(sourceLibraryPublicationSchema, value);
499
+ return parsed.success ? parsed.output : void 0;
500
+ }));
420
501
  const penDocumentSchema = v.looseObject({
421
502
  version: v.optional(strSchema),
422
503
  name: v.optional(strSchema),
423
504
  fonts: v.optional(v.array(fontSchema)),
424
505
  themes: v.optional(v.record(strSchema, v.array(strSchema))),
506
+ /**
507
+ * The selector each mode applies in, by collection and mode name: `.dark` for a Dark mode a
508
+ * stylesheet writes. Pencil has no field for it, so it is an extension other clients ignore;
509
+ * without it a reopened document reads the stylesheet's dark block as a new mode.
510
+ */
511
+ modeConditions: v.optional(v.record(strSchema, v.record(strSchema, strSchema))),
425
512
  imports: v.optional(v.record(strSchema, strSchema)),
426
513
  variables: v.optional(v.record(strSchema, variableSchema)),
514
+ /** The code the document's variables are linked to, as Core keeps it on the document node. */
515
+ tokenSources: v.optional(penTokenSourcesSchema),
516
+ /**
517
+ * The design memory agents follow, as Core keeps it on the document node: allowed values,
518
+ * decisions, and pinned examples. Pencil has no field for it, so it is an extension other
519
+ * Pencil clients ignore; without it a reopened document loses its rules.
520
+ */
521
+ designMemory: v.optional(penDesignMemorySchema),
522
+ /**
523
+ * The states the document's layers can be in, as Core keeps them on the document node. Pencil
524
+ * has no field for it, so it is an extension other Pencil clients ignore; without it a reopened
525
+ * document falls back to Figma's own two statuses.
526
+ */
527
+ statuses: v.optional(penStatusWorkflowSchema),
528
+ /**
529
+ * The libraries the document switched on, as Core keeps them on the document node: the revision
530
+ * each library's components were inserted from. Pencil has no field for it, so it is an
531
+ * extension other Pencil clients ignore; without it a reopened document forgets the bindings.
532
+ */
533
+ enabledLibraries: v.optional(penEnabledLibrariesSchema),
534
+ /**
535
+ * The library this document publishes as, as Core keeps it on the document node. Pencil has no
536
+ * field for it, so it is an extension other Pencil clients ignore; without it the next publish
537
+ * starts a new library rather than a revision of this one.
538
+ */
539
+ sourceLibraryPublication: v.optional(penSourceLibraryPublicationSchema),
427
540
  children: v.array(nodeSchema)
428
541
  });
429
542
  /** A `.pen` file's text, which may hold comments, as its document. */
@@ -779,6 +892,6 @@ function convertEffects(effect, ctx, shaders) {
779
892
  return (Array.isArray(effect) ? effect : [effect]).flatMap((item) => convertEffect(item, ctx, shaders) ?? []);
780
893
  }
781
894
  //#endregion
782
- export { applyStroke, convertEffects, convertPaints, createImageStore, penFileSchema, strokeFields };
895
+ export { applyStroke, convertEffects, convertPaints, createImageStore, penCropTransform, penFileSchema, strokeFields };
783
896
 
784
897
  //# sourceMappingURL=effects.js.map