plitejs 54.0.0-beta.2 → 54.0.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (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 +18679 -4
  6. package/dist/{core/authored-veto.js → authored-veto-D_9wCJcK.js} +2 -2
  7. package/dist/{internal/browser-protocol.js → browser-protocol-pvt4HFF7.js} +1 -1
  8. package/dist/comparison-plan-DY_vuGPq.js +1338 -0
  9. package/dist/{diff/lib/comparison-types.d.ts → comparison-types-DdwE6mYq.d.ts} +11 -6
  10. package/dist/create-editor-CLQEkEZ1.js +1108 -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-CH2BXXj6.js +9220 -0
  16. package/dist/{core/same-result.js → editor-owner-C9rVbMTs.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-CeT83ZLB.js} +134 -8
  23. package/dist/{annotations/store.d.ts → index-BWPcE4ac.d.ts} +27 -6
  24. package/dist/index-BXjLmx1n.d.ts +9827 -0
  25. package/dist/index-DVMNewDn.d.ts +1243 -0
  26. package/dist/index-Db-ktCTE.d.ts +1092 -0
  27. package/dist/index-Dq3Jlj8O.d.ts +119 -0
  28. package/dist/{yjs/core/plugin.d.ts → index-UrB4jAwl.d.ts} +88 -5
  29. package/dist/index.d.ts +2 -51
  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-CbWqba_1.js} +2 -3
  34. package/dist/{core/native-grouping-input.js → native-grouping-input-DXNhlPHd.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-CBdYiOuR.js +1021 -0
  40. package/dist/plugin-SR3HTH0j.js +51505 -0
  41. package/dist/{react/range-geometry.js → range-geometry-CdltxcH6.js} +23 -18
  42. package/dist/{react/range-geometry.d.ts → range-geometry-Dwp2oyCc.d.ts} +2 -2
  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-CN-iBh1z.js +1018 -0
  48. package/dist/{core/change/retraction.js → retraction-BmPJB9cE.js} +16 -4
  49. package/dist/src-B-zm0kz4.js +1511 -0
  50. package/dist/{internal/view/stable-id-mapped-source.js → store-51r4zpCR.js} +253 -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-uDJQ692F.js +28370 -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-IGE0Al3n.js +13416 -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,3642 +0,0 @@
1
- import { getDefined } from "../../internal/get-defined.js";
2
- import { countCoreWork } from "../../core/work.js";
3
- import { deepFreeze, jsonEqual } from "../../core/change/json.js";
4
- import { PreparedTokenSlice, PreparedTokenSliceStructureError, isElementNode, pathKey } from "../../core/change/tokens.js";
5
- import { DocumentIndex } from "../../core/change/document-index.js";
6
- import { RootChange, ancestorType } from "../../core/change/root-change.js";
7
- import { createInternalDocumentChange, createInternalRootChangeFromSections, getInternalDocumentRootChange } from "../../core/change/document-change.js";
8
- import { PathApi } from "../../interfaces/path.js";
9
- import { failInvariant } from "../../internal/fail-invariant.js";
10
- import { getDocumentChangeRelocations, getExactDocumentChangeRelocation, hasIndexedPathAncestor } from "../../core/change/mapping.js";
11
- import { NodeApi } from "../../interfaces/node.js";
12
- import { YJS_CHILD_VISIBILITY_KEYS, YJS_CUT_SOURCE_KEY, YJS_HIDDEN_KEY, YJS_NODE_ID_KEY, YJS_VIRTUAL_CHILD_ID_KEY, isYjsMarkRecordKey } from "./keys.js";
13
- import { getYjsAttributes } from "./attributes.js";
14
- import { parentPath } from "./path.js";
15
- import { yjsAddressesOf, yjsNodeOf } from "./addresses.js";
16
- import { areJsonLikeValuesEqual } from "./json-equality.js";
17
- import { alignYjsChildren, continuesYjsText, createYjsRunEncoder, createYjsTextChain, dropYjsTextGaps, elementOnlySpliceEdits, fillYjsTextGaps, hasYjsCut, healYjsCut, isYjsCutItem, retainTextChainRange, rewriteTextRuns, segmentPliteChildren, textPieceOf, textsChangedBy, writeTextRuns, yjsTextLength } from "./text-runs.js";
18
- import { createVirtualYjsMovePlaceholder, createYjsNode, createYjsNodes, createYjsPropertyContext, createYjsPropertyLocationAt, getYjsVisibleChild, getYjsVisibleChildren, indexYjsPropertyContexts, insertYjsChild, isEmptyAttributeFreeShownYjsText, isEmptyAttributeFreeYjsText, noSetProperties, plainYjsChildren, projectYjsRoot, readPliteNodeFromYjs, readYjsChildrenNotingPlainList, readYjsRootIndex, readYjsRootSlot, readYjsTreeRefs, removeJoinedYjsLine, removeRedundantEmptyYjsTextNodesAt, removeYjsChild, removeYjsVirtualPlaceholderChild, replaceYjsChildren, setVirtualYjsMove, settleYjsMoveContests, withYjsRootIds, withYjsRootIndex, withYjsSynchronizedIndex, yjsKeyStorageOf, yjsRootNeedsNormalization } from "./document.js";
19
- import { firstEndingAfter, holdsNewLetters, keptLettersSpan, lettersAfter, lettersBefore, placeOfLeaves, runLettersOf, slicePlace, textStartsOf, yjsLettersOf } from "./new-letters.js";
20
- import { canReplaceCompatibleYjsChildren, replaceCompatibleYjsChildren, sameSkeleton, setYjsElementAttributes } from "./replacement.js";
21
- import { splitAncestorPropertyEdits, splitElementPropertyEdits } from "./ancestor-properties.js";
22
- import { boundariesInBatch, boundariesOf, splitChangeTo } from "./boundaries.js";
23
- import { writeSplit } from "./canonical-split.js";
24
- import { editsNodeOf, splitChangeRegions } from "./change-regions.js";
25
- import { enclosureStepsOf, storageFlipsOf, writeEnclosure } from "./enclosures.js";
26
- import { composeTextDeltas, editOf, joinRunsOf, joinWrittenAsCopy, joinedChange, letterEditsIn, lettersInsertedAt, pushDiff, replacedWhole, splitAtRuns, withoutEqualEdges } from "./joins.js";
27
- import { keptScriptsOf, linesChangeByLetters, readLineScripts } from "./letter-scripts.js";
28
- import { RootProjectionIndex } from "./root-projection-index.js";
29
- import { DiffOp } from "diff-match-patch-ts";
30
- import * as Y from "yjs";
31
- //#region src/yjs/core/event-change-bridge.ts
32
- const splitOffMovedEdges = (region, sources, targets) => {
33
- const head = [];
34
- const tail = [];
35
- let { afterFrom, afterTo, beforeFrom, beforeTo } = region;
36
- for (;;) if (beforeFrom < beforeTo && sources.has(beforeFrom)) {
37
- head.push({
38
- afterFrom,
39
- afterTo: afterFrom,
40
- beforeFrom,
41
- beforeTo: beforeFrom + 1
42
- });
43
- beforeFrom += 1;
44
- } else if (afterFrom < afterTo && targets.has(afterFrom)) {
45
- head.push({
46
- afterFrom,
47
- afterTo: afterFrom + 1,
48
- beforeFrom,
49
- beforeTo: beforeFrom
50
- });
51
- afterFrom += 1;
52
- } else if (beforeFrom < beforeTo && sources.has(beforeTo - 1)) {
53
- tail.unshift({
54
- afterFrom: afterTo,
55
- afterTo,
56
- beforeFrom: beforeTo - 1,
57
- beforeTo
58
- });
59
- beforeTo -= 1;
60
- } else if (afterFrom < afterTo && targets.has(afterTo - 1)) {
61
- tail.unshift({
62
- afterFrom: afterTo - 1,
63
- afterTo,
64
- beforeFrom: beforeTo,
65
- beforeTo
66
- });
67
- afterTo -= 1;
68
- } else break;
69
- const rest = beforeFrom < beforeTo || afterFrom < afterTo ? [{
70
- afterFrom,
71
- afterTo,
72
- beforeFrom,
73
- beforeTo
74
- }] : [];
75
- return [
76
- ...head,
77
- ...rest,
78
- ...tail
79
- ];
80
- };
81
- const UNCHECKED_IMPORT_FIT = {
82
- admitsText: () => true,
83
- block: (node) => node,
84
- fits: () => true,
85
- holds: () => true
86
- };
87
- const inPlaceRegions = ({ before, from }) => before.map((_, index) => ({
88
- afterFrom: from + index,
89
- afterTo: from + index + 1,
90
- beforeFrom: from + index,
91
- beforeTo: from + index + 1
92
- }));
93
- const shiftPath = (path, by) => by === 0 ? path : [(path[0] ?? failInvariant("Expected a root index")) + by, ...path.slice(1)];
94
- /** A detector's find, read on a window, at its place in the whole root. */
95
- const inRoot = (found, by) => found === null || by === 0 ? found : found.parentPath.length === 0 ? {
96
- ...found,
97
- from: found.from + by
98
- } : {
99
- ...found,
100
- parentPath: shiftPath(found.parentPath, by)
101
- };
102
- const isEmptyYjsText = (node) => node instanceof Y.XmlText && yjsTextLength(node) === 0;
103
- /**
104
- * Moves the root child at `from` to `to` by placeholder. Both indexes are
105
- * root positions, which the lent root index answers for.
106
- */
107
- const applyExactYjsRelocation = (write, from, to) => {
108
- const { root } = write;
109
- const target = getYjsVisibleChild(root, root, from);
110
- if (target === void 0) return false;
111
- settleYjsMoveContests(write, target);
112
- removeYjsVirtualPlaceholderChild(write, root, from, target);
113
- const firstTargetChild = getYjsVisibleChild(root, root, 0);
114
- const hasMultipleTargetChildren = getYjsVisibleChild(root, root, 1) !== void 0;
115
- let removedEmptyTargetChild = false;
116
- if (to === 0 && !hasMultipleTargetChildren && isEmptyYjsText(firstTargetChild)) {
117
- removeYjsChild(write, root, 0);
118
- removedEmptyTargetChild = true;
119
- }
120
- if (to === 0 && root.length === 0 && (firstTargetChild === void 0 || removedEmptyTargetChild)) {
121
- setVirtualYjsMove(write, target, root);
122
- return true;
123
- }
124
- insertYjsChild(write, root, to, createVirtualYjsMovePlaceholder(write, target));
125
- return true;
126
- };
127
- const isElement = (node) => node !== null && NodeApi.isElement(node);
128
- const isText = (node) => node !== null && NodeApi.isText(node);
129
- const nodePropertiesEqual = (left, right, contentKey) => {
130
- const leftProperties = { ...left };
131
- const rightProperties = { ...right };
132
- delete leftProperties[contentKey];
133
- delete rightProperties[contentKey];
134
- return areJsonLikeValuesEqual(leftProperties, rightProperties);
135
- };
136
- /**
137
- * Whether the room's `held` node is the mirror's `node` less children every
138
- * editor built and the room lacks. A container's `authored` set differs by
139
- * the built marks those children carry.
140
- */
141
- const holdsPartOf = (held, node) => {
142
- if (areJsonLikeValuesEqual(held, node)) return true;
143
- if (!NodeApi.isElement(held) || !NodeApi.isElement(node)) return false;
144
- const { authored: _held, children: heldChildren, ...heldProperties } = held;
145
- const { authored: _node, children, ...nodeProperties } = node;
146
- return areJsonLikeValuesEqual(heldProperties, nodeProperties) && matchHeldChildren(heldChildren, children) !== null;
147
- };
148
- const matchHeldChildren = (held, children) => {
149
- let lacking = children.length - held.length;
150
- if (lacking < 0) return null;
151
- const matched = [];
152
- let at = 0;
153
- for (const child of children) if (at < held.length && holdsPartOf(held[at], child)) {
154
- matched.push(at);
155
- at += 1;
156
- } else if (lacking > 0 && NodeApi.isElement(child)) {
157
- matched.push("lacking");
158
- lacking -= 1;
159
- } else return null;
160
- return matched;
161
- };
162
- const textOf = (nodes) => nodes.map((node) => NodeApi.isText(node) ? node.text : textOf(node.children)).join("");
163
- const sameSegment = (left, right) => left.kind === "text" ? right.kind === "text" && areJsonLikeValuesEqual(left.leaves, right.leaves) : right.kind === "element" && areJsonLikeValuesEqual(left.node, right.node);
164
- const findInlineTextCut = (before, after, ancestorPath = []) => {
165
- const oldSegments = segmentPliteChildren(before);
166
- const newSegments = segmentPliteChildren(after);
167
- let from = 0;
168
- while (from < oldSegments.length && from < newSegments.length && sameSegment(oldSegments[from], newSegments[from])) from += 1;
169
- let suffix = 0;
170
- while (suffix < oldSegments.length - from && suffix < newSegments.length - from && sameSegment(oldSegments[oldSegments.length - 1 - suffix], newSegments[newSegments.length - 1 - suffix])) suffix += 1;
171
- const old = oldSegments[from];
172
- const next = newSegments.slice(from, newSegments.length - suffix);
173
- if (oldSegments.length - from - suffix === 1 && old?.kind === "text" && next.length > 1 && ancestorPath.length > 0) {
174
- const start = next[0].from;
175
- const end = newSegments[newSegments.length - suffix]?.from ?? after.length;
176
- const pieces = after.slice(start, end);
177
- const last = next.findLast((segment) => segment.kind === "text");
178
- if (last?.kind === "text" && textOf(pieces) === textOf(old.leaves)) {
179
- const kept = last.from - start;
180
- return {
181
- parentPath: ancestorPath,
182
- siblings: before,
183
- group: from,
184
- cutLeaves: old.leaves,
185
- after: pieces,
186
- from: start,
187
- kept,
188
- leaves: last.leaves,
189
- offset: textOf(pieces.slice(0, kept)).length
190
- };
191
- }
192
- }
193
- if (before.length !== after.length) return null;
194
- let changed = -1;
195
- for (let index = 0; index < before.length; index++) {
196
- if (areJsonLikeValuesEqual(before[index], after[index])) continue;
197
- if (changed !== -1) return null;
198
- changed = index;
199
- }
200
- const oldNode = before[changed];
201
- const newNode = after[changed];
202
- return oldNode && newNode && NodeApi.isElement(oldNode) && NodeApi.isElement(newNode) && nodePropertiesEqual(oldNode, newNode, "children") ? findInlineTextCut(oldNode.children, newNode.children, [...ancestorPath, changed]) : null;
203
- };
204
- const findNestedChildSplice = (before, after, innerParentPath3 = []) => {
205
- if (areJsonLikeValuesEqual(before, after)) return null;
206
- if (before.length === after.length) {
207
- let changedIndex = null;
208
- for (let index = 0; index < before.length; index++) {
209
- if (areJsonLikeValuesEqual(before[index], after[index])) continue;
210
- if (changedIndex !== null) return null;
211
- changedIndex = index;
212
- }
213
- if (changedIndex === null) return null;
214
- const oldNode = before[changedIndex] ?? null;
215
- const newNode = after[changedIndex] ?? null;
216
- if (isElement(oldNode) && isElement(newNode) && nodePropertiesEqual(oldNode, newNode, "children")) {
217
- const nested = findNestedChildSplice(oldNode.children, newNode.children, [...innerParentPath3, changedIndex]);
218
- if (nested !== null) return nested;
219
- }
220
- if (innerParentPath3.length === 0) return null;
221
- return {
222
- after: [newNode],
223
- before: [oldNode],
224
- from: changedIndex,
225
- parentPath: innerParentPath3
226
- };
227
- }
228
- if (innerParentPath3.length === 0) return null;
229
- let from = 0;
230
- while (from < before.length && from < after.length && areJsonLikeValuesEqual(before[from], after[from])) from += 1;
231
- let suffixCount = 0;
232
- while (suffixCount < before.length - from && suffixCount < after.length - from && areJsonLikeValuesEqual(before.at(-1 - suffixCount), after.at(-1 - suffixCount))) suffixCount += 1;
233
- return {
234
- after: after.slice(from, after.length - suffixCount),
235
- before: before.slice(from, before.length - suffixCount),
236
- from,
237
- parentPath: innerParentPath3
238
- };
239
- };
240
- const relocationPathKey = (path) => path.join(".");
241
- const holdsPathOrAncestor = (paths, path) => paths.has(pathKey(path)) || hasIndexedPathAncestor(paths, path);
242
- /**
243
- * Yjs drops a teammate's concurrent edit inside a deleted element, so the
244
- * relocations this adds let a moved element keep its Yjs node.
245
- */
246
- const withKeptAncestorRelocations = (change, letters, root, relocations) => {
247
- const relocationAncestors = /* @__PURE__ */ new Map();
248
- for (const { targetPath } of relocations) for (let depth = 1; depth < targetPath.length; depth += 1) {
249
- const path = targetPath.slice(0, depth);
250
- relocationAncestors.set(relocationPathKey(path), path);
251
- }
252
- if (relocationAncestors.size === 0) return relocations;
253
- const { after, before } = letters;
254
- const removed = [];
255
- const inserted = [];
256
- change.iterChangedRanges((fromA, toA, fromB, toB) => {
257
- removed.push([fromA, toA]);
258
- inserted.push([fromB, toB]);
259
- });
260
- const holds = (ranges, { from, to }) => {
261
- const at = firstEndingAfter(ranges.length, (index) => ranges[index][1], from);
262
- return at < ranges.length && ranges[at][0] <= from && to <= ranges[at][1];
263
- };
264
- const targets = [...relocationAncestors.values()].map((path) => ({
265
- ...after.nodeRange(path),
266
- path
267
- })).filter((range) => holds(inserted, range)).sort((left, right) => left.path.length - right.path.length);
268
- const kept = [];
269
- const keptSources = /* @__PURE__ */ new Set();
270
- const keptTargets = /* @__PURE__ */ new Set();
271
- for (const target of targets) {
272
- if (holdsPathOrAncestor(keptTargets, target.path)) continue;
273
- const span = keptLettersSpan(letters, target.from, target.to);
274
- const element = after.node(target.path);
275
- if (!span || !isElementNode(element)) continue;
276
- const source = before.openContextAt(span.from).find((range) => {
277
- const node = before.node(range.path);
278
- return range.kind === "element" && range.from <= span.from && span.to <= range.to && holds(removed, range) && isElementNode(node) && node.type === element.type && jsonEqual(node.children, element.children);
279
- });
280
- if (!source || holdsPathOrAncestor(keptSources, source.path)) continue;
281
- keptSources.add(pathKey(source.path));
282
- keptTargets.add(pathKey(target.path));
283
- kept.push(Object.freeze({
284
- path: source.path,
285
- root,
286
- targetPath: target.path
287
- }));
288
- }
289
- return kept.length === 0 ? relocations : [...kept, ...relocations.filter(({ path, targetPath }) => !holdsPathOrAncestor(keptSources, path) && !holdsPathOrAncestor(keptTargets, targetPath))];
290
- };
291
- const nodeAtPath = (children, [top, ...rest]) => rest.reduce((node, index) => getDefined(node.children[index]), getDefined(children.at(getDefined(top))));
292
- const createYjsNodeWithRelocations = (write, node, path, relocationTargets, isSetValued, contexts) => {
293
- const relocationTarget = relocationTargets.get(relocationPathKey(path));
294
- if (relocationTarget !== void 0) return createVirtualYjsMovePlaceholder(write, relocationTarget);
295
- const context = contexts.get(node);
296
- if (!context) throw new Error(`Cannot resolve Yjs property context at ${path.join(".")}.`);
297
- if (!isElement(node)) return createYjsNode(node, isSetValued, context);
298
- const element = createYjsNode({
299
- ...node,
300
- children: []
301
- }, isSetValued, context);
302
- if (!(element instanceof Y.XmlElement)) throw new Error("Cannot create a relocated Yjs element from text.");
303
- if (node.children.length > 0) element.insert(0, node.children.map((child, index) => createYjsNodeWithRelocations(write, child, [...path, index], relocationTargets, isSetValued, contexts)));
304
- return element;
305
- };
306
- const isYjsNode = (value) => value instanceof Y.XmlElement || value instanceof Y.XmlText;
307
- const copyDelta = (delta) => delta.map((part) => ({
308
- ...typeof part.delete === "number" ? { delete: part.delete } : {},
309
- ...part.insert === void 0 ? {} : { insert: Array.isArray(part.insert) ? [...part.insert] : part.insert },
310
- ...typeof part.retain === "number" ? { retain: part.retain } : {}
311
- }));
312
- const changedEventKeys = (event) => {
313
- if (event instanceof Y.YTextEvent) return [...event.keysChanged];
314
- if (event instanceof Y.YXmlEvent) return [...event.attributesChanged];
315
- return [...event.keys.keys()];
316
- };
317
- /**
318
- * Whether a batch wrote or dropped a node, or hid or showed one, rather than
319
- * only changing letters in text it kept.
320
- */
321
- const batchTouchesNodes = (batch) => batch.deletedCuts.length > 0 || batch.deletedChildren.size > 0 || batch.visibilityBefore.size > 0 || batch.events.some(({ childListChanged, delta, target }) => childListChanged && (!(target instanceof Y.XmlText) || delta.some(({ insert }) => insert !== void 0 && typeof insert !== "string")));
322
- const captureYjsEventBatch = (events, transaction) => {
323
- const deletedCuts = [];
324
- const deletedIds = [];
325
- const deletedTextTargets = /* @__PURE__ */ new Set();
326
- const visibilityBefore = /* @__PURE__ */ new Map();
327
- const noteBefore = (node, key, value) => {
328
- const values = visibilityBefore.get(node);
329
- if (!values) visibilityBefore.set(node, /* @__PURE__ */ new Map([[key, value]]));
330
- else if (!values.has(key)) values.set(key, value);
331
- };
332
- const captured = events.map((event) => {
333
- const childListChanged = "childListChanged" in event && event.childListChanged === true;
334
- const keys = changedEventKeys(event);
335
- const { target } = event;
336
- for (const key of keys) if (isYjsNode(target) && YJS_CHILD_VISIBILITY_KEYS.has(key)) noteBefore(target, key, event.keys.get(key)?.oldValue);
337
- return {
338
- childListChanged,
339
- delta: childListChanged ? copyDelta(event.delta) : [],
340
- deleted: childListChanged && target instanceof Y.XmlElement ? [...event.changes.deleted].map(({ content }) => content instanceof Y.ContentType && isYjsNode(content.type) ? content.type : null) : [],
341
- keys,
342
- target
343
- };
344
- });
345
- const deletedItems = /* @__PURE__ */ new Set();
346
- const deletedParents = /* @__PURE__ */ new Set();
347
- Y.iterateDeletedStructs(transaction, transaction.deleteSet, (struct) => {
348
- if (!(struct instanceof Y.Item)) return;
349
- if (struct.parent instanceof Y.XmlText) {
350
- deletedTextTargets.add(struct.parent);
351
- if (isYjsCutItem(struct)) deletedCuts.push(struct);
352
- }
353
- if (!isYjsNode(struct.parent) || struct.parent._item?.deleted !== true) return;
354
- if (struct.parentSub !== null && struct.right === null) {
355
- const value = struct.content.getContent()[0];
356
- if (YJS_CHILD_VISIBILITY_KEYS.has(struct.parentSub)) noteBefore(struct.parent, struct.parentSub, value);
357
- else if (struct.parentSub === "yjs:id" && typeof value === "string") deletedIds.push(value);
358
- }
359
- if (struct.parent instanceof Y.XmlElement && struct.parentSub === null && struct.id.clock < (transaction.beforeState.get(struct.id.client) ?? 0)) {
360
- deletedItems.add(struct);
361
- deletedParents.add(struct.parent);
362
- }
363
- });
364
- const deletedChildren = /* @__PURE__ */ new Map();
365
- for (const parent of deletedParents) {
366
- const children = [];
367
- for (let item = parent._start; item !== null; item = item.right) {
368
- countCoreWork("yjsItemSteps");
369
- if (deletedItems.has(item) && item.content instanceof Y.ContentType && isYjsNode(item.content.type)) children.push(item.content.type);
370
- }
371
- deletedChildren.set(parent, children);
372
- }
373
- return {
374
- deletedChildren,
375
- deletedCuts,
376
- deletedIds,
377
- deletedTextTargets: [...deletedTextTargets],
378
- events: captured,
379
- visibilityBefore
380
- };
381
- };
382
- const mergeYjsEventBatches = (left, right) => {
383
- if (left === null) return right;
384
- const visibilityBefore = new Map(left.visibilityBefore);
385
- for (const [node, values] of right.visibilityBefore) {
386
- const first = visibilityBefore.get(node);
387
- visibilityBefore.set(node, first ? new Map([...values, ...first]) : values);
388
- }
389
- return {
390
- deletedChildren: new Map([...right.deletedChildren, ...left.deletedChildren]),
391
- deletedCuts: [...left.deletedCuts, ...right.deletedCuts],
392
- deletedIds: [...left.deletedIds, ...right.deletedIds],
393
- deletedTextTargets: [.../* @__PURE__ */ new Set([...left.deletedTextTargets, ...right.deletedTextTargets])],
394
- events: [...left.events, ...right.events],
395
- visibilityBefore
396
- };
397
- };
398
- const measureTokenLength = (node) => {
399
- if (NodeApi.isText(node)) return {
400
- length: String(node.text).length + 2,
401
- nodes: 1
402
- };
403
- let length = 2;
404
- let nodes = 1;
405
- for (const child of node.children) {
406
- const measured = measureTokenLength(child);
407
- length += measured.length;
408
- nodes += measured.nodes;
409
- }
410
- return {
411
- length,
412
- nodes
413
- };
414
- };
415
- let tokenLengthPrioritySeed = 2654435769;
416
- const nextTokenLengthPriority = () => {
417
- tokenLengthPrioritySeed ^= tokenLengthPrioritySeed << 13;
418
- tokenLengthPrioritySeed ^= tokenLengthPrioritySeed >>> 17;
419
- tokenLengthPrioritySeed ^= tokenLengthPrioritySeed << 5;
420
- return tokenLengthPrioritySeed >>> 0;
421
- };
422
- const tokenLengthSize = (node) => node?.size ?? 0;
423
- const tokenLengthTotal = (node) => node?.total ?? 0;
424
- const updateTokenLengthNode = (node) => {
425
- node.size = tokenLengthSize(node.left) + tokenLengthSize(node.right) + 1;
426
- node.total = tokenLengthTotal(node.left) + node.length + tokenLengthTotal(node.right);
427
- return node;
428
- };
429
- const createTokenLengthNode = (length) => ({
430
- left: null,
431
- length,
432
- priority: nextTokenLengthPriority(),
433
- right: null,
434
- size: 1,
435
- total: length
436
- });
437
- const mergeTokenLengthNodes = (left, right) => {
438
- if (left === null) return right;
439
- if (right === null) return left;
440
- if (left.priority <= right.priority) {
441
- left.right = mergeTokenLengthNodes(left.right, right);
442
- return updateTokenLengthNode(left);
443
- }
444
- right.left = mergeTokenLengthNodes(left, right.left);
445
- return updateTokenLengthNode(right);
446
- };
447
- const splitTokenLengthNodes = (root, count) => {
448
- if (root === null) return [null, null];
449
- const leftSize = tokenLengthSize(root.left);
450
- if (count <= leftSize) {
451
- const [left, right] = splitTokenLengthNodes(root.left, count);
452
- root.left = right;
453
- return [left, updateTokenLengthNode(root)];
454
- }
455
- const [left, right] = splitTokenLengthNodes(root.right, count - leftSize - 1);
456
- root.right = left;
457
- return [updateTokenLengthNode(root), right];
458
- };
459
- var TokenLengthIndex = class {
460
- measuredNodes = 0;
461
- root = null;
462
- constructor(children) {
463
- this.reset(children);
464
- }
465
- prefix(count) {
466
- let length = 0;
467
- let remaining = Math.max(0, Math.min(count, tokenLengthSize(this.root)));
468
- let current = this.root;
469
- while (current !== null && remaining > 0) {
470
- const leftSize = tokenLengthSize(current.left);
471
- if (remaining <= leftSize) current = current.left;
472
- else {
473
- length += tokenLengthTotal(current.left) + current.length;
474
- remaining -= leftSize + 1;
475
- current = current.right;
476
- }
477
- }
478
- return length;
479
- }
480
- span(from, to) {
481
- const fromBoundary = this.boundary(from);
482
- if (from === to && fromBoundary !== null) return [fromBoundary, fromBoundary];
483
- const fromIndex = fromBoundary ?? Math.min(this.containing(from), this.length);
484
- const toIndex = this.boundary(to) ?? Math.min(this.containing(to) + 1, this.length);
485
- return [fromIndex, Math.max(fromIndex, toIndex)];
486
- }
487
- reset(children) {
488
- this.measuredNodes = 0;
489
- this.root = null;
490
- children.forEach((child) => {
491
- const measured = measureTokenLength(child);
492
- this.measuredNodes += measured.nodes;
493
- this.root = mergeTokenLengthNodes(this.root, createTokenLengthNode(measured.length));
494
- });
495
- }
496
- set(index, node) {
497
- const measured = measureTokenLength(node);
498
- this.root = this.setAt(this.root, index, measured.length);
499
- return measured.nodes;
500
- }
501
- grow(index, delta) {
502
- const from = this.prefix(index);
503
- this.root = this.setAt(this.root, index, this.prefix(index + 1) - from + delta);
504
- }
505
- splice(index, deleteCount, inserted) {
506
- const [left, afterLeft] = splitTokenLengthNodes(this.root, index);
507
- const [, right] = splitTokenLengthNodes(afterLeft, deleteCount);
508
- let middle = null;
509
- let measuredNodes = 0;
510
- for (const node of inserted) {
511
- const measured = measureTokenLength(node);
512
- measuredNodes += measured.nodes;
513
- middle = mergeTokenLengthNodes(middle, createTokenLengthNode(measured.length));
514
- }
515
- this.root = mergeTokenLengthNodes(mergeTokenLengthNodes(left, middle), right);
516
- return measuredNodes;
517
- }
518
- move(from, to) {
519
- if (from === to) return;
520
- const [left, afterLeft] = splitTokenLengthNodes(this.root, from);
521
- const [moved, right] = splitTokenLengthNodes(afterLeft, 1);
522
- const withoutMoved = mergeTokenLengthNodes(left, right);
523
- const [targetLeft, targetRight] = splitTokenLengthNodes(withoutMoved, to);
524
- this.root = mergeTokenLengthNodes(mergeTokenLengthNodes(targetLeft, moved), targetRight);
525
- }
526
- measurement() {
527
- return this.measuredNodes;
528
- }
529
- total() {
530
- return tokenLengthTotal(this.root);
531
- }
532
- get length() {
533
- return tokenLengthSize(this.root);
534
- }
535
- boundary(position) {
536
- if (position < 0 || position > this.total()) return null;
537
- let current = this.root;
538
- let index = 0;
539
- let offset = 0;
540
- while (current !== null) {
541
- const leftSize = tokenLengthSize(current.left);
542
- const start = offset + tokenLengthTotal(current.left);
543
- if (position < start) {
544
- current = current.left;
545
- continue;
546
- }
547
- if (position === start) return index + leftSize;
548
- const end = start + current.length;
549
- if (position < end) return null;
550
- if (position === end) return index + leftSize + 1;
551
- index += leftSize + 1;
552
- offset = end;
553
- current = current.right;
554
- }
555
- return position === offset ? index : null;
556
- }
557
- containing(position) {
558
- let current = this.root;
559
- let index = 0;
560
- let offset = 0;
561
- while (current !== null) {
562
- const leftSize = tokenLengthSize(current.left);
563
- const start = offset + tokenLengthTotal(current.left);
564
- if (position < start) {
565
- current = current.left;
566
- continue;
567
- }
568
- if (position < start + current.length) return index + leftSize;
569
- index += leftSize + 1;
570
- offset = start + current.length;
571
- current = current.right;
572
- }
573
- return index;
574
- }
575
- setAt(node, index, length) {
576
- if (node === null) throw new Error("Cannot update a missing Yjs mirror token length.");
577
- const leftSize = tokenLengthSize(node.left);
578
- if (index < leftSize) node.left = this.setAt(node.left, index, length);
579
- else if (index > leftSize) node.right = this.setAt(node.right, index - leftSize - 1, length);
580
- else node.length = length;
581
- return updateTokenLengthNode(node);
582
- }
583
- };
584
- const rawYjsChildren = (node) => readYjsChildrenNotingPlainList(node).filter(isYjsNode);
585
- const isDeletedYjsNode = (node) => node._item?.deleted === true;
586
- const hasProjectionAttributes = (node) => {
587
- const attributes = getYjsAttributes(node);
588
- for (const key of YJS_CHILD_VISIBILITY_KEYS) if (Object.hasOwn(attributes, key)) return true;
589
- return false;
590
- };
591
- const hasProjectedContent = (node) => {
592
- const stack = [node];
593
- for (let current = stack.pop(); current; current = stack.pop()) {
594
- if (hasProjectionAttributes(current)) return true;
595
- if (current instanceof Y.XmlElement) stack.push(...rawYjsChildren(current));
596
- }
597
- return false;
598
- };
599
- /**
600
- * Whether `node` or a node under it is hidden, so another line shows it. Only
601
- * such a line keeps a rewrite out: a placeholder shows a node no other line
602
- * reads, and the write's settle deletes what the rewrite stops showing.
603
- */
604
- const holdsHiddenNode = (node) => {
605
- const stack = [node];
606
- for (let current = stack.pop(); current; current = stack.pop()) {
607
- if (getYjsAttributes(current)["yjs:hidden"] === true) return true;
608
- if (current instanceof Y.XmlElement) stack.push(...rawYjsChildren(current));
609
- }
610
- return false;
611
- };
612
- const showsAnotherLinesNode = (node) => rawYjsChildren(node).some(holdsHiddenNode);
613
- const lastPlainLevelOnLine = (linePath, top) => {
614
- const ancestors = [];
615
- let { next, node, previous } = top;
616
- let depth = 1;
617
- while (depth < linePath.length && NodeApi.isElement(previous) && NodeApi.isElement(next) && previous.children.length === next.children.length) {
618
- const shown = plainYjsChildren(node);
619
- const index = getDefined(linePath[depth]);
620
- const child = shown?.shownNodeAt(index);
621
- if (!child || shown?.length !== previous.children.length) break;
622
- ancestors.unshift(ancestorType(previous.type));
623
- node = child;
624
- previous = previous.children[index];
625
- next = next.children[index];
626
- depth += 1;
627
- }
628
- return {
629
- ancestors,
630
- depth,
631
- next,
632
- node,
633
- previous
634
- };
635
- };
636
- const sameLetterSkeleton = (before, after) => {
637
- if (NodeApi.isText(before) || NodeApi.isText(after)) {
638
- if (!NodeApi.isText(before) || !NodeApi.isText(after)) return false;
639
- const { text: left, ...beforeMarks } = before;
640
- const { text: right, ...afterMarks } = after;
641
- return left === "" === (right === "") && areJsonLikeValuesEqual(beforeMarks, afterMarks);
642
- }
643
- const { children: left, ...beforeProperties } = before;
644
- const { children: right, ...afterProperties } = after;
645
- return left.length === right.length && areJsonLikeValuesEqual(beforeProperties, afterProperties) && left.every((child, index) => sameLetterSkeleton(child, getDefined(right[index])));
646
- };
647
- const lineHolding = (document, from, to) => {
648
- const holding = document.openContextAt(from).findLast((range) => range.kind === "element" && range.contentFrom <= from && to <= range.contentTo);
649
- if (!holding) return null;
650
- const line = document.node(holding.path);
651
- return NodeApi.isElement(line) && line.children.some(NodeApi.isText) ? holding.path : null;
652
- };
653
- const sameExceptChildren = (before, after) => areJsonLikeValuesEqual({
654
- ...before,
655
- children: []
656
- }, {
657
- ...after,
658
- children: []
659
- });
660
- const getTopLevelNode = (root, target) => {
661
- let current = target;
662
- let { parent } = current;
663
- while (parent !== null && parent !== root) {
664
- current = parent;
665
- ({parent} = current);
666
- }
667
- return parent === root && isYjsNode(current) ? current : null;
668
- };
669
- const isDeltaLength = (value) => typeof value === "number" && Number.isSafeInteger(value) && value > 0;
670
- const parseRootDelta = (before, delta) => {
671
- const regions = [];
672
- let beforeIndex = 0;
673
- let current;
674
- const flush = () => {
675
- if (!current) return;
676
- regions.push(current);
677
- current = void 0;
678
- };
679
- const begin = () => current ??= {
680
- beforeFrom: beforeIndex,
681
- beforeTo: beforeIndex,
682
- nodes: []
683
- };
684
- for (const part of delta) {
685
- if (part.retain !== void 0) {
686
- flush();
687
- if (!isDeltaLength(part.retain) || beforeIndex + part.retain > before.length) return null;
688
- beforeIndex += part.retain;
689
- }
690
- if (part.delete !== void 0) {
691
- if (!isDeltaLength(part.delete) || beforeIndex + part.delete > before.length) return null;
692
- begin();
693
- beforeIndex += part.delete;
694
- (current ?? failInvariant("Expected value to be defined")).beforeTo = beforeIndex;
695
- }
696
- if (part.insert !== void 0) {
697
- if (!Array.isArray(part.insert) || !part.insert.every(isYjsNode)) return null;
698
- begin().nodes.push(...part.insert);
699
- }
700
- }
701
- flush();
702
- const inserted = /* @__PURE__ */ new Set();
703
- for (const region of regions) for (const node of region.nodes) {
704
- if (inserted.has(node)) return null;
705
- inserted.add(node);
706
- const oldIndex = before.indexOf(node);
707
- if (oldIndex !== -1 && !regions.some(({ beforeFrom, beforeTo }) => beforeFrom <= oldIndex && oldIndex < beforeTo)) return null;
708
- }
709
- return regions;
710
- };
711
- /**
712
- * The regions a root delta changes when some root children show another node
713
- * or nothing. It reads inserts, and deletes of children that show nothing and
714
- * held nothing before the batch, such as the joined line a join deletes once a
715
- * later join at the same place keeps another. It refuses a deleted child that
716
- * held children, because a placeholder or a strand elsewhere may have shown
717
- * one of them.
718
- */
719
- const parseProjectedRootDelta = (root, before, delta, deletedChildren) => {
720
- const regions = [];
721
- let visibleAfter;
722
- const showsAfter = (node) => !hasProjectionAttributes(node) || (visibleAfter ??= new Set(getYjsVisibleChildren(root, root))).has(node);
723
- let beforeIndex = 0;
724
- let rawIndex = 0;
725
- for (const part of delta) {
726
- if (part.retain !== void 0) {
727
- if (!isDeltaLength(part.retain) || rawIndex + part.retain > before.rawLength) return null;
728
- const end = rawIndex + part.retain;
729
- while (rawIndex < end) {
730
- const crossing = Math.min(before.nextCrossing(rawIndex), end);
731
- const from = before.visibleBefore(rawIndex);
732
- const shown = before.visibleBefore(crossing) - from;
733
- if (shown > 0 && from !== beforeIndex) return null;
734
- beforeIndex += shown;
735
- rawIndex = crossing;
736
- if (rawIndex === end) break;
737
- const retained = before.rawAt(rawIndex);
738
- if (retained === void 0) return null;
739
- countCoreWork("yjsChildrenRead");
740
- if (before.slotAt(beforeIndex)?.rawIndex === rawIndex) beforeIndex += 1;
741
- else if (before.has(retained) || !hasProjectionAttributes(retained)) return null;
742
- rawIndex += 1;
743
- }
744
- }
745
- if (part.delete !== void 0) {
746
- if (!isDeltaLength(part.delete) || rawIndex + part.delete > before.rawLength) return null;
747
- for (const end = rawIndex + part.delete; rawIndex < end; rawIndex += 1) {
748
- const deleted = before.rawAt(rawIndex);
749
- if (deleted === void 0 || before.has(deleted) || before.visibleBefore(rawIndex + 1) !== before.visibleBefore(rawIndex) || deleted instanceof Y.XmlElement && (deletedChildren.get(deleted)?.length ?? 0) > 0) return null;
750
- }
751
- }
752
- if (part.insert !== void 0) {
753
- if (!Array.isArray(part.insert) || !part.insert.every(isYjsNode)) return null;
754
- const inserted = part.insert;
755
- if (inserted.some((node) => before.has(node) || !showsAfter(node))) return null;
756
- regions.push({
757
- beforeFrom: beforeIndex,
758
- beforeTo: beforeIndex,
759
- nodes: inserted
760
- });
761
- }
762
- }
763
- return regions;
764
- };
765
- const finalizeRootRegions = (base, normalizedNodes, before, showsTopNode) => {
766
- const regions = base.map((region) => ({
767
- beforeFrom: region.beforeFrom,
768
- beforeTo: region.beforeTo,
769
- nodes: [...region.nodes]
770
- }));
771
- for (const node of normalizedNodes) {
772
- const oldIndex = before.indexOf(node);
773
- if (oldIndex === -1) continue;
774
- for (const region of regions) region.nodes = region.nodes.filter((candidate) => candidate !== node);
775
- if (!regions.some(({ beforeFrom, beforeTo }) => beforeFrom <= oldIndex && oldIndex < beforeTo)) regions.push({
776
- beforeFrom: oldIndex,
777
- beforeTo: oldIndex + 1,
778
- nodes: []
779
- });
780
- }
781
- regions.sort((left, right) => left.beforeFrom - right.beforeFrom);
782
- pairTopLevelWraps(regions, before, showsTopNode);
783
- let offset = 0;
784
- let previousTo = 0;
785
- const finalized = [];
786
- for (const region of regions) {
787
- if (region.beforeFrom < previousTo) return null;
788
- const afterFrom = region.beforeFrom + offset;
789
- const afterTo = afterFrom + region.nodes.length;
790
- finalized.push({
791
- afterFrom,
792
- afterTo,
793
- beforeFrom: region.beforeFrom,
794
- beforeTo: region.beforeTo,
795
- nodes: region.nodes
796
- });
797
- offset += region.nodes.length - (region.beforeTo - region.beforeFrom);
798
- previousTo = region.beforeTo;
799
- }
800
- return before.length + offset > 0 ? finalized : null;
801
- };
802
- const pairTopLevelWraps = (regions, before, showsTopNode) => {
803
- for (let index = regions.length - 1; index > 0; index--) {
804
- const removal = regions[index - 1];
805
- const insertion = regions[index];
806
- const old = before.at(removal.beforeFrom);
807
- if (old && removal.nodes.length === 0 && removal.beforeTo === removal.beforeFrom + 1 && insertion.beforeFrom === removal.beforeTo && insertion.beforeTo === insertion.beforeFrom && insertion.nodes.length === 1 && showsTopNode(insertion.nodes[0], old)) {
808
- removal.nodes = insertion.nodes;
809
- regions.splice(index, 1);
810
- }
811
- }
812
- };
813
- const mapRootNodeIndex = (beforeIndex, regions) => {
814
- let offset = 0;
815
- for (const region of regions) {
816
- if (beforeIndex < region.beforeFrom) return beforeIndex + offset;
817
- if (beforeIndex < region.beforeTo) return void 0;
818
- offset += region.nodes.length - (region.beforeTo - region.beforeFrom);
819
- }
820
- return beforeIndex + offset;
821
- };
822
- const mergeRegions = (regions) => {
823
- const ordered = [...regions].sort((left, right) => left.beforeFrom - right.beforeFrom || left.afterFrom - right.afterFrom);
824
- const merged = [];
825
- for (const region of ordered) {
826
- const previous = merged.at(-1);
827
- if (previous && (region.beforeFrom < previous.beforeTo || region.afterFrom < previous.afterTo)) {
828
- previous.beforeTo = Math.max(previous.beforeTo, region.beforeTo);
829
- previous.afterTo = Math.max(previous.afterTo, region.afterTo);
830
- } else merged.push({ ...region });
831
- }
832
- return merged;
833
- };
834
- const internalDocumentChangeRoot = (root) => root ?? "main";
835
- const sparseLowerRegions = (change, rootKey, before, after, lengths) => {
836
- const ranges = [];
837
- change.iterChangedRanges((root, fromBefore, toBefore, fromAfter, toAfter) => {
838
- if (internalDocumentChangeRoot(root) !== rootKey) return;
839
- const [beforeFrom, beforeTo] = lengths.span(fromBefore, toBefore);
840
- ranges.push({
841
- beforeFrom,
842
- beforeTo,
843
- fromAfter,
844
- fromBefore,
845
- toAfter
846
- });
847
- });
848
- ranges.sort((left, right) => left.beforeFrom - right.beforeFrom || left.fromBefore - right.fromBefore);
849
- const stretches = [];
850
- for (const range of ranges) {
851
- const previous = stretches.at(-1);
852
- if (previous && range.beforeFrom < previous.beforeTo) stretches[stretches.length - 1] = {
853
- ...previous,
854
- beforeTo: Math.max(previous.beforeTo, range.beforeTo),
855
- toAfter: range.toAfter
856
- };
857
- else stretches.push(range);
858
- }
859
- if (before.length === after.length && stretches.length <= 1) return stretches.map(({ beforeFrom, beforeTo }) => ({
860
- afterFrom: beforeFrom,
861
- afterTo: beforeTo,
862
- beforeFrom,
863
- beforeTo
864
- }));
865
- const regions = [];
866
- for (const range of stretches) {
867
- const previous = regions.at(-1);
868
- const afterFrom = previous ? previous.afterTo + (range.beforeFrom - previous.beforeTo) : range.beforeFrom;
869
- const beforeBoundary = lengths.prefix(range.beforeFrom);
870
- const afterBoundary = range.fromAfter - (range.fromBefore - beforeBoundary);
871
- const requiredLength = range.toAfter - afterBoundary;
872
- if (afterFrom < 0 || afterFrom > after.length || requiredLength < 0) return null;
873
- let afterTo = afterFrom;
874
- let measuredLength = 0;
875
- while (afterTo < after.length && measuredLength < requiredLength) {
876
- const node = after.at(afterTo);
877
- if (!node) return null;
878
- measuredLength += measureTokenLength(node).length;
879
- afterTo += 1;
880
- }
881
- if (measuredLength < requiredLength) return null;
882
- regions.push({
883
- afterFrom,
884
- afterTo,
885
- beforeFrom: range.beforeFrom,
886
- beforeTo: range.beforeTo
887
- });
888
- }
889
- const last = regions.at(-1);
890
- if (last && after.length - last.afterTo !== before.length - last.beforeTo) return null;
891
- return regions;
892
- };
893
- const isElementValue = (node) => "children" in node;
894
- const sameShell = (left, right) => areJsonLikeValuesEqual({
895
- ...left,
896
- children: []
897
- }, {
898
- ...right,
899
- children: []
900
- });
901
- const splitKeptBlock = (node, before, after, identity, createIndex, offset) => {
902
- const windows = [];
903
- let index;
904
- const at = (path, child) => offset + (index ??= createIndex()).childPosition(path, child);
905
- const descend = (yjs, left, right, path, above) => {
906
- if (areJsonLikeValuesEqual(left, right)) return true;
907
- if (!isElementValue(left) || !isElementValue(right) || !sameShell(left, right) || !left.children.every(isElementValue) || !right.children.every(isElementValue)) return false;
908
- const yjsBefore = identity.before(yjs);
909
- const yjsAfter = identity.after(yjs);
910
- if (!yjsBefore || yjsBefore.length !== left.children.length || yjsAfter.length !== right.children.length || [...yjsBefore, ...yjsAfter].some((child) => !(child instanceof Y.XmlElement) || identity.moved(child))) return false;
911
- const afterIndex = new Map(yjsAfter.map((child, position) => [child, position]));
912
- const ancestors = [ancestorType(left.type), ...above];
913
- const push = (beforeFrom, beforeTo, afterFrom, afterTo) => {
914
- if (beforeFrom === beforeTo && afterFrom === afterTo) return;
915
- windows.push({
916
- after: right.children.slice(afterFrom, afterTo),
917
- ancestors,
918
- before: left.children.slice(beforeFrom, beforeTo),
919
- from: at(path, beforeFrom),
920
- blockPath: path,
921
- start: beforeFrom
922
- });
923
- };
924
- let beforeFrom = 0;
925
- let afterFrom = 0;
926
- for (const [child, yjsChild] of yjsBefore.entries()) {
927
- const kept = afterIndex.get(yjsChild);
928
- if (kept === void 0) continue;
929
- if (kept < afterFrom) return false;
930
- push(beforeFrom, child, afterFrom, kept);
931
- const pushed = windows.length;
932
- if (!descend(yjsChild, left.children[child], right.children[kept], [...path, child], ancestors)) {
933
- windows.length = pushed;
934
- push(child, child + 1, kept, kept + 1);
935
- }
936
- beforeFrom = child + 1;
937
- afterFrom = kept + 1;
938
- }
939
- push(beforeFrom, yjsBefore.length, afterFrom, yjsAfter.length);
940
- return true;
941
- };
942
- return descend(node, before, after, [0], []) ? windows : null;
943
- };
944
- const createEventDocumentChange = (root, before, after, regions, lengths, isSetValued, joins = [], splits = [], unsplits = [], refine = null, scriptsOf) => {
945
- let contexts;
946
- const resolve = (node, key) => {
947
- contexts ??= indexYjsPropertyContexts(before, root === "main" ? null : root, regions.map((region) => ({
948
- from: region.beforeFrom,
949
- to: region.beforeTo
950
- })));
951
- const context = contexts.get(node);
952
- return context ? isSetValued(node, key, context) : false;
953
- };
954
- const byLetters = (left, right, scriptsAt) => {
955
- if (left.length !== right.length) return null;
956
- const lines = left.filter((line, index) => line !== right[index] && !jsonEqual(line, right[index])).length;
957
- const change = linesChangeByLetters(left, right, scriptsAt, resolve);
958
- countCoreWork(change ? "yjsLetterLines" : "yjsValueDiffLines", lines);
959
- return change;
960
- };
961
- const sectionInputs = regions.flatMap((region, regionIndex) => {
962
- const regionAfter = Object.freeze(after(region.afterFrom, region.afterTo));
963
- const regionBefore = Object.freeze(before.slice(region.beforeFrom, region.beforeTo));
964
- const inside = joins.filter(({ lines }) => region.beforeFrom <= lines[0][0] && lines[0][0] < region.beforeTo);
965
- const holds = (top) => region.beforeFrom <= top && top < region.beforeTo;
966
- const cuts = splits.filter(({ line }) => holds(line[0]));
967
- const heals = unsplits.filter(({ left }) => holds(left[0]));
968
- const between = (left, right) => RootChange.betweenChangedBlocks(left, right, {
969
- emptySetsAsValues: true,
970
- isSetValued: resolve,
971
- root: root === "main" ? null : root
972
- });
973
- const shift = ([top, ...rest]) => [top - region.beforeFrom, ...rest];
974
- const linesByLetters = scriptsOf && ((left, right, afterAt, kept) => byLetters(left, right, (index) => kept ? keptScriptsOf(getDefined(right[index])) : scriptsOf(region.afterFrom + afterAt + index, getDefined(right[index]))));
975
- const local = inside.length === 0 ? cuts.length === 0 && heals.length === 0 ? scriptsOf && byLetters(regionBefore, regionAfter, (index) => scriptsOf(region.afterFrom + index, getDefined(regionAfter[index]), region.beforeFrom + index)) : splitChangeTo(DocumentIndex.fromValue(regionBefore), regionAfter, cuts.map(({ levels, line, point }) => ({
976
- levels,
977
- line: shift(line),
978
- point: point.kind === "text" ? {
979
- ...point,
980
- path: shift(point.path)
981
- } : point
982
- })), between, heals.map(({ left, line }) => ({
983
- left: shift(left),
984
- line: shift(line)
985
- })), linesByLetters) : joinedChange(DocumentIndex.fromValue(regionBefore), regionAfter, inside.map((join) => ({
986
- after: join.after === null ? null : join.after - region.afterFrom,
987
- edits: join.edits,
988
- inline: join.inline.map(([first, second]) => [shift(first), shift(second)]),
989
- lines: join.lines.map(shift),
990
- removedElements: join.removedElements
991
- })), between, linesByLetters);
992
- const from = lengths.prefix(region.beforeFrom);
993
- const block = refine?.keptBlockByRegion[regionIndex];
994
- if (!local && refine && block && regionBefore.length === 1 && regionAfter.length === 1) {
995
- const windows = splitKeptBlock(block, regionBefore[0], regionAfter[0], refine.identity, () => DocumentIndex.fromValue(regionBefore), from);
996
- if (windows) return windows.map((window) => {
997
- const { ancestors, blockPath, start } = window;
998
- const path = [region.beforeFrom, ...blockPath.slice(1)];
999
- const lift = (node, key, context) => resolve(node, key) || !contexts?.get(node) && isSetValued(node, key, {
1000
- ...context,
1001
- ancestors: [...context.ancestors, ...ancestors],
1002
- parent: context.parent ?? ancestors[0] ?? null,
1003
- path: [...path, ...context.path.map((part, depth) => depth === 0 ? start + part : part)]
1004
- });
1005
- return Object.freeze({
1006
- after: window.after,
1007
- before: window.before,
1008
- from: window.from,
1009
- local: RootChange.betweenChangedBlocks(DocumentIndex.fromValue(window.before), DocumentIndex.fromValue(window.after), {
1010
- emptySetsAsValues: true,
1011
- isSetValued: lift,
1012
- root: root === "main" ? null : root
1013
- }),
1014
- region: regionIndex
1015
- });
1016
- });
1017
- }
1018
- return [Object.freeze({
1019
- after: regionAfter,
1020
- before: regionBefore,
1021
- from,
1022
- region: regionIndex,
1023
- ...local ? { local } : {}
1024
- })];
1025
- });
1026
- const result = createInternalRootChangeFromSections(root, lengths.total(), sectionInputs, resolve);
1027
- const changedSections = new Set(result.changedSections.map((index) => sectionInputs[index].region));
1028
- let changedChildren = 0;
1029
- regions.forEach((region, index) => {
1030
- if (!changedSections.has(index)) return;
1031
- changedChildren += Math.max(region.beforeTo - region.beforeFrom, region.afterTo - region.afterFrom);
1032
- });
1033
- return {
1034
- change: result.change,
1035
- changedChildren,
1036
- changedRanges: changedSections.size
1037
- };
1038
- };
1039
- const eventNormalizationTargets = (batch) => {
1040
- const insertedNodes = /* @__PURE__ */ new Set();
1041
- const parents = /* @__PURE__ */ new Set();
1042
- const recursiveRoots = /* @__PURE__ */ new Set();
1043
- const truncatedTextNodes = new Set(batch.deletedTextTargets);
1044
- for (const event of batch.events) {
1045
- if (event.childListChanged && event.target instanceof Y.XmlElement) parents.add(event.target);
1046
- if (event.target instanceof Y.XmlText) {
1047
- const { parent } = event.target;
1048
- if (parent instanceof Y.XmlElement) parents.add(parent);
1049
- if (event.delta.some((part) => part.delete !== void 0)) truncatedTextNodes.add(event.target);
1050
- }
1051
- for (const part of event.delta) {
1052
- if (!Array.isArray(part.insert)) continue;
1053
- for (const inserted of part.insert) {
1054
- if (!isYjsNode(inserted)) continue;
1055
- insertedNodes.add(inserted);
1056
- if (inserted instanceof Y.XmlElement) recursiveRoots.add(inserted);
1057
- }
1058
- }
1059
- }
1060
- return {
1061
- insertedNodes,
1062
- parents,
1063
- recursiveRoots,
1064
- truncatedTextNodes
1065
- };
1066
- };
1067
- const combineLowered = (left, right) => {
1068
- if (right.kind !== "lowered") return right;
1069
- if (left.kind !== "lowered") return left;
1070
- return {
1071
- ...right,
1072
- changedRanges: left.changedRanges + right.changedRanges,
1073
- tokenLengthNodes: left.tokenLengthNodes + right.tokenLengthNodes
1074
- };
1075
- };
1076
- const propertiesOf = (node) => Object.fromEntries(Object.entries(node).filter(([key]) => key !== "children"));
1077
- var YjsEventChangeBridge = class {
1078
- fit;
1079
- generation = 0;
1080
- mirror;
1081
- isSetValued;
1082
- lengths;
1083
- maskedBlocks = /* @__PURE__ */ new Set();
1084
- writtenMaskedBlocks = /* @__PURE__ */ new Set();
1085
- /**
1086
- * The lowering commit's letters, by the children of each document it
1087
- * writes: the committed one, and those it writes on the way there. Each
1088
- * names its kept letters in the document the mirror shows while it is
1089
- * written.
1090
- */
1091
- letters = null;
1092
- /** Stored blocks the fill already checked against their mirror block. */
1093
- checkedBlocks = /* @__PURE__ */ new WeakSet();
1094
- ready = false;
1095
- root;
1096
- rootIndex = new RootProjectionIndex();
1097
- rootKey;
1098
- schemaRoot;
1099
- constructor(root, rootKey, children, isSetValued = noSetProperties, fit = UNCHECKED_IMPORT_FIT) {
1100
- this.fit = fit;
1101
- this.mirror = children;
1102
- this.isSetValued = isSetValued;
1103
- this.lengths = new TokenLengthIndex([]);
1104
- this.root = root;
1105
- this.rootKey = rootKey;
1106
- this.schemaRoot = rootKey === "main" ? null : rootKey;
1107
- this.reset(children);
1108
- }
1109
- get synchronized() {
1110
- return this.mirror;
1111
- }
1112
- withRootIndex(pendingRemoteEvents, read) {
1113
- return pendingRemoteEvents === null ? this.readThroughRootIndex(read) : read();
1114
- }
1115
- readThroughRootIndex(read) {
1116
- return this.ready ? withYjsSynchronizedIndex(this.root, this.rootIndex, read) : read();
1117
- }
1118
- setMirror(children) {
1119
- this.generation += 1;
1120
- this.mirror = children;
1121
- }
1122
- lower(write, change, expected, options) {
1123
- this.letters = options.letters ? /* @__PURE__ */ new Map([[expected, yjsLettersOf(options.letters, options.indexes().after, options.indexes().before)]]) : null;
1124
- try {
1125
- return this.lowerCommit(write, change, expected, options);
1126
- } finally {
1127
- this.letters = null;
1128
- }
1129
- }
1130
- lettersOf(children) {
1131
- return this.letters?.get(children);
1132
- }
1133
- lettersAt(children, place) {
1134
- const letters = this.lettersOf(children);
1135
- return letters && {
1136
- letters,
1137
- place: {
1138
- offset: place.offset,
1139
- path: [...place.path]
1140
- }
1141
- };
1142
- }
1143
- /**
1144
- * Record the letters of `document`, a document written on the way to the
1145
- * one `letters` belongs to, which `change` turns into it, so writers of
1146
- * `document`'s children find them.
1147
- */
1148
- recordLettersBefore(document, change, letters) {
1149
- const found = lettersBefore(letters, change, document);
1150
- this.letters?.set(document.nodes, found);
1151
- return found;
1152
- }
1153
- /**
1154
- * Name the kept letters of `children` in `document`, which `changes` wrote
1155
- * from the document they named, because the mirror shows it from now on.
1156
- */
1157
- advanceLetters(children, changes, document) {
1158
- let letters = this.lettersOf(children);
1159
- if (!letters) return;
1160
- for (const change of changes) letters = lettersAfter(letters, change, document);
1161
- this.letters?.set(children, letters);
1162
- }
1163
- lowerCommit(write, change, expected, options) {
1164
- this.writtenMaskedBlocks.clear();
1165
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1166
- const editsNode = (path) => committed !== void 0 && editsNodeOf(committed, options.indexes().before, path);
1167
- return withYjsRootIndex(write, this.rootIndex, () => {
1168
- for (const node of this.maskedBlocks) {
1169
- const index = this.rootIndex.indexOf(node);
1170
- const block = this.mirror.at(index);
1171
- if (index !== -1 && block !== expected.at(index)) {
1172
- this.writtenMaskedBlocks.add(node);
1173
- if (node instanceof Y.XmlElement && NodeApi.isElement(block)) this.writeMissingIn(write, node, block, [index], editsNode);
1174
- }
1175
- }
1176
- const textLine = this.lowerTextLine(write, change, expected, options);
1177
- if (textLine) {
1178
- this.setMirror(expected);
1179
- return textLine;
1180
- }
1181
- this.fillTextGaps(write, change, "before");
1182
- const { inlineJoinedLines, lowered, writtenLines } = this.lowerAgainstMirror(write, change, expected, options);
1183
- if (lowered.kind !== "lowered") return lowered;
1184
- this.setMirror(expected);
1185
- if (options.structureChanged) this.fillTextGaps(write, change, "after");
1186
- const inlineJoined = new Set(inlineJoinedLines);
1187
- for (const line of new Set(writtenLines)) if (!isDeletedYjsNode(line) && getYjsAttributes(line)["yjs:hidden"] !== true) dropYjsTextGaps(write, line, { dropEarlierStored: inlineJoined.has(line) });
1188
- return lowered;
1189
- });
1190
- }
1191
- fillTextGaps(write, change, side) {
1192
- const blocks = /* @__PURE__ */ new Set();
1193
- change.iterChangedRanges((root, fromA, toA, fromB, toB) => {
1194
- if (internalDocumentChangeRoot(root) !== this.rootKey) return;
1195
- const [from, to] = side === "before" ? this.lengths.span(fromA, toA) : this.lengths.span(fromB, toB);
1196
- for (let index = from; index < to; index += 1) blocks.add(index);
1197
- });
1198
- this.fillBlocks(write, blocks, side);
1199
- }
1200
- fillBlocks(write, blocks, side) {
1201
- const children = this.mirror;
1202
- if (!this.ready || this.rootIndex.length !== children.length) return;
1203
- for (const index of blocks) {
1204
- const stored = this.rootIndex.at(index);
1205
- const node = children.at(index);
1206
- if (!(stored instanceof Y.XmlElement) || !node || !NodeApi.isElement(node)) continue;
1207
- if (side === "after" || !this.checkedBlocks.has(stored)) fillYjsTextGaps(write, stored, node);
1208
- this.checkedBlocks.add(stored);
1209
- }
1210
- }
1211
- lowerTextLine(write, change, expected, { indexes, structureChanged }) {
1212
- if (!this.ready || this.rootIndex.length !== this.mirror.length || expected.length !== this.mirror.length) return null;
1213
- const edits = [];
1214
- change.iterChangedRanges((root, fromA, toA, fromB, toB) => {
1215
- if (internalDocumentChangeRoot(root) === this.rootKey) edits.push([
1216
- fromA,
1217
- toA,
1218
- fromB,
1219
- toB
1220
- ]);
1221
- });
1222
- if (edits.length === 0) return null;
1223
- const { after, before } = indexes();
1224
- let path = null;
1225
- let grown = 0;
1226
- for (const [fromA, toA, fromB, toB] of edits) {
1227
- const old = lineHolding(before, fromA, toA);
1228
- if (!old || !PathApi.equals(old, lineHolding(after, fromB, toB) ?? []) || path !== null && !PathApi.equals(path, old)) return null;
1229
- path = old;
1230
- grown += toB - fromB - (toA - fromA);
1231
- }
1232
- const linePath = getDefined(path);
1233
- const top = getDefined(linePath[0]);
1234
- const topNode = this.rootIndex.at(top);
1235
- const topPrevious = this.mirror.at(top);
1236
- if (!(topNode instanceof Y.XmlElement) || this.maskedBlocks.has(topNode) || topPrevious !== before.child(top)) return null;
1237
- const { ancestors, depth, next, node, previous } = lastPlainLevelOnLine(linePath, {
1238
- next: expected.at(top),
1239
- node: topNode,
1240
- previous: topPrevious
1241
- });
1242
- if (depth === 1 || !NodeApi.isElement(previous) || !NodeApi.isElement(next) || showsAnotherLinesNode(node)) return null;
1243
- if (!this.checkedBlocks.has(node)) {
1244
- fillYjsTextGaps(write, node, previous);
1245
- this.checkedBlocks.add(node);
1246
- }
1247
- const parent = linePath.slice(0, depth - 1);
1248
- const index = getDefined(linePath[depth - 1]);
1249
- if (!replaceCompatibleYjsChildren(write, [node], [previous], [next], 0, this.isSetValued, {
1250
- ancestors,
1251
- offset: index,
1252
- path: parent,
1253
- root: this.schemaRoot
1254
- }, false, void 0, this.lettersAt(expected, {
1255
- offset: index,
1256
- path: parent
1257
- }))) return null;
1258
- if (structureChanged) fillYjsTextGaps(write, node, next);
1259
- this.lengths.grow(top, grown);
1260
- return {
1261
- changedRanges: edits.length,
1262
- inserted: 0,
1263
- kind: "lowered",
1264
- removed: 0,
1265
- start: top,
1266
- strategy: "compatible",
1267
- tokenLengthNodes: 0
1268
- };
1269
- }
1270
- /**
1271
- * Runs a write that replaces the lowering, such as a fallback rewrite, with
1272
- * the root index lent while it matches the Yjs root, so its removals settle
1273
- * contested nodes as the lowering's do.
1274
- */
1275
- rewrite(write, run) {
1276
- return this.ready ? withYjsRootIndex(write, this.rootIndex, run) : run();
1277
- }
1278
- lowerAgainstMirror(write, change, expected, { indexes, structureChanged }) {
1279
- if (!this.ready || this.rootIndex.length !== this.mirror.length) return {
1280
- inlineJoinedLines: [],
1281
- lowered: {
1282
- fallback: "remote-event-mirror-mismatch",
1283
- kind: "fallback"
1284
- },
1285
- writtenLines: []
1286
- };
1287
- if (!structureChanged) return {
1288
- inlineJoinedLines: [],
1289
- lowered: this.lowerRegions(write, change, expected, []),
1290
- writtenLines: []
1291
- };
1292
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1293
- const split = committed ? splitAncestorPropertyEdits(committed, indexes().before) : null;
1294
- if (!split) return this.lowerJoinsAndStructure(write, change, expected, indexes);
1295
- const { mirror } = this;
1296
- const middle = split.inner.apply(indexes().before);
1297
- const addresses = yjsAddressesOf(this.root, mirror);
1298
- const elements = split.peeled.map(({ path }) => ({
1299
- node: addresses.elementAt(path),
1300
- path,
1301
- previous: indexes().before.node(path)
1302
- }));
1303
- const middleNodes = middle.nodes;
1304
- this.setMirror(middleNodes);
1305
- this.advanceLetters(expected, [split.inner], middle);
1306
- const rest = this.lowerJoinsAndStructure(write, createInternalDocumentChange(/* @__PURE__ */ new Map([[this.rootKey, split.outer]])), expected, () => ({
1307
- after: indexes().after,
1308
- before: middle
1309
- }));
1310
- if (rest.lowered.kind !== "lowered" && this.mirror === middleNodes) this.setMirror(mirror);
1311
- else this.lowerPeeledProperties(elements, middle);
1312
- return rest;
1313
- }
1314
- /**
1315
- * Write the peeled properties of each element whose Yjs element the rest of
1316
- * the commit kept. One the rest wrote anew already carries them.
1317
- */
1318
- lowerPeeledProperties(elements, document) {
1319
- for (const { node, path, previous } of elements) {
1320
- if (!(node instanceof Y.XmlElement) || !this.isLiveInRoot(node)) continue;
1321
- const next = document.node(path);
1322
- const context = createYjsPropertyContext(next, {
1323
- ...createYjsPropertyLocationAt(document.nodes, parentPath(path), this.schemaRoot),
1324
- path
1325
- });
1326
- setYjsElementAttributes(node, propertiesOf(previous), propertiesOf(next), yjsKeyStorageOf(this.isSetValued, next, context));
1327
- }
1328
- }
1329
- /**
1330
- * Writes each root child the mirror holds and the room lacks where the room
1331
- * holds the rest, so a commit in a root every editor built from its spare
1332
- * lowers against a room that holds it.
1333
- */
1334
- writeMissingRoot(write) {
1335
- const visible = getYjsVisibleChildren(this.root, this.root);
1336
- if (!visible.every((child) => child instanceof Y.XmlElement)) return;
1337
- const children = Array.from({ length: this.mirror.length }, (_, index) => getDefined(this.mirror.at(index)));
1338
- const matched = matchHeldChildren(visible.map((child) => readPliteNodeFromYjs(this.root, child, void 0, this.isSetValued)), children);
1339
- if (!matched?.includes("lacking")) return;
1340
- const location = createYjsPropertyLocationAt(this.mirror, [], this.schemaRoot);
1341
- for (const [index, at] of matched.entries()) {
1342
- if (at !== "lacking") continue;
1343
- const child = children[index];
1344
- insertYjsChild(write, this.root, index, createYjsNode(child, this.isSetValued, createYjsPropertyContext(child, {
1345
- ...location,
1346
- path: [index]
1347
- })));
1348
- }
1349
- this.reset(this.mirror);
1350
- }
1351
- writeMissingIn(write, node, element, path, editsNode) {
1352
- if (!element.children.some(NodeApi.isElement)) return;
1353
- const visible = getYjsVisibleChildren(this.root, node);
1354
- let missing = null;
1355
- if (visible.some((child) => child instanceof Y.XmlElement)) {
1356
- const matched = visible.length === element.children.length ? visible.map((_, index) => index) : visible.every((child) => child instanceof Y.XmlElement) ? matchHeldChildren(visible.map((child) => readPliteNodeFromYjs(this.root, child, void 0, this.isSetValued)), element.children) : null;
1357
- if (!matched) return;
1358
- missing = [];
1359
- for (const [index, at] of matched.entries()) {
1360
- const next = element.children[index];
1361
- if (at === "lacking") {
1362
- missing.push(index);
1363
- continue;
1364
- }
1365
- const child = visible[at];
1366
- if (child instanceof Y.XmlElement && NodeApi.isElement(next)) this.writeMissingIn(write, child, next, [...path, index], editsNode);
1367
- }
1368
- if (missing.length === 0) return;
1369
- } else if (visible.some((child) => child.length > 0)) return;
1370
- if (!editsNode(path)) return;
1371
- const room = readPliteNodeFromYjs(this.root, node, void 0, this.isSetValued);
1372
- const location = createYjsPropertyLocationAt(this.mirror, path, this.schemaRoot);
1373
- const context = createYjsPropertyContext(element, {
1374
- ...createYjsPropertyLocationAt(this.mirror, parentPath(path), this.schemaRoot),
1375
- path
1376
- });
1377
- if (missing) for (const index of missing) {
1378
- const child = element.children[index];
1379
- insertYjsChild(write, node, index, createYjsNode(child, this.isSetValued, createYjsPropertyContext(child, {
1380
- ...location,
1381
- path: [...path, index]
1382
- })));
1383
- }
1384
- else replaceYjsChildren(write, node, element.children, this.isSetValued, location);
1385
- setYjsElementAttributes(node, propertiesOf(room), {
1386
- ...propertiesOf(room),
1387
- ...propertiesOf(element)
1388
- }, yjsKeyStorageOf(this.isSetValued, element, context));
1389
- }
1390
- isLiveInRoot(node) {
1391
- if (node._item?.deleted) return false;
1392
- let current = node.parent;
1393
- while (current !== null && current !== this.root) {
1394
- if (current._item?.deleted) return false;
1395
- current = current.parent;
1396
- }
1397
- return current === this.root;
1398
- }
1399
- lowerJoinsAndStructure(write, change, expected, indexes) {
1400
- const joined = this.lowerJoins(write, change, indexes().before, this.lettersOf(expected));
1401
- const afterJoins = joined ? joined.rest && {
1402
- change: joined.rest,
1403
- before: joined.middle
1404
- } : {
1405
- change,
1406
- before: indexes().before
1407
- };
1408
- if (joined?.rest) this.advanceLetters(expected, [joined.inner], joined.middle);
1409
- const inlineJoinedLines = joined?.inlineJoinedLines ?? [];
1410
- const writtenLines = [...joined?.writtenLines ?? []];
1411
- if (afterJoins === null) return {
1412
- inlineJoinedLines,
1413
- lowered: getDefined(joined).lowered,
1414
- writtenLines
1415
- };
1416
- const split = this.lowerSplits(write, afterJoins.change, afterJoins.before);
1417
- const rest = split ? split.rest && {
1418
- change: split.rest,
1419
- before: split.middle
1420
- } : afterJoins;
1421
- if (split?.rest) this.advanceLetters(expected, split.changes, split.middle);
1422
- const lowered = [joined?.lowered, split?.lowered].filter((result) => result !== void 0);
1423
- writtenLines.push(...split?.writtenLines ?? []);
1424
- if (rest === null) return {
1425
- inlineJoinedLines,
1426
- lowered: lowered.reduce(combineLowered),
1427
- writtenLines
1428
- };
1429
- const enclosed = this.lowerEnclosures(write, rest.change, rest.before);
1430
- if (enclosed) return {
1431
- inlineJoinedLines,
1432
- lowered: [...lowered, enclosed].reduce(combineLowered),
1433
- writtenLines
1434
- };
1435
- return {
1436
- inlineJoinedLines,
1437
- lowered: [...lowered, this.lowerStructure(write, rest.change, expected, () => ({
1438
- after: indexes().after,
1439
- before: rest.before
1440
- }))].reduce(combineLowered),
1441
- writtenLines
1442
- };
1443
- }
1444
- flippedNodes(document, flips) {
1445
- const addresses = yjsAddressesOf(this.root, document.nodes);
1446
- return flips.map((flip) => ({
1447
- flip,
1448
- node: addresses.elementAt(flip.path)
1449
- }));
1450
- }
1451
- /**
1452
- * Write anew each key a moved element stores as a set where it now needs a
1453
- * plain value, or the reverse. False when a moved element has no live Yjs
1454
- * element in the root.
1455
- */
1456
- lowerStorageFlips(flipped) {
1457
- for (const { flip, node } of flipped) {
1458
- if (!(node instanceof Y.XmlElement) || !this.isLiveInRoot(node)) return false;
1459
- const next = propertiesOf(flip.element);
1460
- setYjsElementAttributes(node, Object.fromEntries(Object.entries(next).filter(([key]) => !flip.keys.includes(key))), next, yjsKeyStorageOf(this.isSetValued, flip.element, flip.context));
1461
- }
1462
- return true;
1463
- }
1464
- /**
1465
- * Write a commit that only wraps and unwraps, and may set any element's
1466
- * properties but its type, as the shapes that keep every enclosed letter
1467
- * and child: cuts and views at a wrap's text edges, placeholders for the
1468
- * children an element encloses or releases, then each property write on
1469
- * the element's kept Yjs element. Returns null, before any write, for any
1470
- * other commit.
1471
- */
1472
- lowerEnclosures(write, change, before) {
1473
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1474
- if (!committed) return null;
1475
- const whole = enclosureStepsOf(committed, before);
1476
- const split = whole ? null : splitElementPropertyEdits(committed, before);
1477
- const middle = split ? split.inner.apply(before) : before;
1478
- const steps = whole ?? (split && enclosureStepsOf(split.outer, middle));
1479
- if (!steps) return null;
1480
- const moves = [];
1481
- for (const step of steps) {
1482
- const flips = storageFlipsOf(step, this.isSetValued, this.schemaRoot);
1483
- if (!flips) return null;
1484
- moves.push({
1485
- flips,
1486
- step
1487
- });
1488
- }
1489
- let tokenLengthNodes = 0;
1490
- let written = 0;
1491
- for (const { flips, step } of moves) {
1492
- const kept = step.kind === "wrap" ? null : this.flippedNodes(step.before, flips);
1493
- if (!writeEnclosure(write, step, this.isSetValued, this.schemaRoot) || !this.lowerStorageFlips(kept ?? this.flippedNodes(step.after, flips))) {
1494
- if (written === 0) return null;
1495
- return {
1496
- fallback: "remote-event-mirror-mismatch",
1497
- kind: "fallback"
1498
- };
1499
- }
1500
- written += 1;
1501
- const { at, count, made } = step.top;
1502
- tokenLengthNodes += this.lengths.splice(at, count, Array.from({ length: made }, (_, index) => step.after.child(at + index)));
1503
- }
1504
- const { after } = getDefined(steps.at(-1));
1505
- if (split) {
1506
- const addresses = yjsAddressesOf(this.root, after.nodes);
1507
- this.lowerPeeledProperties(split.peeled.map(({ path }) => {
1508
- const at = steps.reduce((position, step) => getDefined(step.change.mapPos(position, 1)), middle.nodeRange(path).from);
1509
- const { path: moved } = getDefined(after.nodeStartingAt(at));
1510
- return {
1511
- node: addresses.elementAt(moved),
1512
- path: moved,
1513
- previous: before.node(path)
1514
- };
1515
- }), after);
1516
- }
1517
- this.setMirror(after.nodes);
1518
- this.ready = this.rootIndex.length === this.mirror.length;
1519
- return this.ready ? {
1520
- changedRanges: steps.length,
1521
- inserted: 0,
1522
- kind: "lowered",
1523
- removed: 0,
1524
- start: Math.min(...steps.map((step) => step.top.at)),
1525
- strategy: "compatible",
1526
- tokenLengthNodes
1527
- } : {
1528
- fallback: "remote-event-mirror-mismatch",
1529
- kind: "fallback"
1530
- };
1531
- }
1532
- /**
1533
- * Write the commit's splits as cuts, each line keeping its Yjs nodes: a
1534
- * cut inside a text becomes a cut embed and a view, and the children after
1535
- * the cut move by placeholder. Returns the document the rest of the commit
1536
- * applies to, that rest and the Yjs lines it wrote, or null, before any
1537
- * write, when the commit holds no split this can write. A split this cannot
1538
- * write after an earlier one it wrote stays in the rest, with every split
1539
- * after it.
1540
- */
1541
- lowerSplits(write, change, before) {
1542
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1543
- const found = committed && boundariesOf(committed, before);
1544
- if (!found) return null;
1545
- const steps = [];
1546
- let current = before;
1547
- try {
1548
- for (const boundary of found.boundaries) {
1549
- const step = RootChange.create(current, {
1550
- from: boundary.at,
1551
- insert: PreparedTokenSlice.fromTokens(boundary.tokens)
1552
- });
1553
- const next = step.apply(current);
1554
- steps.push({
1555
- after: next,
1556
- before: current,
1557
- change: step
1558
- });
1559
- current = next;
1560
- }
1561
- } catch (error) {
1562
- if (error instanceof PreparedTokenSliceStructureError) return null;
1563
- throw error;
1564
- }
1565
- let tokenLengthNodes = 0;
1566
- let inserted = 0;
1567
- let written = 0;
1568
- const writtenLines = [];
1569
- for (const [index, boundary] of found.boundaries.entries()) {
1570
- const step = steps[index];
1571
- const top = step.before.openContextAt(boundary.at)[0]?.path[0];
1572
- const wrote = top === void 0 ? null : writeSplit(write, step.before, step.after, boundary, this.isSetValued, this.schemaRoot);
1573
- if (top === void 0 || wrote === null) {
1574
- if (index === 0) return null;
1575
- break;
1576
- }
1577
- writtenLines.push(...wrote);
1578
- written += 1;
1579
- if (step.after.nodes.length > step.before.nodes.length) {
1580
- inserted += 1;
1581
- tokenLengthNodes += this.lengths.splice(top, 1, [step.after.child(top), step.after.child(top + 1)]);
1582
- } else tokenLengthNodes += this.lengths.set(top, step.after.child(top));
1583
- }
1584
- const middle = written === steps.length ? current : steps[written].before;
1585
- const rest = steps.slice(written).reduceRight((after, step) => after ? step.change.compose(after) : step.change, found.rest);
1586
- this.setMirror(middle.nodes);
1587
- this.ready = this.rootIndex.length === this.mirror.length;
1588
- return {
1589
- changes: steps.slice(0, written).map((step) => step.change),
1590
- lowered: this.ready ? {
1591
- changedRanges: written,
1592
- inserted,
1593
- kind: "lowered",
1594
- removed: 0,
1595
- start: getDefined(before.openContextAt(found.boundaries[0].at)[0]).path[0],
1596
- strategy: "compatible",
1597
- tokenLengthNodes
1598
- } : {
1599
- fallback: "remote-event-mirror-mismatch",
1600
- kind: "fallback"
1601
- },
1602
- middle,
1603
- rest: rest && this.ready ? createInternalDocumentChange(/* @__PURE__ */ new Map([[this.rootKey, rest]])) : null,
1604
- writtenLines
1605
- };
1606
- }
1607
- /**
1608
- * Write the commit's joins as the shape Yjs keeps for a move: each joined
1609
- * line's own edits from the commit's sections while the lines are apart,
1610
- * then a placeholder in the first line for each child of the lines joined
1611
- * into it, then the joined and removed lines hidden. Returns the document
1612
- * the rest of the commit applies to, that rest and the Yjs lines it wrote,
1613
- * or null, before any write, when the commit holds no join this can write.
1614
- */
1615
- lowerJoins(write, change, before, letters) {
1616
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1617
- if (!committed) return null;
1618
- const edges = withoutEqualEdges(committed, before);
1619
- const found = joinRunsOf(edges, before);
1620
- const copied = found?.length === 0 ? joinWrittenAsCopy(edges, before) : null;
1621
- const rootChange = copied ?? edges;
1622
- const runs = copied ? joinRunsOf(copied, before) : found;
1623
- if (!runs || runs.length === 0) return null;
1624
- const split = splitAtRuns(rootChange, runs);
1625
- if (!split) return null;
1626
- let middle;
1627
- try {
1628
- middle = split.inner.apply(before);
1629
- } catch (error) {
1630
- if (error instanceof PreparedTokenSliceStructureError) return null;
1631
- throw error;
1632
- }
1633
- const planned = [];
1634
- const middleLetters = letters && this.recordLettersBefore(middle, split.outer, letters);
1635
- for (const run of runs) {
1636
- const join = this.planJoin(write, run, before, middle, split.inner, middleLetters);
1637
- if (!join) return null;
1638
- planned.push(join);
1639
- }
1640
- for (const join of planned) join.edit();
1641
- for (const join of planned) join.place();
1642
- const removals = /* @__PURE__ */ new Map();
1643
- for (const { parent, removed } of planned) removals.set(parent, [...removals.get(parent) ?? [], ...removed]);
1644
- const places = new Map(planned.flatMap((join) => [...join.places]));
1645
- for (const [parent, nodes] of removals) {
1646
- const visible = this.visibleChildrenOf(parent);
1647
- const indexes = nodes.map((node) => [visible.indexOf(node), node]).sort(([a], [b]) => b - a);
1648
- for (const [index, node] of indexes) {
1649
- if (index === -1) continue;
1650
- if (places.has(node) && node instanceof Y.XmlElement) removeJoinedYjsLine(write, parent, index, node, places);
1651
- else if (!removeYjsVirtualPlaceholderChild(write, parent, index, node)) removeYjsChild(write, parent, index);
1652
- }
1653
- }
1654
- let tokenLengthNodes = 0;
1655
- for (const { joined, lines } of planned) if (lines[0].length > 1) tokenLengthNodes += this.lengths.set(lines[0][0], middle.child(joined[0]));
1656
- for (const { joined, lines } of [...planned].reverse()) if (lines[0].length === 1) tokenLengthNodes += this.lengths.splice(lines[0][0], getDefined(lines.at(-1))[0] - lines[0][0] + 1, [middle.child(joined[0])]);
1657
- this.setMirror(middle.nodes);
1658
- this.ready = this.rootIndex.length === this.mirror.length;
1659
- const lowered = this.ready ? {
1660
- changedRanges: runs.length,
1661
- inserted: 0,
1662
- kind: "lowered",
1663
- removed: 0,
1664
- start: runs[0].lines[0][0],
1665
- strategy: "compatible",
1666
- tokenLengthNodes
1667
- } : {
1668
- fallback: "remote-event-mirror-mismatch",
1669
- kind: "fallback"
1670
- };
1671
- const rest = split.outer.sections.some((value, index) => index % 2 === 1 && value !== -1);
1672
- return {
1673
- inlineJoinedLines: planned.filter((_, index) => runs[index].inline.length > 0).map(({ joinedLine }) => joinedLine),
1674
- inner: split.inner,
1675
- lowered,
1676
- middle,
1677
- rest: rest && this.ready ? createInternalDocumentChange(/* @__PURE__ */ new Map([[this.rootKey, split.outer]])) : null,
1678
- writtenLines: planned.map(({ joinedLine }) => joinedLine)
1679
- };
1680
- }
1681
- /**
1682
- * Plan one run's writes, reading each joined line's children against its
1683
- * Yjs children and the joined line's children in order. Returns null when
1684
- * they do not line up.
1685
- */
1686
- planJoin(write, run, before, middle, inner, letters) {
1687
- const addresses = yjsAddressesOf(this.root, before.nodes);
1688
- const parent = addresses.elementAt(run.lines[0].slice(0, -1));
1689
- if (parent === null) return null;
1690
- const childAt = (path) => yjsNodeOf(addresses.childAt(parent, getDefined(path.at(-1))));
1691
- const lines = run.lines.map(childAt);
1692
- const removed = run.removed.map(childAt).filter((node) => node !== null);
1693
- if (!removed.every((node) => node !== void 0)) return null;
1694
- const levels = [{
1695
- paths: run.lines,
1696
- yjs: lines
1697
- }, ...run.inline.map((paths) => ({
1698
- paths,
1699
- yjs: paths.map((path) => addresses.elementAt(path))
1700
- }))];
1701
- const yjsLevels = [];
1702
- const edits = [];
1703
- const gone = [];
1704
- let joinedPath;
1705
- for (const [depth, level] of levels.entries()) {
1706
- const path = middle.nodeStartingAt(getDefined(inner.mapPos(before.nodeRange(level.paths[0]).from, 1)))?.path;
1707
- const joined = path && middle.node(path);
1708
- const first = before.node(level.paths[0]);
1709
- if (!path || !NodeApi.isElement(joined) || !NodeApi.isElement(first) || !level.yjs.every((line) => line instanceof Y.XmlElement)) return null;
1710
- const yjsLines = level.yjs;
1711
- yjsLevels.push(yjsLines);
1712
- const inward = levels[depth + 1]?.paths;
1713
- const plan = this.planLineWrites(write, inner, before, level.paths.map((at, index) => [at, yjsLines[index]]), joined, path, (offset) => createYjsPropertyLocationAt(middle.nodes, path, this.schemaRoot, offset), letters, inward && [getDefined(inward[0].at(-1)), getDefined(inward[1].at(-1))]);
1714
- if (!plan) return null;
1715
- edits.push(...plan.edits);
1716
- gone.push(...plan.gone);
1717
- joinedPath ??= path;
1718
- const firstProperties = propertiesOf(first);
1719
- const joinedProperties = propertiesOf(joined);
1720
- if (!areJsonLikeValuesEqual(firstProperties, joinedProperties)) {
1721
- const context = createYjsPropertyContext(joined, {
1722
- ...createYjsPropertyLocationAt(middle.nodes, path.slice(0, -1), this.schemaRoot),
1723
- path
1724
- });
1725
- edits.push(() => setYjsElementAttributes(yjsLines[0], firstProperties, joinedProperties, yjsKeyStorageOf(this.isSetValued, joined, context)));
1726
- }
1727
- }
1728
- const [yjsLines] = yjsLevels;
1729
- const places = /* @__PURE__ */ new Map();
1730
- const append = (line, children) => {
1731
- let end = getYjsVisibleChildren(this.root, line).length;
1732
- for (const child of children) {
1733
- insertYjsChild(write, line, end, createVirtualYjsMovePlaceholder(write, child));
1734
- end += 1;
1735
- }
1736
- };
1737
- return {
1738
- edit: () => {
1739
- for (const edit of edits) edit();
1740
- this.removeLineChildren(write, gone);
1741
- },
1742
- joined: getDefined(joinedPath),
1743
- joinedLine: yjsLines[0],
1744
- lines: run.lines,
1745
- parent,
1746
- place: () => {
1747
- for (const [depth, [first, second]] of yjsLevels.entries()) {
1748
- const inward = yjsLevels[depth + 1];
1749
- if (!inward) break;
1750
- const children = getYjsVisibleChildren(this.root, second);
1751
- append(first, children.slice(children.indexOf(inward[1]) + 1));
1752
- }
1753
- const innermost = getDefined(yjsLevels.at(-1));
1754
- let last = getYjsVisibleChildren(this.root, innermost[0]).at(-1);
1755
- for (const line of innermost.slice(1)) {
1756
- const children = getYjsVisibleChildren(this.root, line);
1757
- const [head] = children;
1758
- const heals = last instanceof Y.XmlText && head instanceof Y.XmlText && continuesYjsText(last, head);
1759
- const emptyEnterCopy = yjsLevels.length > 1 && children.every(isEmptyAttributeFreeYjsText);
1760
- const moved = heals ? children.slice(1) : emptyEnterCopy ? [] : children;
1761
- if (heals) healYjsCut(head);
1762
- append(innermost[0], moved);
1763
- last = moved.at(-1) ?? last;
1764
- const end = moved.length === 0 && !heals ? innermost[0] : null;
1765
- if (last || end) places.set(line, {
1766
- anchor: last ?? null,
1767
- end
1768
- });
1769
- }
1770
- for (const [first, second] of yjsLevels.slice(0, -1)) {
1771
- const anchor = getYjsVisibleChildren(this.root, first).at(-1);
1772
- if (anchor) places.set(second, {
1773
- anchor,
1774
- end: null
1775
- });
1776
- }
1777
- },
1778
- places,
1779
- removed: [...yjsLines.slice(1), ...removed]
1780
- };
1781
- }
1782
- /**
1783
- * Yjs drops a peer's concurrent edits inside a text it deletes, so each
1784
- * kept text takes its letter edits in its own Yjs text instead of being
1785
- * re-created. `inward` names the child of the first line and of the second
1786
- * that join one level in, which the next level's plan writes: the first
1787
- * stands for the joined child, and the second joins it.
1788
- */
1789
- planLineWrites(write, inner, before, lines, joined, joinedPath, location, newLetters, inward) {
1790
- const { children } = joined;
1791
- const starts = newLetters && textStartsOf(newLetters.after, joinedPath, children);
1792
- let at = 0;
1793
- let used = 0;
1794
- let taken = {
1795
- letterEnds: [],
1796
- start: 0
1797
- };
1798
- const take = (count) => {
1799
- const leaves = [];
1800
- const letterEnds = [];
1801
- const leaf = children[at];
1802
- let letters = count;
1803
- taken = {
1804
- letterEnds,
1805
- start: (starts?.[at] ?? 0) + used
1806
- };
1807
- if (letters === 0) {
1808
- if (used === 0 && NodeApi.isText(leaf) && leaf.text === "") {
1809
- at += 1;
1810
- return [leaf];
1811
- }
1812
- return [];
1813
- }
1814
- while (letters > 0) {
1815
- const text = children[at];
1816
- if (!NodeApi.isText(text) || text.text.length === used) return null;
1817
- const length = Math.min(letters, text.text.length - used);
1818
- leaves.push({
1819
- ...text,
1820
- text: text.text.slice(used, used + length)
1821
- });
1822
- letterEnds.push(count - letters + length);
1823
- used += length;
1824
- letters -= length;
1825
- if (used === text.text.length) {
1826
- at += 1;
1827
- used = 0;
1828
- }
1829
- }
1830
- return leaves;
1831
- };
1832
- const edits = [];
1833
- const gone = [];
1834
- const insertNewText = (yjsLine, anchor, leaves, offset) => {
1835
- const encode = createYjsRunEncoder(this.isSetValued, location(offset));
1836
- edits.push(() => {
1837
- const visible = getYjsVisibleChildren(this.root, yjsLine);
1838
- insertYjsChild(write, yjsLine, anchor ? visible.indexOf(anchor) : visible.length, createYjsTextChain(leaves, encode));
1839
- });
1840
- };
1841
- for (const [index, [path, yjsLine]] of lines.entries()) {
1842
- const line = before.node(path);
1843
- if (!NodeApi.isElement(line)) return null;
1844
- const retyped = line.type !== joined.type;
1845
- const aligned = alignYjsChildren(line.children, getYjsVisibleChildren(this.root, yjsLine));
1846
- if (!aligned) return null;
1847
- const { segments, targets } = aligned;
1848
- let collected = -1;
1849
- for (const [order, segment] of segments.entries()) {
1850
- const target = targets[order];
1851
- if (segment.kind === "text") {
1852
- const { from } = before.nodeRange([...path, segment.from]);
1853
- const { to } = before.nodeRange([...path, segment.from + segment.leaves.length - 1]);
1854
- const diff = letterEditsIn(inner, before, from, to);
1855
- const offset = at;
1856
- const after = diff && take(diff.reduce((count, [operation, value]) => operation === DiffOp.Delete ? count : count + value.length, 0));
1857
- if (!diff || !after) return null;
1858
- if (target?.kind !== "text") {
1859
- if (after.some((leaf) => leaf.text !== "")) {
1860
- const next = targets[order + 1];
1861
- insertNewText(yjsLine, next?.kind === "element" ? next.node : null, after, offset);
1862
- }
1863
- continue;
1864
- }
1865
- const encode = createYjsRunEncoder(this.isSetValued, location(offset));
1866
- const beforePlace = newLetters && placeOfLeaves(newLetters.before, path, segment.from, segment.leaves);
1867
- const runLetters = newLetters && starts && beforePlace ? runLettersOf(newLetters, taken, beforePlace) : void 0;
1868
- edits.push(() => retyped ? rewriteTextRuns(target.chain, after, encode, {
1869
- diff,
1870
- letters: runLetters
1871
- }) : writeTextRuns(target.chain, segment.leaves, after, encode, {
1872
- diff,
1873
- letters: runLetters
1874
- }));
1875
- continue;
1876
- }
1877
- if (target?.kind !== "element") return null;
1878
- if (inward?.[index] === segment.from) {
1879
- if (index === 0) {
1880
- if (used !== 0 || !NodeApi.isElement(children[at])) return null;
1881
- at += 1;
1882
- }
1883
- continue;
1884
- }
1885
- const range = before.nodeRange([...path, segment.from]);
1886
- const edit = editOf(inner, range.from, range.to);
1887
- if (edit === "removed") {
1888
- const inserted = lettersInsertedAt(inner, Math.max(range.from, collected + 1), range.to);
1889
- const offset = at;
1890
- const after = inserted ? take(inserted.length) : [];
1891
- if (inserted === null || !after) return null;
1892
- if (inserted) insertNewText(yjsLine, target.node, after, offset);
1893
- collected = range.to;
1894
- gone.push([yjsLine, target.node]);
1895
- continue;
1896
- }
1897
- if (used !== 0) return null;
1898
- const next = children[at];
1899
- if (!NodeApi.isElement(next)) return null;
1900
- at += 1;
1901
- if (edit === "kept") continue;
1902
- if (!canReplaceCompatibleYjsChildren(this.root, [target.node], [segment.node], [next])) return null;
1903
- const inlineLocation = location(at - 1);
1904
- edits.push(() => replaceCompatibleYjsChildren(write, [target.node], [segment.node], [next], 0, this.isSetValued, inlineLocation, retyped, void 0, newLetters && {
1905
- letters: newLetters,
1906
- place: {
1907
- offset: segment.from,
1908
- path
1909
- }
1910
- }));
1911
- }
1912
- }
1913
- return at === children.length && used === 0 ? {
1914
- edits,
1915
- gone
1916
- } : null;
1917
- }
1918
- removeLineChildren(write, gone) {
1919
- for (const [line, node] of gone) {
1920
- const index = getYjsVisibleChildren(this.root, line).indexOf(node);
1921
- if (index !== -1 && !removeYjsVirtualPlaceholderChild(write, line, index, node)) removeYjsChild(write, line, index);
1922
- }
1923
- }
1924
- lowerStructure(write, change, expected, indexes) {
1925
- const window = this.windowOf(change, expected);
1926
- if (window === "mismatch") return {
1927
- fallback: "remote-event-mirror-mismatch",
1928
- kind: "fallback"
1929
- };
1930
- if (window === null) return this.lowerRegions(write, change, expected, []);
1931
- const inPlace = window !== "many" && sameSkeleton(window.before, window.after) ? inPlaceRegions(window) : null;
1932
- let regions;
1933
- if (inPlace) {
1934
- regions = sparseLowerRegions(change, this.rootKey, this.mirror, expected, this.lengths);
1935
- if (regions === null || regions.every((region) => region.beforeTo - region.beforeFrom === region.afterTo - region.afterFrom)) return this.lowerRegions(write, change, expected, [], regions, indexes().before);
1936
- }
1937
- const exactMove = getExactDocumentChangeRelocation(change, this.rootKey, indexes().before);
1938
- const relocationResult = exactMove ? this.lowerExactRelocation(write, change, expected, exactMove) : null;
1939
- if (relocationResult !== null) return relocationResult;
1940
- const detected = window === "many" ? null : this.lowerInlineTextCut(write, change, expected, window) ?? this.lowerNestedChildSplice(write, change, expected, window, indexes) ?? this.lowerRootSplice(write, change, expected, window, indexes);
1941
- if (detected !== null) return detected;
1942
- const { after, before } = indexes();
1943
- const relocations = this.relocationsOf(change, before, after);
1944
- if (relocations.length === 0 && inPlace) return this.lowerRegions(write, change, expected, [], inPlace, before);
1945
- const parts = this.regionPartsOf(change, expected, indexes);
1946
- if (parts) return this.lowerRegionParts(write, parts, expected, indexes);
1947
- return this.lowerRegions(write, change, expected, relocations, regions, before);
1948
- }
1949
- /**
1950
- * The root children the change removes whole, from their open token
1951
- * through their close, as indexes in `before`. A change of a block's type
1952
- * replaces only its open token and keeps the block. A move between root
1953
- * children leaves the blocks between them untouched, so it lowers as a
1954
- * relocation and never reaches this. A move inside one block deletes and
1955
- * inserts the same tokens, which reads like a replacement, so a nested
1956
- * element keeps pairing by shape.
1957
- */
1958
- replacedElements(change, before) {
1959
- const replaced = /* @__PURE__ */ new Set();
1960
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1961
- if (!committed) return replaced;
1962
- let position = 0;
1963
- for (let index = 0; index < committed.sections.length; index += 2) {
1964
- const length = committed.sections[index];
1965
- const at = position;
1966
- position += length;
1967
- if (committed.sections[index + 1] < 0 || length === 0) continue;
1968
- for (const range of before.nodeRangesTouching(at, at + length)) if (range.kind === "element" && range.path.length === 1 && at <= range.from && range.to <= at + length) replaced.add(range.path[0]);
1969
- }
1970
- return replaced;
1971
- }
1972
- /**
1973
- * The change's regions as parts each lowered on its own, so a region that
1974
- * keeps its element is written inside it whatever another region needs.
1975
- * Null for one region, a move, or a change whose top-level regions all
1976
- * replace in place already.
1977
- */
1978
- regionPartsOf(change, expected, indexes) {
1979
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1980
- const { after, before } = indexes();
1981
- if (!committed || this.replacesInPlace(change, expected, before)) return null;
1982
- const parts = splitChangeRegions(committed, before, (from, to) => this.lengths.span(from, to));
1983
- return parts && this.movesOf(change, before, after).length === 0 ? parts : null;
1984
- }
1985
- replacesInPlace(change, expected, before) {
1986
- const regions = sparseLowerRegions(change, this.rootKey, this.mirror, expected, this.lengths);
1987
- const removed = this.replacedElements(change, before);
1988
- return regions !== null && regions.every((region) => canReplaceCompatibleYjsChildren(this.root, this.rootIndex.slice(region.beforeFrom, region.beforeTo), this.mirror.slice(region.beforeFrom, region.beforeTo), expected.slice(region.afterFrom, region.afterTo), 0, (index) => removed.has(region.beforeFrom + index)));
1989
- }
1990
- relocationsOf(change, before, after) {
1991
- const relocations = getDocumentChangeRelocations(change, this.rootKey, before, after);
1992
- const committed = getInternalDocumentRootChange(change, this.rootKey);
1993
- const letters = [...this.letters?.values() ?? []].find((entry) => entry.before === before && entry.after === after);
1994
- return committed && letters ? withKeptAncestorRelocations(committed, letters, this.schemaRoot, relocations) : relocations;
1995
- }
1996
- /**
1997
- * The change's relocations that move a node. A sibling that only shifts
1998
- * reads as a relocation too, but a move removes its node from inside one of
1999
- * the change's ranges.
2000
- */
2001
- movesOf(change, before, after) {
2002
- const removed = [];
2003
- getInternalDocumentRootChange(change, this.rootKey)?.iterChangedRanges((from, to) => {
2004
- if (from < to) removed.push([from, to]);
2005
- });
2006
- return this.relocationsOf(change, before, after).filter(({ path }) => {
2007
- const range = before.nodeRange(path);
2008
- return removed.some(([from, to]) => from <= range.from && range.to <= to);
2009
- });
2010
- }
2011
- lowerRegionParts(write, parts, expected, indexes) {
2012
- let changedRanges = 0;
2013
- let inserted = 0;
2014
- let removed = 0;
2015
- let start = Number.POSITIVE_INFINITY;
2016
- let strategy = "compatible";
2017
- let tokenLengthNodes = 0;
2018
- let letters = this.lettersOf(expected);
2019
- for (let index = parts.length - 1; letters && index > 0; index -= 1) letters = this.recordLettersBefore(parts[index - 1].after, parts[index].change, letters);
2020
- for (const [index, part] of parts.entries()) {
2021
- const last = index === parts.length - 1;
2022
- const next = last ? expected : part.after.nodes;
2023
- if (index > 0) this.advanceLetters(next, parts.slice(0, index).map((earlier) => earlier.change), part.before);
2024
- const result = this.lowerStructure(write, createInternalDocumentChange(/* @__PURE__ */ new Map([[this.rootKey, part.change]])), next, () => ({
2025
- after: last ? indexes().after : part.after,
2026
- before: part.before
2027
- }));
2028
- if (result.kind !== "lowered") return result;
2029
- this.setMirror(next);
2030
- changedRanges += result.changedRanges;
2031
- inserted += result.inserted;
2032
- removed += result.removed;
2033
- start = Math.min(start, result.start);
2034
- tokenLengthNodes += result.tokenLengthNodes;
2035
- if (result.strategy === "range") strategy = "range";
2036
- }
2037
- return {
2038
- changedRanges,
2039
- inserted,
2040
- kind: "lowered",
2041
- removed,
2042
- start,
2043
- strategy,
2044
- tokenLengthNodes
2045
- };
2046
- }
2047
- /**
2048
- * Every block after the changed span is retained, so the after span ends as
2049
- * far from the root's end. Detectors trim inside the window, so a change
2050
- * between equal neighbors stays on the block it touched, where a whole-root
2051
- * trim could slide it to an equal one. A change that leaves blocks untouched
2052
- * between its ranges, such as a move, is `'many'`, because each detector
2053
- * expects one changed stretch.
2054
- */
2055
- windowOf(change, expected) {
2056
- const spans = [];
2057
- change.iterChangedRanges((root, fromA, toA) => {
2058
- if (internalDocumentChangeRoot(root) === this.rootKey) spans.push(this.lengths.span(fromA, toA));
2059
- });
2060
- if (spans.length === 0) return null;
2061
- spans.sort(([a], [b]) => a - b);
2062
- const [from, first] = spans[0];
2063
- let to = first;
2064
- for (const [start, end] of spans) {
2065
- if (start > to) return "many";
2066
- to = Math.max(to, end);
2067
- }
2068
- const afterTo = to + expected.length - this.mirror.length;
2069
- if (to > this.mirror.length || afterTo < from || afterTo > expected.length) return "mismatch";
2070
- return {
2071
- after: expected.slice(from, afterTo),
2072
- before: this.mirror.slice(from, to),
2073
- from
2074
- };
2075
- }
2076
- lowerRegions(write, change, expected, relocations, mergedRegions = sparseLowerRegions(change, this.rootKey, this.mirror, expected, this.lengths), document) {
2077
- const removedElements = document ? this.replacedElements(change, document) : null;
2078
- const replacedIn = (from) => (index) => removedElements?.has(from + index) ?? false;
2079
- if (mergedRegions === null) return {
2080
- fallback: "remote-event-mirror-mismatch",
2081
- kind: "fallback"
2082
- };
2083
- if (mergedRegions.length === 0) {
2084
- if (expected !== this.mirror) return {
2085
- fallback: "remote-event-mirror-mismatch",
2086
- kind: "fallback"
2087
- };
2088
- return {
2089
- changedRanges: 0,
2090
- inserted: 0,
2091
- kind: "lowered",
2092
- removed: 0,
2093
- start: 0,
2094
- strategy: "compatible",
2095
- tokenLengthNodes: 0
2096
- };
2097
- }
2098
- if (relocations.length > 0) {
2099
- const relocated = this.lowerCompositeRelocations(write, expected, mergedRegions, relocations);
2100
- if (relocated !== null) return relocated;
2101
- }
2102
- for (const region of mergedRegions) {
2103
- const touched = this.rootIndex.slice(region.beforeFrom, region.beforeTo);
2104
- const replaced = replacedIn(region.beforeFrom);
2105
- if (touched.some((node, index) => holdsHiddenNode(node) && !replaced(index)) && !canReplaceCompatibleYjsChildren(this.root, touched, this.mirror.slice(region.beforeFrom, region.beforeTo), expected.slice(region.afterFrom, region.afterTo), 0, replaced)) return {
2106
- fallback: "remote-event-projected-content",
2107
- kind: "fallback"
2108
- };
2109
- }
2110
- let inserted = 0;
2111
- let removed = 0;
2112
- let tokenLengthNodes = 0;
2113
- let strategy = "compatible";
2114
- let regionIndex = mergedRegions.length - 1;
2115
- while (regionIndex >= 0) {
2116
- const region = mergedRegions[regionIndex];
2117
- if (region === void 0) {
2118
- regionIndex -= 1;
2119
- continue;
2120
- }
2121
- const before = this.mirror.slice(region.beforeFrom, region.beforeTo);
2122
- const after = expected.slice(region.afterFrom, region.afterTo);
2123
- const touched = this.rootIndex.slice(region.beforeFrom, region.beforeTo);
2124
- if (!replaceCompatibleYjsChildren(write, touched, before, after, 0, this.isSetValued, {
2125
- ancestors: [],
2126
- offset: region.afterFrom,
2127
- path: [],
2128
- root: this.schemaRoot
2129
- }, false, replacedIn(region.beforeFrom), this.lettersAt(expected, {
2130
- offset: region.beforeFrom,
2131
- path: []
2132
- }))) {
2133
- strategy = "range";
2134
- let removeCount = region.beforeTo - region.beforeFrom;
2135
- let removedIndex = 0;
2136
- while (removeCount > 0) {
2137
- const target = touched[removedIndex];
2138
- if (target === void 0 || !removeYjsVirtualPlaceholderChild(write, this.root, region.beforeFrom, target)) removeYjsChild(write, this.root, region.beforeFrom, before[removedIndex]);
2139
- removeCount -= 1;
2140
- removedIndex += 1;
2141
- removed += 1;
2142
- }
2143
- const insertedNodes = after.map((node, index) => createYjsNode(node, this.isSetValued, createYjsPropertyContext(node, {
2144
- ancestors: [],
2145
- path: [region.afterFrom + index],
2146
- root: this.schemaRoot
2147
- })));
2148
- let insertIndex = 0;
2149
- while (insertIndex < insertedNodes.length) {
2150
- const node = insertedNodes[insertIndex];
2151
- if (node !== void 0) {
2152
- insertYjsChild(write, this.root, region.beforeFrom + insertIndex, node);
2153
- inserted += 1;
2154
- }
2155
- insertIndex += 1;
2156
- }
2157
- }
2158
- if (region.beforeTo - region.beforeFrom === region.afterTo - region.afterFrom) for (let index = region.afterFrom; index < region.afterTo; index++) {
2159
- const node = expected.at(index);
2160
- if (node) tokenLengthNodes += this.lengths.set(region.beforeFrom + (index - region.afterFrom), node);
2161
- }
2162
- else tokenLengthNodes += this.lengths.splice(region.beforeFrom, region.beforeTo - region.beforeFrom, after);
2163
- regionIndex -= 1;
2164
- }
2165
- this.ready = this.rootIndex.length === expected.length;
2166
- return {
2167
- changedRanges: mergedRegions.length,
2168
- inserted,
2169
- kind: "lowered",
2170
- removed,
2171
- start: mergedRegions[0]?.beforeFrom ?? 0,
2172
- strategy,
2173
- tokenLengthNodes
2174
- };
2175
- }
2176
- lowerInlineTextCut(write, change, expected, window) {
2177
- const found = findInlineTextCut(window.before, window.after);
2178
- if (!found) return null;
2179
- const cut = {
2180
- ...found,
2181
- parentPath: shiftPath(found.parentPath, window.from)
2182
- };
2183
- const parent = yjsAddressesOf(this.root, this.mirror).elementAt(cut.parentPath);
2184
- if (parent === null) return null;
2185
- const group = alignYjsChildren(cut.siblings, getYjsVisibleChildren(this.root, parent))?.targets[cut.group];
2186
- if (group?.kind !== "text") return null;
2187
- const keptLength = textOf(cut.leaves).length;
2188
- const before = [];
2189
- let offset = 0;
2190
- for (const leaf of cut.cutLeaves) {
2191
- const start = Math.max(0, cut.offset - offset);
2192
- const end = Math.min(leaf.text.length, cut.offset + keptLength - offset);
2193
- if (end > start) before.push({
2194
- ...leaf,
2195
- text: leaf.text.slice(start, end)
2196
- });
2197
- offset += leaf.text.length;
2198
- }
2199
- retainTextChainRange(group.chain, cut.offset, keptLength);
2200
- const location = createYjsPropertyLocationAt(expected, [...cut.parentPath], this.schemaRoot);
2201
- const letters = this.lettersOf(expected);
2202
- const cutPlace = letters && placeOfLeaves(letters.before, cut.parentPath, segmentPliteChildren(cut.siblings)[cut.group].from, cut.cutLeaves);
2203
- const keptPlace = letters && placeOfLeaves(letters.after, cut.parentPath, cut.from + cut.kept, cut.leaves);
2204
- writeTextRuns(group.chain, before.length ? before : [{ text: "" }], cut.leaves, createYjsRunEncoder(this.isSetValued, {
2205
- ...location,
2206
- offset: cut.from + cut.kept
2207
- }), { letters: letters && cutPlace && keptPlace ? runLettersOf(letters, keptPlace, slicePlace(cutPlace, cut.offset, keptLength)) : void 0 });
2208
- const prefix = createYjsNodes(cut.after.slice(0, cut.kept), this.isSetValued, {
2209
- ...location,
2210
- offset: cut.from
2211
- });
2212
- const suffix = createYjsNodes(cut.after.slice(cut.kept + cut.leaves.length), this.isSetValued, {
2213
- ...location,
2214
- offset: cut.from + cut.kept + cut.leaves.length
2215
- });
2216
- suffix.forEach((node, index) => insertYjsChild(write, parent, group.from + group.chain.length + index, node));
2217
- prefix.forEach((node, index) => insertYjsChild(write, parent, group.from + index, node));
2218
- this.rewriteKeptLetters(write, expected, window, cut.parentPath, cut.from, cut.from + cut.after.length, cut.from + cut.cutLeaves.length);
2219
- const topIndex = cut.parentPath[0];
2220
- const topNode = expected.at(topIndex);
2221
- const tokenLengthNodes = topNode ? this.lengths.set(topIndex, topNode) : 0;
2222
- this.ready = this.rootIndex.length === expected.length;
2223
- let changedRanges = 0;
2224
- change.iterChangedRanges((root) => {
2225
- if (internalDocumentChangeRoot(root) === this.rootKey) changedRanges += 1;
2226
- });
2227
- return {
2228
- changedRanges,
2229
- inserted: prefix.length + suffix.length,
2230
- kind: "lowered",
2231
- removed: 0,
2232
- start: topIndex,
2233
- strategy: "compatible",
2234
- tokenLengthNodes
2235
- };
2236
- }
2237
- lowerNestedChildSplice(write, change, expected, window, indexes) {
2238
- const splice = inRoot(findNestedChildSplice(window.before, window.after), window.from);
2239
- if (splice === null) return null;
2240
- const lowered = this.writeNestedChildSplice(write, change, expected, splice, indexes);
2241
- if (lowered === null) return null;
2242
- const { result, written } = lowered;
2243
- this.rewriteKeptLetters(write, expected, window, written.parentPath, written.from, written.from + written.after.length, written.from + written.before.length);
2244
- return result;
2245
- }
2246
- writeNestedChildSplice(write, change, expected, splice, indexes) {
2247
- const parent = yjsAddressesOf(this.root, this.mirror).elementAt(splice.parentPath);
2248
- if (parent === null) return null;
2249
- const visible = getYjsVisibleChildren(this.root, parent);
2250
- const touched = visible.slice(splice.from, splice.from + splice.before.length);
2251
- const beforeSiblings = splice.parentPath.reduce((siblings, index) => siblings.at(index).children, this.mirror);
2252
- const corresponds = visible.length === beforeSiblings.length && visible.every((node, index) => {
2253
- const sibling = beforeSiblings.at(index) ?? null;
2254
- return node instanceof Y.XmlText ? isText(sibling) && sibling.text.length === yjsTextLength(node) : !isText(sibling);
2255
- });
2256
- if (corresponds && replaceCompatibleYjsChildren(write, touched, splice.before, splice.after, 0, this.isSetValued, createYjsPropertyLocationAt(expected, [...splice.parentPath], this.schemaRoot, splice.from), false, void 0, this.lettersAt(expected, {
2257
- offset: splice.from,
2258
- path: splice.parentPath
2259
- }))) return {
2260
- result: this.loweredSplice(change, expected, splice, 0, 0, "compatible"),
2261
- written: splice
2262
- };
2263
- const letters = this.lowerLetterSplice(write, change, expected, splice, parent, indexes);
2264
- if (letters !== null) return {
2265
- result: letters,
2266
- written: {
2267
- after: nodeAtPath(expected, splice.parentPath).children,
2268
- before: beforeSiblings.slice(),
2269
- from: 0,
2270
- parentPath: splice.parentPath
2271
- }
2272
- };
2273
- const edits = this.elementSpliceEdits(change, splice, beforeSiblings, visible, indexes, this.lettersOf(expected));
2274
- if (edits !== null) return {
2275
- result: this.lowerElementSplice(write, change, expected, splice, parent, edits),
2276
- written: splice
2277
- };
2278
- if (!corresponds) return null;
2279
- if (!hasProjectedContent(parent) && !touched.some((node) => hasProjectedContent(node)) && !splice.before.every((node) => isText(node))) return null;
2280
- const location = createYjsPropertyLocationAt(expected, [...splice.parentPath], this.schemaRoot);
2281
- const insertedNodes = splice.after.map((node, index) => createYjsNode(node, this.isSetValued, createYjsPropertyContext(node, {
2282
- ...location,
2283
- path: [...splice.parentPath, splice.from + index]
2284
- })));
2285
- for (const node of splice.before) removeYjsChild(write, parent, splice.from, node);
2286
- insertedNodes.forEach((node, index) => {
2287
- insertYjsChild(write, parent, splice.from + index, node);
2288
- });
2289
- return {
2290
- result: this.loweredSplice(change, expected, splice, insertedNodes.length, splice.before.length, "range"),
2291
- written: splice
2292
- };
2293
- }
2294
- /**
2295
- * A detector writes only the children `[from, to)` of the element at
2296
- * `under`, which stood at `[from, beforeTo)` in the mirror, and keeps every
2297
- * other node of the window because its value did not change, so the new
2298
- * letters such a node holds, such as a word typed over the same word, are
2299
- * written into it in place.
2300
- */
2301
- rewriteKeptLetters(write, expected, window, under, from, to, beforeTo) {
2302
- const letters = this.lettersOf(expected);
2303
- if (!letters) return;
2304
- const addresses = yjsAddressesOf(this.root, expected);
2305
- const writes = [];
2306
- const mirrorIndex = (depth, index) => depth === under.length ? index >= to ? index - to + beforeTo : index : depth === 0 && index > under[0] ? index + window.before.length - window.after.length : index;
2307
- for (let depth = 0; depth <= under.length; depth += 1) {
2308
- const path = under.slice(0, depth);
2309
- const element = addresses.elementAt(path);
2310
- if (element === null) break;
2311
- const location = createYjsPropertyLocationAt(expected, path, this.schemaRoot);
2312
- const [start, end] = depth === 0 ? [window.from, window.from + window.after.length] : [0, nodeAtPath(expected, path).children.length];
2313
- const written = /* @__PURE__ */ new Set();
2314
- for (let index = start; index < end; index += 1) {
2315
- if (depth < under.length ? index === under[depth] : index >= from && index < to) continue;
2316
- if (!holdsNewLetters(letters, path, index, index + 1)) continue;
2317
- const { segment, target } = addresses.childAt(element, index) ?? {};
2318
- if (segment?.kind === "element" && target?.kind === "element") writes.push(() => replaceCompatibleYjsChildren(write, [target.node], [segment.node], [segment.node], 0, this.isSetValued, {
2319
- ...location,
2320
- offset: index
2321
- }, false, void 0, {
2322
- letters,
2323
- place: {
2324
- offset: mirrorIndex(depth, index),
2325
- path
2326
- }
2327
- }));
2328
- else if (segment?.kind === "text" && target?.kind === "text" && !written.has(segment)) {
2329
- written.add(segment);
2330
- const afterPlace = placeOfLeaves(letters.after, path, segment.from, segment.leaves);
2331
- const beforePlace = placeOfLeaves(letters.before, path, mirrorIndex(depth, segment.from), segment.leaves);
2332
- if (afterPlace && beforePlace) writes.push(() => writeTextRuns(target.chain, segment.leaves, segment.leaves, createYjsRunEncoder(this.isSetValued, {
2333
- ...location,
2334
- offset: segment.from
2335
- }), { letters: runLettersOf(letters, afterPlace, beforePlace) }));
2336
- }
2337
- }
2338
- }
2339
- for (const run of writes) run();
2340
- }
2341
- /**
2342
- * The splice as element writes, when its letters stay: the change says
2343
- * which elements it removes or inserts whole, and every other element
2344
- * keeps its Yjs node, so a peer who wrote the same element at the same time
2345
- * writes the same node instead of adding a copy. Null when a kept element's
2346
- * children cannot be written in place.
2347
- */
2348
- elementSpliceEdits(change, splice, siblings, children, indexes, letters) {
2349
- const whole = this.wholeChildren(change, indexes, splice);
2350
- const edits = whole && elementOnlySpliceEdits(siblings.slice(), splice, children, whole);
2351
- if (!edits) return null;
2352
- const updated = edits.updated.filter((edit) => !areJsonLikeValuesEqual(edit.before, edit.after) || letters !== void 0 && holdsNewLetters(letters, splice.parentPath, edit.index, edit.index + 1));
2353
- return updated.every((edit) => canReplaceCompatibleYjsChildren(this.root, [edit.node], [edit.before], [edit.after])) ? {
2354
- ...edits,
2355
- updated
2356
- } : null;
2357
- }
2358
- lowerLetterSplice(write, change, expected, splice, parent, indexes) {
2359
- const committed = getInternalDocumentRootChange(change, this.rootKey);
2360
- if (!committed) return null;
2361
- const { after, before } = indexes();
2362
- const path = [...splice.parentPath];
2363
- const line = before.node(path);
2364
- const next = after.node(path);
2365
- if (!NodeApi.isElement(line) || !NodeApi.isElement(next) || !areJsonLikeValuesEqual(propertiesOf(line), propertiesOf(next))) return null;
2366
- const plan = this.planLineWrites(write, withoutEqualEdges(committed, before), before, [[path, parent]], next, path, (offset) => createYjsPropertyLocationAt(expected, path, this.schemaRoot, offset), this.lettersOf(expected));
2367
- if (!plan || plan.gone.length === 0) return null;
2368
- for (const edit of plan.edits) edit();
2369
- this.removeLineChildren(write, plan.gone);
2370
- return this.loweredSplice(change, expected, splice, 0, plan.gone.length, "compatible");
2371
- }
2372
- /**
2373
- * Which of a stretch of siblings the change removes whole, and which of the
2374
- * nodes in their place it inserts whole.
2375
- */
2376
- wholeChildren(change, indexes, stretch) {
2377
- const committed = getInternalDocumentRootChange(change, this.rootKey);
2378
- if (!committed) return null;
2379
- const { after, before } = indexes();
2380
- const inner = withoutEqualEdges(committed, before);
2381
- const rangesIn = (document, nodes) => nodes.map((_, index) => document.nodeRange([...stretch.parentPath, stretch.from + index]));
2382
- const inserted = replacedWhole(inner, rangesIn(after, stretch.after), true);
2383
- const removed = replacedWhole(inner, rangesIn(before, stretch.before), false);
2384
- const keptIn = (nodes, replaced) => nodes.flatMap((node, index) => replaced[index] || isText(node) ? [] : [index]);
2385
- const sources = keptIn(stretch.before, removed);
2386
- const places = keptIn(stretch.after, inserted);
2387
- const depth = stretch.parentPath.length;
2388
- const childOf = (path) => path.length > depth && stretch.parentPath.every((index, at) => path[at] === index) ? getDefined(path[depth]) - stretch.from : -1;
2389
- return this.movesOf(change, before, after).every(({ path, targetPath }) => {
2390
- const source = sources.indexOf(childOf(path));
2391
- return source !== -1 && places[source] === childOf(targetPath) && path.length === targetPath.length && path.every((index, at) => at <= depth || targetPath[at] === index);
2392
- }) ? {
2393
- inserted,
2394
- removed
2395
- } : null;
2396
- }
2397
- /**
2398
- * The changed top-level blocks as block writes, as lowerNestedChildSplice
2399
- * writes a block's children: the blocks the change removes or inserts whole,
2400
- * and each other block in its Yjs node.
2401
- */
2402
- lowerRootSplice(write, change, expected, window, indexes) {
2403
- const whole = this.wholeChildren(change, indexes, {
2404
- ...window,
2405
- parentPath: []
2406
- });
2407
- if (!whole) return null;
2408
- const touched = this.rootIndex.slice(window.from, window.from + window.before.length);
2409
- const kept = window.before.flatMap((_, index) => whole.removed[index] ? [] : [index]);
2410
- const places = window.after.flatMap((_, index) => whole.inserted[index] ? [] : [index]);
2411
- if (kept.length === 0 || kept.length !== places.length) return null;
2412
- const pairs = kept.map((at, order) => ({
2413
- after: getDefined(window.after[places[order]]),
2414
- before: getDefined(window.before[at]),
2415
- beforeIndex: window.from + at,
2416
- index: window.from + places[order],
2417
- node: getDefined(touched[at])
2418
- }));
2419
- if (touched.some((node, index) => whole.removed[index] && hasProjectedContent(node)) || !pairs.every((pair) => canReplaceCompatibleYjsChildren(this.root, [pair.node], [pair.before], [pair.after]))) return null;
2420
- for (const pair of pairs) replaceCompatibleYjsChildren(write, [pair.node], [pair.before], [pair.after], 0, this.isSetValued, {
2421
- ancestors: [],
2422
- offset: pair.index,
2423
- path: [],
2424
- root: this.schemaRoot
2425
- }, false, void 0, this.lettersAt(expected, {
2426
- offset: pair.beforeIndex,
2427
- path: []
2428
- }));
2429
- let removed = 0;
2430
- for (let index = window.before.length - 1; index >= 0; index--) {
2431
- if (!whole.removed[index]) continue;
2432
- const at = window.from + index;
2433
- if (!removeYjsVirtualPlaceholderChild(write, this.root, at, getDefined(touched[index]))) removeYjsChild(write, this.root, at, window.before[index]);
2434
- removed += 1;
2435
- }
2436
- let inserted = 0;
2437
- for (const [index, node] of window.after.entries()) {
2438
- if (!whole.inserted[index]) continue;
2439
- insertYjsChild(write, this.root, window.from + index, createYjsNode(node, this.isSetValued, createYjsPropertyContext(node, {
2440
- ancestors: [],
2441
- path: [window.from + index],
2442
- root: this.schemaRoot
2443
- })));
2444
- inserted += 1;
2445
- }
2446
- let changedRanges = 0;
2447
- change.iterChangedRanges((root) => {
2448
- if (internalDocumentChangeRoot(root) === this.rootKey) changedRanges += 1;
2449
- });
2450
- const tokenLengthNodes = this.lengths.splice(window.from, window.before.length, window.after);
2451
- this.ready = this.rootIndex.length === expected.length;
2452
- return {
2453
- changedRanges,
2454
- inserted,
2455
- kind: "lowered",
2456
- removed,
2457
- start: window.from,
2458
- strategy: "compatible",
2459
- tokenLengthNodes
2460
- };
2461
- }
2462
- lowerElementSplice(write, change, expected, splice, parent, edits) {
2463
- const location = createYjsPropertyLocationAt(expected, [...splice.parentPath], this.schemaRoot);
2464
- for (const edit of edits.updated) replaceCompatibleYjsChildren(write, [edit.node], [edit.before], [edit.after], 0, this.isSetValued, {
2465
- ...location,
2466
- offset: edit.index
2467
- }, false, void 0, this.lettersAt(expected, {
2468
- offset: edit.beforeIndex,
2469
- path: splice.parentPath
2470
- }));
2471
- const writes = [...edits.removed.map((edit) => ({
2472
- ...edit,
2473
- kind: "remove"
2474
- })), ...edits.inserted.map((edit) => ({
2475
- ...edit,
2476
- kind: "insert"
2477
- }))];
2478
- const removalsFirst = (step) => step.kind === "remove" ? Infinity : step.index;
2479
- writes.sort((left, right) => right.at - left.at || removalsFirst(right) - removalsFirst(left));
2480
- for (const step of writes) if (step.kind === "remove") removeYjsChild(write, parent, step.at, step.node);
2481
- else insertYjsChild(write, parent, step.at, createYjsNode(step.node, this.isSetValued, createYjsPropertyContext(step.node, {
2482
- ...location,
2483
- path: [...splice.parentPath, step.index]
2484
- })));
2485
- return this.loweredSplice(change, expected, splice, edits.inserted.length, edits.removed.length, "compatible");
2486
- }
2487
- loweredSplice(change, expected, splice, inserted, removed, strategy) {
2488
- let changedRanges = 0;
2489
- change.iterChangedRanges((root) => {
2490
- if (internalDocumentChangeRoot(root) === this.rootKey) changedRanges += 1;
2491
- });
2492
- const topIndex = splice.parentPath[0];
2493
- const topNode = expected.at(topIndex);
2494
- const tokenLengthNodes = topNode === void 0 ? 0 : this.lengths.set(topIndex, topNode);
2495
- this.ready = this.rootIndex.length === expected.length;
2496
- return {
2497
- changedRanges,
2498
- inserted,
2499
- kind: "lowered",
2500
- removed,
2501
- start: topIndex,
2502
- strategy,
2503
- tokenLengthNodes
2504
- };
2505
- }
2506
- lowerExactRelocation(write, change, expected, relocation) {
2507
- if (relocation.path.length !== 1 || relocation.targetPath.length !== 1) return null;
2508
- const from = relocation.path[0];
2509
- const to = relocation.targetPath[0];
2510
- const moved = getYjsVisibleChild(write.root, write.root, from);
2511
- if (!applyExactYjsRelocation(write, from, to)) return null;
2512
- this.rewriteMovedLetters(write, expected, [{
2513
- before: [from],
2514
- node: moved,
2515
- path: [to]
2516
- }]);
2517
- let changedRanges = 0;
2518
- change.iterChangedRanges((root) => {
2519
- if (internalDocumentChangeRoot(root) === this.rootKey) changedRanges += 1;
2520
- });
2521
- this.lengths.move(from, to);
2522
- this.ready = this.rootIndex.length === expected.length;
2523
- return {
2524
- changedRanges,
2525
- inserted: 0,
2526
- kind: "lowered",
2527
- removed: 0,
2528
- start: Math.min(relocation.path[0] ?? 0, relocation.targetPath[0] ?? 0),
2529
- strategy: "compatible",
2530
- tokenLengthNodes: 0
2531
- };
2532
- }
2533
- /**
2534
- * A move keeps its Yjs node because the node's value did not change, so
2535
- * the new letters it holds, such as a word typed over the same word, are
2536
- * written into that node in place.
2537
- */
2538
- rewriteMovedLetters(write, expected, moves) {
2539
- for (const { before, node, path } of moves) {
2540
- if (!node) continue;
2541
- replaceCompatibleYjsChildren(write, [node], [nodeAtPath(this.mirror, before)], [nodeAtPath(expected, path)], 0, this.isSetValued, createYjsPropertyLocationAt(expected, parentPath(path), this.schemaRoot, path.at(-1)), false, void 0, this.lettersAt(expected, {
2542
- offset: getDefined(before.at(-1)),
2543
- path: parentPath(before)
2544
- }));
2545
- }
2546
- }
2547
- lowerCompositeRelocations(write, expected, regions, relocations) {
2548
- const relocationTargets = /* @__PURE__ */ new Map();
2549
- const moved = [];
2550
- const addresses = yjsAddressesOf(this.root, this.mirror);
2551
- const propertyContexts = indexYjsPropertyContexts(expected, this.schemaRoot, regions.map((region) => ({
2552
- from: region.afterFrom,
2553
- to: region.afterTo
2554
- })));
2555
- for (const relocation of relocations) {
2556
- const topIndex = relocation.targetPath[0];
2557
- if (!(topIndex !== void 0 && regions.some((region) => region.afterFrom <= topIndex && topIndex < region.afterTo))) {
2558
- const sourceTopIndex = relocation.path[0];
2559
- if (sourceTopIndex !== void 0 && regions.some((region) => region.beforeFrom <= sourceTopIndex && sourceTopIndex < region.beforeTo)) return null;
2560
- continue;
2561
- }
2562
- const parent = addresses.elementAt(relocation.path.slice(0, -1));
2563
- const target = parent && yjsNodeOf(addresses.childAt(parent, getDefined(relocation.path.at(-1))));
2564
- if (!target) return null;
2565
- relocationTargets.set(relocationPathKey(relocation.targetPath), target);
2566
- moved.push({
2567
- before: relocation.path,
2568
- node: target,
2569
- path: relocation.targetPath
2570
- });
2571
- }
2572
- if (relocationTargets.size === 0) return null;
2573
- const blockMoves = relocations.filter(({ path, targetPath }) => path.length === 1 && targetPath.length === 1);
2574
- const sources = new Set(blockMoves.map(({ path }) => getDefined(path[0])));
2575
- const targets = new Set(blockMoves.map(({ targetPath }) => getDefined(targetPath[0])));
2576
- const touchesMove = (region) => relocations.some(({ path, targetPath }) => path[0] !== void 0 && region.beforeFrom <= path[0] && path[0] < region.beforeTo || targetPath[0] !== void 0 && region.afterFrom <= targetPath[0] && targetPath[0] < region.afterTo);
2577
- const prepared = regions.flatMap((region) => splitOffMovedEdges(region, sources, targets)).map((region) => {
2578
- const touched = this.rootIndex.slice(region.beforeFrom, region.beforeTo);
2579
- const before = this.mirror.slice(region.beforeFrom, region.beforeTo);
2580
- const after = expected.slice(region.afterFrom, region.afterTo);
2581
- return {
2582
- after,
2583
- before,
2584
- compatible: canReplaceCompatibleYjsChildren(this.root, touched, before, after, 0) && !touchesMove(region),
2585
- region,
2586
- touched
2587
- };
2588
- });
2589
- for (const entry of prepared) {
2590
- if (!entry.compatible) continue;
2591
- replaceCompatibleYjsChildren(write, entry.touched, entry.before, entry.after, 0, this.isSetValued, {
2592
- ancestors: [],
2593
- offset: entry.region.afterFrom,
2594
- path: [],
2595
- root: this.schemaRoot
2596
- }, false, void 0, this.lettersAt(expected, {
2597
- offset: entry.region.beforeFrom,
2598
- path: []
2599
- }));
2600
- }
2601
- const built = prepared.map((entry) => ({
2602
- at: entry.region.afterFrom,
2603
- nodes: entry.compatible ? [] : entry.after.map((node, index) => createYjsNodeWithRelocations(write, node, [entry.region.afterFrom + index], relocationTargets, this.isSetValued, propertyContexts))
2604
- }));
2605
- let inserted = 0;
2606
- let removed = 0;
2607
- for (const entry of prepared) {
2608
- if (entry.compatible) continue;
2609
- entry.touched.forEach((oldTopNode, offset) => {
2610
- const visibleIndex = this.rootIndex.indexOf(oldTopNode);
2611
- if (visibleIndex === -1) return;
2612
- if (!removeYjsVirtualPlaceholderChild(write, this.root, visibleIndex, oldTopNode)) removeYjsChild(write, this.root, visibleIndex, this.mirror.at(entry.region.beforeFrom + offset));
2613
- removed += 1;
2614
- });
2615
- }
2616
- for (const { at, nodes } of built) nodes.forEach((node, index) => {
2617
- insertYjsChild(write, this.root, at + index, node);
2618
- inserted += 1;
2619
- });
2620
- this.rewriteMovedLetters(write, expected, moved);
2621
- let tokenLengthNodes = 0;
2622
- for (let index = prepared.length - 1; index >= 0; index--) {
2623
- const entry = prepared[index];
2624
- if (!entry) continue;
2625
- tokenLengthNodes += this.lengths.splice(entry.region.beforeFrom, entry.region.beforeTo - entry.region.beforeFrom, expected.slice(entry.region.afterFrom, entry.region.afterTo));
2626
- }
2627
- this.ready = this.rootIndex.length === expected.length;
2628
- return {
2629
- changedRanges: regions.length,
2630
- inserted,
2631
- kind: "lowered",
2632
- removed,
2633
- start: regions[0]?.beforeFrom ?? 0,
2634
- strategy: "range",
2635
- tokenLengthNodes
2636
- };
2637
- }
2638
- /**
2639
- * Normalizing writes to the Yjs root, so the caller runs this in its
2640
- * canonicalize transaction.
2641
- */
2642
- prepareRemote(write, batch, current) {
2643
- if (!batch.events.every(({ target }) => target instanceof Y.XmlText)) this.checkedBlocks = /* @__PURE__ */ new WeakSet();
2644
- return withYjsRootIds(this.root, this.rootIndex, () => {
2645
- this.noteRemoteIds(batch);
2646
- const read = this.ready ? this.readBatch(batch) : null;
2647
- const line = read && current ? this.letterLineOf(batch) : null;
2648
- if (read) for (const { target } of batch.events) for (let node = target instanceof Y.XmlText ? target.parent : target; node instanceof Y.XmlElement && node !== this.root && node !== line?.node.parent; node = node.parent) read.childrenBefore(node);
2649
- const joins = read ? this.findJoins(read) : [];
2650
- const found = read ? boundariesInBatch(read) : {
2651
- splits: [],
2652
- unsplits: []
2653
- };
2654
- const normalization = this.normalize(write, batch);
2655
- const result = (read && current && line && joins.length === 0 && found.splits.length === 0 && found.unsplits.length === 0 ? this.translateLetterLine(read, normalization, line, current) : null) ?? this.translate(batch, read, normalization, joins, found);
2656
- if (result.kind !== "fallback") return result;
2657
- const recover = this.recoverJoins(joins, found);
2658
- return recover ? {
2659
- ...result,
2660
- recover
2661
- } : result;
2662
- });
2663
- }
2664
- letterLineOf(batch) {
2665
- if (batch.deletedCuts.length > 0 || batch.deletedIds.length > 0 || batch.visibilityBefore.size > 0 || this.rootIndex.hasContestChanges()) return null;
2666
- let found = null;
2667
- for (const { delta, keys, target } of batch.events) {
2668
- if (!(target instanceof Y.XmlText) || !keys.every(isYjsMarkRecordKey) || delta.some(({ insert }) => insert !== void 0 && typeof insert !== "string")) return null;
2669
- const views = this.viewsOf(target);
2670
- const shown = views.length === 0 ? [target] : textsChangedBy(target, delta, views, batch.deletedCuts);
2671
- if (shown === null || shown.length === 0) return null;
2672
- for (const text of shown) {
2673
- const line = this.plainLineOf(text);
2674
- if (line === null || found !== null && found.node !== line.node) return null;
2675
- found = line;
2676
- }
2677
- }
2678
- return found;
2679
- }
2680
- viewsOf(text) {
2681
- const id = text.getAttribute(YJS_NODE_ID_KEY);
2682
- return typeof id === "string" ? this.rootIndex.referrersOf(id).filter((node) => node instanceof Y.XmlText) : [];
2683
- }
2684
- plainLineOf(text) {
2685
- const chain = [];
2686
- let shownAt = -1;
2687
- const shown = getYjsAttributes(text)["yjs:hidden"] === true ? this.placeholderShowing(text) : this.namedByElement(text) ? null : text;
2688
- if (!shown) return null;
2689
- for (let node = shown.parent; shownAt === -1;) {
2690
- if (!(node instanceof Y.XmlElement) || node === this.root) return null;
2691
- if (node.parent === this.root) shownAt = this.rootIndex.indexOf(node);
2692
- const hidden = getYjsAttributes(node)[YJS_HIDDEN_KEY] === true;
2693
- if (!hidden && this.namedByElement(node)) return null;
2694
- const slot = shownAt === -1 && hidden ? this.placeholderShowing(node) : node;
2695
- if (slot === null) return null;
2696
- chain.unshift({
2697
- node,
2698
- slot
2699
- });
2700
- node = slot.parent;
2701
- }
2702
- const top = getDefined(chain[0]);
2703
- const path = [shownAt];
2704
- if (this.maskedBlocks.has(top.node)) return null;
2705
- let depth = 0;
2706
- while (depth < chain.length - 1) {
2707
- const index = plainYjsChildren(getDefined(chain[depth]).node)?.indexOfRawChild(getDefined(chain[depth + 1]).slot) ?? -1;
2708
- if (index === -1) break;
2709
- path.push(index);
2710
- depth += 1;
2711
- }
2712
- return depth === 0 ? null : {
2713
- node: getDefined(chain[depth]).node,
2714
- path
2715
- };
2716
- }
2717
- namedByElement(node) {
2718
- const id = node.getAttribute(YJS_NODE_ID_KEY);
2719
- return typeof id === "string" && this.rootIndex.referrersOf(id).some((referrer) => referrer instanceof Y.XmlElement);
2720
- }
2721
- placeholderShowing(node) {
2722
- const id = node.getAttribute(YJS_NODE_ID_KEY);
2723
- if (typeof id !== "string") return null;
2724
- const shown = projectYjsRoot(this.root).referrerOf(id);
2725
- return shown !== null && getYjsAttributes(shown)["yjs:virtual-placeholder"] === true ? shown : null;
2726
- }
2727
- translateLetterLine(read, normalization, line, current) {
2728
- const top = getDefined(line.path[0]);
2729
- const block = this.mirror.at(top);
2730
- for (const node of normalization.removedNodes) {
2731
- let parent = node.parent;
2732
- while (parent instanceof Y.XmlElement && parent !== line.node) ({parent} = parent);
2733
- if (parent !== line.node) return null;
2734
- }
2735
- const index = current();
2736
- if (!block || index.size !== this.mirror.length || index.child(top) !== block) return null;
2737
- const ancestors = [];
2738
- const site = [];
2739
- let container = block;
2740
- for (const position of line.path.slice(1, -1)) {
2741
- if (!NodeApi.isElement(container)) return null;
2742
- ancestors.unshift(ancestorType(container.type));
2743
- site.unshift(container);
2744
- container = getDefined(container.children[position]);
2745
- }
2746
- if (!NodeApi.isElement(container)) return null;
2747
- site.unshift(container);
2748
- const at = getDefined(line.path.at(-1));
2749
- const previous = container.children[at];
2750
- const next = readPliteNodeFromYjs(this.root, line.node, this.fit.admitsText, this.isSetValued);
2751
- if (!previous || !(sameLetterSkeleton(previous, next) || NodeApi.isElement(previous) && NodeApi.isElement(next) && sameExceptChildren(previous, next) && this.fit.fits(next, site))) return null;
2752
- deepFreeze(next);
2753
- ancestors.unshift(ancestorType(container.type));
2754
- const parent = line.path.slice(0, -1);
2755
- const contexts = indexYjsPropertyContexts(container.children, this.schemaRoot, [{
2756
- from: at,
2757
- to: at + 1
2758
- }], {
2759
- ancestors,
2760
- path: parent
2761
- });
2762
- const resolve = (node, key) => {
2763
- const context = contexts.get(node);
2764
- return context ? this.isSetValued(node, key, context) : false;
2765
- };
2766
- const reshaped = /* @__PURE__ */ new Set();
2767
- for (const node of normalization.removedNodes) reshaped.add(node.parent);
2768
- const letters = {
2769
- ...read,
2770
- reshaped,
2771
- sources: /* @__PURE__ */ new Map()
2772
- };
2773
- const scripts = readLineScripts(this.root, line.node, next, letters) ?? readLineScripts(this.root, line.node, next, letters, true);
2774
- const local = linesChangeByLetters([previous], [next], () => scripts, resolve);
2775
- if (!jsonEqual(previous, next)) countCoreWork(local ? "yjsLetterLines" : "yjsValueDiffLines");
2776
- const { change, changedSections } = createInternalRootChangeFromSections(this.rootKey, this.lengths.total(), [{
2777
- after: [next],
2778
- before: [previous],
2779
- from: index.childPosition(parent, at),
2780
- ...local ? { local } : {}
2781
- }], resolve);
2782
- const grown = measureTokenLength(next).length - measureTokenLength(previous).length;
2783
- const ticket = this.generation;
2784
- return {
2785
- import: {
2786
- accept: (published) => {
2787
- if (ticket !== this.generation) return;
2788
- const children = published.nodes;
2789
- this.setMirror(children);
2790
- this.lengths.grow(top, grown);
2791
- this.ready = this.rootIndex.length === children.length;
2792
- },
2793
- change,
2794
- changedChildren: changedSections.length,
2795
- changedRanges: changedSections.length,
2796
- readTopLevelNodes: 0
2797
- },
2798
- kind: "change"
2799
- };
2800
- }
2801
- readFittedBlock(node) {
2802
- const raw = readPliteNodeFromYjs(this.root, node, this.fit.admitsText, this.isSetValued);
2803
- const fitted = deepFreeze(this.fit.block(raw));
2804
- if (areJsonLikeValuesEqual(raw, fitted)) this.maskedBlocks.delete(node);
2805
- else this.maskedBlocks.add(node);
2806
- return fitted;
2807
- }
2808
- refreshMasks(children) {
2809
- this.maskedBlocks.clear();
2810
- for (let index = 0; index < this.rootIndex.length; index++) {
2811
- const node = this.rootIndex.at(index);
2812
- if (node && (children.length !== this.rootIndex.length || !areJsonLikeValuesEqual(readPliteNodeFromYjs(this.root, node, this.fit.admitsText, this.isSetValued), children.at(index)))) this.maskedBlocks.add(node);
2813
- }
2814
- }
2815
- drift(expected, fallback = false) {
2816
- const values = /* @__PURE__ */ new Map();
2817
- for (const node of fallback ? this.maskedBlocks : this.writtenMaskedBlocks) {
2818
- const index = this.rootIndex.indexOf(node);
2819
- if (index === -1) {
2820
- this.maskedBlocks.delete(node);
2821
- continue;
2822
- }
2823
- const fitted = this.readThroughRootIndex(() => this.readFittedBlock(node));
2824
- if (!areJsonLikeValuesEqual(fitted, expected.at(index))) values.set(index, fitted);
2825
- }
2826
- this.writtenMaskedBlocks.clear();
2827
- if (values.size === 0) return null;
2828
- const regions = [...values.keys()].sort((a, b) => a - b).map((index) => ({
2829
- afterFrom: index,
2830
- afterTo: index + 1,
2831
- beforeFrom: index,
2832
- beforeTo: index + 1
2833
- }));
2834
- const prepared = createEventDocumentChange(this.rootKey, expected, (from, to) => Array.from({ length: to - from }, (_, offset) => values.get(from + offset) ?? expected.at(from + offset) ?? failInvariant("Expected drift block")), regions, this.lengths, this.isSetValued);
2835
- const ticket = this.generation;
2836
- return {
2837
- ...prepared,
2838
- accept: (published) => {
2839
- if (ticket !== this.generation) return;
2840
- const children = published.nodes;
2841
- this.setMirror(children);
2842
- for (const index of values.keys()) {
2843
- const child = children.at(index);
2844
- if (child) this.lengths.set(index, child);
2845
- }
2846
- },
2847
- readTopLevelNodes: values.size
2848
- };
2849
- }
2850
- /**
2851
- * Records the ids and virtual references a batch brought, before any
2852
- * reference resolves to them.
2853
- */
2854
- noteRemoteIds(batch) {
2855
- for (const event of batch.events) {
2856
- const { target } = event;
2857
- if (isYjsNode(target)) {
2858
- const id = target.getAttribute(YJS_NODE_ID_KEY);
2859
- const refKey = target instanceof Y.XmlText ? YJS_CUT_SOURCE_KEY : YJS_VIRTUAL_CHILD_ID_KEY;
2860
- const ref = target.getAttribute(refKey);
2861
- if (event.keys.includes("yjs:id") && typeof id === "string") this.rootIndex.noteId(id, target);
2862
- if (event.keys.includes(refKey) && typeof ref === "string") this.rootIndex.noteReferrer(ref, target);
2863
- if (event.keys.some((key) => YJS_CHILD_VISIBILITY_KEYS.has(key))) this.rootIndex.noteChanged(target);
2864
- }
2865
- for (const node of event.deleted) if (node !== null) this.rootIndex.noteChanged(node);
2866
- for (const part of event.delta) {
2867
- if (!Array.isArray(part.insert)) continue;
2868
- for (const inserted of part.insert) {
2869
- if (!isYjsNode(inserted)) continue;
2870
- const tree = readYjsTreeRefs(inserted);
2871
- for (const [id, node] of tree.ids) this.rootIndex.noteId(id, node);
2872
- for (const [id, referrer] of tree.referrers) this.rootIndex.noteReferrer(id, referrer);
2873
- }
2874
- }
2875
- }
2876
- }
2877
- normalize(write, batch) {
2878
- const { insertedNodes, parents, recursiveRoots, truncatedTextNodes } = eventNormalizationTargets(batch);
2879
- return { removedNodes: removeRedundantEmptyYjsTextNodesAt(write, new Set([...parents].filter((parent) => parent.doc === this.root.doc && (parent !== this.root || yjsRootNeedsNormalization(this.root, this.rootIndex, insertedNodes, truncatedTextNodes)))), new Set([...recursiveRoots].filter((node) => node.doc === this.root.doc))) };
2880
- }
2881
- reset(children) {
2882
- this.checkedBlocks = /* @__PURE__ */ new WeakSet();
2883
- this.setMirror(children);
2884
- this.lengths.reset(children);
2885
- this.ready = this.resetRootIndex() && this.rootIndex.length === children.length;
2886
- return this.lengths.measurement();
2887
- }
2888
- /**
2889
- * Returns false for a root that shows a virtual child of its own, which the
2890
- * index cannot hold.
2891
- */
2892
- resetRootIndex() {
2893
- const input = readYjsRootIndex(this.root);
2894
- this.rootIndex.reset(input?.entries ?? [], input?.tree ?? {
2895
- ids: /* @__PURE__ */ new Map(),
2896
- referrers: []
2897
- });
2898
- return input !== null;
2899
- }
2900
- visibleChildrenOf(parent) {
2901
- return parent === this.root ? this.rootIndex : getYjsVisibleChildren(this.root, parent);
2902
- }
2903
- /**
2904
- * Adds each top-level block whose visible content can hold `node`: the
2905
- * block it sits in, when the root shows that block, the block of the
2906
- * placeholder that shows it or an ancestor, and, unless `views` is false,
2907
- * the block of each cut view that shows letters of it. A root child the
2908
- * batch inserted counts as shown, since its region reads it. Returns
2909
- * whether any block shows `node`.
2910
- */
2911
- addShownBlocks(node, blocks, visited = /* @__PURE__ */ new Set(), views = true, projection = projectYjsRoot(this.root)) {
2912
- let shown = false;
2913
- for (let current = node; current !== this.root; current = current.parent) {
2914
- if (current === null || !isYjsNode(current) || visited.has(current)) return shown;
2915
- visited.add(current);
2916
- const id = current.getAttribute(YJS_NODE_ID_KEY);
2917
- if (typeof id === "string") {
2918
- const shownBy = projection.referrerOf(id);
2919
- for (const referrer of this.rootIndex.referrersOf(id)) {
2920
- if (referrer instanceof Y.XmlText ? !views : referrer !== shownBy) continue;
2921
- shown = this.addShownBlocks(referrer, blocks, visited, true, projection) || shown;
2922
- }
2923
- const place = shownBy === null && current instanceof Y.XmlElement ? projection.placeOf(current) : null;
2924
- if (place) shown = this.addShownBlocks(place.kind === "end" ? place.line : place.anchor, blocks, visited, true, projection) || shown;
2925
- }
2926
- if (this.rootIndex.has(current)) {
2927
- blocks.add(current);
2928
- return true;
2929
- }
2930
- if (current.parent === this.root) return shown || !this.rootIndex.holdsRaw(current);
2931
- }
2932
- return shown;
2933
- }
2934
- /**
2935
- * The texts that show what `event` changed when it only changed letters
2936
- * of a text whose letters several pieces show: the text for its head and
2937
- * the view of each piece after a cut. Null for any other event, or when the
2938
- * batch holds another event on the same text, because the pieces are read
2939
- * from the text as the batch left it.
2940
- */
2941
- changedPieces(event, deletedCuts) {
2942
- const { target } = event;
2943
- if (!(target instanceof Y.XmlText) || event.keys.length > 0) return null;
2944
- const views = this.viewsOf(target);
2945
- return views.length === 0 ? null : textsChangedBy(target, event.delta, views, deletedCuts);
2946
- }
2947
- /**
2948
- * Whether `event` hides a root child that showed itself, which leaves the
2949
- * root as a removal. A join that keeps the line also names its anchor.
2950
- */
2951
- hidesRootChild(event) {
2952
- const { target } = event;
2953
- if (!isYjsNode(target)) return false;
2954
- const slot = this.rootIndex.slotAt(this.rootIndex.indexOf(target));
2955
- return slot !== void 0 && this.rootIndex.rawAt(slot.rawIndex) === target && target.getAttribute("yjs:hidden") === true && event.keys.every((key) => key === "yjs:hidden" || key === "yjs:joined-after" || key === "yjs:joined-before" || key === "yjs:joined-end" || !YJS_CHILD_VISIBILITY_KEYS.has(key));
2956
- }
2957
- showsTopNode(node, old) {
2958
- const stack = [node];
2959
- for (let current = stack.pop(); current; current = stack.pop()) {
2960
- const ref = current.getAttribute(YJS_VIRTUAL_CHILD_ID_KEY);
2961
- if (current === old) return true;
2962
- if (typeof ref === "string" && this.rootIndex.resolve(ref) === old) return true;
2963
- if (current instanceof Y.XmlElement) stack.push(...rawYjsChildren(current));
2964
- }
2965
- return false;
2966
- }
2967
- showsAt(node, beforeIndex) {
2968
- const old = this.rootIndex.at(beforeIndex);
2969
- return old !== void 0 && this.showsTopNode(node, old);
2970
- }
2971
- hasUnresolvedReference(node) {
2972
- const stack = [node];
2973
- for (let current = stack.pop(); current; current = stack.pop()) {
2974
- const ref = current.getAttribute(YJS_VIRTUAL_CHILD_ID_KEY);
2975
- if (typeof ref === "string" && this.rootIndex.resolve(ref) === null) return true;
2976
- if (current instanceof Y.XmlElement) stack.push(...rawYjsChildren(current));
2977
- }
2978
- return false;
2979
- }
2980
- /**
2981
- * Read a batch against the document before it: the nodes it inserted and
2982
- * hid, each text's deltas, and each element's shown children and each
2983
- * node's path as they were before it, read on demand.
2984
- */
2985
- readBatch(batch) {
2986
- const inserted = /* @__PURE__ */ new Set();
2987
- const hidden = /* @__PURE__ */ new Set();
2988
- const deltas = /* @__PURE__ */ new Map();
2989
- const childEvents = /* @__PURE__ */ new Map();
2990
- const removed = /* @__PURE__ */ new Set();
2991
- const before = (node, key) => {
2992
- const values = batch.visibilityBefore.get(node);
2993
- return values?.has(key) ? values.get(key) : node.getAttribute(key);
2994
- };
2995
- const deletedReferrers = /* @__PURE__ */ new Map();
2996
- for (const node of batch.visibilityBefore.keys()) {
2997
- const ref = before(node, YJS_VIRTUAL_CHILD_ID_KEY);
2998
- if (node instanceof Y.XmlElement && isDeletedYjsNode(node) && typeof ref === "string") deletedReferrers.set(ref, [...deletedReferrers.get(ref) ?? [], node]);
2999
- }
3000
- for (const event of batch.events) {
3001
- const { target } = event;
3002
- if (isYjsNode(target) && event.keys.includes("yjs:hidden") && before(target, "yjs:hidden") !== true && target.getAttribute("yjs:hidden") === true) hidden.add(target);
3003
- if (target instanceof Y.XmlText && event.delta.length > 0) deltas.set(target, [...deltas.get(target) ?? [], event.delta]);
3004
- if (target instanceof Y.XmlElement && event.childListChanged) {
3005
- childEvents.set(target, [...childEvents.get(target) ?? [], event]);
3006
- for (const node of event.deleted) if (node) removed.add(node);
3007
- }
3008
- for (const part of event.delta) {
3009
- if (!Array.isArray(part.insert)) continue;
3010
- for (const node of part.insert) if (isYjsNode(node)) inserted.add(node);
3011
- }
3012
- }
3013
- const isPlaceholder = (node) => node instanceof Y.XmlElement && getYjsAttributes(node)["yjs:virtual-placeholder"] === true;
3014
- const shown = (node) => {
3015
- if (!isPlaceholder(node)) return node;
3016
- const ref = node.getAttribute(YJS_VIRTUAL_CHILD_ID_KEY);
3017
- return typeof ref === "string" ? this.rootIndex.resolve(ref) : null;
3018
- };
3019
- const rawChildrenBefore = (parent) => {
3020
- let children = isDeletedYjsNode(parent) ? [...batch.deletedChildren.get(parent) ?? []] : readYjsChildrenNotingPlainList(parent).map((child) => isYjsNode(child) ? child : null);
3021
- for (const event of (childEvents.get(parent) ?? []).toReversed()) {
3022
- const previous = [];
3023
- let at = 0;
3024
- let deleted = 0;
3025
- for (const part of event.delta) if (part.retain !== void 0) {
3026
- previous.push(...children.slice(at, at + part.retain));
3027
- at += part.retain;
3028
- } else if (part.delete !== void 0) {
3029
- previous.push(...event.deleted.slice(deleted, deleted + part.delete));
3030
- deleted += part.delete;
3031
- } else if (Array.isArray(part.insert)) at += part.insert.length;
3032
- if (at > children.length || deleted !== event.deleted.length) return null;
3033
- previous.push(...children.slice(at));
3034
- children = previous;
3035
- }
3036
- return children.every((child) => child !== null) ? children : null;
3037
- };
3038
- const childLists = /* @__PURE__ */ new Map();
3039
- const childrenBefore = (parent) => {
3040
- if (!childLists.has(parent)) childLists.set(parent, readChildrenBefore(parent));
3041
- return childLists.get(parent) ?? null;
3042
- };
3043
- const readChildrenBefore = (parent) => {
3044
- if (typeof parent.getAttribute("yjs:virtual-child-id") === "string") return null;
3045
- const raw = rawChildrenBefore(parent);
3046
- if (!raw) return null;
3047
- const children = [];
3048
- for (const child of raw) {
3049
- const ref = before(child, "yjs:virtual-placeholder") === true ? before(child, YJS_VIRTUAL_CHILD_ID_KEY) : null;
3050
- const node = typeof ref === "string" ? this.rootIndex.resolve(ref) ?? this.rootIndex.held(ref) : child;
3051
- if (node === null) return null;
3052
- if (node === child && before(child, "yjs:hidden") === true) continue;
3053
- children.push(node);
3054
- }
3055
- return children;
3056
- };
3057
- const siblingsOf = (parent) => parent === this.root ? this.rootIndex : childrenBefore(parent);
3058
- const childIndexes = /* @__PURE__ */ new Map();
3059
- const indexIn = (parent, node) => {
3060
- if (parent === this.root) return this.rootIndex.indexOf(node);
3061
- let indexes = childIndexes.get(parent);
3062
- if (!indexes) {
3063
- const children = childrenBefore(parent) ?? [];
3064
- countCoreWork("yjsChildrenRead", children.length);
3065
- indexes = new Map(children.map((child, at) => [child, at]));
3066
- childIndexes.set(parent, indexes);
3067
- }
3068
- return indexes.get(node) ?? -1;
3069
- };
3070
- const isNew = (node) => {
3071
- for (let current = node; current !== null && isYjsNode(current); current = current.parent) if (inserted.has(current)) return true;
3072
- return false;
3073
- };
3074
- const projection = projectYjsRoot(this.root);
3075
- const shownBy = (node) => {
3076
- const id = node.getAttribute(YJS_NODE_ID_KEY);
3077
- return typeof id === "string" ? projection.referrerOf(id) : null;
3078
- };
3079
- const shownBefore = (node) => {
3080
- const id = node.getAttribute(YJS_NODE_ID_KEY);
3081
- if (typeof id !== "string") return null;
3082
- const candidates = [...this.rootIndex.referrersOf(id), ...deletedReferrers.get(id) ?? []].filter((referrer) => referrer instanceof Y.XmlElement && before(referrer, "yjs:virtual-child-id") === id && before(referrer, "yjs:hidden") !== true && !isNew(referrer));
3083
- if (candidates.length <= 1) return candidates[0] ?? null;
3084
- const now = shownBy(node);
3085
- return now && candidates.includes(now) ? now : null;
3086
- };
3087
- const parentOf = (node) => {
3088
- if (this.rootIndex.has(node)) return this.root;
3089
- const parent = before(node, "yjs:hidden") === true ? shownBefore(node)?.parent : node.parent;
3090
- return parent instanceof Y.XmlElement ? parent : null;
3091
- };
3092
- const moved = (node) => {
3093
- if (hidden.has(node)) return true;
3094
- const by = shownBy(node);
3095
- return by !== null && isNew(by);
3096
- };
3097
- const pliteIndexes = /* @__PURE__ */ new Map();
3098
- const readPliteIndexes = (parent, path) => {
3099
- const line = lineAt(path);
3100
- const children = childrenBefore(parent);
3101
- if (!line || !children) return null;
3102
- countCoreWork("yjsChildrenRead", children.length);
3103
- const aligned = alignYjsChildren(line.children, children);
3104
- if (!aligned) return null;
3105
- const indexes = /* @__PURE__ */ new Map();
3106
- for (const [order, segment] of aligned.segments.entries()) {
3107
- const target = aligned.targets[order];
3108
- if (target?.kind === "element") indexes.set(target.node, segment.from);
3109
- }
3110
- return indexes;
3111
- };
3112
- const pathOf = (node) => {
3113
- const parent = parentOf(node);
3114
- if (!parent) return null;
3115
- if (parent === this.root) {
3116
- const index = indexIn(parent, node);
3117
- return index === -1 ? null : [index];
3118
- }
3119
- const path = pathOf(parent);
3120
- if (!path) return null;
3121
- if (!pliteIndexes.has(parent)) pliteIndexes.set(parent, readPliteIndexes(parent, path));
3122
- const index = pliteIndexes.get(parent)?.get(node);
3123
- return index === void 0 ? null : [...path, index];
3124
- };
3125
- const gone = (node) => node !== void 0 && (hidden.has(node) || isDeletedYjsNode(node));
3126
- const lineAt = (path) => {
3127
- let node = this.mirror.at(path[0]);
3128
- for (const index of path.slice(1)) node = node && NodeApi.isElement(node) ? node.children[index] : void 0;
3129
- return node && NodeApi.isElement(node) ? node : null;
3130
- };
3131
- const lengthBefore = (text) => (deltas.get(text) ?? []).reduce((sum, delta) => delta.reduce((total, part) => total + (part.delete ?? 0) - (typeof part.insert === "string" ? part.insert.length : 0), sum), text.length);
3132
- return {
3133
- childrenBefore,
3134
- deletedCuts: batch.deletedCuts,
3135
- deltas,
3136
- gone,
3137
- hidden,
3138
- indexIn,
3139
- inserted,
3140
- isPlaceholder,
3141
- lengthBefore,
3142
- lineAt,
3143
- moved,
3144
- parentOf,
3145
- pathOf,
3146
- removed,
3147
- shown,
3148
- siblingsOf,
3149
- sourceOf: (text) => textPieceOf(text).source
3150
- };
3151
- }
3152
- /**
3153
- * Find the batch's joins. A join is a run of sibling lines the batch hid or
3154
- * deleted, right after a line it left in place, whose children show, in
3155
- * order, at that line's end through placeholders the batch wrote there. A
3156
- * line between them whose children show nowhere was removed. A joined line
3157
- * whose children all showed through placeholders is deleted, since the
3158
- * join's placeholders replace them. The search reads each hidden or deleted
3159
- * line, its previous siblings back to a line the batch kept, and the
3160
- * children of the lines it joins.
3161
- */
3162
- findJoins(batch) {
3163
- const found = [];
3164
- const { childrenBefore, deltas, gone, hidden, indexIn, inserted, lengthBefore, lineAt, pathOf, shown, siblingsOf } = batch;
3165
- const candidates = [...hidden, ...batch.removed].filter((node) => node instanceof Y.XmlElement);
3166
- if (candidates.length === 0) return found;
3167
- const removedByJoin = (node) => isDeletedYjsNode(node) || hidden.has(node) && typeof getYjsAttributes(node)["yjs:joined-after"] === "string";
3168
- const editsOf = (line, children) => {
3169
- const aligned = alignYjsChildren(line.children, children);
3170
- const edits = [];
3171
- const removed = [];
3172
- if (!aligned) return null;
3173
- for (const [order, segment] of aligned.segments.entries()) {
3174
- const target = aligned.targets[order];
3175
- if (segment.kind === "element") {
3176
- if (target?.kind === "element" && removedByJoin(target.node)) removed.push(segment.from);
3177
- continue;
3178
- }
3179
- const letters = segment.leaves.map((leaf) => leaf.text).join("");
3180
- if (target?.kind !== "text") {
3181
- edits.push([]);
3182
- continue;
3183
- }
3184
- if (target.chain.some(hasYjsCut)) return null;
3185
- const lengths = target.chain.map((text) => isDeletedYjsNode(text) ? null : lengthBefore(text));
3186
- const known = lengths.reduce((sum, n) => sum + (n ?? 0), 0);
3187
- if (lengths.filter((n) => n === null).length > 1 || known > letters.length) return null;
3188
- const diff = [];
3189
- let offset = 0;
3190
- for (const [index, text] of target.chain.entries()) {
3191
- const length = lengths[index] ?? letters.length - known;
3192
- const own = letters.slice(offset, offset + length);
3193
- const textDiff = lengths[index] === null ? [[DiffOp.Delete, own]] : composeTextDeltas(own, deltas.get(text) ?? []);
3194
- if (!textDiff) return null;
3195
- for (const entry of textDiff) pushDiff(diff, entry[0], entry[1]);
3196
- offset += length;
3197
- }
3198
- if (offset !== letters.length) return null;
3199
- edits.push(diff);
3200
- }
3201
- return {
3202
- edits,
3203
- removed
3204
- };
3205
- };
3206
- const placedAtEnd = (element) => {
3207
- const raw = rawYjsChildren(element);
3208
- const targets = [];
3209
- for (let tail = raw.length - 1; tail >= 0; tail--) {
3210
- const child = raw[tail];
3211
- if (!inserted.has(child) || !(child instanceof Y.XmlElement) || getYjsAttributes(child)["yjs:virtual-placeholder"] !== true) break;
3212
- const target = shown(child);
3213
- if (target === null) return [];
3214
- if (!inserted.has(target)) targets.push(target);
3215
- }
3216
- return targets.reverse();
3217
- };
3218
- const elementBefore = (line, node, index) => {
3219
- const children = childrenBefore(node);
3220
- const aligned = children && alignYjsChildren(line.children, children);
3221
- const order = aligned?.segments.findIndex((segment) => segment.kind === "element" && segment.from === index) ?? -1;
3222
- const target = order === -1 ? null : aligned?.targets[order];
3223
- return target?.kind === "element" && target.node instanceof Y.XmlElement ? target.node : null;
3224
- };
3225
- const isEmptyText = (node) => node !== void 0 && NodeApi.isText(node) && node.text === "";
3226
- const isEmptiedCopy = (node) => {
3227
- if (!(node instanceof Y.XmlElement)) return false;
3228
- const children = childrenBefore(node)?.filter((child) => !isEmptyAttributeFreeShownYjsText(child));
3229
- return children !== void 0 && children.length > 0 && children.every((child) => batch.moved(child) || isEmptiedCopy(child));
3230
- };
3231
- const inlinePairsOf = ([first, second], [left, right]) => {
3232
- const pairs = [];
3233
- let paths = [first, second];
3234
- let nodes = [left, right];
3235
- for (;;) {
3236
- const a = lineAt(paths[0]);
3237
- const b = lineAt(paths[1]);
3238
- if (!a || !b) return [];
3239
- const at = a.children.findLastIndex((child) => !isEmptyText(child));
3240
- const head = b.children.findIndex((child) => !isEmptyText(child));
3241
- const [l, r] = [a.children[at], b.children[head]];
3242
- if (!l || !r || !NodeApi.isElement(l) || !NodeApi.isElement(r) || l.type !== r.type) break;
3243
- const yl = elementBefore(a, nodes[0], at);
3244
- const yr = elementBefore(b, nodes[1], head);
3245
- const live = yr && childrenBefore(yr)?.filter((c) => !removedByJoin(c));
3246
- const moved = yl && placedAtEnd(yl);
3247
- if (!yl || !yr || !live || !moved || gone(yl) || !removedByJoin(yr) || live.length !== moved.length || live.some((child, index) => moved[index] !== child)) break;
3248
- paths = [[...paths[0], at], [...paths[1], head]];
3249
- nodes = [yl, yr];
3250
- pairs.push(paths);
3251
- }
3252
- const innermost = pairs.at(-1);
3253
- const a = innermost && lineAt(innermost[0]);
3254
- const b = innermost && lineAt(innermost[1]);
3255
- return a && b && NodeApi.isText(a.children.at(-1)) && NodeApi.isText(b.children[0]) ? pairs : [];
3256
- };
3257
- const firsts = /* @__PURE__ */ new Set();
3258
- const runStarts = /* @__PURE__ */ new Map();
3259
- const siblingAt = (siblings, at) => {
3260
- countCoreWork("yjsJoinSiblingsRead");
3261
- return siblings.at(at);
3262
- };
3263
- for (const line of candidates) {
3264
- const { parent } = line;
3265
- if (!(parent instanceof Y.XmlElement)) continue;
3266
- const siblings = siblingsOf(parent);
3267
- const index = siblings ? indexIn(parent, line) : -1;
3268
- if (!siblings || index === -1) continue;
3269
- const passed = [line];
3270
- let start = index - 1;
3271
- for (; start >= 0; start -= 1) {
3272
- const sibling = siblingAt(siblings, start);
3273
- if (sibling === void 0 || !gone(sibling)) break;
3274
- const known = runStarts.get(sibling);
3275
- if (known !== void 0) {
3276
- start = known;
3277
- break;
3278
- }
3279
- passed.push(sibling);
3280
- }
3281
- for (const node of passed) runStarts.set(node, start);
3282
- const first = siblings.at(start);
3283
- if (!(first instanceof Y.XmlElement) || firsts.has(first) || getYjsAttributes(first)["yjs:hidden"] === true) continue;
3284
- firsts.add(first);
3285
- const targets = placedAtEnd(first);
3286
- if (targets.length === 0) continue;
3287
- const isTarget = new Set(targets);
3288
- const keptByJoin = (child) => isTarget.has(child) || !(removedByJoin(child) || isEmptyAttributeFreeShownYjsText(child));
3289
- const lines = [start];
3290
- let read = 0;
3291
- let joins = true;
3292
- for (let at = start + 1; joins && at < siblings.length && gone(siblingAt(siblings, at)); at++) {
3293
- const next = siblings.at(at);
3294
- if (next === void 0 || isTarget.has(next)) {
3295
- joins = false;
3296
- break;
3297
- }
3298
- const children = next instanceof Y.XmlElement ? childrenBefore(next) : [];
3299
- if (children === null) {
3300
- joins = false;
3301
- break;
3302
- }
3303
- const kept = children.filter(keptByJoin);
3304
- const live = !isTarget.has(kept[0]) && isEmptiedCopy(kept[0]) ? kept.slice(1) : kept;
3305
- const count = live.filter((child) => isTarget.has(child)).length;
3306
- if (count > 0) {
3307
- joins = count === live.length && live.every((child, offset) => targets[read + offset] === child);
3308
- read += live.length;
3309
- lines.push(at);
3310
- } else if (read === targets.length) break;
3311
- else if (children.some((child) => hidden.has(child))) joins = false;
3312
- }
3313
- if (!joins || read !== targets.length || lines.length < 2) continue;
3314
- const nodes = lines.map((at) => siblings.at(at));
3315
- const paths = nodes.map((node) => node instanceof Y.XmlElement ? pathOf(node) : null);
3316
- if (!paths.every((path) => path !== null)) continue;
3317
- const edits = [];
3318
- const removed = [];
3319
- for (const [order, node] of nodes.entries()) {
3320
- const joined = lineAt(paths[order]);
3321
- const children = node instanceof Y.XmlElement ? childrenBefore(node) : null;
3322
- const lineEdits = joined && children && editsOf(joined, children);
3323
- if (!lineEdits) {
3324
- joins = false;
3325
- break;
3326
- }
3327
- edits.push(lineEdits.edits);
3328
- removed.push(lineEdits.removed);
3329
- }
3330
- let top = first;
3331
- while (top.parent instanceof Y.XmlElement && top.parent !== this.root) top = top.parent;
3332
- if (!joins) continue;
3333
- const [firstNode, secondNode] = nodes;
3334
- const inline = paths.length === 2 && firstNode instanceof Y.XmlElement && secondNode instanceof Y.XmlElement ? inlinePairsOf([paths[0], paths[1]], [firstNode, secondNode]) : [];
3335
- const joinedAt = inline[0]?.[1].at(-1);
3336
- found.push({
3337
- after: null,
3338
- edits,
3339
- inline,
3340
- lines: paths,
3341
- removedElements: removed.map((elements, order) => order === 1 ? elements.filter((at) => at !== joinedAt) : elements),
3342
- top
3343
- });
3344
- }
3345
- return found.sort((left, right) => {
3346
- const at = left.lines[0].findIndex((index, depth) => index !== right.lines[0][depth]);
3347
- return at === -1 ? 0 : left.lines[0][at] - (right.lines[0][at] ?? 0);
3348
- });
3349
- }
3350
- joinRecovery(batch) {
3351
- if (!this.ready) return null;
3352
- const [joins, found] = withYjsRootIds(this.root, this.rootIndex, () => {
3353
- this.noteRemoteIds(batch);
3354
- const read = this.readBatch(batch);
3355
- return [this.findJoins(read), boundariesInBatch(read)];
3356
- });
3357
- return this.recoverJoins(joins, found);
3358
- }
3359
- /**
3360
- * The import's change from its joins or, when it has none, its splits and
3361
- * unsplits, each made first so the lines keep their content.
3362
- */
3363
- recoverJoins(joins, { splits, unsplits }) {
3364
- if (joins.length + splits.length + unsplits.length === 0) return null;
3365
- return (before, after) => {
3366
- if (joins.length === 0) {
3367
- const visible = getYjsVisibleChildren(this.root, this.root);
3368
- const placed = splits.filter(({ copied, levels, line, spine }) => levels < line.length || visible.indexOf(spine) === visible.indexOf(copied) + 1);
3369
- return placed.length + unsplits.length === 0 ? null : splitChangeTo(DocumentIndex.fromValue(before), after, placed, (left, right) => this.between(left, right), unsplits);
3370
- }
3371
- const visible = getYjsVisibleChildren(this.root, this.root);
3372
- if (visible.length !== after.length) return null;
3373
- const placed = joins.map((join) => ({
3374
- ...join,
3375
- after: visible.indexOf(join.top)
3376
- }));
3377
- if (placed.some((join) => join.after === -1)) return null;
3378
- return joinedChange(DocumentIndex.fromValue(before), after, placed, (left, right) => this.between(left, right));
3379
- };
3380
- }
3381
- between(before, after) {
3382
- let contexts;
3383
- return RootChange.betweenChangedBlocks(before, after, {
3384
- emptySetsAsValues: true,
3385
- isSetValued: (node, key) => {
3386
- contexts ??= indexYjsPropertyContexts(before.value, this.schemaRoot);
3387
- const context = contexts.get(node);
3388
- return context ? this.isSetValued(node, key, context) : false;
3389
- },
3390
- root: this.schemaRoot
3391
- });
3392
- }
3393
- translate(batch, read, normalization, found, boundaries) {
3394
- if (!this.ready) return {
3395
- fallback: "remote-event-mirror-mismatch",
3396
- kind: "fallback"
3397
- };
3398
- let rootEvent = null;
3399
- const affectedTopNodes = /* @__PURE__ */ new Set();
3400
- const hiddenTopNodes = /* @__PURE__ */ new Set();
3401
- let changesVisibility = false;
3402
- let hasProjectedTarget = false;
3403
- let hasUnknownTarget = false;
3404
- for (const referrers of this.rootIndex.takeContestChanges()) for (const referrer of referrers) this.addShownBlocks(referrer, affectedTopNodes);
3405
- const textEvents = /* @__PURE__ */ new Map();
3406
- for (const { target } of batch.events) textEvents.set(target, (textEvents.get(target) ?? 0) + 1);
3407
- for (const event of batch.events) {
3408
- const visibility = event.keys.some((key) => YJS_CHILD_VISIBILITY_KEYS.has(key));
3409
- changesVisibility ||= visibility;
3410
- if (visibility && (event.target === this.root || event.target.parent === this.root)) {
3411
- if (event.target === this.root || !this.hidesRootChild(event)) return {
3412
- fallback: "remote-event-projected-content",
3413
- kind: "fallback"
3414
- };
3415
- hiddenTopNodes.add(event.target);
3416
- this.addShownBlocks(event.target, affectedTopNodes);
3417
- continue;
3418
- }
3419
- if (event.target === this.root) {
3420
- if (event.keys.length > 0) return {
3421
- fallback: "remote-event-root-attributes",
3422
- kind: "fallback"
3423
- };
3424
- if (event.childListChanged) {
3425
- if (rootEvent !== null) return {
3426
- fallback: "remote-event-invalid-delta",
3427
- kind: "fallback"
3428
- };
3429
- rootEvent = event;
3430
- }
3431
- continue;
3432
- }
3433
- const pieces = textEvents.get(event.target) === 1 ? this.changedPieces(event, batch.deletedCuts) : null;
3434
- if (getTopLevelNode(this.root, event.target) === null) hasUnknownTarget = true;
3435
- else if (pieces === null ? !this.addShownBlocks(event.target, affectedTopNodes) : !pieces.reduce((shown, text) => this.addShownBlocks(text, affectedTopNodes, /* @__PURE__ */ new Set(), false) || shown, false)) hasProjectedTarget = true;
3436
- }
3437
- for (const id of batch.deletedIds) for (const referrer of this.rootIndex.referrersOf(id)) this.addShownBlocks(referrer, affectedTopNodes);
3438
- if (hasProjectedTarget) return {
3439
- fallback: "remote-event-projected-content",
3440
- kind: "fallback"
3441
- };
3442
- if (hasUnknownTarget && rootEvent === null) return {
3443
- fallback: "remote-event-unknown-target",
3444
- kind: "fallback"
3445
- };
3446
- const removedTopNodes = [...[...normalization.removedNodes].filter((node) => this.rootIndex.has(node)), ...hiddenTopNodes];
3447
- const parsedRootDelta = rootEvent === null ? [] : this.rootIndex.simple ? parseRootDelta(this.rootIndex, rootEvent.delta) : parseProjectedRootDelta(this.root, this.rootIndex, rootEvent.delta, batch.deletedChildren);
3448
- if (parsedRootDelta === null) return {
3449
- fallback: changesVisibility ? "remote-event-projected-content" : "remote-event-invalid-delta",
3450
- kind: "fallback"
3451
- };
3452
- const structural = finalizeRootRegions(parsedRootDelta, removedTopNodes, this.rootIndex, (node, old) => this.showsTopNode(node, old));
3453
- if (structural === null) return {
3454
- fallback: "remote-event-empty-root",
3455
- kind: "fallback"
3456
- };
3457
- const insertedTopIndexes = /* @__PURE__ */ new Map();
3458
- for (const region of structural) region.nodes.forEach((node, index) => {
3459
- insertedTopIndexes.set(node, region.afterFrom + index);
3460
- });
3461
- const getNextTopIndex = (node) => {
3462
- const insertedIndex = insertedTopIndexes.get(node);
3463
- if (insertedIndex !== void 0) return insertedIndex;
3464
- const index = this.rootIndex.indexOf(node);
3465
- return index === -1 ? void 0 : mapRootNodeIndex(index, structural);
3466
- };
3467
- const readNodes = /* @__PURE__ */ new Set();
3468
- for (const region of structural) for (const node of region.nodes) if (!this.rootIndex.has(node)) readNodes.add(node);
3469
- for (const node of affectedTopNodes) if (getNextTopIndex(node) !== void 0) readNodes.add(node);
3470
- for (const node of readNodes) if (node.parent === this.root && hasProjectionAttributes(node) || this.hasUnresolvedReference(node)) return {
3471
- fallback: "remote-event-projected-content",
3472
- kind: "fallback"
3473
- };
3474
- const maskedBefore = new Set(this.maskedBlocks);
3475
- const readValues = /* @__PURE__ */ new Map();
3476
- try {
3477
- for (const node of readNodes) readValues.set(node, this.readFittedBlock(node));
3478
- } catch {
3479
- return {
3480
- fallback: "remote-event-read-failed",
3481
- kind: "fallback"
3482
- };
3483
- }
3484
- const retained = (node, beforeIndex) => (node && readValues.get(node)) ?? (beforeIndex < 0 ? void 0 : this.mirror.at(beforeIndex)) ?? failInvariant("Expected a retained top-level node");
3485
- const nextChildAt = (afterIndex) => {
3486
- let shift = 0;
3487
- for (const region of structural) {
3488
- if (afterIndex < region.afterFrom) break;
3489
- if (afterIndex < region.afterTo) {
3490
- const node = region.nodes[afterIndex - region.afterFrom];
3491
- return retained(node, node ? this.rootIndex.indexOf(node) : -1);
3492
- }
3493
- shift += region.afterTo - region.afterFrom - (region.beforeTo - region.beforeFrom);
3494
- }
3495
- const beforeIndex = afterIndex - shift;
3496
- return retained(this.rootIndex.at(beforeIndex), beforeIndex);
3497
- };
3498
- const regions = [...structural];
3499
- for (const node of affectedTopNodes) {
3500
- const beforeIndex = this.rootIndex.indexOf(node);
3501
- const afterIndex = getNextTopIndex(node);
3502
- if (beforeIndex !== -1 && afterIndex !== void 0) regions.push({
3503
- afterFrom: afterIndex,
3504
- afterTo: afterIndex + 1,
3505
- beforeFrom: beforeIndex,
3506
- beforeTo: beforeIndex + 1
3507
- });
3508
- }
3509
- const joins = [];
3510
- for (const join of found) {
3511
- const at = getNextTopIndex(join.top);
3512
- if (at === void 0) continue;
3513
- if (join.lines[0].length === 1) regions.push({
3514
- afterFrom: at,
3515
- afterTo: at + 1,
3516
- beforeFrom: join.lines[0][0],
3517
- beforeTo: getDefined(join.lines.at(-1))[0] + 1
3518
- });
3519
- joins.push({
3520
- ...join,
3521
- after: at
3522
- });
3523
- }
3524
- const splits = [];
3525
- for (const split of boundaries.splits) {
3526
- const { levels, line, spine } = split;
3527
- const node = this.rootIndex.at(line[0]);
3528
- const at = node && getNextTopIndex(node);
3529
- if (at === void 0 || levels === line.length && getNextTopIndex(spine) !== at + 1) continue;
3530
- splits.push(split);
3531
- regions.push({
3532
- afterFrom: at,
3533
- afterTo: at + (levels === line.length ? 2 : 1),
3534
- beforeFrom: line[0],
3535
- beforeTo: line[0] + 1
3536
- });
3537
- }
3538
- const unsplits = [];
3539
- for (const unsplit of boundaries.unsplits) {
3540
- const { left, line } = unsplit;
3541
- const top = left[0];
3542
- const node = this.rootIndex.at(top);
3543
- const at = node && getNextTopIndex(node);
3544
- if (at === void 0) continue;
3545
- unsplits.push(unsplit);
3546
- regions.push({
3547
- afterFrom: at,
3548
- afterTo: at + 1,
3549
- beforeFrom: top,
3550
- beforeTo: line[0] + 1
3551
- });
3552
- }
3553
- const mergedRegions = mergeRegions(regions);
3554
- if (!this.fit.holds({
3555
- at: nextChildAt,
3556
- length: mergedRegions.reduce((length, region) => length + region.afterTo - region.afterFrom - (region.beforeTo - region.beforeFrom), this.mirror.length)
3557
- }, mergedRegions)) return {
3558
- fallback: "remote-event-read-failed",
3559
- kind: "fallback"
3560
- };
3561
- const readTopIndexes = new Map([...readNodes].map((node) => [node, getNextTopIndex(node)]));
3562
- const prepared = createEventDocumentChange(this.rootKey, this.mirror, (from, to) => Array.from({ length: to - from }, (_, index) => nextChildAt(from + index)), mergedRegions, this.lengths, this.isSetValued, joins, splits, unsplits, read && {
3563
- keptBlockByRegion: mergedRegions.map((region) => {
3564
- const node = this.rootIndex.at(region.beforeFrom);
3565
- return region.beforeTo - region.beforeFrom === 1 && region.afterTo - region.afterFrom === 1 && node instanceof Y.XmlElement && getNextTopIndex(node) === region.afterFrom && !maskedBefore.has(node) && !this.maskedBlocks.has(node) && !hasProjectionAttributes(node) ? node : null;
3566
- }),
3567
- identity: {
3568
- after: (parent) => getYjsVisibleChildren(this.root, parent),
3569
- before: (parent) => read.childrenBefore(parent),
3570
- moved: (node) => read.moved(node)
3571
- }
3572
- }, read ? this.letterScripts(batch, read, normalization, maskedBefore, (index) => {
3573
- let shift = 0;
3574
- for (const region of structural) {
3575
- if (index < region.afterFrom) break;
3576
- if (index < region.afterTo) return region.nodes[index - region.afterFrom];
3577
- shift += region.afterTo - region.afterFrom - (region.beforeTo - region.beforeFrom);
3578
- }
3579
- return this.rootIndex.at(index - shift);
3580
- }) : void 0);
3581
- const ticket = this.generation;
3582
- return {
3583
- import: {
3584
- ...prepared,
3585
- accept: (published) => {
3586
- if (ticket !== this.generation) return;
3587
- const children = published.nodes;
3588
- withYjsRootIds(this.root, this.rootIndex, () => this.spliceRootIndex(rootEvent, normalization.removedNodes, hiddenTopNodes));
3589
- this.setMirror(children);
3590
- for (let index = structural.length - 1; index >= 0; index--) {
3591
- const region = structural[index];
3592
- if (!region) continue;
3593
- this.lengths.splice(region.beforeFrom, region.beforeTo - region.beforeFrom, children.slice(region.afterFrom, region.afterTo));
3594
- }
3595
- this.ready = this.rootIndex.length === children.length;
3596
- for (const [, index] of readTopIndexes) {
3597
- const child = index === void 0 ? void 0 : children.at(index);
3598
- if (index !== void 0 && child !== void 0) this.lengths.set(index, child);
3599
- }
3600
- },
3601
- readTopLevelNodes: readNodes.size
3602
- },
3603
- kind: "change"
3604
- };
3605
- }
3606
- /**
3607
- * Reads the scripts of a line by its top-level index after the batch. Null
3608
- * for a line whose value the schema fit changed, since the letters Yjs
3609
- * holds are not the ones the editor shows, and for any line of a batch that
3610
- * deleted a cut, since letters then move between the texts that show them.
3611
- */
3612
- letterScripts(batch, read, normalization, maskedBefore, nodeAt) {
3613
- const reshaped = new Set(batch.visibilityBefore.keys());
3614
- for (const event of batch.events) if (event.childListChanged && event.target instanceof Y.XmlElement || event.keys.some((key) => YJS_CHILD_VISIBILITY_KEYS.has(key))) reshaped.add(event.target);
3615
- for (const node of normalization.removedNodes) reshaped.add(node.parent);
3616
- const letters = {
3617
- ...read,
3618
- reshaped,
3619
- sources: /* @__PURE__ */ new Map()
3620
- };
3621
- return (afterIndex, line, beforeIndex) => {
3622
- const node = nodeAt(afterIndex);
3623
- return node && batch.deletedCuts.length === 0 && !maskedBefore.has(node) && !this.maskedBlocks.has(node) && (beforeIndex === void 0 || this.showsAt(node, beforeIndex)) ? readLineScripts(this.root, node, line, letters) ?? readLineScripts(this.root, node, line, letters, true) : null;
3624
- };
3625
- }
3626
- spliceRootIndex(rootEvent, removed, hidden) {
3627
- let rawIndex = 0;
3628
- let consistent = true;
3629
- for (const part of rootEvent?.delta ?? []) if (part.retain !== void 0) rawIndex += part.retain;
3630
- else if (part.delete !== void 0) this.rootIndex.delete(rawIndex, part.delete);
3631
- else if (Array.isArray(part.insert)) {
3632
- const inserted = part.insert.filter(isYjsNode);
3633
- consistent = this.rootIndex.insert(rawIndex, inserted.map((node) => readYjsRootSlot(this.root, node))) && consistent;
3634
- rawIndex += inserted.length;
3635
- }
3636
- for (const node of removed) this.rootIndex.remove(node);
3637
- for (const node of hidden) consistent = this.rootIndex.show(readYjsRootSlot(this.root, node)) && consistent;
3638
- if (!consistent || this.rootIndex.rawLength !== this.root.length) this.resetRootIndex();
3639
- }
3640
- };
3641
- //#endregion
3642
- export { YjsEventChangeBridge, batchTouchesNodes, captureYjsEventBatch, mergeYjsEventBatches };