@aionbuilders/nabu 0.1.0-alpha.0 → 0.1.0-alpha.10

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 (108) hide show
  1. package/README.md +70 -1
  2. package/dist/behaviors/text/index.d.ts +1 -1
  3. package/dist/behaviors/text/index.js +1 -1
  4. package/dist/behaviors/text/rich-text.extension.js +96 -30
  5. package/dist/behaviors/text/text.behavior.svelte.d.ts +19 -0
  6. package/dist/behaviors/text/text.behavior.svelte.js +64 -2
  7. package/dist/blocks/Block.svelte +3 -3
  8. package/dist/blocks/BlockGap.svelte +55 -0
  9. package/dist/blocks/BlockGap.svelte.d.ts +11 -0
  10. package/dist/blocks/Nabu.svelte +8 -0
  11. package/dist/blocks/block.extension.d.ts +2 -0
  12. package/dist/blocks/block.extension.js +32 -0
  13. package/dist/blocks/block.svelte.d.ts +41 -9
  14. package/dist/blocks/block.svelte.js +55 -18
  15. package/dist/blocks/container.utils.d.ts +54 -4
  16. package/dist/blocks/container.utils.js +211 -8
  17. package/dist/blocks/dialogue/Dialogue.svelte +46 -0
  18. package/dist/blocks/dialogue/Dialogue.svelte.d.ts +11 -0
  19. package/dist/blocks/dialogue/dialogue.svelte.d.ts +41 -0
  20. package/dist/blocks/dialogue/dialogue.svelte.js +87 -0
  21. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +3 -0
  22. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +52 -0
  23. package/dist/blocks/dialogue/index.d.ts +7 -0
  24. package/dist/blocks/dialogue/index.js +47 -0
  25. package/dist/blocks/heading/Heading.svelte +13 -9
  26. package/dist/blocks/heading/heading.svelte.d.ts +40 -4
  27. package/dist/blocks/heading/heading.svelte.js +60 -4
  28. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +1 -1
  29. package/dist/blocks/heading/index.d.ts +2 -2
  30. package/dist/blocks/heading/index.js +11 -7
  31. package/dist/blocks/index.d.ts +7 -4
  32. package/dist/blocks/index.js +7 -4
  33. package/dist/blocks/list/ListItem.svelte +6 -2
  34. package/dist/blocks/list/hooks/onBeforeInput.hook.d.ts +3 -0
  35. package/dist/blocks/list/hooks/onBeforeInput.hook.js +77 -0
  36. package/dist/blocks/list/index.d.ts +2 -2
  37. package/dist/blocks/list/index.js +17 -3
  38. package/dist/blocks/list/list-item.svelte.d.ts +59 -6
  39. package/dist/blocks/list/list-item.svelte.js +157 -89
  40. package/dist/blocks/list/list.behavior.svelte.d.ts +1 -0
  41. package/dist/blocks/list/list.behavior.svelte.js +5 -4
  42. package/dist/blocks/list/list.svelte.d.ts +60 -7
  43. package/dist/blocks/list/list.svelte.js +116 -15
  44. package/dist/blocks/megablock.svelte.d.ts +30 -5
  45. package/dist/blocks/megablock.svelte.js +113 -17
  46. package/dist/blocks/nabu.svelte.d.ts +44 -6
  47. package/dist/blocks/nabu.svelte.js +397 -15
  48. package/dist/blocks/paragraph/Paragraph.svelte +12 -16
  49. package/dist/blocks/paragraph/Paragraph.svelte.d.ts +2 -2
  50. package/dist/blocks/paragraph/index.d.ts +2 -2
  51. package/dist/blocks/paragraph/index.js +29 -8
  52. package/dist/blocks/paragraph/paragraph.svelte.d.ts +33 -5
  53. package/dist/blocks/paragraph/paragraph.svelte.js +55 -3
  54. package/dist/blocks/selection.svelte.d.ts +6 -5
  55. package/dist/blocks/selection.svelte.js +209 -18
  56. package/dist/blocks/variable.svelte.d.ts +47 -0
  57. package/dist/blocks/variable.svelte.js +51 -0
  58. package/dist/blocks/zone/TemplateEditor.svelte +308 -0
  59. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +11 -0
  60. package/dist/blocks/zone/Zone.svelte +272 -0
  61. package/dist/blocks/zone/Zone.svelte.d.ts +11 -0
  62. package/dist/blocks/zone/ZoneEditor copy.svelte +118 -0
  63. package/dist/blocks/zone/ZoneEditor copy.svelte.d.ts +11 -0
  64. package/dist/blocks/zone/ZoneEditor.svelte +289 -0
  65. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +11 -0
  66. package/dist/blocks/zone/ZoneTemplatesList.svelte +188 -0
  67. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +11 -0
  68. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +3 -0
  69. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +30 -0
  70. package/dist/blocks/zone/index.d.ts +2 -0
  71. package/dist/blocks/zone/index.js +2 -0
  72. package/dist/blocks/zone/zone.extension.d.ts +2 -0
  73. package/dist/blocks/zone/zone.extension.js +227 -0
  74. package/dist/blocks/zone/zone.svelte.d.ts +222 -0
  75. package/dist/blocks/zone/zone.svelte.js +620 -0
  76. package/dist/index.d.ts +3 -0
  77. package/dist/index.js +4 -1
  78. package/dist/nabu-theme.css +92 -0
  79. package/dist/overlays/context/Context.svelte +179 -0
  80. package/dist/overlays/context/Context.svelte.d.ts +16 -0
  81. package/dist/overlays/context/collect.d.ts +17 -0
  82. package/dist/overlays/context/collect.js +33 -0
  83. package/dist/overlays/context/context.extension.d.ts +2 -0
  84. package/dist/overlays/context/context.extension.js +8 -0
  85. package/dist/overlays/context/context.svelte.d.ts +81 -0
  86. package/dist/overlays/context/context.svelte.js +159 -0
  87. package/dist/overlays/context/index.d.ts +3 -0
  88. package/dist/overlays/context/index.js +3 -0
  89. package/dist/paste/html.paste.d.ts +12 -0
  90. package/dist/paste/html.paste.js +192 -0
  91. package/dist/paste/index.d.ts +4 -0
  92. package/dist/paste/index.js +4 -0
  93. package/dist/paste/markdown.paste.d.ts +12 -0
  94. package/dist/paste/markdown.paste.js +140 -0
  95. package/dist/paste/nabu.paste.d.ts +2 -0
  96. package/dist/paste/nabu.paste.js +20 -0
  97. package/dist/paste/plain-text.paste.d.ts +8 -0
  98. package/dist/paste/plain-text.paste.js +42 -0
  99. package/dist/persistence/indexeddb.d.ts +19 -0
  100. package/dist/persistence/indexeddb.js +71 -0
  101. package/dist/persistence/persistence.d.ts +48 -0
  102. package/dist/persistence/persistence.js +80 -0
  103. package/dist/presets.d.ts +38 -0
  104. package/dist/presets.js +86 -0
  105. package/dist/utils/extensions.d.ts +63 -0
  106. package/dist/utils/extensions.js +33 -0
  107. package/dist/utils/selection.svelte.js +0 -5
  108. package/package.json +14 -3
@@ -1,9 +1,10 @@
1
1
  import { LoroDoc, UndoManager } from 'loro-crdt';
2
2
  import { SvelteMap, SvelteSet } from 'svelte/reactivity';
3
- import { Block } from './block.svelte';
4
- import { NabuSelection } from './selection.svelte';
5
- import { handleContainerBeforeInput } from './container.utils.js';
3
+ import { Block } from './block.svelte.js';
4
+ import { NabuSelection } from './selection.svelte.js';
5
+ import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, findDirectChildOf, findLCA } from './container.utils.js';
6
6
  import { tick } from 'svelte';
7
+ import { Pulse } from '@aionbuilders/pulse';
7
8
 
8
9
 
9
10
  /**
@@ -24,6 +25,11 @@ import { tick } from 'svelte';
24
25
  */
25
26
 
26
27
  export class Nabu {
28
+ /** @type {Pulse} */
29
+ #pulse = new Pulse();
30
+ /** @type {import('../utils/extensions.js').PasteInterpreter[]} */
31
+ #pasteInterpreters = [];
32
+
27
33
  /** @param {NabuInit} init */
28
34
  constructor(init = {}) {
29
35
  this.doc = new LoroDoc();
@@ -87,9 +93,29 @@ export class Nabu {
87
93
  }
88
94
  }
89
95
 
96
+ if (ext.actions) {
97
+ for (const [topic, handler] of Object.entries(ext.actions)) {
98
+ this.#pulse.on(topic, ({ event }) => handler(this, event.data, event.topic));
99
+ }
100
+ }
101
+
102
+ if (ext.pasteInterpreters?.length) {
103
+ for (const interpreter of ext.pasteInterpreters) {
104
+ this.#pasteInterpreters.push(interpreter);
105
+ }
106
+ }
107
+
108
+ if (ext.loroTextStyles && Object.keys(ext.loroTextStyles).length) {
109
+ this.doc.configTextStyle(ext.loroTextStyles);
110
+ }
111
+
90
112
  }
91
113
  }
92
-
114
+
115
+ // Core actions — always available
116
+ this.#pulse.on('undo', () => this.undo());
117
+ this.#pulse.on('redo', () => this.redo());
118
+
93
119
  const roots = /** @type {NabuNode[]} */ (this.tree.roots());
94
120
  if (roots?.length) {
95
121
  for (const root of roots) {
@@ -98,6 +124,12 @@ export class Nabu {
98
124
  }
99
125
  }
100
126
 
127
+ // this.doc.subscribe((event) => {
128
+ // // event.events contient un tableau listant TOUTES les opérations
129
+ // // (texte ajouté, nœuds déplacés, etc.) qui viennent d'être commitées.
130
+ // console.log("Rapport de la transaction :", event.events);
131
+ // });
132
+
101
133
  this.tree.subscribe((event) => {
102
134
  event.events.forEach(e => {
103
135
  if (e.diff.type === "tree") {
@@ -155,11 +187,18 @@ export class Nabu {
155
187
  /** @type {SvelteMap<string, SvelteSet<Block>>} */
156
188
  blocksByType = new SvelteMap();
157
189
 
158
- /** @type {SvelteMap<string, any>} */
190
+ /**
191
+ * Registered subsystems. Each system should implement:
192
+ * - `start(): void` — called when the editor mounts
193
+ * - `stop(): void` — called when the editor unmounts
194
+ * @type {SvelteMap<string, { start?: () => void, stop?: () => void, [key: string]: any }>}
195
+ */
159
196
  systems = new SvelteMap();
160
197
 
161
198
  hooks = new Map();
162
199
 
200
+ debugging = $state(false);
201
+
163
202
  /**
164
203
  * Root-level serializers. Each function receives the Nabu instance and returns the serialized document.
165
204
  * @type {Map<string, (nabu: Nabu) => any>}
@@ -179,6 +218,8 @@ export class Nabu {
179
218
 
180
219
  /** @type {Block[]} */
181
220
  children = $state([]);
221
+
222
+ positions = $derived(this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
182
223
 
183
224
  get isEmpty() {
184
225
  return this.children.length === 0;
@@ -188,7 +229,7 @@ export class Nabu {
188
229
  serialize(format) {
189
230
  const fn = this.serializers.get(format);
190
231
  if (!fn) {
191
- console.warn(`No serializer registered for format "${format}" on Nabu`);
232
+ this.warn(`No serializer registered for format "${format}" on Nabu`);
192
233
  return null;
193
234
  }
194
235
  return fn(this);
@@ -220,6 +261,16 @@ export class Nabu {
220
261
  });
221
262
  }
222
263
 
264
+ /**
265
+ * Dispatch an action to all registered handlers for the given topic.
266
+ * @param {string} topic
267
+ * @param {any} [data]
268
+ * @returns {Promise<import('@aionbuilders/pulse').PulseEvent>}
269
+ */
270
+ exec(topic, data) {
271
+ return this.#pulse.emit(topic, data);
272
+ }
273
+
223
274
  trigger(hookName, ...args) {
224
275
  const hooks = this.hooks.get(hookName) || [];
225
276
  for (const hook of hooks) {
@@ -232,9 +283,10 @@ export class Nabu {
232
283
  }
233
284
 
234
285
 
235
- commit() {
286
+ async commit() {
236
287
  this.trigger("onBeforeTransaction", this);
237
288
  this.doc.commit();
289
+ await tick();
238
290
  }
239
291
 
240
292
  /**
@@ -257,18 +309,25 @@ export class Nabu {
257
309
 
258
310
 
259
311
 
260
- /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}}} [options={}] */
312
+ /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}, offset?: number}} [options={}] */
261
313
  focus(options) {
262
314
  tick().then(() => {
263
315
  const sel = this.selection;
264
- const fromBlock = options?.from?.block || sel.anchorBlock;
265
- const toBlock = options?.to?.block || sel.focusBlock;
266
- const fromOffset = options?.from?.offset ?? sel.startOffset ?? 0;
267
- const toOffset = options?.to?.offset ?? sel.endOffset ?? 0;
316
+
317
+ const {offset: fromOffset, block: fromBlock} = options?.from?.block ?
318
+ {offset: options?.from?.offset ?? sel.startOffset ?? 0, block: options?.from?.block} :
319
+ this.resolveDocumentOffset(options?.offset ?? options?.from?.offset ?? sel.startOffset ?? 0) || {offset: sel.startOffset ?? 0, block: sel.anchorBlock};
320
+
321
+ const {offset: toOffset, block: toBlock} = options?.to?.block ?
322
+ {offset: options?.to?.offset ?? sel.endOffset ?? 0, block: options?.to?.block} :
323
+ this.resolveDocumentOffset(options?.offset ?? options?.to?.offset ?? sel.endOffset ?? 0) || {offset: sel.endOffset ?? 0, block: sel.focusBlock};
324
+
325
+ console.log('Focusing from', fromBlock, 'offset', fromOffset, 'to', toBlock, 'offset', toOffset);
268
326
 
269
327
  if (fromBlock && toBlock) {
270
328
  const fromPoint = fromBlock.getDOMPoint(fromOffset);
271
329
  const toPoint = toBlock.getDOMPoint(toOffset);
330
+ console.log('Resolved DOM points:', fromPoint, toPoint);
272
331
  if (fromPoint && toPoint) this.selection.setBaseAndExtent(fromPoint.node, fromPoint.offset, toPoint.node, toPoint.offset);
273
332
  }
274
333
  })
@@ -351,8 +410,8 @@ export class Nabu {
351
410
  }
352
411
 
353
412
  // 3. Appeler la méthode sur le bloc cible s'il la possède
354
- if (targetBlock && typeof targetBlock[handlerName] === 'function') {
355
- const handled = targetBlock[handlerName](e);
413
+ if (targetBlock && typeof (/** @type {any} */ (targetBlock))[handlerName] === 'function') {
414
+ const handled = (/** @type {any} */ (targetBlock))[handlerName](e);
356
415
  if (handled) {
357
416
  e.preventDefault();
358
417
  }
@@ -389,7 +448,330 @@ export class Nabu {
389
448
  return handleContainerBeforeInput(this, this, e);
390
449
  }
391
450
 
392
-
451
+
452
+
453
+
454
+
455
+ // CLIPBOARD
456
+
457
+ /** @param {ClipboardEvent} e */
458
+ handleCopy(e) {
459
+ if (this.selection.isCollapsed) return;
460
+ e.preventDefault();
461
+
462
+ const startBlock = this.selection.startBlock;
463
+ const endBlock = this.selection.endBlock;
464
+ if (!startBlock || !endBlock || !e.clipboardData) return;
465
+
466
+ const startFrom = this.selection.start?.from ?? 0;
467
+ const endTo = this.selection.end?.to ?? null;
468
+
469
+ // Find the root block(s) to serialize.
470
+ // - Same block: serialize it directly (partial 'both'). Going up to its parent
471
+ // would wrap it in its container (e.g. List), producing a fragment with children
472
+ // that bypasses the inline paste path on the receiving end.
473
+ // - Cross-block: use LCA so nested containers are serialized as a unit.
474
+ // - LCA is null: selection spans root-level blocks, fall back to nabu-level slice.
475
+ /** @type {Block[]} */
476
+ let rootBlocks;
477
+ if (startBlock === endBlock) {
478
+ rootBlocks = [startBlock];
479
+ } else {
480
+ const lca = findLCA(startBlock, endBlock);
481
+ if (lca) {
482
+ rootBlocks = [/** @type {Block} */ (/** @type {any} */ (lca))];
483
+ } else {
484
+ const startRoot = findDirectChildOf(startBlock, this);
485
+ const endRoot = findDirectChildOf(endBlock, this);
486
+ if (!startRoot || !endRoot) return;
487
+ const si = this.children.indexOf(startRoot);
488
+ const ei = this.children.indexOf(endRoot);
489
+ if (si === -1 || ei === -1) return;
490
+ rootBlocks = this.children.slice(si, ei + 1);
491
+ }
492
+ }
493
+
494
+ const lastI = rootBlocks.length - 1;
495
+
496
+ const pasteBlocks = rootBlocks.map((block, i) => {
497
+ const isFirst = i === 0;
498
+ const isLast = i === lastI;
499
+
500
+ // MegaBlocks use the generic recursive serializer
501
+ const mb = /** @type {any} */ (block);
502
+ if (typeof mb.serializeForClipboard === 'function') {
503
+ return mb.serializeForClipboard({
504
+ startBlock: isFirst ? startBlock : null,
505
+ startFrom: isFirst ? startFrom : 0,
506
+ endBlock: isLast ? endBlock : null,
507
+ endTo: isLast ? endTo : null,
508
+ });
509
+ }
510
+
511
+ // Leaf blocks use their own serializer with flat context
512
+ return block.serialize('application/x-nabu+json', {
513
+ from: isFirst ? startFrom : 0,
514
+ to: isLast ? endTo : null,
515
+ partial: isFirst && isLast ? 'both' : isFirst ? 'start' : isLast ? 'end' : false,
516
+ });
517
+ }).filter(Boolean);
518
+
519
+ if (!pasteBlocks.length) return;
520
+
521
+ const fragment = { blocks: pasteBlocks };
522
+ e.clipboardData.setData('application/x-nabu+json', JSON.stringify(fragment));
523
+
524
+ // Recursive serializers — dispatch to each BlockClass's static toMarkdown/toHtml.
525
+ // helpers.recurse lets blocks serialize their children without knowing their types.
526
+ /** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
527
+ const pbToMarkdown = (pb, ctx = {}) => {
528
+ const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
529
+ if (BlockClass?.toMarkdown) {
530
+ return BlockClass.toMarkdown(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToMarkdown(child, { ...ctx, ...childCtx }) });
531
+ }
532
+ return (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
533
+ };
534
+
535
+ /** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
536
+ const pbToHtml = (pb, ctx = {}) => {
537
+ const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
538
+ if (BlockClass?.toHtml) {
539
+ return BlockClass.toHtml(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToHtml(child, { ...ctx, ...childCtx }) });
540
+ }
541
+ const text = (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
542
+ return text ? `<p>${text}</p>` : '';
543
+ };
544
+
545
+ e.clipboardData.setData('text/plain', pasteBlocks.map(pb => pbToMarkdown(pb)).join('\n\n'));
546
+ e.clipboardData.setData('text/html', pasteBlocks.map(pb => pbToHtml(pb)).join('\n'));
547
+
548
+ }
549
+
550
+ /** @param {ClipboardEvent} e */
551
+ handleCut(e) {
552
+ if (this.selection.isCollapsed) return;
553
+ e.preventDefault();
554
+
555
+ // 1. Copy selection to clipboard
556
+ this.handleCopy(e);
557
+
558
+ // 2. Delete the selected content without committing
559
+ const result = deleteSelectionContent(this, this);
560
+ if (!result) return;
561
+
562
+ // 3. Single Loro transaction + restore cursor
563
+ this.commit();
564
+ this.selection.setCursor(result.block, result.offset);
565
+ }
566
+
567
+ /** @param {ClipboardEvent} e */
568
+ handlePaste(e) {
569
+ e.preventDefault();
570
+ const clipboard = e.clipboardData;
571
+ if (!clipboard) return;
572
+
573
+ const sorted = [...this.#pasteInterpreters].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
574
+
575
+ for (const interpreter of sorted) {
576
+ const raw = clipboard.getData(interpreter.format);
577
+ if (!raw) continue;
578
+ const fragment = interpreter.interpret(raw, this);
579
+ if (fragment) {
580
+ this.insertFragment(fragment);
581
+ return;
582
+ }
583
+ }
584
+
585
+ this.warn('handlePaste: no interpreter matched');
586
+ }
587
+
588
+ /**
589
+ * Insère un PasteFragment à la position du curseur courant.
590
+ * @param {import('../utils/extensions.js').PasteFragment} fragment
591
+ */
592
+ insertFragment(fragment) {
593
+ const { blocks } = fragment;
594
+ if (!blocks?.length) return;
595
+
596
+ let anchorBlock;
597
+ let offset;
598
+
599
+ if (!this.selection.isCollapsed) {
600
+ const result = deleteSelectionContent(this, this);
601
+ if (!result) return;
602
+ anchorBlock = result.block;
603
+ offset = result.offset;
604
+ } else {
605
+ anchorBlock = this.selection.anchorBlock;
606
+ if (!anchorBlock) return;
607
+ offset = anchorBlock.selection?.from ?? 0;
608
+ }
609
+
610
+ const textBehavior = anchorBlock.behaviors?.get('text');
611
+ if (!textBehavior) {
612
+ this.warn('insertFragment: anchorBlock has no text behavior');
613
+ return;
614
+ }
615
+
616
+ // ── Inline: single flat block ─────────────────────────────────────────
617
+ if (blocks.length === 1 && !blocks[0].children?.length) {
618
+ const pb = blocks[0];
619
+ const delta = pb.delta || [];
620
+ const len = delta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
621
+
622
+ textBehavior.applyDelta([{ retain: offset }, ...delta]);
623
+ this.commit();
624
+ tick().then(() => this.selection.setCursor(anchorBlock, offset + len));
625
+ return;
626
+ }
627
+
628
+ // ── Multi-block or container ──────────────────────────────────────────
629
+ // Save and cut right fragment
630
+ const rightDelta = textBehavior.container.sliceDelta(offset, textBehavior.container.length);
631
+ if (textBehavior.container.length > offset) {
632
+ textBehavior.delete({ index: offset, length: textBehavior.container.length - offset });
633
+ }
634
+
635
+ const firstPb = blocks[0];
636
+ const lastPb = blocks[blocks.length - 1];
637
+ const midPbs = blocks.slice(1, -1);
638
+ let prevNode = anchorBlock.node;
639
+ let focusBlock = anchorBlock;
640
+ let focusOffset = offset;
641
+
642
+ // ── First block ───────────────────────────────────────────────────────
643
+ if (!firstPb.children?.length) {
644
+ // Leaf: merge content into anchor (anchor type survives)
645
+ const firstDelta = firstPb.delta || [];
646
+ if (firstDelta.length) textBehavior.applyDelta([{ retain: offset }, ...firstDelta]);
647
+ focusOffset = offset + firstDelta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
648
+ } else {
649
+ // Container (e.g. List): insert it after anchor
650
+ prevNode = this.#insertPasteBlock(firstPb, prevNode);
651
+ }
652
+
653
+ // ── Middle blocks ─────────────────────────────────────────────────────
654
+ for (const pb of midPbs) {
655
+ prevNode = this.#insertPasteBlock(pb, prevNode);
656
+ }
657
+
658
+ // ── Last block (only when blocks.length > 1) ──────────────────────────
659
+ if (blocks.length > 1) {
660
+ if (!lastPb.children?.length) {
661
+ // Leaf last block: create it, append rightDelta
662
+ const LastClass = this.registry.get(lastPb.type) || this.registry.get('paragraph');
663
+ if (LastClass) {
664
+ const newLast = LastClass.create(this, lastPb.type, lastPb.props || {});
665
+ newLast.node.moveAfter(prevNode);
666
+ const wrapper = wrapOrphan(this, newLast);
667
+ const tb = newLast.behaviors?.get('text');
668
+ if (tb) {
669
+ const lastDelta = lastPb.delta || [];
670
+ if (lastDelta.length || rightDelta.length) tb.applyDelta([...lastDelta, ...rightDelta]);
671
+ focusOffset = lastDelta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
672
+ }
673
+ focusBlock = newLast;
674
+ prevNode = wrapper ? wrapper.node : newLast.node;
675
+ }
676
+ } else {
677
+ // Container last block: insert it, put rightDelta in a new paragraph after
678
+ prevNode = this.#insertPasteBlock(lastPb, prevNode);
679
+ if (rightDelta.length) {
680
+ const PClass = this.registry.get('paragraph');
681
+ if (PClass) {
682
+ const p = PClass.create(this, 'paragraph', {});
683
+ p.node.moveAfter(prevNode);
684
+ p.behaviors?.get('text')?.applyDelta(rightDelta);
685
+ focusBlock = p;
686
+ focusOffset = 0;
687
+ }
688
+ }
689
+ }
690
+ } else {
691
+ // Single container block: rightDelta goes in a new paragraph after it
692
+ if (rightDelta.length) {
693
+ const PClass = this.registry.get('paragraph');
694
+ if (PClass) {
695
+ const p = PClass.create(this, 'paragraph', {});
696
+ p.node.moveAfter(prevNode);
697
+ p.behaviors?.get('text')?.applyDelta(rightDelta);
698
+ focusBlock = p;
699
+ focusOffset = 0;
700
+ }
701
+ }
702
+ }
703
+
704
+ this.commit();
705
+ tick().then(() => {
706
+ const fb = this.blocks.get(focusBlock.id) || focusBlock;
707
+ this.selection.setCursor(fb, focusOffset);
708
+ });
709
+ }
710
+
711
+ /**
712
+ * Inserts a PasteBlock after `afterNode`. Handles both leaf blocks (wrapOrphan)
713
+ * and container blocks (creates container, recurses into children).
714
+ * Returns the outer node to use as the next prevNode.
715
+ * @param {import('../utils/extensions.js').PasteBlock} pb
716
+ * @param {any} afterNode
717
+ * @returns {any}
718
+ */
719
+ #insertPasteBlock(pb, afterNode) {
720
+ if (pb.children?.length) {
721
+ const ContainerClass = this.registry.get(pb.type);
722
+ if (!ContainerClass) return afterNode;
723
+ const container = ContainerClass.create(this, pb.type, pb.props || {});
724
+ container.node.moveAfter(afterNode);
725
+ for (const child of pb.children) {
726
+ this.#createInContainer(child, container.node.id.toString());
727
+ }
728
+ return container.node;
729
+ }
730
+
731
+ const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
732
+ if (!BlockClass) return afterNode;
733
+ const block = BlockClass.create(this, pb.type, pb.props || {});
734
+ block.node.moveAfter(afterNode);
735
+ const wrapper = wrapOrphan(this, block);
736
+ const tb = block.behaviors?.get('text');
737
+ if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
738
+ // After wrapOrphan, outer node is the wrapper (if created) or the block itself
739
+ return wrapper ? wrapper.node : block.node;
740
+ }
741
+
742
+ /**
743
+ * Creates a block inside a container, recursively handling nested children.
744
+ * @param {import('../utils/extensions.js').PasteBlock} pb
745
+ * @param {string} parentId
746
+ */
747
+ #createInContainer(pb, parentId) {
748
+ const BlockClass = this.registry.get(pb.type) || this.registry.get('paragraph');
749
+ if (!BlockClass) return;
750
+ const block = BlockClass.create(this, pb.type, pb.props || {}, parentId);
751
+ const tb = block.behaviors?.get('text');
752
+ if (tb && pb.delta?.length) tb.applyDelta(pb.delta);
753
+ for (const child of pb.children || []) {
754
+ this.#createInContainer(child, block.node.id.toString());
755
+ }
756
+ }
757
+
758
+ /** @param {number} globalOffset */
759
+ resolveDocumentOffset(globalOffset) {
760
+ let remaining = globalOffset;
761
+ for (const block of this.children) {
762
+ const blockPositions = block.positions ?? 0;
763
+ if (remaining < blockPositions) return block.resolveOffset(remaining);
764
+ remaining -= blockPositions;
765
+ }
766
+ // Fallback: clamp to end of last root block
767
+ const last = this.children[this.children.length - 1];
768
+ return last ? last.resolveOffset(Math.max(0, (last.positions ?? 1) - 1)) : null;
769
+ }
770
+
771
+ /** @param {...any} args */
772
+ warn(...args) {
773
+ if (this.debugging) console.warn("[Nabu]", ...args);
774
+ }
393
775
  }
394
776
 
395
777
 
@@ -1,6 +1,6 @@
1
1
  <script>
2
2
  import RichText from '../../behaviors/text/RichText.svelte';
3
- /** @type {{block: import('./paragraph.svelte').Paragraph}}*/
3
+ /** @type {{block: import('./paragraph.svelte.js').Paragraph}}*/
4
4
  let {block} = $props();
5
5
  </script>
6
6
 
@@ -9,6 +9,7 @@
9
9
  data-block-id={block.id}
10
10
  data-block-type="paragraph"
11
11
  class="nabu-paragraph"
12
+ class:debug={block.nabu.debugging}
12
13
  class:selected={block.selected}
13
14
  class:first={block.isSelectionStart}
14
15
  class:last={block.isSelectionEnd}
@@ -18,21 +19,16 @@
18
19
  .nabu-paragraph {
19
20
  white-space: pre-wrap;
20
21
  margin-bottom: 0.5em;
21
- &.selected {
22
- background-color: rgba(59, 130, 246, 0.25);
22
+ &.debug{
23
+ &.selected {
24
+ background-color: rgba(59, 130, 246, 0.25);
25
+ }
26
+ &.first {
27
+ border-top: 1px solid rgba(59, 130, 246, 0.5);
28
+ }
29
+ &.last {
30
+ border-bottom: 1px solid rgba(59, 130, 246, 0.5);
31
+ }
23
32
  }
24
- &.first {
25
- border-top: 1px solid rgba(59, 130, 246, 0.5);
26
- }
27
- &.last {
28
- border-bottom: 1px solid rgba(59, 130, 246, 0.5);
29
- }
30
-
31
-
32
- /* &::before {
33
- content: " ";
34
- display: inline-block;
35
- width: 0;
36
- } */
37
33
  }
38
34
  </style>
@@ -4,8 +4,8 @@ type Paragraph = {
4
4
  $set?(props: Partial<$$ComponentProps>): void;
5
5
  };
6
6
  declare const Paragraph: import("svelte").Component<{
7
- block: import("./paragraph.svelte").Paragraph;
7
+ block: import("./paragraph.svelte.js").Paragraph;
8
8
  }, {}, "">;
9
9
  type $$ComponentProps = {
10
- block: import("./paragraph.svelte").Paragraph;
10
+ block: import("./paragraph.svelte.js").Paragraph;
11
11
  };
@@ -1,7 +1,7 @@
1
1
  /**
2
- * @import { Nabu } from "../nabu.svelte";
2
+ * @import { Nabu } from "../nabu.svelte.js";
3
3
  */
4
4
  export const ParagraphExtension: import("../..").Extension;
5
5
  import ParagraphComponent from "./Paragraph.svelte";
6
- import { Paragraph } from "./paragraph.svelte";
6
+ import { Paragraph } from "./paragraph.svelte.js";
7
7
  export { ParagraphComponent, Paragraph };
@@ -1,21 +1,46 @@
1
1
  import { extension } from "../../utils/extensions";
2
- import { Paragraph } from "./paragraph.svelte";
2
+ import { Paragraph } from "./paragraph.svelte.js";
3
3
  import ParagraphComponent from "./Paragraph.svelte";
4
4
 
5
5
  /**
6
- * @import { Nabu } from "../nabu.svelte";
6
+ * @import { Nabu } from "../nabu.svelte.js";
7
7
  */
8
8
 
9
9
  const ParagraphExtension = extension("paragraph", {
10
10
  block: Paragraph,
11
11
  component: ParagraphComponent,
12
+ actions: {
13
+ 'paragraph': (nabu) => nabu.exec('block:transform', { type: 'paragraph' }),
14
+ 'gap:click': (nabu, data) => {
15
+ const { parentId = null, insertIndex = undefined } = data ?? {};
16
+ const newBlock = nabu.insert('paragraph', {}, parentId, insertIndex);
17
+ nabu.commit().then(() => {
18
+ const fresh = nabu.blocks.get(newBlock.id);
19
+ if (fresh) nabu.selection.setCursor(fresh, 0);
20
+ });
21
+ },
22
+ },
12
23
  hooks: {
13
24
  onInit: (nabu) => {
14
25
  if (nabu.children.length === 0) {
15
26
  nabu.insert("paragraph", {
16
27
  text: ""
17
28
  });
18
-
29
+
30
+ }
31
+ },
32
+ /** @param {Nabu} nabu */
33
+ onBeforeTransaction: (nabu) => {
34
+ const roots = nabu.tree.roots();
35
+ roots.forEach(root => {
36
+ const type = root.data.get("type");
37
+ root.children()?.forEach(child => {
38
+ const childType = child.data.get("type");
39
+ });
40
+ })
41
+ if (roots.length === 0) {
42
+ console.log('Document is empty, inserting initial paragraph block.');
43
+ nabu.insert("paragraph", { text: "" });
19
44
  }
20
45
  },
21
46
  /** @param {Nabu} nabu @param {Paragraph} block @param {Event} event @param {{offset: number, delta: import('loro-crdt').Delta<string>}} data */
@@ -30,11 +55,7 @@ const ParagraphExtension = extension("paragraph", {
30
55
 
31
56
  const newBlock = nabu.insert("paragraph", { delta }, parentId, currentIndex + 1);
32
57
 
33
- block.commit();
34
-
35
- setTimeout(() => {
36
- nabu.selection.setCursor(newBlock, 0);
37
- }, 0);
58
+ block.commit().then(() => nabu.selection.setCursor(newBlock, 0));
38
59
 
39
60
  return { block: newBlock };
40
61
  }