@aionbuilders/nabu 0.1.0-alpha.9 → 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 (319) hide show
  1. package/CHANGELOG.md +523 -0
  2. package/LICENSE +21 -0
  3. package/README.md +82 -144
  4. package/dist/behaviors/text/RichText.svelte +25 -2
  5. package/dist/behaviors/text/index.d.ts +2 -0
  6. package/dist/behaviors/text/index.js +2 -0
  7. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +5 -0
  8. package/dist/behaviors/text/markdown-shortcuts.extension.js +79 -0
  9. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  10. package/dist/behaviors/text/markdown-syntax.js +81 -0
  11. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  12. package/dist/behaviors/text/rich-text.extension.js +135 -53
  13. package/dist/behaviors/text/text.behavior.svelte.d.ts +217 -42
  14. package/dist/behaviors/text/text.behavior.svelte.js +657 -55
  15. package/dist/behaviors/text/typography.extension.d.ts +7 -0
  16. package/dist/behaviors/text/typography.extension.js +25 -0
  17. package/dist/blocks/Block.svelte +5 -2
  18. package/dist/blocks/BlockList.svelte +48 -0
  19. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  20. package/dist/blocks/Nabu.svelte +180 -14
  21. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  22. package/dist/blocks/block.extension.d.ts +3 -0
  23. package/dist/blocks/block.extension.js +8 -9
  24. package/dist/blocks/block.svelte.d.ts +356 -68
  25. package/dist/blocks/block.svelte.js +388 -42
  26. package/dist/blocks/blockquote/Blockquote.svelte +39 -0
  27. package/dist/blocks/blockquote/Blockquote.svelte.d.ts +11 -0
  28. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -0
  29. package/dist/blocks/blockquote/blockquote.extension.js +80 -0
  30. package/dist/blocks/blockquote/blockquote.svelte.d.ts +63 -0
  31. package/dist/blocks/blockquote/blockquote.svelte.js +136 -0
  32. package/dist/blocks/blockquote/index.d.ts +3 -0
  33. package/dist/blocks/blockquote/index.js +3 -0
  34. package/dist/blocks/callout/Callout.svelte +67 -0
  35. package/dist/blocks/callout/Callout.svelte.d.ts +11 -0
  36. package/dist/blocks/callout/callout.extension.d.ts +4 -0
  37. package/dist/blocks/callout/callout.extension.js +84 -0
  38. package/dist/blocks/callout/callout.svelte.d.ts +80 -0
  39. package/dist/blocks/callout/callout.svelte.js +189 -0
  40. package/dist/blocks/callout/index.d.ts +3 -0
  41. package/dist/blocks/callout/index.js +3 -0
  42. package/dist/blocks/chunks.d.ts +49 -0
  43. package/dist/blocks/chunks.js +90 -0
  44. package/dist/blocks/code/Code.svelte +84 -0
  45. package/dist/blocks/code/Code.svelte.d.ts +11 -0
  46. package/dist/blocks/code/code.extension.d.ts +4 -0
  47. package/dist/blocks/code/code.extension.js +88 -0
  48. package/dist/blocks/code/code.svelte.d.ts +68 -0
  49. package/dist/blocks/code/code.svelte.js +245 -0
  50. package/dist/blocks/code/index.d.ts +3 -0
  51. package/dist/blocks/code/index.js +3 -0
  52. package/dist/blocks/container.utils.d.ts +85 -13
  53. package/dist/blocks/container.utils.js +338 -178
  54. package/dist/blocks/dialogue/Dialogue.svelte +8 -2
  55. package/dist/blocks/dialogue/dialogue.svelte.d.ts +36 -23
  56. package/dist/blocks/dialogue/dialogue.svelte.js +51 -45
  57. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  58. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  59. package/dist/blocks/dialogue/index.d.ts +12 -1
  60. package/dist/blocks/dialogue/index.js +51 -35
  61. package/dist/blocks/divider/Divider.svelte +28 -0
  62. package/dist/blocks/divider/Divider.svelte.d.ts +11 -0
  63. package/dist/blocks/divider/divider.extension.d.ts +23 -0
  64. package/dist/blocks/divider/divider.extension.js +153 -0
  65. package/dist/blocks/divider/divider.svelte.d.ts +54 -0
  66. package/dist/blocks/divider/divider.svelte.js +89 -0
  67. package/dist/blocks/divider/index.d.ts +3 -0
  68. package/dist/blocks/divider/index.js +3 -0
  69. package/dist/blocks/file/File.svelte +56 -0
  70. package/dist/blocks/file/File.svelte.d.ts +11 -0
  71. package/dist/blocks/file/file.extension.d.ts +4 -0
  72. package/dist/blocks/file/file.extension.js +27 -0
  73. package/dist/blocks/file/file.svelte.d.ts +29 -0
  74. package/dist/blocks/file/file.svelte.js +77 -0
  75. package/dist/blocks/file/index.d.ts +3 -0
  76. package/dist/blocks/file/index.js +3 -0
  77. package/dist/blocks/heading/Heading.svelte +2 -1
  78. package/dist/blocks/heading/heading.svelte.d.ts +27 -34
  79. package/dist/blocks/heading/heading.svelte.js +72 -60
  80. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  81. package/dist/blocks/heading/index.d.ts +2 -2
  82. package/dist/blocks/heading/index.js +33 -8
  83. package/dist/blocks/image/Image.svelte +41 -0
  84. package/dist/blocks/image/Image.svelte.d.ts +11 -0
  85. package/dist/blocks/image/image.extension.d.ts +5 -0
  86. package/dist/blocks/image/image.extension.js +34 -0
  87. package/dist/blocks/image/image.svelte.d.ts +61 -0
  88. package/dist/blocks/image/image.svelte.js +114 -0
  89. package/dist/blocks/image/index.d.ts +3 -0
  90. package/dist/blocks/image/index.js +3 -0
  91. package/dist/blocks/index.d.ts +11 -1
  92. package/dist/blocks/index.js +11 -1
  93. package/dist/blocks/list/List.svelte +9 -2
  94. package/dist/blocks/list/ListItem.svelte +44 -7
  95. package/dist/blocks/list/convert.d.ts +20 -0
  96. package/dist/blocks/list/convert.js +92 -0
  97. package/dist/blocks/list/hooks/onBeforeInput.hook.js +60 -26
  98. package/dist/blocks/list/html-flat.d.ts +78 -0
  99. package/dist/blocks/list/html-flat.js +244 -0
  100. package/dist/blocks/list/indent.d.ts +86 -0
  101. package/dist/blocks/list/indent.js +205 -0
  102. package/dist/blocks/list/index.d.ts +7 -3
  103. package/dist/blocks/list/index.js +43 -31
  104. package/dist/blocks/list/list-item.svelte.d.ts +43 -17
  105. package/dist/blocks/list/list-item.svelte.js +143 -93
  106. package/dist/blocks/list/list.behavior.svelte.d.ts +7 -4
  107. package/dist/blocks/list/list.behavior.svelte.js +10 -5
  108. package/dist/blocks/list/list.svelte.d.ts +101 -23
  109. package/dist/blocks/list/list.svelte.js +136 -114
  110. package/dist/blocks/list/markdown.d.ts +149 -0
  111. package/dist/blocks/list/markdown.js +442 -0
  112. package/dist/blocks/list/normalize.d.ts +11 -0
  113. package/dist/blocks/list/normalize.js +396 -0
  114. package/dist/blocks/list/paste.d.ts +45 -0
  115. package/dist/blocks/list/paste.js +242 -0
  116. package/dist/blocks/list/step-back.d.ts +24 -0
  117. package/dist/blocks/list/step-back.js +87 -0
  118. package/dist/blocks/list/to-list.d.ts +7 -0
  119. package/dist/blocks/list/to-list.js +44 -0
  120. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  121. package/dist/blocks/list/todos-toggle.js +48 -0
  122. package/dist/blocks/list/todos.svelte.d.ts +35 -0
  123. package/dist/blocks/list/todos.svelte.js +76 -0
  124. package/dist/blocks/media/index.d.ts +2 -0
  125. package/dist/blocks/media/index.js +2 -0
  126. package/dist/blocks/media/markdown.d.ts +12 -0
  127. package/dist/blocks/media/markdown.js +26 -0
  128. package/dist/blocks/media/media-block.svelte.d.ts +107 -0
  129. package/dist/blocks/media/media-block.svelte.js +181 -0
  130. package/dist/blocks/media/media.helpers.d.ts +24 -0
  131. package/dist/blocks/media/media.helpers.js +88 -0
  132. package/dist/blocks/megablock.svelte.d.ts +50 -19
  133. package/dist/blocks/megablock.svelte.js +115 -74
  134. package/dist/blocks/move.d.ts +23 -0
  135. package/dist/blocks/move.js +92 -0
  136. package/dist/blocks/nabu.svelte.d.ts +846 -75
  137. package/dist/blocks/nabu.svelte.js +1990 -182
  138. package/dist/blocks/paragraph/Paragraph.svelte +1 -0
  139. package/dist/blocks/paragraph/index.d.ts +2 -2
  140. package/dist/blocks/paragraph/index.js +35 -16
  141. package/dist/blocks/paragraph/paragraph.svelte.d.ts +49 -35
  142. package/dist/blocks/paragraph/paragraph.svelte.js +81 -69
  143. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  144. package/dist/blocks/paragraph/table.html.js +111 -0
  145. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  146. package/dist/blocks/paragraph/table.markdown.js +90 -0
  147. package/dist/blocks/region/Region.svelte +264 -0
  148. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  149. package/dist/blocks/region/actions.d.ts +135 -0
  150. package/dist/blocks/region/actions.js +402 -0
  151. package/dist/blocks/region/close.d.ts +35 -0
  152. package/dist/blocks/region/close.js +130 -0
  153. package/dist/blocks/region/commands.d.ts +6 -0
  154. package/dist/blocks/region/commands.js +277 -0
  155. package/dist/blocks/region/create.d.ts +72 -0
  156. package/dist/blocks/region/create.js +208 -0
  157. package/dist/blocks/region/end-marker.d.ts +35 -0
  158. package/dist/blocks/region/end-marker.js +51 -0
  159. package/dist/blocks/region/facts.d.ts +69 -0
  160. package/dist/blocks/region/facts.js +152 -0
  161. package/dist/blocks/region/format.d.ts +91 -0
  162. package/dist/blocks/region/format.js +260 -0
  163. package/dist/blocks/region/index.d.ts +14 -0
  164. package/dist/blocks/region/index.js +14 -0
  165. package/dist/blocks/region/insert.d.ts +59 -0
  166. package/dist/blocks/region/insert.js +102 -0
  167. package/dist/blocks/region/messages.d.ts +254 -0
  168. package/dist/blocks/region/messages.js +131 -0
  169. package/dist/blocks/region/normalize.d.ts +7 -0
  170. package/dist/blocks/region/normalize.js +170 -0
  171. package/dist/blocks/region/region.extension.d.ts +58 -0
  172. package/dist/blocks/region/region.extension.js +119 -0
  173. package/dist/blocks/region/region.svelte.d.ts +221 -0
  174. package/dist/blocks/region/region.svelte.js +582 -0
  175. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  176. package/dist/blocks/region/regions.svelte.js +276 -0
  177. package/dist/blocks/region/serialize.d.ts +57 -0
  178. package/dist/blocks/region/serialize.js +112 -0
  179. package/dist/blocks/region/types.d.ts +255 -0
  180. package/dist/blocks/region/types.js +204 -0
  181. package/dist/blocks/selection.svelte.d.ts +106 -8
  182. package/dist/blocks/selection.svelte.js +632 -74
  183. package/dist/blocks/subthread.d.ts +80 -0
  184. package/dist/blocks/subthread.js +167 -0
  185. package/dist/blocks/text-block.svelte.d.ts +70 -0
  186. package/dist/blocks/text-block.svelte.js +108 -0
  187. package/dist/blocks/toggle/Toggle.svelte +73 -0
  188. package/dist/blocks/toggle/Toggle.svelte.d.ts +11 -0
  189. package/dist/blocks/toggle/index.d.ts +3 -0
  190. package/dist/blocks/toggle/index.js +3 -0
  191. package/dist/blocks/toggle/markdown.d.ts +20 -0
  192. package/dist/blocks/toggle/markdown.js +112 -0
  193. package/dist/blocks/toggle/toggle.extension.d.ts +4 -0
  194. package/dist/blocks/toggle/toggle.extension.js +18 -0
  195. package/dist/blocks/toggle/toggle.svelte.d.ts +135 -0
  196. package/dist/blocks/toggle/toggle.svelte.js +352 -0
  197. package/dist/blocks/undo-selection.d.ts +175 -0
  198. package/dist/blocks/undo-selection.js +360 -0
  199. package/dist/blocks/video/Video.svelte +42 -0
  200. package/dist/blocks/video/Video.svelte.d.ts +11 -0
  201. package/dist/blocks/video/index.d.ts +3 -0
  202. package/dist/blocks/video/index.js +3 -0
  203. package/dist/blocks/video/video.extension.d.ts +4 -0
  204. package/dist/blocks/video/video.extension.js +27 -0
  205. package/dist/blocks/video/video.svelte.d.ts +29 -0
  206. package/dist/blocks/video/video.svelte.js +80 -0
  207. package/dist/extend.d.ts +55 -0
  208. package/dist/extend.js +88 -0
  209. package/dist/files/assets.clipboard.d.ts +77 -0
  210. package/dist/files/assets.clipboard.js +152 -0
  211. package/dist/files/files.svelte.d.ts +363 -0
  212. package/dist/files/files.svelte.js +897 -0
  213. package/dist/files/index.d.ts +3 -0
  214. package/dist/files/index.js +3 -0
  215. package/dist/files/outbox.d.ts +69 -0
  216. package/dist/files/outbox.js +48 -0
  217. package/dist/files/status.d.ts +65 -0
  218. package/dist/files/status.js +87 -0
  219. package/dist/files/store.d.ts +97 -0
  220. package/dist/files/store.js +65 -0
  221. package/dist/files/uploads.svelte.d.ts +174 -0
  222. package/dist/files/uploads.svelte.js +504 -0
  223. package/dist/index.d.ts +68 -6
  224. package/dist/index.js +117 -7
  225. package/dist/nabu-theme.css +112 -0
  226. package/dist/paste/html.paste.d.ts +74 -3
  227. package/dist/paste/html.paste.js +555 -83
  228. package/dist/paste/markdown-inline.d.ts +86 -0
  229. package/dist/paste/markdown-inline.js +528 -0
  230. package/dist/paste/markdown.paste.d.ts +2 -8
  231. package/dist/paste/markdown.paste.js +78 -94
  232. package/dist/paste/nabu.paste.d.ts +3 -0
  233. package/dist/paste/nabu.paste.js +29 -3
  234. package/dist/paste/plain-text.paste.d.ts +2 -2
  235. package/dist/paste/plain-text.paste.js +3 -3
  236. package/dist/persistence/asset-store.d.ts +51 -0
  237. package/dist/persistence/asset-store.js +103 -0
  238. package/dist/persistence/autosave.d.ts +53 -0
  239. package/dist/persistence/autosave.js +62 -0
  240. package/dist/persistence/compact.d.ts +162 -0
  241. package/dist/persistence/compact.js +141 -0
  242. package/dist/persistence/history.d.ts +77 -0
  243. package/dist/persistence/history.js +176 -0
  244. package/dist/persistence/indexeddb.d.ts +190 -4
  245. package/dist/persistence/indexeddb.js +333 -29
  246. package/dist/persistence/merge.d.ts +38 -0
  247. package/dist/persistence/merge.js +36 -0
  248. package/dist/persistence/outbox.d.ts +25 -0
  249. package/dist/persistence/outbox.js +40 -0
  250. package/dist/persistence/persistence.d.ts +70 -9
  251. package/dist/persistence/persistence.js +507 -35
  252. package/dist/persistence/recovery.d.ts +79 -0
  253. package/dist/persistence/recovery.js +79 -0
  254. package/dist/persistence/release.d.ts +34 -0
  255. package/dist/persistence/release.js +64 -0
  256. package/dist/persistence/state.svelte.d.ts +53 -0
  257. package/dist/persistence/state.svelte.js +48 -0
  258. package/dist/persistence/sync.d.ts +39 -0
  259. package/dist/persistence/sync.js +138 -0
  260. package/dist/persistence/tail.d.ts +42 -0
  261. package/dist/persistence/tail.js +103 -0
  262. package/dist/presets.d.ts +29 -24
  263. package/dist/presets.js +51 -14
  264. package/dist/themes/atelier.css +318 -0
  265. package/dist/ui/CommandChooser.svelte +153 -0
  266. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  267. package/dist/ui/CommandInvite.svelte +99 -0
  268. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  269. package/dist/ui/DragHandle.svelte +217 -0
  270. package/dist/ui/DragHandle.svelte.d.ts +11 -0
  271. package/dist/ui/FloatingToolbar.svelte +165 -0
  272. package/dist/ui/FloatingToolbar.svelte.d.ts +27 -0
  273. package/dist/ui/SlashMenu.svelte +215 -0
  274. package/dist/ui/SlashMenu.svelte.d.ts +33 -0
  275. package/dist/ui/anchor.d.ts +112 -0
  276. package/dist/ui/anchor.js +136 -0
  277. package/dist/ui/index.d.ts +10 -0
  278. package/dist/ui/index.js +15 -0
  279. package/dist/ui/slash-menu.svelte.d.ts +112 -0
  280. package/dist/ui/slash-menu.svelte.js +150 -0
  281. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  282. package/dist/utils/command-confirm.svelte.js +673 -0
  283. package/dist/utils/commands.d.ts +328 -0
  284. package/dist/utils/commands.js +416 -0
  285. package/dist/utils/dom-scope.d.ts +14 -0
  286. package/dist/utils/dom-scope.js +20 -0
  287. package/dist/utils/drop.d.ts +160 -0
  288. package/dist/utils/drop.js +305 -0
  289. package/dist/utils/extensions.d.ts +488 -40
  290. package/dist/utils/extensions.js +300 -19
  291. package/dist/utils/html.d.ts +44 -0
  292. package/dist/utils/html.js +183 -0
  293. package/dist/utils/index.d.ts +4 -0
  294. package/dist/utils/index.js +4 -0
  295. package/dist/utils/keys.d.ts +120 -0
  296. package/dist/utils/keys.js +248 -0
  297. package/dist/utils/links.d.ts +22 -0
  298. package/dist/utils/links.js +34 -0
  299. package/dist/utils/placeholders.d.ts +88 -0
  300. package/dist/utils/placeholders.js +91 -0
  301. package/dist/utils/selection.svelte.d.ts +47 -19
  302. package/dist/utils/selection.svelte.js +60 -10
  303. package/dist/utils/spellcheck.d.ts +9 -0
  304. package/dist/utils/spellcheck.js +17 -0
  305. package/dist/utils/tab.d.ts +31 -0
  306. package/dist/utils/tab.js +117 -0
  307. package/dist/utils/words.d.ts +7 -0
  308. package/dist/utils/words.js +62 -0
  309. package/dist/vite.d.ts +22 -0
  310. package/dist/vite.js +34 -0
  311. package/package.json +61 -22
  312. package/dist/blocks/zone/Zone.svelte +0 -258
  313. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  314. package/dist/blocks/zone/index.d.ts +0 -2
  315. package/dist/blocks/zone/index.js +0 -2
  316. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  317. package/dist/blocks/zone/zone.extension.js +0 -221
  318. package/dist/blocks/zone/zone.svelte.d.ts +0 -112
  319. package/dist/blocks/zone/zone.svelte.js +0 -321
@@ -1,5 +1,7 @@
1
1
 
2
+ import { untrack } from "svelte";
2
3
  import { SvelteSelection } from "../utils/selection.svelte.js";
4
+ import { closestWithin } from "../utils/dom-scope.js";
3
5
 
4
6
  /**
5
7
  * @import { Nabu } from "./nabu.svelte.js";
@@ -8,11 +10,110 @@ import { SvelteSelection } from "../utils/selection.svelte.js";
8
10
  */
9
11
 
10
12
  export class NabuSelection extends SvelteSelection {
13
+ /** How many times the editor itself placed the selection: lets a deferred fix-up tell that someone else already did. */
14
+ placements = 0;
15
+
16
+ // ── Which part of the page is MINE ───────────────────────────────────────
17
+ // The DOM selection is a single, page-wide object: with several editors on a page every engine sees the caret of all the
18
+ // others. An engine only ever acts on the selection that lies in its OWN root (the `[data-nabu-root]` element that
19
+ // `Nabu.svelte` mounts and hands over with `attachRoot`). Three kinds of endpoint, for an engine:
20
+ // - 'mine' inside my root and not inside a NESTED editor (an editor in one of my UI islands is not mine);
21
+ // - 'foreign' inside another editor's root (a neighbour, or a nested editor);
22
+ // - 'none' inside no editor at all (page text, a form field, the body).
23
+ // And three kinds of selection (see `scope`):
24
+ // - 'mine' at least one end is mine and no end is foreign: normalized, mirrored in the model, recorded for undo;
25
+ // - 'outside' no end is mine and none is foreign: none of my business (not mirrored, not normalized, not recorded);
26
+ // - 'foreign' (including a range that CROSSES roots, anchor in one editor and focus in another, e.g. a drag from one editor
27
+ // to the next): left strictly alone by every engine. Nobody rewrites it, and each engine reads it as "no selection of
28
+ // mine". The browser (or the user) is the only one to change it.
29
+
30
+ /**
31
+ * The root element of this engine (set by `Nabu.svelte` through {@link NabuSelection#attachRoot}); null while no editor is
32
+ * mounted. Not part of the stable contract.
33
+ * @type {HTMLElement | null}
34
+ */
35
+ root = null;
36
+
37
+ /**
38
+ * Declare the element that renders this engine (the `[data-nabu-root]` div). Returns the function that detaches it (only
39
+ * clears the reference when it is still this element: a remount may already have set the next one).
40
+ * @param {HTMLElement} el
41
+ * @returns {() => void}
42
+ */
43
+ attachRoot(el) {
44
+ this.root = el;
45
+ return () => { if (this.root === el) this.root = null; };
46
+ }
47
+
48
+ /**
49
+ * How `node` stands relative to this engine's root (see above). A node of a detached tree is 'none'.
50
+ * @param {Node | null | undefined} node
51
+ * @returns {'mine' | 'foreign' | 'none'}
52
+ */
53
+ kindOf(node) {
54
+ if (!node) return 'none';
55
+ const el = /** @type {Element | null} */ (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement);
56
+ const root = el?.closest('[data-nabu-root]');
57
+ if (!root) return 'none';
58
+ return root === this.root ? 'mine' : 'foreign';
59
+ }
60
+
61
+ /** Whether `node` is inside this engine's own root (and not inside a nested editor). @param {Node | null | undefined} node */
62
+ owns(node) { return this.kindOf(node) === 'mine'; }
63
+
64
+ /**
65
+ * The nearest ancestor-or-self of `node` matching `selector` that lies inside MY root: a `[data-nabu-ui]` island or an inert
66
+ * block AROUND my root (this editor nested in a block of another one) is not a marker of my content.
67
+ * @param {Node | null | undefined} node @param {string} selector
68
+ * @returns {Element | null}
69
+ */
70
+ closestOwn(node, selector) { return closestWithin(node, selector, this.root); }
71
+
72
+ /**
73
+ * The scope of the live DOM selection for this engine (see above).
74
+ * @param {Selection | null} [live] defaults to `window.getSelection()`
75
+ * @returns {'mine' | 'outside' | 'foreign'}
76
+ */
77
+ scope(live = typeof window !== 'undefined' && window.getSelection ? window.getSelection() : null) {
78
+ if (!live || live.rangeCount === 0) return 'outside';
79
+ const a = this.kindOf(live.anchorNode);
80
+ const f = this.kindOf(live.focusNode);
81
+ if (a === 'foreign' || f === 'foreign') return 'foreign';
82
+ return a === 'mine' || f === 'mine' ? 'mine' : 'outside';
83
+ }
84
+
85
+ /**
86
+ * The model mirrors a selection that is mine, and one in an editor's CHROME outside every root (its floating toolbar: the
87
+ * toolbar must not vanish because the user pressed on it). A selection in another editor, across roots, or in the page is
88
+ * not mirrored: the model reads "no selection of mine" (see `scope`).
89
+ * @param {Selection} raw
90
+ */
91
+ reflects(raw) {
92
+ const scope = this.scope(raw);
93
+ if (scope !== 'outside') return scope === 'mine';
94
+ const chrome = (/** @type {Node | null} */ node) => {
95
+ const el = /** @type {Element | null} */ (node && (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement));
96
+ return !!el?.closest('[data-nabu-ui]');
97
+ };
98
+ return chrome(raw.anchorNode) || chrome(raw.focusNode);
99
+ }
100
+
11
101
  /** @param {Nabu} nabu */
12
102
  constructor(nabu) {
13
103
  super();
14
104
  this.nabu = nabu;
15
105
 
106
+ // Every caret the editor itself places (after an action, an undo…) is remembered for undo / redo (ADR 015): it is
107
+ // where that action ended. `setBaseAndExtent` is an own-property arrow function of the base class: wrap it.
108
+ const placeSelection = this.setBaseAndExtent;
109
+ /** @param {Node} anchorNode @param {number} anchorOffset @param {Node} focusNode @param {number} focusOffset */
110
+ this.setBaseAndExtent = (anchorNode, anchorOffset, focusNode, focusOffset) => {
111
+ this.placements++;
112
+ const done = placeSelection(anchorNode, anchorOffset, focusNode, focusOffset);
113
+ this.nabu.captureUndoSelection?.('settle');
114
+ return done;
115
+ };
116
+
16
117
  $effect.root(() => {
17
118
  $effect(() => {
18
119
  if (this.blocks) {
@@ -35,110 +136,549 @@ export class NabuSelection extends SvelteSelection {
35
136
  $effect(() => {
36
137
  /** @param {KeyboardEvent} e */
37
138
  const onKeydown = (e) => {
139
+ // Capture phase on document = runs before every other keydown handler
140
+ // (root handler, slash menu…): make sure they read the CURRENT caret,
141
+ // not the one from a not-yet-delivered `selectionchange`.
142
+ this.sync();
143
+ // A key typed while the selection is in another editor (or nowhere in an editor) is none of my business.
144
+ if (this.scope() !== 'mine') return;
145
+ this.nabu.captureUndoSelection?.(); // the selection an undo step pushed by this key gives back
146
+ if (e.isComposing || e.keyCode === 229) return; // IME composition: hands off the caret
147
+ // A caret left on a dead position by the PREVIOUS key is fixed (with that key's direction)
148
+ // before this one acts on it.
149
+ this.normalize();
150
+ this.#arrowStart = null;
151
+ this.#shiftAnchor = null;
152
+ this.#homeFocus = null;
153
+ this.#vertical = null;
154
+ if ((e.key === 'ArrowUp' || e.key === 'ArrowDown') && !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey) {
155
+ // A plain vertical move: the browser steps over a text block with no text (see `#stepIntoEmpty`).
156
+ const live = window.getSelection();
157
+ const block = live?.isCollapsed ? this.#blockOf(live.anchorNode) : null;
158
+ if (live?.anchorNode && block) this.#vertical = { key: e.key, block, node: live.anchorNode, offset: live.anchorOffset, at: Date.now() };
159
+ }
160
+ if (e.key === 'Home' && e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey) {
161
+ // Shift+Home extends the focus to the start of its line: where it was, to put it back there if the browser
162
+ // answers with the "equivalent" position at the end of the PREVIOUS block (see `#canonicalHome`).
163
+ const live = window.getSelection();
164
+ const block = this.#blockOf(live?.focusNode ?? null);
165
+ if (live?.focusNode && block) this.#homeFocus = { block, node: live.focusNode, offset: live.focusOffset, at: Date.now() };
166
+ }
167
+ if (e.shiftKey && !e.altKey && ['ArrowRight', 'ArrowDown', 'ArrowLeft', 'ArrowUp'].includes(e.key)) {
168
+ // The anchor of a selection being extended: a browser that cannot extend onto a non-editable
169
+ // sibling (a block's label…) may drop it; `normalize()` puts it back.
170
+ const live = window.getSelection();
171
+ if (live?.anchorNode) this.#shiftAnchor = { node: live.anchorNode, offset: live.anchorOffset };
172
+ }
38
173
  if (e.key === 'ArrowRight' || e.key === 'ArrowDown') {
39
174
  this.#pendingDirection = 'forward';
175
+ const live = window.getSelection();
176
+ if (live?.isCollapsed && live.anchorNode && !e.shiftKey && !e.ctrlKey && !e.metaKey && !e.altKey) {
177
+ this.#arrowStart = { key: e.key, node: live.anchorNode, offset: live.anchorOffset };
178
+ }
179
+ this.nabu.storedMarks = null;
40
180
  } else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') {
41
181
  this.#pendingDirection = 'backward';
182
+ this.nabu.storedMarks = null;
42
183
  } else {
43
184
  this.#pendingDirection = null;
185
+ if (e.key === 'Home' || e.key === 'End' || e.key === 'PageUp' || e.key === 'PageDown') {
186
+ this.nabu.storedMarks = null;
187
+ }
44
188
  }
45
189
  };
190
+ // The browser applies an arrow key's caret move right after `keydown`, but delivers `selectionchange`
191
+ // later (a task of its own): fix a dead landing as soon as the key is released, not a task later.
192
+ const onKeyup = (/** @type {KeyboardEvent} */ e) => {
193
+ this.sync();
194
+ if (this.scope() !== 'mine') return;
195
+ if (e.isComposing || e.keyCode === 229) return;
196
+ this.#keyReleased = true; // the browser has moved the caret by now: "it did not move" means something
197
+ this.normalize();
198
+ this.#keyReleased = false;
199
+ const start = this.#arrowStart;
200
+ this.#arrowStart = null;
201
+ if (start && start.key === e.key) this.#openTrailingIfStuck(start);
202
+ };
203
+ const onMousedown = (/** @type {MouseEvent} */ e) => {
204
+ // A click inside another editor (a neighbour, a nested one) is none of my business; one on the page or on a
205
+ // toolbar still ends what I was doing (stored marks, the "where did the last action end" mark).
206
+ if (this.kindOf(/** @type {Node | null} */ (e.target instanceof Node ? e.target : null)) === 'foreign') return;
207
+ this.nabu.storedMarks = null; this.#pendingDirection = null; this.#shiftAnchor = null; this.#vertical = null; this.#homeFocus = null; this.nabu.sealUndoEnd?.();
208
+ };
209
+ // Fires after every selection move, the user's and the editor's: the freshest "selection before the next change".
210
+ const onSelectionChange = () => { if (this.scope() === 'mine') this.nabu.captureUndoSelection?.(); };
211
+ document.addEventListener('selectionchange', onSelectionChange);
46
212
  document.addEventListener('keydown', onKeydown, true);
47
- return () => document.removeEventListener('keydown', onKeydown, true);
213
+ document.addEventListener('keyup', onKeyup, true);
214
+ document.addEventListener('mousedown', onMousedown, true);
215
+ return () => {
216
+ document.removeEventListener('keyup', onKeyup, true);
217
+ document.removeEventListener('keydown', onKeydown, true);
218
+ document.removeEventListener('selectionchange', onSelectionChange);
219
+ document.removeEventListener('mousedown', onMousedown, true);
220
+ };
48
221
  });
49
222
 
50
- // Normalize invalid caret/focus positions: inert elements and element-node
51
- // cursors (which happen in container padding / between block children).
52
- // Works for both collapsed cursors and non-collapsed selections (shift+arrow):
53
- // - anchor invalid → collapse to corrected anchor
54
- // - only focus invalid → keep anchor, correct only focus (preserves the selection)
223
+ // Normalize invalid caret/focus positions (see `normalize()`). The effect only re-runs it when the
224
+ // DOM selection changed; input entry points (keydown / beforeinput…) call `normalize()` themselves,
225
+ // synchronously, so a keystroke never acts on a not-yet-corrected caret.
55
226
  $effect(() => {
56
- const activeEl = document.activeElement;
57
- if (activeEl && activeEl.closest?.('[data-nabu-ui], input, textarea, select, button')) {
227
+ this.anchorNode; this.anchorOffset; this.focusNode; this.focusOffset;
228
+ untrack(() => {
229
+ this.normalize();
230
+ // The pending arrow direction only describes the move that just produced this selection.
58
231
  this.#pendingDirection = null;
59
- return;
60
- }
232
+ this.#shiftAnchor = null;
233
+ });
234
+ });
235
+ });
236
+ }
61
237
 
62
- const anchor = this.anchorNode;
63
- const anchorOffset = this.anchorOffset;
64
- const focus = this.focusNode;
65
- const focusOffset = this.focusOffset;
66
- if (!anchor) return;
238
+ /**
239
+ * Move a caret / focus that sits on a NON-TEXT position to the nearest valid text position, in the
240
+ * direction of travel (arrow keys; a heuristic otherwise): inert blocks (dividers, images…), element
241
+ * carets (container padding, between blocks, the editor root) and stray text nodes outside any text
242
+ * block (whitespace around a toggle's arrow…) are all "dead" positions where typing would be swallowed.
243
+ * Hidden content is never a target (it is not rendered). Works for collapsed carets and for ranges
244
+ * (shift+arrow): invalid anchor → collapse to the corrected anchor; only the focus invalid → keep the
245
+ * anchor, correct the focus.
246
+ *
247
+ * Synchronous and idempotent (reads the live DOM selection): call it right after `sync()`.
248
+ * When ArrowDown / ArrowRight leaves the document with no text position after the caret, the nabu
249
+ * "opens" a trailing caret (see `Nabu.openTrailingCaret`).
250
+ * @returns {boolean} True if the selection was moved
251
+ */
252
+ normalize() {
253
+ if (typeof window === 'undefined' || !window.getSelection) return false;
254
+ if (this.nabu.composing) return false; // IME composition: the browser owns the DOM and the caret
255
+ const live = window.getSelection();
256
+ if (!live || live.rangeCount === 0) return false;
257
+ // Not mine (in another editor, across roots, or in no editor): never rewritten. Whatever direction a key of MINE had
258
+ // announced is stale by now.
259
+ if (this.scope(live) !== 'mine') {
260
+ this.#pendingDirection = null;
261
+ return false;
262
+ }
67
263
 
68
- const anchorEl = /** @type {Element | null} */ (anchor.nodeType === Node.ELEMENT_NODE ? anchor : anchor.parentElement);
69
- const focusEl = /** @type {Element | null} */ (focus?.nodeType === Node.ELEMENT_NODE ? focus : focus?.parentElement);
264
+ const activeEl = document.activeElement;
265
+ if (activeEl && this.closestOwn(activeEl, '[data-nabu-ui], input, textarea, select, button')) {
266
+ this.#pendingDirection = null;
267
+ return false;
268
+ }
70
269
 
71
- // Skip normalization when the selection touches a UI element (e.g. zone title input).
72
- if (anchorEl?.closest('[data-nabu-ui]') || focusEl?.closest('[data-nabu-ui]')) {
73
- this.#pendingDirection = null;
74
- return;
75
- }
270
+ const anchor = live.anchorNode;
271
+ const anchorOffset = live.anchorOffset;
272
+ const focus = live.focusNode;
273
+ const focusOffset = live.focusOffset;
274
+ if (!anchor) return false;
76
275
 
77
- const anchorInvalid = isInInert(anchor) || (
78
- anchor.nodeType !== Node.TEXT_NODE &&
79
- !!/** @type {Element} */ (anchor).closest?.('[data-block-id]')
80
- );
81
- const focusInvalid = !!focus && (isInInert(focus) || (
82
- focus.nodeType !== Node.TEXT_NODE &&
83
- !!/** @type {Element} */ (focus).closest?.('[data-block-id]')
84
- ));
276
+ const anchorEl = /** @type {Element | null} */ (anchor.nodeType === Node.ELEMENT_NODE ? anchor : anchor.parentElement);
277
+ const focusEl = /** @type {Element | null} */ (focus?.nodeType === Node.ELEMENT_NODE ? focus : focus?.parentElement);
85
278
 
86
- if (!anchorInvalid && !focusInvalid) {
87
- this.#pendingDirection = null;
88
- return;
89
- }
279
+ // Skip normalization when the selection touches a UI element (e.g. a block's UI controls).
280
+ if (this.closestOwn(anchorEl, '[data-nabu-ui]') || this.closestOwn(focusEl, '[data-nabu-ui]')) {
281
+ this.#pendingDirection = null;
282
+ return false;
283
+ }
90
284
 
91
- if (anchorInvalid) {
92
- const dir = this.#pendingDirection ?? offsetHeuristic(anchor, anchorOffset);
93
- this.#pendingDirection = null;
94
- const target = findNearestTextNode(anchor, anchorOffset, dir);
95
- if (!target) return;
96
- const offset = dir === 'forward' ? 0 : (target.textContent?.length ?? 0);
97
- this.setBaseAndExtent(target, offset, target, offset);
98
- } else if (focusInvalid && focus) {
99
- const dir = this.#pendingDirection ?? offsetHeuristic(focus, focusOffset);
100
- this.#pendingDirection = null;
101
- const target = findNearestTextNode(focus, focusOffset, dir);
102
- if (!target) return;
103
- const offset = dir === 'forward' ? 0 : (target.textContent?.length ?? 0);
104
- this.setBaseAndExtent(anchor, anchorOffset, target, offset);
105
- }
106
- });
107
- });
285
+ // A caret the browser put right beside a render filler (`<br data-nabu-filler>`, the empty last line after a
286
+ // trailing "\n") is an element position: bring it back onto the end of the block's text, same model offset.
287
+ const anchorFix = this.#fillerEndpoint(anchor, anchorOffset);
288
+ const focusFix = focus ? this.#fillerEndpoint(focus, focusOffset) : null;
289
+ if (anchorFix || focusFix) {
290
+ const a = anchorFix ?? { node: anchor, offset: anchorOffset };
291
+ const f = focusFix ?? { node: /** @type {Node} */ (focus), offset: focusOffset };
292
+ this.setBaseAndExtent(a.node, a.offset, f.node, f.offset);
293
+ return true;
294
+ }
295
+
296
+ const anchorInvalid = this.#isDead(anchor);
297
+ const focusInvalid = !!focus && this.#isDead(focus);
298
+
299
+ if (!anchorInvalid && !focusInvalid) {
300
+ if (this.#canonicalHome(anchor, anchorOffset, focus, focusOffset)) return true;
301
+ if (this.#stepIntoEmpty(live, anchor, anchorOffset)) return true;
302
+ return this.#confine(live, anchor, anchorOffset, focus, focusOffset);
303
+ }
304
+
305
+ /** @type {NodeFilter} */
306
+ const filter = { acceptNode: (node) => this.#isValidTextNode(node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT };
307
+ const explicit = this.#pendingDirection;
308
+ this.#pendingDirection = null;
309
+ const shiftAnchor = this.#shiftAnchor;
310
+ this.#shiftAnchor = null;
311
+
312
+ // Shift+arrow that the browser answered by moving the ANCHOR onto a dead position (it re-expresses a text position as an
313
+ // element position, or loses it next to a non-editable sibling): the selection is still being extended from where it
314
+ // started, up to the focus (corrected to the nearest valid text in the direction of travel when it is dead too).
315
+ if (anchorInvalid && explicit && focus && shiftAnchor?.node.isConnected && !this.#isDead(shiftAnchor.node)) {
316
+ /** @type {{ node: Node, offset: number } | null} */
317
+ let end = { node: focus, offset: focusOffset };
318
+ if (focusInvalid) {
319
+ const target = findNearestTextNode(focus, focusOffset, explicit, filter, this.root);
320
+ const block = target && this.#blockOf(target);
321
+ end = block ? /** @type {any} */ (block).getDOMPoint?.(explicit === 'forward' ? 0 : (block.behaviors?.get('text')?.text.length ?? 0)) ?? null : null;
322
+ }
323
+ if (end) {
324
+ this.setBaseAndExtent(shiftAnchor.node, shiftAnchor.offset, end.node, end.offset);
325
+ return true;
326
+ }
327
+ }
328
+
329
+ if (anchorInvalid) {
330
+ const dir = explicit ?? offsetHeuristic(anchor, anchorOffset);
331
+ const target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
332
+ if (!target) {
333
+ // Leaving the document by keyboard with nothing to land on: the document must offer a caret there.
334
+ if (explicit === 'forward') this.nabu.openTrailingCaret();
335
+ return false;
336
+ }
337
+ const point = this.#landingPoint(target, dir);
338
+ this.setBaseAndExtent(point.node, point.offset, point.node, point.offset);
339
+ return true;
340
+ }
341
+ if (focusInvalid && focus) {
342
+ const dir = explicit ?? offsetHeuristic(focus, focusOffset);
343
+ const target = findNearestTextNode(focus, focusOffset, dir, filter, this.root);
344
+ if (!target) return false;
345
+ const point = this.#landingPoint(target, dir);
346
+ this.setBaseAndExtent(anchor, anchorOffset, point.node, point.offset);
347
+ return true;
348
+ }
349
+ return false;
350
+ }
351
+
352
+ /**
353
+ * The DOM point to land on in `target`, the text node found by a search in direction `dir`: its start (forward) or its end
354
+ * (backward). In a block whose MODEL text is empty, that is the start of the render placeholder (the lone "\n" text node):
355
+ * the last text node of such a block is Svelte's empty node AFTER the "\n", whose end is model offset 1 in a text of length
356
+ * 0 (P-108: Loro panics on an insert there).
357
+ * @param {Text} target @param {'forward' | 'backward'} dir @returns {{ node: Node, offset: number }}
358
+ */
359
+ #landingPoint(target, dir) {
360
+ const block = this.#blockOf(target);
361
+ const text = block?.behaviors?.get('text');
362
+ if (block && text && !text.text.length) {
363
+ const point = /** @type {any} */ (block).getDOMPoint?.(0);
364
+ if (point) return point;
365
+ }
366
+ return { node: target, offset: dir === 'forward' ? 0 : (target.textContent?.length ?? 0) };
367
+ }
368
+
369
+ /** Pending {@link repairAfterRemoval}. @type {ReturnType<typeof setTimeout> | null} */
370
+ #repairTimer = null;
371
+
372
+ /**
373
+ * Blocks were removed from the document (a programmatic change, a collaborator, an import, an undo): once the dust has
374
+ * settled, a DOM selection left on a DEAD position (the editor root or a container, where the removed block was) is brought
375
+ * onto the nearest text, so that the next click, key or paste starts from a real model position (P-108): the browser fires
376
+ * no `selectionchange` when a click re-selects the very position the selection already has. Deferred to a task of its own, so
377
+ * that whoever removed the block, and the editor's own handlers (which place their caret right after the render), win.
378
+ * Debounced: one check per burst. A selection that is not dead (or not in an editor) is left alone.
379
+ */
380
+ scheduleRepair() {
381
+ if (typeof window === 'undefined' || this.#repairTimer !== null) return;
382
+ this.#repairTimer = setTimeout(() => { this.#repairTimer = null; this.repairAfterRemoval(); }, 0);
383
+ }
384
+
385
+ /** @returns {boolean} Whether the selection was moved */
386
+ repairAfterRemoval() {
387
+ if (typeof window === 'undefined' || !window.getSelection || this.nabu.composing) return false;
388
+ const live = window.getSelection();
389
+ const node = live?.anchorNode;
390
+ if (!live || live.rangeCount === 0 || !node || !node.isConnected) return false;
391
+ if (this.scope(live) !== 'mine') return false; // the caret is in another editor, or in none: not mine to repair
392
+ const activeEl = document.activeElement;
393
+ if (activeEl && this.closestOwn(activeEl, '[data-nabu-ui], input, textarea, select, button')) return false;
394
+ // Only a selection that is dead for lack of a block under it: an inert block (an image…) selected on purpose stays.
395
+ const stray = (/** @type {Node | null} */ n) => !!n && !this.#inInert(n) && this.#isDead(n);
396
+ if (!stray(live.anchorNode) && !stray(live.focusNode)) return false;
397
+ this.sync();
398
+ /** @type {NodeFilter} */
399
+ const filter = { acceptNode: (n) => this.#isValidTextNode(n) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT };
400
+ /** @type {'forward' | 'backward'} */
401
+ let dir = 'backward';
402
+ let target = findNearestTextNode(node, live.anchorOffset, 'backward', filter, this.root);
403
+ if (!target) { dir = 'forward'; target = findNearestTextNode(node, live.anchorOffset, 'forward', filter, this.root); }
404
+ if (!target) return false;
405
+ const point = this.#landingPoint(target, dir);
406
+ this.setBaseAndExtent(point.node, point.offset, point.node, point.offset);
407
+ return true;
408
+ }
409
+
410
+ /**
411
+ * Shift+Home that left the focus at the END of another block (P-110). Chrome expresses "the start of the line" of a block's
412
+ * first line as the equivalent position at the end of the previous block's text, so a range extended with Shift+Home stopped
413
+ * one block short (the model focus was the end of the block above, a following Backspace left the last block unmerged).
414
+ * Home never leaves its block: that focus is the start of the block the key was pressed in. Anything else is left alone
415
+ * (the focus is still in the block, or not at the end of the block it landed in).
416
+ * @param {Node} anchor @param {number} anchorOffset @param {Node | null} focus @param {number} focusOffset
417
+ * @returns {boolean} Whether the selection was moved
418
+ */
419
+ #canonicalHome(anchor, anchorOffset, focus, focusOffset) {
420
+ const from = this.#homeFocus;
421
+ if (!from || !focus || Date.now() - from.at > KEY_WINDOW) return false;
422
+ if (focus === from.node && focusOffset === from.offset) return false; // the browser has not moved it (yet)
423
+ this.#homeFocus = null; // one move per key
424
+ const landed = this.#blockOf(focus);
425
+ if (!landed || landed === from.block || !from.block.element?.isConnected) return false;
426
+ const text = landed.behaviors?.get('text');
427
+ if (!text || !landed.element || text.calculateOffset(focus, focusOffset, landed.element) < text.text.length) return false;
428
+ const point = /** @type {any} */ (from.block).getDOMPoint?.(0);
429
+ if (!point) return false;
430
+ this.setBaseAndExtent(anchor, anchorOffset, point.node, point.offset);
431
+ return true;
432
+ }
433
+
434
+ /**
435
+ * ArrowUp / ArrowDown that stepped OVER an empty text block (P-87). An empty block renders a lone "\n" (one line, no filler:
436
+ * a trailing break is not a line of its own), which the browser does not take for a line to stop on when it moves the caret
437
+ * vertically: it goes straight to the next line of text. Every block is a caret stop, so the caret is put in the empty block
438
+ * the key walked past (the previous / next text block of the one the key was pressed in), at its only position. A caret that
439
+ * did not move at all is the same case at the edge of the document (nothing above / below the empty block to go to).
440
+ * @param {Selection} live @param {Node} anchor @param {number} anchorOffset
441
+ * @returns {boolean} Whether the selection was moved
442
+ */
443
+ #stepIntoEmpty(live, anchor, anchorOffset) {
444
+ const from = this.#vertical;
445
+ if (!from || !live.isCollapsed || Date.now() - from.at > KEY_WINDOW) return false;
446
+ const moved = anchor !== from.node || anchorOffset !== from.offset;
447
+ if (!moved && !this.#keyReleased) return false; // the browser has not moved it (yet)
448
+ this.#vertical = null; // one move per key
449
+ const landed = this.#blockOf(anchor);
450
+ if (!landed) return false;
451
+ const up = from.key === 'ArrowUp';
452
+ const hasText = (/** @type {Block} */ b) => !!b.behaviors?.has('text');
453
+ const next = up ? from.block.findBackward(hasText) : from.block.findForward(hasText);
454
+ const text = next?.behaviors?.get('text');
455
+ if (!next || !text || text.text.length || next === landed || !next.element?.isConnected || !landed.element) return false;
456
+ if (landed === from.block) {
457
+ // Still in its own block: it moved inside it (a multi-line block) — or, once the key is released, did not move at all.
458
+ if (moved) return false;
459
+ } else {
460
+ const order = next.element.compareDocumentPosition(landed.element);
461
+ if (!(order & (up ? Node.DOCUMENT_POSITION_PRECEDING : Node.DOCUMENT_POSITION_FOLLOWING))) return false; // not past it
462
+ }
463
+ this.setCursor(next, 0);
464
+ return true;
465
+ }
466
+
467
+ /** The caret an unmodified ArrowUp / ArrowDown was pressed from (see the keydown listener). @type {{ key: string, block: Block, node: Node, offset: number, at: number } | null} */
468
+ #vertical = null;
469
+
470
+ /** Inside the keyup handler (see `#stepIntoEmpty`). */
471
+ #keyReleased = false;
472
+
473
+ /** The focus Shift+Home was pressed from (see the keydown listener). @type {{ block: Block, node: Node, offset: number, at: number } | null} */
474
+ #homeFocus = null;
475
+
476
+ /** The block whose element holds `node` (null outside any block). @param {Node | null} node @returns {Block | null} */
477
+ #blockOf(node) {
478
+ const el = /** @type {Element | null} */ (node && (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement));
479
+ const id = el?.closest('[data-block-id]')?.getAttribute('data-block-id');
480
+ return (id && this.nabu.blocks.get(id)) || null;
481
+ }
482
+
483
+ /**
484
+ * The rules of ISOLATED text fields (`Block#isolatesSelection`, ADR 018 §3.9) on a live, non-collapsed selection whose ends
485
+ * are in two different blocks:
486
+ * - the ANCHOR is in an isolated block: the selection stays BOUNDED to it, the focus is brought back to the end of that
487
+ * block (the focus is after the anchor) or to its start (before);
488
+ * - the FOCUS is in an isolated block and the anchor is outside: the focus is moved PAST it, in the direction of travel,
489
+ * onto the nearest text of a block that is not isolated (nothing there: the selection is given up, collapsed on its anchor).
490
+ * Idempotent. Returns whether the selection was moved.
491
+ * @param {Selection} live @param {Node} anchor @param {number} anchorOffset @param {Node | null} focus @param {number} focusOffset
492
+ * @returns {boolean}
493
+ */
494
+ #confine(live, anchor, anchorOffset, focus, focusOffset) {
495
+ if (!focus || live.isCollapsed) return false;
496
+ const anchorBlock = this.#blockOf(anchor);
497
+ const focusBlock = this.#blockOf(focus);
498
+ if (!anchorBlock || !focusBlock || anchorBlock === focusBlock) return false;
499
+ if (!anchorBlock.isolatesSelection && !focusBlock.isolatesSelection) return false;
500
+
501
+ // Direction of travel: is the focus after the anchor?
502
+ const probe = document.createRange();
503
+ probe.setStart(anchor, anchorOffset);
504
+ probe.collapse(true);
505
+ let forward;
506
+ try { forward = probe.comparePoint(focus, focusOffset) > 0; } catch { return false; }
507
+
508
+ /** @param {Block} block @param {boolean} end @returns {{ node: Node, offset: number } | null} */
509
+ const edgeOf = (block, end) => {
510
+ const text = block.behaviors?.get('text');
511
+ return /** @type {any} */ (block).getDOMPoint?.(end ? (text?.text.length ?? 0) : 0) ?? null;
512
+ };
513
+
514
+ if (anchorBlock.isolatesSelection) {
515
+ const edge = edgeOf(anchorBlock, forward);
516
+ if (!edge) return false;
517
+ this.setBaseAndExtent(anchor, anchorOffset, edge.node, edge.offset);
518
+ return true;
519
+ }
520
+
521
+ // The focus is in an isolated block: the nearest text outside any isolated block, past it.
522
+ /** @type {NodeFilter} */
523
+ const filter = { acceptNode: (node) => this.#isValidTextNode(node) && !this.#blockOf(node)?.isolatesSelection ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT };
524
+ // @ts-ignore — TreeWalker filter shape is correct, TS typedef is overly strict
525
+ const walker = document.createTreeWalker(this.root ?? document.body, NodeFilter.SHOW_TEXT, filter);
526
+ const host = focusBlock.element ?? focus;
527
+ walker.currentNode = forward ? getLastDescendant(host) : host;
528
+ const target = forward ? walker.nextNode() : walker.previousNode();
529
+ const targetBlock = target && this.#blockOf(target);
530
+ const point = targetBlock && edgeOf(targetBlock, !forward);
531
+ if (!point) this.setBaseAndExtent(anchor, anchorOffset, anchor, anchorOffset);
532
+ else this.setBaseAndExtent(anchor, anchorOffset, point.node, point.offset);
533
+ return true;
534
+ }
535
+
536
+ /**
537
+ * Selects exactly the text of `block` (Select All inside an isolated field).
538
+ * @param {Block} block
539
+ * @returns {boolean} False when the block has no DOM point to select
540
+ * @public
541
+ */
542
+ selectBlockText(block) {
543
+ const text = block.behaviors?.get('text');
544
+ const from = /** @type {any} */ (block).getDOMPoint?.(0);
545
+ const to = /** @type {any} */ (block).getDOMPoint?.(text?.text.length ?? 0);
546
+ if (!from || !to) return false;
547
+ this.setBaseAndExtent(from.node, from.offset, to.node, to.offset);
548
+ return true;
549
+ }
550
+
551
+ /**
552
+ * Selects the text of the document between two blocks (first block start -> last block end).
553
+ * @param {Block} first @param {Block} last
554
+ * @returns {boolean}
555
+ * @public
556
+ */
557
+ selectBetween(first, last) {
558
+ const lastText = last.behaviors?.get('text');
559
+ const from = /** @type {any} */ (first).getDOMPoint?.(0);
560
+ const to = /** @type {any} */ (last).getDOMPoint?.(lastText?.text.length ?? 0);
561
+ if (!from || !to) return false;
562
+ this.setBaseAndExtent(from.node, from.offset, to.node, to.offset);
563
+ return true;
564
+ }
565
+
566
+ /**
567
+ * If `(node, offset)` is an element position adjacent to a block's trailing render filler, the equivalent text
568
+ * position (end of the block's text); else null.
569
+ * @param {Node} node
570
+ * @param {number} offset
571
+ * @returns {{ node: Node, offset: number } | null}
572
+ */
573
+ #fillerEndpoint(node, offset) {
574
+ if (node.nodeType !== Node.ELEMENT_NODE) return null;
575
+ const kids = node.childNodes;
576
+ const isFiller = (/** @type {Node | undefined} */ n) => n instanceof Element && n.hasAttribute('data-nabu-filler');
577
+ if (!isFiller(kids[offset]) && !isFiller(kids[offset - 1])) return null;
578
+ const id = /** @type {Element} */ (node).closest('[data-block-id]')?.getAttribute('data-block-id');
579
+ const block = id ? this.nabu.blocks.get(id) : null;
580
+ const text = block?.behaviors?.get('text');
581
+ if (!block || !text || !block.element?.contains(node)) return null;
582
+ const point = /** @type {any} */ (block).getDOMPoint?.(text.text.length);
583
+ // Only a real text point is an improvement (an element fallback would be dead again).
584
+ return point && point.node.nodeType === Node.TEXT_NODE ? point : null;
585
+ }
586
+
587
+ /**
588
+ * A selection endpoint where nothing can be typed: inside an inert block, an element caret anywhere
589
+ * in MY editor, or a text node that is not part of a text block's own text. Endpoints outside my own
590
+ * root (no editor, another editor, a nested editor) are none of my business.
591
+ * @param {Node} node
592
+ */
593
+ #isDead(node) {
594
+ // Only MY root counts: a caret in another editor (or in no editor) is not dead for me, it is not mine at all.
595
+ if (!this.owns(node)) return false;
596
+ if (this.#inInert(node)) return true;
597
+ if (node.nodeType !== Node.TEXT_NODE) return true;
598
+ return !this.#isValidTextNode(node);
599
+ }
600
+
601
+ /** Inside an inert block of MY content (an inert ancestor above my root, when I am nested, does not count). @param {Node} node */
602
+ #inInert(node) { return !!this.closestOwn(node, '[data-nabu-inert]'); }
603
+
604
+ /**
605
+ * True for a text node that belongs to the text of a text block (not inert, not whitespace
606
+ * between a container's children / around its UI).
607
+ * @param {Node} node
608
+ */
609
+ #isValidTextNode(node) {
610
+ if (!this.owns(node)) return false; // a text node of another editor is never a place for MY caret to land
611
+ if (this.#inInert(node)) return false;
612
+ const id = node.parentElement?.closest('[data-block-id]')?.getAttribute('data-block-id');
613
+ const block = id ? this.nabu.blocks.get(id) : null;
614
+ if (!block || !block.behaviors?.has('text')) return false;
615
+ return !block.element || block.element.contains(node);
108
616
  }
109
617
 
110
618
  /** @type {'forward' | 'backward' | null} */
111
619
  #pendingDirection = null;
112
620
 
621
+ /** The anchor a Shift+arrow started from (see the keydown listener). @type {{ node: Node, offset: number } | null} */
622
+ #shiftAnchor = null;
623
+
624
+ /**
625
+ * Caret at the keydown of an unmodified ArrowRight / ArrowDown, to tell at keyup whether the key moved it.
626
+ * @type {{ key: string, node: Node, offset: number } | null}
627
+ */
628
+ #arrowStart = null;
629
+
630
+ /**
631
+ * ArrowRight / ArrowDown that could not move the caret (browsers do not step onto a non-editable block such
632
+ * as an image), pressed in the last text block of a document that ends with a non-text block: the document
633
+ * must offer a caret after it.
634
+ * @param {{ node: Node, offset: number }} start
635
+ */
636
+ #openTrailingIfStuck(start) {
637
+ const live = window.getSelection();
638
+ if (!live?.isCollapsed || live.anchorNode !== start.node || live.anchorOffset !== start.offset) return;
639
+ if (this.scope(live) !== 'mine') return;
640
+ const block = this.anchorBlock;
641
+ if (!block?.behaviors?.has('text') || block.findForward((b) => !!b.behaviors?.has('text'))) return;
642
+ const last = this.nabu.lastVisibleBlock;
643
+ if (!last || last.behaviors?.has('text')) return;
644
+ this.nabu.openTrailingCaret();
645
+ }
646
+
647
+ /** @public */
113
648
  anchorBlock = $derived.by(() => {
114
649
  this.anchorNode;
115
650
  const id = this.anchorNode?.parentElement?.closest("[data-block-id]")?.getAttribute("data-block-id");
116
651
  return id ? this.nabu.blocks.get(id) : null;
117
652
  });
118
653
 
654
+ /** @public */
119
655
  focusBlock = $derived.by(() => {
120
656
  this.focusNode;
121
657
  const id = this.focusNode?.parentElement?.closest("[data-block-id]")?.getAttribute("data-block-id");
122
658
  return id ? this.nabu.blocks.get(id) : null;
123
659
  });
124
660
 
661
+ /** @public */
125
662
  startBlock = $derived.by(() => {
126
663
  this.range;
127
664
  const id = this.range?.startContainer?.parentElement?.closest("[data-block-id]")?.getAttribute("data-block-id");
128
665
  return id ? this.nabu.blocks.get(id) : null;
129
666
  });
130
667
 
668
+ /** @public */
131
669
  endBlock = $derived.by(() => {
132
670
  this.range;
133
671
  const id = this.range?.endContainer?.parentElement?.closest("[data-block-id]")?.getAttribute("data-block-id");
134
672
  return id ? this.nabu.blocks.get(id) : null;
135
673
  });
136
674
 
675
+ /** @public */
137
676
  start = $derived(this.startBlock?.selection && {
138
677
  block: this.startBlock,
139
678
  ...this.startBlock.selection
140
679
  });
141
680
 
681
+ /** @public */
142
682
  end = $derived(this.endBlock?.selection && {
143
683
  block: this.endBlock,
144
684
  ...this.endBlock.selection
@@ -148,6 +688,7 @@ export class NabuSelection extends SvelteSelection {
148
688
  * Définit le curseur à un endroit précis du document (Modèle -> DOM)
149
689
  * @param {Block} block
150
690
  * @param {number} offset
691
+ * @public
151
692
  */
152
693
  setCursor(block, offset) {
153
694
  if (!block.element) return;
@@ -163,22 +704,46 @@ export class NabuSelection extends SvelteSelection {
163
704
 
164
705
  /** @type {Set<Block>} */
165
706
  previous = new Set();
166
- blocks = $derived(new Set(getNodesBetween(this.nabu.tree, this.startBlock?.node.id.toString() || "", this.endBlock?.node.id.toString() || "").map(node => {
167
- return this.nabu.blocks.get(node.id.toString());
168
- }).filter(b => !!b)));
707
+ /**
708
+ * The blocks the selection covers (flagged `selected`: highlighted, marked, …). A selection that does not lie entirely in
709
+ * one block leaves out the blocks that isolate their text (`Block#isolatesSelection`): a title is not part of a range.
710
+ * Nor does it hold the HIDDEN content of a block that hides its children (the body of a collapsed toggle, `hidesChildren`):
711
+ * a mark or a highlight never reaches text nobody sees (P-112). Deleting a range still removes such a body with its owner:
712
+ * the deletion walks the tree itself (`container.utils.js`), it does not read this set.
713
+ * @type {Set<Block>}
714
+ * @public
715
+ */
716
+ blocks = $derived.by(() => {
717
+ const range = this.startBlock !== this.endBlock;
718
+ return new Set(/** @type {Block[]} */ (getNodesBetween(this.nabu.tree, this.startBlock?.node.id.toString() || "", this.endBlock?.node.id.toString() || "").map(node => {
719
+ return this.nabu.blocks.get(node.id.toString());
720
+ }).filter(b => !!b && !(range && b.isolatesSelection) && !(range && this.#isHidden(b)))));
721
+ });
722
+
723
+ /** True when an ancestor of `block` hides its children (the block is not rendered). @param {Block} block */
724
+ #isHidden(block) {
725
+ for (let n = block.node.parent(); n; n = n.parent()) {
726
+ if (this.nabu.blocks.get(n.id.toString())?.hidesChildren) return true;
727
+ }
728
+ return false;
729
+ }
730
+
731
+ /**
732
+ * True while the selection is a non-collapsed range across several blocks. The editor mirrors it as `data-nabu-range` on its
733
+ * root, which the stylesheet uses to not highlight isolated blocks (the model leaves them out of the range, see `blocks`).
734
+ * @public
735
+ */
736
+ isRange = $derived(!this.isCollapsed && !!this.startBlock && !!this.endBlock && this.startBlock !== this.endBlock);
169
737
 
170
738
  }
171
739
 
172
740
 
173
741
 
174
- /** @param {Node | null} node */
175
- function isInInert(node) {
176
- if (!node) return false;
177
- const el = node.nodeType === Node.ELEMENT_NODE
178
- ? /** @type {Element} */ (node)
179
- : node.parentElement;
180
- return !!el?.closest('[data-nabu-inert]');
181
- }
742
+ /**
743
+ * How long (ms) after a Shift+Home / ArrowUp / ArrowDown keydown the caret the browser lands on may still be put right (`#canonicalHome`,
744
+ * `#stepIntoEmpty`): the move is applied after the keydown, and reported by `selectionchange` later still. The first move consumes it.
745
+ */
746
+ const KEY_WINDOW = 600;
182
747
 
183
748
  /**
184
749
  * Heuristic for mouse clicks: infer direction from where in the element the
@@ -195,15 +760,6 @@ function offsetHeuristic(anchor, anchorOffset) {
195
760
  return 'backward';
196
761
  }
197
762
 
198
- /** @type {NodeFilter} */
199
- const TEXT_FILTER = {
200
- acceptNode(/** @type {Node} */ node) {
201
- if (isInInert(node)) return NodeFilter.FILTER_REJECT;
202
- if (!/** @type {Text} */ (node).parentElement?.closest('[data-block-id]')) return NodeFilter.FILTER_REJECT;
203
- return NodeFilter.FILTER_ACCEPT;
204
- }
205
- };
206
-
207
763
  /**
208
764
  * Returns the deepest last descendant of a node (for positioning a TreeWalker
209
765
  * so that nextNode() starts at the node immediately after the subtree).
@@ -227,11 +783,13 @@ function getLastDescendant(node) {
227
783
  * @param {Node} fromNode
228
784
  * @param {number} fromOffset
229
785
  * @param {'forward' | 'backward'} direction
786
+ * @param {NodeFilter} filter Accepts the valid text nodes
787
+ * @param {Node | null} [within] The root of the search: the editor's own root (default: the page)
230
788
  * @returns {Text | null}
231
789
  */
232
- function findNearestTextNode(fromNode, fromOffset, direction) {
790
+ function findNearestTextNode(fromNode, fromOffset, direction, filter, within = null) {
233
791
  // @ts-ignore — TreeWalker filter shape is correct, TS typedef is overly strict
234
- const bodyWalker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT, TEXT_FILTER);
792
+ const bodyWalker = document.createTreeWalker(within ?? document.body, NodeFilter.SHOW_TEXT, filter);
235
793
 
236
794
  if (fromNode.nodeType === Node.TEXT_NODE) {
237
795
  bodyWalker.currentNode = fromNode;
@@ -257,7 +815,7 @@ function findNearestTextNode(fromNode, fromOffset, direction) {
257
815
  }
258
816
  // Past last child → last valid text inside the element (sub-walker), or before it
259
817
  // @ts-ignore
260
- const sub = document.createTreeWalker(fromNode, NodeFilter.SHOW_TEXT, TEXT_FILTER);
818
+ const sub = document.createTreeWalker(fromNode, NodeFilter.SHOW_TEXT, filter);
261
819
  let last = null, n;
262
820
  while ((n = sub.nextNode())) last = n;
263
821
  if (last) return /** @type {Text} */ (last);