@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,4 +1,5 @@
1
1
  import { Extension } from '../utils/extensions.js';
2
+ import { sanitizeUrl } from '../utils/html.js';
2
3
 
3
4
  // ── Inline mark mapping: HTML tag → Nabu mark name ──────────────────────────
4
5
  const MARK_TAGS = {
@@ -9,8 +10,8 @@ const MARK_TAGS = {
9
10
  s: 'strikethrough', del: 'strikethrough', strike: 'strikethrough',
10
11
  };
11
12
 
12
- // ── Tags to skip entirely when parsing inline content ────────────────────────
13
- // These represent structural/block elements that create new blocks, not inline marks.
13
+ // ── Tags skipped when parsing inline content ────────────────────────────────
14
+ // Structural/block elements that create their own blocks, not inline marks.
14
15
  // ul/ol/li are handled as children by their parent block's fromHTML.
15
16
  const SKIP_IN_INLINE = new Set([
16
17
  'ul', 'ol', 'li',
@@ -18,84 +19,327 @@ const SKIP_IN_INLINE = new Set([
18
19
  'script', 'style', 'noscript', 'iframe',
19
20
  ]);
20
21
 
22
+ // ── Tags whose content is NEVER read as text (active / embedded content) ─────
23
+ // Kept apart from SKIP_IN_INLINE: that set also drives block-container detection.
24
+ const DROP_IN_INLINE = new Set([
25
+ 'object', 'embed', 'applet', 'template', 'svg', 'math', 'frame', 'frameset', 'canvas', 'audio', 'video', 'img',
26
+ ]);
27
+
28
+ // ── Tags that never contribute anything, at any level (P-47: scripts / styles never produce text) ──
29
+ const NEVER_CONTENT = new Set([
30
+ 'script', 'style', 'noscript', 'iframe', 'template', 'head', 'title', 'meta', 'link', 'base', 'colgroup', 'col',
31
+ 'object', 'embed', 'applet', 'svg', 'math', 'frame', 'frameset', 'canvas', 'audio',
32
+ ]);
33
+
21
34
  // ── Tags treated as transparent containers: flattened at the top level ───────
22
35
  // A div/section containing block children is not itself a block — expand it.
23
36
  const TRANSPARENT_CONTAINERS = new Set([
24
37
  'div', 'section', 'article', 'main', 'header', 'footer',
25
38
  'aside', 'nav', 'form', 'figure', 'figcaption', 'details', 'summary',
39
+ 'address', 'hgroup', 'fieldset', 'legend', 'center', 'menu', 'dir',
26
40
  ]);
27
41
 
42
+ // ── Structure the engine has no block for (yet): its content is kept as paragraphs, never lost ──
43
+ const STRUCTURAL = new Set([
44
+ 'ul', 'ol', 'li', 'dl', 'dt', 'dd',
45
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th', 'caption',
46
+ ]);
47
+
48
+ // ── Elements that start / end a line when they appear INSIDE inline content (`<blockquote><p>a</p><p>b</p>`) ──
49
+ const LINE_BOUNDARY = new Set([
50
+ 'p', 'div', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'blockquote', 'section', 'article', 'aside', 'header', 'footer',
51
+ 'main', 'nav', 'figure', 'figcaption', 'address', 'dd', 'dt', 'dl', 'fieldset', 'form', 'center', 'details',
52
+ 'summary', 'hr', 'pre',
53
+ ]);
54
+
55
+ // ── `white-space` values under which spaces are significant (not collapsed) ──
56
+ const PRESERVE_WHITESPACE = new Set(['pre', 'pre-wrap', 'break-spaces']);
57
+
58
+ /** Namespace prefixes of Office markup (`<o:p>`, `<v:shape>`, `<w:sdt>`…) that never carry text. */
59
+ const OFFICE_PREFIXES = new Set(['o', 'v', 'w']);
60
+
61
+ // ── Inline style reading ─────────────────────────────────────────────────────
62
+
63
+ /** @type {Readonly<Record<string, string>>} */
64
+ const NO_STYLE = Object.freeze({});
65
+
28
66
  /**
29
- * Returns true if any direct child of el is a structural block element.
30
- * Used to decide whether a transparent container should be flattened.
31
- * Derives block detection from the registered ruleset — no hardcoded block types.
67
+ * Parse the `style` attribute of an element into `{ property: value }` (lower-cased, `!important` removed, the last
68
+ * declaration of a property wins). Reads the attribute itself rather than the CSSOM so that `mso-*` / vendor
69
+ * properties can never be mistaken for the standard property they look like, whatever the DOM implementation.
32
70
  * @param {Element} el
33
- * @param {Array<{ rule: { selector: string } }>} ruleset
34
- * @returns {boolean}
71
+ * @returns {Readonly<Record<string, string>>}
35
72
  */
36
- function hasBlockChildren(el, ruleset) {
37
- for (const child of el.children) {
38
- const tag = child.tagName.toLowerCase();
39
- if (SKIP_IN_INLINE.has(tag) || TRANSPARENT_CONTAINERS.has(tag)) return true;
40
- for (const { rule } of ruleset) {
41
- try { if (child.matches(rule.selector)) return true; } catch { continue; }
73
+ export function parseStyle(el) {
74
+ const raw = el.getAttribute?.('style');
75
+ if (!raw) return NO_STYLE;
76
+ /** @type {Record<string, string>} */
77
+ const out = {};
78
+ let depth = 0;
79
+ /** @type {string | null} */
80
+ let quote = null;
81
+ let start = 0;
82
+ const flush = (/** @type {number} */ end) => {
83
+ const decl = raw.slice(start, end);
84
+ const i = decl.indexOf(':');
85
+ if (i > 0) {
86
+ const name = decl.slice(0, i).trim().toLowerCase();
87
+ const value = decl.slice(i + 1).replace(/!\s*important/i, '').trim().toLowerCase();
88
+ if (name) out[name] = value;
42
89
  }
90
+ start = end + 1;
91
+ };
92
+ for (let i = 0; i < raw.length; i++) {
93
+ const ch = raw[i];
94
+ if (quote) { if (ch === quote) quote = null; continue; }
95
+ if (ch === '"' || ch === "'") quote = ch;
96
+ else if (ch === '(') depth++;
97
+ else if (ch === ')') depth = Math.max(0, depth - 1);
98
+ else if (ch === ';' && depth === 0) flush(i);
43
99
  }
44
- return false;
100
+ flush(raw.length);
101
+ return out;
45
102
  }
46
103
 
47
104
  /**
48
- * Parse the inline content of a DOM element into a Loro-compatible delta array.
49
- * Recurses into inline and unknown elements, inheriting marks.
50
- * Skips block-level children (ul, ol, table…) — those are handled by fromHTML.
51
- *
105
+ * Apply the inline style of an element over the marks inherited from the tags: the style has the last word
106
+ * (`<b style="font-weight:normal">` is NOT bold, `<span style="font-weight:700">` is). Only the marks Nabu knows are
107
+ * touched; colors, fonts, sizes and backgrounds are ignored.
108
+ * @param {Record<string, any>} marks mutated in place
109
+ * @param {Readonly<Record<string, string>>} style
110
+ */
111
+ function applyStyleToMarks(marks, style) {
112
+ const fw = style['font-weight'];
113
+ if (fw) {
114
+ if (fw === 'bold') marks.bold = true;
115
+ else if (fw === 'normal' || fw === 'lighter') delete marks.bold;
116
+ else if (/^\d+$/.test(fw)) { if (Number(fw) >= 600) marks.bold = true; else delete marks.bold; }
117
+ }
118
+ const fs = style['font-style'];
119
+ if (fs) {
120
+ if (fs === 'italic' || fs.startsWith('oblique')) marks.italic = true;
121
+ else if (fs === 'normal') delete marks.italic;
122
+ }
123
+ const td = style['text-decoration-line'] ?? style['text-decoration'];
124
+ if (td) {
125
+ const words = td.split(/\s+/);
126
+ if (words.includes('none')) { delete marks.underline; delete marks.strikethrough; }
127
+ // The underline of a link is the link's own look, not a mark the author put on the text.
128
+ if (words.includes('underline') && !marks.link) marks.underline = true;
129
+ if (words.includes('line-through')) marks.strikethrough = true;
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Whether an element contributes nothing at all: scripts / styles / embedded content, Office markup (`<o:p>`), Word list
135
+ * markers (`mso-list:Ignore`), hidden elements.
52
136
  * @param {Element} el
53
- * @param {Record<string, true>} [marks]
54
- * @returns {import('loro-crdt').Delta<string>[]}
137
+ * @param {string} tag lower-cased tag name
138
+ * @param {Readonly<Record<string, string>>} style
139
+ * @returns {boolean}
55
140
  */
56
- export function parseInline(el, marks = {}) {
57
- /** @type {import('loro-crdt').Delta<string>[]} */
58
- const ops = [];
141
+ function isJunk(el, tag, style) {
142
+ if (NEVER_CONTENT.has(tag)) return true;
143
+ const colon = tag.indexOf(':');
144
+ if (colon > 0 && OFFICE_PREFIXES.has(tag.slice(0, colon))) return true;
145
+ if (tag === 'xml') return true;
146
+ if (style['mso-list']?.startsWith('ignore')) return true;
147
+ if (style['mso-hide'] === 'all' || style.display === 'none' || style.visibility === 'hidden') return true;
148
+ return el.hasAttribute?.('hidden') ?? false;
149
+ }
150
+
151
+ // ── Links ────────────────────────────────────────────────────────────────────
152
+
153
+ /**
154
+ * Unwrap a Google redirect link (`https://www.google.com/url?q=<target>&sa=D&…`, also `&url=`) to its target.
155
+ * Returns `null` when `href` is not such a link, or when its target is missing, relative, malformed or unsafe.
156
+ * @param {string} href
157
+ * @returns {string | null}
158
+ */
159
+ export function unwrapGoogleRedirect(href) {
160
+ let url;
161
+ try { url = new URL(href.trim()); } catch { return null; }
162
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return null;
163
+ const host = url.hostname.toLowerCase();
164
+ if (host !== 'www.google.com' && host !== 'google.com') return null;
165
+ if (url.pathname !== '/url') return null;
166
+ const target = url.searchParams.get('q') || url.searchParams.get('url');
167
+ if (!target || !/^(?:https?:|mailto:|tel:)/i.test(target.trim())) return null;
168
+ const clean = target.trim();
169
+ return sanitizeUrl(clean, { kind: 'link' }) !== null ? clean : null;
170
+ }
171
+
172
+ /**
173
+ * The href a pasted link gets: a Google redirect is unwrapped to its (sanitized) target; otherwise the href itself when
174
+ * `sanitizeUrl` accepts it; `null` when unsafe (the text is kept, just not as a link).
175
+ * @param {string | null} href
176
+ * @returns {string | null}
177
+ */
178
+ export function resolveLinkHref(href) {
179
+ if (!href) return null;
180
+ const target = unwrapGoogleRedirect(href);
181
+ if (target !== null) return target;
182
+ return sanitizeUrl(href, { kind: 'link' }) !== null ? href : null;
183
+ }
184
+
185
+ // ── Inline content → delta ───────────────────────────────────────────────────
186
+
187
+ /**
188
+ * @typedef {Object} TextToken
189
+ * @property {string} s
190
+ * @property {Record<string, any>} marks
191
+ * @property {boolean} preserve spaces are significant (`white-space: pre | pre-wrap | break-spaces`)
192
+ * @property {boolean} verbatim inside a `<pre>`: not even NBSP is touched
193
+ */
194
+ /** @typedef {TextToken | { br: true } | { brk: true }} Token `br`: a `<br>`; `brk`: a block boundary met inside inline content */
195
+
196
+ /**
197
+ * Collect the text and line breaks under `el` as a flat token list, with the marks that apply to each text run.
198
+ * @param {Node} el
199
+ * @param {Record<string, any>} marks
200
+ * @param {boolean} preserve
201
+ * @param {boolean} verbatim
202
+ * @param {Token[]} out
203
+ */
204
+ function collect(el, marks, preserve, verbatim, out) {
59
205
  for (const child of el.childNodes) {
60
206
  if (child.nodeType === Node.TEXT_NODE) {
61
- const text = child.textContent;
62
- if (text) {
63
- ops.push(
64
- Object.keys(marks).length
65
- ? { insert: text, attributes: { ...marks } }
66
- : { insert: text }
67
- );
68
- }
207
+ const s = child.textContent;
208
+ if (s) out.push({ s, marks, preserve, verbatim });
69
209
  } else if (child.nodeType === Node.ELEMENT_NODE) {
70
210
  const el2 = /** @type {Element} */ (child);
71
211
  const tag = el2.tagName.toLowerCase();
72
- if (tag === 'br') { ops.push({ insert: '\n' }); continue; }
73
- if (SKIP_IN_INLINE.has(tag)) continue;
74
- const markName = MARK_TAGS[tag];
75
- const styleMarks = { ...marks };
76
- if (markName) styleMarks[markName] = true;
77
- // <a href> → link mark (value = href)
212
+ if (tag === 'br') { out.push({ br: true }); continue; }
213
+ const style = parseStyle(el2);
214
+ if (isJunk(el2, tag, style) || SKIP_IN_INLINE.has(tag) || DROP_IN_INLINE.has(tag)) continue;
215
+ const next = { ...marks };
216
+ const markName = /** @type {Record<string, string>} */ (MARK_TAGS)[tag];
217
+ if (markName) next[markName] = true;
218
+ // <a href> → link mark (value = href). Unsafe hrefs (javascript:, data:…) are dropped: the text stays, as plain text.
78
219
  if (tag === 'a') {
79
- const href = el2.getAttribute('href');
80
- if (href) styleMarks['link'] = /** @type {any} */ (href);
81
- }
82
- // Detect marks from inline styles (e.g. Google Docs uses font-weight:700 on <span>)
83
- if (el2.nodeType === Node.ELEMENT_NODE) {
84
- const style = /** @type {HTMLElement} */ (el2).style;
85
- if (style) {
86
- const fw = style.fontWeight;
87
- if (fw === 'bold' || fw === '700' || fw === '800' || fw === '900') styleMarks['bold'] = true;
88
- if (style.fontStyle === 'italic') styleMarks['italic'] = true;
89
- if (style.textDecoration?.includes('underline')) styleMarks['underline'] = true;
90
- if (style.textDecoration?.includes('line-through')) styleMarks['strikethrough'] = true;
91
- }
220
+ const href = resolveLinkHref(el2.getAttribute('href'));
221
+ if (href !== null) next.link = href;
92
222
  }
93
- ops.push(...parseInline(el2, styleMarks));
223
+ applyStyleToMarks(next, style);
224
+ const ws = style['white-space'];
225
+ const nextPreserve = tag === 'pre' ? true : ws ? PRESERVE_WHITESPACE.has(ws) : preserve;
226
+ const boundary = LINE_BOUNDARY.has(tag);
227
+ if (boundary) out.push({ brk: true });
228
+ collect(el2, next, nextPreserve, verbatim || tag === 'pre', out);
229
+ if (boundary) out.push({ brk: true });
230
+ }
231
+ }
232
+ }
233
+
234
+ /**
235
+ * @typedef {Object} Cell one character of the flattened inline content
236
+ * @property {string} c
237
+ * @property {Record<string, any> | null} marks null for a line break
238
+ * @property {boolean} preserve
239
+ * @property {boolean} verbatim
240
+ * @property {'br' | 'brk' | null} brk
241
+ * @property {boolean} [collapsible] a space that came out of HTML whitespace collapsing (and may still be trimmed)
242
+ */
243
+
244
+ /** Spaces for the NBSP rule: a U+00A0 touching one of these (or a line / block edge) is a plain space. */
245
+ const SPACE_LIKE = /[ \t\r\f ]/;
246
+ /** HTML whitespace (collapsible): space, tab, line feed, carriage return, form feed. NOT the unicode spaces. */
247
+ const HTML_WS = /^[ \t\n\r\f]$/;
248
+
249
+ /**
250
+ * Turn the token list into a delta, applying the whitespace rules of external HTML (P-57):
251
+ * - HTML whitespace collapses to one space and is trimmed at the edges of a line (CSS), except under
252
+ * `white-space: pre | pre-wrap | break-spaces` where it is kept; `<br>` is a line break;
253
+ * - U+00A0 between two visible characters is KEPT ("10 km", "Bonjour :"); next to another space or at the edge of a
254
+ * line / block it is a regular space (then collapsed like any space);
255
+ * - every other character (U+202F, U+2007, U+2060, U+00AD, ZWJ, ZWNJ…) is left untouched.
256
+ * @param {Token[]} tokens
257
+ * @param {{ keepEdges?: boolean }} [options] `keepEdges`: keep one collapsed space at the edges (a fragment of a line)
258
+ * @returns {import('loro-crdt').Delta<string>[]}
259
+ */
260
+ function buildDelta(tokens, { keepEdges = false } = {}) {
261
+ /** @type {Cell[]} */
262
+ const cells = [];
263
+ for (const t of tokens) {
264
+ if ('s' in t) {
265
+ for (const c of t.s) cells.push({ c, marks: t.marks, preserve: t.preserve, verbatim: t.verbatim, brk: null });
266
+ } else {
267
+ cells.push({ c: '\n', marks: null, preserve: false, verbatim: false, brk: 'br' in t ? 'br' : 'brk' });
94
268
  }
95
269
  }
270
+
271
+ // 1. NBSP: isolated between two visible characters → kept; next to a space or a line / block edge → regular space.
272
+ const isEdge = (/** @type {Cell | undefined} */ cell) => !cell || cell.c === '\n';
273
+ const spaceLike = (/** @type {Cell | undefined} */ cell) => !!cell && SPACE_LIKE.test(cell.c);
274
+ const nbsp = [];
275
+ for (let i = 0; i < cells.length; i++) {
276
+ if (cells[i].c !== ' ' || cells[i].verbatim) continue;
277
+ const l = cells[i - 1];
278
+ const r = cells[i + 1];
279
+ if (isEdge(l) || isEdge(r) || spaceLike(l) || spaceLike(r)) nbsp.push(i);
280
+ }
281
+ for (const i of nbsp) cells[i] = { ...cells[i], c: ' ' };
282
+
283
+ // 2. Collapse HTML whitespace and trim line edges.
284
+ /** @type {Cell[]} */
285
+ const out = [];
286
+ const last = () => out[out.length - 1];
287
+ const dropTrailingSpaces = () => { while (out.length && last().collapsible) out.pop(); };
288
+ for (const cell of cells) {
289
+ if (cell.brk) {
290
+ dropTrailingSpaces();
291
+ if (cell.brk === 'brk' && (!out.length || last().c === '\n')) continue; // block boundaries never stack or lead
292
+ out.push(cell);
293
+ } else if (!cell.preserve && HTML_WS.test(cell.c)) {
294
+ const prev = last();
295
+ if (prev && (prev.collapsible || prev.c === '\n')) continue;
296
+ if (!prev && !keepEdges) continue;
297
+ out.push({ ...cell, c: ' ', collapsible: true });
298
+ } else {
299
+ out.push(cell);
300
+ }
301
+ }
302
+ if (!keepEdges) dropTrailingSpaces();
303
+ while (out.length && (last().brk || (!keepEdges && last().collapsible))) out.pop();
304
+
305
+ // 3. Back to a delta, merging neighbours that carry the same marks.
306
+ /** @type {import('loro-crdt').Delta<string>[]} */
307
+ const ops = [];
308
+ let prevKey = '';
309
+ for (const cell of out) {
310
+ const entries = cell.marks ? Object.entries(cell.marks).sort(([a], [b]) => (a < b ? -1 : 1)) : [];
311
+ const key = entries.length ? JSON.stringify(entries) : '';
312
+ const prev = ops[ops.length - 1];
313
+ if (prev && key === prevKey) { prev.insert += cell.c; continue; }
314
+ ops.push(key && cell.marks ? { insert: cell.c, attributes: { ...cell.marks } } : { insert: cell.c });
315
+ prevKey = key;
316
+ }
96
317
  return ops;
97
318
  }
98
319
 
320
+ /**
321
+ * Parse the inline content of a DOM element into a Loro-compatible delta array.
322
+ * Recurses into inline and unknown elements, inheriting marks; the inline style of an element has the last word over
323
+ * its tag; skips block-level children (ul, ol, table…) — those are handled by fromHTML. Whitespace follows the rules of
324
+ * {@link buildDelta}.
325
+ *
326
+ * @param {Element} el
327
+ * @param {Record<string, true>} [marks]
328
+ * @param {{ keepEdges?: boolean }} [options]
329
+ * @returns {import('loro-crdt').Delta<string>[]}
330
+ */
331
+ export function parseInline(el, marks = {}, options) {
332
+ const style = parseStyle(el);
333
+ const ws = style['white-space'];
334
+ const tag = el.tagName.toLowerCase();
335
+ /** @type {Token[]} */
336
+ const tokens = [];
337
+ collect(el, { ...marks }, tag === 'pre' || (ws ? PRESERVE_WHITESPACE.has(ws) : false), tag === 'pre', tokens);
338
+ return buildDelta(tokens, options);
339
+ }
340
+
341
+ // ── Block level ──────────────────────────────────────────────────────────────
342
+
99
343
  /**
100
344
  * Build the ordered ruleset from all BlockClasses registered in nabu.
101
345
  * Sorted by rule priority descending so specific blocks (e.g. blockquote)
@@ -107,7 +351,7 @@ function buildRuleset(nabu) {
107
351
  /** @type {Array<{ BlockClass: any, rule: any }>} */
108
352
  const ruleset = [];
109
353
  for (const [, BlockClass] of nabu.registry) {
110
- const rules = BlockClass.htmlRules;
354
+ const rules = /** @type {{ htmlRules?: unknown }} */ (BlockClass).htmlRules;
111
355
  if (!Array.isArray(rules)) continue;
112
356
  for (const rule of rules) ruleset.push({ BlockClass, rule });
113
357
  }
@@ -116,55 +360,253 @@ function buildRuleset(nabu) {
116
360
  }
117
361
 
118
362
  /**
119
- * Match a DOM element against the registered ruleset and call the matching
120
- * block class's static fromHTML(). Falls back to a plain paragraph if nothing
121
- * matches but the element has text content.
122
- *
363
+ * The first rule of the ruleset an element matches, if any.
123
364
  * @param {Element} el
124
- * @param {Array} ruleset
125
- * @param {Object} helpers
126
- * @returns {import('../utils/extensions.js').PasteBlock | null}
365
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
366
+ * @returns {{ BlockClass: any, rule: any } | null}
127
367
  */
128
- function parseBlock(el, ruleset, helpers) {
129
- if (el.nodeType !== Node.ELEMENT_NODE) return null;
130
- for (const { BlockClass, rule } of ruleset) {
131
- try { if (!el.matches(rule.selector)) continue; } catch { continue; }
132
- if (rule.filter && !rule.filter(el)) continue;
133
- return BlockClass.fromHTML(el, helpers, rule);
368
+ function findRule(el, ruleset) {
369
+ for (const entry of ruleset) {
370
+ try { if (!el.matches(entry.rule.selector)) continue; } catch { continue; }
371
+ if (entry.rule.filter && !entry.rule.filter(el)) continue;
372
+ return entry;
134
373
  }
135
374
  return null;
136
375
  }
137
376
 
138
377
  /**
139
- * Parse a top-level element, flattening transparent containers.
140
- * Returns an array because one DOM element may expand into multiple PasteBlocks.
378
+ * A text block with no text (and no children): `<p></p>`, `<p><br></p>`, `<p>&nbsp;</p>`, an empty list item… External HTML
379
+ * only, never code. Generic: "has a delta array and nothing in it".
380
+ * @param {import('../utils/extensions.js').PasteBlock} pb
381
+ * @param {Element} el
382
+ * @returns {boolean}
383
+ */
384
+ function isEmptyTextBlock(pb, el) {
385
+ if (!Array.isArray(pb.delta) || pb.children?.length) return false;
386
+ if (el.closest?.('pre')) return false;
387
+ return pb.delta.every((op) => typeof op.insert !== 'string' || !/\S/.test(op.insert));
388
+ }
389
+
390
+ /**
391
+ * Match a DOM element against the registered ruleset and call the matching block class's static `fromHTML()`. The rule's
392
+ * `fromHTML` may return one PasteBlock, several (a table gives one paragraph per row) or nothing. Empty text blocks (see
393
+ * {@link isEmptyTextBlock}) are dropped.
141
394
  *
142
395
  * @param {Element} el
143
- * @param {Array} ruleset
396
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
144
397
  * @param {Object} helpers
398
+ * @param {Element[]} [siblings] the following siblings the rule absorbed (see {@link claimSiblings})
145
399
  * @returns {import('../utils/extensions.js').PasteBlock[]}
146
400
  */
147
- function parseTopLevel(el, ruleset, helpers) {
401
+ function parseBlocks(el, ruleset, helpers, siblings = []) {
148
402
  if (el.nodeType !== Node.ELEMENT_NODE) return [];
403
+ const entry = findRule(el, ruleset);
404
+ if (!entry) return [];
405
+ const out = entry.BlockClass.fromHTML(el, helpers, entry.rule, siblings);
406
+ const list = Array.isArray(out) ? out : out ? [out] : [];
407
+ return list.filter((pb) => pb && !isEmptyTextBlock(pb, el));
408
+ }
409
+
410
+ /**
411
+ * The first block of {@link parseBlocks}, or `null`.
412
+ * @param {Element} el
413
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
414
+ * @param {Object} helpers
415
+ * @returns {import('../utils/extensions.js').PasteBlock | null}
416
+ */
417
+ function parseBlock(el, ruleset, helpers) {
418
+ return parseBlocks(el, ruleset, helpers)[0] ?? null;
419
+ }
420
+
421
+ /**
422
+ * A block class may ask to absorb the siblings that follow its element (`static htmlSiblings(el, rule, helpers)` returns
423
+ * them, in order): the structure continues over several elements (Google Docs puts each nesting level of a list in its own
424
+ * `<ul>`, Word writes a list as consecutive `<p>`). They reach `fromHTML` as 4th argument and are not read on their own.
425
+ * Only blank text and comments may lie between the element and what it absorbs; the claim stops at the first thing that does not.
426
+ * @param {Element} el
427
+ * @param {{ BlockClass: any, rule: any }} entry
428
+ * @param {any} helpers
429
+ * @returns {{ siblings: Element[], nodes: Node[] }} the absorbed elements, and every node covered (blank text / comments included)
430
+ */
431
+ function claimSiblings(el, entry, helpers) {
432
+ /** @type {Element[]} */
433
+ const siblings = [];
434
+ /** @type {Node[]} */
435
+ const nodes = [];
436
+ const ask = entry.BlockClass.htmlSiblings;
437
+ if (typeof ask !== 'function') return { siblings, nodes };
438
+ let wanted;
439
+ try { wanted = new Set(ask.call(entry.BlockClass, el, entry.rule, helpers) ?? []); } catch { return { siblings, nodes }; }
440
+ /** @type {Node[]} */
441
+ let between = [];
442
+ for (let n = el.nextSibling; n && siblings.length < wanted.size; n = n.nextSibling) {
443
+ if (n.nodeType === Node.ELEMENT_NODE) {
444
+ if (!wanted.has(/** @type {Element} */ (n))) break;
445
+ siblings.push(/** @type {Element} */ (n));
446
+ nodes.push(...between, n);
447
+ between = [];
448
+ } else if (n.nodeType === Node.COMMENT_NODE || (n.nodeType === Node.TEXT_NODE && !/\S/.test(n.textContent ?? ''))) {
449
+ between.push(n);
450
+ } else break;
451
+ }
452
+ return { siblings, nodes };
453
+ }
454
+
455
+ // ── Elements embedded in inline content (an <img> in a paragraph) ────────────
456
+
457
+ /**
458
+ * Selector of the elements whose rule says `embed: true`: they may sit inside the inline content of another block, and
459
+ * are then lifted out as blocks of their own.
460
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
461
+ * @returns {string}
462
+ */
463
+ const embedSelector = (ruleset) => ruleset.filter((e) => e.rule.embed).map((e) => e.rule.selector).join(',');
464
+
465
+ /**
466
+ * The embeddable elements of a block element that can be lifted out of it: reached through inline wrappers only (never
467
+ * through a list / table / `<pre>` or another ruled block, which read their own content).
468
+ * An embeddable element that gives no block (an `<img>` with an unsafe or missing source) is not lifted: it simply is not there.
469
+ * @param {Element} host
470
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
471
+ * @param {any} helpers
472
+ * @returns {Element[]}
473
+ */
474
+ function findEmbeds(host, ruleset, helpers) {
475
+ const selector = embedSelector(ruleset);
476
+ if (!selector) return [];
477
+ let candidates;
478
+ try { candidates = [...host.querySelectorAll(selector)]; } catch { return []; }
479
+ return candidates.filter((embed) => {
480
+ if (!findRule(embed, ruleset)?.rule.embed || !parseBlocks(embed, ruleset, helpers).length) return false;
481
+ for (let a = embed.parentElement; a && a !== host; a = a.parentElement) {
482
+ const tag = a.tagName.toLowerCase();
483
+ if (STRUCTURAL.has(tag) || tag === 'pre' || tag === 'code' || findRule(a, ruleset)) return false;
484
+ }
485
+ return true;
486
+ });
487
+ }
488
+
489
+ /**
490
+ * @typedef {{ el: Element } | { embed: Element }} Piece
491
+ */
492
+
493
+ /**
494
+ * Cut `node` around the `embeds` it contains: the content before an embed, the embed, the content after, each side being
495
+ * a shallow copy of `node` (and of the inline wrappers on the way) holding its slice of the children.
496
+ * @param {Element} node
497
+ * @param {Set<Element>} embeds
498
+ * @returns {Piece[]}
499
+ */
500
+ function splitAround(node, embeds) {
501
+ /** @type {Piece[]} */
502
+ const pieces = [];
503
+ let current = /** @type {Element} */ (node.cloneNode(false));
504
+ const flush = () => { if (current.childNodes.length) pieces.push({ el: current }); current = /** @type {Element} */ (node.cloneNode(false)); };
505
+ for (const child of node.childNodes) {
506
+ if (child.nodeType !== Node.ELEMENT_NODE) { current.appendChild(child.cloneNode(true)); continue; }
507
+ const el = /** @type {Element} */ (child);
508
+ if (embeds.has(el)) { flush(); pieces.push({ embed: el }); continue; }
509
+ if ([...embeds].some((e) => el.contains(e))) {
510
+ for (const piece of splitAround(el, embeds)) {
511
+ if ('embed' in piece) { flush(); pieces.push(piece); } else current.appendChild(piece.el);
512
+ }
513
+ } else current.appendChild(el.cloneNode(true));
514
+ }
515
+ if (current.childNodes.length) pieces.push({ el: current });
516
+ return pieces;
517
+ }
518
+
519
+ /**
520
+ * How an element takes part in the block structure:
521
+ * - `skip`: contributes nothing (script, style, hidden, Office markup, embedded content);
522
+ * - `block`: a registered block rule matches it (its `fromHTML` reads the whole element);
523
+ * - `container`: only a wrapper (div, section, table cell, a `<b>` around paragraphs…): its children are read in turn;
524
+ * - `inline`: text-level content, grouped with its neighbours into one paragraph.
525
+ * @param {Element} el
526
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
527
+ * @returns {'skip' | 'block' | 'container' | 'inline'}
528
+ */
529
+ function classify(el, ruleset) {
149
530
  const tag = el.tagName.toLowerCase();
150
- if (TRANSPARENT_CONTAINERS.has(tag) && hasBlockChildren(el, ruleset)) {
151
- return [...el.children].flatMap(child => parseTopLevel(child, ruleset, helpers));
531
+ if (isJunk(el, tag, parseStyle(el))) return 'skip';
532
+ if (findRule(el, ruleset)) return 'block';
533
+ if (DROP_IN_INLINE.has(tag)) return 'skip';
534
+ if (TRANSPARENT_CONTAINERS.has(tag) || STRUCTURAL.has(tag)) return 'container';
535
+ // An unknown element wrapping block children (Google Docs' <b style="font-weight:normal"> wrapper…) is transparent.
536
+ for (const child of el.children) {
537
+ const kind = classify(child, ruleset);
538
+ if (kind === 'block' || kind === 'container') return 'container';
152
539
  }
153
- const pb = parseBlock(el, ruleset, helpers);
154
- if (pb) return [pb];
155
- // Unknown element with block children: treat as transparent.
156
- // Handles Google Docs' <b style="font-weight:normal"> wrapper and similar quirks.
157
- if (hasBlockChildren(el, ruleset)) {
158
- return [...el.children].flatMap(child => parseTopLevel(child, ruleset, helpers));
540
+ return 'inline';
541
+ }
542
+
543
+ /**
544
+ * Read the children of a container: block elements become blocks, container elements are expanded, and the loose inline
545
+ * content between them (text, `<br>`, `<span>`, `<b>`…) is grouped into implicit paragraphs, so that no text is lost
546
+ * next to a `<script>` / `<style>` or a sibling block (P-47).
547
+ *
548
+ * @param {Node} parent
549
+ * @param {Array<{ BlockClass: any, rule: any }>} ruleset
550
+ * @param {any} helpers
551
+ * @param {{ onRun?: (p: Element) => import('../utils/extensions.js').PasteBlock | null }} [hooks]
552
+ * @returns {import('../utils/extensions.js').PasteBlock[]}
553
+ */
554
+ function parseNodes(parent, ruleset, helpers, hooks = {}) {
555
+ /** @type {import('../utils/extensions.js').PasteBlock[]} */
556
+ const blocks = [];
557
+ /** @type {Node[]} */
558
+ let run = [];
559
+ /** @type {Set<Node>} nodes already read as part of the block that absorbed them */
560
+ const claimed = new Set();
561
+ const flush = () => {
562
+ if (!run.length) return;
563
+ const owner = parent.ownerDocument ?? /** @type {Document} */ (parent);
564
+ const p = owner.createElement('p');
565
+ for (const node of run) p.appendChild(node.cloneNode(true));
566
+ run = [];
567
+ if (hooks.onRun) { const pb = hooks.onRun(p); if (pb) blocks.push(pb); }
568
+ else blocks.push(...parseBlocks(p, ruleset, helpers));
569
+ };
570
+ for (const node of [...parent.childNodes]) {
571
+ if (claimed.has(node)) continue;
572
+ if (node.nodeType === Node.TEXT_NODE) { run.push(node); continue; }
573
+ if (node.nodeType !== Node.ELEMENT_NODE) continue;
574
+ const el = /** @type {Element} */ (node);
575
+ const kind = classify(el, ruleset);
576
+ if (kind === 'skip') continue;
577
+ if (kind === 'inline') { run.push(el); continue; }
578
+ flush();
579
+ if (kind === 'block') {
580
+ const entry = /** @type {{ BlockClass: any, rule: any }} */ (findRule(el, ruleset));
581
+ const { siblings, nodes } = claimSiblings(el, entry, helpers);
582
+ for (const n of nodes) claimed.add(n);
583
+ // An <img> inside a paragraph: text before, the image block, text after.
584
+ const embeds = entry.rule.embed || siblings.length ? [] : findEmbeds(el, ruleset, helpers);
585
+ if (embeds.length) {
586
+ for (const piece of splitAround(el, new Set(embeds))) {
587
+ blocks.push(...('embed' in piece ? parseBlocks(piece.embed, ruleset, helpers) : parseBlocks(piece.el, ruleset, helpers)));
588
+ }
589
+ } else {
590
+ blocks.push(...parseBlocks(el, ruleset, helpers, siblings));
591
+ }
592
+ } else {
593
+ blocks.push(...parseNodes(el, ruleset, helpers));
594
+ }
159
595
  }
160
- return [];
596
+ flush();
597
+ return blocks;
161
598
  }
162
599
 
600
+ /**
601
+ * Paste of `text/html` (web pages, Google Docs, Word, spreadsheets): turns the markup into blocks through the rules the registered block classes declare (`htmlRules`).
602
+ */
163
603
  export const HtmlPasteExtension = new Extension('html-paste', {
164
604
  pasteInterpreters: [
165
605
  {
166
606
  format: 'text/html',
167
607
  priority: 50,
608
+ // A spreadsheet range comes with an image of it next to its table: the table is what was copied.
609
+ outranksFiles: (raw) => /<table[\s>]/i.test(raw),
168
610
  /**
169
611
  * @param {string} raw
170
612
  * @param {import('../blocks/nabu.svelte.js').Nabu} nabu
@@ -177,20 +619,42 @@ export const HtmlPasteExtension = new Extension('html-paste', {
177
619
  if (!body) return null;
178
620
 
179
621
  const ruleset = buildRuleset(nabu);
622
+ // Set while the implicit paragraph of an inline-only fragment is read: its edge spaces are meaningful.
623
+ let keepEdges = false;
180
624
 
181
- /** @type {{ parseInline: typeof parseInline, parseBlock: (el: Element) => any, parseChildren: (el: Element) => any[] }} */
625
+ /** @type {{ parseInline: (el: Element) => import('loro-crdt').Delta<string>[], parseBlock: (el: Element) => any, parseBlocks: (el: Element) => any[], parseChildren: (el: Element) => any[] }} */
182
626
  const helpers = {
183
- parseInline: (el) => parseInline(el),
627
+ parseInline: (el) => parseInline(el, {}, { keepEdges }),
184
628
  parseBlock: (el) => parseBlock(el, ruleset, helpers),
185
- parseChildren: (el) => [...el.children]
186
- .map(child => parseBlock(child, ruleset, helpers))
187
- .filter(Boolean),
629
+ parseBlocks: (el) => parseBlocks(el, ruleset, helpers),
630
+ parseChildren: (el) => [...el.children].flatMap(child => parseBlocks(child, ruleset, helpers)),
188
631
  };
189
632
 
190
- const blocks = [...body.children]
191
- .flatMap(el => parseTopLevel(el, ruleset, helpers));
633
+ // Inline-only HTML (a part of a line copied from Docs / a browser): ONE inline fragment, merged at the
634
+ // caret like a plain-text paste, marks kept.
635
+ const inlineOnly = [...body.childNodes].every((n) => n.nodeType !== Node.ELEMENT_NODE
636
+ || ['skip', 'inline'].includes(classify(/** @type {Element} */ (n), ruleset)));
637
+ let blocks;
638
+ if (inlineOnly) {
639
+ blocks = parseNodes(body, ruleset, helpers, {
640
+ onRun: (p) => {
641
+ // Whitespace-only text directly under <body> is source formatting, not content.
642
+ const blank = (/** @type {Node | null} */ n) => n?.nodeType === Node.TEXT_NODE && !/\S/.test(n.textContent ?? '');
643
+ while (blank(p.firstChild)) p.removeChild(/** @type {Node} */ (p.firstChild));
644
+ while (blank(p.lastChild)) p.removeChild(/** @type {Node} */ (p.lastChild));
645
+ keepEdges = true;
646
+ try {
647
+ const pb = parseBlock(p, ruleset, helpers);
648
+ return pb ? { ...pb, partial: /** @type {const} */ ('both') } : null;
649
+ } finally { keepEdges = false; }
650
+ },
651
+ });
652
+ } else {
653
+ blocks = parseNodes(body, ruleset, helpers);
654
+ }
192
655
 
193
- return blocks.length ? { blocks } : null;
656
+ // `external`: the content comes from outside the editor (a web page, Docs…): remote media URLs may be imported.
657
+ return blocks.length ? { blocks, external: true } : null;
194
658
  } catch {
195
659
  return null;
196
660
  }