@aionbuilders/nabu 0.1.0-beta.0 → 0.1.0

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 (306) hide show
  1. package/CHANGELOG.md +523 -0
  2. package/LICENSE +21 -0
  3. package/README.md +72 -341
  4. package/dist/behaviors/text/RichText.svelte +24 -4
  5. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +3 -0
  6. package/dist/behaviors/text/markdown-shortcuts.extension.js +35 -10
  7. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  8. package/dist/behaviors/text/markdown-syntax.js +81 -0
  9. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  10. package/dist/behaviors/text/rich-text.extension.js +95 -38
  11. package/dist/behaviors/text/text.behavior.svelte.d.ts +199 -48
  12. package/dist/behaviors/text/text.behavior.svelte.js +549 -83
  13. package/dist/behaviors/text/typography.extension.d.ts +2 -1
  14. package/dist/behaviors/text/typography.extension.js +3 -2
  15. package/dist/blocks/BlockList.svelte +48 -0
  16. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  17. package/dist/blocks/Nabu.svelte +169 -25
  18. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  19. package/dist/blocks/block.extension.d.ts +3 -0
  20. package/dist/blocks/block.extension.js +4 -7
  21. package/dist/blocks/block.svelte.d.ts +350 -86
  22. package/dist/blocks/block.svelte.js +370 -59
  23. package/dist/blocks/blockquote/Blockquote.svelte +1 -2
  24. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -1
  25. package/dist/blocks/blockquote/blockquote.extension.js +14 -5
  26. package/dist/blocks/blockquote/blockquote.svelte.d.ts +19 -11
  27. package/dist/blocks/blockquote/blockquote.svelte.js +58 -13
  28. package/dist/blocks/callout/Callout.svelte +6 -8
  29. package/dist/blocks/callout/callout.extension.d.ts +4 -1
  30. package/dist/blocks/callout/callout.extension.js +19 -3
  31. package/dist/blocks/callout/callout.svelte.d.ts +5 -3
  32. package/dist/blocks/callout/callout.svelte.js +11 -6
  33. package/dist/blocks/chunks.d.ts +49 -0
  34. package/dist/blocks/chunks.js +90 -0
  35. package/dist/blocks/code/Code.svelte +7 -8
  36. package/dist/blocks/code/code.extension.d.ts +4 -1
  37. package/dist/blocks/code/code.extension.js +22 -2
  38. package/dist/blocks/code/code.svelte.d.ts +9 -2
  39. package/dist/blocks/code/code.svelte.js +49 -25
  40. package/dist/blocks/container.utils.d.ts +85 -13
  41. package/dist/blocks/container.utils.js +338 -178
  42. package/dist/blocks/dialogue/Dialogue.svelte +8 -4
  43. package/dist/blocks/dialogue/dialogue.svelte.d.ts +33 -2
  44. package/dist/blocks/dialogue/dialogue.svelte.js +58 -4
  45. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  46. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  47. package/dist/blocks/dialogue/index.d.ts +12 -1
  48. package/dist/blocks/dialogue/index.js +51 -35
  49. package/dist/blocks/divider/divider.extension.d.ts +23 -1
  50. package/dist/blocks/divider/divider.extension.js +85 -19
  51. package/dist/blocks/divider/divider.svelte.d.ts +7 -2
  52. package/dist/blocks/divider/divider.svelte.js +9 -4
  53. package/dist/blocks/file/File.svelte +13 -6
  54. package/dist/blocks/file/file.extension.d.ts +4 -1
  55. package/dist/blocks/file/file.extension.js +9 -1
  56. package/dist/blocks/file/file.svelte.d.ts +3 -3
  57. package/dist/blocks/file/file.svelte.js +20 -14
  58. package/dist/blocks/heading/Heading.svelte +1 -2
  59. package/dist/blocks/heading/heading.svelte.d.ts +23 -11
  60. package/dist/blocks/heading/heading.svelte.js +68 -13
  61. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  62. package/dist/blocks/heading/index.d.ts +2 -2
  63. package/dist/blocks/heading/index.js +33 -8
  64. package/dist/blocks/image/Image.svelte +5 -2
  65. package/dist/blocks/image/image.extension.d.ts +4 -1
  66. package/dist/blocks/image/image.extension.js +9 -1
  67. package/dist/blocks/image/image.svelte.d.ts +17 -6
  68. package/dist/blocks/image/image.svelte.js +33 -11
  69. package/dist/blocks/index.d.ts +1 -1
  70. package/dist/blocks/index.js +1 -1
  71. package/dist/blocks/list/List.svelte +1 -0
  72. package/dist/blocks/list/ListItem.svelte +1 -0
  73. package/dist/blocks/list/convert.d.ts +20 -0
  74. package/dist/blocks/list/convert.js +92 -0
  75. package/dist/blocks/list/hooks/onBeforeInput.hook.js +49 -28
  76. package/dist/blocks/list/html-flat.d.ts +78 -0
  77. package/dist/blocks/list/html-flat.js +244 -0
  78. package/dist/blocks/list/indent.d.ts +86 -0
  79. package/dist/blocks/list/indent.js +205 -0
  80. package/dist/blocks/list/index.d.ts +6 -3
  81. package/dist/blocks/list/index.js +42 -31
  82. package/dist/blocks/list/list-item.svelte.d.ts +31 -17
  83. package/dist/blocks/list/list-item.svelte.js +99 -100
  84. package/dist/blocks/list/list.behavior.svelte.d.ts +4 -1
  85. package/dist/blocks/list/list.behavior.svelte.js +6 -1
  86. package/dist/blocks/list/list.svelte.d.ts +89 -18
  87. package/dist/blocks/list/list.svelte.js +129 -125
  88. package/dist/blocks/list/markdown.d.ts +149 -0
  89. package/dist/blocks/list/markdown.js +442 -0
  90. package/dist/blocks/list/normalize.d.ts +11 -0
  91. package/dist/blocks/list/normalize.js +396 -0
  92. package/dist/blocks/list/paste.d.ts +45 -0
  93. package/dist/blocks/list/paste.js +242 -0
  94. package/dist/blocks/list/step-back.d.ts +24 -0
  95. package/dist/blocks/list/step-back.js +87 -0
  96. package/dist/blocks/list/to-list.d.ts +7 -0
  97. package/dist/blocks/list/to-list.js +44 -0
  98. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  99. package/dist/blocks/list/todos-toggle.js +48 -0
  100. package/dist/blocks/media/markdown.d.ts +12 -0
  101. package/dist/blocks/media/markdown.js +26 -0
  102. package/dist/blocks/media/media-block.svelte.d.ts +77 -2
  103. package/dist/blocks/media/media-block.svelte.js +124 -12
  104. package/dist/blocks/media/media.helpers.d.ts +6 -1
  105. package/dist/blocks/media/media.helpers.js +43 -6
  106. package/dist/blocks/megablock.svelte.d.ts +50 -19
  107. package/dist/blocks/megablock.svelte.js +114 -74
  108. package/dist/blocks/move.d.ts +23 -0
  109. package/dist/blocks/move.js +92 -0
  110. package/dist/blocks/nabu.svelte.d.ts +764 -71
  111. package/dist/blocks/nabu.svelte.js +1746 -189
  112. package/dist/blocks/paragraph/Paragraph.svelte +1 -2
  113. package/dist/blocks/paragraph/index.d.ts +2 -2
  114. package/dist/blocks/paragraph/index.js +35 -13
  115. package/dist/blocks/paragraph/paragraph.svelte.d.ts +46 -14
  116. package/dist/blocks/paragraph/paragraph.svelte.js +77 -16
  117. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  118. package/dist/blocks/paragraph/table.html.js +111 -0
  119. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  120. package/dist/blocks/paragraph/table.markdown.js +90 -0
  121. package/dist/blocks/region/Region.svelte +264 -0
  122. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  123. package/dist/blocks/region/actions.d.ts +135 -0
  124. package/dist/blocks/region/actions.js +402 -0
  125. package/dist/blocks/region/close.d.ts +35 -0
  126. package/dist/blocks/region/close.js +130 -0
  127. package/dist/blocks/region/commands.d.ts +6 -0
  128. package/dist/blocks/region/commands.js +277 -0
  129. package/dist/blocks/region/create.d.ts +72 -0
  130. package/dist/blocks/region/create.js +208 -0
  131. package/dist/blocks/region/end-marker.d.ts +35 -0
  132. package/dist/blocks/region/end-marker.js +51 -0
  133. package/dist/blocks/region/facts.d.ts +69 -0
  134. package/dist/blocks/region/facts.js +152 -0
  135. package/dist/blocks/region/format.d.ts +91 -0
  136. package/dist/blocks/region/format.js +260 -0
  137. package/dist/blocks/region/index.d.ts +14 -0
  138. package/dist/blocks/region/index.js +14 -0
  139. package/dist/blocks/region/insert.d.ts +59 -0
  140. package/dist/blocks/region/insert.js +102 -0
  141. package/dist/blocks/region/messages.d.ts +254 -0
  142. package/dist/blocks/region/messages.js +131 -0
  143. package/dist/blocks/region/normalize.d.ts +7 -0
  144. package/dist/blocks/region/normalize.js +170 -0
  145. package/dist/blocks/region/region.extension.d.ts +58 -0
  146. package/dist/blocks/region/region.extension.js +119 -0
  147. package/dist/blocks/region/region.svelte.d.ts +221 -0
  148. package/dist/blocks/region/region.svelte.js +582 -0
  149. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  150. package/dist/blocks/region/regions.svelte.js +276 -0
  151. package/dist/blocks/region/serialize.d.ts +57 -0
  152. package/dist/blocks/region/serialize.js +112 -0
  153. package/dist/blocks/region/types.d.ts +255 -0
  154. package/dist/blocks/region/types.js +204 -0
  155. package/dist/blocks/selection.svelte.d.ts +106 -8
  156. package/dist/blocks/selection.svelte.js +622 -74
  157. package/dist/blocks/subthread.d.ts +80 -0
  158. package/dist/blocks/subthread.js +167 -0
  159. package/dist/blocks/text-block.svelte.d.ts +34 -13
  160. package/dist/blocks/text-block.svelte.js +42 -8
  161. package/dist/blocks/toggle/Toggle.svelte +4 -15
  162. package/dist/blocks/toggle/markdown.d.ts +20 -0
  163. package/dist/blocks/toggle/markdown.js +112 -0
  164. package/dist/blocks/toggle/toggle.extension.d.ts +4 -1
  165. package/dist/blocks/toggle/toggle.extension.js +6 -0
  166. package/dist/blocks/toggle/toggle.svelte.d.ts +54 -7
  167. package/dist/blocks/toggle/toggle.svelte.js +134 -34
  168. package/dist/blocks/undo-selection.d.ts +175 -0
  169. package/dist/blocks/undo-selection.js +360 -0
  170. package/dist/blocks/video/Video.svelte +5 -2
  171. package/dist/blocks/video/video.extension.d.ts +4 -1
  172. package/dist/blocks/video/video.extension.js +9 -1
  173. package/dist/blocks/video/video.svelte.d.ts +6 -5
  174. package/dist/blocks/video/video.svelte.js +18 -9
  175. package/dist/extend.d.ts +55 -0
  176. package/dist/extend.js +88 -0
  177. package/dist/files/assets.clipboard.d.ts +77 -0
  178. package/dist/files/assets.clipboard.js +152 -0
  179. package/dist/files/files.svelte.d.ts +321 -19
  180. package/dist/files/files.svelte.js +847 -43
  181. package/dist/files/index.d.ts +3 -1
  182. package/dist/files/index.js +3 -1
  183. package/dist/files/outbox.d.ts +69 -0
  184. package/dist/files/outbox.js +48 -0
  185. package/dist/files/status.d.ts +65 -0
  186. package/dist/files/status.js +87 -0
  187. package/dist/files/store.d.ts +97 -0
  188. package/dist/files/store.js +65 -0
  189. package/dist/files/uploads.svelte.d.ts +174 -0
  190. package/dist/files/uploads.svelte.js +504 -0
  191. package/dist/index.d.ts +68 -9
  192. package/dist/index.js +117 -10
  193. package/dist/nabu-theme.css +21 -1
  194. package/dist/paste/html.paste.d.ts +74 -3
  195. package/dist/paste/html.paste.js +550 -86
  196. package/dist/paste/markdown-inline.d.ts +86 -0
  197. package/dist/paste/markdown-inline.js +528 -0
  198. package/dist/paste/markdown.paste.d.ts +2 -8
  199. package/dist/paste/markdown.paste.js +78 -94
  200. package/dist/paste/nabu.paste.d.ts +3 -0
  201. package/dist/paste/nabu.paste.js +29 -3
  202. package/dist/paste/plain-text.paste.d.ts +2 -2
  203. package/dist/paste/plain-text.paste.js +3 -3
  204. package/dist/persistence/asset-store.d.ts +51 -0
  205. package/dist/persistence/asset-store.js +103 -0
  206. package/dist/persistence/autosave.d.ts +53 -0
  207. package/dist/persistence/autosave.js +62 -0
  208. package/dist/persistence/compact.d.ts +162 -0
  209. package/dist/persistence/compact.js +141 -0
  210. package/dist/persistence/history.d.ts +77 -0
  211. package/dist/persistence/history.js +176 -0
  212. package/dist/persistence/indexeddb.d.ts +190 -4
  213. package/dist/persistence/indexeddb.js +333 -29
  214. package/dist/persistence/merge.d.ts +38 -0
  215. package/dist/persistence/merge.js +36 -0
  216. package/dist/persistence/outbox.d.ts +25 -0
  217. package/dist/persistence/outbox.js +40 -0
  218. package/dist/persistence/persistence.d.ts +70 -9
  219. package/dist/persistence/persistence.js +507 -35
  220. package/dist/persistence/recovery.d.ts +79 -0
  221. package/dist/persistence/recovery.js +79 -0
  222. package/dist/persistence/release.d.ts +34 -0
  223. package/dist/persistence/release.js +64 -0
  224. package/dist/persistence/state.svelte.d.ts +53 -0
  225. package/dist/persistence/state.svelte.js +48 -0
  226. package/dist/persistence/sync.d.ts +39 -0
  227. package/dist/persistence/sync.js +138 -0
  228. package/dist/persistence/tail.d.ts +42 -0
  229. package/dist/persistence/tail.js +103 -0
  230. package/dist/presets.d.ts +29 -26
  231. package/dist/presets.js +35 -13
  232. package/dist/themes/atelier.css +318 -0
  233. package/dist/ui/CommandChooser.svelte +153 -0
  234. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  235. package/dist/ui/CommandInvite.svelte +99 -0
  236. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  237. package/dist/ui/DragHandle.svelte +97 -21
  238. package/dist/ui/FloatingToolbar.svelte +75 -27
  239. package/dist/ui/FloatingToolbar.svelte.d.ts +10 -0
  240. package/dist/ui/SlashMenu.svelte +147 -15
  241. package/dist/ui/SlashMenu.svelte.d.ts +20 -0
  242. package/dist/ui/anchor.d.ts +112 -0
  243. package/dist/ui/anchor.js +136 -0
  244. package/dist/ui/index.d.ts +7 -1
  245. package/dist/ui/index.js +12 -1
  246. package/dist/ui/slash-menu.svelte.d.ts +79 -7
  247. package/dist/ui/slash-menu.svelte.js +85 -51
  248. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  249. package/dist/utils/command-confirm.svelte.js +673 -0
  250. package/dist/utils/commands.d.ts +328 -0
  251. package/dist/utils/commands.js +416 -0
  252. package/dist/utils/dom-scope.d.ts +14 -0
  253. package/dist/utils/dom-scope.js +20 -0
  254. package/dist/utils/drop.d.ts +160 -0
  255. package/dist/utils/drop.js +305 -0
  256. package/dist/utils/extensions.d.ts +439 -45
  257. package/dist/utils/extensions.js +271 -29
  258. package/dist/utils/html.d.ts +44 -0
  259. package/dist/utils/html.js +183 -0
  260. package/dist/utils/index.d.ts +3 -0
  261. package/dist/utils/index.js +3 -0
  262. package/dist/utils/keys.d.ts +120 -0
  263. package/dist/utils/keys.js +248 -0
  264. package/dist/utils/links.d.ts +22 -0
  265. package/dist/utils/links.js +34 -0
  266. package/dist/utils/placeholders.d.ts +81 -3
  267. package/dist/utils/placeholders.js +73 -3
  268. package/dist/utils/selection.svelte.d.ts +47 -19
  269. package/dist/utils/selection.svelte.js +60 -10
  270. package/dist/utils/spellcheck.d.ts +9 -0
  271. package/dist/utils/spellcheck.js +17 -0
  272. package/dist/utils/tab.d.ts +31 -0
  273. package/dist/utils/tab.js +117 -0
  274. package/dist/utils/words.d.ts +7 -0
  275. package/dist/utils/words.js +62 -0
  276. package/dist/vite.d.ts +9 -3
  277. package/dist/vite.js +19 -8
  278. package/package.json +54 -20
  279. package/dist/blocks/variable.svelte.d.ts +0 -47
  280. package/dist/blocks/variable.svelte.js +0 -51
  281. package/dist/blocks/zone/TemplateEditor.svelte +0 -308
  282. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +0 -11
  283. package/dist/blocks/zone/Zone.svelte +0 -272
  284. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  285. package/dist/blocks/zone/ZoneEditor.svelte +0 -289
  286. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +0 -11
  287. package/dist/blocks/zone/ZoneTemplatesList.svelte +0 -188
  288. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +0 -11
  289. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +0 -3
  290. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +0 -30
  291. package/dist/blocks/zone/index.d.ts +0 -2
  292. package/dist/blocks/zone/index.js +0 -2
  293. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  294. package/dist/blocks/zone/zone.extension.js +0 -237
  295. package/dist/blocks/zone/zone.svelte.d.ts +0 -221
  296. package/dist/blocks/zone/zone.svelte.js +0 -608
  297. package/dist/overlays/context/Context.svelte +0 -182
  298. package/dist/overlays/context/Context.svelte.d.ts +0 -17
  299. package/dist/overlays/context/collect.d.ts +0 -17
  300. package/dist/overlays/context/collect.js +0 -33
  301. package/dist/overlays/context/context.extension.d.ts +0 -2
  302. package/dist/overlays/context/context.extension.js +0 -8
  303. package/dist/overlays/context/context.svelte.d.ts +0 -82
  304. package/dist/overlays/context/context.svelte.js +0 -159
  305. package/dist/overlays/context/index.d.ts +0 -3
  306. package/dist/overlays/context/index.js +0 -3
@@ -0,0 +1,396 @@
1
+ /**
2
+ * List schema normalizer.
3
+ *
4
+ * Runs from the List extension's `onBeforeTransaction` hook, i.e. BEFORE `doc.commit()`: every
5
+ * mutation made here belongs to the transaction (hence the undo step) of the operation that broke the
6
+ * structure. Everything works on Loro tree nodes (the source of truth) and uses MOVES, never
7
+ * delete+recreate, so block ids (and the caret) survive.
8
+ *
9
+ * Invariants, enforced to a fixpoint:
10
+ * - R1 a `list` without children is deleted (unless created by the very same transaction).
11
+ * - R2a a `list` directly inside a `list` is unwrapped: its children go into the parent, in place.
12
+ * - R2b a child of a `list` that is neither a `list-item` nor a `list` is hoisted out: the list is split
13
+ * around it (items before stay, the block goes right after, items after go into a new list of the
14
+ * same `listType`, without `start`, after the block).
15
+ * - R3a (P-28) a `list-item` may hold SEVERAL sublists, of different types, in order: nothing to do here,
16
+ * only R4 applies to them (adjacent sublists of the same type merge, as at the root).
17
+ * - R3b a `list-item` with a non-list child: that child (and what follows it, to keep the document
18
+ * order) is hoisted right after the item, in its parent. R2a / R2b then finish the job.
19
+ * - R4 adjacent lists of the same `listType` merge into the first one (which keeps its `start`), whatever
20
+ * their parent (the root, a container, a list item).
21
+ *
22
+ * SCOPE (P-106). The document was valid before the transaction, so only what the transaction touched can be invalid: the nodes it
23
+ * created / moved / retyped, the parents they now sit in, the parent they LEFT and the list neighbours of the seam they left. Those
24
+ * are the only lists and items visited (see `scopeOf`); the passes repeat on the scope of the CUMULATIVE ops, the normalizer's own
25
+ * included, until nothing changes. When the scope cannot be derived (a node leaves a position the block tree does not know) the whole
26
+ * document is scanned, as before. Sibling arrays are cached between two changes (`siblingsOf`): a root-level list no longer costs a
27
+ * `tree.roots()` each.
28
+ *
29
+ * @import { Nabu, NabuNode } from "../nabu.svelte.js";
30
+ */
31
+
32
+ import { List } from "./list.svelte.js";
33
+
34
+ /** Safety net against a rule set that would not converge. */
35
+ const MAX_PASSES = 50;
36
+
37
+ /** @param {NabuNode} node @returns {string | undefined} */
38
+ const typeOf = (node) => /** @type {any} */ (node.data.get("type"));
39
+
40
+ /** @param {NabuNode} node @returns {string} */
41
+ const listTypeOf = (node) => /** @type {any} */ (node.data).get("listType") || "bullet";
42
+
43
+ /** @param {NabuNode} node @returns {NabuNode[]} */
44
+ const kids = (node) => /** @type {NabuNode[]} */ (node.children() ?? []);
45
+
46
+ /** @param {NabuNode} node */
47
+ const isAlive = (node) => {
48
+ try { return !node.isDeleted(); } catch { return false; }
49
+ };
50
+
51
+ /**
52
+ * Inspects the pending (uncommitted) transaction. Returns null when it does not change the document
53
+ * structure (no tree create / move / delete, no block `type` or list `listType` change): no list invariant can have been
54
+ * broken, nothing to do. Otherwise returns what the transaction touched, by node id.
55
+ * @param {Nabu} nabu
56
+ * @returns {{ created: Set<string>, placed: Set<string>, left: Set<string>, changed: Set<string>, parents: Set<string> } | null}
57
+ * `created` the nodes created; `placed` created or moved (they got a new position); `left` moved or deleted (they left one);
58
+ * `changed` whose `type` / `listType` was set; `parents` every parent a create / move named.
59
+ */
60
+ function inspectPendingOps(nabu) {
61
+ const pending = nabu.doc.getUncommittedOpsAsJson();
62
+ if (!pending) return null;
63
+ const treeId = nabu.tree.id;
64
+ let structural = false;
65
+ /** @type {Set<string>} */
66
+ const created = new Set();
67
+ /** @type {Set<string>} */
68
+ const placed = new Set();
69
+ /** @type {Set<string>} */
70
+ const left = new Set();
71
+ /** @type {Set<string>} */
72
+ const changed = new Set();
73
+ /** @type {Set<string>} */
74
+ const parents = new Set();
75
+ for (const change of pending.changes) {
76
+ for (const op of change.ops) {
77
+ const content = /** @type {any} */ (op.content);
78
+ if (op.container === treeId) {
79
+ const target = String(content.target);
80
+ if (content.type === "create") { structural = true; created.add(target); placed.add(target); }
81
+ else if (content.type === "move") { structural = true; placed.add(target); left.add(target); }
82
+ else if (content.type === "delete") { structural = true; left.add(target); }
83
+ if ((content.type === "create" || content.type === "move") && content.parent) parents.add(String(content.parent));
84
+ } else if (content.type === "insert" && (content.key === "type" || content.key === "listType") && op.container.endsWith(":Map")) {
85
+ structural = true;
86
+ changed.add(op.container.slice(4, -4));
87
+ }
88
+ }
89
+ }
90
+ return structural ? { created, placed, left, changed, parents } : null;
91
+ }
92
+
93
+ /** @param {Nabu} nabu @param {string} id @returns {NabuNode | null} the live node, or null */
94
+ function liveNode(nabu, id) {
95
+ try {
96
+ if (!nabu.tree.has(/** @type {any} */ (id))) return null;
97
+ const node = /** @type {NabuNode | undefined} */ (nabu.tree.getNodeByID(/** @type {any} */ (id)));
98
+ return node && isAlive(node) ? node : null;
99
+ } catch { return null; }
100
+ }
101
+
102
+ /**
103
+ * Sibling arrays (the root's included), cached until the next change of the tree.
104
+ * @param {Nabu} nabu
105
+ */
106
+ function siblingsCache(nabu) {
107
+ /** @type {Map<string, NabuNode[]>} */
108
+ const cache = new Map();
109
+ return {
110
+ /** The children of `node`'s parent (the roots when it has none), `node` included. @param {NabuNode} node @returns {NabuNode[]} */
111
+ of(node) {
112
+ const parent = node.parent();
113
+ const key = parent ? parent.id.toString() : "";
114
+ let siblings = cache.get(key);
115
+ if (!siblings) {
116
+ siblings = parent ? kids(parent) : /** @type {NabuNode[]} */ (nabu.tree.roots());
117
+ cache.set(key, siblings);
118
+ }
119
+ return siblings;
120
+ },
121
+ clear() { cache.clear(); },
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Per editor, the ids of the lists a transaction left EMPTY on purpose (created by it: still under construction). The next
127
+ * structural transaction deletes them if they are still empty then, as a scan of the whole document would: they are part of its scope.
128
+ * @type {WeakMap<Nabu, Set<string>>}
129
+ */
130
+ const emptyLists = new WeakMap();
131
+
132
+ /**
133
+ * The lists and list items one pass has to visit, derived from what the pending ops touched; null = "unknown, scan everything".
134
+ * @param {Nabu} nabu
135
+ * @param {NonNullable<ReturnType<typeof inspectPendingOps>>} pending
136
+ * @param {ReturnType<typeof siblingsCache>} siblings
137
+ * @returns {{ lists: NabuNode[], items: NabuNode[] } | null}
138
+ */
139
+ function scopeOf(nabu, pending, siblings) {
140
+ const waiting = emptyLists.get(nabu);
141
+ /** @type {Map<string, NabuNode>} */
142
+ const lists = new Map();
143
+ /** @type {Map<string, NabuNode>} */
144
+ const items = new Map();
145
+ /** @type {Map<string, NabuNode>} */
146
+ const seams = new Map();
147
+ /** @param {NabuNode | null | undefined} node @param {boolean} [seam] also a seam: its list neighbours may have to merge */
148
+ const add = (node, seam = false) => {
149
+ if (!node || !isAlive(node)) return;
150
+ const type = typeOf(node);
151
+ const id = node.id.toString();
152
+ if (type === "list") { lists.set(id, node); if (seam) seams.set(id, node); }
153
+ else if (type === "list-item") items.set(id, node);
154
+ };
155
+
156
+ // Created / moved nodes, retyped ones: themselves (their content), their parent (its content), their seam.
157
+ for (const id of new Set([...pending.placed, ...pending.changed])) {
158
+ const node = liveNode(nabu, id);
159
+ if (!node) continue;
160
+ add(node, true);
161
+ add(node.parent());
162
+ }
163
+ for (const id of pending.parents) add(liveNode(nabu, id));
164
+ // Lists left empty by an earlier transaction (see `emptyLists`): this one may delete them.
165
+ if (waiting) for (const id of waiting) add(liveNode(nabu, id));
166
+
167
+ // Nodes that LEFT a position: the parent they left (it may be empty now) and the lists that were the neighbours of what left
168
+ // (they may be adjacent now). The op does not say where they were: the block tree, which still holds the state before the
169
+ // transaction, does. Grouped by container into runs of consecutive positions: a mass deletion reads two neighbours, not 2 N.
170
+ /** @type {Map<any, number[]>} */
171
+ const gone = new Map();
172
+ for (const id of pending.left) {
173
+ if (pending.created.has(id)) continue; // never was anywhere else: the ops name every parent it went through
174
+ const block = /** @type {any} */ (nabu.blocks.get(id));
175
+ if (!block) return null;
176
+ const container = block.parent ?? nabu;
177
+ const positions = gone.get(container);
178
+ if (positions) positions.push(block.index);
179
+ else { gone.set(container, [block.index]); add(block.parent?.node); }
180
+ }
181
+ for (const [container, positions] of gone) {
182
+ const row = container.children;
183
+ positions.sort((a, b) => a - b);
184
+ for (let i = 0; i < positions.length; ) {
185
+ let end = i;
186
+ while (end + 1 < positions.length && positions[end + 1] === positions[end] + 1) end++;
187
+ const first = positions[i], last = positions[end];
188
+ if (!row[first] || row[first].index !== first) return null; // the block tree is not what the indexes say: scan everything
189
+ for (const neighbour of [row[first - 1], row[last + 1]]) {
190
+ if (neighbour?.type === "list") add(neighbour.node, true);
191
+ }
192
+ i = end + 1;
193
+ }
194
+ }
195
+
196
+ // A seam: the list after it may now be adjacent to a list of its own type (its previous sibling is tested by fixList).
197
+ for (const list of seams.values()) {
198
+ const index = list.index();
199
+ if (index == null) continue;
200
+ const next = siblings.of(list)[index + 1];
201
+ if (next) add(next);
202
+ }
203
+ return { lists: [...lists.values()], items: [...items.values()] };
204
+ }
205
+
206
+ /**
207
+ * Live (not deleted, still of that type) nodes of the blocks of a given type.
208
+ * @param {Nabu} nabu
209
+ * @param {string} type
210
+ * @returns {NabuNode[]}
211
+ */
212
+ function collect(nabu, type) {
213
+ const blocks = nabu.blocksByType.get(type);
214
+ if (!blocks?.size) return [];
215
+ /** @type {Map<string, NabuNode>} */
216
+ const nodes = new Map();
217
+ for (const block of blocks) {
218
+ const node = /** @type {NabuNode | undefined} */ (block.node);
219
+ if (!node || !isAlive(node) || typeOf(node) !== type) continue;
220
+ nodes.set(node.id.toString(), node);
221
+ }
222
+ return [...nodes.values()];
223
+ }
224
+
225
+ /** Appends `node` at the end of `parent`'s children. @param {NabuNode} node @param {NabuNode} parent */
226
+ function append(node, parent) {
227
+ node.move(parent, kids(parent).length);
228
+ }
229
+
230
+ /** Moves every child of `from` to the end of `to`, in order. @param {NabuNode} from @param {NabuNode} to */
231
+ function moveAll(from, to) {
232
+ for (const child of kids(from)) append(child, to);
233
+ }
234
+
235
+ /**
236
+ * @param {Nabu} nabu
237
+ * @param {NabuNode} node
238
+ */
239
+ function remove(nabu, node) {
240
+ nabu.tree.delete(node.id);
241
+ }
242
+
243
+ /**
244
+ * Applies the first rule that matches this list. Returns whether something changed.
245
+ * @param {Nabu} nabu
246
+ * @param {NabuNode} list
247
+ * @param {Set<string>} underConstruction ids of the lists to leave alone while empty
248
+ * @param {(node: NabuNode) => NabuNode[]} siblingsOf
249
+ * @returns {boolean}
250
+ */
251
+ function fixList(nabu, list, underConstruction, siblingsOf) {
252
+ if (!isAlive(list) || typeOf(list) !== "list") return false;
253
+ const children = kids(list);
254
+
255
+ // R1 — empty list. A list created by THIS transaction is still under construction (the
256
+ // `nabu.insert("list")` + `nabu.insert("list-item", ..., list.id)` pattern commits in between): only a
257
+ // list that this transaction EMPTIED (moved / deleted its last child) is removed.
258
+ if (!children.length) {
259
+ if (underConstruction.has(list.id.toString())) return false;
260
+ remove(nabu, list);
261
+ return true;
262
+ }
263
+
264
+ // R2a — list directly inside a list: unwrap in place
265
+ const nested = children.find((child) => typeOf(child) === "list");
266
+ if (nested) {
267
+ for (const grandChild of kids(nested)) grandChild.moveBefore(nested);
268
+ remove(nabu, nested);
269
+ return true;
270
+ }
271
+
272
+ // R2b — foreign block inside a list: split the list around it
273
+ const foreignIndex = children.findIndex((child) => typeOf(child) !== "list-item");
274
+ if (foreignIndex !== -1) {
275
+ const foreign = children[foreignIndex];
276
+ const followers = children.slice(foreignIndex + 1);
277
+ foreign.moveAfter(list);
278
+ if (followers.length) {
279
+ const parentId = list.parent()?.id.toString() ?? null;
280
+ const listType = listTypeOf(list);
281
+ const tail = List.create(nabu, "list", { listType }, parentId).node;
282
+ tail.moveAfter(foreign);
283
+ for (const follower of followers) append(follower, tail);
284
+ }
285
+ return true;
286
+ }
287
+
288
+ // R4 — adjacent lists of the same type merge into the first one
289
+ const index = list.index();
290
+ if (index != null && index > 0) {
291
+ const previous = siblingsOf(list)[index - 1];
292
+ if (
293
+ previous && typeOf(previous) === "list" &&
294
+ listTypeOf(previous) === listTypeOf(list)
295
+ ) {
296
+ moveAll(list, previous);
297
+ remove(nabu, list);
298
+ return true;
299
+ }
300
+ }
301
+
302
+ return false;
303
+ }
304
+
305
+ /**
306
+ * Applies the first rule that matches this list item. Returns whether something changed.
307
+ * @param {Nabu} nabu
308
+ * @param {NabuNode} item
309
+ * @returns {boolean}
310
+ */
311
+ function fixItem(nabu, item) {
312
+ if (!isAlive(item) || typeOf(item) !== "list-item") return false;
313
+ const children = kids(item);
314
+
315
+ // R3b — non-list child: hoist it, and what follows it, right after the item (document order kept)
316
+ const foreignIndex = children.findIndex((child) => typeOf(child) !== "list");
317
+ if (foreignIndex !== -1) {
318
+ /** @type {NabuNode} */
319
+ let anchor = item;
320
+ for (const child of children.slice(foreignIndex)) {
321
+ child.moveAfter(anchor);
322
+ anchor = child;
323
+ }
324
+ return true;
325
+ }
326
+
327
+ return false;
328
+ }
329
+
330
+ /** Every live list and list item of the tree (no use of the block registry). @param {Nabu} nabu @returns {{ lists: NabuNode[], items: NabuNode[] }} */
331
+ function treeScope(nabu) {
332
+ const nodes = /** @type {NabuNode[]} */ (nabu.tree.nodes()).filter(isAlive);
333
+ return { lists: nodes.filter((node) => typeOf(node) === "list"), items: nodes.filter((node) => typeOf(node) === "list-item") };
334
+ }
335
+
336
+ /**
337
+ * One scan over the given lists and list items (every one of the document when `scope` is null). Returns whether anything changed.
338
+ * @param {Nabu} nabu
339
+ * @param {Set<string>} underConstruction
340
+ * @param {{ lists: NabuNode[], items: NabuNode[] } | null} scope
341
+ * @param {ReturnType<typeof siblingsCache>} siblings
342
+ */
343
+ function pass(nabu, underConstruction, scope, siblings) {
344
+ let changed = false;
345
+ const siblingsOf = (/** @type {NabuNode} */ node) => siblings.of(node);
346
+ for (const list of scope ? scope.lists : collect(nabu, "list")) {
347
+ if (fixList(nabu, list, underConstruction, siblingsOf)) { changed = true; siblings.clear(); }
348
+ }
349
+ for (const item of scope ? scope.items : collect(nabu, "list-item")) {
350
+ if (fixItem(nabu, item)) { changed = true; siblings.clear(); }
351
+ }
352
+ return changed;
353
+ }
354
+
355
+ /** Keeps the lists that are still empty (and alive) among those this transaction left alone. @param {Nabu} nabu @param {Set<string>} ids */
356
+ function rememberEmpty(nabu, ids) {
357
+ /** @type {Set<string>} */
358
+ const still = new Set();
359
+ for (const id of ids) {
360
+ const list = liveNode(nabu, id);
361
+ if (list && typeOf(list) === "list" && !kids(list).length) still.add(id);
362
+ }
363
+ if (still.size) emptyLists.set(nabu, still);
364
+ else emptyLists.delete(nabu);
365
+ }
366
+
367
+ /**
368
+ * Brings the list structure back to its invariants (see the file header). Cheap when nothing
369
+ * structural is pending or when the document holds no list.
370
+ * @param {Nabu} nabu
371
+ * @param {{ full?: boolean }} [options] `full`: scan every list of the document instead of the scope of the pending ops
372
+ * found from the tree itself (the reference the scoped one is tested against: no dependence on the block registry)
373
+ */
374
+ export function normalizeLists(nabu, options) {
375
+ if (!nabu.blocksByType.get("list")?.size && !nabu.blocksByType.get("list-item")?.size) return;
376
+ const first = inspectPendingOps(nabu);
377
+ if (!first) return;
378
+ // Lists this transaction created and that are still empty: under construction, not "emptied".
379
+ /** @type {Set<string>} */
380
+ const underConstruction = new Set();
381
+ for (const id of first.created) {
382
+ const list = liveNode(nabu, id);
383
+ if (list && typeOf(list) === "list" && !kids(list).length) underConstruction.add(id);
384
+ }
385
+ const siblings = siblingsCache(nabu);
386
+ let pending = first;
387
+ for (let i = 0; i < MAX_PASSES; i++) {
388
+ if (!pass(nabu, underConstruction, options?.full ? treeScope(nabu) : scopeOf(nabu, pending, siblings), siblings)) {
389
+ rememberEmpty(nabu, underConstruction);
390
+ return;
391
+ }
392
+ // The normalizer's own ops are part of the transaction now: the next pass starts from everything touched so far.
393
+ pending = inspectPendingOps(nabu) ?? pending;
394
+ }
395
+ nabu.warn(`List normalizer did not converge after ${MAX_PASSES} passes; the list structure may be invalid.`);
396
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Sorts every block of the fragment in one of four kinds. Pure: no tree access.
3
+ * - `text`: a paragraph, or the text of a leaf block cut at the fragment's edges (partial copy);
4
+ * - `item`: a list item (alone: it comes from a partial copy of an item with its sublists);
5
+ * - `list`: a list with items;
6
+ * - `foreign`: whatever an item cannot hold.
7
+ * Returns null when the list has nothing to do: a single `text` block is the engine's inline merge.
8
+ * @param {PasteBlock[]} blocks
9
+ * @returns {PasteUnit[] | null}
10
+ */
11
+ export function planPaste(blocks: PasteBlock[]): PasteUnit[] | null;
12
+ /**
13
+ * Applies the paste (see the file header). Returns where the caret goes, or null when the list declines
14
+ * (nothing was touched).
15
+ * @param {Block} block the list item holding the caret
16
+ * @param {number} offset the caret offset in its text
17
+ * @param {PasteBlock[]} blocks
18
+ * @returns {{ block: Block | null, offset: number } | null}
19
+ */
20
+ export function pasteIntoItem(block: Block, offset: number, blocks: PasteBlock[]): {
21
+ block: Block | null;
22
+ offset: number;
23
+ } | null;
24
+ export type PasteUnit = {
25
+ kind: "text" | "item" | "list" | "foreign";
26
+ pb: PasteBlock;
27
+ };
28
+ export type ItemEntry = {
29
+ delta: any[];
30
+ /**
31
+ * the item's sublists
32
+ */
33
+ subs: PasteBlock[];
34
+ checked: boolean | undefined;
35
+ /**
36
+ * a partial copy starting in this item: its text merges into the caret item
37
+ */
38
+ head: boolean;
39
+ /**
40
+ * a partial copy ending in this item: its text merges with the tail
41
+ */
42
+ tail: boolean;
43
+ };
44
+ import type { PasteBlock } from "../../utils/extensions.js";
45
+ import type { Block } from "../block.svelte.js";
@@ -0,0 +1,242 @@
1
+ /**
2
+ * Pasting into a list item (P-49): "what a list item can hold is absorbed; everything else splits the list".
3
+ *
4
+ * Reached through the generic `Block#acceptPaste` extension point (see `ListItem#acceptPaste`); the engine
5
+ * knows nothing about lists. The pasted fragment, whatever its source (internal `application/x-nabu+json`,
6
+ * markdown, HTML, multi-line plain text), is a list of PasteBlocks, taken IN ORDER:
7
+ *
8
+ * - PARAGRAPHS become LIST ITEMS of the list the caret is in, at the same level, with the list's type (a to-do
9
+ * list gets unchecked items);
10
+ * - a pasted LIST gives its items to the list the caret is in, at the same level: they ADOPT THE CURRENT
11
+ * LIST'S TYPE (a numbered list pasted into a bullet list becomes bullets; like Notion, and the destination
12
+ * decides what the user sees). Their own nested sublists are kept as they are, types included (relative
13
+ * nesting preserved); a `checked` flag is kept only when the destination is a to-do list;
14
+ * - anything an item cannot hold (heading, code, quote, callout, divider, image, video, file, toggle,
15
+ * dialogue…) SPLITS the list at that point: the items before stay, the block goes right after them (at the
16
+ * list's parent level), the rest of the original list follows below, an ORDERED tail keeps counting
17
+ * (`start`). This is `liftItemTo` (step-back.js): same mechanism as Backspace / a type change on an item.
18
+ * From then on we are OUTSIDE the list: the remaining pasted blocks are inserted as they are (a paragraph
19
+ * stays a paragraph, a list stays a list) between the last block and the list tail.
20
+ * - the text of the caret item is cut at the caret: the head keeps its item (the FIRST pasted block merges
21
+ * into it when it is a paragraph, or a partial list item), the tail (text after the caret + the item's
22
+ * sublists) becomes the item that follows the pasted content, unless the LAST pasted block is a paragraph
23
+ * (or a partial list item) still inside the list: it then merges with the tail, like Enter + typing would.
24
+ * A sublist-less empty tail creates nothing; the sublists of the caret item stay under it when there is no
25
+ * tail text to carry them.
26
+ * - the caret ends right after the pasted content (at the junction when the last block merged with the tail).
27
+ *
28
+ * Moves / creations on tree NODES only, no commit: the caller owns the transaction (one undo step).
29
+ *
30
+ * @import { Block } from "../block.svelte.js";
31
+ * @import { Nabu, NabuNode } from "../nabu.svelte.js";
32
+ * @import { PasteBlock } from "../../utils/extensions.js";
33
+ */
34
+
35
+ import { kids, typeOf, listTypeOf, dropIfEmpty } from "./indent.js";
36
+ import { retypeItem } from "./convert.js";
37
+
38
+ /**
39
+ * @typedef {{ kind: "text" | "item" | "list" | "foreign", pb: PasteBlock }} PasteUnit
40
+ */
41
+
42
+ /** @param {PasteBlock} pb */
43
+ const isLeaf = (pb) => !pb.children?.length;
44
+
45
+ /** The text of a leaf block cut by the selection at its edges is plain text for the list. @param {PasteBlock} pb @param {boolean} first @param {boolean} last */
46
+ const isEdgeText = (pb, first, last) =>
47
+ isLeaf(pb) && ((first && (pb.partial === "start" || pb.partial === "both")) || (last && (pb.partial === "end" || pb.partial === "both")));
48
+
49
+ /**
50
+ * Sorts every block of the fragment in one of four kinds. Pure: no tree access.
51
+ * - `text`: a paragraph, or the text of a leaf block cut at the fragment's edges (partial copy);
52
+ * - `item`: a list item (alone: it comes from a partial copy of an item with its sublists);
53
+ * - `list`: a list with items;
54
+ * - `foreign`: whatever an item cannot hold.
55
+ * Returns null when the list has nothing to do: a single `text` block is the engine's inline merge.
56
+ * @param {PasteBlock[]} blocks
57
+ * @returns {PasteUnit[] | null}
58
+ */
59
+ export function planPaste(blocks) {
60
+ if (!blocks?.length) return null;
61
+ const last = blocks.length - 1;
62
+ /** @type {PasteUnit[]} */
63
+ const units = blocks.map((pb, i) => {
64
+ if (pb.type === "list" && !isLeaf(pb)) return { kind: "list", pb };
65
+ if (pb.type === "list-item" && !isEdgeText(pb, i === 0, i === last)) return { kind: "item", pb };
66
+ if (pb.type === "paragraph" && isLeaf(pb)) return { kind: "text", pb };
67
+ if (isEdgeText(pb, i === 0, i === last)) return { kind: "text", pb };
68
+ return { kind: "foreign", pb };
69
+ });
70
+ if (units.length === 1 && units[0].kind === "text") return null;
71
+ return units;
72
+ }
73
+
74
+ /**
75
+ * Deletes the sentinel item; the list it leaves empty goes too (the normalizer spares a list created by the
76
+ * same transaction, and a split creates the tail list). @param {Nabu} nabu @param {NabuNode} sentinel
77
+ */
78
+ function dropSentinel(nabu, sentinel) {
79
+ const host = sentinel.parent();
80
+ nabu.tree.delete(sentinel.id);
81
+ dropIfEmpty(nabu, host);
82
+ }
83
+
84
+ /** @param {NabuNode} node */
85
+ const isAlive = (node) => {
86
+ try { return !node.isDeleted(); } catch { return false; }
87
+ };
88
+
89
+ /** @param {NabuNode} node @returns {number} */
90
+ const textLength = (node) => /** @type {any} */ (node.data).get("text")?.length ?? 0;
91
+
92
+ /**
93
+ * The end of the last text under `node` (the node itself when it has no children), or null when that last
94
+ * leaf holds no text (an image…).
95
+ * @param {NabuNode} node
96
+ * @returns {{ node: NabuNode, offset: number } | null}
97
+ */
98
+ function textEnd(node) {
99
+ let current = node;
100
+ for (let children = kids(current); children.length; children = kids(current)) current = children[children.length - 1];
101
+ return /** @type {any} */ (current.data).get("text") ? { node: current, offset: textLength(current) } : null;
102
+ }
103
+
104
+ /**
105
+ * @typedef {Object} ItemEntry
106
+ * @property {any[]} delta
107
+ * @property {PasteBlock[]} subs the item's sublists
108
+ * @property {boolean | undefined} checked
109
+ * @property {boolean} head a partial copy starting in this item: its text merges into the caret item
110
+ * @property {boolean} tail a partial copy ending in this item: its text merges with the tail
111
+ */
112
+
113
+ /** @param {PasteBlock} pb @returns {ItemEntry} */
114
+ const itemEntry = (pb) => ({
115
+ delta: pb.delta ?? [],
116
+ subs: pb.children ?? [],
117
+ checked: pb.props?.checked,
118
+ head: pb.partial === "start" || pb.partial === "both",
119
+ tail: pb.partial === "end" || pb.partial === "both",
120
+ });
121
+
122
+ /**
123
+ * Applies the paste (see the file header). Returns where the caret goes, or null when the list declines
124
+ * (nothing was touched).
125
+ * @param {Block} block the list item holding the caret
126
+ * @param {number} offset the caret offset in its text
127
+ * @param {PasteBlock[]} blocks
128
+ * @returns {{ block: Block | null, offset: number } | null}
129
+ */
130
+ export function pasteIntoItem(block, offset, blocks) {
131
+ const units = planPaste(blocks);
132
+ if (!units) return null;
133
+ const nabu = block.nabu;
134
+ const node = /** @type {NabuNode} */ (block.node);
135
+ const list = node.parent();
136
+ const text = /** @type {any} */ (block.behaviors?.get("text"));
137
+ if (!text || !list || typeOf(list) !== "list") return null;
138
+ const ItemClass = /** @type {any} */ (block.constructor);
139
+
140
+ // ── 1. Cut the caret item: head stays, tail (text + sublists) goes to a sentinel item right after it ──
141
+ const container = text.container;
142
+ const tailDelta = container.sliceDelta(offset, container.length);
143
+ const hasTail = container.length > offset;
144
+ if (hasTail) text.delete({ index: offset, length: container.length - offset });
145
+ const sublists = kids(node);
146
+ const sentinel = ItemClass.create(
147
+ nabu, "list-item",
148
+ { delta: tailDelta, ...(listTypeOf(list) === "todo" ? { checked: false } : {}) },
149
+ list.id.toString(), (node.index() ?? 0) + 1,
150
+ ).node;
151
+ if (hasTail) for (const sub of sublists) sub.move(sentinel, kids(sentinel).length);
152
+
153
+ // Does the first pasted block merge into the head? A paragraph / partial item does; so does any item
154
+ // when the caret item is empty (it is replaced by the pasted content, not left behind empty).
155
+ const firstUnit = units[0];
156
+ const firstEntry = firstUnit.kind === "list" ? itemEntry(firstUnit.pb.children?.[0] ?? firstUnit.pb)
157
+ : firstUnit.kind === "item" ? itemEntry(firstUnit.pb) : null;
158
+ const mergesHead = firstUnit.kind === "text" || (!!firstEntry && (firstEntry.head || (offset === 0 && !hasTail)));
159
+ // Blank head left behind by a first block that does not merge: gone (nothing precedes the caret).
160
+ if (offset === 0 && !mergesHead && !kids(node).length) nabu.tree.delete(node.id);
161
+
162
+ // ── 2. The pasted blocks, in order ──
163
+ /** @type {NabuNode | null} */
164
+ let lastItem = null; // last item emitted inside the list (the head included)
165
+ let lastMergesTail = false;
166
+ let outside = false;
167
+ /** @type {any} */
168
+ let previousOuter = null; // last block inserted outside the list
169
+ /** @type {{ node: NabuNode, offset: number } | null} */
170
+ let focus = null;
171
+ let lastIsVoid = false;
172
+
173
+ /** @param {ItemEntry} entry @param {boolean} isFirst @param {boolean} mergesTailIfLast */
174
+ const emitItem = (entry, isFirst, mergesTailIfLast) => {
175
+ lastMergesTail = mergesTailIfLast;
176
+ if (isFirst && mergesHead) {
177
+ text.applyDelta([{ retain: offset }, ...entry.delta]);
178
+ for (const sub of entry.subs) nabu.createPasteBlock(sub, node.id.toString());
179
+ lastItem = node;
180
+ focus = textEnd(node);
181
+ return;
182
+ }
183
+ const host = /** @type {NabuNode} */ (sentinel.parent());
184
+ /** @type {Record<string, any>} */
185
+ const props = { delta: entry.delta };
186
+ if (listTypeOf(host) === "todo") props.checked = entry.checked === undefined ? false : !!entry.checked;
187
+ const item = ItemClass.create(nabu, "list-item", props, host.id.toString(), sentinel.index() ?? 0);
188
+ for (const sub of entry.subs) nabu.createPasteBlock(sub, item.node.id.toString());
189
+ lastItem = item.node;
190
+ focus = textEnd(item.node);
191
+ };
192
+
193
+ units.forEach((unit, u) => {
194
+ const isLastUnit = u === units.length - 1;
195
+ if (outside) {
196
+ previousOuter = nabu.insertPasteBlock(unit.pb, previousOuter);
197
+ focus = textEnd(previousOuter);
198
+ lastIsVoid = !focus;
199
+ return;
200
+ }
201
+ if (unit.kind === "foreign") {
202
+ // Split the list at the sentinel (= the caret): a placeholder item takes the place, is lifted out of
203
+ // the list (items after it go to a new list, numbering continues) and replaced by the real block.
204
+ const host = /** @type {NabuNode} */ (sentinel.parent());
205
+ const placeholder = ItemClass.create(nabu, "list-item", {}, host.id.toString(), sentinel.index() ?? 0).node;
206
+ retypeItem(nabu, placeholder, "paragraph", {}, false);
207
+ previousOuter = nabu.insertPasteBlock(unit.pb, placeholder);
208
+ nabu.tree.delete(placeholder.id);
209
+ outside = true;
210
+ lastItem = null;
211
+ focus = textEnd(previousOuter);
212
+ lastIsVoid = !focus;
213
+ return;
214
+ }
215
+ if (unit.kind === "text") {
216
+ emitItem({ delta: unit.pb.delta ?? [], subs: [], checked: undefined, head: true, tail: true }, u === 0, isLastUnit);
217
+ return;
218
+ }
219
+ const entries = unit.kind === "list" ? (unit.pb.children ?? []).map(itemEntry) : [itemEntry(unit.pb)];
220
+ entries.forEach((entry, k) => emitItem(entry, u === 0 && k === 0, isLastUnit && k === entries.length - 1 && entry.tail));
221
+ });
222
+
223
+ // ── 3. The tail ──
224
+ if (!outside && lastItem && lastMergesTail) {
225
+ // The last pasted block merges with the tail: the junction is where the caret ends.
226
+ const target = /** @type {NabuNode} */ (lastItem);
227
+ const targetText = /** @type {any} */ (nabu.blocks.get(target.id.toString())?.behaviors?.get("text"));
228
+ const junction = textLength(target);
229
+ if (hasTail) targetText.applyDelta([{ retain: junction }, ...tailDelta]);
230
+ for (const sub of sublists) if (sub.parent()?.id.toString() !== target.id.toString()) sub.move(target, kids(target).length);
231
+ dropSentinel(nabu, sentinel);
232
+ return { block: nabu.blocks.get(target.id.toString()) ?? null, offset: junction };
233
+ }
234
+ if (!textLength(sentinel) && !kids(sentinel).length) {
235
+ dropSentinel(nabu, sentinel);
236
+ } else if (lastIsVoid || !focus) {
237
+ focus = { node: sentinel, offset: 0 };
238
+ }
239
+ if (!focus && isAlive(node)) focus = textEnd(node);
240
+ const caretBlock = focus ? nabu.blocks.get(focus.node.id.toString()) ?? null : null;
241
+ return { block: caretBlock, offset: focus?.offset ?? 0 };
242
+ }