@bendyline/squisq-editor-react 1.6.1 → 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 (208) hide show
  1. package/README.md +12 -3
  2. package/dist/index.d.ts +1304 -208
  3. package/dist/index.js +22838 -14494
  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 +2384 -408
  9. package/package.json +9 -5
  10. package/src/BlockPropertiesPopover.tsx +48 -17
  11. package/src/DocumentSettingsDialog.tsx +13 -21
  12. package/src/EditorContext.tsx +199 -42
  13. package/src/EditorShell.tsx +403 -270
  14. package/src/ImageEditor.tsx +22 -1
  15. package/src/InlinePreviewGutter.tsx +16 -8
  16. package/src/MediaBin.tsx +276 -40
  17. package/src/OutlinePanel.tsx +202 -7
  18. package/src/PlainHtmlPreview.tsx +40 -1
  19. package/src/PreviewControls.tsx +466 -93
  20. package/src/PreviewPanel.tsx +313 -77
  21. package/src/RawEditor.tsx +13 -2
  22. package/src/StatusBar.tsx +5 -2
  23. package/src/TemplateAnnotation.ts +34 -10
  24. package/src/TemplateContentPreview.tsx +56 -0
  25. package/src/TemplatePicker.tsx +355 -134
  26. package/src/ThemeCustomizerPanel.tsx +30 -15
  27. package/src/ThemePicker.tsx +10 -5
  28. package/src/TimelineBlockPreview.tsx +1 -1
  29. package/src/Toolbar.tsx +719 -238
  30. package/src/TransitionPicker.tsx +44 -5
  31. package/src/ViewMenuPanel.tsx +12 -14
  32. package/src/ViewSwitcher.tsx +4 -4
  33. package/src/WysiwygEditor.tsx +167 -92
  34. package/src/__tests__/blockPropertiesPopoverTheme.test.tsx +33 -0
  35. package/src/__tests__/blockTagActivity.test.ts +183 -0
  36. package/src/__tests__/buildDocumentPreviewMarkdown.test.ts +75 -0
  37. package/src/__tests__/buildPreviewDocContent.test.ts +48 -0
  38. package/src/__tests__/buildPreviewDocTransition.test.ts +22 -3
  39. package/src/__tests__/canvasSurfaceTextEditing.test.tsx +60 -0
  40. package/src/__tests__/customLayoutManagerTheme.test.tsx +34 -0
  41. package/src/__tests__/documentSettingsDialog.test.tsx +29 -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 +390 -1
  45. package/src/__tests__/emojiPicker.test.tsx +2 -42
  46. package/src/__tests__/headingTransition.test.ts +53 -15
  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 +38 -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__/mediaBinDrop.test.tsx +90 -0
  54. package/src/__tests__/mediaReferences.test.ts +82 -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 +312 -6
  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__/resolveBlockVisual.test.ts +43 -0
  66. package/src/__tests__/statusBar.test.tsx +27 -0
  67. package/src/__tests__/teleprompter.test.tsx +190 -0
  68. package/src/__tests__/templateAnnotationRoundTrip.test.ts +49 -2
  69. package/src/__tests__/templateContentPreview.test.ts +101 -0
  70. package/src/__tests__/templatePickerPortal.test.tsx +62 -0
  71. package/src/__tests__/tiptapBridge.test.ts +70 -0
  72. package/src/__tests__/tiptapCodeBlockRoundTrip.test.ts +109 -0
  73. package/src/__tests__/transformStyleId.test.ts +13 -0
  74. package/src/__tests__/useImageEditor.test.tsx +67 -0
  75. package/src/__tests__/useMediaRecorder.test.ts +75 -0
  76. package/src/__tests__/viewMenuPanel.test.tsx +130 -0
  77. package/src/__tests__/wysiwygImageUpload.test.ts +69 -0
  78. package/src/__tests__/wysiwygTemplateBadgeFocus.test.tsx +56 -0
  79. package/src/asciiDiagram/AsciiDiagramExtension.ts +343 -0
  80. package/src/asciiDiagram/AsciiDiagramWidget.tsx +224 -0
  81. package/src/asciiDiagram/RepairableDiagramExtension.ts +200 -0
  82. package/src/asciiDiagram/__tests__/AsciiDiagramExtension.test.ts +145 -0
  83. package/src/asciiDiagram/__tests__/RepairableDiagramExtension.test.ts +159 -0
  84. package/src/asciiDiagram/__tests__/asciiDiagramCommands.test.ts +227 -0
  85. package/src/asciiDiagram/__tests__/asciiDiagramOps.test.ts +114 -0
  86. package/src/asciiDiagram/__tests__/asciiPaste.test.ts +43 -0
  87. package/src/asciiDiagram/asciiDiagramCommands.ts +148 -0
  88. package/src/asciiDiagram/asciiDiagramData.ts +116 -0
  89. package/src/asciiDiagram/asciiDiagramOps.ts +219 -0
  90. package/src/asciiDiagram/asciiPaste.ts +19 -0
  91. package/src/blockTagActivity.ts +233 -0
  92. package/src/buildDocumentPreviewMarkdown.ts +168 -0
  93. package/src/buildPreviewDoc.ts +19 -12
  94. package/src/customTemplates/CustomLayoutManager.tsx +3 -2
  95. package/src/customTemplates/CustomTemplateContext.tsx +6 -0
  96. package/src/customTemplates/TemplateDesigner.tsx +7 -4
  97. package/src/customTemplates/__tests__/library.test.ts +8 -0
  98. package/src/customTemplates/designer.css +158 -99
  99. package/src/customTemplates/library.ts +16 -3
  100. package/src/customThemes/CustomThemeContext.tsx +6 -0
  101. package/src/customThemes/CustomThemeDialog.tsx +35 -5
  102. package/src/customThemes/ImportThemeSection.tsx +178 -0
  103. package/src/customThemes/__tests__/customThemeLibrary.test.ts +9 -0
  104. package/src/customThemes/__tests__/importThemeSection.test.tsx +192 -0
  105. package/src/customThemes/customThemeLibrary.ts +7 -4
  106. package/src/customThemes/index.ts +7 -1
  107. package/src/customThemes/themeDraft.ts +23 -7
  108. package/src/diagram/DiagramCanvas.tsx +9 -4
  109. package/src/diagram/types.ts +35 -0
  110. package/src/editorScrollSync.ts +73 -0
  111. package/src/emojiData.ts +3 -23
  112. package/src/headingTransition.ts +85 -25
  113. package/src/imageEditor/CanvasSurface.tsx +29 -23
  114. package/src/imageEditor/LayersPanel.tsx +78 -3
  115. package/src/imageEditor/Toolbar.tsx +5 -1
  116. package/src/imageEditor/icons.tsx +4 -0
  117. package/src/imageEditor/image-editor.css +75 -0
  118. package/src/imageEditor/layers/SelectionHandles.tsx +1 -1
  119. package/src/imageEditor/useImageEditor.ts +71 -14
  120. package/src/index.ts +193 -20
  121. package/src/jsonEditor/JsonEditorContext.tsx +12 -6
  122. package/src/jsonEditor/RenderNode.tsx +24 -3
  123. package/src/jsonEditor/editors.tsx +86 -19
  124. package/src/mediaEntries.ts +12 -0
  125. package/src/mediaReferences.ts +299 -0
  126. package/src/monaco.ts +35 -0
  127. package/src/monacoWorkers.ts +89 -0
  128. package/src/outlineSource.ts +171 -0
  129. package/src/presentation/PresentationMode.tsx +596 -0
  130. package/src/rawEditorIsolation.ts +18 -0
  131. package/src/recorder/hooks/useMediaRecorder.ts +97 -53
  132. package/src/resolveBlockVisual.ts +10 -4
  133. package/src/scene/Scene.tsx +101 -25
  134. package/src/scene/SceneBlockExtension.ts +17 -10
  135. package/src/scene/SceneBlockWidget.tsx +11 -4
  136. package/src/scene/SceneSelection.tsx +19 -15
  137. package/src/scene/SceneSideToolbar.tsx +89 -0
  138. package/src/scene/SceneViewport.tsx +7 -3
  139. package/src/scene/ShapePalette.tsx +17 -2
  140. package/src/scene/__tests__/DiagramAdapter.test.ts +86 -0
  141. package/src/scene/__tests__/SceneBlockExtension.test.ts +33 -0
  142. package/src/scene/__tests__/sceneIsolation.test.tsx +93 -0
  143. package/src/scene/adapters/DiagramAdapter.ts +12 -101
  144. package/src/scene/commands/SceneCommand.ts +4 -1
  145. package/src/scene/index.ts +1 -6
  146. package/src/scene/layers/DiagramEdges.tsx +24 -9
  147. package/src/scene/layers/edgeGeometry.ts +31 -4
  148. package/src/scene/layers/nodeCard.tsx +27 -8
  149. package/src/scene/scene.css +145 -2
  150. package/src/scene/text/SceneTextOverlay.tsx +5 -5
  151. package/src/scene/text/sceneTextChannel.ts +26 -20
  152. package/src/scene/text/sceneTextConfig.ts +4 -0
  153. package/src/scene/tools/ConnectTool.ts +126 -28
  154. package/src/scene/tools/DrawingConnectTool.ts +86 -16
  155. package/src/scene/tools/SceneTool.ts +10 -0
  156. package/src/scene/tools/SelectTool.ts +34 -18
  157. package/src/scene/tools/ShapeTool.ts +2 -3
  158. package/src/styles/ascii-diagram.css +79 -0
  159. package/src/styles/ascii-timeline.css +499 -0
  160. package/src/styles/editor.css +1566 -219
  161. package/src/styles/index.css +3 -0
  162. package/src/styles/tree-view.css +139 -0
  163. package/src/teleprompter/TeleprompterControls.tsx +218 -0
  164. package/src/teleprompter/TeleprompterSelfView.tsx +22 -0
  165. package/src/teleprompter/TeleprompterSurface.tsx +267 -0
  166. package/src/teleprompter/TeleprompterView.tsx +338 -0
  167. package/src/teleprompter/canvasRenderer.ts +161 -0
  168. package/src/teleprompter/floatingWindow.ts +352 -0
  169. package/src/teleprompter/index.ts +61 -0
  170. package/src/teleprompter/pcmWorklet.ts +62 -0
  171. package/src/teleprompter/recording/insertPreamble.ts +80 -0
  172. package/src/teleprompter/recording/narrationSave.ts +134 -0
  173. package/src/teleprompter/recording/useNarrationRecorder.ts +367 -0
  174. package/src/teleprompter/scrollModel.ts +85 -0
  175. package/src/teleprompter/teleprompterTheme.ts +303 -0
  176. package/src/teleprompter/types.ts +38 -0
  177. package/src/teleprompter/useFloatingWindow.ts +74 -0
  178. package/src/teleprompter/useMicAnalysis.ts +211 -0
  179. package/src/teleprompter/useTeleprompter.ts +421 -0
  180. package/src/templateContentPreviewResolver.ts +360 -0
  181. package/src/timeline/TimelineEditorWidget.tsx +702 -0
  182. package/src/timeline/TimelineViewExtension.ts +252 -0
  183. package/src/timeline/__tests__/TimelineEditorWidget.test.tsx +355 -0
  184. package/src/timeline/__tests__/TimelineViewExtension.test.ts +163 -0
  185. package/src/timeline/__tests__/timelineCommands.test.ts +327 -0
  186. package/src/timeline/__tests__/timelineOps.test.ts +222 -0
  187. package/src/timeline/__tests__/timelinePaste.test.ts +34 -0
  188. package/src/timeline/timelineCommands.ts +367 -0
  189. package/src/timeline/timelineData.ts +54 -0
  190. package/src/timeline/timelineOps.ts +277 -0
  191. package/src/timeline/timelinePaste.ts +8 -0
  192. package/src/tiptapBridge.ts +84 -49
  193. package/src/transformStyleId.ts +17 -0
  194. package/src/treeview/TreeOutlineWidget.tsx +240 -0
  195. package/src/treeview/TreeViewExtension.ts +250 -0
  196. package/src/treeview/__tests__/TreeViewExtension.test.ts +122 -0
  197. package/src/treeview/__tests__/treeOps.test.ts +125 -0
  198. package/src/treeview/__tests__/treePaste.test.ts +40 -0
  199. package/src/treeview/__tests__/treeViewCommands.test.ts +163 -0
  200. package/src/treeview/treeOps.ts +172 -0
  201. package/src/treeview/treePaste.ts +13 -0
  202. package/src/treeview/treeViewCommands.ts +94 -0
  203. package/src/treeview/treeViewData.ts +41 -0
  204. package/src/useMonacoLoader.ts +11 -34
  205. package/src/wysiwygImageUpload.ts +113 -0
  206. package/src/diagram/DiagramExtension.ts +0 -209
  207. package/src/diagram/DiagramWidget.tsx +0 -270
  208. package/src/diagram/useDiagramData.ts +0 -126
@@ -0,0 +1,222 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { parseAsciiTimeline, renderAsciiTimeline, type AsciiTimeline } from '@bendyline/squisq/doc';
3
+ import {
4
+ addTimelineEventOp,
5
+ nextTimelineEventId,
6
+ removeTimelineEventOp,
7
+ sanitizeTimelineText,
8
+ updateTimelineEventOp,
9
+ } from '../timelineOps';
10
+
11
+ function makeTimeline(): AsciiTimeline {
12
+ return {
13
+ tracks: [
14
+ {
15
+ id: 'kernel',
16
+ label: 'Kernel',
17
+ row: 0,
18
+ startColumn: 10,
19
+ endColumn: 70,
20
+ events: [
21
+ { id: 'start', label: 'Start', column: 10, side: 'above', marker: 'filled' },
22
+ { id: 'review', label: 'Review', column: 55, side: 'below', marker: 'hollow' },
23
+ ],
24
+ },
25
+ {
26
+ id: 'client',
27
+ label: 'Client',
28
+ row: 2,
29
+ startColumn: 20,
30
+ endColumn: 100,
31
+ events: [
32
+ {
33
+ id: 'frame',
34
+ label: 'f',
35
+ column: 20,
36
+ side: 'above',
37
+ callout: false,
38
+ marker: 'hollow',
39
+ },
40
+ { id: 'paint', label: 'Paint', column: 100, side: 'below', marker: 'filled' },
41
+ ],
42
+ },
43
+ ],
44
+ links: [
45
+ { source: 'start', target: 'frame', label: 'begins' },
46
+ { source: 'review', target: 'paint' },
47
+ ],
48
+ width: 101,
49
+ height: 3,
50
+ style: 'unicode',
51
+ warnings: [],
52
+ };
53
+ }
54
+
55
+ function event(timeline: AsciiTimeline, id: string) {
56
+ return timeline.tracks.flatMap((track) => track.events).find((candidate) => candidate.id === id);
57
+ }
58
+
59
+ function expectFixpoint(timeline: AsciiTimeline): void {
60
+ const rendered = renderAsciiTimeline(timeline);
61
+ expect(renderAsciiTimeline(parseAsciiTimeline(rendered))).toBe(rendered);
62
+ }
63
+
64
+ describe('timeline editor pure operations', () => {
65
+ it('sanitizes one-line text with the renderer vocabulary', () => {
66
+ expect(sanitizeTimelineText(' --watch\n● phase :: ready * ')).toBe(
67
+ '−−watch · phase ∶ ready ∗',
68
+ );
69
+ });
70
+
71
+ it('generates globally unique, stable event ids', () => {
72
+ const timeline = makeTimeline();
73
+ expect(nextTimelineEventId(timeline, 'Start')).toBe('start-2');
74
+ expect(nextTimelineEventId(timeline, 'A new point')).toBe('a-new-point');
75
+ });
76
+
77
+ it('adds at the globally normalized position without mutating its input', () => {
78
+ const timeline = makeTimeline();
79
+ const before = JSON.stringify(timeline);
80
+ // Shared bounds are 10..100, so 25% is source column 32.5.
81
+ const result = addTimelineEventOp(timeline, 'kernel', 0.25, {
82
+ label: 'Compile',
83
+ description: 'Build the frame',
84
+ });
85
+
86
+ expect(result).not.toBeNull();
87
+ expect(JSON.stringify(timeline)).toBe(before);
88
+ expect(result?.eventId).toBe('compile');
89
+ expect(event(result!.timeline, 'compile')).toMatchObject({
90
+ label: 'Compile',
91
+ description: 'Build the frame',
92
+ column: 32.5,
93
+ side: 'below',
94
+ marker: 'filled',
95
+ });
96
+ expect(result?.timeline.tracks[0].events.map((point) => point.id)).toEqual([
97
+ 'start',
98
+ 'compile',
99
+ 'review',
100
+ ]);
101
+ expectFixpoint(result!.timeline);
102
+ });
103
+
104
+ it('clamps positions, rejects nonfinite positions, unknown tracks, and collisions', () => {
105
+ const timeline = makeTimeline();
106
+ expect(addTimelineEventOp(timeline, 'missing', 0.2)).toBeNull();
107
+ expect(addTimelineEventOp(timeline, 'kernel', Number.NaN)).toBeNull();
108
+ expect(addTimelineEventOp(timeline, 'kernel', 0)).toBeNull(); // `start` already at column 10
109
+
110
+ const result = addTimelineEventOp(timeline, 'client', 2, { label: 'After' });
111
+ expect(result).toBeNull(); // clamped column 100 is occupied by `paint`
112
+ });
113
+
114
+ it('updates text and styling while preserving ids and branch endpoints', () => {
115
+ const timeline = makeTimeline();
116
+ const next = updateTimelineEventOp(timeline, 'start', {
117
+ label: 'Boot',
118
+ description: 'Initialize\nworld',
119
+ side: 'below',
120
+ descriptionSide: 'above',
121
+ marker: 'diamond',
122
+ position: 0.4,
123
+ });
124
+
125
+ expect(next).not.toBe(timeline);
126
+ expect(event(timeline, 'start')?.label).toBe('Start');
127
+ expect(event(next, 'start')).toMatchObject({
128
+ id: 'start',
129
+ label: 'Boot',
130
+ description: 'Initialize world',
131
+ column: 46,
132
+ side: 'below',
133
+ descriptionSide: 'above',
134
+ marker: 'diamond',
135
+ });
136
+ expect(next.links[0]).toMatchObject({ source: 'start', target: 'frame' });
137
+ expect(next.tracks[0].startColumn).toBe(46);
138
+ expectFixpoint(next);
139
+ });
140
+
141
+ it('resets track bounds after dropping a point that anchored an edge', () => {
142
+ const timeline = makeTimeline();
143
+
144
+ const movedStart = updateTimelineEventOp(timeline, 'start', { position: 0.3 });
145
+ expect(event(movedStart, 'start')?.column).toBe(37);
146
+ expect(movedStart.tracks[0]).toMatchObject({ startColumn: 37, endColumn: 70 });
147
+
148
+ const crossedStart = updateTimelineEventOp(timeline, 'start', { position: 0.8 });
149
+ expect(crossedStart.tracks[0].events.map((point) => point.id)).toEqual(['review', 'start']);
150
+ expect(crossedStart.tracks[0]).toMatchObject({ startColumn: 55, endColumn: 82 });
151
+
152
+ const movedEnd = updateTimelineEventOp(timeline, 'paint', { position: 0.7 });
153
+ expect(event(movedEnd, 'paint')?.column).toBe(73);
154
+ expect(movedEnd.tracks[1]).toMatchObject({ startColumn: 20, endColumn: 73 });
155
+ expectFixpoint(movedStart);
156
+ expectFixpoint(crossedStart);
157
+ expectFixpoint(movedEnd);
158
+ });
159
+
160
+ it('promotes an edited cadence point to a visible callout and can clear its description', () => {
161
+ const timeline = makeTimeline();
162
+ const visible = updateTimelineEventOp(timeline, 'frame', {
163
+ label: 'Dropped frame',
164
+ description: 'Late snapshot',
165
+ });
166
+ expect(event(visible, 'frame')).toMatchObject({
167
+ label: 'Dropped frame',
168
+ description: 'Late snapshot',
169
+ callout: true,
170
+ });
171
+
172
+ const cleared = updateTimelineEventOp(visible, 'frame', {
173
+ description: null,
174
+ descriptionSide: null,
175
+ });
176
+ expect(event(cleared, 'frame')?.description).toBeUndefined();
177
+ expect(event(cleared, 'frame')?.descriptionSide).toBeUndefined();
178
+ });
179
+
180
+ it('promotes ASCII art to Unicode when a diamond marker is requested', () => {
181
+ const timeline = { ...makeTimeline(), style: 'ascii' as const };
182
+ const next = updateTimelineEventOp(timeline, 'start', { marker: 'diamond' });
183
+ expect(next.style).toBe('unicode');
184
+ expect(parseAsciiTimeline(renderAsciiTimeline(next)).tracks[0].events[0].marker).toBe(
185
+ 'diamond',
186
+ );
187
+ });
188
+
189
+ it('returns the original for invalid or no-op updates', () => {
190
+ const timeline = makeTimeline();
191
+ expect(updateTimelineEventOp(timeline, 'missing', { label: 'Nope' })).toBe(timeline);
192
+ expect(updateTimelineEventOp(timeline, 'start', { label: ' ' })).toBe(timeline);
193
+ expect(updateTimelineEventOp(timeline, 'start', { position: Number.POSITIVE_INFINITY })).toBe(
194
+ timeline,
195
+ );
196
+ expect(updateTimelineEventOp(timeline, 'start', { position: 0.5 })).toBe(timeline); // review
197
+ expect(updateTimelineEventOp(timeline, 'start', { label: 'Start' })).toBe(timeline);
198
+ });
199
+
200
+ it('deletes incident links and removes a track after its final event', () => {
201
+ const timeline = makeTimeline();
202
+ const withoutFrame = removeTimelineEventOp(timeline, 'frame');
203
+ expect(event(withoutFrame, 'frame')).toBeUndefined();
204
+ expect(withoutFrame.links).toEqual([{ source: 'review', target: 'paint' }]);
205
+ expect(withoutFrame.tracks).toHaveLength(2);
206
+
207
+ const withoutClient = removeTimelineEventOp(withoutFrame, 'paint');
208
+ expect(withoutClient.tracks.map((track) => track.id)).toEqual(['kernel']);
209
+ expect(withoutClient.links).toEqual([]);
210
+ expectFixpoint(withoutClient);
211
+ });
212
+
213
+ it('keeps the final event so an edit cannot erase its own fence', () => {
214
+ const timeline = makeTimeline();
215
+ const one: AsciiTimeline = {
216
+ ...timeline,
217
+ tracks: [{ ...timeline.tracks[0], events: [timeline.tracks[0].events[0]] }],
218
+ links: [],
219
+ };
220
+ expect(removeTimelineEventOp(one, 'start')).toBe(one);
221
+ });
222
+ });
@@ -0,0 +1,34 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import { shouldPasteAsTimelineFence } from '../timelinePaste';
3
+
4
+ const MULTI_TRACK = [
5
+ 'Kernel: ● T28 {#t28} ─────● T29 {#t29} ─────►',
6
+ 'Client: ○ F28 {#f28} ─────● F29 {#f29} ─────►',
7
+ 'branch: t29 -> f29 : interpolate',
8
+ ].join('\n');
9
+
10
+ describe('shouldPasteAsTimelineFence', () => {
11
+ it('accepts bare, high-confidence Unicode timeline art', () => {
12
+ expect(shouldPasteAsTimelineFence(MULTI_TRACK)).toBe(true);
13
+ expect(shouldPasteAsTimelineFence(' ┌─ warmup\n────●────●────►')).toBe(true);
14
+ });
15
+
16
+ it('rejects already-fenced input, sparse ASCII, prose, and blank text', () => {
17
+ expect(shouldPasteAsTimelineFence(`\`\`\`timeline\n${MULTI_TRACK}\n\`\`\``)).toBe(false);
18
+ expect(shouldPasteAsTimelineFence('Release: *---- Alpha {#alpha} ---->')).toBe(false);
19
+ expect(shouldPasteAsTimelineFence('Release planning -- Alpha -> Beta')).toBe(false);
20
+ expect(shouldPasteAsTimelineFence(' \n\t')).toBe(false);
21
+ });
22
+
23
+ it('does not steal Markdown tables, trees, or box diagrams', () => {
24
+ const table = ['| Milestone | Date |', '| --- | --- |', '| Alpha | Monday |'].join('\n');
25
+ const tree = ['root/', '├── src/', '│ └── index.ts', '└── README.md'].join('\n');
26
+ const diagram = ['┌─────┐', '│ A │', '└──┬──┘', ' ▼', '┌─────┐', '│ B │', '└─────┘'].join(
27
+ '\n',
28
+ );
29
+
30
+ expect(shouldPasteAsTimelineFence(table)).toBe(false);
31
+ expect(shouldPasteAsTimelineFence(tree)).toBe(false);
32
+ expect(shouldPasteAsTimelineFence(diagram)).toBe(false);
33
+ });
34
+ });
@@ -0,0 +1,367 @@
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
+ addTimelineEventOp,
23
+ removeTimelineEventOp,
24
+ updateTimelineEventOp,
25
+ type TimelineEventPatch,
26
+ } from './timelineOps';
27
+
28
+ export type TimelineCommand =
29
+ | {
30
+ kind: 'addEvent';
31
+ trackId: string;
32
+ /** Normalized position on the global timeline rail. */
33
+ position: number;
34
+ id?: string;
35
+ label?: string;
36
+ description?: string;
37
+ side?: AsciiTimelineSide;
38
+ descriptionSide?: AsciiTimelineSide;
39
+ callout?: boolean;
40
+ marker?: AsciiTimelineMarker;
41
+ }
42
+ | { kind: 'updateEvent'; eventId: string; patch: TimelineEventPatch }
43
+ | { kind: 'removeEvent'; eventId: string };
44
+
45
+ export interface TimelineCommandResult {
46
+ applied: boolean;
47
+ /** Present after add so the widget can select/focus the new marker. */
48
+ eventId?: string;
49
+ /** Why an otherwise valid semantic edit was deliberately blocked. */
50
+ reason?: 'read-only' | 'unsafe-source';
51
+ }
52
+
53
+ interface OpResult {
54
+ timeline: AsciiTimeline;
55
+ eventId?: string;
56
+ }
57
+
58
+ const NOT_APPLIED: TimelineCommandResult = { applied: false };
59
+ const READ_ONLY: TimelineCommandResult = { applied: false, reason: 'read-only' };
60
+ const UNSAFE_SOURCE: TimelineCommandResult = { applied: false, reason: 'unsafe-source' };
61
+
62
+ function countEvents(timeline: AsciiTimeline): number {
63
+ return timeline.tracks.reduce((sum, track) => sum + track.events.length, 0);
64
+ }
65
+
66
+ function hasEvent(timeline: AsciiTimeline, eventId: string): boolean {
67
+ return timeline.tracks.some((track) => track.events.some((event) => event.id === eventId));
68
+ }
69
+
70
+ /**
71
+ * Layout rows and source dimensions are deliberately absent: canonical
72
+ * rendering is allowed to compact hand-authored art. Everything the editor
73
+ * can semantically preserve is included, so this signature can distinguish
74
+ * harmless layout normalization from content loss.
75
+ */
76
+ function semanticSignature(timeline: AsciiTimeline): string {
77
+ return JSON.stringify({
78
+ style: timeline.style,
79
+ tracks: timeline.tracks.map((track) => ({
80
+ id: track.id,
81
+ label: track.label,
82
+ endLabel: track.endLabel,
83
+ startColumn: track.startColumn,
84
+ endColumn: track.endColumn,
85
+ events: track.events.map((event) => ({
86
+ id: event.id,
87
+ label: event.label,
88
+ description: event.description,
89
+ column: event.column,
90
+ side: event.side,
91
+ descriptionSide: event.descriptionSide,
92
+ callout: event.callout,
93
+ marker: event.marker,
94
+ })),
95
+ })),
96
+ links: timeline.links,
97
+ warnings: timeline.warnings,
98
+ });
99
+ }
100
+
101
+ const METADATA_BLOCK_RE = /\{([^{}\r\n]*)\}/gu;
102
+ const METADATA_ATTEMPT_RE = /^(?:#[^\s{}]*|[A-Za-z][A-Za-z0-9]*=)/u;
103
+ const MALFORMED_METADATA_RE =
104
+ /(?:\{[^{}\r\n]*(?:#[^\s{}]+|[A-Za-z][A-Za-z0-9]*=)|(?:#[^\s{}]+|[A-Za-z][A-Za-z0-9]*=)[^{}\r\n]*\})/u;
105
+ const UNICODE_MARKER_RE = /[●○◉◆◇•]/u;
106
+ const ASCII_MARKERS = new Set(['*', 'o', 'O']);
107
+ const RAIL_CHARS = new Set(['─', '━', '═', '╌', '╍', '┄', '┅', '┈', '┉', '-']);
108
+ const STRUCTURAL_CHARS_RE = /[─━═╌╍┄┅┈┉●○◉◆◇•►▶▷→>▲△▼▽│|└┌├┬┘┐╰╭╯╮:\-*]/gu;
109
+ const SEMANTIC_LEXEME_RE = /[\p{L}\p{N}_]+|[^\s]/gu;
110
+
111
+ type MetadataKind = 'track' | 'event';
112
+
113
+ /**
114
+ * Validate every metadata block that the parser could consume, then replace
115
+ * it with whitespace for source-content comparison. The parser deliberately
116
+ * accepts recognized tokens from a mixed block and ignores the rest; the
117
+ * editor must be stricter or `{#id unknown}` would be silently normalized.
118
+ */
119
+ function validateAndStripMetadata(source: string, timeline: AsciiTimeline): string | null {
120
+ const trackRows = new Set(timeline.tracks.map((track) => track.row));
121
+ const lines = source.replace(/\r\n?/g, '\n').split('\n');
122
+
123
+ for (let row = 0; row < lines.length; row++) {
124
+ const line = lines[row];
125
+ const trackRow = trackRows.has(row);
126
+ const pointerRow = /[▲△▼▽^v]/u.test(line);
127
+ if (!trackRow && !pointerRow) continue;
128
+ const firstMarker = trackRow ? firstAxisMarkerOffset(line, timeline.style) : -1;
129
+ let valid = true;
130
+ const stripped = line.replace(METADATA_BLOCK_RE, (block, inner: string, offset: number) => {
131
+ const tokens = inner.trim() ? inner.trim().split(/\s+/u) : [];
132
+ if (!tokens.some((token) => METADATA_ATTEMPT_RE.test(token))) return block;
133
+ const kind: MetadataKind =
134
+ trackRow && firstMarker >= 0 && offset < firstMarker ? 'track' : 'event';
135
+ if (!isValidMetadata(tokens, kind)) valid = false;
136
+ return ' '.repeat(block.length);
137
+ });
138
+ // A missing/opening brace prevents METADATA_BLOCK_RE from seeing the
139
+ // block at all. Reject the remaining metadata-shaped fragment as well.
140
+ if (!valid || MALFORMED_METADATA_RE.test(stripped)) return null;
141
+ lines[row] = stripped;
142
+ }
143
+ return lines.join('\n');
144
+ }
145
+
146
+ function isValidMetadata(tokens: readonly string[], kind: MetadataKind): boolean {
147
+ if (tokens.length === 0) return false;
148
+ const seen = new Set<string>();
149
+ for (const token of tokens) {
150
+ let key: string;
151
+ let valid = false;
152
+ if (token.startsWith('#') && token.length > 1) {
153
+ key = '#';
154
+ valid = !/[{}\s]/u.test(token.slice(1));
155
+ } else {
156
+ const separator = token.indexOf('=');
157
+ key = separator > 0 ? token.slice(0, separator) : token;
158
+ const value = separator > 0 ? token.slice(separator + 1) : '';
159
+ if (kind === 'track' && (key === 'start' || key === 'end')) {
160
+ valid = value.trim() !== '' && Number.isFinite(Number(value));
161
+ } else if (kind === 'event' && key === 'side') {
162
+ valid = value === 'above' || value === 'below';
163
+ } else if (kind === 'event' && key === 'descriptionSide') {
164
+ valid = value === 'above' || value === 'below';
165
+ } else if (kind === 'event' && key === 'column') {
166
+ valid = value.trim() !== '' && Number.isFinite(Number(value));
167
+ } else if (kind === 'event' && key === 'callout') {
168
+ valid = value === 'true' || value === 'false';
169
+ }
170
+ }
171
+ if (!valid || seen.has(key)) return false;
172
+ seen.add(key);
173
+ }
174
+ return true;
175
+ }
176
+
177
+ function firstAxisMarkerOffset(line: string, style: AsciiTimeline['style']): number {
178
+ if (style === 'unicode') return line.search(UNICODE_MARKER_RE);
179
+ for (let index = 0; index < line.length; index++) {
180
+ if (!ASCII_MARKERS.has(line[index])) continue;
181
+ const leftRail = railRun(line, index, -1);
182
+ const rightRail = railRun(line, index, 1);
183
+ const beforeIsWord = /[\p{L}\p{N}_]/u.test(line[index - 1] ?? '');
184
+ const afterIsWord = /[\p{L}\p{N}_]/u.test(line[index + 1] ?? '');
185
+ if ((leftRail >= 2 && !afterIsWord) || (rightRail >= 2 && !beforeIsWord)) return index;
186
+ }
187
+ return -1;
188
+ }
189
+
190
+ function railRun(line: string, index: number, direction: -1 | 1): number {
191
+ let count = 0;
192
+ for (let cursor = index + direction; RAIL_CHARS.has(line[cursor] ?? ''); cursor += direction) {
193
+ count++;
194
+ }
195
+ return count;
196
+ }
197
+
198
+ function semanticLexemeCounts(text: string): Map<string, number> {
199
+ const counts = new Map<string, number>();
200
+ const prose = text.normalize('NFC').replace(STRUCTURAL_CHARS_RE, ' ');
201
+ for (const match of prose.matchAll(SEMANTIC_LEXEME_RE)) {
202
+ const lexeme = match[0].toLocaleLowerCase();
203
+ counts.set(lexeme, (counts.get(lexeme) ?? 0) + 1);
204
+ }
205
+ return counts;
206
+ }
207
+
208
+ function countsEqual(
209
+ left: ReadonlyMap<string, number>,
210
+ right: ReadonlyMap<string, number>,
211
+ ): boolean {
212
+ if (left.size !== right.size) return false;
213
+ for (const [lexeme, count] of left) {
214
+ if (right.get(lexeme) !== count) return false;
215
+ }
216
+ return true;
217
+ }
218
+
219
+ function hasUnrepresentedStructuralOnlyLine(source: string, timeline: AsciiTimeline): boolean {
220
+ const trackRows = new Set(timeline.tracks.map((track) => track.row));
221
+ const lines = source.split('\n');
222
+ for (let row = 0; row < lines.length; row++) {
223
+ if (!lines[row].trim() || trackRows.has(row)) continue;
224
+ if (semanticLexemeCounts(lines[row]).size === 0) return true;
225
+ }
226
+ return false;
227
+ }
228
+
229
+ /**
230
+ * Semantic operations replace the whole fence with canonical rendered art.
231
+ * Fail closed when that would discard source the timeline model cannot
232
+ * represent. Warnings catch unresolved/unlabeled constructs; the semantic
233
+ * round-trip catches renderer normalization that changes modeled content;
234
+ * exact metadata validation rejects partially consumed attrs; and a linear
235
+ * semantic-residue comparison catches ignored prose/symbol rows without
236
+ * reparsing a successively shorter document for every source line.
237
+ */
238
+ export function isTimelineSourceSafeForSemanticEdit(
239
+ source: string,
240
+ timeline: AsciiTimeline,
241
+ ): boolean {
242
+ if (timeline.warnings.length > 0) return false;
243
+
244
+ const rendered = renderAsciiTimeline(timeline);
245
+ if (!rendered) return false;
246
+ const reparsed = parseAsciiTimeline(rendered);
247
+ const signature = semanticSignature(timeline);
248
+ if (reparsed.warnings.length > 0 || semanticSignature(reparsed) !== signature) return false;
249
+ // Wrapped-flow acceptance is deliberately all-or-nothing: its parser only
250
+ // returns a model when every nonblank row is represented. Once the model
251
+ // also survives the canonical render/parse signature above, the differing
252
+ // source vocabulary (lane headings and wrap connectors versus point
253
+ // metadata) is safe to normalize on the first visual edit.
254
+ if (isWrappedFlowTimelineSource(source)) return true;
255
+
256
+ const strippedSource = validateAndStripMetadata(source, timeline);
257
+ const strippedRendered = validateAndStripMetadata(rendered, reparsed);
258
+ if (!strippedSource || !strippedRendered) return false;
259
+ if (hasUnrepresentedStructuralOnlyLine(strippedSource, timeline)) return false;
260
+ return countsEqual(semanticLexemeCounts(strippedSource), semanticLexemeCounts(strippedRendered));
261
+ }
262
+
263
+ /**
264
+ * Verify the renderer/parser boundary before changing the document. Rows and
265
+ * source dimensions intentionally are not compared: canonical rendering
266
+ * compacts authored multi-line art while preserving its semantic content.
267
+ */
268
+ function verifyRenderedTimeline(next: AsciiTimeline, rendered: string): AsciiTimeline | null {
269
+ if (!rendered) return null;
270
+ const verification = parseAsciiTimeline(rendered);
271
+ if (renderAsciiTimeline(verification) !== rendered) return null;
272
+ if (verification.tracks.length !== next.tracks.length) return null;
273
+ if (countEvents(verification) !== countEvents(next)) return null;
274
+ if (verification.links.length !== next.links.length) return null;
275
+
276
+ const ids = new Set(
277
+ verification.tracks.flatMap((track) => track.events.map((event) => event.id)),
278
+ );
279
+ if (ids.size !== countEvents(verification)) return null;
280
+ if (verification.links.some((link) => !ids.has(link.source) || !ids.has(link.target))) {
281
+ return null;
282
+ }
283
+ return verification;
284
+ }
285
+
286
+ function applyOp(
287
+ editor: Editor,
288
+ blockId: string,
289
+ op: (timeline: AsciiTimeline) => OpResult | null,
290
+ verifyResult?: (timeline: AsciiTimeline) => boolean,
291
+ ): TimelineCommandResult {
292
+ // Resolve at dispatch time; captured ProseMirror positions become stale as
293
+ // soon as content above the fence changes.
294
+ const pos = findTimelineBlockPos(editor, blockId);
295
+ if (pos === null) return NOT_APPLIED;
296
+ const node = editor.state.doc.nodeAt(pos);
297
+ if (!node || node.type.name !== 'codeBlock') return NOT_APPLIED;
298
+ const timeline = parseTimelineForNode(node);
299
+ if (!timeline) return NOT_APPLIED;
300
+ if (!isTimelineSourceSafeForSemanticEdit(node.textContent, timeline)) return UNSAFE_SOURCE;
301
+
302
+ const result = op(timeline);
303
+ if (!result || result.timeline === timeline) return NOT_APPLIED;
304
+ const rendered = renderAsciiTimeline(result.timeline);
305
+ const verification = verifyRenderedTimeline(result.timeline, rendered);
306
+ if (
307
+ !verification ||
308
+ (result.eventId && !hasEvent(verification, result.eventId)) ||
309
+ (verifyResult && !verifyResult(verification))
310
+ ) {
311
+ return NOT_APPLIED;
312
+ }
313
+
314
+ // Promoting to the explicit language makes an edited timeline sticky over
315
+ // Markdown <-> Tiptap round trips. Text + attrs change in one undo step.
316
+ if (!replaceAsciiFenceText(editor, pos, rendered, 'timeline')) return NOT_APPLIED;
317
+ return {
318
+ applied: true,
319
+ ...(result.eventId ? { eventId: result.eventId } : {}),
320
+ };
321
+ }
322
+
323
+ /** Apply one semantic timeline command to a registered fence block. */
324
+ export function applyTimelineCommand(
325
+ editor: Editor,
326
+ blockId: string,
327
+ command: TimelineCommand,
328
+ ): TimelineCommandResult {
329
+ // Commands may outlive the render that created their controls. Enforce the
330
+ // editor's current authority at dispatch time, not only in widget props.
331
+ if (!editor.isEditable) return READ_ONLY;
332
+
333
+ switch (command.kind) {
334
+ case 'addEvent':
335
+ return applyOp(editor, blockId, (timeline) => {
336
+ const result = addTimelineEventOp(timeline, command.trackId, command.position, {
337
+ id: command.id,
338
+ label: command.label,
339
+ description: command.description,
340
+ side: command.side,
341
+ descriptionSide: command.descriptionSide,
342
+ callout: command.callout,
343
+ marker: command.marker,
344
+ });
345
+ return result;
346
+ });
347
+ case 'updateEvent':
348
+ return applyOp(
349
+ editor,
350
+ blockId,
351
+ (timeline) => ({
352
+ timeline: updateTimelineEventOp(timeline, command.eventId, command.patch),
353
+ }),
354
+ (timeline) => hasEvent(timeline, command.eventId),
355
+ );
356
+ case 'removeEvent':
357
+ return applyOp(
358
+ editor,
359
+ blockId,
360
+ (timeline) => ({ timeline: removeTimelineEventOp(timeline, command.eventId) }),
361
+ (timeline) => !hasEvent(timeline, command.eventId),
362
+ );
363
+ }
364
+ const exhaustive: never = command;
365
+ void exhaustive;
366
+ return NOT_APPLIED;
367
+ }
@@ -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
+ }