@bendyline/squisq-editor-react 1.6.2 → 2.0.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 (200) hide show
  1. package/README.md +12 -3
  2. package/dist/index.d.ts +1229 -179
  3. package/dist/index.js +18017 -11231
  4. package/dist/index.js.map +1 -1
  5. package/dist/monaco.d.ts +1 -0
  6. package/dist/monaco.js +4 -0
  7. package/dist/monaco.js.map +1 -0
  8. package/dist/styles/index.css +1471 -245
  9. package/package.json +9 -5
  10. package/src/BlockPropertiesPopover.tsx +30 -15
  11. package/src/DocumentSettingsDialog.tsx +13 -21
  12. package/src/EditorContext.tsx +199 -42
  13. package/src/EditorShell.tsx +348 -260
  14. package/src/ImageEditor.tsx +22 -1
  15. package/src/InlinePreviewGutter.tsx +16 -8
  16. package/src/MediaBin.tsx +107 -14
  17. package/src/OutlinePanel.tsx +202 -7
  18. package/src/PlainHtmlPreview.tsx +40 -1
  19. package/src/PreviewControls.tsx +309 -69
  20. package/src/PreviewPanel.tsx +312 -78
  21. package/src/RawEditor.tsx +13 -2
  22. package/src/StatusBar.tsx +5 -2
  23. package/src/TemplateAnnotation.ts +12 -3
  24. package/src/TemplatePicker.tsx +75 -21
  25. package/src/ThemeCustomizerPanel.tsx +8 -0
  26. package/src/ThemePicker.tsx +10 -5
  27. package/src/TimelineBlockPreview.tsx +1 -1
  28. package/src/Toolbar.tsx +202 -41
  29. package/src/TransitionPicker.tsx +36 -4
  30. package/src/ViewMenuPanel.tsx +12 -14
  31. package/src/WysiwygEditor.tsx +124 -91
  32. package/src/__tests__/blockPropertiesPopoverTheme.test.tsx +33 -0
  33. package/src/__tests__/blockTagActivity.test.ts +183 -0
  34. package/src/__tests__/buildDocumentPreviewMarkdown.test.ts +75 -0
  35. package/src/__tests__/buildPreviewDocContent.test.ts +48 -0
  36. package/src/__tests__/buildPreviewDocTransition.test.ts +21 -1
  37. package/src/__tests__/canvasSurfaceTextEditing.test.tsx +60 -0
  38. package/src/__tests__/customLayoutManagerTheme.test.tsx +34 -0
  39. package/src/__tests__/documentSettingsDialog.test.tsx +29 -1
  40. package/src/__tests__/editorScrollHandoff.test.tsx +102 -0
  41. package/src/__tests__/editorScrollSync.test.ts +65 -0
  42. package/src/__tests__/editorShellProps.test.tsx +123 -1
  43. package/src/__tests__/emojiPicker.test.tsx +2 -42
  44. package/src/__tests__/headingTransition.test.ts +0 -12
  45. package/src/__tests__/imageEditAffordance.test.tsx +5 -1
  46. package/src/__tests__/imageEditModalContract.test.tsx +119 -0
  47. package/src/__tests__/imageEditorShell.test.tsx +15 -1
  48. package/src/__tests__/jsonEditor.test.tsx +56 -1
  49. package/src/__tests__/layersPanel.test.tsx +75 -5
  50. package/src/__tests__/majorApiTypes.test.ts +26 -0
  51. package/src/__tests__/mediaBinDrop.test.tsx +90 -0
  52. package/src/__tests__/narrationSave.test.ts +148 -0
  53. package/src/__tests__/outlinePanel.test.tsx +93 -3
  54. package/src/__tests__/outlineSource.test.ts +217 -0
  55. package/src/__tests__/plainHtmlPreview.test.tsx +17 -1
  56. package/src/__tests__/presentationMode.test.tsx +290 -0
  57. package/src/__tests__/previewControls.test.tsx +218 -5
  58. package/src/__tests__/previewPanelAudioFailure.test.tsx +46 -0
  59. package/src/__tests__/previewPanelPresentation.test.tsx +126 -0
  60. package/src/__tests__/previewPanelTransforms.test.tsx +117 -0
  61. package/src/__tests__/rawEditorModelIsolation.test.ts +19 -0
  62. package/src/__tests__/resolveBlockVisual.test.ts +43 -0
  63. package/src/__tests__/statusBar.test.tsx +27 -0
  64. package/src/__tests__/teleprompter.test.tsx +190 -0
  65. package/src/__tests__/templateAnnotationRoundTrip.test.ts +26 -0
  66. package/src/__tests__/templatePickerPortal.test.tsx +62 -0
  67. package/src/__tests__/tiptapBridge.test.ts +23 -0
  68. package/src/__tests__/tiptapCodeBlockRoundTrip.test.ts +109 -0
  69. package/src/__tests__/transformStyleId.test.ts +13 -0
  70. package/src/__tests__/useImageEditor.test.tsx +67 -0
  71. package/src/__tests__/useMediaRecorder.test.ts +75 -0
  72. package/src/__tests__/viewMenuPanel.test.tsx +130 -0
  73. package/src/__tests__/wysiwygImageUpload.test.ts +69 -0
  74. package/src/__tests__/wysiwygTemplateBadgeFocus.test.tsx +56 -0
  75. package/src/asciiDiagram/AsciiDiagramExtension.ts +343 -0
  76. package/src/asciiDiagram/AsciiDiagramWidget.tsx +224 -0
  77. package/src/asciiDiagram/RepairableDiagramExtension.ts +200 -0
  78. package/src/asciiDiagram/__tests__/AsciiDiagramExtension.test.ts +145 -0
  79. package/src/asciiDiagram/__tests__/RepairableDiagramExtension.test.ts +159 -0
  80. package/src/asciiDiagram/__tests__/asciiDiagramCommands.test.ts +227 -0
  81. package/src/asciiDiagram/__tests__/asciiDiagramOps.test.ts +114 -0
  82. package/src/asciiDiagram/__tests__/asciiPaste.test.ts +43 -0
  83. package/src/asciiDiagram/asciiDiagramCommands.ts +148 -0
  84. package/src/asciiDiagram/asciiDiagramData.ts +116 -0
  85. package/src/asciiDiagram/asciiDiagramOps.ts +219 -0
  86. package/src/asciiDiagram/asciiPaste.ts +19 -0
  87. package/src/blockTagActivity.ts +233 -0
  88. package/src/buildDocumentPreviewMarkdown.ts +168 -0
  89. package/src/buildPreviewDoc.ts +19 -12
  90. package/src/customTemplates/CustomLayoutManager.tsx +3 -2
  91. package/src/customTemplates/CustomTemplateContext.tsx +6 -0
  92. package/src/customTemplates/TemplateDesigner.tsx +7 -4
  93. package/src/customTemplates/__tests__/library.test.ts +8 -0
  94. package/src/customTemplates/designer.css +158 -99
  95. package/src/customTemplates/library.ts +16 -3
  96. package/src/customThemes/CustomThemeContext.tsx +6 -0
  97. package/src/customThemes/CustomThemeDialog.tsx +35 -5
  98. package/src/customThemes/ImportThemeSection.tsx +178 -0
  99. package/src/customThemes/__tests__/customThemeLibrary.test.ts +9 -0
  100. package/src/customThemes/__tests__/importThemeSection.test.tsx +192 -0
  101. package/src/customThemes/customThemeLibrary.ts +7 -4
  102. package/src/customThemes/index.ts +7 -1
  103. package/src/customThemes/themeDraft.ts +23 -7
  104. package/src/diagram/DiagramCanvas.tsx +9 -4
  105. package/src/diagram/types.ts +35 -0
  106. package/src/editorScrollSync.ts +73 -0
  107. package/src/emojiData.ts +3 -23
  108. package/src/headingTransition.ts +0 -15
  109. package/src/imageEditor/CanvasSurface.tsx +29 -23
  110. package/src/imageEditor/LayersPanel.tsx +78 -3
  111. package/src/imageEditor/Toolbar.tsx +5 -1
  112. package/src/imageEditor/icons.tsx +4 -0
  113. package/src/imageEditor/image-editor.css +75 -0
  114. package/src/imageEditor/layers/SelectionHandles.tsx +1 -1
  115. package/src/imageEditor/useImageEditor.ts +71 -14
  116. package/src/index.ts +191 -19
  117. package/src/jsonEditor/JsonEditorContext.tsx +12 -6
  118. package/src/jsonEditor/RenderNode.tsx +24 -3
  119. package/src/jsonEditor/editors.tsx +86 -19
  120. package/src/mediaEntries.ts +12 -0
  121. package/src/monaco.ts +35 -0
  122. package/src/monacoWorkers.ts +89 -0
  123. package/src/outlineSource.ts +171 -0
  124. package/src/presentation/PresentationMode.tsx +596 -0
  125. package/src/rawEditorIsolation.ts +18 -0
  126. package/src/recorder/hooks/useMediaRecorder.ts +97 -53
  127. package/src/resolveBlockVisual.ts +10 -4
  128. package/src/scene/Scene.tsx +48 -18
  129. package/src/scene/SceneBlockExtension.ts +17 -10
  130. package/src/scene/SceneBlockWidget.tsx +5 -1
  131. package/src/scene/SceneViewport.tsx +7 -3
  132. package/src/scene/ShapePalette.tsx +17 -2
  133. package/src/scene/__tests__/DiagramAdapter.test.ts +86 -0
  134. package/src/scene/__tests__/SceneBlockExtension.test.ts +33 -0
  135. package/src/scene/__tests__/sceneIsolation.test.tsx +93 -0
  136. package/src/scene/adapters/DiagramAdapter.ts +12 -101
  137. package/src/scene/commands/SceneCommand.ts +4 -1
  138. package/src/scene/index.ts +1 -6
  139. package/src/scene/layers/DiagramEdges.tsx +21 -7
  140. package/src/scene/layers/edgeGeometry.ts +9 -1
  141. package/src/scene/layers/nodeCard.tsx +27 -8
  142. package/src/scene/scene.css +5 -2
  143. package/src/scene/text/SceneTextOverlay.tsx +5 -5
  144. package/src/scene/text/sceneTextChannel.ts +26 -20
  145. package/src/scene/text/sceneTextConfig.ts +4 -0
  146. package/src/scene/tools/ConnectTool.ts +13 -4
  147. package/src/scene/tools/SceneTool.ts +8 -0
  148. package/src/scene/tools/SelectTool.ts +34 -18
  149. package/src/scene/tools/ShapeTool.ts +2 -3
  150. package/src/styles/ascii-diagram.css +79 -0
  151. package/src/styles/ascii-timeline.css +499 -0
  152. package/src/styles/editor.css +706 -120
  153. package/src/styles/index.css +3 -0
  154. package/src/styles/tree-view.css +139 -0
  155. package/src/teleprompter/TeleprompterControls.tsx +218 -0
  156. package/src/teleprompter/TeleprompterSelfView.tsx +22 -0
  157. package/src/teleprompter/TeleprompterSurface.tsx +267 -0
  158. package/src/teleprompter/TeleprompterView.tsx +338 -0
  159. package/src/teleprompter/canvasRenderer.ts +161 -0
  160. package/src/teleprompter/floatingWindow.ts +352 -0
  161. package/src/teleprompter/index.ts +61 -0
  162. package/src/teleprompter/pcmWorklet.ts +62 -0
  163. package/src/teleprompter/recording/insertPreamble.ts +80 -0
  164. package/src/teleprompter/recording/narrationSave.ts +134 -0
  165. package/src/teleprompter/recording/useNarrationRecorder.ts +367 -0
  166. package/src/teleprompter/scrollModel.ts +85 -0
  167. package/src/teleprompter/teleprompterTheme.ts +303 -0
  168. package/src/teleprompter/types.ts +38 -0
  169. package/src/teleprompter/useFloatingWindow.ts +74 -0
  170. package/src/teleprompter/useMicAnalysis.ts +211 -0
  171. package/src/teleprompter/useTeleprompter.ts +421 -0
  172. package/src/templateContentPreviewResolver.ts +12 -5
  173. package/src/timeline/TimelineEditorWidget.tsx +702 -0
  174. package/src/timeline/TimelineViewExtension.ts +252 -0
  175. package/src/timeline/__tests__/TimelineEditorWidget.test.tsx +355 -0
  176. package/src/timeline/__tests__/TimelineViewExtension.test.ts +163 -0
  177. package/src/timeline/__tests__/timelineCommands.test.ts +327 -0
  178. package/src/timeline/__tests__/timelineOps.test.ts +222 -0
  179. package/src/timeline/__tests__/timelinePaste.test.ts +34 -0
  180. package/src/timeline/timelineCommands.ts +367 -0
  181. package/src/timeline/timelineData.ts +54 -0
  182. package/src/timeline/timelineOps.ts +277 -0
  183. package/src/timeline/timelinePaste.ts +8 -0
  184. package/src/tiptapBridge.ts +24 -16
  185. package/src/transformStyleId.ts +17 -0
  186. package/src/treeview/TreeOutlineWidget.tsx +240 -0
  187. package/src/treeview/TreeViewExtension.ts +250 -0
  188. package/src/treeview/__tests__/TreeViewExtension.test.ts +122 -0
  189. package/src/treeview/__tests__/treeOps.test.ts +125 -0
  190. package/src/treeview/__tests__/treePaste.test.ts +40 -0
  191. package/src/treeview/__tests__/treeViewCommands.test.ts +163 -0
  192. package/src/treeview/treeOps.ts +172 -0
  193. package/src/treeview/treePaste.ts +13 -0
  194. package/src/treeview/treeViewCommands.ts +94 -0
  195. package/src/treeview/treeViewData.ts +41 -0
  196. package/src/useMonacoLoader.ts +11 -34
  197. package/src/wysiwygImageUpload.ts +113 -0
  198. package/src/diagram/DiagramExtension.ts +0 -209
  199. package/src/diagram/DiagramWidget.tsx +0 -272
  200. package/src/diagram/useDiagramData.ts +0 -126
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Read direction of the ASCII diagram loop: fence text → canvas data.
3
+ *
4
+ * `useAsciiDiagramData` re-derives on every editor transaction (mirroring
5
+ * the philosophy of the old heading-based `useDiagramData`: no store, so
6
+ * nothing to invalidate). Parsing is memoized per PMNode instance by the
7
+ * extension's WeakMap caches, so untouched fences cost nothing.
8
+ */
9
+
10
+ import { useEffect, useMemo, useState } from 'react';
11
+ import type { Editor } from '@tiptap/react';
12
+ import {
13
+ asciiCellToCanvas,
14
+ asciiDiagramToTemplateData,
15
+ ASCII_CHAR_H,
16
+ ASCII_CHAR_W,
17
+ type AsciiDiagram,
18
+ } from '@bendyline/squisq/doc';
19
+ import type { DiagramEdge, DiagramNode } from '../diagram/types';
20
+ import { findAsciiDiagramBlockPos, parseAsciiDiagramForNode } from './AsciiDiagramExtension';
21
+
22
+ export interface AsciiDiagramView {
23
+ /** Canvas nodes, containers ordered first so their cards paint behind. */
24
+ nodes: DiagramNode[];
25
+ edges: DiagramEdge[];
26
+ warnings: string[];
27
+ style: 'unicode' | 'ascii';
28
+ /** The current fence text. */
29
+ text: string;
30
+ /** The parse behind `nodes`/`edges` (grid units) — ops operate on this. */
31
+ diagram: AsciiDiagram;
32
+ }
33
+
34
+ /** Grid model → canvas model, containers-first for paint order. */
35
+ export function asciiDiagramToCanvas(
36
+ diagram: AsciiDiagram,
37
+ ): Pick<AsciiDiagramView, 'nodes' | 'edges'> {
38
+ const containerIds = new Set(
39
+ diagram.nodes.map((n) => n.containerId).filter((id): id is string => id !== undefined),
40
+ );
41
+ const depthOf = (id: string | undefined): number => {
42
+ let depth = 0;
43
+ let current = diagram.nodes.find((n) => n.id === id);
44
+ while (current?.containerId) {
45
+ depth++;
46
+ current = diagram.nodes.find((n) => n.id === current?.containerId);
47
+ if (depth > diagram.nodes.length) break;
48
+ }
49
+ return depth;
50
+ };
51
+ const ordered = [...diagram.nodes].sort((a, b) => {
52
+ const aContainer = containerIds.has(a.id) ? 0 : 1;
53
+ const bContainer = containerIds.has(b.id) ? 0 : 1;
54
+ return aContainer - bContainer || depthOf(a.id) - depthOf(b.id);
55
+ });
56
+ const nodes: DiagramNode[] = ordered.map((n) => ({
57
+ id: n.id,
58
+ position: asciiCellToCanvas(n.col, n.row),
59
+ data: { label: n.label },
60
+ width: n.wCols * ASCII_CHAR_W,
61
+ height: n.hRows * ASCII_CHAR_H,
62
+ ...(containerIds.has(n.id) ? { kind: 'container' as const } : {}),
63
+ }));
64
+ const templateEdges = asciiDiagramToTemplateData(diagram).edges;
65
+ const edges: DiagramEdge[] = diagram.edges.map((e, index) => ({
66
+ id: e.label ? `${e.source}->${e.target}:${e.label}` : `${e.source}->${e.target}`,
67
+ source: e.source,
68
+ target: e.target,
69
+ ...(e.label ? { label: e.label } : {}),
70
+ ...(e.directed ? {} : { directed: false }),
71
+ ...(templateEdges[index]?.sourceAnchor
72
+ ? { sourceAnchor: templateEdges[index].sourceAnchor }
73
+ : {}),
74
+ ...(templateEdges[index]?.targetAnchor
75
+ ? { targetAnchor: templateEdges[index].targetAnchor }
76
+ : {}),
77
+ ...(templateEdges[index]?.routing ? { routing: templateEdges[index].routing } : {}),
78
+ }));
79
+ return { nodes, edges };
80
+ }
81
+
82
+ /**
83
+ * Live view of one registered ASCII diagram block. Returns null when the
84
+ * block no longer exists or no longer parses (the extension will drop the
85
+ * widget on its next pass).
86
+ */
87
+ export function useAsciiDiagramData(editor: Editor, blockId: string): AsciiDiagramView | null {
88
+ const [version, setVersion] = useState(0);
89
+ useEffect(() => {
90
+ const onUpdate = () => setVersion((v) => v + 1);
91
+ editor.on('transaction', onUpdate);
92
+ return () => {
93
+ editor.off('transaction', onUpdate);
94
+ };
95
+ }, [editor]);
96
+
97
+ return useMemo(() => {
98
+ const pos = findAsciiDiagramBlockPos(editor, blockId);
99
+ if (pos === null) return null;
100
+ const node = editor.state.doc.nodeAt(pos);
101
+ if (!node || node.type.name !== 'codeBlock') return null;
102
+ const diagram = parseAsciiDiagramForNode(node);
103
+ if (!diagram) return null;
104
+ const { nodes, edges } = asciiDiagramToCanvas(diagram);
105
+ return {
106
+ nodes,
107
+ edges,
108
+ warnings: diagram.warnings,
109
+ style: diagram.style,
110
+ text: node.textContent,
111
+ diagram,
112
+ };
113
+ // `version` tracks transactions; editor/blockId are stable.
114
+ // eslint-disable-next-line react-hooks/exhaustive-deps
115
+ }, [editor, blockId, version]);
116
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Pure data operations over the ASCII diagram model — the write-direction
3
+ * half of the fence-is-source-of-truth loop:
4
+ *
5
+ * fence text → parseAsciiDiagram → op → renderAsciiDiagram → fence text
6
+ *
7
+ * Every op returns a new AsciiDiagram (inputs are never mutated) and
8
+ * maintains the invariants the renderer/parser fixpoint relies on:
9
+ * container moves translate whole subtrees, removals promote children and
10
+ * drop incident edges, sizes never fall below what a label needs.
11
+ */
12
+
13
+ import type { AsciiDiagram, AsciiDiagramEdge, AsciiDiagramNode } from '@bendyline/squisq/doc';
14
+
15
+ /**
16
+ * Make arbitrary (rename-dialog) input safe as a box label: box-drawing /
17
+ * arrow glyphs would corrupt the art, and the Scene's inline editor is
18
+ * single-line, so newlines collapse to spaces.
19
+ */
20
+ export function sanitizeAsciiLabel(label: string): string {
21
+ return label
22
+ .replace(/[─-╿▲▼◀-◄▶-►←-↓`]/gu, ' ') // backticks would terminate the fence
23
+ .replace(/\s+/g, ' ')
24
+ .trim();
25
+ }
26
+
27
+ function descendantsOf(diagram: AsciiDiagram, nodeId: string): Set<string> {
28
+ const out = new Set<string>();
29
+ let grew = true;
30
+ while (grew) {
31
+ grew = false;
32
+ for (const n of diagram.nodes) {
33
+ if (out.has(n.id)) continue;
34
+ if (n.containerId === nodeId || (n.containerId && out.has(n.containerId))) {
35
+ out.add(n.id);
36
+ grew = true;
37
+ }
38
+ }
39
+ }
40
+ return out;
41
+ }
42
+
43
+ /** Move a node to (col, row); a container drags its whole subtree along. */
44
+ export function moveNodeOp(
45
+ diagram: AsciiDiagram,
46
+ nodeId: string,
47
+ col: number,
48
+ row: number,
49
+ ): AsciiDiagram {
50
+ const node = diagram.nodes.find((n) => n.id === nodeId);
51
+ if (!node) return diagram;
52
+ const dCol = Math.max(0, col) - node.col;
53
+ const dRow = Math.max(0, row) - node.row;
54
+ if (dCol === 0 && dRow === 0) return diagram;
55
+ const moving = descendantsOf(diagram, nodeId);
56
+ moving.add(nodeId);
57
+ return {
58
+ ...diagram,
59
+ nodes: diagram.nodes.map((n) =>
60
+ moving.has(n.id)
61
+ ? { ...n, col: Math.max(0, n.col + dCol), row: Math.max(0, n.row + dRow) }
62
+ : n,
63
+ ),
64
+ };
65
+ }
66
+
67
+ /** Resize a node (grid cells). Clamped so the label always fits. */
68
+ export function resizeNodeOp(
69
+ diagram: AsciiDiagram,
70
+ nodeId: string,
71
+ wCols: number,
72
+ hRows: number,
73
+ ): AsciiDiagram {
74
+ const node = diagram.nodes.find((n) => n.id === nodeId);
75
+ if (!node) return diagram;
76
+ const labelLines = node.label.length > 0 ? node.label.split('\n') : [];
77
+ const minW = Math.max(3, labelLines.reduce((w, l) => Math.max(w, l.length), 0) + 4);
78
+ const minH = Math.max(3, labelLines.length + 2);
79
+ return {
80
+ ...diagram,
81
+ nodes: diagram.nodes.map((n) =>
82
+ n.id === nodeId
83
+ ? {
84
+ ...n,
85
+ wCols: Math.max(minW, Math.round(wCols)),
86
+ hRows: Math.max(minH, Math.round(hRows)),
87
+ }
88
+ : n,
89
+ ),
90
+ };
91
+ }
92
+
93
+ /** Add a directed edge; duplicates (same source/target/label) are no-ops. */
94
+ export function addEdgeOp(
95
+ diagram: AsciiDiagram,
96
+ source: string,
97
+ target: string,
98
+ label?: string,
99
+ ): AsciiDiagram {
100
+ const ids = new Set(diagram.nodes.map((n) => n.id));
101
+ if (!ids.has(source) || !ids.has(target) || source === target) return diagram;
102
+ const exists = diagram.edges.some(
103
+ (e) => e.source === source && e.target === target && (e.label ?? '') === (label ?? ''),
104
+ );
105
+ if (exists) return diagram;
106
+ const edge: AsciiDiagramEdge = {
107
+ source,
108
+ target,
109
+ ...(label ? { label } : {}),
110
+ directed: true,
111
+ };
112
+ return { ...diagram, edges: [...diagram.edges, edge] };
113
+ }
114
+
115
+ /**
116
+ * Remove an edge. A label-qualified call removes the exact match; without
117
+ * a label the first (source, target) match goes — mirroring the legacy
118
+ * `removeConnection` semantics.
119
+ */
120
+ export function removeEdgeOp(
121
+ diagram: AsciiDiagram,
122
+ source: string,
123
+ target: string,
124
+ label?: string,
125
+ ): AsciiDiagram {
126
+ let removed = false;
127
+ const edges = diagram.edges.filter((e) => {
128
+ if (removed) return true;
129
+ const match =
130
+ e.source === source &&
131
+ e.target === target &&
132
+ (label !== undefined ? (e.label ?? '') === label : true);
133
+ if (match) {
134
+ removed = true;
135
+ return false;
136
+ }
137
+ return true;
138
+ });
139
+ return removed ? { ...diagram, edges } : diagram;
140
+ }
141
+
142
+ /**
143
+ * Rename a node. The label drives the node's parse-derived id, so edges
144
+ * and containment references are rewritten to the id the next parse will
145
+ * produce. (Selection in the canvas drops after a rename — documented.)
146
+ */
147
+ export function renameNodeOp(diagram: AsciiDiagram, nodeId: string, label: string): AsciiDiagram {
148
+ const node = diagram.nodes.find((n) => n.id === nodeId);
149
+ if (!node) return diagram;
150
+ const clean = sanitizeAsciiLabel(label);
151
+ if (clean.length === 0 || clean === node.label) return diagram;
152
+ return {
153
+ ...diagram,
154
+ nodes: diagram.nodes.map((n) => (n.id === nodeId ? { ...n, label: clean } : n)),
155
+ };
156
+ }
157
+
158
+ /** Add a node at (col, row). Inherits a container when placed inside one. */
159
+ export function addNodeOp(
160
+ diagram: AsciiDiagram,
161
+ opts: { col: number; row: number; label?: string },
162
+ ): { diagram: AsciiDiagram; label: string } {
163
+ // First free "Node N" label.
164
+ let label = opts.label;
165
+ if (!label) {
166
+ let i = 1;
167
+ const labels = new Set(diagram.nodes.map((n) => n.label.split('\n')[0]));
168
+ while (labels.has(`Node ${i}`)) i++;
169
+ label = `Node ${i}`;
170
+ }
171
+ const clean = sanitizeAsciiLabel(label) || 'Node';
172
+ const col = Math.max(0, Math.round(opts.col));
173
+ const row = Math.max(0, Math.round(opts.row));
174
+ const wCols = clean.length + 4;
175
+ const hRows = 3;
176
+ // Container inheritance: the new box's center falls inside a container.
177
+ const centerCol = col + wCols / 2;
178
+ const centerRow = row + hRows / 2;
179
+ const containers = diagram.nodes
180
+ .filter((n) => diagram.nodes.some((m) => m.containerId === n.id))
181
+ .filter(
182
+ (n) =>
183
+ centerCol > n.col &&
184
+ centerCol < n.col + n.wCols &&
185
+ centerRow > n.row &&
186
+ centerRow < n.row + n.hRows,
187
+ )
188
+ .sort((a, b) => a.wCols * a.hRows - b.wCols * b.hRows);
189
+ const node: AsciiDiagramNode = {
190
+ id: `__new-${diagram.nodes.length}`, // provisional; the re-parse derives the real slug id
191
+ label: clean,
192
+ col,
193
+ row,
194
+ wCols,
195
+ hRows,
196
+ ...(containers[0] ? { containerId: containers[0].id } : {}),
197
+ };
198
+ return { diagram: { ...diagram, nodes: [...diagram.nodes, node] }, label: clean };
199
+ }
200
+
201
+ /**
202
+ * Remove a node: incident edges (both directions) drop, direct children
203
+ * are promoted to the removed node's own container (or top level).
204
+ */
205
+ export function removeNodeOp(diagram: AsciiDiagram, nodeId: string): AsciiDiagram {
206
+ const node = diagram.nodes.find((n) => n.id === nodeId);
207
+ if (!node) return diagram;
208
+ const nodes = diagram.nodes
209
+ .filter((n) => n.id !== nodeId)
210
+ .map((n) => {
211
+ if (n.containerId !== nodeId) return n;
212
+ const promoted = { ...n };
213
+ if (node.containerId) promoted.containerId = node.containerId;
214
+ else delete promoted.containerId;
215
+ return promoted;
216
+ });
217
+ const edges = diagram.edges.filter((e) => e.source !== nodeId && e.target !== nodeId);
218
+ return { ...diagram, nodes, edges };
219
+ }
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Paste gate for bare (unfenced) ASCII diagram art.
3
+ *
4
+ * `+--+ | |` art pasted as plain text is otherwise mangled: its `| x |`
5
+ * rows match the GFM table-row pattern in `detectMarkdown`, so the paste
6
+ * handler routes it through the markdown converter, fails table
7
+ * validation, and emits one broken paragraph per line. When this gate
8
+ * matches, the paste handler inserts the text verbatim into a fresh code
9
+ * block instead — which the AsciiDiagramExtension then picks up as an
10
+ * interactive diagram.
11
+ */
12
+
13
+ import { detectAsciiDiagram } from '@bendyline/squisq/doc';
14
+
15
+ export function shouldPasteAsAsciiFence(text: string): boolean {
16
+ if (!text || text.includes('```')) return false;
17
+ const detection = detectAsciiDiagram(text);
18
+ return detection.isDiagram && (detection.diagram?.nodes.length ?? 0) >= 2;
19
+ }
@@ -0,0 +1,233 @@
1
+ import { Extension } from '@tiptap/core';
2
+ import { Plugin, PluginKey, type Transaction } from '@tiptap/pm/state';
3
+ import { Decoration, DecorationSet, type EditorView as ProseMirrorView } from '@tiptap/pm/view';
4
+ import type { Node as ProseMirrorNode } from '@tiptap/pm/model';
5
+
6
+ export const BLOCK_TAG_SELECTED_CLASS = 'squisq-block-tags--selected';
7
+ export const BLOCK_TAG_HOVERED_CLASS = 'squisq-block-tags--hovered';
8
+
9
+ export interface BlockTagActivityPluginState {
10
+ selectedPosition: number | null;
11
+ hoveredPosition: number | null;
12
+ decorations: DecorationSet;
13
+ }
14
+
15
+ interface BlockTagHoverMeta {
16
+ hoveredPosition: number | null;
17
+ }
18
+
19
+ export const BLOCK_TAG_ACTIVITY_KEY = new PluginKey<BlockTagActivityPluginState>(
20
+ 'squisq-block-tag-activity',
21
+ );
22
+
23
+ function isHeadingElement(element: Element): element is HTMLElement {
24
+ return /^H[1-6]$/.test(element.tagName);
25
+ }
26
+
27
+ /**
28
+ * Returns the heading position for the block owning a document position.
29
+ * A block begins at a top-level heading and continues until the next heading.
30
+ */
31
+ export function findOwningHeadingPosition(doc: ProseMirrorNode, position: number): number | null {
32
+ let offset = 0;
33
+ let owningPosition: number | null = null;
34
+
35
+ for (let index = 0; index < doc.childCount && offset <= position; index += 1) {
36
+ const node = doc.child(index);
37
+ if (node.type.name === 'heading') owningPosition = offset;
38
+ offset += node.nodeSize;
39
+ }
40
+
41
+ return owningPosition;
42
+ }
43
+
44
+ /** Find the preceding top-level heading for a DOM node under ProseMirror. */
45
+ export function findOwningHeadingElement(
46
+ editorDom: HTMLElement,
47
+ target: EventTarget | null,
48
+ ): HTMLElement | null {
49
+ if (!(target instanceof Node)) return null;
50
+
51
+ let element =
52
+ target.nodeType === Node.ELEMENT_NODE
53
+ ? (target as HTMLElement)
54
+ : (target.parentElement as HTMLElement | null);
55
+ if (!element || element === editorDom || !editorDom.contains(element)) return null;
56
+
57
+ while (element.parentElement && element.parentElement !== editorDom) {
58
+ element = element.parentElement;
59
+ }
60
+ if (element.parentElement !== editorDom) return null;
61
+
62
+ let candidate: Element | null = element;
63
+ while (candidate && !isHeadingElement(candidate)) {
64
+ candidate = candidate.previousElementSibling;
65
+ }
66
+ return candidate && isHeadingElement(candidate) ? candidate : null;
67
+ }
68
+
69
+ /**
70
+ * Resolve blank canvas space to the heading-defined block at that vertical
71
+ * position. Margins between top-level nodes are not owned by either node in
72
+ * the DOM, so pointer events there target the ProseMirror root. Treating the
73
+ * root as "no block" makes active-only tags disappear while the pointer
74
+ * crosses ordinary paragraph/list spacing.
75
+ */
76
+ export function findOwningHeadingElementAtPoint(
77
+ editorDom: HTMLElement,
78
+ target: EventTarget | null,
79
+ clientY: number,
80
+ ): HTMLElement | null {
81
+ const direct = findOwningHeadingElement(editorDom, target);
82
+ if (direct) return direct;
83
+ if (!(target instanceof Node) || !editorDom.contains(target) || !Number.isFinite(clientY)) {
84
+ return null;
85
+ }
86
+
87
+ const children = Array.from(editorDom.children);
88
+ const lastChild = children[children.length - 1];
89
+ if (!lastChild || clientY > lastChild.getBoundingClientRect().bottom) return null;
90
+
91
+ let owningHeading: HTMLElement | null = null;
92
+ for (const child of children) {
93
+ if (child.getBoundingClientRect().top > clientY) break;
94
+ if (isHeadingElement(child)) owningHeading = child;
95
+ }
96
+ return owningHeading;
97
+ }
98
+
99
+ function validHeadingPosition(doc: ProseMirrorNode, position: number | null): number | null {
100
+ if (position === null) return null;
101
+ return doc.nodeAt(position)?.type.name === 'heading' ? position : null;
102
+ }
103
+
104
+ function buildDecorations(
105
+ doc: ProseMirrorNode,
106
+ selectedPosition: number | null,
107
+ hoveredPosition: number | null,
108
+ ): DecorationSet {
109
+ const classesByPosition = new Map<number, string[]>();
110
+
111
+ if (selectedPosition !== null) {
112
+ classesByPosition.set(selectedPosition, [BLOCK_TAG_SELECTED_CLASS]);
113
+ }
114
+ if (hoveredPosition !== null) {
115
+ const classes = classesByPosition.get(hoveredPosition) ?? [];
116
+ classes.push(BLOCK_TAG_HOVERED_CLASS);
117
+ classesByPosition.set(hoveredPosition, classes);
118
+ }
119
+
120
+ const decorations: Decoration[] = [];
121
+ for (const [position, classes] of classesByPosition) {
122
+ const node = doc.nodeAt(position);
123
+ if (!node || node.type.name !== 'heading') continue;
124
+ decorations.push(
125
+ Decoration.node(position, position + node.nodeSize, { class: classes.join(' ') }),
126
+ );
127
+ }
128
+
129
+ return decorations.length > 0 ? DecorationSet.create(doc, decorations) : DecorationSet.empty;
130
+ }
131
+
132
+ function createPluginState(
133
+ doc: ProseMirrorNode,
134
+ selectionFrom: number,
135
+ hoveredPosition: number | null,
136
+ ): BlockTagActivityPluginState {
137
+ const selectedPosition = findOwningHeadingPosition(doc, selectionFrom);
138
+ const validHoveredPosition = validHeadingPosition(doc, hoveredPosition);
139
+ return {
140
+ selectedPosition,
141
+ hoveredPosition: validHoveredPosition,
142
+ decorations: buildDecorations(doc, selectedPosition, validHoveredPosition),
143
+ };
144
+ }
145
+
146
+ function nextHoveredPosition(
147
+ transaction: Transaction,
148
+ previousPosition: number | null,
149
+ doc: ProseMirrorNode,
150
+ ): number | null {
151
+ const meta = transaction.getMeta(BLOCK_TAG_ACTIVITY_KEY) as BlockTagHoverMeta | undefined;
152
+ if (meta !== undefined) return validHeadingPosition(doc, meta.hoveredPosition);
153
+ if (!transaction.docChanged || previousPosition === null) return previousPosition;
154
+
155
+ const mapped = transaction.mapping.mapResult(previousPosition, 1);
156
+ return mapped.deleted ? null : validHeadingPosition(doc, mapped.pos);
157
+ }
158
+
159
+ function headingPositionForTarget(
160
+ view: ProseMirrorView,
161
+ target: EventTarget | null,
162
+ clientY: number,
163
+ ): number | null {
164
+ const heading = findOwningHeadingElementAtPoint(view.dom, target, clientY);
165
+ if (!heading) return null;
166
+
167
+ try {
168
+ const positionInsideHeading = view.posAtDOM(heading, 0);
169
+ return findOwningHeadingPosition(view.state.doc, positionInsideHeading);
170
+ } catch {
171
+ return null;
172
+ }
173
+ }
174
+
175
+ function setHoveredPosition(view: ProseMirrorView, hoveredPosition: number | null): void {
176
+ const current = BLOCK_TAG_ACTIVITY_KEY.getState(view.state)?.hoveredPosition ?? null;
177
+ if (current === hoveredPosition) return;
178
+ view.dispatch(
179
+ view.state.tr
180
+ .setMeta(BLOCK_TAG_ACTIVITY_KEY, { hoveredPosition } satisfies BlockTagHoverMeta)
181
+ .setMeta('addToHistory', false),
182
+ );
183
+ }
184
+
185
+ /**
186
+ * ProseMirror-owned block activity decorations. Using node decorations keeps
187
+ * the classes stable when ProseMirror reconciles its managed heading DOM.
188
+ */
189
+ export const BlockTagActivityExtension = Extension.create({
190
+ name: 'squisqBlockTagActivity',
191
+
192
+ addProseMirrorPlugins() {
193
+ return [
194
+ new Plugin<BlockTagActivityPluginState>({
195
+ key: BLOCK_TAG_ACTIVITY_KEY,
196
+ state: {
197
+ init: (_config, state) => createPluginState(state.doc, state.selection.from, null),
198
+ apply: (transaction, previous, _oldState, newState) =>
199
+ createPluginState(
200
+ newState.doc,
201
+ newState.selection.from,
202
+ nextHoveredPosition(transaction, previous.hoveredPosition, newState.doc),
203
+ ),
204
+ },
205
+ props: {
206
+ decorations(state) {
207
+ return this.getState(state)?.decorations ?? DecorationSet.empty;
208
+ },
209
+ handleDOMEvents: {
210
+ mouseover(view, event) {
211
+ setHoveredPosition(view, headingPositionForTarget(view, event.target, event.clientY));
212
+ return false;
213
+ },
214
+ mousemove(view, event) {
215
+ // `mouseover` covers real document nodes. Only track continuous
216
+ // movement while the root itself owns the pointer (the blank
217
+ // margin/gutter case), avoiding geometry reads over text.
218
+ if (event.target !== view.dom) return false;
219
+ setHoveredPosition(view, headingPositionForTarget(view, event.target, event.clientY));
220
+ return false;
221
+ },
222
+ mouseleave(view) {
223
+ setHoveredPosition(view, null);
224
+ return false;
225
+ },
226
+ },
227
+ },
228
+ }),
229
+ ];
230
+ },
231
+ });
232
+
233
+ export default BlockTagActivityExtension;