@pairdraw/core 0.16.0 → 0.16.1

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 (146) 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/formats/design-tokens/apply.d.ts +1 -1
  88. package/dist/io/subgraph.d.ts +5 -2
  89. package/dist/io/subgraph.d.ts.map +1 -1
  90. package/dist/io/subgraph.js +6 -2
  91. package/dist/io/subgraph.js.map +1 -1
  92. package/dist/layout/mutations.d.ts +1 -1
  93. package/dist/layout/mutations.d.ts.map +1 -1
  94. package/dist/layout/mutations.js +1 -1
  95. package/dist/layout/mutations.js.map +1 -1
  96. package/dist/text/font/faces.js +1 -1
  97. package/dist/text/font/faces.js.map +1 -1
  98. package/dist/text/web-font/providers.d.ts +2 -11
  99. package/dist/text/web-font/providers.d.ts.map +1 -1
  100. package/dist/text/web-font/providers.js +8 -7
  101. package/dist/text/web-font/providers.js.map +1 -1
  102. package/dist/tools/analyze/diff/jsx.d.ts +2 -1
  103. package/dist/tools/analyze/diff/jsx.d.ts.map +1 -1
  104. package/dist/tools/analyze/diff/jsx.js +4 -2
  105. package/dist/tools/analyze/diff/jsx.js.map +1 -1
  106. package/package.json +24 -9
  107. package/src/ai/providers.ts +15 -1
  108. package/src/canvas/highlight-rect.ts +30 -9
  109. package/src/canvas/index.ts +1 -15
  110. package/src/canvas/issues/draw.ts +2 -165
  111. package/src/canvas/issues/types.ts +1 -36
  112. package/src/canvas/overlays/ai/draw.ts +129 -0
  113. package/src/canvas/overlays/ai/motion.ts +46 -0
  114. package/src/canvas/renderer/methods.ts +1 -1
  115. package/src/canvas/renderer/overlay-pass.ts +2 -49
  116. package/src/canvas/renderer/pipeline.ts +1 -1
  117. package/src/canvas/renderer/state.ts +20 -5
  118. package/src/canvas/renderer/types.ts +2 -2
  119. package/src/canvas/renderer.ts +9 -10
  120. package/src/canvas/text/preparation/cache.ts +9 -1
  121. package/src/constants.ts +12 -17
  122. package/src/design-jsx/index.ts +1 -1
  123. package/src/design-jsx/preview/picture.ts +55 -18
  124. package/src/editor/history/atomic-tool.ts +15 -8
  125. package/src/editor/history/document-change.ts +117 -1
  126. package/src/editor/history/snapshot/graph.ts +48 -8
  127. package/src/editor/index.ts +10 -2
  128. package/src/editor/issues.ts +6 -36
  129. package/src/editor/nudge.ts +4 -2
  130. package/src/editor/read-only/actions.ts +0 -3
  131. package/src/editor/state/shared.ts +1 -1
  132. package/src/editor/types.ts +6 -4
  133. package/src/io/subgraph.ts +10 -5
  134. package/src/layout/mutations.ts +2 -2
  135. package/src/text/font/faces.ts +1 -1
  136. package/src/text/web-font/providers.ts +19 -13
  137. package/src/tools/analyze/diff/jsx.ts +10 -5
  138. package/dist/canvas/issues/layout.d.ts +0 -37
  139. package/dist/canvas/issues/layout.d.ts.map +0 -1
  140. package/dist/canvas/issues/layout.js +0 -303
  141. package/dist/canvas/issues/layout.js.map +0 -1
  142. package/dist/canvas/overlays/ai.d.ts.map +0 -1
  143. package/dist/canvas/overlays/ai.js +0 -26
  144. package/dist/canvas/overlays/ai.js.map +0 -1
  145. package/src/canvas/issues/layout.ts +0 -376
  146. package/src/canvas/overlays/ai.ts +0 -34
@@ -3,7 +3,7 @@ import type { Color, Rect, Vector } from '@pairdraw/scene-graph/primitives'
3
3
  import type { SnapGuide } from '@pairdraw/scene-graph/snap'
4
4
 
5
5
  import type { GuideOverlayState } from '#core/canvas/guides/types'
6
- import type { DesignIssueOverlay } from '#core/canvas/issues/types'
6
+ import type { DesignIssueHighlight } from '#core/canvas/issues/types'
7
7
  import type { ConnectorTarget } from '#core/editor/connectors/attach'
8
8
  import type { ShapeHandleHover, GradientEdit, ImageEdit, PencilState } from '#core/editor/types'
9
9
  import type { RotationPreview } from '#core/geometry'
@@ -121,6 +121,6 @@ export interface RenderOverlays {
121
121
  transformBox?: Vector[] | null
122
122
  } | null
123
123
  presenceCursors?: PresenceCursor[]
124
- designIssues?: DesignIssueOverlay | null
124
+ designIssueHighlight?: DesignIssueHighlight | null
125
125
  codeFocusNodeId?: string | null
126
126
  }
@@ -3,7 +3,7 @@ import { toUint8Array } from 'js-base64'
3
3
 
4
4
  import type { SceneNode, SceneGraph, Fill, Stroke } from '@pairdraw/scene-graph'
5
5
  import type { RenderColorSpace, ResolvedRenderColor } from '@pairdraw/scene-graph/color'
6
- import type { Color, Rect, Vector } from '@pairdraw/scene-graph/primitives'
6
+ import type { Color, Vector } from '@pairdraw/scene-graph/primitives'
7
7
  import { slotPropertyId } from '@pairdraw/scene-graph/slots'
8
8
 
9
9
  /* eslint-disable max-lines -- SkiaRenderer facade owns CanvasKit state and delegates domain drawing */
@@ -79,7 +79,6 @@ export interface PendingFontNode {
79
79
  keys: Set<string>
80
80
  }
81
81
 
82
- import type { PlacedIssueMarker } from './issues/types'
83
82
  import type { PlacedStatusLabel } from './labels/status'
84
83
  import { EffectRasterCache } from './renderer/effect-raster-cache'
85
84
  import { TiledSceneController } from './renderer/tiles'
@@ -226,12 +225,8 @@ export class SkiaRenderer {
226
225
  /** Selection chrome, set from editor state each frame through {@link setSelectionTheme}. */
227
226
  selectionTheme: SelectionTheme = DEFAULT_SELECTION_THEME
228
227
  pageId: string | null = null
229
- /** Issue markers placed in the last overlay pass; hit testing reads the same layout. */
230
- issueMarkers: PlacedIssueMarker[] = []
231
228
  /** Status labels drawn in the last label pass; clicks on them open the status menu. */
232
229
  statusLabels: PlacedStatusLabel[] = []
233
- /** Screen rectangles of UI floating over this canvas, which overlays such as edge pins avoid. */
234
- overlayObstacles: readonly Rect[] = []
235
230
 
236
231
  /**
237
232
  * The most device pixels this canvas draws per CSS pixel; a low-power canvas caps it at 1 so a
@@ -253,6 +248,8 @@ export class SkiaRenderer {
253
248
  _flashPaint: Paint | null = null
254
249
  _aiActiveNodes: Set<string> = new Set()
255
250
  _aiDoneFlashes: Array<{ nodeId: string; startTime: number }> = []
251
+ /** Layers an agent added, each tracing in from its start, which may still be ahead. */
252
+ _aiEntrances: Array<{ nodeId: string; startTime: number }> = []
256
253
 
257
254
  readonly DEFAULT_FONT_SIZE = DEFAULT_FONT_SIZE
258
255
  readonly COMPONENT_SET_BORDER_WIDTH = COMPONENT_SET_BORDER_WIDTH
@@ -462,8 +459,9 @@ export class SkiaRenderer {
462
459
  RendererState.invalidateScenePicture(this)
463
460
  }
464
461
 
465
- invalidateAllPictures(): void {
466
- RendererState.invalidateAllPictures(this)
462
+ /** Drop every cached picture; `keepShapedText` keeps the sizes identical text shaped to. */
463
+ invalidateAllPictures(options?: { keepShapedText?: boolean }): void {
464
+ RendererState.invalidateAllPictures(this, options)
467
465
  }
468
466
 
469
467
  /**
@@ -529,8 +527,9 @@ export class SkiaRenderer {
529
527
  RendererState.aiFlashDone(this, nodeIds)
530
528
  }
531
529
 
532
- aiClearActive(): void {
533
- RendererState.aiClearActive(this)
530
+ /** Traces in layers an agent added, one after another in the order given. */
531
+ aiEnter(nodeIds: string[]): void {
532
+ RendererState.aiEnter(this, nodeIds)
534
533
  }
535
534
 
536
535
  aiClearAll(): void {
@@ -216,10 +216,18 @@ export class TextPreparationCache {
216
216
  }
217
217
 
218
218
  clear(): void {
219
+ this.releaseLayers()
220
+ this.results.clear()
221
+ }
222
+
223
+ /**
224
+ * Forget every layer, keeping what identical text shaped to, such as its sizes. For a renderer
225
+ * that draws a new graph each time, whose layer IDs can name different text from one to the next.
226
+ */
227
+ releaseLayers(): void {
219
228
  this.nodeKeys.clear()
220
229
  this.shaping = new WeakMap()
221
230
  this.invalidatedShaping.clear()
222
- this.results.clear()
223
231
  this.entries.clear()
224
232
  }
225
233
  }
package/src/constants.ts CHANGED
@@ -147,28 +147,23 @@ export const FLASH_RADIUS = 4
147
147
  export const ISSUE_ERROR_COLOR = { r: 0.949, g: 0.282, b: 0.133, a: 1 } satisfies Color // #F24822
148
148
  export const ISSUE_WARNING_COLOR = { r: 1, g: 0.702, b: 0.078, a: 1 } satisfies Color // #FFB314
149
149
  export const ISSUE_INFO_COLOR = { r: 0.55, g: 0.55, b: 0.55, a: 1 } satisfies Color
150
- export const ISSUE_MARKER_HEIGHT = 16
151
- export const ISSUE_MARKER_PADDING_X = 5
152
- /** Gap between a layer's corner and its marker; clears the 8px selection handle. */
153
- export const ISSUE_MARKER_OFFSET = 4
154
- /** Markers closer than this merge into one. */
155
- export const ISSUE_MARKER_GAP = 2
156
- export const ISSUE_MARKER_VIEWPORT_INSET = 4
157
- /** Layers smaller than this on screen pass their marker to an ancestor. */
158
- export const ISSUE_MARKER_MIN_TARGET = 24
159
- export const ISSUE_MARKER_MAX_COUNT = 99
160
- /** Edge pins closer than this along the viewport edge merge into one. */
161
- export const ISSUE_EDGE_MERGE_GAP = 24
162
- /** Length of the chevron an edge pin points with, beyond its ring. */
163
- export const ISSUE_EDGE_ARROW = 5
164
- export const ISSUE_MARKER_RING_WIDTH = 1.5
165
150
  export const ISSUE_HIGHLIGHT_STROKE_WIDTH = 1.5
166
151
  export const ISSUE_HIGHLIGHT_FILL_ALPHA = 0.08
167
152
 
168
- export const AI_ACTIVE_COLOR = { r: 0.26, g: 0.52, b: 0.96 }
153
+ /** The violet AI agents show in everywhere, the app's `--color-agent`. */
154
+ export const AI_AGENT_COLOR = { r: 0.486, g: 0.361, b: 1 }
169
155
  export const AI_DONE_COLOR = { r: 0.16, g: 0.73, b: 0.36 }
170
- export const AI_PULSE_PERIOD_MS = 1500
171
156
  export const AI_DONE_DURATION_MS = 800
157
+ /** How long a layer an agent adds takes to trace in, once its turn comes. */
158
+ export const AI_ENTER_DURATION_MS = 480
159
+ /** The pause between the layers of one edit, so they appear one after another. */
160
+ export const AI_ENTER_STAGGER_MS = 45
161
+ /** The last layer of an edit starts within this, however many layers the edit adds. */
162
+ export const AI_ENTER_MAX_DELAY_MS = 900
163
+ /** One sweep of the light over an area an agent is working in. */
164
+ export const AI_SHIMMER_PERIOD_MS = 1600
165
+ /** Width of the sweeping light, in screen pixels. */
166
+ export const AI_SHIMMER_BAND = 120
172
167
 
173
168
  /** Opacity of the selection color behind selected text while editing. */
174
169
  export const TEXT_SELECTION_ALPHA = 0.3
@@ -5,5 +5,5 @@ export {
5
5
  type RenderPlacement,
6
6
  type RenderPlacementInput
7
7
  } from './placement'
8
- export { recordJSXPreview } from './preview/picture'
8
+ export { createJSXPreviewRecorder, type JSXPreviewRecorder } from './preview/picture'
9
9
  export { stageJSXPreview, type StagedJSXPreview } from './preview/stage'
@@ -27,8 +27,6 @@ async function recordStaged(
27
27
  signal: AbortSignal
28
28
  ): Promise<SkPicture | null> {
29
29
  renderer.pageId = pageId
30
- await renderer.loadFonts()
31
- signal.throwIfAborted()
32
30
  await renderer.prepareForExport(graph, pageId, nodeIds)
33
31
  signal.throwIfAborted()
34
32
  const bounds = computeDescendantVisualBounds(
@@ -42,23 +40,62 @@ async function recordStaged(
42
40
  })
43
41
  }
44
42
 
43
+ export interface JSXPreviewRecorder {
44
+ /** Record `staged` as a picture the caller owns, even when its request becomes stale. */
45
+ record(staged: StagedJSXPreview, signal: AbortSignal): Promise<SkPicture | null>
46
+ /** Free the private renderer once the records already asked for finish. */
47
+ destroy(): void
48
+ }
49
+
45
50
  /**
46
- * Record a disposable vector picture using a private graph and renderer.
47
- * Neither speculative nodes nor renderer caches enter the live document.
48
- * The caller owns the returned picture, even when its request becomes stale.
51
+ * A private renderer that records preview pictures one at a time, for previews of JSX that is
52
+ * still streaming. Each record draws a new graph, so only what identical text shaped to carries
53
+ * over: a preview that grows measures just its new text instead of all of it again. Neither
54
+ * speculative nodes nor renderer caches enter the live document.
49
55
  */
50
- export async function recordJSXPreview(
51
- ck: CanvasKit,
52
- staged: StagedJSXPreview,
53
- signal: AbortSignal
54
- ): Promise<SkPicture | null> {
55
- signal.throwIfAborted()
56
- const surface = ck.MakeSurface(1, 1)
57
- if (!surface) return null
58
- const renderer = new SkiaRenderer(ck, surface)
59
- try {
60
- return await recordStaged(renderer, staged, signal)
61
- } finally {
62
- renderer.destroy()
56
+ export function createJSXPreviewRecorder(ck: CanvasKit): JSXPreviewRecorder {
57
+ let renderer: SkiaRenderer | null = null
58
+ let destroyed = false
59
+ // Records share one renderer, whose caches and page one record at a time may use.
60
+ let queue: Promise<unknown> = Promise.resolve()
61
+
62
+ async function rendererFor(): Promise<SkiaRenderer | null> {
63
+ if (renderer) return renderer
64
+ const surface = ck.MakeSurface(1, 1)
65
+ if (!surface) return null
66
+ const created = new SkiaRenderer(ck, surface)
67
+ renderer = created
68
+ // Loading fonts drops every cache, so it happens once rather than before each record.
69
+ await created.loadFonts()
70
+ return created
71
+ }
72
+
73
+ async function recordNext(
74
+ staged: StagedJSXPreview,
75
+ signal: AbortSignal
76
+ ): Promise<SkPicture | null> {
77
+ signal.throwIfAborted()
78
+ const current = destroyed ? null : await rendererFor()
79
+ if (!current) return null
80
+ signal.throwIfAborted()
81
+ // Layer IDs repeat between staged graphs with different content, so nothing keyed by them stays.
82
+ current.invalidateAllPictures({ keepShapedText: true })
83
+ return recordStaged(current, staged, signal)
84
+ }
85
+
86
+ return {
87
+ record(staged, signal) {
88
+ const result = queue.then(() => recordNext(staged, signal))
89
+ queue = result.catch(() => undefined)
90
+ return result
91
+ },
92
+ destroy() {
93
+ destroyed = true
94
+ const release = () => {
95
+ renderer?.destroy()
96
+ renderer = null
97
+ }
98
+ queue = queue.then(release)
99
+ }
63
100
  }
64
101
  }
@@ -1,5 +1,5 @@
1
1
  import type { SceneGraph, SceneNode, Variable } from '@pairdraw/scene-graph'
2
- import { captureGraphCheckpoint } from '@pairdraw/scene-graph/checkpoint'
2
+ import { captureEditCheckpoint } from '@pairdraw/scene-graph/checkpoint'
3
3
 
4
4
  import type { Editor } from '#core/editor/create'
5
5
  import { ReadOnlyDocumentError } from '#core/editor/read-only'
@@ -21,7 +21,8 @@ type MutationEditor = Pick<
21
21
 
22
22
  function changes<T extends object>(
23
23
  before: Map<string, T>,
24
- after: Map<string, T>
24
+ after: Map<string, T>,
25
+ expectedSize = before.size
25
26
  ): FieldChanges<T>[] {
26
27
  const result: FieldChanges<T>[] = []
27
28
  for (const [id, previous] of before) {
@@ -30,7 +31,8 @@ function changes<T extends object>(
30
31
  const change = diffFields(id, previous, current)
31
32
  if (change) result.push(change)
32
33
  }
33
- if (before.size !== after.size) throw new Error('Atomic tools must not create nodes or variables')
34
+ if (after.size !== expectedSize)
35
+ throw new Error('Atomic tools must not create nodes or variables')
34
36
  return result
35
37
  }
36
38
 
@@ -56,8 +58,10 @@ export function executeAtomicTool(
56
58
  if (graph.nodes.size + graph.variables.size > MAX_TRANSACTION_NODES) {
57
59
  throw new Error('Document too large for atomic agent editing (maximum 10000 nodes)')
58
60
  }
59
- const checkpoint = captureGraphCheckpoint(graph)
60
- const { nodes, variables } = checkpoint
61
+ // Rollback state costs what the call touches, not a copy of the document.
62
+ const checkpoint = captureEditCheckpoint(graph)
63
+ const { variables } = checkpoint
64
+ const nodeCount = graph.nodes.size
61
65
  const pageId = figma.currentPageId
62
66
 
63
67
  const replay = (
@@ -97,16 +101,17 @@ export function executeAtomicTool(
97
101
  if (result && typeof result === 'object' && 'error' in result) {
98
102
  throw new Error(String(result.error))
99
103
  }
100
- checkpoint.assertPropertiesOnly()
104
+ const touched = checkpoint.assertPropertiesOnly()
101
105
  const variableChanges = changes(variables, graph.variables)
102
106
  layout(
103
107
  graph,
104
108
  editor,
105
109
  pageId,
106
110
  variableChanges.length > 0,
107
- changes(nodes, graph.nodes).map((change) => change.id)
111
+ changes(touched, graph.nodes, nodeCount).map((change) => change.id)
108
112
  )
109
- const nodeChanges = changes(nodes, graph.nodes)
113
+ // Layout may change other layers too.
114
+ const nodeChanges = changes(checkpoint.changedNodes(), graph.nodes, nodeCount)
110
115
  const contentChanged =
111
116
  variableChanges.length > 0 ||
112
117
  nodeChanges.some((change) => Object.keys(change.after).some((key) => key !== 'source'))
@@ -124,6 +129,8 @@ export function executeAtomicTool(
124
129
  checkpoint.restore()
125
130
  editor.requestRender()
126
131
  throw error
132
+ } finally {
133
+ checkpoint.release()
127
134
  }
128
135
  }
129
136
 
@@ -1,4 +1,4 @@
1
- import { isEqual } from 'es-toolkit'
1
+ import { compact, isEqual, uniq, xor } from 'es-toolkit'
2
2
 
3
3
  import type {
4
4
  FigmaSourcePayload,
@@ -314,6 +314,122 @@ export function captureDocumentChange(graph: SceneGraph, pageId: string): () =>
314
314
  }
315
315
  }
316
316
 
317
+ /** Where a layer sits: its page and the page's child holding it, null for a page or the root. */
318
+ interface Placement {
319
+ pageId: string | null
320
+ layerId: string | null
321
+ }
322
+
323
+ /** `undefined` when the layer's parents cannot be followed to a page or the root. */
324
+ function placement(nodes: Lookup, id: string): Placement | undefined {
325
+ let child: SceneNode | null = null
326
+ for (const node of lineage(nodes, id)) {
327
+ if (node.type === 'CANVAS') return { pageId: node.id, layerId: child?.id ?? null }
328
+ if (!node.parentId) return { pageId: null, layerId: null }
329
+ child = node
330
+ }
331
+ return undefined
332
+ }
333
+
334
+ /**
335
+ * Layers as they were before the edit, read from the live graph: removed ones from their copies,
336
+ * and moved ones under the parent whose old child list held them.
337
+ */
338
+ function layersBefore(graph: SceneGraph, change: DocumentChange): Lookup {
339
+ const created = new Set(change.created.map((node) => node.id))
340
+ const deleted = new Map(change.deleted.map((node) => [node.id, node]))
341
+ const parents = new Map<string, string>()
342
+ for (const { id, childIds } of change.children.before) {
343
+ for (const childId of childIds) parents.set(childId, id)
344
+ }
345
+ return {
346
+ size: graph.nodes.size + deleted.size,
347
+ get(id) {
348
+ if (created.has(id)) return undefined
349
+ const node = deleted.get(id) ?? graph.getNode(id)
350
+ const parentId = parents.get(id)
351
+ return node && parentId !== undefined && parentId !== node.parentId
352
+ ? { ...node, parentId }
353
+ : node
354
+ }
355
+ }
356
+ }
357
+
358
+ /** Layers the edit created, removed, changed, or moved, and the parents whose children changed. */
359
+ function touchedLayerIds(change: DocumentChange): string[] {
360
+ const lists = (side: Side) =>
361
+ new Map(change.children[side].map(({ id, childIds }) => [id, childIds]))
362
+ const before = lists('before')
363
+ const after = lists('after')
364
+ // A reorder changes only its parent; a move also touches the layers that came or went.
365
+ const moved = uniq([...before.keys(), ...after.keys()]).flatMap((id) => [
366
+ id,
367
+ ...xor(before.get(id) ?? [], after.get(id) ?? [])
368
+ ])
369
+ return uniq([
370
+ ...change.created.map((node) => node.id),
371
+ ...change.deleted.map((node) => node.id),
372
+ ...change.updated.map((update) => update.id),
373
+ ...moved
374
+ ])
375
+ }
376
+
377
+ /** The ends of the connectors in the graph or removed by the edit, on either side of it. */
378
+ function connectorEnds(graph: SceneGraph, change: DocumentChange): Map<string, string[]> {
379
+ const ends = new Map<string, string[]>()
380
+ const add = (id: string, nodes: Partial<SceneNode>[]) => {
381
+ const nodeIds = nodes.flatMap((node) => [
382
+ node.connectorStart?.nodeId,
383
+ node.connectorEnd?.nodeId
384
+ ])
385
+ ends.set(id, uniq([...(ends.get(id) ?? []), ...compact(nodeIds)]))
386
+ }
387
+ for (const id of graph.connectorIds) add(id, compact([graph.getNode(id)]))
388
+ for (const node of change.deleted) if (node.type === 'CONNECTOR') add(node.id, [node])
389
+ for (const update of change.updated) {
390
+ if (update.fields && ends.has(update.id)) add(update.id, [update.fields.before])
391
+ }
392
+ return ends
393
+ }
394
+
395
+ /**
396
+ * The page children holding what an edit touched, on either side of it, for diffing and drawing
397
+ * just those instead of whole pages (`graphsFromDocumentChange`). A layer whose connector draws
398
+ * to a layer elsewhere brings that layer too, as JSX writes the end by it. `null` when part of
399
+ * the page cannot be told apart this way: the edit changed variables, which any layer may show,
400
+ * moved a layer to another page, or left a layer whose parents cannot be followed.
401
+ */
402
+ export function touchedTopLevelIds(graph: SceneGraph, change: DocumentChange): string[] | null {
403
+ if (change.variables.length > 0 || change.collections.length > 0) return null
404
+ const before = layersBefore(graph, change)
405
+ const sides = [before, graph.nodes]
406
+ const holders = (id: string): (string | null)[] | null => {
407
+ const placements = sides.map((nodes) => (nodes.get(id) ? placement(nodes, id) : null))
408
+ if (placements.includes(undefined)) return null
409
+ const [was, is] = placements
410
+ if (was?.pageId && is?.pageId && was.pageId !== is.pageId) return null
411
+ return placements.map((place) => place?.layerId ?? null)
412
+ }
413
+ const layers = new Set<string>()
414
+ for (const id of touchedLayerIds(change)) {
415
+ const held = holders(id)
416
+ if (!held) return null
417
+ for (const layerId of compact(held)) layers.add(layerId)
418
+ }
419
+ const ends = connectorEnds(graph, change)
420
+ for (let grew = true; grew;) {
421
+ grew = false
422
+ for (const [connectorId, endIds] of ends) {
423
+ if (!holders(connectorId)?.some((layerId) => layerId && layers.has(layerId))) continue
424
+ for (const layerId of compact(endIds.flatMap((id) => holders(id) ?? []))) {
425
+ grew ||= !layers.has(layerId)
426
+ layers.add(layerId)
427
+ }
428
+ }
429
+ }
430
+ return [...layers]
431
+ }
432
+
317
433
  export function isEmptyDocumentChange(change: DocumentChange): boolean {
318
434
  return (
319
435
  change.created.length === 0 &&
@@ -7,11 +7,26 @@ import { extractPageContext } from '#core/io/subgraph'
7
7
 
8
8
  import type { PageSnapshot } from './page'
9
9
 
10
- function pageContext(source: SceneGraph, pageId: string, nodeIds: string[]): SceneGraph {
11
- const graph = extractPageContext(source, pageId, nodeIds)
10
+ /** The variables and collections a copy reads, which copies of one state may share. */
11
+ type VariableTables = Pick<SceneGraph, 'variables' | 'variableCollections'>
12
+
13
+ function copyVariableTables(source: SceneGraph): VariableTables {
14
+ return {
15
+ variables: structuredClone(source.variables),
16
+ variableCollections: structuredClone(source.variableCollections)
17
+ }
18
+ }
19
+
20
+ function pageContext(
21
+ source: SceneGraph,
22
+ pageIds: string | readonly string[],
23
+ nodeIds: readonly string[],
24
+ tables: VariableTables = copyVariableTables(source)
25
+ ): SceneGraph {
26
+ const graph = extractPageContext(source, pageIds, nodeIds)
12
27
  graph.images = new Map(source.images)
13
- graph.variables = structuredClone(source.variables)
14
- graph.variableCollections = structuredClone(source.variableCollections)
28
+ graph.variables = tables.variables
29
+ graph.variableCollections = tables.variableCollections
15
30
  return graph
16
31
  }
17
32
 
@@ -37,21 +52,46 @@ export function graphFromPageSnapshot(
37
52
  /**
38
53
  * A standalone copy of the document with the pages a change touched, and the page it ran on, on
39
54
  * one side of the change. The source must be as the change left it, as it is right after the
40
- * edit. Other pages are left empty.
55
+ * edit. Other pages are left empty. `layerIds`, from `touchedTopLevelIds`, keeps only those page
56
+ * children, each whole, with what they depend on; `tables` are variables the copy reads instead
57
+ * of its own copy of them.
41
58
  */
42
59
  export function graphFromDocumentChange(
43
60
  source: SceneGraph,
44
61
  change: DocumentChange,
45
- side: 'before' | 'after'
62
+ side: 'before' | 'after',
63
+ layerIds?: readonly string[],
64
+ tables?: VariableTables
46
65
  ): SceneGraph | null {
47
- // A page's own id brings its whole subtree; a layer moved between pages can then move back.
48
66
  const pageIds = uniq([change.pageId, ...change.pageIds]).filter((id) => source.getNode(id))
49
67
  // A change that removed every page it touched still needs one to build on; the past side
50
68
  // brings the removed ones back.
51
69
  const host = pageIds[0] ?? source.getPages()[0]?.id
52
70
  if (!host) return null
53
- const graph = pageContext(source, host, pageIds)
71
+ // A page's own id brings its whole subtree, so a layer moved between pages can move back;
72
+ // with `layerIds`, the pages hold only those layers.
73
+ const graph = layerIds
74
+ ? pageContext(source, pageIds.length > 0 ? pageIds : host, layerIds, tables)
75
+ : pageContext(source, host, pageIds, tables)
54
76
  if (side === 'before') applyDocumentChange(graph, change, 'before')
55
77
  graph.clearAbsPosCache()
56
78
  return graph
57
79
  }
80
+
81
+ /**
82
+ * Both sides of a change as `graphFromDocumentChange` builds them. When the change left the
83
+ * variables alone, the two copies share one copy of them; neither may change it.
84
+ */
85
+ export function graphsFromDocumentChange(
86
+ source: SceneGraph,
87
+ change: DocumentChange,
88
+ layerIds?: readonly string[]
89
+ ): { before: SceneGraph; after: SceneGraph } | null {
90
+ const shared =
91
+ change.variables.length === 0 && change.collections.length === 0
92
+ ? copyVariableTables(source)
93
+ : undefined
94
+ const before = graphFromDocumentChange(source, change, 'before', layerIds, shared)
95
+ const after = graphFromDocumentChange(source, change, 'after', layerIds, shared)
96
+ return before && after ? { before, after } : null
97
+ }
@@ -36,10 +36,18 @@ export {
36
36
  export { createDefaultEditorState, createEditor } from './create'
37
37
  export { syncEditedComponents } from './component-sync'
38
38
  export { executeAtomicTool } from './history/atomic-tool'
39
- export { isEmptyDocumentChange, type DocumentChange } from './history/document-change'
39
+ export {
40
+ isEmptyDocumentChange,
41
+ touchedTopLevelIds,
42
+ type DocumentChange
43
+ } from './history/document-change'
40
44
  export type { RecordEditOptions } from './history/edit'
41
45
  export type { PageSnapshot } from './history/snapshot/page'
42
- export { graphFromDocumentChange, graphFromPageSnapshot } from './history/snapshot/graph'
46
+ export {
47
+ graphFromDocumentChange,
48
+ graphFromPageSnapshot,
49
+ graphsFromDocumentChange
50
+ } from './history/snapshot/graph'
43
51
  export type { ClipboardPayload, ClipboardSnapshot, CopyOptions } from './clipboard/copy'
44
52
  export {
45
53
  clipboardImportHasConflicts,
@@ -1,10 +1,10 @@
1
- import type { DesignIssueHighlight, DesignIssueMarker } from '#core/canvas/issues/types'
1
+ import type { DesignIssueHighlight } from '#core/canvas/issues/types'
2
2
 
3
3
  import type { EditorContext } from './types'
4
4
 
5
5
  /**
6
- * Canvas presentation of design check results. The check itself runs outside the editor; these
7
- * actions only publish what the canvas marks and highlights.
6
+ * Canvas presentation of design check results. The check itself runs outside the editor; this
7
+ * only publishes the layer the canvas highlights for a hovered issue.
8
8
  */
9
9
  function sameHighlight(a: DesignIssueHighlight | null, b: DesignIssueHighlight | null): boolean {
10
10
  if (!a || !b) return a === b
@@ -17,41 +17,11 @@ function sameHighlight(a: DesignIssueHighlight | null, b: DesignIssueHighlight |
17
17
  }
18
18
 
19
19
  export function createDesignIssueActions(ctx: EditorContext) {
20
- function current() {
21
- return ctx.state.designIssues ?? { markers: [], highlight: null, hoveredMarkerKey: null }
22
- }
23
-
24
- function setDesignIssueMarkers(markers: readonly DesignIssueMarker[]) {
25
- const overlay = current()
26
- if (overlay.markers.length === 0 && markers.length === 0) return
27
- ctx.state.designIssues = { ...overlay, markers }
28
- ctx.requestRepaint()
29
- }
30
-
31
20
  function setDesignIssueHighlight(highlight: DesignIssueHighlight | null) {
32
- const overlay = current()
33
- if (sameHighlight(overlay.highlight, highlight)) return
34
- ctx.state.designIssues = { ...overlay, highlight }
35
- ctx.requestRepaint()
36
- }
37
-
38
- function setHoveredIssueMarker(key: string | null) {
39
- const overlay = current()
40
- if (overlay.hoveredMarkerKey === key) return
41
- ctx.state.designIssues = { ...overlay, hoveredMarkerKey: key }
42
- ctx.requestRepaint()
43
- }
44
-
45
- function clearDesignIssues() {
46
- if (!ctx.state.designIssues) return
47
- ctx.state.designIssues = null
21
+ if (sameHighlight(ctx.state.designIssueHighlight, highlight)) return
22
+ ctx.state.designIssueHighlight = highlight
48
23
  ctx.requestRepaint()
49
24
  }
50
25
 
51
- return {
52
- setDesignIssueMarkers,
53
- setDesignIssueHighlight,
54
- setHoveredIssueMarker,
55
- clearDesignIssues
56
- }
26
+ return { setDesignIssueHighlight }
57
27
  }
@@ -143,9 +143,11 @@ export function createNudgeActions(ctx: EditorContext) {
143
143
  const reordered = reorderInFlows(movable, dx, dy)
144
144
  const nudged = movable.filter((id) => !reordered.has(id))
145
145
 
146
- if (nudged.length > 0 && !nudgeOriginals) {
147
- nudgeOriginals = new Map()
146
+ // A run can span selection changes; each layer's start is recorded the first time it moves.
147
+ if (nudged.length > 0) {
148
+ nudgeOriginals ??= new Map()
148
149
  for (const id of nudged) {
150
+ if (nudgeOriginals.has(id)) continue
149
151
  const node = ctx.graph.getNode(id)
150
152
  if (node) nudgeOriginals.set(id, { x: node.x, y: node.y })
151
153
  }
@@ -83,16 +83,13 @@ export const READ_ONLY_ACTIONS: ReadonlySet<string> = new Set([
83
83
  'validateEnteredContainer',
84
84
 
85
85
  // Canvas overlays that show without changing anything
86
- 'clearDesignIssues',
87
86
  'endImageEdit',
88
87
  'setAutoLayoutHover',
89
88
  'setDesignIssueHighlight',
90
- 'setDesignIssueMarkers',
91
89
  'setDropTarget',
92
90
  'setGuidePreview',
93
91
  'setGuideRedline',
94
92
  'setHoveredGuide',
95
- 'setHoveredIssueMarker',
96
93
  'setLayoutInsertIndicator',
97
94
  'setRenamingLabel',
98
95
  'setRotationPreview',
@@ -13,7 +13,7 @@ export function createDefaultEditorSharedState(): EditorSharedState {
13
13
  imageEdit: null,
14
14
  presenceCursors: [],
15
15
  documentName: 'Untitled',
16
- designIssues: null,
16
+ designIssueHighlight: null,
17
17
  codeFocusNodeId: null,
18
18
  rulerTheme: undefined,
19
19
  selectionTheme: undefined,