@open-pencil/scene-graph 0.16.0-beta.2 → 0.16.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.
@@ -3,7 +3,6 @@ import { BLACK, TRANSPARENT } from "./color/contrast.js";
3
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 { computeImageHash } from "../images.js";
7
6
  import { randomHex, randomIndex } from "./comments/list.js";
8
7
  import { Matrix, getAbsolutePosition, getNodeLocalMatrix, getParentWorldMatrix, isTranslationOnly, localTransformFromWorld } from "./coordinate.js";
9
8
  import { removeStaleBindings } from "./bindings.js";
@@ -13,6 +12,8 @@ import { hitTest, hitTestDeep, hitTestDropTarget, hitTestOpenContainer, hitTestS
13
12
  import { partition, uniq } from "es-toolkit/array";
14
13
  import { isEqual } from "es-toolkit/predicate";
15
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";
16
17
  //#region src/mutation-impact.ts
17
18
  function createSceneMutationImpact() {
18
19
  return {
@@ -115,6 +116,33 @@ function resolvedNumericBindings(graph, node, fallback = "active") {
115
116
  return updates;
116
117
  }
117
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
+ /**
118
146
  * The text and visibility a node's string and boolean bindings resolve to in its mode, for the
119
147
  * fields whose stored value differs. Text or visibility an instance overrides, which typing in a
120
148
  * layer or toggling its eye records, keeps its own value, as an overridden width or height does.
@@ -128,8 +156,8 @@ function resolvedValueBindings(graph, node, fallback = "active") {
128
156
  if (!variableId || hasInstanceOverride(graph, node.id, field)) return void 0;
129
157
  return graph.resolveVariableForNode(node.id, variableId, fallback);
130
158
  };
131
- const text = node.type === "TEXT" ? resolve("text") : void 0;
132
- 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;
133
161
  const visible = resolve("visible");
134
162
  if (typeof visible === "boolean" && visible !== node.visible) updates.visible = visible;
135
163
  return updates;
@@ -231,11 +259,36 @@ function subtreeNodes(graph, roots) {
231
259
  }
232
260
  return nodes;
233
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
+ }
234
288
  function scopedNodes(graph, scope) {
235
289
  if (!scope) return graph.getAllNodes();
236
290
  if ("subtrees" in scope) return subtreeNodes(graph, scope.subtrees);
237
- const variables = variablesResolvingThrough(graph, scope.variables);
238
- return [...graph.getAllNodes()].filter((node) => boundVariableIds(node).some((id) => variables.has(id)));
291
+ return layersUsingVariables(graph, scope.variables);
239
292
  }
240
293
  /**
241
294
  * Resolve live numeric, text, and visibility bindings, numbers in scene units, without authoring
@@ -1233,7 +1286,7 @@ function createShaderPaint(preset) {
1233
1286
  }
1234
1287
  /** A short key that tells one preset from another, which a rendered frame records. */
1235
1288
  function shaderPresetKey(preset) {
1236
- return computeImageHash(new TextEncoder().encode(JSON.stringify(preset)));
1289
+ return bytesToHex(sha1(utf8ToBytes(JSON.stringify(preset))));
1237
1290
  }
1238
1291
  /**
1239
1292
  * Whether a shader's frame was rendered for its preset at the size `node` has now, so undoing a
@@ -1244,6 +1297,39 @@ function isShaderFrameCurrent(shader, size) {
1244
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);
1245
1298
  }
1246
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
1247
1333
  //#region src/snap.ts
1248
1334
  const DEFAULT_SNAP_THRESHOLD = 5;
1249
1335
  function getEdges(node) {
@@ -2339,6 +2425,6 @@ var SceneGraph = class SceneGraph {
2339
2425
  }
2340
2426
  };
2341
2427
  //#endregion
2342
- 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, computeSelectionBounds, computeSnap, createCollection, createMode, createSceneMutationImpact, createShaderPaint, createSlotProperty, createVariable, formatListNumber, generateId, getActiveModeId, getNodeVariableModeId, getSharedStyles, getVariablesByType, getVariablesForCollection, hasShaderPaint, invalidateTextCaches, isAutoGridCount, isPreferredComponent, isShaderFrameCurrent, 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, shaderOfPaint, shaderPresetKey, sharedStyleRefKey, sharedStyleTypeForKind, slotLimitViolations, slotOwner, slotScope, styleDetachmentChanges, styleRunReferences, 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 };
2343
2429
 
2344
2430
  //# sourceMappingURL=index.js.map