platejs 54.0.0-beta.2 → 54.0.0-beta.4

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 (255) hide show
  1. package/README.md +1 -1
  2. package/THIRD_PARTY_NOTICES.md +56 -0
  3. package/dist/{AIChatRequestContext-BMVWhfPV.d.ts → AIChatRequestContext-DrUahdTc.d.ts} +2 -2
  4. package/dist/{BaseSuggestionPlugin-DBl3fqnm.d.ts → BaseSuggestionPlugin-_7Ka6nY3.d.ts} +7 -3
  5. package/dist/{PlateStatic-DhNv2ejp.d.ts → PlateStatic-D3Cb-QwH.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-Dr0OYZIE.d.ts} +2 -2
  14. package/dist/{comparison-types-CYnJ35qU.d.ts → comparison-types-DdwE6mYq-BogsHoUO.d.ts} +10 -2
  15. package/dist/compiler/index.d.ts +2 -2
  16. package/dist/{core-BJG8l_mk.d.ts → core-BqR-fEDp.d.ts} +493 -116
  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 +5 -3
  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/core.md +45 -5
  24. package/dist/docs/api/dom.md +11 -4
  25. package/dist/docs/api/editor-transforms.md +2 -1
  26. package/dist/docs/api/react-hooks.md +45 -13
  27. package/dist/docs/authored-changes.md +9 -4
  28. package/dist/docs/basic-blocks.md +42 -29
  29. package/dist/docs/block-placeholder.md +4 -2
  30. package/dist/docs/blockquote.md +5 -3
  31. package/dist/docs/board.md +118 -10
  32. package/dist/docs/code-block.md +47 -0
  33. package/dist/docs/comment.md +2 -2
  34. package/dist/docs/discussion.md +1 -1
  35. package/dist/docs/document-model.md +15 -3
  36. package/dist/docs/docx.md +1 -1
  37. package/dist/docs/dom-coverage.md +5 -0
  38. package/dist/docs/editor.md +50 -4
  39. package/dist/docs/examples/editable-voids.md +2 -3
  40. package/dist/docs/external-text.md +2 -0
  41. package/dist/docs/field.md +370 -0
  42. package/dist/docs/find.md +9 -6
  43. package/dist/docs/form.md +2 -0
  44. package/dist/docs/heading.md +6 -0
  45. package/dist/docs/installation/manual.md +0 -4
  46. package/dist/docs/link.md +3 -3
  47. package/dist/docs/llms.txt +4 -2
  48. package/dist/docs/markdown.md +270 -14
  49. package/dist/docs/plugin-components.md +13 -10
  50. package/dist/docs/plugin-input-rules.md +66 -15
  51. package/dist/docs/prompt-editor.md +205 -0
  52. package/dist/docs/roots.md +8 -6
  53. package/dist/docs/rtl.md +6 -4
  54. package/dist/docs/selection.md +7 -4
  55. package/dist/docs/suggestion.md +1 -1
  56. package/dist/docs/toolbar.md +26 -30
  57. package/dist/docs/upload.md +106 -17
  58. package/dist/docx/export/index.d.ts +3 -3
  59. package/dist/docx/export/lib/docxStaticComponents.js +12 -2
  60. package/dist/docx/export/lib/exportDocx.js +46 -17
  61. package/dist/docx/export/lib/internal/xml-builder.js +11 -16
  62. package/dist/docx/export/lib/reviewPart.js +1 -1
  63. package/dist/docx/export/lib/reviewProjection.js +52 -10
  64. package/dist/docx/import/index.d.ts +4 -4
  65. package/dist/docx/paste/index.d.ts +4 -4
  66. package/dist/dom/index.d.ts +1 -6
  67. package/dist/dom/plite-dom.internal.js +2 -2
  68. package/dist/excalidraw/index.d.ts +3 -2
  69. package/dist/excalidraw/react/index.d.ts +3 -2
  70. package/dist/facade.js +2 -2
  71. package/dist/features/basic-nodes/lib/BaseBlockPlugins.js +13 -5
  72. package/dist/features/basic-nodes/lib/BaseHeadingPlugins.js +32 -10
  73. package/dist/features/board/index.d.ts +2 -2
  74. package/dist/features/board/lib/BaseBoardPlugin.js +14 -1
  75. package/dist/features/board/lib/boardStroke.internal.js +13 -1
  76. package/dist/features/board/lib/boardTypes.internal.js +16 -0
  77. package/dist/features/callout/index.d.ts +3 -2
  78. package/dist/features/code-block/lib/BaseCodeBlockPlugin.js +14 -5
  79. package/dist/features/combobox/index.d.ts +2 -2
  80. package/dist/features/comments/BaseCommentsPlugin.js +33 -17
  81. package/dist/features/comments/index.d.ts +1 -1
  82. package/dist/features/date/index.d.ts +3 -2
  83. package/dist/features/details/index.d.ts +3 -2
  84. package/dist/features/details/lib/BaseDetailsPlugin.js +25 -12
  85. package/dist/features/field/index.d.ts +2 -0
  86. package/dist/features/field/index.js +4 -0
  87. package/dist/features/field/lib/BaseFieldPlugin.js +360 -0
  88. package/dist/features/field/lib/applyFieldValues.js +188 -0
  89. package/dist/features/field/lib/fieldRules.internal.js +204 -0
  90. package/dist/features/find/index.d.ts +3 -2
  91. package/dist/features/footnote/index.d.ts +1 -1
  92. package/dist/features/ink/index.d.ts +1 -1
  93. package/dist/features/ink/lib/BaseInkPlugin.js +126 -103
  94. package/dist/features/ink/lib/inkCodec.internal.js +130 -0
  95. package/dist/features/ink/lib/inkGone.internal.js +229 -48
  96. package/dist/features/ink/lib/inkPlaces.internal.js +534 -64
  97. package/dist/features/layout/index.d.ts +1 -1
  98. package/dist/features/link/lib/BaseLinkPlugin.js +6 -4
  99. package/dist/features/lint/index.d.ts +3 -2
  100. package/dist/features/media/index.d.ts +2 -2
  101. package/dist/features/media/index.js +2 -2
  102. package/dist/features/media/lib/media/parseMediaUrl.js +11 -1
  103. package/dist/features/media/lib/media-embed/BaseMediaEmbedPlugin.js +206 -4
  104. package/dist/features/mention/index.d.ts +5 -4
  105. package/dist/features/suggestion/index.d.ts +1 -1
  106. package/dist/features/table/index.d.ts +1 -1
  107. package/dist/features/table/lib/BaseTablePlugin.js +64 -15
  108. package/dist/features/table/lib/internal/selection.js +4 -2
  109. package/dist/features/toc/index.d.ts +1 -1
  110. package/dist/features/upload/index.d.ts +2 -2
  111. package/dist/features/upload/lib/BaseUploadPlugin.js +464 -250
  112. package/dist/history/index.d.ts +2 -2
  113. package/dist/html/index.d.ts +3 -3
  114. package/dist/html/server/index.d.ts +1 -1
  115. package/dist/{htmlTypes-DjeFG3P8.d.ts → htmlTypes-eT2ZGDAj.d.ts} +2 -31
  116. package/dist/hyperscript/index.d.ts +1 -1
  117. package/dist/{index-DzD6BIFJ.d.ts → index-B33E1CRJ.d.ts} +295 -6
  118. package/dist/{index-Cl77E9yr.d.ts → index-B7moSod7.d.ts} +2 -2
  119. package/dist/{index-hsC_sOn2.d.ts → index-B8-5Sr7I.d.ts} +35 -5
  120. package/dist/{index-BiQerPJS.d.ts → index-B8QJDAmG.d.ts} +2 -2
  121. package/dist/{index-BBKGrsG3.d.ts → index-BTx5oK7k.d.ts} +1 -1
  122. package/dist/{index-iaZOhA76.d.ts → index-BWPcE4ac-Cto_IsNs.d.ts} +7 -1
  123. package/dist/{index-BU6k1Aev.d.ts → index-BXjLmx1n-CXk17buG.d.ts} +4781 -4584
  124. package/dist/{index-kLKMc-pI.d.ts → index-BXwU9QH6.d.ts} +2 -2
  125. package/dist/{index-DTgaSxKr.d.ts → index-BkwR-5hH.d.ts} +40 -4
  126. package/dist/{index-Bq3sdm3S.d.ts → index-BsV2McRr.d.ts} +5 -4
  127. package/dist/index-C9Fu-P4E.d.ts +773 -0
  128. package/dist/{index-D5W-p9bS.d.ts → index-Ca48r1ng.d.ts} +49 -4
  129. package/dist/{index-CcZbqPqk.d.ts → index-Cob_iBdu.d.ts} +116 -41
  130. package/dist/{index-Bxfvicyy.d.ts → index-CpY7Xnxw.d.ts} +4 -3
  131. package/dist/{index-BkR7-GLI.d.ts → index-DNQXzU-X.d.ts} +2 -2
  132. package/dist/{index-D1CFXA-i.d.ts → index-DPowErHa.d.ts} +471 -141
  133. package/dist/{index-DaM37gF6.d.ts → index-DShbzec2.d.ts} +38 -23
  134. package/dist/{index-DC_MNGyu.d.ts → index-DYdObeFQ.d.ts} +3 -3
  135. package/dist/{index-Bc2Yg_2j.d.ts → index-Dq3Jlj8O-BJ6NxZm0.d.ts} +2 -2
  136. package/dist/{index-CT7miqQN.d.ts → index-DwWQVwQt.d.ts} +29 -11
  137. package/dist/{index-xdmCBvlT.d.ts → index-JWgwL5l3.d.ts} +5 -2
  138. package/dist/{index-DLA2DUR2.d.ts → index-M781pyx9.d.ts} +4 -3
  139. package/dist/{index-DdIRduDG.d.ts → index-d7io3MzC.d.ts} +3 -2
  140. package/dist/index.d.ts +4 -4
  141. package/dist/{react/internal → internal}/penStroke.internal.js +1 -1
  142. package/dist/internal/plugin/OverridePlugin.js +101 -119
  143. package/dist/internal/plugin/collectPlateNodeMappings.js +5 -1
  144. package/dist/internal/plugin/pastedUploadFiles.js +4 -0
  145. package/dist/internal/plugin/resolvePlugin.js +1 -1
  146. package/dist/internal/plugin/resolvePlugins.js +3 -0
  147. package/dist/internal/plugin/uploadDrafts.js +6 -0
  148. package/dist/internal/utils/mergePlugins.js +1 -0
  149. package/dist/lib/plugins/element-id/ElementIdPlugin.js +14 -18
  150. package/dist/lib/plugins/html/HtmlPlugin.js +9 -0
  151. package/dist/lib/plugins/html/htmlSafety.js +1 -1
  152. package/dist/lib/plugins/input-rules/InputRulesPlugin.js +77 -28
  153. package/dist/lib/plugins/input-rules/inputRuleVeto.internal.js +16 -0
  154. package/dist/markdown/index.d.ts +2 -2
  155. package/dist/markdown/index.js +3 -1
  156. package/dist/markdown/lib/MarkdownPlugin.js +14 -11
  157. package/dist/markdown/lib/RawHtmlPlugin.js +26 -0
  158. package/dist/markdown/lib/deserializer/mdastToSlate.js +12 -2
  159. package/dist/markdown/lib/internal/markdownConversion.js +776 -74
  160. package/dist/markdown/lib/internal/markdownDiagnostics.js +18 -7
  161. package/dist/markdown/lib/internal/markdownFootnoteWriter.js +35 -0
  162. package/dist/markdown/lib/internal/markdownFrontmatter.js +102 -0
  163. package/dist/markdown/lib/internal/markdownIntrinsics.js +125 -43
  164. package/dist/markdown/lib/internal/markdownLine.js +5 -3
  165. package/dist/markdown/lib/internal/markdownMappings.js +19 -7
  166. package/dist/markdown/lib/internal/markdownOpenTail.js +381 -0
  167. package/dist/markdown/lib/internal/markdownRawHtml.js +353 -0
  168. package/dist/markdown/lib/internal/markdownSegments.js +57 -48
  169. package/dist/markdown/lib/internal/markdownTags.js +29 -9
  170. package/dist/markdown/lib/serializer/convertNodesSerialize.js +10 -8
  171. package/dist/markdown/lib/serializer/convertPhrasingSerialize.js +226 -0
  172. package/dist/markdown/lib/serializer/listToMdastTree.js +2 -0
  173. package/dist/math/index.d.ts +3 -2
  174. package/dist/math/react/index.d.ts +4 -3
  175. package/dist/migrations/index.d.ts +3 -3
  176. package/dist/migrations/migratePlateV54.js +4 -6
  177. package/dist/migrations/migratePlateV54RetiredMarks.internal.js +23 -8
  178. package/dist/migrations/migratePlateV54Suggestions.internal.js +2 -2
  179. package/dist/migrations/v53-manifest.internal.js +4 -0
  180. package/dist/pagination/index.d.ts +1 -1
  181. package/dist/pagination/react/index.d.ts +4 -4
  182. package/dist/react/components/EditorContentView.internal.js +42 -23
  183. package/dist/react/components/EditorProvider.js +5 -5
  184. package/dist/react/components/Plate.js +102 -128
  185. package/dist/react/components/PlateContainer.js +40 -32
  186. package/dist/react/components/PlateController.js +28 -16
  187. package/dist/react/components/PlateRoot.internal.js +3 -2
  188. package/dist/react/core.js +4 -4
  189. package/dist/react/features/board/BoardSurface.js +116 -87
  190. package/dist/react/features/board/boardClipboard.internal.js +15 -5
  191. package/dist/react/features/board/boardExport.internal.js +470 -0
  192. package/dist/react/features/board/boardGesture.internal.js +6 -3
  193. package/dist/react/features/board/boardIndex.internal.js +7 -18
  194. package/dist/react/features/board/boardPictureStyles.internal.js +415 -0
  195. package/dist/react/features/board/boardPictures.internal.js +19 -13
  196. package/dist/react/features/board/boardView.internal.js +190 -50
  197. package/dist/react/features/board/boardVoice.internal.js +10 -11
  198. package/dist/react/features/board/index.d.ts +108 -18
  199. package/dist/react/features/callout/index.d.ts +3 -2
  200. package/dist/react/features/combobox/index.d.ts +8 -8
  201. package/dist/react/features/comments/index.d.ts +6 -5
  202. package/dist/react/features/date/index.d.ts +4 -3
  203. package/dist/react/features/details/index.d.ts +4 -3
  204. package/dist/react/features/field/FieldPlugin.js +35 -0
  205. package/dist/react/features/field/index.d.ts +315 -0
  206. package/dist/react/features/field/index.js +2 -0
  207. package/dist/react/features/footnote/index.d.ts +7 -6
  208. package/dist/react/features/format-painter/index.d.ts +4 -3
  209. package/dist/react/features/ink/InkContent.js +313 -0
  210. package/dist/react/features/ink/index.d.ts +57 -33
  211. package/dist/react/features/ink/index.js +2 -2
  212. package/dist/react/features/ink/inkCapture.internal.js +39 -17
  213. package/dist/react/features/ink/inkInput.internal.js +1 -1
  214. package/dist/react/features/ink/inkLayout.internal.js +6 -3
  215. package/dist/react/features/ink/inkPaint.internal.js +78 -2
  216. package/dist/react/features/ink/inkPlacement.internal.js +332 -104
  217. package/dist/react/features/ink/inkWatch.internal.js +7 -5
  218. package/dist/react/features/layout/index.d.ts +5 -4
  219. package/dist/react/features/media/index.d.ts +5 -4
  220. package/dist/react/features/mention/index.d.ts +6 -5
  221. package/dist/react/features/resizable/Resizable.js +4 -6
  222. package/dist/react/features/resizable/index.d.ts +5 -5
  223. package/dist/react/features/suggestion/index.d.ts +6 -5
  224. package/dist/react/features/table/TablePlugin.js +4 -11
  225. package/dist/react/features/table/index.d.ts +10 -8
  226. package/dist/react/features/table/useTableResize.js +10 -1
  227. package/dist/react/features/toc/index.d.ts +2 -2
  228. package/dist/react/features/upload/index.d.ts +11 -6
  229. package/dist/react/index.d.ts +6 -6
  230. package/dist/react/index.js +4 -4
  231. package/dist/react/internal/plate-context.js +434 -188
  232. package/dist/react/plite-react.js +2 -2
  233. package/dist/react/plugins/navigation-feedback/NavigationFeedbackPlugin.js +12 -10
  234. package/dist/react/stores/plate/useEditor.js +32 -14
  235. package/dist/react/stores/plate/useEditorHistory.js +55 -0
  236. package/dist/react/stores/plate/useEditorSelector.js +79 -21
  237. package/dist/react/utils/BlockPlaceholderPlugin.js +5 -2
  238. package/dist/react/utils/pipeRenderElement.internal.js +1 -1
  239. package/dist/react/utils/pluginRenderElement.internal.js +1 -1
  240. package/dist/react/virtualized.d.ts +4 -4
  241. package/dist/{source-CNKy99Th.d.ts → source-BGohy8vH.d.ts} +4 -4
  242. package/dist/static/index.d.ts +18 -18
  243. package/dist/static/internal/renderStaticHtmlWithOverrides.js +2 -2
  244. package/dist/static/internal/staticPresentation.js +4 -4
  245. package/dist/static/internal/writeStaticSelectionClipboardData.js +7 -2
  246. package/dist/tabbable/index.d.ts +1 -1
  247. package/dist/tabbable/react/index.d.ts +3 -3
  248. package/dist/testing/index.d.ts +3 -3
  249. package/dist/yjs/index.d.ts +1 -1
  250. package/dist/yjs/react/index.d.ts +6 -6
  251. package/package.json +20 -2
  252. package/dist/markdown/lib/serializer/convertTextsSerialize.js +0 -163
  253. package/dist/react/components/EditorSelectionView.js +0 -40
  254. package/dist/react/features/ink/InkLayer.js +0 -218
  255. package/dist/react/internal/createPlateTargetScope.js +0 -62
@@ -0,0 +1,360 @@
1
+ import { EditorRefusalError, claimsHistoryReplay, getActiveEditorUpdateId, getActiveEditorUpdateTags, getSnapshotVersion, readElementPropertyWrites, readRootEntries, readViewPage, registerEditorTransactionGuard } from "../../../facade.js";
2
+ import { failInvariant } from "../../../internal/failInvariant.js";
3
+ import { definePlugin } from "../../../lib/plugin/definePlugin.js";
4
+ import { ElementApi, documentReplacement, locateAt, property, schema, target, txLocate } from "../../../core.js";
5
+ import { FIELD_KINDS, FIELD_TESTS, conditionProblem, fieldLinks, fieldProblems, fitsField, isFieldCondition, isFieldKind, isFieldOptions, isFieldValue, sharedFieldLinks, unfitSettings } from "./fieldRules.internal.js";
6
+ import { nanoid } from "nanoid";
7
+ //#region src/features/field/lib/BaseFieldPlugin.ts
8
+ const fieldText = ({ node: { label, options, value } }) => {
9
+ return (options?.find((option) => option.value === value)?.label ?? String(value ?? "")) || `[${label ?? ""}]`;
10
+ };
11
+ const FIELD_TYPE = "field";
12
+ const fieldSchemaPlugin = definePlugin(FIELD_TYPE, {
13
+ formats: ({ defineFormats, schema: { type } }) => defineFormats({
14
+ docx: {
15
+ dropped: "Word keeps each field answer and drops its settings.",
16
+ text: fieldText
17
+ },
18
+ html: {
19
+ decode: ({ element, preserve }) => {
20
+ const kind = element.getAttribute("data-field-kind");
21
+ const label = element.getAttribute("data-field-label");
22
+ const role = element.getAttribute("data-field-role");
23
+ if (!isFieldKind(kind) || label === null || role === null) return;
24
+ const fieldId = element.getAttribute("data-field-id");
25
+ const claimIfValid = (attribute, is) => {
26
+ let value;
27
+ try {
28
+ value = JSON.parse(element.getAttribute(attribute) ?? "");
29
+ } catch {
30
+ return;
31
+ }
32
+ if (!is(value)) return void 0;
33
+ preserve(attribute);
34
+ return value;
35
+ };
36
+ const condition = claimIfValid("data-field-condition", isFieldCondition);
37
+ const defaultValue = claimIfValid("data-field-default-value", isFieldValue);
38
+ const options = claimIfValid("data-field-options", isFieldOptions);
39
+ const required = claimIfValid("data-field-required", (value) => typeof value === "boolean");
40
+ const value = claimIfValid("data-field-value", isFieldValue);
41
+ preserve("data-field-id", "data-field-kind", "data-field-label", "data-field-role");
42
+ return {
43
+ children: [{ text: "" }],
44
+ ...condition === void 0 ? {} : { condition },
45
+ ...defaultValue === void 0 ? {} : { defaultValue },
46
+ ...fieldId === null ? {} : { fieldId },
47
+ kind,
48
+ label,
49
+ ...options === void 0 ? {} : { options },
50
+ ...required === void 0 ? {} : { required },
51
+ role,
52
+ ...value === void 0 ? {} : { value }
53
+ };
54
+ },
55
+ encode: ({ content, node, preserve }) => {
56
+ const json = (value) => value === void 0 ? void 0 : JSON.stringify(value);
57
+ preserve("condition", "defaultValue", "fieldId", "kind", "label", "options", "required", "role", "value");
58
+ return {
59
+ attributes: {
60
+ "data-field-condition": json(node.condition),
61
+ "data-field-default-value": json(node.defaultValue),
62
+ "data-field-id": node.fieldId,
63
+ "data-field-kind": node.kind,
64
+ "data-field-label": node.label,
65
+ "data-field-options": json(node.options),
66
+ "data-field-required": json(node.required),
67
+ "data-field-role": node.role,
68
+ "data-field-value": json(node.value)
69
+ },
70
+ children: [content, { text: fieldText({ node }) }],
71
+ tag: "span"
72
+ };
73
+ },
74
+ match: [{
75
+ attributes: { "data-field-kind": true },
76
+ tag: "span"
77
+ }]
78
+ },
79
+ markdown: {
80
+ tag: type,
81
+ decode: ({ readTagAttributes, refuse }) => {
82
+ const { attributes, properties } = readTagAttributes();
83
+ if (!("kind" in properties && "label" in properties && "role" in properties)) return refuse("A field tag needs a kind, a label and a role.");
84
+ return {
85
+ ...properties,
86
+ ...typeof attributes.fieldId === "string" ? { fieldId: attributes.fieldId } : {},
87
+ children: [{ text: "" }],
88
+ type
89
+ };
90
+ },
91
+ encode: ({ encodeAttributes, encodeNodeAttributes, node }) => ({
92
+ attributes: [...encodeNodeAttributes(), ...encodeAttributes({ fieldId: node.fieldId })],
93
+ children: [],
94
+ name: type,
95
+ type: "mdxJsxTextElement"
96
+ })
97
+ },
98
+ plainText: { encode: fieldText }
99
+ }),
100
+ initialState: { fillRole: null },
101
+ schema: {
102
+ element: {
103
+ properties: {
104
+ defaultValue: property.json({
105
+ validate: isFieldValue,
106
+ validationVersion: 1
107
+ }),
108
+ kind: property.enum(FIELD_KINDS, { required: true }),
109
+ label: property.string({ required: true }),
110
+ options: property.json({
111
+ validate: isFieldOptions,
112
+ validationVersion: 1
113
+ }),
114
+ required: property.boolean(),
115
+ role: property.string({ required: true }),
116
+ value: property.json({
117
+ validate: isFieldValue,
118
+ validationVersion: 1
119
+ })
120
+ },
121
+ void: "inline"
122
+ },
123
+ properties: {
124
+ condition: schema.elementProperty(property.json({
125
+ validate: isFieldCondition,
126
+ validationVersion: 1
127
+ }), {
128
+ references: {
129
+ key: "fieldId",
130
+ map: (condition, renamed) => ({
131
+ ...condition,
132
+ ref: renamed(condition.ref) ?? condition.ref
133
+ })
134
+ },
135
+ target: target.types([FIELD_TYPE]),
136
+ typeChange: "preserve-if-allowed"
137
+ }),
138
+ fieldId: schema.elementProperty(property.string({ generate: nanoid }), {
139
+ landing: "preserve",
140
+ role: "metadata",
141
+ target: target.types([FIELD_TYPE]),
142
+ typeChange: "preserve-if-allowed",
143
+ unique: true
144
+ })
145
+ }
146
+ }
147
+ });
148
+ const refusal = (reason) => /* @__PURE__ */ new TypeError(`Field write refused: ${reason}.`);
149
+ const UNKNOWN_FILL_MODE = Symbol("unknown fill mode");
150
+ /**
151
+ * Fields: inline voids that each collect one value of a kind and hold a
152
+ * document-wide unique `fieldId`. A field's `condition` names another field
153
+ * by that id, so a paste that copies both names the copy.
154
+ */
155
+ const BaseFieldPlugin = fieldSchemaPlugin.extend(({ editor, schema: { properties, type }, store }) => {
156
+ const isField = (node) => ElementApi.isElement(node) && node.type === type;
157
+ let topStep = {
158
+ mode: null,
159
+ version: -1
160
+ };
161
+ let openWrite = null;
162
+ const openWriteOfThisUpdate = () => openWrite?.updateId === getActiveEditorUpdateId(editor) ? openWrite : null;
163
+ return {
164
+ activate({ onCleanup }) {
165
+ topStep = {
166
+ mode: store.get("fillRole") ?? null,
167
+ version: getSnapshotVersion(editor)
168
+ };
169
+ onCleanup(registerEditorTransactionGuard(editor, ({ before, commit, effects }) => {
170
+ const role = store.get("fillRole") ?? null;
171
+ const write = openWriteOfThisUpdate();
172
+ const refuse = (message) => new EditorRefusalError({
173
+ reason: "field-fill",
174
+ role
175
+ }, message);
176
+ const { tags } = commit;
177
+ const collaboration = tags.includes("collaboration");
178
+ const switched = write !== null && (write.switched || write.mode !== role);
179
+ if (switched && !collaboration) throw refuse(`The fill role changed from ${JSON.stringify(write.mode)} to ${JSON.stringify(role)} inside one update.`);
180
+ const replaces = commit.annotations[documentReplacement.key] === true;
181
+ const publish = tags.includes("historic") || replaces || !tags.includes("history-skip") && (!commit.changes.empty || commit.effects.some(({ type: effect }) => effect.history !== "skip")) ? () => {
182
+ if (commit.version <= topStep.version) return;
183
+ topStep = {
184
+ mode: write === null || switched || tags.includes("historic") || replaces ? UNKNOWN_FILL_MODE : tags.includes("history-push") || write.mode === topStep.mode ? write.mode : UNKNOWN_FILL_MODE,
185
+ version: commit.version
186
+ };
187
+ } : void 0;
188
+ if (role === null || collaboration) return publish;
189
+ if (replaces) throw refuse(`A fill as ${JSON.stringify(role)} cannot replace the document.`);
190
+ if ((claimsHistoryReplay(commit) || effects.some(({ type: effect }) => effect.collab === "shared" || effect.persist) ? null : readElementPropertyWrites(editor, {
191
+ before,
192
+ commit
193
+ }))?.every(({ element, modifications }) => isField(element) && element.role === role && modifications.every((modification) => modification.key === "value" && (modification.type === "unset" || modification.type === "set" && fitsField(element, modification.value))))) return publish;
194
+ throw refuse(`A fill as ${JSON.stringify(role)} changes only the values of that role's fields.`);
195
+ }));
196
+ },
197
+ corrections: [{
198
+ event: "properties",
199
+ query: { type },
200
+ correct: ({ tx }) => {
201
+ const mode = store.get("fillRole") ?? null;
202
+ const write = openWriteOfThisUpdate();
203
+ if (write) write.switched ||= write.mode !== mode;
204
+ else openWrite = {
205
+ mode,
206
+ switched: false,
207
+ updateId: getActiveEditorUpdateId(editor)
208
+ };
209
+ if (mode !== topStep.mode && !getActiveEditorUpdateTags(editor).some((tag) => [
210
+ "collaboration",
211
+ "historic",
212
+ "history-merge",
213
+ "history-skip"
214
+ ].includes(tag))) tx.tags.add("history-push");
215
+ }
216
+ }],
217
+ read: ({ editor: reader, state }) => {
218
+ const held = (fieldId) => {
219
+ const holder = state.unique.holder("fieldId", fieldId);
220
+ const node = holder && state.nodes.get(holder.key)?.[0];
221
+ return node && isField(node) ? node : void 0;
222
+ };
223
+ const fieldsIn = (nodes) => nodes.flatMap((node) => {
224
+ if (isField(node)) return [node];
225
+ return ElementApi.isElement(node) ? fieldsIn(node.children) : [];
226
+ });
227
+ const listed = () => {
228
+ const roots = getActiveEditorUpdateId(reader) ? readRootEntries(reader) : reader.read.roots();
229
+ const nodes = [readViewPage(state) ?? state.children(), ...roots.map(({ root }) => state.root(root))].flatMap(fieldsIn);
230
+ const byId = /* @__PURE__ */ new Map();
231
+ const repeated = /* @__PURE__ */ new Set();
232
+ for (const node of nodes) {
233
+ if (typeof node.fieldId !== "string") continue;
234
+ if (byId.has(node.fieldId)) repeated.add(node.fieldId);
235
+ else byId.set(node.fieldId, node);
236
+ }
237
+ const lookup = (id) => repeated.has(id) ? held(id) : byId.get(id);
238
+ return {
239
+ lookup,
240
+ nodes
241
+ };
242
+ };
243
+ return {
244
+ /**
245
+ * The field whose `fieldId` is `fieldId`, in any root, or null when
246
+ * no field holds it. Looks up the field, then one field for each
247
+ * condition it follows along the chain.
248
+ */
249
+ field: (fieldId) => {
250
+ const node = held(fieldId);
251
+ if (!node) return null;
252
+ const link = sharedFieldLinks(reader).link(node, held);
253
+ return {
254
+ applies: link.applies,
255
+ fieldId,
256
+ node,
257
+ problems: fieldProblems(node, link)
258
+ };
259
+ },
260
+ /** Every field of the document, in reading order. */
261
+ fields: () => {
262
+ const { lookup, nodes } = listed();
263
+ const links = fieldLinks();
264
+ return nodes.map((node) => {
265
+ const link = lookup(node.fieldId) === node ? links.link(node, lookup) : links.linkCopy(node, lookup);
266
+ return {
267
+ applies: link.applies,
268
+ fieldId: node.fieldId,
269
+ node,
270
+ problems: fieldProblems(node, link)
271
+ };
272
+ });
273
+ },
274
+ /**
275
+ * The `value` of each field of `role` that holds one, keyed by
276
+ * `fieldId` and read from the field that id names, to pass to
277
+ * `applyFieldValues`.
278
+ */
279
+ submission: (role) => {
280
+ const { lookup, nodes } = listed();
281
+ const values = Object.create(null);
282
+ for (const node of nodes) if (node.role === role && isFieldValue(node.value) && lookup(node.fieldId) === node) values[node.fieldId] = node.value;
283
+ return {
284
+ role,
285
+ values
286
+ };
287
+ }
288
+ };
289
+ },
290
+ update: ({ tx }) => {
291
+ const held = (fieldId) => {
292
+ const holder = tx.unique.holder("fieldId", fieldId);
293
+ const node = holder && tx.nodes.get(holder.key)?.[0];
294
+ return node && isField(node) ? [node, holder.key] : [];
295
+ };
296
+ const checkCondition = (condition, self) => {
297
+ const problem = conditionProblem(condition, condition.ref === self?.fieldId ? self : held(condition.ref)[0]);
298
+ if (problem) throw refusal(`its condition has ${problem}`);
299
+ };
300
+ return {
301
+ /**
302
+ * Insert a field and return its new `fieldId`. Throws when a value,
303
+ * default or options do not fit `kind`, or the condition names no
304
+ * field, or a test or value the named field's kind does not take,
305
+ * or the settings name a `fieldId`.
306
+ */
307
+ insert: txLocate(locateAt(1), (settings, options = {}) => {
308
+ if ("fieldId" in settings) throw refusal("fieldId is not a setting");
309
+ const [unfit] = unfitSettings(settings);
310
+ if (unfit) throw refusal(`${unfit} does not fit a ${settings.kind} field`);
311
+ if (settings.condition) checkCondition(settings.condition);
312
+ const field = tx.schema.create(type, settings);
313
+ tx.nodes.insert(field, options);
314
+ return tx.schema.getProperty(field, properties.fieldId) ?? failInvariant("A created field holds no fieldId.");
315
+ }),
316
+ /**
317
+ * Change the settings or value of the field whose `fieldId` is
318
+ * `fieldId`. A new kind or new options drop each value, default or
319
+ * options the patch leaves out and the field no longer fits. Throws,
320
+ * and changes nothing, when no field holds `fieldId`, a setting the
321
+ * patch names does not fit the field's kind, the patch removes `kind`,
322
+ * `role` or `label` or names `fieldId`, or its condition names no
323
+ * field, a test or value the named field's kind does not take, or a
324
+ * field it did not name before whose chain of conditions leads back
325
+ * to this one. While a fill role is set, a missing field or a
326
+ * setting that does not fit refuses the whole update instead, which
327
+ * then returns `undefined`.
328
+ */
329
+ update: txLocate(false, (fieldId, patch) => {
330
+ if ("fieldId" in patch) throw refusal("fieldId is not a setting");
331
+ const role = store.get("fillRole");
332
+ const refusalForRole = (reason) => role == null ? refusal(reason) : new EditorRefusalError({
333
+ reason: "field-fill",
334
+ role
335
+ }, `A fill as ${JSON.stringify(role)} refused: ${reason}.`);
336
+ const [field, key] = held(fieldId);
337
+ if (!field) throw refusalForRole(`no field holds ${JSON.stringify(fieldId)}`);
338
+ const next = {
339
+ ...field,
340
+ ...patch
341
+ };
342
+ const unfit = unfitSettings(next);
343
+ const named = unfit.find((setting) => setting in patch);
344
+ if (named) throw refusalForRole(`${named} does not fit a ${next.kind} field`);
345
+ if (patch.condition) {
346
+ checkCondition(patch.condition, next);
347
+ if (patch.condition.ref !== field.condition?.ref && fieldLinks().link(next, (id) => id === fieldId ? next : held(id)[0]).loop) throw refusal("its condition closes a loop");
348
+ }
349
+ const reshaped = "kind" in patch || "options" in patch;
350
+ tx.nodes.set({
351
+ ...patch,
352
+ ...reshaped ? Object.fromEntries(unfit.map((setting) => [setting, void 0])) : {}
353
+ }, { at: key });
354
+ })
355
+ };
356
+ }
357
+ };
358
+ });
359
+ //#endregion
360
+ export { BaseFieldPlugin, FIELD_TESTS, fitsField };
@@ -0,0 +1,188 @@
1
+ import { fieldProblems, fitsField, isFieldCondition, isFieldKind, isFieldOptions, isFieldValue, isFilled, submittedFieldLinks } from "./fieldRules.internal.js";
2
+ //#region src/features/field/lib/applyFieldValues.ts
3
+ const isChildren = (template) => Array.isArray(template);
4
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
5
+ const isText = (value) => isRecord(value) && typeof value.text === "string" && !("children" in value);
6
+ const placesIn = (nodes, type, root, path = []) => nodes.flatMap((node, index) => {
7
+ if (!isRecord(node) || isText(node)) return [];
8
+ const at = [...path, index];
9
+ if (node.type === type) return [{
10
+ node,
11
+ path: at,
12
+ ...root === void 0 ? {} : { root }
13
+ }];
14
+ return Array.isArray(node.children) ? placesIn(node.children, type, root, at) : [];
15
+ });
16
+ const isWellFormed = (node) => !("text" in node) && Array.isArray(node.children) && node.children.length === 1 && isText(node.children[0]) && typeof node.fieldId === "string" && isFieldKind(node.kind) && typeof node.label === "string" && typeof node.role === "string" && (node.required === void 0 || typeof node.required === "boolean") && (node.condition === void 0 || isFieldCondition(node.condition)) && (node.defaultValue === void 0 || isFieldValue(node.defaultValue)) && (node.options === void 0 || isFieldOptions(node.options)) && (node.value === void 0 || isFieldValue(node.value));
17
+ const fillNodes = (nodes, type, held) => {
18
+ let changed = false;
19
+ const next = nodes.map((node) => {
20
+ const filled = fillNode(node, type, held);
21
+ changed ||= filled !== node;
22
+ return filled;
23
+ });
24
+ return changed ? next : nodes;
25
+ };
26
+ const fillNode = (node, type, held) => {
27
+ if (!isRecord(node) || !Array.isArray(node.children)) return node;
28
+ if (node.type === type) {
29
+ const answer = typeof node.fieldId === "string" ? held.get(node.fieldId)?.value : void 0;
30
+ return answer === void 0 ? node : {
31
+ ...node,
32
+ value: answer
33
+ };
34
+ }
35
+ const children = fillNodes(node.children, type, held);
36
+ return children === node.children ? node : {
37
+ ...node,
38
+ children
39
+ };
40
+ };
41
+ /**
42
+ * Check each role's answers against a frozen template and build the filled
43
+ * document from the answers alone. `type` names the field element's type when
44
+ * the app renamed it with `schema.override`. `submissions` are in the order
45
+ * the roles submitted, and each is checked against the roles before it plus
46
+ * its own answers. A submitted role's checkbox with no answer reads as `false`
47
+ * while it applies.
48
+ *
49
+ * Refuses a template whose fields hold an answer, lack or repeat a `fieldId`,
50
+ * break the schema or have a problem a read reports, a condition loop
51
+ * included. Then refuses, at the first submission that has any: a malformed
52
+ * submission, a role that submitted before or owns no field, an answer for a
53
+ * field that is missing, of another role or does not fit it, a field of the
54
+ * role that waits on another role, a filled answer on a skipped field, and a
55
+ * required field that applies without a filled answer.
56
+ */
57
+ function applyFieldValues(template, submissions, options) {
58
+ const type = options?.type ?? "field";
59
+ const document = isChildren(template) ? { children: template } : template;
60
+ const roots = Object.entries(document.roots ?? {});
61
+ const places = [...placesIn(document.children, type, void 0), ...roots.flatMap(([root, nodes]) => placesIn(nodes, type, root))];
62
+ const first = /* @__PURE__ */ new Map();
63
+ for (const place of places) {
64
+ const { fieldId } = place.node;
65
+ if (typeof fieldId === "string" && !first.has(fieldId)) first.set(fieldId, place);
66
+ }
67
+ const held = /* @__PURE__ */ new Map();
68
+ for (const [fieldId, { node }] of first) if (isWellFormed(node)) held.set(fieldId, node);
69
+ const lookup = (fieldId) => held.get(fieldId);
70
+ const templateLinks = submittedFieldLinks(/* @__PURE__ */ new Set());
71
+ const [templateRefusal, ...templateRefusals] = places.flatMap((place) => {
72
+ const { node, path, root } = place;
73
+ const invalid = (problem) => ({
74
+ code: "invalid-template",
75
+ ...typeof node.fieldId === "string" ? { fieldId: node.fieldId } : {},
76
+ path,
77
+ problem,
78
+ ...root === void 0 ? {} : { root }
79
+ });
80
+ const duplicate = typeof node.fieldId === "string" && first.get(node.fieldId) !== place ? [invalid("duplicate-id")] : [];
81
+ if (!isWellFormed(node)) return [invalid("malformed"), ...duplicate];
82
+ const answered = node.value === void 0 ? [] : [invalid("answered")];
83
+ if (duplicate.length > 0) return [...answered, ...duplicate];
84
+ return [...answered, ...fieldProblems(node, templateLinks.link(node, lookup)).map((problem) => invalid(problem))];
85
+ });
86
+ if (templateRefusal) return {
87
+ ok: false,
88
+ refusals: [templateRefusal, ...templateRefusals]
89
+ };
90
+ const fields = [...held.values()];
91
+ const roles = [...new Set(fields.map(({ role }) => role))];
92
+ const settled = /* @__PURE__ */ new Set();
93
+ for (const [index, submission] of submissions.entries()) {
94
+ if (!isRecord(submission) || typeof submission.role !== "string" || !isRecord(submission.values)) return {
95
+ ok: false,
96
+ refusals: [{
97
+ code: "invalid-submission",
98
+ index
99
+ }]
100
+ };
101
+ const { role, values } = submission;
102
+ if (settled.has(role)) return {
103
+ ok: false,
104
+ refusals: [{
105
+ code: "duplicate-role",
106
+ role
107
+ }]
108
+ };
109
+ if (!roles.includes(role)) return {
110
+ ok: false,
111
+ refusals: [{
112
+ code: "unknown-role",
113
+ role
114
+ }]
115
+ };
116
+ const refusals = [];
117
+ const refusedIds = /* @__PURE__ */ new Set();
118
+ for (const [fieldId, value] of Object.entries(values)) {
119
+ const field = lookup(fieldId);
120
+ const code = !field ? "unknown-field" : field.role !== role ? "wrong-role" : fitsField(field, value) ? void 0 : "invalid-value";
121
+ if (code) {
122
+ refusals.push({
123
+ code,
124
+ fieldId,
125
+ role
126
+ });
127
+ refusedIds.add(fieldId);
128
+ } else if (field) held.set(fieldId, {
129
+ ...field,
130
+ value
131
+ });
132
+ }
133
+ settled.add(role);
134
+ const links = submittedFieldLinks(settled);
135
+ for (const field of fields) {
136
+ if (field.role !== role) continue;
137
+ const verdict = links.link(field, lookup);
138
+ const { fieldId } = field;
139
+ if (verdict.applies === null) {
140
+ refusals.push({
141
+ code: "waiting",
142
+ fieldId,
143
+ role,
144
+ waitsOn: verdict.waitsOn
145
+ });
146
+ continue;
147
+ }
148
+ if (refusedIds.has(fieldId)) continue;
149
+ const filled = isFilled(field, held.get(fieldId)?.value);
150
+ if (!verdict.applies && filled) refusals.push({
151
+ code: "skipped",
152
+ fieldId,
153
+ role
154
+ });
155
+ else if (verdict.applies && field.required && !filled) refusals.push({
156
+ code: "missing-required",
157
+ fieldId,
158
+ role
159
+ });
160
+ }
161
+ const [refusal, ...rest] = refusals;
162
+ if (refusal) return {
163
+ ok: false,
164
+ refusals: [refusal, ...rest]
165
+ };
166
+ }
167
+ const links = submittedFieldLinks(settled);
168
+ const pending = /* @__PURE__ */ new Set();
169
+ for (const field of fields) {
170
+ if (settled.has(field.role) || !field.required) continue;
171
+ const verdict = links.link(field, lookup);
172
+ if (verdict.applies === false) continue;
173
+ pending.add(field.role);
174
+ if (verdict.applies === null) pending.add(verdict.waitsOn);
175
+ }
176
+ const children = fillNodes(document.children, type, held);
177
+ return {
178
+ document: isChildren(template) ? children : {
179
+ ...document,
180
+ children,
181
+ ...document.roots ? { roots: Object.fromEntries(roots.map(([root, nodes]) => [root, fillNodes(nodes, type, held)])) } : {}
182
+ },
183
+ ok: true,
184
+ pending: roles.filter((role) => pending.has(role))
185
+ };
186
+ }
187
+ //#endregion
188
+ export { applyFieldValues };