@pairdraw/scene-graph 0.16.2 → 0.17.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.
Files changed (98) hide show
  1. package/dist/checkpoint.d.ts.map +1 -1
  2. package/dist/checkpoint.js +8 -3
  3. package/dist/checkpoint.js.map +1 -1
  4. package/dist/color/index.d.ts.map +1 -1
  5. package/dist/color/index.js +3 -3
  6. package/dist/color/index.js.map +1 -1
  7. package/dist/color/management.d.ts.map +1 -1
  8. package/dist/color/management.js +4 -2
  9. package/dist/color/management.js.map +1 -1
  10. package/dist/coordinate.d.ts.map +1 -1
  11. package/dist/coordinate.js +3 -1
  12. package/dist/coordinate.js.map +1 -1
  13. package/dist/copy.d.ts.map +1 -1
  14. package/dist/copy.js +1 -0
  15. package/dist/copy.js.map +1 -1
  16. package/dist/css/values.d.ts.map +1 -1
  17. package/dist/css/values.js +2 -2
  18. package/dist/css/values.js.map +1 -1
  19. package/dist/geometry.d.ts +14 -7
  20. package/dist/geometry.d.ts.map +1 -1
  21. package/dist/geometry.js +130 -26
  22. package/dist/geometry.js.map +1 -1
  23. package/dist/graph.d.ts.map +1 -1
  24. package/dist/graph.js +7 -3
  25. package/dist/graph.js.map +1 -1
  26. package/dist/hit-test.d.ts.map +1 -1
  27. package/dist/hit-test.js +100 -8
  28. package/dist/hit-test.js.map +1 -1
  29. package/dist/instances/content-size.js +1 -1
  30. package/dist/instances/index.d.ts.map +1 -1
  31. package/dist/instances/index.js +4 -1
  32. package/dist/instances/index.js.map +1 -1
  33. package/dist/instances/sync.js +4 -3
  34. package/dist/instances/sync.js.map +1 -1
  35. package/dist/layout/index.js +1 -1
  36. package/dist/resize.d.ts +4 -1
  37. package/dist/resize.d.ts.map +1 -1
  38. package/dist/resize.js +18 -12
  39. package/dist/resize.js.map +1 -1
  40. package/dist/scaling/node.d.ts.map +1 -1
  41. package/dist/scaling/node.js +3 -1
  42. package/dist/scaling/node.js.map +1 -1
  43. package/dist/scaling/tree.d.ts.map +1 -1
  44. package/dist/scaling/tree.js +8 -5
  45. package/dist/scaling/tree.js.map +1 -1
  46. package/dist/slots/authoring.js +3 -6
  47. package/dist/slots/authoring.js.map +1 -1
  48. package/dist/slots/content.d.ts.map +1 -1
  49. package/dist/slots/content.js +15 -25
  50. package/dist/slots/content.js.map +1 -1
  51. package/dist/slots/frames.js +1 -2
  52. package/dist/slots/frames.js.map +1 -1
  53. package/dist/snap.d.ts.map +1 -1
  54. package/dist/snap.js +12 -4
  55. package/dist/snap.js.map +1 -1
  56. package/dist/types.d.ts +5 -0
  57. package/dist/types.d.ts.map +1 -1
  58. package/dist/types.js.map +1 -1
  59. package/dist/undo.d.ts +2 -1
  60. package/dist/undo.d.ts.map +1 -1
  61. package/dist/undo.js +3 -2
  62. package/dist/undo.js.map +1 -1
  63. package/dist/variables/bindings.d.ts +2 -1
  64. package/dist/variables/bindings.d.ts.map +1 -1
  65. package/dist/variables/bindings.js +6 -2
  66. package/dist/variables/bindings.js.map +1 -1
  67. package/dist/variables/index.d.ts +2 -1
  68. package/dist/variables/index.d.ts.map +1 -1
  69. package/dist/variables/index.js +23 -5
  70. package/dist/variables/index.js.map +1 -1
  71. package/dist/variables/units.d.ts +31 -0
  72. package/dist/variables/units.d.ts.map +1 -0
  73. package/dist/variables/units.js +79 -4
  74. package/dist/variables/units.js.map +1 -1
  75. package/package.json +1 -1
  76. package/src/checkpoint.ts +8 -2
  77. package/src/color/index.ts +3 -6
  78. package/src/color/management.ts +8 -2
  79. package/src/coordinate.ts +4 -1
  80. package/src/copy.ts +2 -0
  81. package/src/css/values.ts +3 -2
  82. package/src/geometry.ts +147 -24
  83. package/src/graph.ts +9 -3
  84. package/src/hit-test.ts +138 -16
  85. package/src/instances/index.ts +5 -1
  86. package/src/instances/sync.ts +5 -3
  87. package/src/resize.ts +40 -20
  88. package/src/scaling/node.ts +3 -1
  89. package/src/scaling/tree.ts +3 -2
  90. package/src/slots/authoring.ts +7 -7
  91. package/src/slots/content.ts +13 -19
  92. package/src/slots/frames.ts +3 -3
  93. package/src/snap.ts +14 -4
  94. package/src/types.ts +5 -0
  95. package/src/undo.ts +3 -2
  96. package/src/variables/bindings.ts +6 -2
  97. package/src/variables/index.ts +29 -6
  98. package/src/variables/units.ts +97 -4
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;iBAwBgB,qBAAqB,OAAO,YAAY,MAAM,YAAY;iBAW1D,2BACd,OAAO,YACP,MAAM,WACN;;iBAcc,iBAAiB,eAAe,yBAAyB;;;;;iBAQzD,wBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;;;iBA2BK,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;iBAsBK,oBACd,OAAO,YACP,MAAM,WACN,WAAU;;;;;iBAqBI,oBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;iBA4CA,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;;;;KA2BJ;EAAiB,WAAW;;EAAuB,UAAU;;;iBAGzD,0BAA0B,OAAO,YAAY,KAAK,mBAAmB;;;;;iBAmCrE,mBAAmB,OAAO,YAAY,OAAO,mBAAmB;;;;;iBAoBhE,qBAAqB,OAAO,YAAY,KAAK,mBAAmB;;;;;;iBAkBhE,0BAA0B,OAAO,YAAY,QAAQ"}
1
+ {"version":3,"file":"bindings.d.ts","names":[],"sources":["../../src/variables/bindings.ts"],"mappings":";;;;;;iBAyBgB,qBAAqB,OAAO,YAAY,MAAM,YAAY;iBAW1D,2BACd,OAAO,YACP,MAAM,WACN;;iBAcc,iBAAiB,eAAe,yBAAyB;;;;;iBAQzD,wBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;;;iBA2BK,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,QAAQ;;;;;;iBAsBK,oBACd,OAAO,YACP,MAAM,WACN,WAAU;;;;;;iBAsBI,oBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;iBA8CA,sBACd,OAAO,YACP,MAAM,WACN,WAAU,uBACT,KAAK,QAAQ;;;;;KA2BJ;EAAiB,WAAW;;EAAuB,UAAU;;;iBAGzD,0BAA0B,OAAO,YAAY,KAAK,mBAAmB;;;;;iBAmCrE,mBAAmB,OAAO,YAAY,OAAO,mBAAmB;;;;;iBAoBhE,qBAAqB,OAAO,YAAY,KAAK,mBAAmB;;;;;;iBAkBhE,0BAA0B,OAAO,YAAY,QAAQ"}
@@ -1,6 +1,7 @@
1
1
  import { pixelLength } from "../text/lengths.js";
2
2
  import { copyFills, copyStrokes } from "../copy.js";
3
3
  import { ICON_BINDING_FIELDS, NUMERIC_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget } from "./fields.js";
4
+ import { runBindingScale } from "./units.js";
4
5
  import { hasInstanceOverride } from "../instances/index.js";
5
6
  import { ICON_NAME } from "../icons/schema.js";
6
7
  import { readIcon } from "../icons/model.js";
@@ -99,7 +100,8 @@ const NUMERIC_RUN_FIELDS = [
99
100
  ];
100
101
  /**
101
102
  * The runs a text's character bindings resolve to in its mode, when a bound number or font family
102
- * differs from what its characters hold. Bound font styles are left as stored.
103
+ * differs from what its characters hold, a size or spacing in the run's binding scale for the
104
+ * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.
103
105
  */
104
106
  function resolvedRunBindings(graph, node, fallback = "active") {
105
107
  const styleRuns = node.styleRuns.map((run) => {
@@ -111,7 +113,9 @@ function resolvedRunBindings(graph, node, fallback = "active") {
111
113
  if (!variableId) continue;
112
114
  const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
113
115
  if (value === void 0 || !Number.isFinite(value)) continue;
114
- const next = boundNumberValue(field, value);
116
+ const effective = value * runBindingScale(node, style, field);
117
+ if (!Number.isFinite(effective)) continue;
118
+ const next = boundNumberValue(field, effective);
115
119
  if (isEqual(style[field], next)) continue;
116
120
  style = {
117
121
  ...style,
@@ -1 +1 @@
1
- {"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances'\nimport type { Color } from '../primitives'\nimport { pixelLength } from '../text/lengths'\nimport type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))\n continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined\n return graph.resolveVariableForNode(node.id, variableId, fallback)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || hasInstanceOverride(graph, node.id, 'iconName')) return undefined\n const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold. Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const next = boundNumberValue(field, value)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId\n ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback))\n : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * A bound paint takes its whole color from the variable, alpha included, the way Figma stores\n * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.\n */\nfunction applyBoundColor(paint: Fill | Stroke, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */\nexport function resolvedPaintBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n // Most nodes bind nothing, so no copy is made until a paint binding is actually found.\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n for (const field in node.boundVariables) {\n if (!field.endsWith('/color')) continue\n const paint = paintBindingTarget(field)\n if (!paint) continue\n const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)\n const { index } = paint\n if (!color) continue\n if (paint.list === 'fills') {\n if (!node.fills[index]) continue\n changes.fills ??= copyFills(node.fills)\n applyBoundColor(changes.fills[index], color)\n } else {\n if (!node.strokes[index]) continue\n changes.strokes ??= copyStrokes(node.strokes)\n applyBoundColor(changes.strokes[index], color)\n }\n }\n return changes\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\nfunction subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {\n const nodes: SceneNode[] = []\n const pending = [...roots]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n nodes.push(node)\n pending.push(...node.childIds)\n }\n return nodes\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {\n const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds)\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n pending.push(...variableValueReferences(value))\n }\n return collections\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, without authoring\n * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved\n * values differ from their bindings elsewhere in the document are left as saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n for (const node of scopedNodes(graph, scope)) {\n const updates = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n"],"mappings":";;;;;;;;;;;AAwBA,SAAgB,qBAAqB,OAAmB,MAA4B;CAClF,IAAI,QAAQ;CACZ,IAAI,UAAiC;CACrC,OAAO,SAAS;EACd,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,iBAAiB;EACtE,IAAI,QAAQ,SAAS,YAAY,QAAQ;EACzC,UAAU,QAAQ,WAAW,MAAM,QAAQ,QAAQ,QAAQ,IAAI,KAAA;CACjE;CACA,OAAO;AACT;AAEA,SAAgB,2BACd,OACA,MACA,OACM;CACN,IAAI,CAAC,8BAA8B,KAAK,GAAG;CAC3C,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,KAAK,wBAAwB;EAC3B,GAAG,KAAK;GACP,QAAQ,MAAM,yBAAyB,UAAU;CACpD;AACF;;AAGA,MAAM,qCAA0C,IAAI,IAAI,CAAC,cAAc,eAAe,CAAC;;AAGvF,SAAgB,iBAAiB,OAAe,OAAoC;CAClF,OAAO,mBAAmB,IAAI,KAAK,IAAI,YAAY,KAAK,IAAI;AAC9D;;;;;AAMA,SAAgB,wBACd,OACA,MACA,WAAiC,UACb;CACpB,MAAM,UAA8B,CAAC;CACrC,KAAK,MAAM,CAAC,OAAO,eAAe,OAAO,QAAQ,KAAK,cAAc,GAAG;EACrE,IAAI,CAAC,eAAe,IAAI,KAAK,GAAG;EAChC,KAAK,UAAU,WAAW,UAAU,aAAa,oBAAoB,OAAO,KAAK,IAAI,KAAK,GACxF;EACF,MAAM,QAAQ,MAAM,6BAA6B,KAAK,IAAI,YAAY,QAAQ;EAC9E,IAAI,UAAU,KAAA,KAAa,CAAC,OAAO,SAAS,KAAK,GAA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O,OAAO,MAAM,YAAY;CACrC,IAAI,cAAc,OAAO,OAAO,aAAa,OAAO,MAAM,QAAQ;CAClE,OAAO,qBAAqB,OAAO,MAAM,SAAS;AACpD;;;;;;AAOA,SAAgB,0BAA0B,OAAmB,OAAgC;CAC3F,MAAM,UAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK,GAAG;EAC5C,MAAM,UAAU;GACd,GAAG,wBAAwB,OAAO,IAAI;GACtC,GAAG,sBAAsB,OAAO,IAAI;GACpC,GAAG,oBAAoB,OAAO,IAAI;EACpC;EACA,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI,OAAO;EACjC,QAAQ,KAAK,KAAK,EAAE;CACtB;CACA,OAAO;AACT"}
1
+ {"version":3,"file":"bindings.js","names":[],"sources":["../../src/variables/bindings.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit/predicate'\n\nimport type { VariableModeFallback } from '.'\nimport { copyFills, copyStrokes } from '../copy'\nimport type { SceneGraph } from '../graph'\nimport { readIcon } from '../icons/model'\nimport { ICON_NAME } from '../icons/schema'\nimport { hasInstanceOverride } from '../instances'\nimport type { Color } from '../primitives'\nimport { pixelLength } from '../text/lengths'\nimport type { Fill, SceneNode, Stroke, StyleRun, TextLength } from '../types'\nimport { NUMERIC_FIELDS, isNumericVariableBindingField, paintBindingTarget } from './fields'\nimport { variableFontFamily, variableText, variableTruthy } from './text'\nimport { runBindingScale } from './units'\nimport { variableValueReferences } from './value'\nexport {\n ICON_BINDING_FIELDS,\n isNumericVariableBindingField,\n paintBindingTarget,\n TEXT_CONTENT_VARIABLE_TYPES,\n VISIBILITY_VARIABLE_TYPES,\n type PaintBindingList\n} from './fields'\n\n/** New declarations belong to the outermost occurrence, bounded by a component definition. */\nexport function variableBindingOwner(graph: SceneGraph, node: SceneNode): SceneNode {\n let owner = node\n let current: SceneNode | undefined = node\n while (current) {\n if (current.type === 'COMPONENT' || current.type === 'COMPONENT_SET') break\n if (current.type === 'INSTANCE') owner = current\n current = current.parentId ? graph.getNode(current.parentId) : undefined\n }\n return owner\n}\n\nexport function assignVariableBindingUnits(\n graph: SceneGraph,\n node: SceneNode,\n field: string\n): void {\n if (!isNumericVariableBindingField(field)) return\n const owner = variableBindingOwner(graph, node)\n node.variableBindingScales = {\n ...node.variableBindingScales,\n [field]: owner.variableAssignmentScales[field] ?? 1\n }\n}\n\n/** Fields a bound number sets as a length in pixels, as Figma's do, whatever unit they held. */\nconst TEXT_LENGTH_FIELDS: ReadonlySet<string> = new Set(['lineHeight', 'letterSpacing'])\n\n/** A bound number as the field stores it. */\nexport function boundNumberValue(field: string, value: number): number | TextLength {\n return TEXT_LENGTH_FIELDS.has(field) ? pixelLength(value) : value\n}\n\n/**\n * The values a node's numeric bindings resolve to in its mode, in scene units, for the fields\n * whose stored value differs. A width or height an instance overrides keeps its own value.\n */\nexport function resolvedNumericBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n for (const [field, variableId] of Object.entries(node.boundVariables)) {\n if (!NUMERIC_FIELDS.has(field)) continue\n if ((field === 'width' || field === 'height') && hasInstanceOverride(graph, node.id, field))\n continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const scale = node.variableBindingScales[field] ?? 1\n const effective = value * scale\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(\n field,\n field === 'opacity' ? Math.max(0, Math.min(1, effective)) : effective\n )\n if (!isEqual(node[field as keyof SceneNode], next)) Object.assign(updates, { [field]: next })\n }\n return updates\n}\n\n/**\n * The text, font family, and visibility a node's string and boolean bindings resolve to in its\n * mode, for the fields whose stored value differs. Text, a font family, or visibility an instance\n * overrides, which typing in a layer or toggling its eye records, keeps its own value, as an\n * overridden width or height does. A font family is only named here; the editor loads its faces\n * after the reconcile (`loadBoundFonts` in Core), and the text draws in a fallback until they do.\n */\nexport function resolvedValueBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Partial<SceneNode> {\n const updates: Partial<SceneNode> = {}\n const resolve = (field: 'text' | 'fontFamily' | 'visible') => {\n const variableId = node.boundVariables[field]\n if (!variableId || hasInstanceOverride(graph, node.id, field)) return undefined\n return graph.resolveVariableForNode(node.id, variableId, fallback)\n }\n const text = node.type === 'TEXT' ? variableText(resolve('text')) : undefined\n if (text !== undefined && text !== node.text) updates.text = text\n const fontFamily = node.type === 'TEXT' ? variableFontFamily(resolve('fontFamily')) : undefined\n if (fontFamily !== undefined && fontFamily !== node.fontFamily) updates.fontFamily = fontFamily\n // Figma binds visibility to text too, and shows the layer when the text reads as true.\n const visible = variableTruthy(resolve('visible'))\n if (visible !== undefined && visible !== node.visible) updates.visible = visible\n return updates\n}\n\n/**\n * The icon an icon frame's `iconName` binding names in its mode, when it differs from the icon\n * it draws. Only frames that are icons resolve it; other layers keep the binding inert. The\n * caller redraws the frame, as resolving only names the icon.\n */\nexport function resolvedIconBinding(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): string | undefined {\n if (node.type !== 'FRAME') return undefined\n const icon = readIcon(node)\n if (!icon) return undefined\n const variableId = node.boundVariables['iconName']\n if (!variableId || hasInstanceOverride(graph, node.id, 'iconName')) return undefined\n const resolved = graph.resolveVariableForNode(node.id, variableId, fallback)\n if (typeof resolved !== 'string') return undefined\n const name = resolved.trim()\n if (name === '' || name === icon.name || !ICON_NAME.test(name)) return undefined\n return name\n}\n\n/** Fields of a range of characters a bound number gives its value. */\nconst NUMERIC_RUN_FIELDS = ['fontSize', 'fontWeight', 'letterSpacing', 'lineHeight'] as const\n\n/**\n * The runs a text's character bindings resolve to in its mode, when a bound number or font family\n * differs from what its characters hold, a size or spacing in the run's binding scale for the\n * field, as a rescale left it (`runBindingScale`). Bound font styles are left as stored.\n */\nexport function resolvedRunBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = node.styleRuns.map((run): StyleRun => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let style = run.style\n for (const field of NUMERIC_RUN_FIELDS) {\n const variableId = bound[field]\n if (!variableId) continue\n const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback)\n if (value === undefined || !Number.isFinite(value)) continue\n const effective = value * runBindingScale(node, style, field)\n if (!Number.isFinite(effective)) continue\n const next = boundNumberValue(field, effective)\n if (isEqual(style[field], next)) continue\n style = { ...style, [field]: next }\n }\n const familyId = bound.fontFamily\n const family = familyId\n ? variableFontFamily(graph.resolveVariableForNode(node.id, familyId, fallback))\n : undefined\n if (family !== undefined && family !== style.fontFamily)\n style = { ...style, fontFamily: family }\n return style === run.style ? run : { ...run, style }\n })\n const changed = styleRuns.some((run, index) => run !== node.styleRuns[index])\n return changed ? { styleRuns } : {}\n}\n\n/** The variables a node binds, its own and its characters'. */\nfunction boundVariableIds(node: SceneNode): string[] {\n return [\n ...Object.values(node.boundVariables),\n ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))\n ].filter((id): id is string => typeof id === 'string')\n}\n\n/**\n * A bound paint takes its whole color from the variable, alpha included, the way Figma stores\n * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.\n */\nfunction applyBoundColor(paint: Fill | Stroke, color: Color): void {\n paint.color = { ...color, a: 1 }\n paint.opacity = color.a\n}\n\n/** The fills and strokes a node's color bindings resolve to in its mode, when it has any. */\nexport function resolvedPaintBindings(\n graph: SceneGraph,\n node: SceneNode,\n fallback: VariableModeFallback = 'active'\n): Pick<Partial<SceneNode>, 'fills' | 'strokes'> {\n // Most nodes bind nothing, so no copy is made until a paint binding is actually found.\n const changes: Pick<Partial<SceneNode>, 'fills' | 'strokes'> = {}\n for (const field in node.boundVariables) {\n if (!field.endsWith('/color')) continue\n const paint = paintBindingTarget(field)\n if (!paint) continue\n const color = graph.resolveColorVariableForNode(node.id, node.boundVariables[field], fallback)\n const { index } = paint\n if (!color) continue\n if (paint.list === 'fills') {\n if (!node.fills[index]) continue\n changes.fills ??= copyFills(node.fills)\n applyBoundColor(changes.fills[index], color)\n } else {\n if (!node.strokes[index]) continue\n changes.strokes ??= copyStrokes(node.strokes)\n applyBoundColor(changes.strokes[index], color)\n }\n }\n return changes\n}\n\n/**\n * The layers a reconcile looks at: those bound to these variables, directly or through a variable\n * aliasing them, or the layers in these subtrees. Without a scope, every layer.\n */\nexport type BindingScope = { variables: Iterable<string> } | { subtrees: Iterable<string> }\n\n/** These variables and every variable that aliases one of them, at any depth and in any mode. */\nexport function variablesResolvingThrough(graph: SceneGraph, ids: Iterable<string>): Set<string> {\n const found = new Set(ids)\n let grew = true\n while (grew) {\n grew = false\n for (const variable of graph.variables.values()) {\n if (found.has(variable.id)) continue\n const aliases = Object.values(variable.valuesByMode).some((value) =>\n variableValueReferences(value).some((id) => found.has(id))\n )\n if (aliases) {\n found.add(variable.id)\n grew = true\n }\n }\n }\n return found\n}\n\nfunction subtreeNodes(graph: SceneGraph, roots: Iterable<string>): SceneNode[] {\n const nodes: SceneNode[] = []\n const pending = [...roots]\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n nodes.push(node)\n pending.push(...node.childIds)\n }\n return nodes\n}\n\n/**\n * The collections whose variables the layers in these subtrees resolve: those they bind, and\n * those the bound variables alias, so a mode set on the subtrees can change what they show.\n */\nexport function collectionsBoundIn(graph: SceneGraph, roots: Iterable<string>): Set<string> {\n const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds)\n const seen = new Set<string>()\n const collections = new Set<string>()\n for (let id = pending.pop(); id !== undefined; id = pending.pop()) {\n if (seen.has(id)) continue\n seen.add(id)\n const variable = graph.variables.get(id)\n if (!variable) continue\n collections.add(variable.collectionId)\n for (const value of Object.values(variable.valuesByMode))\n pending.push(...variableValueReferences(value))\n }\n return collections\n}\n\n/**\n * The layers a change to these variables reaches: those binding one of them, or a variable that\n * aliases one, on the layer itself or on its characters.\n */\nexport function layersUsingVariables(graph: SceneGraph, ids: Iterable<string>): SceneNode[] {\n const variables = variablesResolvingThrough(graph, ids)\n return [...graph.getAllNodes()].filter((node) =>\n boundVariableIds(node).some((id) => variables.has(id))\n )\n}\n\nfunction scopedNodes(graph: SceneGraph, scope: BindingScope | undefined): Iterable<SceneNode> {\n if (!scope) return graph.getAllNodes()\n if ('subtrees' in scope) return subtreeNodes(graph, scope.subtrees)\n return layersUsingVariables(graph, scope.variables)\n}\n\n/**\n * Resolve live numeric, text, font family, and visibility bindings, numbers in scene units, without authoring\n * instance overrides. A scope limits it to the layers a change can reach, so layers whose saved\n * values differ from their bindings elsewhere in the document are left as saved.\n */\nexport function reconcileVariableBindings(graph: SceneGraph, scope?: BindingScope): string[] {\n const changed: string[] = []\n for (const node of scopedNodes(graph, scope)) {\n const updates = {\n ...resolvedNumericBindings(graph, node),\n ...resolvedValueBindings(graph, node),\n ...resolvedRunBindings(graph, node)\n }\n if (Object.keys(updates).length === 0) continue\n graph.updateNode(node.id, updates)\n changed.push(node.id)\n }\n return changed\n}\n"],"mappings":";;;;;;;;;;;;AAyBA,SAAgB,qBAAqB,OAAmB,MAA4B;CAClF,IAAI,QAAQ;CACZ,IAAI,UAAiC;CACrC,OAAO,SAAS;EACd,IAAI,QAAQ,SAAS,eAAe,QAAQ,SAAS,iBAAiB;EACtE,IAAI,QAAQ,SAAS,YAAY,QAAQ;EACzC,UAAU,QAAQ,WAAW,MAAM,QAAQ,QAAQ,QAAQ,IAAI,KAAA;CACjE;CACA,OAAO;AACT;AAEA,SAAgB,2BACd,OACA,MACA,OACM;CACN,IAAI,CAAC,8BAA8B,KAAK,GAAG;CAC3C,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,KAAK,wBAAwB;EAC3B,GAAG,KAAK;GACP,QAAQ,MAAM,yBAAyB,UAAU;CACpD;AACF;;AAG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,IAAI,KAAK,QAAQ,IAAI,GAAG,OAAO,KAAA,GAAW,KAAK,QAAQ,IAAI,GAAG;EACjE,IAAI,KAAK,IAAI,EAAE,GAAG;EAClB,KAAK,IAAI,EAAE;EACX,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;EACvC,IAAI,CAAC,UAAU;EACf,YAAY,IAAI,SAAS,YAAY;EACrC,KAAK,MAAM,SAAS,OAAO,OAAO,SAAS,YAAY,GACrD,QAAQ,KAAK,GAAG,wBAAwB,KAAK,CAAC;CAClD;CACA,OAAO;AACT;;;;;AAMA,SAAgB,qBAAqB,OAAmB,KAAoC;CAC1F,MAAM,YAAY,0BAA0B,OAAO,GAAG;CACtD,OAAO,CAAC,GAAG,MAAM,YAAY,CAAC,CAAC,CAAC,QAAQ,SACtC,iBAAiB,IAAI,CAAC,CAAC,MAAM,OAAO,UAAU,IAAI,EAAE,CAAC,CACvD;AACF;AAEA,SAAS,YAAY,OAAmB,OAAsD;CAC5F,IAAI,CAAC,OAAO,OAAO,MAAM,YAAY;CACrC,IAAI,cAAc,OAAO,OAAO,aAAa,OAAO,MAAM,QAAQ;CAClE,OAAO,qBAAqB,OAAO,MAAM,SAAS;AACpD;;;;;;AAOA,SAAgB,0BAA0B,OAAmB,OAAgC;CAC3F,MAAM,UAAoB,CAAC;CAC3B,KAAK,MAAM,QAAQ,YAAY,OAAO,KAAK,GAAG;EAC5C,MAAM,UAAU;GACd,GAAG,wBAAwB,OAAO,IAAI;GACtC,GAAG,sBAAsB,OAAO,IAAI;GACpC,GAAG,oBAAoB,OAAO,IAAI;EACpC;EACA,IAAI,OAAO,KAAK,OAAO,CAAC,CAAC,WAAW,GAAG;EACvC,MAAM,WAAW,KAAK,IAAI,OAAO;EACjC,QAAQ,KAAK,KAAK,EAAE;CACtB;CACA,OAAO;AACT"}
@@ -13,6 +13,7 @@ import { variableFormulaSchema } from "./formula/schema.js";
13
13
  import { variableAliasSchema, variableCollectionSchema, variableColorExpressionSchema, variableSchema } from "./schema.js";
14
14
  import { variableFontFamily, variableText, variableTruthy } from "./text.js";
15
15
  import { ROOT_FONT_SIZE_PX, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, updateTokenExpression } from "./token.js";
16
+ import { SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales } from "./units.js";
16
17
  import { isUnsupportedVariableValue, mapVariableValueReferences, resolveVariableValue, variableValueReferences } from "./value.js";
17
18
  import { SceneGraph } from "../graph.js";
18
19
  import { Variable, VariableCollection, VariableCollectionMode, VariableType, VariableValue } from "../types.js";
@@ -37,5 +38,5 @@ declare function getVariablesByType(graph: SceneGraph, type: VariableType): Vari
37
38
  declare function bindVariable(graph: SceneGraph, nodeId: string, field: string, variableId: string): void;
38
39
  declare function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void;
39
40
  //#endregion
40
- export { BindingScope, type FormulaFold, type FormulaToken, type FormulaTokenKind, type FormulaValueType, ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, NodeVariableResolver, type PaintBindingList, type PrintFormulaOptions, ROOT_FONT_SIZE_PX, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableModeFallback, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough };
41
+ export { BindingScope, type FormulaFold, type FormulaToken, type FormulaTokenKind, type FormulaValueType, ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, NodeVariableResolver, type PaintBindingList, type PrintFormulaOptions, ROOT_FONT_SIZE_PX, SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableModeFallback, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, pinnedRunBindingScales, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, runBindingScale, scaleVariableBindingUnits, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough, withBoundBindingScales };
41
42
  //# sourceMappingURL=index.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;iBAgCgB,YAAY,OAAO,YAAY,UAAU;iBAQzC,eAAe,OAAO,YAAY;iBA4BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAWpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBAgBpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBASxD,kBAAkB,YAAY,qBAAqB;iBAKnD,0BAA0B,OAAO,YAAY,uBAAuB;iBAQpE,mBAAmB,OAAO,YAAY,MAAM,eAAe;iBAgD3D,aACd,OAAO,YACP,gBACA,eACA;iBA0Ec,eAAe,OAAO,YAAY,gBAAgB"}
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../../src/variables/index.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;iBAgDgB,YAAY,OAAO,YAAY,UAAU;iBAQzC,eAAe,OAAO,YAAY;iBA8BlC,cAAc,OAAO,YAAY,YAAY;iBAe7C,eACd,OAAO,YACP,0BACA,cACA,MAAM,cACN,sBACA,QAAQ,gBACP;iBAsBa,iBACd,OAAO,YACP,0BACA,eACC;iBAca,iBAAiB,OAAO,YAAY;iBAWpC,cAAc,OAAO,YAAY,sBAAsB;iBAIvD,QACd,OAAO,YACP,sBACA,gBACA,cACA;;iBAgBc,WACd,OAAO,YACP,0BACA,sBACA,cACA;iBAQc,WAAW,OAAO,YAAY,sBAAsB;iBAgBpD,WACd,OAAO,YACP,sBACA,gBACA;iBAQc,eAAe,OAAO,YAAY,sBAAsB;;iBASxD,kBAAkB,YAAY,qBAAqB;iBAKnD,0BAA0B,OAAO,YAAY,uBAAuB;iBAQpE,mBAAmB,OAAO,YAAY,MAAM,eAAe;iBAgD3D,aACd,OAAO,YACP,gBACA,eACA;iBA4Ec,eAAe,OAAO,YAAY,gBAAgB"}
@@ -1,6 +1,7 @@
1
1
  import { BLACK } from "../constants.js";
2
2
  import { bindingOverrideField, setInstanceOverride } from "../instances/overrides.js";
3
3
  import { BOOLEAN_BINDING_FIELDS, ICON_BINDING_FIELDS, STRING_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, isNumericVariableBindingField, paintBindingTarget, uniformBindingTarget } from "./fields.js";
4
+ import { SCALED_RUN_BINDING_FIELDS, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales } from "./units.js";
4
5
  import { findInstanceAncestor } from "../instances/index.js";
5
6
  import { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from "../shaders/model.js";
6
7
  import { variableFontFamily, variableText, variableTruthy } from "./text.js";
@@ -21,6 +22,16 @@ import { ROOT_FONT_SIZE_PX, tokenExpressionForValue, tokenNumberFromUnit, tokenN
21
22
  import { omit, omitBy } from "es-toolkit/object";
22
23
  import { partition } from "es-toolkit/array";
23
24
  //#region src/variables/index.ts
25
+ /**
26
+ * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's
27
+ * scale for those fields changes or goes, and the change to announce.
28
+ */
29
+ function pinRunBindingScales(node, fields) {
30
+ const styleRuns = pinnedRunBindingScales(node, fields);
31
+ if (!styleRuns) return {};
32
+ node.styleRuns = styleRuns;
33
+ return { styleRuns };
34
+ }
24
35
  function addVariable(graph, variable) {
25
36
  graph.variables.set(variable.id, variable);
26
37
  const collection = graph.variableCollections.get(variable.collectionId);
@@ -36,10 +47,13 @@ function removeVariable(graph, id) {
36
47
  if (!Object.values(node.boundVariables).includes(id)) continue;
37
48
  graph.willChangeNode(node);
38
49
  node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id);
39
- node.variableBindingScales = omitBy(node.variableBindingScales, (_, field) => !(field in node.boundVariables));
50
+ const pruned = Object.keys(node.variableBindingScales).filter((field) => !(field in node.boundVariables));
51
+ const runs = pinRunBindingScales(node, pruned);
52
+ node.variableBindingScales = omit(node.variableBindingScales, pruned);
40
53
  graph.emitter.emit("node:updated", node.id, {
41
54
  boundVariables: { ...node.boundVariables },
42
- variableBindingScales: { ...node.variableBindingScales }
55
+ variableBindingScales: { ...node.variableBindingScales },
56
+ ...runs
43
57
  });
44
58
  markBoundVariablesOverrideOnInstance(graph, node.id);
45
59
  }
@@ -210,11 +224,13 @@ function bindVariable(graph, nodeId, field, variableId) {
210
224
  ...node.boundVariables,
211
225
  [field]: variableId
212
226
  };
227
+ const runs = pinRunBindingScales(node, [field]);
213
228
  assignVariableBindingUnits(graph, node, field);
214
229
  markBoundVariablesOverrideOnInstance(graph, nodeId, field);
215
230
  graph.emitter.emit("node:updated", nodeId, {
216
231
  boundVariables: { ...node.boundVariables },
217
- variableBindingScales: { ...node.variableBindingScales }
232
+ variableBindingScales: { ...node.variableBindingScales },
233
+ ...runs
218
234
  });
219
235
  }
220
236
  function unbindVariable(graph, nodeId, field) {
@@ -223,11 +239,13 @@ function unbindVariable(graph, nodeId, field) {
223
239
  if (!(field in node.boundVariables)) return;
224
240
  graph.willChangeNode(node);
225
241
  node.boundVariables = omit(node.boundVariables, [field]);
242
+ const runs = pinRunBindingScales(node, [field]);
226
243
  node.variableBindingScales = omit(node.variableBindingScales, [field]);
227
244
  markBoundVariablesOverrideOnInstance(graph, nodeId, field);
228
245
  graph.emitter.emit("node:updated", nodeId, {
229
246
  boundVariables: { ...node.boundVariables },
230
- variableBindingScales: { ...node.variableBindingScales }
247
+ variableBindingScales: { ...node.variableBindingScales },
248
+ ...runs
231
249
  });
232
250
  }
233
251
  function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
@@ -241,6 +259,6 @@ function markBoundVariablesOverrideOnInstance(graph, nodeId, field) {
241
259
  if (field) setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, bindingOverrideField(field), node.boundVariables[field] ?? null);
242
260
  }
243
261
  //#endregion
244
- export { ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, ROOT_FONT_SIZE_PX, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough };
262
+ export { ICON_BINDING_FIELDS, MAX_FORMULA_DEPTH, ROOT_FONT_SIZE_PX, SCALED_RUN_BINDING_FIELDS, TEXT_CONTENT_VARIABLE_TYPES, VISIBILITY_VARIABLE_TYPES, VariableFormulaError, VariableResolutionError, addCollection, addMode, addVariable, assignVariableBindingUnits, bindVariable, boundNumberValue, collectionsBoundIn, createBatchVariableResolver, createCollection, createMode, createVariable, evaluateVariableFormula, foldFormula, formatVariableFormula, formulaArity, formulaSymbol, formulaTokenName, formulaTokens, formulaValueType, getActiveModeId, getNodeVariableModeId, getVariablesByType, getVariablesForCollection, independentCornerChanges, inferFormulaType, isFormulaOperation, isFormulaReference, isNumericVariableBindingField, isUnsupportedVariableValue, layersUsingVariables, mapVariableValueReferences, modesDefaultFirst, paintBindingTarget, parseVariableFormula, pinnedRunBindingScales, printFormula, readFormulaToken, reconcileVariableBindings, removeCollection, removeMode, removeVariable, renameMode, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolveVariableInModes, resolveVariableValue, resolvedIconBinding, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, runBindingScale, scaleVariableBindingUnits, setActiveMode, setDefaultMode, tokenExpressionForValue, tokenNumberFromUnit, tokenNumberInUnit, unbindVariable, updateTokenExpression, variableAliasSchema, variableBindingOwner, variableCollectionSchema, variableColorExpressionSchema, variableFontFamily, variableFormulaReference, variableFormulaSchema, variableSchema, variableText, variableTruthy, variableValueInMode, variableValueReferences, variablesResolvingThrough, withBoundBindingScales };
245
263
 
246
264
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES\n} from './fields'\n\nexport * from './resolution'\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n node.variableBindingScales = omitBy(\n node.variableBindingScales,\n (_, field) => !(field in node.boundVariables)\n )\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(`Unknown binding field \"${field}\"`)\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAgB,YAAY,OAAmB,UAA0B;CACvE,MAAM,UAAU,IAAI,SAAS,IAAI,QAAQ;CACzC,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,cAAc,CAAC,WAAW,YAAY,SAAS,SAAS,EAAE,GAC5D,WAAW,YAAY,KAAK,SAAS,EAAE;AAE3C;AAEA,SAAgB,eAAe,OAAmB,IAAkB;CAClE,MAAM,WAAW,MAAM,UAAU,IAAI,EAAE;CACvC,IAAI,CAAC,UAAU;CACf,MAAM,UAAU,OAAO,EAAE;CACzB,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,YACF,WAAW,cAAc,WAAW,YAAY,QAAQ,QAAQ,QAAQ,EAAE;CAE5E,KAAK,MAAM,QAAQ,MAAM,MAAM,OAAO,GAAG;EAEvC,IAAI,CADe,OAAO,OAAO,KAAK,cAAc,CAAC,CAAC,SAAS,EACjD,GAAG;EACjB,MAAM,eAAe,IAAI;EACzB,KAAK,i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EACzC,gBAAgB,EAAE,GAAG,KAAK,eAAe;EACzC,uBAAuB,EAAE,GAAG,KAAK,sBAAsB;CACzD,CAAC;AACH;AAEA,SAAgB,eAAe,OAAmB,QAAgB,OAAqB;CACrF,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CACX,IAAI,EAAE,SAAS,KAAK,iBAAiB;CACrC,MAAM,eAAe,IAAI;CACzB,KAAK,iBAAiB,KAAK,KAAK,gBAAgB,CAAC,KAAK,CAAC;CACvD,KAAK,wBAAwB,KAAK,KAAK,uBAAuB,CAAC,KAAK,CAAC;CACrE,qCAAqC,OAAO,QAAQ,KAAK;CACzD,MAAM,QAAQ,KAAK,gBAAgB,QAAQ;EACzC,gBAAgB,EAAE,GAAG,KAAK,eAAe;EACzC,uBAAuB,EAAE,GAAG,KAAK,sBAAsB;CACzD,CAAC;AACH;AAEA,SAAS,qCACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/variables/index.ts"],"sourcesContent":["import { partition } from 'es-toolkit/array'\nimport { omit, omitBy } from 'es-toolkit/object'\n\nimport { BLACK } from '../constants'\nimport type { SceneGraph } from '../graph'\nimport { findInstanceAncestor } from '../instances'\nimport { bindingOverrideField, setInstanceOverride } from '../instances/overrides'\nimport { isShaderSourcePaint, shaderOfPaint, withShaderPaints } from '../shaders/model'\nimport type {\n SceneNode,\n Variable,\n VariableCollection,\n VariableCollectionMode,\n VariableType,\n VariableValue\n} from '../types'\nimport {\n isNumericVariableBindingField,\n variableBindingOwner,\n assignVariableBindingUnits\n} from './bindings'\nimport {\n BOOLEAN_BINDING_FIELDS,\n ICON_BINDING_FIELDS,\n paintBindingTarget,\n STRING_BINDING_FIELDS,\n TEXT_CONTENT_VARIABLE_TYPES,\n uniformBindingTarget,\n VISIBILITY_VARIABLE_TYPES\n} from './fields'\nimport { pinnedRunBindingScales } from './units'\n\nexport * from './resolution'\n\n/**\n * Gives the runs that bind `fields` the scale they resolve with as their own, before the layer's\n * scale for those fields changes or goes, and the change to announce.\n */\nfunction pinRunBindingScales(\n node: SceneNode,\n fields: readonly string[]\n): Pick<Partial<SceneNode>, 'styleRuns'> {\n const styleRuns = pinnedRunBindingScales(node, fields)\n if (!styleRuns) return {}\n node.styleRuns = styleRuns\n return { styleRuns }\n}\n\nexport function addVariable(graph: SceneGraph, variable: Variable): void {\n graph.variables.set(variable.id, variable)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection && !collection.variableIds.includes(variable.id)) {\n collection.variableIds.push(variable.id)\n }\n}\n\nexport function removeVariable(graph: SceneGraph, id: string): void {\n const variable = graph.variables.get(id)\n if (!variable) return\n graph.variables.delete(id)\n const collection = graph.variableCollections.get(variable.collectionId)\n if (collection) {\n collection.variableIds = collection.variableIds.filter((vid) => vid !== id)\n }\n for (const node of graph.nodes.values()) {\n const hadBinding = Object.values(node.boundVariables).includes(id)\n if (!hadBinding) continue\n graph.willChangeNode(node)\n node.boundVariables = omitBy(node.boundVariables, (varId) => varId === id) as Record<\n string,\n string\n >\n const pruned = Object.keys(node.variableBindingScales).filter(\n (field) => !(field in node.boundVariables)\n )\n const runs = pinRunBindingScales(node, pruned)\n node.variableBindingScales = omit(node.variableBindingScales, pruned)\n graph.emitter.emit('node:updated', node.id, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n markBoundVariablesOverrideOnInstance(graph, node.id)\n }\n}\n\nexport function addCollection(graph: SceneGraph, collection: VariableCollection): void {\n graph.variableCollections.set(collection.id, collection)\n if (!graph.activeMode.has(collection.id)) {\n graph.activeMode.set(collection.id, collection.defaultModeId)\n }\n}\n\nfunction defaultVariableValue(type: VariableType, value?: VariableValue): VariableValue {\n if (value !== undefined) return value\n if (type === 'COLOR') return { ...BLACK }\n if (type === 'FLOAT') return 0\n if (type === 'BOOLEAN') return false\n return ''\n}\n\nexport function createVariable(\n graph: SceneGraph,\n generateId: () => string,\n name: string,\n type: VariableType,\n collectionId: string,\n value?: VariableValue\n): Variable {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) throw new Error(`Collection \"${collectionId}\" not found`)\n const id = generateId()\n const defaultValue = defaultVariableValue(type, value)\n const valuesByMode: Record<string, VariableValue> = {}\n for (const mode of collection.modes) {\n valuesByMode[mode.modeId] = structuredClone(defaultValue)\n }\n const variable: Variable = {\n id,\n name,\n type,\n collectionId,\n valuesByMode,\n description: '',\n hiddenFromPublishing: false\n }\n addVariable(graph, variable)\n return variable\n}\n\nexport function createCollection(\n graph: SceneGraph,\n generateId: () => string,\n name: string\n): VariableCollection {\n const id = generateId()\n const modeId = generateId()\n const collection: VariableCollection = {\n id,\n name,\n modes: [{ modeId, name: 'Mode 1' }],\n defaultModeId: modeId,\n variableIds: []\n }\n addCollection(graph, collection)\n return collection\n}\n\nexport function removeCollection(graph: SceneGraph, id: string): void {\n const collection = graph.variableCollections.get(id)\n if (collection) {\n for (const varId of Array.from(collection.variableIds)) {\n removeVariable(graph, varId)\n }\n }\n graph.variableCollections.delete(id)\n graph.activeMode.delete(id)\n}\n\nexport function setActiveMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n graph.activeMode.set(collectionId, modeId)\n}\n\nexport function addMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string,\n sourceMode?: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n collection.modes.push({ modeId, name })\n const sourceModeId = sourceMode ?? collection.defaultModeId\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (!variable) continue\n variable.valuesByMode[modeId] = structuredClone(\n variable.valuesByMode[sourceModeId] ?? Object.values(variable.valuesByMode)[0]\n )\n }\n}\n\n/** Add a mode with a new ID from `generateId`; undo and redo replay it with `addMode`. */\nexport function createMode(\n graph: SceneGraph,\n generateId: () => string,\n collectionId: string,\n name: string,\n sourceMode?: string\n): string | undefined {\n if (!graph.variableCollections.has(collectionId)) return undefined\n const modeId = generateId()\n addMode(graph, collectionId, modeId, name, sourceMode)\n return modeId\n}\n\nexport function removeMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection || collection.modes.length <= 1) return\n collection.modes = collection.modes.filter((m) => m.modeId !== modeId)\n if (collection.defaultModeId === modeId) {\n collection.defaultModeId = collection.modes[0].modeId\n }\n for (const varId of collection.variableIds) {\n const variable = graph.variables.get(varId)\n if (variable) variable.valuesByMode = omit(variable.valuesByMode, [modeId])\n }\n if (graph.activeMode.get(collectionId) === modeId) {\n graph.activeMode.set(collectionId, collection.defaultModeId)\n }\n}\n\nexport function renameMode(\n graph: SceneGraph,\n collectionId: string,\n modeId: string,\n name: string\n): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n const mode = collection.modes.find((m) => m.modeId === modeId)\n if (mode) mode.name = name\n}\n\nexport function setDefaultMode(graph: SceneGraph, collectionId: string, modeId: string): void {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return\n if (!collection.modes.some((m) => m.modeId === modeId)) return\n collection.defaultModeId = modeId\n collection.modes = modesDefaultFirst(collection)\n}\n\n/** Figma has no default-mode field: the first mode is the default. */\nexport function modesDefaultFirst(collection: VariableCollection): VariableCollectionMode[] {\n const [defaults, rest] = partition(collection.modes, (m) => m.modeId === collection.defaultModeId)\n return [...defaults, ...rest]\n}\n\nexport function getVariablesForCollection(graph: SceneGraph, collectionId: string): Variable[] {\n const collection = graph.variableCollections.get(collectionId)\n if (!collection) return []\n return collection.variableIds\n .map((id) => graph.variables.get(id))\n .filter((v): v is Variable => v !== undefined)\n}\n\nexport function getVariablesByType(graph: SceneGraph, type: VariableType): Variable[] {\n return [...graph.variables.values()].filter((v) => v.type === type)\n}\n\n/**\n * Throws when a variable of `type` cannot bind to `field`, or for a field no binding takes. A\n * paint target is checked by its caller, which also validates its index.\n */\nfunction checkBindingFieldType(field: string, type: VariableType): void {\n if (isNumericVariableBindingField(field) && type !== 'FLOAT') {\n throw new Error(`Cannot bind ${type} variable to scalar field \"${field}\"`)\n }\n\n const textTypes: readonly VariableType[] =\n field === 'text' ? TEXT_CONTENT_VARIABLE_TYPES : ['STRING']\n if (STRING_BINDING_FIELDS.has(field) && !textTypes.includes(type)) {\n throw new Error(`Cannot bind ${type} variable to string field \"${field}\"`)\n }\n\n if (\n BOOLEAN_BINDING_FIELDS.has(field) &&\n !VISIBILITY_VARIABLE_TYPES.some((kind) => kind === type)\n ) {\n throw new Error(`Cannot bind ${type} variable to boolean field \"${field}\"`)\n }\n\n if (ICON_BINDING_FIELDS.has(field) && type !== 'STRING') {\n throw new Error(`Cannot bind ${type} variable to icon field \"${field}\"`)\n }\n\n // A shader uniform takes a number, a colour, or a boolean; its shader declares which.\n const uniform = uniformBindingTarget(field)\n if (uniform && type !== 'FLOAT' && type !== 'COLOR' && type !== 'BOOLEAN') {\n throw new Error(`Cannot bind ${type} variable to shader input \"${field}\"`)\n }\n\n const isKnownField =\n isNumericVariableBindingField(field) ||\n STRING_BINDING_FIELDS.has(field) ||\n BOOLEAN_BINDING_FIELDS.has(field) ||\n ICON_BINDING_FIELDS.has(field) ||\n paintBindingTarget(field) !== null ||\n uniform !== null\n\n if (!isKnownField) {\n throw new Error(`Unknown binding field \"${field}\"`)\n }\n}\nexport function bindVariable(\n graph: SceneGraph,\n nodeId: string,\n field: string,\n variableId: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n // Validate variable exists\n const variable = graph.variables.get(variableId)\n if (!variable) {\n throw new Error(`Variable \"${variableId}\" not found`)\n }\n\n // Color fields require COLOR variable type\n const paint = paintBindingTarget(field)\n if (paint) {\n if (variable.type !== 'COLOR') {\n throw new Error(`Cannot bind ${variable.type} variable to color field \"${field}\"`)\n }\n // Validate index is within current array bounds\n const currentLength = node[paint.list].length\n if (paint.index >= currentLength) {\n throw new Error(\n `Index ${paint.index} out of range for ${paint.list} (length ${currentLength})`\n )\n }\n // Auto-remove top-level dead binding (e.g. 'fills') when setting indexed binding\n if (paint.list in node.boundVariables) {\n node.boundVariables = omit(node.boundVariables, [paint.list])\n }\n }\n\n checkBindingFieldType(field, variable.type)\n\n // A shader input belongs to one paint, so its index must exist on the layer.\n const uniform = uniformBindingTarget(field)\n if (uniform && uniform.index >= node[uniform.list].length) {\n throw new Error(\n `Index ${uniform.index} out of range for ${uniform.list} (length ${node[uniform.list].length})`\n )\n }\n if (uniform) {\n // The binding lives with the shader entry, next to the value it resolves, so any renderer\n // that draws the paint resolves it the same way.\n const paints = node[uniform.list]\n const paint = paints.at(uniform.index)\n const shader = paint ? shaderOfPaint(node, paint) : null\n if (paint && shader && isShaderSourcePaint(shader)) {\n node.pluginData = withShaderPaints(node, paints, [\n {\n ...shader,\n uniformBindings: {\n ...shader.uniformBindings,\n [uniform.name]: variableId\n }\n }\n ])\n }\n graph.willChangeNode(node)\n graph.emitter.emit('node:updated', nodeId, {\n pluginData: node.pluginData,\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales }\n })\n return\n }\n graph.willChangeNode(node)\n node.boundVariables = { ...node.boundVariables, [field]: variableId }\n const runs = pinRunBindingScales(node, [field])\n assignVariableBindingUnits(graph, node, field)\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nexport function unbindVariable(graph: SceneGraph, nodeId: string, field: string): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n if (!(field in node.boundVariables)) return\n graph.willChangeNode(node)\n node.boundVariables = omit(node.boundVariables, [field])\n const runs = pinRunBindingScales(node, [field])\n node.variableBindingScales = omit(node.variableBindingScales, [field])\n markBoundVariablesOverrideOnInstance(graph, nodeId, field)\n graph.emitter.emit('node:updated', nodeId, {\n boundVariables: { ...node.boundVariables },\n variableBindingScales: { ...node.variableBindingScales },\n ...runs\n })\n}\n\nfunction markBoundVariablesOverrideOnInstance(\n graph: SceneGraph,\n nodeId: string,\n field?: string\n): void {\n const node = graph.nodes.get(nodeId)\n if (!node) return\n\n const owner = variableBindingOwner(graph, node)\n if (owner.type !== 'INSTANCE') return\n const nearest = findInstanceAncestor(graph, nodeId)\n if (nearest) setInstanceOverride(nearest.instanceOverrides, nearest.id, nodeId, 'boundVariables')\n setInstanceOverride(owner.instanceOverrides, owner.id, nodeId, 'boundVariables')\n if (field)\n setInstanceOverride(\n owner.instanceOverrides,\n owner.id,\n nodeId,\n bindingOverrideField(field),\n node.boundVariables[field] ?? null\n )\n}\n\nexport * from './bindings'\nexport * from './corners'\nexport * from './formula'\nexport * from './formula/schema'\nexport * from './schema'\nexport * from './text'\nexport * from './token'\nexport * from './units'\nexport * from './value'\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,SAAS,oBACP,MACA,QACuC;CACvC,MAAM,YAAY,uBAAuB,MAAM,MAAM;CACrD,IAAI,CAAC,WAAW,OAAO,CAAC;CACxB,KAAK,YAAY;CACjB,OAAO,EAAE,UAAU;AACrB;AAEA,SAAgB,YAAY,OAAmB,UAA0B;CACvE,MAAM,UAAU,IAAI,SAAS,IAAI,QAAQ;CACzC,MAAM,aAAa,MAAM,oBAAoB,IAAI,SAAS,YAAY;CACtE,IAAI,cAAc,CAAC,WAAW,YAAY,SAAS,SAAS,EAAE,G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,CAAC;AACH;AAEA,SAAS,qCACP,OACA,QACA,OACM;CACN,MAAM,OAAO,MAAM,MAAM,IAAI,MAAM;CACnC,IAAI,CAAC,MAAM;CAEX,MAAM,QAAQ,qBAAqB,OAAO,IAAI;CAC9C,IAAI,MAAM,SAAS,YAAY;CAC/B,MAAM,UAAU,qBAAqB,OAAO,MAAM;CAClD,IAAI,SAAS,oBAAoB,QAAQ,mBAAmB,QAAQ,IAAI,QAAQ,gBAAgB;CAChG,oBAAoB,MAAM,mBAAmB,MAAM,IAAI,QAAQ,gBAAgB;CAC/E,IAAI,OACF,oBACE,MAAM,mBACN,MAAM,IACN,QACA,qBAAqB,KAAK,GAC1B,KAAK,eAAe,UAAU,IAChC;AACJ"}
@@ -0,0 +1,31 @@
1
+ import { CharacterStyleOverride, SceneNode, StyleRun, TextBindableField } from "../types.js";
2
+ //#region src/variables/units.d.ts
3
+ declare const SCALED_RUN_BINDING_FIELD_LIST: readonly ["fontSize", "letterSpacing", "lineHeight"];
4
+ /** A size or spacing a text's characters bind that a rescale scales with the layer. */
5
+ type ScaledRunBindingField = (typeof SCALED_RUN_BINDING_FIELD_LIST)[number];
6
+ /**
7
+ * Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own
8
+ * scale for the field, because the rescale scales the layer and its characters alike.
9
+ */
10
+ declare const SCALED_RUN_BINDING_FIELDS: ReadonlySet<string>;
11
+ /**
12
+ * The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before
13
+ * runs kept one, the layer's scale for a size or spacing, as every run once shared it.
14
+ */
15
+ declare function runBindingScale(node: Pick<SceneNode, 'variableBindingScales'>, style: CharacterStyleOverride, field: TextBindableField): number;
16
+ /** A run's style keeping scales only for the numbers it still binds, and no empty scales. */
17
+ declare function withBoundBindingScales(style: CharacterStyleOverride): CharacterStyleOverride;
18
+ /**
19
+ * The runs with every size or spacing they bind holding the scale it resolves with as their own,
20
+ * or `undefined` when each already does. Called before the layer's scale for a field changes or
21
+ * goes, it migrates a run that still resolves with the layer's, so the run keeps its look.
22
+ */
23
+ declare function pinnedRunBindingScales(node: SceneNode, fields?: readonly string[]): StyleRun[] | undefined;
24
+ /**
25
+ * The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,
26
+ * when it also scales their values, so each keeps them and gains its own scales.
27
+ */
28
+ declare function scaleVariableBindingUnits(node: SceneNode, factor: number, styleRuns?: readonly StyleRun[]): Partial<SceneNode>;
29
+ //#endregion
30
+ export { SCALED_RUN_BINDING_FIELDS, ScaledRunBindingField, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales };
31
+ //# sourceMappingURL=units.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"units.d.ts","names":[],"sources":["../../src/variables/units.ts"],"mappings":";;cAMM;;KAGM,gCAAgC;;;;;cAM/B,2BAA2B;;;;;iBAMxB,gBACd,MAAM,KAAK,qCACX,OAAO,wBACP,OAAO;;iBAQO,uBAAuB,OAAO,yBAAyB;;;;;;iBAqCvD,uBACd,MAAM,WACN,6BACC;;;;;iBAUa,0BACd,MAAM,WACN,gBACA,qBAAoB,aACnB,QAAQ"}
@@ -1,19 +1,94 @@
1
1
  import { NUMERIC_FIELDS } from "./fields.js";
2
+ import { omit, pickBy } from "es-toolkit/object";
3
+ import { isEmptyObject } from "es-toolkit/predicate";
2
4
  //#region src/variables/units.ts
3
- function scaleVariableBindingUnits(node, factor) {
5
+ const SCALED_RUN_BINDING_FIELD_LIST = [
6
+ "fontSize",
7
+ "letterSpacing",
8
+ "lineHeight"
9
+ ];
10
+ /**
11
+ * Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own
12
+ * scale for the field, because the rescale scales the layer and its characters alike.
13
+ */
14
+ const SCALED_RUN_BINDING_FIELDS = new Set(SCALED_RUN_BINDING_FIELD_LIST);
15
+ /**
16
+ * The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before
17
+ * runs kept one, the layer's scale for a size or spacing, as every run once shared it.
18
+ */
19
+ function runBindingScale(node, style, field) {
20
+ const own = style.variableBindingScales?.[field];
21
+ if (own !== void 0) return own;
22
+ return SCALED_RUN_BINDING_FIELDS.has(field) ? node.variableBindingScales[field] ?? 1 : 1;
23
+ }
24
+ /** A run's style keeping scales only for the numbers it still binds, and no empty scales. */
25
+ function withBoundBindingScales(style) {
26
+ if (!Object.hasOwn(style, "variableBindingScales")) return style;
27
+ const scales = pickBy(style.variableBindingScales ?? {}, (_, field) => style.boundVariables?.[field] !== void 0);
28
+ if (isEmptyObject(scales)) return omit(style, ["variableBindingScales"]);
29
+ return {
30
+ ...style,
31
+ variableBindingScales: scales
32
+ };
33
+ }
34
+ /** `runs` with each binding of `fields` holding `next` of the scale it resolves with. */
35
+ function runsWithBindingScales(node, runs, fields, next) {
36
+ const styleRuns = runs.map((run) => {
37
+ const bound = run.style.boundVariables;
38
+ if (!bound) return run;
39
+ let scales = run.style.variableBindingScales;
40
+ for (const field of fields) {
41
+ if (!bound[field]) continue;
42
+ const scale = next(runBindingScale(node, run.style, field));
43
+ if (scales?.[field] !== scale) scales = {
44
+ ...scales,
45
+ [field]: scale
46
+ };
47
+ }
48
+ if (scales === run.style.variableBindingScales) return run;
49
+ return {
50
+ ...run,
51
+ style: {
52
+ ...run.style,
53
+ variableBindingScales: scales
54
+ }
55
+ };
56
+ });
57
+ return styleRuns.some((run, index) => run !== runs[index]) ? styleRuns : void 0;
58
+ }
59
+ /**
60
+ * The runs with every size or spacing they bind holding the scale it resolves with as their own,
61
+ * or `undefined` when each already does. Called before the layer's scale for a field changes or
62
+ * goes, it migrates a run that still resolves with the layer's, so the run keeps its look.
63
+ */
64
+ function pinnedRunBindingScales(node, fields = SCALED_RUN_BINDING_FIELD_LIST) {
65
+ const scaled = SCALED_RUN_BINDING_FIELD_LIST.filter((field) => fields.includes(field));
66
+ if (scaled.length === 0) return void 0;
67
+ return runsWithBindingScales(node, node.styleRuns, scaled, (scale) => scale);
68
+ }
69
+ /**
70
+ * The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,
71
+ * when it also scales their values, so each keeps them and gains its own scales.
72
+ */
73
+ function scaleVariableBindingUnits(node, factor, styleRuns = node.styleRuns) {
4
74
  const variableBindingScales = { ...node.variableBindingScales };
5
75
  const variableAssignmentScales = { ...node.variableAssignmentScales };
6
76
  for (const field of NUMERIC_FIELDS) {
7
- if (field === "opacity" || field === "rotation") continue;
77
+ if (field === "opacity" || field === "rotation" || field === "fontWeight") continue;
8
78
  if (field in node.boundVariables) variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor;
9
79
  if (node.type === "INSTANCE") variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor;
10
80
  }
11
- return {
81
+ const scaledRuns = runsWithBindingScales(node, styleRuns, SCALED_RUN_BINDING_FIELD_LIST, (scale) => scale * factor);
82
+ return scaledRuns ? {
83
+ variableBindingScales,
84
+ variableAssignmentScales,
85
+ styleRuns: scaledRuns
86
+ } : {
12
87
  variableBindingScales,
13
88
  variableAssignmentScales
14
89
  };
15
90
  }
16
91
  //#endregion
17
- export { scaleVariableBindingUnits };
92
+ export { SCALED_RUN_BINDING_FIELDS, pinnedRunBindingScales, runBindingScale, scaleVariableBindingUnits, withBoundBindingScales };
18
93
 
19
94
  //# sourceMappingURL=units.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"units.js","names":[],"sources":["../../src/variables/units.ts"],"sourcesContent":["import type { SceneNode } from '../types'\nimport { NUMERIC_FIELDS } from './fields'\n\nexport function scaleVariableBindingUnits(node: SceneNode, factor: number): Partial<SceneNode> {\n const variableBindingScales = { ...node.variableBindingScales }\n const variableAssignmentScales = { ...node.variableAssignmentScales }\n for (const field of NUMERIC_FIELDS) {\n if (field === 'opacity' || field === 'rotation') continue\n if (field in node.boundVariables)\n variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor\n if (node.type === 'INSTANCE')\n variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor\n }\n return { variableBindingScales, variableAssignmentScales }\n}\n"],"mappings":";;AAGA,SAAgB,0BAA0B,MAAiB,QAAoC;CAC7F,MAAM,wBAAwB,EAAE,GAAG,KAAK,sBAAsB;CAC9D,MAAM,2BAA2B,EAAE,GAAG,KAAK,yBAAyB;CACpE,KAAK,MAAM,SAAS,gBAAgB;EAClC,IAAI,UAAU,aAAa,UAAU,YAAY;EACjD,IAAI,SAAS,KAAK,gBAChB,sBAAsB,UAAU,sBAAsB,UAAU,KAAK;EACvE,IAAI,KAAK,SAAS,YAChB,yBAAyB,UAAU,yBAAyB,UAAU,KAAK;CAC/E;CACA,OAAO;EAAE;EAAuB;CAAyB;AAC3D"}
1
+ {"version":3,"file":"units.js","names":[],"sources":["../../src/variables/units.ts"],"sourcesContent":["import { omit, pickBy } from 'es-toolkit/object'\nimport { isEmptyObject } from 'es-toolkit/predicate'\n\nimport type { CharacterStyleOverride, SceneNode, StyleRun, TextBindableField } from '../types'\nimport { NUMERIC_FIELDS } from './fields'\n\nconst SCALED_RUN_BINDING_FIELD_LIST = ['fontSize', 'letterSpacing', 'lineHeight'] as const\n\n/** A size or spacing a text's characters bind that a rescale scales with the layer. */\nexport type ScaledRunBindingField = (typeof SCALED_RUN_BINDING_FIELD_LIST)[number]\n\n/**\n * Numbers a text's characters bind that a rescale scales with the layer. Each run keeps its own\n * scale for the field, because the rescale scales the layer and its characters alike.\n */\nexport const SCALED_RUN_BINDING_FIELDS: ReadonlySet<string> = new Set(SCALED_RUN_BINDING_FIELD_LIST)\n\n/**\n * The scale a run's binding of `field` resolves with: the run's own, else, for a run saved before\n * runs kept one, the layer's scale for a size or spacing, as every run once shared it.\n */\nexport function runBindingScale(\n node: Pick<SceneNode, 'variableBindingScales'>,\n style: CharacterStyleOverride,\n field: TextBindableField\n): number {\n const own = style.variableBindingScales?.[field]\n if (own !== undefined) return own\n return SCALED_RUN_BINDING_FIELDS.has(field) ? (node.variableBindingScales[field] ?? 1) : 1\n}\n\n/** A run's style keeping scales only for the numbers it still binds, and no empty scales. */\nexport function withBoundBindingScales(style: CharacterStyleOverride): CharacterStyleOverride {\n if (!Object.hasOwn(style, 'variableBindingScales')) return style\n const scales = pickBy(\n style.variableBindingScales ?? {},\n (_, field) => style.boundVariables?.[field] !== undefined\n )\n if (isEmptyObject(scales)) return omit(style, ['variableBindingScales'])\n return { ...style, variableBindingScales: scales }\n}\n\n/** `runs` with each binding of `fields` holding `next` of the scale it resolves with. */\nfunction runsWithBindingScales(\n node: SceneNode,\n runs: readonly StyleRun[],\n fields: readonly ScaledRunBindingField[],\n next: (scale: number) => number\n): StyleRun[] | undefined {\n const styleRuns = runs.map((run) => {\n const bound = run.style.boundVariables\n if (!bound) return run\n let scales = run.style.variableBindingScales\n for (const field of fields) {\n if (!bound[field]) continue\n const scale = next(runBindingScale(node, run.style, field))\n if (scales?.[field] !== scale) scales = { ...scales, [field]: scale }\n }\n if (scales === run.style.variableBindingScales) return run\n return { ...run, style: { ...run.style, variableBindingScales: scales } }\n })\n return styleRuns.some((run, index) => run !== runs[index]) ? styleRuns : undefined\n}\n\n/**\n * The runs with every size or spacing they bind holding the scale it resolves with as their own,\n * or `undefined` when each already does. Called before the layer's scale for a field changes or\n * goes, it migrates a run that still resolves with the layer's, so the run keeps its look.\n */\nexport function pinnedRunBindingScales(\n node: SceneNode,\n fields: readonly string[] = SCALED_RUN_BINDING_FIELD_LIST\n): StyleRun[] | undefined {\n const scaled = SCALED_RUN_BINDING_FIELD_LIST.filter((field) => fields.includes(field))\n if (scaled.length === 0) return undefined\n return runsWithBindingScales(node, node.styleRuns, scaled, (scale) => scale)\n}\n\n/**\n * The binding scales of a layer rescaled by `factor`. `styleRuns` are the runs the rescale leaves,\n * when it also scales their values, so each keeps them and gains its own scales.\n */\nexport function scaleVariableBindingUnits(\n node: SceneNode,\n factor: number,\n styleRuns: readonly StyleRun[] = node.styleRuns\n): Partial<SceneNode> {\n const variableBindingScales = { ...node.variableBindingScales }\n const variableAssignmentScales = { ...node.variableAssignmentScales }\n for (const field of NUMERIC_FIELDS) {\n // A rescale keeps opacity, rotation, and font weight as they are.\n if (field === 'opacity' || field === 'rotation' || field === 'fontWeight') continue\n if (field in node.boundVariables)\n variableBindingScales[field] = (variableBindingScales[field] ?? 1) * factor\n if (node.type === 'INSTANCE')\n variableAssignmentScales[field] = (variableAssignmentScales[field] ?? 1) * factor\n }\n // Each run scales the sizes and spacings it binds in its own scale.\n const scaledRuns = runsWithBindingScales(\n node,\n styleRuns,\n SCALED_RUN_BINDING_FIELD_LIST,\n (scale) => scale * factor\n )\n return scaledRuns\n ? { variableBindingScales, variableAssignmentScales, styleRuns: scaledRuns }\n : { variableBindingScales, variableAssignmentScales }\n}\n"],"mappings":";;;;AAMA,MAAM,gCAAgC;CAAC;CAAY;CAAiB;AAAY;;;;;AAShF,MAAa,4BAAiD,IAAI,IAAI,6BAA6B;;;;;AAMnG,SAAgB,gBACd,MACA,OACA,OACQ;CACR,MAAM,MAAM,MAAM,wBAAwB;CAC1C,IAAI,QAAQ,KAAA,GAAW,OAAO;CAC9B,OAAO,0BAA0B,IAAI,KAAK,IAAK,KAAK,sBAAsB,UAAU,IAAK;AAC3F;;AAGA,SAAgB,uBAAuB,OAAuD;CAC5F,IAAI,CAAC,OAAO,OAAO,OAAO,uBAAuB,GAAG,OAAO;CAC3D,MAAM,SAAS,OACb,MAAM,yBAAyB,CAAC,IAC/B,GAAG,UAAU,MAAM,iBAAiB,WAAW,KAAA,CAClD;CACA,IAAI,cAAc,MAAM,GAAG,OAAO,KAAK,OAAO,CAAC,uBAAuB,CAAC;CACvE,OAAO;EAAE,GAAG;EAAO,uBAAuB;CAAO;AACnD;;AAGA,SAAS,sBACP,MACA,MACA,QACA,MACwB;CACxB,MAAM,YAAY,KAAK,KAAK,QAAQ;EAClC,MAAM,QAAQ,IAAI,MAAM;EACxB,IAAI,CAAC,OAAO,OAAO;EACnB,IAAI,SAAS,IAAI,MAAM;EACvB,KAAK,MAAM,SAAS,QAAQ;GAC1B,IAAI,CAAC,MAAM,QAAQ;GACnB,MAAM,QAAQ,KAAK,gBAAgB,MAAM,IAAI,OAAO,KAAK,CAAC;GAC1D,IAAI,SAAS,WAAW,OAAO,SAAS;IAAE,GAAG;KAAS,QAAQ;GAAM;EACtE;EACA,IAAI,WAAW,IAAI,MAAM,uBAAuB,OAAO;EACvD,OAAO;GAAE,GAAG;GAAK,OAAO;IAAE,GAAG,IAAI;IAAO,uBAAuB;GAAO;EAAE;CAC1E,CAAC;CACD,OAAO,UAAU,MAAM,KAAK,UAAU,QAAQ,KAAK,MAAM,IAAI,YAAY,KAAA;AAC3E;;;;;;AAOA,SAAgB,uBACd,MACA,SAA4B,+BACJ;CACxB,MAAM,SAAS,8BAA8B,QAAQ,UAAU,OAAO,SAAS,KAAK,CAAC;CACrF,IAAI,OAAO,WAAW,GAAG,OAAO,KAAA;CAChC,OAAO,sBAAsB,MAAM,KAAK,WAAW,SAAS,UAAU,KAAK;AAC7E;;;;;AAMA,SAAgB,0BACd,MACA,QACA,YAAiC,KAAK,WAClB;CACpB,MAAM,wBAAwB,EAAE,GAAG,KAAK,sBAAsB;CAC9D,MAAM,2BAA2B,EAAE,GAAG,KAAK,yBAAyB;CACpE,KAAK,MAAM,SAAS,gBAAgB;EAElC,IAAI,UAAU,aAAa,UAAU,cAAc,UAAU,cAAc;EAC3E,IAAI,SAAS,KAAK,gBAChB,sBAAsB,UAAU,sBAAsB,UAAU,KAAK;EACvE,IAAI,KAAK,SAAS,YAChB,yBAAyB,UAAU,yBAAyB,UAAU,KAAK;CAC/E;CAEA,MAAM,aAAa,sBACjB,MACA,WACA,gCACC,UAAU,QAAQ,MACrB;CACA,OAAO,aACH;EAAE;EAAuB;EAA0B,WAAW;CAAW,IACzE;EAAE;EAAuB;CAAyB;AACxD"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pairdraw/scene-graph",
3
- "version": "0.16.2",
3
+ "version": "0.17.0",
4
4
  "license": "MIT",
5
5
  "files": [
6
6
  "dist",
package/src/checkpoint.ts CHANGED
@@ -5,8 +5,8 @@ import type { InstanceOverrideState } from './instances/overrides'
5
5
  import type { SceneNode } from './types'
6
6
 
7
7
  /**
8
- * The document state outside its layers, copied: variables, collections, modes, the instance
9
- * index, libraries, images, and document metadata, which a rollback restores in place.
8
+ * The document state outside its layers, copied: variables, collections, modes, the instance and
9
+ * connector indexes, libraries, images, and document metadata, which a rollback restores in place.
10
10
  */
11
11
  function captureTables(graph: SceneGraph) {
12
12
  const variableRefs = new Map(graph.variables)
@@ -16,8 +16,10 @@ function captureTables(graph: SceneGraph) {
16
16
  variableCollections: graph.variableCollections,
17
17
  activeMode: graph.activeMode,
18
18
  instanceIndex: graph.instanceIndex,
19
+ connectorIds: graph.connectorIds,
19
20
  enabledLibraries: graph.enabledLibraries,
20
21
  rootId: graph.rootId,
22
+ documentKind: graph.documentKind,
21
23
  figKiwiVersion: graph.figKiwiVersion,
22
24
  figSchemaDeflated: graph.figSchemaDeflated,
23
25
  documentColorSpace: graph.documentColorSpace
@@ -48,6 +50,7 @@ function captureTables(graph: SceneGraph) {
48
50
  images.size !== graph.images.size ||
49
51
  [...images].some(([id, bytes]) => graph.images.get(id) !== bytes) ||
50
52
  graph.rootId !== snapshot.rootId ||
53
+ graph.documentKind !== snapshot.documentKind ||
51
54
  graph.documentColorSpace !== snapshot.documentColorSpace ||
52
55
  graph.figKiwiVersion !== snapshot.figKiwiVersion ||
53
56
  !isEqual(graph.figSchemaDeflated, snapshot.figSchemaDeflated)
@@ -61,9 +64,12 @@ function captureTables(graph: SceneGraph) {
61
64
  restoreObjects(graph.variableCollections, snapshot.variableCollections, collectionRefs)
62
65
  restoreMap(graph.activeMode, structuredClone(snapshot.activeMode))
63
66
  restoreMap(graph.instanceIndex, structuredClone(snapshot.instanceIndex))
67
+ graph.connectorIds.clear()
68
+ for (const id of snapshot.connectorIds) graph.connectorIds.add(id)
64
69
  restoreMap(graph.enabledLibraries, structuredClone(snapshot.enabledLibraries))
65
70
  restoreMap(graph.images, images)
66
71
  graph.rootId = snapshot.rootId
72
+ graph.documentKind = snapshot.documentKind
67
73
  graph.figKiwiVersion = snapshot.figKiwiVersion
68
74
  graph.figSchemaDeflated = structuredClone(snapshot.figSchemaDeflated)
69
75
  graph.documentColorSpace = snapshot.documentColorSpace
@@ -7,6 +7,7 @@ import { parse, formatHex, formatHex8, formatRgb, converter, differenceEuclidean
7
7
 
8
8
  import { BLACK } from '../constants'
9
9
  import type { Color } from '../primitives'
10
+ import { normalizeColor } from './normalize'
10
11
 
11
12
  const toRGB = converter('rgb')
12
13
 
@@ -15,12 +16,8 @@ export function tryParseColor(input: string): Color | null {
15
16
  const parsed = parse(input)
16
17
  if (!parsed) return null
17
18
  const rgb = toRGB(parsed)
18
- return {
19
- r: rgb.r,
20
- g: rgb.g,
21
- b: rgb.b,
22
- a: parsed.alpha ?? 1
23
- }
19
+ // culori leaves a `none` channel out, which normalizing reads as zero.
20
+ return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })
24
21
  }
25
22
 
26
23
  /** A CSS color, or black when `input` is not one. */
@@ -1,4 +1,4 @@
1
- import { converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'
1
+ import { clampGamut, converter, formatCss, formatRgb, inGamut, parse, toGamut } from 'culori'
2
2
 
3
3
  import type { Color } from '../primitives'
4
4
  import type { DocumentColorSpace, Fill, SceneNode, Stroke } from '../types'
@@ -28,6 +28,7 @@ const toP3 = converter('p3')
28
28
  const toDisplayableRGB = toGamut('rgb', 'oklch')
29
29
  const toDisplayableP3 = toGamut('p3', 'oklch')
30
30
  const isDisplayableRGB = inGamut('rgb')
31
+ const clampToRGB = clampGamut('rgb')
31
32
  const isDisplayableP3 = inGamut('p3')
32
33
 
33
34
  function normalizeOkLCH(color: OkHCLColor) {
@@ -158,7 +159,12 @@ export function parseDisplayableColor(input: string): Color | null {
158
159
  const parsed = parse(input)
159
160
  if (!parsed) return null
160
161
  // Mapping through OKLCH shifts colors already in sRGB by float noise, so only map the rest.
161
- const rgb = isDisplayableRGB(parsed) ? toRGB(parsed) : toDisplayableRGB(parsed)
162
+ // CSS clamps out-of-range sRGB channels and gamut-maps wider colors; clamping also removes the
163
+ // float noise gamut mapping can leave just outside 0..1.
164
+ const rgb = isDisplayableRGB(parsed)
165
+ ? toRGB(parsed)
166
+ : clampToRGB(parsed.mode === 'rgb' ? parsed : toDisplayableRGB(parsed))
167
+ if (!rgb) return null
162
168
  // culori leaves a `none` channel out, which normalizing reads as zero.
163
169
  return normalizeColor({ r: rgb.r, g: rgb.g, b: rgb.b, a: parsed.alpha })
164
170
  }