@bendyline/squisq-editor-react 1.6.2 → 2.0.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 (218) hide show
  1. package/README.md +12 -3
  2. package/dist/index.d.ts +1275 -183
  3. package/dist/index.js +20345 -12777
  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 +1607 -241
  9. package/package.json +9 -5
  10. package/src/BlockPropertiesPopover.tsx +30 -15
  11. package/src/DocumentSettingsDialog.tsx +39 -33
  12. package/src/EditorContext.tsx +199 -42
  13. package/src/EditorShell.tsx +349 -261
  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 +362 -89
  20. package/src/PreviewPanel.tsx +312 -78
  21. package/src/RawEditor.tsx +13 -2
  22. package/src/RecorderEntry.tsx +2 -0
  23. package/src/StatusBar.tsx +5 -2
  24. package/src/TemplateAnnotation.ts +12 -3
  25. package/src/TemplatePicker.tsx +75 -21
  26. package/src/ThemeCustomizerPanel.tsx +8 -0
  27. package/src/ThemePicker.tsx +10 -5
  28. package/src/TimelineBlockPreview.tsx +1 -1
  29. package/src/Toolbar.tsx +357 -51
  30. package/src/TransitionPicker.tsx +36 -4
  31. package/src/ViewMenuPanel.tsx +12 -14
  32. package/src/WysiwygEditor.tsx +124 -91
  33. package/src/__tests__/blockPropertiesPopoverTheme.test.tsx +33 -0
  34. package/src/__tests__/blockTagActivity.test.ts +183 -0
  35. package/src/__tests__/buildDocumentPreviewMarkdown.test.ts +75 -0
  36. package/src/__tests__/buildPreviewDocContent.test.ts +48 -0
  37. package/src/__tests__/buildPreviewDocTransition.test.ts +21 -1
  38. package/src/__tests__/canvasSurfaceTextEditing.test.tsx +60 -0
  39. package/src/__tests__/codeContextSectionView.test.tsx +8 -6
  40. package/src/__tests__/customLayoutManagerTheme.test.tsx +34 -0
  41. package/src/__tests__/documentSettingsDialog.test.tsx +51 -1
  42. package/src/__tests__/editorScrollHandoff.test.tsx +102 -0
  43. package/src/__tests__/editorScrollSync.test.ts +65 -0
  44. package/src/__tests__/editorShellProps.test.tsx +123 -1
  45. package/src/__tests__/emojiPicker.test.tsx +2 -42
  46. package/src/__tests__/headingTransition.test.ts +0 -12
  47. package/src/__tests__/imageEditAffordance.test.tsx +5 -1
  48. package/src/__tests__/imageEditModalContract.test.tsx +119 -0
  49. package/src/__tests__/imageEditorShell.test.tsx +15 -1
  50. package/src/__tests__/jsonEditor.test.tsx +56 -1
  51. package/src/__tests__/layersPanel.test.tsx +75 -5
  52. package/src/__tests__/majorApiTypes.test.ts +26 -0
  53. package/src/__tests__/mediaAttachmentFlow.test.ts +2 -2
  54. package/src/__tests__/mediaBinDrop.test.tsx +90 -0
  55. package/src/__tests__/narrationSave.test.ts +148 -0
  56. package/src/__tests__/outlinePanel.test.tsx +93 -3
  57. package/src/__tests__/outlineSource.test.ts +217 -0
  58. package/src/__tests__/plainHtmlPreview.test.tsx +17 -1
  59. package/src/__tests__/presentationMode.test.tsx +290 -0
  60. package/src/__tests__/previewControls.test.tsx +382 -5
  61. package/src/__tests__/previewPanelAudioFailure.test.tsx +46 -0
  62. package/src/__tests__/previewPanelPresentation.test.tsx +126 -0
  63. package/src/__tests__/previewPanelTransforms.test.tsx +117 -0
  64. package/src/__tests__/rawEditorModelIsolation.test.ts +19 -0
  65. package/src/__tests__/recorderTheme.test.tsx +42 -0
  66. package/src/__tests__/resolveBlockVisual.test.ts +43 -0
  67. package/src/__tests__/selectionConversions.test.ts +80 -0
  68. package/src/__tests__/statusBar.test.tsx +27 -0
  69. package/src/__tests__/teleprompter.test.tsx +190 -0
  70. package/src/__tests__/templateAnnotationRoundTrip.test.ts +26 -0
  71. package/src/__tests__/templatePickerPortal.test.tsx +62 -0
  72. package/src/__tests__/tiptapBridge.test.ts +71 -7
  73. package/src/__tests__/tiptapCodeBlockRoundTrip.test.ts +109 -0
  74. package/src/__tests__/tiptapImageRoundTrip.test.ts +1 -1
  75. package/src/__tests__/toolbarSelectionConversion.test.tsx +164 -0
  76. package/src/__tests__/transformStyleId.test.ts +13 -0
  77. package/src/__tests__/useImageEditor.test.tsx +67 -0
  78. package/src/__tests__/useMediaRecorder.test.ts +75 -0
  79. package/src/__tests__/viewMenuPanel.test.tsx +130 -0
  80. package/src/__tests__/wysiwygImageUpload.test.ts +69 -0
  81. package/src/__tests__/wysiwygTemplateBadgeFocus.test.tsx +56 -0
  82. package/src/asciiDiagram/AsciiDiagramExtension.ts +343 -0
  83. package/src/asciiDiagram/AsciiDiagramWidget.tsx +254 -0
  84. package/src/asciiDiagram/RepairableDiagramExtension.ts +200 -0
  85. package/src/asciiDiagram/__tests__/AsciiDiagramExtension.test.ts +145 -0
  86. package/src/asciiDiagram/__tests__/RepairableDiagramExtension.test.ts +159 -0
  87. package/src/asciiDiagram/__tests__/asciiDiagramCommands.test.ts +284 -0
  88. package/src/asciiDiagram/__tests__/asciiDiagramOps.test.ts +114 -0
  89. package/src/asciiDiagram/__tests__/asciiPaste.test.ts +43 -0
  90. package/src/asciiDiagram/asciiDiagramCommands.ts +174 -0
  91. package/src/asciiDiagram/asciiDiagramData.ts +149 -0
  92. package/src/asciiDiagram/asciiDiagramOps.ts +238 -0
  93. package/src/asciiDiagram/asciiPaste.ts +19 -0
  94. package/src/blockTagActivity.ts +233 -0
  95. package/src/buildDocumentPreviewMarkdown.ts +168 -0
  96. package/src/buildPreviewDoc.ts +19 -12
  97. package/src/codeContext/types.ts +1 -1
  98. package/src/customTemplates/CustomLayoutManager.tsx +3 -2
  99. package/src/customTemplates/CustomTemplateContext.tsx +6 -0
  100. package/src/customTemplates/TemplateDesigner.tsx +7 -4
  101. package/src/customTemplates/__tests__/library.test.ts +8 -0
  102. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +13 -0
  103. package/src/customTemplates/designer.css +158 -99
  104. package/src/customTemplates/library.ts +16 -3
  105. package/src/customTemplates/useMemoryLayerAdapter.ts +7 -1
  106. package/src/customThemes/CustomThemeContext.tsx +6 -0
  107. package/src/customThemes/CustomThemeDialog.tsx +35 -5
  108. package/src/customThemes/ImportThemeSection.tsx +178 -0
  109. package/src/customThemes/__tests__/customThemeLibrary.test.ts +9 -0
  110. package/src/customThemes/__tests__/importThemeSection.test.tsx +192 -0
  111. package/src/customThemes/customThemeLibrary.ts +7 -4
  112. package/src/customThemes/index.ts +7 -1
  113. package/src/customThemes/themeDraft.ts +23 -7
  114. package/src/diagram/DiagramCanvas.tsx +25 -6
  115. package/src/diagram/types.ts +35 -0
  116. package/src/editorScrollSync.ts +73 -0
  117. package/src/emojiData.ts +3 -23
  118. package/src/frontmatterSettings.ts +23 -0
  119. package/src/headingTransition.ts +0 -15
  120. package/src/imageEditor/CanvasSurface.tsx +29 -23
  121. package/src/imageEditor/LayersPanel.tsx +78 -3
  122. package/src/imageEditor/Toolbar.tsx +5 -1
  123. package/src/imageEditor/icons.tsx +4 -0
  124. package/src/imageEditor/image-editor.css +75 -0
  125. package/src/imageEditor/layers/SelectionHandles.tsx +1 -1
  126. package/src/imageEditor/useImageEditor.ts +71 -14
  127. package/src/index.ts +198 -20
  128. package/src/jsonEditor/JsonEditorContext.tsx +12 -6
  129. package/src/jsonEditor/RenderNode.tsx +24 -3
  130. package/src/jsonEditor/editors.tsx +86 -19
  131. package/src/mediaEntries.ts +12 -0
  132. package/src/monaco.ts +35 -0
  133. package/src/monacoWorkers.ts +89 -0
  134. package/src/outlineSource.ts +171 -0
  135. package/src/presentation/PresentationMode.tsx +596 -0
  136. package/src/rawEditorIsolation.ts +18 -0
  137. package/src/recorder/RecorderButton.tsx +9 -1
  138. package/src/recorder/RecorderModal.tsx +84 -41
  139. package/src/recorder/RecorderPanel.tsx +9 -1
  140. package/src/recorder/hooks/useMediaRecorder.ts +97 -53
  141. package/src/resolveBlockVisual.ts +10 -4
  142. package/src/scene/Scene.tsx +48 -18
  143. package/src/scene/SceneBlockExtension.ts +17 -10
  144. package/src/scene/SceneBlockWidget.tsx +5 -1
  145. package/src/scene/SceneViewport.tsx +7 -3
  146. package/src/scene/ShapePalette.tsx +17 -2
  147. package/src/scene/__tests__/DiagramAdapter.test.ts +86 -0
  148. package/src/scene/__tests__/SceneBlockExtension.test.ts +33 -0
  149. package/src/scene/__tests__/sceneIsolation.test.tsx +119 -0
  150. package/src/scene/adapters/DiagramAdapter.ts +12 -101
  151. package/src/scene/adapters/DrawingAdapter.ts +6 -1
  152. package/src/scene/adapters/LayoutAdapter.ts +3 -0
  153. package/src/scene/commands/SceneCommand.ts +17 -3
  154. package/src/scene/index.ts +1 -6
  155. package/src/scene/layers/DiagramEdges.tsx +21 -7
  156. package/src/scene/layers/edgeGeometry.ts +9 -1
  157. package/src/scene/layers/nodeCard.tsx +27 -8
  158. package/src/scene/scene.css +5 -2
  159. package/src/scene/text/SceneTextOverlay.tsx +5 -5
  160. package/src/scene/text/sceneTextChannel.ts +26 -20
  161. package/src/scene/text/sceneTextConfig.ts +4 -0
  162. package/src/scene/tools/ConnectTool.ts +13 -4
  163. package/src/scene/tools/SceneTool.ts +8 -0
  164. package/src/scene/tools/SelectTool.ts +39 -23
  165. package/src/scene/tools/ShapeTool.ts +2 -3
  166. package/src/selectionConversions.ts +155 -0
  167. package/src/styles/ascii-diagram.css +79 -0
  168. package/src/styles/ascii-timeline.css +596 -0
  169. package/src/styles/editor.css +736 -120
  170. package/src/styles/index.css +3 -0
  171. package/src/styles/tree-view.css +189 -0
  172. package/src/teleprompter/TeleprompterControls.tsx +218 -0
  173. package/src/teleprompter/TeleprompterSelfView.tsx +22 -0
  174. package/src/teleprompter/TeleprompterSurface.tsx +267 -0
  175. package/src/teleprompter/TeleprompterView.tsx +338 -0
  176. package/src/teleprompter/canvasRenderer.ts +161 -0
  177. package/src/teleprompter/floatingWindow.ts +352 -0
  178. package/src/teleprompter/index.ts +61 -0
  179. package/src/teleprompter/pcmWorklet.ts +62 -0
  180. package/src/teleprompter/recording/insertPreamble.ts +80 -0
  181. package/src/teleprompter/recording/narrationSave.ts +134 -0
  182. package/src/teleprompter/recording/useNarrationRecorder.ts +367 -0
  183. package/src/teleprompter/scrollModel.ts +85 -0
  184. package/src/teleprompter/teleprompterTheme.ts +303 -0
  185. package/src/teleprompter/types.ts +38 -0
  186. package/src/teleprompter/useFloatingWindow.ts +74 -0
  187. package/src/teleprompter/useMicAnalysis.ts +211 -0
  188. package/src/teleprompter/useTeleprompter.ts +421 -0
  189. package/src/templateContentPreviewResolver.ts +12 -5
  190. package/src/timeline/TimelineEditorWidget.tsx +861 -0
  191. package/src/timeline/TimelineViewExtension.ts +252 -0
  192. package/src/timeline/__tests__/TimelineEditorWidget.test.tsx +414 -0
  193. package/src/timeline/__tests__/TimelineViewExtension.test.ts +163 -0
  194. package/src/timeline/__tests__/timelineCommands.test.ts +359 -0
  195. package/src/timeline/__tests__/timelineOps.test.ts +277 -0
  196. package/src/timeline/__tests__/timelinePaste.test.ts +34 -0
  197. package/src/timeline/timelineCommands.ts +421 -0
  198. package/src/timeline/timelineData.ts +54 -0
  199. package/src/timeline/timelineOps.ts +381 -0
  200. package/src/timeline/timelinePaste.ts +8 -0
  201. package/src/tiptapBridge.ts +47 -21
  202. package/src/transformStyleId.ts +17 -0
  203. package/src/treeview/TreeOutlineWidget.tsx +390 -0
  204. package/src/treeview/TreeViewExtension.ts +250 -0
  205. package/src/treeview/__tests__/TreeOutlineWidget.test.tsx +156 -0
  206. package/src/treeview/__tests__/TreeViewExtension.test.ts +122 -0
  207. package/src/treeview/__tests__/treeOps.test.ts +177 -0
  208. package/src/treeview/__tests__/treePaste.test.ts +40 -0
  209. package/src/treeview/__tests__/treeViewCommands.test.ts +179 -0
  210. package/src/treeview/treeOps.ts +231 -0
  211. package/src/treeview/treePaste.ts +13 -0
  212. package/src/treeview/treeViewCommands.ts +99 -0
  213. package/src/treeview/treeViewData.ts +41 -0
  214. package/src/useMonacoLoader.ts +11 -34
  215. package/src/wysiwygImageUpload.ts +113 -0
  216. package/src/diagram/DiagramExtension.ts +0 -209
  217. package/src/diagram/DiagramWidget.tsx +0 -272
  218. package/src/diagram/useDiagramData.ts +0 -126
@@ -0,0 +1,421 @@
1
+ /**
2
+ * Write direction for the WYSIWYG timeline editor:
3
+ *
4
+ * fence text -> parse -> pure op -> render -> verify -> one fence rewrite
5
+ *
6
+ * The original code block remains the source of truth and every successful
7
+ * edit is a single ProseMirror transaction/undo step.
8
+ */
9
+
10
+ import type { Editor } from '@tiptap/react';
11
+ import {
12
+ isWrappedFlowTimelineSource,
13
+ parseAsciiTimeline,
14
+ renderAsciiTimeline,
15
+ type AsciiTimeline,
16
+ type AsciiTimelineMarker,
17
+ type AsciiTimelineSide,
18
+ } from '@bendyline/squisq/doc';
19
+ import { replaceAsciiFenceText } from '../asciiDiagram/asciiDiagramCommands';
20
+ import { findTimelineBlockPos, parseTimelineForNode } from './TimelineViewExtension';
21
+ import {
22
+ addTimelineTrackOp,
23
+ addTimelineEventOp,
24
+ removeTimelineTrackOp,
25
+ removeTimelineEventOp,
26
+ sanitizeTimelineText,
27
+ updateTimelineTrackOp,
28
+ updateTimelineEventOp,
29
+ type TimelineEventPatch,
30
+ } from './timelineOps';
31
+
32
+ export type TimelineCommand =
33
+ | {
34
+ kind: 'addTrack';
35
+ id?: string;
36
+ label?: string;
37
+ eventId?: string;
38
+ eventLabel?: string;
39
+ }
40
+ | { kind: 'updateTrack'; trackId: string; label: string }
41
+ | { kind: 'removeTrack'; trackId: string }
42
+ | {
43
+ kind: 'addEvent';
44
+ trackId: string;
45
+ /** Normalized position on the global timeline rail. */
46
+ position: number;
47
+ id?: string;
48
+ label?: string;
49
+ description?: string;
50
+ side?: AsciiTimelineSide;
51
+ descriptionSide?: AsciiTimelineSide;
52
+ callout?: boolean;
53
+ marker?: AsciiTimelineMarker;
54
+ }
55
+ | { kind: 'updateEvent'; eventId: string; patch: TimelineEventPatch }
56
+ | { kind: 'removeEvent'; eventId: string };
57
+
58
+ export interface TimelineCommandResult {
59
+ applied: boolean;
60
+ /** Present after add so the widget can select/focus the new marker. */
61
+ eventId?: string;
62
+ /** Present after adding a track. */
63
+ trackId?: string;
64
+ /** Why an otherwise valid semantic edit was deliberately blocked. */
65
+ reason?: 'read-only' | 'unsafe-source';
66
+ }
67
+
68
+ interface OpResult {
69
+ timeline: AsciiTimeline;
70
+ eventId?: string;
71
+ trackId?: string;
72
+ }
73
+
74
+ const NOT_APPLIED: TimelineCommandResult = { applied: false };
75
+ const READ_ONLY: TimelineCommandResult = { applied: false, reason: 'read-only' };
76
+ const UNSAFE_SOURCE: TimelineCommandResult = { applied: false, reason: 'unsafe-source' };
77
+
78
+ function countEvents(timeline: AsciiTimeline): number {
79
+ return timeline.tracks.reduce((sum, track) => sum + track.events.length, 0);
80
+ }
81
+
82
+ function hasEvent(timeline: AsciiTimeline, eventId: string): boolean {
83
+ return timeline.tracks.some((track) => track.events.some((event) => event.id === eventId));
84
+ }
85
+
86
+ function hasTrack(timeline: AsciiTimeline, trackId: string): boolean {
87
+ return timeline.tracks.some((track) => track.id === trackId);
88
+ }
89
+
90
+ /**
91
+ * Layout rows and source dimensions are deliberately absent: canonical
92
+ * rendering is allowed to compact hand-authored art. Everything the editor
93
+ * can semantically preserve is included, so this signature can distinguish
94
+ * harmless layout normalization from content loss.
95
+ */
96
+ function semanticSignature(timeline: AsciiTimeline): string {
97
+ return JSON.stringify({
98
+ style: timeline.style,
99
+ tracks: timeline.tracks.map((track) => ({
100
+ id: track.id,
101
+ label: track.label,
102
+ endLabel: track.endLabel,
103
+ startColumn: track.startColumn,
104
+ endColumn: track.endColumn,
105
+ events: track.events.map((event) => ({
106
+ id: event.id,
107
+ label: event.label,
108
+ description: event.description,
109
+ column: event.column,
110
+ side: event.side,
111
+ descriptionSide: event.descriptionSide,
112
+ callout: event.callout,
113
+ marker: event.marker,
114
+ })),
115
+ })),
116
+ links: timeline.links,
117
+ warnings: timeline.warnings,
118
+ });
119
+ }
120
+
121
+ const METADATA_BLOCK_RE = /\{([^{}\r\n]*)\}/gu;
122
+ const METADATA_ATTEMPT_RE = /^(?:#[^\s{}]*|[A-Za-z][A-Za-z0-9]*=)/u;
123
+ const MALFORMED_METADATA_RE =
124
+ /(?:\{[^{}\r\n]*(?:#[^\s{}]+|[A-Za-z][A-Za-z0-9]*=)|(?:#[^\s{}]+|[A-Za-z][A-Za-z0-9]*=)[^{}\r\n]*\})/u;
125
+ const UNICODE_MARKER_RE = /[●○◉◆◇•]/u;
126
+ const ASCII_MARKERS = new Set(['*', 'o', 'O']);
127
+ const RAIL_CHARS = new Set(['─', '━', '═', '╌', '╍', '┄', '┅', '┈', '┉', '-']);
128
+ const STRUCTURAL_CHARS_RE = /[─━═╌╍┄┅┈┉●○◉◆◇•►▶▷→>▲△▼▽│|└┌├┬┘┐╰╭╯╮:\-*]/gu;
129
+ const SEMANTIC_LEXEME_RE = /[\p{L}\p{N}_]+|[^\s]/gu;
130
+
131
+ type MetadataKind = 'track' | 'event';
132
+
133
+ /**
134
+ * Validate every metadata block that the parser could consume, then replace
135
+ * it with whitespace for source-content comparison. The parser deliberately
136
+ * accepts recognized tokens from a mixed block and ignores the rest; the
137
+ * editor must be stricter or `{#id unknown}` would be silently normalized.
138
+ */
139
+ function validateAndStripMetadata(source: string, timeline: AsciiTimeline): string | null {
140
+ const trackRows = new Set(timeline.tracks.map((track) => track.row));
141
+ const lines = source.replace(/\r\n?/g, '\n').split('\n');
142
+
143
+ for (let row = 0; row < lines.length; row++) {
144
+ const line = lines[row];
145
+ const trackRow = trackRows.has(row);
146
+ const pointerRow = /[▲△▼▽^v]/u.test(line);
147
+ if (!trackRow && !pointerRow) continue;
148
+ const firstMarker = trackRow ? firstAxisMarkerOffset(line, timeline.style) : -1;
149
+ let valid = true;
150
+ const stripped = line.replace(METADATA_BLOCK_RE, (block, inner: string, offset: number) => {
151
+ const tokens = inner.trim() ? inner.trim().split(/\s+/u) : [];
152
+ if (!tokens.some((token) => METADATA_ATTEMPT_RE.test(token))) return block;
153
+ const kind: MetadataKind =
154
+ trackRow && firstMarker >= 0 && offset < firstMarker ? 'track' : 'event';
155
+ if (!isValidMetadata(tokens, kind)) valid = false;
156
+ return ' '.repeat(block.length);
157
+ });
158
+ // A missing/opening brace prevents METADATA_BLOCK_RE from seeing the
159
+ // block at all. Reject the remaining metadata-shaped fragment as well.
160
+ if (!valid || MALFORMED_METADATA_RE.test(stripped)) return null;
161
+ lines[row] = stripped;
162
+ }
163
+ return lines.join('\n');
164
+ }
165
+
166
+ function isValidMetadata(tokens: readonly string[], kind: MetadataKind): boolean {
167
+ if (tokens.length === 0) return false;
168
+ const seen = new Set<string>();
169
+ for (const token of tokens) {
170
+ let key: string;
171
+ let valid = false;
172
+ if (token.startsWith('#') && token.length > 1) {
173
+ key = '#';
174
+ valid = !/[{}\s]/u.test(token.slice(1));
175
+ } else {
176
+ const separator = token.indexOf('=');
177
+ key = separator > 0 ? token.slice(0, separator) : token;
178
+ const value = separator > 0 ? token.slice(separator + 1) : '';
179
+ if (kind === 'track' && (key === 'start' || key === 'end')) {
180
+ valid = value.trim() !== '' && Number.isFinite(Number(value));
181
+ } else if (kind === 'event' && key === 'side') {
182
+ valid = value === 'above' || value === 'below';
183
+ } else if (kind === 'event' && key === 'descriptionSide') {
184
+ valid = value === 'above' || value === 'below';
185
+ } else if (kind === 'event' && key === 'column') {
186
+ valid = value.trim() !== '' && Number.isFinite(Number(value));
187
+ } else if (kind === 'event' && key === 'callout') {
188
+ valid = value === 'true' || value === 'false';
189
+ }
190
+ }
191
+ if (!valid || seen.has(key)) return false;
192
+ seen.add(key);
193
+ }
194
+ return true;
195
+ }
196
+
197
+ function firstAxisMarkerOffset(line: string, style: AsciiTimeline['style']): number {
198
+ if (style === 'unicode') return line.search(UNICODE_MARKER_RE);
199
+ for (let index = 0; index < line.length; index++) {
200
+ if (!ASCII_MARKERS.has(line[index])) continue;
201
+ const leftRail = railRun(line, index, -1);
202
+ const rightRail = railRun(line, index, 1);
203
+ const beforeIsWord = /[\p{L}\p{N}_]/u.test(line[index - 1] ?? '');
204
+ const afterIsWord = /[\p{L}\p{N}_]/u.test(line[index + 1] ?? '');
205
+ if ((leftRail >= 2 && !afterIsWord) || (rightRail >= 2 && !beforeIsWord)) return index;
206
+ }
207
+ return -1;
208
+ }
209
+
210
+ function railRun(line: string, index: number, direction: -1 | 1): number {
211
+ let count = 0;
212
+ for (let cursor = index + direction; RAIL_CHARS.has(line[cursor] ?? ''); cursor += direction) {
213
+ count++;
214
+ }
215
+ return count;
216
+ }
217
+
218
+ function semanticLexemeCounts(text: string): Map<string, number> {
219
+ const counts = new Map<string, number>();
220
+ const prose = text.normalize('NFC').replace(STRUCTURAL_CHARS_RE, ' ');
221
+ for (const match of prose.matchAll(SEMANTIC_LEXEME_RE)) {
222
+ const lexeme = match[0].toLocaleLowerCase();
223
+ counts.set(lexeme, (counts.get(lexeme) ?? 0) + 1);
224
+ }
225
+ return counts;
226
+ }
227
+
228
+ function countsEqual(
229
+ left: ReadonlyMap<string, number>,
230
+ right: ReadonlyMap<string, number>,
231
+ ): boolean {
232
+ if (left.size !== right.size) return false;
233
+ for (const [lexeme, count] of left) {
234
+ if (right.get(lexeme) !== count) return false;
235
+ }
236
+ return true;
237
+ }
238
+
239
+ function hasUnrepresentedStructuralOnlyLine(source: string, timeline: AsciiTimeline): boolean {
240
+ const trackRows = new Set(timeline.tracks.map((track) => track.row));
241
+ const lines = source.split('\n');
242
+ for (let row = 0; row < lines.length; row++) {
243
+ if (!lines[row].trim() || trackRows.has(row)) continue;
244
+ if (semanticLexemeCounts(lines[row]).size === 0) return true;
245
+ }
246
+ return false;
247
+ }
248
+
249
+ /**
250
+ * Semantic operations replace the whole fence with canonical rendered art.
251
+ * Fail closed when that would discard source the timeline model cannot
252
+ * represent. Warnings catch unresolved/unlabeled constructs; the semantic
253
+ * round-trip catches renderer normalization that changes modeled content;
254
+ * exact metadata validation rejects partially consumed attrs; and a linear
255
+ * semantic-residue comparison catches ignored prose/symbol rows without
256
+ * reparsing a successively shorter document for every source line.
257
+ */
258
+ export function isTimelineSourceSafeForSemanticEdit(
259
+ source: string,
260
+ timeline: AsciiTimeline,
261
+ ): boolean {
262
+ if (timeline.warnings.length > 0) return false;
263
+
264
+ const rendered = renderAsciiTimeline(timeline);
265
+ if (!rendered) return false;
266
+ const reparsed = parseAsciiTimeline(rendered);
267
+ const signature = semanticSignature(timeline);
268
+ if (reparsed.warnings.length > 0 || semanticSignature(reparsed) !== signature) return false;
269
+ // Wrapped-flow acceptance is deliberately all-or-nothing: its parser only
270
+ // returns a model when every nonblank row is represented. Once the model
271
+ // also survives the canonical render/parse signature above, the differing
272
+ // source vocabulary (lane headings and wrap connectors versus point
273
+ // metadata) is safe to normalize on the first visual edit.
274
+ if (isWrappedFlowTimelineSource(source)) return true;
275
+
276
+ const strippedSource = validateAndStripMetadata(source, timeline);
277
+ const strippedRendered = validateAndStripMetadata(rendered, reparsed);
278
+ if (!strippedSource || !strippedRendered) return false;
279
+ if (hasUnrepresentedStructuralOnlyLine(strippedSource, timeline)) return false;
280
+ return countsEqual(semanticLexemeCounts(strippedSource), semanticLexemeCounts(strippedRendered));
281
+ }
282
+
283
+ /**
284
+ * Verify the renderer/parser boundary before changing the document. Rows and
285
+ * source dimensions intentionally are not compared: canonical rendering
286
+ * compacts authored multi-line art while preserving its semantic content.
287
+ */
288
+ function verifyRenderedTimeline(next: AsciiTimeline, rendered: string): AsciiTimeline | null {
289
+ if (!rendered) return null;
290
+ const verification = parseAsciiTimeline(rendered);
291
+ if (renderAsciiTimeline(verification) !== rendered) return null;
292
+ if (verification.tracks.length !== next.tracks.length) return null;
293
+ if (countEvents(verification) !== countEvents(next)) return null;
294
+ if (verification.links.length !== next.links.length) return null;
295
+
296
+ const ids = new Set(
297
+ verification.tracks.flatMap((track) => track.events.map((event) => event.id)),
298
+ );
299
+ const trackIds = new Set(verification.tracks.map((track) => track.id));
300
+ if (trackIds.size !== verification.tracks.length) return null;
301
+ if (ids.size !== countEvents(verification)) return null;
302
+ if (verification.links.some((link) => !ids.has(link.source) || !ids.has(link.target))) {
303
+ return null;
304
+ }
305
+ return verification;
306
+ }
307
+
308
+ function applyOp(
309
+ editor: Editor,
310
+ blockId: string,
311
+ op: (timeline: AsciiTimeline) => OpResult | null,
312
+ verifyResult?: (timeline: AsciiTimeline) => boolean,
313
+ ): TimelineCommandResult {
314
+ // Resolve at dispatch time; captured ProseMirror positions become stale as
315
+ // soon as content above the fence changes.
316
+ const pos = findTimelineBlockPos(editor, blockId);
317
+ if (pos === null) return NOT_APPLIED;
318
+ const node = editor.state.doc.nodeAt(pos);
319
+ if (!node || node.type.name !== 'codeBlock') return NOT_APPLIED;
320
+ const timeline = parseTimelineForNode(node);
321
+ if (!timeline) return NOT_APPLIED;
322
+ if (!isTimelineSourceSafeForSemanticEdit(node.textContent, timeline)) return UNSAFE_SOURCE;
323
+
324
+ const result = op(timeline);
325
+ if (!result || result.timeline === timeline) return NOT_APPLIED;
326
+ const rendered = renderAsciiTimeline(result.timeline);
327
+ const verification = verifyRenderedTimeline(result.timeline, rendered);
328
+ if (
329
+ !verification ||
330
+ (result.eventId && !hasEvent(verification, result.eventId)) ||
331
+ (result.trackId && !hasTrack(verification, result.trackId)) ||
332
+ (verifyResult && !verifyResult(verification))
333
+ ) {
334
+ return NOT_APPLIED;
335
+ }
336
+
337
+ // Promoting to the explicit language makes an edited timeline sticky over
338
+ // Markdown <-> Tiptap round trips. Text + attrs change in one undo step.
339
+ if (!replaceAsciiFenceText(editor, pos, rendered, 'timeline')) return NOT_APPLIED;
340
+ return {
341
+ applied: true,
342
+ ...(result.eventId ? { eventId: result.eventId } : {}),
343
+ ...(result.trackId ? { trackId: result.trackId } : {}),
344
+ };
345
+ }
346
+
347
+ /** Apply one semantic timeline command to a registered fence block. */
348
+ export function applyTimelineCommand(
349
+ editor: Editor,
350
+ blockId: string,
351
+ command: TimelineCommand,
352
+ ): TimelineCommandResult {
353
+ // Commands may outlive the render that created their controls. Enforce the
354
+ // editor's current authority at dispatch time, not only in widget props.
355
+ if (!editor.isEditable) return READ_ONLY;
356
+
357
+ switch (command.kind) {
358
+ case 'addTrack':
359
+ return applyOp(editor, blockId, (timeline) =>
360
+ addTimelineTrackOp(timeline, {
361
+ id: command.id,
362
+ label: command.label,
363
+ eventId: command.eventId,
364
+ eventLabel: command.eventLabel,
365
+ }),
366
+ );
367
+ case 'updateTrack': {
368
+ const expectedLabel = sanitizeTimelineText(command.label);
369
+ return applyOp(
370
+ editor,
371
+ blockId,
372
+ (timeline) => ({
373
+ timeline: updateTimelineTrackOp(timeline, command.trackId, command.label),
374
+ }),
375
+ (timeline) =>
376
+ timeline.tracks.some(
377
+ (track) => track.id === command.trackId && track.label === expectedLabel,
378
+ ),
379
+ );
380
+ }
381
+ case 'removeTrack':
382
+ return applyOp(
383
+ editor,
384
+ blockId,
385
+ (timeline) => ({ timeline: removeTimelineTrackOp(timeline, command.trackId) }),
386
+ (timeline) => !hasTrack(timeline, command.trackId),
387
+ );
388
+ case 'addEvent':
389
+ return applyOp(editor, blockId, (timeline) => {
390
+ const result = addTimelineEventOp(timeline, command.trackId, command.position, {
391
+ id: command.id,
392
+ label: command.label,
393
+ description: command.description,
394
+ side: command.side,
395
+ descriptionSide: command.descriptionSide,
396
+ callout: command.callout,
397
+ marker: command.marker,
398
+ });
399
+ return result;
400
+ });
401
+ case 'updateEvent':
402
+ return applyOp(
403
+ editor,
404
+ blockId,
405
+ (timeline) => ({
406
+ timeline: updateTimelineEventOp(timeline, command.eventId, command.patch),
407
+ }),
408
+ (timeline) => hasEvent(timeline, command.eventId),
409
+ );
410
+ case 'removeEvent':
411
+ return applyOp(
412
+ editor,
413
+ blockId,
414
+ (timeline) => ({ timeline: removeTimelineEventOp(timeline, command.eventId) }),
415
+ (timeline) => !hasEvent(timeline, command.eventId),
416
+ );
417
+ }
418
+ const exhaustive: never = command;
419
+ void exhaustive;
420
+ return NOT_APPLIED;
421
+ }
@@ -0,0 +1,54 @@
1
+ /** Live read-direction adapter from a registered timeline fence to React. */
2
+
3
+ import { useEffect, useMemo, useRef, useState } from 'react';
4
+ import type { Editor } from '@tiptap/react';
5
+ import type { AsciiTimeline } from '@bendyline/squisq/doc';
6
+ import { findTimelineBlockPos, parseTimelineForNode } from './TimelineViewExtension';
7
+
8
+ export interface TimelineViewData {
9
+ timeline: AsciiTimeline;
10
+ text: string;
11
+ warnings: string[];
12
+ }
13
+
14
+ export function useTimelineData(editor: Editor, blockId: string): TimelineViewData | null {
15
+ const [version, setVersion] = useState(0);
16
+ const dataCache = useRef<{
17
+ text: string;
18
+ language: string | null;
19
+ data: TimelineViewData;
20
+ } | null>(null);
21
+ useEffect(() => {
22
+ const onEditorChange = () => setVersion((value) => value + 1);
23
+ editor.on('transaction', onEditorChange);
24
+ // setEditable() updates editor options and emits `update`, but does not
25
+ // necessarily dispatch a ProseMirror transaction. Keep mounted widgets in
26
+ // sync when a host toggles read-only mode at runtime.
27
+ editor.on('update', onEditorChange);
28
+ return () => {
29
+ editor.off('transaction', onEditorChange);
30
+ editor.off('update', onEditorChange);
31
+ };
32
+ }, [editor]);
33
+
34
+ return useMemo(() => {
35
+ const pos = findTimelineBlockPos(editor, blockId);
36
+ if (pos === null) return null;
37
+ const node = editor.state.doc.nodeAt(pos);
38
+ if (!node || node.type.name !== 'codeBlock') return null;
39
+ const text = node.textContent;
40
+ const rawLanguage = (node.attrs as { language?: unknown }).language;
41
+ const language = typeof rawLanguage === 'string' ? rawLanguage : null;
42
+ const cached = dataCache.current;
43
+ // ProseMirror can rebuild ancestor nodes for an unrelated edit. Source
44
+ // text + language fully determine the timeline parse, so retain the data
45
+ // and model identities across those transactions (and editable updates).
46
+ if (cached?.text === text && cached.language === language) return cached.data;
47
+ const timeline = parseTimelineForNode(node);
48
+ if (!timeline) return null;
49
+ const data = { timeline, text, warnings: timeline.warnings };
50
+ dataCache.current = { text, language, data };
51
+ return data;
52
+ // eslint-disable-next-line react-hooks/exhaustive-deps
53
+ }, [editor, blockId, version]);
54
+ }