@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
@@ -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';
@@ -0,0 +1,192 @@
1
+ import { Extension } from '../utils/extensions.js';
2
+
3
+ // ── Inline mark mapping: HTML tag → Nabu mark name ──────────────────────────
4
+ const MARK_TAGS = {
5
+ strong: 'bold', b: 'bold',
6
+ em: 'italic', i: 'italic',
7
+ u: 'underline',
8
+ code: 'code',
9
+ s: 'strikethrough', del: 'strikethrough', strike: 'strikethrough',
10
+ };
11
+
12
+ // ── Tags to skip entirely when parsing inline content ────────────────────────
13
+ // These represent structural/block elements that create new blocks, not inline marks.
14
+ // ul/ol/li are handled as children by their parent block's fromHTML.
15
+ const SKIP_IN_INLINE = new Set([
16
+ 'ul', 'ol', 'li',
17
+ 'table', 'thead', 'tbody', 'tfoot', 'tr', 'td', 'th',
18
+ 'script', 'style', 'noscript', 'iframe',
19
+ ]);
20
+
21
+ // ── Tags treated as transparent containers: flattened at the top level ───────
22
+ // A div/section containing block children is not itself a block — expand it.
23
+ const TRANSPARENT_CONTAINERS = new Set([
24
+ 'div', 'section', 'article', 'main', 'header', 'footer',
25
+ 'aside', 'nav', 'form', 'figure', 'figcaption', 'details', 'summary',
26
+ ]);
27
+
28
+ /**
29
+ * Returns true if any direct child of el is a structural block element.
30
+ * Used to decide whether a transparent container should be flattened.
31
+ * Derives block detection from the registered ruleset — no hardcoded block types.
32
+ * @param {Element} el
33
+ * @param {Array<{ rule: { selector: string } }>} ruleset
34
+ * @returns {boolean}
35
+ */
36
+ function hasBlockChildren(el, ruleset) {
37
+ for (const child of el.children) {
38
+ const tag = child.tagName.toLowerCase();
39
+ if (SKIP_IN_INLINE.has(tag) || TRANSPARENT_CONTAINERS.has(tag)) return true;
40
+ for (const { rule } of ruleset) {
41
+ try { if (child.matches(rule.selector)) return true; } catch { continue; }
42
+ }
43
+ }
44
+ return false;
45
+ }
46
+
47
+ /**
48
+ * Parse the inline content of a DOM element into a Loro-compatible delta array.
49
+ * Recurses into inline and unknown elements, inheriting marks.
50
+ * Skips block-level children (ul, ol, table…) — those are handled by fromHTML.
51
+ *
52
+ * @param {Element} el
53
+ * @param {Record<string, true>} [marks]
54
+ * @returns {import('loro-crdt').Delta<string>[]}
55
+ */
56
+ export function parseInline(el, marks = {}) {
57
+ /** @type {import('loro-crdt').Delta<string>[]} */
58
+ const ops = [];
59
+ for (const child of el.childNodes) {
60
+ if (child.nodeType === Node.TEXT_NODE) {
61
+ const text = child.textContent;
62
+ if (text) {
63
+ ops.push(
64
+ Object.keys(marks).length
65
+ ? { insert: text, attributes: { ...marks } }
66
+ : { insert: text }
67
+ );
68
+ }
69
+ } else if (child.nodeType === Node.ELEMENT_NODE) {
70
+ const el2 = /** @type {Element} */ (child);
71
+ const tag = el2.tagName.toLowerCase();
72
+ if (tag === 'br') { ops.push({ insert: '\n' }); continue; }
73
+ if (SKIP_IN_INLINE.has(tag)) continue;
74
+ const markName = MARK_TAGS[tag];
75
+ const styleMarks = { ...marks };
76
+ if (markName) styleMarks[markName] = true;
77
+ // Detect marks from inline styles (e.g. Google Docs uses font-weight:700 on <span>)
78
+ if (el2.nodeType === Node.ELEMENT_NODE) {
79
+ const style = /** @type {HTMLElement} */ (el2).style;
80
+ if (style) {
81
+ const fw = style.fontWeight;
82
+ if (fw === 'bold' || fw === '700' || fw === '800' || fw === '900') styleMarks['bold'] = true;
83
+ if (style.fontStyle === 'italic') styleMarks['italic'] = true;
84
+ if (style.textDecoration?.includes('underline')) styleMarks['underline'] = true;
85
+ if (style.textDecoration?.includes('line-through')) styleMarks['strikethrough'] = true;
86
+ }
87
+ }
88
+ ops.push(...parseInline(el2, styleMarks));
89
+ }
90
+ }
91
+ return ops;
92
+ }
93
+
94
+ /**
95
+ * Build the ordered ruleset from all BlockClasses registered in nabu.
96
+ * @param {import('../blocks/nabu.svelte.js').Nabu} nabu
97
+ * @returns {Array<{ BlockClass: any, rule: { selector: string, props?: Record<string,any> } }>}
98
+ */
99
+ function buildRuleset(nabu) {
100
+ /** @type {Array<{ BlockClass: any, rule: any }>} */
101
+ const ruleset = [];
102
+ for (const [, BlockClass] of nabu.registry) {
103
+ const rules = BlockClass.htmlRules;
104
+ if (!Array.isArray(rules)) continue;
105
+ for (const rule of rules) ruleset.push({ BlockClass, rule });
106
+ }
107
+ return ruleset;
108
+ }
109
+
110
+ /**
111
+ * Match a DOM element against the registered ruleset and call the matching
112
+ * block class's static fromHTML(). Falls back to a plain paragraph if nothing
113
+ * matches but the element has text content.
114
+ *
115
+ * @param {Element} el
116
+ * @param {Array} ruleset
117
+ * @param {Object} helpers
118
+ * @returns {import('../utils/extensions.js').PasteBlock | null}
119
+ */
120
+ function parseBlock(el, ruleset, helpers) {
121
+ if (el.nodeType !== Node.ELEMENT_NODE) return null;
122
+ for (const { BlockClass, rule } of ruleset) {
123
+ try { if (!el.matches(rule.selector)) continue; } catch { continue; }
124
+ if (rule.filter && !rule.filter(el)) continue;
125
+ return BlockClass.fromHTML(el, helpers, rule);
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * Parse a top-level element, flattening transparent containers.
132
+ * Returns an array because one DOM element may expand into multiple PasteBlocks.
133
+ *
134
+ * @param {Element} el
135
+ * @param {Array} ruleset
136
+ * @param {Object} helpers
137
+ * @returns {import('../utils/extensions.js').PasteBlock[]}
138
+ */
139
+ function parseTopLevel(el, ruleset, helpers) {
140
+ if (el.nodeType !== Node.ELEMENT_NODE) return [];
141
+ const tag = el.tagName.toLowerCase();
142
+ if (TRANSPARENT_CONTAINERS.has(tag) && hasBlockChildren(el, ruleset)) {
143
+ return [...el.children].flatMap(child => parseTopLevel(child, ruleset, helpers));
144
+ }
145
+ const pb = parseBlock(el, ruleset, helpers);
146
+ if (pb) return [pb];
147
+ // Unknown element with block children: treat as transparent.
148
+ // Handles Google Docs' <b style="font-weight:normal"> wrapper and similar quirks.
149
+ if (hasBlockChildren(el, ruleset)) {
150
+ return [...el.children].flatMap(child => parseTopLevel(child, ruleset, helpers));
151
+ }
152
+ return [];
153
+ }
154
+
155
+ export const HtmlPasteExtension = new Extension('html-paste', {
156
+ pasteInterpreters: [
157
+ {
158
+ format: 'text/html',
159
+ priority: 50,
160
+ /**
161
+ * @param {string} raw
162
+ * @param {import('../blocks/nabu.svelte.js').Nabu} nabu
163
+ * @returns {import('../utils/extensions.js').PasteFragment | null}
164
+ */
165
+ interpret(raw, nabu) {
166
+ try {
167
+ const doc = new DOMParser().parseFromString(raw, 'text/html');
168
+ const body = doc.body;
169
+ if (!body) return null;
170
+
171
+ const ruleset = buildRuleset(nabu);
172
+
173
+ /** @type {{ parseInline: typeof parseInline, parseBlock: (el: Element) => any, parseChildren: (el: Element) => any[] }} */
174
+ const helpers = {
175
+ parseInline: (el) => parseInline(el),
176
+ parseBlock: (el) => parseBlock(el, ruleset, helpers),
177
+ parseChildren: (el) => [...el.children]
178
+ .map(child => parseBlock(child, ruleset, helpers))
179
+ .filter(Boolean),
180
+ };
181
+
182
+ const blocks = [...body.children]
183
+ .flatMap(el => parseTopLevel(el, ruleset, helpers));
184
+
185
+ return blocks.length ? { blocks } : null;
186
+ } catch {
187
+ return null;
188
+ }
189
+ }
190
+ }
191
+ ]
192
+ });
@@ -0,0 +1,4 @@
1
+ export { PlainTextPasteExtension } from "./plain-text.paste.js";
2
+ export { NabuPasteExtension } from "./nabu.paste.js";
3
+ export { HtmlPasteExtension } from "./html.paste.js";
4
+ export { MarkdownPasteExtension } from "./markdown.paste.js";
@@ -0,0 +1,4 @@
1
+ export { PlainTextPasteExtension } from './plain-text.paste.js';
2
+ export { NabuPasteExtension } from './nabu.paste.js';
3
+ export { HtmlPasteExtension } from './html.paste.js';
4
+ export { MarkdownPasteExtension } from './markdown.paste.js';
@@ -0,0 +1,12 @@
1
+ /**
2
+ * Parse inline markdown text into a Loro-compatible delta array.
3
+ * Uses a leftmost-match recursive strategy so nested marks work naturally:
4
+ * **bold *italic* still bold** → [bold, bold+italic, bold]
5
+ *
6
+ * @param {string} text
7
+ * @param {Record<string, true>} [marks]
8
+ * @returns {import('loro-crdt').Delta<string>[]}
9
+ */
10
+ export function parseMarkdownInline(text: string, marks?: Record<string, true>): import("loro-crdt").Delta<string>[];
11
+ export const MarkdownPasteExtension: Extension;
12
+ import { Extension } from '../utils/extensions.js';
@@ -0,0 +1,140 @@
1
+ import { Extension } from '../utils/extensions.js';
2
+
3
+ // ── Inline mark patterns — ordered by specificity (longest patterns first) ───
4
+ // Each entry: { re (non-global, used for leftmost-match search), marks }
5
+ const INLINE_PATTERNS = [
6
+ { re: /\*\*\*(.+?)\*\*\*/s, marks: { bold: true, italic: true } },
7
+ { re: /\*\*(.+?)\*\*/s, marks: { bold: true } },
8
+ { re: /\*(.+?)\*/s, marks: { italic: true } },
9
+ { re: /~~(.+?)~~/s, marks: { strikethrough: true } },
10
+ { re: /`([^`]+)`/, marks: { code: true } },
11
+ ];
12
+
13
+ /**
14
+ * Parse inline markdown text into a Loro-compatible delta array.
15
+ * Uses a leftmost-match recursive strategy so nested marks work naturally:
16
+ * **bold *italic* still bold** → [bold, bold+italic, bold]
17
+ *
18
+ * @param {string} text
19
+ * @param {Record<string, true>} [marks]
20
+ * @returns {import('loro-crdt').Delta<string>[]}
21
+ */
22
+ export function parseMarkdownInline(text, marks = {}) {
23
+ if (!text) return [];
24
+
25
+ // Find the leftmost (earliest index) pattern match across all patterns
26
+ let earliest = /** @type {RegExpExecArray | null} */ (null);
27
+ let earliestMarks = /** @type {Record<string, true>} */ ({});
28
+
29
+ for (const pat of INLINE_PATTERNS) {
30
+ const m = pat.re.exec(text);
31
+ if (m && (earliest === null || m.index < earliest.index)) {
32
+ earliest = m;
33
+ earliestMarks = pat.marks;
34
+ }
35
+ }
36
+
37
+ if (!earliest) {
38
+ // No marks — emit plain text (with inherited marks)
39
+ return [
40
+ Object.keys(marks).length
41
+ ? { insert: text, attributes: { ...marks } }
42
+ : { insert: text }
43
+ ];
44
+ }
45
+
46
+ const ops = /** @type {import('loro-crdt').Delta<string>[]} */ ([]);
47
+
48
+ // Plain text before the match
49
+ if (earliest.index > 0) {
50
+ ops.push(...parseMarkdownInline(text.slice(0, earliest.index), marks));
51
+ }
52
+
53
+ // The matched span — recurse with merged marks
54
+ ops.push(...parseMarkdownInline(earliest[1], { ...marks, ...earliestMarks }));
55
+
56
+ // Text after the match
57
+ const after = text.slice(earliest.index + earliest[0].length);
58
+ if (after) ops.push(...parseMarkdownInline(after, marks));
59
+
60
+ return ops;
61
+ }
62
+
63
+ /**
64
+ * Build the ordered markdown ruleset from all BlockClasses registered in nabu.
65
+ * Sorted by priority descending (highest priority = tried first).
66
+ *
67
+ * @param {import('../blocks/nabu.svelte.js').Nabu} nabu
68
+ * @returns {Array<{ BlockClass: any, rule: any }>}
69
+ */
70
+ function buildMarkdownRuleset(nabu) {
71
+ /** @type {Array<{ BlockClass: any, rule: any }>} */
72
+ const ruleset = [];
73
+ for (const [, BlockClass] of nabu.registry) {
74
+ const rules = BlockClass.markdownRules;
75
+ if (!Array.isArray(rules)) continue;
76
+ for (const rule of rules) ruleset.push({ BlockClass, rule });
77
+ }
78
+ ruleset.sort((a, b) => (b.rule.priority ?? 0) - (a.rule.priority ?? 0));
79
+ return ruleset;
80
+ }
81
+
82
+ export const MarkdownPasteExtension = new Extension('markdown-paste', {
83
+ pasteInterpreters: [
84
+ {
85
+ format: 'text/plain',
86
+ priority: 25,
87
+ /**
88
+ * @param {string} raw
89
+ * @param {import('../blocks/nabu.svelte.js').Nabu} nabu
90
+ * @returns {import('../utils/extensions.js').PasteFragment | null}
91
+ */
92
+ interpret(raw, nabu) {
93
+ try {
94
+ const lines = raw.split(/\r?\n/);
95
+ const ruleset = buildMarkdownRuleset(nabu);
96
+ if (!ruleset.length) return null;
97
+
98
+ const helpers = { parseInline: parseMarkdownInline };
99
+
100
+ /** @type {import('../utils/extensions.js').PasteBlock[]} */
101
+ const blocks = [];
102
+ let i = 0;
103
+
104
+ while (i < lines.length) {
105
+ // Skip blank lines between blocks
106
+ if (!lines[i].trim()) { i++; continue; }
107
+
108
+ let matched = false;
109
+ for (const { BlockClass, rule } of ruleset) {
110
+ // Normalize detect: regex or function
111
+ if (rule.detect instanceof RegExp) rule.detect.lastIndex = 0;
112
+ const detects = rule.detect instanceof RegExp
113
+ ? rule.detect.test(lines[i])
114
+ : rule.detect(lines[i], lines, i);
115
+
116
+ if (!detects) continue;
117
+
118
+ const count = rule.consume(lines, i);
119
+ const consumed = lines.slice(i, i + count);
120
+ const pb = BlockClass.fromMarkdown(consumed, helpers, rule);
121
+
122
+ if (pb) {
123
+ blocks.push(pb);
124
+ i += count;
125
+ matched = true;
126
+ break;
127
+ }
128
+ }
129
+
130
+ if (!matched) i++; // safety: skip unrecognized line
131
+ }
132
+
133
+ return blocks.length ? { blocks } : null;
134
+ } catch {
135
+ return null;
136
+ }
137
+ }
138
+ }
139
+ ]
140
+ });
@@ -0,0 +1,2 @@
1
+ export const NabuPasteExtension: Extension;
2
+ import { Extension } from '../utils/extensions.js';
@@ -0,0 +1,20 @@
1
+ import { Extension } from '../utils/extensions.js';
2
+
3
+ export const NabuPasteExtension = new Extension('nabu-paste', {
4
+ pasteInterpreters: [
5
+ {
6
+ format: 'application/x-nabu+json',
7
+ priority: 100,
8
+ /** @param {string} raw */
9
+ interpret(raw) {
10
+ try {
11
+ const fragment = JSON.parse(raw);
12
+ if (!fragment?.blocks?.length) return null;
13
+ return fragment;
14
+ } catch {
15
+ return null;
16
+ }
17
+ }
18
+ }
19
+ ]
20
+ });
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Interprète text/plain comme du texte pur.
3
+ * - Double saut de ligne (\n\n) → blocs séparés
4
+ * - Saut simple (\n) → soft break dans le même bloc
5
+ * Priorité 0 (fallback de dernier recours).
6
+ */
7
+ export const PlainTextPasteExtension: Extension;
8
+ import { Extension } from '../utils/extensions.js';
@@ -0,0 +1,42 @@
1
+ import { Extension } from '../utils/extensions.js';
2
+
3
+ /**
4
+ * Interprète text/plain comme du texte pur.
5
+ * - Double saut de ligne (\n\n) → blocs séparés
6
+ * - Saut simple (\n) → soft break dans le même bloc
7
+ * Priorité 0 (fallback de dernier recours).
8
+ */
9
+ export const PlainTextPasteExtension = new Extension('plain-text-paste', {
10
+ pasteInterpreters: [
11
+ {
12
+ format: 'text/plain',
13
+ priority: 0,
14
+ /** @param {string} raw */
15
+ interpret(raw) {
16
+ if (!raw) return null;
17
+
18
+ const normalized = raw.replace(/\r\n/g, '\n').replace(/\r/g, '\n');
19
+ const paragraphs = normalized.split(/\n\n+/).filter(Boolean);
20
+ if (paragraphs.length === 0) return null;
21
+
22
+ if (paragraphs.length === 1) {
23
+ return {
24
+ blocks: [{
25
+ type: 'paragraph',
26
+ partial: 'both',
27
+ delta: [{ insert: paragraphs[0] }]
28
+ }]
29
+ };
30
+ }
31
+
32
+ return {
33
+ blocks: paragraphs.map((text, i) => ({
34
+ type: 'paragraph',
35
+ partial: i === 0 ? 'start' : i === paragraphs.length - 1 ? 'end' : false,
36
+ delta: [{ insert: text }]
37
+ }))
38
+ };
39
+ }
40
+ }
41
+ ]
42
+ });
package/dist/presets.js CHANGED
@@ -4,22 +4,24 @@ import { HeadingExtension } from './blocks/heading/index.js';
4
4
  import { ListExtension, ListItemExtension } from './blocks/list/index.js';
5
5
  import { DialogueExtension } from './blocks/dialogue/index.js';
6
6
  import { RichTextExtension } from './behaviors/text/index.js';
7
+ import { PlainTextPasteExtension, NabuPasteExtension, HtmlPasteExtension, MarkdownPasteExtension } from './paste/index.js';
8
+ import { BlockExtension } from './blocks/block.extension.js';
7
9
 
8
10
  // ---------------------------------------------------------------------------
9
11
  // Presets — composable extension arrays
10
12
  // ---------------------------------------------------------------------------
11
13
 
12
14
  /** Paragraph only. The simplest possible editor. */
13
- export const MinimalPreset = [ParagraphExtension];
15
+ export const MinimalPreset = [ParagraphExtension, PlainTextPasteExtension, HtmlPasteExtension, NabuPasteExtension, BlockExtension];
14
16
 
15
17
  /** Paragraph + rich text marks (bold, italic, underline, code, strikethrough). */
16
- export const TextPreset = [ParagraphExtension, RichTextExtension];
18
+ export const TextPreset = [ParagraphExtension, RichTextExtension, PlainTextPasteExtension, HtmlPasteExtension, NabuPasteExtension, MarkdownPasteExtension, BlockExtension];
17
19
 
18
20
  /** Paragraph + headings + rich text. Document-like, no lists. */
19
- export const DocumentPreset = [ParagraphExtension, HeadingExtension, RichTextExtension];
21
+ export const DocumentPreset = [ParagraphExtension, HeadingExtension, RichTextExtension, PlainTextPasteExtension, HtmlPasteExtension, MarkdownPasteExtension, NabuPasteExtension, BlockExtension];
20
22
 
21
23
  /** All built-in block types + rich text. */
22
- export const FullPreset = [ParagraphExtension, HeadingExtension, ListExtension, ListItemExtension, DialogueExtension, RichTextExtension];
24
+ export const FullPreset = [ParagraphExtension, HeadingExtension, ListExtension, ListItemExtension, DialogueExtension, RichTextExtension, PlainTextPasteExtension, HtmlPasteExtension, MarkdownPasteExtension, NabuPasteExtension, BlockExtension];
23
25
 
24
26
  // ---------------------------------------------------------------------------
25
27
  // Factory — generic createEditor
@@ -1,6 +1,24 @@
1
1
  /**
2
2
  * @import { Nabu, Block } from '../blocks'
3
3
  */
4
+ /**
5
+ * @typedef {Object} PasteBlock
6
+ * @property {string} type
7
+ * @property {'start' | 'end' | 'both' | false} partial
8
+ * @property {Record<string, any>} [props]
9
+ * @property {import('loro-crdt').Delta<string>[]} [delta]
10
+ * @property {PasteBlock[]} [children]
11
+ */
12
+ /**
13
+ * @typedef {Object} PasteFragment
14
+ * @property {PasteBlock[]} blocks
15
+ */
16
+ /**
17
+ * @typedef {Object} PasteInterpreter
18
+ * @property {string} format - MIME type géré ('application/x-nabu+json', 'text/html', 'text/plain')
19
+ * @property {number} [priority] - Plus haut = appelé en premier (default: 0)
20
+ * @property {(raw: string, nabu: Nabu) => PasteFragment | null} interpret
21
+ */
4
22
  /**
5
23
  * @typedef {{
6
24
  * onInit: function(Nabu): void,
@@ -21,6 +39,12 @@
21
39
  * @property {typeof Block} [block]
22
40
  * @property {Partial<ExtensionHooks>} [hooks]
23
41
  * @property {Record<string, (nabu: Nabu) => any>} [serializers]
42
+ * @property {Record<string, (nabu: Nabu, data: any, topic: string) => any>} [actions]
43
+ * @property {PasteInterpreter[]} [pasteInterpreters]
44
+ * @property {Record<string, { expand: 'after' | 'before' | 'both' | 'none' }>} [loroTextStyles]
45
+ * Loro text style configuration required by this extension.
46
+ * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
47
+ * `applyDelta` with these attributes works correctly.
24
48
  */
25
49
  export class Extension {
26
50
  /** @param {string} name @param {ExtensionInit} init */
@@ -32,8 +56,37 @@ export class Extension {
32
56
  hooks: Partial<ExtensionHooks>;
33
57
  /** @type {Record<string, (nabu: Nabu) => any>} */
34
58
  serializers: Record<string, (nabu: Nabu) => any>;
59
+ /** @type {Record<string, (nabu: Nabu, data: any, topic: string) => any>} */
60
+ actions: Record<string, (nabu: Nabu, data: any, topic: string) => any>;
61
+ /** @type {PasteInterpreter[]} */
62
+ pasteInterpreters: PasteInterpreter[];
63
+ /** @type {Record<string, { expand: 'after' | 'before' | 'both' | 'none' }>} */
64
+ loroTextStyles: Record<string, {
65
+ expand: "after" | "before" | "both" | "none";
66
+ }>;
35
67
  }
36
68
  export function extension(name: string, init: ExtensionInit): Extension;
69
+ export type PasteBlock = {
70
+ type: string;
71
+ partial: "start" | "end" | "both" | false;
72
+ props?: Record<string, any> | undefined;
73
+ delta?: import("loro-crdt").Delta<string>[] | undefined;
74
+ children?: PasteBlock[] | undefined;
75
+ };
76
+ export type PasteFragment = {
77
+ blocks: PasteBlock[];
78
+ };
79
+ export type PasteInterpreter = {
80
+ /**
81
+ * - MIME type géré ('application/x-nabu+json', 'text/html', 'text/plain')
82
+ */
83
+ format: string;
84
+ /**
85
+ * - Plus haut = appelé en premier (default: 0)
86
+ */
87
+ priority?: number | undefined;
88
+ interpret: (raw: string, nabu: Nabu) => PasteFragment | null;
89
+ };
37
90
  export type ExtensionHooks = {
38
91
  onInit: (arg0: Nabu) => void;
39
92
  onBlockCreate: (arg0: Nabu, arg1: Block) => void;
@@ -64,6 +117,16 @@ export type ExtensionInit = {
64
117
  block?: typeof Block | undefined;
65
118
  hooks?: Partial<ExtensionHooks> | undefined;
66
119
  serializers?: Record<string, (nabu: Nabu) => any> | undefined;
120
+ actions?: Record<string, (nabu: Nabu, data: any, topic: string) => any> | undefined;
121
+ pasteInterpreters?: PasteInterpreter[] | undefined;
122
+ /**
123
+ * Loro text style configuration required by this extension.
124
+ * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
125
+ * `applyDelta` with these attributes works correctly.
126
+ */
127
+ loroTextStyles?: Record<string, {
128
+ expand: "after" | "before" | "both" | "none";
129
+ }> | undefined;
67
130
  };
68
131
  import type { Block } from '../blocks';
69
132
  import type { Nabu } from '../blocks';