platejs 54.0.0-beta.7 → 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 (218) hide show
  1. package/dist/{AIChatRequestContext-DVGOeWhQ.d.ts → AIChatRequestContext-PbXTTovP.d.ts} +4 -2
  2. package/dist/{BaseSuggestionPlugin-BRFMMyEo.d.ts → BaseSuggestionPlugin-Dg-cdX26.d.ts} +10 -4
  3. package/dist/{PlateStatic-DIwBAVqF.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 +498 -103
  9. package/dist/ai/react/CopilotPlugin.js +37 -6
  10. package/dist/ai/react/aiOutputLanding.internal.js +19 -4
  11. package/dist/ai/react/index.d.ts +42 -9
  12. package/dist/authored/index.d.ts +4 -4
  13. package/dist/authored/index.js +2 -2
  14. package/dist/code-block/codemirror/index.d.ts +1 -1
  15. package/dist/{combobox-CfCJYKT0.d.ts → combobox-CUUSZR07.d.ts} +2 -2
  16. package/dist/compiler/index.d.ts +2 -2
  17. package/dist/{core-Cqc_KzpG.d.ts → core-D8i_gkA6.d.ts} +173 -106
  18. package/dist/diff/index.d.ts +3 -30
  19. package/dist/docs/api/core/plate-plugin.md +10 -9
  20. package/dist/docs/api/core.md +10 -5
  21. package/dist/docs/api/document-change.md +17 -10
  22. package/dist/docs/api/react-hooks.md +11 -5
  23. package/dist/docs/authored-changes.md +9 -6
  24. package/dist/docs/board.md +5 -4
  25. package/dist/docs/bold.md +0 -2
  26. package/dist/docs/document-model.md +3 -3
  27. package/dist/docs/docx.md +44 -0
  28. package/dist/docs/editor-methods.md +3 -3
  29. package/dist/docs/examples/version-history.md +1 -1
  30. package/dist/docs/footnote.md +80 -28
  31. package/dist/docs/html.md +10 -5
  32. package/dist/docs/indent.md +7 -5
  33. package/dist/docs/ink.md +18 -20
  34. package/dist/docs/installation/node.md +1 -1
  35. package/dist/docs/list.md +23 -3
  36. package/dist/docs/llms.txt +4 -3
  37. package/dist/docs/lock.md +264 -0
  38. package/dist/docs/markdown.md +13 -96
  39. package/dist/docs/plugin-context.md +14 -10
  40. package/dist/docs/serializing.md +26 -3
  41. package/dist/docs/static.md +19 -5
  42. package/dist/docx/export/index.d.ts +3 -3
  43. package/dist/docx/export/lib/exportDocx.js +58 -12
  44. package/dist/docx/import/index.d.ts +4 -4
  45. package/dist/docx/paste/index.d.ts +4 -4
  46. package/dist/dom/index.d.ts +1 -1
  47. package/dist/excalidraw/index.d.ts +3 -3
  48. package/dist/excalidraw/react/index.d.ts +3 -3
  49. package/dist/facade.js +2 -2
  50. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +1 -1
  51. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +27 -6
  52. package/dist/features/basic-nodes/lib/BaseMarkPlugins.js +64 -12
  53. package/dist/features/board/index.d.ts +1 -1
  54. package/dist/features/board/lib/boardTypes.internal.js +3 -0
  55. package/dist/features/callout/index.d.ts +3 -3
  56. package/dist/features/callout/lib/BaseCalloutPlugin.js +1 -4
  57. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +1 -2
  58. package/dist/features/combobox/index.d.ts +2 -2
  59. package/dist/features/combobox/lib/filterWords.js +7 -11
  60. package/dist/features/comments/index.d.ts +1 -1
  61. package/dist/features/date/index.d.ts +3 -3
  62. package/dist/features/details/index.d.ts +4 -3
  63. package/dist/features/details/lib/BaseDetailsPlugin.js +228 -122
  64. package/dist/features/field/index.d.ts +1 -1
  65. package/dist/features/field/lib/BaseFieldPlugin.js +18 -2
  66. package/dist/features/find/index.d.ts +3 -3
  67. package/dist/features/footnote/index.d.ts +1 -1
  68. package/dist/features/footnote/lib/BaseFootnotePlugin.js +9 -2
  69. package/dist/features/ink/index.d.ts +2 -2
  70. package/dist/features/ink/lib/BaseInkPlugin.js +118 -82
  71. package/dist/features/ink/lib/inkMatch.internal.js +79 -78
  72. package/dist/features/ink/lib/inkPlaces.internal.js +166 -535
  73. package/dist/features/layout/index.d.ts +1 -1
  74. package/dist/features/layout/lib/BaseColumnPlugin.js +37 -14
  75. package/dist/features/link/lib/BaseLinkPlugin.js +38 -3
  76. package/dist/features/lint/index.d.ts +3 -3
  77. package/dist/features/list/lib/BaseListPlugin.js +30 -11
  78. package/dist/features/list/lib/listFamily.internal.js +2 -2
  79. package/dist/features/list/lib/listHtml.internal.js +1 -0
  80. package/dist/features/lock/index.d.ts +2 -0
  81. package/dist/features/lock/index.js +2 -0
  82. package/dist/features/lock/lib/BaseLockPlugin.js +526 -0
  83. package/dist/features/media/index.d.ts +1 -1
  84. package/dist/features/mention/index.d.ts +5 -5
  85. package/dist/features/suggestion/index.d.ts +1 -1
  86. package/dist/features/table/index.d.ts +1 -1
  87. package/dist/features/toc/index.d.ts +1 -1
  88. package/dist/features/upload/index.d.ts +1 -1
  89. package/dist/features/upload/lib/BaseUploadPlugin.js +5 -4
  90. package/dist/history/index.d.ts +2 -2
  91. package/dist/html/index.d.ts +3 -3
  92. package/dist/html/server/index.d.ts +1 -1
  93. package/dist/html/server/index.js +2 -1
  94. package/dist/html/server/serverCssParser.internal.js +500 -0
  95. package/dist/html/server/serverCssStyle.internal.js +208 -0
  96. package/dist/{htmlTypes-i_FBCMf2.d.ts → htmlTypes-zTLU3aTb.d.ts} +9 -13
  97. package/dist/hyperscript/index.d.ts +1 -1
  98. package/dist/index-0YxPsHwd.d.ts +1 -0
  99. package/dist/{index-Bv13FX9o.d.ts → index-3CExu_fj.d.ts} +3 -3
  100. package/dist/{index-CTTjpWgb-Fdrn8NP4.d.ts → index-4PpawhYe-yelJvgk1.d.ts} +1 -1
  101. package/dist/{index-B4ZhSQdk.d.ts → index-BCYBYfGM.d.ts} +3 -3
  102. package/dist/{index-CJGkjkH6.d.ts → index-BODDOPEd.d.ts} +1 -1
  103. package/dist/{index-DNXr_SN-.d.ts → index-BPOa4Z5n.d.ts} +9 -3
  104. package/dist/{index-Cc2ajXAd.d.ts → index-BSBkt2bm.d.ts} +44 -48
  105. package/dist/{index-CLNem74G.d.ts → index-BeyI3RUg.d.ts} +42 -39
  106. package/dist/{index-CmISVYmz.d.ts → index-BisOdLXI.d.ts} +14 -49
  107. package/dist/{index-CVAHIQ3p.d.ts → index-Bt5YI_JN.d.ts} +4 -4
  108. package/dist/{index-CrJ9Km8W.d.ts → index-CD_Ym9WQ.d.ts} +2 -2
  109. package/dist/{index-KteL56rA.d.ts → index-CX_JaDRY.d.ts} +4 -3
  110. package/dist/{index-BI0NS7kx.d.ts → index-CfK4uv4I.d.ts} +3 -3
  111. package/dist/{index-By7BkzIN.d.ts → index-CfRUKYCM.d.ts} +2 -2
  112. package/dist/{index-OMa7dlcS.d.ts → index-Cil7kghY.d.ts} +5 -5
  113. package/dist/index-D11C0iLb.d.ts +97 -0
  114. package/dist/{index-CS4G_W_R.d.ts → index-DJW6AjJ6.d.ts} +1 -1
  115. package/dist/{comparison-types-CsmDG5r2-z1s4gX06.d.ts → index-DM-b6jEe-BqkdOlav.d.ts} +19 -57
  116. package/dist/{index-1PlYsibA.d.ts → index-DoZhM7nD.d.ts} +3 -3
  117. package/dist/{index-DfkFmApH.d.ts → index-DsNwo8dd.d.ts} +35 -14
  118. package/dist/{index-CxG1Atvg.d.ts → index-DuElD_q6.d.ts} +3 -3
  119. package/dist/{index-BWCC4DCP.d.ts → index-f3aV3Kt-.d.ts} +5 -5
  120. package/dist/{index-uVbqCpDa.d.ts → index-u_h6ow4e.d.ts} +3 -3
  121. package/dist/{index-1rcWTB-o.d.ts → index-yZDmK6ab.d.ts} +3 -3
  122. package/dist/index.d.ts +3 -3
  123. package/dist/internal/plugin/OverridePlugin.js +22 -3
  124. package/dist/internal/plugin/blockInsertion.js +4 -4
  125. package/dist/internal/plugin/collectPlateNodeMappings.js +11 -4
  126. package/dist/internal/plugin/compilePlainTextMappings.js +2 -0
  127. package/dist/internal/plugin/plateRuntime.js +7 -1
  128. package/dist/internal/plugin/resolvePlugin.js +4 -1
  129. package/dist/internal/plugin/resolvePlugins.js +5 -3
  130. package/dist/lib/plugins/html/HtmlPlugin.js +32 -13
  131. package/dist/lib/plugins/html/htmlAst.js +5 -3
  132. package/dist/lib/plugins/html/htmlDom.js +1 -10
  133. package/dist/markdown/index.d.ts +2 -2
  134. package/dist/markdown/index.js +1 -2
  135. package/dist/markdown/lib/MarkdownPlugin.js +5 -7
  136. package/dist/markdown/lib/deserializer/convertNodesDeserialize.js +27 -3
  137. package/dist/markdown/lib/internal/markdownConversion.js +308 -340
  138. package/dist/markdown/lib/internal/markdownIntrinsics.js +36 -71
  139. package/dist/markdown/lib/internal/markdownLine.js +2 -4
  140. package/dist/markdown/lib/internal/markdownMappings.js +21 -3
  141. package/dist/markdown/lib/internal/markdownSafety.js +101 -1
  142. package/dist/markdown/lib/internal/markdownTags.js +2 -26
  143. package/dist/markdown/lib/serializer/convertNodesSerialize.js +5 -3
  144. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +1 -10
  145. package/dist/math/index.d.ts +3 -3
  146. package/dist/math/react/index.d.ts +4 -4
  147. package/dist/migrations/documentMigrationSelection.internal.js +107 -2
  148. package/dist/migrations/documentMigrations.js +17 -112
  149. package/dist/migrations/index.d.ts +3 -3
  150. package/dist/migrations/migratePlateV54.js +41 -40
  151. package/dist/migrations/migratePlateV54Ast.internal.js +143 -55
  152. package/dist/migrations/migratePlateV54CodeBlocks.internal.js +24 -29
  153. package/dist/migrations/migratePlateV54Inputs.internal.js +39 -32
  154. package/dist/migrations/migratePlateV54Profile.internal.js +52 -22
  155. package/dist/migrations/migratePlateV54Stage.internal.js +127 -0
  156. package/dist/migrations/migratePlateV54Urls.internal.js +77 -57
  157. package/dist/pagination/index.d.ts +1 -1
  158. package/dist/pagination/react/index.d.ts +2 -2
  159. package/dist/react/components/NodeSelection.js +8 -1
  160. package/dist/react/components/Plate.js +198 -152
  161. package/dist/react/components/PlateView.js +1 -1
  162. package/dist/{static/internal/getPlainText.js → react/components/getPlainText.internal.js} +1 -4
  163. package/dist/react/components/plate-nodes.js +48 -40
  164. package/dist/{static/internal/writeStaticSelectionClipboardData.js → react/components/writeStaticSelectionClipboardData.internal.js} +3 -4
  165. package/dist/react/features/board/BoardShape.js +48 -22
  166. package/dist/react/features/board/boardConnect.internal.js +0 -9
  167. package/dist/react/features/board/boardKeys.internal.js +41 -12
  168. package/dist/react/features/board/boardPicking.internal.js +0 -17
  169. package/dist/react/features/board/boardResize.internal.js +13 -18
  170. package/dist/react/features/board/boardView.internal.js +37 -8
  171. package/dist/react/features/board/boardVoice.internal.js +17 -4
  172. package/dist/react/features/board/index.d.ts +13 -11
  173. package/dist/react/features/callout/index.d.ts +3 -3
  174. package/dist/react/features/combobox/comboboxOwner.internal.js +10 -4
  175. package/dist/react/features/combobox/index.d.ts +5 -5
  176. package/dist/react/features/comments/index.d.ts +5 -5
  177. package/dist/react/features/date/index.d.ts +4 -4
  178. package/dist/react/features/details/index.d.ts +5 -5
  179. package/dist/react/features/field/index.d.ts +6 -5
  180. package/dist/react/features/footnote/index.d.ts +7 -7
  181. package/dist/react/features/format-painter/index.d.ts +4 -4
  182. package/dist/react/features/ink/InkContent.js +28 -100
  183. package/dist/react/features/ink/InkPlugin.js +12 -23
  184. package/dist/react/features/ink/index.d.ts +29 -102
  185. package/dist/react/features/ink/index.js +1 -2
  186. package/dist/react/features/ink/inkCapture.internal.js +97 -61
  187. package/dist/react/features/ink/inkImages.internal.js +20 -5
  188. package/dist/react/features/ink/inkMeasure.internal.js +35 -22
  189. package/dist/react/features/ink/inkPlacement.internal.js +78 -203
  190. package/dist/react/features/ink/inkWatch.internal.js +1 -32
  191. package/dist/react/features/layout/index.d.ts +5 -5
  192. package/dist/react/features/lock/LockPlugin.js +66 -0
  193. package/dist/react/features/lock/index.d.ts +58 -0
  194. package/dist/react/features/lock/index.js +2 -0
  195. package/dist/react/features/media/index.d.ts +5 -5
  196. package/dist/react/features/mention/index.d.ts +6 -6
  197. package/dist/react/features/suggestion/index.d.ts +6 -6
  198. package/dist/react/features/table/index.d.ts +5 -5
  199. package/dist/react/features/toc/index.d.ts +2 -2
  200. package/dist/react/features/upload/index.d.ts +5 -5
  201. package/dist/react/index.d.ts +4 -4
  202. package/dist/react/utils/pipeRenderElement.internal.js +32 -30
  203. package/dist/react/virtualized.d.ts +2 -2
  204. package/dist/{source-Dcgqj5Mf.d.ts → source-B1rLozUs.d.ts} +3 -3
  205. package/dist/static/components/plite-nodes.js +1 -1
  206. package/dist/static/index.d.ts +8 -10
  207. package/dist/static/pluginRenderLeafStatic.internal.js +1 -2
  208. package/dist/tabbable/index.d.ts +1 -1
  209. package/dist/tabbable/react/index.d.ts +3 -3
  210. package/dist/testing/index.d.ts +2 -2
  211. package/dist/{tx-only-1FM45FSj-D40jacZv.d.ts → tx-only-D8lpB-sT-ZiAbZRMU.d.ts} +133 -59
  212. package/dist/yjs/index.d.ts +1 -1
  213. package/dist/yjs/react/index.d.ts +5 -5
  214. package/package.json +16 -3
  215. package/dist/features/ink/lib/inkGone.internal.js +0 -290
  216. package/dist/markdown/lib/RawHtmlPlugin.js +0 -26
  217. package/dist/markdown/lib/internal/markdownRawHtml.js +0 -353
  218. package/dist/react/features/ink/InkCopyView.js +0 -214
@@ -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({
@@ -175,8 +189,15 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
175
189
  };
176
190
  };
177
191
  const stop = () => {
192
+ const hasLockedRefs = Object.keys(context.store.get("_lockedBlockRefs")).length > 0;
178
193
  context.store.get().chat?.stop?.();
179
- context.store.set({ streaming: false });
194
+ context.store.set({
195
+ ...hasLockedRefs ? {
196
+ _lockedBlockRefs: {},
197
+ _requestId: null
198
+ } : {},
199
+ streaming: false
200
+ });
180
201
  };
181
202
  const cancel = () => {
182
203
  context.store.set({
@@ -250,6 +271,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
250
271
  _blockKey: null,
251
272
  _blockRefs: {},
252
273
  _changeId: null,
274
+ _lockedBlockRefs: {},
253
275
  _requestId: null,
254
276
  _tableCellRefs: {},
255
277
  chatNodeMode: null,
@@ -257,6 +279,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
257
279
  chatSelection: null,
258
280
  mode: "insert",
259
281
  previewValue: [],
282
+ refusalMessage: null,
260
283
  toolName: null
261
284
  });
262
285
  try {
@@ -274,7 +297,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
274
297
  return result;
275
298
  };
276
299
  const hideOptions = () => {
277
- context.store.set({ open: false });
300
+ context.store.set({
301
+ open: false,
302
+ refusalMessage: null
303
+ });
278
304
  };
279
305
  const promptMarkdown = (options) => {
280
306
  const result = editor.api.markdown.serialize({
@@ -352,7 +378,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
352
378
  const tableNodes = tableView?.read.nodes ?? state.nodes;
353
379
  const tableKey = (path) => tableView ? tableView.key(path) : state.key(path);
354
380
  const selectedNodeKeys = new Set(cells.map(([, path]) => tableKey(path)));
355
- 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
+ });
356
385
  if (!tableEntry) return "";
357
386
  const [table, tablePath] = tableEntry;
358
387
  const refs = {};
@@ -361,12 +390,14 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
361
390
  if (!ElementApi.isElement(row) || row.type !== editor.plugin(BaseTableRowPlugin).schema.type) throw new Error("Tables must contain table rows.");
362
391
  const values = row.children.map((cell, cellIndex) => {
363
392
  if (!ElementApi.isElement(cell) || cell.type !== editor.plugin(BaseTableCellPlugin).schema.type) throw new Error("Table rows must contain table cells.");
364
- const nodeKey = tableKey([
393
+ const cellPath = [
365
394
  ...tablePath,
366
395
  rowIndex,
367
396
  cellIndex
368
- ]);
369
- 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) {
370
401
  const ref = `c${selectedCells.length + 1}`;
371
402
  refs[ref] = { key: nodeKey };
372
403
  selectedCells.push({
@@ -447,18 +478,47 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
447
478
  }];
448
479
  });
449
480
  const tableCellRefs = {};
450
- 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;
451
509
  const key = requestEditor.key(path);
452
- if (!key) return [];
453
- const ref = `c${index + 1}`;
454
- tableCellRefs[ref] = { key };
455
- return [{
510
+ if (!key) continue;
511
+ lockedRefIndex += 1;
512
+ const ref = `l${lockedRefIndex}`;
513
+ lockedBlockRefs[ref] = { key };
514
+ lockedBlocks.push({
456
515
  path: inScope(path),
457
516
  ref
458
- }];
459
- }) : [];
517
+ });
518
+ }
460
519
  context.store.set({
461
520
  _blockRefs: blockRefs,
521
+ _lockedBlockRefs: lockedBlockRefs,
462
522
  _tableCellRefs: tableCellRefs
463
523
  });
464
524
  return {
@@ -466,11 +526,40 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
466
526
  nodeSelection,
467
527
  refs: {
468
528
  blocks,
529
+ ...lockedBlocks.length > 0 ? { lockedBlocks } : {},
469
530
  tableCells
470
531
  },
471
532
  selection: requestAt
472
533
  };
473
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
+ };
474
563
  const resolvePrompt = (prompt, params) => {
475
564
  if (typeof prompt === "function") return prompt(params);
476
565
  if (typeof prompt === "string") return prompt;
@@ -512,7 +601,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
512
601
  const sourceNode = source[index];
513
602
  if (!ElementApi.isElement(node) || !ElementApi.isElement(sourceNode) || sourceNode.type !== node.type) return node;
514
603
  return {
515
- ...NodeApi.extractProps(sourceNode),
604
+ ...extractCopiedBlockProps(sourceNode, editor.read.schema, { preserveIdentity: true }),
516
605
  ...node,
517
606
  children: node.children
518
607
  };
@@ -526,15 +615,33 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
526
615
  }
527
616
  };
528
617
  const landAndClose = (actionEditor, land) => {
618
+ if (!actionEditor) return;
529
619
  let closed = false;
530
- if (actionEditor?.update((tx, { afterCommit }) => {
531
- if (!land(tx)) return false;
532
- afterCommit(() => {
533
- closed = true;
534
- 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;
535
636
  });
536
- return true;
537
- }) && !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();
538
645
  };
539
646
  const getActionChatBlocks = (tx) => {
540
647
  const chatNodes = context.store.get("chatNodes");
@@ -561,6 +668,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
561
668
  const blocks = formatAIOutput({
562
669
  blocks: source,
563
670
  format: anchor === target ? format : "none",
671
+ schema: editor.read.schema,
564
672
  sourceBlock: target[0]
565
673
  });
566
674
  if (!blocks) return false;
@@ -620,43 +728,144 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
620
728
  const entry = tx.nodes.get(path, { match: ElementApi.isElement });
621
729
  return entry ? [entry[0]] : [];
622
730
  });
623
- if (target.kind === "blocks" && sourceNodes.length === paths.length && isEqual(sourceNodes.map(withoutText), nextNodes.map(withoutText))) {
624
- const edits = sourceNodes.flatMap((sourceNode, blockIndex) => {
625
- const nextNode = nextNodes[blockIndex];
626
- const blockPath = paths[blockIndex];
627
- if (!nextNode || !blockPath) return [];
628
- const afterTexts = [...NodeApi.texts(nextNode)];
629
- return [...NodeApi.texts(sourceNode)].flatMap(([before, path], textIndex) => {
630
- const after = afterTexts[textIndex]?.[0];
631
- return after && before.text !== after.text ? textEdits(before.text, after.text).map((edit) => ({
632
- ...edit,
633
- path: [...blockPath, ...path]
634
- })) : [];
635
- });
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
+ })) : [];
636
759
  });
637
- for (const { from, path, text, to } of edits.toSorted((left, right) => PathApi.compare(right.path, left.path) || right.from - left.from)) {
638
- if (to > from) tx.text.delete({ at: {
639
- anchor: {
640
- offset: from,
641
- path
642
- },
643
- focus: {
644
- offset: to,
645
- path
646
- }
647
- } });
648
- 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: {
649
764
  offset: from,
650
765
  path
651
- } });
652
- }
653
- 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
+ } });
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;
654
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;
655
861
  return tx.slice.replace(ContentSlice.fromJSON({
656
- content: nextNodes,
862
+ content: cloneDeep([...nextNodes]),
657
863
  openEnd: 0,
658
864
  openStart: 0
659
- }), { at: target.range });
865
+ }), { at: {
866
+ anchor,
867
+ focus
868
+ } });
660
869
  };
661
870
  const applySuggestion = (commandEditor, content, { requestId } = {}) => {
662
871
  const state = context.store.get();
@@ -669,6 +878,144 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
669
878
  const capturedSelection = resolveChatSelection();
670
879
  if (state.chatSelection && !capturedSelection) return false;
671
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
+ }
672
1019
  const parsed = editor.api.markdown.parseSlice(content);
673
1020
  if (!parsed.ok) {
674
1021
  const result = decideCurrentChange("reject");
@@ -682,12 +1029,8 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
682
1029
  if (targetKeys.length === 0 || new Set(targetKeys).size !== targetKeys.length) return false;
683
1030
  let target = suggestionTarget;
684
1031
  if (!target) {
685
- const entries = targetKeys.flatMap((key) => {
686
- const entry = actionEditor.read.nodes.get(key, { match: ElementApi.isElement });
687
- return entry ? [entry] : [];
688
- });
689
- if (entries.length !== targetKeys.length) return false;
690
- const ordered = entries.toSorted(([, a], [, b]) => PathApi.compare(a, b));
1032
+ const ordered = resolveOrderedTargetEntries(actionEditor, targetKeys);
1033
+ if (!ordered) return false;
691
1034
  const first = ordered[0];
692
1035
  const last = ordered.at(-1);
693
1036
  if (!first || !last) return false;
@@ -718,24 +1061,13 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
718
1061
  }
719
1062
  const nextNodes = parseSuggestion(parsed.slice.content, target);
720
1063
  if (suggestion && actionEditor.read.children() !== suggestion.children) return false;
721
- const previous = currentChangeId ? editor.plugin(AuthoredPlugin).read.change(currentChangeId) : null;
722
- if (previous) {
723
- let withdrawn = false;
724
- actionEditor.update((tx, { afterCommit }) => {
725
- tx.history.merge();
726
- tx.plugin(AuthoredPlugin).withdraw([previous]);
727
- afterCommit(({ snapshot }) => {
728
- withdrawn = true;
729
- suggestion &&= {
730
- ...suggestion,
731
- children: snapshot.children
732
- };
733
- });
734
- });
735
- if (!withdrawn || suggestion && actionEditor.read.children() !== suggestion.children) return false;
736
- }
1064
+ if (!withdrawPendingChange(actionEditor, currentChangeId)) return false;
737
1065
  const response = parsed.slice.content.filter((node) => ElementApi.isElement(node));
738
1066
  let publishedChangeId = null;
1067
+ let lockedRefusal = false;
1068
+ const unsubscribe = subscribeEditorRefusals(actionEditor, (record) => {
1069
+ if (isLockRefusalRecord(record)) lockedRefusal = true;
1070
+ });
739
1071
  const publish = (changeId, children = actionEditor.read.children()) => {
740
1072
  publishedChangeId = changeId;
741
1073
  suggestion = {
@@ -745,7 +1077,8 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
745
1077
  suggestionTarget = target;
746
1078
  context.store.set({
747
1079
  _changeId: changeId,
748
- previewValue: []
1080
+ previewValue: [],
1081
+ refusalMessage: null
749
1082
  });
750
1083
  const published = pendingChange();
751
1084
  if (published) responseAuthor = {
@@ -753,13 +1086,23 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
753
1086
  requestId: context.store.get("_requestId")
754
1087
  };
755
1088
  };
756
- if (actionEditor.update((tx, { afterCommit }) => {
757
- const changeId = tx.plugin(AuthoredPlugin).propose(currentChangeId ? { changeId: currentChangeId } : void 0);
758
- if (currentChangeId) tx.history.merge();
759
- else tx.history.newBatch();
760
- if (writeSuggestion(tx, target, nextNodes)) afterCommit(({ snapshot }) => publish(changeId, snapshot.children));
761
- return true;
762
- }) && 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);
763
1106
  return publishedChangeId !== null;
764
1107
  };
765
1108
  const acceptAIResponse = (commandEditor) => {
@@ -770,7 +1113,36 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
770
1113
  }
771
1114
  responseAuthor = null;
772
1115
  if (tableDraft.size > 0) {
773
- 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) => {
774
1146
  const targets = [...tableDraft].map(([key, draft]) => ({
775
1147
  draft,
776
1148
  entry: resolveTargetRoot(commandEditor, key)?.root === tx.view.root() ? tx.nodes.get(key, { match: ElementApi.isElement }) : void 0
@@ -786,14 +1158,15 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
786
1158
  completeDetachedOutput(commandEditor, "replaceSelection", "single");
787
1159
  return;
788
1160
  }
789
- landAndClose(getActionEditor(commandEditor), (tx) => {
1161
+ const actionEditor = getActionEditor(commandEditor);
1162
+ landAndClose(actionEditor, (tx) => {
790
1163
  const output = getActionPreviewSource();
791
1164
  const blockKey = context.store.get("_blockKey");
792
1165
  const target = blockKey ? tx.nodes.get(blockKey, { match: ElementApi.isElement }) : void 0;
793
1166
  if (!target || !output) return false;
794
1167
  tx.history.newBatch();
795
1168
  const [node, path] = target;
796
- 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));
797
1170
  const [anchor, anchorPath] = replace ? target : resolveInsertionAnchor(editor, tx, target);
798
1171
  const firstPath = replace ? path : PathApi.next(anchorPath);
799
1172
  const firstIndex = firstPath.at(-1);
@@ -837,6 +1210,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
837
1210
  const blocks = formatAIOutput({
838
1211
  blocks: cloneDeep(source),
839
1212
  format,
1213
+ schema: editor.read.schema,
840
1214
  sourceBlock: block[0]
841
1215
  });
842
1216
  if (!blocks) return false;
@@ -869,6 +1243,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
869
1243
  const blocks = formatAIOutput({
870
1244
  blocks: cloneDeep(source),
871
1245
  format: format === "single" && selected.length > 1 ? "none" : format,
1246
+ schema: editor.read.schema,
872
1247
  sourceBlock: sourceBlock[0]
873
1248
  });
874
1249
  if (!blocks) return false;
@@ -959,16 +1334,29 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
959
1334
  previewParse = void 0;
960
1335
  context.store.set({
961
1336
  _blockKey: null,
1337
+ _lockedBlockRefs: {},
962
1338
  _requestId: null,
963
- previewValue: []
1339
+ previewValue: [],
1340
+ refusalMessage: null
964
1341
  });
965
1342
  tableDraft.clear();
966
1343
  if (!restoreTarget(commandEditor)) return void 0;
967
1344
  captureTarget(commandEditor);
968
1345
  aiChatCommandEditors.set(editor, commandEditor);
969
- 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() });
970
1358
  chat?.regenerate({ body: { ctx: {
971
- ...getRequestContext(commandEditor, commandEditor.read.selection() ?? editor.read.selection()),
1359
+ ...requestContext,
972
1360
  toolName
973
1361
  } } });
974
1362
  return result;
@@ -986,7 +1374,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
986
1374
  setPreview: (content, { final = true, requestId } = {}) => {
987
1375
  const state = context.store.get();
988
1376
  if (requestId !== void 0 && requestId !== state._requestId) return;
989
- 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
+ }
990
1381
  const ownerRequestId = requestId ?? state._requestId;
991
1382
  const invalidatePreview = () => {
992
1383
  previewOwner = {
@@ -1056,6 +1447,10 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1056
1447
  if (!actionEditor || actionEditor.read.view.root() !== getActionEditor(commandEditor)?.read.view.root()) return;
1057
1448
  const cell = actionEditor.read.nodes.get(target.key, { match: ElementApi.isElement });
1058
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
+ }
1059
1454
  const table = actionEditor.read.nodes.above({
1060
1455
  at: cell[1],
1061
1456
  match: (node) => ElementApi.isElement(node) && node.type === tablePlugin.schema.type
@@ -1068,16 +1463,7 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1068
1463
  block: cell[0].children.find((node) => ElementApi.isElement(node)),
1069
1464
  kind: "replaced"
1070
1465
  }) });
1071
- const previewNode = (node, path) => {
1072
- if (!ElementApi.isElement(node)) return node;
1073
- const key = actionEditor.key(path);
1074
- const draft = key ? tableDraft.get(key) : void 0;
1075
- return {
1076
- ...node,
1077
- children: draft?.children ?? node.children.map((child, index) => previewNode(child, [...path, index]))
1078
- };
1079
- };
1080
- const preview = previewNode(table[0], table[1]);
1466
+ const preview = buildTableDraftPreview(actionEditor, table[0], table[1]);
1081
1467
  if (!ElementApi.isElement(preview)) return;
1082
1468
  context.store.set({
1083
1469
  _blockKey: actionEditor.key(table[0]),
@@ -1100,7 +1486,9 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1100
1486
  previewParse = void 0;
1101
1487
  context.store.set({
1102
1488
  _blockKey: null,
1103
- previewValue: []
1489
+ _lockedBlockRefs: {},
1490
+ previewValue: [],
1491
+ refusalMessage: null
1104
1492
  });
1105
1493
  tableDraft.clear();
1106
1494
  if (isOpen && !restoreTarget(commandEditor)) return discarded;
@@ -1122,7 +1510,14 @@ const AIChatPlugin = definePlugin(PLUGINS.aiChat, {
1122
1510
  });
1123
1511
  const promptText = prompt === void 0 ? resolvedPrompt : commandEditor.plugin(AIChatPlugin).read.resolvePlaceholders(resolvedPrompt, { prompt: input });
1124
1512
  const requestContext = getRequestContext(commandEditor, selection ?? null, selectedNodePaths);
1125
- 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() });
1126
1521
  chat?.sendMessage(promptText, {
1127
1522
  body: { ctx: {
1128
1523
  ...requestContext,