platejs 54.0.0-beta.6 → 54.0.0-beta.8

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 (312) hide show
  1. package/dist/{AIChatRequestContext-BYpGufVe.d.ts → AIChatRequestContext-PbXTTovP.d.ts} +4 -2
  2. package/dist/{BaseSuggestionPlugin-C52LR8RN.d.ts → BaseSuggestionPlugin-Dg-cdX26.d.ts} +14 -7
  3. package/dist/{PlateStatic-DMClx-tH.d.ts → PlateStatic-CggiBCuD.d.ts} +3 -3
  4. package/dist/ai/index.d.ts +40 -2
  5. package/dist/ai/index.js +2 -1
  6. package/dist/ai/lib/lockedContext.internal.js +105 -0
  7. package/dist/ai/lib/lockedContext.js +179 -0
  8. package/dist/ai/react/AIChatPlugin.js +510 -109
  9. package/dist/ai/react/CopilotPlugin.js +46 -10
  10. package/dist/ai/react/aiOutputLanding.internal.js +19 -4
  11. package/dist/ai/react/index.d.ts +127 -82
  12. package/dist/ai/react/useAIChat.js +41 -36
  13. package/dist/authored/index.d.ts +4 -4
  14. package/dist/authored/index.js +2 -2
  15. package/dist/code-block/codemirror/index.d.ts +1 -1
  16. package/dist/{combobox-DgYdu5mZ.d.ts → combobox-CUUSZR07.d.ts} +2 -2
  17. package/dist/compiler/index.d.ts +2 -2
  18. package/dist/{core-CQKT9eNc.d.ts → core-D8i_gkA6.d.ts} +583 -579
  19. package/dist/core.js +1 -2
  20. package/dist/diff/index.d.ts +3 -30
  21. package/dist/docs/annotations.md +37 -120
  22. package/dist/docs/api/core/plate-components.md +5 -4
  23. package/dist/docs/api/core/plate-plugin.md +11 -10
  24. package/dist/docs/api/core/plate-store.md +5 -5
  25. package/dist/docs/api/core.md +41 -69
  26. package/dist/docs/api/document-change.md +38 -10
  27. package/dist/docs/api/editor-api.md +19 -16
  28. package/dist/docs/api/editor-transforms.md +27 -8
  29. package/dist/docs/api/react-hooks.md +112 -133
  30. package/dist/docs/authored-changes.md +21 -19
  31. package/dist/docs/board.md +48 -37
  32. package/dist/docs/bold.md +0 -2
  33. package/dist/docs/clipboard.md +11 -7
  34. package/dist/docs/decorations.md +3 -4
  35. package/dist/docs/dnd.md +1 -1
  36. package/dist/docs/document-model.md +3 -3
  37. package/dist/docs/docx.md +50 -4
  38. package/dist/docs/editor-methods.md +10 -19
  39. package/dist/docs/editor.md +22 -66
  40. package/dist/docs/examples/version-history.md +1 -1
  41. package/dist/docs/field.md +120 -54
  42. package/dist/docs/find.md +36 -28
  43. package/dist/docs/footnote.md +94 -36
  44. package/dist/docs/history.md +166 -12
  45. package/dist/docs/html.md +10 -5
  46. package/dist/docs/indent.md +7 -5
  47. package/dist/docs/ink.md +229 -0
  48. package/dist/docs/installation/node.md +1 -1
  49. package/dist/docs/installation/plate-ui.md +16 -0
  50. package/dist/docs/list.md +23 -3
  51. package/dist/docs/llms.txt +7 -6
  52. package/dist/docs/lock.md +264 -0
  53. package/dist/docs/markdown.md +17 -99
  54. package/dist/docs/plugin-context.md +14 -10
  55. package/dist/docs/roots.md +92 -28
  56. package/dist/docs/schema.md +5 -3
  57. package/dist/docs/serializing.md +26 -3
  58. package/dist/docs/static.md +19 -5
  59. package/dist/docs/suggestion.md +27 -14
  60. package/dist/docs/table.md +2 -2
  61. package/dist/docs/toc.md +2 -2
  62. package/dist/docx/export/index.d.ts +3 -3
  63. package/dist/docx/export/lib/comments.js +124 -44
  64. package/dist/docx/export/lib/exportDocx.js +89 -34
  65. package/dist/docx/export/lib/hostIndex.js +92 -0
  66. package/dist/docx/export/lib/reviewProjection.js +154 -55
  67. package/dist/docx/import/index.d.ts +4 -4
  68. package/dist/docx/paste/index.d.ts +4 -4
  69. package/dist/dom/index.d.ts +2 -2
  70. package/dist/dom/plite-dom.internal.js +2 -2
  71. package/dist/excalidraw/index.d.ts +3 -3
  72. package/dist/excalidraw/react/index.d.ts +3 -3
  73. package/dist/facade.js +3 -3
  74. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +1 -1
  75. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +31 -8
  76. package/dist/features/basic-nodes/lib/BaseMarkPlugins.js +64 -12
  77. package/dist/features/basic-styles/lib/BaseFormattingPlugin.js +5 -2
  78. package/dist/features/board/index.d.ts +2 -2
  79. package/dist/features/board/index.js +2 -1
  80. package/dist/features/board/lib/BaseBoardPlugin.js +80 -22
  81. package/dist/features/board/lib/BaseBoardTextPlugin.js +12 -0
  82. package/dist/features/board/lib/boardArrow.internal.js +2 -2
  83. package/dist/features/board/lib/boardHeights.internal.js +57 -0
  84. package/dist/features/board/lib/boardHtml.internal.js +18 -1
  85. package/dist/features/board/lib/boardMember.internal.js +2 -2
  86. package/dist/features/board/lib/boardShape.internal.js +6 -1
  87. package/dist/features/board/lib/boardStyle.internal.js +5 -1
  88. package/dist/features/board/lib/boardTypes.internal.js +7 -1
  89. package/dist/features/callout/index.d.ts +3 -3
  90. package/dist/features/callout/lib/BaseCalloutPlugin.js +1 -4
  91. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +1 -2
  92. package/dist/features/combobox/index.d.ts +2 -2
  93. package/dist/features/combobox/lib/filterWords.js +7 -11
  94. package/dist/features/comments/BaseCommentsPlugin.js +47 -227
  95. package/dist/features/comments/comment-thread-index.internal.js +822 -0
  96. package/dist/features/comments/index.d.ts +2 -2
  97. package/dist/features/date/index.d.ts +3 -3
  98. package/dist/features/details/index.d.ts +4 -3
  99. package/dist/features/details/lib/BaseDetailsPlugin.js +228 -122
  100. package/dist/features/field/index.d.ts +2 -2
  101. package/dist/features/field/lib/BaseFieldPlugin.js +166 -53
  102. package/dist/features/field/lib/applyFieldValues.js +45 -26
  103. package/dist/features/field/lib/fieldRules.internal.js +518 -100
  104. package/dist/features/find/index.d.ts +15 -16
  105. package/dist/features/find/lib/BaseFindPlugin.js +871 -123
  106. package/dist/features/footnote/index.d.ts +1 -1
  107. package/dist/features/footnote/lib/BaseFootnotePlugin.js +44 -17
  108. package/dist/features/ink/index.d.ts +2 -2
  109. package/dist/features/ink/lib/BaseInkPlugin.js +477 -80
  110. package/dist/features/ink/lib/inkAnchor.internal.js +436 -0
  111. package/dist/features/ink/lib/inkMatch.internal.js +276 -64
  112. package/dist/features/ink/lib/inkPlaces.internal.js +172 -500
  113. package/dist/features/ink/lib/inkReflow.internal.js +406 -0
  114. package/dist/features/layout/index.d.ts +1 -1
  115. package/dist/features/layout/lib/BaseColumnPlugin.js +37 -14
  116. package/dist/features/link/lib/BaseLinkPlugin.js +38 -3
  117. package/dist/features/lint/index.d.ts +16 -16
  118. package/dist/features/list/lib/BaseListPlugin.js +32 -12
  119. package/dist/features/list/lib/listFamily.internal.js +2 -2
  120. package/dist/features/list/lib/listHtml.internal.js +1 -0
  121. package/dist/features/lock/index.d.ts +2 -0
  122. package/dist/features/lock/index.js +2 -0
  123. package/dist/features/lock/lib/BaseLockPlugin.js +526 -0
  124. package/dist/features/media/index.d.ts +1 -1
  125. package/dist/features/media/lib/media-embed/BaseMediaEmbedPlugin.js +2 -1
  126. package/dist/features/mention/index.d.ts +5 -5
  127. package/dist/features/suggestion/index.d.ts +1 -1
  128. package/dist/features/table/index.d.ts +1 -1
  129. package/dist/features/table/lib/BaseTablePlugin.js +284 -142
  130. package/dist/features/toc/index.d.ts +1 -1
  131. package/dist/features/upload/index.d.ts +1 -1
  132. package/dist/features/upload/lib/BaseUploadPlugin.js +10 -8
  133. package/dist/history/index.d.ts +3 -3
  134. package/dist/history/index.js +2 -1
  135. package/dist/html/index.d.ts +3 -3
  136. package/dist/html/server/index.d.ts +1 -1
  137. package/dist/html/server/index.js +2 -1
  138. package/dist/html/server/serverCssParser.internal.js +500 -0
  139. package/dist/html/server/serverCssStyle.internal.js +208 -0
  140. package/dist/{htmlTypes-8IFX0ezP.d.ts → htmlTypes-zTLU3aTb.d.ts} +10 -14
  141. package/dist/hyperscript/index.d.ts +1 -1
  142. package/dist/index-0YxPsHwd.d.ts +1 -0
  143. package/dist/{index-D2w_9_tb.d.ts → index-3CExu_fj.d.ts} +32 -32
  144. package/dist/{index-PDROnF1G-Ds_dbJsr.d.ts → index-4PpawhYe-yelJvgk1.d.ts} +1 -1
  145. package/dist/{index-C-5w6252.d.ts → index-BCYBYfGM.d.ts} +41 -41
  146. package/dist/{index-B4oeyc99.d.ts → index-BODDOPEd.d.ts} +1 -1
  147. package/dist/{index-BcuSI8EM.d.ts → index-BPOa4Z5n.d.ts} +17 -9
  148. package/dist/{index-DUk2VZ_1.d.ts → index-BSBkt2bm.d.ts} +48 -52
  149. package/dist/{index-BBsiQIzw.d.ts → index-BeyI3RUg.d.ts} +64 -44
  150. package/dist/{index-BfHCmKG3.d.ts → index-BisOdLXI.d.ts} +119 -106
  151. package/dist/{index-BapA_uvI.d.ts → index-Bt5YI_JN.d.ts} +5 -5
  152. package/dist/{index-BAz_KJSV.d.ts → index-CD_Ym9WQ.d.ts} +2 -2
  153. package/dist/{index-AOVPovEr.d.ts → index-CX_JaDRY.d.ts} +212 -224
  154. package/dist/{index-DE1Mcccg.d.ts → index-CfK4uv4I.d.ts} +3 -3
  155. package/dist/{index-BTFrh2Cz.d.ts → index-CfRUKYCM.d.ts} +2 -2
  156. package/dist/{index-DM6z4D7q.d.ts → index-Cil7kghY.d.ts} +35 -33
  157. package/dist/index-D11C0iLb.d.ts +97 -0
  158. package/dist/{index-CrUMAwqm.d.ts → index-DJW6AjJ6.d.ts} +1 -5
  159. package/dist/{comparison-types-DBQFu7Rt-DYc2TC2H.d.ts → index-DM-b6jEe-BqkdOlav.d.ts} +19 -57
  160. package/dist/{index-Cp0QfjUV.d.ts → index-DoZhM7nD.d.ts} +11 -12
  161. package/dist/{index-BbsVGwn8.d.ts → index-DsNwo8dd.d.ts} +333 -396
  162. package/dist/{index-Dh7pWHZo.d.ts → index-DuElD_q6.d.ts} +298 -38
  163. package/dist/{index-BIP1GoWI.d.ts → index-f3aV3Kt-.d.ts} +6 -16
  164. package/dist/{index-DFMkcY5V.d.ts → index-u_h6ow4e.d.ts} +149 -130
  165. package/dist/{index-DbPoiwq_.d.ts → index-yZDmK6ab.d.ts} +3 -3
  166. package/dist/index.d.ts +4 -4
  167. package/dist/index.js +1 -2
  168. package/dist/internal/plugin/OverridePlugin.js +22 -3
  169. package/dist/internal/plugin/blockInsertion.js +4 -4
  170. package/dist/internal/plugin/collectPlateNodeMappings.js +11 -4
  171. package/dist/internal/plugin/compilePlainTextMappings.js +2 -0
  172. package/dist/internal/plugin/compilePlateModel.js +15 -1
  173. package/dist/internal/plugin/plateChangeHandlers.js +1 -1
  174. package/dist/internal/plugin/plateRuntime.js +7 -1
  175. package/dist/internal/plugin/resolvePlugin.js +14 -2
  176. package/dist/internal/plugin/resolvePlugins.js +5 -3
  177. package/dist/lib/editor/withPlite.js +33 -3
  178. package/dist/lib/plugins/dom/DOMPlugin.js +6 -2
  179. package/dist/lib/plugins/html/HtmlPlugin.js +37 -16
  180. package/dist/lib/plugins/html/htmlAst.js +5 -3
  181. package/dist/lib/plugins/html/htmlDom.js +1 -10
  182. package/dist/lib/plugins/input-rules/createInputRules.js +3 -3
  183. package/dist/lib/utils/getInjectMatch.js +1 -1
  184. package/dist/markdown/index.d.ts +2 -2
  185. package/dist/markdown/index.js +1 -2
  186. package/dist/markdown/lib/MarkdownPlugin.js +5 -7
  187. package/dist/markdown/lib/deserializer/convertNodesDeserialize.js +29 -5
  188. package/dist/markdown/lib/internal/markdownConversion.js +315 -357
  189. package/dist/markdown/lib/internal/markdownIntrinsics.js +36 -71
  190. package/dist/markdown/lib/internal/markdownLine.js +2 -4
  191. package/dist/markdown/lib/internal/markdownMappings.js +21 -3
  192. package/dist/markdown/lib/internal/markdownSafety.js +101 -1
  193. package/dist/markdown/lib/internal/markdownTags.js +2 -26
  194. package/dist/markdown/lib/serializer/convertNodesSerialize.js +5 -3
  195. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +1 -10
  196. package/dist/math/index.d.ts +3 -3
  197. package/dist/math/react/index.d.ts +4 -4
  198. package/dist/migrations/documentMigrationSelection.internal.js +107 -2
  199. package/dist/migrations/documentMigrations.js +37 -114
  200. package/dist/migrations/index.d.ts +3 -3
  201. package/dist/migrations/migratePlateV54.js +41 -40
  202. package/dist/migrations/migratePlateV54Ast.internal.js +147 -56
  203. package/dist/migrations/migratePlateV54CodeBlocks.internal.js +24 -29
  204. package/dist/migrations/migratePlateV54Inputs.internal.js +39 -32
  205. package/dist/migrations/migratePlateV54Profile.internal.js +52 -26
  206. package/dist/migrations/migratePlateV54Stage.internal.js +127 -0
  207. package/dist/migrations/migratePlateV54Urls.internal.js +77 -57
  208. package/dist/pagination/index.d.ts +1 -1
  209. package/dist/pagination/react/PagedEditorContent.js +6 -6
  210. package/dist/pagination/react/index.d.ts +16 -13
  211. package/dist/react/components/NodeSelection.js +136 -50
  212. package/dist/react/components/Plate.js +214 -145
  213. package/dist/react/components/PlateContainer.js +51 -47
  214. package/dist/react/components/PlateContent.js +3 -3
  215. package/dist/react/components/PlateView.js +1 -1
  216. package/dist/{static/internal/getPlainText.js → react/components/getPlainText.internal.js} +1 -4
  217. package/dist/react/components/plate-nodes.js +48 -40
  218. package/dist/{static/internal/writeStaticSelectionClipboardData.js → react/components/writeStaticSelectionClipboardData.internal.js} +3 -4
  219. package/dist/react/core.js +3 -4
  220. package/dist/react/editor/getPlateCorePlugins.internal.js +1 -1
  221. package/dist/react/editor/withPlate.js +10 -4
  222. package/dist/react/features/board/BoardPlugin.js +7 -1
  223. package/dist/react/features/board/BoardShape.js +261 -180
  224. package/dist/react/features/board/BoardSurface.js +2 -2
  225. package/dist/react/features/board/boardConnect.internal.js +0 -9
  226. package/dist/react/features/board/boardExport.internal.js +225 -80
  227. package/dist/react/features/board/boardGesture.internal.js +193 -33
  228. package/dist/react/features/board/boardIndex.internal.js +271 -26
  229. package/dist/react/features/board/boardKeys.internal.js +48 -15
  230. package/dist/react/features/board/boardPick.internal.js +3 -2
  231. package/dist/react/features/board/boardPicking.internal.js +0 -17
  232. package/dist/react/features/board/boardPreview.internal.js +56 -8
  233. package/dist/react/features/board/boardResize.internal.js +123 -46
  234. package/dist/react/features/board/boardSnap.internal.js +14 -9
  235. package/dist/react/features/board/boardView.internal.js +477 -32
  236. package/dist/react/features/board/boardVoice.internal.js +18 -4
  237. package/dist/react/features/board/index.d.ts +329 -47
  238. package/dist/react/features/board/index.js +2 -2
  239. package/dist/react/features/callout/index.d.ts +3 -3
  240. package/dist/react/features/combobox/comboboxOwner.internal.js +10 -4
  241. package/dist/react/features/combobox/index.d.ts +5 -5
  242. package/dist/react/features/comments/index.d.ts +66 -65
  243. package/dist/react/features/date/index.d.ts +4 -4
  244. package/dist/react/features/details/index.d.ts +6 -6
  245. package/dist/react/features/field/FieldPlugin.js +3 -3
  246. package/dist/react/features/field/index.d.ts +73 -92
  247. package/dist/react/features/footnote/index.d.ts +63 -60
  248. package/dist/react/features/format-painter/index.d.ts +4 -4
  249. package/dist/react/features/ink/InkContent.js +76 -120
  250. package/dist/react/features/ink/InkPlugin.js +40 -17
  251. package/dist/react/features/ink/index.d.ts +214 -377
  252. package/dist/react/features/ink/index.js +1 -2
  253. package/dist/react/features/ink/inkCapture.internal.js +99 -61
  254. package/dist/react/features/ink/inkImages.internal.js +278 -0
  255. package/dist/react/features/ink/inkMeasure.internal.js +42 -16
  256. package/dist/react/features/ink/inkPaint.internal.js +31 -23
  257. package/dist/react/features/ink/inkPick.internal.js +45 -20
  258. package/dist/react/features/ink/inkPlacement.internal.js +205 -185
  259. package/dist/react/features/ink/inkWatch.internal.js +1 -32
  260. package/dist/react/features/layout/index.d.ts +6 -6
  261. package/dist/react/features/list/ListPlugin.js +10 -6
  262. package/dist/react/features/lock/LockPlugin.js +66 -0
  263. package/dist/react/features/lock/index.d.ts +58 -0
  264. package/dist/react/features/lock/index.js +2 -0
  265. package/dist/react/features/media/index.d.ts +26 -26
  266. package/dist/react/features/mention/index.d.ts +6 -6
  267. package/dist/react/features/suggestion/index.d.ts +6 -6
  268. package/dist/react/features/suggestion/suggestion-view.internal.js +38 -36
  269. package/dist/react/features/suggestion/useSuggestion.js +17 -14
  270. package/dist/react/features/table/TablePlugin.js +12 -5
  271. package/dist/react/features/table/index.d.ts +20 -22
  272. package/dist/react/features/table/useTableResize.js +4 -4
  273. package/dist/react/features/toc/index.d.ts +2 -2
  274. package/dist/react/features/upload/index.d.ts +44 -44
  275. package/dist/react/index.d.ts +5 -6
  276. package/dist/react/index.js +3 -4
  277. package/dist/react/internal/plate-context.js +13 -42
  278. package/dist/react/internal/plite-components.js +2 -2
  279. package/dist/react/internal/usePlateModelRevision.js +2 -3
  280. package/dist/react/plite-react.js +2 -2
  281. package/dist/react/stores/element/useElementStore.js +78 -52
  282. package/dist/react/stores/plate/useEditor.js +70 -32
  283. package/dist/react/stores/plate/useEditorSelector.js +193 -53
  284. package/dist/react/utils/BlockPlaceholderPlugin.js +10 -4
  285. package/dist/react/utils/pipeRenderElement.internal.js +32 -30
  286. package/dist/react/virtualized.d.ts +4 -4
  287. package/dist/react/virtualized.js +2 -2
  288. package/dist/root.js +1 -2
  289. package/dist/{source-D5CyclpX.d.ts → source-B1rLozUs.d.ts} +3 -3
  290. package/dist/static/components/PlateStatic.js +13 -2
  291. package/dist/static/components/plite-nodes.js +1 -1
  292. package/dist/static/index.d.ts +9 -11
  293. package/dist/static/internal/staticDocumentView.js +67 -1
  294. package/dist/static/pluginRenderLeafStatic.internal.js +1 -2
  295. package/dist/static/pluginRenderTextStatic.internal.js +2 -1
  296. package/dist/tabbable/index.d.ts +1 -1
  297. package/dist/tabbable/react/index.d.ts +3 -3
  298. package/dist/testing/index.d.ts +2 -2
  299. package/dist/{index-DHt8nZQ6-NUTahb8N.d.ts → tx-only-D8lpB-sT-ZiAbZRMU.d.ts} +6980 -6633
  300. package/dist/yjs/index.d.ts +1 -1
  301. package/dist/yjs/react/index.d.ts +5 -5
  302. package/package.json +16 -7
  303. package/dist/docs/migration/plite-to-plate.md +0 -352
  304. package/dist/features/comments/plite-comments.internal.js +0 -2
  305. package/dist/features/ink/lib/inkGone.internal.js +0 -288
  306. package/dist/index-BvQzYVAW-Jvz2iG8B.d.ts +0 -65
  307. package/dist/lib/plugins/element-id/ElementIdPlugin.js +0 -43
  308. package/dist/lib/plugins/element-id/elementIdAdmission.internal.js +0 -34
  309. package/dist/markdown/lib/RawHtmlPlugin.js +0 -26
  310. package/dist/markdown/lib/internal/markdownRawHtml.js +0 -353
  311. package/dist/react/features/ink/InkCopyView.js +0 -203
  312. package/dist/react/libs/jotai.js +0 -3
@@ -1,4 +1,4 @@
1
- import { canPlaceBlocksAtPath, getCompiledEditorSchema, getEditorAuthoredDocumentCapability, placeElementAt, projectEditorView } from "../../facade.js";
1
+ import { canPlaceBlocksAtPath, getCompiledEditorSchema, getEditorAuthoredDocumentCapability, hasNonWritableAt, placeElementAt, projectEditorView, subscribeEditorRefusals } from "../../facade.js";
2
2
  import { getCompiledPlatePlugin } from "../../internal/plugin/compilePlateModel.js";
3
3
  import { resolveInsertionAnchor } from "../../internal/plugin/insertionAnchor.js";
4
4
  import { HistoryPlugin } from "../../lib/plugins/HistoryPlugin.js";
@@ -10,12 +10,24 @@ import { isListItem } from "../../features/list/lib/listIndex.internal.js";
10
10
  import { definePlugin } from "../../react/plugin/definePlugin.js";
11
11
  import { AuthoredPlugin } from "../../authored/AuthoredPlugin.js";
12
12
  import { BaseTableCellPlugin, BaseTablePlugin, BaseTableRowPlugin } from "../../features/table/lib/BaseTablePlugin.js";
13
+ import { isAIPathNonWritable, resolveAISelectedBlocks } from "../lib/lockedContext.internal.js";
14
+ import { LOCKED_BLOCK_PLACEHOLDER_TAG } from "../lib/lockedContext.js";
13
15
  import { MarkdownPlugin } from "../../markdown/lib/MarkdownPlugin.js";
14
16
  import { findQuotedSpan } from "../lib/findQuotedSpan.internal.js";
15
- import { captureTextRange, fillEmptyListItem, formatAIOutput, landAIOutput, suggestionBlocks, textEdits, wholeTextBlocks, withoutText } from "./aiOutputLanding.internal.js";
17
+ import { captureTextRange, extractCopiedBlockProps, fillEmptyListItem, formatAIOutput, landAIOutput, suggestionBlocks, textEdits, wholeTextBlocks, withoutText } from "./aiOutputLanding.internal.js";
16
18
  import isEqual from "lodash/isEqual.js";
17
19
  import cloneDeep from "lodash/cloneDeep.js";
18
20
  //#region src/ai/react/AIChatPlugin.ts
21
+ const HEX = Array.from({ length: 256 }, (_, byte) => byte.toString(16).padStart(2, "0"));
22
+ const createRequestId = () => {
23
+ if (typeof globalThis.crypto?.randomUUID === "function") return globalThis.crypto.randomUUID();
24
+ const bytes = /* @__PURE__ */ new Uint8Array(16);
25
+ if (typeof globalThis.crypto?.getRandomValues === "function") globalThis.crypto.getRandomValues(bytes);
26
+ else for (let index = 0; index < bytes.length; index += 1) bytes[index] = Math.floor(Math.random() * 256);
27
+ bytes[6] = bytes[6] & 15 | 64;
28
+ bytes[8] = bytes[8] & 63 | 128;
29
+ return `${HEX[bytes[0]]}${HEX[bytes[1]]}${HEX[bytes[2]]}${HEX[bytes[3]]}-${HEX[bytes[4]]}${HEX[bytes[5]]}-${HEX[bytes[6]]}${HEX[bytes[7]]}-${HEX[bytes[8]]}${HEX[bytes[9]]}-${HEX[bytes[10]]}${HEX[bytes[11]]}${HEX[bytes[12]]}${HEX[bytes[13]]}${HEX[bytes[14]]}${HEX[bytes[15]]}`;
30
+ };
19
31
  const aiChatShowEffect = defineEffect({
20
32
  history: "skip",
21
33
  key: "ai.chat.show"
@@ -40,6 +52,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
40
52
  _blockKey: null,
41
53
  _blockRefs: {},
42
54
  _changeId: null,
55
+ _lockedBlockRefs: {},
43
56
  _requestId: null,
44
57
  _tableCellRefs: {},
45
58
  authorId: null,
@@ -50,6 +63,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
50
63
  mode: "insert",
51
64
  open: false,
52
65
  previewValue: [],
66
+ refusalMessage: null,
53
67
  streaming: false,
54
68
  toolName: null,
55
69
  trigger: " ",
@@ -81,7 +95,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
81
95
  const captureEditor = projectEditorView(commandEditor, root ? { root } : {});
82
96
  const selection = current && !isNodeSelecting ? captureEditor.read((state) => captureTextRange(state, current)) : current;
83
97
  if (viewSelection && selection && !RangeApi.equals(selection, viewSelection)) commandEditor.update.selection.set(selection);
84
- const blocks = isNodeSelecting ? selectedNodes : captureEditor.read.nodes.blocks(selection ? { at: selection } : {});
98
+ const blocks = isNodeSelecting ? selectedNodes : selection ? resolveAISelectedBlocks(captureEditor, selection).entries : captureEditor.read.nodes.blocks();
85
99
  const isEndpoint = (path, endpoint) => isNodeSelecting && !!endpoint && (PathApi.equals(path, endpoint) || PathApi.isAncestor(path, endpoint));
86
100
  captureSelection(captureEditor, selection);
87
101
  context.store.set({
@@ -161,7 +175,8 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
161
175
  const selectionPath = state.selection.nodes().at(-1)?.[1] ?? selection?.focus.path;
162
176
  const path = generated?.[1] ?? selectionPath?.slice(0, 1) ?? [0];
163
177
  const entry = state.nodes.get(path, { match: ElementApi.isElement });
164
- const containerTypes = /* @__PURE__ */ new Set([...columnGroup ? [columnGroup.schema.type] : [], ...tablePlugin.installed ? [tablePlugin.schema.type] : []]);
178
+ const columnGroupSchema = columnGroup?.schema;
179
+ const containerTypes = /* @__PURE__ */ new Set([...columnGroupSchema && "type" in columnGroupSchema ? [columnGroupSchema.type] : [], ...tablePlugin.installed ? [tablePlugin.schema.type] : []]);
165
180
  return entry && containerTypes.has(entry[0].type) ? state.nodes.above()?.[1] ?? path : path;
166
181
  };
167
182
  const getInsertStart = (state) => {
@@ -174,8 +189,15 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
174
189
  };
175
190
  };
176
191
  const stop = () => {
192
+ const hasLockedRefs = Object.keys(context.store.get("_lockedBlockRefs")).length > 0;
177
193
  context.store.get().chat?.stop?.();
178
- context.store.set({ streaming: false });
194
+ context.store.set({
195
+ ...hasLockedRefs ? {
196
+ _lockedBlockRefs: {},
197
+ _requestId: null
198
+ } : {},
199
+ streaming: false
200
+ });
179
201
  };
180
202
  const cancel = () => {
181
203
  context.store.set({
@@ -212,11 +234,16 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
212
234
  const view = projectEditorView(editor, root ? { root } : {});
213
235
  const { chatNodes } = context.store.get();
214
236
  const restored = suggestionTarget.paths.map((path) => view.read.nodes.get(path, { match: ElementApi.isElement })?.[0]);
215
- if (restored.length !== chatNodes.length || !restored.every((node, index) => node !== void 0 && node.type === chatNodes[index].node.type && NodeApi.string(node) === NodeApi.string(chatNodes[index].node))) return;
216
- context.store.set({ chatNodes: chatNodes.map((chatNode, index) => ({
217
- ...chatNode,
218
- nodeKey: view.key(restored[index])
219
- })) });
237
+ if (restored.length !== chatNodes.length) return;
238
+ const nextChatNodes = chatNodes.flatMap((chatNode, index) => {
239
+ const node = restored[index];
240
+ return node && node.type === chatNode.node.type && NodeApi.string(node) === NodeApi.string(chatNode.node) ? [{
241
+ ...chatNode,
242
+ nodeKey: view.key(node)
243
+ }] : [];
244
+ });
245
+ if (nextChatNodes.length !== chatNodes.length) return;
246
+ context.store.set({ chatNodes: nextChatNodes });
220
247
  };
221
248
  const withReviewRecords = (blocks) => {
222
249
  const { records } = editor.read.value();
@@ -244,6 +271,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
244
271
  _blockKey: null,
245
272
  _blockRefs: {},
246
273
  _changeId: null,
274
+ _lockedBlockRefs: {},
247
275
  _requestId: null,
248
276
  _tableCellRefs: {},
249
277
  chatNodeMode: null,
@@ -251,6 +279,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
251
279
  chatSelection: null,
252
280
  mode: "insert",
253
281
  previewValue: [],
282
+ refusalMessage: null,
254
283
  toolName: null
255
284
  });
256
285
  try {
@@ -268,7 +297,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
268
297
  return result;
269
298
  };
270
299
  const hideOptions = () => {
271
- context.store.set({ open: false });
300
+ context.store.set({
301
+ open: false,
302
+ refusalMessage: null
303
+ });
272
304
  };
273
305
  const promptMarkdown = (options) => {
274
306
  const result = editor.api.markdown.serialize({
@@ -346,7 +378,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
346
378
  const tableNodes = tableView?.read.nodes ?? state.nodes;
347
379
  const tableKey = (path) => tableView ? tableView.key(path) : state.key(path);
348
380
  const selectedNodeKeys = new Set(cells.map(([, path]) => tableKey(path)));
349
- const tableEntry = tableNodes.block({ match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type });
381
+ const tableEntry = tableNodes.block({ match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type }) ?? tableNodes.above({
382
+ at: cells[0][1],
383
+ match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type
384
+ });
350
385
  if (!tableEntry) return "";
351
386
  const [table, tablePath] = tableEntry;
352
387
  const refs = {};
@@ -355,12 +390,14 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
355
390
  if (!ElementApi.isElement(row) || row.type !== editor.plugin(BaseTableRowPlugin).schema.type) throw new Error("Tables must contain table rows.");
356
391
  const values = row.children.map((cell, cellIndex) => {
357
392
  if (!ElementApi.isElement(cell) || cell.type !== editor.plugin(BaseTableCellPlugin).schema.type) throw new Error("Table rows must contain table cells.");
358
- const nodeKey = tableKey([
393
+ const cellPath = [
359
394
  ...tablePath,
360
395
  rowIndex,
361
396
  cellIndex
362
- ]);
363
- if (nodeKey && selectedNodeKeys.has(nodeKey)) {
397
+ ];
398
+ const nodeKey = tableKey(cellPath);
399
+ const cellWritable = !isAIPathNonWritable(tableView ?? view, cellPath);
400
+ if (nodeKey && selectedNodeKeys.has(nodeKey) && cellWritable) {
364
401
  const ref = `c${selectedCells.length + 1}`;
365
402
  refs[ref] = { key: nodeKey };
366
403
  selectedCells.push({
@@ -441,18 +478,47 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
441
478
  }];
442
479
  });
443
480
  const tableCellRefs = {};
444
- const tableCells = tablePlugin.installed ? (requestEditor.plugin(BaseTablePlugin).read.selection({ at: viewAt ?? void 0 })?.cells ?? []).flatMap(([, path], index) => {
481
+ const tableCells = [];
482
+ let isMultiCellTable = false;
483
+ if (tablePlugin.installed) {
484
+ const selectedCells = requestEditor.plugin(BaseTablePlugin).read.selection(isNodeSelecting || !viewAt ? void 0 : { at: viewAt })?.cells ?? [];
485
+ isMultiCellTable = selectedCells.length > 1;
486
+ let cellRefIndex = 0;
487
+ for (const [, path] of selectedCells) {
488
+ if (isAIPathNonWritable(requestEditor, path)) continue;
489
+ const key = requestEditor.key(path);
490
+ if (!key) continue;
491
+ cellRefIndex += 1;
492
+ const ref = `c${cellRefIndex}`;
493
+ tableCellRefs[ref] = { key };
494
+ tableCells.push({
495
+ path: inScope(path),
496
+ ref
497
+ });
498
+ }
499
+ }
500
+ const selectedBlockEntries = isMultiCellTable ? [] : isNodeSelecting ? selectedPaths.flatMap((path) => {
501
+ const entry = requestEditor.read.nodes.get(path, { match: ElementApi.isElement });
502
+ return entry ? [entry] : [];
503
+ }) : viewAt && RangeApi.isExpanded(viewAt) ? resolveAISelectedBlocks(requestEditor, viewAt).entries : [];
504
+ const lockedBlockRefs = {};
505
+ const lockedBlocks = [];
506
+ let lockedRefIndex = 0;
507
+ for (const [, path] of selectedBlockEntries) {
508
+ if (!isAIPathNonWritable(requestEditor, path)) continue;
445
509
  const key = requestEditor.key(path);
446
- if (!key) return [];
447
- const ref = `c${index + 1}`;
448
- tableCellRefs[ref] = { key };
449
- return [{
510
+ if (!key) continue;
511
+ lockedRefIndex += 1;
512
+ const ref = `l${lockedRefIndex}`;
513
+ lockedBlockRefs[ref] = { key };
514
+ lockedBlocks.push({
450
515
  path: inScope(path),
451
516
  ref
452
- }];
453
- }) : [];
517
+ });
518
+ }
454
519
  context.store.set({
455
520
  _blockRefs: blockRefs,
521
+ _lockedBlockRefs: lockedBlockRefs,
456
522
  _tableCellRefs: tableCellRefs
457
523
  });
458
524
  return {
@@ -460,11 +526,40 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
460
526
  nodeSelection,
461
527
  refs: {
462
528
  blocks,
529
+ ...lockedBlocks.length > 0 ? { lockedBlocks } : {},
463
530
  tableCells
464
531
  },
465
532
  selection: requestAt
466
533
  };
467
534
  };
535
+ const hasEditableRequestTarget = (commandEditor, at, selectedNodePaths, requestContext) => {
536
+ const current = at ?? commandEditor.read.selection() ?? editor.read.selection();
537
+ const root = current ? SelectionApi.root(current) : commandEditor.read.view.root();
538
+ const view = projectEditorView(commandEditor, root ? { root } : {});
539
+ const viewAt = at ? {
540
+ ...at,
541
+ anchor: {
542
+ offset: at.anchor.offset,
543
+ path: at.anchor.path
544
+ },
545
+ focus: {
546
+ offset: at.focus.offset,
547
+ path: at.focus.path
548
+ }
549
+ } : null;
550
+ if (tablePlugin.installed && (selectedNodePaths.length > 0 || viewAt)) {
551
+ if ((view.plugin(BaseTablePlugin).read.selection(selectedNodePaths.length > 0 || !viewAt ? void 0 : { at: viewAt })?.cells ?? []).length > 1) return requestContext.refs.tableCells.length > 0;
552
+ }
553
+ if (selectedNodePaths.length > 0) return (requestContext.refs.lockedBlocks?.length ?? 0) < selectedNodePaths.length;
554
+ if (!viewAt) return true;
555
+ if (!RangeApi.isExpanded(viewAt)) {
556
+ const caretBlock = view.read.nodes.block({ at: viewAt.anchor });
557
+ return !caretBlock || !isAIPathNonWritable(view, caretBlock[1]);
558
+ }
559
+ const resolved = resolveAISelectedBlocks(view, viewAt);
560
+ if (resolved.partialLockedContainer || resolved.entries.length === 0) return false;
561
+ return (requestContext.refs.lockedBlocks?.length ?? 0) < resolved.entries.length;
562
+ };
468
563
  const resolvePrompt = (prompt, params) => {
469
564
  if (typeof prompt === "function") return prompt(params);
470
565
  if (typeof prompt === "string") return prompt;
@@ -506,7 +601,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
506
601
  const sourceNode = source[index];
507
602
  if (!ElementApi.isElement(node) || !ElementApi.isElement(sourceNode) || sourceNode.type !== node.type) return node;
508
603
  return {
509
- ...NodeApi.extractProps(sourceNode),
604
+ ...extractCopiedBlockProps(sourceNode, editor.read.schema, { preserveIdentity: true }),
510
605
  ...node,
511
606
  children: node.children
512
607
  };
@@ -520,15 +615,33 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
520
615
  }
521
616
  };
522
617
  const landAndClose = (actionEditor, land) => {
618
+ if (!actionEditor) return;
523
619
  let closed = false;
524
- if (actionEditor?.update((tx, { afterCommit }) => {
525
- if (!land(tx)) return false;
526
- afterCommit(() => {
527
- closed = true;
528
- finishCompleteAction();
620
+ let lockedRefusal = false;
621
+ context.store.set({ refusalMessage: null });
622
+ const stopRefusals = subscribeEditorRefusals(actionEditor, (refusal) => {
623
+ if (typeof refusal !== "object" || refusal === null) return;
624
+ const record = refusal;
625
+ if (record.reason === "block-locked" || record.reason === "node-write-veto" && hasNonWritableAt(actionEditor, actionEditor.read.selection())) lockedRefusal = true;
626
+ });
627
+ let landed;
628
+ try {
629
+ landed = actionEditor.update((tx, { afterCommit }) => {
630
+ if (!land(tx)) return false;
631
+ afterCommit(() => {
632
+ closed = true;
633
+ finishCompleteAction();
634
+ });
635
+ return true;
529
636
  });
530
- return true;
531
- }) && !closed) finishCompleteAction();
637
+ } finally {
638
+ stopRefusals();
639
+ }
640
+ if (lockedRefusal) {
641
+ context.store.set({ refusalMessage: "This selection contains a locked block. Unlock it or insert below instead." });
642
+ return;
643
+ }
644
+ if (landed && !closed) finishCompleteAction();
532
645
  };
533
646
  const getActionChatBlocks = (tx) => {
534
647
  const chatNodes = context.store.get("chatNodes");
@@ -555,6 +668,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
555
668
  const blocks = formatAIOutput({
556
669
  blocks: source,
557
670
  format: anchor === target ? format : "none",
671
+ schema: editor.read.schema,
558
672
  sourceBlock: target[0]
559
673
  });
560
674
  if (!blocks) return false;
@@ -614,43 +728,144 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
614
728
  const entry = tx.nodes.get(path, { match: ElementApi.isElement });
615
729
  return entry ? [entry[0]] : [];
616
730
  });
617
- if (target.kind === "blocks" && sourceNodes.length === paths.length && isEqual(sourceNodes.map(withoutText), nextNodes.map(withoutText))) {
618
- const edits = sourceNodes.flatMap((sourceNode, blockIndex) => {
619
- const nextNode = nextNodes[blockIndex];
620
- const blockPath = paths[blockIndex];
621
- if (!nextNode || !blockPath) return [];
622
- const afterTexts = [...NodeApi.texts(nextNode)];
623
- return [...NodeApi.texts(sourceNode)].flatMap(([before, path], textIndex) => {
624
- const after = afterTexts[textIndex]?.[0];
625
- return after && before.text !== after.text ? textEdits(before.text, after.text).map((edit) => ({
626
- ...edit,
627
- path: [...blockPath, ...path]
628
- })) : [];
629
- });
731
+ if (target.kind === "blocks") {
732
+ const minimal = applyMinimalTextBlockEdits(tx, sourceNodes, paths, nextNodes);
733
+ if (minimal !== null) return minimal;
734
+ }
735
+ return tx.slice.replace(ContentSlice.fromJSON({
736
+ content: nextNodes,
737
+ openEnd: 0,
738
+ openStart: 0
739
+ }), { at: target.range });
740
+ };
741
+ const LOCKED_BLOCK_REFUSAL_MESSAGE = "This selection contains a locked block. Unlock it or insert below instead.";
742
+ const isLockRefusalRecord = (record) => {
743
+ const reason = record && typeof record === "object" ? record.reason : void 0;
744
+ return reason === "block-locked" || reason === "node-write-veto";
745
+ };
746
+ const applyMinimalTextBlockEdits = (tx, sourceNodes, paths, nextNodes) => {
747
+ if (sourceNodes.length !== paths.length || sourceNodes.length !== nextNodes.length || !isEqual(sourceNodes.map(withoutText), nextNodes.map(withoutText))) return null;
748
+ const edits = sourceNodes.flatMap((sourceNode, blockIndex) => {
749
+ const nextNode = nextNodes[blockIndex];
750
+ const blockPath = paths[blockIndex];
751
+ if (!nextNode || !blockPath) return [];
752
+ const afterTexts = [...NodeApi.texts(nextNode)];
753
+ return [...NodeApi.texts(sourceNode)].flatMap(([before, path], textIndex) => {
754
+ const after = afterTexts[textIndex]?.[0];
755
+ return after && before.text !== after.text ? textEdits(before.text, after.text).map((edit) => ({
756
+ ...edit,
757
+ path: [...blockPath, ...path]
758
+ })) : [];
630
759
  });
631
- for (const { from, path, text, to } of edits.toSorted((left, right) => PathApi.compare(right.path, left.path) || right.from - left.from)) {
632
- if (to > from) tx.text.delete({ at: {
633
- anchor: {
634
- offset: from,
635
- path
636
- },
637
- focus: {
638
- offset: to,
639
- path
640
- }
641
- } });
642
- if (text) tx.text.insert(text, { at: {
760
+ });
761
+ for (const { from, path, text, to } of edits.toSorted((left, right) => PathApi.compare(right.path, left.path) || right.from - left.from)) {
762
+ if (to > from) tx.text.delete({ at: {
763
+ anchor: {
643
764
  offset: from,
644
765
  path
645
- } });
646
- }
647
- return edits.length > 0;
766
+ },
767
+ focus: {
768
+ offset: to,
769
+ path
770
+ }
771
+ } });
772
+ if (text) tx.text.insert(text, { at: {
773
+ offset: from,
774
+ path
775
+ } });
648
776
  }
777
+ return edits.length > 0;
778
+ };
779
+ const buildTableDraftPreview = (actionEditor, node, path) => {
780
+ if (!ElementApi.isElement(node)) return node;
781
+ const key = actionEditor.key(path);
782
+ const rawDraft = key ? tableDraft.get(key) : void 0;
783
+ const draft = key && rawDraft && isAIPathNonWritable(actionEditor, path) ? (tableDraft.delete(key), void 0) : rawDraft;
784
+ const { locked: _locked, ...rest } = node;
785
+ return {
786
+ ...rest,
787
+ children: draft?.children ?? node.children.map((child, index) => buildTableDraftPreview(actionEditor, child, [...path, index]))
788
+ };
789
+ };
790
+ const stripLockedDeep = (node) => {
791
+ if (!ElementApi.isElement(node)) return node;
792
+ const { locked: _locked, ...rest } = node;
793
+ return {
794
+ ...rest,
795
+ children: node.children.map(stripLockedDeep)
796
+ };
797
+ };
798
+ const resolveOrderedTargetEntries = (actionEditor, targetKeys) => {
799
+ if (targetKeys.length === 0 || new Set(targetKeys).size !== targetKeys.length) return null;
800
+ const entries = targetKeys.flatMap((key) => {
801
+ const entry = actionEditor.read.nodes.get(key, { match: ElementApi.isElement });
802
+ return entry ? [entry] : [];
803
+ });
804
+ if (entries.length !== targetKeys.length) return null;
805
+ return entries.toSorted(([, a], [, b]) => PathApi.compare(a, b));
806
+ };
807
+ const withdrawPendingChange = (actionEditor, currentChangeId) => {
808
+ const previous = currentChangeId ? editor.plugin(AuthoredPlugin).read.change(currentChangeId) : null;
809
+ if (!previous) return true;
810
+ let withdrawn = false;
811
+ actionEditor.update((tx, { afterCommit }) => {
812
+ tx.history.merge();
813
+ tx.plugin(AuthoredPlugin).withdraw([previous]);
814
+ afterCommit(({ snapshot }) => {
815
+ withdrawn = true;
816
+ suggestion &&= {
817
+ ...suggestion,
818
+ children: snapshot.children
819
+ };
820
+ });
821
+ });
822
+ return withdrawn && (!suggestion || actionEditor.read.children() === suggestion.children);
823
+ };
824
+ const normalizeUnlockedListRun = (sourceRun, nextRun) => {
825
+ const firstSource = sourceRun[0];
826
+ if (!firstSource || !sourceRun.every((node) => isListItem(node)) || !nextRun.every((node) => isListItem(node))) return nextRun;
827
+ const baseIndent = typeof firstSource.indent === "number" ? firstSource.indent : void 0;
828
+ const uniformIndent = baseIndent !== void 0 && sourceRun.every((node) => node.indent === baseIndent);
829
+ const sharedListId = uniformIndent && typeof firstSource.listId === "string" && sourceRun.every((node) => node.listId === firstSource.listId) ? firstSource.listId : void 0;
830
+ const firstNextIndent = typeof nextRun[0]?.indent === "number" ? nextRun[0].indent : void 0;
831
+ const indentDelta = uniformIndent && firstNextIndent !== void 0 ? baseIndent - firstNextIndent : 0;
832
+ const sourceHadListStart = Object.hasOwn(firstSource, "listStart");
833
+ return nextRun.map((node, index) => {
834
+ const updated = { ...node };
835
+ if (sharedListId) updated.listId = sharedListId;
836
+ if (indentDelta > 0 && typeof node.indent === "number") updated.indent = node.indent + indentDelta;
837
+ if (index === 0 && !sourceHadListStart && Object.hasOwn(updated, "listStart")) delete updated.listStart;
838
+ return updated;
839
+ });
840
+ };
841
+ const writeUnlockedRun = (tx, sourceRun, nextNodes, insertAt) => {
842
+ if (sourceRun.length === 0) {
843
+ if (nextNodes.length === 0 || !insertAt) return false;
844
+ tx.nodes.insert(cloneDeep([...nextNodes]), { at: insertAt });
845
+ return true;
846
+ }
847
+ if (nextNodes.length === 0) {
848
+ for (const [, path] of sourceRun.toReversed()) tx.nodes.remove({ at: path });
849
+ return true;
850
+ }
851
+ const sourceNodes = sourceRun.map(([node]) => node);
852
+ const sourcePaths = sourceRun.map(([, path]) => path);
853
+ const minimal = applyMinimalTextBlockEdits(tx, sourceNodes, sourcePaths, nextNodes);
854
+ if (minimal !== null) return minimal;
855
+ const first = sourceRun[0];
856
+ const last = sourceRun.at(-1);
857
+ if (!first || !last) return false;
858
+ const anchor = tx.points.start(first[1]);
859
+ const focus = tx.points.end(last[1]);
860
+ if (!anchor || !focus) return false;
649
861
  return tx.slice.replace(ContentSlice.fromJSON({
650
- content: nextNodes,
862
+ content: cloneDeep([...nextNodes]),
651
863
  openEnd: 0,
652
864
  openStart: 0
653
- }), { at: target.range });
865
+ }), { at: {
866
+ anchor,
867
+ focus
868
+ } });
654
869
  };
655
870
  const applySuggestion = (commandEditor, content, { requestId } = {}) => {
656
871
  const state = context.store.get();
@@ -663,6 +878,144 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
663
878
  const capturedSelection = resolveChatSelection();
664
879
  if (state.chatSelection && !capturedSelection) return false;
665
880
  const currentChangeId = state._changeId;
881
+ const lockedRefs = state._lockedBlockRefs;
882
+ const expectedLockedRefs = Object.keys(lockedRefs);
883
+ const failLockedSuggestion = (message) => {
884
+ const result = decideCurrentChange("reject");
885
+ if (!result || reviewSucceeded(result)) {
886
+ suggestion = null;
887
+ suggestionTarget = null;
888
+ }
889
+ context.store.set({ refusalMessage: message });
890
+ return false;
891
+ };
892
+ if (expectedLockedRefs.length > 0) {
893
+ const parsedPlaceholders = editor.api.markdown.parsePlaceholders(content, { tag: LOCKED_BLOCK_PLACEHOLDER_TAG });
894
+ if (!parsedPlaceholders.ok) return failLockedSuggestion("AI response altered or omitted a locked block and was not applied.");
895
+ const actualRefs = parsedPlaceholders.segments.flatMap((segment) => segment.kind === "placeholder" ? [segment.ref] : []);
896
+ if (actualRefs.length !== expectedLockedRefs.length || actualRefs.some((ref, index) => ref !== expectedLockedRefs[index])) return failLockedSuggestion("AI response altered or omitted a locked block and was not applied.");
897
+ const ordered = resolveOrderedTargetEntries(actionEditor, state.chatNodes.map(({ nodeKey }) => nodeKey));
898
+ if (!ordered) return false;
899
+ if (!ordered.every(([, path], index) => {
900
+ if (index === 0) return true;
901
+ const previous = ordered[index - 1];
902
+ return previous !== void 0 && PathApi.equals(path, PathApi.next(previous[1]));
903
+ })) return failLockedSuggestion("Selected blocks are not contiguous or changed before AI finished.");
904
+ const lockedEntries = [];
905
+ const lockedIndices = [];
906
+ for (const ref of expectedLockedRefs) {
907
+ const key = lockedRefs[ref]?.key;
908
+ const index = key ? ordered.findIndex(([node]) => actionEditor.key(node) === key) : -1;
909
+ const previousIndex = lockedIndices.at(-1) ?? -1;
910
+ const lockedEntry = index >= 0 ? ordered[index] : void 0;
911
+ if (!lockedEntry || index <= previousIndex) return failLockedSuggestion("A locked block in this selection moved or changed before AI finished.");
912
+ lockedIndices.push(index);
913
+ lockedEntries.push(lockedEntry);
914
+ }
915
+ const sourceRuns = [];
916
+ let cursor = 0;
917
+ for (const lockedIndex of lockedIndices) {
918
+ sourceRuns.push(ordered.slice(cursor, lockedIndex));
919
+ cursor = lockedIndex + 1;
920
+ }
921
+ sourceRuns.push(ordered.slice(cursor));
922
+ for (const run of sourceRuns) for (const [, path] of run) if (isAIPathNonWritable(actionEditor, path)) return failLockedSuggestion("A selected block was locked while AI was responding. Unlock it or try again.");
923
+ const answerRuns = Array.from({ length: expectedLockedRefs.length + 1 }, () => []);
924
+ let slotIndex = 0;
925
+ for (const segment of parsedPlaceholders.segments) if (segment.kind === "placeholder") slotIndex += 1;
926
+ else answerRuns[slotIndex]?.push(...segment.nodes);
927
+ if (suggestion && actionEditor.read.children() !== suggestion.children) return false;
928
+ if (!withdrawPendingChange(actionEditor, currentChangeId)) return false;
929
+ const preparedRuns = sourceRuns.map((sourceRun, index) => {
930
+ const answerRun = answerRuns[index] ?? [];
931
+ if (sourceRun.length === 0 || answerRun.length === 0) return answerRun;
932
+ const sourceNodes = proposedBlocks(actionEditor, root ?? "main", sourceRun);
933
+ const serialized = sourceNodes.length > 0 ? editor.api.markdown.serialize({
934
+ document: { children: sourceNodes },
935
+ lossPolicy: "allow"
936
+ }) : null;
937
+ const reparsed = serialized?.ok ? editor.api.markdown.parseSlice(serialized.data, { lossPolicy: "allow" }) : void 0;
938
+ const roundTrip = reparsed?.ok && ElementApi.isElementList(reparsed.slice.content) ? reparsed.slice.content : null;
939
+ const fitted = suggestionBlocks(editor, actionEditor.read, {
940
+ answer: answerRun,
941
+ roundTrip,
942
+ source: sourceNodes
943
+ });
944
+ return normalizeUnlockedListRun(sourceNodes, fitted);
945
+ });
946
+ const unlockedResponse = [];
947
+ for (let index = 0; index < preparedRuns.length; index += 1) {
948
+ unlockedResponse.push(...(preparedRuns[index] ?? []).map(stripLockedDeep));
949
+ const lockedEntry = lockedEntries[index];
950
+ if (lockedEntry && !Object.hasOwn(lockedEntry[0], "childRoots")) unlockedResponse.push(stripLockedDeep(lockedEntry[0]));
951
+ }
952
+ const first = ordered[0];
953
+ const last = ordered.at(-1);
954
+ const anchor = first ? actionEditor.read.points.start(first[1]) : null;
955
+ const focus = last ? actionEditor.read.points.end(last[1]) : null;
956
+ const range = capturedSelection ?? (anchor && focus ? {
957
+ anchor,
958
+ focus
959
+ } : actionEditor.read.ranges.fromEntries(ordered));
960
+ if (!range) return false;
961
+ const target = {
962
+ kind: "blocks",
963
+ paths: ordered.map(([, path]) => path),
964
+ range,
965
+ roundTrip: null,
966
+ source: proposedBlocks(actionEditor, root ?? "main", ordered)
967
+ };
968
+ let publishedChangeId = null;
969
+ let lockedRefusal = false;
970
+ const unsubscribe = subscribeEditorRefusals(actionEditor, (record) => {
971
+ if (isLockRefusalRecord(record)) lockedRefusal = true;
972
+ });
973
+ const publish = (changeId, children = actionEditor.read.children()) => {
974
+ publishedChangeId = changeId;
975
+ suggestion = {
976
+ children,
977
+ response: unlockedResponse
978
+ };
979
+ suggestionTarget = target;
980
+ context.store.set({
981
+ _changeId: changeId,
982
+ previewValue: [],
983
+ refusalMessage: null
984
+ });
985
+ const published = pendingChange();
986
+ if (published) responseAuthor = {
987
+ authorId: published.authorId,
988
+ requestId: context.store.get("_requestId")
989
+ };
990
+ };
991
+ let proposed;
992
+ try {
993
+ proposed = actionEditor.update((tx, { afterCommit }) => {
994
+ const changeId = tx.plugin(AuthoredPlugin).propose(currentChangeId ? { changeId: currentChangeId } : void 0);
995
+ if (currentChangeId) tx.history.merge();
996
+ else tx.history.newBatch();
997
+ let mutated = false;
998
+ for (let index = sourceRuns.length - 1; index >= 0; index -= 1) {
999
+ const sourceRun = sourceRuns[index] ?? [];
1000
+ const nextRun = preparedRuns[index] ?? [];
1001
+ const lockedAfter = lockedEntries[index];
1002
+ const lastLocked = lockedEntries.at(-1);
1003
+ const insertAt = sourceRun.length === 0 ? lockedAfter ? lockedAfter[1] : lastLocked ? PathApi.next(lastLocked[1]) : null : null;
1004
+ if (writeUnlockedRun(tx, sourceRun, nextRun, insertAt)) mutated = true;
1005
+ }
1006
+ if (mutated) afterCommit(({ snapshot }) => publish(changeId, snapshot.children));
1007
+ return true;
1008
+ });
1009
+ } finally {
1010
+ unsubscribe();
1011
+ }
1012
+ if (lockedRefusal || !proposed) {
1013
+ context.store.set({ refusalMessage: LOCKED_BLOCK_REFUSAL_MESSAGE });
1014
+ return false;
1015
+ }
1016
+ if (publishedChangeId === null) publish(null);
1017
+ return publishedChangeId !== null;
1018
+ }
666
1019
  const parsed = editor.api.markdown.parseSlice(content);
667
1020
  if (!parsed.ok) {
668
1021
  const result = decideCurrentChange("reject");
@@ -676,12 +1029,8 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
676
1029
  if (targetKeys.length === 0 || new Set(targetKeys).size !== targetKeys.length) return false;
677
1030
  let target = suggestionTarget;
678
1031
  if (!target) {
679
- const entries = targetKeys.flatMap((key) => {
680
- const entry = actionEditor.read.nodes.get(key, { match: ElementApi.isElement });
681
- return entry ? [entry] : [];
682
- });
683
- if (entries.length !== targetKeys.length) return false;
684
- const ordered = entries.toSorted(([, a], [, b]) => PathApi.compare(a, b));
1032
+ const ordered = resolveOrderedTargetEntries(actionEditor, targetKeys);
1033
+ if (!ordered) return false;
685
1034
  const first = ordered[0];
686
1035
  const last = ordered.at(-1);
687
1036
  if (!first || !last) return false;
@@ -712,24 +1061,13 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
712
1061
  }
713
1062
  const nextNodes = parseSuggestion(parsed.slice.content, target);
714
1063
  if (suggestion && actionEditor.read.children() !== suggestion.children) return false;
715
- const previous = currentChangeId ? editor.plugin(AuthoredPlugin).read.change(currentChangeId) : null;
716
- if (previous) {
717
- let withdrawn = false;
718
- actionEditor.update((tx, { afterCommit }) => {
719
- tx.history.merge();
720
- tx.plugin(AuthoredPlugin).withdraw([previous]);
721
- afterCommit(({ snapshot }) => {
722
- withdrawn = true;
723
- suggestion &&= {
724
- ...suggestion,
725
- children: snapshot.children
726
- };
727
- });
728
- });
729
- if (!withdrawn || suggestion && actionEditor.read.children() !== suggestion.children) return false;
730
- }
1064
+ if (!withdrawPendingChange(actionEditor, currentChangeId)) return false;
731
1065
  const response = parsed.slice.content.filter((node) => ElementApi.isElement(node));
732
1066
  let publishedChangeId = null;
1067
+ let lockedRefusal = false;
1068
+ const unsubscribe = subscribeEditorRefusals(actionEditor, (record) => {
1069
+ if (isLockRefusalRecord(record)) lockedRefusal = true;
1070
+ });
733
1071
  const publish = (changeId, children = actionEditor.read.children()) => {
734
1072
  publishedChangeId = changeId;
735
1073
  suggestion = {
@@ -739,7 +1077,8 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
739
1077
  suggestionTarget = target;
740
1078
  context.store.set({
741
1079
  _changeId: changeId,
742
- previewValue: []
1080
+ previewValue: [],
1081
+ refusalMessage: null
743
1082
  });
744
1083
  const published = pendingChange();
745
1084
  if (published) responseAuthor = {
@@ -747,13 +1086,23 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
747
1086
  requestId: context.store.get("_requestId")
748
1087
  };
749
1088
  };
750
- if (actionEditor.update((tx, { afterCommit }) => {
751
- const changeId = tx.plugin(AuthoredPlugin).propose(currentChangeId ? { changeId: currentChangeId } : void 0);
752
- if (currentChangeId) tx.history.merge();
753
- else tx.history.newBatch();
754
- if (writeSuggestion(tx, target, nextNodes)) afterCommit(({ snapshot }) => publish(changeId, snapshot.children));
755
- return true;
756
- }) && publishedChangeId === null) publish(null);
1089
+ let proposed;
1090
+ try {
1091
+ proposed = actionEditor.update((tx, { afterCommit }) => {
1092
+ const changeId = tx.plugin(AuthoredPlugin).propose(currentChangeId ? { changeId: currentChangeId } : void 0);
1093
+ if (currentChangeId) tx.history.merge();
1094
+ else tx.history.newBatch();
1095
+ if (writeSuggestion(tx, target, nextNodes)) afterCommit(({ snapshot }) => publish(changeId, snapshot.children));
1096
+ return true;
1097
+ });
1098
+ } finally {
1099
+ unsubscribe();
1100
+ }
1101
+ if (lockedRefusal) {
1102
+ context.store.set({ refusalMessage: LOCKED_BLOCK_REFUSAL_MESSAGE });
1103
+ return false;
1104
+ }
1105
+ if (proposed && publishedChangeId === null) publish(null);
757
1106
  return publishedChangeId !== null;
758
1107
  };
759
1108
  const acceptAIResponse = (commandEditor) => {
@@ -764,7 +1113,36 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
764
1113
  }
765
1114
  responseAuthor = null;
766
1115
  if (tableDraft.size > 0) {
767
- landAndClose(getActionEditor(commandEditor), (tx) => {
1116
+ const actionEditor = getActionEditor(commandEditor);
1117
+ if (!actionEditor || actionEditor.read.view.isReadOnly()) return;
1118
+ const lockedKeys = [];
1119
+ let remainingTable = null;
1120
+ for (const [key] of tableDraft) {
1121
+ const entry = resolveTargetRoot(commandEditor, key)?.root === actionEditor.read.view.root() ? actionEditor.read.nodes.get(key, { match: ElementApi.isElement }) : void 0;
1122
+ if (!entry) continue;
1123
+ if (isAIPathNonWritable(actionEditor, entry[1])) lockedKeys.push(key);
1124
+ else if (!remainingTable) remainingTable = actionEditor.read.nodes.above({
1125
+ at: entry[1],
1126
+ match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type
1127
+ }) ?? null;
1128
+ }
1129
+ if (lockedKeys.length > 0) {
1130
+ for (const key of lockedKeys) tableDraft.delete(key);
1131
+ if (tableDraft.size === 0) {
1132
+ context.store.set({
1133
+ previewValue: [],
1134
+ refusalMessage: "All staged table cells are now locked. Unlock a cell or discard this draft."
1135
+ });
1136
+ return;
1137
+ }
1138
+ const preview = remainingTable ? buildTableDraftPreview(actionEditor, remainingTable[0], remainingTable[1]) : null;
1139
+ context.store.set({
1140
+ previewValue: preview && ElementApi.isElement(preview) ? [preview] : [],
1141
+ refusalMessage: "Locked table cells were removed from this draft. Click Accept again to apply the remaining unlocked cells."
1142
+ });
1143
+ return;
1144
+ }
1145
+ landAndClose(actionEditor, (tx) => {
768
1146
  const targets = [...tableDraft].map(([key, draft]) => ({
769
1147
  draft,
770
1148
  entry: resolveTargetRoot(commandEditor, key)?.root === tx.view.root() ? tx.nodes.get(key, { match: ElementApi.isElement }) : void 0
@@ -780,14 +1158,15 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
780
1158
  completeDetachedOutput(commandEditor, "replaceSelection", "single");
781
1159
  return;
782
1160
  }
783
- landAndClose(getActionEditor(commandEditor), (tx) => {
1161
+ const actionEditor = getActionEditor(commandEditor);
1162
+ landAndClose(actionEditor, (tx) => {
784
1163
  const output = getActionPreviewSource();
785
1164
  const blockKey = context.store.get("_blockKey");
786
1165
  const target = blockKey ? tx.nodes.get(blockKey, { match: ElementApi.isElement }) : void 0;
787
1166
  if (!target || !output) return false;
788
1167
  tx.history.newBatch();
789
1168
  const [node, path] = target;
790
- const replace = node.type === paragraph.schema.type && tx.nodes.isEmpty(node);
1169
+ const replace = node.type === paragraph.schema.type && tx.nodes.isEmpty(node) && !(actionEditor && hasNonWritableAt(actionEditor, path));
791
1170
  const [anchor, anchorPath] = replace ? target : resolveInsertionAnchor(editor, tx, target);
792
1171
  const firstPath = replace ? path : PathApi.next(anchorPath);
793
1172
  const firstIndex = firstPath.at(-1);
@@ -831,6 +1210,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
831
1210
  const blocks = formatAIOutput({
832
1211
  blocks: cloneDeep(source),
833
1212
  format,
1213
+ schema: editor.read.schema,
834
1214
  sourceBlock: block[0]
835
1215
  });
836
1216
  if (!blocks) return false;
@@ -863,6 +1243,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
863
1243
  const blocks = formatAIOutput({
864
1244
  blocks: cloneDeep(source),
865
1245
  format: format === "single" && selected.length > 1 ? "none" : format,
1246
+ schema: editor.read.schema,
866
1247
  sourceBlock: sourceBlock[0]
867
1248
  });
868
1249
  if (!blocks) return false;
@@ -953,16 +1334,29 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
953
1334
  previewParse = void 0;
954
1335
  context.store.set({
955
1336
  _blockKey: null,
1337
+ _lockedBlockRefs: {},
956
1338
  _requestId: null,
957
- previewValue: []
1339
+ previewValue: [],
1340
+ refusalMessage: null
958
1341
  });
959
1342
  tableDraft.clear();
960
1343
  if (!restoreTarget(commandEditor)) return void 0;
961
1344
  captureTarget(commandEditor);
962
1345
  aiChatCommandEditors.set(editor, commandEditor);
963
- context.store.set({ _requestId: crypto.randomUUID() });
1346
+ const selection = commandEditor.read.selection() ?? editor.read.selection();
1347
+ const viewNodes = commandEditor.read.selection.nodes();
1348
+ const selectedNodePaths = (viewNodes.length ? viewNodes : editor.read.selection.nodes()).map(([, path]) => [...path]);
1349
+ const requestContext = getRequestContext(commandEditor, selection ?? null, selectedNodePaths);
1350
+ if (toolName === "edit" && !hasEditableRequestTarget(commandEditor, selection ?? null, selectedNodePaths, requestContext)) {
1351
+ context.store.set({
1352
+ refusalMessage: "All selected blocks are locked. Unlock a block or insert below instead.",
1353
+ streaming: false
1354
+ });
1355
+ return result;
1356
+ }
1357
+ context.store.set({ _requestId: createRequestId() });
964
1358
  chat?.regenerate({ body: { ctx: {
965
- ...getRequestContext(commandEditor, commandEditor.read.selection() ?? editor.read.selection()),
1359
+ ...requestContext,
966
1360
  toolName
967
1361
  } } });
968
1362
  return result;
@@ -980,7 +1374,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
980
1374
  setPreview: (content, { final = true, requestId } = {}) => {
981
1375
  const state = context.store.get();
982
1376
  if (requestId !== void 0 && requestId !== state._requestId) return;
983
- if (state.toolName === "edit" && state.mode === "chat") return applySuggestion(commandEditor, content, { requestId });
1377
+ if (state.toolName === "edit" && state.mode === "chat") {
1378
+ if (!final && Object.keys(state._lockedBlockRefs).length > 0) return;
1379
+ return applySuggestion(commandEditor, content, { requestId });
1380
+ }
984
1381
  const ownerRequestId = requestId ?? state._requestId;
985
1382
  const invalidatePreview = () => {
986
1383
  previewOwner = {
@@ -1050,6 +1447,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1050
1447
  if (!actionEditor || actionEditor.read.view.root() !== getActionEditor(commandEditor)?.read.view.root()) return;
1051
1448
  const cell = actionEditor.read.nodes.get(target.key, { match: ElementApi.isElement });
1052
1449
  if (!cell) return;
1450
+ if (isAIPathNonWritable(actionEditor, cell[1])) {
1451
+ context.store.set({ refusalMessage: "One or more locked table cells were skipped and left unchanged." });
1452
+ return;
1453
+ }
1053
1454
  const table = actionEditor.read.nodes.above({
1054
1455
  at: cell[1],
1055
1456
  match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type
@@ -1062,16 +1463,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1062
1463
  block: cell[0].children.find((node) => ElementApi.isElement(node)),
1063
1464
  kind: "replaced"
1064
1465
  }) });
1065
- const previewNode = (node, path) => {
1066
- if (!ElementApi.isElement(node)) return node;
1067
- const key = actionEditor.key(path);
1068
- const draft = key ? tableDraft.get(key) : void 0;
1069
- return {
1070
- ...node,
1071
- children: draft?.children ?? node.children.map((child, index) => previewNode(child, [...path, index]))
1072
- };
1073
- };
1074
- const preview = previewNode(table[0], table[1]);
1466
+ const preview = buildTableDraftPreview(actionEditor, table[0], table[1]);
1075
1467
  if (!ElementApi.isElement(preview)) return;
1076
1468
  context.store.set({
1077
1469
  _blockKey: actionEditor.key(table[0]),
@@ -1094,7 +1486,9 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1094
1486
  previewParse = void 0;
1095
1487
  context.store.set({
1096
1488
  _blockKey: null,
1097
- previewValue: []
1489
+ _lockedBlockRefs: {},
1490
+ previewValue: [],
1491
+ refusalMessage: null
1098
1492
  });
1099
1493
  tableDraft.clear();
1100
1494
  if (isOpen && !restoreTarget(commandEditor)) return discarded;
@@ -1116,7 +1510,14 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1116
1510
  });
1117
1511
  const promptText = prompt === void 0 ? resolvedPrompt : commandEditor.plugin(AIChatPlugin).read.resolvePlaceholders(resolvedPrompt, { prompt: input });
1118
1512
  const requestContext = getRequestContext(commandEditor, selection ?? null, selectedNodePaths);
1119
- context.store.set({ _requestId: crypto.randomUUID() });
1513
+ if (nextToolName === "edit" && !hasEditableRequestTarget(commandEditor, selection ?? null, selectedNodePaths, requestContext)) {
1514
+ context.store.set({
1515
+ refusalMessage: "All selected blocks are locked. Unlock a block or insert below instead.",
1516
+ streaming: false
1517
+ });
1518
+ return discarded;
1519
+ }
1520
+ context.store.set({ _requestId: createRequestId() });
1120
1521
  chat?.sendMessage(promptText, {
1121
1522
  body: { ctx: {
1122
1523
  ...requestContext,