@bendyline/squisq-editor-react 2.0.1 → 2.2.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 (357) hide show
  1. package/LICENSE +21 -0
  2. package/NOTICE.md +40 -0
  3. package/README.md +10 -2
  4. package/dist/index.d.ts +683 -60
  5. package/dist/index.js +9648 -3750
  6. package/dist/monaco.js +0 -1
  7. package/dist/styles/index.css +1160 -241
  8. package/package.json +10 -6
  9. package/dist/index.js.map +0 -1
  10. package/dist/monaco.js.map +0 -1
  11. package/src/BlockCardView.tsx +0 -121
  12. package/src/BlockPreviewPanel.tsx +0 -69
  13. package/src/BlockPropertiesPopover.tsx +0 -222
  14. package/src/DocumentSettingsDialog.tsx +0 -272
  15. package/src/DropZoneOverlay.tsx +0 -137
  16. package/src/EditorContext.tsx +0 -1247
  17. package/src/EditorShell.tsx +0 -1334
  18. package/src/EmojiPicker.tsx +0 -332
  19. package/src/FolderView.tsx +0 -131
  20. package/src/Icon.tsx +0 -26
  21. package/src/ImageEditor.tsx +0 -395
  22. package/src/ImageNodeView.tsx +0 -284
  23. package/src/ImageViewer.tsx +0 -221
  24. package/src/InlineIcon.ts +0 -84
  25. package/src/InlinePreviewGutter.tsx +0 -590
  26. package/src/LinkDialog.tsx +0 -276
  27. package/src/MediaBin.tsx +0 -500
  28. package/src/MentionExtension.tsx +0 -261
  29. package/src/OutlinePanel.tsx +0 -547
  30. package/src/PlainHtmlPreview.tsx +0 -277
  31. package/src/PreviewControls.tsx +0 -1250
  32. package/src/PreviewPanel.tsx +0 -422
  33. package/src/RawEditor.tsx +0 -731
  34. package/src/RecorderEntry.tsx +0 -159
  35. package/src/StatusBar.tsx +0 -51
  36. package/src/TemplateAnnotation.ts +0 -167
  37. package/src/TemplateContentPreview.tsx +0 -56
  38. package/src/TemplatePicker.tsx +0 -1314
  39. package/src/ThemeCustomizerPanel.tsx +0 -304
  40. package/src/ThemePicker.tsx +0 -433
  41. package/src/TimelineBlockPreview.tsx +0 -37
  42. package/src/TimelineTrack.tsx +0 -671
  43. package/src/Toolbar.tsx +0 -2587
  44. package/src/Tooltip.tsx +0 -142
  45. package/src/TransitionPicker.tsx +0 -390
  46. package/src/VersionHistoryPanel.tsx +0 -359
  47. package/src/ViewMenuPanel.tsx +0 -189
  48. package/src/ViewSwitcher.tsx +0 -56
  49. package/src/WysiwygEditor.tsx +0 -792
  50. package/src/__tests__/blockProperties.test.ts +0 -92
  51. package/src/__tests__/blockPropertiesPopoverTheme.test.tsx +0 -33
  52. package/src/__tests__/blockRange.test.ts +0 -105
  53. package/src/__tests__/blockTagActivity.test.ts +0 -183
  54. package/src/__tests__/buildDocumentPreviewMarkdown.test.ts +0 -75
  55. package/src/__tests__/buildPreviewDocContent.test.ts +0 -48
  56. package/src/__tests__/buildPreviewDocTransition.test.ts +0 -92
  57. package/src/__tests__/canvasSurfaceTextEditing.test.tsx +0 -60
  58. package/src/__tests__/codeContextSectionView.test.tsx +0 -97
  59. package/src/__tests__/codeContextZoneManager.test.ts +0 -127
  60. package/src/__tests__/createShapeLayer.test.ts +0 -46
  61. package/src/__tests__/customLayoutManagerTheme.test.tsx +0 -34
  62. package/src/__tests__/detectMarkdown.test.ts +0 -73
  63. package/src/__tests__/diffContextSections.test.ts +0 -39
  64. package/src/__tests__/documentSettingsDialog.test.tsx +0 -197
  65. package/src/__tests__/drawingShapeRoundTrip.test.ts +0 -49
  66. package/src/__tests__/editorScrollHandoff.test.tsx +0 -102
  67. package/src/__tests__/editorScrollSync.test.ts +0 -65
  68. package/src/__tests__/editorShellCodeContext.test.tsx +0 -86
  69. package/src/__tests__/editorShellProps.test.tsx +0 -485
  70. package/src/__tests__/embeddedMedia.test.ts +0 -48
  71. package/src/__tests__/emojiPicker.test.tsx +0 -93
  72. package/src/__tests__/fileKind.test.ts +0 -112
  73. package/src/__tests__/headingTransition.test.ts +0 -176
  74. package/src/__tests__/imageEditAffordance.test.tsx +0 -272
  75. package/src/__tests__/imageEditModalContract.test.tsx +0 -119
  76. package/src/__tests__/imageEditorShell.test.tsx +0 -94
  77. package/src/__tests__/imageEditorState.test.ts +0 -171
  78. package/src/__tests__/inlinePreviewGutter.test.tsx +0 -62
  79. package/src/__tests__/inlinePreviewGutterAllBlocks.test.tsx +0 -103
  80. package/src/__tests__/jsonEditor.test.tsx +0 -223
  81. package/src/__tests__/layersPanel.test.tsx +0 -167
  82. package/src/__tests__/layoutChildRoundTrip.test.ts +0 -71
  83. package/src/__tests__/linkDialogDocPicker.test.tsx +0 -137
  84. package/src/__tests__/majorApiTypes.test.ts +0 -26
  85. package/src/__tests__/mediaAttachmentFlow.test.ts +0 -110
  86. package/src/__tests__/mediaBinDrop.test.tsx +0 -90
  87. package/src/__tests__/mediaReferences.test.ts +0 -82
  88. package/src/__tests__/narrationSave.test.ts +0 -148
  89. package/src/__tests__/outlinePanel.test.tsx +0 -169
  90. package/src/__tests__/outlineSource.test.ts +0 -217
  91. package/src/__tests__/plainHtmlPreview.test.tsx +0 -125
  92. package/src/__tests__/presentationMode.test.tsx +0 -290
  93. package/src/__tests__/previewControls.test.tsx +0 -540
  94. package/src/__tests__/previewPanelAudioFailure.test.tsx +0 -46
  95. package/src/__tests__/previewPanelPresentation.test.tsx +0 -126
  96. package/src/__tests__/previewPanelTransforms.test.tsx +0 -117
  97. package/src/__tests__/propertiesPanel.test.tsx +0 -69
  98. package/src/__tests__/rawEditorModelIsolation.test.ts +0 -19
  99. package/src/__tests__/recorderFormats.test.ts +0 -146
  100. package/src/__tests__/recorderMediaInsert.test.ts +0 -86
  101. package/src/__tests__/recorderTheme.test.tsx +0 -42
  102. package/src/__tests__/recorderTimingJson.test.ts +0 -41
  103. package/src/__tests__/resolveBlockVisual.test.ts +0 -43
  104. package/src/__tests__/selectionConversions.test.ts +0 -80
  105. package/src/__tests__/statusBar.test.tsx +0 -27
  106. package/src/__tests__/teleprompter.test.tsx +0 -190
  107. package/src/__tests__/templateAnnotationRoundTrip.test.ts +0 -99
  108. package/src/__tests__/templateContentPreview.test.ts +0 -101
  109. package/src/__tests__/templatePickerMetadata.test.ts +0 -32
  110. package/src/__tests__/templatePickerPortal.test.tsx +0 -62
  111. package/src/__tests__/timelineSource.test.ts +0 -134
  112. package/src/__tests__/tiptapBridge.test.ts +0 -566
  113. package/src/__tests__/tiptapBridgeConformance.test.ts +0 -47
  114. package/src/__tests__/tiptapCodeBlockRoundTrip.test.ts +0 -109
  115. package/src/__tests__/tiptapImageRoundTrip.test.ts +0 -73
  116. package/src/__tests__/toolbarSelectionConversion.test.tsx +0 -164
  117. package/src/__tests__/tooltip.test.tsx +0 -72
  118. package/src/__tests__/transformStyleId.test.ts +0 -13
  119. package/src/__tests__/transitionCatalog.test.ts +0 -64
  120. package/src/__tests__/useBlockNavigator.test.tsx +0 -67
  121. package/src/__tests__/useImageEditor.test.tsx +0 -226
  122. package/src/__tests__/useJsonEditorTokens.test.ts +0 -59
  123. package/src/__tests__/useMediaRecorder.test.ts +0 -302
  124. package/src/__tests__/useTimelineClock.test.ts +0 -21
  125. package/src/__tests__/versionHistory.test.tsx +0 -197
  126. package/src/__tests__/viewMenuPanel.test.tsx +0 -130
  127. package/src/__tests__/wysiwygImageUpload.test.ts +0 -69
  128. package/src/__tests__/wysiwygTemplateBadgeFocus.test.tsx +0 -56
  129. package/src/asciiDiagram/AsciiDiagramExtension.ts +0 -343
  130. package/src/asciiDiagram/AsciiDiagramWidget.tsx +0 -254
  131. package/src/asciiDiagram/RepairableDiagramExtension.ts +0 -200
  132. package/src/asciiDiagram/__tests__/AsciiDiagramExtension.test.ts +0 -145
  133. package/src/asciiDiagram/__tests__/RepairableDiagramExtension.test.ts +0 -159
  134. package/src/asciiDiagram/__tests__/asciiDiagramCommands.test.ts +0 -284
  135. package/src/asciiDiagram/__tests__/asciiDiagramOps.test.ts +0 -114
  136. package/src/asciiDiagram/__tests__/asciiPaste.test.ts +0 -43
  137. package/src/asciiDiagram/asciiDiagramCommands.ts +0 -174
  138. package/src/asciiDiagram/asciiDiagramData.ts +0 -149
  139. package/src/asciiDiagram/asciiDiagramOps.ts +0 -238
  140. package/src/asciiDiagram/asciiPaste.ts +0 -19
  141. package/src/blockProperties.ts +0 -88
  142. package/src/blockRange.ts +0 -132
  143. package/src/blockSlice.ts +0 -75
  144. package/src/blockTagActivity.ts +0 -233
  145. package/src/buildDocumentPreviewMarkdown.ts +0 -168
  146. package/src/buildPreviewDoc.ts +0 -405
  147. package/src/codeContext/CodeContextSectionView.tsx +0 -124
  148. package/src/codeContext/CodeContextZoneManager.ts +0 -149
  149. package/src/codeContext/CodeContextZones.tsx +0 -121
  150. package/src/codeContext/diffContextSections.ts +0 -38
  151. package/src/codeContext/types.ts +0 -75
  152. package/src/customTemplates/AddBin.tsx +0 -126
  153. package/src/customTemplates/CustomLayoutManager.tsx +0 -234
  154. package/src/customTemplates/CustomTemplateContext.tsx +0 -188
  155. package/src/customTemplates/LayerToolbar.tsx +0 -580
  156. package/src/customTemplates/ShapeGlyph.tsx +0 -47
  157. package/src/customTemplates/TemplateDesigner.tsx +0 -433
  158. package/src/customTemplates/__tests__/library.test.ts +0 -96
  159. package/src/customTemplates/__tests__/normalizePositions.test.ts +0 -109
  160. package/src/customTemplates/__tests__/shapeDefs.test.ts +0 -49
  161. package/src/customTemplates/__tests__/useMemoryLayerAdapter.test.ts +0 -108
  162. package/src/customTemplates/designer.css +0 -732
  163. package/src/customTemplates/index.ts +0 -31
  164. package/src/customTemplates/library.ts +0 -110
  165. package/src/customTemplates/normalizePositions.ts +0 -75
  166. package/src/customTemplates/shapeDefs.ts +0 -131
  167. package/src/customTemplates/thumbnail.tsx +0 -63
  168. package/src/customTemplates/tokenDefs.ts +0 -60
  169. package/src/customTemplates/useDocCustomTemplates.ts +0 -52
  170. package/src/customTemplates/useMemoryLayerAdapter.ts +0 -129
  171. package/src/customThemes/CustomThemeContext.tsx +0 -185
  172. package/src/customThemes/CustomThemeDialog.tsx +0 -316
  173. package/src/customThemes/ImportThemeSection.tsx +0 -178
  174. package/src/customThemes/__tests__/CustomThemeContext.test.tsx +0 -64
  175. package/src/customThemes/__tests__/CustomThemeDialog.test.tsx +0 -47
  176. package/src/customThemes/__tests__/customThemeLibrary.test.ts +0 -60
  177. package/src/customThemes/__tests__/importThemeSection.test.tsx +0 -192
  178. package/src/customThemes/customThemeLibrary.ts +0 -100
  179. package/src/customThemes/index.ts +0 -37
  180. package/src/customThemes/themeControls.tsx +0 -229
  181. package/src/customThemes/themeDraft.ts +0 -288
  182. package/src/customThemes/useDocCustomThemes.ts +0 -49
  183. package/src/detectMarkdown.ts +0 -62
  184. package/src/diagram/DiagramCanvas.tsx +0 -259
  185. package/src/diagram/DiagramMaximizedOverlay.tsx +0 -46
  186. package/src/diagram/diagramCommands.ts +0 -604
  187. package/src/diagram/diagramConstants.ts +0 -17
  188. package/src/diagram/types.ts +0 -35
  189. package/src/editorScrollSync.ts +0 -73
  190. package/src/embeddedMedia.ts +0 -78
  191. package/src/emojiData.ts +0 -1317
  192. package/src/fileKind.ts +0 -158
  193. package/src/frontmatter.ts +0 -29
  194. package/src/frontmatterSettings.ts +0 -23
  195. package/src/headingTransition.ts +0 -291
  196. package/src/hooks/useFileDrop.ts +0 -266
  197. package/src/imageEditor/CanvasSurface.tsx +0 -703
  198. package/src/imageEditor/ImageVersionHistoryDropdown.tsx +0 -396
  199. package/src/imageEditor/LayersPanel.tsx +0 -218
  200. package/src/imageEditor/PropertiesPanel.tsx +0 -474
  201. package/src/imageEditor/Toolbar.tsx +0 -459
  202. package/src/imageEditor/createShapeLayer.ts +0 -280
  203. package/src/imageEditor/icons.tsx +0 -68
  204. package/src/imageEditor/image-editor.css +0 -574
  205. package/src/imageEditor/layers/EditorImageLayer.tsx +0 -45
  206. package/src/imageEditor/layers/EditorShapeLayer.tsx +0 -62
  207. package/src/imageEditor/layers/EditorTextLayer.tsx +0 -45
  208. package/src/imageEditor/layers/SelectionHandles.tsx +0 -86
  209. package/src/imageEditor/state.ts +0 -173
  210. package/src/imageEditor/useImageEditor.ts +0 -385
  211. package/src/imageEditor/useImageEditorTokens.ts +0 -70
  212. package/src/index.ts +0 -470
  213. package/src/jsonEditor/EmbeddedRichTextField.tsx +0 -81
  214. package/src/jsonEditor/JsonEditor.tsx +0 -81
  215. package/src/jsonEditor/JsonEditorContext.tsx +0 -81
  216. package/src/jsonEditor/RenderNode.tsx +0 -87
  217. package/src/jsonEditor/editors.tsx +0 -745
  218. package/src/jsonEditor/index.ts +0 -2
  219. package/src/jsonEditor/json-editor.css +0 -463
  220. package/src/jsonEditor/useJsonEditorTokens.ts +0 -33
  221. package/src/mediaDragMime.ts +0 -32
  222. package/src/mediaEntries.ts +0 -12
  223. package/src/mediaReferences.ts +0 -299
  224. package/src/monaco.ts +0 -35
  225. package/src/monacoWorkers.ts +0 -89
  226. package/src/outlineSource.ts +0 -171
  227. package/src/presentation/PresentationMode.tsx +0 -596
  228. package/src/rawEditorIsolation.ts +0 -18
  229. package/src/recorder/RecorderButton.tsx +0 -80
  230. package/src/recorder/RecorderModal.tsx +0 -706
  231. package/src/recorder/RecorderPanel.tsx +0 -77
  232. package/src/recorder/formats.ts +0 -159
  233. package/src/recorder/hooks/useMediaRecorder.ts +0 -436
  234. package/src/recorder/hooks/useStreamPreview.ts +0 -47
  235. package/src/recorder/insertMediaBlock.ts +0 -30
  236. package/src/recorder/sources/cameraStream.ts +0 -32
  237. package/src/recorder/sources/micStream.ts +0 -25
  238. package/src/recorder/sources/screenStream.ts +0 -162
  239. package/src/recorder/timingJson.ts +0 -66
  240. package/src/resolveBlockVisual.ts +0 -39
  241. package/src/scene/Scene.tsx +0 -616
  242. package/src/scene/SceneBlockExtension.ts +0 -205
  243. package/src/scene/SceneBlockToolbar.tsx +0 -201
  244. package/src/scene/SceneBlockWidget.tsx +0 -441
  245. package/src/scene/ScenePropsBar.tsx +0 -85
  246. package/src/scene/SceneSelection.tsx +0 -111
  247. package/src/scene/SceneSideToolbar.tsx +0 -89
  248. package/src/scene/SceneViewport.tsx +0 -106
  249. package/src/scene/ShapePalette.tsx +0 -196
  250. package/src/scene/__tests__/DiagramAdapter.test.ts +0 -142
  251. package/src/scene/__tests__/SceneBlockExtension.test.ts +0 -33
  252. package/src/scene/__tests__/bezierEdit.test.ts +0 -85
  253. package/src/scene/__tests__/blockLayers.test.ts +0 -57
  254. package/src/scene/__tests__/sceneIsolation.test.tsx +0 -119
  255. package/src/scene/__tests__/shapeLayers.test.ts +0 -106
  256. package/src/scene/__tests__/useSceneHitTest.test.ts +0 -90
  257. package/src/scene/__tests__/useScenePanZoom.test.ts +0 -103
  258. package/src/scene/adapters/DiagramAdapter.ts +0 -79
  259. package/src/scene/adapters/DrawingAdapter.ts +0 -420
  260. package/src/scene/adapters/LayoutAdapter.ts +0 -313
  261. package/src/scene/adapters/blockLayers.ts +0 -159
  262. package/src/scene/commands/SceneCommand.ts +0 -84
  263. package/src/scene/commands/drawingCommands.ts +0 -318
  264. package/src/scene/commands/layoutCommands.ts +0 -301
  265. package/src/scene/hooks/useSceneHitTest.ts +0 -105
  266. package/src/scene/hooks/useScenePanZoom.ts +0 -147
  267. package/src/scene/hooks/useSceneSelection.ts +0 -62
  268. package/src/scene/index.ts +0 -90
  269. package/src/scene/layers/DiagramEdges.tsx +0 -142
  270. package/src/scene/layers/edgeGeometry.ts +0 -104
  271. package/src/scene/layers/nodeCard.tsx +0 -164
  272. package/src/scene/layers/renderLayer.tsx +0 -70
  273. package/src/scene/layers/shapeLayers.ts +0 -201
  274. package/src/scene/paths/bezierEdit.ts +0 -208
  275. package/src/scene/scene.css +0 -792
  276. package/src/scene/text/SceneTextOverlay.tsx +0 -161
  277. package/src/scene/text/sceneTextChannel.ts +0 -46
  278. package/src/scene/text/sceneTextConfig.ts +0 -31
  279. package/src/scene/text/sceneTiptap.ts +0 -36
  280. package/src/scene/text/useSceneTextEditing.ts +0 -39
  281. package/src/scene/tools/ConnectTool.ts +0 -209
  282. package/src/scene/tools/DrawingConnectTool.ts +0 -231
  283. package/src/scene/tools/PathTool.ts +0 -158
  284. package/src/scene/tools/PlaceTool.ts +0 -47
  285. package/src/scene/tools/SceneTool.ts +0 -85
  286. package/src/scene/tools/SelectTool.ts +0 -300
  287. package/src/scene/tools/ShapeTool.ts +0 -143
  288. package/src/scene/tools/TextTool.ts +0 -72
  289. package/src/scene/tools/TokenTool.ts +0 -95
  290. package/src/scene/tools/createDrawShapeTool.ts +0 -82
  291. package/src/selectionConversions.ts +0 -155
  292. package/src/styles/ascii-diagram.css +0 -79
  293. package/src/styles/ascii-timeline.css +0 -596
  294. package/src/styles/code-context.css +0 -155
  295. package/src/styles/diagram.css +0 -183
  296. package/src/styles/editor.css +0 -6811
  297. package/src/styles/folder-view.css +0 -210
  298. package/src/styles/image-edit-affordance.css +0 -201
  299. package/src/styles/index.css +0 -18
  300. package/src/styles/tree-view.css +0 -189
  301. package/src/teleprompter/TeleprompterControls.tsx +0 -218
  302. package/src/teleprompter/TeleprompterSelfView.tsx +0 -22
  303. package/src/teleprompter/TeleprompterSurface.tsx +0 -267
  304. package/src/teleprompter/TeleprompterView.tsx +0 -338
  305. package/src/teleprompter/canvasRenderer.ts +0 -161
  306. package/src/teleprompter/floatingWindow.ts +0 -352
  307. package/src/teleprompter/index.ts +0 -61
  308. package/src/teleprompter/pcmWorklet.ts +0 -62
  309. package/src/teleprompter/recording/insertPreamble.ts +0 -80
  310. package/src/teleprompter/recording/narrationSave.ts +0 -134
  311. package/src/teleprompter/recording/useNarrationRecorder.ts +0 -367
  312. package/src/teleprompter/scrollModel.ts +0 -85
  313. package/src/teleprompter/teleprompterTheme.ts +0 -303
  314. package/src/teleprompter/types.ts +0 -38
  315. package/src/teleprompter/useFloatingWindow.ts +0 -74
  316. package/src/teleprompter/useMicAnalysis.ts +0 -211
  317. package/src/teleprompter/useTeleprompter.ts +0 -421
  318. package/src/templateContentPreviewResolver.ts +0 -360
  319. package/src/timeline/TimelineEditorWidget.tsx +0 -861
  320. package/src/timeline/TimelineViewExtension.ts +0 -252
  321. package/src/timeline/__tests__/TimelineEditorWidget.test.tsx +0 -414
  322. package/src/timeline/__tests__/TimelineViewExtension.test.ts +0 -163
  323. package/src/timeline/__tests__/timelineCommands.test.ts +0 -359
  324. package/src/timeline/__tests__/timelineOps.test.ts +0 -277
  325. package/src/timeline/__tests__/timelinePaste.test.ts +0 -34
  326. package/src/timeline/timelineCommands.ts +0 -421
  327. package/src/timeline/timelineData.ts +0 -54
  328. package/src/timeline/timelineOps.ts +0 -381
  329. package/src/timeline/timelinePaste.ts +0 -8
  330. package/src/timelineSource.ts +0 -244
  331. package/src/tiptap/TiptapAudio.tsx +0 -86
  332. package/src/tiptap/TiptapVideo.tsx +0 -119
  333. package/src/tiptap/useResolvedMediaSrc.ts +0 -47
  334. package/src/tiptapBridge.ts +0 -986
  335. package/src/tooltipPlacement.ts +0 -13
  336. package/src/transformStyleId.ts +0 -17
  337. package/src/transitionCatalog.ts +0 -159
  338. package/src/treeview/TreeOutlineWidget.tsx +0 -390
  339. package/src/treeview/TreeViewExtension.ts +0 -250
  340. package/src/treeview/__tests__/TreeOutlineWidget.test.tsx +0 -156
  341. package/src/treeview/__tests__/TreeViewExtension.test.ts +0 -122
  342. package/src/treeview/__tests__/treeOps.test.ts +0 -177
  343. package/src/treeview/__tests__/treePaste.test.ts +0 -40
  344. package/src/treeview/__tests__/treeViewCommands.test.ts +0 -179
  345. package/src/treeview/treeOps.ts +0 -231
  346. package/src/treeview/treePaste.ts +0 -13
  347. package/src/treeview/treeViewCommands.ts +0 -99
  348. package/src/treeview/treeViewData.ts +0 -41
  349. package/src/types/monaco-shims.d.ts +0 -10
  350. package/src/useBlockNavigator.ts +0 -153
  351. package/src/useHeadingLayout.ts +0 -294
  352. package/src/useMonacoLoader.ts +0 -82
  353. package/src/useTimelineClock.ts +0 -76
  354. package/src/utils/collectInlineFontAwesomeCss.ts +0 -69
  355. package/src/utils/dropUtils.ts +0 -136
  356. package/src/utils/normalizeMalformedAssetUrl.ts +0 -22
  357. package/src/wysiwygImageUpload.ts +0 -113
@@ -1,792 +0,0 @@
1
- /**
2
- * WysiwygEditor
3
- *
4
- * Tiptap-based rich text editor that provides a WYSIWYG editing experience
5
- * for markdown content. Uses squisq's parseMarkdown/stringifyMarkdown for
6
- * conversion rather than Tiptap's built-in HTML serialization, ensuring
7
- * perfect fidelity with the markdown format.
8
- *
9
- * Includes extensions for GFM features: tables, task lists, strikethrough,
10
- * and code blocks.
11
- */
12
-
13
- import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
14
- import type { CSSProperties } from 'react';
15
- import { useEditor, EditorContent } from '@tiptap/react';
16
- import { Selection } from '@tiptap/pm/state';
17
- import type { EditorView as ProseMirrorView } from '@tiptap/pm/view';
18
- import StarterKit from '@tiptap/starter-kit';
19
- import Table from '@tiptap/extension-table';
20
- import TableRow from '@tiptap/extension-table-row';
21
- import TableCell from '@tiptap/extension-table-cell';
22
- import TableHeader from '@tiptap/extension-table-header';
23
- import TaskList from '@tiptap/extension-task-list';
24
- import TaskItem from '@tiptap/extension-task-item';
25
- import Link from '@tiptap/extension-link';
26
- import Placeholder from '@tiptap/extension-placeholder';
27
- import { resolveFontFamily, FONT_FALLBACKS, VIEWPORT_PRESETS } from '@bendyline/squisq/schemas';
28
- import { DEFAULT_THEME, flattenBlocks, markdownToDoc } from '@bendyline/squisq/doc';
29
- import { parseMarkdown } from '@bendyline/squisq/markdown';
30
- import { HeadingWithTemplate } from './TemplateAnnotation';
31
- import { AsciiDiagramExtension } from './asciiDiagram/AsciiDiagramExtension';
32
- import { RepairableDiagramExtension } from './asciiDiagram/RepairableDiagramExtension';
33
- import { applyRepairCommand } from './asciiDiagram/asciiDiagramCommands';
34
- import { shouldPasteAsAsciiFence } from './asciiDiagram/asciiPaste';
35
- import { TreeViewExtension } from './treeview/TreeViewExtension';
36
- import { shouldPasteAsTreeFence } from './treeview/treePaste';
37
- import { TimelineViewExtension } from './timeline/TimelineViewExtension';
38
- import { shouldPasteAsTimelineFence } from './timeline/timelinePaste';
39
- import { BlockTagActivityExtension } from './blockTagActivity';
40
- import { SceneBlockExtension } from './scene/SceneBlockExtension';
41
- import { InlineIcon } from './InlineIcon';
42
- import { ImageWithMediaProvider } from './ImageNodeView';
43
- import { TiptapVideo } from './tiptap/TiptapVideo';
44
- import { TiptapAudio } from './tiptap/TiptapAudio';
45
- import { TemplateBadgePopover, TEMPLATE_NAMES } from './TemplatePicker';
46
- import { BlockPropertiesPopover } from './BlockPropertiesPopover';
47
- import {
48
- CustomTemplateProvider,
49
- TemplateDesigner,
50
- type DesignerSaveTarget,
51
- } from './customTemplates';
52
- import { saveLibraryTemplate } from './customTemplates/library';
53
- import { useDocCustomTemplates } from './customTemplates/useDocCustomTemplates';
54
- import type { CustomTemplateDefinition } from '@bendyline/squisq/schemas';
55
- import { profileBlockContents, recommendTemplatesForBlock } from '@bendyline/squisq/recommend';
56
- import { findBlockSliceByHeadingIndex } from './blockSlice';
57
- import { stripFrontmatter } from './frontmatter';
58
- import { useEditorContext } from './EditorContext';
59
- import { buildMentionExtension } from './MentionExtension';
60
- import { markdownToTiptap, tiptapToMarkdown } from './tiptapBridge';
61
- import { looksLikeMarkdown } from './detectMarkdown';
62
- import { SQUISQ_MEDIA_MIME, parseSquisqMediaPayload } from './mediaDragMime';
63
- import { usePreviewSettingsOptional } from './PreviewControls';
64
- import { uploadAndInsertImages } from './wysiwygImageUpload';
65
-
66
- type ImageMutationView = Pick<ProseMirrorView, 'state' | 'dispatch'>;
67
-
68
- /**
69
- * Rotating placeholder prompts shown when the editor is empty. One is
70
- * picked at random per editor mount. Hosts can override by passing the
71
- * `placeholder` prop with a fixed string.
72
- */
73
- const EMPTY_PROMPTS = [
74
- 'Start typing your content, or drop images on top of me…',
75
- 'Write anything — paste markdown, drag in images, or just start typing…',
76
- 'Type away. Markdown syntax works too…',
77
- 'Chapter 1 begins here…',
78
- 'Once upon a time…',
79
- 'A blank page. Exciting, isn\u2019t it?',
80
- 'The first word is always the hardest…',
81
- 'Plot twist: this is where it all starts…',
82
- 'Write something the future you will thank you for…',
83
- 'Begin at the beginning…',
84
- ];
85
-
86
- const BLOCK_TAG_DATA_VALUES = {
87
- none: 'hidden',
88
- active: 'active',
89
- always: 'visible',
90
- } as const;
91
-
92
- function pickEmptyPrompt(): string {
93
- return EMPTY_PROMPTS[Math.floor(Math.random() * EMPTY_PROMPTS.length)];
94
- }
95
-
96
- export interface WysiwygEditorProps {
97
- /**
98
- * Placeholder text when the editor is empty. If omitted, one of several
99
- * rotating prompts is picked at random on mount. Pass a fixed string to
100
- * override with a host-specific call to action.
101
- */
102
- placeholder?: string;
103
- /** Additional class name for the container */
104
- className?: string;
105
- /**
106
- * If set, a plain Enter keypress fires this callback instead of inserting
107
- * a newline, and Cmd/Ctrl+Enter inserts a soft break. Chat-composer UX.
108
- */
109
- submitOnEnter?: () => void;
110
- /** Disable Tiptap editing — renders content but blocks input. */
111
- readOnly?: boolean;
112
- }
113
-
114
- /**
115
- * Rich WYSIWYG markdown editor built on Tiptap (ProseMirror).
116
- * Binds to the shared EditorContext for source synchronization.
117
- */
118
- export function WysiwygEditor({
119
- placeholder,
120
- className,
121
- submitOnEnter,
122
- readOnly = false,
123
- }: WysiwygEditorProps) {
124
- const {
125
- editorSource,
126
- setEditorSource,
127
- setTiptapEditor,
128
- mediaProvider,
129
- mentionProvider,
130
- blockTagVisibility,
131
- themeInheritance,
132
- colorScheme,
133
- bumpMediaRevision,
134
- sceneTextChannel,
135
- } = useEditorContext();
136
- // Custom templates inlined in the active doc's frontmatter + the
137
- // persist callback that writes a new list back into the source.
138
- const { docTemplates, onDocTemplatesChange } = useDocCustomTemplates();
139
- // Designer modal visibility. `null` when closed; `{ initial }` when
140
- // open. `initial` is undefined for a "+ New" flow or set to an
141
- // existing template to edit it.
142
- const [designerState, setDesignerState] = useState<{ initial?: CustomTemplateDefinition } | null>(
143
- null,
144
- );
145
- const handleDesignerSave = useCallback(
146
- (def: CustomTemplateDefinition, target: DesignerSaveTarget) => {
147
- if (target === 'doc') {
148
- const existingIdx = docTemplates.findIndex((t) => t.name === def.name);
149
- const next =
150
- existingIdx >= 0
151
- ? docTemplates.map((t, i) => (i === existingIdx ? def : t))
152
- : [...docTemplates, def];
153
- onDocTemplatesChange(next);
154
- } else {
155
- saveLibraryTemplate(def);
156
- }
157
- },
158
- [docTemplates, onDocTemplatesChange],
159
- );
160
- // Keep a ref so the mention extension — created once at editor mount —
161
- // always sees the latest provider. Swapping projects changes
162
- // the provider without remounting the editor.
163
- const mentionProviderRef = useRef(mentionProvider);
164
- useEffect(() => {
165
- mentionProviderRef.current = mentionProvider;
166
- }, [mentionProvider]);
167
- // Stable per mount: either the host-supplied string, or a random pick
168
- // from EMPTY_PROMPTS. Re-renders don't reshuffle.
169
- const resolvedPlaceholder = useMemo(() => placeholder ?? pickEmptyPrompt(), [placeholder]);
170
- const isExternalUpdate = useRef(false);
171
- const lastSourceRef = useRef(editorSource);
172
- // Keep a ref so the editor's drop/paste handlers (created once) always
173
- // see the current MediaProvider without needing to recreate the editor.
174
- const mediaProviderRef = useRef(mediaProvider);
175
- useEffect(() => {
176
- mediaProviderRef.current = mediaProvider;
177
- }, [mediaProvider]);
178
- // Preserve frontmatter across edits — hidden from WYSIWYG but prepended on
179
- // save. In block mode the bound slice carries no frontmatter, so this is an
180
- // empty string and the splice in `setEditorSource` keeps the doc's real
181
- // frontmatter intact.
182
- const frontmatterRef = useRef(stripFrontmatter(editorSource).frontmatter);
183
- // Stash the latest submit callback so the editor's handleKeyDown (bound
184
- // once at creation) always sees the current value.
185
- const submitOnEnterRef = useRef(submitOnEnter);
186
- useEffect(() => {
187
- submitOnEnterRef.current = submitOnEnter;
188
- }, [submitOnEnter]);
189
- const editor = useEditor({
190
- editable: !readOnly,
191
- extensions: [
192
- StarterKit.configure({
193
- // Disable built-in heading; we use HeadingWithTemplate instead
194
- heading: false,
195
- codeBlock: {
196
- HTMLAttributes: { class: 'squisq-code-block' },
197
- },
198
- }),
199
- HeadingWithTemplate.configure({ levels: [1, 2, 3, 4, 5, 6] }),
200
- BlockTagActivityExtension,
201
- AsciiDiagramExtension.configure({ textChannel: sceneTextChannel }),
202
- RepairableDiagramExtension.configure({ onRepair: applyRepairCommand }),
203
- TimelineViewExtension,
204
- TreeViewExtension,
205
- SceneBlockExtension.configure({ textChannel: sceneTextChannel }),
206
- Table.configure({ resizable: true }),
207
- TableRow,
208
- TableCell,
209
- TableHeader,
210
- TaskList,
211
- TaskItem.configure({ nested: true }),
212
- Link.configure({
213
- openOnClick: false,
214
- autolink: true,
215
- HTMLAttributes: { rel: 'noopener noreferrer', target: '_blank' },
216
- }),
217
- ImageWithMediaProvider.configure({ inline: false }),
218
- TiptapVideo,
219
- TiptapAudio,
220
- Placeholder.configure({ placeholder: resolvedPlaceholder }),
221
- buildMentionExtension(() => mentionProviderRef.current),
222
- InlineIcon,
223
- ],
224
- content: markdownToTiptap(stripFrontmatter(editorSource).body),
225
- onUpdate: ({ editor: ed }) => {
226
- if (isExternalUpdate.current) return;
227
- // Keep the source channel synchronous with Tiptap. Structural actions
228
- // such as block navigation/addition may run in the very next browser
229
- // event; deferring this write lets a stale callback serialize the newly
230
- // selected block into the previous block's range. The expensive full-doc
231
- // parse remains debounced in EditorContext, so correctness here does not
232
- // reintroduce parse-on-every-keystroke work.
233
- const bodyMd = tiptapToMarkdown(ed.getHTML());
234
- const newSource = frontmatterRef.current + bodyMd;
235
- lastSourceRef.current = newSource;
236
- setEditorSource(newSource);
237
- },
238
- editorProps: {
239
- attributes: {
240
- class: 'squisq-wysiwyg-editor',
241
- 'data-testid': 'wysiwyg-editor',
242
- },
243
- // Chat-composer mode: Enter commits via submitOnEnter(), Cmd/Ctrl+Enter
244
- // inserts a soft break. When no callback is set, fall through to Tiptap's
245
- // normal behavior (Enter = paragraph break, Shift+Enter = soft break).
246
- handleKeyDown: (view, event) => {
247
- if (event.key !== 'Enter' || !submitOnEnterRef.current) return false;
248
- // Defer Enter to an open mention/suggestion popover so the user
249
- // can pick the highlighted candidate. ProseMirror plugins fire
250
- // AFTER editorProps.handleKeyDown, so without this short-circuit
251
- // plain Enter submits the message and the popover closes
252
- // without inserting the mention. The MentionExtension marks
253
- // its container with `display: block` while items are showing
254
- // and `display: none` when empty — only short-circuit when
255
- // there's actually a candidate to pick.
256
- const popover = view.dom
257
- .closest('.squisq-editor-shell')
258
- ?.querySelector<HTMLElement>('.squisq-mention-popover');
259
- if (popover && popover.style.display !== 'none') {
260
- return false;
261
- }
262
- if (event.metaKey || event.ctrlKey) {
263
- // User wants a newline. Insert a hard-break and stop propagation so
264
- // we don't also create a new paragraph.
265
- event.preventDefault();
266
- view.dispatch(
267
- view.state.tr.replaceSelectionWith(view.state.schema.nodes.hardBreak.create()),
268
- );
269
- return true;
270
- }
271
- if (event.shiftKey) {
272
- // Preserve the conventional Shift+Enter soft break.
273
- return false;
274
- }
275
- // Plain Enter — submit.
276
- event.preventDefault();
277
- submitOnEnterRef.current();
278
- return true;
279
- },
280
- // When the clipboard's plain-text payload looks like markdown source,
281
- // convert it via tiptapBridge before pasting. This applies even when
282
- // the clipboard also contains HTML (most rich-text sources do), since
283
- // the markdown-looking text is usually what the user actually wants.
284
- // Without this, pasted markdown shows up as literal "# Heading" text
285
- // instead of becoming a real heading.
286
- handlePaste: (view, event) => {
287
- const clipboard = event.clipboardData;
288
- if (!clipboard) return false;
289
-
290
- // Image files in the clipboard → upload via MediaProvider and insert
291
- const imageFiles = filesFromClipboard(clipboard);
292
- if (imageFiles.length > 0 && mediaProviderRef.current) {
293
- event.preventDefault();
294
- uploadAndInsertImages(view, imageFiles, mediaProviderRef.current, bumpMediaRevision);
295
- return true;
296
- }
297
-
298
- const text = clipboard.getData('text/plain');
299
- if (!text) return false;
300
-
301
- // Bare (unfenced) ASCII diagram art → verbatim into a fresh code
302
- // block, which AsciiDiagramExtension turns into an interactive
303
- // canvas. Must run BEFORE the markdown branch: `| x |` art rows
304
- // false-positive as GFM table rows and would be mangled.
305
- if (shouldPasteAsAsciiFence(text)) {
306
- const codeBlockType = view.state.schema.nodes.codeBlock;
307
- if (codeBlockType) {
308
- event.preventDefault();
309
- // Tag the fence `diagram` so its identity survives a later
310
- // flatten → markdown → re-import round-trip (the language class
311
- // round-trips; fence meta does not).
312
- view.dispatch(
313
- view.state.tr.replaceSelectionWith(
314
- codeBlockType.create({ language: 'diagram' }, view.state.schema.text(text)),
315
- ),
316
- );
317
- return true;
318
- }
319
- }
320
-
321
- // Bare (unfenced) marker rails → an explicit timeline code block.
322
- // Run before the tree gate because timeline callout elbows can look
323
- // like nested tree connectors to a deliberately lenient parser.
324
- if (shouldPasteAsTimelineFence(text)) {
325
- const codeBlockType = view.state.schema.nodes.codeBlock;
326
- if (codeBlockType) {
327
- event.preventDefault();
328
- view.dispatch(
329
- view.state.tr.replaceSelectionWith(
330
- codeBlockType.create({ language: 'timeline' }, view.state.schema.text(text)),
331
- ),
332
- );
333
- return true;
334
- }
335
- }
336
-
337
- // Bare (unfenced) ASCII tree art → a fresh code block that the
338
- // TreeViewExtension turns into an outline. After the diagram gate,
339
- // before markdown (the `├──` lines must not be mangled as prose).
340
- if (shouldPasteAsTreeFence(text)) {
341
- const codeBlockType = view.state.schema.nodes.codeBlock;
342
- if (codeBlockType) {
343
- event.preventDefault();
344
- // Tag the fence `tree` so its identity survives round-trips.
345
- view.dispatch(
346
- view.state.tr.replaceSelectionWith(
347
- codeBlockType.create({ language: 'tree' }, view.state.schema.text(text)),
348
- ),
349
- );
350
- return true;
351
- }
352
- }
353
-
354
- if (!looksLikeMarkdown(text)) return false;
355
- const html = markdownToTiptap(text);
356
- if (!html) return false;
357
- event.preventDefault();
358
- view.pasteHTML(html);
359
- return true;
360
- },
361
- // When image files are dropped onto the editor, upload them via the
362
- // MediaProvider and insert <img> nodes referencing the relative paths.
363
- // Also handles drags from the MediaBin, which reference existing
364
- // entries via a custom MIME type and skip the upload step.
365
- // Falls through to default handling for non-image drops or when no
366
- // MediaProvider is available.
367
- handleDrop: (view, event, _slice, moved) => {
368
- const dt = event.dataTransfer;
369
- if (!dt) return false;
370
-
371
- // Internal node move (the user dragged an existing node within
372
- // the document). ProseMirror's `moved` flag is true in this
373
- // case; let it handle the reposition natively so width/height
374
- // attributes are preserved and the source node is removed.
375
- // Without this short-circuit, the browser also exposes the
376
- // dragged `<img>` as a virtual file in `dataTransfer`, so the
377
- // upload-and-insert path below would fire — producing a
378
- // dimension-less duplicate next to the original.
379
- if (moved) return false;
380
-
381
- // In-app drag from the MediaBin — insert without uploading
382
- const squisqRaw = dt.getData(SQUISQ_MEDIA_MIME);
383
- if (squisqRaw) {
384
- const payload = parseSquisqMediaPayload(squisqRaw);
385
- if (payload && payload.mimeType.startsWith('image/')) {
386
- event.preventDefault();
387
- moveSelectionToDropPoint(view, event);
388
- insertImageNode(view, payload.name, payload.alt);
389
- return true;
390
- }
391
- }
392
-
393
- const imageFiles = filesFromDataTransfer(dt);
394
- if (imageFiles.length === 0) {
395
- // Nothing image-like in the drop. Let the browser / ProseMirror
396
- // handle it (links, text, etc.). Log enough to debug if the user
397
- // expected this to be an image drop — Windows/browser combos
398
- // sometimes deliver image drags without a usable File payload.
399
- if (dt.files.length > 0 || dt.items.length > 0) {
400
- console.warn(
401
- '[squisq-editor] Drop received with no recognizable image File. Types:',
402
- Array.from(dt.types ?? []),
403
- 'files:',
404
- Array.from(dt.files).map((f) => `${f.name} (${f.type || 'no-type'})`),
405
- );
406
- }
407
- return false;
408
- }
409
- if (!mediaProviderRef.current) {
410
- console.warn(
411
- '[squisq-editor] Image drop received but no MediaProvider is wired up; cannot persist the image. Pass `mediaProvider` to EditorShell / EditorProvider.',
412
- );
413
- return false;
414
- }
415
-
416
- event.preventDefault();
417
- moveSelectionToDropPoint(view, event);
418
- uploadAndInsertImages(view, imageFiles, mediaProviderRef.current, bumpMediaRevision);
419
- return true;
420
- },
421
- },
422
- });
423
-
424
- // Register / unregister the Tiptap editor instance with the shared context
425
- useEffect(() => {
426
- if (editor) {
427
- setTiptapEditor(editor);
428
- }
429
- return () => setTiptapEditor(null);
430
- }, [editor, setTiptapEditor]);
431
-
432
- // Tiptap reads `editable` only at creation; mirror later changes via
433
- // setEditable so flipping readOnly from the host takes effect without
434
- // remounting the editor.
435
- useEffect(() => {
436
- if (editor) editor.setEditable(!readOnly);
437
- }, [editor, readOnly]);
438
-
439
- // ── Template badge → popover ─────────────────────────────────────
440
- // The HeadingWithTemplate extension renders an inert `.squisq-template-badge`
441
- // span inside templated headings. We delegate clicks at the container
442
- // level so we can locate the heading position and open the gallery
443
- // anchored at that badge.
444
- const containerRef = useRef<HTMLDivElement | null>(null);
445
- const [badgeMenu, setBadgeMenu] = useState<{
446
- rect: DOMRect;
447
- template: string;
448
- headingPos: number;
449
- headingIndex: number;
450
- } | null>(null);
451
- const [propsMenu, setPropsMenu] = useState<{
452
- rect: DOMRect;
453
- headingPos: number;
454
- blockAttrs: string | null;
455
- templateParams: string | null;
456
- } | null>(null);
457
-
458
- const closeBadgeMenu = useCallback(() => {
459
- setBadgeMenu(null);
460
- // The portaled gallery moves focus into its search field. Restore the
461
- // document's preserved ProseMirror selection after React has unmounted the
462
- // dialog, so the caret resumes blinking where the author left it.
463
- requestAnimationFrame(() => {
464
- if (editor && !editor.isDestroyed) editor.commands.focus();
465
- });
466
- }, [editor]);
467
-
468
- useEffect(() => {
469
- if (!editor) return;
470
- const root = containerRef.current;
471
- if (!root) return;
472
- const onClick = (e: MouseEvent) => {
473
- const target = e.target as HTMLElement | null;
474
- if (!target) return;
475
- const propsBadge = target.closest('.squisq-props-badge') as HTMLElement | null;
476
- const templateBadge = target.closest('.squisq-template-badge') as HTMLElement | null;
477
- const badge = propsBadge ?? templateBadge;
478
- if (!badge || !root.contains(badge)) return;
479
- e.preventDefault();
480
- e.stopPropagation();
481
- // Find the parent heading element and resolve its document position.
482
- const headingEl = badge.closest('h1,h2,h3,h4,h5,h6') as HTMLElement | null;
483
- if (!headingEl) return;
484
- let pos: number | null = null;
485
- try {
486
- pos = editor.view.posAtDOM(headingEl, 0);
487
- } catch {
488
- pos = null;
489
- }
490
- if (pos == null) return;
491
- // posAtDOM returns the position *inside* the heading; subtract 1
492
- // to land on the heading node itself so setNodeMarkup targets it.
493
- const headingPos = Math.max(0, pos - 1);
494
- const node = editor.state.doc.nodeAt(headingPos);
495
- if (!node || node.type.name !== 'heading') return;
496
-
497
- // Block-properties badge → open the properties palette.
498
- if (propsBadge) {
499
- setBadgeMenu(null);
500
- setPropsMenu({
501
- rect: badge.getBoundingClientRect(),
502
- headingPos,
503
- blockAttrs: (node.attrs.dataBlockAttrs as string | null) ?? null,
504
- templateParams: (node.attrs.dataTemplateParams as string | null) ?? null,
505
- });
506
- return;
507
- }
508
-
509
- // Template badge → open the template gallery. Count how many headings
510
- // precede this one so the markdown-source slice helper can locate the
511
- // matching heading by index.
512
- let headingIndex = 0;
513
- let count = 0;
514
- editor.state.doc.descendants((n, p) => {
515
- if (n.type.name !== 'heading') return;
516
- if (p === headingPos) {
517
- headingIndex = count;
518
- return false;
519
- }
520
- count++;
521
- });
522
- setPropsMenu(null);
523
- setBadgeMenu({
524
- rect: badge.getBoundingClientRect(),
525
- template: (node.attrs.dataTemplate as string | null) ?? '',
526
- headingPos,
527
- headingIndex,
528
- });
529
- };
530
- root.addEventListener('mousedown', onClick);
531
- return () => root.removeEventListener('mousedown', onClick);
532
- }, [editor]);
533
-
534
- // Sync external changes into Tiptap. `editorSource` also changes when the
535
- // user navigates to a different block in block-at-a-time mode, so this same
536
- // path reloads the card with the newly selected block's slice.
537
- useEffect(() => {
538
- if (!editor) return;
539
- if (editorSource === lastSourceRef.current) return;
540
- // In block/timeline mode `setEditorSource` normalizes the slice's trailing
541
- // whitespace (a `\n\n` before the next block) before splicing, so the
542
- // re-extracted `editorSource` differs from what we just emitted by trailing
543
- // whitespace only. Re-setting content for that would reset the caret to the
544
- // end on every keystroke — so only reload when the body actually changed.
545
- if (editorSource.replace(/\s+$/, '') === lastSourceRef.current.replace(/\s+$/, '')) {
546
- lastSourceRef.current = editorSource;
547
- return;
548
- }
549
- isExternalUpdate.current = true;
550
- const { body, frontmatter } = stripFrontmatter(editorSource);
551
- frontmatterRef.current = frontmatter;
552
- const content = markdownToTiptap(body);
553
- editor.commands.setContent(content);
554
- lastSourceRef.current = editorSource;
555
- isExternalUpdate.current = false;
556
- }, [editorSource, editor]);
557
-
558
- // Match the WYSIWYG editor's appearance to the active Squisq theme when one
559
- // is set in frontmatter or picked in the preview dropdown. The block-props
560
- // affordance always carries the theme's primary as UI accent (like the
561
- // outline); document-content inheritance is driven by the View menu setting:
562
- // - 'none' → don't inherit anything
563
- // - 'fonts' → body + heading fonts only (historical default)
564
- // - 'fonts-colors' → fonts plus the theme's canvas / text colors
565
- // Pushed as CSS custom properties on the container so the stylesheet
566
- // can pick them up (with sensible fallbacks for hosts that don't have
567
- // a PreviewSettingsProvider in scope).
568
- const previewSettings = usePreviewSettingsOptional();
569
- const activeTheme = previewSettings?.activeTheme;
570
- const badgePreviewSource = useMemo(() => {
571
- if (!badgeMenu) return undefined;
572
- try {
573
- const previewDoc = markdownToDoc(parseMarkdown(editorSource), { autoTemplates: false });
574
- const block = flattenBlocks(previewDoc.blocks)[badgeMenu.headingIndex];
575
- if (!block) return undefined;
576
- return {
577
- block,
578
- theme: previewSettings?.activeTheme ?? DEFAULT_THEME,
579
- viewport: previewSettings?.activeViewport ?? VIEWPORT_PRESETS.landscape,
580
- basePath: '/',
581
- mediaProvider,
582
- customTemplates: docTemplates,
583
- };
584
- } catch {
585
- return undefined;
586
- }
587
- }, [
588
- badgeMenu,
589
- docTemplates,
590
- editorSource,
591
- mediaProvider,
592
- previewSettings?.activeTheme,
593
- previewSettings?.activeViewport,
594
- ]);
595
- const themeStyle = useMemo<CSSProperties>(() => {
596
- if (!activeTheme) return {};
597
- const out: Record<string, string> = {
598
- '--squisq-block-props-accent': activeTheme.colors.primary,
599
- };
600
- if (themeInheritance === 'none') return out as CSSProperties;
601
- Object.assign(out, {
602
- '--squisq-theme-body-font': resolveFontFamily(
603
- activeTheme.typography.bodyFont,
604
- FONT_FALLBACKS.sans,
605
- ),
606
- '--squisq-theme-title-font': resolveFontFamily(
607
- activeTheme.typography.titleFont,
608
- FONT_FALLBACKS.sans,
609
- ),
610
- });
611
- if (themeInheritance === 'fonts-colors') {
612
- const colors = activeTheme.colors;
613
- out['--squisq-theme-bg'] = colors.background;
614
- // backgroundLight gives a subtle on-canvas surface for inline emphasis
615
- // (inline `code`, code blocks). Themes always define it.
616
- out['--squisq-theme-bg-muted'] = colors.backgroundLight;
617
- out['--squisq-theme-text'] = colors.text;
618
- out['--squisq-theme-text-muted'] = colors.textMuted;
619
- out['--squisq-theme-primary'] = colors.primary;
620
- }
621
- return out as CSSProperties;
622
- }, [activeTheme, themeInheritance]);
623
-
624
- return (
625
- <CustomTemplateProvider docTemplates={docTemplates} onDocTemplatesChange={onDocTemplatesChange}>
626
- <div
627
- className={`squisq-wysiwyg-container${className ? ` ${className}` : ''}`}
628
- style={{ width: '100%', height: '100%', overflow: 'auto', ...themeStyle }}
629
- data-testid="wysiwyg-container"
630
- data-block-tags={BLOCK_TAG_DATA_VALUES[blockTagVisibility]}
631
- data-theme-inheritance={themeInheritance}
632
- ref={containerRef}
633
- >
634
- <EditorContent editor={editor} style={{ height: '100%' }} />
635
- {badgeMenu && (
636
- <TemplateBadgePopover
637
- anchorRect={badgeMenu.rect}
638
- value={badgeMenu.template}
639
- colorScheme={colorScheme}
640
- recommended={(() => {
641
- // `headingIndex` is counted within the mounted Tiptap doc, which
642
- // reflects `editorSource` — the active block's slice in block
643
- // mode, the full document otherwise.
644
- const slice = findBlockSliceByHeadingIndex(editorSource, badgeMenu.headingIndex);
645
- if (!slice) return undefined;
646
- const profile = profileBlockContents(slice);
647
- return recommendTemplatesForBlock(profile, TEMPLATE_NAMES).recommended;
648
- })()}
649
- previewSource={badgePreviewSource}
650
- onOpenDesigner={() => {
651
- setBadgeMenu(null);
652
- setDesignerState({});
653
- }}
654
- onChange={(name) => {
655
- if (!editor) return;
656
- const tr = editor.state.tr.setNodeMarkup(badgeMenu.headingPos, undefined, {
657
- ...editor.state.doc.nodeAt(badgeMenu.headingPos)?.attrs,
658
- dataTemplate: name === '' ? null : name,
659
- });
660
- editor.view.dispatch(tr);
661
- }}
662
- onClose={closeBadgeMenu}
663
- />
664
- )}
665
- {propsMenu && (
666
- <BlockPropertiesPopover
667
- anchorRect={propsMenu.rect}
668
- blockAttrs={propsMenu.blockAttrs}
669
- templateParams={propsMenu.templateParams}
670
- colorScheme={colorScheme}
671
- accentColor={activeTheme?.colors.primary}
672
- onChange={(nextInner) => {
673
- if (!editor) return;
674
- const current = editor.state.doc.nodeAt(propsMenu.headingPos);
675
- if (!current || current.type.name !== 'heading') return;
676
- const tr = editor.state.tr.setNodeMarkup(propsMenu.headingPos, undefined, {
677
- ...current.attrs,
678
- dataBlockAttrs: nextInner,
679
- });
680
- editor.view.dispatch(tr);
681
- }}
682
- onAnnotationChange={(next) => {
683
- if (!editor) return;
684
- const current = editor.state.doc.nodeAt(propsMenu.headingPos);
685
- if (!current || current.type.name !== 'heading') return;
686
- const tr = editor.state.tr.setNodeMarkup(propsMenu.headingPos, undefined, {
687
- ...current.attrs,
688
- dataBlockAttrs: next.blockAttrsInner,
689
- dataTemplateParams: next.templateParams,
690
- });
691
- editor.view.dispatch(tr);
692
- }}
693
- onClose={() => setPropsMenu(null)}
694
- />
695
- )}
696
- {designerState && (
697
- <TemplateDesigner
698
- initial={designerState.initial}
699
- onSave={handleDesignerSave}
700
- onClose={() => setDesignerState(null)}
701
- mediaProvider={mediaProvider}
702
- colorScheme={colorScheme}
703
- />
704
- )}
705
- </div>
706
- </CustomTemplateProvider>
707
- );
708
- }
709
-
710
- // ── Image drop / paste helpers ─────────────────────────────────────
711
-
712
- /** Extension-based fallback when a dragged file has no `type` set (rare
713
- * but happens when sources omit the MIME — e.g. some screenshot tools). */
714
- const IMAGE_EXT_RE = /\.(png|jpe?g|gif|webp|bmp|svg|avif|ico)$/i;
715
-
716
- function looksLikeImageFile(file: File): boolean {
717
- if (file.type.startsWith('image/')) return true;
718
- return IMAGE_EXT_RE.test(file.name);
719
- }
720
-
721
- /** Extract image File objects from a DataTransfer (drop event). Reads
722
- * from both `dt.files` and `dt.items`; some drag sources (cross-tab
723
- * drags, certain native apps) populate only one of the two. */
724
- function filesFromDataTransfer(dt: DataTransfer): File[] {
725
- const files: File[] = [];
726
- const seen = new Set<string>();
727
-
728
- for (let i = 0; i < dt.files.length; i++) {
729
- const file = dt.files[i];
730
- if (looksLikeImageFile(file)) {
731
- files.push(file);
732
- seen.add(`${file.name}|${file.size}`);
733
- }
734
- }
735
-
736
- if (dt.items) {
737
- for (let i = 0; i < dt.items.length; i++) {
738
- const item = dt.items[i];
739
- if (item.kind !== 'file') continue;
740
- const file = item.getAsFile();
741
- if (!file) continue;
742
- if (!looksLikeImageFile(file)) continue;
743
- const key = `${file.name}|${file.size}`;
744
- if (seen.has(key)) continue;
745
- files.push(file);
746
- seen.add(key);
747
- }
748
- }
749
-
750
- return files;
751
- }
752
-
753
- /** Extract image File objects from a clipboard's items (paste event). */
754
- function filesFromClipboard(clipboard: DataTransfer): File[] {
755
- const files: File[] = [];
756
- // clipboardData.items is the most reliable source for pasted images
757
- if (clipboard.items) {
758
- for (let i = 0; i < clipboard.items.length; i++) {
759
- const item = clipboard.items[i];
760
- if (item.kind === 'file' && item.type.startsWith('image/')) {
761
- const file = item.getAsFile();
762
- if (file) files.push(file);
763
- }
764
- }
765
- }
766
- return files;
767
- }
768
-
769
- /** Insert an image node at the current selection using the schema image type. */
770
- function insertImageNode(view: ImageMutationView, src: string, alt: string): void {
771
- const { schema } = view.state;
772
- const imageType = schema.nodes.image;
773
- if (!imageType) return;
774
- const node = imageType.create({ src, alt });
775
- const tr = view.state.tr.replaceSelectionWith(node);
776
- view.dispatch(tr);
777
- }
778
-
779
- /** Move the selection to the document position under the drop event's coordinates. */
780
- function moveSelectionToDropPoint(view: ProseMirrorView, event: DragEvent): void {
781
- const coords = view.posAtCoords({ left: event.clientX, top: event.clientY });
782
- if (!coords) return;
783
- const tr = view.state.tr.setSelection(Selection.near(view.state.doc.resolve(coords.pos)));
784
- view.dispatch(tr);
785
- }
786
-
787
- /**
788
- * Hook to access the Tiptap editor instance for toolbar commands.
789
- * The WysiwygEditor must be mounted as a sibling or descendant.
790
- */
791
- // eslint-disable-next-line react-refresh/only-export-components
792
- export { useEditor as useTiptapEditor } from '@tiptap/react';