@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
@@ -1,29 +1,84 @@
1
1
  import { LoroDoc, UndoManager } from 'loro-crdt';
2
2
  import { SvelteMap, SvelteSet } from 'svelte/reactivity';
3
3
  import { Block } from './block.svelte.js';
4
+ import { MegaBlock } from './megablock.svelte.js';
4
5
  import { NabuSelection } from './selection.svelte.js';
5
- import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, findDirectChildOf, findLCA } from './container.utils.js';
6
- import { jsonToPasteBlocks } from '../utils/extensions.js';
7
- import { tick } from 'svelte';
6
+ import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, deleteRange, selectionRange, findDirectChildOf, findLCA, textBlocksInOrder } from './container.utils.js';
7
+ import { jsonToPasteBlocks, degradeUnknownBlocks, CLIPBOARD_FORMAT_VERSION, JSON_FORMAT_VERSION, isSupportedJsonVersion } from '../utils/extensions.js';
8
+ import { escapeHtml, sanitizePasteBlocks } from '../utils/html.js';
9
+ import { tick, flushSync } from 'svelte';
10
+ import { Files } from '../files/files.svelte.js';
8
11
  import { Pulse } from '@aionbuilders/pulse';
12
+ import { CommandRegistry } from '../utils/commands.js';
13
+ import { CommandConfirmation } from '../utils/command-confirm.svelte.js';
14
+ import { normalizePlaceholders } from '../utils/placeholders.js';
15
+ import { normalizeLang } from '../utils/spellcheck.js';
16
+ import { resolveTabMode, handleTabKey, isModifierKey, DEFAULT_TAB_HINT } from '../utils/tab.js';
17
+ import { moveBlocks } from './move.js';
18
+ import { closestWithin } from '../utils/dom-scope.js';
19
+ import { captureSelection, explicitSelection, legacySelection, restoreSelection, keepSelection, makeEndpoint, resolveOffset, revealFocus } from './undo-selection.js';
20
+ import { LARGE_DOC } from './chunks.js';
21
+ import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
9
22
 
10
23
 
11
24
  /**
12
25
  * @import {Component} from "svelte";
13
26
  * @import { LoroTreeNode, LoroTree } from "loro-crdt";
14
27
  * @import {Extension} from '../utils/extensions.js';
28
+ * @import {DropPosition, DropTarget, DropKind} from '../utils/drop.js';
15
29
  */
16
30
 
17
31
  /**
18
- * @template {Object<string, any>} [T={}]
32
+ * The data map of a block's tree node: a `type` plus the block's own (open-ended) properties. Block classes narrow it
33
+ * with their own node typedef (`NabuNode<{text: LoroText}>`).
34
+ * @typedef {{type: string} & Record<string, any>} NabuNodeData
35
+ */
36
+
37
+ /**
38
+ * @template {Object<string, any>} [T=Record<string, any>]
19
39
  * @typedef {LoroTreeNode<{type: string} & T>} NabuNode
20
40
  */
21
41
 
22
42
  /**
23
43
  * @typedef {Object} NabuInit
44
+ * The options of an editor: the extensions to load, an initial snapshot, files, placeholders, readonly, language, Tab behaviour, keymap and
45
+ * command confirmation. Accepted by `new Nabu(init)`, by `createEditor` and the preset factories, and by `createPersistedEditor`.
24
46
  * @property {Extension[]} [extensions]
25
47
  * @property {Uint8Array<ArrayBufferLike>} [snapshot]
26
48
  * @property {import('../files/files.svelte.js').FilesConfig} [files]
49
+ * @property {import('../utils/placeholders.js').PlaceholdersOption} [placeholders] - Hint text of empty blocks.
50
+ * `false`: none. `true` / omitted: defaults (shown on the empty block holding the cursor).
51
+ * Object: `{ show?: 'focus' | 'empty', text?: Record<blockType, string | false | ((block) => string | false)> }`.
52
+ * @property {boolean} [spellcheck] - Browser spellcheck on the editor (default `true`). `false` turns it off and adds the opt-out
53
+ * hints of the Grammarly extension (`data-gramm="false"`, ...). Code blocks are never spellchecked. Reactive: `nabu.spellcheck`.
54
+ * @property {boolean} [readonly] - Show the document without letting the user change it (default `false`). Reactive: `nabu.readonly`,
55
+ * assign to toggle live (`<NabuEditor readonly>` sets it). The editor root becomes `contenteditable="false"`; the engine ignores
56
+ * typing, paste, cut, drop, drag moves and every command / shortcut (undo and redo included). Copy, text selection and links
57
+ * keep working, and the floating UI (toolbar, slash menu, drag handle) hides itself. Code of the host is NOT restricted:
58
+ * `insert`, `importJSON`, `importMarkdown`, `importRemote`, `transact` still work, which is how a viewer loads its document.
59
+ * @property {string} [lang] - Language of the content, a BCP 47 tag (`'fr'`, `'en-GB'`). Set on the root as `lang`, so the browser's
60
+ * spellchecker, hyphenation and screen readers use it. Unset: inherits the page language. An invalid tag is ignored (warning).
61
+ * Reactive: `nabu.lang`.
62
+ * @property {'focus' | 'stay' | 'indent'} [tab] - What Tab / Shift+Tab do in a plain text block, where no block handles them
63
+ * structurally (list indent, code indentation and region titles keep their own meaning, whatever this says; P-41).
64
+ * `'focus'`: the browser default, Tab leaves the editor. `'stay'`: both keys are swallowed and the caret stays; Escape then Tab
65
+ * leaves (announced to screen readers, see `tabHint`). `'indent'`: Tab inserts a tab character at the caret (replacing a selection
66
+ * inside one block), Shift+Tab removes one right before it; several blocks selected: like `'stay'`. `'nest'` is planned, not
67
+ * implemented. Default: `tabDefault` (the factories of `presets.js` set it from the preset: Minimal / Text `'focus'`, Document /
68
+ * Full `'stay'`), else `'focus'`. An unknown value warns and uses the default. Reactive: `nabu.tab`.
69
+ * @property {'focus' | 'stay' | 'indent'} [tabDefault] - The mode used when `tab` is unset or invalid. Meant for the preset factories.
70
+ * @property {string | false} [tabHint] - Text announced on the editor root (`aria-description`) while `tab` traps the focus
71
+ * (`'stay'`, `'indent'`): default `"Press Escape then Tab to leave the editor"`; translate it here, `false` for none.
72
+ * Reactive: `nabu.tabHint`.
73
+ * @property {Record<string, string[]>} [keymap] - Replaces the keyboard shortcuts of commands (ADR 017): `{ 'mark:bold': ['Mod-Alt-b'] }`;
74
+ * `[]` disables a command's keys. Chords: see `utils/keys.js`; the same checks as for a declared key apply (reserved chords,
75
+ * a key without modifier needs the command's `when`).
76
+ * @property {import('../utils/command-confirm.svelte.js').CommandConfirmOptions} [commandConfirm] - Confirmation of commands asked by a
77
+ * key press (ADR 017 lot 2): `{ holdMs?: number (700), inviteMs?: number (5000), messages?: ConfirmMessages }`. `messages` are the
78
+ * texts of the prompts and outcomes announced to screen readers (English by default; each is a string or a function of the
79
+ * parameters, see `ConfirmMessages`); a command can override them with `confirm.messages`.
80
+ * @property {'mac' | 'other'} [platform] - Which platform's conventions `Mod` and the displayed shortcuts follow. Detected from the
81
+ * browser by default; set it for tests or server-side rendering.
27
82
  */
28
83
 
29
84
  /**
@@ -45,11 +100,76 @@ function inheritedMarkAt(behavior, pos, name) {
45
100
  return false;
46
101
  }
47
102
 
103
+ /**
104
+ * True for the input types that can trigger a block transform (typing / Enter), as opposed to
105
+ * deletions.
106
+ * @param {Event | { inputType?: string }} e
107
+ */
108
+ export const isTransformInput = (e) => {
109
+ const type = /** @type {any} */ (e).inputType;
110
+ return type === 'insertText' || type === 'insertParagraph' || type === 'insertLineBreak' || type === 'insertSoftLineBreak';
111
+ };
112
+
113
+ /**
114
+ * @typedef {Object} NabuInternals
115
+ * The engine machinery behind {@link Nabu#internals}. **Unstable**: may change in any version (see `docs/guides/extensions.md`,
116
+ * "Stability"). Methods are bound to the editor; their signatures are those of the `Nabu` methods of the same name.
117
+ * @property {Pulse} pulse The action bus behind `exec()`: `pulse.on(topic, handler)` observes or adds a topic at runtime.
118
+ * @property {CommandConfirmation} commandConfirm The confirmation controller of commands (hold / invite / choose): `start`, `stop`, `offer`, `choose`, `cancel`, `pending`.
119
+ * @property {Map<string, Array<(nabu: Nabu, ...args: any[]) => any>>} hooks Extension hooks by name, in registration order (the normalizers of `onBeforeTransaction`, the `onBeforeInput` handlers...).
120
+ * @property {WeakMap<Function, string>} hookOwners Hook function to the name of the extension that registered it.
121
+ * @property {import('../utils/extensions.js').InputRule[]} inputRules The input rules collected from the extensions.
122
+ * @property {import('../utils/extensions.js').PasteInterpreter[]} pasteInterpreters The paste interpreters collected from the extensions.
123
+ * @property {import('../utils/extensions.js').PasteFileHandler[]} pasteFileHandlers The paste file handlers, by priority.
124
+ * @property {UndoManager} undoManager The Loro undo manager (undo steps, merge window).
125
+ * @property {import('loro-crdt').LoroMap} content The free-form `content` map of the document.
126
+ * @property {import('../files/files.svelte.js').FilesConfig} fileConfig The resolved `files` option.
127
+ * @property {Record<string, boolean> | null} storedMarks Pending inline marks for the next typed character (reactive; assignable).
128
+ * @property {Nabu['toggleStoredMark']} toggleStoredMark
129
+ * @property {Nabu['clearStoredMarks']} clearStoredMarks
130
+ * @property {Nabu['noteTextChange']} noteTextChange
131
+ * @property {Nabu['captureUndoSelection']} captureUndoSelection Remember the selection for the undo step now being recorded.
132
+ * @property {Nabu['sealUndoEnd']} sealUndoEnd Close the "where did the last action end" mark of the undo history.
133
+ * @property {Nabu['updateRoots']} updateRoots Re-read the root blocks from the tree.
134
+ * @property {Nabu['deleteNode']} deleteNode Delete a block by node id (no commit).
135
+ * @property {Nabu['rearmTab']} rearmTab
136
+ * @property {string | undefined} tabDescription The `aria-description` the root carries while `tab` traps the focus.
137
+ * @property {Nabu['dispatchEventToSelection']} dispatchEventToSelection Route a native event to the block that holds the selection.
138
+ * @property {Nabu['handleKeydown']} handleKeydown The keydown pipeline (commands first, then hooks, then the block).
139
+ * @property {Nabu['handleBeforeinput']} handleBeforeinput
140
+ * @property {Nabu['beforeinput']} beforeinput
141
+ * @property {Nabu['handleCompositionStart']} handleCompositionStart
142
+ * @property {Nabu['handleCompositionUpdate']} handleCompositionUpdate
143
+ * @property {Nabu['handleCompositionEnd']} handleCompositionEnd
144
+ * @property {Nabu['handleMousedown']} handleMousedown
145
+ * @property {Nabu['handleCopy']} handleCopy Write the selection to a clipboard (every format).
146
+ * @property {Nabu['handleCut']} handleCut
147
+ * @property {Nabu['handlePaste']} handlePaste The paste pipeline (interpreters, files, `acceptPaste`).
148
+ * @property {Nabu['insertFragment']} insertFragment Insert a `PasteFragment` at the selection (what a paste does after interpreting).
149
+ * @property {Nabu['handleDragStart']} handleDragStart
150
+ * @property {Nabu['handleDragOver']} handleDragOver
151
+ * @property {Nabu['handleDragLeave']} handleDragLeave
152
+ * @property {Nabu['handleDragEnd']} handleDragEnd
153
+ * @property {Nabu['handleDrop']} handleDrop
154
+ * @property {Nabu['dropAt']} dropAt Drop a `DataTransfer` at a position, as the drag and drop does.
155
+ * @property {DropTarget | null} dropTarget The drop indicator being shown (reactive).
156
+ * @property {{ normalize: NabuSelection['normalize'], scheduleRepair: NabuSelection['scheduleRepair'], repairAfterRemoval: NabuSelection['repairAfterRemoval'], placements: number, attachRoot: NabuSelection['attachRoot'], owns: NabuSelection['owns'], scope: NabuSelection['scope'], root: HTMLElement | null }} selection The selection's own repair machinery, and the engine's root element: `attachRoot(el)` (what `Nabu.svelte` calls on mount, it returns the detach function), `root`, `owns(node)` (inside MY root, not in a nested editor) and `scope()` ('mine' | 'outside' | 'foreign': whose business the live DOM selection is).
157
+ */
158
+
159
+ /**
160
+ * The editor engine. It owns the document (a Loro CRDT), the block tree and its registry, the selection, the commands and the
161
+ * extensions, and runs the event, clipboard and drag and drop pipelines; `NabuEditor` renders it. Create one with `createEditor`
162
+ * (or a preset factory such as `createDocumentEditor`) rather than `new Nabu(...)`, then read and write the content through
163
+ * `serialize`, `importMarkdown`, `importJSON`, `exec` and `transact`. The members documented as public are the stable contract of
164
+ * `@aionbuilders/nabu/extend`; `internals` is the unstable door to the rest.
165
+ */
48
166
  export class Nabu {
49
167
  /** @type {Pulse} */
50
168
  #pulse = new Pulse();
51
169
  /** @type {import('../utils/extensions.js').PasteInterpreter[]} */
52
170
  #pasteInterpreters = [];
171
+ /** @type {import('../utils/extensions.js').PasteFileHandler[]} sorted by priority, highest first */
172
+ #pasteFileHandlers = [];
53
173
 
54
174
  // ── IME composition state ────────────────────────────────────────────────
55
175
  // During an active IME composition the browser mutates the DOM freely
@@ -57,10 +177,63 @@ export class Nabu {
57
177
  // for the duration of the composition and sync the result into Loro at
58
178
  // compositionend. See issue #6.
59
179
  #composing = false;
60
- /** @type {number | null} offset modèle au début de la composition */
180
+ /**
181
+ * True during an IME composition: the browser owns the DOM, the caret must not be touched.
182
+ * @public
183
+ */
184
+ get composing() { return this.#composing; }
185
+ /** @type {number | null} offset modèle au début de la composition (repli si le curseur Loro ne se résout pas) */
61
186
  #compositionStartOffset = null;
187
+ /**
188
+ * Where the composed text goes, as Loro cursors (P-101): an edit of the SAME block before the caret during the composition
189
+ * (a programmatic insert, a direct `importRemote`) shifts it, a plain offset would not.
190
+ * @type {import('./undo-selection.js').Endpoint | null}
191
+ */
192
+ #compositionAnchor = null;
193
+ /** The block a composition runs in, reactive: its placeholder is hidden meanwhile (P-103). @type {Block | null} */
194
+ #composingBlock = $state.raw(null);
195
+ /**
196
+ * The block holding the running composition, or null. Reactive.
197
+ * @public
198
+ */
199
+ get composingBlock() { return this.#composingBlock; }
200
+ /** An undo group is open: the deletion of a selection replaced by a composition and the composed text are ONE undo step. */
201
+ #compositionGroup = false;
62
202
  /** @type {Block | null} bloc cible au début de la composition */
63
203
  #compositionStartBlock = null;
204
+ /** Configured UndoManager merge window (ms), restored after a paste isolation. */
205
+ #mergeInterval = 1000;
206
+ /** Undo steps still to push with merging disabled (paste / structural op / cut + the next one); 0 = not isolating. */
207
+ #isolatedSteps = 0;
208
+ #isolating = false;
209
+ /** True during the synchronous turn that started a structural undo step (see commit()). */
210
+ #structuralBurst = false;
211
+ /**
212
+ * Explicit caret to store with the NEXT pushed undo step (instead of the live selection): set by
213
+ * shortcut() so that undoing a block shortcut puts the caret back right after the typed trigger.
214
+ * @type {{ block: Block, offset: number } | null}
215
+ */
216
+ #undoCursor = null;
217
+ /**
218
+ * The selection as it was before the change now being recorded, kept as Loro cursors (see undo-selection.js): refreshed by
219
+ * {@link Nabu#captureUndoSelection} while the model and the DOM agree, handed to the UndoManager when it pushes a step.
220
+ * @type {import('./undo-selection.js').UndoSelection | null}
221
+ */
222
+ #undoSel = null;
223
+ /** Undo / redo whose render is still pending: they put the selection back themselves. */
224
+ #undoing = 0;
225
+ /** Value of `selection.placements` when `#undoSel` was captured: tells whether the editor placed the selection since. */
226
+ #undoSelPlacements = 0;
227
+ /** A selection fix-up after a text change is already scheduled. */
228
+ #keepPending = false;
229
+ /** Commits and undo / redo whose render is still pending: the DOM lags the model, so the selection must not be captured. */
230
+ #busy = 0;
231
+ /** Counter end of the undo step just pushed: the next settled selection is where that action ENDED (what redo restores). */
232
+ #endKey = /** @type {number | null} */ (null);
233
+ /** Counter end of the step being undone (set by its pop, read by the redo step pushed right after). */
234
+ #undoneEnd = /** @type {number | null} */ (null);
235
+ /** Selection where each recent action ended, by the counter end of its undo step. @type {Map<number, import('./undo-selection.js').UndoSelection>} */
236
+ #actionEnds = new Map();
64
237
 
65
238
  /** @param {NabuInit} init */
66
239
  constructor(init = {}) {
@@ -69,54 +242,94 @@ export class Nabu {
69
242
  this.doc.import(init.snapshot);
70
243
  }
71
244
 
245
+ /**
246
+ * The text selection of the editor (a reactive wrapper of the DOM selection, in terms of blocks).
247
+ * @type {NabuSelection}
248
+ * @public
249
+ */
72
250
  this.selection = new NabuSelection(this);
73
- this.tree = /** @type {LoroTree<Record<string, NabuNode>>} */ (this.doc.getTree("blocks"));
251
+ /**
252
+ * The document tree (Loro): one node per block, `node.data` holds the block's `type` and props.
253
+ * @public
254
+ */
255
+ this.tree = /** @type {LoroTree<NabuNodeData>} */ (this.doc.getTree("blocks"));
74
256
  this.content = this.doc.getMap("content");
75
257
 
76
258
  // Initialize Undo/Redo Manager
77
259
  this.undoManager = new UndoManager(this.doc, {
78
260
  maxUndoSteps: 100,
79
- mergeInterval: 1000,
80
- onPush: () => {
81
- // Save cursor position for restoration on undo/redo
82
- const sel = this.selection;
83
- if (!sel || !sel.anchorBlock) return { value: null, cursors: [] };
84
-
85
- return {
86
- value: {
87
- blockId: sel.anchorBlock.id,
88
- offset: sel.startOffset
89
- },
90
- cursors: []
91
- };
261
+ // Background completions (e.g. a pasted file finishing its upload) are not undo steps of their own.
262
+ excludeOriginPrefixes: ['nabu:silent'],
263
+ mergeInterval: this.#mergeInterval,
264
+ onPush: (isUndo, range) => {
265
+ if (this.#isolatedSteps > 0) this.#isolatedSteps--;
266
+ // The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
267
+ // (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
268
+ // an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
269
+ const explicit = this.#undoCursor;
270
+ this.#undoCursor = null;
271
+ const ended = !isUndo && this.#undoneEnd !== null ? this.#actionEnds.get(this.#undoneEnd) : undefined;
272
+ const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? this.#undoSel) ?? legacySelection(this);
273
+ this.#endKey = isUndo ? range?.end ?? null : null;
274
+ return { value: /** @type {any} */ (stored), cursors: [] };
92
275
  },
93
- onPop: (_, storedValue) => {
94
- // Restore cursor position after undo/redo
95
- const value = /** @type {{blockId: string, offset: number} | null} */ (storedValue?.value);
96
- if (value && typeof value === 'object' && 'blockId' in value) {
97
- tick().then(() => {
98
- const block = this.blocks.get(value.blockId);
99
- if (block && block.behaviors?.has('text')) {
100
- this.selection.setCursor(block, value.offset);
101
- }
102
- });
103
- }
276
+ onPop: (isUndo, storedValue, range) => {
277
+ this.#undoneEnd = isUndo ? range?.end ?? null : null;
278
+ this.#endKey = null;
279
+ const value = /** @type {any} */ (storedValue?.value);
280
+ if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(this, value);
104
281
  }
105
282
  });
106
283
 
284
+ /**
285
+ * The extensions the editor was built with, in order.
286
+ * @type {Extension[]}
287
+ * @public
288
+ */
107
289
  this.extensions = init.extensions || [];
108
290
  this.fileConfig = init.files || {};
291
+ this.placeholders = normalizePlaceholders(init.placeholders);
292
+ this.spellcheck = init.spellcheck !== false;
293
+ this.lang = init.lang;
294
+ this.readonly = !!init.readonly;
295
+ this.#tabDefault = resolveTabMode(init.tabDefault, 'focus', (message) => this.warn(message));
296
+ this.tab = init.tab;
297
+ if (typeof init.tabHint === 'string' || init.tabHint === false) this.tabHint = init.tabHint;
298
+
299
+ /**
300
+ * Commands and keyboard shortcuts (ADR 017): `list()`, `get(id)`, `run(id, data)`. A plain snapshot API, the set of
301
+ * commands is fixed once the editor is built.
302
+ */
303
+ this.commandConfirm = new CommandConfirmation(this, init.commandConfirm);
304
+ this.systems.set('command-confirm', { start: () => this.commandConfirm.start(), stop: () => this.commandConfirm.stop() });
305
+ /**
306
+ * Commands and keyboard shortcuts (ADR 017): `list()`, `get(id)`, `has(id)`, `run(id, data)`, `offer(id)`. A plain
307
+ * snapshot API; the set of commands is fixed once the editor is built.
308
+ * @type {CommandRegistry}
309
+ * @public
310
+ */
311
+ this.commands = new CommandRegistry(this, { keymap: init.keymap, platform: init.platform });
312
+ // Engine commands first: they win a tie with an extension's command on the same chord.
313
+ this.#registerCommands('core', {
314
+ undo: { label: 'Undo', keys: ['Mod-z'], run: () => { this.undo(); } },
315
+ redo: { label: 'Redo', keys: ['Mod-Shift-z', 'Mod-y'], run: () => { this.redo(); } },
316
+ // Keyboard alternative to dragging (see move.js): `data.block` (a Block or its id) moves that block instead.
317
+ 'block:move-up': { label: 'Move block up', keys: ['Mod-Shift-ArrowUp'], run: (_nabu, _ctx, data) => moveBlocks(this, 'up', data?.block ?? null) },
318
+ 'block:move-down': { label: 'Move block down', keys: ['Mod-Shift-ArrowDown'], run: (_nabu, _ctx, data) => moveBlocks(this, 'down', data?.block ?? null) },
319
+ });
109
320
 
110
321
  if (this.extensions?.length) {
111
322
  for (const ext of this.extensions) {
112
323
  if (ext.block) this.registry.set(ext.name, ext.block);
324
+ if (ext.block && ext.defaultBlock) this.defaultBlockType = ext.name;
113
325
  if (ext.component) this.components.set(ext.name, ext.component);
114
326
  if (ext.hooks) {
115
- for (const [hookName, hookFn] of Object.entries(ext.hooks)) {
327
+ for (const [hookName, hookFn] of /** @type {[string, (nabu: Nabu, ...args: any[]) => any][]} */ (Object.entries(ext.hooks))) {
116
328
  if (!this.hooks.has(hookName)) {
117
329
  this.hooks.set(hookName, []);
118
330
  }
119
- this.hooks.get(hookName).push(hookFn);
331
+ /** @type {Array<(nabu: Nabu, ...args: any[]) => any>} */ (this.hooks.get(hookName)).push(hookFn);
332
+ this.hookOwners.set(hookFn, ext.name);
120
333
  }
121
334
  }
122
335
 
@@ -128,22 +341,32 @@ export class Nabu {
128
341
 
129
342
  if (ext.actions) {
130
343
  for (const [topic, handler] of Object.entries(ext.actions)) {
131
- this.#pulse.on(topic, ({ event }) => handler(this, event.data, event.topic));
344
+ this.#pulse.on(topic, ({ event }) => { if (this.#readonly) return; return handler(this, event.data, event.topic); }); // read-only: actions are edits, they do nothing
132
345
  }
133
346
  }
134
347
 
348
+ if (ext.commands) this.#registerCommands(ext.name, ext.commands);
349
+ if (ext.commandContext) this.commands.addContextProvider(ext.commandContext, ext.name);
350
+
135
351
  if (ext.pasteInterpreters?.length) {
136
352
  for (const interpreter of ext.pasteInterpreters) {
137
353
  this.#pasteInterpreters.push(interpreter);
138
354
  }
139
355
  }
140
356
 
357
+ if (ext.pasteFileHandlers?.length) {
358
+ this.#pasteFileHandlers.push(...ext.pasteFileHandlers);
359
+ this.#pasteFileHandlers.sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
360
+ }
361
+
141
362
  if (ext.inputRules?.length) {
142
363
  for (const rule of ext.inputRules) {
143
364
  this.inputRules.push(rule);
144
365
  }
145
366
  }
146
367
 
368
+ if (ext.slashCommands?.length) this.slashCommands.push(...ext.slashCommands);
369
+
147
370
  if (ext.loroTextStyles && Object.keys(ext.loroTextStyles).length) {
148
371
  this.doc.configTextStyle(ext.loroTextStyles);
149
372
  }
@@ -151,79 +374,144 @@ export class Nabu {
151
374
  }
152
375
  }
153
376
 
154
- // Core actions — always available
155
- this.#pulse.on('undo', () => this.undo());
156
- this.#pulse.on('redo', () => this.redo());
377
+ // Core actions (`undo`, `redo`) are commands, registered above.
378
+ this.commands.checkKeymap();
157
379
 
158
380
  const roots = /** @type {NabuNode[]} */ (this.tree.roots());
159
381
  if (roots?.length) {
160
382
  for (const root of roots) {
161
383
  const block = Block.load(this, root);
384
+ block.index = this.children.length;
162
385
  this.children.push(block);
163
386
  }
164
387
  }
165
388
 
389
+ // Files: the local asset store, and the migration of a beta document whose files are still inside it (ADR 014 §3.7).
390
+ Files.get(this);
391
+
166
392
  // this.doc.subscribe((event) => {
167
393
  // // event.events contient un tableau listant TOUTES les opérations
168
394
  // // (texte ajouté, nœuds déplacés, etc.) qui viennent d'être commitées.
169
395
  // console.log("Rapport de la transaction :", event.events);
170
396
  // });
171
397
 
398
+ // One event batch = one refresh. The affected containers are COLLECTED while the batch is read, then each is refreshed
399
+ // once (the root list at most once, every parent at most once): refreshing per action made an import / a mass undo / a
400
+ // big paste quadratic (P-104). The doc already holds the final state of the batch, so the order of the actions is moot.
172
401
  this.tree.subscribe((event) => {
402
+ let rootsDirty = false;
403
+ /** @type {Set<string>} */
404
+ const parents = new Set();
405
+ /** @type {Set<string>} */
406
+ const retyped = new Set();
407
+
408
+ let removed = false;
173
409
  event.events.forEach(e => {
174
410
  if (e.diff.type === "tree") {
175
411
  e.diff.diff.forEach(action => {
412
+ if (action.action === 'delete') removed = true;
176
413
  if (action.action === 'create' || action.action === 'move' || action.action === 'delete') {
177
- if (action.parent) {
178
- const parentId = action.parent.toString();
179
- const parentBlock = this.blocks.get(parentId);
180
- if (parentBlock) parentBlock.updateChildren();
181
- } else {
182
- this.updateRoots();
183
- }
184
-
185
- if (action.oldParent) {
186
- const oldParentId = action.oldParent.toString();
187
- const oldParentBlock = this.blocks.get(oldParentId);
188
- if (oldParentBlock) oldParentBlock.updateChildren();
189
- }
414
+ // `parent` is set on create / move, `oldParent` on move / delete (a TreeDiffItem is a union of the three)
415
+ const { parent, oldParent } = /** @type {{ parent?: string, oldParent?: string }} */ (action);
416
+ if (parent) parents.add(parent.toString());
417
+ else rootsDirty = true;
418
+
419
+ if (oldParent) parents.add(oldParent.toString());
420
+ // A node that LEAVES the root for a container has no `oldParent` (the root is no node): the
421
+ // root list must be refreshed too, else the old element stays rendered next to the new one.
422
+ else if (action.action === 'move' && parent) rootsDirty = true;
190
423
  }
191
424
  })
192
425
  }
193
426
 
194
427
  if (e.diff.type === "map") {
195
-
196
428
  const newType = e.diff.updated["type"];
197
429
  if (newType !== undefined) {
198
430
  const nodeId = e.path[1].toString();
199
431
  const block = this.blocks.get(nodeId);
200
432
  if (block && block.type !== newType) {
201
- if (block.parent) block.parent.updateChildren();
202
- else this.updateRoots();
433
+ retyped.add(nodeId);
434
+ if (block.parent) parents.add(block.parent.id);
435
+ else rootsDirty = true;
203
436
  }
204
437
  }
205
438
  }
206
439
  })
440
+
441
+ if (removed) this.selection.scheduleRepair?.(); // the caret may have been in the removed blocks (P-108)
442
+ if (rootsDirty) this.updateRoots(retyped);
443
+ for (const parentId of parents) {
444
+ // A block retyped into a leaf (no children) in the same transaction has no updateChildren().
445
+ /** @type {{ updateChildren?: (retyped?: Set<string>) => void } | undefined} */ (this.blocks.get(parentId))?.updateChildren?.(retyped);
446
+ }
207
447
  });
208
448
 
209
449
  this.init();
210
450
  }
211
451
 
452
+ /**
453
+ * What a hook or an `onBeforeInput` handler returns to stop the engine (and the hooks after it).
454
+ * @type {symbol}
455
+ * @public
456
+ */
212
457
  static BREAK = Symbol("BREAK");
458
+ /**
459
+ * What a hook returns to let the engine go on (same as returning nothing).
460
+ * @type {symbol}
461
+ * @public
462
+ */
213
463
  static CONTINUE = Symbol("CONTINUE");
464
+ /**
465
+ * `Nabu.BREAK`, reachable from the instance a hook receives.
466
+ * @type {symbol}
467
+ * @public
468
+ */
214
469
  BREAK = Nabu.BREAK;
470
+ /**
471
+ * `Nabu.CONTINUE`, reachable from the instance a hook receives.
472
+ * @type {symbol}
473
+ * @public
474
+ */
215
475
  CONTINUE = Nabu.CONTINUE;
216
476
 
217
- /** @type {LoroDoc} */
477
+ /**
478
+ * The Loro document behind the editor (public: connect it to a server with `doc.subscribeLocalUpdates` and `importRemote`).
479
+ * @type {LoroDoc}
480
+ * @public
481
+ */
218
482
  doc;
219
- /** @type {SvelteMap<string, typeof Block>} */
483
+ /**
484
+ * The block classes registered by the loaded extensions, by block type.
485
+ * @type {SvelteMap<string, typeof Block>}
486
+ * @public
487
+ */
220
488
  registry = new SvelteMap();
221
- /** @type {SvelteMap<string, Component>} */
489
+
490
+ /**
491
+ * Type of the default text block (declared by an extension with `defaultBlock: true`): created by the
492
+ * engine when it needs an empty text block of its own, e.g. a caret after a trailing void block.
493
+ * @type {string | null}
494
+ * @public
495
+ */
496
+ defaultBlockType = null;
497
+ /**
498
+ * The Svelte components registered by the loaded extensions, by block type.
499
+ * @type {SvelteMap<string, Component>}
500
+ * @public
501
+ */
222
502
  components = new SvelteMap();
223
- /** @type {SvelteMap<string, Block>} */
503
+ /**
504
+ * Every live block of the document, by tree id.
505
+ * @type {SvelteMap<string, Block>}
506
+ * @public
507
+ */
224
508
  blocks = new SvelteMap();
225
509
 
226
- /** @type {SvelteMap<string, SvelteSet<Block>>} */
510
+ /**
511
+ * The live blocks of each type (reactive sets, by block type).
512
+ * @type {SvelteMap<string, SvelteSet<Block>>}
513
+ * @public
514
+ */
227
515
  blocksByType = new SvelteMap();
228
516
 
229
517
  /**
@@ -231,11 +519,23 @@ export class Nabu {
231
519
  * - `start(): void` — called when the editor mounts
232
520
  * - `stop(): void` — called when the editor unmounts
233
521
  * @type {SvelteMap<string, { start?: () => void, stop?: () => void, [key: string]: any }>}
522
+ * @public
234
523
  */
235
524
  systems = new SvelteMap();
236
525
 
526
+ /**
527
+ * Extension hooks by name, in registration order (see `ExtensionHooks`).
528
+ * @type {Map<string, Array<(nabu: Nabu, ...args: any[]) => any>>}
529
+ */
237
530
  hooks = new Map();
238
531
 
532
+ /**
533
+ * Hook function -> name of the extension that registered it. Lets `Block#ascend` run the hooks of the
534
+ * extension that OWNS the block type before the generic ones (type-specific handler wins).
535
+ * @type {WeakMap<Function, string>}
536
+ */
537
+ hookOwners = new WeakMap();
538
+
239
539
  /**
240
540
  * Declarative input rules collected from extensions, tested by TextBehavior
241
541
  * against the text before the cursor on matching beforeinput events.
@@ -243,9 +543,96 @@ export class Nabu {
243
543
  */
244
544
  inputRules = [];
245
545
 
546
+ /**
547
+ * Slash-menu entries contributed by extensions (`Extension#slashCommands`); the slash menu lists ONLY these (plus the
548
+ * integrator's extras), sorted by `group` / `order`, keeping those whose `when(engine, block)` holds at the caret.
549
+ * @type {import('../ui/slash-menu.svelte.js').SlashCommand[]}
550
+ * @public
551
+ */
552
+ slashCommands = [];
553
+
246
554
  /** @type {import('../files/files.svelte.js').FilesConfig} */
247
555
  fileConfig = {};
248
556
 
557
+ /**
558
+ * Resolved `placeholders` option (see NabuInit). Reassign to change it at runtime.
559
+ * @type {import('../utils/placeholders.js').ResolvedPlaceholders}
560
+ * @public
561
+ */
562
+ placeholders = $state.raw(normalizePlaceholders());
563
+
564
+ /**
565
+ * Resolved `spellcheck` option (see NabuInit). Reactive: assign to change it at runtime.
566
+ * @type {boolean}
567
+ * @public
568
+ */
569
+ spellcheck = $state.raw(true);
570
+
571
+ #readonly = $state.raw(false);
572
+
573
+ /**
574
+ * Read-only mode (see the `readonly` option of NabuInit). Reactive: assign to switch it on or off at runtime. While `true`
575
+ * the user cannot change the document: input, paste, cut, drop, drag moves and commands (shortcuts, `commands.run`,
576
+ * `exec` of a command, undo / redo) are ignored by the engine, and the UI components hide themselves. Programmatic
577
+ * edits by the host (`insert`, `importJSON`...) are not blocked. View state that is not part of the document (a toggle
578
+ * opened to read it) stays possible and is never written to the document.
579
+ * @type {boolean}
580
+ * @public
581
+ */
582
+ get readonly() { return this.#readonly; }
583
+ set readonly(value) {
584
+ this.#readonly = !!value;
585
+ if (this.#readonly) this.commandConfirm?.cancel('api'); // a hold / invite / chooser in progress is moot
586
+ }
587
+
588
+ /** @type {string | undefined} */
589
+ #lang = $state.raw(undefined);
590
+
591
+ /**
592
+ * Resolved `lang` option (see NabuInit): a valid BCP 47 tag, or `undefined` (inherit the page language).
593
+ * Reactive: assign to change it at runtime; an invalid value is ignored (warning) and leaves it unchanged.
594
+ * @type {string | undefined}
595
+ * @public
596
+ */
597
+ get lang() { return this.#lang; }
598
+ set lang(value) {
599
+ const { lang, valid } = normalizeLang(value);
600
+ if (!valid) { this.warn(`Ignoring invalid "lang" (not a BCP 47 tag): ${String(value)}`); return; }
601
+ this.#lang = lang;
602
+ }
603
+
604
+ /** @type {import('../utils/tab.js').TabMode} */
605
+ #tabDefault = 'focus';
606
+
607
+ /** @type {import('../utils/tab.js').TabMode} */
608
+ #tab = $state.raw('focus');
609
+
610
+ /**
611
+ * Resolved `tab` option (see NabuInit): what Tab / Shift+Tab do in a plain text block. Reactive: assign to change it at runtime;
612
+ * an unknown value warns and gives the default of the editor (its preset).
613
+ * @type {import('../utils/tab.js').TabMode}
614
+ * @public
615
+ */
616
+ get tab() { return this.#tab; }
617
+ /** @param {unknown} value */
618
+ set tab(value) { this.#tab = resolveTabMode(value, this.#tabDefault, (message) => this.warn(message)); }
619
+
620
+ /**
621
+ * Announcement of the Escape-then-Tab way out (option `tabHint`), `false` for none. Reactive.
622
+ * @type {string | false}
623
+ * @public
624
+ */
625
+ tabHint = $state.raw(DEFAULT_TAB_HINT);
626
+
627
+ /** What the editor root exposes as `aria-description`: the hint, only while the mode keeps the focus in. */
628
+ get tabDescription() { return !this.#readonly && this.#tab !== 'focus' && this.tabHint ? this.tabHint : undefined; }
629
+
630
+ /** An Escape nobody consumed was the previous key: the next Tab / Shift+Tab leaves the editor (see `utils/tab.js`). */
631
+ #tabEscaped = false;
632
+
633
+ /** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
634
+ rearmTab() { this.#tabEscaped = false; }
635
+
249
636
  /**
250
637
  * Pending inline formatting for the next typed character (active marks at a
251
638
  * collapsed cursor). null = inherit from the span at the cursor.
@@ -253,35 +640,60 @@ export class Nabu {
253
640
  */
254
641
  storedMarks = $state(null);
255
642
 
643
+ /**
644
+ * When true, `nabu.warn()` logs to the console (`[Nabu]`).
645
+ * @public
646
+ */
256
647
  debugging = $state(false);
257
648
 
258
649
  /**
259
650
  * Root-level serializers. Each function receives the Nabu instance and returns the serialized document.
260
651
  * @type {Map<string, (nabu: Nabu) => any>}
652
+ * @public
261
653
  */
262
- serializers = new Map([
654
+ serializers = new Map(/** @type {Array<[string, (nabu: Nabu) => any]>} */ ([
263
655
  ['markdown', (nabu) =>
264
656
  nabu.children
265
657
  .map(b => b.serialize('markdown'))
266
658
  .filter(Boolean)
267
659
  .join('\n\n')
268
660
  ],
269
- ['json', (nabu) => ({
270
- version: '1',
271
- blocks: nabu.children.map(b => b.serialize('json')).filter(Boolean)
272
- })]
273
- ]);
661
+ ['json', (nabu) => {
662
+ const blocks = nabu.children.map(b => b.serialize('json')).filter(Boolean);
663
+ // The bytes of the `nabu-asset:` media travel with the document (same `assets` map as the clipboard format).
664
+ const assets = Files.get(nabu).embedAssets(blocks);
665
+ return { version: JSON_FORMAT_VERSION, blocks, ...(assets ? { assets } : {}) };
666
+ }]
667
+ ]));
274
668
 
275
- /** @type {Block[]} */
669
+ /**
670
+ * The root blocks of the document, in order (reactive).
671
+ * @type {Block[]}
672
+ * @public
673
+ */
276
674
  children = $state([]);
277
675
 
676
+ /**
677
+ * Number of caret positions in the document (the sum of the root blocks').
678
+ * @public
679
+ */
278
680
  positions = $derived(this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
279
681
 
682
+ /**
683
+ * True when the document has no block.
684
+ * @public
685
+ */
280
686
  get isEmpty() {
281
687
  return this.children.length === 0;
282
688
  }
283
689
 
284
- /** @param {string} format */
690
+ /**
691
+ * Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, or one an extension
692
+ * adds with `serializers`); `null` (and a warning) for an unknown format.
693
+ * @param {string} format
694
+ * @returns {any}
695
+ * @public
696
+ */
285
697
  serialize(format) {
286
698
  const fn = this.serializers.get(format);
287
699
  if (!fn) {
@@ -295,21 +707,27 @@ export class Nabu {
295
707
  this.hooks.get("onInit")?.forEach(hook => hook(this));
296
708
  }
297
709
 
298
- /** Rafraîchit les blocs racines de l'éditeur */
299
- updateRoots() {
710
+ /**
711
+ * Rafraîchit les blocs racines de l'éditeur. Les blocs déjà connus sont réutilisés tels quels : seul le type des nœuds
712
+ * listés dans `retyped` (ids dont le `type` vient de changer) est relu.
713
+ * @param {Set<string>} [retyped] without it, the type of every root is checked
714
+ */
715
+ updateRoots(retyped) {
300
716
  const roots = /** @type {NabuNode[]} */ (this.tree.roots());
301
717
  this.children = roots.map((root, i) => {
302
718
  const id = root.id.toString();
303
719
  let block = this.blocks.get(id);
304
- const currentType = root.data.get("type");
305
-
306
- if (!block || block.type !== currentType) {
307
- if (block) {
308
- this.blocks.delete(id);
309
- this.blocksByType.get(block.type)?.delete(block);
310
- }
311
720
 
312
- block = Block.load(this, root);
721
+ if (!block || !retyped || retyped.has(id)) {
722
+ const currentType = root.data.get("type");
723
+ if (!block || block.type !== currentType) {
724
+ if (block) {
725
+ this.blocks.delete(id);
726
+ this.blocksByType.get(block.type)?.delete(block);
727
+ }
728
+
729
+ block = Block.load(this, root);
730
+ }
313
731
  }
314
732
  block.index = i;
315
733
  block.parent = null;
@@ -319,14 +737,67 @@ export class Nabu {
319
737
 
320
738
  /**
321
739
  * Dispatch an action to all registered handlers for the given topic.
740
+ * Re-syncs the model selection from the DOM first: `selectionchange` is async, so right after a
741
+ * keyboard-only selection change (Shift+Arrow, Home/End, Ctrl+A) the model would be stale.
322
742
  * @param {string} topic
323
743
  * @param {any} [data]
324
744
  * @returns {Promise<import('@aionbuilders/pulse').PulseEvent>}
745
+ * @public
325
746
  */
326
747
  exec(topic, data) {
748
+ this.selection.sync();
327
749
  return this.#pulse.emit(topic, data);
328
750
  }
329
751
 
752
+ /**
753
+ * The command waiting for the user's confirmation (ADR 017 §3.4), reactive; `null` when none:
754
+ * `{ id, strategy: 'hold' | 'invite' | 'choose', label, display, message, target?, progress, options?, selectedIndex }`.
755
+ * `progress` (hold, 0 → 1) and `selectedIndex` (choose) are reactive fields of that object.
756
+ * @returns {import('../utils/command-confirm.svelte.js').PendingCommand | null}
757
+ * @public
758
+ */
759
+ get pendingCommand() { return this.commandConfirm.pending; }
760
+
761
+ /**
762
+ * Cancel the pending confirmation, if any: nothing runs.
763
+ * @public
764
+ */
765
+ cancelPendingCommand() { this.commandConfirm.cancel('api'); }
766
+
767
+ /**
768
+ * The pending confirmation when it is ABOUT `target` (what `confirm.target(ctx)` returned: usually a block), else `null`.
769
+ * Reactive: a block that draws its own hold progress reads `nabu.pendingCommandOn(block)?.progress`.
770
+ * @param {any} target
771
+ * @returns {import('../utils/command-confirm.svelte.js').PendingCommand | null}
772
+ * @public
773
+ */
774
+ pendingCommandOn(target) { return this.commandConfirm.pendingOn(target); }
775
+
776
+ /**
777
+ * Text of the polite live region of the editor (prompts and outcomes of confirmations). Reactive.
778
+ * @returns {string}
779
+ * @public
780
+ */
781
+ get commandAnnouncement() { return this.commandConfirm.announcement; }
782
+
783
+ /**
784
+ * Register commands (ADR 017): the registry keeps them and resolves their keys; each one is also an action of the bus.
785
+ * @param {string} owner extension name
786
+ * @param {Record<string, import('../utils/commands.js').CommandDef>} commands
787
+ */
788
+ #registerCommands(owner, commands) {
789
+ for (const [id, def] of Object.entries(commands)) {
790
+ const entry = this.commands.register(id, def, owner);
791
+ if (entry) this.#pulse.on(id, ({ event }) => (this.#readonly ? undefined : this.commands.invoke(entry, event.data)));
792
+ }
793
+ }
794
+
795
+ /**
796
+ * Run the `hookName` hooks of every extension, in order, until one returns `BREAK`. Each is called as `hook(nabu, ...args)`.
797
+ * @param {string} hookName
798
+ * @param {...any} args
799
+ * @public
800
+ */
330
801
  trigger(hookName, ...args) {
331
802
  const hooks = this.hooks.get(hookName) || [];
332
803
  for (const hook of hooks) {
@@ -339,10 +810,143 @@ export class Nabu {
339
810
  }
340
811
 
341
812
 
342
- async commit() {
813
+ /**
814
+ * Commit the pending changes as one Loro transaction.
815
+ * @param {{ origin?: string }} [options] `origin` tags the transaction; an origin starting with `nabu:silent` is
816
+ * not recorded as an undo step (background completions that must not be undone on their own).
817
+ * @public
818
+ */
819
+ async commit({ origin } = {}) {
820
+ this.#evictChildrenOfLeaves();
343
821
  this.trigger("onBeforeTransaction", this);
344
- this.doc.commit();
822
+ // Structural operations (split, merge, delete/move of blocks, type change, list indent…)
823
+ // are their own undo step, and so is the typing that follows (see #hasPendingStructuralOps).
824
+ // Skipped when an isolation is already armed for this very commit (paste, cut).
825
+ let continuation = false;
826
+ const stepsBefore = this.#isolatedSteps;
827
+ if (!(this.#isolating && this.#isolatedSteps === 2) && this.#hasPendingStructuralOps()) {
828
+ if (this.#structuralBurst) {
829
+ // A second structural commit in the same synchronous turn is the same user
830
+ // operation (e.g. a list indent = create the sublist via nabu.insert(), which
831
+ // commits, then move the item): let it merge into the step just pushed.
832
+ continuation = true;
833
+ this.undoManager.setMergeInterval(this.#mergeInterval);
834
+ } else {
835
+ this.#structuralBurst = true;
836
+ queueMicrotask(() => { this.#structuralBurst = false; });
837
+ this.#isolateNextCommits();
838
+ }
839
+ }
840
+ this.#busy++; // until the render: the DOM lags the model, no selection capture meanwhile (see captureUndoSelection)
841
+ try {
842
+ this.doc.commit(typeof origin === 'string' ? { origin } : undefined);
843
+ } catch (err) {
844
+ this.#busy--;
845
+ throw err;
846
+ }
847
+ if (continuation && this.#isolating) {
848
+ // The merge above must not leak: the typing after the operation stays isolated
849
+ // (a merged commit may still call onPush, so don't count it as a pushed step).
850
+ this.#isolatedSteps = stepsBefore;
851
+ this.undoManager.setMergeInterval(0);
852
+ }
853
+ if (this.#isolating && this.#isolatedSteps === 0) {
854
+ this.#isolating = false;
855
+ this.undoManager.setMergeInterval(this.#mergeInterval);
856
+ }
345
857
  await tick();
858
+ this.#busy--;
859
+ // Rendered: the selection is where the action left it (the caller may still move it, which is captured again).
860
+ this.captureUndoSelection('settle');
861
+ }
862
+
863
+ /**
864
+ * Generic schema rule: a block whose class cannot hold children (anything that is not a MegaBlock)
865
+ * never keeps child nodes. When the pending transaction retypes a node into such a block (transform,
866
+ * markdown shortcut, `data.set('type')`) or moves / creates a node under one, its children are moved
867
+ * out to right after it, in order, in the same transaction: nothing is lost, and the (type-specific)
868
+ * `onBeforeTransaction` normalizers then reshape the result. Knows no concrete block type.
869
+ */
870
+ #evictChildrenOfLeaves() {
871
+ const pending = this.doc.getUncommittedOpsAsJson();
872
+ if (!pending) return;
873
+ const treeId = this.tree.id;
874
+ /** @type {Set<string>} */
875
+ const candidates = new Set();
876
+ for (const change of pending.changes) {
877
+ for (const op of change.ops) {
878
+ const content = /** @type {any} */ (op.content);
879
+ if (op.container === treeId) {
880
+ if ((content.type === 'move' || content.type === 'create') && content.parent) candidates.add(String(content.parent));
881
+ } else if (content.type === 'insert' && content.key === 'type' && op.container.endsWith(':Map')) {
882
+ candidates.add(op.container.slice(4, -4));
883
+ }
884
+ }
885
+ }
886
+ for (const id of candidates) {
887
+ if (!this.tree.has(/** @type {any} */ (id))) continue;
888
+ const node = /** @type {NabuNode | undefined} */ (this.tree.getNodeByID(/** @type {any} */ (id)));
889
+ if (!node || node.isDeleted()) continue;
890
+ const BlockClass = this.registry.get(/** @type {any} */ (node.data.get('type')));
891
+ if (!BlockClass || BlockClass === MegaBlock || BlockClass.prototype instanceof MegaBlock) continue;
892
+ /** @type {NabuNode} */
893
+ let anchor = node;
894
+ for (const child of /** @type {NabuNode[]} */ (node.children() ?? [])) {
895
+ child.moveAfter(anchor);
896
+ anchor = child;
897
+ }
898
+ }
899
+ }
900
+
901
+ /**
902
+ * Whether the pending (uncommitted) Loro transaction changes the document structure:
903
+ * a tree create / move / delete (every block creation, destruction, re-parenting or
904
+ * reordering — split, merge, multi-block deletion, list indent…) or a change of a
905
+ * block's `type` (transforms, markdown shortcuts).
906
+ *
907
+ * This is the one central choke point: whatever the call site (tree.createNode,
908
+ * node.move, destroy, adoptChildren, data.set('type')…), the ops end up in the
909
+ * pending transaction that commit() is about to flush, so nothing has to be marked
910
+ * at the ~46 mutation sites.
911
+ * @returns {boolean}
912
+ */
913
+ #hasPendingStructuralOps() {
914
+ const pending = this.doc.getUncommittedOpsAsJson();
915
+ if (!pending) return false;
916
+ const treeId = this.tree.id;
917
+ for (const change of pending.changes) {
918
+ for (const op of change.ops) {
919
+ const content = /** @type {any} */ (op.content);
920
+ if (op.container === treeId) {
921
+ if (content.type === 'create' || content.type === 'move' || content.type === 'delete') return true;
922
+ } else if (content.type === 'insert' && content.key === 'type' && op.container.endsWith(':Map')) {
923
+ // `type` set on a block's data map ("cid:<nodeId>:Map"), not e.g. a file asset's MIME type.
924
+ if (this.blocks.has(op.container.slice(4, -4))) return true;
925
+ }
926
+ }
927
+ }
928
+ return false;
929
+ }
930
+
931
+ /**
932
+ * Make the next commit (a paste, a cut, a structural op) AND the one after it their own undo steps:
933
+ * merging is off until both pushed a step (empty commits don't count), then
934
+ * the configured interval is restored at the end of commit().
935
+ */
936
+ #isolateNextCommits() {
937
+ this.undoManager.setMergeInterval(0);
938
+ this.#isolating = true;
939
+ this.#isolatedSteps = 2;
940
+ }
941
+
942
+ /**
943
+ * Make the NEXT commit its own undo step (and the typing right after it another one), even though it
944
+ * holds no structural op: for a non-structural change that must undo on its own, e.g. a flag toggled
945
+ * from the keyboard, which would otherwise merge with the typing around it. Call it just before commit().
946
+ * @public
947
+ */
948
+ isolateUndoStep() {
949
+ this.#isolateNextCommits();
346
950
  }
347
951
 
348
952
  /**
@@ -351,6 +955,7 @@ export class Nabu {
351
955
  * @param {() => void} mutateFn - Mutations Loro ici. Ne PAS appeler commit() dedans.
352
956
  * @param {{ block: Block, offset: number } | null} [cursorIntent]
353
957
  * @returns {Promise<void>}
958
+ * @public
354
959
  */
355
960
  async transact(mutateFn, cursorIntent = null) {
356
961
  mutateFn();
@@ -360,12 +965,52 @@ export class Nabu {
360
965
  }
361
966
  }
362
967
 
968
+ /**
969
+ * Apply a markdown BLOCK shortcut (`# `, `- `, `> `, `--- `…) so that undo gives back exactly what
970
+ * the user typed, trigger included: one Ctrl+Z after `# ` leaves a paragraph "# " with the caret
971
+ * after the space; a second one removes the typing as usual.
972
+ *
973
+ * 1. `trigger` (the swallowed space) is inserted at the caret and committed like normal typing;
974
+ * 2. `transform` runs (delete the prefix incl. the trigger, change/replace the block…) and is
975
+ * committed as its own structural undo step (see commit()), whose stored caret is right
976
+ * after the trigger.
977
+ * Both commits run in the same synchronous turn, so the intermediate "# " is never painted.
978
+ *
979
+ * For a trigger that is not text (``` + Enter), pass `trigger = ''`: nothing is inserted and
980
+ * undo restores the text typed before the key (the fence line, without the Enter).
981
+ * @param {Block} block the block the shortcut was typed in
982
+ * @param {string} trigger text of the trigger key, inserted before transforming ('' = none)
983
+ * @param {(behavior: any) => void} transform mutations only (it may commit itself, e.g. via transformTo)
984
+ * @returns {Promise<void>} resolves immediately, doing nothing, when `block.transformsEnabled === false`
985
+ * @public
986
+ */
987
+ async shortcut(block, trigger, transform) {
988
+ // Defence in depth: a block that opts out of transforms (`transformsEnabled === false`) never
989
+ // converts. The primary guard is upstream (dispatchEventToSelection skips the extension hooks
990
+ // for typing in such a block, so the keystroke proceeds as plain text); this covers direct callers.
991
+ if (block.transformsEnabled === false) return;
992
+ const behavior = block.behaviors.get('text');
993
+ const sel = behavior?.selection;
994
+ if (!behavior || !sel) return;
995
+ const at = sel.from;
996
+ if (trigger) {
997
+ behavior.insert(at, trigger);
998
+ this.commit();
999
+ }
1000
+ this.#undoCursor = { block, offset: at + trigger.length };
1001
+ transform(behavior);
1002
+ const committed = this.commit(); // pushes the undo step synchronously (the await is only a tick)
1003
+ this.#undoCursor = null;
1004
+ await committed;
1005
+ }
1006
+
363
1007
  /**
364
1008
  * True when every selected text run carries the given mark.
365
1009
  * Reactive: reads block.selected and the behaviors' selections/deltas,
366
1010
  * so it can be used directly in component templates (e.g. FloatingToolbar).
367
1011
  * @param {string} markName
368
1012
  * @returns {boolean}
1013
+ * @public
369
1014
  */
370
1015
  isMarkActive(markName) {
371
1016
  let found = false;
@@ -382,23 +1027,101 @@ export class Nabu {
382
1027
  }
383
1028
 
384
1029
  /**
385
- * Undo the last operation
1030
+ * Import changes made ELSEWHERE (another tab, a peer, a stored copy of the document: ADR 010 multi-tab sync). They are the
1031
+ * document's own history, not the user's actions: Loro's UndoManager records local commits only, so an import is never an undo
1032
+ * step (undoing the user's own edits afterwards still works, Loro transforms them). The DOM follows through the normal Loro
1033
+ * events. The caret of the local user stays on the same CHARACTER: it is captured as Loro cursors before the import and put
1034
+ * back after the render (a text node rewritten by Svelte would otherwise send it to the start of the block); the page is
1035
+ * never scrolled for it. Idempotent (importing what the document already has changes nothing).
1036
+ * Called DURING an IME composition it is applied at once (not held): the model is safe, because the composition anchor is a Loro
1037
+ * cursor that follows the edit, and the caret restore is skipped meanwhile (the browser owns it). (`persistence/sync.js` still
1038
+ * holds the updates it receives while composing, which keeps the composing text node untouched by the render.)
1039
+ * @param {Uint8Array} bytes a Loro snapshot or update
1040
+ * @returns {import('loro-crdt').ImportStatus}
1041
+ * @public
1042
+ */
1043
+ importRemote(bytes) {
1044
+ const keep = !this.#composing && this.#busy === 0 && this.doc.getPendingTxnLength() === 0 ? captureSelection(this) : null;
1045
+ const status = this.doc.import(bytes);
1046
+ if (keep) restoreSelection(this, keep, 0, false);
1047
+ return status;
1048
+ }
1049
+
1050
+ /**
1051
+ * Undo the last operation. The selection as it was before that operation comes back (see ADR 015).
1052
+ * @public
386
1053
  */
387
1054
  undo() {
388
- if (this.undoManager.canUndo()) {
389
- this.undoManager.undo();
390
- }
1055
+ if (this.undoManager.canUndo()) this.#whileRendering(() => this.undoManager.undo());
391
1056
  }
392
1057
 
393
1058
  /**
394
- * Redo the last undone operation
1059
+ * Redo the last undone operation. The selection comes back where that operation ended.
1060
+ * @public
395
1061
  */
396
1062
  redo() {
397
- if (this.undoManager.canRedo()) {
398
- this.undoManager.redo();
1063
+ if (this.undoManager.canRedo()) this.#whileRendering(() => this.undoManager.redo());
1064
+ }
1065
+
1066
+ /**
1067
+ * Run `fn` (an undo / redo, whose render is asynchronous) with the selection capture off until it is rendered.
1068
+ * @param {() => void} fn
1069
+ */
1070
+ #whileRendering(fn) {
1071
+ this.#busy++;
1072
+ this.#undoing++;
1073
+ try { fn(); } finally { tick().then(() => { this.#busy--; this.#undoing--; }); }
1074
+ }
1075
+
1076
+
1077
+ /**
1078
+ * The text of `block` just changed (a Loro event of its text container: local, programmatic or imported). When a selection end
1079
+ * is in that block and the change is NOT the user's own typing (the handlers place their caret themselves), the selection is
1080
+ * put back on the characters it was on once the render is done: Svelte rewrites the edited text node, which would send the end
1081
+ * of the DOM range to offset 0 of it (P-109). The ends are the Loro cursors of the last selection captured while the model and
1082
+ * the DOM agreed (`#undoSel`), so an insertion before them shifts them. O(1) when the block holds no selection end. Skipped
1083
+ * during a composition and an undo / redo (which restore the selection themselves), and when the editor has placed the selection
1084
+ * since that capture (an input handler puts its own caret after the render: it is the one that knows where the caret goes, and
1085
+ * what it placed is captured again, `captureUndoSelection('settle')`).
1086
+ * @param {Block} block
1087
+ */
1088
+ noteTextChange(block) {
1089
+ const snap = this.#undoSel;
1090
+ if (!snap || this.#keepPending || this.#composing || this.#undoing > 0) return;
1091
+ if (snap.anchor.blockId !== block.id && snap.focus.blockId !== block.id) return;
1092
+ const placed = this.#undoSelPlacements;
1093
+ if (this.selection.placements !== placed) return;
1094
+ this.#keepPending = true;
1095
+ tick().then(() => {
1096
+ this.#keepPending = false;
1097
+ if (this.#composing || this.#undoing > 0 || this.selection.placements !== placed) return;
1098
+ keepSelection(this, snap);
1099
+ });
1100
+ }
1101
+
1102
+ /**
1103
+ * Remember the live selection as the one an undo step pushed from now on gives back (ADR 015). Called wherever the selection
1104
+ * changes or an input starts (selection change, key down, programmatic caret placement), always while the model and the DOM
1105
+ * agree: it does nothing during a composition, while a commit / undo is rendering, and while a transaction is pending (the
1106
+ * Loro cursors have to bind to the text as it was BEFORE the change).
1107
+ * @param {'user' | 'settle'} [source] 'settle' = the editor itself placed the selection after an action: it is where that
1108
+ * action ended (what a redo gives back). 'user' = the user moved it.
1109
+ */
1110
+ captureUndoSelection(source = 'user') {
1111
+ if (this.#composing || this.#busy > 0 || this.doc.getPendingTxnLength() > 0) return;
1112
+ const snap = captureSelection(this);
1113
+ if (!snap) return;
1114
+ this.#undoSel = snap;
1115
+ this.#undoSelPlacements = this.selection.placements ?? 0;
1116
+ if (source === 'settle' && this.#endKey !== null) {
1117
+ this.#actionEnds.set(this.#endKey, snap);
1118
+ if (this.#actionEnds.size > 200) this.#actionEnds.delete(/** @type {number} */ (this.#actionEnds.keys().next().value));
399
1119
  }
400
1120
  }
401
1121
 
1122
+ /** A pointer interaction starts: the selection that follows is the user's, no longer where the last action ended. */
1123
+ sealUndoEnd() { this.#endKey = null; }
1124
+
402
1125
  /** Clear the pending stored marks. */
403
1126
  clearStoredMarks() { this.storedMarks = null; }
404
1127
 
@@ -419,9 +1142,17 @@ export class Nabu {
419
1142
 
420
1143
 
421
1144
 
422
- /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}, offset?: number}} [options={}] */
1145
+ /**
1146
+ * Place the DOM + model selection. Asynchronous by nature: it waits for Svelte to flush pending state
1147
+ * (`tick()`), because the target blocks' DOM may not be rendered yet (e.g. right after a commit/insert).
1148
+ * The returned promise resolves once the selection has been set, i.e. once `nabu.selection` reflects it:
1149
+ * `await nabu.focus(...)` before `exec(...)` / typing. Fire-and-forget callers are unaffected.
1150
+ * @param {{from?: {offset?: number, block?: Block}, to?: {offset?: number, block?: Block}, offset?: number}} [options]
1151
+ * @returns {Promise<void>}
1152
+ * @public
1153
+ */
423
1154
  focus(options) {
424
- tick().then(() => {
1155
+ return tick().then(() => {
425
1156
  const sel = this.selection;
426
1157
 
427
1158
  const {offset: fromOffset, block: fromBlock} = options?.from?.block ?
@@ -440,17 +1171,90 @@ export class Nabu {
440
1171
  this.warn('Resolved DOM points:', fromPoint, toPoint);
441
1172
  if (fromPoint && toPoint) this.selection.setBaseAndExtent(fromPoint.node, fromPoint.offset, toPoint.node, toPoint.offset);
442
1173
  }
443
- })
1174
+ });
1175
+ }
444
1176
 
1177
+ /**
1178
+ * The deepest last block of the document that can hold a caret in the rendered document: follows
1179
+ * the last child at each level, but never enters a block that hides its children.
1180
+ * @returns {Block | null}
1181
+ * @public
1182
+ */
1183
+ get lastVisibleBlock() {
1184
+ /** @type {any} */
1185
+ let block = this.children[this.children.length - 1] ?? null;
1186
+ while (block) {
1187
+ /** @type {Block[] | undefined} */
1188
+ const kids = block.children;
1189
+ if (!kids?.length || block.hidesChildren) break;
1190
+ block = kids[kids.length - 1];
1191
+ }
1192
+ return block;
445
1193
  }
446
1194
 
1195
+ #openingTrailingCaret = false;
1196
+
447
1197
  /**
448
- * Insère un nouveau bloc dans le document
449
- * @param {string} type - Le type du bloc (ex: 'paragraph')
450
- * @param {Object} [props={}] - Les propriétés initiales
451
- * @param {string|null} [parentId=null] - ID du parent (null pour racine)
452
- * @param {number|null} [index=null] - Position dans la liste des enfants
453
- */
1198
+ * The document must always offer a caret after its last block. Call it on user intent (ArrowDown /
1199
+ * ArrowRight leaving the document, a click below the last block): when the last block holds text, the
1200
+ * caret goes to its end; when it does not (a void block such as a divider / image, or a container
1201
+ * whose end is not a text position), an empty default text block is appended at the root, in one
1202
+ * undo step, and takes the caret. Never called eagerly on load.
1203
+ * @returns {Promise<Block | null>} The block now holding the caret
1204
+ * @public
1205
+ */
1206
+ async openTrailingCaret() {
1207
+ if (this.#openingTrailingCaret) return null;
1208
+ const last = this.lastVisibleBlock;
1209
+ if (!last) return null;
1210
+ this.#openingTrailingCaret = true;
1211
+ try {
1212
+ /** @type {Block | null | undefined} */
1213
+ let target = last;
1214
+ let offset = last.behaviors?.get('text')?.text?.length ?? 0;
1215
+ if (!last.behaviors?.has('text')) {
1216
+ const type = this.defaultBlockType;
1217
+ if (!type || !this.registry.has(type)) return null;
1218
+ const created = this.insert(type, {}, null, this.children.length);
1219
+ await this.commit();
1220
+ target = this.blocks.get(created.id);
1221
+ offset = 0;
1222
+ }
1223
+ if (!target) return null;
1224
+ await tick();
1225
+ this.selection.setCursor(target, offset);
1226
+ return target;
1227
+ } finally {
1228
+ this.#openingTrailingCaret = false;
1229
+ }
1230
+ }
1231
+
1232
+ /**
1233
+ * Mouse down on the editor itself (not on a block): below the last block, that block is a void →
1234
+ * put a caret after it (see `openTrailingCaret`).
1235
+ * @param {MouseEvent} e
1236
+ */
1237
+ handleMousedown(e) {
1238
+ this.rearmTab();
1239
+ if (this.#readonly) return;
1240
+ if (e.button !== 0 || e.defaultPrevented || e.target !== e.currentTarget) return;
1241
+ const last = this.lastVisibleBlock;
1242
+ const lastEl = /** @type {HTMLElement | null} */ (last?.element);
1243
+ if (!last || last.behaviors?.has('text') || !lastEl?.isConnected) return;
1244
+ if (e.clientY <= lastEl.getBoundingClientRect().bottom) return;
1245
+ this.openTrailingCaret(); // overrides the native caret the click leaves on the root
1246
+
1247
+ }
1248
+
1249
+ /**
1250
+ * Insert a new block of a registered type and commit (throws when the type is not registered).
1251
+ * @param {string} type - Block type (`'paragraph'`, or the name of an extension that declares a `block`)
1252
+ * @param {Record<string, any>} [props] - Initial props, read by the class's `static create` (`text`, `delta`...)
1253
+ * @param {string | null} [parentId] - Id of the parent block (`null`: the document root)
1254
+ * @param {number | null} [index] - Position among the siblings (`null`: last)
1255
+ * @returns {Block} The created block
1256
+ * @public
1257
+ */
454
1258
  insert(type, props = {}, parentId = null, index = null) {
455
1259
 
456
1260
  const BlockClass = this.registry.get(type);
@@ -467,7 +1271,11 @@ export class Nabu {
467
1271
 
468
1272
 
469
1273
 
470
- /** @param {Block} block */
1274
+ /**
1275
+ * Delete a block (and its children) from the tree. No commit: call `commit()` afterwards.
1276
+ * @param {Block} block
1277
+ * @public
1278
+ */
471
1279
  delete(block) {
472
1280
  this.deleteNode(block.node.id);
473
1281
  }
@@ -497,8 +1305,12 @@ export class Nabu {
497
1305
  const sel = this.selection;
498
1306
  if (!sel.anchorBlock || !sel.focusBlock) return;
499
1307
 
500
- // 1. Essayer les hooks globaux d'extension d'abord
501
- if (hookName) {
1308
+ // 1. Essayer les hooks globaux d'extension d'abord.
1309
+ // Un bloc `transformsEnabled === false` (code, callout, toggle…) ne se laisse pas transformer
1310
+ // par la frappe (raccourcis markdown `# `, `> `, ``` …) : on saute les hooks sur les insertions
1311
+ // (les hooks de suppression — sortie de bloc, garde-fous — tournent toujours) et la frappe
1312
+ // continue comme du texte normal. Même règle que TextBehavior.handleBeforeInput.
1313
+ if (hookName && !(hookName === 'onBeforeInput' && isTransformInput(e) && sel.anchorBlock.transformsEnabled === false)) {
502
1314
  const hooks = this.hooks.get(hookName) || [];
503
1315
  for (const hook of hooks) {
504
1316
  const handled = hook(this, e, sel.anchorBlock);
@@ -530,12 +1342,22 @@ export class Nabu {
530
1342
 
531
1343
  /** @param {InputEvent} e */
532
1344
  handleBeforeinput(e) {
1345
+ if (this.#readonly) { e.preventDefault(); return; } // nothing is typed, deleted, pasted or dropped in a read-only editor
1346
+ this.selection.sync(); // selectionchange is async: don't act on a stale caret
533
1347
  // Ne pas interférer avec la composition IME en cours : le navigateur
534
1348
  // doit pouvoir muter librement le text node (insertCompositionText
535
1349
  // n'est de toute façon pas annulable). Sync dans Loro à compositionend.
536
1350
  if (this.#composing && (e.inputType === 'insertCompositionText' || e.inputType === 'deleteCompositionText')) {
537
1351
  return;
538
1352
  }
1353
+ // Any other input while a composition runs (a real Enter that the IME did not swallow, a paste, a delete…): the model
1354
+ // does not hold the composing text yet, so acting on it would use a stale offset (P-102). It is ignored; the composition
1355
+ // goes on and its commit (compositionend) follows. Never throws, `composing` is only ever reset by compositionend.
1356
+ if (this.#composing) {
1357
+ e.preventDefault();
1358
+ return;
1359
+ }
1360
+ this.selection.normalize(); // a caret on a dead position (void block, wrapper…) must not swallow the keystroke
539
1361
  e.preventDefault(); // Toujours bloquer les mutations natives
540
1362
  this.dispatchEventToSelection('beforeinput', e, 'onBeforeInput');
541
1363
  }
@@ -548,17 +1370,57 @@ export class Nabu {
548
1370
  * @param {CompositionEvent} e
549
1371
  */
550
1372
  handleCompositionStart(e) {
1373
+ if (this.#readonly) return;
1374
+ this.selection.sync();
1375
+ // A second compositionstart in the SAME block while one runs (Chrome silently restarts a composition when a script
1376
+ // rewrites its text node, e.g. a programmatic edit of the block: no compositionend in between): the first start is the
1377
+ // one that counts, its Loro-cursor anchor already follows the edit.
1378
+ if (this.#composing && this.#compositionStartBlock && this.#compositionStartBlock === this.selection.anchorBlock) return;
1379
+ // A composition over a selection replaces it (P-98 / P-99): the range is deleted through the MODEL first, rendered, and the
1380
+ // caret put at the junction, BEFORE the browser starts mutating the DOM (it would otherwise merge the blocks natively and
1381
+ // leave the model untouched). The deletion and the composed text are one undo step (see #compositionGroup).
1382
+ if (!this.selection.isCollapsed) this.#replaceSelectionForComposition();
551
1383
  this.#composing = true;
552
1384
  const anchor = this.selection.anchorBlock;
553
1385
  if (!anchor) {
554
1386
  this.#compositionStartBlock = null;
555
1387
  this.#compositionStartOffset = null;
1388
+ this.#compositionAnchor = null;
1389
+ this.#endCompositionGroup();
556
1390
  return;
557
1391
  }
558
1392
  const behavior = anchor.behaviors?.get('text');
559
1393
  const sel = behavior?.selection;
560
1394
  this.#compositionStartBlock = anchor;
561
1395
  this.#compositionStartOffset = sel?.from ?? 0;
1396
+ this.#compositionAnchor = behavior ? makeEndpoint(anchor, sel?.from ?? 0, 'end') : null;
1397
+ this.#composingBlock = anchor;
1398
+ /** @type {any} */ (behavior)?.snapshotForComposition?.();
1399
+ }
1400
+
1401
+ /**
1402
+ * Delete the selected range (one block or several, isolated fields honoured: exactly what typing a character over it does,
1403
+ * see {@link deleteRange}) and leave a collapsed caret at the junction, with the DOM rendered synchronously.
1404
+ * Undo: the deletion opens an undo group that the end of the composition closes, so "replace the selection with the composed
1405
+ * text" is ONE step; a composition canceled right away leaves the deletion as its own step.
1406
+ */
1407
+ #replaceSelectionForComposition() {
1408
+ const range = selectionRange(this);
1409
+ if (!range) return;
1410
+ try { this.undoManager.groupStart(); this.#compositionGroup = true; } catch { this.#compositionGroup = false; }
1411
+ const junction = deleteRange(this, range);
1412
+ if (!junction) { this.#endCompositionGroup(); return; }
1413
+ this.commit(); // the Loro transaction (and its undo step) is made synchronously; the await is only the render
1414
+ flushSync(); // the DOM matches the model before the browser starts the composition
1415
+ const block = this.blocks.get(junction.block.id) ?? junction.block;
1416
+ this.selection.setCursor(block, junction.offset);
1417
+ this.selection.sync();
1418
+ }
1419
+
1420
+ #endCompositionGroup() {
1421
+ if (!this.#compositionGroup) return;
1422
+ this.#compositionGroup = false;
1423
+ try { this.undoManager.groupEnd(); } catch { /* the group already ended (remote import) */ }
562
1424
  }
563
1425
 
564
1426
  /**
@@ -574,11 +1436,33 @@ export class Nabu {
574
1436
  * @param {CompositionEvent} e
575
1437
  */
576
1438
  handleCompositionEnd(e) {
1439
+ if (this.#readonly && !this.#composing) return;
577
1440
  this.#composing = false;
1441
+ const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
1442
+ const composedBlock = this.#compositionStartBlock;
1443
+ this.#composingBlock = null;
1444
+ /** @type {any} */ (composedIn)?.restoreAfterComposition?.(e.data || ''); // before the model catches up: no duplicate of the composed text
1445
+ try {
1446
+ this.#syncComposition(e);
1447
+ } finally {
1448
+ this.#endCompositionGroup();
1449
+ }
1450
+ this.selection.normalize(); // a dead caret must not survive the composition
1451
+ // A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
1452
+ if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
1453
+ this.selection.setCursor(composedBlock, 0);
1454
+ tick().then(() => { if (!this.#composing && composedBlock.element?.isConnected && !composedIn?.text) this.selection.setCursor(composedBlock, 0); });
1455
+ }
1456
+ }
1457
+
1458
+ /** @param {CompositionEvent} e */
1459
+ #syncComposition(e) {
578
1460
  const block = this.#compositionStartBlock;
579
- const startOffset = this.#compositionStartOffset;
1461
+ let startOffset = this.#compositionStartOffset;
1462
+ const anchor = this.#compositionAnchor;
580
1463
  this.#compositionStartBlock = null;
581
1464
  this.#compositionStartOffset = null;
1465
+ this.#compositionAnchor = null;
582
1466
  if (!block || startOffset === null) return;
583
1467
 
584
1468
  // The block may have been destroyed/replaced during the composition
@@ -595,30 +1479,128 @@ export class Nabu {
595
1479
  const composedText = e.data || '';
596
1480
  if (!composedText) return;
597
1481
 
1482
+ // Where the composition began NOW: the Loro cursors followed every edit of this text made meanwhile (P-101).
1483
+ if (anchor) {
1484
+ const moved = resolveOffset(this.doc, anchor, behavior.container.length);
1485
+ if (moved !== null) startOffset = moved;
1486
+ }
1487
+ startOffset = Math.max(0, Math.min(startOffset, behavior.container.length));
1488
+
598
1489
  behavior.insert(startOffset, composedText);
599
1490
  block.commit();
1491
+ const caret = startOffset + composedText.length;
600
1492
  tick().then(() => {
601
- this.selection.setCursor(block, startOffset + composedText.length);
1493
+ this.selection.setCursor(block, caret);
602
1494
  });
603
1495
  }
604
1496
 
605
1497
  /** @param {KeyboardEvent} e */
606
1498
  handleKeydown(e) {
607
- // Undo: Ctrl+Z or Cmd+Z (without Shift)
608
- if ((e.ctrlKey || e.metaKey) && e.key === 'z' && !e.shiftKey) {
1499
+ // Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
1500
+ if (this.#readonly) return;
1501
+ this.selection.sync(); // no-op when the document capture listener already synced
1502
+ this.selection.normalize();
1503
+ // The Escape-then-Tab way out of the `tab` option (utils/tab.js): any key but a lone modifier closes it, whoever handles the key.
1504
+ const escaped = this.#tabEscaped;
1505
+ if (!isModifierKey(e)) this.#tabEscaped = false;
1506
+ // Commands first (ADR 017): undo / redo and every declared shortcut. What no command handles falls through to the
1507
+ // legacy `onKeyDown` hooks and the block's own keydown, then to the native behavior.
1508
+ if (this.commands.handleKeydown(e)) return;
1509
+ if (this.#selectAll(e) || this.#landOnIsolated(e) || this.#jumpToEdge(e)) return;
1510
+
1511
+ this.dispatchEventToSelection('keydown', e, 'onKeyDown');
1512
+ // Tab / Shift+Tab that no command, hook or block took: the `tab` option decides (structural meanings come first).
1513
+ if (handleTabKey(this, e, escaped)) return;
1514
+ // An Escape that nothing consumed (slash menu, chooser, pending command, a block…) opens the way out for the next Tab.
1515
+ if (e.key === 'Escape' && !e.defaultPrevented && !e.ctrlKey && !e.altKey && !e.metaKey && !e.shiftKey) this.#tabEscaped = true;
1516
+ }
1517
+
1518
+ /**
1519
+ * Ctrl / Cmd + A when the document holds ISOLATED text fields (`Block#isolatesSelection`, e.g. region titles). Inside one it
1520
+ * selects exactly that field's text (like an input); elsewhere it selects the text of the document from the first to the last
1521
+ * block that is not isolated (the isolated fields are left out of the selection, as of any range). A document without
1522
+ * isolated block keeps the browser's own Select All.
1523
+ * @param {KeyboardEvent} e
1524
+ * @returns {boolean} Whether the key was handled
1525
+ */
1526
+ #selectAll(e) {
1527
+ if (!(e.ctrlKey || e.metaKey) || e.shiftKey || e.altKey || typeof e.key !== 'string' || e.key.toLowerCase() !== 'a') return false;
1528
+ if (e.isComposing || this.#composing) return false;
1529
+ const sel = this.selection;
1530
+ const inside = sel.anchorBlock;
1531
+ if (inside?.isolatesSelection && sel.focusBlock === inside) {
609
1532
  e.preventDefault();
610
- this.undo();
611
- return;
1533
+ sel.selectBlockText(inside);
1534
+ return true;
612
1535
  }
1536
+ const texts = textBlocksInOrder(this, { visible: true });
1537
+ if (!texts.some((b) => b.isolatesSelection)) return false;
1538
+ e.preventDefault();
1539
+ const plain = texts.filter((b) => !b.isolatesSelection && b.element);
1540
+ const first = plain[0];
1541
+ const last = plain.at(-1);
1542
+ if (first && last) sel.selectBetween(first, last);
1543
+ return true;
1544
+ }
1545
+
1546
+ /**
1547
+ * Ctrl / Cmd + End and Ctrl / Cmd + Home (with Shift: extend the selection) in a LARGE document (`LARGE_DOC` blocks, whose
1548
+ * off-screen parts the browser skips, see `blocks/chunks.js`). The browser moves the caret to the end of what it has laid out, and
1549
+ * a skipped part has none: it would stop short of the real end. The caret goes to the end of the last text block (the start of
1550
+ * the first) of the model instead, and the page scrolls to it. A smaller document keeps the browser's own key.
1551
+ * @param {KeyboardEvent} e
1552
+ * @returns {boolean} Whether the key was handled
1553
+ */
1554
+ #jumpToEdge(e) {
1555
+ if (!(e.ctrlKey || e.metaKey) || e.altKey || (e.key !== 'End' && e.key !== 'Home')) return false;
1556
+ if (e.isComposing || this.#composing || this.blocks.size < LARGE_DOC) return false;
1557
+ const texts = textBlocksInOrder(this, { visible: true });
1558
+ const toEnd = e.key === 'End';
1559
+ const target = toEnd ? texts[texts.length - 1] : texts[0];
1560
+ const point = target?.element ? /** @type {any} */ (target).getDOMPoint?.(toEnd ? (target.behaviors?.get('text')?.text.length ?? 0) : 0) : null;
1561
+ if (!target || !point) return false;
1562
+ e.preventDefault();
1563
+ const live = typeof window !== 'undefined' ? window.getSelection() : null;
1564
+ const anchor = e.shiftKey && live?.anchorNode && this.selection.owns(live.anchorNode) ? { node: live.anchorNode, offset: live.anchorOffset } : point;
1565
+ this.selection.setBaseAndExtent(anchor.node, anchor.offset, point.node, point.offset);
1566
+ // The skipped parts above take their real height as they are shown: reveal again once the layout has settled.
1567
+ revealFocus(target);
1568
+ requestAnimationFrame(() => requestAnimationFrame(() => { if (target.element?.isConnected) revealFocus(target); }));
1569
+ return true;
1570
+ }
613
1571
 
614
- // Redo: Ctrl+Y, Cmd+Y, or Ctrl+Shift+Z, Cmd+Shift+Z
615
- if ((e.ctrlKey || e.metaKey) && (e.key === 'y' || (e.key === 'z' && e.shiftKey))) {
1572
+ /**
1573
+ * Arrow keys at the edge of an ISOLATED text field (`Block#isolatesSelection`): a field is entered at its START going down /
1574
+ * right and at its END going up / left, whatever the column the caret had, and ArrowDown / ArrowRight at the end of a field
1575
+ * goes to the start of the next text. Only a collapsed caret at the very end (down / right) or start (up / left) of its
1576
+ * block is concerned; anywhere else the browser moves the caret as usual.
1577
+ * @param {KeyboardEvent} e
1578
+ * @returns {boolean} Whether the key was handled
1579
+ */
1580
+ #landOnIsolated(e) {
1581
+ if (e.ctrlKey || e.metaKey || e.altKey || e.shiftKey || e.isComposing || this.#composing) return false;
1582
+ const down = e.key === 'ArrowDown' || e.key === 'ArrowRight';
1583
+ if (!down && e.key !== 'ArrowUp' && e.key !== 'ArrowLeft') return false;
1584
+ const sel = this.selection;
1585
+ const block = sel.anchorBlock;
1586
+ const text = block?.behaviors?.get('text');
1587
+ const caret = block?.selection;
1588
+ if (!block || !text || !sel.isCollapsed || !caret || caret.from !== caret.to) return false;
1589
+ const hasText = (/** @type {Block} */ b) => !!b.behaviors?.has('text');
1590
+ if (down) {
1591
+ if (caret.to !== text.text.length) return false;
1592
+ const next = block.findForward(hasText);
1593
+ if (!next || !(next.isolatesSelection || block.isolatesSelection)) return false;
616
1594
  e.preventDefault();
617
- this.redo();
618
- return;
1595
+ sel.setCursor(next, 0);
1596
+ } else {
1597
+ if (caret.from !== 0) return false;
1598
+ const previous = block.findBackward(hasText);
1599
+ if (!previous?.isolatesSelection) return false;
1600
+ e.preventDefault();
1601
+ sel.setCursor(previous, previous.behaviors.get('text').text.length);
619
1602
  }
620
-
621
- this.dispatchEventToSelection('keydown', e, 'onKeyDown');
1603
+ return true;
622
1604
  }
623
1605
 
624
1606
  /** @param {InputEvent} e */
@@ -634,12 +1616,24 @@ export class Nabu {
634
1616
 
635
1617
  /** @param {ClipboardEvent} e */
636
1618
  handleCopy(e) {
1619
+ this.selection.sync();
637
1620
  if (this.selection.isCollapsed) return;
638
1621
  e.preventDefault();
1622
+ if (!e.clipboardData) return;
1623
+ this.#writeSelection(e.clipboardData);
1624
+ }
639
1625
 
1626
+ /**
1627
+ * Serialize the current (non-collapsed) selection into `dt`: `application/x-nabu+json` (the fragment, with the bytes of
1628
+ * the stored media), `text/plain` (raw text for one text block, markdown otherwise) and `text/html`. Shared by copy / cut
1629
+ * (the clipboard) and by the drag of a text selection.
1630
+ * @param {DataTransfer} dt
1631
+ * @returns {boolean} False when there is nothing to serialize
1632
+ */
1633
+ #writeSelection(dt) {
640
1634
  const startBlock = this.selection.startBlock;
641
1635
  const endBlock = this.selection.endBlock;
642
- if (!startBlock || !endBlock || !e.clipboardData) return;
1636
+ if (!startBlock || !endBlock) return false;
643
1637
 
644
1638
  const startFrom = this.selection.start?.from ?? 0;
645
1639
  const endTo = this.selection.end?.to ?? null;
@@ -661,10 +1655,10 @@ export class Nabu {
661
1655
  } else {
662
1656
  const startRoot = findDirectChildOf(startBlock, this);
663
1657
  const endRoot = findDirectChildOf(endBlock, this);
664
- if (!startRoot || !endRoot) return;
1658
+ if (!startRoot || !endRoot) return false;
665
1659
  const si = this.children.indexOf(startRoot);
666
1660
  const ei = this.children.indexOf(endRoot);
667
- if (si === -1 || ei === -1) return;
1661
+ if (si === -1 || ei === -1) return false;
668
1662
  rootBlocks = this.children.slice(si, ei + 1);
669
1663
  }
670
1664
  }
@@ -683,6 +1677,7 @@ export class Nabu {
683
1677
  startFrom: isFirst ? startFrom : 0,
684
1678
  endBlock: isLast ? endBlock : null,
685
1679
  endTo: isLast ? endTo : null,
1680
+ textOnly: true, // a text selection: isolated fields (region titles) and their containers are not copied
686
1681
  });
687
1682
  }
688
1683
 
@@ -692,20 +1687,30 @@ export class Nabu {
692
1687
  to: isLast ? endTo : null,
693
1688
  partial: isFirst && isLast ? 'both' : isFirst ? 'start' : isLast ? 'end' : false,
694
1689
  });
695
- }).filter(Boolean);
1690
+ }).flat().filter(Boolean); // an isolating container returns its selected children directly (an array)
696
1691
 
697
- if (!pasteBlocks.length) return;
1692
+ if (!pasteBlocks.length) return false;
698
1693
 
699
- const fragment = { blocks: pasteBlocks };
700
- e.clipboardData.setData('application/x-nabu+json', JSON.stringify(fragment));
1694
+ // Media stored in the document (`nabu-asset:` refs) is meaningless in another document: its bytes travel in the
1695
+ // fragment (`assets`), the blocks keep their ref. Outside Nabu (html / plain) such a ref is replaced, never leaked.
1696
+ const files = Files.get(this);
1697
+ const assets = files.embedAssets(pasteBlocks);
1698
+ const fragment = { version: CLIPBOARD_FORMAT_VERSION, blocks: pasteBlocks, ...(assets ? { assets } : {}) };
1699
+ dt.setData('application/x-nabu+json', JSON.stringify(fragment));
701
1700
 
702
1701
  // Recursive serializers — dispatch to each BlockClass's static toMarkdown/toHtml.
703
- // helpers.recurse lets blocks serialize their children without knowing their types.
1702
+ // helpers.recurse lets blocks serialize a child without knowing its type; helpers.recurseAll serializes a list of
1703
+ // siblings in order, telling each one the siblings before it (`before`) and after it (`after`): a block may depend on
1704
+ // its neighbours (adjacent lists must not read back as one; a block that closes only when something follows it).
704
1705
  /** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
705
1706
  const pbToMarkdown = (pb, ctx = {}) => {
706
1707
  const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
707
1708
  if (BlockClass?.toMarkdown) {
708
- return BlockClass.toMarkdown(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToMarkdown(child, { ...ctx, ...childCtx }) });
1709
+ return BlockClass.toMarkdown(pb, {
1710
+ ...ctx,
1711
+ recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToMarkdown(child, { ...ctx, before: [], after: [], ...childCtx }),
1712
+ recurseAll: (/** @type {any[]} */ children, /** @type {any} */ childCtx) => children.map((child, k) => pbToMarkdown(child, { ...ctx, ...childCtx, before: children.slice(0, k), after: children.slice(k + 1) })),
1713
+ });
709
1714
  }
710
1715
  return (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
711
1716
  };
@@ -717,18 +1722,27 @@ export class Nabu {
717
1722
  return BlockClass.toHtml(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToHtml(child, { ...ctx, ...childCtx }) });
718
1723
  }
719
1724
  const text = (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
720
- return text ? `<p>${text}</p>` : '';
1725
+ return text ? `<p>${escapeHtml(text)}</p>` : ''; // unknown block type: escaped, never raw
721
1726
  };
722
1727
 
723
- e.clipboardData.setData('text/plain', pasteBlocks.map(pb => pbToMarkdown(pb)).join('\n\n'));
724
- e.clipboardData.setData('text/html', pasteBlocks.map(pb => pbToHtml(pb)).join('\n'));
725
-
1728
+ // text/plain: a selection inside ONE text block is its raw selected text (no markdown syntax: no `**`, fences,
1729
+ // `# `, `- `); several blocks -> markdown.
1730
+ const single = pasteBlocks.length === 1 && startBlock === endBlock && !pasteBlocks[0].children?.length && Array.isArray(pasteBlocks[0].delta)
1731
+ ? pasteBlocks[0] : null;
1732
+ const plain = single
1733
+ ? /** @type {any[]} */ (single.delta).map(op => typeof op.insert === 'string' ? op.insert : '').join('')
1734
+ : files.externalize(pasteBlocks).map((pb, k, all) => pbToMarkdown(pb, { before: all.slice(0, k), after: all.slice(k + 1) })).join('\n\n');
1735
+ dt.setData('text/plain', plain);
1736
+ dt.setData('text/html', files.externalize(pasteBlocks, { inline: true }).map(pb => pbToHtml(pb)).join('\n'));
1737
+ return true;
726
1738
  }
727
1739
 
728
1740
  /** @param {ClipboardEvent} e */
729
1741
  handleCut(e) {
1742
+ this.selection.sync();
730
1743
  if (this.selection.isCollapsed) return;
731
1744
  e.preventDefault();
1745
+ if (this.#readonly) { this.handleCopy(e); return; } // cutting a read-only text copies it and removes nothing
732
1746
 
733
1747
  // 1. Copy selection to clipboard
734
1748
  this.handleCopy(e);
@@ -737,25 +1751,58 @@ export class Nabu {
737
1751
  const result = deleteSelectionContent(this, this);
738
1752
  if (!result) return;
739
1753
 
740
- // 3. Single Loro transaction + restore cursor
741
- this.commit();
742
- this.selection.setCursor(result.block, result.offset);
1754
+ // 3. Single Loro transaction (its own undo step, like a structural op) + restore cursor. The caret is placed
1755
+ // once the commit has re-rendered the text: set earlier, the DOM node it points into is replaced.
1756
+ this.#isolateNextCommits();
1757
+ this.commit().then(() => this.selection.setCursor(this.blocks.get(result.block.id) ?? result.block, result.offset));
743
1758
  }
744
1759
 
745
1760
  /** @param {ClipboardEvent} e */
746
1761
  handlePaste(e) {
747
1762
  e.preventDefault();
1763
+ if (this.#readonly) return;
1764
+ this.selection.sync();
748
1765
  const clipboard = e.clipboardData;
749
1766
  if (!clipboard) return;
1767
+ this.#insertTransfer(clipboard, null);
1768
+ }
750
1769
 
1770
+ /**
1771
+ * THE pipeline that turns a `DataTransfer` (the clipboard of a paste, the payload of a drop) into content: files become
1772
+ * the blocks their file handlers make of them, text goes to the verbatim buffer of a `pastesAsPlainText` block, else the
1773
+ * first paste interpreter (internal fragment, HTML, markdown, plain text) that reads the payload makes the fragment.
1774
+ * One undo step. `at` is where it lands: null = at the caret (a paste), else a drop position.
1775
+ * @param {DataTransfer} clipboard
1776
+ * @param {DropPosition | null} at
1777
+ */
1778
+ #insertTransfer(clipboard, at) {
751
1779
  const sorted = [...this.#pasteInterpreters].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
752
1780
 
1781
+ // Files on the clipboard (a screenshot, a file copied from the OS) win over its text payloads: each one becomes the
1782
+ // block their file handler makes of it. Except an internal copy (`application/x-nabu+json` already holds the blocks,
1783
+ // and their bytes), and a text payload that declares itself worth more (a spreadsheet range comes with an image of it).
1784
+ const planned = this.#planPastedFiles(clipboard, sorted);
1785
+
1786
+ // A block with `pastesAsPlainText` (code…) is a verbatim buffer: take the clipboard text as-is,
1787
+ // before any interpreter (markdown / HTML / nabu JSON) gets a chance to split it into blocks.
1788
+ const target = at ? (at.side === 'inside' ? at.block : null) : this.selection.anchorBlock;
1789
+ if (target && (at || target === this.selection.focusBlock) && target.pastesAsPlainText) {
1790
+ const text = clipboard.getData('text/plain');
1791
+ if (text) { this.#pasteVerbatim(target, text, at ? at.offset : undefined); return; }
1792
+ if (!planned.length) return;
1793
+ }
1794
+
1795
+ if (planned.length) {
1796
+ this.#pasteFiles(planned, at);
1797
+ return;
1798
+ }
1799
+
753
1800
  for (const interpreter of sorted) {
754
1801
  const raw = clipboard.getData(interpreter.format);
755
1802
  if (!raw) continue;
756
1803
  const fragment = interpreter.interpret(raw, this);
757
1804
  if (fragment) {
758
- this.insertFragment(fragment);
1805
+ this.insertFragment(fragment, at ? { at } : undefined);
759
1806
  return;
760
1807
  }
761
1808
  }
@@ -764,17 +1811,358 @@ export class Nabu {
764
1811
  }
765
1812
 
766
1813
  /**
767
- * Insère un PasteFragment à la position du curseur courant.
1814
+ * The files of a paste event that an extension's `pasteFileHandlers` takes, with the block each one becomes. Empty when
1815
+ * the paste is not a file paste (no file, no handler accepting one, an internal copy, a text payload that outranks them).
1816
+ * @param {DataTransfer} clipboard
1817
+ * @param {import('../utils/extensions.js').PasteInterpreter[]} interpreters
1818
+ * @returns {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>}
1819
+ */
1820
+ #planPastedFiles(clipboard, interpreters) {
1821
+ if (!this.#pasteFileHandlers.length) return [];
1822
+ /** @type {File[]} */
1823
+ let files = [...(clipboard.files ?? [])];
1824
+ if (!files.length) {
1825
+ files = [...(clipboard.items ?? [])].filter((item) => item.kind === 'file').map((item) => item.getAsFile()).filter((f) => !!f);
1826
+ }
1827
+ if (!files.length) return [];
1828
+ if (clipboard.getData('application/x-nabu+json')) return [];
1829
+ for (const interpreter of interpreters) {
1830
+ if (!interpreter.outranksFiles) continue;
1831
+ const raw = clipboard.getData(interpreter.format);
1832
+ if (raw && interpreter.outranksFiles(raw)) return [];
1833
+ }
1834
+ /** @type {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>} */
1835
+ const planned = [];
1836
+ for (const file of files) {
1837
+ for (const handler of this.#pasteFileHandlers) {
1838
+ let block = null;
1839
+ try { if (handler.accepts(file, this)) block = handler.block(file, this); } catch (error) { this.warn('paste: a file handler failed: ' + error); }
1840
+ if (block) { planned.push({ file, block }); break; }
1841
+ }
1842
+ }
1843
+ return planned;
1844
+ }
1845
+
1846
+ /**
1847
+ * Insert the blocks made of pasted files, at the caret, in order. The files are hashed and stored first (`Files#stage`),
1848
+ * then ONE `insertFragment` does the rest like any other paste: the blocks hold the hash refs (`pending` while a host's
1849
+ * `onBeforePersist` uploads the file, `rejected` for a file over `files.maxFileSize`); a single undo step.
1850
+ * @param {Array<{ file: File, block: import('../utils/extensions.js').PasteBlock }>} planned
1851
+ * @param {DropPosition | null} [at] where the blocks land (a drop); null = at the caret (a paste)
1852
+ */
1853
+ async #pasteFiles(planned, at = null) {
1854
+ const files = Files.get(this);
1855
+ // Staging is asynchronous: a drop position is followed through concurrent edits (Loro cursor), not re-read as an offset.
1856
+ const resolveAt = at ? this.#followPosition(at) : null;
1857
+ /** @type {import('../utils/extensions.js').PasteBlock[]} */
1858
+ const blocks = [];
1859
+ /** @type {Record<string, import('../files/files.svelte.js').EmbeddedAsset>} */
1860
+ const assets = {};
1861
+ for (const { file, block } of planned) {
1862
+ try {
1863
+ const staged = await files.stage(file);
1864
+ blocks.push({ ...block, props: { ...block.props, ref: staged.ref, ...staged.props }, partial: false });
1865
+ if (staged.asset) assets[staged.id] = staged.asset;
1866
+ } catch (error) {
1867
+ this.warn(`paste: could not read file "${file.name}": ${error}`);
1868
+ }
1869
+ }
1870
+ if (!blocks.length) return;
1871
+ const where = resolveAt ? resolveAt() : null;
1872
+ this.insertFragment({ blocks, assets }, where ? { at: where } : undefined);
1873
+ }
1874
+
1875
+ /**
1876
+ * Insert `text` verbatim at the caret of `block`, replacing its selection: no interpretation, no new
1877
+ * block. One undo step (isolated commit).
1878
+ * @param {Block} block
1879
+ * @param {string} text
1880
+ * @param {number} [offset] insert here instead of replacing the selection (a drop)
1881
+ */
1882
+ #pasteVerbatim(block, text, offset) {
1883
+ const behavior = block.behaviors?.get('text');
1884
+ const sel = offset === undefined ? behavior?.selection : { from: offset, to: offset };
1885
+ if (!behavior || !sel) return;
1886
+ const from = Math.min(sel.from, sel.to);
1887
+ const to = Math.max(sel.from, sel.to);
1888
+ if (to > from) behavior.delete({ index: from, length: to - from });
1889
+ behavior.insert(from, text);
1890
+ this.#isolateNextCommits();
1891
+ this.commit();
1892
+ tick().then(() => this.selection.setCursor(this.blocks.get(block.id) || block, from + text.length));
1893
+ }
1894
+
1895
+ // DRAG & DROP (ADR 014, lot 4)
1896
+ //
1897
+ // The browser never edits the document: every `dragover` / `drop` over the editor is taken here, whatever it carries.
1898
+ // What is dropped goes through the SAME pipeline as a paste (`#insertTransfer`: files → media blocks, then the paste
1899
+ // interpreters), at the model position under the pointer. The editor's own text selection can be dragged: it is a MOVE.
1900
+ // (The block drag handle — `ui/DragHandle.svelte` — uses pointer events, not HTML5 DnD: the two never meet.)
1901
+
1902
+ /**
1903
+ * Where the drop would land while something is dragged over the editor, `null` otherwise (left, dropped, cancelled, or
1904
+ * nothing the editor can take). Reactive state for a UI: Nabu itself draws nothing.
1905
+ * - `block` / `offset` / `side`: a caret position in the text of `block` (`side: 'inside'`, `offset` in its text), or
1906
+ * beside a block that holds no text (image, divider…: `side: 'before' | 'after'`, by the pointer's half).
1907
+ * - `kind`: `'files'` (OS files → media blocks), `'content'` (text / HTML / markdown / Nabu fragment from outside, or a
1908
+ * copy of the editor's own selection), `'move'` (the editor's own selection being moved). Decided from the drag's
1909
+ * declared types: a drag that mixes files and text resolves as it does for a paste (files win) at the drop.
1910
+ * @type {DropTarget | null}
1911
+ */
1912
+ dropTarget = $state.raw(null);
1913
+
1914
+ /**
1915
+ * The text selection being dragged out of this editor (set by `handleDragStart`, until the drop / dragend).
1916
+ * @type {{ token: string, range: import('./container.utils.js').DeletionRange } | null}
1917
+ */
1918
+ #dragSource = null;
1919
+
1920
+ /** @param {DropTarget | null} target */
1921
+ #setDropTarget(target) {
1922
+ if (!sameTarget(this.dropTarget, target)) this.dropTarget = target;
1923
+ }
1924
+
1925
+ /** What this editor can take from a drag: the formats its interpreters read, whether it takes files. */
1926
+ #dropCaps() {
1927
+ return { formats: this.#pasteInterpreters.map((interpreter) => interpreter.format), files: this.#pasteFileHandlers.length > 0 };
1928
+ }
1929
+
1930
+ /**
1931
+ * Whether a drag event is for this editor's own content: not for a nested editor, a UI island or a form control
1932
+ * inside it (those keep their native behavior), and not during an IME composition.
1933
+ * @param {DragEvent} e
1934
+ */
1935
+ #ownsDrag(e) {
1936
+ const root = /** @type {HTMLElement | null} */ (e.currentTarget);
1937
+ const target = /** @type {Node | null} */ (e.target instanceof Node ? e.target : null);
1938
+ const el = target && (target.nodeType === Node.ELEMENT_NODE ? /** @type {Element} */ (target) : target.parentElement);
1939
+ if (!root || !el || this.#composing) return false;
1940
+ if (el.closest('[data-nabu-root]') !== root) return false;
1941
+ return !closestWithin(el, '[data-nabu-ui], input, textarea, select', root);
1942
+ }
1943
+
1944
+ /**
1945
+ * Start of a drag inside the editor. A drag of the TEXT SELECTION is serialized like a copy (internal fragment, plain text,
1946
+ * HTML — so it can also be dropped in another editor or application) and remembered: dropped back in the editor it is a
1947
+ * MOVE (see `dropAt`). Any other drag (an image, a link, a draggable element) is cancelled: the browser would hand a drop
1948
+ * its own serialization of the DOM node.
1949
+ * @param {DragEvent} e
1950
+ */
1951
+ handleDragStart(e) {
1952
+ this.#dragSource = null;
1953
+ this.#setDropTarget(null);
1954
+ if (!this.#ownsDrag(e) || !e.dataTransfer) return;
1955
+ const target = e.target;
1956
+ const draggedElement = target instanceof Element && !!target.closest('img, a[href], [draggable="true"]');
1957
+ this.selection.sync();
1958
+ const range = draggedElement || this.selection.isCollapsed ? null : selectionRange(this);
1959
+ const canMove = this.#pasteInterpreters.some((interpreter) => interpreter.format === NABU_FORMAT);
1960
+ if (!range || !canMove || !this.#writeSelection(e.dataTransfer)) {
1961
+ e.preventDefault();
1962
+ return;
1963
+ }
1964
+ const token = Math.random().toString(36).slice(2) + Date.now().toString(36);
1965
+ e.dataTransfer.setData(DRAG_MARKER, token);
1966
+ e.dataTransfer.effectAllowed = this.#readonly ? 'copy' : 'copyMove'; // read-only: the text can be dragged out, never moved
1967
+ this.#dragSource = { token, range };
1968
+ }
1969
+
1970
+ /**
1971
+ * `dragenter` / `dragover` over the editor: accept what it can take (cancelling the event is how a drop is allowed),
1972
+ * announce move vs copy, and publish the position in `dropTarget`.
1973
+ * @param {DragEvent} e
1974
+ */
1975
+ handleDragOver(e) {
1976
+ const dt = e.dataTransfer;
1977
+ if (!dt) return;
1978
+ if (this.#readonly) { this.#setDropTarget(null); dt.dropEffect = 'none'; return; } // not cancelled: nothing can be dropped
1979
+ if (!this.#ownsDrag(e)) { this.#setDropTarget(null); return; }
1980
+ const own = !!this.#dragSource && Array.from(dt.types ?? []).includes(DRAG_MARKER);
1981
+ const copy = own && wantsCopy(e);
1982
+ /** @type {DropKind | null} */
1983
+ const kind = own ? (copy ? 'content' : 'move') : transferKind(dt.types, this.#dropCaps());
1984
+ if (!kind) { this.#setDropTarget(null); dt.dropEffect = 'none'; return; }
1985
+ const root = /** @type {HTMLElement} */ (e.currentTarget);
1986
+ const position = resolveDropPosition(this, root, e.clientX, e.clientY);
1987
+ e.preventDefault(); // allows the drop
1988
+ if (kind === 'move' && position && this.#dragSource && positionInRange(this.#dragSource.range, position)) {
1989
+ dt.dropEffect = 'none'; // onto the dragged text itself: nothing to do
1990
+ this.#setDropTarget(null);
1991
+ return;
1992
+ }
1993
+ dt.dropEffect = pickDropEffect(dt.effectAllowed, kind === 'move' ? 'move' : 'copy');
1994
+ this.#setDropTarget(position ? { ...position, kind } : null);
1995
+ }
1996
+
1997
+ /** @param {DragEvent} e */
1998
+ handleDragLeave(e) {
1999
+ if (!this.#ownsDrag(e)) return;
2000
+ const root = /** @type {HTMLElement} */ (e.currentTarget);
2001
+ if (e.relatedTarget instanceof Node && root.contains(e.relatedTarget)) return; // still inside the editor
2002
+ this.#setDropTarget(null);
2003
+ }
2004
+
2005
+ /** The drag that started in this editor ended (dropped anywhere, or cancelled). @param {DragEvent} [e] */
2006
+ handleDragEnd(e) {
2007
+ this.#dragSource = null;
2008
+ this.#setDropTarget(null);
2009
+ }
2010
+
2011
+ /**
2012
+ * `drop` on the editor: the browser's default (inserting DOM nodes behind Loro's back, or navigating to a dropped
2013
+ * file) never happens. The position under the pointer is resolved, then {@link Nabu#dropAt} does the rest.
2014
+ * @param {DragEvent} e
2015
+ */
2016
+ handleDrop(e) {
2017
+ const dt = e.dataTransfer;
2018
+ if (!dt || !this.#ownsDrag(e)) return;
2019
+ e.preventDefault(); // the browser never navigates to a dropped file, read-only or not
2020
+ if (this.#readonly) { this.#dragSource = null; this.#setDropTarget(null); return; }
2021
+ const source = this.#dragSource;
2022
+ this.#dragSource = null;
2023
+ this.#setDropTarget(null);
2024
+ const root = /** @type {HTMLElement} */ (e.currentTarget);
2025
+ const position = resolveDropPosition(this, root, e.clientX, e.clientY) ?? documentEnd(this);
2026
+ if (!position) return;
2027
+ // The editor takes the focus (undo, typing…) even when the drop leaves no text caret to put in it (a dropped image).
2028
+ if (document.activeElement !== root) root.focus({ preventScroll: true });
2029
+ const own = !!source && dt.getData(DRAG_MARKER) === source.token;
2030
+ this.dropAt(dt, position, { source: own && !wantsCopy(e) ? source : null });
2031
+ }
2032
+
2033
+ /**
2034
+ * Drop `dt` at `position`, as ONE undo step, through the paste pipeline (files → media blocks, `pasteInterpreters`:
2035
+ * internal fragment, HTML, markdown, plain text; verbatim text into a `pastesAsPlainText` block).
2036
+ * With `opts.source` (the editor's own dragged selection) it is a MOVE: the source range is deleted and the content
2037
+ * inserted in the same transaction, the position corrected for the deletion; a position inside (or at the edge of) the
2038
+ * source range does nothing. Without it, content from outside — or a copy of the selection — is simply inserted.
2039
+ * @param {DataTransfer} dt
2040
+ * @param {DropPosition} position
2041
+ * @param {{ source?: { range: import('./container.utils.js').DeletionRange } | null }} [opts]
2042
+ */
2043
+ dropAt(dt, position, opts = {}) {
2044
+ if (this.#readonly) return;
2045
+ const source = opts.source ?? null;
2046
+ if (source) {
2047
+ const { range } = source;
2048
+ const alive = (/** @type {Block} */ b) => !!b && !b.node?.isDeleted?.() && this.blocks.get(b.id) === b;
2049
+ if (!alive(range.startBlock) || !alive(range.endBlock) || !alive(position.block)) return;
2050
+ if (positionInRange(range, position)) return;
2051
+ // Check the payload reads back BEFORE deleting anything: a move that cannot insert must not lose text.
2052
+ const reader = this.#pasteInterpreters.find((interpreter) => interpreter.format === NABU_FORMAT);
2053
+ const raw = dt.getData(NABU_FORMAT);
2054
+ if (!reader || !raw || !reader.interpret(raw, this)) return;
2055
+ if (!deleteRange(this, range)) return;
2056
+ position = positionAfterRemoval(range, position, !!range.endBlock.node?.isDeleted?.());
2057
+ }
2058
+ this.#insertTransfer(dt, position);
2059
+ }
2060
+
2061
+ /**
2062
+ * Degrades the pasted / imported blocks whose type is not registered in THIS editor to the default text
2063
+ * block (text kept, children kept as following siblings, nothing dropped). See `degradeUnknownBlocks`.
2064
+ * @param {import('../utils/extensions.js').PasteBlock[]} blocks
2065
+ * @returns {import('../utils/extensions.js').PasteBlock[]}
2066
+ */
2067
+ #degradeUnknown(blocks) {
2068
+ const fallback = this.defaultBlockType && this.registry.has(this.defaultBlockType) ? this.defaultBlockType
2069
+ : this.registry.has('paragraph') ? 'paragraph' : null;
2070
+ if (!Array.isArray(blocks)) return blocks;
2071
+ /** @type {Set<string>} */
2072
+ const unknown = new Set();
2073
+ const degraded = degradeUnknownBlocks(blocks, (type) => {
2074
+ const known = this.registry.has(type);
2075
+ if (!known) unknown.add(type);
2076
+ return known;
2077
+ }, fallback);
2078
+ if (fallback && unknown.size) this.warn(`paste: unregistered block type(s) [${[...unknown].join(', ')}] degraded to "${fallback}"`);
2079
+ return degraded;
2080
+ }
2081
+
2082
+ /**
2083
+ * What a block IS for the clipboard (its type and structural props), used to continue it after a paste.
2084
+ * @param {Block} block
2085
+ * @returns {{ type: string, props: Record<string, any> }}
2086
+ */
2087
+ #blockSpec(block) {
2088
+ /** @type {any} */
2089
+ let serialized = null;
2090
+ try { serialized = block.serialize('application/x-nabu+json', { from: 0, to: 0, partial: false }); } catch { /* no serializer */ }
2091
+ return { type: block.type, props: { ...(serialized?.props ?? {}) } };
2092
+ }
2093
+
2094
+ /**
2095
+ * The caret position a drop position stands for. Beside a block without text (before / after an image, a divider…) there
2096
+ * is no caret: an empty default text block is created there (same transaction as the insertion, so one undo step), and the
2097
+ * fragment lands in it like in any empty block (a text becomes its text, a media block replaces it).
2098
+ * @param {DropPosition} at
2099
+ * @returns {{ block: Block, offset: number } | null}
2100
+ */
2101
+ #landingFor(at) {
2102
+ const { block, side } = at;
2103
+ if (!block || block.node?.isDeleted?.()) return null;
2104
+ if (side === 'inside') {
2105
+ const length = block.behaviors?.get('text')?.text?.length;
2106
+ if (length === undefined) return null;
2107
+ return { block, offset: Math.max(0, Math.min(at.offset, length)) };
2108
+ }
2109
+ const type = this.defaultBlockType;
2110
+ const Class = type && this.registry.get(type);
2111
+ if (!Class) return null;
2112
+ const created = Class.create(this, type, {});
2113
+ if (side === 'before') created.node.moveBefore(block.node);
2114
+ else created.node.moveAfter(block.node);
2115
+ wrapOrphan(this, created);
2116
+ return { block: created, offset: 0 };
2117
+ }
2118
+
2119
+ /**
2120
+ * A function that re-reads a drop position later, after edits that happened meanwhile (the files of a drop are hashed
2121
+ * asynchronously): a text position follows the text through a Loro cursor; a block that vanished falls back to the end
2122
+ * of the document.
2123
+ * @param {DropPosition} at
2124
+ * @returns {() => DropPosition | null}
2125
+ */
2126
+ #followPosition(at) {
2127
+ const text = at.side === 'inside' ? /** @type {any} */ (at.block.behaviors?.get('text')?.container) : null;
2128
+ /** @type {any} */
2129
+ let cursor = null;
2130
+ try { cursor = text?.getCursor?.(at.offset) ?? null; } catch { /* static fallback */ }
2131
+ return () => {
2132
+ if (at.block.node?.isDeleted?.()) return documentEnd(this);
2133
+ if (!cursor) return at;
2134
+ try {
2135
+ const pos = this.doc.getCursorPos(cursor);
2136
+ return pos ? { ...at, offset: pos.offset } : at;
2137
+ } catch { return at; }
2138
+ };
2139
+ }
2140
+
2141
+ /**
2142
+ * Insère un PasteFragment à la position du curseur courant — or at `opts.at` (a drop position: a caret position in a
2143
+ * text block, or beside a block without text, where an empty text block receives the fragment), whatever the DOM selection is.
768
2144
  * @param {import('../utils/extensions.js').PasteFragment} fragment
2145
+ * @param {{ at?: DropPosition }} [opts]
769
2146
  */
770
- insertFragment(fragment) {
771
- const { blocks } = fragment;
2147
+ insertFragment(fragment, opts = {}) {
2148
+ this.selection.sync(); // public entry point: may be called outside an input event
2149
+ // Every fragment (HTML / markdown / nabu JSON / API) goes through here: unsafe link & media URLs are dropped.
2150
+ const files = Files.get(this);
2151
+ let adopted = files.adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets);
2152
+ // Content from outside (a web page): remote images are fetched and stored, when the host asked for it (`files.importRemote`).
2153
+ if (fragment.external) adopted = files.importRemote(adopted);
2154
+ const blocks = this.#degradeUnknown(adopted);
772
2155
  if (!blocks?.length) return;
773
2156
 
774
2157
  let anchorBlock;
775
2158
  let offset;
776
2159
 
777
- if (!this.selection.isCollapsed) {
2160
+ if (opts.at) {
2161
+ const landing = this.#landingFor(opts.at);
2162
+ if (!landing) return;
2163
+ anchorBlock = landing.block;
2164
+ offset = landing.offset;
2165
+ } else if (!this.selection.isCollapsed) {
778
2166
  const result = deleteSelectionContent(this, this);
779
2167
  if (!result) return;
780
2168
  anchorBlock = result.block;
@@ -791,15 +2179,50 @@ export class Nabu {
791
2179
  return;
792
2180
  }
793
2181
 
2182
+ // The caret block may take over the insertion (a list item keeps pasted paragraphs in its list, and
2183
+ // splits the list around a block it cannot hold…). It declines with null: the default path runs.
2184
+ const landing = anchorBlock.acceptPaste(blocks, { offset });
2185
+ if (landing) {
2186
+ this.#isolateNextCommits();
2187
+ this.commit();
2188
+ tick().then(() => {
2189
+ if (!landing.block) return;
2190
+ const fb = this.blocks.get(landing.block.id) || landing.block;
2191
+ this.selection.setCursor(fb, landing.offset);
2192
+ });
2193
+ return;
2194
+ }
2195
+
2196
+ // A whole pasted block landing in an EMPTY root-level block (e.g. `# Title` into an
2197
+ // empty paragraph) brings its type along. Pasting into existing text never coerces.
2198
+ // Blocks nested in a container (list item…) keep their type to preserve the structure, unless that
2199
+ // container holds free-form content (`Block#adoptsPastedTypes`, e.g. a toggle body).
2200
+ const anchorEmpty = textBehavior.container.length === 0 && (!anchorBlock.parent || anchorBlock.parent.adoptsPastedTypes);
2201
+ /** @param {import('../utils/extensions.js').PasteBlock} pb */
2202
+ const adoptType = (pb) => {
2203
+ if (!anchorEmpty || pb.partial !== false || pb.type === anchorBlock.type || !this.registry.has(pb.type)) return;
2204
+ const data = /** @type {any} */ (anchorBlock.node.data);
2205
+ data.set('type', pb.type);
2206
+ for (const [key, value] of Object.entries(pb.props || {})) data.set(key, value);
2207
+ };
2208
+
2209
+ // A pasted block is TEXT when it carries a delta; one without (image, divider…) cannot merge into the caret block's
2210
+ // text: it is inserted as a block (the caret block is split around it), or replaces an empty caret block (see adoptType).
2211
+ /** @param {import('../utils/extensions.js').PasteBlock} pb */
2212
+ const isText = (pb) => Array.isArray(pb.delta);
2213
+
794
2214
  // ── Inline: single flat block ─────────────────────────────────────────
795
- if (blocks.length === 1 && !blocks[0].children?.length) {
2215
+ if (blocks.length === 1 && !blocks[0].children?.length && (isText(blocks[0]) || anchorEmpty)) {
796
2216
  const pb = blocks[0];
797
2217
  const delta = pb.delta || [];
798
2218
  const len = delta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
799
2219
 
2220
+ adoptType(pb);
800
2221
  textBehavior.applyDelta([{ retain: offset }, ...delta]);
2222
+ this.#isolateNextCommits();
801
2223
  this.commit();
802
- tick().then(() => this.selection.setCursor(anchorBlock, offset + len));
2224
+ // A type change makes updateRoots() replace the block instance — re-fetch it.
2225
+ tick().then(() => this.selection.setCursor(this.blocks.get(anchorBlock.id) || anchorBlock, offset + len));
803
2226
  return;
804
2227
  }
805
2228
 
@@ -810,6 +2233,11 @@ export class Nabu {
810
2233
  textBehavior.delete({ index: offset, length: textBehavior.container.length - offset });
811
2234
  }
812
2235
 
2236
+ // What the caret block IS (type + props), captured before it may adopt a pasted type: the text that
2237
+ // follows the caret continues in a block of the same kind, like Enter would (`Ti|tle` heading stays a
2238
+ // heading on both sides of the pasted blocks).
2239
+ const tailSpec = rightDelta.length ? this.#blockSpec(anchorBlock) : null;
2240
+
813
2241
  const firstPb = blocks[0];
814
2242
  const lastPb = blocks[blocks.length - 1];
815
2243
  const midPbs = blocks.slice(1, -1);
@@ -818,67 +2246,74 @@ export class Nabu {
818
2246
  let focusOffset = offset;
819
2247
 
820
2248
  // ── First block ───────────────────────────────────────────────────────
821
- if (!firstPb.children?.length) {
822
- // Leaf: merge content into anchor (anchor type survives)
2249
+ if (!firstPb.children?.length && (isText(firstPb) || anchorEmpty)) {
2250
+ // Leaf: merge content into anchor (anchor type survives, unless it was empty — see adoptType)
2251
+ adoptType(firstPb);
823
2252
  const firstDelta = firstPb.delta || [];
824
2253
  if (firstDelta.length) textBehavior.applyDelta([{ retain: offset }, ...firstDelta]);
825
2254
  focusOffset = offset + firstDelta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
826
2255
  } else {
827
- // Container (e.g. List): insert it after anchor
828
- prevNode = this.#insertPasteBlock(firstPb, prevNode);
2256
+ // Container (e.g. List) or void block (image…): insert it after anchor
2257
+ prevNode = this.insertPasteBlock(firstPb, prevNode);
829
2258
  }
2259
+ // The caret was at the very start of a text block and a block (not text) comes first: nothing precedes the pasted
2260
+ // block, the blank head left behind goes (the tail, created below, is the block that keeps the text).
2261
+ const dropHead = offset === 0 && !!rightDelta.length && !isText(firstPb) && !anchorEmpty && !/** @type {any} */ (anchorBlock).children?.length;
830
2262
 
831
2263
  // ── Middle blocks ─────────────────────────────────────────────────────
832
2264
  for (const pb of midPbs) {
833
- prevNode = this.#insertPasteBlock(pb, prevNode);
2265
+ prevNode = this.insertPasteBlock(pb, prevNode);
834
2266
  }
835
2267
 
836
2268
  // ── Last block (only when blocks.length > 1) ──────────────────────────
2269
+ // The text after the caret (`rightDelta`) merges with the last pasted block when that one is TEXT
2270
+ // (cut at the edge of a partial copy, or a default text block), in a block of the caret block's kind;
2271
+ // otherwise (heading, code, image, container…) the block is inserted as it is and the tail follows in
2272
+ // a block of the caret block's kind. Without a tail the last block is simply inserted as it is.
2273
+ /** @param {{type: string, props?: Record<string, any>}} spec @param {import('loro-crdt').Delta<string>[]} delta @param {any} after */
2274
+ const insertLeaf = (spec, delta, after) => {
2275
+ const Class = this.registry.get(spec.type) || this.registry.get('paragraph');
2276
+ if (!Class) return null;
2277
+ const created = Class.create(this, spec.type, spec.props || {});
2278
+ created.node.moveAfter(after);
2279
+ const wrapper = wrapOrphan(this, created);
2280
+ if (delta.length) created.behaviors?.get('text')?.applyDelta(delta);
2281
+ return { block: created, node: wrapper ? wrapper.node : created.node };
2282
+ };
2283
+ const deltaLen = (/** @type {any[]} */ d) => d.reduce((n, op) => n + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
2284
+
837
2285
  if (blocks.length > 1) {
838
2286
  if (!lastPb.children?.length) {
839
- // Leaf last block: create it, append rightDelta
840
- const LastClass = this.registry.get(lastPb.type) || this.registry.get('paragraph');
841
- if (LastClass) {
842
- const newLast = LastClass.create(this, lastPb.type, lastPb.props || {});
843
- newLast.node.moveAfter(prevNode);
844
- const wrapper = wrapOrphan(this, newLast);
845
- const tb = newLast.behaviors?.get('text');
846
- if (tb) {
847
- const lastDelta = lastPb.delta || [];
848
- if (lastDelta.length || rightDelta.length) tb.applyDelta([...lastDelta, ...rightDelta]);
849
- focusOffset = lastDelta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
850
- }
851
- focusBlock = newLast;
852
- prevNode = wrapper ? wrapper.node : newLast.node;
2287
+ const lastDelta = lastPb.delta || [];
2288
+ const lastIsText = lastPb.partial === 'end' || lastPb.partial === 'both' || lastPb.type === this.defaultBlockType;
2289
+ if (!tailSpec) {
2290
+ const done = insertLeaf({ type: lastPb.type, props: lastPb.props }, lastDelta, prevNode);
2291
+ if (done) { focusBlock = done.block; focusOffset = deltaLen(lastDelta); prevNode = done.node; }
2292
+ } else if (lastIsText) {
2293
+ const done = insertLeaf(tailSpec, [...lastDelta, ...rightDelta], prevNode);
2294
+ if (done) { focusBlock = done.block; focusOffset = deltaLen(lastDelta); prevNode = done.node; }
2295
+ } else {
2296
+ prevNode = this.insertPasteBlock(lastPb, prevNode);
2297
+ const done = insertLeaf(tailSpec, rightDelta, prevNode);
2298
+ if (done) { focusBlock = done.block; focusOffset = 0; prevNode = done.node; }
853
2299
  }
854
2300
  } else {
855
- // Container last block: insert it, put rightDelta in a new paragraph after
856
- prevNode = this.#insertPasteBlock(lastPb, prevNode);
857
- if (rightDelta.length) {
858
- const PClass = this.registry.get('paragraph');
859
- if (PClass) {
860
- const p = PClass.create(this, 'paragraph', {});
861
- p.node.moveAfter(prevNode);
862
- p.behaviors?.get('text')?.applyDelta(rightDelta);
863
- focusBlock = p;
864
- focusOffset = 0;
865
- }
866
- }
867
- }
868
- } else {
869
- // Single container block: rightDelta goes in a new paragraph after it
870
- if (rightDelta.length) {
871
- const PClass = this.registry.get('paragraph');
872
- if (PClass) {
873
- const p = PClass.create(this, 'paragraph', {});
874
- p.node.moveAfter(prevNode);
875
- p.behaviors?.get('text')?.applyDelta(rightDelta);
876
- focusBlock = p;
877
- focusOffset = 0;
2301
+ // Container last block: insert it, the tail goes in a new block after it
2302
+ prevNode = this.insertPasteBlock(lastPb, prevNode);
2303
+ if (tailSpec) {
2304
+ const done = insertLeaf(tailSpec, rightDelta, prevNode);
2305
+ if (done) { focusBlock = done.block; focusOffset = 0; }
878
2306
  }
879
2307
  }
2308
+ } else if (tailSpec) {
2309
+ // Single container block: the tail goes in a new block after it
2310
+ const done = insertLeaf(tailSpec, rightDelta, prevNode);
2311
+ if (done) { focusBlock = done.block; focusOffset = 0; }
880
2312
  }
881
2313
 
2314
+ if (dropHead && focusBlock !== anchorBlock) this.tree.delete(anchorBlock.node.id);
2315
+
2316
+ this.#isolateNextCommits();
882
2317
  this.commit();
883
2318
  tick().then(() => {
884
2319
  const fb = this.blocks.get(focusBlock.id) || focusBlock;
@@ -889,21 +2324,35 @@ export class Nabu {
889
2324
  /**
890
2325
  * Inserts a PasteBlock after `afterNode`. Handles both leaf blocks (wrapOrphan)
891
2326
  * and container blocks (creates container, recurses into children).
892
- * Returns the outer node to use as the next prevNode.
2327
+ * Returns the outer node to use as the next prevNode. Public: part of the paste toolbox a block's
2328
+ * `acceptPaste` hook builds on. No commit.
893
2329
  * @param {import('../utils/extensions.js').PasteBlock} pb
894
2330
  * @param {any} afterNode
895
2331
  * @returns {any}
2332
+ * @public
896
2333
  */
897
- #insertPasteBlock(pb, afterNode) {
2334
+ insertPasteBlock(pb, afterNode) {
2335
+ if (!this.registry.has(pb.type)) {
2336
+ // Unknown type: degraded to the default text block, its children follow it (nothing is dropped).
2337
+ const degraded = this.#degradeUnknown([pb]);
2338
+ if (degraded.length === 1 && !this.registry.has(degraded[0].type)) return afterNode; // no default block to degrade to
2339
+ let previous = afterNode;
2340
+ for (const d of degraded) previous = this.insertPasteBlock(d, previous);
2341
+ return previous;
2342
+ }
898
2343
  if (pb.children?.length) {
899
2344
  const ContainerClass = this.registry.get(pb.type);
900
2345
  if (!ContainerClass) return afterNode;
901
2346
  const container = ContainerClass.create(this, pb.type, pb.props || {});
902
2347
  container.node.moveAfter(afterNode);
2348
+ // A container with its own text (list item, toggle…) keeps it.
2349
+ const ctb = container.behaviors?.get('text');
2350
+ if (ctb && pb.delta?.length) ctb.applyDelta(pb.delta);
903
2351
  for (const child of pb.children) {
904
- this.#createInContainer(child, container.node.id.toString());
2352
+ this.createPasteBlock(child, container.node.id.toString());
905
2353
  }
906
- return container.node;
2354
+ const wrapper = wrapOrphan(this, container);
2355
+ return wrapper ? wrapper.node : container.node;
907
2356
  }
908
2357
 
909
2358
  const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
@@ -918,19 +2367,31 @@ export class Nabu {
918
2367
  }
919
2368
 
920
2369
  /**
921
- * Creates a block inside a container, recursively handling nested children.
2370
+ * Creates a block inside a container, recursively handling nested children. Public: part of the paste
2371
+ * toolbox a block's `acceptPaste` hook builds on. No commit.
922
2372
  * @param {import('../utils/extensions.js').PasteBlock} pb
923
2373
  * @param {string} parentId
2374
+ * @returns {Block | null} the created block
2375
+ * @public
924
2376
  */
925
- #createInContainer(pb, parentId) {
2377
+ createPasteBlock(pb, parentId) {
2378
+ if (!this.registry.has(pb.type)) {
2379
+ // Unknown type: the default text block, then its children as ITS following siblings (not inside it).
2380
+ const [head, ...rest] = this.#degradeUnknown([pb]);
2381
+ if (!head || !this.registry.has(head.type)) return null;
2382
+ const created = this.createPasteBlock(head, parentId);
2383
+ for (const sibling of rest) this.createPasteBlock(sibling, parentId);
2384
+ return created;
2385
+ }
926
2386
  const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
927
- if (!BlockClass) return;
2387
+ if (!BlockClass) return null;
928
2388
  const block = BlockClass.create(this, pb.type, pb.props || {}, parentId);
929
2389
  const tb = block.behaviors?.get('text');
930
2390
  if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
931
2391
  for (const child of pb.children || []) {
932
- this.#createInContainer(child, block.node.id.toString());
2392
+ this.createPasteBlock(child, block.node.id.toString());
933
2393
  }
2394
+ return block;
934
2395
  }
935
2396
 
936
2397
  // DOCUMENT IMPORT
@@ -941,9 +2402,10 @@ export class Nabu {
941
2402
  * blocks are created at the root through the same registry pipeline as paste.
942
2403
  * @param {import('../utils/extensions.js').PasteFragment} fragment
943
2404
  * @returns {Promise<void>}
2405
+ * @public
944
2406
  */
945
2407
  async importFragment(fragment) {
946
- const { blocks } = fragment;
2408
+ const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets));
947
2409
  if (!blocks?.length) return;
948
2410
 
949
2411
  [...this.tree.roots()].forEach(root => this.tree.delete(root.id));
@@ -955,11 +2417,13 @@ export class Nabu {
955
2417
  const tb = block.behaviors?.get('text');
956
2418
  if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
957
2419
  for (const child of pb.children || []) {
958
- this.#createInContainer(child, block.node.id.toString());
2420
+ this.createPasteBlock(child, block.node.id.toString());
959
2421
  }
960
2422
  }
961
2423
 
962
2424
  await this.commit();
2425
+ // The files of the import are verified and stored in the background: the import is complete once they are (a host upload is not waited for).
2426
+ await Files.get(this).whenIdle();
963
2427
  }
964
2428
 
965
2429
  /**
@@ -967,6 +2431,7 @@ export class Nabu {
967
2431
  * Requires MarkdownPasteExtension (or any text/plain interpreter) to be loaded.
968
2432
  * @param {string} markdown
969
2433
  * @returns {Promise<void>}
2434
+ * @public
970
2435
  */
971
2436
  async importMarkdown(markdown) {
972
2437
  const interpreter = [...this.#pasteInterpreters]
@@ -977,7 +2442,8 @@ export class Nabu {
977
2442
  return;
978
2443
  }
979
2444
 
980
- const fragment = interpreter.interpret(markdown, this);
2445
+ // CommonMark semantics: consecutive lines join into one paragraph (paste splits per line).
2446
+ const fragment = interpreter.interpret(markdown, this, { joinLines: true });
981
2447
  if (!fragment) {
982
2448
  this.warn('importMarkdown: nothing to import');
983
2449
  return;
@@ -987,21 +2453,33 @@ export class Nabu {
987
2453
  }
988
2454
 
989
2455
  /**
990
- * Replace the entire document with a `serialize('json')` export.
991
- * @param {{version?: string, blocks: any[]} | string} json
2456
+ * Replace the entire document with a `serialize('json')` export. An export of a version this editor does not know
2457
+ * is refused with a warning (the document is left untouched), like the clipboard does; a block type that is not
2458
+ * registered is degraded to the default text block (`degradeUnknownBlocks`), nothing is dropped.
2459
+ * @param {{version?: string | number, blocks: Parameters<typeof import('../utils/extensions.js').jsonToPasteBlocks>[0], assets?: Record<string, import('../files/files.svelte.js').EmbeddedAsset>} | string} json
992
2460
  * @returns {Promise<void>}
2461
+ * @public
993
2462
  */
994
2463
  async importJSON(json) {
995
2464
  const doc = typeof json === 'string' ? JSON.parse(json) : json;
2465
+ if (!isSupportedJsonVersion(doc?.version)) {
2466
+ this.warn(`importJSON: unsupported export version ${JSON.stringify(doc.version)} (this editor reads version ${JSON_FORMAT_VERSION}): nothing imported`);
2467
+ return;
2468
+ }
996
2469
  const blocks = jsonToPasteBlocks(doc?.blocks || []);
997
2470
  if (!blocks.length) {
998
2471
  this.warn('importJSON: nothing to import');
999
2472
  return;
1000
2473
  }
1001
- await this.importFragment({ blocks });
2474
+ await this.importFragment({ blocks, ...(doc.assets && typeof doc.assets === 'object' ? { assets: doc.assets } : {}) });
1002
2475
  }
1003
2476
 
1004
- /** @param {number} globalOffset */
2477
+ /**
2478
+ * The block and local offset that hold a document-wide caret offset (`positions` counted from the start of the document).
2479
+ * @param {number} globalOffset
2480
+ * @returns {{ block: Block, offset: number } | null}
2481
+ * @public
2482
+ */
1005
2483
  resolveDocumentOffset(globalOffset) {
1006
2484
  let remaining = globalOffset;
1007
2485
  for (const block of this.children) {
@@ -1014,7 +2492,86 @@ export class Nabu {
1014
2492
  return last ? last.resolveOffset(Math.max(0, (last.positions ?? 1) - 1)) : null;
1015
2493
  }
1016
2494
 
1017
- /** @param {...any} args */
2495
+ /** @type {NabuInternals | null} */
2496
+ #internals = null;
2497
+
2498
+ /**
2499
+ * The door to everything the engine uses internally that the stable contract (the members tagged `public` in their JSDoc) does not cover: the
2500
+ * command-confirm controller, the action bus, the hook and rule registries, the clipboard / drop / event pipelines, undo
2501
+ * capture, stored marks, the selection's repair machinery. They are the same references the engine runs on, not copies.
2502
+ *
2503
+ * The door itself is part of the stable contract; **@unstable** is everything behind it: nothing reached through `internals` is a
2504
+ * promise, it may change, move or disappear in ANY minor version.
2505
+ * Prefer the stable members; use this when you must, and pin the version of the package. The set of keys is frozen by a
2506
+ * test, so a change shows up in the changelog.
2507
+ * @returns {NabuInternals}
2508
+ * @public
2509
+ * @unstable
2510
+ */
2511
+ get internals() {
2512
+ if (this.#internals) return this.#internals;
2513
+ const nabu = this;
2514
+ const selection = nabu.selection;
2515
+ return this.#internals = Object.freeze({
2516
+ pulse: this.#pulse,
2517
+ commandConfirm: this.commandConfirm,
2518
+ hooks: this.hooks,
2519
+ hookOwners: this.hookOwners,
2520
+ inputRules: this.inputRules,
2521
+ pasteInterpreters: this.#pasteInterpreters,
2522
+ pasteFileHandlers: this.#pasteFileHandlers,
2523
+ undoManager: this.undoManager,
2524
+ content: this.content,
2525
+ fileConfig: this.fileConfig,
2526
+ get storedMarks() { return nabu.storedMarks; },
2527
+ set storedMarks(value) { nabu.storedMarks = value; },
2528
+ toggleStoredMark: this.toggleStoredMark.bind(this),
2529
+ clearStoredMarks: this.clearStoredMarks.bind(this),
2530
+ noteTextChange: this.noteTextChange.bind(this),
2531
+ captureUndoSelection: this.captureUndoSelection.bind(this),
2532
+ sealUndoEnd: this.sealUndoEnd.bind(this),
2533
+ updateRoots: this.updateRoots.bind(this),
2534
+ deleteNode: this.deleteNode.bind(this),
2535
+ rearmTab: this.rearmTab.bind(this),
2536
+ get tabDescription() { return nabu.tabDescription; },
2537
+ dispatchEventToSelection: this.dispatchEventToSelection.bind(this),
2538
+ handleKeydown: this.handleKeydown.bind(this),
2539
+ handleBeforeinput: this.handleBeforeinput.bind(this),
2540
+ beforeinput: this.beforeinput.bind(this),
2541
+ handleCompositionStart: this.handleCompositionStart.bind(this),
2542
+ handleCompositionUpdate: this.handleCompositionUpdate.bind(this),
2543
+ handleCompositionEnd: this.handleCompositionEnd.bind(this),
2544
+ handleMousedown: this.handleMousedown.bind(this),
2545
+ handleCopy: this.handleCopy.bind(this),
2546
+ handleCut: this.handleCut.bind(this),
2547
+ handlePaste: this.handlePaste.bind(this),
2548
+ insertFragment: this.insertFragment.bind(this),
2549
+ handleDragStart: this.handleDragStart.bind(this),
2550
+ handleDragOver: this.handleDragOver.bind(this),
2551
+ handleDragLeave: this.handleDragLeave.bind(this),
2552
+ handleDragEnd: this.handleDragEnd.bind(this),
2553
+ handleDrop: this.handleDrop.bind(this),
2554
+ dropAt: this.dropAt.bind(this),
2555
+ get dropTarget() { return nabu.dropTarget; },
2556
+ selection: Object.freeze({
2557
+ normalize: selection.normalize.bind(selection),
2558
+ scheduleRepair: selection.scheduleRepair.bind(selection),
2559
+ repairAfterRemoval: selection.repairAfterRemoval.bind(selection),
2560
+ get placements() { return selection.placements; },
2561
+ attachRoot: selection.attachRoot.bind(selection),
2562
+ owns: selection.owns.bind(selection),
2563
+ scope: selection.scope.bind(selection),
2564
+ get root() { return selection.root; },
2565
+ }),
2566
+ });
2567
+ }
2568
+
2569
+ /**
2570
+ * Log a diagnostic to the console when `debugging` is on. Silent otherwise.
2571
+ * @param {...any} args
2572
+ * @returns {void}
2573
+ * @public
2574
+ */
1018
2575
  warn(...args) {
1019
2576
  if (this.debugging) console.warn("[Nabu]", ...args);
1020
2577
  }