@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,130 @@
1
+ /**
2
+ * @vitest-environment jsdom
3
+ */
4
+ import { afterEach, describe, expect, it, vi } from 'vitest';
5
+ import { cleanup, fireEvent, render, screen, within } from '@testing-library/react';
6
+ import {
7
+ EditorProvider,
8
+ useEditorContext,
9
+ type BlockTagVisibility,
10
+ type ViewPreferences,
11
+ } from '../EditorContext';
12
+ import { ViewMenuPanel } from '../ViewMenuPanel';
13
+
14
+ afterEach(cleanup);
15
+
16
+ function BlockTagVisibilityProbe() {
17
+ const { blockTagVisibility } = useEditorContext();
18
+ return <output data-testid="block-tag-visibility">{blockTagVisibility}</output>;
19
+ }
20
+
21
+ function renderViewMenu({
22
+ blockTags,
23
+ blockTagVisibility,
24
+ viewPreferences,
25
+ onViewPreferencesChange,
26
+ }: {
27
+ blockTags?: boolean;
28
+ blockTagVisibility?: BlockTagVisibility;
29
+ viewPreferences?: ViewPreferences;
30
+ onViewPreferencesChange?: (preferences: ViewPreferences) => void;
31
+ } = {}) {
32
+ render(
33
+ <EditorProvider
34
+ initialMarkdown="# One\n\nFirst block.\n\n## Two\n\nSecond block.\n"
35
+ initialView="wysiwyg"
36
+ blockTags={blockTags}
37
+ blockTagVisibility={blockTagVisibility}
38
+ viewPreferences={viewPreferences}
39
+ onViewPreferencesChange={onViewPreferencesChange}
40
+ >
41
+ <ViewMenuPanel />
42
+ <BlockTagVisibilityProbe />
43
+ </EditorProvider>,
44
+ );
45
+
46
+ fireEvent.click(screen.getByRole('button', { name: 'View options' }));
47
+ return screen.getByRole('radiogroup', { name: 'Show block tags' });
48
+ }
49
+
50
+ describe('ViewMenuPanel block-tag visibility', () => {
51
+ it('offers the three visibility choices and defaults to the selected/hovered block', () => {
52
+ const group = renderViewMenu();
53
+
54
+ const items = within(group).getAllByRole('menuitemradio');
55
+ expect(items.map((item) => item.textContent?.trim())).toEqual([
56
+ 'No inline block tags',
57
+ 'Selected/hovered block',
58
+ 'Always show',
59
+ ]);
60
+ expect(
61
+ within(group)
62
+ .getByRole('menuitemradio', { name: 'Selected/hovered block' })
63
+ .getAttribute('aria-checked'),
64
+ ).toBe('true');
65
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('active');
66
+ });
67
+
68
+ it('switches to active and none and emits both new and legacy preferences', () => {
69
+ const onViewPreferencesChange = vi.fn<(preferences: ViewPreferences) => void>();
70
+ const group = renderViewMenu({ onViewPreferencesChange });
71
+
72
+ fireEvent.click(within(group).getByRole('menuitemradio', { name: 'Always show' }));
73
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('always');
74
+
75
+ fireEvent.click(within(group).getByRole('menuitemradio', { name: 'Selected/hovered block' }));
76
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('active');
77
+ expect(onViewPreferencesChange).toHaveBeenLastCalledWith(
78
+ expect.objectContaining({
79
+ blockTagVisibility: 'active',
80
+ blockTags: true,
81
+ }),
82
+ );
83
+
84
+ fireEvent.click(within(group).getByRole('menuitemradio', { name: 'No inline block tags' }));
85
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('none');
86
+ expect(onViewPreferencesChange).toHaveBeenLastCalledWith(
87
+ expect.objectContaining({
88
+ blockTagVisibility: 'none',
89
+ blockTags: false,
90
+ }),
91
+ );
92
+ });
93
+
94
+ it('maps the legacy blockTags={false} prop to no inline block tags', () => {
95
+ const group = renderViewMenu({ blockTags: false });
96
+
97
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('none');
98
+ expect(
99
+ within(group)
100
+ .getByRole('menuitemradio', { name: 'No inline block tags' })
101
+ .getAttribute('aria-checked'),
102
+ ).toBe('true');
103
+ });
104
+
105
+ it('maps the legacy blockTags={true} prop to always show', () => {
106
+ const group = renderViewMenu({ blockTags: true });
107
+
108
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('always');
109
+ expect(
110
+ within(group)
111
+ .getByRole('menuitemradio', { name: 'Always show' })
112
+ .getAttribute('aria-checked'),
113
+ ).toBe('true');
114
+ });
115
+
116
+ it('restores the active mode from bundled view preferences', () => {
117
+ const group = renderViewMenu({
118
+ blockTags: false,
119
+ blockTagVisibility: 'always',
120
+ viewPreferences: { blockTags: false, blockTagVisibility: 'active' },
121
+ });
122
+
123
+ expect(screen.getByTestId('block-tag-visibility').textContent).toBe('active');
124
+ expect(
125
+ within(group)
126
+ .getByRole('menuitemradio', { name: 'Selected/hovered block' })
127
+ .getAttribute('aria-checked'),
128
+ ).toBe('true');
129
+ });
130
+ });
@@ -0,0 +1,69 @@
1
+ import { Schema } from '@tiptap/pm/model';
2
+ import { EditorState, TextSelection } from '@tiptap/pm/state';
3
+ import { describe, expect, it, vi } from 'vitest';
4
+ import type { MediaProvider } from '@bendyline/squisq/schemas';
5
+ import { uploadAndInsertImages } from '../wysiwygImageUpload';
6
+
7
+ const schema = new Schema({
8
+ nodes: {
9
+ doc: { content: 'paragraph+' },
10
+ paragraph: { content: 'inline*', group: 'block' },
11
+ text: { group: 'inline' },
12
+ image: {
13
+ inline: true,
14
+ group: 'inline',
15
+ atom: true,
16
+ attrs: {
17
+ src: {},
18
+ alt: { default: null },
19
+ title: { default: null },
20
+ },
21
+ },
22
+ },
23
+ });
24
+
25
+ describe('asynchronous WYSIWYG image upload', () => {
26
+ it('replaces a mapped placeholder instead of the user’s later selection', async () => {
27
+ const doc = schema.node('doc', null, [
28
+ schema.node('paragraph', null, schema.text('before after')),
29
+ ]);
30
+ let state = EditorState.create({
31
+ schema,
32
+ doc,
33
+ selection: TextSelection.create(doc, 8),
34
+ });
35
+ const view = {
36
+ get state() {
37
+ return state;
38
+ },
39
+ dispatch(tr: typeof state.tr) {
40
+ state = state.apply(tr);
41
+ },
42
+ };
43
+ let finishUpload!: (path: string) => void;
44
+ const upload = new Promise<string>((resolve) => {
45
+ finishUpload = resolve;
46
+ });
47
+ const provider = {
48
+ addMedia: vi.fn(() => upload),
49
+ } as unknown as MediaProvider;
50
+ const file = {
51
+ name: 'photo.png',
52
+ type: 'image/png',
53
+ arrayBuffer: async () => new Uint8Array([1]).buffer,
54
+ } as File;
55
+
56
+ const pending = uploadAndInsertImages(view, [file], provider);
57
+ // Keep editing elsewhere while storage is pending.
58
+ view.dispatch(state.tr.insertText(' tail', state.doc.content.size - 1));
59
+ finishUpload('assets/photo.png');
60
+ await pending;
61
+
62
+ const paragraph = state.doc.firstChild!;
63
+ expect(paragraph.childCount).toBe(3);
64
+ expect(paragraph.child(0).text).toBe('before ');
65
+ expect(paragraph.child(1).type.name).toBe('image');
66
+ expect(paragraph.child(1).attrs.src).toBe('assets/photo.png');
67
+ expect(paragraph.child(2).text).toBe('after tail');
68
+ });
69
+ });
@@ -0,0 +1,56 @@
1
+ import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react';
2
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest';
3
+ import { EditorProvider } from '../EditorContext';
4
+ import { WysiwygEditor } from '../WysiwygEditor';
5
+
6
+ const originalElementsFromPoint = document.elementsFromPoint;
7
+ const originalElementFromPoint = document.elementFromPoint;
8
+
9
+ beforeEach(() => {
10
+ Object.defineProperty(document, 'elementsFromPoint', {
11
+ configurable: true,
12
+ value: () => [],
13
+ });
14
+ Object.defineProperty(document, 'elementFromPoint', {
15
+ configurable: true,
16
+ value: () => null,
17
+ });
18
+ });
19
+
20
+ afterEach(() => {
21
+ cleanup();
22
+ Object.defineProperty(document, 'elementsFromPoint', {
23
+ configurable: true,
24
+ value: originalElementsFromPoint,
25
+ });
26
+ Object.defineProperty(document, 'elementFromPoint', {
27
+ configurable: true,
28
+ value: originalElementFromPoint,
29
+ });
30
+ });
31
+
32
+ describe('WysiwygEditor inline block-type picker focus', () => {
33
+ it('restores document focus after choosing a block type', async () => {
34
+ render(
35
+ <EditorProvider
36
+ initialMarkdown={'# Heading {[title]}\n\nBody text.\n'}
37
+ initialView="wysiwyg"
38
+ blockTagVisibility="always"
39
+ >
40
+ <WysiwygEditor />
41
+ </EditorProvider>,
42
+ );
43
+
44
+ const editor = await screen.findByTestId('wysiwyg-editor');
45
+ const badge = await screen.findByTitle('Change block type');
46
+ fireEvent.mouseDown(badge);
47
+
48
+ const search = await screen.findByRole('searchbox', { name: 'Search block types' });
49
+ await waitFor(() => expect(document.activeElement).toBe(search));
50
+
51
+ fireEvent.click(screen.getByRole('option', { name: /^Quote\b/ }));
52
+
53
+ await waitFor(() => expect(screen.queryByRole('dialog')).toBeNull());
54
+ await waitFor(() => expect(document.activeElement).toBe(editor));
55
+ });
56
+ });
@@ -0,0 +1,343 @@
1
+ /**
2
+ * AsciiDiagramExtension — Tiptap/ProseMirror plugin that turns code blocks
3
+ * containing ASCII box-and-line diagrams into interactive diagram canvases.
4
+ *
5
+ * The FENCE TEXT REMAINS THE SOURCE OF TRUTH: the plugin never converts
6
+ * the document. For each qualifying codeBlock it:
7
+ * 1. hides the `<pre>` via a node decoration (or tags it visible-monospace
8
+ * when the user toggles "source" mode), and
9
+ * 2. mounts an `AsciiDiagramWidget` after it via a widget decoration.
10
+ *
11
+ * Identity: codeBlocks have no persisted id and their content changes on
12
+ * every canvas edit (self-inflicted fence rewrite), so neither a content
13
+ * hash nor a raw position can key the widget. Instead the plugin keeps a
14
+ * POSITION REGISTRY in its state: each qualifying block gets a synthetic
15
+ * session id (`ascii-N`); on every doc change old positions are remapped
16
+ * through `tr.mapping` and matched against the new doc walk. Same id →
17
+ * same widget decoration key → ProseMirror keeps the DOM + React root
18
+ * alive (pan/zoom survives), exactly like the heading-key trick the
19
+ * legacy DiagramExtension used.
20
+ *
21
+ * Hysteresis: a NEW block must pass full detection (`detectAsciiDiagram`,
22
+ * ≥2 boxes + thresholds); an already-registered block stays interactive
23
+ * while its fence still parses to ≥1 box, so deleting down to one node
24
+ * doesn't kick the user back to a raw code block mid-edit.
25
+ */
26
+
27
+ import { Extension } from '@tiptap/core';
28
+ import { Plugin, PluginKey } from '@tiptap/pm/state';
29
+ import type { Transaction } from '@tiptap/pm/state';
30
+ import { Decoration, DecorationSet } from '@tiptap/pm/view';
31
+ import type { Node as PMNode } from '@tiptap/pm/model';
32
+ import type { Editor } from '@tiptap/react';
33
+ import { createRoot, type Root } from 'react-dom/client';
34
+ import { createElement } from 'react';
35
+ import {
36
+ detectAsciiDiagram,
37
+ isEligibleAsciiFenceLang,
38
+ isExplicitDiagramLang,
39
+ parseAsciiDiagram,
40
+ type AsciiDiagram,
41
+ } from '@bendyline/squisq/doc';
42
+ import { AsciiDiagramWidget } from './AsciiDiagramWidget';
43
+ import type { SceneTextChannel } from '../scene/text/sceneTextChannel';
44
+
45
+ export interface AsciiDiagramBlockEntry {
46
+ /** Synthetic session id (`ascii-N`), stable across edits for one block. */
47
+ id: string;
48
+ /** Document position of the codeBlock node at the current state. */
49
+ pos: number;
50
+ }
51
+
52
+ export interface AsciiDiagramPluginState {
53
+ entries: AsciiDiagramBlockEntry[];
54
+ decorations: DecorationSet;
55
+ sourceVisible: ReadonlySet<string>;
56
+ /** Monotonic id allocator. */
57
+ seq: number;
58
+ }
59
+
60
+ export const ASCII_DIAGRAM_KEY = new PluginKey<AsciiDiagramPluginState>('squisq-ascii-diagram');
61
+
62
+ // ---------------------------------------------------------------------------
63
+ // Gate caches — keyed on the PMNode instance. ProseMirror's structural
64
+ // sharing reuses node objects for unchanged blocks, so only an actually
65
+ // edited fence re-runs detection/parsing.
66
+ // ---------------------------------------------------------------------------
67
+
68
+ const detectCache = new WeakMap<PMNode, AsciiDiagram | null>();
69
+ const parseCache = new WeakMap<PMNode, AsciiDiagram | null>();
70
+
71
+ function fenceLangOf(node: PMNode): string | null {
72
+ const lang = (node.attrs as { language?: string | null }).language;
73
+ return typeof lang === 'string' ? lang : null;
74
+ }
75
+
76
+ /** Full-detection gate for NEW blocks: lang allowlist + content thresholds. */
77
+ export function getAsciiDiagramForNode(node: PMNode): AsciiDiagram | null {
78
+ if (node.type.name !== 'codeBlock') return null;
79
+ const cached = detectCache.get(node);
80
+ if (cached !== undefined) return cached;
81
+ let result: AsciiDiagram | null = null;
82
+ const lang = fenceLangOf(node);
83
+ if (isEligibleAsciiFenceLang(lang)) {
84
+ const detection = detectAsciiDiagram(node.textContent, {
85
+ explicit: isExplicitDiagramLang(lang),
86
+ });
87
+ if (detection.isDiagram && detection.diagram) {
88
+ result = detection.diagram;
89
+ parseCache.set(node, result);
90
+ }
91
+ }
92
+ detectCache.set(node, result);
93
+ return result;
94
+ }
95
+
96
+ /** Box-drawing corners/junctions/verticals leaking into a label = a garbled parse. */
97
+ const GARBLED_LABEL = /[│┃║┌┐└┘├┤┬┴┼╭╮╰╯┏┓┗┛╔╗╚╝┣┫┳┻╋╠╣╦╩╬]/;
98
+
99
+ /**
100
+ * Relaxed gate for ALREADY-REGISTERED blocks: any parse with ≥1 box, so
101
+ * editing a diagram down doesn't kick the user out mid-edit. But a GARBLED
102
+ * parse (box-drawing chars leaked into labels — the desync signature of
103
+ * broken art) is never a valid diagram; rejecting it here keeps a broken
104
+ * fence from being held as a diagram by hysteresis (e.g. after undoing a
105
+ * repair, where the fence reverts to broken art the RepairableExtension owns).
106
+ */
107
+ export function parseAsciiDiagramForNode(node: PMNode): AsciiDiagram | null {
108
+ if (node.type.name !== 'codeBlock') return null;
109
+ const cached = parseCache.get(node);
110
+ if (cached !== undefined) return cached;
111
+ let result: AsciiDiagram | null = null;
112
+ if (isEligibleAsciiFenceLang(fenceLangOf(node))) {
113
+ const parsed = parseAsciiDiagram(node.textContent);
114
+ if (parsed.nodes.length > 0 && !parsed.nodes.some((n) => GARBLED_LABEL.test(n.label))) {
115
+ result = parsed;
116
+ }
117
+ }
118
+ parseCache.set(node, result);
119
+ return result;
120
+ }
121
+
122
+ /** Resolve a registered block's current doc position (null when gone). */
123
+ export function findAsciiDiagramBlockPos(editor: Editor, blockId: string): number | null {
124
+ const state = ASCII_DIAGRAM_KEY.getState(editor.state);
125
+ return state?.entries.find((e) => e.id === blockId)?.pos ?? null;
126
+ }
127
+
128
+ export function isAsciiSourceVisible(editor: Editor, blockId: string): boolean {
129
+ const state = ASCII_DIAGRAM_KEY.getState(editor.state);
130
+ return state?.sourceVisible.has(blockId) ?? false;
131
+ }
132
+
133
+ /** Toggle the raw-fence view for one diagram block (meta-only transaction). */
134
+ export function toggleAsciiSource(editor: Editor, blockId: string): void {
135
+ const tr = editor.state.tr.setMeta(ASCII_DIAGRAM_KEY, { toggleSource: blockId });
136
+ editor.view.dispatch(tr);
137
+ }
138
+
139
+ // ---------------------------------------------------------------------------
140
+ // Plugin state
141
+ // ---------------------------------------------------------------------------
142
+
143
+ interface WidgetRootRef {
144
+ root: Root;
145
+ }
146
+
147
+ function buildDecorations(
148
+ doc: PMNode,
149
+ entries: AsciiDiagramBlockEntry[],
150
+ sourceVisible: ReadonlySet<string>,
151
+ editor: Editor,
152
+ textChannel?: SceneTextChannel,
153
+ ): DecorationSet {
154
+ const decos: Decoration[] = [];
155
+ for (const entry of entries) {
156
+ const node = doc.nodeAt(entry.pos);
157
+ if (!node || node.type.name !== 'codeBlock') continue;
158
+ const cls = sourceVisible.has(entry.id)
159
+ ? 'squisq-ascii-fence-source'
160
+ : 'squisq-ascii-fence-hidden';
161
+ decos.push(Decoration.node(entry.pos, entry.pos + node.nodeSize, { class: cls }));
162
+ const blockId = entry.id;
163
+ const fallbackPos = entry.pos;
164
+ decos.push(
165
+ Decoration.widget(
166
+ entry.pos + node.nodeSize,
167
+ (view) => {
168
+ const container = document.createElement('div');
169
+ container.className = 'squisq-ascii-diagram-widget-host';
170
+ container.contentEditable = 'false';
171
+ // Keep ProseMirror from treating clicks/keys inside the widget
172
+ // as document interactions.
173
+ container.addEventListener('mousedown', (e) => e.stopPropagation());
174
+ container.addEventListener('keydown', (e) => e.stopPropagation());
175
+ const root = createRoot(container);
176
+ root.render(
177
+ createElement(AsciiDiagramWidget, {
178
+ editor,
179
+ blockId,
180
+ fallbackPos,
181
+ host: view.dom.parentElement ?? view.dom,
182
+ textChannel,
183
+ }),
184
+ );
185
+ (container as HTMLElement & { __squisqAsciiRoot?: WidgetRootRef }).__squisqAsciiRoot = {
186
+ root,
187
+ };
188
+ return container;
189
+ },
190
+ {
191
+ destroy: (dom) => {
192
+ const ref = (dom as HTMLElement & { __squisqAsciiRoot?: WidgetRootRef })
193
+ .__squisqAsciiRoot;
194
+ // Defer so React isn't unmounted mid-render.
195
+ if (ref) setTimeout(() => ref.root.unmount(), 0);
196
+ },
197
+ side: 1,
198
+ ignoreSelection: true,
199
+ key: `squisq-ascii-${entry.id}`,
200
+ },
201
+ ),
202
+ );
203
+ }
204
+ return DecorationSet.create(doc, decos);
205
+ }
206
+
207
+ function applyState(
208
+ tr: Transaction,
209
+ prev: AsciiDiagramPluginState,
210
+ editor: Editor,
211
+ doc: PMNode,
212
+ textChannel?: SceneTextChannel,
213
+ ): AsciiDiagramPluginState {
214
+ const meta = tr.getMeta(ASCII_DIAGRAM_KEY) as { toggleSource?: string } | undefined;
215
+ let sourceVisible = prev.sourceVisible;
216
+ if (meta?.toggleSource) {
217
+ const next = new Set(sourceVisible);
218
+ if (next.has(meta.toggleSource)) next.delete(meta.toggleSource);
219
+ else next.add(meta.toggleSource);
220
+ sourceVisible = next;
221
+ }
222
+
223
+ if (!tr.docChanged) {
224
+ if (!meta?.toggleSource) return prev;
225
+ return {
226
+ ...prev,
227
+ sourceVisible,
228
+ decorations: buildDecorations(doc, prev.entries, sourceVisible, editor, textChannel),
229
+ };
230
+ }
231
+
232
+ // Doc changed: remap known positions (bias 1 so an insertion exactly at
233
+ // the block's start shifts the tracked position forward WITH the node),
234
+ // then walk the new doc and reconcile.
235
+ const mapped = new Map<number, string>();
236
+ const claimed = new Set<string>();
237
+ // Pass 1: survivors whose start position wasn't touched.
238
+ for (const entry of prev.entries) {
239
+ const result = tr.mapping.mapResult(entry.pos, 1);
240
+ if (!result.deleted) {
241
+ mapped.set(result.pos, entry.id);
242
+ claimed.add(entry.id);
243
+ }
244
+ }
245
+ // Pass 2: boundary-churn survivors. An attrs-only `setNodeMarkup` (the
246
+ // language-promotion step) rewrites the codeBlock's opening token, so
247
+ // `mapResult` reports the start as `deleted` even though the block is still
248
+ // there. Adopt the old id when a codeBlock still sits at the mapped position
249
+ // and that slot isn't already claimed — this keeps the widget's React root
250
+ // (pan/zoom) alive across the one-time promotion, instead of remounting.
251
+ for (const entry of prev.entries) {
252
+ if (claimed.has(entry.id)) continue;
253
+ const result = tr.mapping.mapResult(entry.pos, 1);
254
+ if (mapped.has(result.pos)) continue;
255
+ if (doc.nodeAt(result.pos)?.type.name === 'codeBlock') {
256
+ mapped.set(result.pos, entry.id);
257
+ claimed.add(entry.id);
258
+ }
259
+ }
260
+
261
+ let seq = prev.seq;
262
+ const entries: AsciiDiagramBlockEntry[] = [];
263
+ doc.descendants((node, pos) => {
264
+ if (node.type.name !== 'codeBlock') return;
265
+ const knownId = mapped.get(pos);
266
+ // Hysteresis: known blocks stay while they parse at all; new blocks
267
+ // must pass full detection.
268
+ const diagram = knownId ? parseAsciiDiagramForNode(node) : getAsciiDiagramForNode(node);
269
+ if (!diagram) return false;
270
+ entries.push({ id: knownId ?? `ascii-${++seq}`, pos });
271
+ return false;
272
+ });
273
+
274
+ const liveIds = new Set(entries.map((e) => e.id));
275
+ const prunedSourceVisible = new Set([...sourceVisible].filter((id) => liveIds.has(id)));
276
+
277
+ return {
278
+ entries,
279
+ seq,
280
+ sourceVisible: prunedSourceVisible,
281
+ decorations: buildDecorations(doc, entries, prunedSourceVisible, editor, textChannel),
282
+ };
283
+ }
284
+
285
+ export interface AsciiDiagramExtensionOptions {
286
+ /** When false, the extension is inert (no widgets, no decorations). */
287
+ enabled?: boolean;
288
+ textChannel?: SceneTextChannel;
289
+ }
290
+
291
+ export const AsciiDiagramExtension = Extension.create<AsciiDiagramExtensionOptions>({
292
+ name: 'squisqAsciiDiagram',
293
+
294
+ addOptions() {
295
+ return {
296
+ enabled: true,
297
+ };
298
+ },
299
+
300
+ addProseMirrorPlugins() {
301
+ const editor = this.editor as Editor;
302
+ if (this.options.enabled === false) return [];
303
+
304
+ return [
305
+ new Plugin<AsciiDiagramPluginState>({
306
+ key: ASCII_DIAGRAM_KEY,
307
+ state: {
308
+ init: (_config, state) => {
309
+ let seq = 0;
310
+ const entries: AsciiDiagramBlockEntry[] = [];
311
+ state.doc.descendants((node, pos) => {
312
+ if (node.type.name !== 'codeBlock') return;
313
+ if (!getAsciiDiagramForNode(node)) return false;
314
+ entries.push({ id: `ascii-${++seq}`, pos });
315
+ return false;
316
+ });
317
+ return {
318
+ entries,
319
+ seq,
320
+ sourceVisible: new Set<string>(),
321
+ decorations: buildDecorations(
322
+ state.doc,
323
+ entries,
324
+ new Set(),
325
+ editor,
326
+ this.options.textChannel,
327
+ ),
328
+ };
329
+ },
330
+ apply: (tr, prev, _oldState, newState) =>
331
+ applyState(tr, prev, editor, newState.doc, this.options.textChannel),
332
+ },
333
+ props: {
334
+ decorations(state) {
335
+ return this.getState(state)?.decorations ?? DecorationSet.empty;
336
+ },
337
+ },
338
+ }),
339
+ ];
340
+ },
341
+ });
342
+
343
+ export default AsciiDiagramExtension;