@sixb/app 0.2.3 → 0.2.5

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 (329) hide show
  1. package/assets/connector-icons/README.md +1 -0
  2. package/assets/connector-icons/ctm.png +0 -0
  3. package/dist/agent/activity-label.d.ts.map +1 -1
  4. package/dist/agent/agent-chat.d.ts +3 -1
  5. package/dist/agent/agent-chat.d.ts.map +1 -1
  6. package/dist/agent/agent-panel.d.ts.map +1 -1
  7. package/dist/agent/artifact-panel.d.ts +3 -1
  8. package/dist/agent/artifact-panel.d.ts.map +1 -1
  9. package/dist/agent/background/background-tool-row.d.ts.map +1 -1
  10. package/dist/agent/background/interpret.d.ts +1 -1
  11. package/dist/agent/background/interpret.d.ts.map +1 -1
  12. package/dist/agent/components/composer-settings.d.ts +1 -1
  13. package/dist/agent/components/composer-settings.d.ts.map +1 -1
  14. package/dist/agent/components/composer.d.ts +22 -5
  15. package/dist/agent/components/composer.d.ts.map +1 -1
  16. package/dist/agent/components/context-meter.d.ts +1 -1
  17. package/dist/agent/components/context-meter.d.ts.map +1 -1
  18. package/dist/agent/components/conversation-panel.d.ts +8 -2
  19. package/dist/agent/components/conversation-panel.d.ts.map +1 -1
  20. package/dist/agent/components/message-parts.d.ts +2 -1
  21. package/dist/agent/components/message-parts.d.ts.map +1 -1
  22. package/dist/agent/components/message-view.d.ts.map +1 -1
  23. package/dist/agent/components/pending-messages.d.ts +20 -0
  24. package/dist/agent/components/pending-messages.d.ts.map +1 -0
  25. package/dist/agent/components/sandbox-recovery.d.ts +11 -2
  26. package/dist/agent/components/sandbox-recovery.d.ts.map +1 -1
  27. package/dist/agent/components/threads-button.d.ts +1 -1
  28. package/dist/agent/components/threads-button.d.ts.map +1 -1
  29. package/dist/agent/components/transcript.d.ts +5 -0
  30. package/dist/agent/components/transcript.d.ts.map +1 -1
  31. package/dist/agent/conversation.d.ts +3 -6
  32. package/dist/agent/conversation.d.ts.map +1 -1
  33. package/dist/agent/delegation/agent-exchange.d.ts +16 -0
  34. package/dist/agent/delegation/agent-exchange.d.ts.map +1 -0
  35. package/dist/agent/delegation/child-card.d.ts +3 -3
  36. package/dist/agent/delegation/child-card.d.ts.map +1 -1
  37. package/dist/agent/delegation/child-parts.d.ts +1 -10
  38. package/dist/agent/delegation/child-parts.d.ts.map +1 -1
  39. package/dist/agent/delegation/child-work.d.ts.map +1 -1
  40. package/dist/agent/delegation/interpret.d.ts +9 -10
  41. package/dist/agent/delegation/interpret.d.ts.map +1 -1
  42. package/dist/agent/delegation/use-children.d.ts.map +1 -1
  43. package/dist/agent/file-edits/file-edit-tool-view.d.ts +10 -0
  44. package/dist/agent/file-edits/file-edit-tool-view.d.ts.map +1 -0
  45. package/dist/agent/file-edits/interpret.d.ts +25 -0
  46. package/dist/agent/file-edits/interpret.d.ts.map +1 -0
  47. package/dist/agent/hooks/use-agent-conversation.d.ts +16 -4
  48. package/dist/agent/hooks/use-agent-conversation.d.ts.map +1 -1
  49. package/dist/agent/hooks/use-thread-lists.d.ts.map +1 -1
  50. package/dist/agent/hooks/use-thread-stream.d.ts.map +1 -1
  51. package/dist/agent/i18n/en.d.ts +114 -5
  52. package/dist/agent/i18n/en.d.ts.map +1 -1
  53. package/dist/agent/i18n/fr.d.ts.map +1 -1
  54. package/dist/agent/i18n/index.d.ts +190 -8
  55. package/dist/agent/i18n/index.d.ts.map +1 -1
  56. package/dist/agent/inbox-handoff.d.ts +10 -0
  57. package/dist/agent/inbox-handoff.d.ts.map +1 -0
  58. package/dist/agent/live-run.d.ts +8 -1
  59. package/dist/agent/live-run.d.ts.map +1 -1
  60. package/dist/agent/message-agent/interpret.d.ts +2 -2
  61. package/dist/agent/message-agent/interpret.d.ts.map +1 -1
  62. package/dist/agent/publish-artifact/interpret.d.ts +1 -1
  63. package/dist/agent/publish-artifact/interpret.d.ts.map +1 -1
  64. package/dist/agent/questions/interpret.d.ts +31 -0
  65. package/dist/agent/questions/interpret.d.ts.map +1 -0
  66. package/dist/agent/questions/question-card.d.ts +16 -0
  67. package/dist/agent/questions/question-card.d.ts.map +1 -0
  68. package/dist/agent/questions/question-composer.d.ts +15 -0
  69. package/dist/agent/questions/question-composer.d.ts.map +1 -0
  70. package/dist/agent/read/interpret.d.ts +8 -1
  71. package/dist/agent/read/interpret.d.ts.map +1 -1
  72. package/dist/agent/read/read-tool-view.d.ts.map +1 -1
  73. package/dist/agent/search/interpret.d.ts +101 -0
  74. package/dist/agent/search/interpret.d.ts.map +1 -0
  75. package/dist/agent/search/search-tool-view.d.ts +10 -0
  76. package/dist/agent/search/search-tool-view.d.ts.map +1 -0
  77. package/dist/agent/thread-state.d.ts +26 -0
  78. package/dist/agent/thread-state.d.ts.map +1 -0
  79. package/dist/agent/tool-views/built-in.d.ts.map +1 -1
  80. package/dist/agent/tool-views/registry.d.ts +5 -6
  81. package/dist/agent/tool-views/registry.d.ts.map +1 -1
  82. package/dist/agent/types.d.ts +5 -1
  83. package/dist/agent/types.d.ts.map +1 -1
  84. package/dist/agent/view-file/view-file-tool-view.d.ts +2 -1
  85. package/dist/agent/view-file/view-file-tool-view.d.ts.map +1 -1
  86. package/dist/agent/waits.d.ts +14 -0
  87. package/dist/agent/waits.d.ts.map +1 -0
  88. package/dist/artifacts/card-preview.d.ts.map +1 -1
  89. package/dist/artifacts/edit-session.d.ts +11 -1
  90. package/dist/artifacts/edit-session.d.ts.map +1 -1
  91. package/dist/artifacts/editor/block-handle.d.ts +20 -0
  92. package/dist/artifacts/editor/block-handle.d.ts.map +1 -0
  93. package/dist/artifacts/editor/blocks.d.ts +34 -0
  94. package/dist/artifacts/editor/blocks.d.ts.map +1 -0
  95. package/dist/artifacts/editor/callout-view.d.ts +7 -0
  96. package/dist/artifacts/editor/callout-view.d.ts.map +1 -0
  97. package/dist/artifacts/editor/document-editor.d.ts +30 -0
  98. package/dist/artifacts/editor/document-editor.d.ts.map +1 -0
  99. package/dist/artifacts/editor/figure-view.d.ts +12 -0
  100. package/dist/artifacts/editor/figure-view.d.ts.map +1 -0
  101. package/dist/artifacts/editor/find-blocks.d.ts +6 -0
  102. package/dist/artifacts/editor/find-blocks.d.ts.map +1 -0
  103. package/dist/artifacts/editor/markdown-document.d.ts +12 -0
  104. package/dist/artifacts/editor/markdown-document.d.ts.map +1 -0
  105. package/dist/artifacts/editor/messages.d.ts +4 -0
  106. package/dist/artifacts/editor/messages.d.ts.map +1 -0
  107. package/dist/artifacts/editor/schema.d.ts +21 -0
  108. package/dist/artifacts/editor/schema.d.ts.map +1 -0
  109. package/dist/artifacts/editor/selection-toolbar.d.ts +35 -0
  110. package/dist/artifacts/editor/selection-toolbar.d.ts.map +1 -0
  111. package/dist/artifacts/editor/slash-menu.d.ts +43 -0
  112. package/dist/artifacts/editor/slash-menu.d.ts.map +1 -0
  113. package/dist/artifacts/editor/upload.d.ts +12 -0
  114. package/dist/artifacts/editor/upload.d.ts.map +1 -0
  115. package/dist/artifacts/file-source.d.ts +5 -0
  116. package/dist/artifacts/file-source.d.ts.map +1 -1
  117. package/dist/artifacts/frame-editor/bundle.d.ts +7 -0
  118. package/dist/artifacts/frame-editor/bundle.d.ts.map +1 -0
  119. package/dist/artifacts/frame-editor/commands.d.ts +93 -0
  120. package/dist/artifacts/frame-editor/commands.d.ts.map +1 -0
  121. package/dist/artifacts/frame-editor/entry.d.ts +2 -0
  122. package/dist/artifacts/frame-editor/entry.d.ts.map +1 -0
  123. package/dist/artifacts/frame-editor/frame.d.ts +5 -0
  124. package/dist/artifacts/frame-editor/frame.d.ts.map +1 -0
  125. package/dist/artifacts/frame-editor/keys.d.ts +8 -0
  126. package/dist/artifacts/frame-editor/keys.d.ts.map +1 -0
  127. package/dist/artifacts/frame-editor/protocol.d.ts +186 -0
  128. package/dist/artifacts/frame-editor/protocol.d.ts.map +1 -0
  129. package/dist/artifacts/frame-editor/schema.d.ts +34 -0
  130. package/dist/artifacts/frame-editor/schema.d.ts.map +1 -0
  131. package/dist/artifacts/frame-editor/style.d.ts +2 -0
  132. package/dist/artifacts/frame-editor/style.d.ts.map +1 -0
  133. package/dist/artifacts/frame.d.ts +2 -2
  134. package/dist/artifacts/frame.d.ts.map +1 -1
  135. package/dist/artifacts/live/boards.d.ts +2 -0
  136. package/dist/artifacts/live/boards.d.ts.map +1 -1
  137. package/dist/artifacts/live/document.d.ts +32 -0
  138. package/dist/artifacts/live/document.d.ts.map +1 -0
  139. package/dist/artifacts/live/header.d.ts +4 -4
  140. package/dist/artifacts/live/header.d.ts.map +1 -1
  141. package/dist/artifacts/live/presence.d.ts.map +1 -1
  142. package/dist/artifacts/live/session.d.ts +2 -0
  143. package/dist/artifacts/live/session.d.ts.map +1 -1
  144. package/dist/artifacts/live/view.d.ts +4 -3
  145. package/dist/artifacts/live/view.d.ts.map +1 -1
  146. package/dist/artifacts/messages.d.ts +278 -2
  147. package/dist/artifacts/messages.d.ts.map +1 -1
  148. package/dist/artifacts/pdf.d.ts +8 -0
  149. package/dist/artifacts/pdf.d.ts.map +1 -0
  150. package/dist/artifacts/queries.d.ts +80 -0
  151. package/dist/artifacts/queries.d.ts.map +1 -1
  152. package/dist/artifacts/references/references.d.ts +3 -3
  153. package/dist/artifacts/references/references.d.ts.map +1 -1
  154. package/dist/artifacts/renderers/canvas/board-editor.d.ts +11 -4
  155. package/dist/artifacts/renderers/canvas/board-editor.d.ts.map +1 -1
  156. package/dist/artifacts/renderers/canvas/board.d.ts +14 -2
  157. package/dist/artifacts/renderers/canvas/board.d.ts.map +1 -1
  158. package/dist/artifacts/renderers/canvas/canvas.d.ts +4 -3
  159. package/dist/artifacts/renderers/canvas/canvas.d.ts.map +1 -1
  160. package/dist/artifacts/renderers/canvas/comment-pins.d.ts +4 -2
  161. package/dist/artifacts/renderers/canvas/comment-pins.d.ts.map +1 -1
  162. package/dist/artifacts/renderers/canvas/comments-panel.d.ts.map +1 -1
  163. package/dist/artifacts/renderers/canvas/comments.d.ts +2 -1
  164. package/dist/artifacts/renderers/canvas/comments.d.ts.map +1 -1
  165. package/dist/artifacts/renderers/canvas/controls.d.ts +15 -4
  166. package/dist/artifacts/renderers/canvas/controls.d.ts.map +1 -1
  167. package/dist/artifacts/renderers/canvas/focus.d.ts +19 -5
  168. package/dist/artifacts/renderers/canvas/focus.d.ts.map +1 -1
  169. package/dist/artifacts/renderers/canvas/gestures.d.ts +46 -0
  170. package/dist/artifacts/renderers/canvas/gestures.d.ts.map +1 -0
  171. package/dist/artifacts/renderers/canvas/page-resize.d.ts +21 -0
  172. package/dist/artifacts/renderers/canvas/page-resize.d.ts.map +1 -0
  173. package/dist/artifacts/renderers/canvas/page-size-controls.d.ts +21 -0
  174. package/dist/artifacts/renderers/canvas/page-size-controls.d.ts.map +1 -0
  175. package/dist/artifacts/renderers/canvas/page-size.d.ts +93 -0
  176. package/dist/artifacts/renderers/canvas/page-size.d.ts.map +1 -0
  177. package/dist/artifacts/renderers/canvas/page-zoom.d.ts +64 -0
  178. package/dist/artifacts/renderers/canvas/page-zoom.d.ts.map +1 -0
  179. package/dist/artifacts/renderers/canvas/shown-size.d.ts +26 -0
  180. package/dist/artifacts/renderers/canvas/shown-size.d.ts.map +1 -0
  181. package/dist/artifacts/renderers/designed-document.d.ts +28 -0
  182. package/dist/artifacts/renderers/designed-document.d.ts.map +1 -0
  183. package/dist/artifacts/renderers/document-tree.d.ts +2 -0
  184. package/dist/artifacts/renderers/document-tree.d.ts.map +1 -1
  185. package/dist/artifacts/renderers/document.d.ts +9 -1
  186. package/dist/artifacts/renderers/document.d.ts.map +1 -1
  187. package/dist/artifacts/renderers/live-frame.d.ts +145 -0
  188. package/dist/artifacts/renderers/live-frame.d.ts.map +1 -0
  189. package/dist/artifacts/renderers/page-editor.d.ts +16 -0
  190. package/dist/artifacts/renderers/page-editor.d.ts.map +1 -0
  191. package/dist/artifacts/renderers/page.d.ts +10 -1
  192. package/dist/artifacts/renderers/page.d.ts.map +1 -1
  193. package/dist/artifacts/viewer.d.ts.map +1 -1
  194. package/dist/{chunk-001c4gnk.js → chunk-4fex83k2.js} +19965 -13027
  195. package/dist/chunk-4fex83k2.js.map +239 -0
  196. package/dist/{chunk-5crvhjp2.js → chunk-4wm09prf.js} +1633 -1999
  197. package/dist/chunk-4wm09prf.js.map +27 -0
  198. package/dist/{chunk-fwb9mxwm.js → chunk-5sgac68y.js} +1 -1
  199. package/dist/{chunk-kes4ygmz.js → chunk-69qgh20f.js} +1 -1
  200. package/dist/chunk-y51c4tsz.js +11 -0
  201. package/dist/chunk-y51c4tsz.js.map +10 -0
  202. package/dist/index.d.ts +4 -1
  203. package/dist/index.d.ts.map +1 -1
  204. package/dist/index.js +13 -6
  205. package/dist/index.js.map +5 -5
  206. package/dist/pages/console/data/messages.d.ts +6 -0
  207. package/dist/pages/console/data/messages.d.ts.map +1 -1
  208. package/dist/pages/console/data/shared.d.ts.map +1 -1
  209. package/dist/pages.js +12 -5
  210. package/dist/pages.js.map +6 -6
  211. package/dist/shell/search-command.d.ts.map +1 -1
  212. package/package.json +22 -5
  213. package/src/agent/activity-label.ts +9 -1
  214. package/src/agent/agent-chat.tsx +57 -37
  215. package/src/agent/agent-execution-trace.tsx +2 -2
  216. package/src/agent/agent-panel.tsx +6 -4
  217. package/src/agent/agent.css +254 -0
  218. package/src/agent/artifact-panel.tsx +77 -22
  219. package/src/agent/background/background-tool-row.tsx +24 -10
  220. package/src/agent/background/interpret.ts +60 -51
  221. package/src/agent/components/composer-settings.tsx +20 -10
  222. package/src/agent/components/composer.tsx +342 -104
  223. package/src/agent/components/context-meter.tsx +7 -3
  224. package/src/agent/components/conversation-panel.tsx +96 -37
  225. package/src/agent/components/message-parts.tsx +390 -64
  226. package/src/agent/components/message-view.tsx +12 -2
  227. package/src/agent/components/pending-messages.tsx +338 -0
  228. package/src/agent/components/sandbox-recovery.tsx +36 -17
  229. package/src/agent/components/threads-button.tsx +3 -2
  230. package/src/agent/components/transcript.tsx +92 -45
  231. package/src/agent/conversation.ts +203 -54
  232. package/src/agent/delegation/agent-exchange.tsx +53 -0
  233. package/src/agent/delegation/child-card.tsx +6 -40
  234. package/src/agent/delegation/child-parts.tsx +1 -84
  235. package/src/agent/delegation/child-work.tsx +19 -5
  236. package/src/agent/delegation/interpret.ts +64 -61
  237. package/src/agent/delegation/model.ts +1 -1
  238. package/src/agent/file-edits/file-edit-tool-view.tsx +126 -0
  239. package/src/agent/file-edits/interpret.ts +120 -0
  240. package/src/agent/hooks/use-agent-conversation.ts +360 -92
  241. package/src/agent/hooks/use-thread-stream.ts +10 -0
  242. package/src/agent/i18n/en.ts +134 -16
  243. package/src/agent/i18n/fr.ts +122 -16
  244. package/src/agent/inbox-handoff.ts +47 -0
  245. package/src/agent/live-run.ts +23 -2
  246. package/src/agent/message-agent/interpret.ts +4 -3
  247. package/src/agent/publish-artifact/interpret.ts +14 -5
  248. package/src/agent/publish-artifact/publish-artifact-tool-view.tsx +2 -2
  249. package/src/agent/questions/interpret.ts +90 -0
  250. package/src/agent/questions/question-card.tsx +57 -0
  251. package/src/agent/questions/question-composer.tsx +257 -0
  252. package/src/agent/react-router.tsx +2 -2
  253. package/src/agent/read/interpret.ts +34 -1
  254. package/src/agent/read/read-tool-view.tsx +20 -4
  255. package/src/agent/search/interpret.ts +367 -0
  256. package/src/agent/search/search-tool-view.tsx +235 -0
  257. package/src/agent/thread-state.ts +114 -0
  258. package/src/agent/tool-views/built-in.tsx +33 -6
  259. package/src/agent/tool-views/registry.tsx +28 -2
  260. package/src/agent/types.ts +7 -0
  261. package/src/agent/view-file/view-file-tool-view.tsx +33 -19
  262. package/src/agent/waits.ts +50 -0
  263. package/src/artifacts/artifacts.css +434 -0
  264. package/src/artifacts/card-preview.tsx +6 -1
  265. package/src/artifacts/edit-session.tsx +15 -1
  266. package/src/artifacts/editor/block-handle.tsx +278 -0
  267. package/src/artifacts/editor/blocks.ts +216 -0
  268. package/src/artifacts/editor/callout-view.tsx +31 -0
  269. package/src/artifacts/editor/document-editor.tsx +484 -0
  270. package/src/artifacts/editor/figure-view.tsx +66 -0
  271. package/src/artifacts/editor/find-blocks.ts +19 -0
  272. package/src/artifacts/editor/markdown-document.tsx +72 -0
  273. package/src/artifacts/editor/messages.ts +4 -0
  274. package/src/artifacts/editor/schema.ts +159 -0
  275. package/src/artifacts/editor/selection-toolbar.tsx +364 -0
  276. package/src/artifacts/editor/slash-menu.tsx +251 -0
  277. package/src/artifacts/editor/upload.ts +40 -0
  278. package/src/artifacts/file-source.ts +11 -0
  279. package/src/artifacts/frame-editor/bundle.ts +8 -0
  280. package/src/artifacts/frame-editor/commands.ts +565 -0
  281. package/src/artifacts/frame-editor/entry.ts +6 -0
  282. package/src/artifacts/frame-editor/frame.ts +847 -0
  283. package/src/artifacts/frame-editor/generated/editor.txt +149 -0
  284. package/src/artifacts/frame-editor/generated.d.ts +5 -0
  285. package/src/artifacts/frame-editor/keys.ts +323 -0
  286. package/src/artifacts/frame-editor/protocol.ts +151 -0
  287. package/src/artifacts/frame-editor/schema.ts +293 -0
  288. package/src/artifacts/frame-editor/style.ts +58 -0
  289. package/src/artifacts/frame.tsx +14 -5
  290. package/src/artifacts/live/boards.ts +46 -3
  291. package/src/artifacts/live/document.ts +89 -0
  292. package/src/artifacts/live/header.tsx +9 -14
  293. package/src/artifacts/live/presence.ts +5 -1
  294. package/src/artifacts/live/session.ts +4 -2
  295. package/src/artifacts/live/view.ts +14 -8
  296. package/src/artifacts/messages.ts +192 -2
  297. package/src/artifacts/pdf.ts +50 -0
  298. package/src/artifacts/references/references.tsx +46 -11
  299. package/src/artifacts/renderers/canvas/board-editor.tsx +44 -155
  300. package/src/artifacts/renderers/canvas/board.tsx +70 -8
  301. package/src/artifacts/renderers/canvas/canvas.tsx +66 -15
  302. package/src/artifacts/renderers/canvas/comment-pins.tsx +5 -0
  303. package/src/artifacts/renderers/canvas/comments-panel.tsx +58 -1
  304. package/src/artifacts/renderers/canvas/comments.ts +8 -4
  305. package/src/artifacts/renderers/canvas/controls.tsx +64 -30
  306. package/src/artifacts/renderers/canvas/focus.tsx +200 -56
  307. package/src/artifacts/renderers/canvas/gestures.ts +265 -0
  308. package/src/artifacts/renderers/canvas/page-resize.tsx +542 -0
  309. package/src/artifacts/renderers/canvas/page-size-controls.tsx +193 -0
  310. package/src/artifacts/renderers/canvas/page-size.ts +218 -0
  311. package/src/artifacts/renderers/canvas/page-zoom.ts +280 -0
  312. package/src/artifacts/renderers/canvas/shown-size.ts +105 -0
  313. package/src/artifacts/renderers/designed-document.tsx +277 -0
  314. package/src/artifacts/renderers/document-tree.ts +9 -0
  315. package/src/artifacts/renderers/document.tsx +13 -102
  316. package/src/artifacts/renderers/live-frame.ts +163 -0
  317. package/src/artifacts/renderers/page-editor.tsx +613 -0
  318. package/src/artifacts/renderers/page.tsx +21 -4
  319. package/src/artifacts/viewer.tsx +101 -41
  320. package/src/index.ts +8 -0
  321. package/src/pages/console/data/messages.ts +6 -0
  322. package/src/pages/console/data/projections.tsx +4 -0
  323. package/src/pages/console/data/shared.tsx +1 -0
  324. package/src/pages/console/ontology/lineage/trail.tsx +3 -0
  325. package/src/shell/search-command.tsx +2 -0
  326. package/dist/chunk-001c4gnk.js.map +0 -204
  327. package/dist/chunk-5crvhjp2.js.map +0 -28
  328. /package/dist/{chunk-fwb9mxwm.js.map → chunk-5sgac68y.js.map} +0 -0
  329. /package/dist/{chunk-kes4ygmz.js.map → chunk-69qgh20f.js.map} +0 -0
@@ -0,0 +1,847 @@
1
+ import { isArtifactAddress } from "@sixb/core/artifacts"
2
+ import { isPageEntry, LIVE_FILES, PAGE_BODY } from "@sixb/core/artifacts/live"
3
+ import { Editor, Extension } from "@tiptap/core"
4
+ import { Collaboration } from "@tiptap/extension-collaboration"
5
+ import { CollaborationCaret } from "@tiptap/extension-collaboration-caret"
6
+ import { Placeholder } from "@tiptap/extensions"
7
+ import { Fragment, type Node as ProseMirrorNode, Slice } from "@tiptap/pm/model"
8
+ import { NodeSelection, Plugin, PluginKey, Selection, TextSelection } from "@tiptap/pm/state"
9
+ import type { Mappable } from "@tiptap/pm/transform"
10
+ import { Decoration, DecorationSet, type EditorView, type NodeView } from "@tiptap/pm/view"
11
+ import { exitSuggestion, Suggestion, type SuggestionProps } from "@tiptap/suggestion"
12
+ import { Awareness, applyAwarenessUpdate } from "y-protocols/awareness"
13
+ import * as Y from "yjs"
14
+ import { findBlockTypes } from "../editor/find-blocks"
15
+ import {
16
+ blockAt,
17
+ blockKind,
18
+ caretInto,
19
+ dropTarget,
20
+ duplicate,
21
+ insertBlock,
22
+ move,
23
+ moveTo,
24
+ placeAfter,
25
+ placeBlock,
26
+ rectOf,
27
+ remove,
28
+ SINGLE_BLOCK_TAGS,
29
+ tagOf,
30
+ turnable,
31
+ turnInto,
32
+ withoutId,
33
+ words,
34
+ wordsAt,
35
+ } from "./commands"
36
+ import { PageKeys } from "./keys"
37
+ import type {
38
+ AppToEditor,
39
+ EditorCommand,
40
+ EditorRect,
41
+ EditorToApp,
42
+ EditorWords,
43
+ HoverState,
44
+ PageBlockChoice,
45
+ PageMark,
46
+ SelectionState,
47
+ SlashState,
48
+ } from "./protocol"
49
+ import {
50
+ PageImage,
51
+ pageSchemaExtensions,
52
+ RawBlock,
53
+ RawInline,
54
+ sanitize,
55
+ startTag,
56
+ tagAttributes,
57
+ } from "./schema"
58
+ import { PAGE_EDITOR_CSS } from "./style"
59
+
60
+ // A designed document's editor, running in its frame on the page itself: the body is the editor,
61
+ // so the page's stylesheets style what is typed as they style the page. It edits a copy of the
62
+ // live document the app keeps in step through the port, and tells the app what to draw over the
63
+ // frame: the toolbar over selected words, the `/` menu, the handle beside the block the pointer
64
+ // is over, and where a dragged block would land. See ./protocol.ts.
65
+
66
+ /** The origin of what the app sends, which is never sent back. */
67
+ const FROM_APP = Symbol("app")
68
+
69
+ const slashKey = new PluginKey("sixb-page-slash")
70
+ const breaksKey = new PluginKey<DecorationSet>("sixb-page-breaks")
71
+
72
+ /** The tags of each mark the toolbar shows, the first the one it adds. */
73
+ const MARK_TAGS: Readonly<Record<PageMark, readonly string[]>> = {
74
+ bold: ["strong", "b"],
75
+ italic: ["em", "i"],
76
+ underline: ["u"],
77
+ strike: ["s", "del"],
78
+ code: ["code"],
79
+ }
80
+
81
+ const PAGE_BREAKS = ["page", "left", "right", "recto", "verso"]
82
+
83
+ export function startFrameEditor({
84
+ port,
85
+ body,
86
+ }: {
87
+ readonly port: MessagePort
88
+ readonly body: HTMLElement
89
+ }): void {
90
+ const post = (message: EditorToApp) => port.postMessage(message)
91
+ const doc = new Y.Doc()
92
+ const awareness = new Awareness(doc)
93
+ /** Pictures the reader just added, shown from their bytes until a version holds them. */
94
+ const previews = new Map<string, string>()
95
+ let editor: Editor | null = null
96
+ let blocks: readonly PageBlockChoice[] = []
97
+ let slash: {
98
+ items: PageBlockChoice[]
99
+ index: number
100
+ range: { from: number; to: number }
101
+ } | null = null
102
+ let pointer: { x: number; y: number } | null = null
103
+ let dragging = false
104
+ const last = { selection: "", slash: "", hover: "" }
105
+
106
+ // Positions the app was told of, each mapped through every change since, so a command that
107
+ // names one acts on the block it was told of: the menu, a drag or an upload takes a while, and
108
+ // others type meanwhile. One whose block is gone names nothing.
109
+ const told = new Map<number, number | null>()
110
+ const tell = (pos: number | null): number | null => {
111
+ if (pos === null) return null
112
+ told.delete(pos)
113
+ told.set(pos, pos)
114
+ if (told.size > 64) told.delete(told.keys().next().value as number)
115
+ return pos
116
+ }
117
+ const mapTold = (mapping: Mappable) => {
118
+ for (const [reported, current] of told) {
119
+ if (current === null) continue
120
+ const mapped = mapping.mapResult(current, 1)
121
+ told.set(reported, mapped.deletedAfter ? null : mapped.pos)
122
+ }
123
+ }
124
+ /** Where the block the app names by `pos` is now; null when it is gone. */
125
+ const now = (pos: number): number | null => (told.has(pos) ? (told.get(pos) ?? null) : pos)
126
+
127
+ const send = <Key extends keyof typeof last>(key: Key, value: unknown, message: EditorToApp) => {
128
+ const json = JSON.stringify(value)
129
+ if (last[key] === json) return
130
+ last[key] = json
131
+ post(message)
132
+ }
133
+
134
+ // ── What the app draws over the frame ─────────────────────────────────
135
+
136
+ let scheduled = 0
137
+ const schedule = () => {
138
+ if (scheduled) return
139
+ scheduled = requestAnimationFrame(() => {
140
+ scheduled = 0
141
+ report()
142
+ })
143
+ }
144
+
145
+ const report = () => {
146
+ if (!editor) return
147
+ const selection = selectionState(editor)
148
+ send("selection", selection, { type: "selection", selection })
149
+ const menu: SlashState | null =
150
+ slash && editor.isEditable
151
+ ? {
152
+ rect: caretRect(editor.view, slash.range.from),
153
+ items: slash.items.map((item) => item.id),
154
+ index: slash.index,
155
+ }
156
+ : null
157
+ send("slash", menu, { type: "slash", slash: menu })
158
+ if (!dragging) {
159
+ const hover = hoverState(editor)
160
+ if (hover) tell(hover.pos)
161
+ send("hover", hover, { type: "hover", hover })
162
+ }
163
+ }
164
+
165
+ const hoverState = (current: Editor): HoverState | null => {
166
+ if (!pointer || !current.isEditable) return null
167
+ const target = blockAt(current.view, pointer.x, pointer.y)
168
+ const rect = target ? rectOf(current.view.nodeDOM(target.pos)) : null
169
+ if (!target || !rect) return null
170
+ return { pos: target.pos, rect, textual: turnable(current.state.doc, target.pos) }
171
+ }
172
+
173
+ document.addEventListener("mousemove", (event) => {
174
+ pointer = { x: event.clientX, y: event.clientY }
175
+ schedule()
176
+ })
177
+ document.documentElement.addEventListener("mouseleave", () => {
178
+ pointer = null
179
+ schedule()
180
+ })
181
+ window.addEventListener("scroll", schedule, { passive: true })
182
+ window.addEventListener("resize", schedule)
183
+
184
+ // ── The `/` menu ──────────────────────────────────────────────────────
185
+
186
+ const openMenu = (props: SuggestionProps<PageBlockChoice>) => {
187
+ const keep = slash !== null && slash.items.length === props.items.length
188
+ slash = {
189
+ items: props.items,
190
+ index: keep && slash ? Math.min(slash.index, Math.max(0, props.items.length - 1)) : 0,
191
+ range: props.range,
192
+ }
193
+ schedule()
194
+ }
195
+
196
+ const choose = (index: number) => {
197
+ const current = editor
198
+ const item = slash?.items[index]
199
+ const range = slash?.range
200
+ if (!current || !item || !range) return
201
+ slash = null
202
+ if (item.id === "image") {
203
+ current.chain().focus().deleteRange(range).run()
204
+ post({ type: "pickImage", at: tell(wordsAt(current.state.selection)?.pos ?? null) })
205
+ return
206
+ }
207
+ insertBlock(current, item.id, range)
208
+ }
209
+
210
+ const SlashMenu = Extension.create({
211
+ name: "pageSlash",
212
+ addProseMirrorPlugins() {
213
+ return [
214
+ Suggestion<PageBlockChoice>({
215
+ editor: this.editor,
216
+ pluginKey: slashKey,
217
+ char: "/",
218
+ // Not in `<pre>`, where `/` is a character like any other.
219
+ allow: ({ state, range }) => {
220
+ const parent = state.doc.resolve(range.from).parent
221
+ return parent.type.name === "textBlock" && tagOf(parent) !== "pre"
222
+ },
223
+ items: ({ query }) => findBlockTypes(blocks, query),
224
+ command: () => {},
225
+ render: () => ({
226
+ onStart: openMenu,
227
+ onUpdate: openMenu,
228
+ onKeyDown: ({ event }) => {
229
+ if (!slash) return false
230
+ const count = slash.items.length
231
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
232
+ if (count > 0) {
233
+ const by = event.key === "ArrowDown" ? 1 : -1
234
+ slash.index = (slash.index + by + count) % count
235
+ schedule()
236
+ }
237
+ return true
238
+ }
239
+ if (event.key === "Enter" || event.key === "Tab") {
240
+ if (count === 0) return false
241
+ choose(slash.index)
242
+ return true
243
+ }
244
+ return false
245
+ },
246
+ onExit: () => {
247
+ slash = null
248
+ schedule()
249
+ },
250
+ }),
251
+ }),
252
+ ]
253
+ },
254
+ })
255
+
256
+ // ── Page breaks, as the sheet shows them ──────────────────────────────
257
+
258
+ let pageBreakLabel = ""
259
+ const PageBreaks = Extension.create({
260
+ name: "pageBreaks",
261
+ addProseMirrorPlugins() {
262
+ return [
263
+ new Plugin<DecorationSet>({
264
+ key: breaksKey,
265
+ state: {
266
+ init: () => DecorationSet.empty,
267
+ apply: (tr, set) =>
268
+ (tr.getMeta(breaksKey) as DecorationSet | undefined) ?? set.map(tr.mapping, tr.doc),
269
+ },
270
+ props: { decorations: (state) => breaksKey.getState(state) },
271
+ view: (view) => {
272
+ let timer: ReturnType<typeof setTimeout> | undefined
273
+ let shown = ""
274
+ const measure = () => {
275
+ const at = pageBreaks(view)
276
+ const key = at.join(",")
277
+ if (key === shown) return
278
+ shown = key
279
+ const set = DecorationSet.create(
280
+ view.state.doc,
281
+ at.map((pos) =>
282
+ Decoration.widget(pos, () => pageBreak(pageBreakLabel), {
283
+ side: -1,
284
+ ignoreSelection: true,
285
+ key: `break-${pos}`,
286
+ })
287
+ )
288
+ )
289
+ view.dispatch(view.state.tr.setMeta(breaksKey, set).setMeta("addToHistory", false))
290
+ }
291
+ const later = () => {
292
+ clearTimeout(timer)
293
+ timer = setTimeout(measure, 120)
294
+ }
295
+ later()
296
+ document.fonts?.ready.then(later)
297
+ // Where the page breaks moves with its blocks and its width, never with the caret.
298
+ window.addEventListener("resize", later)
299
+ return {
300
+ update: (_view, previous) => {
301
+ if (view.state.doc !== previous.doc) later()
302
+ },
303
+ destroy: () => {
304
+ clearTimeout(timer)
305
+ window.removeEventListener("resize", later)
306
+ },
307
+ }
308
+ },
309
+ }),
310
+ ]
311
+ },
312
+ })
313
+
314
+ // ── Marks and links ───────────────────────────────────────────────────
315
+
316
+ const toggleMark = (current: Editor, mark: PageMark) => {
317
+ const tags = MARK_TAGS[mark]
318
+ const chain = current.chain().focus()
319
+ if (tags.some((tag) => current.isActive(tag))) {
320
+ for (const tag of tags) chain.unsetMark(tag)
321
+ } else {
322
+ const tag = tags[0] as string
323
+ chain.setMark(tag, { open: `<${tag}>`, close: `</${tag}>` })
324
+ }
325
+ chain.run()
326
+ }
327
+
328
+ const setLink = (current: Editor, href: string | null) => {
329
+ const chain = current.chain().focus().extendMarkRange("a")
330
+ if (href === null) {
331
+ chain.unsetMark("a").run()
332
+ return
333
+ }
334
+ // A link keeps whatever else its tag says, its class among them.
335
+ const attrs = { ...tagAttributes(current.getAttributes("a").open as string | undefined), href }
336
+ chain.setMark("a", { open: startTag("a", attrs), close: "</a>" }).run()
337
+ }
338
+
339
+ // ── What the app asks ─────────────────────────────────────────────────
340
+
341
+ const run = (current: Editor, given: EditorCommand) => {
342
+ const { state } = current
343
+ let command = given
344
+ if ("pos" in command && command.pos !== undefined) {
345
+ const pos = now(command.pos)
346
+ // The block it named is gone, or no longer starts there: it does nothing.
347
+ if (pos === null || !state.doc.nodeAt(pos)?.isBlock) {
348
+ if (command.name === "drag" || command.name === "drop") post({ type: "drop", line: null })
349
+ return
350
+ }
351
+ command = { ...command, pos }
352
+ }
353
+ if (command.name === "image" && command.at !== undefined) {
354
+ const { at: told, ...rest } = command
355
+ const at = now(told)
356
+ command = at === null ? rest : { ...rest, at }
357
+ }
358
+ switch (command.name) {
359
+ case "mark":
360
+ return toggleMark(current, command.mark)
361
+ case "link":
362
+ return setLink(current, command.href)
363
+ case "turnInto":
364
+ return void turnInto(current, command.block, command.pos)
365
+ case "choose":
366
+ return choose(command.index)
367
+ case "point":
368
+ if (slash) slash.index = command.index
369
+ return schedule()
370
+ case "closeMenu":
371
+ return exitSuggestion(current.view, slashKey)
372
+ case "addBelow": {
373
+ const node = state.doc.nodeAt(command.pos)
374
+ if (!node) return
375
+ const tr = state.tr
376
+ let at = command.pos
377
+ if (node.type.name === "textBlock" && tagOf(node) === "li") {
378
+ at = command.pos + node.nodeSize
379
+ const open =
380
+ typeof node.attrs.open === "string" ? withoutId(node.attrs.open, "li") : undefined
381
+ tr.insert(at, words(current.schema, "li", open))
382
+ } else if (
383
+ node.type.name !== "textBlock" ||
384
+ node.content.size > 0 ||
385
+ SINGLE_BLOCK_TAGS.has(tagOf(node))
386
+ ) {
387
+ at = placeAfter(state.doc, command.pos)
388
+ tr.insert(at, words(current.schema, "p"))
389
+ }
390
+ tr.setSelection(TextSelection.create(tr.doc, at + 1)).insertText("/")
391
+ current.view.dispatch(tr.scrollIntoView())
392
+ current.view.focus()
393
+ return
394
+ }
395
+ case "duplicate":
396
+ return void duplicate(current, command.pos)
397
+ case "remove":
398
+ return void remove(current, command.pos)
399
+ case "move":
400
+ return void move(current, command.pos, command.by)
401
+ case "pick": {
402
+ if (!state.doc.nodeAt(command.pos)) return
403
+ // Not focused: the app's menu for it keeps the focus while it is open.
404
+ current.view.dispatch(state.tr.setSelection(NodeSelection.create(state.doc, command.pos)))
405
+ return
406
+ }
407
+ case "drag": {
408
+ dragging = true
409
+ const target = dropTarget(current.view, command.pos, command.x, command.y)
410
+ post({ type: "drop", line: target?.line ?? null })
411
+ // Near the frame's top or bottom edge, the page scrolls to where the block is going.
412
+ const edge = 56
413
+ if (command.y < edge) window.scrollBy(0, -Math.ceil((edge - command.y) / 3))
414
+ else if (command.y > window.innerHeight - edge) {
415
+ window.scrollBy(0, Math.ceil((command.y - window.innerHeight + edge) / 3))
416
+ }
417
+ return
418
+ }
419
+ case "drop": {
420
+ const target = dropTarget(current.view, command.pos, command.x, command.y)
421
+ if (target) moveTo(current, command.pos, target.at)
422
+ dragging = false
423
+ post({ type: "drop", line: null })
424
+ return schedule()
425
+ }
426
+ case "endDrag":
427
+ dragging = false
428
+ post({ type: "drop", line: null })
429
+ return schedule()
430
+ case "image": {
431
+ if (command.preview) previews.set(command.src, URL.createObjectURL(command.preview))
432
+ const image = current.schema.nodes.image.create({
433
+ source: startTag("img", { src: command.src, alt: command.alt }),
434
+ })
435
+ const tr = state.tr
436
+ const target = command.at ?? wordsAt(state.selection)?.pos
437
+ let placed = tr.doc.content.size
438
+ if (target === undefined || target === null || !tr.doc.nodeAt(target)) {
439
+ tr.insert(placed, image)
440
+ } else {
441
+ placed = placeBlock(tr, target, image)
442
+ }
443
+ caretInto(tr, placed)
444
+ current.view.dispatch(tr.scrollIntoView())
445
+ current.view.focus()
446
+ return
447
+ }
448
+ case "focus":
449
+ current.commands.focus()
450
+ return
451
+ }
452
+ }
453
+
454
+ // ── The editor ────────────────────────────────────────────────────────
455
+
456
+ const mount = (fragment: Y.XmlFragment, editable: boolean, text: EditorWords) => {
457
+ pageBreakLabel = text.pageBreak
458
+ const style = document.createElement("style")
459
+ style.id = "sixb-page-editor"
460
+ style.textContent = PAGE_EDITOR_CSS
461
+ document.head.append(style)
462
+
463
+ // The page the frame loaded gives way to the live one, which the editor draws.
464
+ const bodyClass = body.getAttribute("class")
465
+ body.replaceChildren()
466
+ const extensions = pageSchemaExtensions().map((extension) => {
467
+ if (extension.name === RawBlock.name) {
468
+ return RawBlock.extend({
469
+ addNodeView:
470
+ () =>
471
+ ({ node }) =>
472
+ rawView(node, false),
473
+ })
474
+ }
475
+ if (extension.name === RawInline.name) {
476
+ return RawInline.extend({
477
+ addNodeView:
478
+ () =>
479
+ ({ node }) =>
480
+ rawView(node, true),
481
+ })
482
+ }
483
+ if (extension.name === PageImage.name) {
484
+ return PageImage.extend({
485
+ addNodeView:
486
+ () =>
487
+ ({ node }) =>
488
+ imageView(node, previews),
489
+ })
490
+ }
491
+ return extension
492
+ })
493
+
494
+ const current = new Editor({
495
+ element: { mount: body },
496
+ injectCSS: false,
497
+ editable,
498
+ extensions: [
499
+ ...extensions,
500
+ Collaboration.configure({ fragment }),
501
+ CollaborationCaret.configure({
502
+ provider: { awareness },
503
+ // Who someone is, the server says: what this reader says of itself is replaced.
504
+ user: {},
505
+ render: caret,
506
+ selectionRender: (user: { readonly color?: string }) => ({
507
+ nodeName: "span",
508
+ class: "sixb-caret-selection",
509
+ style: `--caret: ${user.color ?? "#888"}`,
510
+ }),
511
+ }),
512
+ Placeholder.configure({
513
+ includeChildren: true,
514
+ showOnlyCurrent: true,
515
+ placeholder: ({ node }) => placeholder(node, text),
516
+ }),
517
+ PageKeys.configure({ toggleMark, onLink: () => post({ type: "linkRequest" }) }),
518
+ SlashMenu,
519
+ PageBreaks,
520
+ ],
521
+ editorProps: {
522
+ attributes: bodyClass ? { class: bodyClass } : {},
523
+ // A link is for reading: in the editor, a click puts the caret in its words.
524
+ handleDOMEvents: {
525
+ click: (_view, event) => {
526
+ if ((event.target as Element | null)?.closest?.("a[href]")) event.preventDefault()
527
+ return false
528
+ },
529
+ },
530
+ handlePaste: (view, event) => {
531
+ const files = imagesOf(event.clipboardData)
532
+ if (files.length === 0) return false
533
+ post({ type: "upload", files, at: tell(wordsAt(view.state.selection)?.pos ?? null) })
534
+ return true
535
+ },
536
+ handleDrop: (view, event, _slice, moved) => {
537
+ const files = imagesOf(event.dataTransfer)
538
+ if (moved || files.length === 0) return false
539
+ event.preventDefault()
540
+ const at = blockAt(view, event.clientX, event.clientY)
541
+ post({ type: "upload", files, at: tell(at?.pos ?? null) })
542
+ return true
543
+ },
544
+ // What is pasted from elsewhere brings its words and structure, not its styles.
545
+ transformPastedHTML: (html) => (html.includes("data-pm-slice") ? html : plainHtml(html)),
546
+ // And of its pictures, only the artifact's own: the page could not be saved with any
547
+ // other.
548
+ transformPasted: (slice) => {
549
+ const files = doc.getMap<unknown>(LIVE_FILES)
550
+ const content = withOwnImages(slice.content, (src) => isOwnImage(src, files))
551
+ if (content === slice.content) return slice
552
+ const open = Slice.maxOpen(content)
553
+ return new Slice(
554
+ content,
555
+ Math.min(slice.openStart, open.openStart),
556
+ Math.min(slice.openEnd, open.openEnd)
557
+ )
558
+ },
559
+ },
560
+ // The live blocks replace the empty page the editor starts with, and the caret it had there
561
+ // lands in a box: it starts at the first words instead.
562
+ onCreate: ({ editor: created }) => {
563
+ // A page with no blocks yet gets one to type in.
564
+ if (created.isEditable && fragment.length === 0) {
565
+ created.view.dispatch(
566
+ created.state.tr.replaceWith(
567
+ 0,
568
+ created.state.doc.content.size,
569
+ words(created.schema, "p")
570
+ )
571
+ )
572
+ }
573
+ const start = Selection.atStart(created.state.doc)
574
+ created.view.dispatch(created.state.tr.setSelection(start).setMeta("addToHistory", false))
575
+ },
576
+ onTransaction: ({ transaction }) => {
577
+ if (transaction.docChanged) mapTold(transaction.mapping)
578
+ schedule()
579
+ },
580
+ onSelectionUpdate: schedule,
581
+ onFocus: () => {
582
+ post({ type: "focus", focused: true })
583
+ schedule()
584
+ },
585
+ onBlur: () => post({ type: "focus", focused: false }),
586
+ })
587
+ editor = current
588
+ schedule()
589
+ }
590
+
591
+ port.onmessage = (event: MessageEvent<AppToEditor>) => {
592
+ const message = event.data
593
+ switch (message.type) {
594
+ case "start": {
595
+ Y.applyUpdate(doc, message.state, FROM_APP)
596
+ blocks = message.blocks
597
+ const files = doc.getMap<unknown>(LIVE_FILES)
598
+ const entry = files.get(message.path)
599
+ if (!isPageEntry(entry)) {
600
+ post({ type: "gone" })
601
+ return
602
+ }
603
+ doc.on("update", (update: Uint8Array, origin: unknown) => {
604
+ if (origin !== FROM_APP) post({ type: "update", update })
605
+ })
606
+ files.observe((change) => {
607
+ if (!change.keysChanged.has(message.path) || files.get(message.path) === entry) return
608
+ editor?.setEditable(false)
609
+ post({ type: "gone" })
610
+ })
611
+ awareness.on("update", (_changes: unknown, origin: unknown) => {
612
+ if (origin === FROM_APP) return
613
+ post({ type: "cursor", cursor: awareness.getLocalState()?.cursor ?? null })
614
+ })
615
+ mount(entry.get(PAGE_BODY) as Y.XmlFragment, message.editable, message.words)
616
+ return
617
+ }
618
+ case "update":
619
+ Y.applyUpdate(doc, message.update, FROM_APP)
620
+ return
621
+ case "awareness":
622
+ applyAwarenessUpdate(awareness, message.update, FROM_APP)
623
+ return
624
+ case "editable":
625
+ editor?.setEditable(message.editable)
626
+ schedule()
627
+ return
628
+ case "run":
629
+ if (editor) run(editor, message.command)
630
+ return
631
+ }
632
+ }
633
+ post({ type: "ready" })
634
+ }
635
+
636
+ /** The toolbar's state for selected words; null for none, or for a block picked whole. */
637
+ function selectionState(editor: Editor): SelectionState | null {
638
+ const { selection } = editor.state
639
+ if (!editor.isEditable || !(selection instanceof TextSelection) || selection.empty) return null
640
+ const parent = selection.$from.parent
641
+ if (parent.type.name !== "textBlock" || tagOf(parent) === "pre") return null
642
+ const view = editor.view
643
+ const start = view.coordsAtPos(selection.from)
644
+ const end = view.coordsAtPos(selection.to)
645
+ const block = rectOf(view.nodeDOM(selection.$from.before()))
646
+ const oneLine = Math.abs(start.top - end.top) < 2
647
+ const rect: EditorRect = {
648
+ left: oneLine ? Math.min(start.left, end.left) : (block?.left ?? start.left),
649
+ right: oneLine ? Math.max(start.right, end.right) : (block?.right ?? end.right),
650
+ top: Math.min(start.top, end.top),
651
+ bottom: Math.max(start.bottom, end.bottom),
652
+ }
653
+ const active = (tags: readonly string[]) => tags.some((tag) => editor.isActive(tag))
654
+ const link = editor.isActive("a")
655
+ ? (tagAttributes(editor.getAttributes("a").open as string | undefined).href ?? "")
656
+ : null
657
+ return {
658
+ rect,
659
+ marks: {
660
+ bold: active(MARK_TAGS.bold),
661
+ italic: active(MARK_TAGS.italic),
662
+ underline: active(MARK_TAGS.underline),
663
+ strike: active(MARK_TAGS.strike),
664
+ code: active(MARK_TAGS.code),
665
+ },
666
+ link,
667
+ block: blockKind(selection.$from),
668
+ turnable: turnable(editor.state.doc, selection.$from.before()),
669
+ }
670
+ }
671
+
672
+ function caretRect(view: EditorView, pos: number): EditorRect {
673
+ const at = view.coordsAtPos(pos)
674
+ return { left: at.left, top: at.top, right: at.right, bottom: at.bottom }
675
+ }
676
+
677
+ /**
678
+ * Where the page breaks, as the frame's runtime marks them on one sheet: before a block whose
679
+ * style breaks the page before it, after one whose style breaks it after, never in a flex or grid
680
+ * layout, nor before what starts the sheet.
681
+ */
682
+ function pageBreaks(view: EditorView): number[] {
683
+ const found = new Set<number>()
684
+ const top =
685
+ view.dom.getBoundingClientRect().top +
686
+ Number.parseFloat(getComputedStyle(view.dom).paddingTop || "0")
687
+ view.state.doc.descendants((node, pos) => {
688
+ if (!node.isBlock) return false
689
+ const dom = view.nodeDOM(pos)
690
+ if (!(dom instanceof HTMLElement)) return false
691
+ const parent = dom.parentElement
692
+ if (parent && /flex|grid/.test(getComputedStyle(parent).display)) return false
693
+ const style = getComputedStyle(dom)
694
+ if (PAGE_BREAKS.includes(style.breakBefore) && dom.getBoundingClientRect().top > top + 1) {
695
+ found.add(pos)
696
+ }
697
+ if (PAGE_BREAKS.includes(style.breakAfter)) found.add(pos + node.nodeSize)
698
+ return node.type.name === "box"
699
+ })
700
+ return [...found].sort((left, right) => left - right)
701
+ }
702
+
703
+ function pageBreak(label: string): HTMLElement {
704
+ const element = document.createElement("div")
705
+ element.className = "sixb-page-break"
706
+ element.contentEditable = "false"
707
+ element.setAttribute("aria-hidden", "true")
708
+ element.setAttribute("data-label", label)
709
+ return element
710
+ }
711
+
712
+ /** Markup kept as it was written, drawn from its source; nothing in it takes typing. */
713
+ function rawView(node: ProseMirrorNode, inline: boolean): NodeView {
714
+ const template = document.createElement("template")
715
+ template.innerHTML = String(node.attrs.source ?? "")
716
+ sanitize(template.content)
717
+ const nodes = Array.from(template.content.childNodes)
718
+ const only = nodes.length === 1 && nodes[0] instanceof HTMLElement ? nodes[0] : null
719
+ const dom = only ?? document.createElement(inline ? "span" : "div")
720
+ if (!only) {
721
+ dom.style.display = "contents"
722
+ dom.append(...nodes)
723
+ }
724
+ dom.setAttribute("data-sixb-raw", "")
725
+ dom.contentEditable = "false"
726
+ return {
727
+ dom,
728
+ ignoreMutation: () => true,
729
+ update: (next) => next.type === node.type && next.attrs.source === node.attrs.source,
730
+ }
731
+ }
732
+
733
+ /** A picture, shown from the bytes just added when no version holds it yet. */
734
+ function imageView(node: ProseMirrorNode, previews: ReadonlyMap<string, string>): NodeView {
735
+ const image = document.createElement("img")
736
+ const show = (current: ProseMirrorNode) => {
737
+ const attrs = tagAttributes(current.attrs.source as string | null)
738
+ for (const name of image.getAttributeNames()) if (!(name in attrs)) image.removeAttribute(name)
739
+ for (const [name, value] of Object.entries(attrs)) image.setAttribute(name, value)
740
+ const preview = previews.get(attrs.src ?? "")
741
+ if (preview) image.src = preview
742
+ }
743
+ show(node)
744
+ image.draggable = false
745
+ return {
746
+ dom: image,
747
+ ignoreMutation: () => true,
748
+ update: (next) => {
749
+ if (next.type !== node.type) return false
750
+ show(next)
751
+ return true
752
+ },
753
+ }
754
+ }
755
+
756
+ /** Another editor's caret: a line in their color, their name above it. */
757
+ function caret(user: { readonly name?: string; readonly color?: string }): HTMLElement {
758
+ const element = document.createElement("span")
759
+ element.className = "sixb-caret"
760
+ element.style.setProperty("--caret", user.color ?? "#888")
761
+ const label = document.createElement("span")
762
+ label.className = "sixb-caret-label"
763
+ label.textContent = user.name || "·"
764
+ element.append(label)
765
+ return element
766
+ }
767
+
768
+ function placeholder(node: ProseMirrorNode, text: EditorWords): string {
769
+ if (node.type.name !== "textBlock") return ""
770
+ const tag = tagOf(node)
771
+ if (tag === "li") return text.listItem
772
+ const heading = /^h([1-6])$/.exec(tag)
773
+ if (heading) return text.headings[Number(heading[1]) - 1] ?? ""
774
+ return SINGLE_BLOCK_TAGS.has(tag) ? "" : text.placeholder
775
+ }
776
+
777
+ function imagesOf(data: DataTransfer | null | undefined): File[] {
778
+ return Array.from(data?.files ?? []).filter((file) => file.type.startsWith("image/"))
779
+ }
780
+
781
+ /**
782
+ * `content` without the pictures `own` does not take, nor the markup kept as written that shows
783
+ * one; the same fragment when it holds none. A box they leave empty gets what it must hold.
784
+ */
785
+ function withOwnImages(content: Fragment, own: (src: string) => boolean): Fragment {
786
+ let changed = false
787
+ const kept: ProseMirrorNode[] = []
788
+ content.forEach((node) => {
789
+ const source = node.attrs.source
790
+ if (node.isAtom && typeof source === "string" && !imageSources(source).every(own)) {
791
+ changed = true
792
+ return
793
+ }
794
+
795
+ const inner = node.isLeaf ? node.content : withOwnImages(node.content, own)
796
+ if (inner === node.content) {
797
+ kept.push(node)
798
+ return
799
+ }
800
+ changed = true
801
+ // Words that were pictures alone go with them.
802
+ if (node.isTextblock && inner.size === 0) return
803
+ const rebuilt = node.type.createAndFill(node.attrs, inner, node.marks)
804
+ if (rebuilt) kept.push(rebuilt)
805
+ })
806
+ return changed ? Fragment.from(kept) : content
807
+ }
808
+
809
+ /** Where the pictures of markup point. */
810
+ function imageSources(source: string): string[] {
811
+ const template = document.createElement("template")
812
+ template.innerHTML = source
813
+ return Array.from(template.content.querySelectorAll("img[src]"), (image) =>
814
+ (image.getAttribute("src") ?? "").trim()
815
+ )
816
+ }
817
+
818
+ /** Whether publishing takes a picture: another artifact's, or one of `files` by its path. */
819
+ function isOwnImage(src: string, files: Y.Map<unknown>): boolean {
820
+ if (isArtifactAddress(src)) return true
821
+ if (src === "" || src.startsWith("/") || /^[a-z][a-z\d+.-]*:/i.test(src)) return false
822
+ let path = src.split(/[?#]/)[0] ?? ""
823
+ try {
824
+ path = decodeURI(path)
825
+ } catch {
826
+ // Kept as written: it simply names no file.
827
+ }
828
+ const segments: string[] = []
829
+ for (const segment of path.split("/")) {
830
+ if (segment === "..") segments.pop()
831
+ else if (segment !== "" && segment !== ".") segments.push(segment)
832
+ }
833
+ return files.has(segments.join("/"))
834
+ }
835
+
836
+ /** Markup pasted from elsewhere without its attributes, but for where a link or picture points. */
837
+ function plainHtml(html: string): string {
838
+ const template = document.createElement("template")
839
+ template.innerHTML = html
840
+ const keep = new Set(["href", "src", "alt", "colspan", "rowspan"])
841
+ for (const element of Array.from(template.content.querySelectorAll("*"))) {
842
+ for (const name of element.getAttributeNames()) {
843
+ if (!keep.has(name)) element.removeAttribute(name)
844
+ }
845
+ }
846
+ return template.innerHTML
847
+ }