@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,240 @@
1
+ /**
2
+ * DiagramCanvas — thin wrapper around the Squisq Scene engine.
3
+ *
4
+ * Translates between the diagram's command vocabulary (which the host
5
+ * `DiagramWidget` translates into Tiptap mutations) and the Scene's
6
+ * generic SceneCommand vocabulary. The Scene itself owns viewport
7
+ * pan/zoom, selection, hit-testing, and tool dispatch.
8
+ *
9
+ * Diagram nodes are rendered as synthetic card+label Layer pairs
10
+ * (`nodeCard.tsx`) so what you see in the editor is the same Layer
11
+ * schema the SSR `diagramBlock.ts` template emits. Edges are drawn by
12
+ * `<DiagramEdges>` as a separate background layer.
13
+ */
14
+
15
+ import { useCallback, useMemo, useRef, useState } from 'react';
16
+ import {
17
+ Scene,
18
+ buildDiagramScene,
19
+ nodeIdFromCardLayerId,
20
+ diagramLayerFollows,
21
+ DiagramEdges,
22
+ type SceneCommand,
23
+ } from '../scene';
24
+ import type { SceneTextEditConfig } from '../scene/text/sceneTextConfig';
25
+ import { markdownToTiptap } from '../tiptapBridge';
26
+ import type { DiagramRFNode, DiagramRFEdge } from './useDiagramData';
27
+ import { DIAGRAM_VIEWPORT, DIAGRAM_TOOLS } from './diagramConstants';
28
+
29
+ export type DiagramCommand =
30
+ | { kind: 'moveNode'; nodeId: string; x: number; y: number }
31
+ | { kind: 'resizeNode'; nodeId: string; width: number; height: number }
32
+ | { kind: 'addConnection'; source: string; target: string; type?: string }
33
+ | { kind: 'removeConnection'; source: string; target: string; type?: string }
34
+ | { kind: 'renameNode'; nodeId: string; newLabel: string }
35
+ | { kind: 'addNode'; x: number; y: number }
36
+ | { kind: 'removeNode'; nodeId: string };
37
+
38
+ interface DiagramCanvasProps {
39
+ nodes: DiagramRFNode[];
40
+ edges: DiagramRFEdge[];
41
+ onCommand: (cmd: DiagramCommand) => void;
42
+ /** When true, render the maximize button. Click toggles `onToggleMaximize`. */
43
+ showMaximize?: boolean;
44
+ /** Whether the canvas is currently maximized (affects button icon). */
45
+ maximized?: boolean;
46
+ /** Callback when the maximize button is clicked. */
47
+ onToggleMaximize?: () => void;
48
+ /**
49
+ * Active tool id, controlled by the host (DiagramWidget) so the tool
50
+ * buttons can live in the shared toolbar above the canvas. Falls back
51
+ * to internal state when omitted.
52
+ */
53
+ activeToolId?: string;
54
+ onActiveToolIdChange?: (id: string) => void;
55
+ /** Forwarded to the Scene so the host can drive a Delete action. */
56
+ onSelectionChange?: (ids: ReadonlySet<string>) => void;
57
+ }
58
+
59
+ const TOOLS = DIAGRAM_TOOLS;
60
+
61
+ export function DiagramCanvas({
62
+ nodes: incomingNodes,
63
+ edges: incomingEdges,
64
+ onCommand,
65
+ showMaximize = true,
66
+ maximized = false,
67
+ onToggleMaximize,
68
+ activeToolId: controlledToolId,
69
+ onActiveToolIdChange,
70
+ onSelectionChange,
71
+ }: DiagramCanvasProps) {
72
+ const scene = useMemo(
73
+ () => buildDiagramScene(incomingNodes, incomingEdges),
74
+ [incomingNodes, incomingEdges],
75
+ );
76
+ // Track the active tool so we can keep selection when the user toggles
77
+ // back to Select after using Connect. Controlled by the host when it
78
+ // owns the shared toolbar; falls back to internal state otherwise.
79
+ const [internalToolId, setInternalToolId] = useState<string>('select');
80
+ const activeToolId = controlledToolId ?? internalToolId;
81
+ const setActiveToolId = onActiveToolIdChange ?? setInternalToolId;
82
+
83
+ // Translate generic SceneCommand → diagram-specific DiagramCommand,
84
+ // then hand off to the host (DiagramWidget) which writes to Tiptap.
85
+ const handleSceneCommand = useCallback(
86
+ (cmd: SceneCommand) => {
87
+ switch (cmd.kind) {
88
+ case 'moveLayer': {
89
+ // Only the node-card layer carries the position; ignore drag
90
+ // commits on the label layer (it'd duplicate the write).
91
+ if (!cmd.id.startsWith('node-card-')) return;
92
+ const nodeId = nodeIdFromCardLayerId(cmd.id);
93
+ if (!nodeId) return;
94
+ onCommand({ kind: 'moveNode', nodeId, x: cmd.x, y: cmd.y });
95
+ return;
96
+ }
97
+ case 'addEdge':
98
+ onCommand({
99
+ kind: 'addConnection',
100
+ source: cmd.source,
101
+ target: cmd.target,
102
+ type: cmd.type,
103
+ });
104
+ return;
105
+ case 'removeEdge':
106
+ onCommand({
107
+ kind: 'removeConnection',
108
+ source: cmd.source,
109
+ target: cmd.target,
110
+ type: cmd.type,
111
+ });
112
+ return;
113
+ case 'removeLayer': {
114
+ const nodeId = nodeIdFromCardLayerId(cmd.id);
115
+ if (nodeId) onCommand({ kind: 'removeNode', nodeId });
116
+ return;
117
+ }
118
+ case 'renameLayer': {
119
+ const nodeId = nodeIdFromCardLayerId(cmd.id);
120
+ if (nodeId) onCommand({ kind: 'renameNode', nodeId, newLabel: cmd.label });
121
+ return;
122
+ }
123
+ case 'setLayerText': {
124
+ // Diagram node labels persist as heading text (markdown inline
125
+ // marks); the rich `html` is not stored separately.
126
+ const nodeId = nodeIdFromCardLayerId(cmd.id);
127
+ if (nodeId) onCommand({ kind: 'renameNode', nodeId, newLabel: cmd.text });
128
+ return;
129
+ }
130
+ case 'addLayer': {
131
+ // Diagram mode interprets addLayer as "add a node at the layer's
132
+ // position". The Scene's empty-state "add" button and any future
133
+ // double-click handler dispatch this.
134
+ const pos = cmd.layer.position;
135
+ const x = typeof pos.x === 'number' ? pos.x : 0;
136
+ const y = typeof pos.y === 'number' ? pos.y : 0;
137
+ onCommand({ kind: 'addNode', x, y });
138
+ return;
139
+ }
140
+ case 'resizeLayer': {
141
+ if (!cmd.id.startsWith('node-card-')) return;
142
+ const nodeId = nodeIdFromCardLayerId(cmd.id);
143
+ if (!nodeId) return;
144
+ onCommand({ kind: 'resizeNode', nodeId, width: cmd.width, height: cmd.height });
145
+ return;
146
+ }
147
+ case 'setLayerAttr':
148
+ // Diagram nodes don't expose generic attr writes; renames go
149
+ // through `renameLayer` and positions through move/resize.
150
+ return;
151
+ }
152
+ const _exhaustive: never = cmd;
153
+ void _exhaustive;
154
+ },
155
+ [onCommand],
156
+ );
157
+
158
+ // Edges render in the renderExtras callback so they sit behind the
159
+ // node cards (which the Scene renders itself).
160
+ const nodesForExtras = scene.nodes;
161
+ const edgesForExtras = scene.edges;
162
+ const renderExtras = useCallback(
163
+ () => <DiagramEdges nodes={nodesForExtras} edges={edgesForExtras} />,
164
+ [nodesForExtras, edgesForExtras],
165
+ );
166
+
167
+ // Inline label editing: double-click a node card to edit its label.
168
+ // Labels persist as the node's heading text (inline markdown marks), so
169
+ // the editor is `inline` level. Refs keep the config stable.
170
+ const incomingNodesRef = useRef(incomingNodes);
171
+ incomingNodesRef.current = incomingNodes;
172
+ const textConfig = useMemo<SceneTextEditConfig>(
173
+ () => ({
174
+ resolveEditableId: (id) => (nodeIdFromCardLayerId(id) ? id : null),
175
+ getHtml: (id) => {
176
+ const nodeId = nodeIdFromCardLayerId(id);
177
+ const node = incomingNodesRef.current.find((n) => n.id === nodeId);
178
+ return markdownToTiptap(node?.data.label ?? '');
179
+ },
180
+ commit: (id, { text }) => {
181
+ // Node labels persist as plain heading text for now (rich marks on
182
+ // labels are a follow-up — the rendering foundation is in place).
183
+ handleSceneCommand({ kind: 'renameLayer', id, label: text });
184
+ },
185
+ level: 'inline',
186
+ }),
187
+ [handleSceneCommand],
188
+ );
189
+
190
+ return (
191
+ <div className="squisq-diagram-canvas">
192
+ <Scene
193
+ viewport={DIAGRAM_VIEWPORT}
194
+ layers={scene.layers}
195
+ edges={scene.edges}
196
+ tools={TOOLS}
197
+ activeToolId={activeToolId}
198
+ onActiveToolIdChange={setActiveToolId}
199
+ onSelectionChange={onSelectionChange}
200
+ onCommand={handleSceneCommand}
201
+ renderExtras={renderExtras}
202
+ layerFollows={diagramLayerFollows}
203
+ showMaximize={showMaximize}
204
+ maximized={maximized}
205
+ onToggleMaximize={onToggleMaximize}
206
+ showToolbar={false}
207
+ textEditing={textConfig}
208
+ />
209
+ {scene.nodes.length === 0 && (
210
+ <DiagramEmptyState
211
+ onAdd={() => {
212
+ // Place the first node at the center of the viewport's
213
+ // logical surface; the Scene's fit-on-mount keeps it visible.
214
+ onCommand({
215
+ kind: 'addNode',
216
+ x: DIAGRAM_VIEWPORT.width / 2 - 90,
217
+ y: DIAGRAM_VIEWPORT.height / 2 - 32,
218
+ });
219
+ }}
220
+ />
221
+ )}
222
+ </div>
223
+ );
224
+ }
225
+
226
+ function DiagramEmptyState({ onAdd }: { onAdd: () => void }) {
227
+ return (
228
+ <div className="squisq-diagram-empty">
229
+ <div className="squisq-diagram-empty-title">No diagram nodes yet</div>
230
+ <div className="squisq-diagram-empty-hint">
231
+ Click "+ Add first node" below, or add sub-headings under this block.
232
+ </div>
233
+ <button type="button" className="squisq-diagram-empty-btn" onClick={onAdd}>
234
+ + Add first node
235
+ </button>
236
+ </div>
237
+ );
238
+ }
239
+
240
+ export default DiagramCanvas;
@@ -0,0 +1,209 @@
1
+ /**
2
+ * DiagramExtension — Tiptap/ProseMirror plugin that:
3
+ *
4
+ * 1. Mounts a React-Flow canvas (`DiagramWidget`) immediately after every
5
+ * heading whose `dataTemplate === 'diagram'`.
6
+ * 2. Hides the direct sub-headings of each diagram parent (until the next
7
+ * equal-or-shallower heading) by tagging them with a `data-squisq-diagram-child`
8
+ * attribute — CSS in `styles/diagram.css` does the actual hiding.
9
+ *
10
+ * Widgets are rendered as plain DOM nodes attached to a ProseMirror
11
+ * `Decoration.widget`. React is mounted into the widget DOM with
12
+ * `react-dom/client`'s `createRoot`, and unmounted on the widget's
13
+ * `destroy` hook.
14
+ */
15
+
16
+ import { Extension } from '@tiptap/core';
17
+ import { Plugin, PluginKey } from '@tiptap/pm/state';
18
+ import { Decoration, DecorationSet } from '@tiptap/pm/view';
19
+ import type { EditorState } from '@tiptap/pm/state';
20
+ import type { Editor } from '@tiptap/react';
21
+ import { createRoot, type Root } from 'react-dom/client';
22
+ import { createElement } from 'react';
23
+ import type { Node as PMNode } from '@tiptap/pm/model';
24
+ import { parsePandocAttrTokens } from '@bendyline/squisq/markdown';
25
+ import { DiagramWidget } from './DiagramWidget';
26
+
27
+ /**
28
+ * Stable identifier for a diagram heading — prefers the persisted
29
+ * Pandoc `#id`, falls back to a slugified version of the heading's
30
+ * text. Used as part of the widget decoration's `key` so the widget
31
+ * survives attribute-only doc changes (drag/resize commits).
32
+ */
33
+ export function getHeadingKey(node: PMNode): string {
34
+ const raw = (node.attrs as Record<string, unknown>).dataBlockAttrs;
35
+ if (typeof raw === 'string' && raw.length > 0) {
36
+ const attrs = parsePandocAttrTokens(raw);
37
+ if (attrs.id) return attrs.id;
38
+ }
39
+ let text = '';
40
+ node.content.forEach((child) => {
41
+ if (child.isText) text += child.text ?? '';
42
+ });
43
+ return (
44
+ text
45
+ .toLowerCase()
46
+ .replace(/[^\w\s-]/g, '')
47
+ .replace(/[\s_]+/g, '-')
48
+ .replace(/-+/g, '-')
49
+ .replace(/^-|-$/g, '') || 'block'
50
+ );
51
+ }
52
+
53
+ /**
54
+ * Find the current document position of a diagram heading by its
55
+ * stable key. Returns `null` if the heading no longer exists (e.g. the
56
+ * user removed it). Used by the widget to re-resolve its parent
57
+ * position on every read, since the kept-alive widget's captured
58
+ * `parentPos` would otherwise go stale when content above shifts.
59
+ */
60
+ export function findDiagramHeadingPos(editor: Editor, headingKey: string): number | null {
61
+ let found: number | null = null;
62
+ editor.state.doc.descendants((node, pos) => {
63
+ if (found != null) return false;
64
+ if (node.type.name !== 'heading') return;
65
+ const attrs = node.attrs as { dataTemplate?: string };
66
+ if (attrs.dataTemplate !== 'diagram') return;
67
+ if (getHeadingKey(node) === headingKey) {
68
+ found = pos;
69
+ return false;
70
+ }
71
+ });
72
+ return found;
73
+ }
74
+
75
+ const KEY = new PluginKey('squisq-diagram');
76
+
77
+ interface DiagramRoot {
78
+ el: HTMLElement;
79
+ root: Root;
80
+ }
81
+
82
+ function buildDecorations(state: EditorState, editor: Editor): DecorationSet {
83
+ const decos: Decoration[] = [];
84
+
85
+ state.doc.descendants((node, pos) => {
86
+ if (node.type.name !== 'heading') return;
87
+ const attrs = node.attrs as { level: number; dataTemplate?: string };
88
+ if (attrs.dataTemplate === 'diagram') {
89
+ const parentDepth = attrs.level;
90
+ const widgetPos = pos + node.nodeSize;
91
+ const parentPos = pos;
92
+ // Stable widget key derived from the heading's persisted id (or its
93
+ // text-derived slug). ProseMirror treats decorations with matching
94
+ // keys as equal, so it keeps the existing widget DOM (and the
95
+ // mounted React root) across attribute-only doc changes — which
96
+ // happen on every drag commit when we write `x=`/`y=` back to the
97
+ // heading. Without this, every drop would destroy and recreate the
98
+ // canvas, blowing away pan/zoom and making the cards appear to snap
99
+ // back to their pre-fit position.
100
+ const headingKey = getHeadingKey(node);
101
+ decos.push(
102
+ Decoration.widget(
103
+ widgetPos,
104
+ (view) => {
105
+ const container = document.createElement('div');
106
+ container.className = 'squisq-diagram-widget-host';
107
+ container.contentEditable = 'false';
108
+ // Stop ProseMirror from treating clicks/keys inside the
109
+ // widget as document interactions.
110
+ container.addEventListener('mousedown', (e) => e.stopPropagation());
111
+ container.addEventListener('keydown', (e) => e.stopPropagation());
112
+
113
+ const root = createRoot(container);
114
+ root.render(
115
+ createElement(DiagramWidget, {
116
+ editor,
117
+ headingKey,
118
+ fallbackParentPos: parentPos,
119
+ host: view.dom.parentElement ?? view.dom,
120
+ }),
121
+ );
122
+
123
+ // Stash for destroy.
124
+ (container as HTMLElement & { __squisqDiagramRoot?: DiagramRoot }).__squisqDiagramRoot =
125
+ {
126
+ el: container,
127
+ root,
128
+ };
129
+ return container;
130
+ },
131
+ {
132
+ destroy: (dom) => {
133
+ const ref = (dom as HTMLElement & { __squisqDiagramRoot?: DiagramRoot })
134
+ .__squisqDiagramRoot;
135
+ if (ref) {
136
+ // Defer to next tick so React isn't unmounted mid-render.
137
+ setTimeout(() => ref.root.unmount(), 0);
138
+ }
139
+ },
140
+ // Cluster the widget tightly after the heading; don't side-bias.
141
+ side: 1,
142
+ ignoreSelection: true,
143
+ key: `squisq-diagram-${headingKey}`,
144
+ },
145
+ ),
146
+ );
147
+
148
+ // Mark child headings (depth = parentDepth + 1 .. 6, until next ≤parentDepth).
149
+ let cursor = pos + node.nodeSize;
150
+ while (cursor < state.doc.content.size) {
151
+ const child = state.doc.nodeAt(cursor);
152
+ if (!child) break;
153
+ if (child.type.name === 'heading') {
154
+ const childLevel = (child.attrs as { level: number }).level;
155
+ if (childLevel <= parentDepth) break;
156
+ decos.push(
157
+ Decoration.node(cursor, cursor + child.nodeSize, {
158
+ 'data-squisq-diagram-child': 'true',
159
+ }),
160
+ );
161
+ }
162
+ cursor += child.nodeSize;
163
+ }
164
+ }
165
+ });
166
+
167
+ return DecorationSet.create(state.doc, decos);
168
+ }
169
+
170
+ export interface DiagramExtensionOptions {
171
+ /** When false, the extension is inert (no widgets, no decorations). */
172
+ enabled?: boolean;
173
+ }
174
+
175
+ export const DiagramExtension = Extension.create<DiagramExtensionOptions>({
176
+ name: 'squisqDiagram',
177
+
178
+ addOptions() {
179
+ return {
180
+ enabled: true,
181
+ };
182
+ },
183
+
184
+ addProseMirrorPlugins() {
185
+ const editor = this.editor as Editor;
186
+ const enabled = this.options.enabled !== false;
187
+ if (!enabled) return [];
188
+
189
+ return [
190
+ new Plugin({
191
+ key: KEY,
192
+ state: {
193
+ init: (_config, state) => buildDecorations(state, editor),
194
+ apply: (tr, oldDecos, _oldState, newState) => {
195
+ if (!tr.docChanged) return oldDecos;
196
+ return buildDecorations(newState, editor);
197
+ },
198
+ },
199
+ props: {
200
+ decorations(state) {
201
+ return this.getState(state);
202
+ },
203
+ },
204
+ }),
205
+ ];
206
+ },
207
+ });
208
+
209
+ export default DiagramExtension;
@@ -0,0 +1,46 @@
1
+ /**
2
+ * DiagramMaximizedOverlay — full-editor overlay that hosts the diagram
3
+ * canvas when the user clicks the maximize button.
4
+ *
5
+ * Positions over the closest `position: relative` / `position: absolute`
6
+ * ancestor (in practice, the editor shell's root). `Esc` and an overlay
7
+ * close button both call `onClose`.
8
+ */
9
+
10
+ import { useEffect } from 'react';
11
+ import { createPortal } from 'react-dom';
12
+
13
+ interface DiagramMaximizedOverlayProps {
14
+ /** DOM node to portal into. Falls back to document.body. */
15
+ host?: HTMLElement | null;
16
+ /** Closes the overlay (e.g., returns to inline view). */
17
+ onClose: () => void;
18
+ children: React.ReactNode;
19
+ }
20
+
21
+ export function DiagramMaximizedOverlay({ host, onClose, children }: DiagramMaximizedOverlayProps) {
22
+ useEffect(() => {
23
+ const onKey = (e: KeyboardEvent) => {
24
+ if (e.key === 'Escape') {
25
+ e.preventDefault();
26
+ onClose();
27
+ }
28
+ };
29
+ document.addEventListener('keydown', onKey);
30
+ return () => {
31
+ document.removeEventListener('keydown', onKey);
32
+ };
33
+ }, [onClose]);
34
+
35
+ const target = host ?? (typeof document !== 'undefined' ? document.body : null);
36
+ if (!target) return null;
37
+
38
+ return createPortal(
39
+ <div className="squisq-diagram-maximized-overlay">
40
+ <div className="squisq-diagram-maximized-content">{children}</div>
41
+ </div>,
42
+ target,
43
+ );
44
+ }
45
+
46
+ export default DiagramMaximizedOverlay;