@aionbuilders/nabu 0.1.0-alpha.9 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (319) hide show
  1. package/CHANGELOG.md +523 -0
  2. package/LICENSE +21 -0
  3. package/README.md +82 -144
  4. package/dist/behaviors/text/RichText.svelte +25 -2
  5. package/dist/behaviors/text/index.d.ts +2 -0
  6. package/dist/behaviors/text/index.js +2 -0
  7. package/dist/behaviors/text/markdown-shortcuts.extension.d.ts +5 -0
  8. package/dist/behaviors/text/markdown-shortcuts.extension.js +79 -0
  9. package/dist/behaviors/text/markdown-syntax.d.ts +42 -0
  10. package/dist/behaviors/text/markdown-syntax.js +81 -0
  11. package/dist/behaviors/text/rich-text.extension.d.ts +3 -0
  12. package/dist/behaviors/text/rich-text.extension.js +135 -53
  13. package/dist/behaviors/text/text.behavior.svelte.d.ts +217 -42
  14. package/dist/behaviors/text/text.behavior.svelte.js +657 -55
  15. package/dist/behaviors/text/typography.extension.d.ts +7 -0
  16. package/dist/behaviors/text/typography.extension.js +25 -0
  17. package/dist/blocks/Block.svelte +5 -2
  18. package/dist/blocks/BlockList.svelte +48 -0
  19. package/dist/blocks/BlockList.svelte.d.ts +17 -0
  20. package/dist/blocks/Nabu.svelte +180 -14
  21. package/dist/blocks/Nabu.svelte.d.ts +13 -0
  22. package/dist/blocks/block.extension.d.ts +3 -0
  23. package/dist/blocks/block.extension.js +8 -9
  24. package/dist/blocks/block.svelte.d.ts +356 -68
  25. package/dist/blocks/block.svelte.js +388 -42
  26. package/dist/blocks/blockquote/Blockquote.svelte +39 -0
  27. package/dist/blocks/blockquote/Blockquote.svelte.d.ts +11 -0
  28. package/dist/blocks/blockquote/blockquote.extension.d.ts +4 -0
  29. package/dist/blocks/blockquote/blockquote.extension.js +80 -0
  30. package/dist/blocks/blockquote/blockquote.svelte.d.ts +63 -0
  31. package/dist/blocks/blockquote/blockquote.svelte.js +136 -0
  32. package/dist/blocks/blockquote/index.d.ts +3 -0
  33. package/dist/blocks/blockquote/index.js +3 -0
  34. package/dist/blocks/callout/Callout.svelte +67 -0
  35. package/dist/blocks/callout/Callout.svelte.d.ts +11 -0
  36. package/dist/blocks/callout/callout.extension.d.ts +4 -0
  37. package/dist/blocks/callout/callout.extension.js +84 -0
  38. package/dist/blocks/callout/callout.svelte.d.ts +80 -0
  39. package/dist/blocks/callout/callout.svelte.js +189 -0
  40. package/dist/blocks/callout/index.d.ts +3 -0
  41. package/dist/blocks/callout/index.js +3 -0
  42. package/dist/blocks/chunks.d.ts +49 -0
  43. package/dist/blocks/chunks.js +90 -0
  44. package/dist/blocks/code/Code.svelte +84 -0
  45. package/dist/blocks/code/Code.svelte.d.ts +11 -0
  46. package/dist/blocks/code/code.extension.d.ts +4 -0
  47. package/dist/blocks/code/code.extension.js +88 -0
  48. package/dist/blocks/code/code.svelte.d.ts +68 -0
  49. package/dist/blocks/code/code.svelte.js +245 -0
  50. package/dist/blocks/code/index.d.ts +3 -0
  51. package/dist/blocks/code/index.js +3 -0
  52. package/dist/blocks/container.utils.d.ts +85 -13
  53. package/dist/blocks/container.utils.js +338 -178
  54. package/dist/blocks/dialogue/Dialogue.svelte +8 -2
  55. package/dist/blocks/dialogue/dialogue.svelte.d.ts +36 -23
  56. package/dist/blocks/dialogue/dialogue.svelte.js +51 -45
  57. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +2 -2
  58. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +6 -4
  59. package/dist/blocks/dialogue/index.d.ts +12 -1
  60. package/dist/blocks/dialogue/index.js +51 -35
  61. package/dist/blocks/divider/Divider.svelte +28 -0
  62. package/dist/blocks/divider/Divider.svelte.d.ts +11 -0
  63. package/dist/blocks/divider/divider.extension.d.ts +23 -0
  64. package/dist/blocks/divider/divider.extension.js +153 -0
  65. package/dist/blocks/divider/divider.svelte.d.ts +54 -0
  66. package/dist/blocks/divider/divider.svelte.js +89 -0
  67. package/dist/blocks/divider/index.d.ts +3 -0
  68. package/dist/blocks/divider/index.js +3 -0
  69. package/dist/blocks/file/File.svelte +56 -0
  70. package/dist/blocks/file/File.svelte.d.ts +11 -0
  71. package/dist/blocks/file/file.extension.d.ts +4 -0
  72. package/dist/blocks/file/file.extension.js +27 -0
  73. package/dist/blocks/file/file.svelte.d.ts +29 -0
  74. package/dist/blocks/file/file.svelte.js +77 -0
  75. package/dist/blocks/file/index.d.ts +3 -0
  76. package/dist/blocks/file/index.js +3 -0
  77. package/dist/blocks/heading/Heading.svelte +2 -1
  78. package/dist/blocks/heading/heading.svelte.d.ts +27 -34
  79. package/dist/blocks/heading/heading.svelte.js +72 -60
  80. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +7 -5
  81. package/dist/blocks/heading/index.d.ts +2 -2
  82. package/dist/blocks/heading/index.js +33 -8
  83. package/dist/blocks/image/Image.svelte +41 -0
  84. package/dist/blocks/image/Image.svelte.d.ts +11 -0
  85. package/dist/blocks/image/image.extension.d.ts +5 -0
  86. package/dist/blocks/image/image.extension.js +34 -0
  87. package/dist/blocks/image/image.svelte.d.ts +61 -0
  88. package/dist/blocks/image/image.svelte.js +114 -0
  89. package/dist/blocks/image/index.d.ts +3 -0
  90. package/dist/blocks/image/index.js +3 -0
  91. package/dist/blocks/index.d.ts +11 -1
  92. package/dist/blocks/index.js +11 -1
  93. package/dist/blocks/list/List.svelte +9 -2
  94. package/dist/blocks/list/ListItem.svelte +44 -7
  95. package/dist/blocks/list/convert.d.ts +20 -0
  96. package/dist/blocks/list/convert.js +92 -0
  97. package/dist/blocks/list/hooks/onBeforeInput.hook.js +60 -26
  98. package/dist/blocks/list/html-flat.d.ts +78 -0
  99. package/dist/blocks/list/html-flat.js +244 -0
  100. package/dist/blocks/list/indent.d.ts +86 -0
  101. package/dist/blocks/list/indent.js +205 -0
  102. package/dist/blocks/list/index.d.ts +7 -3
  103. package/dist/blocks/list/index.js +43 -31
  104. package/dist/blocks/list/list-item.svelte.d.ts +43 -17
  105. package/dist/blocks/list/list-item.svelte.js +143 -93
  106. package/dist/blocks/list/list.behavior.svelte.d.ts +7 -4
  107. package/dist/blocks/list/list.behavior.svelte.js +10 -5
  108. package/dist/blocks/list/list.svelte.d.ts +101 -23
  109. package/dist/blocks/list/list.svelte.js +136 -114
  110. package/dist/blocks/list/markdown.d.ts +149 -0
  111. package/dist/blocks/list/markdown.js +442 -0
  112. package/dist/blocks/list/normalize.d.ts +11 -0
  113. package/dist/blocks/list/normalize.js +396 -0
  114. package/dist/blocks/list/paste.d.ts +45 -0
  115. package/dist/blocks/list/paste.js +242 -0
  116. package/dist/blocks/list/step-back.d.ts +24 -0
  117. package/dist/blocks/list/step-back.js +87 -0
  118. package/dist/blocks/list/to-list.d.ts +7 -0
  119. package/dist/blocks/list/to-list.js +44 -0
  120. package/dist/blocks/list/todos-toggle.d.ts +20 -0
  121. package/dist/blocks/list/todos-toggle.js +48 -0
  122. package/dist/blocks/list/todos.svelte.d.ts +35 -0
  123. package/dist/blocks/list/todos.svelte.js +76 -0
  124. package/dist/blocks/media/index.d.ts +2 -0
  125. package/dist/blocks/media/index.js +2 -0
  126. package/dist/blocks/media/markdown.d.ts +12 -0
  127. package/dist/blocks/media/markdown.js +26 -0
  128. package/dist/blocks/media/media-block.svelte.d.ts +107 -0
  129. package/dist/blocks/media/media-block.svelte.js +181 -0
  130. package/dist/blocks/media/media.helpers.d.ts +24 -0
  131. package/dist/blocks/media/media.helpers.js +88 -0
  132. package/dist/blocks/megablock.svelte.d.ts +50 -19
  133. package/dist/blocks/megablock.svelte.js +115 -74
  134. package/dist/blocks/move.d.ts +23 -0
  135. package/dist/blocks/move.js +92 -0
  136. package/dist/blocks/nabu.svelte.d.ts +846 -75
  137. package/dist/blocks/nabu.svelte.js +1990 -182
  138. package/dist/blocks/paragraph/Paragraph.svelte +1 -0
  139. package/dist/blocks/paragraph/index.d.ts +2 -2
  140. package/dist/blocks/paragraph/index.js +35 -16
  141. package/dist/blocks/paragraph/paragraph.svelte.d.ts +49 -35
  142. package/dist/blocks/paragraph/paragraph.svelte.js +81 -69
  143. package/dist/blocks/paragraph/table.html.d.ts +9 -0
  144. package/dist/blocks/paragraph/table.html.js +111 -0
  145. package/dist/blocks/paragraph/table.markdown.d.ts +32 -0
  146. package/dist/blocks/paragraph/table.markdown.js +90 -0
  147. package/dist/blocks/region/Region.svelte +264 -0
  148. package/dist/blocks/region/Region.svelte.d.ts +11 -0
  149. package/dist/blocks/region/actions.d.ts +135 -0
  150. package/dist/blocks/region/actions.js +402 -0
  151. package/dist/blocks/region/close.d.ts +35 -0
  152. package/dist/blocks/region/close.js +130 -0
  153. package/dist/blocks/region/commands.d.ts +6 -0
  154. package/dist/blocks/region/commands.js +277 -0
  155. package/dist/blocks/region/create.d.ts +72 -0
  156. package/dist/blocks/region/create.js +208 -0
  157. package/dist/blocks/region/end-marker.d.ts +35 -0
  158. package/dist/blocks/region/end-marker.js +51 -0
  159. package/dist/blocks/region/facts.d.ts +69 -0
  160. package/dist/blocks/region/facts.js +152 -0
  161. package/dist/blocks/region/format.d.ts +91 -0
  162. package/dist/blocks/region/format.js +260 -0
  163. package/dist/blocks/region/index.d.ts +14 -0
  164. package/dist/blocks/region/index.js +14 -0
  165. package/dist/blocks/region/insert.d.ts +59 -0
  166. package/dist/blocks/region/insert.js +102 -0
  167. package/dist/blocks/region/messages.d.ts +254 -0
  168. package/dist/blocks/region/messages.js +131 -0
  169. package/dist/blocks/region/normalize.d.ts +7 -0
  170. package/dist/blocks/region/normalize.js +170 -0
  171. package/dist/blocks/region/region.extension.d.ts +58 -0
  172. package/dist/blocks/region/region.extension.js +119 -0
  173. package/dist/blocks/region/region.svelte.d.ts +221 -0
  174. package/dist/blocks/region/region.svelte.js +582 -0
  175. package/dist/blocks/region/regions.svelte.d.ts +141 -0
  176. package/dist/blocks/region/regions.svelte.js +276 -0
  177. package/dist/blocks/region/serialize.d.ts +57 -0
  178. package/dist/blocks/region/serialize.js +112 -0
  179. package/dist/blocks/region/types.d.ts +255 -0
  180. package/dist/blocks/region/types.js +204 -0
  181. package/dist/blocks/selection.svelte.d.ts +106 -8
  182. package/dist/blocks/selection.svelte.js +632 -74
  183. package/dist/blocks/subthread.d.ts +80 -0
  184. package/dist/blocks/subthread.js +167 -0
  185. package/dist/blocks/text-block.svelte.d.ts +70 -0
  186. package/dist/blocks/text-block.svelte.js +108 -0
  187. package/dist/blocks/toggle/Toggle.svelte +73 -0
  188. package/dist/blocks/toggle/Toggle.svelte.d.ts +11 -0
  189. package/dist/blocks/toggle/index.d.ts +3 -0
  190. package/dist/blocks/toggle/index.js +3 -0
  191. package/dist/blocks/toggle/markdown.d.ts +20 -0
  192. package/dist/blocks/toggle/markdown.js +112 -0
  193. package/dist/blocks/toggle/toggle.extension.d.ts +4 -0
  194. package/dist/blocks/toggle/toggle.extension.js +18 -0
  195. package/dist/blocks/toggle/toggle.svelte.d.ts +135 -0
  196. package/dist/blocks/toggle/toggle.svelte.js +352 -0
  197. package/dist/blocks/undo-selection.d.ts +175 -0
  198. package/dist/blocks/undo-selection.js +360 -0
  199. package/dist/blocks/video/Video.svelte +42 -0
  200. package/dist/blocks/video/Video.svelte.d.ts +11 -0
  201. package/dist/blocks/video/index.d.ts +3 -0
  202. package/dist/blocks/video/index.js +3 -0
  203. package/dist/blocks/video/video.extension.d.ts +4 -0
  204. package/dist/blocks/video/video.extension.js +27 -0
  205. package/dist/blocks/video/video.svelte.d.ts +29 -0
  206. package/dist/blocks/video/video.svelte.js +80 -0
  207. package/dist/extend.d.ts +55 -0
  208. package/dist/extend.js +88 -0
  209. package/dist/files/assets.clipboard.d.ts +77 -0
  210. package/dist/files/assets.clipboard.js +152 -0
  211. package/dist/files/files.svelte.d.ts +363 -0
  212. package/dist/files/files.svelte.js +897 -0
  213. package/dist/files/index.d.ts +3 -0
  214. package/dist/files/index.js +3 -0
  215. package/dist/files/outbox.d.ts +69 -0
  216. package/dist/files/outbox.js +48 -0
  217. package/dist/files/status.d.ts +65 -0
  218. package/dist/files/status.js +87 -0
  219. package/dist/files/store.d.ts +97 -0
  220. package/dist/files/store.js +65 -0
  221. package/dist/files/uploads.svelte.d.ts +174 -0
  222. package/dist/files/uploads.svelte.js +504 -0
  223. package/dist/index.d.ts +68 -6
  224. package/dist/index.js +117 -7
  225. package/dist/nabu-theme.css +112 -0
  226. package/dist/paste/html.paste.d.ts +74 -3
  227. package/dist/paste/html.paste.js +555 -83
  228. package/dist/paste/markdown-inline.d.ts +86 -0
  229. package/dist/paste/markdown-inline.js +528 -0
  230. package/dist/paste/markdown.paste.d.ts +2 -8
  231. package/dist/paste/markdown.paste.js +78 -94
  232. package/dist/paste/nabu.paste.d.ts +3 -0
  233. package/dist/paste/nabu.paste.js +29 -3
  234. package/dist/paste/plain-text.paste.d.ts +2 -2
  235. package/dist/paste/plain-text.paste.js +3 -3
  236. package/dist/persistence/asset-store.d.ts +51 -0
  237. package/dist/persistence/asset-store.js +103 -0
  238. package/dist/persistence/autosave.d.ts +53 -0
  239. package/dist/persistence/autosave.js +62 -0
  240. package/dist/persistence/compact.d.ts +162 -0
  241. package/dist/persistence/compact.js +141 -0
  242. package/dist/persistence/history.d.ts +77 -0
  243. package/dist/persistence/history.js +176 -0
  244. package/dist/persistence/indexeddb.d.ts +190 -4
  245. package/dist/persistence/indexeddb.js +333 -29
  246. package/dist/persistence/merge.d.ts +38 -0
  247. package/dist/persistence/merge.js +36 -0
  248. package/dist/persistence/outbox.d.ts +25 -0
  249. package/dist/persistence/outbox.js +40 -0
  250. package/dist/persistence/persistence.d.ts +70 -9
  251. package/dist/persistence/persistence.js +507 -35
  252. package/dist/persistence/recovery.d.ts +79 -0
  253. package/dist/persistence/recovery.js +79 -0
  254. package/dist/persistence/release.d.ts +34 -0
  255. package/dist/persistence/release.js +64 -0
  256. package/dist/persistence/state.svelte.d.ts +53 -0
  257. package/dist/persistence/state.svelte.js +48 -0
  258. package/dist/persistence/sync.d.ts +39 -0
  259. package/dist/persistence/sync.js +138 -0
  260. package/dist/persistence/tail.d.ts +42 -0
  261. package/dist/persistence/tail.js +103 -0
  262. package/dist/presets.d.ts +29 -24
  263. package/dist/presets.js +51 -14
  264. package/dist/themes/atelier.css +318 -0
  265. package/dist/ui/CommandChooser.svelte +153 -0
  266. package/dist/ui/CommandChooser.svelte.d.ts +13 -0
  267. package/dist/ui/CommandInvite.svelte +99 -0
  268. package/dist/ui/CommandInvite.svelte.d.ts +12 -0
  269. package/dist/ui/DragHandle.svelte +217 -0
  270. package/dist/ui/DragHandle.svelte.d.ts +11 -0
  271. package/dist/ui/FloatingToolbar.svelte +165 -0
  272. package/dist/ui/FloatingToolbar.svelte.d.ts +27 -0
  273. package/dist/ui/SlashMenu.svelte +215 -0
  274. package/dist/ui/SlashMenu.svelte.d.ts +33 -0
  275. package/dist/ui/anchor.d.ts +112 -0
  276. package/dist/ui/anchor.js +136 -0
  277. package/dist/ui/index.d.ts +10 -0
  278. package/dist/ui/index.js +15 -0
  279. package/dist/ui/slash-menu.svelte.d.ts +112 -0
  280. package/dist/ui/slash-menu.svelte.js +150 -0
  281. package/dist/utils/command-confirm.svelte.d.ts +349 -0
  282. package/dist/utils/command-confirm.svelte.js +673 -0
  283. package/dist/utils/commands.d.ts +328 -0
  284. package/dist/utils/commands.js +416 -0
  285. package/dist/utils/dom-scope.d.ts +14 -0
  286. package/dist/utils/dom-scope.js +20 -0
  287. package/dist/utils/drop.d.ts +160 -0
  288. package/dist/utils/drop.js +305 -0
  289. package/dist/utils/extensions.d.ts +488 -40
  290. package/dist/utils/extensions.js +300 -19
  291. package/dist/utils/html.d.ts +44 -0
  292. package/dist/utils/html.js +183 -0
  293. package/dist/utils/index.d.ts +4 -0
  294. package/dist/utils/index.js +4 -0
  295. package/dist/utils/keys.d.ts +120 -0
  296. package/dist/utils/keys.js +248 -0
  297. package/dist/utils/links.d.ts +22 -0
  298. package/dist/utils/links.js +34 -0
  299. package/dist/utils/placeholders.d.ts +88 -0
  300. package/dist/utils/placeholders.js +91 -0
  301. package/dist/utils/selection.svelte.d.ts +47 -19
  302. package/dist/utils/selection.svelte.js +60 -10
  303. package/dist/utils/spellcheck.d.ts +9 -0
  304. package/dist/utils/spellcheck.js +17 -0
  305. package/dist/utils/tab.d.ts +31 -0
  306. package/dist/utils/tab.js +117 -0
  307. package/dist/utils/words.d.ts +7 -0
  308. package/dist/utils/words.js +62 -0
  309. package/dist/vite.d.ts +22 -0
  310. package/dist/vite.js +34 -0
  311. package/package.json +61 -22
  312. package/dist/blocks/zone/Zone.svelte +0 -258
  313. package/dist/blocks/zone/Zone.svelte.d.ts +0 -11
  314. package/dist/blocks/zone/index.d.ts +0 -2
  315. package/dist/blocks/zone/index.js +0 -2
  316. package/dist/blocks/zone/zone.extension.d.ts +0 -2
  317. package/dist/blocks/zone/zone.extension.js +0 -221
  318. package/dist/blocks/zone/zone.svelte.d.ts +0 -112
  319. package/dist/blocks/zone/zone.svelte.js +0 -321
@@ -0,0 +1,582 @@
1
+ import { LoroMap, LoroText } from "loro-crdt";
2
+ import { MegaBlock } from "../megablock.svelte.js";
3
+ import { TextBehavior, deltaToHtml, deltaToMarkdown } from "../../behaviors/text";
4
+ import RegionComponent from "./Region.svelte";
5
+ import { resolveConfig, fieldSpec, validateField } from "./types.js";
6
+ import { scanRegion, parseRegionComment, parseRegionHtml, sanitizeFieldDelta, levelOfType } from "./format.js";
7
+ import { regionBlockToMarkdown, regionBlockToHtml, closingNeeded, followOf, regionTypeOf } from "./serialize.js";
8
+ import { createMessages } from "./messages.js";
9
+
10
+ /**
11
+ * @import { Nabu, NabuNode } from "../nabu.svelte.js";
12
+ * @import { RegionsConfig, FieldSpec } from "./types.js";
13
+ */
14
+
15
+ /**
16
+ * @typedef {NabuNode<{type: "region", regionType: string, fields: LoroMap, text: LoroText}>} RegionNode
17
+ */
18
+
19
+ /** A Loro container handler (map, text…). @param {unknown} v @returns {v is any} */
20
+ const isContainer = (v) => !!v && typeof v === 'object' && typeof (/** @type {any} */ (v)).kind === 'function';
21
+
22
+ /**
23
+ * The `fields` map of a region node's data map, created on first use. It is a MERGEABLE child (`ensureMergeableMap`): two peers that
24
+ * each create it concurrently get the same container id, so their writes converge instead of one branch being hidden by the map's
25
+ * LWW. A document written before the mergeable API holds a REGULAR child there: it is returned as-is (`ensureMergeable*` would
26
+ * refuse a slot holding a non-mergeable value). Anything else in the slot (never written by Nabu) is replaced by a regular map.
27
+ * @param {any} data the node's data map @returns {LoroMap}
28
+ */
29
+ export function fieldsMap(data) {
30
+ const existing = data.get('fields');
31
+ if (isContainer(existing) && existing.kind() === 'Map') return /** @type {LoroMap} */ (existing);
32
+ try { return /** @type {LoroMap} */ (data.ensureMergeableMap('fields')); }
33
+ catch { return /** @type {LoroMap} */ (data.setContainer('fields', new LoroMap())); }
34
+ }
35
+
36
+ /**
37
+ * Writes `value` into the `fields` map under `name`, following the declared type of the field.
38
+ * Returns false (and writes nothing) when the value is invalid for a declared field.
39
+ * - declared field: validated (see `validateField`); `null` / `undefined` clear it;
40
+ * - the `title` is NOT a field of the map: it is the header text of the block (see RegionBlock);
41
+ * - UNKNOWN field (not declared by the type): kept as-is, whatever it is (it must be Loro-storable).
42
+ * @param {LoroMap} map @param {FieldSpec | undefined} spec @param {string} name @param {unknown} value
43
+ * @returns {boolean}
44
+ */
45
+ function writeField(map, spec, name, value) {
46
+ if (!spec) {
47
+ if (value === undefined) map.delete(name); else map.set(name, /** @type {any} */ (value));
48
+ return true;
49
+ }
50
+ const checked = validateField(spec, value);
51
+ if (!checked.ok) return false;
52
+ if (checked.value === undefined) { map.delete(name); return true; }
53
+ if (spec.kind === 'richtext') {
54
+ const existing = map.get(name);
55
+ const text = isContainer(existing) && existing.kind() === 'Text' ? /** @type {LoroText} */ (/** @type {unknown} */ (existing)) : map.setContainer(name, new LoroText());
56
+ if (text.length) text.delete(0, text.length);
57
+ if (checked.value.length) text.applyDelta(sanitizeFieldDelta(checked.value)); // an unsafe link mark never gets stored
58
+ return true;
59
+ }
60
+ map.set(name, checked.value);
61
+ return true;
62
+ }
63
+
64
+ /** A title is one line: line breaks become spaces. @param {string} s @returns {string} */
65
+ const oneLine = (s) => s.replace(/\s*[\r\n]+\s*/g, ' ');
66
+
67
+ /** A title delta: text runs only, on one line. @param {unknown} delta @returns {{ insert: string, attributes?: Record<string, any> }[]} */
68
+ const titleDelta = (delta) => /** @type {{ insert: string, attributes?: Record<string, any> }[]} */ (Array.isArray(delta) ? delta : [])
69
+ .filter((op) => op && typeof op.insert === 'string' && op.insert)
70
+ .map((op) => ({ ...op, insert: oneLine(op.insert) }));
71
+
72
+ /**
73
+ * A region (ADR 018 §3.1): a CONTAINER block, like the toggle. Its HEADER is its TITLE (a LoroText under the data key `text`,
74
+ * inline marks allowed, edited in place in the seam); its BODY is its children: any blocks, and sub-regions. It also stores
75
+ * - `regionType` the id of a declared region type;
76
+ * - `fields` a LoroMap holding the fields the type declares.
77
+ * Its level, label, number and parent region are NOT stored: they are derived from the document by the `Regions` registry
78
+ * (`nabu.regions`).
79
+ *
80
+ * The title behaves as a LOCKED FIELD (ADR 018 §3.9) although it is stored as text: Enter never splits it (the caret goes to
81
+ * the body), Backspace at its start and Delete at its end do nothing (the protected merge is a command), a multi-block paste
82
+ * lands flat, and no text merge goes into or out of it (the `onBeforeMerge` veto of the extension).
83
+ *
84
+ * The configuration (declared types) is carried by the class (`static config`): `RegionsExtension(options)` builds a
85
+ * subclass bound to its options, as `createDialogueExtension` does for the dash.
86
+ */
87
+ // @ts-ignore — static-side variance on create() (same pattern as the Toggle)
88
+ export class RegionBlock extends MegaBlock {
89
+ /** @type {RegionsConfig} */
90
+ static config = resolveConfig();
91
+
92
+ /** Texts of the integrator (`RegionsExtension({ messages })`), for the placeholder of the title. @type {import('./messages.js').RegionMessages | undefined} */
93
+ static messages = undefined;
94
+
95
+ /** The placeholder of an empty title (the `untitled` message). @param {RegionBlock} block */
96
+ static placeholder = (block) => createMessages(/** @type {typeof RegionBlock} */ (block.constructor).messages)('untitled');
97
+
98
+ /** @param {Nabu} nabu @param {RegionNode} node */
99
+ constructor(nabu, node) {
100
+ super(nabu, node);
101
+
102
+ const data = node.data;
103
+ this.container = data.get("text") ?? data.setContainer("text", new LoroText());
104
+
105
+ /** @type {TextBehavior} */
106
+ this.behavior = new TextBehavior(this, this.container);
107
+ this.behaviors.set("text", this.behavior);
108
+
109
+ this.#read();
110
+ // Local commits, imports and remote peers all end up here (the `fields` map is a child container of `data`).
111
+ node.data.subscribe(() => this.#read());
112
+
113
+ // Document export: exact round trip (`importJSON` reads `props` and `content` back, see RegionBlock.create).
114
+ this.serializers.set('json', () => ({
115
+ id: this.id,
116
+ type: 'region',
117
+ props: this.exportProps,
118
+ content: this.behavior.toJSON(),
119
+ children: this.children.map(c => c.serialize('json')).filter(Boolean)
120
+ }));
121
+ this.serializers.set('application/x-nabu+json', () => ({
122
+ type: 'region',
123
+ props: this.exportProps,
124
+ delta: this.container.sliceDelta(0, this.container.length),
125
+ children: this.children.map(c => c.serialize('application/x-nabu+json')).filter(Boolean)
126
+ }));
127
+ // Markdown: the data comment + the title as a heading + the body (+ the closing comment when needed, see serialize.js).
128
+ // `context.tail` is what follows the PARENT region (set by a parent region for its children, see `#markdown`).
129
+ this.serializers.set('markdown', (/** @type {{ tail?: import('./serialize.js').Follow }} */ context = {}) => this.#markdown(context.tail ?? 'end'));
130
+ }
131
+
132
+ /**
133
+ * The markdown of this region. Whether it closes depends on what follows it in the text: the next siblings (read lazily,
134
+ * a region is compared by level without being serialized), else what follows the parent (`tail`). Its body is told what
135
+ * follows ITS last child: the closing comment of this region when it writes one, else what follows this region.
136
+ * @param {import('./serialize.js').Follow} tail
137
+ * @returns {string}
138
+ */
139
+ #markdown(tail) {
140
+ const config = this.config;
141
+ const siblings = /** @type {any[]} */ (this.parent?.children ?? this.nabu.children);
142
+ const at = siblings.indexOf(this);
143
+ const after = (function* () {
144
+ for (let k = at + 1; at >= 0 && k < siblings.length; k++) {
145
+ const next = siblings[k];
146
+ yield next.type === 'region' ? { region: levelOfType(config, regionTypeOf(config, { regionType: next.regionType })) } : String(next.serialize('markdown') ?? '');
147
+ }
148
+ })();
149
+ const follow = followOf(after, tail);
150
+ const close = closingNeeded(config, regionTypeOf(config, { regionType: this.regionType }), follow);
151
+ const body = this.children.map(c => String(c.serialize('markdown', { tail: close ? 'close' : follow }) ?? ''));
152
+ return regionBlockToMarkdown(config, this.exportProps, this.behavior.toMarkdown(), body, { close });
153
+ }
154
+
155
+ // ── Capability flags ────────────────────────────────────────────────────
156
+ // No `# ` & co in a title (like the toggle header); marks stay allowed.
157
+ transformsEnabled = false;
158
+ // The title is an isolated field (ADR 018 §3.9): a selection that is not entirely in it never touches its text (core rule,
159
+ // see `Block#isolatesSelection`); the caret enters it at its start going down / right.
160
+ isolatesSelection = true;
161
+
162
+ /** @type {RegionsConfig} */
163
+ get config() { return /** @type {typeof RegionBlock} */ (this.constructor).config; }
164
+
165
+ component = $derived(this.nabu.components.get("region") || RegionComponent);
166
+
167
+ get text() { return this.behavior.text; }
168
+ get delta() { return this.behavior.delta; }
169
+
170
+ selection = $derived(this.behavior.selection);
171
+
172
+ // The title first, then the body
173
+ positions = $derived(this.behavior.positions + this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
174
+
175
+ // How many blocks the body holds, roughly (a sub-region counts its own body, any other container its direct children): the estimate
176
+ // of the height of a body that the browser skips while it is off screen (Region.svelte, large documents). Reactive in the structure only.
177
+ /** @type {number} */
178
+ weight = $derived(this.children.reduce((/** @type {number} */ sum, /** @type {any} */ c) => sum + 1 + (c instanceof RegionBlock ? c.weight : (c.children?.length ?? 0)), 0));
179
+
180
+ // Words of the BODY only: a title is a label, not prose, so neither this region's title nor the titles of its sub-regions
181
+ // (each sub-region block counts its own body the same way) are counted.
182
+ wordCount = $derived(this.children.reduce((s, c) => s + (c.wordCount ?? 0), 0));
183
+
184
+ /**
185
+ * Mixed block (like the toggle): the title comes first, then the body. The caret never gets collapsed away.
186
+ * @param {number} localOffset
187
+ * @returns {{ block: import('../block.svelte.js').Block, offset: number } | null}
188
+ */
189
+ resolveOffset(localOffset) {
190
+ const textPositions = this.behavior.positions; // text.length + 1
191
+ if (localOffset < textPositions || !this.children.length) {
192
+ return { block: this, offset: Math.min(localOffset, this.behavior.text.length) };
193
+ }
194
+ let remaining = localOffset - textPositions;
195
+ for (const child of this.children) {
196
+ const cp = child.positions ?? 0;
197
+ if (remaining < cp) return child.resolveOffset(remaining);
198
+ remaining -= cp;
199
+ }
200
+ return { block: this, offset: this.behavior.text.length };
201
+ }
202
+
203
+ /** The id of the region type (`''` while unset). Reactive. @type {string} */
204
+ regionType = $state('');
205
+
206
+ /** The stored fields, as plain JSON (LoroText → string), before validation. @type {Record<string, any>} */
207
+ #raw = $state.raw({});
208
+
209
+ /**
210
+ * The fields, typed by the declaration of the region type. Reactive.
211
+ * - `title` is always there: the plain text of the header (`''` when empty);
212
+ * - a declared field holds its value, or `null` when it is unset OR holds something of the wrong type
213
+ * (the stored value is kept untouched; `richtext` reads as its plain string, see `richtext(name)`);
214
+ * - a field the type does NOT declare is returned as-is.
215
+ * @type {Record<string, any>}
216
+ */
217
+ fields = $derived.by(() => {
218
+ const def = this.config.types.get(this.regionType);
219
+ const raw = this.#raw;
220
+ /** @type {Record<string, any>} */
221
+ const out = {};
222
+ for (const [name, value] of Object.entries(raw)) {
223
+ if (name === 'title' || fieldSpec(def, name)) continue; // `title` is the header; declared fields are typed below
224
+ out[name] = value;
225
+ }
226
+ out.title = this.behavior.text;
227
+ for (const [name, spec] of def?.fields ?? []) {
228
+ const v = raw[name];
229
+ if (spec.kind === 'richtext') { out[name] = typeof v === 'string' ? v : null; continue; }
230
+ const checked = validateField(spec, v);
231
+ out[name] = checked.ok && checked.value !== undefined ? checked.value : null;
232
+ }
233
+ return out;
234
+ });
235
+
236
+ /** The title: the plain text of the header. Reactive. @type {string} */
237
+ get title() { return this.behavior.text; }
238
+
239
+ #read() {
240
+ const data = /** @type {any} */ (this.node.data);
241
+ this.regionType = data.get('regionType') || '';
242
+ const map = data.get('fields');
243
+ this.#raw = isContainer(map) && map.kind() === 'Map' ? map.toJSON() : {};
244
+ }
245
+
246
+ /** The fields as stored, richtext as Loro deltas: what a document / clipboard export writes. The title is the header, never a field. @returns {Record<string, any>} */
247
+ get exportFields() {
248
+ const map = /** @type {any} */ (this.node.data).get('fields');
249
+ /** @type {Record<string, any>} */
250
+ const out = {};
251
+ if (!isContainer(map) || map.kind() !== 'Map') return out;
252
+ for (const key of map.keys()) {
253
+ if (key === 'title') continue;
254
+ const v = map.get(key);
255
+ out[key] = isContainer(v) ? (v.kind() === 'Text' ? /** @type {any} */ (v).toDelta() : v.toJSON()) : v;
256
+ }
257
+ return out;
258
+ }
259
+
260
+ /** @returns {{ regionType: string, fields: Record<string, any> }} */
261
+ get exportProps() { return { regionType: this.regionType, fields: this.exportFields }; }
262
+
263
+ /** What the clipboard form of a (partially) selected region carries besides its title and children. */
264
+ get clipboardProps() { return this.exportProps; }
265
+
266
+ /**
267
+ * The LoroText behind a `richtext` field (to read its delta / marks, or to bind an editor), or null.
268
+ * @param {string} name
269
+ * @returns {LoroText | null}
270
+ */
271
+ richtext(name) {
272
+ const map = /** @type {any} */ (this.node.data).get('fields');
273
+ const v = isContainer(map) && map.kind() === 'Map' ? map.get(name) : null;
274
+ return isContainer(v) && v.kind() === 'Text' ? /** @type {LoroText} */ (/** @type {unknown} */ (v)) : null;
275
+ }
276
+
277
+ /** Replaces the header text (plain, one line). No commit; the reactive text is refreshed right away. @param {string} value */
278
+ #setTitle(value) {
279
+ const text = this.container;
280
+ if (text.length) text.delete(0, text.length);
281
+ if (value) text.insert(0, oneLine(value));
282
+ this.behavior.text = text.toString();
283
+ this.behavior.delta = text.toDelta();
284
+ }
285
+
286
+ /**
287
+ * Sets (or, with `null` / `undefined`, clears) a field. The `title` is the header text: setting it replaces that text
288
+ * (marks are dropped). A declared field is validated (see `validateField`): an invalid value is refused (returns false,
289
+ * warns, nothing is written). A field the type does not declare is stored as-is. Own undo step like any commit.
290
+ * @param {string} name @param {unknown} value
291
+ * @param {{ commit?: boolean }} [options] `commit: false` leaves the transaction open (the caller commits)
292
+ * @returns {boolean} whether the value was written
293
+ */
294
+ setField(name, value, { commit = true } = {}) {
295
+ if (name === 'title') {
296
+ if (value != null && typeof value !== 'string') {
297
+ this.nabu.warn(`Region title refused a non-string value: ${JSON.stringify(value)}`);
298
+ return false;
299
+ }
300
+ this.#setTitle(value ?? '');
301
+ if (commit) this.commit();
302
+ return true;
303
+ }
304
+ const data = /** @type {any} */ (this.node.data);
305
+ const spec = fieldSpec(this.config.types.get(this.regionType), name);
306
+ if (spec && !validateField(spec, value).ok) {
307
+ this.nabu.warn(`Region field "${name}" (${spec.kind}) refused an invalid value: ${JSON.stringify(value)}`);
308
+ return false;
309
+ }
310
+ const map = fieldsMap(data);
311
+ writeField(map, spec, name, value);
312
+ this.#read();
313
+ if (commit) this.commit();
314
+ return true;
315
+ }
316
+
317
+ /**
318
+ * Changes the type of this region (its level follows). The fields are kept: those the new type does not declare
319
+ * remain stored as unknown fields. An unknown type id is refused.
320
+ * @param {string} regionType
321
+ * @param {{ commit?: boolean }} [options]
322
+ * @returns {boolean}
323
+ */
324
+ setRegionType(regionType, { commit = true } = {}) {
325
+ if (!this.config.types.has(regionType)) {
326
+ this.nabu.warn(`Region type "${regionType}" is not declared.`);
327
+ return false;
328
+ }
329
+ /** @type {any} */ (this.node.data).set('regionType', regionType);
330
+ this.#read();
331
+ if (commit) this.commit();
332
+ return true;
333
+ }
334
+
335
+ // ── Proxies to TextBehavior ─────────────────────────────────────────────
336
+
337
+ /**
338
+ * @param {number} targetOffset
339
+ * @returns {{node: Node, offset: number} | null}
340
+ */
341
+ getDOMPoint(targetOffset) { return this.behavior.getDOMPoint(targetOffset); }
342
+
343
+ /** @param {import('../block.svelte.js').Block} block */
344
+ absorbs(block) { return this.behavior.absorbs(block); }
345
+
346
+ /** @param {number} index @param {string} text */
347
+ insert(index, text) { return this.behavior.insert(index, text); }
348
+
349
+ /** @param {Parameters<import('../block.svelte.js').Block["delete"]>[0]} [deletion] */
350
+ delete(deletion) { return this.behavior.delete(deletion); }
351
+
352
+ /** @param {import('loro-crdt').Delta<string>[]} data */
353
+ applyDelta(data = []) { return this.behavior.applyDelta(data); }
354
+
355
+ // ── The title is a locked field (ADR 018 §3.9) ──────────────────────────
356
+
357
+ /** The body is free-form: an empty paragraph of the body takes the type of a whole block pasted into it. */
358
+ get adoptsPastedTypes() { return true; }
359
+
360
+ /**
361
+ * Enter in the title: it is never split. The caret goes to the start of the body: into its first child when that one is
362
+ * an empty default paragraph, else into a NEW empty paragraph inserted at the top of the body. One undo step.
363
+ */
364
+ #enterBody() {
365
+ const nabu = this.nabu;
366
+ const defaultType = nabu.defaultBlockType && nabu.registry.has(nabu.defaultBlockType) ? nabu.defaultBlockType : 'paragraph';
367
+ const first = /** @type {any} */ (this.children[0]);
368
+ if (first && first.type === defaultType && !first.children?.length && first.behaviors.get('text')?.text === '') {
369
+ nabu.selection.setCursor(first, 0);
370
+ return;
371
+ }
372
+ const created = nabu.insert(defaultType, {}, this.node.id.toString(), 0);
373
+ nabu.commit().then(() => {
374
+ const fresh = nabu.blocks.get(created.id);
375
+ if (fresh) nabu.selection.setCursor(fresh, 0);
376
+ });
377
+ }
378
+
379
+ /**
380
+ * Paste with the caret in the TITLE (text only, flat). Several blocks (or a container): the text of every pasted text
381
+ * block, depth first, joined by a single space, goes into the title at the caret, marks kept; nothing goes to the
382
+ * body. One pasted text block is the engine's inline paste (declined). Blocks without text (an image…) are dropped.
383
+ * @param {import('../../utils/extensions.js').PasteBlock[]} blocks
384
+ * @param {{ offset: number }} ctx
385
+ * @returns {{ block: RegionBlock, offset: number } | null}
386
+ */
387
+ acceptPaste(blocks, ctx) {
388
+ if (!blocks?.length || (blocks.length === 1 && !blocks[0].children?.length)) return null;
389
+ /** @type {{ insert: string, attributes?: Record<string, any> }[]} */
390
+ const flat = [];
391
+ let length = 0;
392
+ /** @param {import('../../utils/extensions.js').PasteBlock[]} list */
393
+ const walk = (list) => {
394
+ for (const pb of list) {
395
+ const delta = titleDelta(pb.delta);
396
+ if (delta.length && delta.some((op) => op.insert.trim())) {
397
+ if (flat.length) { flat.push({ insert: ' ' }); length += 1; }
398
+ flat.push(...delta);
399
+ length += delta.reduce((n, op) => n + op.insert.length, 0);
400
+ }
401
+ if (pb.children?.length) walk(pb.children);
402
+ }
403
+ };
404
+ walk(blocks);
405
+ if (flat.length) this.behavior.applyDelta([{ retain: ctx.offset }, ...flat]);
406
+ return { block: this, offset: ctx.offset + length };
407
+ }
408
+
409
+ /**
410
+ * @param {InputEvent} event
411
+ * @returns {boolean}
412
+ */
413
+ beforeinput(event) {
414
+ const sel = this.behavior.selection;
415
+
416
+ // The selection lies in the BODY (across several of its blocks, the title is outside the range): the container handles it.
417
+ const live = this.nabu.selection;
418
+ if (!sel && live?.anchorBlock && live.anchorBlock !== this && live.focusBlock && live.focusBlock !== this) return super.beforeinput(event);
419
+
420
+ // Enter: never splits the title; the caret goes to the body (the selection, if any, is left alone).
421
+ if (event.inputType === 'insertParagraph') {
422
+ this.#enterBody();
423
+ return true;
424
+ }
425
+
426
+ // Backspace at the very start / Delete at the very end: nothing merges into or out of a title. (The protected
427
+ // merge with the neighbouring region is a command; any other attempt meets the `onBeforeMerge` veto.)
428
+ if (sel?.isCollapsed) {
429
+ if (event.inputType === 'deleteContentBackward' && sel.from === 0) return true;
430
+ if (event.inputType === 'deleteContentForward' && sel.from === this.behavior.text.length) return true;
431
+ }
432
+
433
+ return this.behavior.handleBeforeInput(event);
434
+ }
435
+
436
+ // ── Statics ─────────────────────────────────────────────────────────────
437
+
438
+ /**
439
+ * Clipboard `text/plain` (several blocks) and static export: the data comment, the title as a heading, the body, and the
440
+ * closing comment when what follows would be swallowed (serialize.js). `after` (the following siblings) and `tail` (what
441
+ * follows the parent) are the neighbour context the engine hands to every serializer.
442
+ * @param {import('../../utils/extensions.js').PasteBlock} pb
443
+ * @param {{ recurse?: (child: import('../../utils/extensions.js').PasteBlock, ctx?: object) => string, recurseAll?: (children: import('../../utils/extensions.js').PasteBlock[], ctx?: object) => string[], after?: import('../../utils/extensions.js').PasteBlock[], tail?: import('./serialize.js').Follow }} [helpers]
444
+ */
445
+ static toMarkdown(pb, { recurse, recurseAll, after = [], tail = 'end' } = {}) {
446
+ const config = this.config;
447
+ const props = pb.props ?? {};
448
+ const next = (function* () {
449
+ for (const sibling of after) {
450
+ yield sibling.type === 'region' ? { region: levelOfType(config, regionTypeOf(config, sibling.props ?? {})) } : (recurse ? recurse(sibling) : '');
451
+ }
452
+ })();
453
+ const follow = followOf(next, tail);
454
+ const close = closingNeeded(config, regionTypeOf(config, props), follow);
455
+ const children = pb.children || [];
456
+ const ctx = { tail: close ? 'close' : follow };
457
+ const body = recurseAll ? recurseAll(children, ctx) : children.map(c => recurse ? recurse(c, ctx) : '');
458
+ return regionBlockToMarkdown(config, props, deltaToMarkdown(pb.delta || []), body, { close });
459
+ }
460
+
461
+ /**
462
+ * Clipboard `text/html`: a `<section>` carrying the data, the title as a heading, the body (serialize.js).
463
+ * @param {import('../../utils/extensions.js').PasteBlock} pb
464
+ * @param {{ recurse?: (child: import('../../utils/extensions.js').PasteBlock) => string }} [helpers]
465
+ */
466
+ static toHtml(pb, { recurse } = {}) {
467
+ const body = (pb.children || []).map(c => recurse ? recurse(c) : '');
468
+ return regionBlockToHtml(this.config, pb.props ?? {}, deltaToHtml(pb.delta || []), body);
469
+ }
470
+
471
+ /**
472
+ * Markdown rules (paste AND `importMarkdown`): the opening data comment (exact form, see format.js). `detect` is cheap (one
473
+ * line); `consume` computes the extent of the region (`scanRegion`: explicit close, next opening of the same or a higher
474
+ * level, end of the lines), and `fromMarkdown` reads the title and parses the body as a document of its own, exactly like
475
+ * the toggle, so sub-regions nest by recursion. A stray `<!-- /region -->` (nothing to close) is not a rule: literal text.
476
+ */
477
+ static get markdownRules() {
478
+ const config = this.config;
479
+ return [{
480
+ priority: 20,
481
+ interruptsParagraph: true,
482
+ detect: (/** @type {string} */ line) => !!parseRegionComment(config, line),
483
+ consume: (/** @type {string[]} */ lines, /** @type {number} */ i) => (scanRegion(config, lines, i)?.end ?? i) - i,
484
+ }];
485
+ }
486
+
487
+ /**
488
+ * The region: type and fields from the comment, the title (inline markdown) from the heading right after it, the body
489
+ * (the lines up to the end of the region, closing comment excluded) parsed as a document of its own.
490
+ * @param {string[]} lines exactly the lines `consume` took
491
+ * @param {{ parseInline: (text: string) => import('loro-crdt').Delta<string>[], parseBlocks?: (lines: string[]) => import('../../utils/extensions.js').PasteBlock[] }} helpers
492
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
493
+ */
494
+ static fromMarkdown(lines, { parseInline, parseBlocks }) {
495
+ const region = scanRegion(this.config, lines, 0);
496
+ if (!region) return null;
497
+ const children = parseBlocks ? parseBlocks(lines.slice(region.bodyStart, region.bodyEnd)) : [];
498
+ return {
499
+ type: 'region',
500
+ props: { regionType: region.regionType, fields: region.fields },
501
+ delta: region.title ? parseInline(region.title) : [],
502
+ partial: false,
503
+ ...(children.length ? { children } : {}),
504
+ };
505
+ }
506
+
507
+ /**
508
+ * HTML rules (paste): `<section data-nabu-region="type">` with a plausible type id. A `<section>` without it, or with an
509
+ * empty / absurd one, is not matched: it stays a transparent wrapper, as before.
510
+ */
511
+ static get htmlRules() {
512
+ return [{
513
+ selector: 'section[data-nabu-region]',
514
+ priority: 100,
515
+ filter: (/** @type {Element} */ el) => { const id = el.getAttribute('data-nabu-region')?.trim() ?? ''; return id.length > 0 && id.length <= 200; },
516
+ }];
517
+ }
518
+
519
+ /**
520
+ * The region of a `<section data-nabu-region>`: type and fields from the attributes (invalid fields = no fields, never
521
+ * markup), the title from the heading (`h1`-`h6`) that is its FIRST element child (inline), the body from the other
522
+ * children, read like the toggle's.
523
+ * @param {Element} el
524
+ * @param {{ parseInline: (el: Element) => import('loro-crdt').Delta<string>[], parseChildren?: (el: Element) => import('../../utils/extensions.js').PasteBlock[] }} helpers
525
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
526
+ */
527
+ static fromHTML(el, { parseInline, parseChildren }) {
528
+ const parsed = parseRegionHtml(this.config, el);
529
+ if (!parsed) return null;
530
+ const [first, ...rest] = [...el.children];
531
+ const hasTitle = !!first && /^h[1-6]$/i.test(first.tagName);
532
+ const delta = hasTitle ? parseInline(first) : [];
533
+ const bodyEls = hasTitle ? rest : [first, ...rest].filter(Boolean);
534
+ /** @type {import('../../utils/extensions.js').PasteBlock[]} */
535
+ let children = [];
536
+ const ownerDoc = el.ownerDocument;
537
+ if (parseChildren && bodyEls.length && ownerDoc) {
538
+ const wrapper = ownerDoc.createElement('div');
539
+ for (const bodyEl of bodyEls) wrapper.appendChild(bodyEl.cloneNode(true));
540
+ children = parseChildren(wrapper);
541
+ }
542
+ return {
543
+ type: 'region',
544
+ props: { regionType: parsed.regionType, fields: parsed.fields },
545
+ delta,
546
+ partial: false,
547
+ ...(children.length ? { children } : {}),
548
+ };
549
+ }
550
+
551
+ /**
552
+ * @param {Nabu} nabu @param {string} type
553
+ * @param {{ regionType?: string, title?: string, text?: string, delta?: import('loro-crdt').Delta<string>[], fields?: Record<string, any> }} [props={}]
554
+ * `regionType` defaults to the lowest-level declared type. The TITLE (the header text) comes from `delta`, else `text`,
555
+ * else `title`, else `fields.title`: it is never stored in the `fields` map. Invalid values for declared fields are
556
+ * dropped (warning); unknown fields are kept as-is.
557
+ * @param {string|null} [parentId=null] @param {number|null} [index=null]
558
+ * @returns {RegionBlock}
559
+ */
560
+ static create(nabu, type, props = {}, parentId = null, index = null) {
561
+ const config = this.config;
562
+ const node = nabu.tree.createNode(/** @type {import('loro-crdt').TreeID | undefined} */ (parentId || undefined), index ?? undefined);
563
+ const data = /** @type {any} */ (node.data);
564
+ const regionType = typeof props.regionType === 'string' && props.regionType ? props.regionType : config.defaultType;
565
+ data.set("type", "region");
566
+ data.set("regionType", regionType);
567
+ const map = fieldsMap(data);
568
+ const text = /** @type {LoroText} */ (data.setContainer("text", new LoroText()));
569
+ const def = config.types.get(regionType);
570
+ const { title: fieldsTitle, ...values } = props.fields && typeof props.fields === 'object' ? props.fields : /** @type {Record<string, any>} */ ({});
571
+ for (const [name, value] of Object.entries(values)) {
572
+ if (!writeField(map, fieldSpec(def, name), name, value)) {
573
+ nabu.warn(`Region field "${name}" dropped: invalid value ${JSON.stringify(value)} for its declared type.`);
574
+ }
575
+ }
576
+ const delta = titleDelta(props.delta);
577
+ const plain = [props.text, props.title, fieldsTitle].find((v) => typeof v === 'string' && v);
578
+ if (delta.length) text.applyDelta(delta);
579
+ else if (plain) text.insert(0, oneLine(plain));
580
+ return new this(nabu, /** @type {RegionNode} */ (/** @type {unknown} */ (node)));
581
+ }
582
+ }