@aionbuilders/nabu 0.1.0-beta.0 → 0.1.1

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 (308) hide show
  1. package/CHANGELOG.md +531 -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 +195 -55
  12. package/dist/behaviors/text/text.behavior.svelte.js +531 -103
  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 +32 -18
  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 +1753 -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 +35 -14
  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 +55 -8
  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/composition.d.ts +28 -0
  253. package/dist/utils/composition.js +51 -0
  254. package/dist/utils/dom-scope.d.ts +14 -0
  255. package/dist/utils/dom-scope.js +20 -0
  256. package/dist/utils/drop.d.ts +160 -0
  257. package/dist/utils/drop.js +305 -0
  258. package/dist/utils/extensions.d.ts +439 -45
  259. package/dist/utils/extensions.js +271 -29
  260. package/dist/utils/html.d.ts +44 -0
  261. package/dist/utils/html.js +183 -0
  262. package/dist/utils/index.d.ts +3 -0
  263. package/dist/utils/index.js +3 -0
  264. package/dist/utils/keys.d.ts +120 -0
  265. package/dist/utils/keys.js +248 -0
  266. package/dist/utils/links.d.ts +22 -0
  267. package/dist/utils/links.js +34 -0
  268. package/dist/utils/placeholders.d.ts +81 -3
  269. package/dist/utils/placeholders.js +73 -3
  270. package/dist/utils/selection.svelte.d.ts +48 -20
  271. package/dist/utils/selection.svelte.js +60 -10
  272. package/dist/utils/spellcheck.d.ts +9 -0
  273. package/dist/utils/spellcheck.js +17 -0
  274. package/dist/utils/tab.d.ts +31 -0
  275. package/dist/utils/tab.js +117 -0
  276. package/dist/utils/words.d.ts +42 -0
  277. package/dist/utils/words.js +147 -0
  278. package/dist/vite.d.ts +9 -3
  279. package/dist/vite.js +19 -8
  280. package/package.json +56 -20
  281. package/dist/blocks/variable.svelte.d.ts +0 -47
  282. package/dist/blocks/variable.svelte.js +0 -51
  283. package/dist/blocks/zone/TemplateEditor.svelte +0 -308
  284. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +0 -11
  285. package/dist/blocks/zone/Zone.svelte +0 -272
  286. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  287. package/dist/blocks/zone/ZoneEditor.svelte +0 -289
  288. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +0 -11
  289. package/dist/blocks/zone/ZoneTemplatesList.svelte +0 -188
  290. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +0 -11
  291. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +0 -3
  292. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +0 -30
  293. package/dist/blocks/zone/index.d.ts +0 -2
  294. package/dist/blocks/zone/index.js +0 -2
  295. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  296. package/dist/blocks/zone/zone.extension.js +0 -237
  297. package/dist/blocks/zone/zone.svelte.d.ts +0 -221
  298. package/dist/blocks/zone/zone.svelte.js +0 -608
  299. package/dist/overlays/context/Context.svelte +0 -182
  300. package/dist/overlays/context/Context.svelte.d.ts +0 -17
  301. package/dist/overlays/context/collect.d.ts +0 -17
  302. package/dist/overlays/context/collect.js +0 -33
  303. package/dist/overlays/context/context.extension.d.ts +0 -2
  304. package/dist/overlays/context/context.extension.js +0 -8
  305. package/dist/overlays/context/context.svelte.d.ts +0 -82
  306. package/dist/overlays/context/context.svelte.js +0 -159
  307. package/dist/overlays/context/index.d.ts +0 -3
  308. package/dist/overlays/context/index.js +0 -3
@@ -4,18 +4,10 @@
4
4
 
5
5
  import { LoroText } from "loro-crdt";
6
6
  import { tick } from "svelte";
7
-
8
- /**
9
- * Escape special HTML characters in plain text.
10
- * @param {string} text
11
- * @returns {string}
12
- */
13
- function escapeHtml(text) {
14
- return text
15
- .replace(/&/g, '&')
16
- .replace(/</g, '&lt;')
17
- .replace(/>/g, '&gt;');
18
- }
7
+ import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
8
+ import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
9
+ import { countWords, wordDeleteRange } from "../../utils/words.js";
10
+ import { detectPlatform } from "../../utils/keys.js";
19
11
 
20
12
  /**
21
13
  * Converts a Loro text delta to inline HTML.
@@ -33,62 +25,202 @@ export function deltaToHtml(delta) {
33
25
  if (attrs.italic) text = `<em>${text}</em>`;
34
26
  if (attrs.underline) text = `<u>${text}</u>`;
35
27
  if (attrs.strikethrough) text = `<s>${text}</s>`;
36
- if (attrs.link) text = `<a href="${escapeHtml(String(attrs.link))}">${text}</a>`;
28
+ if (attrs.link) {
29
+ // An unsafe href (javascript:, data:…) never becomes a live link: the label survives, the <a> does not.
30
+ const href = sanitizeUrl(attrs.link, { kind: 'link' });
31
+ if (href !== null) text = `<a href="${escapeAttr(href)}">${text}</a>`;
32
+ }
37
33
  return text;
38
34
  }).join('');
39
35
  }
40
36
 
41
37
  /**
42
38
  * Converts a Loro text delta to inline Markdown.
39
+ * A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
40
+ * (a block that re-reads its own lines, like a callout body, keeps the plain newline).
43
41
  * @param {import('loro-crdt').Delta<string>[]} delta
42
+ * @param {{ rawBreaks?: boolean }} [options]
44
43
  * @returns {string}
45
44
  */
46
- export function deltaToMarkdown(delta) {
47
- return delta.map(op => {
48
- if (typeof op.insert !== 'string') return '';
49
- let text = op.insert;
45
+ export function deltaToMarkdown(delta, { rawBreaks = false } = {}) {
46
+ const ops = delta.filter((op) => typeof op.insert === 'string' && op.insert);
47
+ let out = '';
48
+ for (let i = 0; i < ops.length;) {
49
+ const link = ops[i].attributes?.link;
50
+ let j = i + 1;
51
+ while (j < ops.length && ops[j].attributes?.link === link) j++;
52
+ const run = markdownRuns(ops.slice(i, j), rawBreaks); // same href (or none): ONE `[…](href)`, marks inside
53
+ out += link ? `[${run}](${markdownDestination(String(link))})` : run;
54
+ i = j;
55
+ }
56
+ return escapeBlockStart(out);
57
+ }
58
+
59
+ /** Mark delimiters, outermost first (nesting order). Code is not here: a code span takes no other mark. */
60
+ const MARK_DELIMITERS = /** @type {const} */ ([
61
+ ['underline', '<u>', '</u>'],
62
+ ['strikethrough', '~~', '~~'],
63
+ ['bold', '**', '**'],
64
+ ['italic', '*', '*'],
65
+ ]);
66
+
67
+ /**
68
+ * Runs of text (no link boundary inside) as markdown. A mark spanning several runs is ONE delimiter pair
69
+ * (`**a *b* c**`); whitespace at the edge of a span moves outside the delimiters (`**a **` would not parse).
70
+ * @param {any[]} ops
71
+ * @param {boolean} rawBreaks
72
+ * @returns {string}
73
+ */
74
+ function markdownRuns(ops, rawBreaks) {
75
+ /** @type {Array<{ text?: string, raw?: boolean, open?: string, close?: string }>} */
76
+ let tokens = [];
77
+ /** @type {number[]} */
78
+ let active = [];
79
+ const closeFrom = (/** @type {number} */ k) => {
80
+ for (let j = active.length - 1; j >= k; j--) tokens.push({ close: MARK_DELIMITERS[active[j]][2] });
81
+ active = active.slice(0, k);
82
+ };
83
+ for (const op of ops) {
50
84
  const attrs = op.attributes || {};
51
- if (attrs.code) text = `\`${text}\``;
52
- else if (attrs.bold && attrs.italic) text = `***${text}***`;
53
- else if (attrs.bold) text = `**${text}**`;
54
- else if (attrs.italic) text = `*${text}*`;
55
- else if (attrs.strikethrough) text = `~~${text}~~`;
56
- else if (attrs.underline) text = `<u>${text}</u>`;
57
- if (attrs.link) text = `[${text}](${attrs.link})`;
58
- return text;
59
- }).join('');
85
+ if (attrs.code) { closeFrom(0); tokens.push({ text: markdownCodeSpan(op.insert), raw: true }); continue; }
86
+ const want = MARK_DELIMITERS.map((m, idx) => (attrs[m[0]] ? idx : -1)).filter((idx) => idx >= 0);
87
+ let k = 0;
88
+ while (k < active.length && k < want.length && active[k] === want[k]) k++;
89
+ closeFrom(k);
90
+ for (let j = k; j < want.length; j++) tokens.push({ open: MARK_DELIMITERS[want[j]][1] });
91
+ active = want;
92
+ tokens.push({ text: op.insert });
93
+ }
94
+ closeFrom(0);
95
+
96
+ // Whitespace at the inner edge of a delimiter run moves outside it.
97
+ for (let t = 0; t < tokens.length; t++) {
98
+ if (tokens[t].open !== undefined && tokens[t - 1]?.open === undefined) {
99
+ let j = t;
100
+ while (tokens[j + 1]?.open !== undefined) j++;
101
+ const next = tokens[j + 1];
102
+ const m = next && next.text !== undefined && !next.raw ? /^\s+/.exec(next.text) : null;
103
+ if (next && m) { next.text = /** @type {string} */ (next.text).slice(m[0].length); tokens.splice(t, 0, { text: m[0] }); t += 1; }
104
+ } else if (tokens[t].close !== undefined && tokens[t - 1]?.close === undefined) {
105
+ let j = t;
106
+ while (tokens[j + 1]?.close !== undefined) j++;
107
+ const prev = tokens[t - 1];
108
+ const m = prev && prev.text !== undefined && !prev.raw ? /\s+$/.exec(prev.text) : null;
109
+ if (prev && m) { prev.text = /** @type {string} */ (prev.text).slice(0, -m[0].length); tokens.splice(j + 1, 0, { text: m[0] }); }
110
+ }
111
+ }
112
+ // Drop the delimiter pairs left empty.
113
+ tokens = tokens.filter((tk) => tk.text !== '');
114
+ for (let t = 0; t < tokens.length - 1;) {
115
+ if (tokens[t].open !== undefined && tokens[t + 1].close !== undefined) { tokens.splice(t, 2); t = Math.max(0, t - 1); } else t++;
116
+ }
117
+ return tokens.map((tk) => tk.open ?? tk.close ?? (tk.raw ? tk.text : escapeMarkdownText(/** @type {string} */ (tk.text)).replace(/\n/g, rawBreaks ? '\n' : '\\\n'))).join('');
118
+ }
119
+
120
+ /** A code span: a backtick fence longer than any run inside, padded when the text touches a backtick or is space-wrapped. */
121
+ function markdownCodeSpan(/** @type {string} */ text) {
122
+ const runs = new Set((text.match(/`+/g) || []).map((r) => r.length));
123
+ let n = 1;
124
+ while (runs.has(n)) n++;
125
+ const fence = '`'.repeat(n);
126
+ const pad = /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : '';
127
+ return fence + pad + text + pad + fence;
128
+ }
129
+
130
+ /** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
131
+ export function markdownDestination(/** @type {string} */ href) {
132
+ let depth = 0;
133
+ let balanced = true;
134
+ for (const ch of href) {
135
+ if (ch === '(') depth++;
136
+ else if (ch === ')' && --depth < 0) balanced = false;
137
+ }
138
+ if (!href || depth !== 0 || !balanced || /[\s<>\u0000-\u001f]/.test(href)) return '<' + href.replace(/[<>\\]/g, (m) => '\\' + m) + '>';
139
+ return href.replace(/\\/g, '\\\\');
60
140
  }
61
141
 
62
142
  /**
63
143
  * @typedef {NabuNode<{type: "paragraph", text: LoroText}>} TextNode
64
144
  */
65
145
 
146
+ /** @type {Intl.Segmenter | null} */
147
+ const graphemeSegmenter = typeof Intl !== 'undefined' && 'Segmenter' in Intl ? new Intl.Segmenter(undefined, { granularity: 'grapheme' }) : null;
148
+
149
+ /**
150
+ * Length (UTF-16 units) of the user-perceived character starting at `index` — the unit one Delete press removes.
151
+ * `Intl.Segmenter` handles ZWJ sequences, flags and combining marks; without it a surrogate pair is kept whole.
152
+ * A caret inside a cluster deletes up to the end of that cluster. 0 at the end of the text.
153
+ * @param {string} text @param {number} index
154
+ */
155
+ export function nextGraphemeLength(text, index) {
156
+ if (index < 0 || index >= text.length) return 0;
157
+ if (graphemeSegmenter) {
158
+ const seg = graphemeSegmenter.segment(text).containing(index);
159
+ if (seg) return seg.index + seg.segment.length - index;
160
+ }
161
+ const code = text.charCodeAt(index);
162
+ const low = text.charCodeAt(index + 1);
163
+ return code >= 0xD800 && code <= 0xDBFF && low >= 0xDC00 && low <= 0xDFFF ? 2 : 1;
164
+ }
165
+
166
+ /**
167
+ * Length (UTF-16 units) of the user-perceived character ENDING at `index` — the unit one Backspace press removes.
168
+ * Mirror of {@link nextGraphemeLength}: `Intl.Segmenter` handles ZWJ sequences, flags and combining marks; without it a
169
+ * surrogate pair is kept whole. A caret inside a cluster deletes back to the start of that cluster. 0 at the start.
170
+ * @param {string} text @param {number} index
171
+ */
172
+ export function prevGraphemeLength(text, index) {
173
+ if (index <= 0 || index > text.length) return 0;
174
+ if (graphemeSegmenter) {
175
+ const seg = graphemeSegmenter.segment(text).containing(index - 1);
176
+ if (seg) return index - seg.index;
177
+ }
178
+ const low = text.charCodeAt(index - 1);
179
+ const high = text.charCodeAt(index - 2);
180
+ return low >= 0xDC00 && low <= 0xDFFF && high >= 0xD800 && high <= 0xDBFF ? 2 : 1;
181
+ }
182
+
183
+ /**
184
+ * The editing of a block's rich text: wraps a Loro text and offers the reactive `text` and `delta`, the selection in that text, and insertion, deletion, splitting, marks and links. Text blocks use it through `TextBlock`; a container with a header (list item, toggle) owns one.
185
+ */
66
186
  export class TextBehavior {
67
187
  /** @param {Block} block @param {LoroText} [container] */
68
188
  constructor(block, container) {
189
+ /** @public */
69
190
  this.block = block;
70
191
  this.nabu = block.nabu;
71
192
  const node = /** @type {TextNode} */ (block.node);
72
- /** @type {LoroText} */
193
+ /**
194
+ * @type {LoroText}
195
+ * @public
196
+ */
73
197
  this.container = container ?? node.data.get("text") ?? node.data.setContainer("text", new LoroText());
198
+ /** @public */
74
199
  this.text = $state(this.container.toString());
200
+ /** @public */
75
201
  this.delta = $state(this.container.toDelta());
76
202
  this.container.subscribe(() => {
77
203
  this.text = this.container.toString();
78
204
  this.delta = this.container.toDelta();
205
+ this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
79
206
  });
80
207
  }
81
208
 
209
+ /** @public */
82
210
  selection = $derived(this.block.element && this.block.nabu.selection && this.getSelection(this.block.element, this.block.nabu.selection));
83
211
 
212
+ /** @public */
84
213
  positions = $derived(this.text.length + 1);
85
214
 
86
215
  /**
87
- * Number of whitespace-separated words in this text.
216
+ * Number of words in this text: segmented with `Intl.Segmenter` in the language of the editor (`nabu.lang`) when the platform
217
+ * has it, so Chinese or Japanese text counts its words rather than one per sentence; whitespace-separated otherwise. See
218
+ * `utils/words.js`. Reactive in the text and in `nabu.lang`.
88
219
  * @returns {number}
220
+ * @public
89
221
  */
90
222
  get wordCount() {
91
- return this.text.trim().split(/\s+/).filter(Boolean).length;
223
+ return countWords(this.text, this.nabu?.lang);
92
224
  }
93
225
 
94
226
  /**
@@ -108,11 +240,11 @@ export class TextBehavior {
108
240
  let to = this.text.length;
109
241
 
110
242
  if (containsStart) {
111
- from = this.calculateOffset(globalRange.startContainer, globalRange.startOffset);
243
+ from = this.modelOffset(globalRange.startContainer, globalRange.startOffset);
112
244
  }
113
245
 
114
246
  if (containsEnd) {
115
- to = this.calculateOffset(globalRange.endContainer, globalRange.endOffset);
247
+ to = this.modelOffset(globalRange.endContainer, globalRange.endOffset);
116
248
  }
117
249
 
118
250
  return {
@@ -137,11 +269,86 @@ export class TextBehavior {
137
269
  return range.toString().length;
138
270
  }
139
271
 
140
- /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
272
+ /**
273
+ * {@link TextBehavior#calculateOffset} bounded by the MODEL text: an empty text renders a lone "\n" placeholder, and a caret
274
+ * after it is still offset 0, not 1 (P-108). (Not during an IME composition: the browser's text is ahead of the model then.)
275
+ * @param {Node} node @param {number} offset @param {HTMLElement?} [element]
276
+ */
277
+ modelOffset(node, offset, element = this.block.element) {
278
+ const at = this.calculateOffset(node, offset, element);
279
+ return this.nabu.composing ? at : Math.min(at, this.text.length);
280
+ }
281
+
282
+ /** The render of an EMPTY block when an IME composition started (Svelte's own child nodes and their text), to put back if it is canceled. @type {{ nodes: Node[], data: string[] } | null} */
283
+ #emptySnapshot = null;
284
+
285
+ /** Svelte's own nodes around a trailing render filler when an IME composition started: its text nodes and the filler with its place. @type {{ texts: Set<Node>, filler: Element, parent: Node, next: Node | null } | null} */
286
+ #compositionSnapshot = null;
287
+
288
+ /**
289
+ * IME composition starts. With a trailing render filler (`<br data-nabu-filler>`, the empty last line after a "\n")
290
+ * the browser puts the composed text in a NEW text node before the filler (and may swap the filler for a `<br>` of
291
+ * its own) — nodes Svelte does not know, which would stay next to the ones it updates once the model catches up
292
+ * (text shown twice). Remember Svelte's nodes so {@link TextBehavior#restoreAfterComposition} can undo the browser's
293
+ * additions at the end. No filler: nothing to do.
294
+ */
295
+ snapshotForComposition() {
296
+ const element = this.block.element;
297
+ this.#compositionSnapshot = null;
298
+ this.#emptySnapshot = null;
299
+ // An EMPTY block renders a lone "\n" text node: a canceled composition makes the browser swap it for a <br> (caret lost).
300
+ if (element && !this.text) {
301
+ const nodes = [...element.childNodes];
302
+ this.#emptySnapshot = { nodes, data: nodes.map((n) => n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n).data : '') };
303
+ return;
304
+ }
305
+ const filler = element?.querySelector('[data-nabu-filler]');
306
+ if (!element || !filler?.parentNode) return;
307
+ const texts = new Set();
308
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
309
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) texts.add(n);
310
+ this.#compositionSnapshot = { texts, filler, parent: filler.parentNode, next: filler.nextSibling };
311
+ }
312
+
313
+ /**
314
+ * End of a composition begun next to a filler, BEFORE the composed text reaches the model: remove the text nodes and
315
+ * `<br>` the browser created meanwhile (the composed text is committed to the model, which the next render shows
316
+ * through Svelte's own nodes); a canceled composition (`composedText` empty) gets its filler back.
317
+ * @param {string} composedText
318
+ */
319
+ restoreAfterComposition(composedText) {
320
+ const snap = this.#compositionSnapshot;
321
+ this.#compositionSnapshot = null;
322
+ const element = this.block.element;
323
+ const empty = this.#emptySnapshot;
324
+ this.#emptySnapshot = null;
325
+ if (empty && element && !composedText) {
326
+ // Canceled in an empty block: the render text node (not a browser <br>) with its text, as Svelte left it.
327
+ element.replaceChildren(...empty.nodes);
328
+ empty.nodes.forEach((n, i) => { if (n.nodeType === Node.TEXT_NODE && /** @type {Text} */ (n).data !== empty.data[i]) /** @type {Text} */ (n).data = empty.data[i]; });
329
+ return;
330
+ }
331
+ if (!snap || !element) return;
332
+ /** @type {Node[]} */
333
+ const stray = [];
334
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
335
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) if (!snap.texts.has(n)) stray.push(n);
336
+ for (const br of element.querySelectorAll('br')) if (br !== snap.filler) stray.push(br);
337
+ for (const n of stray) n.parentNode?.removeChild(n);
338
+ if (!composedText && !snap.filler.isConnected) {
339
+ snap.parent.insertBefore(snap.filler, snap.next?.parentNode === snap.parent ? snap.next : null);
340
+ }
341
+ }
342
+
343
+ /**
344
+ * @param {InputEvent} event
345
+ * @param {ReturnType<TextBehavior["getSelection"]>} [selection]
346
+ * @public
347
+ */
141
348
  handleBeforeInput(event, selection = this.selection) {
142
349
  // Hook system (Markdown shortcuts, de-transformation, structural guards…).
143
350
  // `transformsEnabled: false` (e.g. code blocks) only suppresses transforms,
144
- // which fire on insertions — deletion hooks (block exit, zone guards) still run.
351
+ // which fire on insertions — deletion hooks (block exit, structural guards) still run.
145
352
  const isInsertion = event.inputType === "insertText"
146
353
  || event.inputType === "insertParagraph"
147
354
  || event.inputType === "insertLineBreak"
@@ -174,7 +381,32 @@ export class TextBehavior {
174
381
  case "deleteWordForward":
175
382
  return this.handleDeleteWordForward(event, selection);
176
383
  case "deleteSoftLineBackward":
384
+ case "deleteHardLineBackward":
177
385
  return this.handleDeleteSoftLineBackward(event, selection);
386
+ case "deleteSoftLineForward":
387
+ case "deleteHardLineForward":
388
+ return this.handleDeleteSoftLineForward(event, selection);
389
+ case "deleteEntireSoftLine":
390
+ case "deleteEntireHardLine":
391
+ return this.handleDeleteEntireLine(event, selection);
392
+ case "deleteContent":
393
+ return this.handleDeleteContent(event, selection);
394
+ case "insertReplacementText":
395
+ return this.handleInsertReplacementText(event, selection);
396
+ case "insertFromYank":
397
+ return this.handleInsertFromYank(event, selection);
398
+ case "insertTranspose":
399
+ return this.handleInsertTranspose(event, selection);
400
+ case "formatBold":
401
+ case "formatItalic":
402
+ case "formatUnderline":
403
+ case "formatStrikeThrough":
404
+ case "formatSubscript":
405
+ case "formatSuperscript":
406
+ case "formatRemove":
407
+ // Formatting is the rich-text extension's business (its `onBeforeInput` hook already ran); without it: nothing.
408
+ event.preventDefault();
409
+ return true;
178
410
  case "insertParagraph":
179
411
  return this.handleInsertParagraph(event, selection);
180
412
  case "historyUndo":
@@ -241,6 +473,19 @@ export class TextBehavior {
241
473
  tick().then(() => this.nabu.selection.setCursor(this.block, sel.from + 1));
242
474
  }
243
475
 
476
+ /**
477
+ * Whether an extension vetoes the merge of two text blocks that Backspace / Delete at a block boundary is about to do
478
+ * (the `onBeforeMerge(nabu, survivor, victim)` hook; returning `nabu.BREAK` refuses: nothing is merged, nothing is
479
+ * deleted). The engine names no reason: an extension may protect a structural boundary between the two blocks.
480
+ * @param {Block} survivor @param {Block} victim
481
+ */
482
+ #mergeRefused(survivor, victim) {
483
+ const hooks = this.nabu.hooks.get("onBeforeMerge");
484
+ if (!hooks) return false;
485
+ for (const hook of hooks) if (hook(this.nabu, survivor, victim) === this.nabu.BREAK) return true;
486
+ return false;
487
+ }
488
+
244
489
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
245
490
  handleDeleteContentBackward(event, sel = this.selection) {
246
491
  if (!sel) return;
@@ -250,6 +495,7 @@ export class TextBehavior {
250
495
  const previousBehavior = previousBlock?.behaviors.get("text");
251
496
  if (previousBehavior && previousBehavior instanceof TextBehavior) {
252
497
  event.preventDefault();
498
+ if (this.#mergeRefused(previousBlock, this.block)) return true;
253
499
  const previousLength = previousBehavior.text.length;
254
500
  // previousBehavior.delta([
255
501
  // { retain: previousLength },
@@ -263,8 +509,11 @@ export class TextBehavior {
263
509
  }
264
510
  } else {
265
511
  event.preventDefault();
266
- const length = sel.isCollapsed ? 1 : sel.to - sel.from;
267
- const index = sel.isCollapsed ? sel.from - 1 : sel.from;
512
+ // A collapsed caret deletes the PREVIOUS grapheme cluster (a ZWJ emoji, a flag, a letter + combining accent,
513
+ // a surrogate pair — never half of one); a selection inside the block is deleted whole.
514
+ const length = sel.isCollapsed ? prevGraphemeLength(this.text, sel.from) : sel.to - sel.from;
515
+ const index = sel.isCollapsed ? sel.from - length : sel.from;
516
+ if (length <= 0) return true;
268
517
  this.delete({index, length});
269
518
  this.block.commit();
270
519
 
@@ -282,6 +531,7 @@ export class TextBehavior {
282
531
  const nextBehavior = nextBlock?.behaviors.get("text");
283
532
  if (nextBehavior && nextBehavior instanceof TextBehavior) {
284
533
  event.preventDefault();
534
+ if (this.#mergeRefused(this.block, nextBlock)) return true;
285
535
  // this.delta([
286
536
  // { retain: this.container.length },
287
537
  // ...nextBehavior.container.toDelta()
@@ -294,88 +544,222 @@ export class TextBehavior {
294
544
 
295
545
  tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
296
546
  }
547
+ return;
297
548
  }
549
+ // Everywhere else the native mutation is prevented, so the key must be handled here or it is swallowed:
550
+ // a selection inside the block is deleted whole, a collapsed caret deletes the NEXT grapheme cluster
551
+ // (a ZWJ emoji, a flag, a letter + combining accent, a surrogate pair — never half of one).
552
+ event.preventDefault();
553
+ const index = sel.from;
554
+ const length = sel.isCollapsed ? nextGraphemeLength(this.text, sel.from) : sel.to - sel.from;
555
+ if (length <= 0) return true;
556
+ this.delete({ index, length });
557
+ this.block.commit();
558
+ tick().then(() => this.nabu.selection.setCursor(this.block, index));
559
+ return true;
298
560
  }
299
561
 
300
562
  /**
301
- * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux,
302
- * Option+Delete on Mac), including the whitespace that precedes it
303
- * so no orphan space is left behind (issue #4).
563
+ * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux, Option+Backspace on Mac): the whitespace between the
564
+ * caret and the word goes with it, and the caret lands where the word started ("one two |" -> "one |", issue #4).
565
+ *
566
+ * For a collapsed selection the range is computed from the model text, never from `event.getTargetRanges()`: browsers
567
+ * disagree on it (Chromium stops right after the previous space, leaving "one two " from "one two three"), so the
568
+ * behavior would differ per engine. The rules (words by `Intl.Segmenter`, punctuation, line breaks) are in
569
+ * {@link wordDeleteRange}. A selection is deleted whole.
304
570
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
305
571
  */
306
572
  handleDeleteWordBackward(event, sel = this.selection) {
307
573
  if (!sel) return;
308
- if (!sel.isCollapsed) {
309
- this.delete({ index: sel.from, length: sel.to - sel.from });
574
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
575
+ const { from } = wordDeleteRange(this.text, sel.from, 'backward', { lang: this.nabu?.lang });
576
+ return this.#deleteSpan(from, sel.from);
577
+ }
578
+
579
+ /**
580
+ * Deletes the word after the cursor (Ctrl+Delete on Win/Linux, Option+Fn+Delete on Mac). Like the backward deletion it is
581
+ * resolved from the model text only (`getTargetRanges()` is engine-dependent). macOS deletes up to the end of the next
582
+ * word ("one |two three" -> "one | three"), Windows up to the start of the one after ("one |two three" -> "one |three");
583
+ * see {@link wordDeleteRange}. A selection is deleted whole.
584
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
585
+ */
586
+ handleDeleteWordForward(event, sel = this.selection) {
587
+ if (!sel) return;
588
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
589
+ const { to } = wordDeleteRange(this.text, sel.from, 'forward', { platform: detectPlatform(), lang: this.nabu?.lang });
590
+ return this.#deleteSpan(sel.from, to);
591
+ }
592
+
593
+ /**
594
+ * Start of the line holding `index` (after the previous "\n", or 0). A model line is a "\n"-delimited run: soft and
595
+ * hard lines are the same thing here (the model knows no visual wrapping).
596
+ * @param {number} index
597
+ */
598
+ #lineStart(index) {
599
+ return index <= 0 ? 0 : this.text.lastIndexOf('\n', index - 1) + 1;
600
+ }
601
+
602
+ /** End of the line holding `index` (the next "\n", or the end of the text). @param {number} index */
603
+ #lineEnd(index) {
604
+ const nl = this.text.indexOf('\n', index);
605
+ return nl === -1 ? this.text.length : nl;
606
+ }
607
+
608
+ /**
609
+ * Deletes `[from, to)` as ONE edit (one commit), caret at `from`. Always returns true (the event is handled).
610
+ * @param {number} from @param {number} to
611
+ */
612
+ #deleteSpan(from, to) {
613
+ if (to > from) {
614
+ this.delete({ index: from, length: to - from });
310
615
  this.block.commit();
311
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
312
- return true;
313
- }
314
- // Prefer getTargetRanges() when available (more reliable cross-platform)
315
- const ranges = event.getTargetRanges?.();
316
- let deleteFrom;
317
- if (ranges?.length) {
318
- const r = ranges[0];
319
- deleteFrom = this.calculateOffset(r.startContainer, r.startOffset);
320
- } else {
321
- // FIX issue #4 : inclure le whitespace AVANT le mot dans la suppression
322
- const textBefore = this.text.slice(0, sel.from);
323
- // \s* leading : l'espace qui précède le mot est supprimé aussi (comportement Mac)
324
- const wordMatch = textBefore.match(/(\s*\S+\s*)$/);
325
- deleteFrom = wordMatch ? sel.from - wordMatch[0].length : 0;
616
+ tick().then(() => this.nabu.selection.setCursor(this.block, from));
326
617
  }
327
- const len = sel.from - deleteFrom;
328
- if (len > 0) this.delete({ index: deleteFrom, length: len });
329
- this.block.commit();
330
- tick().then(() => this.nabu.selection.setCursor(this.block, deleteFrom));
331
618
  return true;
332
619
  }
333
620
 
334
621
  /**
335
- * Deletes the word after the cursor (Ctrl+Delete / Option+Fn+Delete),
336
- * including its trailing whitespace/punctuation.
622
+ * Deletes from the start of the current line to the cursor (Cmd+Backspace on Mac; `deleteHardLineBackward`).
623
+ * A selection inside the block is deleted whole.
337
624
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
338
625
  */
339
- handleDeleteWordForward(event, sel = this.selection) {
626
+ handleDeleteSoftLineBackward(event, sel = this.selection) {
340
627
  if (!sel) return;
341
- if (!sel.isCollapsed) {
342
- this.delete({ index: sel.from, length: sel.to - sel.from });
343
- this.block.commit();
344
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
345
- return true;
628
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
629
+ return this.#deleteSpan(this.#lineStart(sel.from), sel.from);
630
+ }
631
+
632
+ /**
633
+ * Deletes from the cursor to the end of the current line (Cmd+Fn+Delete, Ctrl+K style; `deleteHardLineForward`).
634
+ * At the end of a line (before a "\n") or of the block nothing is deleted. A selection is deleted whole.
635
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
636
+ */
637
+ handleDeleteSoftLineForward(event, sel = this.selection) {
638
+ if (!sel) return;
639
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
640
+ return this.#deleteSpan(sel.from, this.#lineEnd(sel.from));
641
+ }
642
+
643
+ /**
644
+ * Deletes the whole line(s) touched by the selection (`deleteEntireSoftLine`): the text between the surrounding "\n"
645
+ * (or block edges), the line breaks themselves are kept. Caret at the start of the emptied line.
646
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
647
+ */
648
+ handleDeleteEntireLine(event, sel = this.selection) {
649
+ if (!sel) return;
650
+ return this.#deleteSpan(this.#lineStart(sel.from), this.#lineEnd(sel.to));
651
+ }
652
+
653
+ /**
654
+ * `deleteContent`: delete the selection (no direction). A collapsed caret deletes nothing.
655
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
656
+ */
657
+ handleDeleteContent(event, sel = this.selection) {
658
+ if (!sel) return;
659
+ return this.#deleteSpan(sel.from, sel.to);
660
+ }
661
+
662
+ /**
663
+ * The attributes (marks) of the run holding the character at `index`, or null.
664
+ * @param {number} index
665
+ * @returns {Record<string, any> | null}
666
+ */
667
+ #marksAt(index) {
668
+ let offset = 0;
669
+ for (const op of this.container.toDelta()) {
670
+ if (typeof op.insert !== 'string') continue;
671
+ const end = offset + op.insert.length;
672
+ if (index >= offset && index < end) return op.attributes ? { ...op.attributes } : null;
673
+ offset = end;
346
674
  }
347
- const ranges = event.getTargetRanges?.();
348
- let deleteTo;
349
- if (ranges?.length) {
350
- const r = ranges[0];
351
- deleteTo = this.calculateOffset(r.endContainer, r.endOffset);
675
+ return null;
676
+ }
677
+
678
+ /**
679
+ * Inserts `text` at `index` carrying `marks` (the inserted run only; marks are exact, they never leak to neighbours).
680
+ * @param {number} index @param {string} text @param {Record<string, any> | null} marks
681
+ */
682
+ #insertWithMarks(index, text, marks) {
683
+ if (!text) return;
684
+ this.insert(index, text);
685
+ if (!marks) return;
686
+ const range = { from: index, to: index + text.length, isCollapsed: false, direction: /** @type {const} */ ('none') };
687
+ for (const [name, value] of Object.entries(marks)) if (value) this.applyMark(name, value, range);
688
+ }
689
+
690
+ /**
691
+ * `insertReplacementText`: a spellcheck / autocorrect replacement. The replacement text comes in
692
+ * `dataTransfer` (`text/plain`) or `data`; the range to replace in `getTargetRanges()` (mapped to model offsets), else
693
+ * the selection. The replaced run's marks are kept on the new text. One edit (one undo step), caret after it.
694
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
695
+ */
696
+ handleInsertReplacementText(event, sel = this.selection) {
697
+ const text = event.dataTransfer?.getData?.('text/plain') || event.data || '';
698
+ const element = this.block.element;
699
+ const target = typeof event.getTargetRanges === 'function' ? event.getTargetRanges()[0] : null;
700
+ let from;
701
+ let to;
702
+ if (target && element && element.contains(target.startContainer) && element.contains(target.endContainer)) {
703
+ from = this.calculateOffset(target.startContainer, target.startOffset);
704
+ to = this.calculateOffset(target.endContainer, target.endOffset);
705
+ } else if (sel) {
706
+ from = sel.from;
707
+ to = sel.to;
352
708
  } else {
353
- const textAfter = this.text.slice(sel.from);
354
- // Inclure le whitespace leading + le mot + son trailing whitespace
355
- const wordMatch = textAfter.match(/^(\s*\S+\s*)/);
356
- deleteTo = sel.from + (wordMatch ? wordMatch[0].length : textAfter.length);
709
+ return true;
357
710
  }
358
- const len = deleteTo - sel.from;
359
- if (len > 0) this.delete({ index: sel.from, length: len });
711
+ if (to < from) [from, to] = [to, from];
712
+ from = Math.max(0, Math.min(from, this.text.length));
713
+ to = Math.max(from, Math.min(to, this.text.length));
714
+ if (from === to && !text) return true;
715
+ const marks = from < to ? this.#marksAt(from) : null;
716
+ if (to > from) this.delete({ index: from, length: to - from });
717
+ this.#insertWithMarks(from, text, marks);
718
+ this.nabu.storedMarks = null;
360
719
  this.block.commit();
361
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
720
+ tick().then(() => this.nabu.selection.setCursor(this.block, from + text.length));
362
721
  return true;
363
722
  }
364
723
 
365
724
  /**
366
- * Deletes from the start of the current soft line to the cursor
367
- * (Cmd+Backspace on Mac).
725
+ * `insertFromYank` (Emacs-style yank on macOS): the text is inserted as plain text at the caret, replacing the selection.
726
+ * No input rule runs (it is a paste, not typing).
368
727
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
369
728
  */
370
- handleDeleteSoftLineBackward(event, sel = this.selection) {
729
+ handleInsertFromYank(event, sel = this.selection) {
371
730
  if (!sel) return;
372
- const lastNL = this.text.lastIndexOf('\n', sel.from - 1);
373
- const deleteFrom = lastNL === -1 ? 0 : lastNL + 1;
374
- if (deleteFrom < sel.from) {
375
- this.delete({ index: deleteFrom, length: sel.from - deleteFrom });
376
- this.block.commit();
377
- tick().then(() => this.nabu.selection.setCursor(this.block, deleteFrom));
378
- }
731
+ const text = event.data || event.dataTransfer?.getData?.('text/plain') || '';
732
+ if (!text) return true;
733
+ if (!sel.isCollapsed) this.delete({ index: sel.from, length: sel.to - sel.from });
734
+ this.insert(sel.from, text);
735
+ this.nabu.storedMarks = null;
736
+ this.block.commit();
737
+ tick().then(() => this.nabu.selection.setCursor(this.block, sel.from + text.length));
738
+ return true;
739
+ }
740
+
741
+ /**
742
+ * `insertTranspose` (macOS Ctrl+T): swaps the two graphemes around the caret; at the end of the text, the last two.
743
+ * Marks travel with their character. No-op with a selection, at the start, with a single character or across a line break.
744
+ * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
745
+ */
746
+ handleInsertTranspose(event, sel = this.selection) {
747
+ if (!sel || !sel.isCollapsed) return true;
748
+ const text = this.text;
749
+ const end = sel.from >= text.length ? text.length : sel.from + nextGraphemeLength(text, sel.from);
750
+ const middle = end - prevGraphemeLength(text, end); // boundary between the two graphemes
751
+ const start = middle - prevGraphemeLength(text, middle);
752
+ if (middle <= start || end <= middle) return true;
753
+ const left = text.slice(start, middle);
754
+ const right = text.slice(middle, end);
755
+ if (left === '\n' || right === '\n') return true;
756
+ const leftMarks = this.#marksAt(start);
757
+ const rightMarks = this.#marksAt(middle);
758
+ this.delete({ index: start, length: end - start });
759
+ this.#insertWithMarks(start, right, rightMarks);
760
+ this.#insertWithMarks(start + right.length, left, leftMarks);
761
+ this.block.commit();
762
+ tick().then(() => this.nabu.selection.setCursor(this.block, end));
379
763
  return true;
380
764
  }
381
765
 
@@ -400,6 +784,7 @@ export class TextBehavior {
400
784
  * Retrouve le nœud texte et l'offset DOM pour un offset Modèle donné
401
785
  * @param {number} targetOffset
402
786
  * @param {HTMLElement?} [element]
787
+ * @public
403
788
  */
404
789
  getDOMPoint(targetOffset, element = this.block.element) {
405
790
  if (!element) return null;
@@ -421,12 +806,21 @@ export class TextBehavior {
421
806
  return { node: element, offset: element.childNodes.length };
422
807
  }
423
808
 
424
- /** @param {number} index @param {string} text */
809
+ /**
810
+ * @param {number} index
811
+ * @param {string} text
812
+ * @public
813
+ */
425
814
  insert(index, text) {
426
- this.container.insert(index, text);
815
+ // Never past the end of the text, whatever the caller computed (a stale DOM offset would panic Loro).
816
+ this.container.insert(Math.max(0, Math.min(index, this.container.length)), text);
427
817
  }
428
818
 
429
- /** @param {Parameters<Block["delete"]>[0]} [deletion] @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
819
+ /**
820
+ * @param {Parameters<Block["delete"]>[0]} [deletion]
821
+ * @param {ReturnType<TextBehavior["getSelection"]>} [selection]
822
+ * @public
823
+ */
430
824
  delete(deletion, selection = this.selection) {
431
825
  const l = this.container.length;
432
826
  let from = deletion?.from ?? selection?.from ?? 0;
@@ -438,7 +832,10 @@ export class TextBehavior {
438
832
  this.container.delete(index, length);
439
833
  }
440
834
 
441
- /** @param {import('loro-crdt').Delta<string>[]} data */
835
+ /**
836
+ * @param {import('loro-crdt').Delta<string>[]} data
837
+ * @public
838
+ */
442
839
  applyDelta(data = []) {
443
840
  this.container.applyDelta(data);
444
841
  }
@@ -447,6 +844,7 @@ export class TextBehavior {
447
844
  * @param {Parameters<Block["split"]>[0]} [options]
448
845
  * @param {ReturnType<TextBehavior["getSelection"]>} [selection]
449
846
  * @returns {ReturnType<Block["split"]>}
847
+ * @public
450
848
  */
451
849
  split(options, selection = this.selection) {
452
850
  const sel = selection;
@@ -457,19 +855,37 @@ export class TextBehavior {
457
855
  return this.block.ascend("onSplit", null, { offset: from, delta: this.container.sliceDelta(from, to)});
458
856
  }
459
857
 
460
- /** @param {string} markName @param {any} value @param {ReturnType<TextBehavior["getSelection"]>} sel */
858
+ /**
859
+ * @param {string} markName
860
+ * @param {any} value
861
+ * @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
862
+ * @public
863
+ */
461
864
  applyMark(markName, value, sel) {
462
865
  if (!sel || sel.isCollapsed) return;
866
+ // Model guard: an unsafe link (javascript:…) never enters the document through any mark API.
867
+ if (markName === 'link' && sanitizeUrl(value, { kind: 'link' }) === null) {
868
+ this.nabu.warn('applyMark: refused unsafe link href', value);
869
+ return;
870
+ }
463
871
  this.container.mark({ start: sel.from, end: sel.to }, markName, value);
464
872
  }
465
873
 
466
- /** @param {string} markName @param {ReturnType<TextBehavior["getSelection"]>} sel */
874
+ /**
875
+ * @param {string} markName
876
+ * @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
877
+ * @public
878
+ */
467
879
  removeMark(markName, sel) {
468
880
  if (!sel || sel.isCollapsed) return;
469
881
  this.container.unmark({ start: sel.from, end: sel.to }, markName);
470
882
  }
471
883
 
472
- /** @param {string} markName @param {ReturnType<TextBehavior["getSelection"]>} sel */
884
+ /**
885
+ * @param {string} markName
886
+ * @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
887
+ * @public
888
+ */
473
889
  isMarkActive(markName, sel) {
474
890
  if (!sel || sel.isCollapsed) return false;
475
891
  const delta = this.container.toDelta();
@@ -485,7 +901,12 @@ export class TextBehavior {
485
901
  return true;
486
902
  }
487
903
 
488
- /** @param {string} markName @param {any} value @param {ReturnType<TextBehavior["getSelection"]>} sel */
904
+ /**
905
+ * @param {string} markName
906
+ * @param {any} value
907
+ * @param {Pick<NonNullable<ReturnType<TextBehavior["getSelection"]>>, 'from' | 'to' | 'isCollapsed'> | null} sel
908
+ * @public
909
+ */
489
910
  toggleMark(markName, value, sel) {
490
911
  if (!sel || sel.isCollapsed) return;
491
912
  if (this.isMarkActive(markName, sel)) {
@@ -495,14 +916,17 @@ export class TextBehavior {
495
916
  }
496
917
  }
497
918
 
498
- /** @returns {string} */
499
- toMarkdown() {
500
- return deltaToMarkdown(this.delta);
919
+ /** @param {{ rawBreaks?: boolean }} [options] see {@link deltaToMarkdown}
920
+ * @public
921
+ * @returns {string} */
922
+ toMarkdown(options) {
923
+ return deltaToMarkdown(this.delta, options);
501
924
  }
502
925
 
503
926
  /**
504
927
  * Converts the text delta to a Slate-like JSON format.
505
928
  * @returns {{text: string, [mark: string]: any}[]}
929
+ * @public
506
930
  */
507
931
  toJSON() {
508
932
  return this.delta
@@ -516,8 +940,9 @@ export class TextBehavior {
516
940
 
517
941
  /**
518
942
  * Serializes a (partial) range of this block's text as a PasteBlock.
519
- * @param {{ from?: number, to?: number, partial?: 'start'|'end'|'both'|false, props?: Record<string,any> }} [context]
520
- * @returns {import('../utils/extensions.js').PasteBlock}
943
+ * @param {{ from?: number, to?: number | null, partial?: 'start'|'end'|'both'|false, props?: Record<string,any> }} [context]
944
+ * @returns {import('../../utils/extensions.js').PasteBlock}
945
+ * @public
521
946
  */
522
947
  toClipboardBlock({ from = 0, to = null, partial = false, props = {} } = {}) {
523
948
  const end = to ?? this.container.length;
@@ -529,7 +954,10 @@ export class TextBehavior {
529
954
  };
530
955
  }
531
956
 
532
- /** @param {Block} other */
957
+ /**
958
+ * @param {Block} other
959
+ * @public
960
+ */
533
961
  absorbs(other) {
534
962
  const otherBehavior = other.behaviors.get("text");
535
963
  if (!otherBehavior || !(otherBehavior instanceof TextBehavior)) return false;