plitejs 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 (865) hide show
  1. package/dist/{internal/view/annotation-store-metrics.js → annotation-store-metrics-Ccjkef45.js} +1 -1
  2. package/dist/annotations/index.d.ts +1 -1
  3. package/dist/annotations/index.js +1 -1
  4. package/dist/authored/index.d.ts +596 -9
  5. package/dist/authored/index.js +18557 -4
  6. package/dist/{core/authored-veto.js → authored-veto-DSnQcHGR.js} +2 -2
  7. package/dist/{internal/browser-protocol.js → browser-protocol-pvt4HFF7.js} +1 -1
  8. package/dist/comparison-plan-CEQL0ooW.js +1338 -0
  9. package/dist/{diff/lib/comparison-types.d.ts → comparison-types-Dt-unJZY.d.ts} +11 -6
  10. package/dist/create-editor-CkHtPWXV.js +1107 -0
  11. package/dist/diff/index.d.ts +31 -3
  12. package/dist/diff/index.js +1747 -1
  13. package/dist/dom/index.d.ts +2 -19
  14. package/dist/dom/index.js +2 -16
  15. package/dist/dom-Cgfscvnm.js +9220 -0
  16. package/dist/{core/same-result.js → editor-owner-IUmkTeXz.js} +77 -2
  17. package/dist/{core/editor-view-lifetime.js → editor-view-lifetime-GJKa_QGh.js} +1 -1
  18. package/dist/history/index.d.ts +169 -3
  19. package/dist/history/index.js +6717 -2
  20. package/dist/hyperscript/index.d.ts +1 -19
  21. package/dist/hyperscript/index.js +1 -8
  22. package/dist/{hyperscript/creators.js → hyperscript-FPuoArEi.js} +134 -8
  23. package/dist/index-BpQx2UG4.d.ts +1093 -0
  24. package/dist/{yjs/core/plugin.d.ts → index-Cw-oC2ps.d.ts} +88 -5
  25. package/dist/{annotations/store.d.ts → index-DPWyk3lG.d.ts} +21 -6
  26. package/dist/index-DpltOCot.d.ts +9753 -0
  27. package/dist/index-HPYawTae.d.ts +119 -0
  28. package/dist/index-K0Za9YXc.d.ts +1246 -0
  29. package/dist/index.d.ts +1 -50
  30. package/dist/index.js +4 -34
  31. package/dist/internal/index.d.ts +2 -54
  32. package/dist/internal/index.js +156 -52
  33. package/dist/{internal/view/mapped-view-store.js → mapped-view-store-ld-6uxEU.js} +2 -3
  34. package/dist/{core/native-grouping-input.js → native-grouping-input-DMNcsIaW.js} +2 -2
  35. package/dist/pagination/index.d.ts +1 -7
  36. package/dist/pagination/index.js +1 -693
  37. package/dist/pagination/react.d.ts +2 -4
  38. package/dist/pagination/react.js +436 -30
  39. package/dist/pagination-D_A8iPJP.js +1021 -0
  40. package/dist/plugin-DWzkJbnJ.js +50999 -0
  41. package/dist/{react/range-geometry.d.ts → range-geometry-BLAHRE11.d.ts} +2 -2
  42. package/dist/{react/range-geometry.js → range-geometry-BjeLHOnl.js} +23 -18
  43. package/dist/react/index.d.ts +5 -97
  44. package/dist/react/index.js +7 -72
  45. package/dist/react/virtualized.d.ts +2 -4
  46. package/dist/react/virtualized.js +146 -7
  47. package/dist/react-DZ15gmz2.js +1018 -0
  48. package/dist/{core/change/retraction.js → retraction-BMem8Rfk.js} +16 -4
  49. package/dist/src-cT1OTKP_.js +1386 -0
  50. package/dist/{internal/view/stable-id-mapped-source.js → store-Cz2mXyDe.js} +240 -3
  51. package/dist/testing/index.d.ts +182 -8
  52. package/dist/testing/index.js +95 -8
  53. package/dist/use-editor-dom-scope-BbMDSCpW.js +28354 -0
  54. package/dist/yjs/index.d.ts +1 -4
  55. package/dist/yjs/index.js +1 -2
  56. package/dist/yjs/react/index.d.ts +25 -5
  57. package/dist/yjs/react/index.js +84 -3
  58. package/dist/yjs-DOK-m7kl.js +13413 -0
  59. package/package.json +1 -1
  60. package/dist/annotations/store.js +0 -244
  61. package/dist/authored/authored.d.ts +0 -116
  62. package/dist/authored/authored.js +0 -1271
  63. package/dist/authored/changes.js +0 -365
  64. package/dist/authored/comparison.d.ts +0 -41
  65. package/dist/authored/comparison.js +0 -270
  66. package/dist/authored/decision-window.js +0 -42
  67. package/dist/authored/decision.js +0 -306
  68. package/dist/authored/facts/admission.js +0 -388
  69. package/dist/authored/facts/compact.d.ts +0 -2
  70. package/dist/authored/facts/compact.js +0 -91
  71. package/dist/authored/facts/dependencies.d.ts +0 -5
  72. package/dist/authored/facts/dependencies.js +0 -66
  73. package/dist/authored/facts/editing.js +0 -12
  74. package/dist/authored/facts/facts.d.ts +0 -8
  75. package/dist/authored/facts/facts.js +0 -535
  76. package/dist/authored/facts/records.d.ts +0 -28
  77. package/dist/authored/facts/records.js +0 -226
  78. package/dist/authored/facts/settle.js +0 -529
  79. package/dist/authored/format.d.ts +0 -34
  80. package/dist/authored/format.js +0 -175
  81. package/dist/authored/ledger/book.js +0 -809
  82. package/dist/authored/ledger/cards.js +0 -223
  83. package/dist/authored/ledger/ledger.js +0 -830
  84. package/dist/authored/ledger/level.js +0 -1081
  85. package/dist/authored/ledger/links.js +0 -20
  86. package/dist/authored/ledger/pairs.js +0 -334
  87. package/dist/authored/ledger/places.js +0 -524
  88. package/dist/authored/ledger/preview-lens.js +0 -252
  89. package/dist/authored/ledger/projection.js +0 -163
  90. package/dist/authored/ledger/roots.js +0 -11
  91. package/dist/authored/ledger/runs.js +0 -480
  92. package/dist/authored/ledger/slots.js +0 -330
  93. package/dist/authored/ledger/work.js +0 -66
  94. package/dist/authored/refusal.d.ts +0 -33
  95. package/dist/authored/refusal.js +0 -188
  96. package/dist/authored/resolve-schema.js +0 -62
  97. package/dist/authored/tree/alignment.js +0 -456
  98. package/dist/authored/tree/carried.js +0 -205
  99. package/dist/authored/tree/command-values.js +0 -344
  100. package/dist/authored/tree/cuts.js +0 -320
  101. package/dist/authored/tree/grid.js +0 -49
  102. package/dist/authored/tree/halves.js +0 -120
  103. package/dist/authored/tree/holders.js +0 -345
  104. package/dist/authored/tree/holds.js +0 -135
  105. package/dist/authored/tree/layers.d.ts +0 -49
  106. package/dist/authored/tree/layers.js +0 -354
  107. package/dist/authored/tree/marks.d.ts +0 -136
  108. package/dist/authored/tree/marks.js +0 -263
  109. package/dist/authored/tree/proposed.js +0 -212
  110. package/dist/authored/tree/readiness.js +0 -545
  111. package/dist/authored/tree/record-completion.js +0 -423
  112. package/dist/authored/tree/record.js +0 -2908
  113. package/dist/authored/tree/reserves.js +0 -449
  114. package/dist/authored/tree/resolve.d.ts +0 -9
  115. package/dist/authored/tree/resolve.js +0 -1860
  116. package/dist/authored/tree/shown.js +0 -153
  117. package/dist/authored/tree/spare-lines.js +0 -119
  118. package/dist/authored/tree/spares.js +0 -61
  119. package/dist/authored/types.d.ts +0 -177
  120. package/dist/core/anchor-state.d.ts +0 -15
  121. package/dist/core/anchor-state.js +0 -792
  122. package/dist/core/anchor.d.ts +0 -34
  123. package/dist/core/anchor.js +0 -843
  124. package/dist/core/authored-document-capability.d.ts +0 -106
  125. package/dist/core/authored-document-capability.js +0 -6
  126. package/dist/core/authored-runtime.d.ts +0 -10
  127. package/dist/core/authored-runtime.js +0 -67
  128. package/dist/core/authored-veto.d.ts +0 -30
  129. package/dist/core/change/builder.d.ts +0 -546
  130. package/dist/core/change/builder.js +0 -1120
  131. package/dist/core/change/carried-projection.js +0 -1518
  132. package/dist/core/change/carried-run.d.ts +0 -26
  133. package/dist/core/change/carried-run.js +0 -251
  134. package/dist/core/change/carry-program.js +0 -537
  135. package/dist/core/change/classification.d.ts +0 -22
  136. package/dist/core/change/classification.js +0 -205
  137. package/dist/core/change/cross-rule.js +0 -238
  138. package/dist/core/change/cross.js +0 -577
  139. package/dist/core/change/document-change.d.ts +0 -137
  140. package/dist/core/change/document-change.js +0 -872
  141. package/dist/core/change/document-index.d.ts +0 -117
  142. package/dist/core/change/document-index.js +0 -542
  143. package/dist/core/change/draft-facts.js +0 -323
  144. package/dist/core/change/enclosure.d.ts +0 -12
  145. package/dist/core/change/enclosure.js +0 -272
  146. package/dist/core/change/join.js +0 -751
  147. package/dist/core/change/json.d.ts +0 -4
  148. package/dist/core/change/json.js +0 -26
  149. package/dist/core/change/lazy-root.d.ts +0 -1
  150. package/dist/core/change/lazy-root.js +0 -73
  151. package/dist/core/change/lineage.d.ts +0 -49
  152. package/dist/core/change/lineage.js +0 -390
  153. package/dist/core/change/mapping.d.ts +0 -31
  154. package/dist/core/change/mapping.js +0 -186
  155. package/dist/core/change/new-letters.d.ts +0 -14
  156. package/dist/core/change/new-letters.js +0 -139
  157. package/dist/core/change/range-association.js +0 -10
  158. package/dist/core/change/read-back.d.ts +0 -7
  159. package/dist/core/change/read-back.js +0 -7
  160. package/dist/core/change/record.d.ts +0 -59
  161. package/dist/core/change/record.js +0 -346
  162. package/dist/core/change/root-change.d.ts +0 -180
  163. package/dist/core/change/root-change.js +0 -3544
  164. package/dist/core/change/slice-facts.js +0 -89
  165. package/dist/core/change/text-splices.js +0 -98
  166. package/dist/core/change/tokens.d.ts +0 -97
  167. package/dist/core/change/tokens.js +0 -449
  168. package/dist/core/change/transform.d.ts +0 -36
  169. package/dist/core/change/transform.js +0 -97
  170. package/dist/core/change/wrap-fidelity.js +0 -295
  171. package/dist/core/change-events.js +0 -223
  172. package/dist/core/clone.js +0 -28
  173. package/dist/core/command-definition.d.ts +0 -25
  174. package/dist/core/command-definition.js +0 -48
  175. package/dist/core/command-document.d.ts +0 -4
  176. package/dist/core/command-document.js +0 -20
  177. package/dist/core/command-frame.js +0 -628
  178. package/dist/core/command-registry.d.ts +0 -36
  179. package/dist/core/command-registry.js +0 -283
  180. package/dist/core/commit-publication.js +0 -40
  181. package/dist/core/commit.d.ts +0 -26
  182. package/dist/core/commit.js +0 -686
  183. package/dist/core/composition-stamp.d.ts +0 -14
  184. package/dist/core/composition-stamp.js +0 -79
  185. package/dist/core/content-completion.d.ts +0 -4
  186. package/dist/core/content-completion.js +0 -343
  187. package/dist/core/content-landing.js +0 -124
  188. package/dist/core/content-slice-roots.js +0 -36
  189. package/dist/core/content-slice.d.ts +0 -38
  190. package/dist/core/content-slice.js +0 -253
  191. package/dist/core/content.js +0 -18
  192. package/dist/core/correction.js +0 -25
  193. package/dist/core/default-storage.js +0 -53
  194. package/dist/core/document-admission.d.ts +0 -4
  195. package/dist/core/document-admission.js +0 -64
  196. package/dist/core/document-change.d.ts +0 -3
  197. package/dist/core/document-recorder.d.ts +0 -6
  198. package/dist/core/document-recorder.js +0 -67
  199. package/dist/core/document-shape.d.ts +0 -68
  200. package/dist/core/document-shape.js +0 -173
  201. package/dist/core/document-view-read.d.ts +0 -16
  202. package/dist/core/document-view-read.js +0 -36
  203. package/dist/core/draft-track.d.ts +0 -3
  204. package/dist/core/draft-track.js +0 -90
  205. package/dist/core/editor-commands.d.ts +0 -99
  206. package/dist/core/editor-commands.js +0 -505
  207. package/dist/core/editor-lifecycle-api.d.ts +0 -8
  208. package/dist/core/editor-lifecycle-api.js +0 -219
  209. package/dist/core/editor-lifetime.js +0 -12
  210. package/dist/core/editor-owner.d.ts +0 -24
  211. package/dist/core/editor-owner.js +0 -78
  212. package/dist/core/editor-read-execution.d.ts +0 -6
  213. package/dist/core/editor-read-execution.js +0 -64
  214. package/dist/core/editor-read-runtime.js +0 -176
  215. package/dist/core/editor-reads.d.ts +0 -128
  216. package/dist/core/editor-reads.js +0 -63
  217. package/dist/core/editor-runtime.d.ts +0 -112
  218. package/dist/core/editor-runtime.js +0 -20
  219. package/dist/core/editor-schema.d.ts +0 -314
  220. package/dist/core/editor-schema.js +0 -2295
  221. package/dist/core/element-owned-root-index.d.ts +0 -4
  222. package/dist/core/element-owned-root-index.js +0 -353
  223. package/dist/core/get-content-slice.js +0 -118
  224. package/dist/core/get-fragment.js +0 -22
  225. package/dist/core/identity-owner.js +0 -697
  226. package/dist/core/import-content-slice.js +0 -26
  227. package/dist/core/initial-value.js +0 -87
  228. package/dist/core/insert-limit.js +0 -81
  229. package/dist/core/is-empty-element.js +0 -20
  230. package/dist/core/json-fingerprint.js +0 -16
  231. package/dist/core/landing.d.ts +0 -11
  232. package/dist/core/landing.js +0 -279
  233. package/dist/core/lifecycle-error.d.ts +0 -11
  234. package/dist/core/lifecycle-error.js +0 -68
  235. package/dist/core/listener-state.d.ts +0 -1
  236. package/dist/core/listener-state.js +0 -59
  237. package/dist/core/measured-sequence.d.ts +0 -43
  238. package/dist/core/measured-sequence.js +0 -404
  239. package/dist/core/missing-reference.js +0 -15
  240. package/dist/core/node-property-mutation.js +0 -10
  241. package/dist/core/node-selection.js +0 -85
  242. package/dist/core/node-write-veto.d.ts +0 -37
  243. package/dist/core/node-write-veto.js +0 -17
  244. package/dist/core/persisted-document.d.ts +0 -6
  245. package/dist/core/persisted-document.js +0 -39
  246. package/dist/core/persistent-map.js +0 -139
  247. package/dist/core/plain-text.d.ts +0 -32
  248. package/dist/core/plain-text.js +0 -92
  249. package/dist/core/plugin-dispatch.d.ts +0 -21
  250. package/dist/core/plugin-dispatch.js +0 -166
  251. package/dist/core/plugin-point.d.ts +0 -6
  252. package/dist/core/plugin-point.js +0 -21
  253. package/dist/core/plugin-registry.d.ts +0 -78
  254. package/dist/core/plugin-registry.js +0 -485
  255. package/dist/core/plugin-slot.d.ts +0 -23
  256. package/dist/core/plugin-slot.js +0 -30
  257. package/dist/core/plugin.d.ts +0 -125
  258. package/dist/core/plugin.js +0 -1485
  259. package/dist/core/prefix-occupant-join.js +0 -52
  260. package/dist/core/profiling.js +0 -18
  261. package/dist/core/property-validity.d.ts +0 -14
  262. package/dist/core/property-validity.js +0 -65
  263. package/dist/core/public-root.d.ts +0 -10
  264. package/dist/core/public-root.js +0 -50
  265. package/dist/core/public-state.d.ts +0 -191
  266. package/dist/core/public-state.js +0 -6772
  267. package/dist/core/read-definition.js +0 -22
  268. package/dist/core/read-registry.js +0 -127
  269. package/dist/core/record-store.d.ts +0 -12
  270. package/dist/core/record-store.js +0 -297
  271. package/dist/core/refusal.d.ts +0 -1
  272. package/dist/core/refusal.js +0 -40
  273. package/dist/core/representation.d.ts +0 -11
  274. package/dist/core/representation.js +0 -844
  275. package/dist/core/resolved-token-cursor.d.ts +0 -21
  276. package/dist/core/resolved-token-cursor.js +0 -294
  277. package/dist/core/root-entries.js +0 -121
  278. package/dist/core/root-ownership.d.ts +0 -19
  279. package/dist/core/root-ownership.js +0 -354
  280. package/dist/core/root-target.d.ts +0 -7
  281. package/dist/core/root-target.js +0 -281
  282. package/dist/core/same-result.d.ts +0 -18
  283. package/dist/core/schema-compiler.d.ts +0 -345
  284. package/dist/core/schema-compiler.js +0 -3166
  285. package/dist/core/schema-contribution-registry.d.ts +0 -12
  286. package/dist/core/schema-contribution-registry.js +0 -88
  287. package/dist/core/schema-definition.d.ts +0 -307
  288. package/dist/core/schema-definition.js +0 -628
  289. package/dist/core/schema-source.internal.d.ts +0 -49
  290. package/dist/core/schema-validation.d.ts +0 -11
  291. package/dist/core/schema-validation.js +0 -85
  292. package/dist/core/screen-reader-announcement.d.ts +0 -13
  293. package/dist/core/screen-reader-announcement.js +0 -17
  294. package/dist/core/selection-protocol.d.ts +0 -38
  295. package/dist/core/selection-protocol.js +0 -523
  296. package/dist/core/selection-state.js +0 -9
  297. package/dist/core/semantic-update-method.d.ts +0 -11
  298. package/dist/core/semantic-update-method.js +0 -26
  299. package/dist/core/set-root.d.ts +0 -3
  300. package/dist/core/set-root.js +0 -244
  301. package/dist/core/slice-end-matter.js +0 -77
  302. package/dist/core/slice-fit/compiled-slice-fitter.d.ts +0 -56
  303. package/dist/core/slice-fit/compiled-slice-fitter.js +0 -2087
  304. package/dist/core/slice-fit/fit-report.d.ts +0 -36
  305. package/dist/core/slice-fit/fit-report.js +0 -122
  306. package/dist/core/slice-fit/frontier.js +0 -98
  307. package/dist/core/slice-fit/origin.js +0 -57
  308. package/dist/core/slice-fit/provenance.d.ts +0 -30
  309. package/dist/core/slice-fit/provenance.js +0 -245
  310. package/dist/core/slice-identities.js +0 -21
  311. package/dist/core/slice-landing-types.d.ts +0 -61
  312. package/dist/core/slice-landing.js +0 -124
  313. package/dist/core/snapshot-index.d.ts +0 -13
  314. package/dist/core/snapshot-index.js +0 -860
  315. package/dist/core/state-field.d.ts +0 -12
  316. package/dist/core/state-field.js +0 -102
  317. package/dist/core/state-fields.js +0 -36
  318. package/dist/core/survival.js +0 -61
  319. package/dist/core/target-runtime.d.ts +0 -5
  320. package/dist/core/target-runtime.js +0 -42
  321. package/dist/core/transaction-values.d.ts +0 -47
  322. package/dist/core/transaction-values.js +0 -66
  323. package/dist/core/transfer-guard.js +0 -299
  324. package/dist/core/transfer-types.d.ts +0 -170
  325. package/dist/core/transfer.d.ts +0 -72
  326. package/dist/core/transfer.js +0 -655
  327. package/dist/core/tx-only.d.ts +0 -64
  328. package/dist/core/tx-only.js +0 -84
  329. package/dist/core/unique-values.js +0 -298
  330. package/dist/core/update-context.js +0 -28
  331. package/dist/core/update-policy.d.ts +0 -17
  332. package/dist/core/update-policy.js +0 -45
  333. package/dist/core/value-codec.d.ts +0 -35
  334. package/dist/core/value-codec.js +0 -240
  335. package/dist/core/view-carets.d.ts +0 -39
  336. package/dist/core/view-carets.js +0 -676
  337. package/dist/core/view-presentation.d.ts +0 -9
  338. package/dist/core/view-presentation.js +0 -70
  339. package/dist/core/work.d.ts +0 -192
  340. package/dist/core/work.js +0 -122
  341. package/dist/core/writable-text.js +0 -37
  342. package/dist/create-editor.d.ts +0 -187
  343. package/dist/create-editor.js +0 -281
  344. package/dist/diff/lib/compare.d.ts +0 -33
  345. package/dist/diff/lib/compare.js +0 -459
  346. package/dist/diff/lib/comparison-align.js +0 -324
  347. package/dist/diff/lib/comparison-index.js +0 -160
  348. package/dist/diff/lib/comparison-internal.js +0 -108
  349. package/dist/diff/lib/comparison-matcher.js +0 -1221
  350. package/dist/diff/lib/comparison-moves.js +0 -151
  351. package/dist/diff/lib/comparison-plan.js +0 -556
  352. package/dist/diff/lib/index.d.ts +0 -3
  353. package/dist/dom/dom-soft-line-end.d.ts +0 -3
  354. package/dist/dom/dom-soft-line-end.js +0 -295
  355. package/dist/dom/internal/index.d.ts +0 -15
  356. package/dist/dom/plugin/data-transfer-format.d.ts +0 -90
  357. package/dist/dom/plugin/data-transfer-format.js +0 -525
  358. package/dist/dom/plugin/dom-clipboard-runtime.d.ts +0 -50
  359. package/dist/dom/plugin/dom-clipboard-runtime.js +0 -482
  360. package/dist/dom/plugin/dom-coverage.d.ts +0 -140
  361. package/dist/dom/plugin/dom-coverage.js +0 -443
  362. package/dist/dom/plugin/dom-drag-scroll.js +0 -176
  363. package/dist/dom/plugin/dom-drag.d.ts +0 -54
  364. package/dist/dom/plugin/dom-drag.js +0 -507
  365. package/dist/dom/plugin/dom-editor.d.ts +0 -421
  366. package/dist/dom/plugin/dom-editor.js +0 -1316
  367. package/dist/dom/plugin/dom-event-range-targets.js +0 -39
  368. package/dist/dom/plugin/dom-geometry.d.ts +0 -11
  369. package/dist/dom/plugin/dom-geometry.js +0 -888
  370. package/dist/dom/plugin/dom-input-runtime.d.ts +0 -1
  371. package/dist/dom/plugin/dom-input-runtime.js +0 -571
  372. package/dist/dom/plugin/dom-integrity-observer.js +0 -436
  373. package/dist/dom/plugin/dom-node-path.js +0 -61
  374. package/dist/dom/plugin/dom-phase-scheduler.d.ts +0 -1
  375. package/dist/dom/plugin/dom-phase-scheduler.js +0 -284
  376. package/dist/dom/plugin/dom-root-runtime.d.ts +0 -10
  377. package/dist/dom/plugin/dom-root-runtime.js +0 -716
  378. package/dist/dom/plugin/dom-sync-mutation-ownership.d.ts +0 -1
  379. package/dist/dom/plugin/dom-sync-mutation-ownership.js +0 -120
  380. package/dist/dom/plugin/dom-text-flow-index.js +0 -396
  381. package/dist/dom/plugin/dom-text-freshness.js +0 -188
  382. package/dist/dom/plugin/dom-text-proofs.d.ts +0 -2
  383. package/dist/dom/plugin/dom-text-proofs.js +0 -350
  384. package/dist/dom/plugin/dom-view-caret.js +0 -28
  385. package/dist/dom/plugin/with-dom.d.ts +0 -53
  386. package/dist/dom/plugin/with-dom.js +0 -101
  387. package/dist/dom/utils/constants.d.ts +0 -5
  388. package/dist/dom/utils/constants.js +0 -5
  389. package/dist/dom/utils/diff-text.d.ts +0 -51
  390. package/dist/dom/utils/diff-text.js +0 -264
  391. package/dist/dom/utils/dom.d.ts +0 -104
  392. package/dist/dom/utils/dom.js +0 -257
  393. package/dist/dom/utils/drag-session.d.ts +0 -2
  394. package/dist/dom/utils/drag-session.js +0 -115
  395. package/dist/dom/utils/drop-indicator.d.ts +0 -18
  396. package/dist/dom/utils/drop-indicator.js +0 -36
  397. package/dist/dom/utils/environment.d.ts +0 -12
  398. package/dist/dom/utils/environment.js +0 -118
  399. package/dist/dom/utils/hotkey-match.d.ts +0 -36
  400. package/dist/dom/utils/hotkey-match.js +0 -208
  401. package/dist/dom/utils/hotkeys.d.ts +0 -32
  402. package/dist/dom/utils/hotkeys.js +0 -121
  403. package/dist/dom/utils/key.d.ts +0 -14
  404. package/dist/dom/utils/key.js +0 -18
  405. package/dist/dom/utils/plite-dom-markers.d.ts +0 -26
  406. package/dist/dom/utils/plite-dom-markers.js +0 -25
  407. package/dist/dom/utils/selection-writes.d.ts +0 -18
  408. package/dist/dom/utils/selection-writes.js +0 -63
  409. package/dist/dom/utils/weak-maps.d.ts +0 -2
  410. package/dist/dom/utils/weak-maps.js +0 -51
  411. package/dist/editor/above.js +0 -30
  412. package/dist/editor/add-mark.js +0 -79
  413. package/dist/editor/adjacent-character-point.js +0 -120
  414. package/dist/editor/after.js +0 -37
  415. package/dist/editor/before.js +0 -124
  416. package/dist/editor/block-void-break.js +0 -20
  417. package/dist/editor/correct-document.js +0 -225
  418. package/dist/editor/delete-backward.js +0 -64
  419. package/dist/editor/delete-forward.js +0 -11
  420. package/dist/editor/delete-fragment.js +0 -40
  421. package/dist/editor/edges.js +0 -5
  422. package/dist/editor/element-read-only.js +0 -35
  423. package/dist/editor/end.d.ts +0 -7
  424. package/dist/editor/end.js +0 -5
  425. package/dist/editor/exit-break.js +0 -51
  426. package/dist/editor/first.js +0 -8
  427. package/dist/editor/get-void.js +0 -9
  428. package/dist/editor/has-blocks.js +0 -6
  429. package/dist/editor/has-inlines.js +0 -6
  430. package/dist/editor/has-path.js +0 -5
  431. package/dist/editor/has-texts.js +0 -5
  432. package/dist/editor/insert-break.js +0 -77
  433. package/dist/editor/insert-default-child.js +0 -55
  434. package/dist/editor/insert-soft-break.js +0 -14
  435. package/dist/editor/insert-text.js +0 -83
  436. package/dist/editor/is-block.js +0 -5
  437. package/dist/editor/is-edge.js +0 -5
  438. package/dist/editor/is-editor.js +0 -13
  439. package/dist/editor/is-empty.js +0 -6
  440. package/dist/editor/is-end.js +0 -9
  441. package/dist/editor/is-start.js +0 -9
  442. package/dist/editor/last.js +0 -20
  443. package/dist/editor/leaf.js +0 -9
  444. package/dist/editor/levels.js +0 -21
  445. package/dist/editor/next.js +0 -46
  446. package/dist/editor/node.js +0 -9
  447. package/dist/editor/nodes.js +0 -106
  448. package/dist/editor/parent.js +0 -14
  449. package/dist/editor/path.js +0 -26
  450. package/dist/editor/point.js +0 -52
  451. package/dist/editor/positions.js +0 -322
  452. package/dist/editor/previous.js +0 -48
  453. package/dist/editor/project-range.js +0 -6
  454. package/dist/editor/range.js +0 -12
  455. package/dist/editor/remove-mark.js +0 -65
  456. package/dist/editor/should-merge-nodes-remove-prev-node.js +0 -11
  457. package/dist/editor/string.js +0 -35
  458. package/dist/editor/toggle-mark.js +0 -71
  459. package/dist/editor/unhang-range.js +0 -71
  460. package/dist/editor-runtime-view.d.ts +0 -33
  461. package/dist/editor-runtime-view.js +0 -788
  462. package/dist/history/history-carets.js +0 -127
  463. package/dist/history/history-character-map.js +0 -425
  464. package/dist/history/history-codec.js +0 -176
  465. package/dist/history/history-merge-policy.js +0 -164
  466. package/dist/history/history-plugin.d.ts +0 -71
  467. package/dist/history/history-plugin.js +0 -814
  468. package/dist/history/history-replay.js +0 -799
  469. package/dist/history/history-selection.js +0 -75
  470. package/dist/history/history-state.js +0 -1287
  471. package/dist/history/history.d.ts +0 -112
  472. package/dist/history/history.js +0 -29
  473. package/dist/hyperscript/creators.d.ts +0 -51
  474. package/dist/hyperscript/hyperscript.d.ts +0 -36
  475. package/dist/hyperscript/hyperscript.js +0 -66
  476. package/dist/hyperscript/tokens.d.ts +0 -31
  477. package/dist/hyperscript/tokens.js +0 -63
  478. package/dist/interfaces/decoration.d.ts +0 -35
  479. package/dist/interfaces/editor.d.ts +0 -2783
  480. package/dist/interfaces/editor.js +0 -348
  481. package/dist/interfaces/element.d.ts +0 -66
  482. package/dist/interfaces/element.js +0 -34
  483. package/dist/interfaces/index.d.ts +0 -13
  484. package/dist/interfaces/json.d.ts +0 -7
  485. package/dist/interfaces/location.d.ts +0 -50
  486. package/dist/interfaces/location.js +0 -26
  487. package/dist/interfaces/node.d.ts +0 -306
  488. package/dist/interfaces/node.js +0 -339
  489. package/dist/interfaces/path.d.ts +0 -118
  490. package/dist/interfaces/path.js +0 -116
  491. package/dist/interfaces/point.d.ts +0 -45
  492. package/dist/interfaces/point.js +0 -32
  493. package/dist/interfaces/range.d.ts +0 -80
  494. package/dist/interfaces/range.js +0 -85
  495. package/dist/interfaces/schema-validation.d.ts +0 -33
  496. package/dist/interfaces/schema.d.ts +0 -870
  497. package/dist/interfaces/selection.d.ts +0 -61
  498. package/dist/interfaces/selection.js +0 -106
  499. package/dist/interfaces/text.d.ts +0 -68
  500. package/dist/interfaces/text.js +0 -52
  501. package/dist/interfaces/transforms/node.d.ts +0 -222
  502. package/dist/interfaces/transforms/selection.d.ts +0 -48
  503. package/dist/interfaces/transforms/text.d.ts +0 -58
  504. package/dist/internal/browser-protocol.d.ts +0 -5
  505. package/dist/internal/document-range.d.ts +0 -9
  506. package/dist/internal/document-range.js +0 -31
  507. package/dist/internal/editor-options.d.ts +0 -37
  508. package/dist/internal/editor-options.js +0 -36
  509. package/dist/internal/fail-invariant.d.ts +0 -4
  510. package/dist/internal/fail-invariant.js +0 -6
  511. package/dist/internal/get-defined.js +0 -7
  512. package/dist/internal/law-check.js +0 -7
  513. package/dist/internal/range-text-marks.js +0 -31
  514. package/dist/internal/root-location.d.ts +0 -23
  515. package/dist/internal/root-location.js +0 -86
  516. package/dist/internal/text-run.d.ts +0 -13
  517. package/dist/internal/text-run.js +0 -44
  518. package/dist/internal/view/annotation-store-metrics.d.ts +0 -11
  519. package/dist/internal/view/view-source.d.ts +0 -20
  520. package/dist/pagination/page-composition.internal.js +0 -313
  521. package/dist/pagination/page-geometry.internal.js +0 -99
  522. package/dist/pagination/page-layout-engine-invalidation.internal.js +0 -20
  523. package/dist/pagination/page-mount-plan.js +0 -84
  524. package/dist/pagination/paged-view-lines.js +0 -163
  525. package/dist/range-projection.d.ts +0 -7
  526. package/dist/range-projection.js +0 -50
  527. package/dist/react/components/dom-coverage-boundary.d.ts +0 -14
  528. package/dist/react/components/dom-coverage-boundary.js +0 -143
  529. package/dist/react/components/editable-descendant-binding.js +0 -70
  530. package/dist/react/components/editable-dom-commit-fence.js +0 -107
  531. package/dist/react/components/editable-element-placement.d.ts +0 -2
  532. package/dist/react/components/editable-element-placement.js +0 -117
  533. package/dist/react/components/editable-external-text.js +0 -47
  534. package/dist/react/components/editable-node-equality.js +0 -25
  535. package/dist/react/components/editable-rendered-element.d.ts +0 -3
  536. package/dist/react/components/editable-rendered-element.js +0 -61
  537. package/dist/react/components/editable-text-blocks.d.ts +0 -192
  538. package/dist/react/components/editable-text-blocks.js +0 -896
  539. package/dist/react/components/editable-text-containers.d.ts +0 -3
  540. package/dist/react/components/editable-text-containers.js +0 -28
  541. package/dist/react/components/editable-text-flow.js +0 -1039
  542. package/dist/react/components/editable-text-pieces.d.ts +0 -7
  543. package/dist/react/components/editable-text-pieces.js +0 -193
  544. package/dist/react/components/editable-text.d.ts +0 -80
  545. package/dist/react/components/editable-text.js +0 -322
  546. package/dist/react/components/editable.d.ts +0 -35
  547. package/dist/react/components/editable.js +0 -406
  548. package/dist/react/components/editor-announcement-live-region.js +0 -113
  549. package/dist/react/components/plite-element.d.ts +0 -18
  550. package/dist/react/components/plite-element.js +0 -54
  551. package/dist/react/components/plite-leaf.d.ts +0 -18
  552. package/dist/react/components/plite-leaf.js +0 -21
  553. package/dist/react/components/plite-placeholder.d.ts +0 -19
  554. package/dist/react/components/plite-placeholder.js +0 -39
  555. package/dist/react/components/plite-spacer.js +0 -14
  556. package/dist/react/components/plite-text.d.ts +0 -23
  557. package/dist/react/components/plite-text.js +0 -32
  558. package/dist/react/components/plite-void-shell.js +0 -49
  559. package/dist/react/components/plite.d.ts +0 -45
  560. package/dist/react/components/plite.js +0 -297
  561. package/dist/react/components/text-string.js +0 -18
  562. package/dist/react/components/windowed-editable.internal.js +0 -51
  563. package/dist/react/components/zero-width-string.js +0 -26
  564. package/dist/react/context.js +0 -11
  565. package/dist/react/decoration-context.d.ts +0 -2
  566. package/dist/react/decoration-context.js +0 -22
  567. package/dist/react/decoration-source.d.ts +0 -11
  568. package/dist/react/decoration-source.js +0 -1030
  569. package/dist/react/dom-text-sync.d.ts +0 -24
  570. package/dist/react/dom-text-sync.js +0 -48
  571. package/dist/react/editable/android-composition.d.ts +0 -3
  572. package/dist/react/editable/android-composition.js +0 -496
  573. package/dist/react/editable/browser-handle.js +0 -515
  574. package/dist/react/editable/caret-engine.js +0 -681
  575. package/dist/react/editable/clipboard-input-strategy.js +0 -632
  576. package/dist/react/editable/composition-lease.d.ts +0 -3
  577. package/dist/react/editable/composition-lease.js +0 -350
  578. package/dist/react/editable/composition-state.js +0 -716
  579. package/dist/react/editable/content-root-boundaries.js +0 -79
  580. package/dist/react/editable/content-root-coordinate-navigation.js +0 -28
  581. package/dist/react/editable/content-root-navigation-actions.js +0 -190
  582. package/dist/react/editable/content-root-navigation.js +0 -819
  583. package/dist/react/editable/content-root-owner-target.js +0 -36
  584. package/dist/react/editable/content-root-owners.js +0 -191
  585. package/dist/react/editable/content-root-vertical-geometry.js +0 -60
  586. package/dist/react/editable/decoration-repair-bridge.js +0 -29
  587. package/dist/react/editable/dom-coverage-selection.js +0 -158
  588. package/dist/react/editable/dom-coverage-vertical-selection.js +0 -446
  589. package/dist/react/editable/dom-input-event.js +0 -14
  590. package/dist/react/editable/dom-repair-queue.d.ts +0 -7
  591. package/dist/react/editable/dom-repair-queue.js +0 -543
  592. package/dist/react/editable/dom-repair-text.js +0 -47
  593. package/dist/react/editable/editable-command-types.d.ts +0 -1
  594. package/dist/react/editable/editable-dom-runtime.d.ts +0 -66
  595. package/dist/react/editable/editable-dom-runtime.js +0 -1022
  596. package/dist/react/editable/editing-epoch-adapter.js +0 -46
  597. package/dist/react/editable/editing-kernel.d.ts +0 -7
  598. package/dist/react/editable/editing-kernel.js +0 -593
  599. package/dist/react/editable/external-text-binding.js +0 -43
  600. package/dist/react/editable/external-text-runtime.d.ts +0 -5
  601. package/dist/react/editable/external-text-runtime.js +0 -851
  602. package/dist/react/editable/history-focus.js +0 -71
  603. package/dist/react/editable/history-keyboard.d.ts +0 -4
  604. package/dist/react/editable/history-keyboard.js +0 -9
  605. package/dist/react/editable/input-controller.d.ts +0 -7
  606. package/dist/react/editable/input-controller.js +0 -175
  607. package/dist/react/editable/input-history.js +0 -21
  608. package/dist/react/editable/input-router.js +0 -742
  609. package/dist/react/editable/input-state.d.ts +0 -18
  610. package/dist/react/editable/input-state.js +0 -330
  611. package/dist/react/editable/input-target.js +0 -30
  612. package/dist/react/editable/install-browser-handle.d.ts +0 -12
  613. package/dist/react/editable/install-browser-handle.js +0 -18
  614. package/dist/react/editable/interaction-owner.js +0 -88
  615. package/dist/react/editable/keyboard-input-strategy.js +0 -730
  616. package/dist/react/editable/line-boundary.js +0 -37
  617. package/dist/react/editable/model-input-strategy.d.ts +0 -9
  618. package/dist/react/editable/model-input-strategy.js +0 -242
  619. package/dist/react/editable/model-selection-dom-preference.js +0 -11
  620. package/dist/react/editable/mutation-block-editing.js +0 -48
  621. package/dist/react/editable/mutation-controller.d.ts +0 -32
  622. package/dist/react/editable/mutation-controller.js +0 -632
  623. package/dist/react/editable/mutation-full-block-editing.d.ts +0 -2
  624. package/dist/react/editable/mutation-full-block-editing.js +0 -44
  625. package/dist/react/editable/mutation-history.d.ts +0 -3
  626. package/dist/react/editable/mutation-history.js +0 -146
  627. package/dist/react/editable/native-input-strategy.js +0 -86
  628. package/dist/react/editable/native-text-input-delta.js +0 -40
  629. package/dist/react/editable/placed-drag.js +0 -177
  630. package/dist/react/editable/plite-string-coordinate-placement.js +0 -46
  631. package/dist/react/editable/press-fence.d.ts +0 -2
  632. package/dist/react/editable/press-fence.js +0 -70
  633. package/dist/react/editable/projected-clipboard.js +0 -123
  634. package/dist/react/editable/projected-native-affordance.js +0 -30
  635. package/dist/react/editable/projected-selection-target.js +0 -13
  636. package/dist/react/editable/render-contract-monitor.d.ts +0 -3
  637. package/dist/react/editable/render-contract-monitor.js +0 -152
  638. package/dist/react/editable/root-interaction-controller.js +0 -1400
  639. package/dist/react/editable/root-interaction-dom-selection-replay.js +0 -40
  640. package/dist/react/editable/root-interaction-resolver.js +0 -116
  641. package/dist/react/editable/root-selector-sources.js +0 -90
  642. package/dist/react/editable/runtime-android-engine.js +0 -40
  643. package/dist/react/editable/runtime-before-input-events.js +0 -671
  644. package/dist/react/editable/runtime-browser-handle-events.js +0 -40
  645. package/dist/react/editable/runtime-clipboard-events.js +0 -169
  646. package/dist/react/editable/runtime-composition-events.js +0 -163
  647. package/dist/react/editable/runtime-drag-events.js +0 -136
  648. package/dist/react/editable/runtime-editor-api.d.ts +0 -20
  649. package/dist/react/editable/runtime-editor-api.js +0 -21
  650. package/dist/react/editable/runtime-event-engine.js +0 -213
  651. package/dist/react/editable/runtime-focus-mouse-events.js +0 -264
  652. package/dist/react/editable/runtime-input-events.js +0 -166
  653. package/dist/react/editable/runtime-kernel-trace.js +0 -185
  654. package/dist/react/editable/runtime-keyboard-events.js +0 -333
  655. package/dist/react/editable/runtime-live-state.js +0 -44
  656. package/dist/react/editable/runtime-mutation-state.js +0 -11
  657. package/dist/react/editable/runtime-repair-engine.js +0 -118
  658. package/dist/react/editable/runtime-root-engine.js +0 -244
  659. package/dist/react/editable/runtime-root-lifecycle.js +0 -118
  660. package/dist/react/editable/runtime-root-selection-export.js +0 -38
  661. package/dist/react/editable/runtime-root-selection-import.js +0 -54
  662. package/dist/react/editable/runtime-root-state.js +0 -62
  663. package/dist/react/editable/runtime-selection-engine.js +0 -260
  664. package/dist/react/editable/runtime-selection-state.js +0 -12
  665. package/dist/react/editable/runtime-target-bridge.js +0 -29
  666. package/dist/react/editable/schema-runtime-invalidation.js +0 -26
  667. package/dist/react/editable/selection-change-listener.js +0 -99
  668. package/dist/react/editable/selection-claim.d.ts +0 -3
  669. package/dist/react/editable/selection-claim.js +0 -398
  670. package/dist/react/editable/selection-controller.d.ts +0 -8
  671. package/dist/react/editable/selection-controller.js +0 -693
  672. package/dist/react/editable/selection-dom-range.js +0 -84
  673. package/dist/react/editable/selection-projected-dom.js +0 -156
  674. package/dist/react/editable/selection-reconciler.js +0 -630
  675. package/dist/react/editable/selection-runtime.js +0 -89
  676. package/dist/react/editable/selection-side-effect-policy.js +0 -20
  677. package/dist/react/editable/selection-triple-click.js +0 -48
  678. package/dist/react/editable/selection-void-target.js +0 -172
  679. package/dist/react/editable/set-root-endpoints.js +0 -75
  680. package/dist/react/editable/soft-line-end-delete.js +0 -106
  681. package/dist/react/editable/text-direction.js +0 -82
  682. package/dist/react/editable/typed-text.d.ts +0 -17
  683. package/dist/react/editable/typed-text.js +0 -89
  684. package/dist/react/editable/unread-press.d.ts +0 -2
  685. package/dist/react/editable/unread-press.js +0 -86
  686. package/dist/react/editable/view-caret-restore.js +0 -128
  687. package/dist/react/editable/view-lines.d.ts +0 -7
  688. package/dist/react/editable/view-lines.js +0 -166
  689. package/dist/react/external-text.d.ts +0 -131
  690. package/dist/react/history-step-views.d.ts +0 -4
  691. package/dist/react/history-step-views.js +0 -119
  692. package/dist/react/hooks/android-input-manager/android-input-manager.d.ts +0 -7
  693. package/dist/react/hooks/android-input-manager/android-input-manager.js +0 -716
  694. package/dist/react/hooks/android-input-manager/use-android-input-manager.js +0 -53
  695. package/dist/react/hooks/focus-plite-editable.js +0 -116
  696. package/dist/react/hooks/use-claim-editable-dom-commit.d.ts +0 -12
  697. package/dist/react/hooks/use-claim-editable-dom-commit.js +0 -31
  698. package/dist/react/hooks/use-drop-indicator.d.ts +0 -9
  699. package/dist/react/hooks/use-drop-indicator.js +0 -14
  700. package/dist/react/hooks/use-editable-clip.d.ts +0 -18
  701. package/dist/react/hooks/use-editable-clip.js +0 -31
  702. package/dist/react/hooks/use-editable-layout-pass.js +0 -53
  703. package/dist/react/hooks/use-editor-composing.d.ts +0 -7
  704. package/dist/react/hooks/use-editor-composing.js +0 -12
  705. package/dist/react/hooks/use-editor-context.d.ts +0 -10
  706. package/dist/react/hooks/use-editor-context.js +0 -18
  707. package/dist/react/hooks/use-editor-dom-scope.d.ts +0 -27
  708. package/dist/react/hooks/use-editor-dom-scope.js +0 -23
  709. package/dist/react/hooks/use-editor-focused.d.ts +0 -7
  710. package/dist/react/hooks/use-editor-focused.js +0 -12
  711. package/dist/react/hooks/use-editor-read-only.d.ts +0 -25
  712. package/dist/react/hooks/use-editor-read-only.js +0 -19
  713. package/dist/react/hooks/use-editor-runtime-state.d.ts +0 -18
  714. package/dist/react/hooks/use-editor-runtime-state.js +0 -38
  715. package/dist/react/hooks/use-editor-selection.d.ts +0 -10
  716. package/dist/react/hooks/use-editor-selection.js +0 -13
  717. package/dist/react/hooks/use-editor-selector.d.ts +0 -38
  718. package/dist/react/hooks/use-editor-selector.js +0 -265
  719. package/dist/react/hooks/use-editor-view-state.d.ts +0 -16
  720. package/dist/react/hooks/use-editor-view-state.js +0 -20
  721. package/dist/react/hooks/use-editor.d.ts +0 -26
  722. package/dist/react/hooks/use-editor.js +0 -27
  723. package/dist/react/hooks/use-element-path.d.ts +0 -7
  724. package/dist/react/hooks/use-element-path.js +0 -36
  725. package/dist/react/hooks/use-element-selected.d.ts +0 -26
  726. package/dist/react/hooks/use-element-selected.js +0 -91
  727. package/dist/react/hooks/use-element.d.ts +0 -13
  728. package/dist/react/hooks/use-element.js +0 -17
  729. package/dist/react/hooks/use-generic-selector.js +0 -91
  730. package/dist/react/hooks/use-hydrated.js +0 -12
  731. package/dist/react/hooks/use-isomorphic-layout-effect.js +0 -9
  732. package/dist/react/hooks/use-node-selector.d.ts +0 -40
  733. package/dist/react/hooks/use-node-selector.js +0 -102
  734. package/dist/react/hooks/use-plite-annotation-store.d.ts +0 -21
  735. package/dist/react/hooks/use-plite-annotation-store.js +0 -61
  736. package/dist/react/hooks/use-plite-annotations.d.ts +0 -9
  737. package/dist/react/hooks/use-plite-annotations.js +0 -16
  738. package/dist/react/hooks/use-plite-child-root.d.ts +0 -14
  739. package/dist/react/hooks/use-plite-child-root.js +0 -38
  740. package/dist/react/hooks/use-plite-content-root.d.ts +0 -21
  741. package/dist/react/hooks/use-plite-content-root.js +0 -26
  742. package/dist/react/hooks/use-plite-history.d.ts +0 -43
  743. package/dist/react/hooks/use-plite-history.js +0 -137
  744. package/dist/react/hooks/use-plite-node-ref.js +0 -513
  745. package/dist/react/hooks/use-plite-root-chrome.d.ts +0 -34
  746. package/dist/react/hooks/use-plite-root-chrome.js +0 -98
  747. package/dist/react/hooks/use-plite-runtime.d.ts +0 -86
  748. package/dist/react/hooks/use-plite-runtime.js +0 -433
  749. package/dist/react/hooks/use-runtime-focus-state.js +0 -37
  750. package/dist/react/hooks/use-selection-geometry.d.ts +0 -12
  751. package/dist/react/hooks/use-selection-geometry.js +0 -39
  752. package/dist/react/hooks/use-selection-view.d.ts +0 -14
  753. package/dist/react/hooks/use-selection-view.js +0 -14
  754. package/dist/react/hooks/use-state-field.d.ts +0 -26
  755. package/dist/react/hooks/use-state-field.js +0 -38
  756. package/dist/react/inactive-selection.js +0 -175
  757. package/dist/react/plugin/react-editor.d.ts +0 -20
  758. package/dist/react/plugin/react-editor.js +0 -6
  759. package/dist/react/plugin/with-react.d.ts +0 -108
  760. package/dist/react/plugin/with-react.js +0 -58
  761. package/dist/react/render-profiler.js +0 -20
  762. package/dist/react/root-key.js +0 -12
  763. package/dist/react/shell-runtime.js +0 -29
  764. package/dist/react/update-policy.d.ts +0 -10
  765. package/dist/react/update-policy.js +0 -15
  766. package/dist/react/utils/environment.js +0 -5
  767. package/dist/react/view-boundary-graph-core.d.ts +0 -1
  768. package/dist/react/view-boundary-graph-core.js +0 -208
  769. package/dist/react/view-boundary-graph.js +0 -105
  770. package/dist/react/view-selection-decoration.js +0 -97
  771. package/dist/react/view-selection.js +0 -184
  772. package/dist/react/viewport-boundary.js +0 -45
  773. package/dist/react/viewport-commands.d.ts +0 -1
  774. package/dist/react/viewport-commands.js +0 -17
  775. package/dist/react/viewport-plan.d.ts +0 -2
  776. package/dist/react/viewport-plan.js +0 -77
  777. package/dist/react/virtualized/use-virtualized-root-plan.js +0 -148
  778. package/dist/testing/createDataTransfer.d.ts +0 -4
  779. package/dist/testing/createDataTransfer.js +0 -13
  780. package/dist/testing/jsx.d.ts +0 -181
  781. package/dist/testing/jsx.js +0 -82
  782. package/dist/transforms-node/insert-nodes.js +0 -143
  783. package/dist/transforms-node/lift-nodes.js +0 -117
  784. package/dist/transforms-node/merge-nodes.js +0 -180
  785. package/dist/transforms-node/move-nodes.js +0 -58
  786. package/dist/transforms-node/remove-nodes.js +0 -86
  787. package/dist/transforms-node/replace-children.js +0 -117
  788. package/dist/transforms-node/set-nodes.js +0 -188
  789. package/dist/transforms-node/split-nodes.js +0 -258
  790. package/dist/transforms-node/unset-nodes.js +0 -10
  791. package/dist/transforms-node/unwrap-nodes.js +0 -182
  792. package/dist/transforms-node/wrap-nodes.js +0 -250
  793. package/dist/transforms-selection/collapse.js +0 -20
  794. package/dist/transforms-selection/deselect.js +0 -8
  795. package/dist/transforms-selection/move.js +0 -35
  796. package/dist/transforms-selection/select.js +0 -59
  797. package/dist/transforms-selection/set-point.js +0 -32
  798. package/dist/transforms-selection/set-selection.js +0 -52
  799. package/dist/transforms-text/delete-text-collapsed-path-targets.js +0 -102
  800. package/dist/transforms-text/delete-text-grid.js +0 -402
  801. package/dist/transforms-text/delete-text-inline-points.js +0 -82
  802. package/dist/transforms-text/delete-text-plan.js +0 -55
  803. package/dist/transforms-text/delete-text-removal.js +0 -153
  804. package/dist/transforms-text/delete-text-structural-cleanup.js +0 -130
  805. package/dist/transforms-text/delete-text-whole-blocks.js +0 -70
  806. package/dist/transforms-text/delete-text.js +0 -804
  807. package/dist/transforms-text/full-document-range.js +0 -12
  808. package/dist/transforms-text/insert-text.js +0 -314
  809. package/dist/types/types.d.ts +0 -13
  810. package/dist/utils/format-debug-value.d.ts +0 -8
  811. package/dist/utils/format-debug-value.js +0 -31
  812. package/dist/utils/get-default-insert-location.js +0 -19
  813. package/dist/utils/is-object.d.ts +0 -4
  814. package/dist/utils/is-object.js +0 -4
  815. package/dist/utils/match-path.js +0 -8
  816. package/dist/utils/node-keys.d.ts +0 -15
  817. package/dist/utils/node-keys.js +0 -179
  818. package/dist/utils/node-match.js +0 -9
  819. package/dist/utils/string.js +0 -283
  820. package/dist/yjs/core/addresses.js +0 -98
  821. package/dist/yjs/core/ancestor-properties.js +0 -56
  822. package/dist/yjs/core/attributes.js +0 -21
  823. package/dist/yjs/core/awareness-adapter.d.ts +0 -5
  824. package/dist/yjs/core/awareness-adapter.js +0 -399
  825. package/dist/yjs/core/awareness-relative-selection.js +0 -22
  826. package/dist/yjs/core/awareness.js +0 -25
  827. package/dist/yjs/core/binding.d.ts +0 -3
  828. package/dist/yjs/core/binding.js +0 -128
  829. package/dist/yjs/core/boundaries.js +0 -453
  830. package/dist/yjs/core/canonical-split.js +0 -130
  831. package/dist/yjs/core/change-bridge.js +0 -124
  832. package/dist/yjs/core/change-regions.js +0 -119
  833. package/dist/yjs/core/controller-registry.js +0 -70
  834. package/dist/yjs/core/controller.d.ts +0 -6
  835. package/dist/yjs/core/controller.js +0 -1282
  836. package/dist/yjs/core/document.js +0 -1499
  837. package/dist/yjs/core/editor-adapter.d.ts +0 -18
  838. package/dist/yjs/core/editor-adapter.js +0 -145
  839. package/dist/yjs/core/editor-only-roots.js +0 -53
  840. package/dist/yjs/core/editor-types.d.ts +0 -1
  841. package/dist/yjs/core/enclosures.js +0 -410
  842. package/dist/yjs/core/event-change-bridge.js +0 -3642
  843. package/dist/yjs/core/index.d.ts +0 -4
  844. package/dist/yjs/core/joined-lines.js +0 -81
  845. package/dist/yjs/core/joins.js +0 -587
  846. package/dist/yjs/core/json-equality.js +0 -31
  847. package/dist/yjs/core/keys.js +0 -29
  848. package/dist/yjs/core/letter-scripts.js +0 -449
  849. package/dist/yjs/core/new-letters.js +0 -300
  850. package/dist/yjs/core/path.js +0 -25
  851. package/dist/yjs/core/plugin.js +0 -206
  852. package/dist/yjs/core/record.js +0 -4
  853. package/dist/yjs/core/replacement.js +0 -165
  854. package/dist/yjs/core/retraction.js +0 -132
  855. package/dist/yjs/core/root-owners.js +0 -110
  856. package/dist/yjs/core/root-projection-index.js +0 -428
  857. package/dist/yjs/core/schema-metadata.js +0 -88
  858. package/dist/yjs/core/selection.js +0 -34
  859. package/dist/yjs/core/set-valued-attributes.js +0 -57
  860. package/dist/yjs/core/shared-effect-log.d.ts +0 -4
  861. package/dist/yjs/core/shared-effect-log.js +0 -674
  862. package/dist/yjs/core/text-runs.js +0 -1596
  863. package/dist/yjs/core/types.d.ts +0 -76
  864. package/dist/yjs/react/useYjs.d.ts +0 -25
  865. package/dist/yjs/react/useYjs.js +0 -85
@@ -1,3544 +0,0 @@
1
- import { getDefined } from "../../internal/get-defined.js";
2
- import { countCoreWork } from "../work.js";
3
- import { cloneFrozen, cloneJson, isRecord, jsonEqual } from "./json.js";
4
- import { assertEditorJsonValue } from "../value-codec.js";
5
- import { DOCUMENT_SLICE_PREPARED_NODES, PreparedTokenSlice, claimPreparedNodeSlice, closeToken, commonPrefixLength, commonSuffixLength, getDocumentSliceNodeKeys, isElementNode, isTextNode, nodeProps, openToken, pathKey, tokenLength, tokensEqual } from "./tokens.js";
6
- import { assertNodePropertyKey, canonicalJsonKey, clonePropertyModification, normalizeSetValues, transformEarlierPropertyModifications, transformPathAfterRemove, unsafeNodePropertyKeys } from "./transform.js";
7
- import { DocumentIndex, decodeNodes } from "./document-index.js";
8
- import { profileCoreDuration } from "../profiling.js";
9
- import { convergedResult, editsInMovedLine, liftOf, rebaseOverJoins, rebaseOverLift } from "./join.js";
10
- import { enclosureApplied, rebaseOverPieces } from "./enclosure.js";
11
- import { markReadBack } from "./read-back.js";
12
- import { crossed, wrapFidelity } from "./wrap-fidelity.js";
13
- //#region src/core/change/root-change.ts
14
- const normalizePropertyDelta = (delta) => {
15
- assertEditorJsonValue(delta, "Node property delta");
16
- if (!isRecord(delta)) throw new Error("Invalid node property delta.");
17
- const modifications = [];
18
- const keyKinds = /* @__PURE__ */ new Map();
19
- const reserve = (key, kind) => {
20
- assertNodePropertyKey(key);
21
- const existing = keyKinds.get(key);
22
- if (existing && (existing === "scalar" || kind === "scalar")) throw new Error(`Node property delta repeats key ${key}.`);
23
- keyKinds.set(key, kind);
24
- };
25
- if (delta.unset !== void 0) {
26
- if (!Array.isArray(delta.unset)) throw new Error("Invalid node property delta.");
27
- for (const key of [...delta.unset].sort((left, right) => left < right ? -1 : left > right ? 1 : 0)) {
28
- reserve(key, "scalar");
29
- modifications.push(Object.freeze({
30
- key,
31
- type: "unset"
32
- }));
33
- }
34
- }
35
- if (delta.set !== void 0) {
36
- if (!isRecord(delta.set)) throw new Error("Invalid node property delta.");
37
- for (const key of Object.keys(delta.set).sort()) {
38
- reserve(key, "scalar");
39
- modifications.push(clonePropertyModification({
40
- key,
41
- type: "set",
42
- value: delta.set[key]
43
- }));
44
- }
45
- }
46
- for (const type of ["remove", "add"]) {
47
- const entries = delta[type];
48
- if (entries === void 0) continue;
49
- if (!isRecord(entries)) throw new Error("Invalid node property delta.");
50
- for (const key of Object.keys(entries).sort()) {
51
- const values = entries[key];
52
- reserve(key, "set");
53
- if (!Array.isArray(values)) throw new Error("Invalid node property delta.");
54
- const normalized = normalizeSetValues(values);
55
- if (normalized.length > 0) modifications.push(Object.freeze({
56
- key,
57
- type,
58
- values: normalized
59
- }));
60
- }
61
- }
62
- return Object.freeze(modifications);
63
- };
64
- const applyPropertyModifications = (props, modifications) => {
65
- const next = { ...props };
66
- for (const modification of modifications) {
67
- const { key } = modification;
68
- if (modification.type === "set") {
69
- next[key] = cloneFrozen(modification.value);
70
- continue;
71
- }
72
- if (modification.type === "unset") {
73
- delete next[key];
74
- continue;
75
- }
76
- const current = Object.hasOwn(next, key) ? next[key] : void 0;
77
- if (current !== void 0 && !Array.isArray(current)) throw new Error(`Set-valued node property ${key} is not an array.`);
78
- const currentValues = normalizeSetValues(current ?? []);
79
- const values = modification.type === "add" ? normalizeSetValues([...currentValues, ...modification.values]) : normalizeSetValues(currentValues.filter((value) => !modification.values.some((item) => jsonEqual(item, value))));
80
- if (values.length === 0) delete next[key];
81
- else next[key] = values;
82
- }
83
- return cloneFrozen(next);
84
- };
85
- const semanticPropertyModifications = (before, after, isSetValued) => {
86
- const modifications = [];
87
- for (const key of [.../* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(after)])].filter((innerKey) => !unsafeNodePropertyKeys.has(innerKey)).sort()) {
88
- if (!isSetValued(key)) {
89
- if (!Object.hasOwn(after, key)) modifications.push(Object.freeze({
90
- key,
91
- type: "unset"
92
- }));
93
- else if (!Object.hasOwn(before, key) || !jsonEqual(before[key], after[key])) modifications.push(clonePropertyModification({
94
- key,
95
- type: "set",
96
- value: after[key]
97
- }));
98
- continue;
99
- }
100
- const beforeValue = Object.hasOwn(before, key) ? before[key] : void 0;
101
- const afterValue = Object.hasOwn(after, key) ? after[key] : void 0;
102
- if (beforeValue !== void 0 && !Array.isArray(beforeValue) || afterValue !== void 0 && !Array.isArray(afterValue)) throw new Error(`Set-valued node property ${key} is not an array.`);
103
- const previous = normalizeSetValues(beforeValue ?? []);
104
- const next = normalizeSetValues(afterValue ?? []);
105
- const removed = previous.filter((value) => !next.some((item) => jsonEqual(item, value)));
106
- const added = next.filter((value) => !previous.some((item) => jsonEqual(item, value)));
107
- if (removed.length > 0) modifications.push(Object.freeze({
108
- key,
109
- type: "remove",
110
- values: removed
111
- }));
112
- if (added.length > 0) modifications.push(Object.freeze({
113
- key,
114
- type: "add",
115
- values: added
116
- }));
117
- }
118
- return Object.freeze(modifications);
119
- };
120
- const isEmptyList = (value) => Array.isArray(value) && value.length === 0;
121
- const betweenPropertyModifications = (before, after, isSetValued, emptySetsAsValues = false) => semanticPropertyModifications(before, after, (key) => isSetValued(key) && !(emptySetsAsValues && (isEmptyList(before[key]) || isEmptyList(after[key]))));
122
- const invertPropertyModifications = (props, modifications) => {
123
- let current = cloneFrozen(props);
124
- const inverse = [];
125
- for (const modification of modifications) {
126
- const { key } = modification;
127
- let inverted;
128
- if (modification.type === "set" || modification.type === "unset") inverted = Object.hasOwn(current, key) ? clonePropertyModification({
129
- key,
130
- type: "set",
131
- value: current[key]
132
- }) : modification.type === "set" ? Object.freeze({
133
- key,
134
- type: "unset"
135
- }) : null;
136
- else {
137
- const currentValue = Object.hasOwn(current, key) ? current[key] : void 0;
138
- if (currentValue !== void 0 && !Array.isArray(currentValue)) throw new Error(`Set-valued node property ${key} is not an array.`);
139
- const currentValues = normalizeSetValues(currentValue ?? []);
140
- const affected = modification.type === "add" ? modification.values.filter((value) => !currentValues.some((item) => jsonEqual(item, value))) : currentValues.filter((value) => modification.values.some((item) => jsonEqual(item, value)));
141
- inverted = affected.length === 0 ? null : Object.freeze({
142
- key,
143
- type: modification.type === "add" ? "remove" : "add",
144
- values: normalizeSetValues(affected)
145
- });
146
- }
147
- current = applyPropertyModifications(current, [modification]);
148
- if (inverted) inverse.unshift(inverted);
149
- }
150
- return Object.freeze(inverse);
151
- };
152
- const propertyModificationToJSON = (modification) => modification.type === "set" ? {
153
- key: modification.key,
154
- type: modification.type,
155
- value: cloneJson(modification.value)
156
- } : modification.type === "unset" ? {
157
- key: modification.key,
158
- type: modification.type
159
- } : {
160
- key: modification.key,
161
- type: modification.type,
162
- values: cloneJson(modification.values)
163
- };
164
- const propertyModificationFromJSON = (value) => {
165
- if (!isRecord(value)) throw new Error("Invalid property delta JSON.");
166
- const { key, type } = value;
167
- assertNodePropertyKey(key);
168
- if (type === "unset") return Object.freeze({
169
- key,
170
- type
171
- });
172
- if (type === "set" && Object.hasOwn(value, "value")) return clonePropertyModification({
173
- key,
174
- type,
175
- value: value.value
176
- });
177
- if ((type === "add" || type === "remove") && Array.isArray(value.values)) {
178
- const values = normalizeSetValues(value.values);
179
- if (values.length === 0) throw new Error("Invalid property delta JSON.");
180
- return Object.freeze({
181
- key,
182
- type,
183
- values
184
- });
185
- }
186
- throw new Error("Invalid property delta JSON.");
187
- };
188
- const propertyModificationsFromJSON = (value) => {
189
- if (!isRecord(value) || value.version !== 1 || !Array.isArray(value.operations)) throw new Error("Invalid property delta JSON.");
190
- return Object.freeze(value.operations.map(propertyModificationFromJSON));
191
- };
192
- const propertyDeltaFromModifications = (modifications) => {
193
- const add = {};
194
- const remove = {};
195
- const set = {};
196
- const unset = [];
197
- for (const modification of modifications) if (modification.type === "set") set[modification.key] = modification.value;
198
- else if (modification.type === "unset") unset.push(modification.key);
199
- else (modification.type === "add" ? add : remove)[modification.key] = modification.values;
200
- return Object.freeze({
201
- ...Object.keys(add).length > 0 ? { add: Object.freeze(add) } : {},
202
- ...Object.keys(remove).length > 0 ? { remove: Object.freeze(remove) } : {},
203
- ...Object.keys(set).length > 0 ? { set: Object.freeze(set) } : {},
204
- ...unset.length > 0 ? { unset: Object.freeze(unset) } : {}
205
- });
206
- };
207
- const applyPropertyModificationsToSlice = (slice, modifications) => {
208
- let changed = false;
209
- const tokens = slice.tokens.map((token) => {
210
- if (token.kind !== "open") return token;
211
- changed = true;
212
- return openToken(token.nodeKind, applyPropertyModifications(token.props, modifications));
213
- });
214
- if (!changed) throw new Error("Node property delta does not target an open node token.");
215
- return PreparedTokenSlice.fromTokens(tokens);
216
- };
217
- const CHANGE_SET_APPLY_STATS = /* @__PURE__ */ new WeakMap();
218
- var SectionIterator = class {
219
- data;
220
- sections;
221
- index = 0;
222
- inserted = -3;
223
- length = 0;
224
- offset = 0;
225
- constructor(sections, data) {
226
- this.data = data;
227
- this.sections = sections;
228
- this.next();
229
- }
230
- get done() {
231
- return this.inserted === -3;
232
- }
233
- get keep() {
234
- return this.inserted === -1 || this.inserted === -2;
235
- }
236
- get outputLength() {
237
- return this.keep ? this.length : this.inserted;
238
- }
239
- /** The current section's index in the change's data. */
240
- get pair() {
241
- return this.index - 2 >> 1;
242
- }
243
- get slice() {
244
- return this.data[this.pair] ?? PreparedTokenSlice.empty;
245
- }
246
- get modifications() {
247
- return this.inserted === -2 ? this.data[this.pair] : null;
248
- }
249
- forward(length) {
250
- if (length === this.length) this.next();
251
- else {
252
- this.length -= length;
253
- this.offset += length;
254
- }
255
- }
256
- forwardOutput(length) {
257
- if (this.keep) this.forward(length);
258
- else if (length === this.inserted) this.next();
259
- else {
260
- this.inserted -= length;
261
- this.offset += length;
262
- }
263
- }
264
- next() {
265
- if (this.index < this.sections.length) {
266
- this.length = getDefined(this.sections[this.index]);
267
- this.inserted = getDefined(this.sections[this.index + 1]);
268
- this.index += 2;
269
- } else {
270
- this.length = 0;
271
- this.inserted = -3;
272
- }
273
- this.offset = 0;
274
- }
275
- slicePart(length) {
276
- return this.slice.slice(this.offset, length === void 0 ? void 0 : this.offset + length);
277
- }
278
- };
279
- const flushJoins = (data, joins) => {
280
- if (joins.length === 0) return;
281
- const filled = [data.at(-1) ?? PreparedTokenSlice.empty, ...joins].filter((slice) => slice.length > 0);
282
- data[data.length - 1] = filled.length > 1 ? PreparedTokenSlice.concat(filled) : filled[0] ?? PreparedTokenSlice.empty;
283
- joins.length = 0;
284
- };
285
- const addSection = (sections, data, length, inserted, value, forceJoin = false, joins) => {
286
- if (length === 0 && inserted <= 0) return;
287
- const last = sections.length - 2;
288
- if (last >= 0 && (inserted === -1 || inserted === 0) && sections[last + 1] === inserted) {
289
- sections[last] += length;
290
- return;
291
- }
292
- if (inserted >= 0 && (forceJoin || last >= 0 && length === 0 && sections[last] === 0)) {
293
- sections[last] += length;
294
- sections[last + 1] += inserted;
295
- const slice = value ?? PreparedTokenSlice.empty;
296
- if (joins) joins.push(slice);
297
- else data[data.length - 1] = (data.at(-1) ?? PreparedTokenSlice.empty).concat(slice);
298
- return;
299
- }
300
- if (joins) flushJoins(data, joins);
301
- sections.push(length, inserted);
302
- data.push(value);
303
- };
304
- const composeSections = (sectionsA, dataA, sectionsB, dataB) => {
305
- const sections = [];
306
- const data = [];
307
- const joins = [];
308
- const add = (length, inserted, value, forceJoin) => addSection(sections, data, length, inserted, value, forceJoin, joins);
309
- const a = new SectionIterator(sectionsA, dataA);
310
- const b = new SectionIterator(sectionsB, dataB);
311
- let open = false;
312
- for (;;) {
313
- if (a.done && b.done) {
314
- flushJoins(data, joins);
315
- return {
316
- data,
317
- sections
318
- };
319
- }
320
- if (a.inserted === 0) {
321
- add(a.length, 0, a.slice, open);
322
- a.next();
323
- continue;
324
- }
325
- if (b.length === 0 && !b.done) {
326
- add(0, b.inserted, b.slice, open);
327
- b.next();
328
- continue;
329
- }
330
- if (a.done || b.done) throw new Error("Cannot compose mismatched change-set lengths.");
331
- const length = Math.min(a.outputLength, b.length);
332
- const sectionLength = sections.length;
333
- if (a.keep && b.keep) {
334
- const modifications = Object.freeze([...a.modifications ?? [], ...b.modifications ?? []]);
335
- add(length, modifications.length > 0 ? -2 : -1, modifications.length > 0 ? modifications : null, open);
336
- } else if (a.keep) add(length, b.offset > 0 ? 0 : b.inserted, b.offset > 0 ? PreparedTokenSlice.empty : b.slice, open);
337
- else if (b.keep) {
338
- const slice = a.slicePart(length);
339
- add(a.offset > 0 ? 0 : a.length, length, b.modifications ? applyPropertyModificationsToSlice(slice, b.modifications) : slice, open);
340
- } else add(a.offset > 0 ? 0 : a.length, b.offset > 0 ? 0 : b.inserted, b.offset > 0 ? PreparedTokenSlice.empty : b.slice, open);
341
- open = (a.inserted > length || !b.keep && b.length > length) && (open || sections.length > sectionLength);
342
- a.forwardOutput(length);
343
- b.forward(length);
344
- }
345
- };
346
- /** Whether inserted tokens open an element they do not close: a wrap's lead. */
347
- const opensEnclosure = (slice) => {
348
- let depth = 0;
349
- for (const token of slice?.tokens ?? []) if (token.kind === "open") depth += 1;
350
- else if (token.kind === "close") depth -= 1;
351
- return depth > 0;
352
- };
353
- const tokenKey = (token) => token.kind === "open" ? [
354
- "open",
355
- token.nodeKind,
356
- token.props
357
- ] : token.kind === "close" ? ["close", token.nodeKind] : ["text", token.text];
358
- const insertedElementKeys = ({ from, insert, to }) => {
359
- if (from !== to) return void 0;
360
- const keys = [];
361
- let element = [];
362
- let depth = 0;
363
- for (const token of insert.tokens) {
364
- if (depth === 0) {
365
- if (token.kind !== "open" || token.nodeKind !== "element") return;
366
- element = [];
367
- }
368
- element.push(tokenKey(token));
369
- depth += depthChange(token);
370
- if (depth === 0) keys.push(canonicalJsonKey(element));
371
- }
372
- return depth === 0 && keys.length > 0 ? keys : void 0;
373
- };
374
- const placesBlocks = (document, position) => {
375
- const context = document.openContextAt(position).findLast(({ contentFrom, contentTo }) => contentFrom <= position && position <= contentTo);
376
- if (context === void 0) return true;
377
- if (context.kind !== "element") return false;
378
- const node = document.node(context.path);
379
- const first = node && isElementNode(node) ? node.children[0] : void 0;
380
- return !(first !== void 0 && isTextNode(first));
381
- };
382
- const removesElement = (document, replacements) => replacements.some(({ from, to }) => {
383
- let depth = 0;
384
- return document.slice(from, to).tokens.some((token) => {
385
- if (token.kind === "open") depth += 1;
386
- if (token.kind !== "close" || depth === 0) return false;
387
- depth -= 1;
388
- return token.nodeKind === "element";
389
- });
390
- });
391
- const sameSlice = (left, right) => left.length === right.length && left.tokens.every((token, index) => tokensEqual(token, right.tokens[index]));
392
- const netDepth = (tokens) => tokens.reduce((depth, token) => depth + depthChange(token), 0);
393
- const editedRanges = (change, side) => {
394
- const ranges = [];
395
- let position = 0;
396
- for (let index = 0; index < change.sections.length; index += 2) {
397
- const length = change.sections[index];
398
- const inserted = change.sections[index + 1];
399
- const size = side === "to" && inserted >= 0 ? inserted : length;
400
- if (inserted !== -1) ranges.push([position, position + size]);
401
- position += size;
402
- }
403
- return ranges;
404
- };
405
- /** Whether every edit `change` made to give `result` is still in `later`. */
406
- const keptIn = (change, result, later) => {
407
- const written = editedRanges(change, "to");
408
- return editedRanges(RootChange.betweenWhole(result, later), "from").every(([from, to]) => written.every(([start, end]) => to < start || end < from));
409
- };
410
- const editKey = (from, to) => `${from}:${to}`;
411
- /**
412
- * The places where both sides insert whole blocks between blocks, by
413
- * `editKey`. The same blocks count once, with each other edit both sides make
414
- * alike, and different blocks both stay. Null when there is no such place,
415
- * when two inserts there share blocks but not all of them in order, when
416
- * the same blocks go in while a side takes an element out, as a move does,
417
- * or when both sides also wrap letters, which the rebase decides as a pair.
418
- */
419
- const sharedPlaceEdits = (document, aReplacements, bReplacements) => {
420
- const bByRange = new Map(bReplacements.map((replacement) => [editKey(replacement.from, replacement.to), replacement]));
421
- const blocks = [];
422
- const alike = [];
423
- let sameBlocks = false;
424
- let removes;
425
- for (const replacement of aReplacements) {
426
- const { from, insert, to } = replacement;
427
- const other = bByRange.get(editKey(from, to));
428
- if (!other) continue;
429
- const keys = insertedElementKeys(replacement);
430
- const otherKeys = insertedElementKeys(other);
431
- if (!keys || !otherKeys || !placesBlocks(document, from)) {
432
- if (sameSlice(insert, other.insert) && netDepth(insert.tokens) === netDepth(document.slice(from, to).tokens)) alike.push({
433
- from,
434
- kind: "same",
435
- merged: insert,
436
- to
437
- });
438
- continue;
439
- }
440
- const otherKeySet = new Set(otherKeys);
441
- if (keys.filter((key) => otherKeySet.has(key)).length === 0) {
442
- blocks.push({
443
- first: insert,
444
- from,
445
- kind: "different",
446
- merged: insert.concat(other.insert),
447
- second: other.insert,
448
- to
449
- });
450
- continue;
451
- }
452
- if (keys.length !== otherKeys.length || keys.some((key, index) => key !== otherKeys[index])) return null;
453
- removes ??= removesElement(document, [...aReplacements, ...bReplacements]);
454
- if (removes) return null;
455
- sameBlocks = true;
456
- blocks.push({
457
- from,
458
- kind: "same",
459
- merged: insert,
460
- to
461
- });
462
- }
463
- if (blocks.length === 0) return null;
464
- const edits = new Map([...blocks, ...sameBlocks ? alike : []].map((edit) => [editKey(edit.from, edit.to), edit]));
465
- const wraps = (replacements) => replacements.some(({ from, insert, to }) => !edits.has(editKey(from, to)) && opensEnclosure(insert));
466
- return wraps(aReplacements) && wraps(bReplacements) ? null : edits;
467
- };
468
- const overSharedEdits = (change, edits) => {
469
- const sections = [];
470
- const data = [];
471
- let position = 0;
472
- for (let index = 0; index < change.sections.length; index += 2) {
473
- const length = change.sections[index];
474
- const inserted = change.sections[index + 1];
475
- const edit = inserted >= 0 ? edits.get(editKey(position, position + length)) : null;
476
- if (edit) addSection(sections, data, edit.merged.length, -1, null);
477
- else addSection(sections, data, length, inserted, change.data[index >> 1]);
478
- position += length;
479
- }
480
- return RootChange.fromSections(sections, data);
481
- };
482
- /**
483
- * Adds the other side's blocks beside `change`'s own at each place both
484
- * insert different ones.
485
- */
486
- const resultToSharedDocument = (change, edits, side) => {
487
- const sections = [];
488
- const data = [];
489
- let position = 0;
490
- for (let index = 0; index < change.sections.length; index += 2) {
491
- const length = change.sections[index];
492
- const inserted = change.sections[index + 1];
493
- const edit = inserted >= 0 ? edits.get(editKey(position, position + length)) : null;
494
- const different = edit?.kind === "different" ? edit : null;
495
- const before = side === "second" ? different?.first : null;
496
- const after = side === "first" ? different?.second : null;
497
- if (before) addSection(sections, data, 0, before.length, before);
498
- addSection(sections, data, inserted < 0 ? length : inserted, -1, null);
499
- if (after) addSection(sections, data, 0, after.length, after);
500
- position += length;
501
- }
502
- return RootChange.fromSections(sections, data);
503
- };
504
- const replaySections = /* @__PURE__ */ new WeakMap();
505
- const leadingNodeTokens = (tokens, from = 0) => {
506
- let depth = 0;
507
- let at = from;
508
- for (; at < tokens.length; at++) {
509
- const token = getDefined(tokens[at]);
510
- if (depth === 0 && !isElementOpen(token)) break;
511
- if (token.kind === "open") depth += 1;
512
- else if (token.kind === "close") depth -= 1;
513
- }
514
- return at - from;
515
- };
516
- const insertsWhere = (change, passes) => {
517
- const positions = [];
518
- let position = 0;
519
- for (let at = 0; at < change.sections.length; at += 2) {
520
- const length = getDefined(change.sections[at]);
521
- const inserted = getDefined(change.sections[at + 1]);
522
- if (length === 0 && inserted > 0 && passes(change.data[at >> 1].tokens)) positions.push(position);
523
- position += length;
524
- }
525
- return positions;
526
- };
527
- const isElementClose = (token) => token?.kind === "close" && token.nodeKind === "element";
528
- const isElementOpen = (token) => token?.kind === "open" && token.nodeKind === "element";
529
- const closesAfterNodes = (tokens) => isElementClose(tokens[leadingNodeTokens(tokens)]);
530
- const meetsNodesAtClose = (change, other) => {
531
- const closes = insertsWhere(change, closesAfterNodes);
532
- if (closes.length === 0) return false;
533
- const nodes = new Set(insertsWhere(other, (tokens) => isElementOpen(tokens[0])));
534
- return closes.some((position) => nodes.has(position));
535
- };
536
- const openKind = (token) => token.kind === "open" ? token.nodeKind : "";
537
- const nodeKey = (token) => `${openKind(token)}:${String(token.kind === "open" ? token.props.type : "")}`;
538
- const documentCloses = (change, document) => {
539
- const base = document.tokens.tokens;
540
- const { offsets } = document.tokens;
541
- const closeOf = /* @__PURE__ */ new Map();
542
- const deleted = new Uint8Array(base.length);
543
- const opens = [];
544
- for (let at = 0; at < base.length; at++) {
545
- const { kind } = getDefined(base[at]);
546
- if (kind === "open") opens.push(at);
547
- else if (kind === "close") closeOf.set(getDefined(opens.pop()), at);
548
- }
549
- let at = 0;
550
- let position = 0;
551
- let written;
552
- for (let pair = 0; pair < change.sections.length; pair += 2) {
553
- const length = getDefined(change.sections[pair]);
554
- const inserted = getDefined(change.sections[pair + 1]);
555
- const tokens = inserted > 0 ? change.data[pair >> 1].tokens : [];
556
- let writesClose = isElementClose(length > 0 && inserted > 0 ? tokens.at(-1) : written);
557
- for (; at < base.length && getDefined(offsets[at]) < position + length; at++) {
558
- if (inserted >= 0 && !(writesClose && isElementClose(base[at]))) deleted[at] = 1;
559
- writesClose = false;
560
- }
561
- written = length === 0 ? tokens.at(-1) : void 0;
562
- position += length;
563
- }
564
- countCoreWork("replayWalkVisits", base.length);
565
- const closeAt = (open) => getDefined(closeOf.get(open));
566
- return {
567
- closeAt,
568
- closeDeleted: (open) => deleted[closeAt(open)] === 1
569
- };
570
- };
571
- const splitOwnCloses = (change, document) => {
572
- const base = document.tokens.tokens;
573
- const { offsets } = document.tokens;
574
- const sections = [];
575
- const data = [];
576
- const ownCloses = /* @__PURE__ */ new Set();
577
- const baseOpen = [];
578
- const outputOpen = [];
579
- const cut = /* @__PURE__ */ new Map();
580
- let retypeCandidates = /* @__PURE__ */ new Set();
581
- const paired = /* @__PURE__ */ new Set();
582
- const deletedByKind = /* @__PURE__ */ new Map();
583
- const { closeAt, closeDeleted } = documentCloses(change, document);
584
- let token = 0;
585
- let position = 0;
586
- const stillOpen = (continued) => continued !== null && continued.closesAt >= token;
587
- const lastCut = (key) => {
588
- const elements = cut.get(key) ?? [];
589
- let last = elements.at(-1);
590
- countCoreWork("replayWalkVisits");
591
- while (last && (last.taken || !stillOpen(last.continued))) {
592
- countCoreWork("replayWalkVisits");
593
- elements.pop();
594
- last = elements.at(-1);
595
- }
596
- return last;
597
- };
598
- const continues = (written) => {
599
- const typed = lastCut(nodeKey(written));
600
- if (typed) return typed;
601
- const any = lastCut(`${openKind(written)}:*`);
602
- if (any) return any;
603
- const last = lastCut(openKind(written));
604
- return last?.continued.everyCloseDeleted ? last : void 0;
605
- };
606
- const unmatchedOpens = (from, to) => {
607
- const opens = [];
608
- let at = from;
609
- for (; at < base.length && getDefined(offsets[at]) < to; at++) {
610
- const { kind } = getDefined(base[at]);
611
- if (kind === "open") opens.push(at);
612
- else if (kind === "close") opens.pop();
613
- }
614
- countCoreWork("replayWalkVisits", at - from);
615
- return opens;
616
- };
617
- for (let at = 0; at < change.sections.length; at += 2) {
618
- const length = getDefined(change.sections[at]);
619
- const inserted = getDefined(change.sections[at + 1]);
620
- const value = change.data[at >> 1] ?? null;
621
- let split = 0;
622
- if (inserted < 0) retypeCandidates = /* @__PURE__ */ new Set();
623
- if (length === 0 && inserted > 0) {
624
- const { tokens } = value;
625
- let closed = 0;
626
- let next = 0;
627
- for (;;) {
628
- const nodes = next + leadingNodeTokens(tokens, next);
629
- let own = 0;
630
- while (isElementClose(tokens[nodes + own])) {
631
- const element = outputOpen.at(-1 - closed - own);
632
- if (element === void 0 || stillOpen(element.continued)) break;
633
- own += 1;
634
- }
635
- if (own === 0) break;
636
- closed += own;
637
- next = nodes + own;
638
- }
639
- if (next > 0) split = value.offsets[next] ?? inserted;
640
- }
641
- if (split > 0) {
642
- const slice = value;
643
- ownCloses.add(data.length);
644
- sections.push(0, split);
645
- data.push(slice.slice(0, split));
646
- if (inserted > split) {
647
- sections.push(0, inserted - split);
648
- data.push(slice.slice(split));
649
- }
650
- } else if (length > 0 || inserted > 0) {
651
- sections.push(length, inserted);
652
- data.push(value);
653
- }
654
- countCoreWork("replayWalkVisits", Math.max(inserted, 0));
655
- for (; token < base.length && getDefined(offsets[token]) < position + length; token++) {
656
- const written = getDefined(base[token]);
657
- if (written.kind === "open") {
658
- baseOpen.push(token);
659
- if (inserted < 0) outputOpen.push({
660
- continued: {
661
- closesAt: closeAt(token),
662
- everyCloseDeleted: closeDeleted(token)
663
- },
664
- key: inserted === -1 ? nodeKey(written) : `${openKind(written)}:*`,
665
- kind: openKind(written)
666
- });
667
- else {
668
- const kind = openKind(written);
669
- const sameKind = deletedByKind.get(kind) ?? {
670
- keptCloses: 0,
671
- opens: []
672
- };
673
- sameKind.opens.push(token);
674
- if (!closeDeleted(token)) sameKind.keptCloses += 1;
675
- deletedByKind.set(kind, sameKind);
676
- if (!paired.has(token)) retypeCandidates.add(token);
677
- }
678
- } else if (written.kind === "close") {
679
- const open = getDefined(baseOpen.pop());
680
- const sameKind = deletedByKind.get(openKind(getDefined(base[open])));
681
- retypeCandidates.delete(open);
682
- if (sameKind?.opens.at(-1) === open) {
683
- sameKind.opens.pop();
684
- if (!closeDeleted(open)) sameKind.keptCloses -= 1;
685
- }
686
- if (inserted < 0) outputOpen.pop();
687
- }
688
- }
689
- if (inserted > 0) {
690
- const next = change.sections[at + 2] ?? 0;
691
- if (next > 0 && change.sections[at + 3] === 0) for (const open of unmatchedOpens(token, position + length + next)) {
692
- retypeCandidates.add(open);
693
- paired.add(open);
694
- }
695
- const opened = [];
696
- for (const written of value.tokens) if (written.kind === "open") {
697
- const from = continues(written);
698
- if (from) from.taken = true;
699
- opened.push(outputOpen.length);
700
- outputOpen.push({
701
- continued: from?.continued ?? null,
702
- key: nodeKey(written),
703
- kind: openKind(written)
704
- });
705
- } else if (written.kind === "close") {
706
- const element = getDefined(outputOpen.pop());
707
- if (opened.at(-1) === outputOpen.length) opened.pop();
708
- if (element.continued && stillOpen(element.continued)) {
709
- const cutElement = {
710
- continued: element.continued,
711
- taken: false
712
- };
713
- for (const key of [element.key, element.kind]) {
714
- const elements = cut.get(key) ?? [];
715
- elements.push(cutElement);
716
- cut.set(key, elements);
717
- }
718
- }
719
- }
720
- const wraps = opened.filter((index) => getDefined(outputOpen[index]).continued === null);
721
- if (wraps.length > 0) {
722
- let retypeClosesAt = -1;
723
- let retypeClosesDeleted = true;
724
- countCoreWork("replayWalkVisits", retypeCandidates.size);
725
- for (const open of retypeCandidates) {
726
- retypeClosesAt = Math.max(retypeClosesAt, closeAt(open));
727
- retypeClosesDeleted &&= closeDeleted(open);
728
- }
729
- for (const index of wraps) {
730
- const element = getDefined(outputOpen[index]);
731
- const sameKind = deletedByKind.get(element.kind);
732
- const outermost = sameKind?.opens[0];
733
- const closesAt = Math.max(retypeClosesAt, outermost === void 0 ? -1 : closeAt(outermost));
734
- if (closesAt < 0) continue;
735
- outputOpen[index] = {
736
- ...element,
737
- continued: {
738
- closesAt,
739
- everyCloseDeleted: retypeClosesDeleted && (sameKind?.keptCloses ?? 0) === 0
740
- }
741
- };
742
- }
743
- retypeCandidates = /* @__PURE__ */ new Set();
744
- }
745
- }
746
- position += length;
747
- }
748
- return {
749
- data,
750
- ownCloses,
751
- sections
752
- };
753
- };
754
- const replaySectionsOf = (change, other, document) => {
755
- if (!meetsNodesAtClose(change, other)) return null;
756
- let byDocument = replaySections.get(change);
757
- if (!byDocument) {
758
- byDocument = /* @__PURE__ */ new WeakMap();
759
- replaySections.set(change, byDocument);
760
- }
761
- let split = byDocument.get(document);
762
- if (!split) {
763
- split = splitOwnCloses(change, document);
764
- byDocument.set(document, split);
765
- }
766
- return split;
767
- };
768
- const landing = {
769
- beforePeer: -1,
770
- tie: 0,
771
- afterPeer: 1
772
- };
773
- const landingOrder = (side, ownCloses, other, otherLeftOpen) => {
774
- if (ownCloses?.has(side.pair) && !otherLeftOpen && other.slice.tokens.length > 0 && leadingNodeTokens(other.slice.tokens) === other.slice.tokens.length) return landing.beforePeer;
775
- return opensEnclosure(side.slice) ? landing.afterPeer : landing.tie;
776
- };
777
- /**
778
- * Whether `b`'s insertion goes before `a`'s at one position. A replayed insert
779
- * split off as own lands before the other side's whole blocks, unless the
780
- * other side's insert just before it here left an element open. Content one
781
- * side inserts at the lead of an element the other wraps stays outside it, as
782
- * it was before the wrap; otherwise `before` breaks the tie.
783
- */
784
- const bLandsFirst = (a, b, ownA, ownB, before, leftOpen) => {
785
- const aOrder = landingOrder(a, ownA, b, leftOpen === "b");
786
- const bOrder = landingOrder(b, ownB, a, leftOpen === "a");
787
- return aOrder === bOrder ? !before : bOrder < aOrder;
788
- };
789
- const transformChange = (changeA, changeB, before, replayBase, readBack = null) => {
790
- if (changeA.length !== changeB.length) throw new Error("Cannot transform mismatched change-set lengths.");
791
- const sections = [];
792
- const data = [];
793
- const fidelity = readBack && replayBase ? wrapFidelity(changeA, changeB, replayBase, before ? "a" : "b") : null;
794
- if (fidelity) markReadBack(readBack);
795
- const replayA = !fidelity && replayBase && replaySectionsOf(changeA, changeB, replayBase);
796
- const replayB = !fidelity && replayBase && replaySectionsOf(changeB, changeA, replayBase);
797
- const a = new SectionIterator(fidelity ? fidelity.a.sections : replayA ? replayA.sections : changeA.sections, fidelity ? fidelity.a.data : replayA ? replayA.data : changeA.data);
798
- const b = new SectionIterator(fidelity ? fidelity.b.sections : replayB ? replayB.sections : changeB.sections, fidelity ? fidelity.b.data : replayB ? replayB.data : changeB.data);
799
- let inserted = -1;
800
- let position = 0;
801
- let leftOpen = null;
802
- for (;;) {
803
- if (a.keep && b.keep) {
804
- const length = Math.min(a.length, b.length);
805
- if (length > 0) leftOpen = null;
806
- const modifications = a.modifications ? before ? transformEarlierPropertyModifications(a.modifications, b.modifications ?? []) : a.modifications : null;
807
- addSection(sections, data, length, modifications && modifications.length > 0 ? -2 : -1, modifications && modifications.length > 0 ? modifications : null);
808
- a.forward(length);
809
- b.forward(length);
810
- position += length;
811
- continue;
812
- }
813
- if (b.inserted >= 0 && (a.inserted < 0 || inserted === a.index || a.offset === 0 && (b.length < a.length || b.length === a.length && (a.length === 0 ? fidelity?.merges(position) ? fidelity.bFirst(position) : bLandsFirst(a, b, replayA ? replayA.ownCloses : void 0, replayB ? replayB.ownCloses : void 0, before, leftOpen) : !before)))) {
814
- const end = position + b.length;
815
- addSection(sections, data, b.inserted, -1, null);
816
- if (replayBase && b.inserted > 0) leftOpen = opensEnclosure(b.slice) ? "b" : null;
817
- while (position < end) {
818
- if (a.done) throw new Error("Mismatched transformed change sets.");
819
- const piece = Math.min(a.length, end - position);
820
- if (a.inserted >= 0 && inserted < a.index && a.length <= piece) {
821
- addSection(sections, data, 0, a.inserted, a.slice);
822
- inserted = a.index;
823
- if (replayBase && a.inserted > 0) leftOpen = opensEnclosure(a.slice) ? "a" : null;
824
- }
825
- a.forward(piece);
826
- position += piece;
827
- }
828
- b.next();
829
- continue;
830
- }
831
- if (a.inserted >= 0) {
832
- const start = position;
833
- const end = position + a.length;
834
- let length = 0;
835
- while (position < end) if (b.keep) {
836
- const piece = Math.min(end - position, b.length);
837
- position += piece;
838
- length += piece;
839
- b.forward(piece);
840
- } else if (b.inserted === 0) {
841
- const piece = Math.min(end - position, b.length);
842
- position += piece;
843
- b.forward(piece);
844
- } else break;
845
- if (inserted < a.index) {
846
- addSection(sections, data, length, a.inserted, a.slice);
847
- inserted = a.index;
848
- if (replayBase && a.inserted > 0) leftOpen = opensEnclosure(a.slice) ? "a" : null;
849
- } else addSection(sections, data, length, 0, PreparedTokenSlice.empty);
850
- a.forward(position - start);
851
- continue;
852
- }
853
- return RootChange.fromSections(sections, data);
854
- }
855
- };
856
- const ancestorType = (type) => typeof type === "string" ? type : "element";
857
- const getDocumentPropertyContext = (document, path, root, offset = 0) => {
858
- const node = document.node(path);
859
- const ancestorTypes = [];
860
- for (let depth = path.length - 1; depth > 0; depth--) {
861
- const ancestor = document.node(path.slice(0, depth));
862
- if (!isTextNode(ancestor)) ancestorTypes.push(ancestorType(ancestor.type));
863
- }
864
- const placement = isTextNode(node) ? "text" : "element";
865
- const parent = ancestorTypes[0] ?? null;
866
- return Object.freeze({
867
- ancestors: placement === "text" ? ancestorTypes.slice(1) : ancestorTypes,
868
- parent,
869
- path: Object.freeze(offset === 0 || path.length === 0 ? [...path] : [getDefined(path[0]) + offset, ...path.slice(1)]),
870
- placement,
871
- root,
872
- type: placement === "text" ? parent ?? "text" : typeof node.type === "string" ? node.type : "element"
873
- });
874
- };
875
- /** @internal */
876
- const writesOnlyElementProperties = (change, document) => {
877
- let position = 0;
878
- for (let at = 0; at < change.sections.length; at += 2) {
879
- const inserted = getDefined(change.sections[at + 1]);
880
- if (inserted >= 0) return false;
881
- if (inserted === -2 && document.nodeStartingAt(position)?.kind !== "element") return false;
882
- position += getDefined(change.sections[at]);
883
- }
884
- return true;
885
- };
886
- /** @internal */
887
- const collapseElementPropertyWrites = (change, document, isSetValued, root, text = false) => {
888
- const sections = [];
889
- const data = [];
890
- let applied;
891
- let position = 0;
892
- let appliedPosition = 0;
893
- let collapsed = false;
894
- const appliedAt = (at) => {
895
- applied ??= change.apply(document);
896
- const { path } = getDefined(applied.nodeStartingAt(at));
897
- return [applied.node(path), getDocumentPropertyContext(applied, path, root)];
898
- };
899
- for (let at = 0; at < change.sections.length; at += 2) {
900
- const length = getDefined(change.sections[at]);
901
- const inserted = getDefined(change.sections[at + 1]);
902
- const value = change.data[at / 2] ?? null;
903
- const entry = inserted === -2 ? document.nodeStartingAt(position) : void 0;
904
- if (entry?.kind === "element" || text && entry?.kind === "text") {
905
- const node = document.node(entry.path);
906
- const modifications = value;
907
- const keys = new Set(modifications.map(({ key }) => key));
908
- const written = Object.fromEntries(Object.entries(nodeProps(node)).filter(([key]) => keys.has(key)));
909
- const context = getDocumentPropertyContext(document, entry.path, root);
910
- const start = appliedPosition;
911
- let after;
912
- const kept = semanticPropertyModifications(written, applyPropertyModifications(written, modifications), (key) => {
913
- if (!isSetValued(node, key, context)) return false;
914
- after ??= appliedAt(start);
915
- return isSetValued(after[0], key, after[1]);
916
- });
917
- addSection(sections, data, length, kept.length > 0 ? -2 : -1, kept.length > 0 ? kept : null);
918
- collapsed = true;
919
- } else addSection(sections, data, length, inserted, value);
920
- position += length;
921
- appliedPosition += inserted < 0 ? length : inserted;
922
- }
923
- return collapsed ? RootChange.fromSections(sections, data) : change;
924
- };
925
- const TREE_DIFF_MATRIX_LIMIT = 4096;
926
- const commonTextPrefixLength = (left, right) => {
927
- const limit = Math.min(left.length, right.length);
928
- let length = 0;
929
- while (length < limit && left[length] === right[length]) length += 1;
930
- return length;
931
- };
932
- const commonTextSuffixLength = (left, right, limit = Math.min(left.length, right.length)) => {
933
- let length = 0;
934
- while (length < limit && left.at(-length - 1) === right.at(-length - 1)) length += 1;
935
- return length;
936
- };
937
- /**
938
- * Build a structural diff when unchanged siblings shift or one source node has
939
- * a uniquely stronger continuation later in its sibling list. Flat diffs can
940
- * otherwise retain an opening token on one inserted sibling and that node's
941
- * content/closing token on another, splitting one node key in two.
942
- */
943
- const createStructurallyAlignedChanges = (before, after, options) => {
944
- const changes = [];
945
- const boundaries = /* @__PURE__ */ new WeakMap();
946
- const properties = /* @__PURE__ */ new WeakMap();
947
- let flatDiffRekeys = false;
948
- const getProperties = (node) => {
949
- let result = properties.get(node);
950
- if (!result) {
951
- result = nodeProps(node);
952
- properties.set(node, result);
953
- }
954
- return result;
955
- };
956
- const getBoundary = (node) => {
957
- const cached = boundaries.get(node);
958
- if (cached) return cached;
959
- if (isTextNode(node)) {
960
- const result = Object.freeze({
961
- length: node.text.length,
962
- prefix: node.text.slice(0, 128),
963
- suffix: node.text.slice(-128)
964
- });
965
- boundaries.set(node, result);
966
- return result;
967
- }
968
- let length = 0;
969
- let prefix = "";
970
- let suffix = "";
971
- for (const child of node.children) {
972
- const childBoundary = getBoundary(child);
973
- length += childBoundary.length;
974
- if (prefix.length < 128) prefix += childBoundary.prefix.slice(0, 128 - prefix.length);
975
- }
976
- for (let index = node.children.length - 1; index >= 0; index--) {
977
- const childBoundary = getBoundary(node.children[index]);
978
- suffix = `${childBoundary.suffix.slice(Math.max(0, childBoundary.suffix.length - (128 - suffix.length)))}${suffix}`;
979
- if (suffix.length >= 128) break;
980
- }
981
- const result = Object.freeze({
982
- length,
983
- prefix,
984
- suffix
985
- });
986
- boundaries.set(node, result);
987
- return result;
988
- };
989
- const continuityScore = (source, target) => {
990
- if (isTextNode(source) !== isTextNode(target)) return 0;
991
- if (Object.is(source, target)) return 2e9;
992
- if (jsonEqual(source, target)) return 1e9;
993
- const sourceProperties = getProperties(source);
994
- const targetProperties = getProperties(target);
995
- const propertiesEqual = jsonEqual(sourceProperties, targetProperties);
996
- const sourceType = sourceProperties.type;
997
- const targetType = targetProperties.type;
998
- if (!propertiesEqual && (sourceType === void 0 || sourceType !== targetType)) return 0;
999
- const sourceText = getBoundary(source);
1000
- const targetText = getBoundary(target);
1001
- const prefix = commonTextPrefixLength(sourceText.prefix, targetText.prefix);
1002
- const overlap = prefix + commonTextSuffixLength(sourceText.suffix, targetText.suffix, Math.max(0, Math.min(sourceText.length, targetText.length) - prefix));
1003
- if (overlap === 0) return 0;
1004
- return (propertiesEqual ? 1024 : 512) + overlap * 16;
1005
- };
1006
- const isCompleteTextContinuation = (source, target) => {
1007
- const sourceText = getBoundary(source);
1008
- if (sourceText.length === 0 || sourceText.length > 128) return false;
1009
- const targetText = getBoundary(target);
1010
- const prefix = commonTextPrefixLength(sourceText.prefix, targetText.prefix);
1011
- return prefix + commonTextSuffixLength(sourceText.suffix, targetText.suffix, Math.max(0, Math.min(sourceText.length, targetText.length) - prefix)) === sourceText.length;
1012
- };
1013
- const addPropertyChanges = (source, target, path) => {
1014
- const sourceProperties = getProperties(source);
1015
- const targetProperties = getProperties(target);
1016
- if (jsonEqual(sourceProperties, targetProperties)) return;
1017
- const context = getDocumentPropertyContext(before, path, options.root ?? null, options.offset);
1018
- const modifications = betweenPropertyModifications(sourceProperties, targetProperties, (key) => options.isSetValued?.(source, key, context) ?? false, options.emptySetsAsValues);
1019
- if (modifications.length > 0) changes.push({
1020
- from: before.nodeRange(path).from,
1021
- properties: propertyDeltaFromModifications(modifications)
1022
- });
1023
- };
1024
- const diffNode = (source, target, path) => {
1025
- if (jsonEqual(source, target)) return true;
1026
- if (isTextNode(source) !== isTextNode(target)) return false;
1027
- addPropertyChanges(source, target, path);
1028
- if (isTextNode(source) && isTextNode(target)) {
1029
- const range = before.nodeRange(path);
1030
- const prefix = commonTextPrefixLength(source.text, target.text);
1031
- const suffix = commonTextSuffixLength(source.text, target.text, Math.min(source.text.length, target.text.length) - prefix);
1032
- if (prefix !== source.text.length || prefix !== target.text.length) changes.push({
1033
- from: range.from + 1 + prefix,
1034
- insert: PreparedTokenSlice.text(target.text.slice(prefix, target.text.length - suffix)),
1035
- to: range.to - 1 - suffix
1036
- });
1037
- return true;
1038
- }
1039
- if (!isElementNode(source) || !isElementNode(target)) return false;
1040
- if (getProperties(source).type === getProperties(target).type && !jsonEqual(getProperties(source), getProperties(target)) && !jsonEqual(source.children, target.children)) flatDiffRekeys = true;
1041
- return diffChildren(source.children, target.children, path);
1042
- };
1043
- const diffChildren = (source, target, parentPath) => {
1044
- let prefix = 0;
1045
- while (prefix < source.length && prefix < target.length && jsonEqual(source[prefix], target[prefix])) prefix += 1;
1046
- let suffix = 0;
1047
- while (suffix < source.length - prefix && suffix < target.length - prefix && jsonEqual(source.at(-suffix - 1), target.at(-suffix - 1))) suffix += 1;
1048
- const sourceEnd = source.length - suffix;
1049
- const targetEnd = target.length - suffix;
1050
- const sourceCount = sourceEnd - prefix;
1051
- const targetCount = targetEnd - prefix;
1052
- if (suffix > 0 && sourceCount !== targetCount && (sourceCount === 0 || targetCount === 0)) flatDiffRekeys = true;
1053
- if (sourceCount > 0 && targetCount > 0 && sourceCount !== targetCount) {
1054
- const sourceRun = source.slice(prefix, sourceEnd);
1055
- const targetRun = target.slice(prefix, targetEnd);
1056
- if (sourceRun.every(isTextNode) && targetRun.every(isTextNode) && sourceRun.map((node) => node.text).join("") === targetRun.map((node) => node.text).join("")) {
1057
- const startsOf = (run) => {
1058
- let offset = 0;
1059
- return run.map((node) => {
1060
- const at = offset;
1061
- offset += node.text.length;
1062
- return at;
1063
- });
1064
- };
1065
- const sourceStarts = startsOf(sourceRun);
1066
- const targetStarts = startsOf(targetRun);
1067
- let next = 1;
1068
- const splitAt = (targetIndex) => {
1069
- const offset = getDefined(targetStarts[targetIndex]);
1070
- const index = sourceStarts.findLastIndex((at) => at <= offset);
1071
- changes.push({
1072
- from: before.positionAt({
1073
- path: [...parentPath, prefix + index],
1074
- offset: offset - getDefined(sourceStarts[index])
1075
- }),
1076
- insert: PreparedTokenSlice.fromTokens([closeToken("text"), openToken("text", getProperties(getDefined(targetRun[targetIndex])))])
1077
- });
1078
- };
1079
- addPropertyChanges(sourceRun[0], targetRun[0], [...parentPath, prefix]);
1080
- for (let index = 1; index < sourceRun.length; index++) {
1081
- const at = getDefined(sourceStarts[index]);
1082
- for (; next < targetCount && getDefined(targetStarts[next]) < at; next += 1) splitAt(next);
1083
- if (next < targetCount && targetStarts[next] === at) {
1084
- addPropertyChanges(getDefined(sourceRun[index]), getDefined(targetRun[next]), [...parentPath, prefix + index]);
1085
- next += 1;
1086
- } else {
1087
- const boundary = before.childPosition(parentPath, prefix + index);
1088
- changes.push({
1089
- from: boundary - 1,
1090
- to: boundary + 1
1091
- });
1092
- }
1093
- }
1094
- for (; next < targetCount; next += 1) splitAt(next);
1095
- flatDiffRekeys = true;
1096
- return true;
1097
- }
1098
- }
1099
- if (sourceCount * targetCount > 4096) return false;
1100
- const scores = Array.from({ length: sourceCount }, (_value, sourceIndex) => Array.from({ length: targetCount }, (_targetValue, targetIndex) => continuityScore(source[prefix + sourceIndex], target[prefix + targetIndex])));
1101
- const matrix = Array.from({ length: sourceCount + 1 }, () => new Float64Array(targetCount + 1));
1102
- for (let sourceIndex = sourceCount - 1; sourceIndex >= 0; sourceIndex--) for (let targetIndex = targetCount - 1; targetIndex >= 0; targetIndex--) {
1103
- const score = scores[sourceIndex][targetIndex];
1104
- const matched = score > 0 ? score + matrix[sourceIndex + 1][targetIndex + 1] : Number.NEGATIVE_INFINITY;
1105
- matrix[sourceIndex][targetIndex] = Math.max(matched, matrix[sourceIndex + 1][targetIndex], matrix[sourceIndex][targetIndex + 1]);
1106
- }
1107
- const matches = [];
1108
- let sourceIndex = 0;
1109
- let targetIndex = 0;
1110
- while (sourceIndex < sourceCount && targetIndex < targetCount) {
1111
- const score = scores[sourceIndex][targetIndex];
1112
- const matched = score > 0 ? score + matrix[sourceIndex + 1][targetIndex + 1] : Number.NEGATIVE_INFINITY;
1113
- const skipSource = matrix[sourceIndex + 1][targetIndex];
1114
- const skipTarget = matrix[sourceIndex][targetIndex + 1];
1115
- if (matched >= skipSource && matched >= skipTarget) {
1116
- matches.push(Object.freeze([prefix + sourceIndex, prefix + targetIndex]));
1117
- sourceIndex += 1;
1118
- targetIndex += 1;
1119
- } else if (skipTarget >= skipSource) targetIndex += 1;
1120
- else sourceIndex += 1;
1121
- }
1122
- let sourceCursor = prefix;
1123
- let targetCursor = prefix;
1124
- const addGap = (sourceTo, targetTo) => {
1125
- if (sourceCursor === sourceTo && targetCursor === targetTo) return;
1126
- changes.push({
1127
- from: before.childPosition(parentPath, sourceCursor),
1128
- insert: PreparedTokenSlice.fromNodes(target.slice(targetCursor, targetTo)),
1129
- to: before.childPosition(parentPath, sourceTo)
1130
- });
1131
- };
1132
- for (const [matchedSource, matchedTarget] of matches) {
1133
- addGap(matchedSource, matchedTarget);
1134
- const row = scores[matchedSource - prefix];
1135
- const score = row[matchedTarget - prefix];
1136
- const best = Math.max(...row);
1137
- const column = scores.map((candidateRow) => candidateRow[matchedTarget - prefix]);
1138
- const columnBest = Math.max(...column);
1139
- if (matchedSource !== matchedTarget && isCompleteTextContinuation(source[matchedSource], target[matchedTarget]) && score === best && row.filter((candidate) => candidate === best).length === 1 && score === columnBest && column.filter((candidate) => candidate === columnBest).length === 1) flatDiffRekeys = true;
1140
- if (!diffNode(source[matchedSource], target[matchedTarget], [...parentPath, matchedSource])) return false;
1141
- sourceCursor = matchedSource + 1;
1142
- targetCursor = matchedTarget + 1;
1143
- }
1144
- addGap(sourceEnd, targetEnd);
1145
- return true;
1146
- };
1147
- return diffChildren(before.value, after.value, []) && flatDiffRekeys ? changes : null;
1148
- };
1149
- const changedRangesAreSeparated = (a, b) => {
1150
- const bRanges = [];
1151
- let separated = true;
1152
- let bIndex = 0;
1153
- b.iterChangedRanges((from, to) => {
1154
- bRanges.push([from, to]);
1155
- });
1156
- a.iterChangedRanges((from, to) => {
1157
- while (bIndex < bRanges.length && bRanges[bIndex][1] < from) bIndex += 1;
1158
- if (bIndex < bRanges.length && bRanges[bIndex][0] <= to) separated = false;
1159
- });
1160
- return separated;
1161
- };
1162
- const sameNodeStructure = (left, right) => {
1163
- if (left === right) return true;
1164
- if (isTextNode(left) || isTextNode(right)) return isTextNode(left) && isTextNode(right);
1165
- if (!isElementNode(left) || !isElementNode(right) || left.type !== right.type || left.children.length !== right.children.length) return false;
1166
- return left.children.every((child, index) => sameNodeStructure(child, right.children[index]));
1167
- };
1168
- /**
1169
- * Whether a range takes out no letter and no whole node, only edges that
1170
- * open or close an element it leaves in place.
1171
- */
1172
- const takesOutEdgesOnly = (document, { from, to }) => {
1173
- let depth = 0;
1174
- for (const token of document.slice(from, to).tokens) {
1175
- if (token.kind === "text") return false;
1176
- depth += token.kind === "open" ? 1 : -1;
1177
- }
1178
- return from === to || depth !== 0;
1179
- };
1180
- /**
1181
- * One key per position of `[from, to)` that `removed` leaves, so two token
1182
- * runs compare however their text is cut.
1183
- */
1184
- const positionKeys = (document, removed, from, to) => {
1185
- const keys = [];
1186
- let position = from;
1187
- for (const range of [...removed, {
1188
- from: to,
1189
- to
1190
- }]) {
1191
- let at = position;
1192
- for (const token of document.slice(position, range.from).tokens) {
1193
- if (token.kind === "text") {
1194
- for (let unit = 0; unit < token.text.length; unit += 1) keys.push(token.text.charAt(unit));
1195
- at += token.text.length;
1196
- continue;
1197
- }
1198
- const edge = token.kind === "open" ? `<${token.nodeKind}${JSON.stringify(token.props)}` : `</${token.nodeKind}`;
1199
- const identity = token.nodeKind === "element" ? `@${at}` : "";
1200
- keys.push(`${edge}${identity}`);
1201
- at += 1;
1202
- }
1203
- position = range.to;
1204
- }
1205
- return keys;
1206
- };
1207
- /**
1208
- * When `removal` only takes element and text edges out, and `other` takes
1209
- * out edges that leave the very same tokens before putting edges of its own
1210
- * in, as a step does that re-takes a teammate's equal wrap the teammate then
1211
- * unwraps, `other` over `removal` is its own edges alone, each placed where
1212
- * its removals left it.
1213
- */
1214
- const putBackOver = (removal, other, document) => {
1215
- const removed = other.filter(({ from, to }) => from < to);
1216
- if (removal.length === 0 || removed.length === 0 || !removal.every(({ insert }) => insert.length === 0) || ![...removal, ...other].every((range) => takesOutEdgesOnly(document, range))) return null;
1217
- const spanFrom = Math.min(...[...removal, ...removed].map((range) => range.from));
1218
- const spanTo = Math.max(...[...removal, ...removed].map((range) => range.to));
1219
- const left = positionKeys(document, removal, spanFrom, spanTo);
1220
- const right = positionKeys(document, removed, spanFrom, spanTo);
1221
- if (left.length !== right.length || left.some((key, index) => key !== right[index])) return null;
1222
- let shift = 0;
1223
- return other.flatMap(({ from, insert, to }) => {
1224
- const at = from - shift;
1225
- shift += to - from;
1226
- return insert.length === 0 ? [] : [{
1227
- from: at,
1228
- insert,
1229
- to: at
1230
- }];
1231
- });
1232
- };
1233
- /** Whether a positional transform gives one document from both sides. */
1234
- const convergesOn = (transformed, afterA, afterB) => {
1235
- try {
1236
- return sameChangedChildren(transformed.b.apply(afterA), transformed.a.apply(afterB), jsonEqual);
1237
- } catch {
1238
- return false;
1239
- }
1240
- };
1241
- const depthChange = (token) => token.kind === "open" ? 1 : token.kind === "close" ? -1 : 0;
1242
- const writtenBackCloses = (removed, insert) => {
1243
- let closes = 0;
1244
- while (closes < removed.length && removed[removed.length - 1 - closes].kind === "close") closes += 1;
1245
- if (closes === 0) return null;
1246
- let target = -closes;
1247
- for (let index = 0; index < removed.length - closes; index += 1) target += depthChange(removed[index]);
1248
- let depth = 0;
1249
- let insertEnd = 0;
1250
- while (insertEnd < insert.length && (insertEnd === 0 || depth !== target)) {
1251
- depth += depthChange(insert[insertEnd]);
1252
- insertEnd += 1;
1253
- }
1254
- if (depth !== target) return null;
1255
- let keptCloses = 0;
1256
- while (keptCloses < closes && keptCloses < insertEnd && tokensEqual(insert[insertEnd - 1 - keptCloses], removed[removed.length - 1 - keptCloses])) keptCloses += 1;
1257
- return keptCloses === 0 ? null : {
1258
- insertEnd,
1259
- keptCloses
1260
- };
1261
- };
1262
- const soleWrapProps = (replacements, document) => {
1263
- if (replacements.length !== 2) return null;
1264
- const [open, close] = replacements;
1265
- const [lead] = open.insert.tokens;
1266
- const [end] = close.insert.tokens;
1267
- if (open.from !== open.to || close.from !== close.to || open.from >= close.from || open.insert.tokens.length !== 1 || close.insert.tokens.length !== 1 || lead.kind !== "open" || lead.nodeKind !== "element" || end.kind !== "close" || end.nodeKind !== "element") return null;
1268
- const { tokens } = document.slice(open.from, close.from);
1269
- let depth = 0;
1270
- for (const token of tokens) {
1271
- depth += depthChange(token);
1272
- if (depth < 0) return null;
1273
- }
1274
- if (depth !== 0) return null;
1275
- return lead.props;
1276
- };
1277
- const wrapsInsideReplacement = (wrap, other, document) => wrap.length > 1 && wrap.every(({ from, insert, to }) => from === to && insert.tokens.length === 1 && insert.tokens[0].kind !== "text" && insert.tokens[0].nodeKind === "element") && other.some((range) => wrap.every(({ from }) => range.from < from && from < range.to)) && !other.some(({ insert }) => JSON.stringify(insert.toJSON()).includes(JSON.stringify(document.slice(getDefined(wrap[0]).from, getDefined(wrap.at(-1)).from).toJSON()).slice(1, -1)));
1278
- const propertyWritesOf = (change) => {
1279
- const sections = [];
1280
- const data = [];
1281
- for (let index = 0; index < change.sections.length; index += 2) {
1282
- const length = change.sections[index];
1283
- if (change.sections[index + 1] === -2) addSection(sections, data, length, -2, change.data[index >> 1] ?? null);
1284
- else addSection(sections, data, length, -1, null);
1285
- }
1286
- return RootChange.fromSections(sections, data);
1287
- };
1288
- const rebaseWritesBesideEqualMove = (a, b, move, document, options) => {
1289
- const writes = RootChange.transformInDocument(propertyWritesOf(a), propertyWritesOf(b), document, options);
1290
- return {
1291
- a: RootChange.transform(writes.a, move).a,
1292
- b: RootChange.transform(writes.b, move).a
1293
- };
1294
- };
1295
- const piecesOf = (slice) => {
1296
- const pieces = [];
1297
- let piece = [];
1298
- let depth = 0;
1299
- for (const token of slice.toJSON()) {
1300
- const step = depthChange(token);
1301
- piece.push(token);
1302
- depth += step;
1303
- if (depth <= 0) {
1304
- pieces.push(JSON.stringify(piece));
1305
- piece = [];
1306
- depth = 0;
1307
- }
1308
- }
1309
- if (piece.length > 0) pieces.push(...piece.map((token) => JSON.stringify([token])));
1310
- return pieces;
1311
- };
1312
- const insertedElementsOf = (change, document) => {
1313
- const elements = [];
1314
- const open = [];
1315
- let position = 0;
1316
- for (let index = 0; index < change.sections.length;) {
1317
- if (change.sections[index + 1] < 0) {
1318
- const length = change.sections[index];
1319
- const { closes, opens } = crossed(document, position, position + length);
1320
- open.length = Math.max(0, open.length - closes);
1321
- for (const _ of opens) open.push(null);
1322
- position += length;
1323
- index += 2;
1324
- continue;
1325
- }
1326
- const from = position;
1327
- const tokens = [];
1328
- while (index < change.sections.length && change.sections[index + 1] >= 0) {
1329
- position += change.sections[index];
1330
- tokens.push(...change.data[index >> 1]?.tokens ?? []);
1331
- index += 2;
1332
- }
1333
- const run = {
1334
- from,
1335
- to: position
1336
- };
1337
- for (const token of tokens) if (token.kind === "open") open.push(token.nodeKind === "element" ? {
1338
- props: token.props,
1339
- run
1340
- } : null);
1341
- else if (token.kind === "close") {
1342
- const element = open.pop();
1343
- if (element) elements.push({
1344
- close: run,
1345
- open: element.run,
1346
- props: element.props
1347
- });
1348
- }
1349
- }
1350
- return elements;
1351
- };
1352
- const touches = ({ from, to }, at) => from <= at && at <= to;
1353
- const insertsWithin = (inner, outer, innerReplacements, outerReplacements, document) => {
1354
- if (innerReplacements.length === 0 || innerReplacements.some(({ from, insert, to }) => from !== to || insert.length === 0)) return false;
1355
- if (!innerReplacements.every(({ from, insert }) => {
1356
- const around = outerReplacements.filter((replacement) => touches(replacement, from)).map((replacement) => JSON.stringify(replacement.insert.toJSON())).join("");
1357
- return piecesOf(insert).every((piece) => {
1358
- const [token, ...rest] = JSON.parse(piece);
1359
- return rest.length === 0 ? token.kind !== "text" && token.nodeKind === "element" : around.includes(piece.slice(1, -1));
1360
- });
1361
- })) return false;
1362
- const written = insertedElementsOf(outer, document);
1363
- return insertedElementsOf(inner, document).filter(({ close, open }) => open.from !== close.from).every((element) => written.some((other) => jsonEqual(other.props, element.props) && touches(other.open, element.open.from) && touches(other.close, element.close.from)));
1364
- };
1365
- const addsElementOrRetypesTo = (step, type) => {
1366
- for (let index = 0; index < step.sections.length; index += 2) {
1367
- const inserted = step.sections[index + 1];
1368
- const data = step.data[index >> 1];
1369
- if (inserted === -2 ? data.some((modification) => modification.key === "type" && modification.type === "set" && modification.value === type) : inserted > 0 && data.tokens.some((token) => token.kind === "open" && token.nodeKind === "element")) return true;
1370
- }
1371
- return false;
1372
- };
1373
- /** Whether `other` inserts strictly between the edges of a wrap in `wrap`. */
1374
- const addsInsideEnclosure = (wrap, other) => {
1375
- const leads = wrap.filter(({ insert }) => opensEnclosure(insert));
1376
- if (leads.length === 0) return false;
1377
- const from = Math.min(...leads.map((lead) => lead.from));
1378
- const to = Math.max(...wrap.map((edge) => edge.from));
1379
- return other.some((edit) => from < edit.from && edit.from < to);
1380
- };
1381
- const onlyAddsStructure = (replacements) => replacements.every(({ from, insert, to }) => from === to && insert.tokens.every((token) => token.kind !== "text"));
1382
- const sameDocumentStructure = (left, right) => left.length === right.length && left.every((node, index) => sameNodeStructure(node, right[index]));
1383
- const sameChangedChildren = (left, right, same) => left.size === right.size && left.changedChildren(right).every(([from, to, otherFrom, otherTo]) => {
1384
- if (to - from !== otherTo - otherFrom) return false;
1385
- for (let at = 0; at < to - from; at += 1) if (!same(getDefined(left.child(from + at)), getDefined(right.child(otherFrom + at)))) return false;
1386
- return true;
1387
- });
1388
- const mergeStructuralRunByPosition = (structural, concurrent, concurrentReplacements, before, afterStructural, afterConcurrent) => {
1389
- if (deletesBlocksAndInserts(before, concurrentReplacements)) return null;
1390
- let rebased = null;
1391
- let twin = false;
1392
- const structuralRanges = [];
1393
- const concurrentRanges = [];
1394
- structural.iterChangedRanges((from, to) => structuralRanges.push([from, to]));
1395
- concurrent.iterChangedRanges((from, to, fromB, toB) => concurrentRanges.push([
1396
- from,
1397
- to,
1398
- fromB,
1399
- toB
1400
- ]));
1401
- const childrenAt = (document, path) => {
1402
- if (path.length === 0) return document.value;
1403
- const node = document.node(path);
1404
- return isElementNode(node) ? node.children : [];
1405
- };
1406
- const childStartingAt = (path, position) => childrenAt(afterConcurrent, path).findIndex((_, index) => afterConcurrent.nodeRange([...path, index]).from === position);
1407
- const descendantStartingAt = (path, position) => {
1408
- const nodes = childrenAt(afterConcurrent, path);
1409
- for (let index = 0; index < nodes.length; index++) {
1410
- const { from, to } = afterConcurrent.nodeRange([...path, index]);
1411
- if (from === position) return [index];
1412
- if (from < position && position < to) {
1413
- const rest = descendantStartingAt([...path, index], position);
1414
- return rest && [index, ...rest];
1415
- }
1416
- }
1417
- return null;
1418
- };
1419
- const withNodeAt = (nodes, [index, ...rest], node) => {
1420
- const at = getDefined(index);
1421
- const current = nodes[at];
1422
- return nodes.with(at, rest.length === 0 || !isElementNode(current) ? node : {
1423
- ...current,
1424
- children: withNodeAt(current.children, rest, node)
1425
- });
1426
- };
1427
- const mergeAt = (path, concurrentPath) => {
1428
- const beforeNodes = childrenAt(before, path);
1429
- const structuralNodes = childrenAt(afterStructural, path);
1430
- const concurrentNodes = childrenAt(afterConcurrent, concurrentPath);
1431
- const shorter = Math.min(beforeNodes.length, structuralNodes.length);
1432
- const prefixOf = (limit) => {
1433
- let length = 0;
1434
- while (length < limit && jsonEqual(beforeNodes[length], structuralNodes[length])) length += 1;
1435
- return length;
1436
- };
1437
- const suffixOf = (limit) => {
1438
- let length = 0;
1439
- while (length < limit && jsonEqual(beforeNodes.at(-1 - length), structuralNodes.at(-1 - length))) length += 1;
1440
- return length;
1441
- };
1442
- const from = prefixOf(shorter);
1443
- const suffix = suffixOf(shorter - from);
1444
- const lowest = prefixOf(shorter - suffixOf(shorter));
1445
- const source = beforeNodes.slice(from, beforeNodes.length - suffix);
1446
- const replacement = structuralNodes.slice(from, structuralNodes.length - suffix);
1447
- if (source.length === 0 || sameDocumentStructure(source, replacement)) return null;
1448
- const [element] = source;
1449
- const range = before.nodeRange([...path, from]);
1450
- const rewritesOnlyOpenToken = (changeFrom, changeTo, fromB, toB) => changeFrom === range.from && changeTo === range.from + 1 && toB - fromB === 1;
1451
- if (source.length === 1 && replacement.length === 1 && isElementNode(element) && structuralRanges.every(([changeFrom, changeTo]) => range.from < changeFrom && changeTo < range.to) && concurrentRanges.every(([changeFrom, changeTo, fromB, toB]) => changeTo <= range.from || range.to <= changeFrom || range.from < changeFrom && changeTo < range.to || rewritesOnlyOpenToken(changeFrom, changeTo, fromB, toB))) {
1452
- const opened = concurrent.mapPos(range.from + 1, -1);
1453
- const at = opened === null ? null : descendantStartingAt(concurrentPath, opened - 1);
1454
- const kept = at && afterConcurrent.node([...concurrentPath, ...at]);
1455
- if (kept && isElementNode(kept) && kept.type === element.type) {
1456
- const children = mergeAt([...path, from], [...concurrentPath, ...at]);
1457
- if (children) return withNodeAt(concurrentNodes, at, {
1458
- ...kept,
1459
- children
1460
- });
1461
- }
1462
- }
1463
- const runRange = (at) => ({
1464
- from: before.nodeRange([...path, at]).from,
1465
- to: before.nodeRange([...path, at + source.length - 1]).to
1466
- });
1467
- const shift = source.length - replacement.length;
1468
- const tailMatches = [];
1469
- tailMatches[structuralNodes.length] = true;
1470
- for (let at = structuralNodes.length - 1; at >= lowest; at--) tailMatches[at] = tailMatches[at + 1] && jsonEqual(beforeNodes[at + shift], structuralNodes[at]);
1471
- const candidates = [];
1472
- for (let at = lowest; at <= from; at++) if (tailMatches[at + replacement.length]) candidates.push(at);
1473
- const rewrittenOpen = candidates.filter((at) => structuralRanges.some(([changeFrom, changeTo]) => changeFrom <= runRange(at).from && runRange(at).from < changeTo));
1474
- const touched = candidates.filter((at) => structuralRanges.some(([changeFrom, changeTo]) => changeFrom < runRange(at).to && runRange(at).from < changeTo));
1475
- const ownStarts = candidates.length === 1 ? candidates : rewrittenOpen.length ? rewrittenOpen : touched;
1476
- if (ownStarts.length !== 1) return null;
1477
- const [start] = ownStarts;
1478
- const { from: runFrom, to: runTo } = runRange(start);
1479
- const untouchedCopyAt = () => {
1480
- const position = concurrent.mapPos(runFrom, 1);
1481
- const untouched = concurrentRanges.every(([changeFrom, changeTo]) => changeTo <= runFrom || runTo <= changeFrom);
1482
- return position !== null && untouched ? childStartingAt(concurrentPath, position) : -1;
1483
- };
1484
- const match = untouchedCopyAt();
1485
- if (match === -1) return null;
1486
- const placed = structuralNodes.slice(start, start + replacement.length);
1487
- const merged = [...concurrentNodes];
1488
- merged.splice(match, source.length, ...placed);
1489
- const copyFrom = afterConcurrent.nodeRange([...concurrentPath, match]).from;
1490
- twin = candidates.length > 1;
1491
- rebased = structural.within(runFrom, runTo)?.embed(afterConcurrent.length, copyFrom) ?? (twin ? RootChange.betweenWhole(DocumentIndex.fromValue(concurrentNodes.slice(match, match + source.length)), DocumentIndex.fromValue(placed)).embed(afterConcurrent.length, copyFrom) : null);
1492
- return merged;
1493
- };
1494
- const merged = mergeAt([], []);
1495
- if (!merged) return null;
1496
- const document = DocumentIndex.fromValue(merged);
1497
- const lands = (change, from) => {
1498
- try {
1499
- return jsonEqual(change.apply(from).value, merged);
1500
- } catch {
1501
- return false;
1502
- }
1503
- };
1504
- const removedLength = (change) => {
1505
- let length = 0;
1506
- change.iterChangedRanges((from, to) => {
1507
- length += to - from;
1508
- });
1509
- return length;
1510
- };
1511
- const [rebasedChange] = [rebased, twin ? null : RootChange.betweenWhole(afterConcurrent, document)].filter((change) => change !== null && lands(change, afterConcurrent)).sort((left, right) => removedLength(left) - removedLength(right));
1512
- if (!rebasedChange) return null;
1513
- return {
1514
- merged: document,
1515
- other: [RootChange.transform(concurrent, structural).a, RootChange.transform(structural, concurrent).b].find((change) => lands(change, afterStructural)) ?? RootChange.betweenWhole(afterStructural, document),
1516
- rebased: rebasedChange
1517
- };
1518
- };
1519
- const mergeStructuralChangeAtStableSiblingRange = (before, afterStructural, afterConcurrent) => {
1520
- let from = 0;
1521
- while (from < before.value.length && from < afterStructural.value.length && jsonEqual(before.value[from], afterStructural.value[from])) from += 1;
1522
- let suffix = 0;
1523
- while (suffix < before.value.length - from && suffix < afterStructural.value.length - from && jsonEqual(before.value.at(-1 - suffix), afterStructural.value.at(-1 - suffix))) suffix += 1;
1524
- const source = before.value.slice(from, before.value.length - suffix);
1525
- const replacement = afterStructural.value.slice(from, afterStructural.value.length - suffix);
1526
- if (source.length === 0 || sameDocumentStructure(source, replacement)) return null;
1527
- let match = -1;
1528
- for (let index = 0; index <= afterConcurrent.value.length - source.length; index++) if (source.every((node, offset) => jsonEqual(node, afterConcurrent.value[index + offset]))) {
1529
- if (match !== -1) return null;
1530
- match = index;
1531
- }
1532
- if (match === -1) return null;
1533
- const merged = [...afterConcurrent.value];
1534
- merged.splice(match, source.length, ...replacement);
1535
- const document = DocumentIndex.fromValue(merged);
1536
- return {
1537
- merged: document,
1538
- other: RootChange.betweenWhole(afterStructural, document),
1539
- rebased: RootChange.betweenWhole(afterConcurrent, document)
1540
- };
1541
- };
1542
- const collectDocumentNodes = (nodes, parentPath = [], result = []) => {
1543
- nodes.forEach((node, index) => {
1544
- const path = [...parentPath, index];
1545
- result.push({
1546
- node,
1547
- path
1548
- });
1549
- if (isElementNode(node)) collectDocumentNodes(node.children, path, result);
1550
- });
1551
- return result;
1552
- };
1553
- const mergeNestedChangeThroughStructuralRelocation = (nested, structural, before, afterNested, afterStructural) => {
1554
- if (sameDocumentStructure(before.value, afterStructural.value) || nested.empty) return null;
1555
- const changedRanges = [];
1556
- nested.iterChangedRanges((from, to) => changedRanges.push([from, to]));
1557
- if (changedRanges.length === 0) return null;
1558
- const structuralRanges = [];
1559
- structural.iterChangedRanges((from, to) => structuralRanges.push([from, to]));
1560
- const afterNodes = collectDocumentNodes(afterStructural.value);
1561
- const candidates = collectDocumentNodes(before.value).filter(({ path }) => {
1562
- const range = before.nodeRange(path);
1563
- return changedRanges.every(([from, to]) => range.from <= from && to <= range.to) && nested.mapPos(range.from, -1) !== nested.mapPos(range.to, 1);
1564
- }).sort((left, right) => right.path.length - left.path.length);
1565
- let partial = null;
1566
- for (const candidate of candidates) {
1567
- const range = before.nodeRange(candidate.path);
1568
- if (structuralRanges.every(([from, to]) => to <= range.from || range.to <= from)) continue;
1569
- const targets = afterNodes.filter(({ node }) => jsonEqual(node, candidate.node));
1570
- if (targets.length !== 1) continue;
1571
- const end = range.to + nested.newLength - nested.length;
1572
- const parentPath = candidate.path.slice(0, -1);
1573
- const edited = [];
1574
- let at = range.from;
1575
- let index = candidate.path.at(-1) ?? 0;
1576
- let siblings = [];
1577
- try {
1578
- const parent = parentPath.length === 0 ? null : afterNested.node(parentPath);
1579
- siblings = parent === null ? afterNested.value : isElementNode(parent) ? parent.children : [];
1580
- for (; at < end && index < siblings.length; index++) {
1581
- const siblingRange = afterNested.nodeRange([...parentPath, index]);
1582
- if (siblingRange.from !== at) break;
1583
- edited.push(siblings[index]);
1584
- at = siblingRange.to;
1585
- }
1586
- } catch {
1587
- continue;
1588
- }
1589
- if (edited.length === 0 || at !== end && index < siblings.length) continue;
1590
- if (edited.some((node) => jsonEqual(node, candidate.node))) continue;
1591
- const targetPath = targets[0].path;
1592
- const targetIndex = targetPath.at(-1);
1593
- if (targetIndex === void 0) continue;
1594
- const merged = afterStructural.withSplicedNodes(targetPath.slice(0, -1), targetIndex, 1, edited);
1595
- if (at === end) return merged;
1596
- partial ??= merged;
1597
- }
1598
- return partial;
1599
- };
1600
- const deletesWholeSiblings = (document, replacement) => {
1601
- if (!replacement || replacement.insert.length > 0) return false;
1602
- const first = document.nodeStartingAt(replacement.from);
1603
- const end = document.childBoundaryAt(replacement.to);
1604
- if (!first || !end) return false;
1605
- const index = getDefined(first.path.at(-1));
1606
- return end.index > index && pathKey(first.path.slice(0, -1)) === pathKey(end.parentPath);
1607
- };
1608
- const deletesBlocksAndInserts = (document, replacements) => replacements.some((replacement) => deletesWholeSiblings(document, replacement)) && replacements.some(({ insert }) => insert.length > 0);
1609
- /**
1610
- * When `edit` only inserts inside the whole siblings `deletion` removes,
1611
- * finds each element `edit` inserts whose content is only removed tokens or
1612
- * such elements. Returns `edit` without those elements and the change that
1613
- * takes them out of `edit`'s output, or null when there are none or an
1614
- * insert does not nest whole between the deleted tokens. It reads which
1615
- * tokens are original, never their letters.
1616
- */
1617
- const wrapsInsideDeletion = (document, deletion, edit) => {
1618
- const inserts = [];
1619
- let position = 0;
1620
- for (let index = 0; index < edit.sections.length; index += 2) {
1621
- const length = edit.sections[index];
1622
- const from = position;
1623
- position += length;
1624
- if (edit.sections[index + 1] < 0) continue;
1625
- if (length > 0) {
1626
- if (from < deletion.to && position > deletion.from) return null;
1627
- continue;
1628
- }
1629
- if (deletion.from <= from && from <= deletion.to) inserts.push({
1630
- at: from,
1631
- section: index,
1632
- tokens: edit.data[index >> 1].tokens
1633
- });
1634
- }
1635
- if (inserts.length === 0) return null;
1636
- const absorbed = /* @__PURE__ */ new Map();
1637
- const stack = [{
1638
- holdsKept: false,
1639
- holdsRemoved: false,
1640
- open: null
1641
- }];
1642
- const visit = (token, origin) => {
1643
- const top = getDefined(stack.at(-1));
1644
- if (token.kind === "text") {
1645
- if (origin) top.holdsKept = true;
1646
- else top.holdsRemoved = true;
1647
- return true;
1648
- }
1649
- if (token.kind === "open") {
1650
- stack.push({
1651
- holdsKept: false,
1652
- holdsRemoved: false,
1653
- open: origin
1654
- });
1655
- return true;
1656
- }
1657
- if (stack.length === 1) return false;
1658
- const frame = getDefined(stack.pop());
1659
- const parent = getDefined(stack.at(-1));
1660
- if (!frame.open && !origin) {
1661
- parent.holdsRemoved = true;
1662
- parent.holdsKept ||= frame.holdsKept;
1663
- } else if (frame.open && origin && token.nodeKind === "element" && frame.holdsRemoved && !frame.holdsKept) {
1664
- for (const [section, index] of [frame.open, origin]) {
1665
- const peeled = absorbed.get(section) ?? /* @__PURE__ */ new Set();
1666
- peeled.add(index);
1667
- absorbed.set(section, peeled);
1668
- }
1669
- parent.holdsRemoved = true;
1670
- } else parent.holdsKept = true;
1671
- return true;
1672
- };
1673
- let next = 0;
1674
- const visitInsertsUpTo = (at) => {
1675
- for (; next < inserts.length && inserts[next].at <= at; next += 1) {
1676
- const { section, tokens } = inserts[next];
1677
- if (inserts[next].at < at) return false;
1678
- for (let index = 0; index < tokens.length; index += 1) if (!visit(tokens[index], [section, index])) return false;
1679
- }
1680
- return true;
1681
- };
1682
- let at = deletion.from;
1683
- for (const token of document.slice(deletion.from, deletion.to).tokens) {
1684
- if (!visitInsertsUpTo(at) || !visit(token, null)) return null;
1685
- at += tokenLength(token);
1686
- }
1687
- if (!visitInsertsUpTo(at) || stack.length !== 1 || absorbed.size === 0) return null;
1688
- const sections = [];
1689
- const data = [];
1690
- const unwrapSections = [];
1691
- const unwrapData = [];
1692
- for (let index = 0; index < edit.sections.length; index += 2) {
1693
- const length = edit.sections[index];
1694
- const inserted = edit.sections[index + 1];
1695
- const value = edit.data[index >> 1];
1696
- const peeled = absorbed.get(index);
1697
- if (!peeled) {
1698
- addSection(sections, data, length, inserted, value);
1699
- addSection(unwrapSections, unwrapData, inserted < 0 ? length : inserted, -1, null);
1700
- continue;
1701
- }
1702
- const slice = value;
1703
- const { tokens } = slice;
1704
- const keptTokens = [];
1705
- const keptAt = /* @__PURE__ */ new Map();
1706
- let start = 0;
1707
- let peeledLength = 0;
1708
- tokens.forEach((token, tokenIndex) => {
1709
- if (peeled.has(tokenIndex)) peeledLength += tokenLength(token);
1710
- else {
1711
- keptTokens.push(token);
1712
- keptAt.set(start, start - peeledLength);
1713
- }
1714
- start += tokenLength(token);
1715
- });
1716
- const nodeKeys = /* @__PURE__ */ new Map();
1717
- for (const [keyAt, key] of getDocumentSliceNodeKeys(slice)) {
1718
- const to = keptAt.get(keyAt);
1719
- if (to !== void 0) nodeKeys.set(to, key);
1720
- }
1721
- const kept = PreparedTokenSlice.fromTokens(keptTokens).withNodeKeys(nodeKeys);
1722
- addSection(sections, data, length, kept.length, kept);
1723
- tokens.forEach((token, offset) => {
1724
- if (peeled.has(offset)) addSection(unwrapSections, unwrapData, 1, 0, PreparedTokenSlice.empty);
1725
- else addSection(unwrapSections, unwrapData, tokenLength(token), -1, null);
1726
- });
1727
- }
1728
- return {
1729
- stripped: RootChange.fromSections(sections, data),
1730
- unwrap: RootChange.fromSections(unwrapSections, unwrapData)
1731
- };
1732
- };
1733
- const keepsElementsWhole = (document, change) => {
1734
- let from = 0;
1735
- for (let index = 0; index < change.sections.length; index += 2) {
1736
- const length = change.sections[index];
1737
- if (change.sections[index + 1] >= 0) {
1738
- const to = from + length;
1739
- let depth = 0;
1740
- if (length > 0 && document.nodeRangesTouching(from, to).some((range) => range.kind === "element" && (range.contentFrom > from || range.contentTo < to))) return false;
1741
- for (const token of change.data[index >> 1].tokens) {
1742
- if (token.kind === "text" || token.nodeKind === "text") continue;
1743
- depth += token.kind === "open" ? 1 : -1;
1744
- if (depth < 0) return false;
1745
- }
1746
- if (depth !== 0) return false;
1747
- }
1748
- from += length;
1749
- }
1750
- return true;
1751
- };
1752
- const transformMixedEditOverSiblingRemoval = (a, b, aReplacements, bReplacements, document, afterA, afterB) => {
1753
- for (const [removal, edit, replacements, side] of [[
1754
- b,
1755
- a,
1756
- bReplacements,
1757
- "b"
1758
- ], [
1759
- a,
1760
- b,
1761
- aReplacements,
1762
- "a"
1763
- ]]) {
1764
- const [removed] = replacements;
1765
- if (replacements.length !== 1 || !deletesWholeSiblings(document, removed)) continue;
1766
- const parts = edit.partition(removed.from, removed.to - 1);
1767
- const from = edit.mapPos(removed.from, 1);
1768
- const to = edit.mapPos(removed.to, -1);
1769
- if (!parts || parts.inside.empty || parts.outside.empty || !keepsElementsWhole(document, parts.outside) || from === null || to === null) continue;
1770
- const [afterEdit, afterRemoval] = side === "b" ? [afterA, afterB] : [afterB, afterA];
1771
- const kept = RootChange.transform(parts.outside, removal).a;
1772
- const merged = kept.apply(afterRemoval);
1773
- const removalAfterEdit = RootChange.create(afterEdit, {
1774
- from,
1775
- to
1776
- });
1777
- const removedAfterEdit = removalAfterEdit.compose(RootChange.betweenWhole(removalAfterEdit.apply(afterEdit), merged));
1778
- return side === "b" ? {
1779
- a: kept,
1780
- b: removedAfterEdit
1781
- } : {
1782
- a: removedAfterEdit,
1783
- b: kept
1784
- };
1785
- }
1786
- return null;
1787
- };
1788
- /**
1789
- * Transform a deletion of whole siblings by position alone against an edit
1790
- * whose wrappers hold only what it deletes, and take those wrappers with it.
1791
- * Null leaves the pair, wrappers included, to the value repairs.
1792
- */
1793
- const transformByPositionOverAbsorbedWraps = (a, b, aReplacements, bReplacements, document, replayBase, readBack) => {
1794
- for (const side of ["a", "b"]) {
1795
- const [replacements, edit] = side === "a" ? [aReplacements, b] : [bReplacements, a];
1796
- const [deletion] = replacements;
1797
- if (replacements.length !== 1 || !deletesWholeSiblings(document, deletion)) continue;
1798
- const wraps = wrapsInsideDeletion(document, deletion, edit);
1799
- if (!wraps) continue;
1800
- const inner = side === "a" ? RootChange.transform(a, wraps.stripped, replayBase, readBack) : RootChange.transform(wraps.stripped, b, replayBase, readBack);
1801
- const [afterInnerA, afterInnerB] = side === "a" ? [a.apply(document), wraps.stripped.apply(document)] : [wraps.stripped.apply(document), b.apply(document)];
1802
- if (!convergesOn(inner, afterInnerA, afterInnerB)) continue;
1803
- return side === "a" ? {
1804
- a: wraps.unwrap.compose(inner.a),
1805
- b: inner.b
1806
- } : {
1807
- a: inner.a,
1808
- b: wraps.unwrap.compose(inner.b)
1809
- };
1810
- }
1811
- return null;
1812
- };
1813
- const SECTION_ENDS = /* @__PURE__ */ new WeakMap();
1814
- /**
1815
- * The sections from `before` to `after` that keep every letter and element
1816
- * token, rewriting only the leaf tokens between them; null when the two hold
1817
- * other letters or element tokens.
1818
- */
1819
- const alignLetters = (before, after) => {
1820
- const left = before.tokens;
1821
- const right = after.tokens;
1822
- const sections = [];
1823
- const data = [];
1824
- let leftToken = 0;
1825
- let rightToken = 0;
1826
- let leftLetter = 0;
1827
- let rightLetter = 0;
1828
- let rightPosition = 0;
1829
- for (;;) {
1830
- const leftGap = leftToken;
1831
- const rightGap = rightToken;
1832
- const gapFrom = rightPosition;
1833
- while (leftToken < left.length && isLeafToken(left[leftToken])) leftToken += 1;
1834
- while (rightToken < right.length && isLeafToken(right[rightToken])) {
1835
- rightToken += 1;
1836
- rightPosition += 1;
1837
- }
1838
- const leftLength = leftToken - leftGap;
1839
- const rightLength = rightToken - rightGap;
1840
- if (leftLength === rightLength && left.slice(leftGap, leftToken).every((token, at) => tokensEqual(token, right[rightGap + at]))) addSection(sections, data, leftLength, -1, null);
1841
- else addSection(sections, data, leftLength, rightLength, after.slice(gapFrom, rightPosition));
1842
- if (leftToken === left.length || rightToken === right.length) return leftToken === left.length && rightToken === right.length ? {
1843
- data,
1844
- sections
1845
- } : null;
1846
- const leftAnchor = left[leftToken];
1847
- const rightAnchor = right[rightToken];
1848
- if (leftAnchor.kind === "text" && rightAnchor.kind === "text") {
1849
- const length = Math.min(leftAnchor.text.length - leftLetter, rightAnchor.text.length - rightLetter);
1850
- if (leftAnchor.text.slice(leftLetter, leftLetter + length) !== rightAnchor.text.slice(rightLetter, rightLetter + length)) return null;
1851
- addSection(sections, data, length, -1, null);
1852
- leftLetter += length;
1853
- rightLetter += length;
1854
- rightPosition += length;
1855
- if (leftLetter === leftAnchor.text.length) {
1856
- leftToken += 1;
1857
- leftLetter = 0;
1858
- }
1859
- if (rightLetter === rightAnchor.text.length) {
1860
- rightToken += 1;
1861
- rightLetter = 0;
1862
- }
1863
- } else if (leftLetter === 0 && rightLetter === 0 && tokensEqual(leftAnchor, rightAnchor)) {
1864
- addSection(sections, data, 1, -1, null);
1865
- leftToken += 1;
1866
- rightToken += 1;
1867
- rightPosition += 1;
1868
- } else return null;
1869
- }
1870
- };
1871
- /** An open or close of a text leaf, which holds no letter of its own. */
1872
- const isLeafToken = (token) => token.kind !== "text" && token.nodeKind === "text";
1873
- const sectionEndsOf = (change) => {
1874
- let ends = SECTION_ENDS.get(change);
1875
- if (!ends) {
1876
- const count = change.sections.length / 2;
1877
- const startA = new Float64Array(count);
1878
- const startB = new Float64Array(count);
1879
- const endA = new Float64Array(count);
1880
- const endB = new Float64Array(count);
1881
- let a = 0;
1882
- let b = 0;
1883
- for (let section = 0; section < count; section++) {
1884
- const length = change.sections[section * 2];
1885
- const inserted = change.sections[section * 2 + 1];
1886
- startA[section] = a;
1887
- startB[section] = b;
1888
- a += length;
1889
- b += inserted < 0 ? length : inserted;
1890
- endA[section] = a;
1891
- endB[section] = b;
1892
- }
1893
- ends = {
1894
- endA,
1895
- endB,
1896
- startA,
1897
- startB
1898
- };
1899
- SECTION_ENDS.set(change, ends);
1900
- }
1901
- return ends;
1902
- };
1903
- /** The first section whose end, in `ends`, is past `position` (or at it). */
1904
- const firstSectionEnding = (ends, position, inclusive) => {
1905
- let low = 0;
1906
- let high = ends.length;
1907
- while (low < high) {
1908
- const middle = low + high >> 1;
1909
- if (inclusive ? ends[middle] < position : ends[middle] <= position) low = middle + 1;
1910
- else high = middle;
1911
- }
1912
- return low;
1913
- };
1914
- /**
1915
- * Whether a section that replaces content covers `position`, read in the
1916
- * change's input (`before`) or output (`after`) coordinates.
1917
- *
1918
- * @internal
1919
- */
1920
- const isRootChangePositionReplaced = (change, position, side) => {
1921
- const ends = sectionEndsOf(change);
1922
- const section = firstSectionEnding(side === "before" ? ends.endA : ends.endB, position, false);
1923
- if (section >= ends.endA.length) return false;
1924
- const start = side === "before" ? ends.startA[section] : ends.startB[section];
1925
- return change.sections[section * 2 + 1] >= 0 && start <= position;
1926
- };
1927
- const CHANGED_RANGES = /* @__PURE__ */ new WeakMap();
1928
- /**
1929
- * Whether one of the change's changed ranges, as `iterChangedRanges` merges
1930
- * them, covers `from` to `to` in its input.
1931
- *
1932
- * @internal
1933
- */
1934
- const isRootChangeRangeReplaced = (change, from, to) => {
1935
- let ranges = CHANGED_RANGES.get(change);
1936
- if (!ranges) {
1937
- const starts = [];
1938
- const ends = [];
1939
- change.iterChangedRanges((fromA, toA) => {
1940
- starts.push(fromA);
1941
- ends.push(toA);
1942
- });
1943
- ranges = {
1944
- fromA: Float64Array.from(starts),
1945
- toA: Float64Array.from(ends)
1946
- };
1947
- CHANGED_RANGES.set(change, ranges);
1948
- }
1949
- const after = firstSectionEnding(ranges.fromA, from, false);
1950
- return after > 0 && ranges.toA[after - 1] >= to;
1951
- };
1952
- /**
1953
- * The input token runs the change keeps for output tokens `from` to `to`, in
1954
- * order: each run is the same tokens in the input, starting at `at`, so the
1955
- * output tokens a replacement wrote have no run. Walks only the sections that
1956
- * reach the range.
1957
- *
1958
- * @internal
1959
- */
1960
- const keptRunsOf = (change, from, to) => {
1961
- const ends = sectionEndsOf(change);
1962
- const runs = [];
1963
- for (let section = firstSectionEnding(ends.endB, from, false); section < ends.endB.length && ends.startB[section] < to; section++) {
1964
- if (change.sections[section * 2 + 1] >= 0) continue;
1965
- const start = Math.max(from, ends.startB[section]);
1966
- const end = Math.min(to, ends.endB[section]);
1967
- if (start < end) runs.push({
1968
- at: ends.startA[section] + start - ends.startB[section],
1969
- from: start,
1970
- to: end
1971
- });
1972
- }
1973
- return runs;
1974
- };
1975
- const sortJoiningInsertions = (replacements) => {
1976
- const sorted = [];
1977
- for (const replacement of [...replacements].sort((left, right) => left.from - right.from)) {
1978
- const previous = sorted.at(-1);
1979
- if (previous && previous.from === previous.to && previous.to === replacement.from) sorted[sorted.length - 1] = {
1980
- from: previous.from,
1981
- insert: previous.insert.concat(replacement.insert),
1982
- to: replacement.to
1983
- };
1984
- else sorted.push(replacement);
1985
- }
1986
- return sorted;
1987
- };
1988
- /**
1989
- * Map an output position back to the input, as `change.invert(before).mapPos`
1990
- * would, without copying the content the change replaced.
1991
- *
1992
- * @internal
1993
- */
1994
- const mapRootChangePositionBackward = (change, position, assoc = -1, track) => {
1995
- const ends = sectionEndsOf(change);
1996
- const first = firstSectionEnding(ends.endB, position, true);
1997
- let positionB = first < ends.startB.length ? ends.startB[first] : change.newLength;
1998
- let positionA = first < ends.startA.length ? ends.startA[first] : change.length;
1999
- for (let index = first * 2; index < change.sections.length;) {
2000
- const length = change.sections[index];
2001
- const inserted = change.sections[index + 1];
2002
- index += 2;
2003
- if (inserted < 0) {
2004
- const endB = positionB + length;
2005
- if (endB > position) return positionA + position - positionB;
2006
- positionA += length;
2007
- positionB = endB;
2008
- continue;
2009
- }
2010
- const endB = positionB + inserted;
2011
- if (track && endB >= position && (track === "around" && positionB < position && endB > position || track === "before" && positionB < position || track === "after" && endB > position)) return null;
2012
- if (endB > position || endB === position && assoc < 0 && inserted === 0) return position === positionB || assoc < 0 ? positionA : positionA + length;
2013
- positionA += length;
2014
- positionB = endB;
2015
- }
2016
- if (position > positionB) throw new RangeError(`Position ${position} exceeds RootChange output length ${positionB}.`);
2017
- return positionA;
2018
- };
2019
- const childStart = (document, child) => child < document.size ? document.nodeRange([child]).from : document.length;
2020
- var RootChange = class RootChange {
2021
- data;
2022
- length;
2023
- newLength;
2024
- sections;
2025
- constructor(sections, data) {
2026
- this.sections = Object.freeze(sections);
2027
- this.data = Object.freeze(data);
2028
- this.length = this.sections.reduce((length, value, index) => index % 2 === 0 ? length + value : length, 0);
2029
- this.newLength = this.sections.reduce((length, value, index) => {
2030
- if (index % 2 === 0) return length;
2031
- return length + (value < 0 ? this.sections[index - 1] : value);
2032
- }, 0);
2033
- Object.freeze(this);
2034
- }
2035
- static create(document, changes) {
2036
- const ordered = (Array.isArray(changes) ? changes : [changes]).map((change, index) => ({
2037
- ...change,
2038
- index
2039
- })).sort((left, right) => left.from - right.from || left.index - right.index);
2040
- const sections = [];
2041
- const data = [];
2042
- let position = 0;
2043
- for (const change of ordered) {
2044
- const to = change.to ?? (change.properties === void 0 ? change.from : change.from + 1);
2045
- if (!Number.isInteger(change.from) || !Number.isInteger(to) || change.from < position || to < change.from || to > document.length) throw new RangeError(`Invalid or overlapping change range ${change.from}-${to}.`);
2046
- if (change.insert && change.properties) throw new Error("A document change section cannot replace content and modify properties.");
2047
- if (change.from > position) addSection(sections, data, change.from - position, -1, null);
2048
- if (change.properties) {
2049
- if (!document.nodeStartingAt(change.from) || to !== change.from + 1) throw new Error("Node property delta must target one open node token.");
2050
- const modifications = normalizePropertyDelta(change.properties);
2051
- addSection(sections, data, 1, modifications.length > 0 ? -2 : -1, modifications.length > 0 ? modifications : null);
2052
- position = to;
2053
- continue;
2054
- }
2055
- const insert = change.insert ?? PreparedTokenSlice.empty;
2056
- addSection(sections, data, to - change.from, insert.length, insert);
2057
- position = to;
2058
- }
2059
- if (position < document.length) addSection(sections, data, document.length - position, -1, null);
2060
- return new RootChange(sections, data);
2061
- }
2062
- static betweenChangedBlocks(before, after, options = {}) {
2063
- const ranges = before.changedChildren(after);
2064
- const first = ranges[0];
2065
- const last = ranges.at(-1);
2066
- if (!first || !last) return RootChange.empty(before.length);
2067
- if (first[0] === 0 && last[1] === before.size && last[3] === after.size) return RootChange.betweenWhole(before, after, options);
2068
- return RootChange.betweenWhole(DocumentIndex.fromIndexedNodes(before.nodes.slice(first[0], last[1])), DocumentIndex.fromIndexedNodes(after.nodes.slice(first[2], last[3])), {
2069
- ...options,
2070
- offset: first[0]
2071
- }).embed(before.length, childStart(before, first[0]));
2072
- }
2073
- static betweenWhole(before, after, options = {}) {
2074
- if (jsonEqual(before.value, after.value)) return RootChange.empty(before.length);
2075
- const beforeTokens = before.tokens;
2076
- const afterTokens = after.tokens;
2077
- if (beforeTokens.length === afterTokens.length && beforeTokens.tokens.length === afterTokens.tokens.length && beforeTokens.tokens.every((token, index) => {
2078
- const next = afterTokens.tokens[index];
2079
- if (!next || token.kind !== next.kind) return false;
2080
- if (token.kind === "text" && next.kind === "text") return token.text === next.text;
2081
- if (token.kind === "open" && next.kind === "open") return token.nodeKind === next.nodeKind;
2082
- return token.kind === "close" && next.kind === "close" && token.nodeKind === next.nodeKind;
2083
- })) {
2084
- const changes = beforeTokens.tokens.flatMap((token, index) => {
2085
- const next = afterTokens.tokens[index];
2086
- if (token.kind !== "open" || next.kind !== "open" || jsonEqual(token.props, next.props)) return [];
2087
- const entry = before.nodeStartingAt(beforeTokens.offsets[index]);
2088
- if (!entry) throw new Error("Cannot resolve changed node properties.");
2089
- const node = before.node(entry.path);
2090
- const context = getDocumentPropertyContext(before, entry.path, options.root ?? null, options.offset);
2091
- const modifications = betweenPropertyModifications(token.props, next.props, (key) => options.isSetValued?.(node, key, context) ?? false, options.emptySetsAsValues);
2092
- return modifications.length === 0 ? [] : [{
2093
- from: beforeTokens.offsets[index],
2094
- properties: propertyDeltaFromModifications(modifications),
2095
- to: beforeTokens.offsets[index] + 1
2096
- }];
2097
- });
2098
- return RootChange.create(before, changes);
2099
- }
2100
- const from = commonPrefixLength(beforeTokens.tokens, afterTokens.tokens);
2101
- const suffix = commonSuffixLength(before.tokens.tokens, after.tokens.tokens, Math.min(before.length, after.length) - from);
2102
- const flat = RootChange.create(before, {
2103
- from,
2104
- insert: after.slice(from, after.length - suffix),
2105
- to: before.length - suffix
2106
- });
2107
- const aligned = createStructurallyAlignedChanges(before, after, options);
2108
- return aligned ? RootChange.create(before, aligned) : flat;
2109
- }
2110
- /**
2111
- * The change from `before` to `after` that keeps every letter and element
2112
- * token and rewrites only the text-leaf tokens around them, so a change of
2113
- * marks or leaf splits keeps what each letter is; null when the two hold
2114
- * other letters or element tokens, or the same in another order.
2115
- */
2116
- static aligned(before, after) {
2117
- const ranges = before.changedChildren(after);
2118
- const first = ranges[0];
2119
- const last = ranges.at(-1);
2120
- if (!first || !last) return RootChange.empty(before.length);
2121
- const from = childStart(before, first[0]);
2122
- const to = childStart(before, last[1]);
2123
- const window = alignLetters(before.slice(from, to), after.slice(childStart(after, first[2]), childStart(after, last[3])));
2124
- if (!window) return null;
2125
- const sections = [];
2126
- const data = [];
2127
- addSection(sections, data, from, -1, null);
2128
- for (let index = 0; index < window.sections.length; index += 2) addSection(sections, data, window.sections[index], window.sections[index + 1], window.data[index >> 1]);
2129
- addSection(sections, data, before.length - to, -1, null);
2130
- return new RootChange(sections, data);
2131
- }
2132
- static empty(length) {
2133
- return length === 0 ? new RootChange([], []) : new RootChange([length, -1], [null]);
2134
- }
2135
- /**
2136
- * Lift this change from a token window into its parent document.
2137
- *
2138
- * @internal
2139
- */
2140
- embed(length, offset) {
2141
- if (!Number.isSafeInteger(length) || !Number.isSafeInteger(offset) || offset < 0 || offset + this.length > length) throw new RangeError("Cannot embed a change outside its document.");
2142
- const sections = [];
2143
- const data = [];
2144
- addSection(sections, data, offset, -1, null);
2145
- for (let index = 0, dataIndex = 0; index < this.sections.length; dataIndex++) {
2146
- const innerLength = this.sections[index];
2147
- const inserted = this.sections[index + 1];
2148
- index += 2;
2149
- addSection(sections, data, innerLength, inserted, this.data[dataIndex]);
2150
- }
2151
- addSection(sections, data, length - offset - this.length, -1, null);
2152
- return new RootChange(sections, data);
2153
- }
2154
- /**
2155
- * Split this change into its edits inside `from..to` and its edits outside,
2156
- * each over the same document. An insertion at `from` is outside and one at
2157
- * `to` is inside. Null when an edit crosses either boundary.
2158
- */
2159
- partition(from, to) {
2160
- const inside = [];
2161
- const insideData = [];
2162
- const outside = [];
2163
- const outsideData = [];
2164
- let at = 0;
2165
- for (let index = 0, dataIndex = 0; index < this.sections.length; index += 2, dataIndex++) {
2166
- const length = this.sections[index];
2167
- const inserted = this.sections[index + 1];
2168
- const value = this.data[dataIndex];
2169
- const end = at + length;
2170
- if (inserted === -1) {
2171
- addSection(inside, insideData, length, -1, null);
2172
- addSection(outside, outsideData, length, -1, null);
2173
- } else if (length > 0 ? at >= from && end <= to : at > from && at <= to) {
2174
- addSection(inside, insideData, length, inserted, value);
2175
- addSection(outside, outsideData, length, -1, null);
2176
- } else if (end <= from || at >= to) {
2177
- addSection(inside, insideData, length, -1, null);
2178
- addSection(outside, outsideData, length, inserted, value);
2179
- } else return null;
2180
- at = end;
2181
- }
2182
- return {
2183
- inside: new RootChange(inside, insideData),
2184
- outside: new RootChange(outside, outsideData)
2185
- };
2186
- }
2187
- /**
2188
- * This change's part inside `from` to `to` of its document, as a change to
2189
- * that window, the inverse of `embed`. Null when a section that changes
2190
- * content does not lie inside the window; an insertion at either end lies
2191
- * inside.
2192
- *
2193
- * @internal
2194
- */
2195
- within(from, to) {
2196
- const sections = [];
2197
- const data = [];
2198
- let at = 0;
2199
- for (let index = 0, dataIndex = 0; index < this.sections.length; index += 2, dataIndex++) {
2200
- const length = this.sections[index];
2201
- const inserted = this.sections[index + 1];
2202
- const end = at + length;
2203
- if (inserted === -1) addSection(sections, data, Math.max(0, Math.min(end, to) - Math.max(at, from)), -1, null);
2204
- else if (at < from || end > to) return null;
2205
- else addSection(sections, data, length, inserted, this.data[dataIndex]);
2206
- at = end;
2207
- }
2208
- return new RootChange(sections, data);
2209
- }
2210
- static fromJSON(json) {
2211
- assertEditorJsonValue(json, "RootChange JSON");
2212
- if (!Array.isArray(json)) throw new Error("Invalid RootChange JSON.");
2213
- const sections = [];
2214
- const data = [];
2215
- const joins = [];
2216
- for (const section of json) {
2217
- if (!isRecord(section) || typeof section.length !== "number" || !Number.isSafeInteger(section.length) || section.length < 0) throw new Error("Invalid RootChange JSON.");
2218
- if (section.replacement !== void 0 && section.properties !== void 0) throw new Error("Invalid RootChange JSON.");
2219
- if (section.properties !== void 0) {
2220
- if (section.length !== 1) throw new Error("Invalid RootChange JSON.");
2221
- const modifications = propertyModificationsFromJSON(section.properties);
2222
- if (modifications.length === 0) throw new Error("Invalid property delta JSON.");
2223
- addSection(sections, data, 1, -2, modifications, false, joins);
2224
- } else if (section.replacement === void 0) addSection(sections, data, section.length, -1, null, false, joins);
2225
- else {
2226
- if (!Array.isArray(section.replacement)) throw new Error("Invalid RootChange JSON.");
2227
- const replacement = PreparedTokenSlice.fromJSON(section.replacement);
2228
- addSection(sections, data, section.length, replacement.length, replacement, false, joins);
2229
- }
2230
- }
2231
- flushJoins(data, joins);
2232
- return new RootChange(sections, data);
2233
- }
2234
- static fromSections(sections, data) {
2235
- return new RootChange([...sections], [...data]);
2236
- }
2237
- static transform(a, b, replayBase, readBack = null) {
2238
- return {
2239
- a: transformChange(a, b, true, replayBase, readBack),
2240
- b: transformChange(b, a, false, replayBase, readBack)
2241
- };
2242
- }
2243
- static carryAcrossMove(a, b, document, options, runMoves) {
2244
- if (changedRangesAreSeparated(a, b)) return null;
2245
- const [aMove, bMove] = runMoves();
2246
- if (aMove && bMove) return null;
2247
- if (bMove) {
2248
- const carried = RootChange.carryEditAcrossMove(a, b, bMove, document, options, true);
2249
- return carried && {
2250
- a: carried.edit,
2251
- b: carried.move
2252
- };
2253
- }
2254
- if (aMove) {
2255
- const carried = RootChange.carryEditAcrossMove(b, a, aMove, document, options, false);
2256
- return carried && {
2257
- a: carried.move,
2258
- b: carried.edit
2259
- };
2260
- }
2261
- return null;
2262
- }
2263
- static carryEditAcrossMove(edit, moveChange, move, document, options, editIsA) {
2264
- if (move.count !== 1 || pathKey(move.path) === pathKey(move.targetPath) || !isElementNode(document.node(move.path)) || moveChange.propertyChanges().length > 0) return null;
2265
- const parts = edit.partition(move.from, move.to - 1);
2266
- if (!parts || parts.inside.empty || !deletesAcrossLandingOnly(parts.outside, move)) return null;
2267
- const afterInside = parts.inside.apply(document);
2268
- const moved = moveChangeAfterEdit(afterInside, move, parts.inside);
2269
- if (!moved) return null;
2270
- const carried = getDefined(parts.inside.within(move.from, move.to - 1)).embed(moveChange.newLength, move.fromAfterMove);
2271
- const outside = RootChange.transform(parts.outside, parts.inside).a.withEmptyLinesRemoved(afterInside);
2272
- const rest = editIsA ? RootChange.transformInDocument(outside, moved, afterInside, options) : RootChange.transformInDocument(moved, outside, afterInside, options);
2273
- if (rest.keptWrap) return null;
2274
- const outsideAfterMove = editIsA ? rest.a : rest.b;
2275
- const moveAfterEdit = editIsA ? rest.b : rest.a;
2276
- const residualReplacements = moveAfterEdit.replacements();
2277
- const residual = residualReplacements.length === 2 && siblingRunMove(edit.apply(document), residualReplacements);
2278
- return {
2279
- edit: carried.compose(outsideAfterMove),
2280
- move: residual && pathKey(residual.path) === pathKey(residual.targetPath) ? RootChange.empty(moveAfterEdit.length) : moveAfterEdit
2281
- };
2282
- }
2283
- withEmptyLinesRemoved(document) {
2284
- const replacements = this.replacements();
2285
- const properties = this.propertyChanges();
2286
- const sections = [...replacements];
2287
- let changed = false;
2288
- replacements.forEach((join, index) => {
2289
- const removal = emptyLineRemovalFor(document, join);
2290
- if (!removal) return;
2291
- const typed = replacements.filter((other) => other !== join && meets(removal, other));
2292
- const moved = typingMovedToJoinStart(join, typed);
2293
- if (!moved) return;
2294
- sections[index] = removal;
2295
- moved.forEach((replacement, at) => {
2296
- sections[replacements.indexOf(getDefined(typed[at]))] = replacement;
2297
- });
2298
- changed = true;
2299
- });
2300
- if (!changed) return this;
2301
- return RootChange.create(document, [...sections, ...properties.map(({ from, modifications, to }) => ({
2302
- from,
2303
- properties: propertyDeltaFromModifications(modifications),
2304
- to
2305
- }))]);
2306
- }
2307
- /**
2308
- * With `replay`, `b` is a recorded step replayed over `a`: a wrap of `a`
2309
- * equal to its own stays its own, and a wrap a split cuts gives each next
2310
- * piece the properties `replay.pieceProps` returns.
2311
- */
2312
- static transformInDocument(a, b, document, { crossedMoves, keepEqualEdits = false, keepEqualInserts = keepEqualEdits, keepEqualMoves = keepEqualEdits, replay } = {}) {
2313
- const settings = {
2314
- crossedMoves,
2315
- keepEqualInserts,
2316
- keepEqualMoves,
2317
- replay
2318
- };
2319
- const replayBase = replay && document;
2320
- let runMoves;
2321
- const readRunMoves = () => runMoves ??= [siblingRunMove(document, a.replacements()), siblingRunMove(document, b.replacements())];
2322
- const acrossMove = RootChange.carryAcrossMove(a, b, document, settings, readRunMoves);
2323
- if (acrossMove) return acrossMove;
2324
- const readBack = replay?.readBack ?? null;
2325
- const inMovedLine = replay?.carriesLift && editsInMovedLine(a, b, document) ? rebaseOverLift(a, b, document, settings) : null;
2326
- if (inMovedLine) {
2327
- markReadBack(readBack);
2328
- return inMovedLine;
2329
- }
2330
- const joined = rebaseOverJoins(a, b, document, replayBase, readBack);
2331
- if (joined) return joined;
2332
- const pieces = rebaseOverPieces(a, b, document, replay?.pieceProps, replayBase);
2333
- if (pieces) return pieces;
2334
- if (changedRangesAreSeparated(a, b)) return RootChange.transform(a, b, replayBase, readBack);
2335
- const aReplacements = a.replacements();
2336
- const bReplacements = b.replacements();
2337
- const wrapGoesWithReplaced = (wrapping, other) => {
2338
- const rest = propertyWritesOf(wrapping);
2339
- const over = rest.propertyChanges().length === 0 ? {
2340
- a: RootChange.empty(other.newLength),
2341
- b: other
2342
- } : RootChange.transformInDocument(rest, other, document, settings);
2343
- markReadBack(readBack);
2344
- return {
2345
- kept: over.a,
2346
- other: wrapping.invert(document).compose(rest).compose(over.b)
2347
- };
2348
- };
2349
- if (readBack && wrapsInsideReplacement(aReplacements, bReplacements, document)) {
2350
- const { kept, other } = wrapGoesWithReplaced(a, b);
2351
- return {
2352
- a: kept,
2353
- b: other
2354
- };
2355
- }
2356
- if (readBack && wrapsInsideReplacement(bReplacements, aReplacements, document)) {
2357
- const { kept, other } = wrapGoesWithReplaced(b, a);
2358
- return {
2359
- a: other,
2360
- b: kept
2361
- };
2362
- }
2363
- const absorbed = transformByPositionOverAbsorbedWraps(a, b, aReplacements, bReplacements, document, replayBase, readBack);
2364
- if (absorbed) return absorbed;
2365
- const bPutBack = putBackOver(aReplacements, bReplacements, document);
2366
- if (bPutBack) {
2367
- const afterB = b.apply(document);
2368
- return {
2369
- a: RootChange.empty(afterB.length),
2370
- b: RootChange.create(a.apply(document), bPutBack)
2371
- };
2372
- }
2373
- const aPutBack = putBackOver(bReplacements, aReplacements, document);
2374
- if (aPutBack) {
2375
- const afterA = a.apply(document);
2376
- return {
2377
- a: RootChange.create(b.apply(document), aPutBack),
2378
- b: RootChange.empty(afterA.length)
2379
- };
2380
- }
2381
- const aPropertyChanges = a.propertyChanges();
2382
- const bPropertyChanges = b.propertyChanges();
2383
- const [aReplacement] = aReplacements;
2384
- const [bReplacement] = bReplacements;
2385
- const contains = (outer, inner) => !!outer && !!inner && (inner.from === inner.to ? outer.from < inner.from && inner.to < outer.to : outer.from <= inner.from && inner.to <= outer.to);
2386
- const containsAll = (outer, inner) => inner.length > 0 && inner.every((replacement) => contains(outer, replacement));
2387
- const [aRunMove, bRunMove] = readRunMoves();
2388
- const aMove = aRunMove?.count === 1 ? aRunMove : null;
2389
- const bMove = bRunMove?.count === 1 ? bRunMove : null;
2390
- if (aMove && bMove && pathKey(aMove.path) === pathKey(bMove.path)) {
2391
- const sameTarget = pathKey(aMove.targetPath) === pathKey(bMove.targetPath);
2392
- if (sameTarget && !keepEqualMoves) return rebaseWritesBesideEqualMove(a, b, RootChange.create(document, aReplacements), document, settings);
2393
- if (!sameTarget && crossedMoves === "first-wins" && aPropertyChanges.length === 0 && bPropertyChanges.length === 0) return {
2394
- a: b.invert(document).compose(a),
2395
- b: RootChange.empty(a.newLength)
2396
- };
2397
- }
2398
- const carryThroughMove = (edit, moveChange, move) => {
2399
- if (pathKey(move.path) === pathKey(move.targetPath) || !isElementNode(document.node(move.path))) return null;
2400
- const parts = edit.partition(move.from, move.to - 1);
2401
- if (!parts || parts.inside.empty) return null;
2402
- let touchesNode = false;
2403
- parts.outside.iterChangedRanges((from, to) => {
2404
- if (to > move.from && from < move.to) touchesNode = true;
2405
- });
2406
- if (touchesNode) return null;
2407
- const afterMove = moveChange.apply(document);
2408
- const afterEdit = edit.apply(document);
2409
- const carried = getDefined(parts.inside.within(move.from, move.to - 1)).embed(afterMove.length, move.fromAfterMove);
2410
- if (parts.outside.empty && moveChange.propertyChanges().length === 0) {
2411
- const moved = moveChangeAfterEdit(afterEdit, move, edit);
2412
- if (moved) return {
2413
- edit: carried,
2414
- move: moved
2415
- };
2416
- }
2417
- if (move.count > 1) return null;
2418
- const editAfterMove = carried.compose(RootChange.transform(RootChange.transform(parts.outside, moveChange).a, carried).a);
2419
- return {
2420
- edit: editAfterMove,
2421
- move: RootChange.betweenWhole(afterEdit, editAfterMove.apply(afterMove))
2422
- };
2423
- };
2424
- const carriesOver = (move, other) => !!move && (move.count === 1 ? other?.count !== 1 : !other);
2425
- if (carriesOver(bRunMove, aRunMove)) {
2426
- const carried = carryThroughMove(a, b, bRunMove);
2427
- if (carried) return {
2428
- a: carried.edit,
2429
- b: carried.move
2430
- };
2431
- }
2432
- if (carriesOver(aRunMove, bRunMove)) {
2433
- const carried = carryThroughMove(b, a, aRunMove);
2434
- if (carried) return {
2435
- a: carried.move,
2436
- b: carried.edit
2437
- };
2438
- }
2439
- const afterA = a.apply(document);
2440
- const afterB = b.apply(document);
2441
- const shared = keepEqualInserts ? null : sharedPlaceEdits(document, aReplacements, bReplacements);
2442
- if (shared && keptIn(b, afterB, afterA)) return {
2443
- a: RootChange.betweenWhole(afterB, afterA),
2444
- b: RootChange.empty(afterA.length)
2445
- };
2446
- if (shared && keptIn(a, afterA, afterB)) return {
2447
- a: RootChange.empty(afterB.length),
2448
- b: RootChange.betweenWhole(afterA, afterB)
2449
- };
2450
- const rebaseAfterShared = (edits) => {
2451
- const rest = RootChange.transformInDocument(overSharedEdits(a, edits), overSharedEdits(b, edits), RootChange.create(document, [...edits.values()].map(({ from, merged, to }) => ({
2452
- from,
2453
- insert: merged,
2454
- to
2455
- }))).apply(document), settings);
2456
- return {
2457
- ...rest,
2458
- a: resultToSharedDocument(b, edits, "second").compose(rest.a),
2459
- b: resultToSharedDocument(a, edits, "first").compose(rest.b)
2460
- };
2461
- };
2462
- const sameShared = shared && new Map([...shared].filter(([, { kind }]) => kind === "same"));
2463
- if (sameShared?.size) return rebaseAfterShared(sameShared);
2464
- const wrapGoesWithMove = (edit, moveChange, move) => {
2465
- const insertion = moveChange.replacements().find(({ from, insert, to }) => from === to && insert.length > 0);
2466
- const wraps = insertedElementsOf(edit, document).some(({ close, open }) => open.from === move.from && open.to === move.from && close.from === move.to && close.to === move.to);
2467
- if (!insertion || !wraps) return null;
2468
- const afterEdit = edit.apply(document);
2469
- const node = afterEdit.nodeStartingAt(getDefined(edit.mapPos(move.from, 1)));
2470
- const wrapperPath = node?.path.slice(0, -1);
2471
- if (!node || !wrapperPath?.length) return null;
2472
- const wrapper = afterEdit.nodeRange(wrapperPath);
2473
- const wrapperNode = afterEdit.node(wrapperPath);
2474
- const target = edit.mapPos(insertion.from, -1);
2475
- if (!isElementNode(wrapperNode) || wrapperNode.children.length !== 1 || target === null || wrapper.from <= target && target <= wrapper.to) return null;
2476
- const wrapperMove = RootChange.create(afterEdit, [{
2477
- from: wrapper.from,
2478
- to: wrapper.to
2479
- }, {
2480
- from: target,
2481
- insert: afterEdit.slice(wrapper.from, wrapper.to)
2482
- }]);
2483
- const writes = propertyWritesOf(moveChange);
2484
- let inMoved = false;
2485
- writes.iterChangedRanges((from, to) => {
2486
- if (to > move.from && from < move.to) inMoved = true;
2487
- });
2488
- if (inMoved) return null;
2489
- const moved = writes.propertyChanges().length ? wrapperMove.compose(RootChange.transform(RootChange.transform(writes, edit).a, wrapperMove).a) : wrapperMove;
2490
- return {
2491
- edit: RootChange.betweenWhole(moveChange.apply(document), moved.apply(afterEdit)),
2492
- move: moved
2493
- };
2494
- };
2495
- if (readBack && bMove && !aMove) {
2496
- const wrapped = wrapGoesWithMove(a, b, bMove);
2497
- const kept = wrapped && convergedResult(document, a, b, {
2498
- a: wrapped.edit,
2499
- b: wrapped.move
2500
- });
2501
- if (kept) {
2502
- markReadBack(readBack);
2503
- return kept;
2504
- }
2505
- }
2506
- if (readBack && aMove && !bMove) {
2507
- const wrapped = wrapGoesWithMove(b, a, aMove);
2508
- const kept = wrapped && convergedResult(document, a, b, {
2509
- a: wrapped.move,
2510
- b: wrapped.edit
2511
- });
2512
- if (kept) {
2513
- markReadBack(readBack);
2514
- return kept;
2515
- }
2516
- }
2517
- const transformed = RootChange.transform(a, b, replayBase, readBack);
2518
- const aChangesStructure = !sameChangedChildren(document, afterA, sameNodeStructure);
2519
- const bChangesStructure = !sameChangedChildren(document, afterB, sameNodeStructure);
2520
- const sharesStructuralStart = aReplacements.some(({ from }) => bReplacements.some((replacement) => replacement.from === from));
2521
- const sameEdit = () => onlyAddsStructure(aReplacements) && onlyAddsStructure(bReplacements) ? jsonEqual(afterA.value, afterB.value) : sameDocumentStructure(afterA.value, afterB.value);
2522
- const oneEdit = !keepEqualInserts && (aChangesStructure || bChangesStructure) && sharesStructuralStart && sameEdit();
2523
- const moveMeetsNonMove = readBack !== null && Boolean(aMove) !== Boolean(bMove);
2524
- if (oneEdit && moveMeetsNonMove) markReadBack(readBack);
2525
- if (oneEdit && !moveMeetsNonMove) {
2526
- if (shared) return rebaseAfterShared(shared);
2527
- if (replay !== void 0 && onlyAddsStructure(aReplacements) && aReplacements.some(({ insert }) => opensEnclosure(insert))) return {
2528
- a: RootChange.empty(afterB.length),
2529
- b: a.invert(document).compose(b)
2530
- };
2531
- return {
2532
- a: RootChange.betweenWhole(afterB, afterA),
2533
- b: RootChange.empty(afterA.length)
2534
- };
2535
- }
2536
- if (onlyAddsStructure(aReplacements) && onlyAddsStructure(bReplacements) && [...aReplacements, ...bReplacements].some(({ insert }) => opensEnclosure(insert)) && !addsInsideEnclosure(aReplacements, bReplacements) && !addsInsideEnclosure(bReplacements, aReplacements) && convergesOn(transformed, afterA, afterB)) return transformed;
2537
- const bThroughStableA = bChangesStructure ? mergeStructuralRunByPosition(b, a, aReplacements, document, afterB, afterA) ?? mergeStructuralChangeAtStableSiblingRange(document, afterB, afterA) : null;
2538
- if (bThroughStableA !== null) return {
2539
- a: bThroughStableA.other,
2540
- b: bThroughStableA.rebased
2541
- };
2542
- const aThroughStableB = aChangesStructure ? mergeStructuralRunByPosition(a, b, bReplacements, document, afterA, afterB) ?? mergeStructuralChangeAtStableSiblingRange(document, afterA, afterB) : null;
2543
- if (aThroughStableB !== null) return {
2544
- a: aThroughStableB.rebased,
2545
- b: aThroughStableB.other
2546
- };
2547
- const aThroughB = bChangesStructure ? mergeNestedChangeThroughStructuralRelocation(a, b, document, afterA, afterB) : null;
2548
- if (aThroughB !== null) return {
2549
- a: RootChange.betweenWhole(afterB, aThroughB),
2550
- b: RootChange.betweenWhole(afterA, aThroughB)
2551
- };
2552
- const bThroughA = aChangesStructure ? mergeNestedChangeThroughStructuralRelocation(b, a, document, afterB, afterA) : null;
2553
- if (bThroughA !== null) return {
2554
- a: RootChange.betweenWhole(afterB, bThroughA),
2555
- b: RootChange.betweenWhole(afterA, bThroughA)
2556
- };
2557
- if (convergesOn(transformed, afterA, afterB)) return transformed;
2558
- if (bMove && aReplacements.length === 1 && bMove.from <= aReplacement.from && aReplacement.to < bMove.to) {
2559
- const moveAfterA = moveNodeChange(afterA, bMove.path, bMove.targetPath);
2560
- const merged = moveAfterA.apply(afterA);
2561
- return {
2562
- a: RootChange.betweenWhole(afterB, merged),
2563
- b: moveAfterA
2564
- };
2565
- }
2566
- if (aMove && bReplacements.length === 1 && aMove.from <= bReplacement.from && bReplacement.to < aMove.to) {
2567
- const moveAfterB = moveNodeChange(afterB, aMove.path, aMove.targetPath);
2568
- const merged = moveAfterB.apply(afterB);
2569
- return {
2570
- a: moveAfterB,
2571
- b: RootChange.betweenWhole(afterA, merged)
2572
- };
2573
- }
2574
- const keepOutsideDeletion = (deletion, afterDeletion, propertyChanges) => {
2575
- const sections = [];
2576
- const data = [];
2577
- let position = 0;
2578
- for (const { from, modifications, to } of propertyChanges) {
2579
- if (to > deletion.from && from < deletion.to) continue;
2580
- const start = from < deletion.from ? from : from - (deletion.to - deletion.from);
2581
- if (start > position) addSection(sections, data, start - position, -1, null);
2582
- addSection(sections, data, to - from, -2, modifications);
2583
- position = start + to - from;
2584
- }
2585
- if (position < afterDeletion.length) addSection(sections, data, afterDeletion.length - position, -1, null);
2586
- return RootChange.fromSections(sections, data).apply(afterDeletion);
2587
- };
2588
- const deletion = bReplacements.length === 1 && deletesWholeSiblings(document, bReplacement) && containsAll(bReplacement, aReplacements) ? {
2589
- edit: a,
2590
- kept: aPropertyChanges,
2591
- replacement: bReplacement,
2592
- side: "b"
2593
- } : aReplacements.length === 1 && deletesWholeSiblings(document, aReplacement) && containsAll(aReplacement, bReplacements) ? {
2594
- edit: b,
2595
- kept: bPropertyChanges,
2596
- replacement: aReplacement,
2597
- side: "a"
2598
- } : null;
2599
- if (deletion) {
2600
- const [afterEdit, afterDeletion] = deletion.side === "b" ? [afterA, afterB] : [afterB, afterA];
2601
- const merged = keepOutsideDeletion(deletion.replacement, afterDeletion, deletion.kept);
2602
- const deletionAfterEdit = RootChange.create(afterEdit, {
2603
- from: deletion.replacement.from,
2604
- to: deletion.replacement.to + deletion.edit.newLength - deletion.edit.length
2605
- });
2606
- const deleted = deletionAfterEdit.compose(RootChange.betweenWhole(deletionAfterEdit.apply(afterEdit), merged));
2607
- const edited = RootChange.betweenWhole(afterDeletion, merged);
2608
- return deletion.side === "b" ? {
2609
- a: edited,
2610
- b: deleted
2611
- } : {
2612
- a: deleted,
2613
- b: edited
2614
- };
2615
- }
2616
- const overRemoval = transformMixedEditOverSiblingRemoval(a, b, aReplacements, bReplacements, document, afterA, afterB);
2617
- if (overRemoval) return overRemoval;
2618
- const soleWrap = soleWrapProps(aReplacements, document);
2619
- const bHoldsEdit = readBack && !keepEqualInserts && aPropertyChanges.length === 0 && (insertsWithin(a, b, aReplacements, bReplacements, document) || soleWrap !== null && bPropertyChanges.some(({ from, modifications }) => from < getDefined(aReplacements[0]).from && document.nodeStartingAt(from)?.to !== void 0 && getDefined(aReplacements[1]).from < getDefined(document.nodeStartingAt(from)).to && modifications.some((modification) => modification.key === "type" && modification.type === "set" && modification.value === soleWrap.type)));
2620
- if (bHoldsEdit && liftOf(b, document)) {
2621
- markReadBack(readBack);
2622
- return {
2623
- a: RootChange.empty(afterB.length),
2624
- b: a.invert(document).compose(b)
2625
- };
2626
- }
2627
- const lifted = readBack && !bHoldsEdit ? rebaseOverLift(a, b, document, settings) : null;
2628
- if (lifted) {
2629
- markReadBack(readBack);
2630
- return lifted;
2631
- }
2632
- const wrap = replay?.anchor ? soleWrap : null;
2633
- const anchored = wrap && RootChange.keepOverWrittenBack(a, b, document, afterA, afterB, wrap);
2634
- if (anchored) return anchored;
2635
- return {
2636
- a: RootChange.empty(afterB.length),
2637
- b: RootChange.betweenWhole(afterA, afterB)
2638
- };
2639
- }
2640
- static keepOverWrittenBack(a, b, document, afterA, afterB, wrap) {
2641
- try {
2642
- const step = b.keepWrittenBackCloses(document);
2643
- if (!step || addsElementOrRetypesTo(b, wrap.type)) return null;
2644
- const kept = RootChange.transform(a, step);
2645
- if (!jsonEqual(kept.b.apply(afterA).value, kept.a.apply(afterB).value)) return null;
2646
- return {
2647
- ...kept,
2648
- keptWrap: { props: wrap }
2649
- };
2650
- } catch {
2651
- return null;
2652
- }
2653
- }
2654
- get empty() {
2655
- return this.sections.length === 0 || this.sections.length === 2 && this.sections[1] === -1;
2656
- }
2657
- sameAs(other) {
2658
- return this === other || this.sections.length === other.sections.length && this.sections.every((value, index) => value === other.sections[index]) && this.data.every((data, index) => {
2659
- const theirs = other.data[index];
2660
- if (data instanceof PreparedTokenSlice) return theirs instanceof PreparedTokenSlice && data.tokens.length === theirs.tokens.length && data.tokens.every((token, at) => tokensEqual(token, theirs.tokens[at]));
2661
- return jsonEqual(data, theirs);
2662
- });
2663
- }
2664
- isNoopOn(document) {
2665
- let position = 0;
2666
- for (let index = 0; index < this.sections.length;) {
2667
- if (this.sections[index + 1] === -1) {
2668
- position += this.sections[index];
2669
- index += 2;
2670
- continue;
2671
- }
2672
- const from = position;
2673
- const first = index;
2674
- let insertedLength = 0;
2675
- while (index < this.sections.length && this.sections[index + 1] !== -1) {
2676
- if (this.sections[index + 1] === -2) return false;
2677
- position += this.sections[index];
2678
- insertedLength += this.sections[index + 1];
2679
- index += 2;
2680
- }
2681
- if (insertedLength !== position - from) return false;
2682
- if (!jsonEqual(PreparedTokenSlice.concat(this.data.slice(first >> 1, index >> 1).map((slice) => slice ?? PreparedTokenSlice.empty)).toJSON(), document.slice(from, position).toJSON())) return false;
2683
- }
2684
- return true;
2685
- }
2686
- pureDeletionOn(document) {
2687
- const replacements = this.replacements();
2688
- const last = replacements.at(-1);
2689
- if (!last || this.propertyChanges().length > 0 || replacements.some((replacement, index) => index > 0 && replacement.from !== replacements[index - 1].to)) return null;
2690
- const { from } = replacements[0];
2691
- const { to } = last;
2692
- const written = PreparedTokenSlice.concat(replacements.map((replacement) => replacement.insert));
2693
- if (written.length >= to - from) return null;
2694
- const removed = document.slice(from, to);
2695
- const writesBack = (removedAt, writtenAt) => jsonEqual(removed.slice(removedAt, removedAt + 1).toJSON(), written.slice(writtenAt, writtenAt + 1).toJSON());
2696
- let head = 0;
2697
- while (head < written.length && writesBack(head, head)) head += 1;
2698
- let tail = 0;
2699
- while (head + tail < written.length && writesBack(removed.length - 1 - tail, written.length - 1 - tail)) tail += 1;
2700
- return head + tail === written.length ? [from + head, to - tail] : null;
2701
- }
2702
- keepWrittenBackCloses(document) {
2703
- const sections = [];
2704
- const data = [];
2705
- let changed = false;
2706
- let position = 0;
2707
- for (let index = 0; index < this.sections.length;) {
2708
- const first = index;
2709
- const from = position;
2710
- do {
2711
- position += this.sections[index];
2712
- index += 2;
2713
- } while (this.sections[first + 1] >= 0 && index < this.sections.length && this.sections[index + 1] >= 0);
2714
- const insert = this.sections[first + 1] >= 0 ? PreparedTokenSlice.concat(this.data.slice(first >> 1, index >> 1).map((slice) => slice ?? PreparedTokenSlice.empty)) : null;
2715
- const written = insert && writtenBackCloses(document.slice(from, position).tokens, insert.tokens);
2716
- if (!insert || !written) {
2717
- for (let at = first; at < index; at += 2) addSection(sections, data, this.sections[at], this.sections[at + 1], this.data[at >> 1]);
2718
- continue;
2719
- }
2720
- const { offsets } = insert;
2721
- const rest = written.insertEnd < offsets.length ? offsets[written.insertEnd] : insert.length;
2722
- const lead = offsets[written.insertEnd - written.keptCloses];
2723
- changed = true;
2724
- addSection(sections, data, position - written.keptCloses - from, lead, insert.slice(0, lead));
2725
- addSection(sections, data, written.keptCloses, -1, null);
2726
- if (rest < insert.length) addSection(sections, data, 0, insert.length - rest, insert.slice(rest));
2727
- }
2728
- return changed ? RootChange.fromSections(sections, data) : null;
2729
- }
2730
- /** @internal */
2731
- alignOpens(document, aligns) {
2732
- const sections = [];
2733
- const data = [];
2734
- let position = 0;
2735
- let aligned = false;
2736
- for (let index = 0; index < this.sections.length; index += 2) {
2737
- const length = this.sections[index];
2738
- const inserted = this.sections[index + 1];
2739
- const value = this.data[index / 2];
2740
- let kept = 0;
2741
- if (inserted > 0 && length > 0 && value instanceof PreparedTokenSlice) {
2742
- const removed = document.slice(position, position + length).tokens;
2743
- const insert = value.tokens;
2744
- while (kept < removed.length && kept < insert.length) {
2745
- const before = removed[kept];
2746
- const after = insert[kept];
2747
- if (before.kind !== "open" || after.kind !== "open" || before.nodeKind !== after.nodeKind || !aligns(before.props, after.props)) break;
2748
- const modifications = semanticPropertyModifications(before.props, after.props, () => false);
2749
- addSection(sections, data, 1, modifications.length > 0 ? -2 : -1, modifications.length > 0 ? modifications : null);
2750
- kept += 1;
2751
- }
2752
- }
2753
- if (kept === 0) addSection(sections, data, length, inserted, value);
2754
- else {
2755
- aligned = true;
2756
- const rest = value.slice(kept);
2757
- addSection(sections, data, length - kept, rest.length, rest);
2758
- }
2759
- position += length;
2760
- }
2761
- return aligned ? new RootChange(sections, data) : this;
2762
- }
2763
- applyIndexed(document, replacements, propertyChanges, work) {
2764
- if (propertyChanges.length > 0) {
2765
- if (replacements.length > 0) {
2766
- work.fallbackReason = "mixed-properties-and-replacements";
2767
- return null;
2768
- }
2769
- const updates = [];
2770
- for (const propertyChange of propertyChanges) {
2771
- const entry = document.nodeStartingAt(propertyChange.from);
2772
- if (!entry || propertyChange.to !== propertyChange.from + 1) {
2773
- work.fallbackReason = "invalid-property-target";
2774
- return null;
2775
- }
2776
- const node = document.node(entry.path);
2777
- updates.push({
2778
- path: entry.path,
2779
- props: applyPropertyModifications(nodeProps(node), propertyChange.modifications)
2780
- });
2781
- work.ancestorPaths.push([...entry.path]);
2782
- }
2783
- return document.withNodeUpdates(updates);
2784
- }
2785
- const enclosed = enclosureApplied(document, replacements);
2786
- if (enclosed) {
2787
- work.ancestorPaths.push([...enclosed.parent]);
2788
- work.localizedReplacements = 2;
2789
- return enclosed.after;
2790
- }
2791
- if (replacements.length === 2) {
2792
- const deletion = replacements.find((replacement) => replacement.from < replacement.to && replacement.insert.length === 0);
2793
- const insertion = replacements.find((replacement) => replacement.from === replacement.to && replacement.insert.length > 0);
2794
- if (deletion && insertion) {
2795
- const source = document.nodeStartingAt(deletion.from);
2796
- const target = document.childBoundaryAt(insertion.from);
2797
- if (source?.to === deletion.to && target) try {
2798
- const inserted = decodeNodes(insertion.insert).nodes;
2799
- const sourceNode = document.node(source.path);
2800
- if (inserted.length === 1 && jsonEqual(inserted[0], sourceNode)) {
2801
- const sourceParent = source.path.slice(0, -1);
2802
- const sourceIndex = getDefined(source.path.at(-1));
2803
- const targetIndex = pathKey(sourceParent) === pathKey(target.parentPath) && sourceIndex < target.index ? target.index - 1 : target.index;
2804
- work.ancestorPaths.push([...sourceParent], [...target.parentPath]);
2805
- work.localizedReplacements = 2;
2806
- return document.withMovedNode(source.path, [...target.parentPath, targetIndex]);
2807
- }
2808
- } catch {}
2809
- }
2810
- }
2811
- const replacementsByPosition = sortJoiningInsertions(replacements);
2812
- for (let index = 1; index < replacementsByPosition.length; index++) {
2813
- const previous = replacementsByPosition[index - 1];
2814
- const replacement = replacementsByPosition[index];
2815
- if (previous.from === replacement.from) {
2816
- work.fallbackReason = "ambiguous-replacement-position";
2817
- return null;
2818
- }
2819
- if (previous.to > replacement.from) {
2820
- work.fallbackReason = "overlapping-replacement-range";
2821
- return null;
2822
- }
2823
- }
2824
- if (replacementsByPosition.length > 1) {
2825
- const updates = /* @__PURE__ */ new Map();
2826
- const paths = [];
2827
- for (const replacement of replacementsByPosition.toReversed()) {
2828
- const entry = document.textAt(replacement.from);
2829
- if (!entry || entry.contentFrom > replacement.from || replacement.to > entry.contentTo || !replacement.insert.tokens.every((token) => token.kind === "text")) break;
2830
- const node = document.node(entry.path);
2831
- if (!isTextNode(node)) break;
2832
- const key = pathKey(entry.path);
2833
- const previous = updates.get(key)?.text ?? node.text;
2834
- const inserted = replacement.insert.tokens.map((token) => token.kind === "text" ? token.text : "").join("");
2835
- updates.set(key, {
2836
- path: entry.path,
2837
- text: previous.slice(0, replacement.from - entry.contentFrom) + inserted + previous.slice(replacement.to - entry.contentFrom)
2838
- });
2839
- paths.push([...entry.path]);
2840
- }
2841
- if (paths.length === replacementsByPosition.length) {
2842
- for (const path of paths) work.ancestorPaths.push(path);
2843
- work.localizedReplacements += paths.length;
2844
- return document.withNodeUpdates([...updates.values()]);
2845
- }
2846
- }
2847
- let current = document;
2848
- const recordLocality = (path, replacementCount = 1) => {
2849
- work.ancestorPaths.push([...path]);
2850
- work.localizedReplacements += replacementCount;
2851
- return true;
2852
- };
2853
- const ancestorContains = (ancestor, { from, to }) => ancestor.from <= from && to <= ancestor.to && (from !== to || ancestor.from < from && from < ancestor.to);
2854
- const unapplied = [...replacementsByPosition];
2855
- while (unapplied.length > 0) {
2856
- const replacement = getDefined(unapplied.pop());
2857
- const preparedNodes = DOCUMENT_SLICE_PREPARED_NODES.get(replacement.insert);
2858
- const fromBoundary = current.childBoundaryAt(replacement.from);
2859
- const toBoundary = current.childBoundaryAt(replacement.to);
2860
- if (preparedNodes && fromBoundary && toBoundary && pathKey(fromBoundary.parentPath) === pathKey(toBoundary.parentPath) && claimPreparedNodeSlice(preparedNodes.nodes)) {
2861
- if (!recordLocality(fromBoundary.parentPath)) return null;
2862
- current = profileCoreDuration("change-set-local-splice", () => current.withPreparedSplicedNodes(fromBoundary.parentPath, fromBoundary.index, toBoundary.index - fromBoundary.index, preparedNodes));
2863
- continue;
2864
- }
2865
- const text = replacement.insert.tokens.every((token) => token.kind === "text") ? replacement.insert.tokens.map((token) => token.kind === "text" ? token.text : "").join("") : null;
2866
- const textEntry = current.textAt(replacement.from);
2867
- if (text !== null && textEntry && textEntry.contentFrom <= replacement.from && replacement.to <= textEntry.contentTo) {
2868
- if (!recordLocality(textEntry.path)) return null;
2869
- current = current.withText(textEntry.path, replacement.from - textEntry.contentFrom, replacement.to - textEntry.contentFrom, text);
2870
- continue;
2871
- }
2872
- const insertedTokens = replacement.insert.tokens;
2873
- const nodeEntry = current.nodeStartingAt(replacement.from);
2874
- if (replacement.to === replacement.from + 1 && insertedTokens.length === 1 && insertedTokens[0]?.kind === "open" && nodeEntry?.kind === insertedTokens[0].nodeKind) {
2875
- if (!recordLocality(nodeEntry.path)) return null;
2876
- current = current.withExactNodeProperties(nodeEntry.path, insertedTokens[0].props);
2877
- continue;
2878
- }
2879
- let insertedNodes = null;
2880
- try {
2881
- insertedNodes = profileCoreDuration("change-set-local-decode", () => decodeNodes(replacement.insert, [], { reuseUnpreparedSources: false }).nodes);
2882
- } catch {}
2883
- if (fromBoundary && toBoundary && insertedNodes && pathKey(fromBoundary.parentPath) === pathKey(toBoundary.parentPath)) {
2884
- if (!recordLocality(fromBoundary.parentPath)) return null;
2885
- current = profileCoreDuration("change-set-local-splice", () => current.withDecodedSplicedNodes(fromBoundary.parentPath, fromBoundary.index, toBoundary.index - fromBoundary.index, insertedNodes));
2886
- continue;
2887
- }
2888
- if (insertedNodes && nodeEntry?.to === replacement.to) {
2889
- const index = getDefined(nodeEntry.path.at(-1));
2890
- const parentPath = nodeEntry.path.slice(0, -1);
2891
- if (!recordLocality(parentPath)) return null;
2892
- current = profileCoreDuration("change-set-local-splice", () => current.withDecodedSplicedNodes(parentPath, index, 1, insertedNodes));
2893
- continue;
2894
- }
2895
- if (insertedNodes && replacement.from === replacement.to && insertedNodes.length > 0) {
2896
- const boundary = current.childBoundaryAt(replacement.from);
2897
- if (boundary) {
2898
- if (!recordLocality(boundary.parentPath)) return null;
2899
- current = profileCoreDuration("change-set-local-splice", () => current.withDecodedSplicedNodes(boundary.parentPath, boundary.index, 0, insertedNodes));
2900
- continue;
2901
- }
2902
- }
2903
- const fromContext = current.openContextAt(replacement.from);
2904
- const toPaths = new Set(current.openContextAt(replacement.to).map((entry) => pathKey(entry.path)));
2905
- const ancestors = [...fromContext].reverse().filter((entry) => toPaths.has(pathKey(entry.path)) && ancestorContains(entry, replacement));
2906
- let localized = false;
2907
- for (const ancestor of ancestors) {
2908
- let first = unapplied.length;
2909
- while (first > 0 && ancestorContains(ancestor, unapplied[first - 1])) first -= 1;
2910
- const batch = [...unapplied.slice(first), replacement];
2911
- try {
2912
- const ancestorSlice = current.nodeSlice(ancestor.path);
2913
- const pieces = [];
2914
- let position = 0;
2915
- for (const { from, insert, to } of batch) {
2916
- pieces.push(ancestorSlice.slice(position, from - ancestor.from), insert);
2917
- position = to - ancestor.from;
2918
- }
2919
- pieces.push(ancestorSlice.slice(position));
2920
- const local = PreparedTokenSlice.concat(pieces);
2921
- const nodes = profileCoreDuration("change-set-local-decode", () => decodeNodes(local).nodes);
2922
- const index = getDefined(ancestor.path.at(-1));
2923
- if (!recordLocality(ancestor.path, batch.length)) return null;
2924
- current = profileCoreDuration("change-set-local-splice", () => current.withDecodedSplicedNodes(ancestor.path.slice(0, -1), index, 1, nodes));
2925
- unapplied.length = first;
2926
- localized = true;
2927
- break;
2928
- } catch {}
2929
- }
2930
- if (localized) continue;
2931
- const topLevelRanges = current.nodeRangesTouching(replacement.from, replacement.to).filter((entry) => entry.path.length === 1);
2932
- const firstTopLevelIndex = Math.min(...topLevelRanges.map((entry) => entry.path[0]));
2933
- const lastTopLevelIndex = Math.max(...topLevelRanges.map((entry) => entry.path[0]));
2934
- if (Number.isFinite(firstTopLevelIndex) && Number.isFinite(lastTopLevelIndex)) {
2935
- const firstRange = current.nodeRange([firstTopLevelIndex]);
2936
- const lastRange = current.nodeRange([lastTopLevelIndex]);
2937
- if (firstRange.from <= replacement.from && replacement.to <= lastRange.to) try {
2938
- const local = PreparedTokenSlice.concat([
2939
- current.slice(firstRange.from, replacement.from),
2940
- replacement.insert,
2941
- current.slice(replacement.to, lastRange.to)
2942
- ]);
2943
- const nodes = profileCoreDuration("change-set-local-root-window-decode", () => decodeNodes(local).nodes);
2944
- if (!recordLocality([])) return null;
2945
- current = profileCoreDuration("change-set-local-root-window-splice", () => current.withDecodedSplicedNodes([], firstTopLevelIndex, lastTopLevelIndex - firstTopLevelIndex + 1, nodes));
2946
- continue;
2947
- } catch {}
2948
- }
2949
- work.fallbackReason = "unresolved-local-replacement";
2950
- return null;
2951
- }
2952
- return current;
2953
- }
2954
- replacements() {
2955
- const replacements = [];
2956
- let position = 0;
2957
- for (let index = 0, dataIndex = 0; index < this.sections.length;) {
2958
- const length = this.sections[index];
2959
- const inserted = this.sections[index + 1];
2960
- const data = this.data[dataIndex];
2961
- index += 2;
2962
- dataIndex += 1;
2963
- if (inserted >= 0) replacements.push({
2964
- from: position,
2965
- insert: data ?? PreparedTokenSlice.empty,
2966
- to: position + length
2967
- });
2968
- position += length;
2969
- }
2970
- return replacements;
2971
- }
2972
- propertyChanges() {
2973
- const changes = [];
2974
- let position = 0;
2975
- for (let index = 0, dataIndex = 0; index < this.sections.length;) {
2976
- const length = this.sections[index];
2977
- const inserted = this.sections[index + 1];
2978
- const data = this.data[dataIndex];
2979
- index += 2;
2980
- dataIndex += 1;
2981
- if (inserted === -2) changes.push({
2982
- from: position,
2983
- modifications: data,
2984
- to: position + length
2985
- });
2986
- position += length;
2987
- }
2988
- return changes;
2989
- }
2990
- exactMove(document) {
2991
- return this.propertyChanges().length === 0 ? this.movedNode(document) : null;
2992
- }
2993
- movedNode(document) {
2994
- const replacements = this.replacements();
2995
- if (replacements.length !== 2) return null;
2996
- const deletion = replacements.find((replacement) => replacement.from < replacement.to && replacement.insert.length === 0);
2997
- const insertion = replacements.find((replacement) => replacement.from === replacement.to && replacement.insert.length > 0);
2998
- if (!deletion || !insertion) return null;
2999
- const source = document.nodeStartingAt(deletion.from);
3000
- const target = document.childBoundaryAt(insertion.from);
3001
- if (!source || source.to !== deletion.to || !target) return null;
3002
- try {
3003
- const inserted = decodeNodes(insertion.insert).nodes;
3004
- const sourceNode = document.node(source.path);
3005
- if (inserted.length !== 1 || !jsonEqual(inserted[0], sourceNode)) return null;
3006
- const sourceParent = source.path.slice(0, -1);
3007
- const sourceIndex = getDefined(source.path.at(-1));
3008
- const targetIndex = pathKey(sourceParent) === pathKey(target.parentPath) && sourceIndex < target.index ? target.index - 1 : target.index;
3009
- const targetParent = transformPathAfterRemove(target.parentPath, source.path);
3010
- if (!targetParent) return null;
3011
- return Object.freeze({
3012
- path: Object.freeze([...source.path]),
3013
- targetPath: Object.freeze([...targetParent, targetIndex])
3014
- });
3015
- } catch {
3016
- return null;
3017
- }
3018
- }
3019
- apply(document) {
3020
- return profileCoreDuration("change-set-apply", () => this.applyInternal(document));
3021
- }
3022
- applyInternal(document) {
3023
- if (document.length !== this.length) throw new Error(`Cannot apply change length ${this.length} to document length ${document.length}.`);
3024
- if (this.empty) return document;
3025
- const replacements = this.replacements();
3026
- const propertyChanges = this.propertyChanges();
3027
- const changedRanges = [];
3028
- const work = {
3029
- ancestorPaths: [],
3030
- fallbackReason: null,
3031
- localizedReplacements: 0
3032
- };
3033
- this.iterChangedRanges((fromBefore, toBefore, fromAfter, toAfter) => {
3034
- changedRanges.push({
3035
- fromAfter,
3036
- fromBefore,
3037
- toAfter,
3038
- toBefore
3039
- });
3040
- });
3041
- const recordStats = (usedTokenFallback) => {
3042
- CHANGE_SET_APPLY_STATS.set(this, Object.freeze({
3043
- ancestorPaths: Object.freeze(work.ancestorPaths.map((path) => Object.freeze([...path]))),
3044
- changedRanges: Object.freeze(changedRanges.map((range) => Object.freeze({ ...range }))),
3045
- fallbackReason: work.fallbackReason,
3046
- localizedReplacements: work.localizedReplacements,
3047
- propertyChanges: propertyChanges.length,
3048
- replacements: replacements.length,
3049
- usedTokenFallback
3050
- }));
3051
- };
3052
- const indexed = profileCoreDuration("change-set-apply-indexed", () => {
3053
- if (propertyChanges.length === 0 || replacements.length === 0) return this.applyIndexed(document, replacements, propertyChanges, work);
3054
- const withProperties = this.applyIndexed(document, [], propertyChanges, work);
3055
- return withProperties ? this.applyIndexed(withProperties, replacements, [], work) : null;
3056
- });
3057
- if (indexed) {
3058
- recordStats(false);
3059
- return indexed;
3060
- }
3061
- profileCoreDuration(`change-set-apply-token-fallback:${work.fallbackReason ?? "unknown"}`, () => void 0);
3062
- return profileCoreDuration("change-set-apply-token-fallback", () => {
3063
- const outputTokens = [];
3064
- let position = 0;
3065
- const append = (slice) => {
3066
- for (const token of slice.tokens) outputTokens.push(token);
3067
- };
3068
- for (let index = 0, dataIndex = 0; index < this.sections.length;) {
3069
- const length = this.sections[index];
3070
- const inserted = this.sections[index + 1];
3071
- const value = this.data[dataIndex];
3072
- index += 2;
3073
- dataIndex += 1;
3074
- const source = document.slice(position, position + length);
3075
- append(inserted === -1 ? source : inserted === -2 ? applyPropertyModificationsToSlice(source, value) : value ?? PreparedTokenSlice.empty);
3076
- position += length;
3077
- }
3078
- if (position !== document.length) throw new Error("RootChange does not cover the source document.");
3079
- const outputRanges = [];
3080
- for (const { fromAfter, toAfter } of changedRanges) outputRanges.push([fromAfter, toAfter]);
3081
- recordStats(true);
3082
- return DocumentIndex.fromChangedTokens(PreparedTokenSlice.fromTokens(outputTokens), outputRanges);
3083
- });
3084
- }
3085
- compose(other) {
3086
- if (this.newLength !== other.length) throw new Error("Cannot compose mismatched change-set lengths.");
3087
- const { data, sections } = composeSections(this.sections, this.data, other.sections, other.data);
3088
- return new RootChange(sections, data);
3089
- }
3090
- /** Invert a change that only inserts tokens without reading the document. */
3091
- invertInsertions() {
3092
- const sections = [];
3093
- const data = [];
3094
- for (let index = 0; index < this.sections.length; index += 2) {
3095
- const length = this.sections[index];
3096
- const inserted = this.sections[index + 1];
3097
- if (inserted === -1) {
3098
- addSection(sections, data, length, -1, null);
3099
- continue;
3100
- }
3101
- if (inserted < 0 || length !== 0) return null;
3102
- addSection(sections, data, inserted, 0, PreparedTokenSlice.empty);
3103
- }
3104
- return new RootChange(sections, data);
3105
- }
3106
- /** Resize only the unchanged trailing document region. */
3107
- resizeTrailingDocument(length) {
3108
- if (!Number.isSafeInteger(length) || length < 0) return null;
3109
- if (length === this.length) return this;
3110
- if (length > this.length) return this.embed(length, 0);
3111
- const sections = [];
3112
- const data = [];
3113
- let position = 0;
3114
- for (let index = 0, dataIndex = 0; index < this.sections.length;) {
3115
- const sectionLength = this.sections[index];
3116
- const inserted = this.sections[index + 1];
3117
- const value = this.data[dataIndex];
3118
- index += 2;
3119
- dataIndex += 1;
3120
- if (inserted !== -1) {
3121
- if (position > length || position + sectionLength > length) return null;
3122
- addSection(sections, data, sectionLength, inserted, value);
3123
- } else if (position < length) addSection(sections, data, Math.min(sectionLength, length - position), -1, null);
3124
- position += sectionLength;
3125
- }
3126
- return new RootChange(sections, data);
3127
- }
3128
- invert(document) {
3129
- if (document.length !== this.length) throw new Error("Cannot invert against a mismatched document.");
3130
- const sections = [];
3131
- const data = [];
3132
- let position = 0;
3133
- for (let index = 0; index < this.sections.length; index += 2) {
3134
- let length = this.sections[index];
3135
- const inserted = this.sections[index + 1];
3136
- if (inserted === -1) addSection(sections, data, length, -1, null);
3137
- else if (inserted === -2) {
3138
- const entry = document.nodeStartingAt(position);
3139
- if (!entry || length !== 1) throw new Error("Cannot invert an invalid node property delta.");
3140
- addSection(sections, data, 1, -2, invertPropertyModifications(nodeProps(document.node(entry.path)), this.data[index >> 1]));
3141
- } else if (inserted === 0) {
3142
- while (this.sections[index + 3] === 0) {
3143
- index += 2;
3144
- length += this.sections[index];
3145
- }
3146
- addSection(sections, data, 0, length, document.slice(position, position + length));
3147
- } else {
3148
- const original = length === 0 ? PreparedTokenSlice.empty : document.slice(position, position + length);
3149
- addSection(sections, data, inserted, length, original);
3150
- }
3151
- position += length;
3152
- }
3153
- return new RootChange(sections, data);
3154
- }
3155
- /**
3156
- * Bind existing runtime identities to node openings inserted by this change.
3157
- *
3158
- * @internal
3159
- */
3160
- withInsertedNodeKeys(after, nodeKeyAt) {
3161
- if (after.length !== this.newLength) throw new Error("Cannot bind node keys against a mismatched document.");
3162
- const data = [...this.data];
3163
- let changed = false;
3164
- let outputPosition = 0;
3165
- for (let sectionIndex = 0, dataIndex = 0; sectionIndex < this.sections.length; dataIndex++) {
3166
- const length = this.sections[sectionIndex];
3167
- const inserted = this.sections[sectionIndex + 1];
3168
- sectionIndex += 2;
3169
- const outputLength = inserted < 0 ? length : inserted;
3170
- const value = data[dataIndex];
3171
- if (inserted > 0 && value instanceof PreparedTokenSlice && value.length === inserted) {
3172
- const from = after.childBoundaryAt(outputPosition);
3173
- const to = after.childBoundaryAt(outputPosition + inserted);
3174
- if (from && to && pathKey(from.parentPath) === pathKey(to.parentPath) && from.index < to.index) {
3175
- const nodes = from.parentPath.length === 0 ? after.nodes.slice(from.index, to.index) : (() => {
3176
- const parent = after.node(from.parentPath);
3177
- return isElementNode(parent) ? parent.children.slice(from.index, to.index) : [];
3178
- })();
3179
- const prepared = PreparedTokenSlice.fromPreparedNodes(nodes, (path) => nodeKeyAt([
3180
- ...from.parentPath,
3181
- from.index + path[0],
3182
- ...path.slice(1)
3183
- ]));
3184
- if (prepared.length === inserted) {
3185
- data[dataIndex] = prepared;
3186
- changed = true;
3187
- }
3188
- } else if (value.tokens.some((token) => token.kind === "open")) {
3189
- const keys = /* @__PURE__ */ new Map();
3190
- value.tokens.forEach((token, index) => {
3191
- if (token.kind !== "open") return;
3192
- const offset = value.offsets[index];
3193
- const node = after.nodeStartingAt(outputPosition + offset);
3194
- const key = node && nodeKeyAt(node.path);
3195
- if (key) keys.set(offset, key);
3196
- });
3197
- data[dataIndex] = value.withNodeKeys(keys);
3198
- changed = true;
3199
- }
3200
- }
3201
- outputPosition += outputLength;
3202
- }
3203
- return changed ? new RootChange(this.sections, data) : this;
3204
- }
3205
- *insertedSlices() {
3206
- for (let index = 0, position = 0; index < this.sections.length; index += 2) {
3207
- const length = this.sections[index];
3208
- const inserted = this.sections[index + 1];
3209
- const slice = this.data[index / 2];
3210
- if (inserted > 0 && slice instanceof PreparedTokenSlice) yield [position, slice];
3211
- position += inserted < 0 ? length : inserted;
3212
- }
3213
- }
3214
- iterChangedRanges(visit) {
3215
- let positionA = 0;
3216
- let positionB = 0;
3217
- for (let index = 0; index < this.sections.length;) {
3218
- let length = this.sections[index];
3219
- let inserted = this.sections[index + 1];
3220
- index += 2;
3221
- if (inserted === -1) {
3222
- positionA += length;
3223
- positionB += length;
3224
- continue;
3225
- }
3226
- if (inserted === -2) inserted = length;
3227
- while (index < this.sections.length && this.sections[index + 1] !== -1) {
3228
- length += this.sections[index];
3229
- const added = this.sections[index + 1];
3230
- index += 2;
3231
- inserted += added === -2 ? this.sections[index - 2] : added;
3232
- }
3233
- visit(positionA, positionA + length, positionB, positionB + inserted);
3234
- positionA += length;
3235
- positionB += inserted;
3236
- }
3237
- }
3238
- mapPos(position, assoc = -1, track) {
3239
- const ends = sectionEndsOf(this);
3240
- const first = firstSectionEnding(ends.endA, position, true);
3241
- let positionA = first < ends.startA.length ? ends.startA[first] : this.length;
3242
- let positionB = first < ends.startB.length ? ends.startB[first] : this.newLength;
3243
- for (let index = first * 2; index < this.sections.length;) {
3244
- const length = this.sections[index];
3245
- const inserted = this.sections[index + 1];
3246
- index += 2;
3247
- const endA = positionA + length;
3248
- if (inserted < 0) {
3249
- if (endA > position) return positionB + position - positionA;
3250
- positionB += length;
3251
- } else {
3252
- if (track && endA >= position && (track === "around" && positionA < position && endA > position || track === "before" && positionA < position || track === "after" && endA > position)) return null;
3253
- if (endA > position || endA === position && assoc < 0 && length === 0) return position === positionA || assoc < 0 ? positionB : positionB + inserted;
3254
- positionB += inserted;
3255
- }
3256
- positionA = endA;
3257
- }
3258
- if (position > positionA) throw new RangeError(`Position ${position} exceeds RootChange length ${positionA}.`);
3259
- return positionB;
3260
- }
3261
- toJSON() {
3262
- return this.data.map((value, index) => {
3263
- const length = this.sections[index * 2];
3264
- const inserted = this.sections[index * 2 + 1];
3265
- if (inserted === -1) return { length };
3266
- if (inserted === -2) return {
3267
- length,
3268
- properties: {
3269
- operations: value.map(propertyModificationToJSON),
3270
- version: 1
3271
- }
3272
- };
3273
- return {
3274
- length,
3275
- replacement: value?.toJSON() ?? []
3276
- };
3277
- });
3278
- }
3279
- };
3280
- const changeText = (document, path, from, to, text) => {
3281
- const start = document.positionAt({
3282
- offset: from,
3283
- path
3284
- });
3285
- const end = document.positionAt({
3286
- offset: to,
3287
- path
3288
- });
3289
- return RootChange.create(document, {
3290
- from: start,
3291
- insert: PreparedTokenSlice.text(text),
3292
- to: end
3293
- });
3294
- };
3295
- const insertTextChange = (document, path, offset, text) => changeText(document, path, offset, offset, text);
3296
- const removeTextChange = (document, path, offset, text) => changeText(document, path, offset, offset + text.length, "");
3297
- const insertNodeChange = (document, path, node) => {
3298
- const parentPath = path.slice(0, -1);
3299
- const index = path.at(-1);
3300
- if (index === void 0) throw new Error("Cannot insert the document root.");
3301
- return RootChange.create(document, {
3302
- from: document.childPosition(parentPath, index),
3303
- insert: PreparedTokenSlice.fromNodes([node])
3304
- });
3305
- };
3306
- const removeNodeChange = (document, path) => {
3307
- const range = document.nodeRange(path);
3308
- return RootChange.create(document, range);
3309
- };
3310
- const setNodesChange = (document, updates, isSetValued = () => false, root = null) => {
3311
- const changes = updates.flatMap(({ newProperties, path, properties }) => {
3312
- const node = document.node(path);
3313
- const context = getDocumentPropertyContext(document, path, root);
3314
- const next = { ...node };
3315
- for (const key of Object.keys(properties)) if (!Object.hasOwn(newProperties, key)) delete next[key];
3316
- for (const [key, value] of Object.entries(newProperties)) if (value === null) delete next[key];
3317
- else next[key] = value;
3318
- const modifications = semanticPropertyModifications(nodeProps(node), nodeProps(next), (key) => isSetValued(node, key, context));
3319
- if (modifications.length === 0) return [];
3320
- const range = document.nodeRange(path);
3321
- return [{
3322
- from: range.from,
3323
- properties: propertyDeltaFromModifications(modifications),
3324
- to: range.from + 1
3325
- }];
3326
- });
3327
- return RootChange.create(document, changes);
3328
- };
3329
- const setNodeChange = (document, path, newProperties, properties = {}, isSetValued = () => false, root = null) => setNodesChange(document, [{
3330
- newProperties,
3331
- path,
3332
- properties
3333
- }], isSetValued, root);
3334
- const siblingRunMove = (document, replacements) => {
3335
- if (replacements.length !== 2) return null;
3336
- const deletion = replacements.find((replacement) => replacement.from < replacement.to && replacement.insert.length === 0);
3337
- const insertion = replacements.find((replacement) => replacement.from === replacement.to && replacement.insert.length > 0);
3338
- if (!deletion || !insertion) return null;
3339
- const source = document.nodeStartingAt(deletion.from);
3340
- const target = document.childBoundaryAt(insertion.from);
3341
- if (!source || !target || insertion.insert.length !== deletion.to - deletion.from) return null;
3342
- const sourceParent = source.path.slice(0, -1);
3343
- const sourceNodes = [];
3344
- for (let at = deletion.from; at < deletion.to;) {
3345
- const node = document.nodeStartingAt(at);
3346
- if (!node || node.to > deletion.to || pathKey(node.path.slice(0, -1)) !== pathKey(sourceParent)) return null;
3347
- sourceNodes.push(document.node(node.path));
3348
- at = node.to;
3349
- }
3350
- let insertedNodes;
3351
- try {
3352
- insertedNodes = decodeNodes(insertion.insert).nodes;
3353
- } catch {
3354
- return null;
3355
- }
3356
- if (!jsonEqual(insertedNodes, sourceNodes)) return null;
3357
- const sourceIndex = getDefined(source.path.at(-1));
3358
- const targetIndex = pathKey(sourceParent) === pathKey(target.parentPath) && sourceIndex < target.index ? target.index - sourceNodes.length : target.index;
3359
- return {
3360
- count: sourceNodes.length,
3361
- from: source.from,
3362
- fromAfterMove: insertion.from >= deletion.to ? insertion.from - (deletion.to - deletion.from) : insertion.from,
3363
- insertAt: insertion.from,
3364
- path: source.path,
3365
- to: deletion.to,
3366
- targetPath: [...target.parentPath, targetIndex]
3367
- };
3368
- };
3369
- const typingMovedToJoinStart = (join, typed) => typed.every((other) => other.from === join.to && other.to === join.to) ? typed.map((other) => ({
3370
- ...other,
3371
- from: join.from,
3372
- to: join.from
3373
- })) : null;
3374
- const meets = (range, other) => other.from === other.to ? range.from < other.from && other.from < range.to : other.from < range.to && range.from < other.to;
3375
- const deletesAcrossLandingOnly = (outside, move) => {
3376
- let touchesNode = false;
3377
- let spansLanding = false;
3378
- outside.iterChangedRanges((from, to) => {
3379
- if (to > move.from && from < move.to) touchesNode = true;
3380
- if (from < move.insertAt && move.insertAt < to) spansLanding = true;
3381
- });
3382
- return spansLanding && !touchesNode;
3383
- };
3384
- const LINE_CLOSE_TOKENS = 2;
3385
- const LINE_BREAK_TOKENS = 2 * LINE_CLOSE_TOKENS;
3386
- const emptyLineRemovalFor = (document, replacement) => {
3387
- if (replacement.insert.length > 0 || replacement.to - replacement.from !== LINE_BREAK_TOKENS) return null;
3388
- const line = document.nodeStartingAt(replacement.from + LINE_CLOSE_TOKENS);
3389
- if (!line || line.to !== replacement.to + LINE_CLOSE_TOKENS) return null;
3390
- const index = getDefined(line.path.at(-1));
3391
- const node = document.node(line.path);
3392
- if (index === 0 || !isElementNode(node) || node.children.length !== 1) return null;
3393
- const [text] = node.children;
3394
- if (!text || !isTextNode(text) || text.text !== "") return null;
3395
- const previousPath = [...line.path.slice(0, -1), index - 1];
3396
- const previous = document.node(previousPath);
3397
- if (!isElementNode(previous)) return null;
3398
- const lastIndex = previous.children.length - 1;
3399
- const last = previous.children[lastIndex];
3400
- if (!last || !isTextNode(last) || document.nodeRange([...previousPath, lastIndex]).to !== replacement.from + 1) return null;
3401
- return {
3402
- from: line.from,
3403
- insert: PreparedTokenSlice.empty,
3404
- to: line.to
3405
- };
3406
- };
3407
- const moveChangeAfterEdit = (afterEdit, move, edit) => {
3408
- const end = move.to + edit.newLength - edit.length;
3409
- if (move.count === 1 && afterEdit.nodeStartingAt(move.from)?.to === end) return moveNodeChange(afterEdit, move.path, move.targetPath);
3410
- if (end <= move.from) return null;
3411
- const parent = pathKey(move.path.slice(0, -1));
3412
- let at = move.from;
3413
- while (at < end) {
3414
- const node = afterEdit.nodeStartingAt(at);
3415
- if (!node || node.to > end || pathKey(node.path.slice(0, -1)) !== parent) return null;
3416
- at = node.to;
3417
- }
3418
- return RootChange.create(afterEdit, [{
3419
- from: move.from,
3420
- to: end
3421
- }, {
3422
- from: move.insertAt >= move.to ? move.insertAt + end - move.to : move.insertAt,
3423
- insert: afterEdit.slice(move.from, end)
3424
- }]);
3425
- };
3426
- const moveNodeChange = (document, path, newPath) => {
3427
- if (pathKey(path) === pathKey(newPath)) return RootChange.empty(document.length);
3428
- const range = document.nodeRange(path);
3429
- const sourceParent = path.slice(0, -1);
3430
- const targetParent = newPath.slice(0, -1);
3431
- const sourceIndex = path.at(-1);
3432
- const targetIndex = newPath.at(-1);
3433
- if (sourceIndex === void 0 || targetIndex === void 0) throw new Error("Cannot move the document root.");
3434
- const sameParent = pathKey(sourceParent) === pathKey(targetParent);
3435
- const targetParentChildren = targetParent.length === 0 ? document.value : (() => {
3436
- const parent = document.node(targetParent);
3437
- if (!isElementNode(parent)) throw new Error(`Node at [${targetParent}] is not an element.`);
3438
- return parent.children;
3439
- })();
3440
- const originTargetIndex = sameParent && sourceIndex < targetIndex ? Math.min(targetIndex + 1, targetParentChildren.length) : targetIndex;
3441
- const target = document.childPosition(targetParent, originTargetIndex);
3442
- if (range.from <= target && target <= range.to) throw new Error("Cannot move a node inside itself.");
3443
- return RootChange.create(document, [{
3444
- from: range.from,
3445
- to: range.to
3446
- }, {
3447
- from: target,
3448
- insert: document.nodeSlice(path)
3449
- }]);
3450
- };
3451
- const replaceChildrenChange = (document, path, index, removeCount, newChildren) => {
3452
- const removed = path.length === 0 ? document.nodes.slice(index, index + removeCount) : (() => {
3453
- const parent = document.node(path);
3454
- if (!isElementNode(parent)) throw new Error(`Node at [${path}] is not an element.`);
3455
- return parent.children.slice(index, index + removeCount);
3456
- })();
3457
- if (removed.length === newChildren.length && removed.every((node, childIndex) => jsonEqual(node, newChildren[childIndex]))) return RootChange.empty(document.length);
3458
- return RootChange.create(document, {
3459
- from: document.childPosition(path, index),
3460
- insert: PreparedTokenSlice.fromNodes(newChildren),
3461
- to: document.childPosition(path, index + removed.length)
3462
- });
3463
- };
3464
- const replaceChildRunsChange = (document, runs) => RootChange.create(document, runs.map(({ children, index, path, removeCount }) => ({
3465
- from: document.childPosition(path, index),
3466
- insert: PreparedTokenSlice.fromNodes(children),
3467
- to: document.childPosition(path, index + removeCount)
3468
- })));
3469
- /**
3470
- * Build one canonical child reconciliation without applying it.
3471
- *
3472
- * @internal
3473
- */
3474
- const reconcileChildrenStep = (document, path, index, removeCount, newChildren) => {
3475
- const removed = (path.length === 0 ? document.nodes : (() => {
3476
- const parent = document.node(path);
3477
- if (!isElementNode(parent)) throw new Error(`Node at [${path}] is not an element.`);
3478
- return parent.children;
3479
- })()).slice(index, index + removeCount);
3480
- if (removed.length === newChildren.length && removed.every((node, childIndex) => jsonEqual(node, newChildren[childIndex]))) return Object.freeze({
3481
- after: document,
3482
- change: RootChange.empty(document.length)
3483
- });
3484
- const after = document.withSplicedNodes(path, index, removed.length, newChildren);
3485
- if (removed.length === 0 || newChildren.length === 0) return Object.freeze({
3486
- after,
3487
- change: RootChange.create(document, {
3488
- from: document.childPosition(path, index),
3489
- insert: PreparedTokenSlice.fromNodes(newChildren),
3490
- to: document.childPosition(path, index + removed.length)
3491
- })
3492
- });
3493
- const beforeWindow = DocumentIndex.fromValue(removed);
3494
- const afterWindow = DocumentIndex.fromValue(newChildren);
3495
- const localChange = RootChange.betweenWhole(beforeWindow, afterWindow);
3496
- const offset = document.childPosition(path, index);
3497
- return Object.freeze({
3498
- after,
3499
- change: localChange.embed(document.length, offset)
3500
- });
3501
- };
3502
- const mergeNodeChange = (document, path) => {
3503
- const index = path.at(-1);
3504
- if (index === void 0 || index === 0) throw new Error(`Cannot merge node at [${path}].`);
3505
- const previousPath = [...path.slice(0, -1), index - 1];
3506
- const previous = document.node(previousPath);
3507
- const node = document.node(path);
3508
- if (!(isTextNode(previous) && isTextNode(node) || isElementNode(previous) && isElementNode(node))) throw new Error(`Cannot merge nodes of different kinds at [${path}].`);
3509
- const boundary = document.nodeRange(path).from;
3510
- return RootChange.create(document, {
3511
- from: boundary - 1,
3512
- to: boundary + 1
3513
- });
3514
- };
3515
- const splitNodeChange = (document, path, position, properties) => {
3516
- if (path.at(-1) === void 0) throw new Error("Cannot split the document root.");
3517
- const node = document.node(path);
3518
- let after;
3519
- if (isTextNode(node)) {
3520
- if (position < 0 || position > node.text.length) throw new Error(`Cannot split text at offset ${position}.`);
3521
- after = {
3522
- ...properties,
3523
- text: ""
3524
- };
3525
- } else {
3526
- if (position < 0 || position > node.children.length) throw new Error(`Cannot split element at child index ${position}.`);
3527
- after = {
3528
- ...typeof properties.type === "string" ? { type: properties.type } : typeof node.type === "string" ? { type: node.type } : {},
3529
- ...properties,
3530
- children: []
3531
- };
3532
- }
3533
- const nodeKind = isTextNode(node) ? "text" : "element";
3534
- const boundary = isTextNode(node) ? document.positionAt({
3535
- path,
3536
- offset: position
3537
- }) : document.childPosition(path, position);
3538
- return RootChange.create(document, {
3539
- from: boundary,
3540
- insert: PreparedTokenSlice.fromTokens([closeToken(nodeKind), openToken(nodeKind, nodeProps(after))])
3541
- });
3542
- };
3543
- //#endregion
3544
- export { CHANGE_SET_APPLY_STATS, RootChange, SectionIterator, TREE_DIFF_MATRIX_LIMIT, addSection, ancestorType, applyPropertyModifications, applyPropertyModificationsToSlice, changeText, collapseElementPropertyWrites, commonTextPrefixLength, commonTextSuffixLength, composeSections, createStructurallyAlignedChanges, getDocumentPropertyContext, insertNodeChange, insertTextChange, insertedElementsOf, invertPropertyModifications, isLeafToken, isRootChangePositionReplaced, isRootChangeRangeReplaced, keptRunsOf, mapRootChangePositionBackward, mergeNodeChange, moveNodeChange, normalizePropertyDelta, propertyDeltaFromModifications, propertyModificationFromJSON, propertyModificationToJSON, propertyModificationsFromJSON, reconcileChildrenStep, removeNodeChange, removeTextChange, replaceChildRunsChange, replaceChildrenChange, semanticPropertyModifications, setNodeChange, setNodesChange, splitNodeChange, transformChange, writesOnlyElementProperties };