@aionbuilders/nabu 0.1.0-alpha.5 → 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 (42) hide show
  1. package/dist/behaviors/text/rich-text.extension.js +9 -0
  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.js +1 -0
  6. package/dist/blocks/block.svelte.d.ts +17 -4
  7. package/dist/blocks/block.svelte.js +18 -4
  8. package/dist/blocks/container.utils.d.ts +54 -0
  9. package/dist/blocks/container.utils.js +165 -8
  10. package/dist/blocks/dialogue/dialogue.svelte.js +2 -0
  11. package/dist/blocks/dialogue/index.js +1 -5
  12. package/dist/blocks/heading/heading.svelte.d.ts +36 -0
  13. package/dist/blocks/heading/heading.svelte.js +58 -2
  14. package/dist/blocks/heading/index.js +1 -5
  15. package/dist/blocks/list/list-item.svelte.d.ts +29 -0
  16. package/dist/blocks/list/list-item.svelte.js +69 -6
  17. package/dist/blocks/list/list.svelte.d.ts +53 -0
  18. package/dist/blocks/list/list.svelte.js +112 -11
  19. package/dist/blocks/megablock.svelte.d.ts +27 -0
  20. package/dist/blocks/megablock.svelte.js +103 -1
  21. package/dist/blocks/nabu.svelte.d.ts +20 -2
  22. package/dist/blocks/nabu.svelte.js +358 -9
  23. package/dist/blocks/paragraph/index.js +18 -6
  24. package/dist/blocks/paragraph/paragraph.svelte.d.ts +28 -0
  25. package/dist/blocks/paragraph/paragraph.svelte.js +53 -1
  26. package/dist/index.d.ts +1 -0
  27. package/dist/index.js +2 -1
  28. package/dist/paste/html.paste.d.ts +12 -0
  29. package/dist/paste/html.paste.js +192 -0
  30. package/dist/paste/index.d.ts +4 -0
  31. package/dist/paste/index.js +4 -0
  32. package/dist/paste/markdown.paste.d.ts +12 -0
  33. package/dist/paste/markdown.paste.js +140 -0
  34. package/dist/paste/nabu.paste.d.ts +2 -0
  35. package/dist/paste/nabu.paste.js +20 -0
  36. package/dist/paste/plain-text.paste.d.ts +8 -0
  37. package/dist/paste/plain-text.paste.js +42 -0
  38. package/dist/presets.js +6 -4
  39. package/dist/utils/extensions.d.ts +59 -0
  40. package/dist/utils/extensions.js +30 -0
  41. package/dist/utils/selection.svelte.js +0 -5
  42. package/package.json +13 -3
@@ -45,6 +45,7 @@ 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;
@@ -59,7 +60,7 @@ export class Nabu {
59
60
  */
60
61
  exec(topic: string, data?: any): Promise<import("@aionbuilders/pulse").PulseEvent>;
61
62
  trigger(hookName: any, ...args: any[]): void;
62
- commit(): void;
63
+ commit(): Promise<void>;
63
64
  /**
64
65
  * Undo the last operation
65
66
  */
@@ -68,7 +69,7 @@ export class Nabu {
68
69
  * Redo the last undone operation
69
70
  */
70
71
  redo(): void;
71
- /** @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={}] */
72
73
  focus(options?: {
73
74
  from: {
74
75
  offset: number;
@@ -78,6 +79,7 @@ export class Nabu {
78
79
  offset: number;
79
80
  block: Block;
80
81
  };
82
+ offset?: number;
81
83
  }): void;
82
84
  /**
83
85
  * Insère un nouveau bloc dans le document
@@ -107,6 +109,22 @@ export class Nabu {
107
109
  handleKeydown(e: KeyboardEvent): void;
108
110
  /** @param {InputEvent} e */
109
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;
110
128
  /** @param {...any} args */
111
129
  warn(...args: any[]): void;
112
130
  #private;
@@ -2,7 +2,7 @@ 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
7
  import { Pulse } from '@aionbuilders/pulse';
8
8
 
@@ -27,6 +27,8 @@ import { Pulse } from '@aionbuilders/pulse';
27
27
  export class Nabu {
28
28
  /** @type {Pulse} */
29
29
  #pulse = new Pulse();
30
+ /** @type {import('../utils/extensions.js').PasteInterpreter[]} */
31
+ #pasteInterpreters = [];
30
32
 
31
33
  /** @param {NabuInit} init */
32
34
  constructor(init = {}) {
@@ -97,6 +99,16 @@ export class Nabu {
97
99
  }
98
100
  }
99
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
+
100
112
  }
101
113
  }
102
114
 
@@ -112,6 +124,12 @@ export class Nabu {
112
124
  }
113
125
  }
114
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
+
115
133
  this.tree.subscribe((event) => {
116
134
  event.events.forEach(e => {
117
135
  if (e.diff.type === "tree") {
@@ -195,6 +213,8 @@ export class Nabu {
195
213
 
196
214
  /** @type {Block[]} */
197
215
  children = $state([]);
216
+
217
+ positions = $derived(this.children.reduce((sum, child) => sum + (child.positions ?? 0), 0));
198
218
 
199
219
  get isEmpty() {
200
220
  return this.children.length === 0;
@@ -258,9 +278,10 @@ export class Nabu {
258
278
  }
259
279
 
260
280
 
261
- commit() {
281
+ async commit() {
262
282
  this.trigger("onBeforeTransaction", this);
263
283
  this.doc.commit();
284
+ await tick();
264
285
  }
265
286
 
266
287
  /**
@@ -283,18 +304,25 @@ export class Nabu {
283
304
 
284
305
 
285
306
 
286
- /** @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={}] */
287
308
  focus(options) {
288
309
  tick().then(() => {
289
310
  const sel = this.selection;
290
- const fromBlock = options?.from?.block || sel.anchorBlock;
291
- const toBlock = options?.to?.block || sel.focusBlock;
292
- const fromOffset = options?.from?.offset ?? sel.startOffset ?? 0;
293
- 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);
294
321
 
295
322
  if (fromBlock && toBlock) {
296
323
  const fromPoint = fromBlock.getDOMPoint(fromOffset);
297
324
  const toPoint = toBlock.getDOMPoint(toOffset);
325
+ console.log('Resolved DOM points:', fromPoint, toPoint);
298
326
  if (fromPoint && toPoint) this.selection.setBaseAndExtent(fromPoint.node, fromPoint.offset, toPoint.node, toPoint.offset);
299
327
  }
300
328
  })
@@ -377,8 +405,8 @@ export class Nabu {
377
405
  }
378
406
 
379
407
  // 3. Appeler la méthode sur le bloc cible s'il la possède
380
- if (targetBlock && typeof targetBlock[handlerName] === 'function') {
381
- const handled = targetBlock[handlerName](e);
408
+ if (targetBlock && typeof (/** @type {any} */ (targetBlock))[handlerName] === 'function') {
409
+ const handled = (/** @type {any} */ (targetBlock))[handlerName](e);
382
410
  if (handled) {
383
411
  e.preventDefault();
384
412
  }
@@ -419,6 +447,327 @@ export class Nabu {
419
447
 
420
448
 
421
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
+
422
771
  /** @param {...any} args */
423
772
  warn(...args) {
424
773
  if (this.debugging) console.warn("[Nabu]", ...args);
@@ -18,7 +18,23 @@ const ParagraphExtension = extension("paragraph", {
18
18
  nabu.insert("paragraph", {
19
19
  text: ""
20
20
  });
21
-
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: "" });
22
38
  }
23
39
  },
24
40
  /** @param {Nabu} nabu @param {Paragraph} block @param {Event} event @param {{offset: number, delta: import('loro-crdt').Delta<string>}} data */
@@ -33,11 +49,7 @@ const ParagraphExtension = extension("paragraph", {
33
49
 
34
50
  const newBlock = nabu.insert("paragraph", { delta }, parentId, currentIndex + 1);
35
51
 
36
- block.commit();
37
-
38
- setTimeout(() => {
39
- nabu.selection.setCursor(newBlock, 0);
40
- }, 0);
52
+ block.commit().then(() => nabu.selection.setCursor(newBlock, 0));
41
53
 
42
54
  return { block: newBlock };
43
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 */
@@ -1,7 +1,7 @@
1
1
  import { Block } from "../block.svelte.js";
2
2
  import { LoroText } from "loro-crdt";
3
3
  import ParagraphComponent from "./Paragraph.svelte";
4
- import { TextBehavior } from "../../behaviors/text";
4
+ import { TextBehavior, deltaToHtml, deltaToMarkdown } from "../../behaviors/text";
5
5
 
6
6
  /**
7
7
  * @import { Nabu, NabuNode } from "../nabu.svelte.js";
@@ -29,6 +29,7 @@ export class Paragraph extends Block {
29
29
  type: 'paragraph',
30
30
  content: this.behavior.toJSON()
31
31
  }));
32
+ this.serializers.set('application/x-nabu+json', (ctx = {}) => this.behavior.toClipboardBlock(ctx));
32
33
  }
33
34
 
34
35
  component = $derived(this.nabu.components.get("paragraph") || ParagraphComponent);
@@ -42,6 +43,7 @@ export class Paragraph extends Block {
42
43
  }
43
44
 
44
45
  selection = $derived(this.behavior.selection);
46
+ positions = $derived(this.behavior.positions);
45
47
 
46
48
  /** @param {InputEvent} event */
47
49
  beforeinput(event) {
@@ -73,6 +75,56 @@ export class Paragraph extends Block {
73
75
  /** @param {Parameters<Block["split"]>[0]} [options] @returns {ReturnType<Block["split"]>} */
74
76
  split(options) { return this.behavior.split(options); }
75
77
 
78
+ /** @param {import('../../utils/extensions.js').PasteBlock} pb */
79
+ static toMarkdown(pb) {
80
+ return deltaToMarkdown(pb.delta || []);
81
+ }
82
+
83
+ /** @param {import('../../utils/extensions.js').PasteBlock} pb */
84
+ static toHtml(pb) {
85
+ return `<p>${deltaToHtml(pb.delta || [])}</p>`;
86
+ }
87
+
88
+ static markdownRules = [
89
+ {
90
+ priority: 0, // catch-all — must be lowest
91
+ detect: () => true,
92
+ consume(/** @type {string[]} */ lines, /** @type {number} */ i) {
93
+ let j = i;
94
+ while (j < lines.length && lines[j].trim()) j++;
95
+ return Math.max(1, j - i);
96
+ },
97
+ }
98
+ ];
99
+
100
+ /**
101
+ * @param {string[]} lines
102
+ * @param {{ parseInline: (text: string) => import('loro-crdt').Delta<string>[] }} helpers
103
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
104
+ */
105
+ static fromMarkdown(lines, { parseInline }) {
106
+ const delta = parseInline(lines.join(' '));
107
+ if (!delta.length) return null;
108
+ return { type: 'paragraph', delta, partial: false };
109
+ }
110
+
111
+ static htmlRules = [
112
+ { selector: 'p' },
113
+ { selector: 'blockquote' },
114
+ { selector: 'pre' },
115
+ ];
116
+
117
+ /**
118
+ * @param {Element} el
119
+ * @param {{ parseInline: (el: Element) => import('loro-crdt').Delta<string>[] }} helpers
120
+ * @returns {import('../../utils/extensions.js').PasteBlock | null}
121
+ */
122
+ static fromHTML(el, { parseInline }) {
123
+ const delta = parseInline(el);
124
+ if (!delta.length) return null;
125
+ return { type: 'paragraph', delta, partial: false };
126
+ }
127
+
76
128
  /** @param {Nabu} nabu @param {string} type @param {Object} [props={}] @param {string|null} [parentId=null] @param {number|null} [index=null] */
77
129
  static create(nabu, type, props = {}, parentId = null, index = null) {
78
130
  const node = nabu.tree.createNode(parentId || undefined, index || undefined);
package/dist/index.d.ts CHANGED
@@ -2,4 +2,5 @@ export * from "./blocks";
2
2
  export * from "./utils";
3
3
  export * from "./behaviors";
4
4
  export * from "./presets";
5
+ export * from "./paste";
5
6
  export { RichTextExtension, RichText } from "./behaviors/text";
package/dist/index.js CHANGED
@@ -3,4 +3,5 @@ export { RichTextExtension, RichText } from './behaviors/text';
3
3
  export * from './blocks';
4
4
  export * from "./utils";
5
5
  export * from './behaviors';
6
- export * from './presets';
6
+ export * from './presets';
7
+ export * from './paste';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Parse the inline content of a DOM element into a Loro-compatible delta array.
3
+ * Recurses into inline and unknown elements, inheriting marks.
4
+ * Skips block-level children (ul, ol, table…) — those are handled by fromHTML.
5
+ *
6
+ * @param {Element} el
7
+ * @param {Record<string, true>} [marks]
8
+ * @returns {import('loro-crdt').Delta<string>[]}
9
+ */
10
+ export function parseInline(el: Element, marks?: Record<string, true>): import("loro-crdt").Delta<string>[];
11
+ export const HtmlPasteExtension: Extension;
12
+ import { Extension } from '../utils/extensions.js';