@aionbuilders/nabu 0.1.0-alpha.4 → 0.1.0-alpha.6

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 (46) hide show
  1. package/dist/behaviors/text/rich-text.extension.js +96 -30
  2. package/dist/behaviors/text/text.behavior.svelte.d.ts +19 -0
  3. package/dist/behaviors/text/text.behavior.svelte.js +49 -0
  4. package/dist/blocks/Nabu.svelte +3 -0
  5. package/dist/blocks/block.extension.d.ts +2 -0
  6. package/dist/blocks/block.extension.js +32 -0
  7. package/dist/blocks/block.svelte.d.ts +17 -4
  8. package/dist/blocks/block.svelte.js +18 -4
  9. package/dist/blocks/container.utils.d.ts +54 -0
  10. package/dist/blocks/container.utils.js +165 -8
  11. package/dist/blocks/dialogue/dialogue.svelte.js +2 -0
  12. package/dist/blocks/dialogue/index.js +1 -5
  13. package/dist/blocks/heading/heading.svelte.d.ts +36 -0
  14. package/dist/blocks/heading/heading.svelte.js +58 -2
  15. package/dist/blocks/heading/index.js +9 -5
  16. package/dist/blocks/index.d.ts +1 -0
  17. package/dist/blocks/index.js +1 -0
  18. package/dist/blocks/list/index.js +13 -1
  19. package/dist/blocks/list/list-item.svelte.d.ts +41 -0
  20. package/dist/blocks/list/list-item.svelte.js +136 -85
  21. package/dist/blocks/list/list.svelte.d.ts +53 -0
  22. package/dist/blocks/list/list.svelte.js +112 -11
  23. package/dist/blocks/megablock.svelte.d.ts +27 -0
  24. package/dist/blocks/megablock.svelte.js +103 -1
  25. package/dist/blocks/nabu.svelte.d.ts +28 -2
  26. package/dist/blocks/nabu.svelte.js +383 -10
  27. package/dist/blocks/paragraph/index.js +21 -6
  28. package/dist/blocks/paragraph/paragraph.svelte.d.ts +28 -0
  29. package/dist/blocks/paragraph/paragraph.svelte.js +53 -1
  30. package/dist/index.d.ts +1 -0
  31. package/dist/index.js +2 -1
  32. package/dist/paste/html.paste.d.ts +12 -0
  33. package/dist/paste/html.paste.js +192 -0
  34. package/dist/paste/index.d.ts +4 -0
  35. package/dist/paste/index.js +4 -0
  36. package/dist/paste/markdown.paste.d.ts +12 -0
  37. package/dist/paste/markdown.paste.js +140 -0
  38. package/dist/paste/nabu.paste.d.ts +2 -0
  39. package/dist/paste/nabu.paste.js +20 -0
  40. package/dist/paste/plain-text.paste.d.ts +8 -0
  41. package/dist/paste/plain-text.paste.js +42 -0
  42. package/dist/presets.js +6 -4
  43. package/dist/utils/extensions.d.ts +63 -0
  44. package/dist/utils/extensions.js +33 -0
  45. package/dist/utils/selection.svelte.js +0 -5
  46. package/package.json +14 -3
@@ -45,14 +45,22 @@ export class Nabu {
45
45
  serializers: Map<string, (nabu: Nabu) => any>;
46
46
  /** @type {Block[]} */
47
47
  children: Block[];
48
+ positions: number;
48
49
  get isEmpty(): boolean;
49
50
  /** @param {string} format */
50
51
  serialize(format: string): any;
51
52
  init(): void;
52
53
  /** Rafraîchit les blocs racines de l'éditeur */
53
54
  updateRoots(): void;
55
+ /**
56
+ * Dispatch an action to all registered handlers for the given topic.
57
+ * @param {string} topic
58
+ * @param {any} [data]
59
+ * @returns {Promise<import('@aionbuilders/pulse').PulseEvent>}
60
+ */
61
+ exec(topic: string, data?: any): Promise<import("@aionbuilders/pulse").PulseEvent>;
54
62
  trigger(hookName: any, ...args: any[]): void;
55
- commit(): void;
63
+ commit(): Promise<void>;
56
64
  /**
57
65
  * Undo the last operation
58
66
  */
@@ -61,7 +69,7 @@ export class Nabu {
61
69
  * Redo the last undone operation
62
70
  */
63
71
  redo(): void;
64
- /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}}} [options={}] */
72
+ /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}, offset?: number}} [options={}] */
65
73
  focus(options?: {
66
74
  from: {
67
75
  offset: number;
@@ -71,6 +79,7 @@ export class Nabu {
71
79
  offset: number;
72
80
  block: Block;
73
81
  };
82
+ offset?: number;
74
83
  }): void;
75
84
  /**
76
85
  * Insère un nouveau bloc dans le document
@@ -100,8 +109,25 @@ export class Nabu {
100
109
  handleKeydown(e: KeyboardEvent): void;
101
110
  /** @param {InputEvent} e */
102
111
  beforeinput(e: InputEvent): any;
112
+ /** @param {ClipboardEvent} e */
113
+ handleCopy(e: ClipboardEvent): void;
114
+ /** @param {ClipboardEvent} e */
115
+ handleCut(e: ClipboardEvent): void;
116
+ /** @param {ClipboardEvent} e */
117
+ handlePaste(e: ClipboardEvent): void;
118
+ /**
119
+ * Insère un PasteFragment à la position du curseur courant.
120
+ * @param {import('../utils/extensions.js').PasteFragment} fragment
121
+ */
122
+ insertFragment(fragment: import("../utils/extensions.js").PasteFragment): void;
123
+ /** @param {number} globalOffset */
124
+ resolveDocumentOffset(globalOffset: number): {
125
+ block: Block;
126
+ offset: number;
127
+ } | null;
103
128
  /** @param {...any} args */
104
129
  warn(...args: any[]): void;
130
+ #private;
105
131
  }
106
132
  export type NabuNode<T extends {
107
133
  [x: string]: any;
@@ -2,8 +2,9 @@ import { LoroDoc, UndoManager } from 'loro-crdt';
2
2
  import { SvelteMap, SvelteSet } from 'svelte/reactivity';
3
3
  import { Block } from './block.svelte.js';
4
4
  import { NabuSelection } from './selection.svelte.js';
5
- import { handleContainerBeforeInput } from './container.utils.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") {
@@ -181,6 +213,8 @@ export class Nabu {
181
213
 
182
214
  /** @type {Block[]} */
183
215
  children = $state([]);
216
+
217
+ positions = $derived(this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
184
218
 
185
219
  get isEmpty() {
186
220
  return this.children.length === 0;
@@ -222,6 +256,16 @@ export class Nabu {
222
256
  });
223
257
  }
224
258
 
259
+ /**
260
+ * Dispatch an action to all registered handlers for the given topic.
261
+ * @param {string} topic
262
+ * @param {any} [data]
263
+ * @returns {Promise<import('@aionbuilders/pulse').PulseEvent>}
264
+ */
265
+ exec(topic, data) {
266
+ return this.#pulse.emit(topic, data);
267
+ }
268
+
225
269
  trigger(hookName, ...args) {
226
270
  const hooks = this.hooks.get(hookName) || [];
227
271
  for (const hook of hooks) {
@@ -234,9 +278,10 @@ export class Nabu {
234
278
  }
235
279
 
236
280
 
237
- commit() {
281
+ async commit() {
238
282
  this.trigger("onBeforeTransaction", this);
239
283
  this.doc.commit();
284
+ await tick();
240
285
  }
241
286
 
242
287
  /**
@@ -259,18 +304,25 @@ export class Nabu {
259
304
 
260
305
 
261
306
 
262
- /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}}} [options={}] */
307
+ /** @param {{from: {offset: number, block: Block}, to: {offset: number, block: Block}, offset?: number}} [options={}] */
263
308
  focus(options) {
264
309
  tick().then(() => {
265
310
  const sel = this.selection;
266
- const fromBlock = options?.from?.block || sel.anchorBlock;
267
- const toBlock = options?.to?.block || sel.focusBlock;
268
- const fromOffset = options?.from?.offset ?? sel.startOffset ?? 0;
269
- const toOffset = options?.to?.offset ?? sel.endOffset ?? 0;
311
+
312
+ const {offset: fromOffset, block: fromBlock} = options?.from?.block ?
313
+ {offset: options?.from?.offset ?? sel.startOffset ?? 0, block: options?.from?.block} :
314
+ this.resolveDocumentOffset(options?.offset ?? options?.from?.offset ?? sel.startOffset ?? 0) || {offset: sel.startOffset ?? 0, block: sel.anchorBlock};
315
+
316
+ const {offset: toOffset, block: toBlock} = options?.to?.block ?
317
+ {offset: options?.to?.offset ?? sel.endOffset ?? 0, block: options?.to?.block} :
318
+ this.resolveDocumentOffset(options?.offset ?? options?.to?.offset ?? sel.endOffset ?? 0) || {offset: sel.endOffset ?? 0, block: sel.focusBlock};
319
+
320
+ console.log('Focusing from', fromBlock, 'offset', fromOffset, 'to', toBlock, 'offset', toOffset);
270
321
 
271
322
  if (fromBlock && toBlock) {
272
323
  const fromPoint = fromBlock.getDOMPoint(fromOffset);
273
324
  const toPoint = toBlock.getDOMPoint(toOffset);
325
+ console.log('Resolved DOM points:', fromPoint, toPoint);
274
326
  if (fromPoint && toPoint) this.selection.setBaseAndExtent(fromPoint.node, fromPoint.offset, toPoint.node, toPoint.offset);
275
327
  }
276
328
  })
@@ -353,8 +405,8 @@ export class Nabu {
353
405
  }
354
406
 
355
407
  // 3. Appeler la méthode sur le bloc cible s'il la possède
356
- if (targetBlock && typeof targetBlock[handlerName] === 'function') {
357
- const handled = targetBlock[handlerName](e);
408
+ if (targetBlock && typeof (/** @type {any} */ (targetBlock))[handlerName] === 'function') {
409
+ const handled = (/** @type {any} */ (targetBlock))[handlerName](e);
358
410
  if (handled) {
359
411
  e.preventDefault();
360
412
  }
@@ -395,6 +447,327 @@ export class Nabu {
395
447
 
396
448
 
397
449
 
450
+ // CLIPBOARD
451
+
452
+ /** @param {ClipboardEvent} e */
453
+ handleCopy(e) {
454
+ if (this.selection.isCollapsed) return;
455
+ e.preventDefault();
456
+
457
+ const startBlock = this.selection.startBlock;
458
+ const endBlock = this.selection.endBlock;
459
+ if (!startBlock || !endBlock || !e.clipboardData) return;
460
+
461
+ const startFrom = this.selection.start?.from ?? 0;
462
+ const endTo = this.selection.end?.to ?? null;
463
+
464
+ // Find the Lowest Common Ancestor of startBlock and endBlock.
465
+ // If LCA is a block (nested selection inside a container), serialize from that
466
+ // block directly — avoids creating phantom ancestor wrappers for unselected content.
467
+ // If LCA is null (selection spans root-level blocks), fall back to nabu-level slice.
468
+ const lca = findLCA(startBlock, endBlock);
469
+
470
+ /** @type {Block[]} */
471
+ let rootBlocks;
472
+ if (lca) {
473
+ rootBlocks = [/** @type {Block} */ (/** @type {any} */ (lca))];
474
+ } else {
475
+ const startRoot = findDirectChildOf(startBlock, this);
476
+ const endRoot = findDirectChildOf(endBlock, this);
477
+ if (!startRoot || !endRoot) return;
478
+ const si = this.children.indexOf(startRoot);
479
+ const ei = this.children.indexOf(endRoot);
480
+ if (si === -1 || ei === -1) return;
481
+ rootBlocks = this.children.slice(si, ei + 1);
482
+ }
483
+
484
+ const lastI = rootBlocks.length - 1;
485
+
486
+ const pasteBlocks = rootBlocks.map((block, i) => {
487
+ const isFirst = i === 0;
488
+ const isLast = i === lastI;
489
+
490
+ // MegaBlocks use the generic recursive serializer
491
+ const mb = /** @type {any} */ (block);
492
+ if (typeof mb.serializeForClipboard === 'function') {
493
+ return mb.serializeForClipboard({
494
+ startBlock: isFirst ? startBlock : null,
495
+ startFrom: isFirst ? startFrom : 0,
496
+ endBlock: isLast ? endBlock : null,
497
+ endTo: isLast ? endTo : null,
498
+ });
499
+ }
500
+
501
+ // Leaf blocks use their own serializer with flat context
502
+ return block.serialize('application/x-nabu+json', {
503
+ from: isFirst ? startFrom : 0,
504
+ to: isLast ? endTo : null,
505
+ partial: isFirst && isLast ? 'both' : isFirst ? 'start' : isLast ? 'end' : false,
506
+ });
507
+ }).filter(Boolean);
508
+
509
+ if (!pasteBlocks.length) return;
510
+
511
+ const fragment = { blocks: pasteBlocks };
512
+ e.clipboardData.setData('application/x-nabu+json', JSON.stringify(fragment));
513
+
514
+ // Recursive serializers — dispatch to each BlockClass's static toMarkdown/toHtml.
515
+ // helpers.recurse lets blocks serialize their children without knowing their types.
516
+ /** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
517
+ const pbToMarkdown = (pb, ctx = {}) => {
518
+ const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
519
+ if (BlockClass?.toMarkdown) {
520
+ return BlockClass.toMarkdown(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToMarkdown(child, { ...ctx, ...childCtx }) });
521
+ }
522
+ return (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
523
+ };
524
+
525
+ /** @param {import('../utils/extensions.js').PasteBlock} pb @param {Record<string,any>} [ctx] @returns {string} */
526
+ const pbToHtml = (pb, ctx = {}) => {
527
+ const BlockClass = /** @type {any} */ (this.registry.get(pb.type));
528
+ if (BlockClass?.toHtml) {
529
+ return BlockClass.toHtml(pb, { ...ctx, recurse: (/** @type {any} */ child, /** @type {any} */ childCtx) => pbToHtml(child, { ...ctx, ...childCtx }) });
530
+ }
531
+ const text = (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
532
+ return text ? `<p>${text}</p>` : '';
533
+ };
534
+
535
+ e.clipboardData.setData('text/plain', pasteBlocks.map(pb => pbToMarkdown(pb)).join('\n\n'));
536
+ e.clipboardData.setData('text/html', pasteBlocks.map(pb => pbToHtml(pb)).join('\n'));
537
+
538
+ }
539
+
540
+ /** @param {ClipboardEvent} e */
541
+ handleCut(e) {
542
+ if (this.selection.isCollapsed) return;
543
+ e.preventDefault();
544
+
545
+ // 1. Copy selection to clipboard
546
+ this.handleCopy(e);
547
+
548
+ // 2. Delete the selected content without committing
549
+ const result = deleteSelectionContent(this, this);
550
+ if (!result) return;
551
+
552
+ // 3. Single Loro transaction + restore cursor
553
+ this.commit();
554
+ this.selection.setCursor(result.block, result.offset);
555
+ }
556
+
557
+ /** @param {ClipboardEvent} e */
558
+ handlePaste(e) {
559
+ e.preventDefault();
560
+ const clipboard = e.clipboardData;
561
+ if (!clipboard) return;
562
+
563
+ const sorted = [...this.#pasteInterpreters].sort((a, b) => (b.priority ?? 0) - (a.priority ?? 0));
564
+
565
+ for (const interpreter of sorted) {
566
+ const raw = clipboard.getData(interpreter.format);
567
+ if (!raw) continue;
568
+ const fragment = interpreter.interpret(raw, this);
569
+ if (fragment) {
570
+ this.insertFragment(fragment);
571
+ return;
572
+ }
573
+ }
574
+
575
+ this.warn('handlePaste: no interpreter matched');
576
+ }
577
+
578
+ /**
579
+ * Insère un PasteFragment à la position du curseur courant.
580
+ * @param {import('../utils/extensions.js').PasteFragment} fragment
581
+ */
582
+ insertFragment(fragment) {
583
+ const { blocks } = fragment;
584
+ if (!blocks?.length) return;
585
+
586
+ let anchorBlock;
587
+ let offset;
588
+
589
+ if (!this.selection.isCollapsed) {
590
+ const result = deleteSelectionContent(this, this);
591
+ if (!result) return;
592
+ anchorBlock = result.block;
593
+ offset = result.offset;
594
+ } else {
595
+ anchorBlock = this.selection.anchorBlock;
596
+ if (!anchorBlock) return;
597
+ offset = anchorBlock.selection?.from ?? 0;
598
+ }
599
+
600
+ const textBehavior = anchorBlock.behaviors?.get('text');
601
+ if (!textBehavior) {
602
+ this.warn('insertFragment: anchorBlock has no text behavior');
603
+ return;
604
+ }
605
+
606
+ // ── Inline: single flat block ─────────────────────────────────────────
607
+ if (blocks.length === 1 && !blocks[0].children?.length) {
608
+ const pb = blocks[0];
609
+ const delta = pb.delta || [];
610
+ const len = delta.reduce((s, op) => s + (typeof op.insert === 'string' ? op.insert.length : 0), 0);
611
+
612
+ // If the pasted block has a different type (e.g. heading pasted into paragraph),
613
+ // transform the anchor block in the same transaction before applying the delta.
614
+ if (pb.type !== anchorBlock.type) {
615
+ const data = /** @type {any} */ (anchorBlock.node.data);
616
+ data.set('type', pb.type);
617
+ for (const [key, value] of Object.entries(pb.props || {})) {
618
+ data.set(key, value);
619
+ }
620
+ }
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
+
398
771
  /** @param {...any} args */
399
772
  warn(...args) {
400
773
  if (this.debugging) console.warn("[Nabu]", ...args);
@@ -9,13 +9,32 @@ import ParagraphComponent from "./Paragraph.svelte";
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
+ },
12
15
  hooks: {
13
16
  onInit: (nabu) => {
14
17
  if (nabu.children.length === 0) {
15
18
  nabu.insert("paragraph", {
16
19
  text: ""
17
20
  });
18
-
21
+
22
+ }
23
+ },
24
+ /** @param {Nabu} nabu */
25
+ onBeforeTransaction: (nabu) => {
26
+ const roots = nabu.tree.roots();
27
+ roots.forEach(root => {
28
+ const type = root.data.get("type");
29
+ console.log('Root block type:', type);
30
+ root.children()?.forEach(child => {
31
+ const childType = child.data.get("type");
32
+ console.log('Child block type:', childType);
33
+ });
34
+ })
35
+ if (roots.length === 0) {
36
+ console.log('Document is empty, inserting initial paragraph block.');
37
+ nabu.insert("paragraph", { text: "" });
19
38
  }
20
39
  },
21
40
  /** @param {Nabu} nabu @param {Paragraph} block @param {Event} event @param {{offset: number, delta: import('loro-crdt').Delta<string>}} data */
@@ -30,11 +49,7 @@ const ParagraphExtension = extension("paragraph", {
30
49
 
31
50
  const newBlock = nabu.insert("paragraph", { delta }, parentId, currentIndex + 1);
32
51
 
33
- block.commit();
34
-
35
- setTimeout(() => {
36
- nabu.selection.setCursor(newBlock, 0);
37
- }, 0);
52
+ block.commit().then(() => nabu.selection.setCursor(newBlock, 0));
38
53
 
39
54
  return { block: newBlock };
40
55
  }
@@ -5,6 +5,34 @@
5
5
  * @typedef {NabuNode<{type: "paragraph", text: LoroText}>} ParagraphNode
6
6
  */
7
7
  export class Paragraph extends Block {
8
+ /** @param {import('../../utils/extensions.js').PasteBlock} pb */
9
+ static toMarkdown(pb: import("../../utils/extensions.js").PasteBlock): string;
10
+ /** @param {import('../../utils/extensions.js').PasteBlock} pb */
11
+ static toHtml(pb: import("../../utils/extensions.js").PasteBlock): string;
12
+ static markdownRules: {
13
+ priority: number;
14
+ detect: () => boolean;
15
+ consume(lines: string[], i: number): number;
16
+ }[];
17
+ /**
18
+ * @param {string[]} lines
19
+ * @param {{ parseInline: (text: string) => import('loro-crdt').Delta<string>[] }} helpers
20
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
21
+ */
22
+ static fromMarkdown(lines: string[], { parseInline }: {
23
+ parseInline: (text: string) => import("loro-crdt").Delta<string>[];
24
+ }): import("../../utils/extensions.js").PasteBlock | null;
25
+ static htmlRules: {
26
+ selector: string;
27
+ }[];
28
+ /**
29
+ * @param {Element} el
30
+ * @param {{ parseInline: (el: Element) => import('loro-crdt').Delta<string>[] }} helpers
31
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
32
+ */
33
+ static fromHTML(el: Element, { parseInline }: {
34
+ parseInline: (el: Element) => import("loro-crdt").Delta<string>[];
35
+ }): import("../../utils/extensions.js").PasteBlock | null;
8
36
  /** @param {Nabu} nabu @param {string} type @param {Object} [props={}] @param {string|null} [parentId=null] @param {number|null} [index=null] */
9
37
  static create(nabu: Nabu, type: string, props?: Object, parentId?: string | null, index?: number | null): Paragraph;
10
38
  /** @param {Nabu} nabu @param {ParagraphNode} node */