@bendyline/squisq-editor-react 1.5.3 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (165) hide show
  1. package/dist/index.d.ts +757 -20
  2. package/dist/index.js +16875 -6883
  3. package/dist/index.js.map +1 -1
  4. package/package.json +4 -4
  5. package/src/BlockCardView.tsx +121 -0
  6. package/src/BlockPreviewPanel.tsx +69 -0
  7. package/src/BlockPropertiesPopover.tsx +191 -0
  8. package/src/EditorContext.tsx +143 -0
  9. package/src/EditorShell.tsx +200 -120
  10. package/src/FolderView.tsx +131 -0
  11. package/src/Icon.tsx +26 -0
  12. package/src/ImageEditor.tsx +69 -22
  13. package/src/OutlinePanel.tsx +38 -3
  14. package/src/PlainHtmlPreview.tsx +30 -3
  15. package/src/PreviewControls.tsx +180 -8
  16. package/src/RawEditor.tsx +169 -13
  17. package/src/RecorderEntry.tsx +9 -16
  18. package/src/TemplateAnnotation.ts +44 -0
  19. package/src/TemplatePicker.tsx +329 -54
  20. package/src/ThemeCustomizerPanel.tsx +30 -336
  21. package/src/ThemePicker.tsx +112 -3
  22. package/src/TimelineBlockPreview.tsx +37 -0
  23. package/src/TimelineTrack.tsx +671 -0
  24. package/src/Toolbar.tsx +528 -174
  25. package/src/Tooltip.tsx +22 -4
  26. package/src/TransitionPicker.tsx +351 -0
  27. package/src/VersionHistoryPanel.tsx +2 -14
  28. package/src/ViewMenuPanel.tsx +17 -14
  29. package/src/WysiwygEditor.tsx +161 -65
  30. package/src/__tests__/blockProperties.test.ts +92 -0
  31. package/src/__tests__/blockRange.test.ts +105 -0
  32. package/src/__tests__/buildPreviewDocTransition.test.ts +73 -0
  33. package/src/__tests__/createShapeLayer.test.ts +46 -0
  34. package/src/__tests__/drawingShapeRoundTrip.test.ts +49 -0
  35. package/src/__tests__/embeddedMedia.test.ts +48 -0
  36. package/src/__tests__/headingTransition.test.ts +138 -0
  37. package/src/__tests__/layoutChildRoundTrip.test.ts +71 -0
  38. package/src/__tests__/plainHtmlPreview.test.tsx +10 -8
  39. package/src/__tests__/recorderMediaInsert.test.ts +86 -0
  40. package/src/__tests__/templateAnnotationRoundTrip.test.ts +18 -0
  41. package/src/__tests__/templatePickerMetadata.test.ts +32 -0
  42. package/src/__tests__/timelineSource.test.ts +134 -0
  43. package/src/__tests__/tiptapBridge.test.ts +92 -0
  44. package/src/__tests__/tiptapBridgeConformance.test.ts +47 -0
  45. package/src/__tests__/tooltip.test.tsx +72 -0
  46. package/src/__tests__/transitionCatalog.test.ts +64 -0
  47. package/src/__tests__/useBlockNavigator.test.tsx +67 -0
  48. package/src/__tests__/useMediaRecorder.test.ts +24 -0
  49. package/src/__tests__/useTimelineClock.test.ts +21 -0
  50. package/src/blockProperties.ts +88 -0
  51. package/src/blockRange.ts +132 -0
  52. package/src/buildPreviewDoc.ts +98 -9
  53. package/src/customTemplates/AddBin.tsx +126 -0
  54. package/src/customTemplates/CustomLayoutManager.tsx +233 -0
  55. package/src/customTemplates/CustomTemplateContext.tsx +182 -0
  56. package/src/customTemplates/LayerToolbar.tsx +580 -0
  57. package/src/customTemplates/ShapeGlyph.tsx +47 -0
  58. package/src/customTemplates/TemplateDesigner.tsx +430 -0
  59. package/src/customTemplates/__tests__/library.test.ts +88 -0
  60. package/src/customTemplates/__tests__/normalizePositions.test.ts +109 -0
  61. package/src/customTemplates/__tests__/shapeDefs.test.ts +49 -0
  62. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +95 -0
  63. package/src/customTemplates/designer.css +673 -0
  64. package/src/customTemplates/index.ts +31 -0
  65. package/src/customTemplates/library.ts +97 -0
  66. package/src/customTemplates/normalizePositions.ts +75 -0
  67. package/src/customTemplates/shapeDefs.ts +131 -0
  68. package/src/customTemplates/thumbnail.tsx +63 -0
  69. package/src/customTemplates/tokenDefs.ts +60 -0
  70. package/src/customTemplates/useDocCustomTemplates.ts +52 -0
  71. package/src/customTemplates/useMemoryLayerAdapter.ts +123 -0
  72. package/src/customThemes/CustomThemeContext.tsx +179 -0
  73. package/src/customThemes/CustomThemeDialog.tsx +286 -0
  74. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +64 -0
  75. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +47 -0
  76. package/src/customThemes/__tests__/customThemeLibrary.test.ts +51 -0
  77. package/src/customThemes/customThemeLibrary.ts +97 -0
  78. package/src/customThemes/index.ts +31 -0
  79. package/src/customThemes/themeControls.tsx +229 -0
  80. package/src/customThemes/themeDraft.ts +272 -0
  81. package/src/customThemes/useDocCustomThemes.ts +49 -0
  82. package/src/diagram/DiagramCanvas.tsx +240 -0
  83. package/src/diagram/DiagramExtension.ts +209 -0
  84. package/src/diagram/DiagramMaximizedOverlay.tsx +46 -0
  85. package/src/diagram/DiagramWidget.tsx +270 -0
  86. package/src/diagram/diagramCommands.ts +604 -0
  87. package/src/diagram/diagramConstants.ts +17 -0
  88. package/src/diagram/useDiagramData.ts +126 -0
  89. package/src/embeddedMedia.ts +78 -0
  90. package/src/frontmatter.ts +29 -0
  91. package/src/headingTransition.ts +231 -0
  92. package/src/imageEditor/CanvasSurface.tsx +383 -88
  93. package/src/imageEditor/PropertiesPanel.tsx +47 -1
  94. package/src/imageEditor/Toolbar.tsx +229 -16
  95. package/src/imageEditor/createShapeLayer.ts +280 -0
  96. package/src/imageEditor/icons.tsx +34 -114
  97. package/src/imageEditor/image-editor.css +54 -5
  98. package/src/imageEditor/state.ts +23 -3
  99. package/src/index.ts +77 -0
  100. package/src/recorder/RecorderModal.tsx +120 -53
  101. package/src/recorder/RecorderPanel.tsx +2 -26
  102. package/src/recorder/hooks/useMediaRecorder.ts +8 -1
  103. package/src/recorder/insertMediaBlock.ts +30 -0
  104. package/src/resolveBlockVisual.ts +33 -0
  105. package/src/scene/Scene.tsx +540 -0
  106. package/src/scene/SceneBlockExtension.ts +198 -0
  107. package/src/scene/SceneBlockToolbar.tsx +201 -0
  108. package/src/scene/SceneBlockWidget.tsx +434 -0
  109. package/src/scene/ScenePropsBar.tsx +85 -0
  110. package/src/scene/SceneSelection.tsx +107 -0
  111. package/src/scene/SceneViewport.tsx +102 -0
  112. package/src/scene/ShapePalette.tsx +181 -0
  113. package/src/scene/__tests__/DiagramAdapter.test.ts +56 -0
  114. package/src/scene/__tests__/bezierEdit.test.ts +85 -0
  115. package/src/scene/__tests__/blockLayers.test.ts +57 -0
  116. package/src/scene/__tests__/shapeLayers.test.ts +106 -0
  117. package/src/scene/__tests__/useSceneHitTest.test.ts +90 -0
  118. package/src/scene/__tests__/useScenePanZoom.test.ts +103 -0
  119. package/src/scene/adapters/DiagramAdapter.ts +168 -0
  120. package/src/scene/adapters/DrawingAdapter.ts +415 -0
  121. package/src/scene/adapters/LayoutAdapter.ts +310 -0
  122. package/src/scene/adapters/blockLayers.ts +159 -0
  123. package/src/scene/commands/SceneCommand.ts +70 -0
  124. package/src/scene/commands/drawingCommands.ts +318 -0
  125. package/src/scene/commands/layoutCommands.ts +301 -0
  126. package/src/scene/hooks/useSceneHitTest.ts +105 -0
  127. package/src/scene/hooks/useScenePanZoom.ts +147 -0
  128. package/src/scene/hooks/useSceneSelection.ts +62 -0
  129. package/src/scene/index.ts +95 -0
  130. package/src/scene/layers/DiagramEdges.tsx +127 -0
  131. package/src/scene/layers/edgeGeometry.ts +77 -0
  132. package/src/scene/layers/nodeCard.tsx +145 -0
  133. package/src/scene/layers/renderLayer.tsx +70 -0
  134. package/src/scene/layers/shapeLayers.ts +201 -0
  135. package/src/scene/paths/bezierEdit.ts +208 -0
  136. package/src/scene/scene.css +649 -0
  137. package/src/scene/text/SceneTextOverlay.tsx +161 -0
  138. package/src/scene/text/sceneTextChannel.ts +40 -0
  139. package/src/scene/text/sceneTextConfig.ts +27 -0
  140. package/src/scene/text/sceneTiptap.ts +36 -0
  141. package/src/scene/text/useSceneTextEditing.ts +39 -0
  142. package/src/scene/tools/ConnectTool.ts +111 -0
  143. package/src/scene/tools/DrawingConnectTool.ts +161 -0
  144. package/src/scene/tools/PathTool.ts +158 -0
  145. package/src/scene/tools/PlaceTool.ts +47 -0
  146. package/src/scene/tools/SceneTool.ts +75 -0
  147. package/src/scene/tools/SelectTool.ts +284 -0
  148. package/src/scene/tools/ShapeTool.ts +144 -0
  149. package/src/scene/tools/TextTool.ts +72 -0
  150. package/src/scene/tools/TokenTool.ts +95 -0
  151. package/src/scene/tools/createDrawShapeTool.ts +82 -0
  152. package/src/styles/diagram.css +183 -0
  153. package/src/styles/editor.css +1615 -203
  154. package/src/styles/folder-view.css +210 -0
  155. package/src/styles/image-edit-affordance.css +2 -2
  156. package/src/styles/index.css +4 -0
  157. package/src/timelineSource.ts +244 -0
  158. package/src/tiptapBridge.ts +115 -34
  159. package/src/tooltipPlacement.ts +13 -0
  160. package/src/transitionCatalog.ts +159 -0
  161. package/src/types/monaco-shims.d.ts +10 -0
  162. package/src/useBlockNavigator.ts +153 -0
  163. package/src/useMonacoLoader.ts +23 -1
  164. package/src/useTimelineClock.ts +76 -0
  165. package/src/utils/dropUtils.ts +1 -1
@@ -0,0 +1,318 @@
1
+ /**
2
+ * Tiptap commands for drawing editing.
3
+ *
4
+ * The drawing counterpart to `diagramCommands.ts`. Each command finds a
5
+ * shape's child heading inside a `{[drawing]}` section and mutates its
6
+ * `{[shape …]}` annotation (the `dataTemplate` + `dataTemplateParams` node
7
+ * attrs) or its text. Geometry/style live in the annotation params; the
8
+ * shape's id lives in `dataBlockAttrs` (`#id`). All edits round-trip back to
9
+ * markdown via `tiptapBridge` — no parallel data store.
10
+ *
11
+ * The section walk + a node rename are identical to diagrams, so those
12
+ * generic helpers are reused from `diagramCommands.ts`.
13
+ */
14
+
15
+ import type { Editor } from '@tiptap/react';
16
+ import type { Node as PMNode } from '@tiptap/pm/model';
17
+ import {
18
+ parsePandocAttrTokens,
19
+ serializePandocAttributes,
20
+ quoteAttrValue,
21
+ } from '@bendyline/squisq/markdown';
22
+ import {
23
+ listDiagramChildren,
24
+ getDiagramSectionEnd,
25
+ renameNode,
26
+ } from '../../diagram/diagramCommands';
27
+
28
+ /** Renaming a shape = replacing its heading text (same op as a diagram node). */
29
+ export { renameNode as renameShape };
30
+
31
+ export interface DrawingChild {
32
+ /** Heading node start position (absolute). */
33
+ pos: number;
34
+ node: PMNode;
35
+ /** Computed id (explicit `#id`, else slugified text). */
36
+ id: string;
37
+ /** Shape/connector kind from the `{[…]}` annotation (`dataTemplate`). */
38
+ kind: string | null;
39
+ /** Parsed `{[…]}` params (`dataTemplateParams`). */
40
+ params: Record<string, string>;
41
+ /** Heading text (the shape label). */
42
+ text: string;
43
+ }
44
+
45
+ /** List the drawing's child shapes/connectors with their annotation parsed. */
46
+ export function listDrawingChildren(editor: Editor, parentPos: number): DrawingChild[] {
47
+ return listDiagramChildren(editor, parentPos).map((c) => {
48
+ const a = c.node.attrs as { dataTemplate?: string | null; dataTemplateParams?: string | null };
49
+ return {
50
+ pos: c.pos,
51
+ node: c.node,
52
+ id: c.id,
53
+ kind: a.dataTemplate ?? null,
54
+ params: a.dataTemplateParams
55
+ ? (parsePandocAttrTokens(a.dataTemplateParams).params ?? {})
56
+ : {},
57
+ text: headingText(c.node),
58
+ };
59
+ });
60
+ }
61
+
62
+ /**
63
+ * Insert a new shape as a child heading at the end of the drawing section.
64
+ * The heading carries `dataTemplate=<kind>`, `dataTemplateParams=<geometry>`,
65
+ * and `dataBlockAttrs="#<id>"`, so it round-trips to `### label {#id} {[kind …]}`.
66
+ */
67
+ export function addShape(
68
+ editor: Editor,
69
+ parentPos: number,
70
+ id: string,
71
+ kind: string,
72
+ params: Record<string, string>,
73
+ label = '',
74
+ ): boolean {
75
+ const parent = editor.state.doc.nodeAt(parentPos);
76
+ if (!parent || parent.type.name !== 'heading') return false;
77
+ const childDepth = childDepthFor(editor, parentPos, parent);
78
+ const insertPos = getDiagramSectionEnd(editor, parentPos);
79
+ const tParams = serializeParams(params);
80
+ const blockAttrs = idToBlockAttrs(id);
81
+
82
+ return editor
83
+ .chain()
84
+ .command(({ tr, state }) => {
85
+ const headingType = state.schema.nodes.heading;
86
+ if (!headingType) return false;
87
+ const content = label.length > 0 ? state.schema.text(label) : null;
88
+ const heading = headingType.create(
89
+ {
90
+ level: childDepth,
91
+ dataTemplate: kind,
92
+ dataTemplateParams: tParams.length > 0 ? tParams : null,
93
+ dataBlockAttrs: blockAttrs,
94
+ },
95
+ content,
96
+ );
97
+ tr.insert(insertPos, heading);
98
+ return true;
99
+ })
100
+ .run();
101
+ }
102
+
103
+ /** Update a shape's `x`/`y` from a drag. */
104
+ export function moveShape(
105
+ editor: Editor,
106
+ parentPos: number,
107
+ id: string,
108
+ x: number,
109
+ y: number,
110
+ ): boolean {
111
+ return updateChildParams(editor, parentPos, id, (p) => {
112
+ p.x = String(Math.round(x));
113
+ p.y = String(Math.round(y));
114
+ });
115
+ }
116
+
117
+ /** Update a shape's `width`/`height` from a resize-handle drag. */
118
+ export function resizeShape(
119
+ editor: Editor,
120
+ parentPos: number,
121
+ id: string,
122
+ width: number,
123
+ height: number,
124
+ ): boolean {
125
+ return updateChildParams(editor, parentPos, id, (p) => {
126
+ p.width = String(Math.round(width));
127
+ p.height = String(Math.round(height));
128
+ });
129
+ }
130
+
131
+ /** Set (or, when value is empty, clear) a single style/param on a shape. */
132
+ export function setShapeParam(
133
+ editor: Editor,
134
+ parentPos: number,
135
+ id: string,
136
+ key: string,
137
+ value: string,
138
+ ): boolean {
139
+ return updateChildParams(editor, parentPos, id, (p) => {
140
+ if (value.length === 0) delete p[key];
141
+ else p[key] = value;
142
+ });
143
+ }
144
+
145
+ /** Set a connector's end-styles / line-style / routing params (empty value clears). */
146
+ export function setConnectorStyle(
147
+ editor: Editor,
148
+ parentPos: number,
149
+ id: string,
150
+ style: { startStyle?: string; endStyle?: string; lineStyle?: string; routing?: string },
151
+ ): boolean {
152
+ return updateChildParams(editor, parentPos, id, (p) => {
153
+ for (const [key, value] of Object.entries(style)) {
154
+ if (value == null || value.length === 0) delete p[key];
155
+ else p[key] = value;
156
+ }
157
+ });
158
+ }
159
+
160
+ /**
161
+ * Insert a connector (`{[arrow from=.. to=..]}`, or `line`) as a child
162
+ * heading joining two shapes by id.
163
+ */
164
+ export function addConnector(
165
+ editor: Editor,
166
+ parentPos: number,
167
+ id: string,
168
+ from: string,
169
+ to: string,
170
+ kind: 'arrow' | 'line' = 'arrow',
171
+ label = '',
172
+ ): boolean {
173
+ return addShape(editor, parentPos, id, kind, { from, to }, label);
174
+ }
175
+
176
+ /** Re-point a connector's `from` or `to` endpoint at a different shape. */
177
+ export function retargetConnector(
178
+ editor: Editor,
179
+ parentPos: number,
180
+ connectorId: string,
181
+ end: 'from' | 'to',
182
+ newTarget: string,
183
+ ): boolean {
184
+ return updateChildParams(editor, parentPos, connectorId, (p) => {
185
+ p[end] = newTarget;
186
+ });
187
+ }
188
+
189
+ /** Delete the connector heading joining `from`→`to`, if present. */
190
+ export function removeConnector(
191
+ editor: Editor,
192
+ parentPos: number,
193
+ from: string,
194
+ to: string,
195
+ ): boolean {
196
+ const target = listDrawingChildren(editor, parentPos).find(
197
+ (c) => isConnector(c) && c.params.from === from && c.params.to === to,
198
+ );
199
+ if (!target) return false;
200
+ const [start, end] = headingRange(editor, target.pos);
201
+ return editor
202
+ .chain()
203
+ .command(({ tr }) => {
204
+ tr.delete(start, end);
205
+ return true;
206
+ })
207
+ .run();
208
+ }
209
+
210
+ /**
211
+ * Delete a shape's heading (and body) plus any connector that referenced
212
+ * it. Ranges are computed against the original doc and deleted high→low so
213
+ * earlier deletions don't shift later positions.
214
+ */
215
+ export function removeShape(editor: Editor, parentPos: number, id: string): boolean {
216
+ const children = listDrawingChildren(editor, parentPos);
217
+ const target = children.find((c) => c.id === id);
218
+ if (!target) return false;
219
+
220
+ const ranges: Array<[number, number]> = [headingRange(editor, target.pos)];
221
+ for (const c of children) {
222
+ if (c.id === id) continue;
223
+ if (isConnector(c) && (c.params.from === id || c.params.to === id)) {
224
+ ranges.push(headingRange(editor, c.pos));
225
+ }
226
+ }
227
+ ranges.sort((a, b) => b[0] - a[0]);
228
+
229
+ return editor
230
+ .chain()
231
+ .command(({ tr }) => {
232
+ for (const [start, end] of ranges) tr.delete(start, end);
233
+ return true;
234
+ })
235
+ .run();
236
+ }
237
+
238
+ // ============================================
239
+ // Internal helpers
240
+ // ============================================
241
+
242
+ /** A `line`/`arrow` child carrying `from`/`to` is a connector (not a plain line). */
243
+ function isConnector(c: DrawingChild): boolean {
244
+ if (c.kind !== 'line' && c.kind !== 'arrow') return false;
245
+ return c.params.from != null || c.params.to != null;
246
+ }
247
+
248
+ /** Read params, mutate, and write the heading's `dataTemplateParams` back. */
249
+ function updateChildParams(
250
+ editor: Editor,
251
+ parentPos: number,
252
+ id: string,
253
+ mutate: (params: Record<string, string>) => void,
254
+ ): boolean {
255
+ const target = listDrawingChildren(editor, parentPos).find((c) => c.id === id);
256
+ if (!target) return false;
257
+ const params = { ...target.params };
258
+ mutate(params);
259
+ const tParams = serializeParams(params);
260
+ return editor
261
+ .chain()
262
+ .command(({ tr }) => {
263
+ if (!tr.doc.nodeAt(target.pos)) return false;
264
+ tr.setNodeAttribute(target.pos, 'dataTemplateParams', tParams.length > 0 ? tParams : null);
265
+ return true;
266
+ })
267
+ .run();
268
+ }
269
+
270
+ /** Heading section range `[start, end)` — the heading plus its body content. */
271
+ function headingRange(editor: Editor, pos: number): [number, number] {
272
+ const { state } = editor;
273
+ const node = state.doc.nodeAt(pos);
274
+ if (!node) return [pos, pos];
275
+ let cursor = pos + node.nodeSize;
276
+ const docSize = state.doc.content.size;
277
+ while (cursor < docSize) {
278
+ const n = state.doc.nodeAt(cursor);
279
+ if (!n) break;
280
+ if (n.type.name === 'heading') break;
281
+ cursor += n.nodeSize;
282
+ }
283
+ return [pos, cursor];
284
+ }
285
+
286
+ /** Child heading depth: inherit existing children's level, else parent+1. */
287
+ function childDepthFor(editor: Editor, parentPos: number, parent: PMNode): number {
288
+ const parentDepth = (parent.attrs as { level: number }).level;
289
+ const existing = listDrawingChildren(editor, parentPos);
290
+ const inherited = existing[0]?.node.attrs.level as number | undefined;
291
+ return Math.min(6, inherited ?? parentDepth + 1);
292
+ }
293
+
294
+ /** Serialize a param map to a `{[…]}` body string (`k=v k=v`), quoted canonically. */
295
+ function serializeParams(params: Record<string, string>): string {
296
+ return Object.entries(params)
297
+ .map(([k, v]) => `${k}=${quoteAttrValue(v)}`)
298
+ .join(' ');
299
+ }
300
+
301
+ /** The `#id` inner string for `dataBlockAttrs` (no outer braces). */
302
+ function idToBlockAttrs(id: string): string | null {
303
+ return stripBraces(serializePandocAttributes({ id }));
304
+ }
305
+
306
+ function stripBraces(s: string | null): string | null {
307
+ if (s == null || s === '{}') return null;
308
+ if (s.startsWith('{') && s.endsWith('}')) return s.slice(1, -1);
309
+ return s;
310
+ }
311
+
312
+ function headingText(node: PMNode): string {
313
+ let text = '';
314
+ node.content.forEach((child) => {
315
+ if (child.isText) text += child.text ?? '';
316
+ });
317
+ return text;
318
+ }
@@ -0,0 +1,301 @@
1
+ /**
2
+ * Tiptap commands for layout editing.
3
+ *
4
+ * The layout counterpart to `drawingCommands.ts`: each layer is a child
5
+ * heading inside a `{[layout]}` section, and its `{[type …]}` annotation
6
+ * (`dataTemplate` + `dataTemplateParams`) carries geometry/style while its
7
+ * `{#id}` lives in `dataBlockAttrs`. The one difference from drawing is
8
+ * that a **text** layer's content lives in the child heading's *body*
9
+ * (paragraphs/lists/marks) rather than the heading text — so it round-trips
10
+ * to readable markdown. All edits flow through the main editor's
11
+ * transactions, so the doc's normal save path serializes them; there is no
12
+ * parallel data store.
13
+ *
14
+ * The section walk is identical to diagrams/drawings, so those generic
15
+ * helpers are reused from `diagramCommands.ts`.
16
+ */
17
+
18
+ import type { Editor } from '@tiptap/react';
19
+ import type { Node as PMNode, Schema } from '@tiptap/pm/model';
20
+ import { DOMSerializer, DOMParser as PMDOMParser, Fragment } from '@tiptap/pm/model';
21
+ import {
22
+ parsePandocAttrTokens,
23
+ serializePandocAttributes,
24
+ quoteAttrValue,
25
+ } from '@bendyline/squisq/markdown';
26
+ import { listDiagramChildren } from '../../diagram/diagramCommands';
27
+
28
+ export interface LayoutChild {
29
+ /** Heading node start position (absolute). */
30
+ pos: number;
31
+ node: PMNode;
32
+ /** Computed id (explicit `#id`, else slugified text). */
33
+ id: string;
34
+ /** Layer kind from the `{[…]}` annotation (`text`/`rectangle`/`image`/…). */
35
+ kind: string | null;
36
+ /** Parsed `{[…]}` params (`dataTemplateParams`). */
37
+ params: Record<string, string>;
38
+ /** The child's body serialized to HTML (a text layer's rich content). */
39
+ bodyHtml: string;
40
+ /** Plain text of the body (newline-joined across block nodes). */
41
+ bodyText: string;
42
+ }
43
+
44
+ /** List the layout's child layers with their annotation + body parsed. */
45
+ export function listLayoutChildren(editor: Editor, parentPos: number): LayoutChild[] {
46
+ return listDiagramChildren(editor, parentPos).map((c) => {
47
+ const a = c.node.attrs as { dataTemplate?: string | null; dataTemplateParams?: string | null };
48
+ return {
49
+ pos: c.pos,
50
+ node: c.node,
51
+ id: c.id,
52
+ kind: a.dataTemplate ?? null,
53
+ params: a.dataTemplateParams
54
+ ? (parsePandocAttrTokens(a.dataTemplateParams).params ?? {})
55
+ : {},
56
+ bodyHtml: bodyToHtml(editor, c.pos, c.node),
57
+ bodyText: bodyToText(editor, c.pos, c.node),
58
+ };
59
+ });
60
+ }
61
+
62
+ /**
63
+ * Insert a new layer as a child heading at the end of the layout section.
64
+ * The heading carries `dataTemplate=<kind>`, `dataTemplateParams=<geometry>`,
65
+ * and `dataBlockAttrs="#<id>"`; a non-empty `bodyHtml` is parsed into the
66
+ * child's body so it round-trips to `### {#id} {[kind …]}` + markdown body.
67
+ */
68
+ export function addLayoutLayer(
69
+ editor: Editor,
70
+ parentPos: number,
71
+ id: string,
72
+ kind: string,
73
+ params: Record<string, string>,
74
+ bodyHtml = '',
75
+ ): boolean {
76
+ const parent = editor.state.doc.nodeAt(parentPos);
77
+ if (!parent || parent.type.name !== 'heading') return false;
78
+ const childDepth = childDepthFor(editor, parentPos, parent);
79
+ const insertPos = layoutInsertPos(editor, parentPos);
80
+ const tParams = serializeParams(params);
81
+ const blockAttrs = idToBlockAttrs(id);
82
+
83
+ return editor
84
+ .chain()
85
+ .command(({ tr, state }) => {
86
+ const headingType = state.schema.nodes.heading;
87
+ if (!headingType) return false;
88
+ const heading = headingType.create({
89
+ level: childDepth,
90
+ dataTemplate: kind,
91
+ dataTemplateParams: tParams.length > 0 ? tParams : null,
92
+ dataBlockAttrs: blockAttrs,
93
+ });
94
+ let content = Fragment.from(heading);
95
+ if (bodyHtml.trim()) content = content.append(htmlToBody(state.schema, bodyHtml));
96
+ tr.insert(insertPos, content);
97
+ return true;
98
+ })
99
+ .run();
100
+ }
101
+
102
+ /** Update a layer's `x`/`y` from a drag. */
103
+ export function moveLayoutLayer(
104
+ editor: Editor,
105
+ parentPos: number,
106
+ id: string,
107
+ x: number,
108
+ y: number,
109
+ ): boolean {
110
+ return updateChildParams(editor, parentPos, id, (p) => {
111
+ p.x = String(Math.round(x));
112
+ p.y = String(Math.round(y));
113
+ });
114
+ }
115
+
116
+ /** Update a layer's `width`/`height` from a resize-handle drag. */
117
+ export function resizeLayoutLayer(
118
+ editor: Editor,
119
+ parentPos: number,
120
+ id: string,
121
+ width: number,
122
+ height: number,
123
+ ): boolean {
124
+ return updateChildParams(editor, parentPos, id, (p) => {
125
+ p.width = String(Math.round(width));
126
+ p.height = String(Math.round(height));
127
+ });
128
+ }
129
+
130
+ /** Set (or, when value is empty, clear) a single style/param on a layer. */
131
+ export function setLayoutParam(
132
+ editor: Editor,
133
+ parentPos: number,
134
+ id: string,
135
+ key: string,
136
+ value: string,
137
+ ): boolean {
138
+ return updateChildParams(editor, parentPos, id, (p) => {
139
+ if (value.length === 0) delete p[key];
140
+ else p[key] = value;
141
+ });
142
+ }
143
+
144
+ /**
145
+ * Replace a text layer's body with the content parsed from `bodyHtml`
146
+ * (an empty value clears it). The heading + its `{[text …]}` annotation are
147
+ * preserved; only the body changes.
148
+ */
149
+ export function setLayoutText(
150
+ editor: Editor,
151
+ parentPos: number,
152
+ id: string,
153
+ bodyHtml: string,
154
+ ): boolean {
155
+ const target = listLayoutChildren(editor, parentPos).find((c) => c.id === id);
156
+ if (!target) return false;
157
+ const bodyStart = target.pos + target.node.nodeSize;
158
+ const [, bodyEnd] = headingRange(editor, target.pos);
159
+ return editor
160
+ .chain()
161
+ .command(({ tr, state }) => {
162
+ if (!tr.doc.nodeAt(target.pos)) return false;
163
+ const body = bodyHtml.trim() ? htmlToBody(state.schema, bodyHtml) : Fragment.empty;
164
+ tr.replaceWith(bodyStart, bodyEnd, body);
165
+ return true;
166
+ })
167
+ .run();
168
+ }
169
+
170
+ /** Delete a layer's heading and its body. */
171
+ export function removeLayoutLayer(editor: Editor, parentPos: number, id: string): boolean {
172
+ const target = listLayoutChildren(editor, parentPos).find((c) => c.id === id);
173
+ if (!target) return false;
174
+ const [start, end] = headingRange(editor, target.pos);
175
+ return editor
176
+ .chain()
177
+ .command(({ tr }) => {
178
+ tr.delete(start, end);
179
+ return true;
180
+ })
181
+ .run();
182
+ }
183
+
184
+ // ============================================
185
+ // Internal helpers
186
+ // ============================================
187
+
188
+ /** Read params, mutate, and write the heading's `dataTemplateParams` back. */
189
+ function updateChildParams(
190
+ editor: Editor,
191
+ parentPos: number,
192
+ id: string,
193
+ mutate: (params: Record<string, string>) => void,
194
+ ): boolean {
195
+ const target = listLayoutChildren(editor, parentPos).find((c) => c.id === id);
196
+ if (!target) return false;
197
+ const params = { ...target.params };
198
+ mutate(params);
199
+ const tParams = serializeParams(params);
200
+ return editor
201
+ .chain()
202
+ .command(({ tr }) => {
203
+ if (!tr.doc.nodeAt(target.pos)) return false;
204
+ tr.setNodeAttribute(target.pos, 'dataTemplateParams', tParams.length > 0 ? tParams : null);
205
+ return true;
206
+ })
207
+ .run();
208
+ }
209
+
210
+ /**
211
+ * Body range `[start, end)` for a layout child — the heading plus its body,
212
+ * stopping at the next heading OR a horizontal rule. A layout textbox can't
213
+ * contain an `hr` (the `block` editor level forbids it), so a `---` always
214
+ * marks the end of the layout's content; bounding on it keeps a trailing
215
+ * child's body from swallowing loose document content that follows the
216
+ * layout block (e.g. a closing paragraph after a `---`).
217
+ */
218
+ function headingRange(editor: Editor, pos: number): [number, number] {
219
+ const { state } = editor;
220
+ const node = state.doc.nodeAt(pos);
221
+ if (!node) return [pos, pos];
222
+ let cursor = pos + node.nodeSize;
223
+ const docSize = state.doc.content.size;
224
+ while (cursor < docSize) {
225
+ const n = state.doc.nodeAt(cursor);
226
+ if (!n) break;
227
+ if (n.type.name === 'heading' || n.type.name === 'horizontalRule') break;
228
+ cursor += n.nodeSize;
229
+ }
230
+ return [pos, cursor];
231
+ }
232
+
233
+ /** Serialize a child's body fragment to HTML (a text layer's rich content). */
234
+ function bodyToHtml(editor: Editor, headingPos: number, headingNode: PMNode): string {
235
+ const { state } = editor;
236
+ const bodyStart = headingPos + headingNode.nodeSize;
237
+ const [, bodyEnd] = headingRange(editor, headingPos);
238
+ if (bodyEnd <= bodyStart) return '';
239
+ const fragment = state.doc.slice(bodyStart, bodyEnd).content;
240
+ if (fragment.size === 0) return '';
241
+ const dom = DOMSerializer.fromSchema(state.schema).serializeFragment(fragment);
242
+ const div = document.createElement('div');
243
+ div.appendChild(dom);
244
+ return div.innerHTML;
245
+ }
246
+
247
+ /** Plain text of a child's body (newline-joined across block nodes). */
248
+ function bodyToText(editor: Editor, headingPos: number, headingNode: PMNode): string {
249
+ const { state } = editor;
250
+ const bodyStart = headingPos + headingNode.nodeSize;
251
+ const [, bodyEnd] = headingRange(editor, headingPos);
252
+ if (bodyEnd <= bodyStart) return '';
253
+ return state.doc.textBetween(bodyStart, bodyEnd, '\n').trim();
254
+ }
255
+
256
+ /** Parse Tiptap HTML into a Fragment of block nodes for the doc body. */
257
+ function htmlToBody(schema: Schema, html: string): Fragment {
258
+ const div = document.createElement('div');
259
+ div.innerHTML = html;
260
+ return PMDOMParser.fromSchema(schema).parse(div).content;
261
+ }
262
+
263
+ /**
264
+ * Where to append a new layer heading: after the last child's bounded body
265
+ * (or, with no children, after the parent heading's bounded body). Unlike
266
+ * `getDiagramSectionEnd` (which runs to the next ≤parent heading and so spans
267
+ * any trailing loose document content), this stops at the layout's `---`/next
268
+ * heading boundary — so new children don't leapfrog content that follows the
269
+ * layout block.
270
+ */
271
+ function layoutInsertPos(editor: Editor, parentPos: number): number {
272
+ const children = listLayoutChildren(editor, parentPos);
273
+ const anchor = children.length > 0 ? children[children.length - 1].pos : parentPos;
274
+ return headingRange(editor, anchor)[1];
275
+ }
276
+
277
+ /** Child heading depth: inherit existing children's level, else parent+1. */
278
+ function childDepthFor(editor: Editor, parentPos: number, parent: PMNode): number {
279
+ const parentDepth = (parent.attrs as { level: number }).level;
280
+ const existing = listLayoutChildren(editor, parentPos);
281
+ const inherited = existing[0]?.node.attrs.level as number | undefined;
282
+ return Math.min(6, inherited ?? parentDepth + 1);
283
+ }
284
+
285
+ /** Serialize a param map to a `{[…]}` body string (`k=v k=v`), quoted canonically. */
286
+ function serializeParams(params: Record<string, string>): string {
287
+ return Object.entries(params)
288
+ .map(([k, v]) => `${k}=${quoteAttrValue(v)}`)
289
+ .join(' ');
290
+ }
291
+
292
+ /** The `#id` inner string for `dataBlockAttrs` (no outer braces). */
293
+ function idToBlockAttrs(id: string): string | null {
294
+ return stripBraces(serializePandocAttributes({ id }));
295
+ }
296
+
297
+ function stripBraces(s: string | null): string | null {
298
+ if (s == null || s === '{}') return null;
299
+ if (s.startsWith('{') && s.endsWith('}')) return s.slice(1, -1);
300
+ return s;
301
+ }