@bendyline/squisq-editor-react 1.5.3 → 1.6.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 (186) hide show
  1. package/README.md +57 -10
  2. package/dist/index.d.ts +1114 -52
  3. package/dist/index.js +18446 -8050
  4. package/dist/index.js.map +1 -1
  5. package/dist/styles/fa-brands-400-AHOAZHCU.woff2 +0 -0
  6. package/dist/styles/fa-regular-400-VRZYIBIZ.woff2 +0 -0
  7. package/dist/styles/fa-solid-900-MDEYK55F.woff2 +0 -0
  8. package/dist/styles/fa-v4compatibility-ETEVP6IB.woff2 +0 -0
  9. package/dist/styles/index.css +13867 -0
  10. package/package.json +15 -7
  11. package/src/BlockCardView.tsx +121 -0
  12. package/src/BlockPreviewPanel.tsx +69 -0
  13. package/src/BlockPropertiesPopover.tsx +191 -0
  14. package/src/EditorContext.tsx +165 -16
  15. package/src/EditorShell.tsx +265 -144
  16. package/src/FolderView.tsx +131 -0
  17. package/src/Icon.tsx +26 -0
  18. package/src/ImageEditor.tsx +69 -22
  19. package/src/OutlinePanel.tsx +64 -7
  20. package/src/PlainHtmlPreview.tsx +30 -3
  21. package/src/PreviewControls.tsx +491 -122
  22. package/src/PreviewPanel.tsx +15 -9
  23. package/src/RawEditor.tsx +179 -17
  24. package/src/RecorderEntry.tsx +9 -16
  25. package/src/TemplateAnnotation.ts +44 -0
  26. package/src/TemplatePicker.tsx +329 -54
  27. package/src/ThemeCustomizerPanel.tsx +30 -336
  28. package/src/ThemePicker.tsx +112 -3
  29. package/src/TimelineBlockPreview.tsx +37 -0
  30. package/src/TimelineTrack.tsx +671 -0
  31. package/src/Toolbar.tsx +544 -180
  32. package/src/Tooltip.tsx +22 -4
  33. package/src/TransitionPicker.tsx +351 -0
  34. package/src/VersionHistoryPanel.tsx +4 -16
  35. package/src/ViewMenuPanel.tsx +17 -14
  36. package/src/WysiwygEditor.tsx +161 -65
  37. package/src/__tests__/blockProperties.test.ts +92 -0
  38. package/src/__tests__/blockRange.test.ts +105 -0
  39. package/src/__tests__/buildPreviewDocTransition.test.ts +73 -0
  40. package/src/__tests__/codeContextSectionView.test.tsx +95 -0
  41. package/src/__tests__/codeContextZoneManager.test.ts +127 -0
  42. package/src/__tests__/createShapeLayer.test.ts +46 -0
  43. package/src/__tests__/diffContextSections.test.ts +39 -0
  44. package/src/__tests__/drawingShapeRoundTrip.test.ts +49 -0
  45. package/src/__tests__/editorShellCodeContext.test.tsx +86 -0
  46. package/src/__tests__/editorShellProps.test.tsx +96 -0
  47. package/src/__tests__/embeddedMedia.test.ts +48 -0
  48. package/src/__tests__/headingTransition.test.ts +138 -0
  49. package/src/__tests__/layoutChildRoundTrip.test.ts +71 -0
  50. package/src/__tests__/plainHtmlPreview.test.tsx +10 -8
  51. package/src/__tests__/previewControls.test.tsx +70 -0
  52. package/src/__tests__/recorderMediaInsert.test.ts +86 -0
  53. package/src/__tests__/templateAnnotationRoundTrip.test.ts +18 -0
  54. package/src/__tests__/templatePickerMetadata.test.ts +32 -0
  55. package/src/__tests__/timelineSource.test.ts +134 -0
  56. package/src/__tests__/tiptapBridge.test.ts +92 -0
  57. package/src/__tests__/tiptapBridgeConformance.test.ts +47 -0
  58. package/src/__tests__/tooltip.test.tsx +72 -0
  59. package/src/__tests__/transitionCatalog.test.ts +64 -0
  60. package/src/__tests__/useBlockNavigator.test.tsx +67 -0
  61. package/src/__tests__/useJsonEditorTokens.test.ts +59 -0
  62. package/src/__tests__/useMediaRecorder.test.ts +41 -0
  63. package/src/__tests__/useTimelineClock.test.ts +21 -0
  64. package/src/blockProperties.ts +88 -0
  65. package/src/blockRange.ts +132 -0
  66. package/src/buildPreviewDoc.ts +98 -9
  67. package/src/codeContext/CodeContextSectionView.tsx +124 -0
  68. package/src/codeContext/CodeContextZoneManager.ts +149 -0
  69. package/src/codeContext/CodeContextZones.tsx +121 -0
  70. package/src/codeContext/diffContextSections.ts +38 -0
  71. package/src/codeContext/types.ts +75 -0
  72. package/src/customTemplates/AddBin.tsx +126 -0
  73. package/src/customTemplates/CustomLayoutManager.tsx +233 -0
  74. package/src/customTemplates/CustomTemplateContext.tsx +182 -0
  75. package/src/customTemplates/LayerToolbar.tsx +580 -0
  76. package/src/customTemplates/ShapeGlyph.tsx +47 -0
  77. package/src/customTemplates/TemplateDesigner.tsx +430 -0
  78. package/src/customTemplates/__tests__/library.test.ts +88 -0
  79. package/src/customTemplates/__tests__/normalizePositions.test.ts +109 -0
  80. package/src/customTemplates/__tests__/shapeDefs.test.ts +49 -0
  81. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +95 -0
  82. package/src/customTemplates/designer.css +673 -0
  83. package/src/customTemplates/index.ts +31 -0
  84. package/src/customTemplates/library.ts +97 -0
  85. package/src/customTemplates/normalizePositions.ts +75 -0
  86. package/src/customTemplates/shapeDefs.ts +131 -0
  87. package/src/customTemplates/thumbnail.tsx +63 -0
  88. package/src/customTemplates/tokenDefs.ts +60 -0
  89. package/src/customTemplates/useDocCustomTemplates.ts +52 -0
  90. package/src/customTemplates/useMemoryLayerAdapter.ts +123 -0
  91. package/src/customThemes/CustomThemeContext.tsx +179 -0
  92. package/src/customThemes/CustomThemeDialog.tsx +286 -0
  93. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +64 -0
  94. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +47 -0
  95. package/src/customThemes/__tests__/customThemeLibrary.test.ts +51 -0
  96. package/src/customThemes/customThemeLibrary.ts +97 -0
  97. package/src/customThemes/index.ts +31 -0
  98. package/src/customThemes/themeControls.tsx +229 -0
  99. package/src/customThemes/themeDraft.ts +272 -0
  100. package/src/customThemes/useDocCustomThemes.ts +49 -0
  101. package/src/diagram/DiagramCanvas.tsx +240 -0
  102. package/src/diagram/DiagramExtension.ts +209 -0
  103. package/src/diagram/DiagramMaximizedOverlay.tsx +46 -0
  104. package/src/diagram/DiagramWidget.tsx +270 -0
  105. package/src/diagram/diagramCommands.ts +604 -0
  106. package/src/diagram/diagramConstants.ts +17 -0
  107. package/src/diagram/useDiagramData.ts +126 -0
  108. package/src/embeddedMedia.ts +78 -0
  109. package/src/frontmatter.ts +29 -0
  110. package/src/headingTransition.ts +231 -0
  111. package/src/imageEditor/CanvasSurface.tsx +383 -88
  112. package/src/imageEditor/PropertiesPanel.tsx +47 -1
  113. package/src/imageEditor/Toolbar.tsx +229 -16
  114. package/src/imageEditor/createShapeLayer.ts +280 -0
  115. package/src/imageEditor/icons.tsx +34 -114
  116. package/src/imageEditor/image-editor.css +54 -5
  117. package/src/imageEditor/state.ts +23 -3
  118. package/src/index.ts +109 -1
  119. package/src/jsonEditor/useJsonEditorTokens.ts +13 -43
  120. package/src/recorder/RecorderModal.tsx +120 -53
  121. package/src/recorder/RecorderPanel.tsx +2 -26
  122. package/src/recorder/hooks/useMediaRecorder.ts +17 -11
  123. package/src/recorder/insertMediaBlock.ts +30 -0
  124. package/src/resolveBlockVisual.ts +33 -0
  125. package/src/scene/Scene.tsx +540 -0
  126. package/src/scene/SceneBlockExtension.ts +198 -0
  127. package/src/scene/SceneBlockToolbar.tsx +201 -0
  128. package/src/scene/SceneBlockWidget.tsx +434 -0
  129. package/src/scene/ScenePropsBar.tsx +85 -0
  130. package/src/scene/SceneSelection.tsx +107 -0
  131. package/src/scene/SceneViewport.tsx +102 -0
  132. package/src/scene/ShapePalette.tsx +181 -0
  133. package/src/scene/__tests__/DiagramAdapter.test.ts +56 -0
  134. package/src/scene/__tests__/bezierEdit.test.ts +85 -0
  135. package/src/scene/__tests__/blockLayers.test.ts +57 -0
  136. package/src/scene/__tests__/shapeLayers.test.ts +106 -0
  137. package/src/scene/__tests__/useSceneHitTest.test.ts +90 -0
  138. package/src/scene/__tests__/useScenePanZoom.test.ts +103 -0
  139. package/src/scene/adapters/DiagramAdapter.ts +168 -0
  140. package/src/scene/adapters/DrawingAdapter.ts +415 -0
  141. package/src/scene/adapters/LayoutAdapter.ts +310 -0
  142. package/src/scene/adapters/blockLayers.ts +159 -0
  143. package/src/scene/commands/SceneCommand.ts +70 -0
  144. package/src/scene/commands/drawingCommands.ts +318 -0
  145. package/src/scene/commands/layoutCommands.ts +301 -0
  146. package/src/scene/hooks/useSceneHitTest.ts +105 -0
  147. package/src/scene/hooks/useScenePanZoom.ts +147 -0
  148. package/src/scene/hooks/useSceneSelection.ts +62 -0
  149. package/src/scene/index.ts +95 -0
  150. package/src/scene/layers/DiagramEdges.tsx +127 -0
  151. package/src/scene/layers/edgeGeometry.ts +77 -0
  152. package/src/scene/layers/nodeCard.tsx +145 -0
  153. package/src/scene/layers/renderLayer.tsx +70 -0
  154. package/src/scene/layers/shapeLayers.ts +201 -0
  155. package/src/scene/paths/bezierEdit.ts +208 -0
  156. package/src/scene/scene.css +649 -0
  157. package/src/scene/text/SceneTextOverlay.tsx +161 -0
  158. package/src/scene/text/sceneTextChannel.ts +40 -0
  159. package/src/scene/text/sceneTextConfig.ts +27 -0
  160. package/src/scene/text/sceneTiptap.ts +36 -0
  161. package/src/scene/text/useSceneTextEditing.ts +39 -0
  162. package/src/scene/tools/ConnectTool.ts +111 -0
  163. package/src/scene/tools/DrawingConnectTool.ts +161 -0
  164. package/src/scene/tools/PathTool.ts +158 -0
  165. package/src/scene/tools/PlaceTool.ts +47 -0
  166. package/src/scene/tools/SceneTool.ts +75 -0
  167. package/src/scene/tools/SelectTool.ts +284 -0
  168. package/src/scene/tools/ShapeTool.ts +144 -0
  169. package/src/scene/tools/TextTool.ts +72 -0
  170. package/src/scene/tools/TokenTool.ts +95 -0
  171. package/src/scene/tools/createDrawShapeTool.ts +82 -0
  172. package/src/styles/code-context.css +155 -0
  173. package/src/styles/diagram.css +183 -0
  174. package/src/styles/editor.css +1708 -150
  175. package/src/styles/folder-view.css +210 -0
  176. package/src/styles/image-edit-affordance.css +2 -2
  177. package/src/styles/index.css +5 -0
  178. package/src/timelineSource.ts +244 -0
  179. package/src/tiptapBridge.ts +115 -34
  180. package/src/tooltipPlacement.ts +13 -0
  181. package/src/transitionCatalog.ts +159 -0
  182. package/src/types/monaco-shims.d.ts +10 -0
  183. package/src/useBlockNavigator.ts +153 -0
  184. package/src/useMonacoLoader.ts +23 -1
  185. package/src/useTimelineClock.ts +76 -0
  186. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,604 @@
1
+ /**
2
+ * Tiptap commands for diagram editing.
3
+ *
4
+ * Each command finds the relevant heading inside a diagram section (parent
5
+ * heading + its direct sub-headings until the next equal-or-shallower
6
+ * heading) and mutates either its `data-block-attrs` attribute or its
7
+ * text content. All edits flow back into markdown via the existing
8
+ * `tiptapBridge` round-trip — no parallel data store.
9
+ */
10
+
11
+ import type { Editor } from '@tiptap/react';
12
+ import type { Node as PMNode } from '@tiptap/pm/model';
13
+ import {
14
+ parsePandocAttrTokens,
15
+ serializePandocAttributes,
16
+ quoteAttrValue,
17
+ type HeadingAttributes,
18
+ } from '@bendyline/squisq/markdown';
19
+ import type { Block, BlockConnection } from '@bendyline/squisq/schemas';
20
+ import { computeDiagramLayout } from '@bendyline/squisq/doc';
21
+
22
+ export interface HeadingLocation {
23
+ /** Node start position in the doc (absolute). */
24
+ pos: number;
25
+ /** The heading PMNode. */
26
+ node: PMNode;
27
+ /** Parsed attributes derived from the heading's `data-block-attrs` (always defined). */
28
+ attrs: HeadingAttributes;
29
+ /** Computed id: explicit `#id` if set, otherwise the slugified heading text. */
30
+ id: string;
31
+ }
32
+
33
+ /**
34
+ * Slugify heading text the same way `core/src/doc/markdownToDoc.ts` does
35
+ * (so an unset `#id` round-trips cleanly).
36
+ */
37
+ function slugify(text: string): string {
38
+ const out = text
39
+ .toLowerCase()
40
+ .replace(/[^\w\s-]/g, '')
41
+ .replace(/[\s_]+/g, '-')
42
+ .replace(/-+/g, '-')
43
+ .replace(/^-|-$/g, '');
44
+ return out || 'block';
45
+ }
46
+
47
+ function getHeadingText(node: PMNode): string {
48
+ let text = '';
49
+ node.content.forEach((child) => {
50
+ if (child.isText) text += child.text ?? '';
51
+ });
52
+ return text;
53
+ }
54
+
55
+ function getHeadingAttrs(node: PMNode): HeadingAttributes {
56
+ const raw = (node.attrs as Record<string, unknown>).dataBlockAttrs;
57
+ if (typeof raw === 'string' && raw.length > 0) {
58
+ return parsePandocAttrTokens(raw);
59
+ }
60
+ return {};
61
+ }
62
+
63
+ function computeId(node: PMNode): string {
64
+ const attrs = getHeadingAttrs(node);
65
+ return attrs.id ?? slugify(getHeadingText(node));
66
+ }
67
+
68
+ /**
69
+ * Find the diagram section that starts at `parentPos` (the position of the
70
+ * parent heading with `dataTemplate === 'diagram'`). Returns the headings
71
+ * that should appear as diagram nodes — defined as every heading at the
72
+ * **shallowest** depth greater than the parent within the section, until
73
+ * the next equal-or-shallower heading.
74
+ *
75
+ * Using the shallowest deeper depth (rather than a strict parentDepth + 1)
76
+ * mirrors `markdownToDoc`'s stack behavior: when authors skip a level
77
+ * (e.g. `# parent` + `### child`), those `###` headings are still treated
78
+ * as direct children of the `#` parent. Any headings deeper than the
79
+ * detected child depth are sub-sections of a node and are not surfaced as
80
+ * separate diagram nodes.
81
+ */
82
+ export function listDiagramChildren(editor: Editor, parentPos: number): HeadingLocation[] {
83
+ const { state } = editor;
84
+ const parent = state.doc.nodeAt(parentPos);
85
+ if (!parent || parent.type.name !== 'heading') return [];
86
+ const parentDepth = (parent.attrs as { level: number }).level;
87
+
88
+ // First pass: find the shallowest heading depth that appears below the
89
+ // parent (and before the next ≤parent heading). That's the diagram's
90
+ // child level.
91
+ let childDepth: number | undefined;
92
+ {
93
+ let cursor = parentPos + parent.nodeSize;
94
+ const docSize = state.doc.content.size;
95
+ while (cursor < docSize) {
96
+ const node = state.doc.nodeAt(cursor);
97
+ if (!node) break;
98
+ if (node.type.name === 'heading') {
99
+ const level = (node.attrs as { level: number }).level;
100
+ if (level <= parentDepth) break;
101
+ if (childDepth === undefined || level < childDepth) childDepth = level;
102
+ }
103
+ cursor += node.nodeSize;
104
+ }
105
+ }
106
+ if (childDepth === undefined) return [];
107
+
108
+ // Second pass: emit headings at exactly that child depth.
109
+ const results: HeadingLocation[] = [];
110
+ let cursor = parentPos + parent.nodeSize;
111
+ const docSize = state.doc.content.size;
112
+ while (cursor < docSize) {
113
+ const node = state.doc.nodeAt(cursor);
114
+ if (!node) break;
115
+ if (node.type.name === 'heading') {
116
+ const level = (node.attrs as { level: number }).level;
117
+ if (level <= parentDepth) break;
118
+ if (level === childDepth) {
119
+ results.push({
120
+ pos: cursor,
121
+ node,
122
+ attrs: getHeadingAttrs(node),
123
+ id: computeId(node),
124
+ });
125
+ }
126
+ }
127
+ cursor += node.nodeSize;
128
+ }
129
+ return results;
130
+ }
131
+
132
+ /**
133
+ * Compute the doc position immediately after the last node belonging to the
134
+ * diagram section (the parent heading + everything until the next
135
+ * equal-or-shallower heading).
136
+ */
137
+ export function getDiagramSectionEnd(editor: Editor, parentPos: number): number {
138
+ const { state } = editor;
139
+ const parent = state.doc.nodeAt(parentPos);
140
+ if (!parent || parent.type.name !== 'heading') return parentPos;
141
+ const parentDepth = (parent.attrs as { level: number }).level;
142
+
143
+ let cursor = parentPos + parent.nodeSize;
144
+ const docSize = state.doc.content.size;
145
+ while (cursor < docSize) {
146
+ const node = state.doc.nodeAt(cursor);
147
+ if (!node) break;
148
+ if (node.type.name === 'heading') {
149
+ const level = (node.attrs as { level: number }).level;
150
+ if (level <= parentDepth) return cursor;
151
+ }
152
+ cursor += node.nodeSize;
153
+ }
154
+ return cursor;
155
+ }
156
+
157
+ /**
158
+ * Read the diagram parent heading's `{[diagram …]}` template params
159
+ * (stored in `dataTemplateParams`). Returns an empty object when the
160
+ * heading carries no params. Mirrors the per-shape reader in
161
+ * `drawingCommands.listDrawingChildren`, but for the parent heading.
162
+ */
163
+ export function getDiagramParams(editor: Editor, parentPos: number): Record<string, string> {
164
+ const node = editor.state.doc.nodeAt(parentPos);
165
+ if (!node || node.type.name !== 'heading') return {};
166
+ const raw = (node.attrs as { dataTemplateParams?: string | null }).dataTemplateParams;
167
+ if (typeof raw === 'string' && raw.length > 0) {
168
+ return parsePandocAttrTokens(raw).params ?? {};
169
+ }
170
+ return {};
171
+ }
172
+
173
+ /**
174
+ * The diagram's pinned canvas height in pixels (the `height=` template
175
+ * param), or `null` when unset / invalid. This is an editor-only display
176
+ * hint: the SSR `diagramBlock` template scales to its block viewport and
177
+ * ignores it, but it round-trips in markdown via the annotation so the
178
+ * chosen height is remembered.
179
+ */
180
+ export function getDiagramHeight(editor: Editor, parentPos: number): number | null {
181
+ const raw = getDiagramParams(editor, parentPos).height;
182
+ if (raw == null) return null;
183
+ const n = Number(raw);
184
+ return Number.isFinite(n) && n > 0 ? n : null;
185
+ }
186
+
187
+ /**
188
+ * Pin (or clear) the diagram's canvas height, persisted as a `height=<px>`
189
+ * token in the parent heading's `{[diagram …]}` annotation. Pass `null`
190
+ * to drop the override and revert to the default height. Other params on
191
+ * the heading are preserved.
192
+ */
193
+ export function setDiagramHeight(
194
+ editor: Editor,
195
+ parentPos: number,
196
+ height: number | null,
197
+ ): boolean {
198
+ const node = editor.state.doc.nodeAt(parentPos);
199
+ if (!node || node.type.name !== 'heading') return false;
200
+ const params = getDiagramParams(editor, parentPos);
201
+ if (height == null) {
202
+ delete params.height;
203
+ } else {
204
+ params.height = String(Math.round(height));
205
+ }
206
+ const serialized = Object.entries(params)
207
+ .map(([k, v]) => `${k}=${quoteAttrValue(v)}`)
208
+ .join(' ');
209
+ return editor
210
+ .chain()
211
+ .command(({ tr }) => {
212
+ if (!tr.doc.nodeAt(parentPos)) return false;
213
+ tr.setNodeAttribute(
214
+ parentPos,
215
+ 'dataTemplateParams',
216
+ serialized.length > 0 ? serialized : null,
217
+ );
218
+ return true;
219
+ })
220
+ .run();
221
+ }
222
+
223
+ function applyAttrs(editor: Editor, pos: number, attrs: HeadingAttributes): boolean {
224
+ // `serializePandocAttributes` returns the full `{…}` block, but
225
+ // `data-block-attrs` stores the INSIDE of those braces (matching the
226
+ // parser in tiptapBridge.ts that captures the inner text only). Strip
227
+ // them here so we round-trip cleanly — otherwise the next save would
228
+ // wrap the value in a second pair of braces.
229
+ const raw = serializePandocAttributes(attrs);
230
+ const inner = stripBraces(raw);
231
+ return editor
232
+ .chain()
233
+ .command(({ tr }) => {
234
+ const node = tr.doc.nodeAt(pos);
235
+ if (!node) return false;
236
+ tr.setNodeAttribute(pos, 'dataBlockAttrs', inner ?? null);
237
+ return true;
238
+ })
239
+ .run();
240
+ }
241
+
242
+ function stripBraces(s: string | null): string | null {
243
+ if (s == null) return null;
244
+ // Empty Pandoc marker `{}` collapses to null (no attribute to persist).
245
+ if (s === '{}') return null;
246
+ if (s.startsWith('{') && s.endsWith('}')) return s.slice(1, -1);
247
+ return s;
248
+ }
249
+
250
+ /**
251
+ * Update a node's `x` / `y` attributes from a drag.
252
+ *
253
+ * Before writing the moved node, this also "freezes" any siblings that
254
+ * lack an explicit position by snapshotting their currently-displayed
255
+ * (auto-laid) coordinates. Without that, `computeDiagramLayout`'s grid
256
+ * auto-placement is relative to the bounding box of pinned nodes — so
257
+ * dragging one node would pull every unpinned sibling along behind it.
258
+ * Freezing converts the implicit layout into explicit per-node
259
+ * positions on the first interaction, after which each node moves
260
+ * independently.
261
+ */
262
+ export function moveNode(
263
+ editor: Editor,
264
+ parentPos: number,
265
+ nodeId: string,
266
+ x: number,
267
+ y: number,
268
+ ): boolean {
269
+ const children = listDiagramChildren(editor, parentPos);
270
+ const target = children.find((c) => c.id === nodeId);
271
+ if (!target) return false;
272
+ const positions = computeCurrentPositions(children);
273
+ return editor
274
+ .chain()
275
+ .command(({ tr }) => {
276
+ for (const child of children) {
277
+ const pos = positions.get(child.id);
278
+ if (!pos) continue;
279
+ const isMoved = child.id === nodeId;
280
+ // Skip siblings that already have an explicit position — they
281
+ // weren't moving anyway, and writing the same value back would
282
+ // be a noisy no-op.
283
+ if (!isMoved && pos.pinned) continue;
284
+ const newX = isMoved ? x : pos.x;
285
+ const newY = isMoved ? y : pos.y;
286
+ writeChildPosition(tr, child, nodeId === child.id ? nodeId : child.id, newX, newY);
287
+ }
288
+ return true;
289
+ })
290
+ .run();
291
+ }
292
+
293
+ /**
294
+ * Compute each child's currently-rendered position by running the
295
+ * shared `computeDiagramLayout` on a set of synthetic blocks. Returns
296
+ * a map of `nodeId → {x, y, pinned}`. `pinned` reflects whether the
297
+ * child already had an authored position (so callers can decide
298
+ * whether a write is necessary).
299
+ */
300
+ function computeCurrentPositions(
301
+ children: readonly HeadingLocation[],
302
+ ): Map<string, { x: number; y: number; pinned: boolean }> {
303
+ const blocks: Block[] = children.map((c) => {
304
+ const params = c.attrs.params ?? {};
305
+ const xRaw = params.x;
306
+ const yRaw = params.y;
307
+ const xN = xRaw != null ? Number(xRaw) : NaN;
308
+ const yN = yRaw != null ? Number(yRaw) : NaN;
309
+ return {
310
+ id: c.id,
311
+ startTime: 0,
312
+ duration: 0,
313
+ audioSegment: 0,
314
+ title: getHeadingText(c.node) || c.id,
315
+ ...(Number.isFinite(xN) ? { x: xN } : {}),
316
+ ...(Number.isFinite(yN) ? { y: yN } : {}),
317
+ } as Block;
318
+ });
319
+ const layout = computeDiagramLayout(blocks);
320
+ const out = new Map<string, { x: number; y: number; pinned: boolean }>();
321
+ for (const node of layout.nodes) {
322
+ out.set(node.id, { x: node.x, y: node.y, pinned: node.pinned });
323
+ }
324
+ return out;
325
+ }
326
+
327
+ /**
328
+ * Set a child heading's `data-block-attrs` to the given position. The
329
+ * heading's existing attrs (id, classes, other params) are preserved.
330
+ * Used by {@link moveNode} when batch-writing the snapshot.
331
+ */
332
+ function writeChildPosition(
333
+ tr: import('@tiptap/pm/state').Transaction,
334
+ child: HeadingLocation,
335
+ ensureId: string,
336
+ x: number,
337
+ y: number,
338
+ ): void {
339
+ const attrs: HeadingAttributes = { ...child.attrs };
340
+ if (!attrs.id) attrs.id = ensureId;
341
+ const params = { ...(attrs.params ?? {}) };
342
+ params.x = String(Math.round(x));
343
+ params.y = String(Math.round(y));
344
+ attrs.params = params;
345
+ const raw = serializePandocAttributes(attrs);
346
+ const inner = stripBraces(raw);
347
+ tr.setNodeAttribute(child.pos, 'dataBlockAttrs', inner ?? null);
348
+ }
349
+
350
+ /**
351
+ * Update a node's per-node `w` / `h` attributes from a corner-handle
352
+ * drag. Nodes without these params fall back to the default card size
353
+ * (`NODE_WIDTH` / `NODE_HEIGHT`) at render time, so most authors never
354
+ * see them in markdown.
355
+ */
356
+ export function resizeNode(
357
+ editor: Editor,
358
+ parentPos: number,
359
+ nodeId: string,
360
+ width: number,
361
+ height: number,
362
+ ): boolean {
363
+ const target = listDiagramChildren(editor, parentPos).find((c) => c.id === nodeId);
364
+ if (!target) return false;
365
+ const attrs = { ...target.attrs };
366
+ if (!attrs.id) attrs.id = nodeId;
367
+ const params = { ...(attrs.params ?? {}) };
368
+ params.w = String(Math.round(width));
369
+ params.h = String(Math.round(height));
370
+ attrs.params = params;
371
+ return applyAttrs(editor, target.pos, attrs);
372
+ }
373
+
374
+ /**
375
+ * Add a connection from `sourceId` to `targetId` (optionally typed). No-op
376
+ * if the same connection already exists.
377
+ */
378
+ export function addConnection(
379
+ editor: Editor,
380
+ parentPos: number,
381
+ sourceId: string,
382
+ targetId: string,
383
+ type?: string,
384
+ ): boolean {
385
+ const source = listDiagramChildren(editor, parentPos).find((c) => c.id === sourceId);
386
+ if (!source) return false;
387
+ const attrs = { ...source.attrs };
388
+ if (!attrs.id) attrs.id = sourceId;
389
+ const params = { ...(attrs.params ?? {}) };
390
+ const existing = parseConnectionsList(params.connectsTo);
391
+ const dup = existing.find((c) => c.target === targetId && (c.type ?? '') === (type ?? ''));
392
+ if (dup) return false;
393
+ existing.push(type ? { target: targetId, type } : { target: targetId });
394
+ params.connectsTo = serializeConnectionsList(existing);
395
+ attrs.params = params;
396
+ return applyAttrs(editor, source.pos, attrs);
397
+ }
398
+
399
+ /**
400
+ * Remove a connection from `sourceId` to `targetId`. If `type` is provided,
401
+ * only the matching-typed entry is removed; otherwise the first match
402
+ * (regardless of type) is removed.
403
+ */
404
+ export function removeConnection(
405
+ editor: Editor,
406
+ parentPos: number,
407
+ sourceId: string,
408
+ targetId: string,
409
+ type?: string,
410
+ ): boolean {
411
+ const source = listDiagramChildren(editor, parentPos).find((c) => c.id === sourceId);
412
+ if (!source) return false;
413
+ const attrs = { ...source.attrs };
414
+ const params = { ...(attrs.params ?? {}) };
415
+ const existing = parseConnectionsList(params.connectsTo);
416
+ const remaining = existing.filter((c) => {
417
+ if (c.target !== targetId) return true;
418
+ if (type != null && (c.type ?? '') !== type) return true;
419
+ return false;
420
+ });
421
+ if (remaining.length === existing.length) return false;
422
+ if (remaining.length === 0) {
423
+ delete params.connectsTo;
424
+ } else {
425
+ params.connectsTo = serializeConnectionsList(remaining);
426
+ }
427
+ attrs.params = Object.keys(params).length > 0 ? params : undefined;
428
+ return applyAttrs(editor, source.pos, attrs);
429
+ }
430
+
431
+ /**
432
+ * Replace a heading's text content (used when the user renames a node
433
+ * via a double-click in the canvas).
434
+ */
435
+ export function renameNode(
436
+ editor: Editor,
437
+ parentPos: number,
438
+ nodeId: string,
439
+ newText: string,
440
+ ): boolean {
441
+ const target = listDiagramChildren(editor, parentPos).find((c) => c.id === nodeId);
442
+ if (!target) return false;
443
+ const headingPos = target.pos;
444
+ const heading = target.node;
445
+ // Replace the heading's content with a single text node containing the
446
+ // new text. This preserves heading attrs (including dataBlockAttrs).
447
+ return editor
448
+ .chain()
449
+ .command(({ tr, state }) => {
450
+ const from = headingPos + 1;
451
+ const to = headingPos + heading.nodeSize - 1;
452
+ const textNode = state.schema.text(newText);
453
+ tr.replaceWith(from, to, textNode);
454
+ return true;
455
+ })
456
+ .run();
457
+ }
458
+
459
+ /**
460
+ * Insert a new heading node at the end of the diagram section. The new
461
+ * heading carries `data-block-attrs` with the supplied id and position,
462
+ * so the freshly-inserted node appears in React Flow at the expected
463
+ * coordinates.
464
+ */
465
+ export function addNode(
466
+ editor: Editor,
467
+ parentPos: number,
468
+ id: string,
469
+ label: string,
470
+ x: number,
471
+ y: number,
472
+ ): boolean {
473
+ const { state } = editor;
474
+ const parent = state.doc.nodeAt(parentPos);
475
+ if (!parent || parent.type.name !== 'heading') return false;
476
+ const parentDepth = (parent.attrs as { level: number }).level;
477
+ // Inherit the depth of existing diagram children so a new node is a
478
+ // sibling, not an accidental new shallower parent. Falls back to
479
+ // parent+1 when the section is empty.
480
+ const existing = listDiagramChildren(editor, parentPos);
481
+ const inheritedDepth = existing[0]?.node.attrs.level as number | undefined;
482
+ const childDepth = Math.min(6, inheritedDepth ?? parentDepth + 1);
483
+
484
+ const insertPos = getDiagramSectionEnd(editor, parentPos);
485
+ const dataBlockAttrs = serializePandocAttributes({
486
+ id,
487
+ params: { x: String(Math.round(x)), y: String(Math.round(y)) },
488
+ });
489
+ // Freeze any unpinned siblings before inserting — see `moveNode` for
490
+ // the rationale. Without this, adding a node would shift other
491
+ // unpinned siblings as the auto-layout's bounding box grows.
492
+ const freezePositions = computeCurrentPositions(existing);
493
+
494
+ return editor
495
+ .chain()
496
+ .command(({ tr, state: s }) => {
497
+ for (const child of existing) {
498
+ const pos = freezePositions.get(child.id);
499
+ if (!pos || pos.pinned) continue;
500
+ writeChildPosition(tr, child, child.id, pos.x, pos.y);
501
+ }
502
+ const headingType = s.schema.nodes.heading;
503
+ if (!headingType) return false;
504
+ const newHeading = headingType.create(
505
+ {
506
+ level: childDepth,
507
+ dataTemplate: null,
508
+ dataTemplateParams: null,
509
+ dataBlockAttrs: stripBraces(dataBlockAttrs) ?? null,
510
+ },
511
+ s.schema.text(label),
512
+ );
513
+ tr.insert(insertPos, newHeading);
514
+ return true;
515
+ })
516
+ .run();
517
+ }
518
+
519
+ /**
520
+ * Remove a child node's heading (and any body content under it up to the
521
+ * next heading). Also strips inbound `connectsTo` references on remaining
522
+ * siblings so the diagram doesn't carry dangling targets.
523
+ */
524
+ export function removeNode(editor: Editor, parentPos: number, nodeId: string): boolean {
525
+ const children = listDiagramChildren(editor, parentPos);
526
+ const target = children.find((c) => c.id === nodeId);
527
+ if (!target) return false;
528
+
529
+ // Determine the deletion range: from the heading's start to the start
530
+ // of the next heading at any depth (or the diagram section end).
531
+ const { state } = editor;
532
+ const docSize = state.doc.content.size;
533
+ let cursor = target.pos + target.node.nodeSize;
534
+ while (cursor < docSize) {
535
+ const node = state.doc.nodeAt(cursor);
536
+ if (!node) break;
537
+ if (node.type.name === 'heading') break;
538
+ cursor += node.nodeSize;
539
+ }
540
+ const deleteFrom = target.pos;
541
+ const deleteTo = cursor;
542
+
543
+ return editor
544
+ .chain()
545
+ .command(({ tr }) => {
546
+ tr.delete(deleteFrom, deleteTo);
547
+ return true;
548
+ })
549
+ .command(({ tr }) => {
550
+ // After deletion, positions for remaining children have shifted;
551
+ // re-walk and strip inbound references. We use the live doc from
552
+ // the transaction so the positions stay correct.
553
+ const stale = listDiagramChildren(editor, parentPos);
554
+ for (const sib of stale) {
555
+ if (sib.id === nodeId) continue;
556
+ const params = { ...(sib.attrs.params ?? {}) };
557
+ if (!params.connectsTo) continue;
558
+ const entries = parseConnectionsList(params.connectsTo).filter((c) => c.target !== nodeId);
559
+ const before = parseConnectionsList(params.connectsTo).length;
560
+ if (entries.length === before) continue;
561
+ if (entries.length === 0) {
562
+ delete params.connectsTo;
563
+ } else {
564
+ params.connectsTo = serializeConnectionsList(entries);
565
+ }
566
+ const nextAttrs: HeadingAttributes = { ...sib.attrs };
567
+ nextAttrs.params = Object.keys(params).length > 0 ? params : undefined;
568
+ const raw = serializePandocAttributes(nextAttrs);
569
+ tr.setNodeAttribute(sib.pos, 'dataBlockAttrs', raw ?? null);
570
+ }
571
+ return true;
572
+ })
573
+ .run();
574
+ }
575
+
576
+ // ============================================
577
+ // Internal: connection-list parse / serialize
578
+ // ============================================
579
+ //
580
+ // Mirrors `parseConnectionList` from core/annotationCoercion.ts, but
581
+ // returns the raw object shape so we can mutate before re-serialising.
582
+
583
+ function parseConnectionsList(raw: string | undefined): BlockConnection[] {
584
+ if (!raw) return [];
585
+ const out: BlockConnection[] = [];
586
+ for (const part of raw.split(',')) {
587
+ const entry = part.trim();
588
+ if (!entry) continue;
589
+ const colonIdx = entry.indexOf(':');
590
+ if (colonIdx < 0) {
591
+ out.push({ target: entry });
592
+ } else {
593
+ const target = entry.slice(0, colonIdx).trim();
594
+ const type = entry.slice(colonIdx + 1).trim();
595
+ if (!target) continue;
596
+ out.push(type ? { target, type } : { target });
597
+ }
598
+ }
599
+ return out;
600
+ }
601
+
602
+ function serializeConnectionsList(list: BlockConnection[]): string {
603
+ return list.map((c) => (c.type ? `${c.target}:${c.type}` : c.target)).join(',');
604
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Shared diagram constants — kept out of `DiagramCanvas.tsx` so that file can
3
+ * export only its component (which keeps React Fast Refresh working).
4
+ */
5
+
6
+ import { SelectTool, ConnectTool } from '../scene';
7
+
8
+ /**
9
+ * Viewport size for the diagram canvas — a wide-ish surface in author
10
+ * units. The Scene's fit-on-mount centers the diagram inside whatever
11
+ * container the canvas is rendered into. Exported so the host can place
12
+ * new nodes at the viewport center.
13
+ */
14
+ export const DIAGRAM_VIEWPORT = { width: 1600, height: 900 };
15
+
16
+ /** The diagram's tool vocabulary — surfaced in the shared block toolbar. */
17
+ export const DIAGRAM_TOOLS = [SelectTool, ConnectTool];