@open-pencil/scene-graph 0.16.0-beta.1 → 0.16.0-beta.3

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 (59) hide show
  1. package/dist/chunks/asset-keys.js +27 -0
  2. package/dist/chunks/asset-keys.js.map +1 -0
  3. package/dist/chunks/behaviours/layers.js +16 -1
  4. package/dist/chunks/behaviours/layers.js.map +1 -1
  5. package/dist/chunks/color/contrast.js +23 -1
  6. package/dist/chunks/color/contrast.js.map +1 -1
  7. package/dist/chunks/color/index.js +43 -4
  8. package/dist/chunks/color/index.js.map +1 -1
  9. package/dist/chunks/components/exposure.js +273 -3
  10. package/dist/chunks/components/exposure.js.map +1 -1
  11. package/dist/chunks/index.js +247 -150
  12. package/dist/chunks/index.js.map +1 -1
  13. package/dist/color.d.ts +7 -1
  14. package/dist/color.d.ts.map +1 -1
  15. package/dist/color.js +2 -2
  16. package/dist/geometry.d.ts +2 -2
  17. package/dist/hit-test.js +24 -18
  18. package/dist/hit-test.js.map +1 -1
  19. package/dist/images.d.ts +2 -2
  20. package/dist/images.js +21 -38
  21. package/dist/images.js.map +1 -1
  22. package/dist/images2.d.ts +12 -1
  23. package/dist/images2.d.ts.map +1 -1
  24. package/dist/index.d.ts +3 -3
  25. package/dist/index.js +6 -6
  26. package/dist/layout.d.ts +2 -2
  27. package/dist/layout.js +3 -3
  28. package/dist/text.d.ts +2 -2
  29. package/dist/text.js +2 -2
  30. package/dist/types.d.ts +129 -12
  31. package/dist/types.d.ts.map +1 -1
  32. package/dist/types.js +2 -2
  33. package/dist/types2.d.ts +2 -2
  34. package/package.json +2 -1
  35. package/src/asset-keys.ts +25 -0
  36. package/src/color/contrast.ts +28 -0
  37. package/src/copy.ts +4 -1
  38. package/src/geometry.ts +64 -14
  39. package/src/hit-test.ts +45 -23
  40. package/src/images.ts +24 -32
  41. package/src/index.ts +8 -4
  42. package/src/instances/content-size.ts +63 -0
  43. package/src/instances/fields.ts +1 -1
  44. package/src/instances/sync.ts +7 -6
  45. package/src/instances/vector-geometry.ts +81 -0
  46. package/src/instances.ts +3 -0
  47. package/src/layout/guides.ts +40 -11
  48. package/src/shaders/model.ts +4 -2
  49. package/src/shaders/still.ts +41 -0
  50. package/src/shared-styles.ts +5 -2
  51. package/src/text/index.ts +1 -0
  52. package/src/text/references.ts +50 -0
  53. package/src/transfer/nodes.ts +12 -0
  54. package/src/transfer/plan.ts +25 -2
  55. package/src/transfer/validation.ts +6 -1
  56. package/src/types.ts +50 -2
  57. package/src/variables/bindings.ts +110 -8
  58. package/dist/chunks/fields/text.js +0 -36
  59. package/dist/chunks/fields/text.js.map +0 -1
@@ -1,10 +1,8 @@
1
1
  import { CONTAINER_TYPES, cloneNodeProps, copyFills, copyStrokes, createDefaultNode, getInstanceOverride, normalizeVectorNetwork, remapInstanceOverrideState, rotatedBBox, setInstanceOverride } from "./color/index.js";
2
2
  import { BLACK, TRANSPARENT } from "./color/contrast.js";
3
- import { BOOLEAN_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, cloneChildrenWithMapping, createInstance, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, isNumericVariableBindingField, ownsSlotContent, paragraphStyleAt, populateInstanceChildren, scaleNodeChanges, scaleVariableBindingUnits, slotPropertyId, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, textParagraphRanges } from "./components/exposure.js";
3
+ import { BOOLEAN_BINDING_FIELDS, NUMERIC_FIELDS, STRING_BINDING_FIELDS, TEXT_LAYOUT_FIELDS, TEXT_SHAPING_FIELDS, cloneChildrenWithMapping, createInstance, detachInstance, findInstanceAncestor, getInstances, getMainComponent, hasInstanceOverride, isNumericVariableBindingField, ownsSlotContent, paragraphStyleAt, populateInstanceChildren, scaleNodeChanges, scaleVariableBindingUnits, slotPropertyId, swapInstanceComponent, syncInstance, syncInstances, syncInstancesTogether, textParagraphRanges } from "./components/exposure.js";
4
4
  import { OPEN_PENCIL_PLUGIN_DATA, readAllPluginData, withAllPluginData } from "./behaviours/layers.js";
5
5
  import { SIZE_FIELDS, TRANSFORM_FIELDS } from "./fields/geometry.js";
6
- import { TEXT_LAYOUT_FIELDS, TEXT_SHAPING_FIELDS } from "./fields/text.js";
7
- import { computeImageHash } from "../images.js";
8
6
  import { randomHex, randomIndex } from "./comments/list.js";
9
7
  import { Matrix, getAbsolutePosition, getNodeLocalMatrix, getParentWorldMatrix, isTranslationOnly, localTransformFromWorld } from "./coordinate.js";
10
8
  import { removeStaleBindings } from "./bindings.js";
@@ -13,7 +11,9 @@ import { bindNodeEvents } from "./events.js";
13
11
  import { hitTest, hitTestDeep, hitTestDropTarget, hitTestOpenContainer, hitTestSelectable, isOpenContainer, isPointInNode } from "../hit-test.js";
14
12
  import { partition, uniq } from "es-toolkit/array";
15
13
  import { isEqual } from "es-toolkit/predicate";
16
- import { omit, omitBy } from "es-toolkit/object";
14
+ import { mapValues, omit, omitBy } from "es-toolkit/object";
15
+ import { sha1 } from "@noble/hashes/legacy.js";
16
+ import { bytesToHex, utf8ToBytes } from "@noble/hashes/utils.js";
17
17
  //#region src/mutation-impact.ts
18
18
  function createSceneMutationImpact() {
19
19
  return {
@@ -116,6 +116,33 @@ function resolvedNumericBindings(graph, node, fallback = "active") {
116
116
  return updates;
117
117
  }
118
118
  /**
119
+ * The text a variable bound to text content shows: a string as it is, and a number or boolean
120
+ * as Figma writes it, since Figma lets either be text content.
121
+ */
122
+ function variableText(value) {
123
+ if (typeof value === "string") return value;
124
+ if (typeof value === "boolean") return String(value);
125
+ if (typeof value === "number" && Number.isFinite(value)) return numberText(value);
126
+ }
127
+ const INT32_MIN = -2147483648;
128
+ const INT32_MAX = 2147483647;
129
+ /** How near a whole number a value must be for Figma to write it as one. */
130
+ const WHOLE_NUMBER_TOLERANCE = 1e-6;
131
+ /**
132
+ * A number as Figma desktop 126 writes it as text: one within a millionth of a whole number as
133
+ * that integer, clamped to 32 bits, and anything else with two decimals, its sign kept and an
134
+ * exact tie rounded to even, as C's `%.2f` does (0.125 is "0.12", 0.999 is "1.00", -0.004 is
135
+ * "-0.00").
136
+ */
137
+ function numberText(value) {
138
+ const whole = Math.round(value);
139
+ if (Math.abs(value - whole) < WHOLE_NUMBER_TOLERANCE) return String(Math.min(INT32_MAX, Math.max(INT32_MIN, whole)) || 0);
140
+ const scaled = Math.abs(value) * 100;
141
+ const floor = Math.floor(scaled);
142
+ const cents = scaled - floor === .5 ? floor + floor % 2 : Math.round(scaled);
143
+ return `${value < 0 ? "-" : ""}${Math.floor(cents / 100)}.${String(cents % 100).padStart(2, "0")}`;
144
+ }
145
+ /**
119
146
  * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
120
147
  * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
121
148
  * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
@@ -129,12 +156,49 @@ function resolvedValueBindings(graph, node, fallback = "active") {
129
156
  if (!variableId || hasInstanceOverride(graph, node.id, field)) return void 0;
130
157
  return graph.resolveVariableForNode(node.id, variableId, fallback);
131
158
  };
132
- const text = node.type === "TEXT" ? resolve("text") : void 0;
133
- if (typeof text === "string" && text !== node.text) updates.text = text;
159
+ const text = node.type === "TEXT" ? variableText(resolve("text")) : void 0;
160
+ if (text !== void 0 && text !== node.text) updates.text = text;
134
161
  const visible = resolve("visible");
135
162
  if (typeof visible === "boolean" && visible !== node.visible) updates.visible = visible;
136
163
  return updates;
137
164
  }
165
+ /** Fields of a range of characters a bound number gives its value; the rest need fonts loaded. */
166
+ const NUMERIC_RUN_FIELDS = [
167
+ "fontSize",
168
+ "fontWeight",
169
+ "letterSpacing",
170
+ "lineHeight"
171
+ ];
172
+ /**
173
+ * The runs a text's character bindings resolve to in its mode, when a bound number differs from
174
+ * what its characters hold. Bound font families and styles are left as stored, as the text's own.
175
+ */
176
+ function resolvedRunBindings(graph, node, fallback = "active") {
177
+ const styleRuns = node.styleRuns.map((run) => {
178
+ const bound = run.style.boundVariables;
179
+ if (!bound) return run;
180
+ let style = run.style;
181
+ for (const field of NUMERIC_RUN_FIELDS) {
182
+ const variableId = bound[field];
183
+ if (!variableId) continue;
184
+ const value = graph.resolveNumberVariableForNode(node.id, variableId, fallback);
185
+ if (value === void 0 || !Number.isFinite(value) || style[field] === value) continue;
186
+ style = {
187
+ ...style,
188
+ [field]: value
189
+ };
190
+ }
191
+ return style === run.style ? run : {
192
+ ...run,
193
+ style
194
+ };
195
+ });
196
+ return styleRuns.some((run, index) => run !== node.styleRuns[index]) ? { styleRuns } : {};
197
+ }
198
+ /** The variables a node binds, its own and its characters'. */
199
+ function boundVariableIds(node) {
200
+ return [...Object.values(node.boundVariables), ...node.styleRuns.flatMap((run) => Object.values(run.style.boundVariables ?? {}))].filter((id) => typeof id === "string");
201
+ }
138
202
  /**
139
203
  * A bound paint takes its whole color from the variable, alpha included, the way Figma stores
140
204
  * it: the variable's RGB at full alpha, and its alpha as the paint's opacity.
@@ -195,11 +259,36 @@ function subtreeNodes(graph, roots) {
195
259
  }
196
260
  return nodes;
197
261
  }
262
+ /**
263
+ * The collections whose variables the layers in these subtrees resolve: those they bind, and
264
+ * those the bound variables alias, so a mode set on the subtrees can change what they show.
265
+ */
266
+ function collectionsBoundIn(graph, roots) {
267
+ const pending = subtreeNodes(graph, roots).flatMap(boundVariableIds);
268
+ const seen = /* @__PURE__ */ new Set();
269
+ const collections = /* @__PURE__ */ new Set();
270
+ for (let id = pending.pop(); id !== void 0; id = pending.pop()) {
271
+ if (seen.has(id)) continue;
272
+ seen.add(id);
273
+ const variable = graph.variables.get(id);
274
+ if (!variable) continue;
275
+ collections.add(variable.collectionId);
276
+ for (const value of Object.values(variable.valuesByMode)) if (typeof value === "object" && "aliasId" in value) pending.push(value.aliasId);
277
+ }
278
+ return collections;
279
+ }
280
+ /**
281
+ * The layers a change to these variables reaches: those binding one of them, or a variable that
282
+ * aliases one, on the layer itself or on its characters.
283
+ */
284
+ function layersUsingVariables(graph, ids) {
285
+ const variables = variablesResolvingThrough(graph, ids);
286
+ return [...graph.getAllNodes()].filter((node) => boundVariableIds(node).some((id) => variables.has(id)));
287
+ }
198
288
  function scopedNodes(graph, scope) {
199
289
  if (!scope) return graph.getAllNodes();
200
290
  if ("subtrees" in scope) return subtreeNodes(graph, scope.subtrees);
201
- const variables = variablesResolvingThrough(graph, scope.variables);
202
- return [...graph.getAllNodes()].filter((node) => Object.values(node.boundVariables).some((id) => variables.has(id)));
291
+ return layersUsingVariables(graph, scope.variables);
203
292
  }
204
293
  /**
205
294
  * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
@@ -211,7 +300,8 @@ function reconcileVariableBindings(graph, scope) {
211
300
  for (const node of scopedNodes(graph, scope)) {
212
301
  const updates = {
213
302
  ...resolvedNumericBindings(graph, node),
214
- ...resolvedValueBindings(graph, node)
303
+ ...resolvedValueBindings(graph, node),
304
+ ...resolvedRunBindings(graph, node)
215
305
  };
216
306
  if (Object.keys(updates).length === 0) continue;
217
307
  graph.updateNode(node.id, updates);
@@ -526,6 +616,45 @@ function rescaleNodeTree(graph, rootId, scale) {
526
616
  });
527
617
  }
528
618
  //#endregion
619
+ //#region src/text/references.ts
620
+ /** The variables and styles a text's runs refer to, which copies and transfers carry with it. */
621
+ function styleRunReferences(runs) {
622
+ const variables = /* @__PURE__ */ new Set();
623
+ const styles = /* @__PURE__ */ new Set();
624
+ for (const { style } of runs) {
625
+ for (const id of Object.values(style.boundVariables ?? {})) if (id) variables.add(id);
626
+ if (style.textStyleId) styles.add(style.textStyleId);
627
+ if (style.fillStyleId) styles.add(style.fillStyleId);
628
+ }
629
+ return {
630
+ variables: [...variables],
631
+ styles: [...styles]
632
+ };
633
+ }
634
+ /**
635
+ * Runs whose variables, styles, and linked layers are renamed, as a copy into another document
636
+ * renames them. Layers are renamed only when given, since a link may name a layer left behind.
637
+ */
638
+ function remapStyleRunReferences(runs, rename) {
639
+ return runs.map((run) => {
640
+ const { boundVariables, textStyleId, fillStyleId, hyperlink } = run.style;
641
+ const linksLayer = hyperlink?.type === "NODE" && rename.node !== void 0;
642
+ if (!boundVariables && !textStyleId && !fillStyleId && !linksLayer) return run;
643
+ const style = { ...run.style };
644
+ if (hyperlink?.type === "NODE" && rename.node) style.hyperlink = {
645
+ type: "NODE",
646
+ value: rename.node(hyperlink.value)
647
+ };
648
+ if (boundVariables) style.boundVariables = mapValues(boundVariables, (id) => id ? rename.variable(id) : id);
649
+ if (textStyleId) style.textStyleId = rename.style(textStyleId);
650
+ if (fillStyleId) style.fillStyleId = rename.style(fillStyleId);
651
+ return {
652
+ ...run,
653
+ style
654
+ };
655
+ });
656
+ }
657
+ //#endregion
529
658
  //#region src/transfer/references.ts
530
659
  function requireTransferReference(ids, id, kind) {
531
660
  const value = ids.get(id);
@@ -535,9 +664,12 @@ function requireTransferReference(ids, id, kind) {
535
664
  //#endregion
536
665
  //#region src/transfer/nodes.ts
537
666
  function semanticTransferReferences(node) {
667
+ const runs = styleRunReferences(node.styleRuns);
538
668
  return [
539
669
  ...node.componentId ? [node.componentId] : [],
540
670
  ...Object.values(node.boundVariables),
671
+ ...runs.variables,
672
+ ...runs.styles,
541
673
  ...[
542
674
  node.fillStyleId,
543
675
  node.strokeStyleId,
@@ -581,6 +713,11 @@ function prepareNodeTransfer(source, refs) {
581
713
  "effectStyleId",
582
714
  "gridStyleId"
583
715
  ]) result[field] = source[field] ? style(source[field]) : null;
716
+ if (result.styleRuns) result.styleRuns = remapStyleRunReferences(result.styleRuns, {
717
+ variable,
718
+ style,
719
+ node: (id) => refs.nodes.get(id) ?? id
720
+ });
584
721
  for (const paths of [result.fillGeometry, result.strokeGeometry]) for (const path of paths ?? []) if (path.fillStyleId) path.fillStyleId = style(path.fillStyleId);
585
722
  result.componentPropertyDefinitions = source.componentPropertyDefinitions.map((definition) => ({
586
723
  ...structuredClone(definition),
@@ -679,7 +816,7 @@ function validateTransferReferences(target, plan) {
679
816
  const collections = new Map(plan.collections.map((collection) => [collection.id, collection]));
680
817
  const references = {
681
818
  nodes: identities,
682
- styles: identities,
819
+ styles: new Map([...nodes.values()].flatMap((node) => node.sharedStyleType !== null && node.source.id ? [[node.source.id, node.source.id]] : [])),
683
820
  properties,
684
821
  propertyTypes,
685
822
  ...variableIdentityReferences(plan.variables, plan.collections)
@@ -805,6 +942,18 @@ function applyGraphTransfer(target, input) {
805
942
  }
806
943
  //#endregion
807
944
  //#region src/transfer/plan.ts
945
+ /** A transferred style's props under the ID the transfer gives it. */
946
+ function withStyleId(node, props, styles) {
947
+ const id = node.sharedStyleType !== null && node.source.id ? styles.get(node.source.id) : void 0;
948
+ if (!id || id === node.source.id) return props;
949
+ return {
950
+ ...props,
951
+ source: {
952
+ ...props.source ?? node.source,
953
+ id
954
+ }
955
+ };
956
+ }
808
957
  /** Preflight a self-contained fragment; allocation does not insert anything into the target. */
809
958
  function prepareGraphTransfer(input) {
810
959
  const { source, target, parentId } = input;
@@ -846,6 +995,14 @@ function prepareGraphTransfer(input) {
846
995
  propertyTypes.set(definition.id, definition.type);
847
996
  if (!properties.has(definition.id)) properties.set(definition.id, allocate());
848
997
  }
998
+ const targetStyleIds = /* @__PURE__ */ new Set();
999
+ for (const node of target.getAllNodes()) if (node.sharedStyleType !== null && node.source.id) targetStyleIds.add(node.source.id);
1000
+ const styles = /* @__PURE__ */ new Map();
1001
+ for (const node of ordered) {
1002
+ const id = node.source.id;
1003
+ if (node.sharedStyleType === null || !id) continue;
1004
+ styles.set(id, targetStyleIds.has(id) ? allocate() : id);
1005
+ }
849
1006
  const references = {
850
1007
  nodes,
851
1008
  variables,
@@ -853,7 +1010,7 @@ function prepareGraphTransfer(input) {
853
1010
  modes,
854
1011
  properties,
855
1012
  propertyTypes,
856
- styles: nodes
1013
+ styles
857
1014
  };
858
1015
  const resources = prepareVariableTransfer([...source.variables.values()], [...source.variableCollections.values()], references);
859
1016
  const mapped = (id) => {
@@ -876,7 +1033,7 @@ function prepareGraphTransfer(input) {
876
1033
  id: mapped(node.id),
877
1034
  type: node.type,
878
1035
  parentId: destinationParent(node),
879
- props: prepareNodeTransfer(node, references)
1036
+ props: withStyleId(node, prepareNodeTransfer(node, references), styles)
880
1037
  })),
881
1038
  ...resources,
882
1039
  activeModes: new Map([...source.activeMode].map(([collection, mode]) => [requireTransferReference(collections, collection, "collection"), requireTransferReference(modes, mode, "mode")])),
@@ -1129,7 +1286,7 @@ function createShaderPaint(preset) {
1129
1286
  }
1130
1287
  /** A short key that tells one preset from another, which a rendered frame records. */
1131
1288
  function shaderPresetKey(preset) {
1132
- return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)));
1289
+ return bytesToHex(sha1(utf8ToBytes(JSON.stringify(preset))));
1133
1290
  }
1134
1291
  /**
1135
1292
  * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
@@ -1140,6 +1297,39 @@ function isShaderFrameCurrent(shader, size) {
1140
1297
  return frame !== void 0 && frame.preset === shaderPresetKey(shader.preset) && Math.round(frame.width) === Math.round(size.width) && Math.round(frame.height) === Math.round(size.height);
1141
1298
  }
1142
1299
  //#endregion
1300
+ //#region src/shaders/still.ts
1301
+ /**
1302
+ * How a shader paint's still frame is drawn and stored, for every renderer that draws one: the
1303
+ * editor's canvas and the tools that prebuild documents. The frame is an image fill in `.fig`
1304
+ * files, so Figma must be able to read it, which rules out WebP.
1305
+ */
1306
+ /** Frames are drawn at twice the layer's size, for sharp high-density displays. */
1307
+ const FRAME_SCALE = 2;
1308
+ /** The longest side a frame is drawn at, however large the layer. */
1309
+ const MAX_FRAME_EDGE = 2048;
1310
+ /** JPEG quality for opaque frames: no visible difference from PNG at a fraction of the size. */
1311
+ const JPEG_QUALITY = .9;
1312
+ /** The pixels a frame for a layer of `size` is drawn at. */
1313
+ function shaderFramePixels(size) {
1314
+ const scale = Math.min(FRAME_SCALE, MAX_FRAME_EDGE / Math.max(size.width, size.height, 1));
1315
+ return {
1316
+ width: Math.max(1, Math.round(size.width * scale)),
1317
+ height: Math.max(1, Math.round(size.height * scale))
1318
+ };
1319
+ }
1320
+ /**
1321
+ * The encoding a frame with these RGBA pixels is stored in: JPEG when every pixel is opaque, which
1322
+ * is about 25 times smaller than PNG for a shader, and PNG when any pixel lets the layer behind
1323
+ * show through, which JPEG cannot keep.
1324
+ */
1325
+ function shaderFrameEncoding(rgba) {
1326
+ for (let alpha = 3; alpha < rgba.length; alpha += 4) if (rgba[alpha] !== 255) return { type: "image/png" };
1327
+ return {
1328
+ type: "image/jpeg",
1329
+ quality: JPEG_QUALITY
1330
+ };
1331
+ }
1332
+ //#endregion
1143
1333
  //#region src/snap.ts
1144
1334
  const DEFAULT_SNAP_THRESHOLD = 5;
1145
1335
  function getEdges(node) {
@@ -1248,10 +1438,19 @@ function computeSelectionBounds(nodes) {
1248
1438
  //#endregion
1249
1439
  //#region src/layout/guides.ts
1250
1440
  const MAX_LAYOUT_GUIDE_LINES = 1e4;
1251
- function normalizedCount(grid) {
1252
- const value = grid.count ?? grid.numSections ?? 1;
1253
- if (!Number.isFinite(value)) return 0;
1254
- return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)));
1441
+ /** Figma's Auto count, as its archive stores it: as many sections as fit. */
1442
+ const AUTO_LAYOUT_GRID_COUNT = 2147483647;
1443
+ /** Whether a guide's count is Auto: the archive's value, or the plugin API's `Infinity` or `null`. */
1444
+ function isAutoGridCount(count) {
1445
+ return count === null || count === Infinity || (count ?? 0) >= 2147483647;
1446
+ }
1447
+ /**
1448
+ * A guide's count, set in Figma's plugin shape (`count`) or read from a file (`numSections`); an
1449
+ * edit's `count` wins over the count the file had. Auto is {@link AUTO_LAYOUT_GRID_COUNT}.
1450
+ */
1451
+ function layoutGridCount(grid) {
1452
+ const count = grid.count === void 0 ? grid.numSections : grid.count;
1453
+ return isAutoGridCount(count) ? AUTO_LAYOUT_GRID_COUNT : count ?? 1;
1255
1454
  }
1256
1455
  function pattern(grid) {
1257
1456
  if (grid.pattern === "GRID" || grid.pattern === "ROWS") return grid.pattern;
@@ -1263,15 +1462,29 @@ function alignment(grid) {
1263
1462
  if (value === "CENTER" || value === "MAX" || value === "STRETCH") return value;
1264
1463
  return "MIN";
1265
1464
  }
1266
- function sectionSize(nodeSize, grid) {
1465
+ /**
1466
+ * How many sections a guide draws. Auto fits as many fixed sections as the frame holds, counting
1467
+ * the offset once from the aligned edge, as Figma desktop 126 draws them.
1468
+ */
1469
+ function sectionCount(nodeSize, grid) {
1470
+ const value = layoutGridCount(grid);
1471
+ if (value === 2147483647) {
1472
+ const size = grid.sectionSize ?? 0;
1473
+ if (alignment(grid) === "STRETCH" || size <= 0) return 0;
1474
+ const gutter = grid.gutterSize ?? 0;
1475
+ const offset = alignment(grid) === "CENTER" ? 0 : grid.offset ?? 0;
1476
+ return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor((nodeSize - offset + gutter) / (size + gutter))));
1477
+ }
1478
+ if (!Number.isFinite(value)) return 0;
1479
+ return Math.min(MAX_LAYOUT_GUIDE_LINES, Math.max(0, Math.floor(value)));
1480
+ }
1481
+ function sectionSize(nodeSize, grid, count) {
1267
1482
  const fixed = grid.sectionSize ?? 0;
1268
1483
  if (alignment(grid) !== "STRETCH") return fixed;
1269
- const count = normalizedCount(grid);
1270
1484
  const gutter = grid.gutterSize ?? 0;
1271
1485
  return (nodeSize - (grid.offset ?? 0) * 2 - Math.max(0, count - 1) * gutter) / count;
1272
1486
  }
1273
- function start(nodeSize, grid, size) {
1274
- const count = normalizedCount(grid);
1487
+ function start(nodeSize, grid, size, count) {
1275
1488
  const gutter = grid.gutterSize ?? 0;
1276
1489
  const offset = grid.offset ?? 0;
1277
1490
  const span = count * size + Math.max(0, count - 1) * gutter;
@@ -1283,10 +1496,10 @@ function layoutGuideSections(node, grid) {
1283
1496
  if (grid.visible === false || pattern(grid) === "GRID") return [];
1284
1497
  const axis = pattern(grid) === "ROWS" ? "y" : "x";
1285
1498
  const nodeSize = axis === "x" ? node.width : node.height;
1286
- const size = sectionSize(nodeSize, grid);
1287
- const count = normalizedCount(grid);
1499
+ const count = sectionCount(nodeSize, grid);
1500
+ const size = sectionSize(nodeSize, grid, count);
1288
1501
  if (count <= 0 || size <= 0) return [];
1289
- const first = start(nodeSize, grid, size);
1502
+ const first = start(nodeSize, grid, size, count);
1290
1503
  const step = size + (grid.gutterSize ?? 0);
1291
1504
  return Array.from({ length: count }, (_, index) => {
1292
1505
  const sectionStart = first + index * step;
@@ -1325,125 +1538,6 @@ function layoutGuideLines(node, grid) {
1325
1538
  return lines;
1326
1539
  }
1327
1540
  //#endregion
1328
- //#region src/layout/sizing.ts
1329
- function primaryAxis(mode) {
1330
- return mode === "VERTICAL" ? "VERTICAL" : "HORIZONTAL";
1331
- }
1332
- /** The auto-layout parent that sizes a node's fill, or `undefined` when nothing does. */
1333
- function fillingParent(parent, node) {
1334
- if (!parent || parent.layoutMode === "NONE" || node.layoutPositioning === "ABSOLUTE") return void 0;
1335
- return parent;
1336
- }
1337
- function graphParent(graph, node) {
1338
- return node.parentId ? graph.getNode(node.parentId) : void 0;
1339
- }
1340
- function fills(parent, node, axis) {
1341
- if (parent.layoutMode === "NONE") return false;
1342
- if (axis === primaryAxis(parent.layoutMode)) return node.layoutGrow > 0;
1343
- if (node.layoutAlignSelf === "STRETCH") return true;
1344
- return node.layoutAlignSelf === "AUTO" && parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH";
1345
- }
1346
- function ownSizingField(node, axis) {
1347
- if (node.layoutMode === "NONE") return void 0;
1348
- return axis === primaryAxis(node.layoutMode) ? "primaryAxisSizing" : "counterAxisSizing";
1349
- }
1350
- function textHugs(autoResize, axis) {
1351
- if (autoResize === "WIDTH_AND_HEIGHT") return true;
1352
- return axis === "VERTICAL" && autoResize === "HEIGHT";
1353
- }
1354
- function hugs(node, axis) {
1355
- if (node.type === "TEXT") return textHugs(node.textAutoResize, axis);
1356
- const field = ownSizingField(node, axis);
1357
- return field !== void 0 && node[field] === "HUG";
1358
- }
1359
- /** The node's sizing along `axis`: fill from its parent, else its own hug, else fixed. */
1360
- function layoutSizing(graph, node, axis) {
1361
- return layoutSizingInParent(graphParent(graph, node), node, axis);
1362
- }
1363
- /** `layoutSizing` for code that holds the parent rather than the graph. */
1364
- function layoutSizingInParent(parentNode, node, axis) {
1365
- const parent = fillingParent(parentNode, node);
1366
- if (parent && fills(parent, node, axis)) return "FILL";
1367
- if (hugs(node, axis) && (parent || node.layoutMode !== "NONE")) return "HUG";
1368
- return "FIXED";
1369
- }
1370
- /** The sizings this node accepts on either axis, in Figma's order. */
1371
- function layoutSizingOptions(graph, node) {
1372
- return [
1373
- "FIXED",
1374
- "HUG",
1375
- "FILL"
1376
- ].filter((value) => layoutSizingError(graph, node, value) === void 0);
1377
- }
1378
- /** Figma's reason for refusing `value` on this node, or `undefined` when it applies. */
1379
- function layoutSizingError(graph, node, value) {
1380
- const parent = graphParent(graph, node);
1381
- const inAutoLayout = parent !== void 0 && parent.layoutMode !== "NONE";
1382
- if (!inAutoLayout && node.layoutMode === "NONE") return "node must be an auto-layout frame or a child of an auto-layout frame";
1383
- if (value === "FILL") {
1384
- if (!inAutoLayout) return "FILL can only be set on children of auto-layout frames";
1385
- if (node.layoutPositioning === "ABSOLUTE") return "FILL cannot be set on absolute positioned auto-layout children";
1386
- }
1387
- if (value === "HUG" && node.layoutMode === "NONE" && node.type !== "TEXT") return "HUG can only be set on auto-layout frames or text children of auto-layout frames";
1388
- }
1389
- /** The text auto-resize that hugs the content along the axes given. */
1390
- function textAutoResizeFor(hugsWidth, hugsHeight) {
1391
- if (hugsWidth && hugsHeight) return "WIDTH_AND_HEIGHT";
1392
- return hugsHeight ? "HEIGHT" : "NONE";
1393
- }
1394
- function textSizingUpdates(graph, node, axis, value) {
1395
- const other = axis === "HORIZONTAL" ? "VERTICAL" : "HORIZONTAL";
1396
- const hugsAxis = value === "HUG";
1397
- const hugsOther = layoutSizing(graph, node, other) === "HUG";
1398
- const autoResize = axis === "HORIZONTAL" ? textAutoResizeFor(hugsAxis, hugsOther) : textAutoResizeFor(hugsOther, hugsAxis);
1399
- if (autoResize === "NONE" && node.textAutoResize === "TRUNCATE") return {};
1400
- return autoResize === node.textAutoResize ? {} : { textAutoResize: autoResize };
1401
- }
1402
- /**
1403
- * The fields that set the node's sizing along `axis` to `value`, as Figma's setter writes
1404
- * them. A value Figma refuses yields no updates; `layoutSizingError` says why.
1405
- */
1406
- function layoutSizingUpdates(graph, node, axis, value) {
1407
- if (layoutSizingError(graph, node, value) !== void 0) return {};
1408
- const updates = {};
1409
- const parent = fillingParent(graphParent(graph, node), node);
1410
- if (parent && parent.layoutMode !== "NONE") {
1411
- const fill = value === "FILL";
1412
- if (axis === primaryAxis(parent.layoutMode)) {
1413
- if (fill !== node.layoutGrow > 0) updates.layoutGrow = fill ? 1 : 0;
1414
- } else if (fill && node.layoutAlignSelf !== "STRETCH") updates.layoutAlignSelf = "STRETCH";
1415
- else if (!fill && fills(parent, node, axis)) updates.layoutAlignSelf = parent.layoutMode !== "GRID" && parent.counterAxisAlign === "STRETCH" ? "MIN" : "AUTO";
1416
- }
1417
- const field = ownSizingField(node, axis);
1418
- if (field) {
1419
- const own = value === "HUG" ? "HUG" : "FIXED";
1420
- if (node[field] !== own) updates[field] = own;
1421
- }
1422
- if (node.type === "TEXT") Object.assign(updates, textSizingUpdates(graph, node, axis, value));
1423
- return updates;
1424
- }
1425
- /**
1426
- * The fields that make a child fill `axis` of a parent laid out as `parentLayout`, for a node
1427
- * an importer builds before it joins the graph. Under a parent without auto layout, such as a
1428
- * staging parent the node leaves when placed, both are set, so it fills whichever axis its
1429
- * eventual parent stacks along.
1430
- */
1431
- function fillSizingFields(parentLayout, axis) {
1432
- if (parentLayout === "NONE") return {
1433
- layoutGrow: 1,
1434
- layoutAlignSelf: "STRETCH"
1435
- };
1436
- return axis === primaryAxis(parentLayout) ? { layoutGrow: 1 } : { layoutAlignSelf: "STRETCH" };
1437
- }
1438
- /** An auto-layout frame's own sizing when it hugs or fixes its width and height. */
1439
- function autoLayoutSizingFields(direction, width, height) {
1440
- const horizontal = primaryAxis(direction) === "HORIZONTAL";
1441
- return {
1442
- primaryAxisSizing: horizontal ? width : height,
1443
- counterAxisSizing: horizontal ? height : width
1444
- };
1445
- }
1446
- //#endregion
1447
1541
  //#region src/text/lists.ts
1448
1542
  /** The marker of an unordered item, at every level. */
1449
1543
  const LIST_BULLET = "•";
@@ -1555,7 +1649,8 @@ const STYLE_TYPES = {
1555
1649
  effect: "EFFECT",
1556
1650
  grid: "GRID"
1557
1651
  };
1558
- const TEXT_STYLE_KEYS = /* @__PURE__ */ new Set([
1652
+ /** The fields a text style gives what uses it; changing one leaves the style. */
1653
+ const SHARED_TEXT_STYLE_FIELDS = [
1559
1654
  "fontFamily",
1560
1655
  "fontWeight",
1561
1656
  "italic",
@@ -1565,7 +1660,8 @@ const TEXT_STYLE_KEYS = /* @__PURE__ */ new Set([
1565
1660
  "textDecoration",
1566
1661
  "textCase",
1567
1662
  "fontFeatures"
1568
- ]);
1663
+ ];
1664
+ const TEXT_STYLE_KEYS = new Set(SHARED_TEXT_STYLE_FIELDS);
1569
1665
  function sharedStyleRefKey(kind) {
1570
1666
  return STYLE_REF_KEYS[kind];
1571
1667
  }
@@ -2249,11 +2345,12 @@ var SceneGraph = class SceneGraph {
2249
2345
  hitTest(px, py, scopeId) {
2250
2346
  return hitTest(this, px, py, scopeId);
2251
2347
  }
2252
- hitTestDeep(px, py, scopeId) {
2253
- return hitTestDeep(this, px, py, scopeId);
2348
+ /** `pad`, in canvas units, grows each shape's box, as Figma takes clicks just outside one. */
2349
+ hitTestDeep(px, py, scopeId, pad = 0) {
2350
+ return hitTestDeep(this, px, py, scopeId, pad);
2254
2351
  }
2255
- hitTestSelectable(px, py, scopeId, selectedIds) {
2256
- return hitTestSelectable(this, px, py, scopeId, selectedIds);
2352
+ hitTestSelectable(px, py, scopeId, selectedIds, pad = 0) {
2353
+ return hitTestSelectable(this, px, py, scopeId, selectedIds, pad);
2257
2354
  }
2258
2355
  hitTestOpenContainer(px, py, scopeId) {
2259
2356
  return hitTestOpenContainer(this, px, py, scopeId);
@@ -2328,6 +2425,6 @@ var SceneGraph = class SceneGraph {
2328
2425
  }
2329
2426
  };
2330
2427
  //#endregion
2331
- export { DEFAULT_SLOT_SETTINGS, GLYPH_AFFECTING_KEYS, LIST_BULLET, ROOT_FONT_SIZE_PX, SceneGraph, TEXT_PICTURE_KEYS, addCollection, addMode, addVariable, applyGraphTransfer, assignVariableBindingUnits, autoLayoutSizingFields, bindVariable, canCreateSlot, captureTransferredState, claimSlotContent, clearSlotContent, collectSceneMutation, computeSelectionBounds, computeSnap, createCollection, createMode, createSceneMutationImpact, createShaderPaint, createSlotProperty, createVariable, fillSizingFields, formatListNumber, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, hasShaderPaint, invalidateTextCaches, isPreferredComponent, isShaderFrameCurrent, layoutGuideLines, layoutGuideSections, layoutSizing, layoutSizingError, layoutSizingInParent, layoutSizingOptions, layoutSizingUpdates, listNumberFormat, markSourceFieldsEdited, modesDefaultFirst, mutationLayoutScopeIds, nonPreferredLayers, prepareGraphTransfer, prepareNodeTransfer, prepareVariableTransfer, readShaderPaints, reconcileVariableBindings, recordSceneMutations, removeCollection, removeGraphTransfer, removeMode, removeVariable, renameMode, rescaleNodeTree, resetSlotContent, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolvedNumericBindings, resolvedPaintBindings, resolvedValueBindings, setActiveMode, setDefaultMode, setIdSession, shaderOfPaint, shaderPresetKey, sharedStyleRefKey, sharedStyleTypeForKind, slotLimitViolations, slotOwner, slotScope, styleDetachmentChanges, textAutoResizeFor, textCacheInvalidationChanges, textListItems, tokenNumberFromUnit, tokenNumberInUnit, topLevelNumberDigits, unbindVariable, updateNodePreview, updateSlotProperty, variableBindingOwner, variablesResolvingThrough, withShaderPaints };
2428
+ export { AUTO_LAYOUT_GRID_COUNT, DEFAULT_SLOT_SETTINGS, GLYPH_AFFECTING_KEYS, LIST_BULLET, ROOT_FONT_SIZE_PX, SHARED_TEXT_STYLE_FIELDS, SceneGraph, TEXT_PICTURE_KEYS, addCollection, addMode, addVariable, applyGraphTransfer, assignVariableBindingUnits, bindVariable, canCreateSlot, captureTransferredState, claimSlotContent, clearSlotContent, collectSceneMutation, collectionsBoundIn, computeSelectionBounds, computeSnap, createCollection, createMode, createSceneMutationImpact, createShaderPaint, createSlotProperty, createVariable, formatListNumber, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, hasShaderPaint, invalidateTextCaches, isAutoGridCount, isPreferredComponent, isShaderFrameCurrent, layersUsingVariables, layoutGridCount, layoutGuideLines, layoutGuideSections, listNumberFormat, markSourceFieldsEdited, modesDefaultFirst, mutationLayoutScopeIds, nonPreferredLayers, prepareGraphTransfer, prepareNodeTransfer, prepareVariableTransfer, readShaderPaints, reconcileVariableBindings, recordSceneMutations, remapStyleRunReferences, removeCollection, removeGraphTransfer, removeMode, removeVariable, renameMode, rescaleNodeTree, resetSlotContent, resolveColorVariable, resolveColorVariableForNode, resolveNumberVariable, resolveNumberVariableForNode, resolveStringVariableForNode, resolveVariable, resolveVariableForNode, resolvedNumericBindings, resolvedPaintBindings, resolvedRunBindings, resolvedValueBindings, setActiveMode, setDefaultMode, setIdSession, shaderFrameEncoding, shaderFramePixels, shaderOfPaint, shaderPresetKey, sharedStyleRefKey, sharedStyleTypeForKind, slotLimitViolations, slotOwner, slotScope, styleDetachmentChanges, styleRunReferences, textCacheInvalidationChanges, textListItems, tokenNumberFromUnit, tokenNumberInUnit, topLevelNumberDigits, unbindVariable, updateNodePreview, updateSlotProperty, variableBindingOwner, variableText, variablesResolvingThrough, withShaderPaints };
2332
2429
 
2333
2430
  //# sourceMappingURL=index.js.map