platejs 54.0.0-beta.2 → 54.0.0-beta.3

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 (237) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +56 -0
  3. package/dist/{AIChatRequestContext-BMVWhfPV.d.ts → AIChatRequestContext-DY104TqL.d.ts} +2 -2
  4. package/dist/{BaseSuggestionPlugin-DBl3fqnm.d.ts → BaseSuggestionPlugin-Deo6n6Fs.d.ts} +7 -3
  5. package/dist/{PlateStatic-DhNv2ejp.d.ts → PlateStatic-CJX5bKuv.d.ts} +7 -7
  6. package/dist/ai/index.d.ts +1 -1
  7. package/dist/ai/react/AIChatPlugin.js +113 -78
  8. package/dist/ai/react/CopilotPlugin.js +1 -1
  9. package/dist/ai/react/index.d.ts +23 -16
  10. package/dist/authored/index.d.ts +4 -4
  11. package/dist/code-block/codemirror/createCodeMirrorAdapter.js +12 -9
  12. package/dist/code-block/codemirror/index.d.ts +1 -1
  13. package/dist/{combobox-DkBGgyd3.d.ts → combobox-DAOYWuvC.d.ts} +2 -2
  14. package/dist/{comparison-types-CYnJ35qU.d.ts → comparison-types-Dt-unJZY-DCddmbSD.d.ts} +10 -2
  15. package/dist/compiler/index.d.ts +2 -2
  16. package/dist/{core-BJG8l_mk.d.ts → core-ClHasORr.d.ts} +433 -95
  17. package/dist/diff/index.d.ts +2 -2
  18. package/dist/docs/ai.md +4 -3
  19. package/dist/docs/api/core/plate-components.md +0 -19
  20. package/dist/docs/api/core/plate-controller.md +4 -2
  21. package/dist/docs/api/core/plate-plugin.md +3 -0
  22. package/dist/docs/api/core/plate-store.md +3 -3
  23. package/dist/docs/api/dom.md +14 -4
  24. package/dist/docs/api/editor-transforms.md +2 -1
  25. package/dist/docs/api/react-hooks.md +25 -11
  26. package/dist/docs/authored-changes.md +5 -2
  27. package/dist/docs/basic-blocks.md +42 -29
  28. package/dist/docs/blockquote.md +5 -3
  29. package/dist/docs/board.md +63 -8
  30. package/dist/docs/code-block.md +47 -0
  31. package/dist/docs/discussion.md +1 -1
  32. package/dist/docs/docx.md +1 -1
  33. package/dist/docs/dom-coverage.md +5 -0
  34. package/dist/docs/examples/editable-voids.md +2 -3
  35. package/dist/docs/external-text.md +2 -0
  36. package/dist/docs/field.md +370 -0
  37. package/dist/docs/find.md +9 -6
  38. package/dist/docs/form.md +2 -0
  39. package/dist/docs/heading.md +6 -0
  40. package/dist/docs/installation/manual.md +0 -4
  41. package/dist/docs/link.md +3 -3
  42. package/dist/docs/llms.txt +4 -2
  43. package/dist/docs/markdown.md +176 -8
  44. package/dist/docs/plugin-components.md +13 -10
  45. package/dist/docs/plugin-input-rules.md +4 -12
  46. package/dist/docs/prompt-editor.md +205 -0
  47. package/dist/docs/roots.md +8 -6
  48. package/dist/docs/rtl.md +6 -4
  49. package/dist/docs/selection.md +7 -4
  50. package/dist/docs/suggestion.md +1 -1
  51. package/dist/docs/toolbar.md +26 -30
  52. package/dist/docs/upload.md +106 -17
  53. package/dist/docx/export/index.d.ts +3 -3
  54. package/dist/docx/export/lib/docxStaticComponents.js +12 -2
  55. package/dist/docx/export/lib/exportDocx.js +29 -5
  56. package/dist/docx/export/lib/reviewPart.js +1 -1
  57. package/dist/docx/export/lib/reviewProjection.js +10 -8
  58. package/dist/docx/import/index.d.ts +4 -4
  59. package/dist/docx/paste/index.d.ts +4 -4
  60. package/dist/dom/index.d.ts +1 -6
  61. package/dist/dom/plite-dom.internal.js +2 -2
  62. package/dist/excalidraw/index.d.ts +3 -2
  63. package/dist/excalidraw/react/index.d.ts +3 -2
  64. package/dist/facade.js +2 -2
  65. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +13 -5
  66. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +32 -10
  67. package/dist/features/board/index.d.ts +2 -2
  68. package/dist/features/board/lib/BaseBoardPlugin.js +14 -1
  69. package/dist/features/board/lib/boardStroke.internal.js +13 -1
  70. package/dist/features/board/lib/boardTypes.internal.js +16 -0
  71. package/dist/features/callout/index.d.ts +3 -2
  72. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +14 -5
  73. package/dist/features/combobox/index.d.ts +2 -2
  74. package/dist/features/comments/index.d.ts +1 -1
  75. package/dist/features/date/index.d.ts +3 -2
  76. package/dist/features/details/index.d.ts +3 -2
  77. package/dist/features/details/lib/BaseDetailsPlugin.js +10 -10
  78. package/dist/features/field/index.d.ts +2 -0
  79. package/dist/features/field/index.js +2 -0
  80. package/dist/features/field/lib/BaseFieldPlugin.js +414 -0
  81. package/dist/features/field/lib/fieldRules.internal.js +42 -0
  82. package/dist/features/find/index.d.ts +3 -2
  83. package/dist/features/footnote/index.d.ts +1 -1
  84. package/dist/features/ink/index.d.ts +1 -1
  85. package/dist/features/ink/lib/BaseInkPlugin.js +126 -103
  86. package/dist/features/ink/lib/inkCodec.internal.js +130 -0
  87. package/dist/features/ink/lib/inkGone.internal.js +229 -48
  88. package/dist/features/ink/lib/inkPlaces.internal.js +533 -62
  89. package/dist/features/layout/index.d.ts +1 -1
  90. package/dist/features/link/lib/BaseLinkPlugin.js +6 -4
  91. package/dist/features/lint/index.d.ts +3 -2
  92. package/dist/features/media/index.d.ts +1 -1
  93. package/dist/features/media/lib/media/parseMediaUrl.js +11 -1
  94. package/dist/features/media/lib/media-embed/BaseMediaEmbedPlugin.js +6 -2
  95. package/dist/features/mention/index.d.ts +5 -4
  96. package/dist/features/suggestion/index.d.ts +1 -1
  97. package/dist/features/table/index.d.ts +1 -1
  98. package/dist/features/table/lib/BaseTablePlugin.js +14 -8
  99. package/dist/features/table/lib/internal/selection.js +4 -2
  100. package/dist/features/toc/index.d.ts +1 -1
  101. package/dist/features/upload/index.d.ts +2 -2
  102. package/dist/features/upload/lib/BaseUploadPlugin.js +464 -250
  103. package/dist/history/index.d.ts +2 -2
  104. package/dist/html/index.d.ts +3 -3
  105. package/dist/html/server/index.d.ts +1 -1
  106. package/dist/{htmlTypes-DjeFG3P8.d.ts → htmlTypes-cg_cWsaN.d.ts} +2 -31
  107. package/dist/hyperscript/index.d.ts +1 -1
  108. package/dist/{index-D1CFXA-i.d.ts → index-8WO2vI0U.d.ts} +475 -143
  109. package/dist/{index-DaM37gF6.d.ts → index-B5mYEawV.d.ts} +37 -21
  110. package/dist/{index-Bq3sdm3S.d.ts → index-BZWFoUXt.d.ts} +5 -4
  111. package/dist/{index-DdIRduDG.d.ts → index-C0POz7rg.d.ts} +3 -2
  112. package/dist/{index-Bxfvicyy.d.ts → index-C1_JIhL4.d.ts} +4 -3
  113. package/dist/{index-DC_MNGyu.d.ts → index-C35V_hj0.d.ts} +3 -3
  114. package/dist/{index-kLKMc-pI.d.ts → index-C6ql9pKw.d.ts} +2 -2
  115. package/dist/{index-hsC_sOn2.d.ts → index-C9DiGDVj.d.ts} +35 -5
  116. package/dist/{index-DTgaSxKr.d.ts → index-CLsEe3LY.d.ts} +40 -4
  117. package/dist/{index-CT7miqQN.d.ts → index-CdOLsPaW.d.ts} +29 -9
  118. package/dist/{index-DLA2DUR2.d.ts → index-CktYvOgk.d.ts} +4 -3
  119. package/dist/{index-BBKGrsG3.d.ts → index-Cmuluh6f.d.ts} +1 -1
  120. package/dist/{index-BiQerPJS.d.ts → index-CzLwBZpY.d.ts} +2 -2
  121. package/dist/{index-DzD6BIFJ.d.ts → index-D3-2iM1b.d.ts} +7 -5
  122. package/dist/{index-Cl77E9yr.d.ts → index-DKOFvteF.d.ts} +2 -2
  123. package/dist/{index-iaZOhA76.d.ts → index-DPWyk3lG-DOYwohXO.d.ts} +1 -1
  124. package/dist/index-DQnjqtQa.d.ts +678 -0
  125. package/dist/{index-CcZbqPqk.d.ts → index-Do9pj1GK.d.ts} +73 -39
  126. package/dist/{index-BU6k1Aev.d.ts → index-DpltOCot-A2b3p3Eb.d.ts} +4735 -4586
  127. package/dist/{index-Bc2Yg_2j.d.ts → index-HPYawTae-BCUQLEWF.d.ts} +2 -2
  128. package/dist/{index-BkR7-GLI.d.ts → index-baQOK89E.d.ts} +2 -2
  129. package/dist/{index-D5W-p9bS.d.ts → index-oIJAZxc2.d.ts} +49 -4
  130. package/dist/{index-xdmCBvlT.d.ts → index-r7yb77Wy.d.ts} +3 -2
  131. package/dist/index.d.ts +4 -4
  132. package/dist/{react/internal → internal}/penStroke.internal.js +1 -1
  133. package/dist/internal/plugin/OverridePlugin.js +101 -119
  134. package/dist/internal/plugin/collectPlateNodeMappings.js +5 -1
  135. package/dist/internal/plugin/pastedUploadFiles.js +4 -0
  136. package/dist/internal/plugin/resolvePlugin.js +1 -1
  137. package/dist/internal/plugin/resolvePlugins.js +3 -0
  138. package/dist/internal/plugin/uploadDrafts.js +6 -0
  139. package/dist/internal/utils/mergePlugins.js +1 -0
  140. package/dist/lib/plugins/element-id/ElementIdPlugin.js +8 -2
  141. package/dist/lib/plugins/html/HtmlPlugin.js +9 -0
  142. package/dist/lib/plugins/html/htmlSafety.js +1 -1
  143. package/dist/lib/plugins/input-rules/InputRulesPlugin.js +5 -15
  144. package/dist/lib/plugins/input-rules/inputRuleVeto.internal.js +16 -0
  145. package/dist/markdown/index.d.ts +2 -2
  146. package/dist/markdown/index.js +2 -1
  147. package/dist/markdown/lib/MarkdownPlugin.js +16 -9
  148. package/dist/markdown/lib/RawHtmlPlugin.js +24 -0
  149. package/dist/markdown/lib/deserializer/mdastToSlate.js +12 -2
  150. package/dist/markdown/lib/internal/markdownConversion.js +773 -74
  151. package/dist/markdown/lib/internal/markdownDiagnostics.js +18 -7
  152. package/dist/markdown/lib/internal/markdownFrontmatter.js +102 -0
  153. package/dist/markdown/lib/internal/markdownIntrinsics.js +125 -43
  154. package/dist/markdown/lib/internal/markdownLine.js +5 -3
  155. package/dist/markdown/lib/internal/markdownMappings.js +19 -7
  156. package/dist/markdown/lib/internal/markdownOpenTail.js +381 -0
  157. package/dist/markdown/lib/internal/markdownRawHtml.js +314 -0
  158. package/dist/markdown/lib/internal/markdownSegments.js +57 -48
  159. package/dist/markdown/lib/internal/markdownTags.js +22 -8
  160. package/dist/markdown/lib/serializer/convertNodesSerialize.js +10 -8
  161. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +226 -0
  162. package/dist/markdown/lib/serializer/listToMdastTree.js +2 -0
  163. package/dist/math/index.d.ts +3 -2
  164. package/dist/math/react/index.d.ts +4 -3
  165. package/dist/migrations/index.d.ts +3 -3
  166. package/dist/pagination/index.d.ts +1 -1
  167. package/dist/pagination/react/index.d.ts +4 -4
  168. package/dist/react/components/EditorContentView.internal.js +17 -8
  169. package/dist/react/components/EditorProvider.js +5 -5
  170. package/dist/react/components/Plate.js +103 -122
  171. package/dist/react/components/PlateContainer.js +40 -32
  172. package/dist/react/components/PlateController.js +28 -16
  173. package/dist/react/components/PlateRoot.internal.js +3 -2
  174. package/dist/react/core.js +4 -4
  175. package/dist/react/features/board/BoardSurface.js +116 -87
  176. package/dist/react/features/board/boardClipboard.internal.js +15 -5
  177. package/dist/react/features/board/boardGesture.internal.js +6 -3
  178. package/dist/react/features/board/boardIndex.internal.js +7 -18
  179. package/dist/react/features/board/boardPictures.internal.js +19 -13
  180. package/dist/react/features/board/boardView.internal.js +184 -49
  181. package/dist/react/features/board/boardVoice.internal.js +10 -11
  182. package/dist/react/features/board/index.d.ts +64 -18
  183. package/dist/react/features/callout/index.d.ts +3 -2
  184. package/dist/react/features/combobox/index.d.ts +8 -8
  185. package/dist/react/features/comments/index.d.ts +6 -5
  186. package/dist/react/features/date/index.d.ts +4 -3
  187. package/dist/react/features/details/index.d.ts +4 -3
  188. package/dist/react/features/field/FieldPlugin.js +34 -0
  189. package/dist/react/features/field/index.d.ts +312 -0
  190. package/dist/react/features/field/index.js +2 -0
  191. package/dist/react/features/footnote/index.d.ts +7 -6
  192. package/dist/react/features/format-painter/index.d.ts +4 -3
  193. package/dist/react/features/ink/InkContent.js +313 -0
  194. package/dist/react/features/ink/index.d.ts +57 -29
  195. package/dist/react/features/ink/index.js +2 -2
  196. package/dist/react/features/ink/inkCapture.internal.js +39 -17
  197. package/dist/react/features/ink/inkInput.internal.js +1 -1
  198. package/dist/react/features/ink/inkLayout.internal.js +6 -3
  199. package/dist/react/features/ink/inkPaint.internal.js +78 -2
  200. package/dist/react/features/ink/inkPlacement.internal.js +331 -104
  201. package/dist/react/features/ink/inkWatch.internal.js +7 -5
  202. package/dist/react/features/layout/index.d.ts +5 -4
  203. package/dist/react/features/media/index.d.ts +5 -4
  204. package/dist/react/features/mention/index.d.ts +6 -5
  205. package/dist/react/features/resizable/Resizable.js +4 -6
  206. package/dist/react/features/resizable/index.d.ts +5 -5
  207. package/dist/react/features/suggestion/index.d.ts +6 -5
  208. package/dist/react/features/table/TablePlugin.js +4 -11
  209. package/dist/react/features/table/index.d.ts +8 -7
  210. package/dist/react/features/toc/index.d.ts +2 -2
  211. package/dist/react/features/upload/index.d.ts +11 -6
  212. package/dist/react/index.d.ts +6 -6
  213. package/dist/react/index.js +4 -4
  214. package/dist/react/internal/plate-context.js +425 -188
  215. package/dist/react/plite-react.js +2 -2
  216. package/dist/react/plugins/navigation-feedback/NavigationFeedbackPlugin.js +12 -10
  217. package/dist/react/stores/plate/useEditor.js +32 -14
  218. package/dist/react/stores/plate/useEditorHistory.js +55 -0
  219. package/dist/react/stores/plate/useEditorSelector.js +66 -21
  220. package/dist/react/utils/pipeRenderElement.internal.js +1 -1
  221. package/dist/react/utils/pluginRenderElement.internal.js +1 -1
  222. package/dist/react/virtualized.d.ts +4 -4
  223. package/dist/{source-CNKy99Th.d.ts → source-aUwpNnAw.d.ts} +4 -4
  224. package/dist/static/index.d.ts +18 -18
  225. package/dist/static/internal/renderStaticHtmlWithOverrides.js +2 -2
  226. package/dist/static/internal/staticPresentation.js +4 -4
  227. package/dist/static/internal/writeStaticSelectionClipboardData.js +7 -2
  228. package/dist/tabbable/index.d.ts +1 -1
  229. package/dist/tabbable/react/index.d.ts +3 -3
  230. package/dist/testing/index.d.ts +3 -3
  231. package/dist/yjs/index.d.ts +1 -1
  232. package/dist/yjs/react/index.d.ts +6 -6
  233. package/package.json +20 -2
  234. package/dist/markdown/lib/serializer/convertTextsSerialize.js +0 -163
  235. package/dist/react/components/EditorSelectionView.js +0 -40
  236. package/dist/react/features/ink/InkLayer.js +0 -218
  237. package/dist/react/internal/createPlateTargetScope.js +0 -62
@@ -1,4 +1,4 @@
1
- import { attachTransactionSpecAfterCommit, canPlaceBlocksAtPath, configureAuthoredView, getActiveEditorTransaction, getAuthoredUpdateView, getEditorCommitNode, getEditorRuntimeRootKeys, getSnapshotVersion, getViewAuthor, readAuthoredView, reportEditorLifecycleError, withStoredAuthoredRead } from "../../../facade.js";
1
+ import { attachTransactionSpecAfterCommit, canPlaceBlocksAtPath, configureAuthoredView, getActiveEditorTransaction, getAuthoredUpdateView, getEditorCommitNode, getEditorRuntimeRootKeys, getSnapshotVersion, getViewAuthor, isEditorPublishingCommit, readAuthoredView, registerEditorTransactionGuard, reportEditorLifecycleError, txStored, withStoredAuthoredRead } from "../../../facade.js";
2
2
  import { domCommands } from "../../../dom/plite-dom.internal.js";
3
3
  import { getCompiledPlatePlugin } from "../../../internal/plugin/compilePlateModel.js";
4
4
  import { createZustandStore } from "../../../lib/libs/zustand.js";
@@ -7,6 +7,8 @@ import { getCaretAnchor } from "../../../internal/plugin/insertionAnchor.js";
7
7
  import { isReplaceableEmptyBlock } from "../../../internal/plugin/blockInsertion.js";
8
8
  import { PLUGINS } from "../../../utils/plate-keys.js";
9
9
  import { EditorSchemaValidationError, ElementApi, NodeApi, PathApi, TextApi, createEditorView, defineEffect, documentReplacement, locateAt, property, transferVeto, txLocate } from "../../../core.js";
10
+ import { pastedUploadFiles } from "../../../internal/plugin/pastedUploadFiles.js";
11
+ import { UPLOAD_COMMIT_TAG } from "../../../internal/plugin/uploadDrafts.js";
10
12
  import { lookup } from "./mimeTypes.internal.js";
11
13
  //#region src/features/upload/lib/BaseUploadPlugin.ts
12
14
  const UPLOAD_FILE_TYPES = [
@@ -43,6 +45,15 @@ const uploadAdmissionEffect = defineEffect({
43
45
  history: "skip",
44
46
  key: "upload.admission"
45
47
  });
48
+ const admissionMarks = (effects) => effects.flatMap(({ type, value }) => type === uploadAdmissionEffect ? [value] : []);
49
+ const onceAcrossReplays = (handler) => {
50
+ let ran = false;
51
+ return (...args) => {
52
+ if (ran) return;
53
+ ran = true;
54
+ handler(...args);
55
+ };
56
+ };
46
57
  const isUploadFileType = (value) => UPLOAD_FILE_TYPES.includes(value);
47
58
  const isUploadKind = (value) => typeof value === "string" && UPLOAD_KINDS.includes(value);
48
59
  const assertPositiveInteger = (value, name) => {
@@ -141,6 +152,19 @@ const validateFiles = (files, state) => {
141
152
  fileTypes
142
153
  };
143
154
  };
155
+ const refusedWhateverFollows = (count, types, rule, maxFiles) => count > maxFiles || maxFiles === Number.POSITIVE_INFINITY && types.size === 1 && count >= (rule.minFiles ?? 0) && count > (rule.maxFiles ?? Number.POSITIVE_INFINITY);
156
+ const lowBytes = (text) => {
157
+ const bytes = new Uint8Array(text.length);
158
+ for (let index = 0; index < text.length; index += 1) bytes[index] = text.charCodeAt(index) & 255;
159
+ return bytes;
160
+ };
161
+ const rasterFormat = (bytes) => {
162
+ const head = String.fromCharCode(...bytes.subarray(0, 12));
163
+ if (head.startsWith("‰PNG\r\n\n")) return "png";
164
+ if (head.startsWith("ÿØÿ")) return "jpeg";
165
+ if (head.startsWith("GIF87a") || head.startsWith("GIF89a")) return "gif";
166
+ if (head.startsWith("RIFF") && head.slice(8) === "WEBP") return "webp";
167
+ };
144
168
  /** Owns persisted upload drafts and editor-lifetime Files SDK requests. */
145
169
  const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
146
170
  component: () => null,
@@ -162,56 +186,60 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
162
186
  selectors: { task: (state, key) => state.tasks[key] }
163
187
  }).extend((context) => {
164
188
  const { editor, schema: { type }, store } = context;
165
- const tasks = /* @__PURE__ */ new Map();
166
- const pastedPictures = /* @__PURE__ */ new Map();
167
- const pending = /* @__PURE__ */ new Map();
168
- let cancelAllCount = 0;
169
- const revokePending = (key) => {
170
- for (const start of pending.get(key) ?? []) start.revoked = true;
171
- pending.delete(key);
189
+ const records = /* @__PURE__ */ new Map();
190
+ const unpublished = /* @__PURE__ */ new Set();
191
+ const unlist = (key) => {
192
+ const current = store.get("tasks");
193
+ const gone = (key ? [key] : Object.keys(current)).filter((listed) => current[listed] && !records.get(listed)?.task);
194
+ if (gone.length === 0) return;
195
+ const next = { ...current };
196
+ for (const listed of gone) delete next[listed];
197
+ store.set({ tasks: next });
198
+ };
199
+ const prune = (key, record) => {
200
+ if (!record.task && !record.waiting && records.get(key) === record) records.delete(key);
172
201
  };
173
- const currentSlot = (key, kind) => {
174
- const entry = withStoredAuthoredRead(editor, () => editor.read.nodes.get(key));
175
- return entry && NodeApi.isElement(entry[0]) && entry[0].type === type && isUploadKind(entry[0].kind) && (kind === void 0 || entry[0].kind === kind) ? [entry[0], entry[1]] : void 0;
202
+ const stop = (key, task) => {
203
+ const record = records.get(key);
204
+ if (record?.task !== task) return;
205
+ record.task = void 0;
206
+ prune(key, record);
207
+ task.controller.abort();
208
+ unlist(key);
176
209
  };
210
+ let admissions = 0;
211
+ const markAdmission = (effects, form, keys, kinds = []) => {
212
+ admissions += 1;
213
+ effects.emit(uploadAdmissionEffect, {
214
+ form,
215
+ id: admissions,
216
+ keys,
217
+ kinds
218
+ });
219
+ return admissions;
220
+ };
221
+ let closed = () => true;
222
+ const draftKind = (node) => NodeApi.isElement(node) && node.type === type && isUploadKind(node.kind) ? node.kind : void 0;
223
+ const isStoredDraft = (key, kind) => draftKind(withStoredAuthoredRead(editor, () => editor.read.nodes.get(key))?.[0]) === kind;
224
+ const placeAfter = (tx, slot, drafts) => tx.blocks.insert(drafts, {
225
+ after: slot,
226
+ replaceEmpty: false
227
+ });
177
228
  const slotIn = (commit, key, kind) => getEditorRuntimeRootKeys(editor).some((root) => {
178
229
  const node = getEditorCommitNode(commit, key, root)?.[0];
179
230
  return NodeApi.isElement(node) && node.type === type && node.kind === kind;
180
231
  });
181
- const removeTaskResource = (key, task) => {
182
- const current = tasks.get(key);
183
- if (task && current && current !== task) return;
184
- const next = { ...store.get("tasks") };
185
- if (!next[key]) return;
186
- delete next[key];
187
- store.set({ tasks: next });
188
- };
189
- const stopTask = (key, expected) => {
190
- const task = tasks.get(key);
191
- if (!task || expected && task !== expected) return false;
192
- tasks.delete(key);
193
- task.controller.abort();
194
- removeTaskResource(key, task);
195
- return true;
196
- };
197
- const cancel = (key, expected) => {
198
- if (stopTask(key, expected)) pastedPictures.delete(key);
199
- };
200
232
  const createOwnerView = (authorId, authored) => {
201
233
  const owner = createEditorView(editor, { authorId });
202
234
  configureAuthoredView(owner, authored);
203
235
  return owner;
204
236
  };
205
- const cancelAll = () => {
206
- const active = [...tasks.values()];
207
- cancelAllCount += 1;
208
- tasks.clear();
209
- pastedPictures.clear();
210
- active.forEach(({ controller }) => controller.abort());
211
- if (Object.keys(store.get("tasks")).length > 0) store.set({ tasks: {} });
212
- };
213
237
  const notifyFailure = (failure) => {
214
- store.get("onError")?.(failure);
238
+ if (!closed()) store.get("onError")?.(failure);
239
+ };
240
+ const refuse = (effects, afterCommit, failure) => {
241
+ markAdmission(effects, "refuse", []);
242
+ afterCommit(onceAcrossReplays(() => notifyFailure(failure)));
215
243
  };
216
244
  const reportTaskError = (cause) => {
217
245
  reportEditorLifecycleError({
@@ -221,6 +249,21 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
221
249
  pluginName: PLUGINS.upload
222
250
  });
223
251
  };
252
+ const revokeWhere = (matches) => {
253
+ const stopped = [];
254
+ for (const admission of unpublished) if (matches(admission.key, admission)) unpublished.delete(admission);
255
+ for (const [key, record] of records) {
256
+ if (record.waiting && matches(key, record.waiting)) record.waiting = void 0;
257
+ if (record.task && matches(key, record.task)) {
258
+ stopped.push(record.task);
259
+ record.task = void 0;
260
+ record.picture = void 0;
261
+ }
262
+ prune(key, record);
263
+ }
264
+ for (const task of stopped) task.controller.abort();
265
+ unlist();
266
+ };
224
267
  const destination = (kind) => {
225
268
  const name = kind === "audio" ? PLUGINS.audio : kind === "file" ? PLUGINS.file : kind === "image" ? PLUGINS.image : PLUGINS.video;
226
269
  const descriptor = getCompiledPlatePlugin(editor, name);
@@ -241,15 +284,7 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
241
284
  type: portal.schema.type
242
285
  };
243
286
  };
244
- const startTask = (upload, client, getUrl, owner, revoked, admittedVersion) => {
245
- if (!currentSlot(upload.key, upload.kind)) return;
246
- stopTask(upload.key);
247
- if (revoked()) {
248
- if (!tasks.has(upload.key)) pastedPictures.delete(upload.key);
249
- return;
250
- }
251
- if ("caption" in upload) pastedPictures.set(upload.key, upload);
252
- else if (pastedPictures.get(upload.key)?.file !== upload.file) pastedPictures.delete(upload.key);
287
+ const startTask = (upload, record, admittedVersion, { client, getUrl }, owner) => {
253
288
  const controller = new AbortController();
254
289
  const state = createZustandStore(Object.freeze({
255
290
  progress: Object.freeze({
@@ -259,24 +294,23 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
259
294
  }),
260
295
  status: "uploading"
261
296
  }));
262
- const resource = {
263
- file: upload.file,
264
- getSnapshot: state.get,
265
- subscribe: state.subscribe
266
- };
267
297
  const task = {
268
298
  admittedVersion,
269
299
  controller,
270
300
  kind: upload.kind,
271
- state,
272
- token: {}
301
+ resource: {
302
+ file: upload.file,
303
+ getSnapshot: state.get,
304
+ subscribe: state.subscribe
305
+ },
306
+ state
273
307
  };
274
- tasks.set(upload.key, task);
308
+ record.task = task;
275
309
  store.set({ tasks: {
276
310
  ...store.get("tasks"),
277
- [upload.key]: resource
311
+ [upload.key]: task.resource
278
312
  } });
279
- const owns = () => tasks.get(upload.key)?.token === task.token && !controller.signal.aborted && !!currentSlot(upload.key, upload.kind);
313
+ const owns = () => records.get(upload.key)?.task === task && !controller.signal.aborted && isStoredDraft(upload.key, upload.kind);
280
314
  const fail = (failure) => {
281
315
  if (!owns()) return;
282
316
  controller.abort();
@@ -292,6 +326,7 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
292
326
  }
293
327
  };
294
328
  (async () => {
329
+ if (closed() || !owns()) return;
295
330
  let result;
296
331
  try {
297
332
  result = await client.upload(upload.file, {
@@ -357,10 +392,13 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
357
392
  });
358
393
  return;
359
394
  }
360
- owner.update({ history: "skip" }, (tx) => {
395
+ owner.update({
396
+ history: "skip",
397
+ tags: UPLOAD_COMMIT_TAG
398
+ }, (tx) => {
361
399
  const entry = tx.nodes.get(upload.key);
362
- if (tasks.get(upload.key)?.token !== task.token || !entry || !NodeApi.isElement(entry[0]) || entry[0].type !== type || entry[0].kind !== upload.kind) return;
363
- const kept = pastedPictures.get(upload.key);
400
+ if (records.get(upload.key)?.task !== task || !entry || !NodeApi.isElement(entry[0]) || entry[0].type !== type || entry[0].kind !== upload.kind) return;
401
+ const kept = record.picture;
364
402
  tx.nodes.set({
365
403
  ...kept?.properties,
366
404
  ...normalized
@@ -377,7 +415,7 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
377
415
  if (owns()) throw new Error("The editor refused the completed upload.");
378
416
  } catch (error) {
379
417
  if (!owns()) {
380
- cancel(upload.key, task);
418
+ stop(upload.key, task);
381
419
  reportTaskError(error);
382
420
  return;
383
421
  }
@@ -392,74 +430,229 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
392
430
  }
393
431
  })();
394
432
  };
395
- const admit = (afterCommit, admission) => {
396
- const cancelledBefore = cancelAllCount;
433
+ const bind = (effects, afterCommit, admission, form) => {
434
+ const id = markAdmission(effects, form, admission.uploads.map(({ key }) => key), admission.uploads.map(({ kind }) => kind));
397
435
  let owner;
398
- for (const upload of admission.uploads) {
399
- const start = {
400
- kind: upload.kind,
401
- revoked: false
402
- };
403
- const starts = pending.get(upload.key) ?? /* @__PURE__ */ new Set();
404
- pending.set(upload.key, starts.add(start));
405
- afterCommit(({ commit }) => {
406
- const own = commit.annotations[documentReplacement.key] === true;
407
- const revoked = () => start.revoked || cancelAllCount !== cancelledBefore + (own ? 1 : 0);
408
- if (revoked()) return;
409
- for (const older of starts) {
410
- if (older === start) break;
411
- older.revoked = true;
412
- starts.delete(older);
413
- }
414
- owner ??= createOwnerView(admission.authorId, admission.authored);
415
- startTask(upload, admission.client, admission.getUrl, owner, revoked, commit.version);
416
- starts.delete(start);
417
- if (starts.size === 0 && pending.get(upload.key) === starts) pending.delete(upload.key);
436
+ for (const upload of admission.uploads) afterCommit(({ commit }) => {
437
+ const record = records.get(upload.key);
438
+ const waiting = record?.waiting;
439
+ if (!record || waiting?.id !== id || waiting.admittedVersion !== commit.previousVersion) return;
440
+ if (closed() || !isStoredDraft(upload.key, upload.kind)) {
441
+ record.waiting = void 0;
442
+ prune(upload.key, record);
443
+ return;
444
+ }
445
+ if (record.task) stop(upload.key, record.task);
446
+ if (records.get(upload.key) !== record || record.waiting !== waiting || closed()) {
447
+ prune(upload.key, record);
448
+ return;
449
+ }
450
+ record.waiting = void 0;
451
+ record.picture = "caption" in upload ? upload : record.picture?.file === upload.file ? record.picture : void 0;
452
+ owner ??= createOwnerView(admission.authorId, admission.authored);
453
+ startTask(upload, record, waiting.admittedVersion, admission, owner);
454
+ });
455
+ };
456
+ const writerWithWork = (updateEditor, files) => {
457
+ const writer = getAuthoredUpdateView(updateEditor);
458
+ const authored = readAuthoredView(writer);
459
+ return closed() || files.length === 0 || updateEditor.read.view.isReadOnly() || authored && "preview" in authored ? void 0 : {
460
+ authored,
461
+ authorId: getViewAuthor(writer)
462
+ };
463
+ };
464
+ const refusal = (failure) => ({ failure });
465
+ const check = (files, requireKind) => {
466
+ const state = store.get();
467
+ if (requireKind) {
468
+ const fileTypes = Object.keys(state.rules).filter(isUploadFileType);
469
+ const allowed = new Set(fileTypes);
470
+ const others = requireKind.files.filter((file) => {
471
+ const fileType = classifyFile(file, allowed);
472
+ return !fileType || state.rules[fileType]?.kind !== requireKind.kind;
473
+ });
474
+ if (others.length > 0) return refusal({
475
+ allowedTypes: fileTypes.filter((fileType) => state.rules[fileType]?.kind === requireKind.kind),
476
+ code: "unsupported-file-type",
477
+ files: others,
478
+ phase: "admission"
418
479
  });
419
480
  }
481
+ const validation = validateFiles(files, state);
482
+ if (validation.error) return refusal({
483
+ ...validation.error,
484
+ phase: "admission"
485
+ });
486
+ const { client, getUrl } = state;
487
+ if (!client || !getUrl) return refusal({
488
+ code: client ? "missing-url-resolver" : "missing-client",
489
+ files,
490
+ phase: "configuration"
491
+ });
492
+ const uploads = files.map((file) => {
493
+ const fileType = validation.fileTypes.get(file);
494
+ const rule = fileType ? state.rules[fileType] : void 0;
495
+ if (!fileType || !rule) throw new Error("Validated upload file requires a configured rule.");
496
+ return {
497
+ file,
498
+ kind: rule.kind
499
+ };
500
+ });
501
+ for (const { kind } of uploads) if (!destination(kind)) return refusal({
502
+ code: "missing-destination",
503
+ files,
504
+ kind,
505
+ phase: "configuration"
506
+ });
507
+ return {
508
+ client,
509
+ getUrl,
510
+ uploads
511
+ };
420
512
  };
421
513
  return {
422
- activate({ beforePublish, onCleanup }) {
514
+ activate({ acquire, beforePublish, onCleanup }) {
515
+ let taken = false;
516
+ acquire(() => {
517
+ taken = true;
518
+ return () => {
519
+ taken = false;
520
+ };
521
+ });
522
+ closed = () => !taken;
423
523
  beforePublish(() => validateConfiguration(store.get()));
424
- onCleanup(cancelAll);
524
+ onCleanup(registerEditorTransactionGuard(editor, ({ commit, effects }) => {
525
+ const given = /* @__PURE__ */ new Set();
526
+ const admitted = /* @__PURE__ */ new Map();
527
+ for (const { form, id, keys, kinds } of admissionMarks(effects)) keys.forEach((key, index) => {
528
+ if (form === "cancel") {
529
+ admitted.delete(key);
530
+ return;
531
+ }
532
+ if (form === "replace" || !given.has(key)) admitted.set(key, {
533
+ admittedVersion: commit.previousVersion,
534
+ id,
535
+ key,
536
+ kind: kinds[index]
537
+ });
538
+ given.add(key);
539
+ });
540
+ if (admitted.size === 0) return void 0;
541
+ if (!isEditorPublishingCommit(editor)) unpublished.clear();
542
+ for (const admission of admitted.values()) unpublished.add(admission);
543
+ return () => {
544
+ for (const [key, waiting] of admitted) {
545
+ if (!unpublished.delete(waiting)) continue;
546
+ const record = records.get(key) ?? {};
547
+ if (Math.max(record.task?.admittedVersion ?? -1, record.waiting?.admittedVersion ?? -1) > waiting.admittedVersion || !isStoredDraft(key, waiting.kind)) continue;
548
+ record.waiting = waiting;
549
+ records.set(key, record);
550
+ }
551
+ };
552
+ }));
553
+ onCleanup(() => revokeWhere(() => true));
425
554
  },
426
- api: () => ({ cancel: (key) => {
427
- revokePending(key);
428
- cancel(key);
429
- } }),
555
+ api: () => ({
556
+ cancel: (key) => {
557
+ const active = getActiveEditorTransaction(editor);
558
+ if (active) markAdmission(active.effects, "cancel", [key]);
559
+ for (const admission of unpublished) if (admission.key === key) unpublished.delete(admission);
560
+ const record = records.get(key);
561
+ if (!record) return;
562
+ const { task } = record;
563
+ record.waiting = void 0;
564
+ if (!task) {
565
+ if (!record.picture) prune(key, record);
566
+ return;
567
+ }
568
+ records.delete(key);
569
+ task.controller.abort();
570
+ unlist(key);
571
+ },
572
+ /**
573
+ * Whether another draft of the same kind fits after the upload draft
574
+ * at `key`, where a slot submit lands the draft of a second file. It
575
+ * writes nothing, and it is false when `key` names no upload draft.
576
+ */
577
+ fitsAfter: (key) => {
578
+ let fits = false;
579
+ withStoredAuthoredRead(editor, () => editor.read((state) => state.transaction((tx) => {
580
+ const kind = draftKind(tx.nodes.get(key)?.[0]);
581
+ fits = !!kind && !!placeAfter(tx, key, [tx.schema.create(type, { kind })]);
582
+ })));
583
+ return fits;
584
+ }
585
+ }),
430
586
  commands: ({ around }) => [around(domCommands.insertData, ({ input, next, state }) => {
431
- const { client, getUrl, rules } = store.get();
432
587
  const pictureType = destination("image")?.schema.type;
433
- const hasDataUrl = (picture) => typeof picture.url === "string" && /^data:/iu.test(picture.url);
588
+ const writer = getAuthoredUpdateView(editor);
589
+ const keepsPictures = () => {
590
+ const authored = readAuthoredView(writer);
591
+ return closed() || writer.read.view.isReadOnly() || authored !== void 0 && ("preview" in authored || authored.intent === "propose");
592
+ };
593
+ const admitting = () => {
594
+ const settings = store.get();
595
+ const { client, getUrl, rules } = settings;
596
+ return !keepsPictures() && client && getUrl && Object.values(rules).some((rule) => rule?.kind === "image") ? {
597
+ client,
598
+ getUrl,
599
+ settings
600
+ } : void 0;
601
+ };
602
+ const hasLocalUrl = (picture) => typeof picture.url === "string" && /^(?:blob|data):/iu.test(picture.url);
434
603
  const stringsCarryPicture = () => Array.from(input.types ?? []).some((format) => {
435
604
  const data = input.getData(format);
436
- return typeof data === "string" && (/data:image\//iu.test(data) || data.includes("\\pict"));
605
+ return typeof data === "string" && (/data:image\/|blob:(?:null\/|[a-z][\d+.a-z-]*:)/iu.test(data) || data.includes("\\pict"));
437
606
  });
438
607
  const editorSliceCarriesPicture = () => {
439
608
  const read = editor.api.dom.clipboard.readSlice(input);
440
- return read.kind === "slice" && [read.slice.content, ...Object.values(read.slice.roots ?? {})].flat().some((node) => [...NodeApi.elements(node)].some(([element]) => element.type === pictureType && hasDataUrl(element)));
609
+ return read.kind === "slice" && [read.slice.content, ...Object.values(read.slice.roots ?? {})].flat().some((node) => [...NodeApi.elements(node)].some(([element]) => element.type === pictureType && hasLocalUrl(element)));
441
610
  };
442
- if (!client || !getUrl || !pictureType || !Object.values(rules).some((rule) => rule?.kind === "image") || !(stringsCarryPicture() || editorSliceCarriesPicture())) return next();
611
+ if (!pictureType || !admitting() || !(stringsCarryPicture() || editorSliceCarriesPicture())) return next();
443
612
  const known = /* @__PURE__ */ new Set();
444
613
  for (const [picture, path] of state.nodes.entries({
445
614
  at: [],
446
615
  type: pictureType
447
616
  })) {
448
- const key = hasDataUrl(picture) ? state.key(path) : null;
617
+ const key = hasLocalUrl(picture) ? state.key(path) : null;
449
618
  if (key) known.add(key);
450
619
  }
451
620
  const before = new Set(state.nodes.children([]));
452
- const writer = getAuthoredUpdateView(editor);
621
+ const roots = new Set(getEditorRuntimeRootKeys(editor));
453
622
  const pasted = next();
454
623
  if (pasted === false) return false;
455
624
  const handlers = [];
456
625
  const result = state.transaction.extend(pasted, (tx) => {
626
+ const admission = admitting();
627
+ if (!admission) return;
628
+ const { client, getUrl, settings } = admission;
629
+ const { rules } = settings;
457
630
  const allowedTypes = new Set(Object.keys(rules).filter(isUploadFileType));
458
- const decodeDataUrl = (url) => {
459
- const mime = url.slice(5, url.indexOf(";")).toLowerCase();
631
+ const suggestingLosesPaste = getEditorRuntimeRootKeys(editor).some((root) => !roots.has(root));
632
+ const blocks = tx.nodes.children([]);
633
+ const stale = () => {
634
+ const now = tx.nodes.children([]);
635
+ const current = store.get();
636
+ return keepsPictures() || current.client !== client || current.getUrl !== getUrl || current.maxFiles !== settings.maxFiles || current.rules !== rules || now !== blocks && (now.length !== blocks.length || now.some((block, index) => block !== blocks[index]));
637
+ };
638
+ const readPicture = (url) => {
460
639
  try {
461
- const bytes = Uint8Array.from(atob(url.slice(url.indexOf(",") + 1)), (char) => char.charCodeAt(0));
462
- return new File([bytes], `image.${mime.slice(6)}`, { type: mime });
640
+ if (/^data:/iu.test(url)) {
641
+ const mime = url.slice(5, url.indexOf(";")).toLowerCase();
642
+ return new File([lowBytes(atob(url.slice(url.indexOf(",") + 1)))], `image.${mime.slice(6)}`, { type: mime });
643
+ }
644
+ if (suggestingLosesPaste) return void 0;
645
+ const request = new XMLHttpRequest();
646
+ request.open("GET", url, false);
647
+ request.overrideMimeType("text/plain; charset=x-user-defined");
648
+ if (stale()) return void 0;
649
+ request.send();
650
+ if (request.status !== 200) return void 0;
651
+ const text = request.responseText;
652
+ if (text.length !== Number(request.getResponseHeader("Content-Length"))) return;
653
+ const format = rasterFormat(lowBytes(text.slice(0, 12)));
654
+ if (!format) return void 0;
655
+ return new File([lowBytes(text)], `image.${format}`, { type: `image/${format}` });
463
656
  } catch {
464
657
  return;
465
658
  }
@@ -477,20 +670,17 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
477
670
  }
478
671
  };
479
672
  const candidates = [];
480
- tx.nodes.children([]).forEach((block, index) => {
673
+ blocks.forEach((block, index) => {
481
674
  if (before.has(block)) return;
482
675
  for (const [picture, path] of tx.nodes.entries({
483
676
  at: [index],
484
677
  type: pictureType
485
678
  })) {
486
- const key = hasDataUrl(picture) ? tx.key(path) : null;
679
+ const key = hasLocalUrl(picture) ? tx.key(path) : null;
487
680
  if (key && !known.has(key)) candidates.push([picture, path]);
488
681
  }
489
682
  });
490
- const pictures = candidates.flatMap(([node, path]) => {
491
- const file = decodeDataUrl(String(node.url));
492
- const fileType = file && classifyFile(file, allowedTypes);
493
- if (!file || !fileType || rules[fileType]?.kind !== "image") return [];
683
+ const placeable = candidates.flatMap(([node, path]) => {
494
684
  const properties = {};
495
685
  const draftProperties = {};
496
686
  for (const [key, value] of Object.entries(node)) {
@@ -512,23 +702,40 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
512
702
  return [{
513
703
  caption: node.children,
514
704
  draft,
515
- file,
516
705
  path,
517
- properties
706
+ properties,
707
+ url: String(node.url)
518
708
  }];
519
709
  });
710
+ const pictures = [];
711
+ const types = /* @__PURE__ */ new Set();
712
+ for (const picture of placeable) {
713
+ if (pictures.some(({ path }) => PathApi.isAncestor(path, picture.path))) continue;
714
+ const file = readPicture(picture.url);
715
+ const fileType = file && classifyFile(file, allowedTypes);
716
+ const rule = fileType ? rules[fileType] : void 0;
717
+ if (!file || !fileType || rule?.kind !== "image") continue;
718
+ types.add(fileType);
719
+ pictures.push({
720
+ ...picture,
721
+ file
722
+ });
723
+ if (refusedWhateverFollows(pictures.length, types, rule, settings.maxFiles)) break;
724
+ }
520
725
  if (pictures.length === 0) return;
521
- const validation = validateFiles(pictures.map(({ file }) => file), store.get());
726
+ const validation = validateFiles(pictures.map(({ file }) => file), settings);
727
+ if (stale()) return;
522
728
  if (validation.error) {
523
729
  const failure = {
524
730
  ...validation.error,
525
731
  phase: "admission"
526
732
  };
527
- handlers.push(() => notifyFailure(failure));
733
+ handlers.push(onceAcrossReplays(() => notifyFailure(failure)));
528
734
  return;
529
735
  }
530
736
  const selection = tx.selection();
531
- const caretPicture = pictures.find(({ path }) => selection && (PathApi.isAncestor(path, selection.anchor.path) || PathApi.isAncestor(path, selection.focus.path)));
737
+ const holds = (path, point) => point.root === tx.view.root() && PathApi.isAncestor(path, point.path);
738
+ const caretPicture = pictures.find(({ path }) => selection && (holds(path, selection.anchor) || holds(path, selection.focus)));
532
739
  const swapped = pictures.flatMap(({ caption, draft, file, path, properties }) => {
533
740
  if (!tx.nodes.replace(draft, { at: path })) return [];
534
741
  const key = tx.key(path);
@@ -545,164 +752,171 @@ const BaseUploadPlugin = definePlugin(PLUGINS.upload, {
545
752
  const start = tx.points.start(caretPicture.path);
546
753
  if (start) tx.selection.set(start);
547
754
  }
548
- admit((handler) => handlers.push(handler), {
755
+ bind(tx.effects, (handler) => handlers.push(handler), {
549
756
  authored: readAuthoredView(writer),
550
757
  authorId: getViewAuthor(writer),
551
758
  client,
552
759
  getUrl,
553
760
  uploads: swapped
554
- });
761
+ }, "yield");
555
762
  });
556
763
  for (const handler of handlers) attachTransactionSpecAfterCommit(result, handler);
557
764
  return result;
558
765
  })],
559
766
  on: { commit({ commit }) {
560
- if (commit.annotations[documentReplacement.key] === true) {
561
- cancelAll();
562
- return;
563
- }
564
- if (!commit.changed.hasAny("document")) return;
767
+ const replaces = commit.annotations[documentReplacement.key] === true;
768
+ if (!replaces && !commit.changed.hasAny("document")) return;
565
769
  const isLatest = commit.version >= getSnapshotVersion(editor);
566
- const survives = (key, kind, admittedVersion) => {
567
- if (!currentSlot(key, kind)) return false;
568
- const admittedSinceCommit = admittedVersion !== void 0 && admittedVersion >= commit.version;
569
- return isLatest || admittedSinceCommit || slotIn(commit, key, kind);
570
- };
571
- for (const [key, task] of tasks) if (!survives(key, task.kind, task.admittedVersion)) cancel(key, task);
572
- for (const [key, starts] of pending) {
573
- for (const start of starts) {
574
- if (survives(key, start.kind)) continue;
575
- start.revoked = true;
576
- starts.delete(start);
577
- }
578
- if (starts.size === 0) pending.delete(key);
579
- }
580
- } },
581
- update: ({ context: { afterCommit }, editor: updateEditor, tx }) => ({ submit: txLocate((args, place) => {
582
- const [, { after, at, before, slot } = {}] = args;
583
- const liveCaret = getActiveEditorTransaction(updateEditor)?.selection();
584
- if ([
585
- after,
586
- at,
587
- before,
588
- slot
589
- ].some((target) => target !== void 0) || !liveCaret) return locateAt(1, "slot", "at", "after", "before")(args, place);
590
- return place.location(liveCaret) === null ? null : args;
591
- }, (input, options = {}) => {
592
- const files = Array.from(input);
593
- const writer = getAuthoredUpdateView(updateEditor);
594
- const authored = readAuthoredView(writer);
595
- if (files.length === 0 || updateEditor.read.view.isReadOnly() || authored && "preview" in authored) return false;
596
- const state = store.get();
597
- const slot = "slot" in options ? options.slot : void 0;
598
- const slotEntry = slot ? currentSlot(slot) : void 0;
599
- if (slot && (!slotEntry || updateEditor.read.nodes.elementReadOnly({ at: slot }))) return false;
600
- const reject = (failure) => {
601
- tx.effects.emit(uploadAdmissionEffect, null);
602
- afterCommit(() => notifyFailure(failure));
603
- return true;
604
- };
605
- const refuseDoesNotFit = () => reject({
606
- code: "does-not-fit",
607
- files,
608
- phase: "placement"
609
- });
610
- const validation = validateFiles(files, state);
611
- if (validation.error) return reject({
612
- ...validation.error,
613
- phase: "admission"
770
+ revokeWhere((key, { admittedVersion, kind }) => {
771
+ if (admittedVersion >= commit.version) return false;
772
+ if (replaces && admittedVersion < commit.previousVersion) return true;
773
+ return !(isStoredDraft(key, kind) && (isLatest || slotIn(commit, key, kind)));
614
774
  });
615
- const { client, getUrl } = state;
616
- if (!client || !getUrl) return reject({
617
- code: client ? "missing-url-resolver" : "missing-client",
618
- files,
619
- phase: "configuration"
620
- });
621
- const uploads = files.map((file) => {
622
- const fileType = validation.fileTypes.get(file);
623
- const rule = fileType ? state.rules[fileType] : void 0;
624
- if (!fileType || !rule) throw new Error("Validated upload file requires a configured rule.");
775
+ } },
776
+ update: ({ context: { afterCommit }, editor: updateEditor, tx }) => ({
777
+ /**
778
+ * Check a batch for drafts the caller inserts itself. It writes nothing,
779
+ * and returns nothing when there is nothing to do.
780
+ */
781
+ admit: txStored((input, options = {}) => {
782
+ const files = Array.from(input);
783
+ const writer = writerWithWork(updateEditor, files);
784
+ if (!writer) return void 0;
785
+ const batch = check(files, options.kind && {
786
+ files,
787
+ kind: options.kind
788
+ });
789
+ if ("failure" in batch) {
790
+ const { failure } = batch;
791
+ refuse(tx.effects, afterCommit, failure);
792
+ return batch;
793
+ }
794
+ const { client, getUrl, uploads } = batch;
795
+ let filled = false;
625
796
  return {
626
- file,
627
- kind: rule.kind
797
+ drafts: uploads.map(({ kind }) => tx.schema.create(type, { kind })),
798
+ fill: (given) => {
799
+ const keys = Array.from(given);
800
+ if (keys.length !== uploads.length) throw new Error("Upload fill takes one draft key for each file.");
801
+ if (keys.some((key) => typeof key !== "string")) throw new Error("Upload fill takes node keys only.");
802
+ if (new Set(keys).size !== keys.length) throw new Error("Upload fill takes a different draft key for each file.");
803
+ const taken = new Set(admissionMarks(tx.effects.all()).flatMap((mark) => mark.form === "replace" || mark.form === "yield" ? mark.keys : []));
804
+ const prepared = keys.map((key, index) => {
805
+ const { file, kind } = uploads[index];
806
+ const draft = tx.nodes.get(key)?.[0];
807
+ if (!NodeApi.isElement(draft) || draft.type !== type || draft.kind !== kind) throw new Error("Upload fill takes the key of a live upload draft of its file kind.");
808
+ if (tx.nodes.elementReadOnly({ at: key })) throw new Error("Upload fill cannot give a file to a draft inside a read-only element.");
809
+ if (taken.has(key)) throw new Error("Upload fill names a draft that this update already gave a file.");
810
+ return {
811
+ file,
812
+ key,
813
+ kind
814
+ };
815
+ });
816
+ if (filled) throw new Error("Upload fill runs once for each admitted batch.");
817
+ tx.tags.add("history-push");
818
+ bind(tx.effects, afterCommit, {
819
+ ...writer,
820
+ client,
821
+ getUrl,
822
+ uploads: prepared
823
+ }, "yield");
824
+ filled = true;
825
+ }
628
826
  };
629
- });
630
- for (const { kind } of uploads) if (!destination(kind)) return reject({
631
- code: "missing-destination",
632
- files,
633
- kind,
634
- phase: "configuration"
635
- });
636
- if (slot && slotEntry && uploads[0].kind !== slotEntry[0].kind) return reject({
637
- allowedTypes: Object.entries(state.rules).filter(([, rule]) => rule?.kind === slotEntry[0].kind).map(([fileType]) => fileType).filter(isUploadFileType),
638
- code: "unsupported-file-type",
639
- files: [uploads[0].file],
640
- phase: "admission"
641
- });
642
- const prepared = [];
643
- const prepareInserted = (insertedUploads) => insertedUploads.map(({ element, file, kind }) => {
644
- const key = tx.key(element);
645
- if (!key) throw new Error("Upload insertion did not retain its node identity.");
646
- return {
647
- file,
648
- key,
649
- kind
827
+ }),
828
+ submit: txLocate((args, place) => {
829
+ const [, { after, at, before, slot } = {}] = args;
830
+ const liveCaret = getActiveEditorTransaction(updateEditor)?.selection();
831
+ if ([
832
+ after,
833
+ at,
834
+ before,
835
+ slot
836
+ ].some((target) => target !== void 0) || !liveCaret) return locateAt(1, "slot", "at", "after", "before")(args, place);
837
+ return place.location(liveCaret) === null ? null : args;
838
+ }, (input, options = {}) => {
839
+ const files = Array.from(input);
840
+ const writer = writerWithWork(updateEditor, files);
841
+ if (!writer) return false;
842
+ const slot = "slot" in options ? options.slot : void 0;
843
+ const slotKind = slot ? draftKind(tx.nodes.get(slot)?.[0]) : void 0;
844
+ if (slot && (!slotKind || tx.nodes.elementReadOnly({ at: slot }))) return false;
845
+ const reject = (failure) => {
846
+ refuse(tx.effects, afterCommit, failure);
847
+ return true;
650
848
  };
651
- });
652
- if (slot) {
653
- prepared.push({
654
- ...uploads[0],
655
- key: slot
849
+ const refuseDoesNotFit = () => reject({
850
+ code: "does-not-fit",
851
+ files,
852
+ phase: "placement"
656
853
  });
657
- const additional = uploads.slice(1).map((upload) => ({
658
- ...upload,
659
- element: tx.schema.create(type, { kind: upload.kind })
660
- }));
661
- if (additional.length > 0) {
662
- if (!tx.blocks.insert(additional.map(({ element }) => element), {
663
- after: slot,
664
- replaceEmpty: false
665
- })) return refuseDoesNotFit();
666
- tx.tags.add("history-push");
667
- prepared.push(...prepareInserted(additional));
668
- }
669
- tx.effects.emit(uploadAdmissionEffect, null);
670
- } else {
671
- const elements = uploads.map((upload) => ({
672
- ...upload,
673
- element: tx.schema.create(type, { kind: upload.kind })
674
- }));
675
- const nodes = elements.map(({ element }) => element);
676
- const { slot: _slot, ...insertOptions } = options;
677
- let inserted;
678
- if (insertOptions.at !== void 0 || insertOptions.before !== void 0) inserted = tx.blocks.insert(nodes, insertOptions);
679
- else {
680
- const after = insertOptions.after ?? getCaretAnchor(editor, tx);
681
- const anchor = tx.nodes.block({ at: after })?.[0];
682
- const replaceEmpty = insertOptions.replaceEmpty ?? insertOptions.after === void 0;
683
- inserted = tx.blocks.insert(nodes, {
684
- ...insertOptions,
685
- after,
686
- replaceEmpty: replaceEmpty && (!anchor || isReplaceableEmptyBlock(tx, anchor))
854
+ const batch = check(files, slotKind && {
855
+ files: files.slice(0, 1),
856
+ kind: slotKind
857
+ });
858
+ if ("failure" in batch) return reject(batch.failure);
859
+ const { client, getUrl, uploads } = batch;
860
+ const prepared = [];
861
+ const prepareInserted = (insertedUploads) => insertedUploads.map(({ element, file, kind }) => {
862
+ const key = tx.key(element);
863
+ if (!key) throw new Error("Upload insertion did not retain its node identity.");
864
+ return {
865
+ file,
866
+ key,
867
+ kind
868
+ };
869
+ });
870
+ if (slot) {
871
+ prepared.push({
872
+ ...uploads[0],
873
+ key: slot
687
874
  });
875
+ const additional = uploads.slice(1).map((upload) => ({
876
+ ...upload,
877
+ element: tx.schema.create(type, { kind: upload.kind })
878
+ }));
879
+ if (additional.length > 0) {
880
+ if (!placeAfter(tx, slot, additional.map(({ element }) => element))) return refuseDoesNotFit();
881
+ tx.tags.add("history-push");
882
+ prepared.push(...prepareInserted(additional));
883
+ }
884
+ } else {
885
+ const elements = uploads.map((upload) => ({
886
+ ...upload,
887
+ element: tx.schema.create(type, { kind: upload.kind })
888
+ }));
889
+ const nodes = elements.map(({ element }) => element);
890
+ const { slot: _slot, ...insertOptions } = options;
891
+ let inserted;
892
+ if (insertOptions.at !== void 0 || insertOptions.before !== void 0) inserted = tx.blocks.insert(nodes, insertOptions);
893
+ else {
894
+ const after = insertOptions.after ?? getCaretAnchor(editor, tx);
895
+ const anchor = tx.nodes.block({ at: after })?.[0];
896
+ const replaceEmpty = insertOptions.replaceEmpty ?? insertOptions.after === void 0;
897
+ inserted = tx.blocks.insert(nodes, {
898
+ ...insertOptions,
899
+ after,
900
+ replaceEmpty: replaceEmpty && (!anchor || isReplaceableEmptyBlock(tx, anchor))
901
+ });
902
+ }
903
+ if (!inserted) return refuseDoesNotFit();
904
+ tx.tags.add("history-push");
905
+ prepared.push(...prepareInserted(elements));
688
906
  }
689
- if (!inserted) return refuseDoesNotFit();
690
- tx.tags.add("history-push");
691
- prepared.push(...prepareInserted(elements));
692
- }
693
- admit(afterCommit, {
694
- authored,
695
- authorId: getViewAuthor(writer),
696
- client,
697
- getUrl,
698
- uploads: prepared
699
- });
700
- return true;
701
- }) })
907
+ bind(tx.effects, afterCommit, {
908
+ ...writer,
909
+ client,
910
+ getUrl,
911
+ uploads: prepared
912
+ }, slot ? "replace" : "yield");
913
+ return true;
914
+ })
915
+ })
702
916
  };
703
917
  }).extend(() => ({ commands: ({ around }) => [around(domCommands.insertData, ({ input, next, state }) => {
704
- const files = Array.from(input.files ?? []);
705
- if (files.length === 0 || Array.from(input.types ?? []).includes("text/html")) return next();
918
+ const files = pastedUploadFiles(input);
919
+ if (files.length === 0) return next();
706
920
  let handled = false;
707
921
  const transaction = state.transaction((tx) => {
708
922
  handled = tx.upload.submit(files);