@pairdraw/core 0.16.0 → 0.16.2

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 (145) hide show
  1. package/README.md +1 -1
  2. package/dist/ai/providers.d.ts +6 -1
  3. package/dist/ai/providers.d.ts.map +1 -1
  4. package/dist/ai/providers.js +9 -0
  5. package/dist/ai/providers.js.map +1 -1
  6. package/dist/canvas/highlight-rect.d.ts +10 -1
  7. package/dist/canvas/highlight-rect.d.ts.map +1 -1
  8. package/dist/canvas/highlight-rect.js +16 -8
  9. package/dist/canvas/highlight-rect.js.map +1 -1
  10. package/dist/canvas/index.d.ts +2 -3
  11. package/dist/canvas/index.js +1 -2
  12. package/dist/canvas/issues/draw.d.ts +2 -6
  13. package/dist/canvas/issues/draw.d.ts.map +1 -1
  14. package/dist/canvas/issues/draw.js +2 -99
  15. package/dist/canvas/issues/draw.js.map +1 -1
  16. package/dist/canvas/issues/types.d.ts +2 -33
  17. package/dist/canvas/issues/types.d.ts.map +1 -1
  18. package/dist/canvas/overlays/{ai.d.ts → ai/draw.d.ts} +3 -3
  19. package/dist/canvas/overlays/ai/draw.d.ts.map +1 -0
  20. package/dist/canvas/overlays/ai/draw.js +102 -0
  21. package/dist/canvas/overlays/ai/draw.js.map +1 -0
  22. package/dist/canvas/overlays/ai/motion.d.ts +23 -0
  23. package/dist/canvas/overlays/ai/motion.d.ts.map +1 -0
  24. package/dist/canvas/overlays/ai/motion.js +32 -0
  25. package/dist/canvas/overlays/ai/motion.js.map +1 -0
  26. package/dist/canvas/renderer/methods.js +1 -1
  27. package/dist/canvas/renderer/methods.js.map +1 -1
  28. package/dist/canvas/renderer/overlay-pass.d.ts.map +1 -1
  29. package/dist/canvas/renderer/overlay-pass.js +2 -47
  30. package/dist/canvas/renderer/overlay-pass.js.map +1 -1
  31. package/dist/canvas/renderer/pipeline.js +1 -1
  32. package/dist/canvas/renderer/pipeline.js.map +1 -1
  33. package/dist/canvas/renderer/state.d.ts +5 -3
  34. package/dist/canvas/renderer/state.d.ts.map +1 -1
  35. package/dist/canvas/renderer/state.js +18 -6
  36. package/dist/canvas/renderer/state.js.map +1 -1
  37. package/dist/canvas/renderer/types.d.ts +2 -2
  38. package/dist/canvas/renderer/types.d.ts.map +1 -1
  39. package/dist/canvas/renderer.d.ts +12 -8
  40. package/dist/canvas/renderer.d.ts.map +1 -1
  41. package/dist/canvas/renderer.js +9 -9
  42. package/dist/canvas/renderer.js.map +1 -1
  43. package/dist/canvas/text/preparation/cache.d.ts +5 -0
  44. package/dist/canvas/text/preparation/cache.d.ts.map +1 -1
  45. package/dist/canvas/text/preparation/cache.js +8 -1
  46. package/dist/canvas/text/preparation/cache.js.map +1 -1
  47. package/dist/constants.d.ts +13 -18
  48. package/dist/constants.d.ts.map +1 -1
  49. package/dist/constants.js +16 -21
  50. package/dist/constants.js.map +1 -1
  51. package/dist/design-jsx/index.d.ts +2 -2
  52. package/dist/design-jsx/index.js +2 -2
  53. package/dist/design-jsx/preview/picture.d.ts +12 -5
  54. package/dist/design-jsx/preview/picture.d.ts.map +1 -1
  55. package/dist/design-jsx/preview/picture.js +40 -15
  56. package/dist/design-jsx/preview/picture.js.map +1 -1
  57. package/dist/editor/bridges/undo.d.ts +1 -1
  58. package/dist/editor/create.d.ts +3 -6
  59. package/dist/editor/create.d.ts.map +1 -1
  60. package/dist/editor/history/atomic-tool.d.ts.map +1 -1
  61. package/dist/editor/history/atomic-tool.js +11 -8
  62. package/dist/editor/history/atomic-tool.js.map +1 -1
  63. package/dist/editor/history/document-change.d.ts +9 -1
  64. package/dist/editor/history/document-change.d.ts.map +1 -1
  65. package/dist/editor/history/document-change.js +100 -2
  66. package/dist/editor/history/document-change.js.map +1 -1
  67. package/dist/editor/history/snapshot/graph.d.ts +15 -3
  68. package/dist/editor/history/snapshot/graph.d.ts.map +1 -1
  69. package/dist/editor/history/snapshot/graph.js +29 -8
  70. package/dist/editor/history/snapshot/graph.js.map +1 -1
  71. package/dist/editor/index.d.ts +3 -3
  72. package/dist/editor/index.js +3 -3
  73. package/dist/editor/issues.d.ts +1 -4
  74. package/dist/editor/issues.d.ts.map +1 -1
  75. package/dist/editor/issues.js +5 -44
  76. package/dist/editor/issues.js.map +1 -1
  77. package/dist/editor/nudge.js +3 -2
  78. package/dist/editor/nudge.js.map +1 -1
  79. package/dist/editor/read-only/actions.js +0 -3
  80. package/dist/editor/read-only/actions.js.map +1 -1
  81. package/dist/editor/state/shared.js +1 -1
  82. package/dist/editor/state/shared.js.map +1 -1
  83. package/dist/editor/types.d.ts +7 -4
  84. package/dist/editor/types.d.ts.map +1 -1
  85. package/dist/index.d.ts +3 -3
  86. package/dist/index.js +3 -3
  87. package/dist/io/subgraph.d.ts +5 -2
  88. package/dist/io/subgraph.d.ts.map +1 -1
  89. package/dist/io/subgraph.js +6 -2
  90. package/dist/io/subgraph.js.map +1 -1
  91. package/dist/layout/mutations.d.ts +1 -1
  92. package/dist/layout/mutations.d.ts.map +1 -1
  93. package/dist/layout/mutations.js +1 -1
  94. package/dist/layout/mutations.js.map +1 -1
  95. package/dist/text/font/faces.js +1 -1
  96. package/dist/text/font/faces.js.map +1 -1
  97. package/dist/text/web-font/providers.d.ts +2 -11
  98. package/dist/text/web-font/providers.d.ts.map +1 -1
  99. package/dist/text/web-font/providers.js +8 -7
  100. package/dist/text/web-font/providers.js.map +1 -1
  101. package/dist/tools/analyze/diff/jsx.d.ts +2 -1
  102. package/dist/tools/analyze/diff/jsx.d.ts.map +1 -1
  103. package/dist/tools/analyze/diff/jsx.js +4 -2
  104. package/dist/tools/analyze/diff/jsx.js.map +1 -1
  105. package/package.json +24 -9
  106. package/src/ai/providers.ts +15 -1
  107. package/src/canvas/highlight-rect.ts +30 -9
  108. package/src/canvas/index.ts +1 -15
  109. package/src/canvas/issues/draw.ts +2 -165
  110. package/src/canvas/issues/types.ts +1 -36
  111. package/src/canvas/overlays/ai/draw.ts +129 -0
  112. package/src/canvas/overlays/ai/motion.ts +46 -0
  113. package/src/canvas/renderer/methods.ts +1 -1
  114. package/src/canvas/renderer/overlay-pass.ts +2 -49
  115. package/src/canvas/renderer/pipeline.ts +1 -1
  116. package/src/canvas/renderer/state.ts +20 -5
  117. package/src/canvas/renderer/types.ts +2 -2
  118. package/src/canvas/renderer.ts +9 -10
  119. package/src/canvas/text/preparation/cache.ts +9 -1
  120. package/src/constants.ts +12 -17
  121. package/src/design-jsx/index.ts +1 -1
  122. package/src/design-jsx/preview/picture.ts +55 -18
  123. package/src/editor/history/atomic-tool.ts +15 -8
  124. package/src/editor/history/document-change.ts +117 -1
  125. package/src/editor/history/snapshot/graph.ts +48 -8
  126. package/src/editor/index.ts +10 -2
  127. package/src/editor/issues.ts +6 -36
  128. package/src/editor/nudge.ts +4 -2
  129. package/src/editor/read-only/actions.ts +0 -3
  130. package/src/editor/state/shared.ts +1 -1
  131. package/src/editor/types.ts +6 -4
  132. package/src/io/subgraph.ts +10 -5
  133. package/src/layout/mutations.ts +2 -2
  134. package/src/text/font/faces.ts +1 -1
  135. package/src/text/web-font/providers.ts +19 -13
  136. package/src/tools/analyze/diff/jsx.ts +10 -5
  137. package/dist/canvas/issues/layout.d.ts +0 -37
  138. package/dist/canvas/issues/layout.d.ts.map +0 -1
  139. package/dist/canvas/issues/layout.js +0 -303
  140. package/dist/canvas/issues/layout.js.map +0 -1
  141. package/dist/canvas/overlays/ai.d.ts.map +0 -1
  142. package/dist/canvas/overlays/ai.js +0 -26
  143. package/dist/canvas/overlays/ai.js.map +0 -1
  144. package/src/canvas/issues/layout.ts +0 -376
  145. package/src/canvas/overlays/ai.ts +0 -34
@@ -1,6 +1,6 @@
1
1
  import { computeAllLayouts } from "../../layout.js";
2
2
  import { diffFields } from "./diff.js";
3
- import { isEqual } from "es-toolkit";
3
+ import { compact, isEqual, uniq, xor } from "es-toolkit";
4
4
  import { cloneInstanceOverrideState } from "@pairdraw/scene-graph/instances/overrides";
5
5
  import { createSceneMutationImpact, recordSceneMutations } from "@pairdraw/scene-graph/mutation-impact";
6
6
  import { withLiveComments } from "@pairdraw/scene-graph/comments";
@@ -221,6 +221,104 @@ function captureDocumentChange(graph, pageId) {
221
221
  return change;
222
222
  };
223
223
  }
224
+ /** `undefined` when the layer's parents cannot be followed to a page or the root. */
225
+ function placement(nodes, id) {
226
+ let child = null;
227
+ for (const node of lineage(nodes, id)) {
228
+ if (node.type === "CANVAS") return {
229
+ pageId: node.id,
230
+ layerId: child?.id ?? null
231
+ };
232
+ if (!node.parentId) return {
233
+ pageId: null,
234
+ layerId: null
235
+ };
236
+ child = node;
237
+ }
238
+ }
239
+ /**
240
+ * Layers as they were before the edit, read from the live graph: removed ones from their copies,
241
+ * and moved ones under the parent whose old child list held them.
242
+ */
243
+ function layersBefore(graph, change) {
244
+ const created = new Set(change.created.map((node) => node.id));
245
+ const deleted = new Map(change.deleted.map((node) => [node.id, node]));
246
+ const parents = /* @__PURE__ */ new Map();
247
+ for (const { id, childIds } of change.children.before) for (const childId of childIds) parents.set(childId, id);
248
+ return {
249
+ size: graph.nodes.size + deleted.size,
250
+ get(id) {
251
+ if (created.has(id)) return void 0;
252
+ const node = deleted.get(id) ?? graph.getNode(id);
253
+ const parentId = parents.get(id);
254
+ return node && parentId !== void 0 && parentId !== node.parentId ? {
255
+ ...node,
256
+ parentId
257
+ } : node;
258
+ }
259
+ };
260
+ }
261
+ /** Layers the edit created, removed, changed, or moved, and the parents whose children changed. */
262
+ function touchedLayerIds(change) {
263
+ const lists = (side) => new Map(change.children[side].map(({ id, childIds }) => [id, childIds]));
264
+ const before = lists("before");
265
+ const after = lists("after");
266
+ const moved = uniq([...before.keys(), ...after.keys()]).flatMap((id) => [id, ...xor(before.get(id) ?? [], after.get(id) ?? [])]);
267
+ return uniq([
268
+ ...change.created.map((node) => node.id),
269
+ ...change.deleted.map((node) => node.id),
270
+ ...change.updated.map((update) => update.id),
271
+ ...moved
272
+ ]);
273
+ }
274
+ /** The ends of the connectors in the graph or removed by the edit, on either side of it. */
275
+ function connectorEnds(graph, change) {
276
+ const ends = /* @__PURE__ */ new Map();
277
+ const add = (id, nodes) => {
278
+ const nodeIds = nodes.flatMap((node) => [node.connectorStart?.nodeId, node.connectorEnd?.nodeId]);
279
+ ends.set(id, uniq([...ends.get(id) ?? [], ...compact(nodeIds)]));
280
+ };
281
+ for (const id of graph.connectorIds) add(id, compact([graph.getNode(id)]));
282
+ for (const node of change.deleted) if (node.type === "CONNECTOR") add(node.id, [node]);
283
+ for (const update of change.updated) if (update.fields && ends.has(update.id)) add(update.id, [update.fields.before]);
284
+ return ends;
285
+ }
286
+ /**
287
+ * The page children holding what an edit touched, on either side of it, for diffing and drawing
288
+ * just those instead of whole pages (`graphsFromDocumentChange`). A layer whose connector draws
289
+ * to a layer elsewhere brings that layer too, as JSX writes the end by it. `null` when part of
290
+ * the page cannot be told apart this way: the edit changed variables, which any layer may show,
291
+ * moved a layer to another page, or left a layer whose parents cannot be followed.
292
+ */
293
+ function touchedTopLevelIds(graph, change) {
294
+ if (change.variables.length > 0 || change.collections.length > 0) return null;
295
+ const sides = [layersBefore(graph, change), graph.nodes];
296
+ const holders = (id) => {
297
+ const placements = sides.map((nodes) => nodes.get(id) ? placement(nodes, id) : null);
298
+ if (placements.includes(void 0)) return null;
299
+ const [was, is] = placements;
300
+ if (was?.pageId && is?.pageId && was.pageId !== is.pageId) return null;
301
+ return placements.map((place) => place?.layerId ?? null);
302
+ };
303
+ const layers = /* @__PURE__ */ new Set();
304
+ for (const id of touchedLayerIds(change)) {
305
+ const held = holders(id);
306
+ if (!held) return null;
307
+ for (const layerId of compact(held)) layers.add(layerId);
308
+ }
309
+ const ends = connectorEnds(graph, change);
310
+ for (let grew = true; grew;) {
311
+ grew = false;
312
+ for (const [connectorId, endIds] of ends) {
313
+ if (!holders(connectorId)?.some((layerId) => layerId && layers.has(layerId))) continue;
314
+ for (const layerId of compact(endIds.flatMap((id) => holders(id) ?? []))) {
315
+ grew ||= !layers.has(layerId);
316
+ layers.add(layerId);
317
+ }
318
+ }
319
+ }
320
+ return [...layers];
321
+ }
224
322
  function isEmptyDocumentChange(change) {
225
323
  return change.created.length === 0 && change.deleted.length === 0 && change.updated.length === 0 && change.children.before.length === 0 && change.children.after.length === 0 && change.variables.length === 0 && change.collections.length === 0;
226
324
  }
@@ -275,6 +373,6 @@ function restoreDocumentChange(ctx, change, side, options = {}) {
275
373
  ctx.requestRender();
276
374
  }
277
375
  //#endregion
278
- export { applyDocumentChange, captureDocumentChange, isEmptyDocumentChange, restoreDocumentChange, writeRecord };
376
+ export { applyDocumentChange, captureDocumentChange, isEmptyDocumentChange, restoreDocumentChange, touchedTopLevelIds, writeRecord };
279
377
 
280
378
  //# sourceMappingURL=document-change.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"document-change.js","names":[],"sources":["../../../src/editor/history/document-change.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type {\n FigmaSourcePayload,\n SceneGraph,\n SceneNode,\n SourceMetadata,\n Variable,\n VariableCollection\n} from '@pairdraw/scene-graph'\nimport { withLiveComments } from '@pairdraw/scene-graph/comments'\nimport { cloneInstanceOverrideState } from '@pairdraw/scene-graph/instances/overrides'\nimport {\n createSceneMutationImpact,\n recordSceneMutations\n} from '@pairdraw/scene-graph/mutation-impact'\n\nimport type { EditorContext } from '#core/editor/types'\nimport { computeAllLayouts } from '#core/layout'\n\nimport { diffFields, type FieldChanges } from './diff'\n\ntype Side = 'before' | 'after'\n\n/**\n * The fields an edit changed on a layer that exists on both sides. Source metadata is compared\n * a level down and its `.fig` payload a level below that, so marking a field edited keeps that\n * change rather than the layer's whole `.fig` record.\n */\ninterface LayerUpdate {\n id: string\n fields: FieldChanges<SceneNode> | null\n source: FieldChanges<SourceMetadata> | null\n fig: FieldChanges<FigmaSourcePayload> | null\n}\n\n/** A parent's children in one state, listed parents first. */\ninterface ChildList {\n id: string\n childIds: string[]\n}\n\n/** A variable or collection on each side of an edit; `null` on the side it does not exist. */\ninterface RecordChange<T> {\n id: string\n before: T | null\n after: T | null\n}\n\n/**\n * What one edit did to the document: copies of only the layers, variables, and collections it\n * created, deleted, or changed, on any page, so an undo step costs what the edit touched rather\n * than a copy of the document. Comments on the document node are left out, as undo never takes\n * them back.\n */\nexport interface DocumentChange {\n /** The page the edit ran on, which a review of it shows. */\n pageId: string\n /** Pages whose layers the edit changed, laid out again when it is undone or redone. */\n pageIds: string[]\n /** Layers as the edit left them, parents first. */\n created: SceneNode[]\n /** Layers as they were before the edit removed them, parents first. */\n deleted: SceneNode[]\n /** Fields the edit changed on layers that exist in both states, children aside. */\n updated: LayerUpdate[]\n /** Child lists that differ between the states, each side's parents first. */\n children: Record<Side, ChildList[]>\n variables: RecordChange<Variable>[]\n collections: RecordChange<VariableCollection>[]\n}\n\n/** Layers by id: the live graph's, or those captured before the edit. */\ntype Lookup = Pick<ReadonlyMap<string, SceneNode>, 'get' | 'size'>\n\nconst NESTED_FIELDS: ReadonlySet<keyof SceneNode> = new Set(['childIds', 'parentId', 'source'])\nconst SOURCE_PAYLOAD: ReadonlySet<keyof SourceMetadata> = new Set(['fig'])\n\nfunction diffLayer(id: string, previous: SceneNode, current: SceneNode): LayerUpdate | null {\n const update: LayerUpdate = {\n id,\n fields: diffFields(id, previous, current, NESTED_FIELDS),\n source: diffFields(id, previous.source, current.source, SOURCE_PAYLOAD),\n fig: diffFields(id, previous.source.fig, current.source.fig)\n }\n return update.fields || update.source || update.fig ? update : null\n}\n\nfunction withChanges<T extends object>(value: T, changes: FieldChanges<T> | null, side: Side): T {\n if (!changes) return value\n const result = { ...value, ...structuredClone(changes[side]) }\n for (const key of changes.absent[side]) Reflect.deleteProperty(result, key)\n return result\n}\n\n/**\n * `editedFields` marking plugin data edited as `live` does. The mark makes `.fig` export write\n * the document node's comments, so it follows them rather than undo.\n */\nfunction markedLike(editedFields: string[], live: SceneNode): string[] {\n const marked = live.source.editedFields.includes('pluginData')\n if (editedFields.includes('pluginData') === marked) return editedFields\n return marked\n ? [...editedFields, 'pluginData']\n : editedFields.filter((field) => field !== 'pluginData')\n}\n\n/** The document node holding the comments of `live`, as undo never takes them back. */\nfunction withCommentsOf(root: SceneNode, live: SceneNode): SceneNode {\n return {\n ...root,\n pluginData: withLiveComments(root.pluginData, live.pluginData),\n source: { ...root.source, editedFields: markedLike(root.source.editedFields, live) }\n }\n}\n\nfunction restoreLayer(graph: SceneGraph, update: LayerUpdate, side: Side): void {\n const node = graph.getNode(update.id)\n if (!node) return\n const changes: Partial<SceneNode> = update.fields ? structuredClone(update.fields[side]) : {}\n if (update.source || update.fig) {\n changes.source = {\n ...withChanges(node.source, update.source, side),\n fig: withChanges(node.source.fig, update.fig, side)\n }\n }\n if (node.id === graph.rootId) {\n if (changes.pluginData)\n changes.pluginData = withLiveComments(changes.pluginData, node.pluginData)\n if (changes.source) {\n changes.source.editedFields = markedLike(changes.source.editedFields, node)\n }\n }\n graph.restoreNodeProperties(update.id, changes, update.fields?.absent[side] ?? [])\n}\n\n/**\n * A copy that keeps the layer's values as they are now. Values are replaced, never written into\n * (`materialize-instance.ts` in `@pairdraw/fig`), so sharing them is safe; the graph edits\n * child lists, source metadata, and override maps in place, so those are copied.\n */\nfunction captureNode(node: SceneNode): SceneNode {\n const { source, instanceOverrides } = node\n return {\n ...node,\n childIds: [...node.childIds],\n source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },\n instanceOverrides: cloneInstanceOverrideState(instanceOverrides)\n }\n}\n\n/** Copies a page's layers not copied yet; a layer moved in from another page keeps its copy. */\nfunction capturePage(graph: SceneGraph, pageId: string, captured: Map<string, SceneNode>): void {\n const stack = [pageId]\n for (let id = stack.pop(); id !== undefined; id = stack.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n if (!captured.has(id)) captured.set(id, captureNode(node))\n stack.push(...node.childIds)\n }\n}\n\n/**\n * A layer and its ancestors, nearest first. Like `SceneGraph.closest`, the walk visits at most as\n * many layers as there are, so a parent cycle in bad data cannot hang it.\n */\nfunction* lineage(nodes: Lookup, id: string): Generator<SceneNode> {\n let node = nodes.get(id)\n for (let steps = 0; node && steps < nodes.size; steps++) {\n yield node\n node = node.parentId ? nodes.get(node.parentId) : undefined\n }\n}\n\nfunction pageOf(nodes: Lookup, id: string): string | null {\n for (const node of lineage(nodes, id)) if (node.type === 'CANVAS') return node.id\n return null\n}\n\nfunction depthIn(nodes: Lookup, id: string): number {\n let depth = 0\n for (const node of lineage(nodes, id)) if (node.parentId) depth++\n return depth\n}\n\n/** Adds one touched layer to the change, given its state on each side, if it has one. */\nfunction recordLayer(\n change: DocumentChange,\n id: string,\n previous: SceneNode | undefined,\n current: SceneNode | undefined\n): void {\n if (previous && !isEqual(previous.childIds, current?.childIds ?? [])) {\n change.children.before.push({ id, childIds: previous.childIds })\n }\n if (current && !isEqual(current.childIds, previous?.childIds ?? [])) {\n change.children.after.push({ id, childIds: [...current.childIds] })\n }\n if (!previous) {\n if (current) change.created.push(structuredClone(current))\n } else if (!current) {\n change.deleted.push(structuredClone(previous))\n } else {\n const update = diffLayer(id, previous, current)\n if (update) change.updated.push(update)\n }\n}\n\nfunction diffRecords<T>(previous: Map<string, T>, current: Map<string, T>): RecordChange<T>[] {\n const ids = new Set([...previous.keys(), ...current.keys()])\n return [...ids].flatMap((id) => {\n const before = previous.get(id) ?? null\n const after = current.get(id) ?? null\n return isEqual(before, after) ? [] : [{ id, before, after: structuredClone(after) }]\n })\n}\n\n/** Restores records in place where they exist, as views may hold them, as atomic tools do. */\n/** Make `target` hold `value` under `id`, or nothing; an existing record is kept and rewritten. */\nexport function writeRecord<T extends object>(\n target: Map<string, T>,\n id: string,\n value: T | null\n): void {\n const existing = target.get(id)\n if (!value) {\n target.delete(id)\n } else if (existing) {\n for (const key of Object.keys(existing)) {\n if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)\n }\n Object.assign(existing, structuredClone(value))\n } else {\n target.set(id, structuredClone(value))\n }\n}\n\nfunction restoreRecords<T extends object>(\n target: Map<string, T>,\n changes: RecordChange<T>[],\n side: Side\n): void {\n for (const change of changes) writeRecord(target, change.id, change[side])\n}\n\n/**\n * Starts recording an edit made from `pageId`. Call the returned function once the edit is\n * done, also when it failed, to stop recording and get what the edit changed.\n *\n * The page is copied up front, so values written into its layers in place are kept too. Another\n * page, or the document node, is copied the first time the edit is about to change it.\n */\nexport function captureDocumentChange(graph: SceneGraph, pageId: string): () => DocumentChange {\n const captured = new Map<string, SceneNode>()\n const capturedPages = new Set([pageId])\n const created = new Set<string>()\n capturePage(graph, pageId, captured)\n const variables = structuredClone(graph.variables)\n const collections = structuredClone(graph.variableCollections)\n const impact = createSceneMutationImpact()\n const unbindEvents = recordSceneMutations(graph, impact)\n const unobserve = graph.observeNodeChanges({\n created: (node) => created.add(node.id),\n before: (node) => {\n if (captured.has(node.id) || created.has(node.id)) return\n const page = pageOf(graph.nodes, node.id)\n if (page && !capturedPages.has(page)) {\n capturedPages.add(page)\n capturePage(graph, page, captured)\n }\n if (!captured.has(node.id)) captured.set(node.id, captureNode(node))\n }\n })\n\n return () => {\n unobserve()\n unbindEvents()\n const change: DocumentChange = {\n pageId,\n pageIds: [],\n created: [],\n deleted: [],\n updated: [],\n children: { before: [], after: [] },\n variables: diffRecords(variables, graph.variables),\n collections: diffRecords(collections, graph.variableCollections)\n }\n const pageIds = new Set<string>()\n const touched = new Set([\n ...impact.changedNodeIds,\n ...impact.previousParentIds,\n ...impact.currentParentIds\n ])\n for (const id of touched) {\n const previous = captured.get(id)\n // A layer changed without telling observers has no state to go back to.\n if (!previous && !created.has(id)) continue\n const current = graph.getNode(id)\n // Comments are never part of an undo step.\n const kept =\n previous && current && id === graph.rootId ? withCommentsOf(previous, current) : previous\n recordLayer(change, id, kept, current)\n for (const page of [pageOf(captured, id), pageOf(graph.nodes, id)])\n if (page) pageIds.add(page)\n }\n change.pageIds = [...pageIds]\n const byDepth = (nodes: Lookup) => (a: { id: string }, b: { id: string }) =>\n depthIn(nodes, a.id) - depthIn(nodes, b.id)\n change.created.sort(byDepth(graph.nodes))\n change.children.after.sort(byDepth(graph.nodes))\n change.deleted.sort(byDepth(captured))\n change.children.before.sort(byDepth(captured))\n return change\n }\n}\n\nexport function isEmptyDocumentChange(change: DocumentChange): boolean {\n return (\n change.created.length === 0 &&\n change.deleted.length === 0 &&\n change.updated.length === 0 &&\n change.children.before.length === 0 &&\n change.children.after.length === 0 &&\n change.variables.length === 0 &&\n change.collections.length === 0\n )\n}\n\n/**\n * Puts what an edit touched back as it was on one side of it. The graph must be as the other\n * side left it; what the edit did not touch is left alone, and so are comments. A graph that\n * holds only part of the document, such as one page, gets the part of the change it has room\n * for.\n */\nexport function applyDocumentChange(graph: SceneGraph, change: DocumentChange, side: Side): void {\n const restored = side === 'before' ? change.deleted : change.created\n const removed = side === 'before' ? change.created : change.deleted\n restoreRecords(graph.variableCollections, change.collections, side)\n restoreRecords(graph.variables, change.variables, side)\n graph.preserveSourceMetadataDuring(() => {\n for (const node of restored) {\n const { parentId, childIds: _childIds, ...fields } = structuredClone(node)\n if (!parentId || !graph.getNode(parentId)) continue\n graph.createNode(node.type, parentId, { ...fields, childIds: [] })\n }\n // Parents come first, so a layer never moves under one of its own descendants.\n for (const { id, childIds } of change.children[side]) {\n for (const [index, childId] of childIds.entries()) {\n if (graph.getNode(id)?.childIds[index] !== childId) graph.insertChildAt(childId, id, index)\n }\n }\n // Layers that survive have moved out of the removed ones by now.\n for (const node of removed) graph.deleteNode(node.id)\n for (const update of change.updated) restoreLayer(graph, update, side)\n })\n graph.clearAbsPosCache()\n}\n\n/** Drops the selected and hovered layers that no longer exist, and keeps the rest. */\nfunction keepLiveSelection(ctx: EditorContext): void {\n const live = [...ctx.state.selectedIds].filter((id) => ctx.graph.getNode(id))\n if (live.length !== ctx.state.selectedIds.size) ctx.setSelectedIds(new Set(live))\n const hovered = ctx.state.hoveredNodeId\n if (hovered !== null && !ctx.graph.getNode(hovered)) ctx.state.hoveredNodeId = null\n}\n\n/**\n * Undoes or redoes an edit in the editor, whichever page is on screen. Undo and redo clear the\n * selection on that page; `keepSelection`, for an edit put back that the person did not ask to\n * undo, keeps the selected layers that still exist.\n */\nexport function restoreDocumentChange(\n ctx: EditorContext,\n change: DocumentChange,\n side: Side,\n options: { keepSelection?: boolean } = {}\n): void {\n applyDocumentChange(ctx.graph, change, side)\n const pageIds = new Set(change.pageIds)\n // Bound values follow their variables, so the page on screen is laid out again.\n if (change.variables.length > 0) pageIds.add(ctx.state.currentPageId)\n for (const pageId of pageIds) {\n if (ctx.graph.getNode(pageId)) computeAllLayouts(ctx.graph, pageId)\n }\n if (options.keepSelection) {\n keepLiveSelection(ctx)\n } else if (pageIds.has(ctx.state.currentPageId)) {\n ctx.setSelectedIds(new Set())\n ctx.state.hoveredNodeId = null\n }\n ctx.requestRender()\n}\n"],"mappings":";;;;;;;AA2EA,MAAM,gCAA8C,IAAI,IAAI;CAAC;CAAY;CAAY;AAAQ,CAAC;AAC9F,MAAM,iCAAoD,IAAI,IAAI,CAAC,KAAK,CAAC;AAEzE,SAAS,UAAU,IAAY,UAAqB,SAAwC;CAC1F,MAAM,SAAsB;EAC1B;EACA,QAAQ,WAAW,IAAI,UAAU,SAAS,aAAa;EACvD,QAAQ,WAAW,IAAI,SAAS,QAAQ,QAAQ,QAAQ,cAAc;EACtE,KAAK,WAAW,IAAI,SAAS,OAAO,KAAK,QAAQ,OAAO,GAAG;CAC7D;CACA,OAAO,OAAO,UAAU,OAAO,UAAU,OAAO,MAAM,SAAS;AACjE;AAEA,SAAS,YAA8B,OAAU,SAAiC,MAAe;CAC/F,IAAI,CAAC,SAAS,OAAO;CACrB,MAAM,SAAS;EAAE,GAAG;EAAO,GAAG,gBAAgB,QAAQ,KAAK;CAAE;CAC7D,KAAK,MAAM,OAAO,QAAQ,OAAO,OAAO,QAAQ,eAAe,QAAQ,GAAG;CAC1E,OAAO;AACT;;;;;AAMA,SAAS,WAAW,cAAwB,MAA2B;CACrE,MAAM,SAAS,KAAK,OAAO,aAAa,SAAS,YAAY;CAC7D,IAAI,aAAa,SAAS,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,GAC9C,IAAI,MAAM,QAAQ,EAAE,CAAC,EAAE,SAAS,WAAW,SAAS,MAAM,cAAc,SAAS,IAAI,KAAK;EAI9F,KAAK,MAAM,QAAQ,SAAS,MAAM,WAAW,KAAK,EAAE;EACpD,KAAK,MAAM,UAAU,OAAO,SAAS,aAAa,OAAO,QAAQ,IAAI;CACvE,CAAC;CACD,MAAM,iBAAiB;AACzB;;AAGA,SAAS,kBAAkB,KAA0B;CACnD,MAAM,OAAO,CAAC,GAAG,IAAI,MAAM,WAAW,CAAC,CAAC,QAAQ,OAAO,IAAI,MAAM,QAAQ,EAAE,CAAC;CAC5E,IAAI,KAAK,WAAW,IAAI,MAAM,YAAY,MAAM,IAAI,eAAe,IAAI,IAAI,IAAI,CAAC;CAChF,MAAM,UAAU,IAAI,MAAM;CAC1B,IAAI,YAAY,QAAQ,CAAC,IAAI,MAAM,QAAQ,OAAO,GAAG,IAAI,MAAM,gBAAgB;AACjF;;;;;;AAOA,SAAgB,sBACd,KACA,QACA,MACA,UAAuC,CAAC,GAClC;CACN,oBAAoB,IAAI,OAAO,QAAQ,IAAI;CAC3C,MAAM,UAAU,IAAI,IAAI,OAAO,OAAO;CAEtC,IAAI,OAAO,UAAU,SAAS,GAAG,QAAQ,IAAI,IAAI,MAAM,aAAa;CACpE,KAAK,MAAM,UAAU,SACnB,IAAI,IAAI,MAAM,QAAQ,MAAM,GAAG,kBAAkB,IAAI,OAAO,MAAM;CAEpE,IAAI,QAAQ,eACV,kBAAkB,GAAG;MAChB,IAAI,QAAQ,IAAI,IAAI,MAAM,aAAa,GAAG;EAC/C,IAAI,+BAAe,IAAI,IAAI,CAAC;EAC5B,IAAI,MAAM,gBAAgB;CAC5B;CACA,IAAI,cAAc;AACpB"}
1
+ {"version":3,"file":"document-change.js","names":[],"sources":["../../../src/editor/history/document-change.ts"],"sourcesContent":["import { compact, isEqual, uniq, xor } from 'es-toolkit'\n\nimport type {\n FigmaSourcePayload,\n SceneGraph,\n SceneNode,\n SourceMetadata,\n Variable,\n VariableCollection\n} from '@pairdraw/scene-graph'\nimport { withLiveComments } from '@pairdraw/scene-graph/comments'\nimport { cloneInstanceOverrideState } from '@pairdraw/scene-graph/instances/overrides'\nimport {\n createSceneMutationImpact,\n recordSceneMutations\n} from '@pairdraw/scene-graph/mutation-impact'\n\nimport type { EditorContext } from '#core/editor/types'\nimport { computeAllLayouts } from '#core/layout'\n\nimport { diffFields, type FieldChanges } from './diff'\n\ntype Side = 'before' | 'after'\n\n/**\n * The fields an edit changed on a layer that exists on both sides. Source metadata is compared\n * a level down and its `.fig` payload a level below that, so marking a field edited keeps that\n * change rather than the layer's whole `.fig` record.\n */\ninterface LayerUpdate {\n id: string\n fields: FieldChanges<SceneNode> | null\n source: FieldChanges<SourceMetadata> | null\n fig: FieldChanges<FigmaSourcePayload> | null\n}\n\n/** A parent's children in one state, listed parents first. */\ninterface ChildList {\n id: string\n childIds: string[]\n}\n\n/** A variable or collection on each side of an edit; `null` on the side it does not exist. */\ninterface RecordChange<T> {\n id: string\n before: T | null\n after: T | null\n}\n\n/**\n * What one edit did to the document: copies of only the layers, variables, and collections it\n * created, deleted, or changed, on any page, so an undo step costs what the edit touched rather\n * than a copy of the document. Comments on the document node are left out, as undo never takes\n * them back.\n */\nexport interface DocumentChange {\n /** The page the edit ran on, which a review of it shows. */\n pageId: string\n /** Pages whose layers the edit changed, laid out again when it is undone or redone. */\n pageIds: string[]\n /** Layers as the edit left them, parents first. */\n created: SceneNode[]\n /** Layers as they were before the edit removed them, parents first. */\n deleted: SceneNode[]\n /** Fields the edit changed on layers that exist in both states, children aside. */\n updated: LayerUpdate[]\n /** Child lists that differ between the states, each side's parents first. */\n children: Record<Side, ChildList[]>\n variables: RecordChange<Variable>[]\n collections: RecordChange<VariableCollection>[]\n}\n\n/** Layers by id: the live graph's, or those captured before the edit. */\ntype Lookup = Pick<ReadonlyMap<string, SceneNode>, 'get' | 'size'>\n\nconst NESTED_FIELDS: ReadonlySet<keyof SceneNode> = new Set(['childIds', 'parentId', 'source'])\nconst SOURCE_PAYLOAD: ReadonlySet<keyof SourceMetadata> = new Set(['fig'])\n\nfunction diffLayer(id: string, previous: SceneNode, current: SceneNode): LayerUpdate | null {\n const update: LayerUpdate = {\n id,\n fields: diffFields(id, previous, current, NESTED_FIELDS),\n source: diffFields(id, previous.source, current.source, SOURCE_PAYLOAD),\n fig: diffFields(id, previous.source.fig, current.source.fig)\n }\n return update.fields || update.source || update.fig ? update : null\n}\n\nfunction withChanges<T extends object>(value: T, changes: FieldChanges<T> | null, side: Side): T {\n if (!changes) return value\n const result = { ...value, ...structuredClone(changes[side]) }\n for (const key of changes.absent[side]) Reflect.deleteProperty(result, key)\n return result\n}\n\n/**\n * `editedFields` marking plugin data edited as `live` does. The mark makes `.fig` export write\n * the document node's comments, so it follows them rather than undo.\n */\nfunction markedLike(editedFields: string[], live: SceneNode): string[] {\n const marked = live.source.editedFields.includes('pluginData')\n if (editedFields.includes('pluginData') === marked) return editedFields\n return marked\n ? [...editedFields, 'pluginData']\n : editedFields.filter((field) => field !== 'pluginData')\n}\n\n/** The document node holding the comments of `live`, as undo never takes them back. */\nfunction withCommentsOf(root: SceneNode, live: SceneNode): SceneNode {\n return {\n ...root,\n pluginData: withLiveComments(root.pluginData, live.pluginData),\n source: { ...root.source, editedFields: markedLike(root.source.editedFields, live) }\n }\n}\n\nfunction restoreLayer(graph: SceneGraph, update: LayerUpdate, side: Side): void {\n const node = graph.getNode(update.id)\n if (!node) return\n const changes: Partial<SceneNode> = update.fields ? structuredClone(update.fields[side]) : {}\n if (update.source || update.fig) {\n changes.source = {\n ...withChanges(node.source, update.source, side),\n fig: withChanges(node.source.fig, update.fig, side)\n }\n }\n if (node.id === graph.rootId) {\n if (changes.pluginData)\n changes.pluginData = withLiveComments(changes.pluginData, node.pluginData)\n if (changes.source) {\n changes.source.editedFields = markedLike(changes.source.editedFields, node)\n }\n }\n graph.restoreNodeProperties(update.id, changes, update.fields?.absent[side] ?? [])\n}\n\n/**\n * A copy that keeps the layer's values as they are now. Values are replaced, never written into\n * (`materialize-instance.ts` in `@pairdraw/fig`), so sharing them is safe; the graph edits\n * child lists, source metadata, and override maps in place, so those are copied.\n */\nfunction captureNode(node: SceneNode): SceneNode {\n const { source, instanceOverrides } = node\n return {\n ...node,\n childIds: [...node.childIds],\n source: { ...source, fig: { ...source.fig, rawNodeFields: { ...source.fig.rawNodeFields } } },\n instanceOverrides: cloneInstanceOverrideState(instanceOverrides)\n }\n}\n\n/** Copies a page's layers not copied yet; a layer moved in from another page keeps its copy. */\nfunction capturePage(graph: SceneGraph, pageId: string, captured: Map<string, SceneNode>): void {\n const stack = [pageId]\n for (let id = stack.pop(); id !== undefined; id = stack.pop()) {\n const node = graph.getNode(id)\n if (!node) continue\n if (!captured.has(id)) captured.set(id, captureNode(node))\n stack.push(...node.childIds)\n }\n}\n\n/**\n * A layer and its ancestors, nearest first. Like `SceneGraph.closest`, the walk visits at most as\n * many layers as there are, so a parent cycle in bad data cannot hang it.\n */\nfunction* lineage(nodes: Lookup, id: string): Generator<SceneNode> {\n let node = nodes.get(id)\n for (let steps = 0; node && steps < nodes.size; steps++) {\n yield node\n node = node.parentId ? nodes.get(node.parentId) : undefined\n }\n}\n\nfunction pageOf(nodes: Lookup, id: string): string | null {\n for (const node of lineage(nodes, id)) if (node.type === 'CANVAS') return node.id\n return null\n}\n\nfunction depthIn(nodes: Lookup, id: string): number {\n let depth = 0\n for (const node of lineage(nodes, id)) if (node.parentId) depth++\n return depth\n}\n\n/** Adds one touched layer to the change, given its state on each side, if it has one. */\nfunction recordLayer(\n change: DocumentChange,\n id: string,\n previous: SceneNode | undefined,\n current: SceneNode | undefined\n): void {\n if (previous && !isEqual(previous.childIds, current?.childIds ?? [])) {\n change.children.before.push({ id, childIds: previous.childIds })\n }\n if (current && !isEqual(current.childIds, previous?.childIds ?? [])) {\n change.children.after.push({ id, childIds: [...current.childIds] })\n }\n if (!previous) {\n if (current) change.created.push(structuredClone(current))\n } else if (!current) {\n change.deleted.push(structuredClone(previous))\n } else {\n const update = diffLayer(id, previous, current)\n if (update) change.updated.push(update)\n }\n}\n\nfunction diffRecords<T>(previous: Map<string, T>, current: Map<string, T>): RecordChange<T>[] {\n const ids = new Set([...previous.keys(), ...current.keys()])\n return [...ids].flatMap((id) => {\n const before = previous.get(id) ?? null\n const after = current.get(id) ?? null\n return isEqual(before, after) ? [] : [{ id, before, after: structuredClone(after) }]\n })\n}\n\n/** Restores records in place where they exist, as views may hold them, as atomic tools do. */\n/** Make `target` hold `value` under `id`, or nothing; an existing record is kept and rewritten. */\nexport function writeRecord<T extends object>(\n target: Map<string, T>,\n id: string,\n value: T | null\n): void {\n const existing = target.get(id)\n if (!value) {\n target.delete(id)\n } else if (existing) {\n for (const key of Object.keys(existing)) {\n if (!Object.hasOwn(value, key)) Reflect.deleteProperty(existing, key)\n }\n Object.assign(existing, structuredClone(value))\n } else {\n target.set(id, structuredClone(value))\n }\n}\n\nfunction restoreRecords<T extends object>(\n target: Map<string, T>,\n changes: RecordChange<T>[],\n side: Side\n): void {\n for (const change of changes) writeRecord(target, change.id, change[side])\n}\n\n/**\n * Starts recording an edit made from `pageId`. Call the returned function once the edit is\n * done, also when it failed, to stop recording and get what the edit changed.\n *\n * The page is copied up front, so values written into its layers in place are kept too. Another\n * page, or the document node, is copied the first time the edit is about to change it.\n */\nexport function captureDocumentChange(graph: SceneGraph, pageId: string): () => DocumentChange {\n const captured = new Map<string, SceneNode>()\n const capturedPages = new Set([pageId])\n const created = new Set<string>()\n capturePage(graph, pageId, captured)\n const variables = structuredClone(graph.variables)\n const collections = structuredClone(graph.variableCollections)\n const impact = createSceneMutationImpact()\n const unbindEvents = recordSceneMutations(graph, impact)\n const unobserve = graph.observeNodeChanges({\n created: (node) => created.add(node.id),\n before: (node) => {\n if (captured.has(node.id) || created.has(node.id)) return\n const page = pageOf(graph.nodes, node.id)\n if (page && !capturedPages.has(page)) {\n capturedPages.add(page)\n capturePage(graph, page, captured)\n }\n if (!captured.has(node.id)) captured.set(node.id, captureNode(node))\n }\n })\n\n return () => {\n unobserve()\n unbindEvents()\n const change: DocumentChange = {\n pageId,\n pageIds: [],\n created: [],\n deleted: [],\n updated: [],\n children: { before: [], after: [] },\n variables: diffRecords(variables, graph.variables),\n collections: diffRecords(collections, graph.variableCollections)\n }\n const pageIds = new Set<string>()\n const touched = new Set([\n ...impact.changedNodeIds,\n ...impact.previousParentIds,\n ...impact.currentParentIds\n ])\n for (const id of touched) {\n const previous = captured.get(id)\n // A layer changed without telling observers has no state to go back to.\n if (!previous && !created.has(id)) continue\n const current = graph.getNode(id)\n // Comments are never part of an undo step.\n const kept =\n previous && current && id === graph.rootId ? withCommentsOf(previous, current) : previous\n recordLayer(change, id, kept, current)\n for (const page of [pageOf(captured, id), pageOf(graph.nodes, id)])\n if (page) pageIds.add(page)\n }\n change.pageIds = [...pageIds]\n const byDepth = (nodes: Lookup) => (a: { id: string }, b: { id: string }) =>\n depthIn(nodes, a.id) - depthIn(nodes, b.id)\n change.created.sort(byDepth(graph.nodes))\n change.children.after.sort(byDepth(graph.nodes))\n change.deleted.sort(byDepth(captured))\n change.children.before.sort(byDepth(captured))\n return change\n }\n}\n\n/** Where a layer sits: its page and the page's child holding it, null for a page or the root. */\ninterface Placement {\n pageId: string | null\n layerId: string | null\n}\n\n/** `undefined` when the layer's parents cannot be followed to a page or the root. */\nfunction placement(nodes: Lookup, id: string): Placement | undefined {\n let child: SceneNode | null = null\n for (const node of lineage(nodes, id)) {\n if (node.type === 'CANVAS') return { pageId: node.id, layerId: child?.id ?? null }\n if (!node.parentId) return { pageId: null, layerId: null }\n child = node\n }\n return undefined\n}\n\n/**\n * Layers as they were before the edit, read from the live graph: removed ones from their copies,\n * and moved ones under the parent whose old child list held them.\n */\nfunction layersBefore(graph: SceneGraph, change: DocumentChange): Lookup {\n const created = new Set(change.created.map((node) => node.id))\n const deleted = new Map(change.deleted.map((node) => [node.id, node]))\n const parents = new Map<string, string>()\n for (const { id, childIds } of change.children.before) {\n for (const childId of childIds) parents.set(childId, id)\n }\n return {\n size: graph.nodes.size + deleted.size,\n get(id) {\n if (created.has(id)) return undefined\n const node = deleted.get(id) ?? graph.getNode(id)\n const parentId = parents.get(id)\n return node && parentId !== undefined && parentId !== node.parentId\n ? { ...node, parentId }\n : node\n }\n }\n}\n\n/** Layers the edit created, removed, changed, or moved, and the parents whose children changed. */\nfunction touchedLayerIds(change: DocumentChange): string[] {\n const lists = (side: Side) =>\n new Map(change.children[side].map(({ id, childIds }) => [id, childIds]))\n const before = lists('before')\n const after = lists('after')\n // A reorder changes only its parent; a move also touches the layers that came or went.\n const moved = uniq([...before.keys(), ...after.keys()]).flatMap((id) => [\n id,\n ...xor(before.get(id) ?? [], after.get(id) ?? [])\n ])\n return uniq([\n ...change.created.map((node) => node.id),\n ...change.deleted.map((node) => node.id),\n ...change.updated.map((update) => update.id),\n ...moved\n ])\n}\n\n/** The ends of the connectors in the graph or removed by the edit, on either side of it. */\nfunction connectorEnds(graph: SceneGraph, change: DocumentChange): Map<string, string[]> {\n const ends = new Map<string, string[]>()\n const add = (id: string, nodes: Partial<SceneNode>[]) => {\n const nodeIds = nodes.flatMap((node) => [\n node.connectorStart?.nodeId,\n node.connectorEnd?.nodeId\n ])\n ends.set(id, uniq([...(ends.get(id) ?? []), ...compact(nodeIds)]))\n }\n for (const id of graph.connectorIds) add(id, compact([graph.getNode(id)]))\n for (const node of change.deleted) if (node.type === 'CONNECTOR') add(node.id, [node])\n for (const update of change.updated) {\n if (update.fields && ends.has(update.id)) add(update.id, [update.fields.before])\n }\n return ends\n}\n\n/**\n * The page children holding what an edit touched, on either side of it, for diffing and drawing\n * just those instead of whole pages (`graphsFromDocumentChange`). A layer whose connector draws\n * to a layer elsewhere brings that layer too, as JSX writes the end by it. `null` when part of\n * the page cannot be told apart this way: the edit changed variables, which any layer may show,\n * moved a layer to another page, or left a layer whose parents cannot be followed.\n */\nexport function touchedTopLevelIds(graph: SceneGraph, change: DocumentChange): string[] | null {\n if (change.variables.length > 0 || change.collections.length > 0) return null\n const before = layersBefore(graph, change)\n const sides = [before, graph.nodes]\n const holders = (id: string): (string | null)[] | null => {\n const placements = sides.map((nodes) => (nodes.get(id) ? placement(nodes, id) : null))\n if (placements.includes(undefined)) return null\n const [was, is] = placements\n if (was?.pageId && is?.pageId && was.pageId !== is.pageId) return null\n return placements.map((place) => place?.layerId ?? null)\n }\n const layers = new Set<string>()\n for (const id of touchedLayerIds(change)) {\n const held = holders(id)\n if (!held) return null\n for (const layerId of compact(held)) layers.add(layerId)\n }\n const ends = connectorEnds(graph, change)\n for (let grew = true; grew;) {\n grew = false\n for (const [connectorId, endIds] of ends) {\n if (!holders(connectorId)?.some((layerId) => layerId && layers.has(layerId))) continue\n for (const layerId of compact(endIds.flatMap((id) => holders(id) ?? []))) {\n grew ||= !layers.has(layerId)\n layers.add(layerId)\n }\n }\n }\n return [...layers]\n}\n\nexport function isEmptyDocumentChange(change: DocumentChange): boolean {\n return (\n change.created.length === 0 &&\n change.deleted.length === 0 &&\n change.updated.length === 0 &&\n change.children.before.length === 0 &&\n change.children.after.length === 0 &&\n change.variables.length === 0 &&\n change.collections.length === 0\n )\n}\n\n/**\n * Puts what an edit touched back as it was on one side of it. The graph must be as the other\n * side left it; what the edit did not touch is left alone, and so are comments. A graph that\n * holds only part of the document, such as one page, gets the part of the change it has room\n * for.\n */\nexport function applyDocumentChange(graph: SceneGraph, change: DocumentChange, side: Side): void {\n const restored = side === 'before' ? change.deleted : change.created\n const removed = side === 'before' ? change.created : change.deleted\n restoreRecords(graph.variableCollections, change.collections, side)\n restoreRecords(graph.variables, change.variables, side)\n graph.preserveSourceMetadataDuring(() => {\n for (const node of restored) {\n const { parentId, childIds: _childIds, ...fields } = structuredClone(node)\n if (!parentId || !graph.getNode(parentId)) continue\n graph.createNode(node.type, parentId, { ...fields, childIds: [] })\n }\n // Parents come first, so a layer never moves under one of its own descendants.\n for (const { id, childIds } of change.children[side]) {\n for (const [index, childId] of childIds.entries()) {\n if (graph.getNode(id)?.childIds[index] !== childId) graph.insertChildAt(childId, id, index)\n }\n }\n // Layers that survive have moved out of the removed ones by now.\n for (const node of removed) graph.deleteNode(node.id)\n for (const update of change.updated) restoreLayer(graph, update, side)\n })\n graph.clearAbsPosCache()\n}\n\n/** Drops the selected and hovered layers that no longer exist, and keeps the rest. */\nfunction keepLiveSelection(ctx: EditorContext): void {\n const live = [...ctx.state.selectedIds].filter((id) => ctx.graph.getNode(id))\n if (live.length !== ctx.state.selectedIds.size) ctx.setSelectedIds(new Set(live))\n const hovered = ctx.state.hoveredNodeId\n if (hovered !== null && !ctx.graph.getNode(hovered)) ctx.state.hoveredNodeId = null\n}\n\n/**\n * Undoes or redoes an edit in the editor, whichever page is on screen. Undo and redo clear the\n * selection on that page; `keepSelection`, for an edit put back that the person did not ask to\n * undo, keeps the selected layers that still exist.\n */\nexport function restoreDocumentChange(\n ctx: EditorContext,\n change: DocumentChange,\n side: Side,\n options: { keepSelection?: boolean } = {}\n): void {\n applyDocumentChange(ctx.graph, change, side)\n const pageIds = new Set(change.pageIds)\n // Bound values follow their variables, so the page on screen is laid out again.\n if (change.variables.length > 0) pageIds.add(ctx.state.currentPageId)\n for (const pageId of pageIds) {\n if (ctx.graph.getNode(pageId)) computeAllLayouts(ctx.graph, pageId)\n }\n if (options.keepSelection) {\n keepLiveSelection(ctx)\n } else if (pageIds.has(ctx.state.currentPageId)) {\n ctx.setSelectedIds(new Set())\n ctx.state.hoveredNodeId = null\n }\n ctx.requestRender()\n}\n"],"mappings":";;;;;;;AA2EA,MAAM,gCAA8C,IAAI,IAAI;CAAC;CAAY;CAAY;AAAQ,CAAC;AAC9F,MAAM,iCAAoD,IAAI,IAAI,CAAC,KAAK,CAAC;AAEzE,SAAS,UAAU,IAAY,UAAqB,SAAwC;CAC1F,MAAM,SAAsB;EAC1B;EACA,QAAQ,WAAW,IAAI,UAAU,SAAS,aAAa;EACvD,QAAQ,WAAW,IAAI,SAAS,QAAQ,QAAQ,QAAQ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Snapshot } from "./page.js";
3
3
  import { SceneGraph } from "@pairdraw/scene-graph";
4
4
  //#region src/editor/history/snapshot/graph.d.ts
5
+ /** The variables and collections a copy reads, which copies of one state may share. */
6
+ type VariableTables = Pick<SceneGraph, 'variables' | 'variableCollections'>;
5
7
  /**
6
8
  * A standalone copy of the document whose snapshot page is as it was when taken, so a past
7
9
  * state can be rendered or diffed next to the live one. Other pages are left empty.
@@ -10,9 +12,19 @@ declare function graphFromPageSnapshot(source: SceneGraph, snapshot: PageSnapsho
10
12
  /**
11
13
  * A standalone copy of the document with the pages a change touched, and the page it ran on, on
12
14
  * one side of the change. The source must be as the change left it, as it is right after the
13
- * edit. Other pages are left empty.
15
+ * edit. Other pages are left empty. `layerIds`, from `touchedTopLevelIds`, keeps only those page
16
+ * children, each whole, with what they depend on; `tables` are variables the copy reads instead
17
+ * of its own copy of them.
14
18
  */
15
- declare function graphFromDocumentChange(source: SceneGraph, change: DocumentChange, side: 'before' | 'after'): SceneGraph | null;
19
+ declare function graphFromDocumentChange(source: SceneGraph, change: DocumentChange, side: 'before' | 'after', layerIds?: readonly string[], tables?: VariableTables): SceneGraph | null;
20
+ /**
21
+ * Both sides of a change as `graphFromDocumentChange` builds them. When the change left the
22
+ * variables alone, the two copies share one copy of them; neither may change it.
23
+ */
24
+ declare function graphsFromDocumentChange(source: SceneGraph, change: DocumentChange, layerIds?: readonly string[]): {
25
+ before: SceneGraph;
26
+ after: SceneGraph;
27
+ } | null;
16
28
  //#endregion
17
- export { graphFromDocumentChange, graphFromPageSnapshot };
29
+ export { graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange };
18
30
  //# sourceMappingURL=graph.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph.d.ts","names":[],"sources":["../../../../src/editor/history/snapshot/graph.ts"],"mappings":";;;;;;;;iBAqBgB,sBACd,QAAQ,YACR,UAAU,eACT;;;;;;iBAiBa,wBACd,QAAQ,YACR,QAAQ,gBACR,2BACC"}
1
+ {"version":3,"file":"graph.d.ts","names":[],"sources":["../../../../src/editor/history/snapshot/graph.ts"],"mappings":";;;;;KAUK,iBAAiB,KAAK;;;;;iBA0BX,sBACd,QAAQ,YACR,UAAU,eACT;;;;;;;;iBAmBa,wBACd,QAAQ,YACR,QAAQ,gBACR,0BACA,8BACA,SAAS,iBACR;;;;;iBAoBa,yBACd,QAAQ,YACR,QAAQ,gBACR;EACG,QAAQ;EAAY,OAAO"}
@@ -2,11 +2,17 @@ import { extractPageContext } from "../../../io/subgraph.js";
2
2
  import { applyDocumentChange } from "../document-change.js";
3
3
  import { uniq } from "es-toolkit/array";
4
4
  //#region src/editor/history/snapshot/graph.ts
5
- function pageContext(source, pageId, nodeIds) {
6
- const graph = extractPageContext(source, pageId, nodeIds);
5
+ function copyVariableTables(source) {
6
+ return {
7
+ variables: structuredClone(source.variables),
8
+ variableCollections: structuredClone(source.variableCollections)
9
+ };
10
+ }
11
+ function pageContext(source, pageIds, nodeIds, tables = copyVariableTables(source)) {
12
+ const graph = extractPageContext(source, pageIds, nodeIds);
7
13
  graph.images = new Map(source.images);
8
- graph.variables = structuredClone(source.variables);
9
- graph.variableCollections = structuredClone(source.variableCollections);
14
+ graph.variables = tables.variables;
15
+ graph.variableCollections = tables.variableCollections;
10
16
  return graph;
11
17
  }
12
18
  /**
@@ -26,18 +32,33 @@ function graphFromPageSnapshot(source, snapshot) {
26
32
  /**
27
33
  * A standalone copy of the document with the pages a change touched, and the page it ran on, on
28
34
  * one side of the change. The source must be as the change left it, as it is right after the
29
- * edit. Other pages are left empty.
35
+ * edit. Other pages are left empty. `layerIds`, from `touchedTopLevelIds`, keeps only those page
36
+ * children, each whole, with what they depend on; `tables` are variables the copy reads instead
37
+ * of its own copy of them.
30
38
  */
31
- function graphFromDocumentChange(source, change, side) {
39
+ function graphFromDocumentChange(source, change, side, layerIds, tables) {
32
40
  const pageIds = uniq([change.pageId, ...change.pageIds]).filter((id) => source.getNode(id));
33
41
  const host = pageIds[0] ?? source.getPages()[0]?.id;
34
42
  if (!host) return null;
35
- const graph = pageContext(source, host, pageIds);
43
+ const graph = layerIds ? pageContext(source, pageIds.length > 0 ? pageIds : host, layerIds, tables) : pageContext(source, host, pageIds, tables);
36
44
  if (side === "before") applyDocumentChange(graph, change, "before");
37
45
  graph.clearAbsPosCache();
38
46
  return graph;
39
47
  }
48
+ /**
49
+ * Both sides of a change as `graphFromDocumentChange` builds them. When the change left the
50
+ * variables alone, the two copies share one copy of them; neither may change it.
51
+ */
52
+ function graphsFromDocumentChange(source, change, layerIds) {
53
+ const shared = change.variables.length === 0 && change.collections.length === 0 ? copyVariableTables(source) : void 0;
54
+ const before = graphFromDocumentChange(source, change, "before", layerIds, shared);
55
+ const after = graphFromDocumentChange(source, change, "after", layerIds, shared);
56
+ return before && after ? {
57
+ before,
58
+ after
59
+ } : null;
60
+ }
40
61
  //#endregion
41
- export { graphFromDocumentChange, graphFromPageSnapshot };
62
+ export { graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange };
42
63
 
43
64
  //# sourceMappingURL=graph.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"graph.js","names":[],"sources":["../../../../src/editor/history/snapshot/graph.ts"],"sourcesContent":["import { uniq } from 'es-toolkit/array'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { applyDocumentChange, type DocumentChange } from '#core/editor/history/document-change'\nimport { extractPageContext } from '#core/io/subgraph'\n\nimport type { PageSnapshot } from './page'\n\nfunction pageContext(source: SceneGraph, pageId: string, nodeIds: string[]): SceneGraph {\n const graph = extractPageContext(source, pageId, nodeIds)\n graph.images = new Map(source.images)\n graph.variables = structuredClone(source.variables)\n graph.variableCollections = structuredClone(source.variableCollections)\n return graph\n}\n\n/**\n * A standalone copy of the document whose snapshot page is as it was when taken, so a past\n * state can be rendered or diffed next to the live one. Other pages are left empty.\n */\nexport function graphFromPageSnapshot(\n source: SceneGraph,\n snapshot: PageSnapshot\n): SceneGraph | null {\n // `snapshotPage` records the page first.\n const page = snapshot.nodes.values().next().value\n if (!page || !source.getNode(page.id)) return null\n const graph = pageContext(source, page.id, [])\n graph.variables = structuredClone(snapshot.variables)\n graph.variableCollections = structuredClone(snapshot.collections)\n for (const node of snapshot.nodes.values()) graph.nodes.set(node.id, structuredClone(node))\n graph.clearAbsPosCache()\n return graph\n}\n\n/**\n * A standalone copy of the document with the pages a change touched, and the page it ran on, on\n * one side of the change. The source must be as the change left it, as it is right after the\n * edit. Other pages are left empty.\n */\nexport function graphFromDocumentChange(\n source: SceneGraph,\n change: DocumentChange,\n side: 'before' | 'after'\n): SceneGraph | null {\n // A page's own id brings its whole subtree; a layer moved between pages can then move back.\n const pageIds = uniq([change.pageId, ...change.pageIds]).filter((id) => source.getNode(id))\n // A change that removed every page it touched still needs one to build on; the past side\n // brings the removed ones back.\n const host = pageIds[0] ?? source.getPages()[0]?.id\n if (!host) return null\n const graph = pageContext(source, host, pageIds)\n if (side === 'before') applyDocumentChange(graph, change, 'before')\n graph.clearAbsPosCache()\n return graph\n}\n"],"mappings":";;;;AASA,SAAS,YAAY,QAAoB,QAAgB,SAA+B;CACtF,MAAM,QAAQ,mBAAmB,QAAQ,QAAQ,OAAO;CACxD,MAAM,SAAS,IAAI,IAAI,OAAO,MAAM;CACpC,MAAM,YAAY,gBAAgB,OAAO,SAAS;CAClD,MAAM,sBAAsB,gBAAgB,OAAO,mBAAmB;CACtE,OAAO;AACT;;;;;AAMA,SAAgB,sBACd,QACA,UACmB;CAEnB,MAAM,OAAO,SAAS,MAAM,OAAO,CAAC,CAAC,KAAK,CAAC,CAAC;CAC5C,IAAI,CAAC,QAAQ,CAAC,OAAO,QAAQ,KAAK,EAAE,GAAG,OAAO;CAC9C,MAAM,QAAQ,YAAY,QAAQ,KAAK,IAAI,CAAC,CAAC;CAC7C,MAAM,YAAY,gBAAgB,SAAS,SAAS;CACpD,MAAM,sBAAsB,gBAAgB,SAAS,WAAW;CAChE,KAAK,MAAM,QAAQ,SAAS,MAAM,OAAO,GAAG,MAAM,MAAM,IAAI,KAAK,IAAI,gBAAgB,IAAI,CAAC;CAC1F,MAAM,iBAAiB;CACvB,OAAO;AACT;;;;;;AAOA,SAAgB,wBACd,QACA,QACA,MACmB;CAEnB,MAAM,UAAU,KAAK,CAAC,OAAO,QAAQ,GAAG,OAAO,OAAO,CAAC,CAAC,CAAC,QAAQ,OAAO,OAAO,QAAQ,EAAE,CAAC;CAG1F,MAAM,OAAO,QAAQ,MAAM,OAAO,SAAS,CAAC,CAAC,EAAE,EAAE;CACjD,IAAI,CAAC,MAAM,OAAO;CAClB,MAAM,QAAQ,YAAY,QAAQ,MAAM,OAAO;CAC/C,IAAI,SAAS,UAAU,oBAAoB,OAAO,QAAQ,QAAQ;CAClE,MAAM,iBAAiB;CACvB,OAAO;AACT"}
1
+ {"version":3,"file":"graph.js","names":[],"sources":["../../../../src/editor/history/snapshot/graph.ts"],"sourcesContent":["import { uniq } from 'es-toolkit/array'\n\nimport type { SceneGraph } from '@pairdraw/scene-graph'\n\nimport { applyDocumentChange, type DocumentChange } from '#core/editor/history/document-change'\nimport { extractPageContext } from '#core/io/subgraph'\n\nimport type { PageSnapshot } from './page'\n\n/** The variables and collections a copy reads, which copies of one state may share. */\ntype VariableTables = Pick<SceneGraph, 'variables' | 'variableCollections'>\n\nfunction copyVariableTables(source: SceneGraph): VariableTables {\n return {\n variables: structuredClone(source.variables),\n variableCollections: structuredClone(source.variableCollections)\n }\n}\n\nfunction pageContext(\n source: SceneGraph,\n pageIds: string | readonly string[],\n nodeIds: readonly string[],\n tables: VariableTables = copyVariableTables(source)\n): SceneGraph {\n const graph = extractPageContext(source, pageIds, nodeIds)\n graph.images = new Map(source.images)\n graph.variables = tables.variables\n graph.variableCollections = tables.variableCollections\n return graph\n}\n\n/**\n * A standalone copy of the document whose snapshot page is as it was when taken, so a past\n * state can be rendered or diffed next to the live one. Other pages are left empty.\n */\nexport function graphFromPageSnapshot(\n source: SceneGraph,\n snapshot: PageSnapshot\n): SceneGraph | null {\n // `snapshotPage` records the page first.\n const page = snapshot.nodes.values().next().value\n if (!page || !source.getNode(page.id)) return null\n const graph = pageContext(source, page.id, [])\n graph.variables = structuredClone(snapshot.variables)\n graph.variableCollections = structuredClone(snapshot.collections)\n for (const node of snapshot.nodes.values()) graph.nodes.set(node.id, structuredClone(node))\n graph.clearAbsPosCache()\n return graph\n}\n\n/**\n * A standalone copy of the document with the pages a change touched, and the page it ran on, on\n * one side of the change. The source must be as the change left it, as it is right after the\n * edit. Other pages are left empty. `layerIds`, from `touchedTopLevelIds`, keeps only those page\n * children, each whole, with what they depend on; `tables` are variables the copy reads instead\n * of its own copy of them.\n */\nexport function graphFromDocumentChange(\n source: SceneGraph,\n change: DocumentChange,\n side: 'before' | 'after',\n layerIds?: readonly string[],\n tables?: VariableTables\n): SceneGraph | null {\n const pageIds = uniq([change.pageId, ...change.pageIds]).filter((id) => source.getNode(id))\n // A change that removed every page it touched still needs one to build on; the past side\n // brings the removed ones back.\n const host = pageIds[0] ?? source.getPages()[0]?.id\n if (!host) return null\n // A page's own id brings its whole subtree, so a layer moved between pages can move back;\n // with `layerIds`, the pages hold only those layers.\n const graph = layerIds\n ? pageContext(source, pageIds.length > 0 ? pageIds : host, layerIds, tables)\n : pageContext(source, host, pageIds, tables)\n if (side === 'before') applyDocumentChange(graph, change, 'before')\n graph.clearAbsPosCache()\n return graph\n}\n\n/**\n * Both sides of a change as `graphFromDocumentChange` builds them. When the change left the\n * variables alone, the two copies share one copy of them; neither may change it.\n */\nexport function graphsFromDocumentChange(\n source: SceneGraph,\n change: DocumentChange,\n layerIds?: readonly string[]\n): { before: SceneGraph; after: SceneGraph } | null {\n const shared =\n change.variables.length === 0 && change.collections.length === 0\n ? copyVariableTables(source)\n : undefined\n const before = graphFromDocumentChange(source, change, 'before', layerIds, shared)\n const after = graphFromDocumentChange(source, change, 'after', layerIds, shared)\n return before && after ? { before, after } : null\n}\n"],"mappings":";;;;AAYA,SAAS,mBAAmB,QAAoC;CAC9D,OAAO;EAC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SAAgB,yBACd,QACA,QACA,UACkD;CAClD,MAAM,SACJ,OAAO,UAAU,WAAW,KAAK,OAAO,YAAY,WAAW,IAC3D,mBAAmB,MAAM,IACzB,KAAA;CACN,MAAM,SAAS,wBAAwB,QAAQ,QAAQ,UAAU,UAAU,MAAM;CACjF,MAAM,QAAQ,wBAAwB,QAAQ,QAAQ,SAAS,UAAU,MAAM;CAC/E,OAAO,UAAU,QAAQ;EAAE;EAAQ;CAAM,IAAI;AAC/C"}
@@ -13,7 +13,7 @@ import { createDocumentGraph } from "./document-settings.js";
13
13
  import { createDefaultEditorSharedState } from "./state/shared.js";
14
14
  import { editedGradient, editedGradientLayout } from "./gradient-edit.js";
15
15
  import { EditedImage, ImageEditModifiers, editableImageFillIndex, editedImage, editedImageLayout, imageEditChanges, imageEditCrops } from "./image-edit.js";
16
- import { DocumentChange, isEmptyDocumentChange } from "./history/document-change.js";
16
+ import { DocumentChange, isEmptyDocumentChange, touchedTopLevelIds } from "./history/document-change.js";
17
17
  import { RecordEditOptions } from "./history/edit.js";
18
18
  import { PageSnapshot } from "./history/snapshot/page.js";
19
19
  import { MovePlace } from "./undo.js";
@@ -37,7 +37,7 @@ import { createDefaultEditorState } from "./state/index.js";
37
37
  import { Editor, createEditor } from "./create.js";
38
38
  import { syncEditedComponents } from "./component-sync.js";
39
39
  import { executeAtomicTool } from "./history/atomic-tool.js";
40
- import { graphFromDocumentChange, graphFromPageSnapshot } from "./history/snapshot/graph.js";
40
+ import { graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange } from "./history/snapshot/graph.js";
41
41
  import { pastedPropertyChanges } from "./clipboard/paste/properties.js";
42
42
  import { resolvePasteTarget } from "./clipboard/paste/target.js";
43
43
  import { playIslandRoots } from "./play/islands.js";
@@ -54,4 +54,4 @@ import { LayerType, layerTypeOptions } from "./structure/layer-type.js";
54
54
  import { BOARD_TOOLS, BOARD_TOOL_SHORTCUTS, EDITOR_TOOLS, EditorToolDef, TOOL_SHORTCUTS } from "./tool-registry.js";
55
55
  import { newLayerDefaults } from "./shapes/defaults.js";
56
56
  import { RenameSelectionOptions, RenameSelectionPreview } from "./structure/rename.js";
57
- export { type AttachModifiers, BOARD_TOOLS, BOARD_TOOL_SHORTCUTS, type CanvasView, type ClipboardCollectionDependency, type ClipboardConflictResolution, type ClipboardImageResolution, type ClipboardImportChoice, type ClipboardImportPlan, type ClipboardPayload, type ClipboardSnapshot, type ClipboardStyleDependency, type CopyOptions, DEFAULT_SCALE_ANCHOR, DEFAULT_SNAPPING_PREFERENCES, type DocumentChange, EDITOR_TOOLS, EDIT_VIEW, type EditedImage, type Editor, type EditorContext, type EditorEventName, type EditorEvents, type EditorOptions, type EditorProfile, type EditorProfileInputs, type EditorRestrictions, type EditorSharedState, type EditorState, type EditorToolDef, type EditorViewState, type ExposableComponentField, type FigmaClipboardImageResolver, type GradientEdit, type HyperlinkHit, type ImageEdit, type ImageEditModifiers, type InstanceState, type LayerType, type MovePlace, type NodeEditCapability, type NodePreview, type PageSnapshot, type PageSwitchProgress, type PreparePageOptions, type PreparedPage, type PresentationScale, type PresentationState, ReadOnlyDocumentError, ReadOnlyLibraryDefinitionError, type RecordEditOptions, type RenameSelectionOptions, type RenameSelectionPreview, type RescaleSnapshot, type ResumedPath, SCALE_ANCHORS, type ScaleAnchor, type ScaleSession, type SelectionColor, type SelectionSpacing, type ShaderModeState, type ShaderModeTarget, type ShaderPaintList, type ShaderRasterizer, type ShaderView, type ShapeHandleHover, type SlideMoveTarget, type SnappingPreferences, type SwitchPageOptions, TOOL_SHORTCUTS, type TextHyperlinkState, type Tool, type VariableTokenFields, type VariantConflict, type VariantMutationResult, type VariantValidationIssue, assertNodeEditable, clipboardImportHasConflicts, clipboardImportHasDependencies, copyEditorViewState, createDefaultEditorSharedState, createDefaultEditorState, createDefaultEditorViewState, createDocumentGraph, createEditor, createGuideActions, createTextActions, editableImageFillIndex, editedGradient, editedGradientLayout, editedImage, editedImageLayout, executeAtomicTool, findShaderModeTarget, getNodeEditCapability, graphFromDocumentChange, graphFromPageSnapshot, imageEditChanges, imageEditCrops, isEmptyDocumentChange, isScaleAnchor, layerTypeOptions, newLayerDefaults, opacityFromBuffer, pageSlides, parseScaleFactor, pastedPropertyChanges, pickEditorViewState, planClipboardImport, playIslandRoots, presentationViewport, reapplyInstanceComponentProperties, replaceSelectionColor, rescaleNodes, resizedPathTextGlyphs, resolveEditorProfile, resolvePasteTarget, resolvePlayState, scaleAnchorFraction, scaleAnchorPoint, scaleFactorForSize, scaledBounds, selectionColors, selectionColorsShown, slideMoveTarget, syncEditedComponents };
57
+ export { type AttachModifiers, BOARD_TOOLS, BOARD_TOOL_SHORTCUTS, type CanvasView, type ClipboardCollectionDependency, type ClipboardConflictResolution, type ClipboardImageResolution, type ClipboardImportChoice, type ClipboardImportPlan, type ClipboardPayload, type ClipboardSnapshot, type ClipboardStyleDependency, type CopyOptions, DEFAULT_SCALE_ANCHOR, DEFAULT_SNAPPING_PREFERENCES, type DocumentChange, EDITOR_TOOLS, EDIT_VIEW, type EditedImage, type Editor, type EditorContext, type EditorEventName, type EditorEvents, type EditorOptions, type EditorProfile, type EditorProfileInputs, type EditorRestrictions, type EditorSharedState, type EditorState, type EditorToolDef, type EditorViewState, type ExposableComponentField, type FigmaClipboardImageResolver, type GradientEdit, type HyperlinkHit, type ImageEdit, type ImageEditModifiers, type InstanceState, type LayerType, type MovePlace, type NodeEditCapability, type NodePreview, type PageSnapshot, type PageSwitchProgress, type PreparePageOptions, type PreparedPage, type PresentationScale, type PresentationState, ReadOnlyDocumentError, ReadOnlyLibraryDefinitionError, type RecordEditOptions, type RenameSelectionOptions, type RenameSelectionPreview, type RescaleSnapshot, type ResumedPath, SCALE_ANCHORS, type ScaleAnchor, type ScaleSession, type SelectionColor, type SelectionSpacing, type ShaderModeState, type ShaderModeTarget, type ShaderPaintList, type ShaderRasterizer, type ShaderView, type ShapeHandleHover, type SlideMoveTarget, type SnappingPreferences, type SwitchPageOptions, TOOL_SHORTCUTS, type TextHyperlinkState, type Tool, type VariableTokenFields, type VariantConflict, type VariantMutationResult, type VariantValidationIssue, assertNodeEditable, clipboardImportHasConflicts, clipboardImportHasDependencies, copyEditorViewState, createDefaultEditorSharedState, createDefaultEditorState, createDefaultEditorViewState, createDocumentGraph, createEditor, createGuideActions, createTextActions, editableImageFillIndex, editedGradient, editedGradientLayout, editedImage, editedImageLayout, executeAtomicTool, findShaderModeTarget, getNodeEditCapability, graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange, imageEditChanges, imageEditCrops, isEmptyDocumentChange, isScaleAnchor, layerTypeOptions, newLayerDefaults, opacityFromBuffer, pageSlides, parseScaleFactor, pastedPropertyChanges, pickEditorViewState, planClipboardImport, playIslandRoots, presentationViewport, reapplyInstanceComponentProperties, replaceSelectionColor, rescaleNodes, resizedPathTextGlyphs, resolveEditorProfile, resolvePasteTarget, resolvePlayState, scaleAnchorFraction, scaleAnchorPoint, scaleFactorForSize, scaledBounds, selectionColors, selectionColorsShown, slideMoveTarget, syncEditedComponents, touchedTopLevelIds };
@@ -13,7 +13,7 @@ import { createDocumentGraph } from "./document-settings.js";
13
13
  import { createDefaultEditorSharedState } from "./state/shared.js";
14
14
  import { replaceSelectionColor, selectionColors, selectionColorsShown } from "./selection/colors.js";
15
15
  import { copyEditorViewState, createDefaultEditorViewState, pickEditorViewState } from "./state/view.js";
16
- import { isEmptyDocumentChange } from "./history/document-change.js";
16
+ import { isEmptyDocumentChange, touchedTopLevelIds } from "./history/document-change.js";
17
17
  import { resolvePasteTarget } from "./clipboard/paste/target.js";
18
18
  import { clipboardImportHasConflicts, clipboardImportHasDependencies, planClipboardImport } from "./clipboard/conflicts.js";
19
19
  import { reapplyInstanceComponentProperties } from "./components/properties.js";
@@ -30,6 +30,6 @@ import { layerTypeOptions } from "./structure/layer-type.js";
30
30
  import { createTextActions } from "./text.js";
31
31
  import { createEditor } from "./create.js";
32
32
  import { executeAtomicTool } from "./history/atomic-tool.js";
33
- import { graphFromDocumentChange, graphFromPageSnapshot } from "./history/snapshot/graph.js";
33
+ import { graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange } from "./history/snapshot/graph.js";
34
34
  import { resolvePlayState } from "./play/states.js";
35
- export { BOARD_TOOLS, BOARD_TOOL_SHORTCUTS, DEFAULT_SCALE_ANCHOR, DEFAULT_SNAPPING_PREFERENCES, EDITOR_TOOLS, EDIT_VIEW, ReadOnlyDocumentError, ReadOnlyLibraryDefinitionError, SCALE_ANCHORS, TOOL_SHORTCUTS, assertNodeEditable, clipboardImportHasConflicts, clipboardImportHasDependencies, copyEditorViewState, createDefaultEditorSharedState, createDefaultEditorState, createDefaultEditorViewState, createDocumentGraph, createEditor, createGuideActions, createTextActions, editableImageFillIndex, editedGradient, editedGradientLayout, editedImage, editedImageLayout, executeAtomicTool, findShaderModeTarget, getNodeEditCapability, graphFromDocumentChange, graphFromPageSnapshot, imageEditChanges, imageEditCrops, isEmptyDocumentChange, isScaleAnchor, layerTypeOptions, newLayerDefaults, opacityFromBuffer, pageSlides, parseScaleFactor, pastedPropertyChanges, pickEditorViewState, planClipboardImport, playIslandRoots, presentationViewport, reapplyInstanceComponentProperties, replaceSelectionColor, rescaleNodes, resizedPathTextGlyphs, resolveEditorProfile, resolvePasteTarget, resolvePlayState, scaleAnchorFraction, scaleAnchorPoint, scaleFactorForSize, scaledBounds, selectionColors, selectionColorsShown, slideMoveTarget, syncEditedComponents };
35
+ export { BOARD_TOOLS, BOARD_TOOL_SHORTCUTS, DEFAULT_SCALE_ANCHOR, DEFAULT_SNAPPING_PREFERENCES, EDITOR_TOOLS, EDIT_VIEW, ReadOnlyDocumentError, ReadOnlyLibraryDefinitionError, SCALE_ANCHORS, TOOL_SHORTCUTS, assertNodeEditable, clipboardImportHasConflicts, clipboardImportHasDependencies, copyEditorViewState, createDefaultEditorSharedState, createDefaultEditorState, createDefaultEditorViewState, createDocumentGraph, createEditor, createGuideActions, createTextActions, editableImageFillIndex, editedGradient, editedGradientLayout, editedImage, editedImageLayout, executeAtomicTool, findShaderModeTarget, getNodeEditCapability, graphFromDocumentChange, graphFromPageSnapshot, graphsFromDocumentChange, imageEditChanges, imageEditCrops, isEmptyDocumentChange, isScaleAnchor, layerTypeOptions, newLayerDefaults, opacityFromBuffer, pageSlides, parseScaleFactor, pastedPropertyChanges, pickEditorViewState, planClipboardImport, playIslandRoots, presentationViewport, reapplyInstanceComponentProperties, replaceSelectionColor, rescaleNodes, resizedPathTextGlyphs, resolveEditorProfile, resolvePasteTarget, resolvePlayState, scaleAnchorFraction, scaleAnchorPoint, scaleFactorForSize, scaledBounds, selectionColors, selectionColorsShown, slideMoveTarget, syncEditedComponents, touchedTopLevelIds };
@@ -1,11 +1,8 @@
1
- import { DesignIssueHighlight, DesignIssueMarker } from "../canvas/issues/types.js";
1
+ import { DesignIssueHighlight } from "../canvas/issues/types.js";
2
2
  import { EditorContext } from "./types.js";
3
3
  //#region src/editor/issues.d.ts
4
4
  declare function createDesignIssueActions(ctx: EditorContext): {
5
- setDesignIssueMarkers: (markers: readonly DesignIssueMarker[]) => void;
6
5
  setDesignIssueHighlight: (highlight: DesignIssueHighlight | null) => void;
7
- setHoveredIssueMarker: (key: string | null) => void;
8
- clearDesignIssues: () => void;
9
6
  };
10
7
  //#endregion
11
8
  export { createDesignIssueActions };
@@ -1 +1 @@
1
- {"version":3,"file":"issues.d.ts","names":[],"sources":["../../src/editor/issues.ts"],"mappings":";;;iBAkBgB,yBAAyB,KAAK;EAKJ,wBAAA,kBAAS;EAOL,0BAAA,WAAA;EAOR,wBAAA"}
1
+ {"version":3,"file":"issues.d.ts","names":[],"sources":["../../src/editor/issues.ts"],"mappings":";;;iBAkBgB,yBAAyB,KAAK;EACA,0BAAA,WAAA"}
@@ -1,58 +1,19 @@
1
1
  //#region src/editor/issues.ts
2
2
  /**
3
- * Canvas presentation of design check results. The check itself runs outside the editor; these
4
- * actions only publish what the canvas marks and highlights.
3
+ * Canvas presentation of design check results. The check itself runs outside the editor; this
4
+ * only publishes the layer the canvas highlights for a hovered issue.
5
5
  */
6
6
  function sameHighlight(a, b) {
7
7
  if (!a || !b) return a === b;
8
8
  return a.nodeId === b.nodeId && a.severity === b.severity && a.minSize?.width === b.minSize?.width && a.minSize?.height === b.minSize?.height;
9
9
  }
10
10
  function createDesignIssueActions(ctx) {
11
- function current() {
12
- return ctx.state.designIssues ?? {
13
- markers: [],
14
- highlight: null,
15
- hoveredMarkerKey: null
16
- };
17
- }
18
- function setDesignIssueMarkers(markers) {
19
- const overlay = current();
20
- if (overlay.markers.length === 0 && markers.length === 0) return;
21
- ctx.state.designIssues = {
22
- ...overlay,
23
- markers
24
- };
25
- ctx.requestRepaint();
26
- }
27
11
  function setDesignIssueHighlight(highlight) {
28
- const overlay = current();
29
- if (sameHighlight(overlay.highlight, highlight)) return;
30
- ctx.state.designIssues = {
31
- ...overlay,
32
- highlight
33
- };
34
- ctx.requestRepaint();
35
- }
36
- function setHoveredIssueMarker(key) {
37
- const overlay = current();
38
- if (overlay.hoveredMarkerKey === key) return;
39
- ctx.state.designIssues = {
40
- ...overlay,
41
- hoveredMarkerKey: key
42
- };
43
- ctx.requestRepaint();
44
- }
45
- function clearDesignIssues() {
46
- if (!ctx.state.designIssues) return;
47
- ctx.state.designIssues = null;
12
+ if (sameHighlight(ctx.state.designIssueHighlight, highlight)) return;
13
+ ctx.state.designIssueHighlight = highlight;
48
14
  ctx.requestRepaint();
49
15
  }
50
- return {
51
- setDesignIssueMarkers,
52
- setDesignIssueHighlight,
53
- setHoveredIssueMarker,
54
- clearDesignIssues
55
- };
16
+ return { setDesignIssueHighlight };
56
17
  }
57
18
  //#endregion
58
19
  export { createDesignIssueActions };
@@ -1 +1 @@
1
- {"version":3,"file":"issues.js","names":[],"sources":["../../src/editor/issues.ts"],"sourcesContent":["import type { DesignIssueHighlight, DesignIssueMarker } from '#core/canvas/issues/types'\n\nimport type { EditorContext } from './types'\n\n/**\n * Canvas presentation of design check results. The check itself runs outside the editor; these\n * actions only publish what the canvas marks and highlights.\n */\nfunction sameHighlight(a: DesignIssueHighlight | null, b: DesignIssueHighlight | null): boolean {\n if (!a || !b) return a === b\n return (\n a.nodeId === b.nodeId &&\n a.severity === b.severity &&\n a.minSize?.width === b.minSize?.width &&\n a.minSize?.height === b.minSize?.height\n )\n}\n\nexport function createDesignIssueActions(ctx: EditorContext) {\n function current() {\n return ctx.state.designIssues ?? { markers: [], highlight: null, hoveredMarkerKey: null }\n }\n\n function setDesignIssueMarkers(markers: readonly DesignIssueMarker[]) {\n const overlay = current()\n if (overlay.markers.length === 0 && markers.length === 0) return\n ctx.state.designIssues = { ...overlay, markers }\n ctx.requestRepaint()\n }\n\n function setDesignIssueHighlight(highlight: DesignIssueHighlight | null) {\n const overlay = current()\n if (sameHighlight(overlay.highlight, highlight)) return\n ctx.state.designIssues = { ...overlay, highlight }\n ctx.requestRepaint()\n }\n\n function setHoveredIssueMarker(key: string | null) {\n const overlay = current()\n if (overlay.hoveredMarkerKey === key) return\n ctx.state.designIssues = { ...overlay, hoveredMarkerKey: key }\n ctx.requestRepaint()\n }\n\n function clearDesignIssues() {\n if (!ctx.state.designIssues) return\n ctx.state.designIssues = null\n ctx.requestRepaint()\n }\n\n return {\n setDesignIssueMarkers,\n setDesignIssueHighlight,\n setHoveredIssueMarker,\n clearDesignIssues\n }\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,GAAgC,GAAyC;CAC9F,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO,MAAM;CAC3B,OACE,EAAE,WAAW,EAAE,UACf,EAAE,aAAa,EAAE,YACjB,EAAE,SAAS,UAAU,EAAE,SAAS,SAChC,EAAE,SAAS,WAAW,EAAE,SAAS;AAErC;AAEA,SAAgB,yBAAyB,KAAoB;CAC3D,SAAS,UAAU;EACjB,OAAO,IAAI,MAAM,gBAAgB;GAAE,SAAS,CAAC;GAAG,WAAW;GAAM,kBAAkB;EAAK;CAC1F;CAEA,SAAS,sBAAsB,SAAuC;EACpE,MAAM,UAAU,QAAQ;EACxB,IAAI,QAAQ,QAAQ,WAAW,KAAK,QAAQ,WAAW,GAAG;EAC1D,IAAI,MAAM,eAAe;GAAE,GAAG;GAAS;EAAQ;EAC/C,IAAI,eAAe;CACrB;CAEA,SAAS,wBAAwB,WAAwC;EACvE,MAAM,UAAU,QAAQ;EACxB,IAAI,cAAc,QAAQ,WAAW,SAAS,GAAG;EACjD,IAAI,MAAM,eAAe;GAAE,GAAG;GAAS;EAAU;EACjD,IAAI,eAAe;CACrB;CAEA,SAAS,sBAAsB,KAAoB;EACjD,MAAM,UAAU,QAAQ;EACxB,IAAI,QAAQ,qBAAqB,KAAK;EACtC,IAAI,MAAM,eAAe;GAAE,GAAG;GAAS,kBAAkB;EAAI;EAC7D,IAAI,eAAe;CACrB;CAEA,SAAS,oBAAoB;EAC3B,IAAI,CAAC,IAAI,MAAM,cAAc;EAC7B,IAAI,MAAM,eAAe;EACzB,IAAI,eAAe;CACrB;CAEA,OAAO;EACL;EACA;EACA;EACA;CACF;AACF"}
1
+ {"version":3,"file":"issues.js","names":[],"sources":["../../src/editor/issues.ts"],"sourcesContent":["import type { DesignIssueHighlight } from '#core/canvas/issues/types'\n\nimport type { EditorContext } from './types'\n\n/**\n * Canvas presentation of design check results. The check itself runs outside the editor; this\n * only publishes the layer the canvas highlights for a hovered issue.\n */\nfunction sameHighlight(a: DesignIssueHighlight | null, b: DesignIssueHighlight | null): boolean {\n if (!a || !b) return a === b\n return (\n a.nodeId === b.nodeId &&\n a.severity === b.severity &&\n a.minSize?.width === b.minSize?.width &&\n a.minSize?.height === b.minSize?.height\n )\n}\n\nexport function createDesignIssueActions(ctx: EditorContext) {\n function setDesignIssueHighlight(highlight: DesignIssueHighlight | null) {\n if (sameHighlight(ctx.state.designIssueHighlight, highlight)) return\n ctx.state.designIssueHighlight = highlight\n ctx.requestRepaint()\n }\n\n return { setDesignIssueHighlight }\n}\n"],"mappings":";;;;;AAQA,SAAS,cAAc,GAAgC,GAAyC;CAC9F,IAAI,CAAC,KAAK,CAAC,GAAG,OAAO,MAAM;CAC3B,OACE,EAAE,WAAW,EAAE,UACf,EAAE,aAAa,EAAE,YACjB,EAAE,SAAS,UAAU,EAAE,SAAS,SAChC,EAAE,SAAS,WAAW,EAAE,SAAS;AAErC;AAEA,SAAgB,yBAAyB,KAAoB;CAC3D,SAAS,wBAAwB,WAAwC;EACvE,IAAI,cAAc,IAAI,MAAM,sBAAsB,SAAS,GAAG;EAC9D,IAAI,MAAM,uBAAuB;EACjC,IAAI,eAAe;CACrB;CAEA,OAAO,EAAE,wBAAwB;AACnC"}
@@ -111,9 +111,10 @@ function createNudgeActions(ctx) {
111
111
  if (movable.length === 0) return;
112
112
  const reordered = reorderInFlows(movable, dx, dy);
113
113
  const nudged = movable.filter((id) => !reordered.has(id));
114
- if (nudged.length > 0 && !nudgeOriginals) {
115
- nudgeOriginals = /* @__PURE__ */ new Map();
114
+ if (nudged.length > 0) {
115
+ nudgeOriginals ??= /* @__PURE__ */ new Map();
116
116
  for (const id of nudged) {
117
+ if (nudgeOriginals.has(id)) continue;
117
118
  const node = ctx.graph.getNode(id);
118
119
  if (node) nudgeOriginals.set(id, {
119
120
  x: node.x,
@@ -1 +1 @@
1
- {"version":3,"file":"nudge.js","names":[],"sources":["../../src/editor/nudge.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { collectNodePositions, pushPositionUndo } from './history/position'\nimport { fitEnclosingGroupsWithUndo } from './structure/group/bounds'\nimport type { EditorContext } from './types'\n\nconst NUDGE_COMMIT_DELAY = 300\n\n/** The flow an arrow key moves a layer along: its row or column, or none. */\nfunction flowParent(ctx: EditorContext, node: SceneNode): SceneNode | null {\n if (node.layoutPositioning === 'ABSOLUTE' || !node.parentId) return null\n const parent = ctx.graph.getNode(node.parentId)\n return parent?.layoutMode === 'HORIZONTAL' || parent?.layoutMode === 'VERTICAL' ? parent : null\n}\n\n/**\n * One slot along the flow for an arrow key, as Figma reorders auto layout children: Right and\n * Left in a row (mirrored when it runs right to left), Down and Up in a column, and nothing for\n * the arrows across it. Shift moves one slot too.\n */\nfunction flowStep(parent: SceneNode, dx: number, dy: number): -1 | 0 | 1 {\n const along = parent.layoutMode === 'HORIZONTAL' ? dx : dy\n const visual =\n parent.layoutMode === 'HORIZONTAL' && parent.layoutDirection === 'RTL' ? -along : along\n if (visual === 0) return 0\n return visual > 0 ? 1 : -1\n}\n\n/**\n * The flow with each selected layer moved one slot by `step`; one already at the end of the\n * flow, or behind another selected layer that is, stays put.\n */\nfunction steppedFlow(\n flow: readonly string[],\n selected: ReadonlySet<string>,\n step: 1 | -1\n): string[] {\n const order = [...flow]\n const indices = step > 0 ? order.map((_, i) => order.length - 1 - i) : order.map((_, i) => i)\n for (const i of indices) {\n const j = i + step\n if (!selected.has(order[i]) || j < 0 || j >= order.length || selected.has(order[j])) continue\n ;[order[i], order[j]] = [order[j], order[i]]\n }\n return order\n}\n\nexport function createNudgeActions(ctx: EditorContext) {\n let nudgeOriginals: Map<string, Vector> | null = null\n let reorderOriginals: Map<string, string[]> | null = null\n let nudgeCommitTimer: ReturnType<typeof setTimeout> | null = null\n\n function applyOrder(parentId: string, order: readonly string[]) {\n order.forEach((id, index) => ctx.graph.insertChildAt(id, parentId, index))\n ctx.runLayoutForNode(parentId)\n }\n\n function commitReorder() {\n if (!reorderOriginals) return\n const originals = reorderOriginals\n reorderOriginals = null\n const finals = new Map(\n [...originals.keys()].map((id) => [id, [...(ctx.graph.getNode(id)?.childIds ?? [])]])\n )\n if ([...originals].every(([id, order]) => isEqual(order, finals.get(id)))) return\n ctx.undo.push({\n label: 'Reorder',\n forward: () => {\n for (const [id, order] of finals) applyOrder(id, order)\n },\n inverse: () => {\n for (const [id, order] of originals) applyOrder(id, order)\n }\n })\n }\n\n function commitNudge() {\n nudgeCommitTimer = null\n commitReorder()\n if (!nudgeOriginals) return\n const originals = nudgeOriginals\n nudgeOriginals = null\n\n const finals = collectNodePositions(ctx, originals.keys())\n const parentIds = [...originals.keys()].flatMap((id) => ctx.graph.getNode(id)?.parentId ?? [])\n // Groups and booleans fit their nudged children, in the same undo step.\n ctx.undo.runBatch('Nudge', () => {\n pushPositionUndo(ctx, 'Nudge', originals, finals)\n fitEnclosingGroupsWithUndo(ctx, parentIds)\n })\n ctx.requestRender()\n }\n\n /** Moves the selected layers in auto layout flows one slot; returns the layers it handled. */\n function reorderInFlows(movable: readonly string[], dx: number, dy: number): Set<string> {\n const byParent = new Map<string, Set<string>>()\n for (const id of movable) {\n const node = ctx.graph.getNode(id)\n const parent = node && flowParent(ctx, node)\n if (!parent) continue\n const selected = byParent.get(parent.id) ?? new Set<string>()\n selected.add(id)\n byParent.set(parent.id, selected)\n }\n const handled = new Set<string>()\n for (const [parentId, selected] of byParent) {\n for (const id of selected) handled.add(id)\n const parent = ctx.graph.getNode(parentId)\n const step = parent ? flowStep(parent, dx, dy) : 0\n if (!parent || step === 0) continue\n const children = ctx.graph.getChildren(parentId)\n const flowIds = children\n .filter((child) => child.layoutPositioning !== 'ABSOLUTE')\n .map((c) => c.id)\n const moved = steppedFlow(flowIds, selected, step)\n if (isEqual(moved, flowIds)) continue\n reorderOriginals ??= new Map()\n if (!reorderOriginals.has(parentId)) reorderOriginals.set(parentId, [...parent.childIds])\n // Layers that ignore the layout keep their places in the stack.\n let next = 0\n const order = children.map((child) =>\n child.layoutPositioning === 'ABSOLUTE' ? child.id : moved[next++]\n )\n applyOrder(parentId, order)\n }\n return handled\n }\n\n function nudgeSelected(dx: number, dy: number) {\n const ids = [...ctx.state.selectedIds]\n if (ids.length === 0) return\n\n const movable: string[] = []\n for (const id of ids) {\n const node = ctx.graph.getNode(id)\n if (node && !node.locked) movable.push(id)\n }\n if (movable.length === 0) return\n\n const reordered = reorderInFlows(movable, dx, dy)\n const nudged = movable.filter((id) => !reordered.has(id))\n\n if (nudged.length > 0 && !nudgeOriginals) {\n nudgeOriginals = new Map()\n for (const id of nudged) {\n const node = ctx.graph.getNode(id)\n if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })\n }\n }\n\n for (const id of nudged) {\n const node = ctx.graph.getNode(id)\n if (!node) continue\n ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })\n ctx.runLayoutForNode(id)\n }\n\n if (nudgeCommitTimer) clearTimeout(nudgeCommitTimer)\n nudgeCommitTimer = setTimeout(commitNudge, NUDGE_COMMIT_DELAY)\n\n ctx.requestRender()\n }\n\n function flushNudge() {\n if (nudgeCommitTimer) {\n clearTimeout(nudgeCommitTimer)\n commitNudge()\n }\n }\n\n return { nudgeSelected, flushNudge }\n}\n"],"mappings":";;;;AASA,MAAM,qBAAqB;;AAG3B,SAAS,WAAW,KAAoB,MAAmC;CACzE,IAAI,KAAK,sBAAsB,cAAc,CAAC,KAAK,UAAU,OAAO;CACpE,MAAM,SAAS,IAAI,MAAM,QAAQ,KAAK,QAAQ;CAC9C,OAAO,QAAQ,eAAe,gBAAgB,QAAQ,eAAe,aAAa,SAAS;AAC7F;;;;;;AAOA,SAAS,SAAS,QAAmB,IAAY,IAAwB;CACvE,MAAM,QAAQ,OAAO,eAAe,eAAe,KAAK;CACxD,MAAM,SACJ,OAAO,eAAe,gBAAgB,OAAO,oBAAoB,QAAQ,CAAC,QAAQ;CACpF,IAAI,WAAW,GAAG,OAAO;CACzB,OAAO,SAAS,IAAI,IAAI;AAC1B;;;;;AAMA,SAAS,YACP,MACA,UACA,MACU;CACV,MAAM,QAAQ,CAAC,GAAG,IAAI;CACtB,MAAM,UAAU,OAAO,IAAI,MAAM,KAAK,GAAG,MAAM,MAAM,SAAS,IAAI,CAAC,IAAI,MAAM,KAAK,GAAG,MAAM,CAAC;CAC5F,KAAK,MAAM,KAAK,SAAS;EACvB,MAAM,IAAI,IAAI;EACd,IAAI,CAAC,SAAS,IAAI,MAAM,EAAE,KAAK,IAAI,KAAK,KAAK,MAAM,UAAU,SAAS,IAAI,MAAM,EAAE,GAAG;EACpF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,WAAW;EACrC,IAAI,IAAI,WAAW,GAAG;EAEtB,MAAM,UAAoB,CAAC;EAC3B,KAAK,MAAM,MAAM,KAAK;GACpB,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;GACjC,IAAI,QAAQ,CAAC,KAAK,QAAQ,QAAQ,KAAK,EAAE;EAC3C;EACA,IAAI,QAAQ,WAAW,GAAG;EAE1B,MAAM,YAAY,eAAe,SAAS,IAAI,EAAE;EAChD,MAAM,SAAS,QAAQ,QAAQ,OAAO,CAAC,UAAU,IAAI,EAAE,CAAC;EAExD,IAAI,OAAO,SAAS,KAAK,CAAC,gBAAgB;GACxC,iCAAiB,IAAI,IAAI;GACzB,KAAK,MAAM,MAAM,QAAQ;IACvB,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;IACjC,IAAI,MAAM,eAAe,IAAI,IAAI;KAAE,GAAG,KAAK;KAAG,GAAG,KAAK;IAAE,CAAC;GAC3D;EACF;EAEA,KAAK,MAAM,MAAM,QAAQ;GACvB,MAAM,OAAO,IAAI,MAAM,QAAQ,EAAE;GACjC,IAAI,CAAC,MAAM;GACX,IAAI,MAAM,WAAW,IAAI;IAAE,GAAG,KAAK,IAAI;IAAI,GAAG,KAAK,IAAI;GAAG,CAAC;GAC3D,IAAI,iBAAiB,EAAE;EACzB;EAEA,IAAI,kBAAkB,aAAa,gBAAgB;EACnD,mBAAmB,WAAW,aAAa,kBAAkB;EAE7D,IAAI,cAAc;CACpB;CAEA,SAAS,aAAa;EACpB,IAAI,kBAAkB;GACpB,aAAa,gBAAgB;GAC7B,YAAY;EACd;CACF;CAEA,OAAO;EAAE;EAAe;CAAW;AACrC"}
1
+ {"version":3,"file":"nudge.js","names":[],"sources":["../../src/editor/nudge.ts"],"sourcesContent":["import { isEqual } from 'es-toolkit'\n\nimport type { SceneNode } from '@pairdraw/scene-graph'\nimport type { Vector } from '@pairdraw/scene-graph/primitives'\n\nimport { collectNodePositions, pushPositionUndo } from './history/position'\nimport { fitEnclosingGroupsWithUndo } from './structure/group/bounds'\nimport type { EditorContext } from './types'\n\nconst NUDGE_COMMIT_DELAY = 300\n\n/** The flow an arrow key moves a layer along: its row or column, or none. */\nfunction flowParent(ctx: EditorContext, node: SceneNode): SceneNode | null {\n if (node.layoutPositioning === 'ABSOLUTE' || !node.parentId) return null\n const parent = ctx.graph.getNode(node.parentId)\n return parent?.layoutMode === 'HORIZONTAL' || parent?.layoutMode === 'VERTICAL' ? parent : null\n}\n\n/**\n * One slot along the flow for an arrow key, as Figma reorders auto layout children: Right and\n * Left in a row (mirrored when it runs right to left), Down and Up in a column, and nothing for\n * the arrows across it. Shift moves one slot too.\n */\nfunction flowStep(parent: SceneNode, dx: number, dy: number): -1 | 0 | 1 {\n const along = parent.layoutMode === 'HORIZONTAL' ? dx : dy\n const visual =\n parent.layoutMode === 'HORIZONTAL' && parent.layoutDirection === 'RTL' ? -along : along\n if (visual === 0) return 0\n return visual > 0 ? 1 : -1\n}\n\n/**\n * The flow with each selected layer moved one slot by `step`; one already at the end of the\n * flow, or behind another selected layer that is, stays put.\n */\nfunction steppedFlow(\n flow: readonly string[],\n selected: ReadonlySet<string>,\n step: 1 | -1\n): string[] {\n const order = [...flow]\n const indices = step > 0 ? order.map((_, i) => order.length - 1 - i) : order.map((_, i) => i)\n for (const i of indices) {\n const j = i + step\n if (!selected.has(order[i]) || j < 0 || j >= order.length || selected.has(order[j])) continue\n ;[order[i], order[j]] = [order[j], order[i]]\n }\n return order\n}\n\nexport function createNudgeActions(ctx: EditorContext) {\n let nudgeOriginals: Map<string, Vector> | null = null\n let reorderOriginals: Map<string, string[]> | null = null\n let nudgeCommitTimer: ReturnType<typeof setTimeout> | null = null\n\n function applyOrder(parentId: string, order: readonly string[]) {\n order.forEach((id, index) => ctx.graph.insertChildAt(id, parentId, index))\n ctx.runLayoutForNode(parentId)\n }\n\n function commitReorder() {\n if (!reorderOriginals) return\n const originals = reorderOriginals\n reorderOriginals = null\n const finals = new Map(\n [...originals.keys()].map((id) => [id, [...(ctx.graph.getNode(id)?.childIds ?? [])]])\n )\n if ([...originals].every(([id, order]) => isEqual(order, finals.get(id)))) return\n ctx.undo.push({\n label: 'Reorder',\n forward: () => {\n for (const [id, order] of finals) applyOrder(id, order)\n },\n inverse: () => {\n for (const [id, order] of originals) applyOrder(id, order)\n }\n })\n }\n\n function commitNudge() {\n nudgeCommitTimer = null\n commitReorder()\n if (!nudgeOriginals) return\n const originals = nudgeOriginals\n nudgeOriginals = null\n\n const finals = collectNodePositions(ctx, originals.keys())\n const parentIds = [...originals.keys()].flatMap((id) => ctx.graph.getNode(id)?.parentId ?? [])\n // Groups and booleans fit their nudged children, in the same undo step.\n ctx.undo.runBatch('Nudge', () => {\n pushPositionUndo(ctx, 'Nudge', originals, finals)\n fitEnclosingGroupsWithUndo(ctx, parentIds)\n })\n ctx.requestRender()\n }\n\n /** Moves the selected layers in auto layout flows one slot; returns the layers it handled. */\n function reorderInFlows(movable: readonly string[], dx: number, dy: number): Set<string> {\n const byParent = new Map<string, Set<string>>()\n for (const id of movable) {\n const node = ctx.graph.getNode(id)\n const parent = node && flowParent(ctx, node)\n if (!parent) continue\n const selected = byParent.get(parent.id) ?? new Set<string>()\n selected.add(id)\n byParent.set(parent.id, selected)\n }\n const handled = new Set<string>()\n for (const [parentId, selected] of byParent) {\n for (const id of selected) handled.add(id)\n const parent = ctx.graph.getNode(parentId)\n const step = parent ? flowStep(parent, dx, dy) : 0\n if (!parent || step === 0) continue\n const children = ctx.graph.getChildren(parentId)\n const flowIds = children\n .filter((child) => child.layoutPositioning !== 'ABSOLUTE')\n .map((c) => c.id)\n const moved = steppedFlow(flowIds, selected, step)\n if (isEqual(moved, flowIds)) continue\n reorderOriginals ??= new Map()\n if (!reorderOriginals.has(parentId)) reorderOriginals.set(parentId, [...parent.childIds])\n // Layers that ignore the layout keep their places in the stack.\n let next = 0\n const order = children.map((child) =>\n child.layoutPositioning === 'ABSOLUTE' ? child.id : moved[next++]\n )\n applyOrder(parentId, order)\n }\n return handled\n }\n\n function nudgeSelected(dx: number, dy: number) {\n const ids = [...ctx.state.selectedIds]\n if (ids.length === 0) return\n\n const movable: string[] = []\n for (const id of ids) {\n const node = ctx.graph.getNode(id)\n if (node && !node.locked) movable.push(id)\n }\n if (movable.length === 0) return\n\n const reordered = reorderInFlows(movable, dx, dy)\n const nudged = movable.filter((id) => !reordered.has(id))\n\n // A run can span selection changes; each layer's start is recorded the first time it moves.\n if (nudged.length > 0) {\n nudgeOriginals ??= new Map()\n for (const id of nudged) {\n if (nudgeOriginals.has(id)) continue\n const node = ctx.graph.getNode(id)\n if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })\n }\n }\n\n for (const id of nudged) {\n const node = ctx.graph.getNode(id)\n if (!node) continue\n ctx.graph.updateNode(id, { x: node.x + dx, y: node.y + dy })\n ctx.runLayoutForNode(id)\n }\n\n if (nudgeCommitTimer) clearTimeout(nudgeCommitTimer)\n nudgeCommitTimer = setTimeout(commitNudge, NUDGE_COMMIT_DELAY)\n\n ctx.requestRender()\n }\n\n function flushNudge() {\n if (nudgeCommitTimer) {\n clearTimeout(nudgeCommitTimer)\n commitNudge()\n }\n }\n\n return { nudgeSelected, flushNudge }\n}\n"],"mappings":";;;;AASA,MAAM,qBAAqB;;AAG3B,SAAS,WAAW,KAAoB,MAAmC;CACzE,IAAI,KAAK,sBAAsB,cAAc,CAAC,KAAK,UAAU,OAAO;CACpE,MAAM,SAAS,IAAI,MAAM,QAAQ,KAAK,QAAQ;CAC9C,OAAO,QAAQ,eAAe,gBAAgB,QAAQ,eAAe,aAAa,SAAS;AAC7F;;;;;;AAOA,SAAS,SAAS,QAAmB,IAAY,IAAwB;CACvE,MAAM,QAAQ,OAAO,eAAe,eAAe,KAAK;CACxD,MAAM,SACJ,OAAO,eAAe,gBAAgB,OAAO,oBAAoB,QAAQ,CAAC,QAAQ;CACpF,IAAI,WAAW,GAAG,OAAO;CACzB,OAAO,SAAS,IAAI,IAAI;AAC1B;;;;;AAMA,SAAS,YACP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AkB;EAE7D,IAAI,cAAc;CACpB;CAEA,SAAS,aAAa;EACpB,IAAI,kBAAkB;GACpB,aAAa,gBAAgB;GAC7B,YAAY;EACd;CACF;CAEA,OAAO;EAAE;EAAe;CAAW;AACrC"}
@@ -78,16 +78,13 @@ const READ_ONLY_ACTIONS = /* @__PURE__ */ new Set([
78
78
  "setMeasurementMode",
79
79
  "setTool",
80
80
  "validateEnteredContainer",
81
- "clearDesignIssues",
82
81
  "endImageEdit",
83
82
  "setAutoLayoutHover",
84
83
  "setDesignIssueHighlight",
85
- "setDesignIssueMarkers",
86
84
  "setDropTarget",
87
85
  "setGuidePreview",
88
86
  "setGuideRedline",
89
87
  "setHoveredGuide",
90
- "setHoveredIssueMarker",
91
88
  "setLayoutInsertIndicator",
92
89
  "setRenamingLabel",
93
90
  "setRotationPreview",