@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
@@ -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
+ });
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Load a snapshot from IndexedDB.
3
+ * @param {string} docId
4
+ * @returns {Promise<Uint8Array | null>}
5
+ */
6
+ export function loadSnapshot(docId: string): Promise<Uint8Array | null>;
7
+ /**
8
+ * Save a snapshot to IndexedDB.
9
+ * @param {string} docId
10
+ * @param {Uint8Array} snapshot
11
+ * @returns {Promise<void>}
12
+ */
13
+ export function saveSnapshot(docId: string, snapshot: Uint8Array): Promise<void>;
14
+ /**
15
+ * Delete a snapshot from IndexedDB.
16
+ * @param {string} docId
17
+ * @returns {Promise<void>}
18
+ */
19
+ export function deleteSnapshot(docId: string): Promise<void>;
@@ -0,0 +1,71 @@
1
+ const DB_NAME = 'nabu';
2
+ const STORE = 'snapshots';
3
+ const DB_VERSION = 1;
4
+
5
+ /**
6
+ * @returns {Promise<IDBDatabase>}
7
+ */
8
+ function openDB() {
9
+ return new Promise((resolve, reject) => {
10
+ const request = indexedDB.open(DB_NAME, DB_VERSION);
11
+
12
+ request.onupgradeneeded = (event) => {
13
+ const db = /** @type {IDBOpenDBRequest} */ (event.target).result;
14
+ if (!db.objectStoreNames.contains(STORE)) {
15
+ db.createObjectStore(STORE, { keyPath: 'docId' });
16
+ }
17
+ };
18
+
19
+ request.onsuccess = (event) => resolve(/** @type {IDBOpenDBRequest} */ (event.target).result);
20
+ request.onerror = (event) => reject(/** @type {IDBOpenDBRequest} */ (event.target).error);
21
+ });
22
+ }
23
+
24
+ /**
25
+ * Load a snapshot from IndexedDB.
26
+ * @param {string} docId
27
+ * @returns {Promise<Uint8Array | null>}
28
+ */
29
+ export async function loadSnapshot(docId) {
30
+ const db = await openDB();
31
+ return new Promise((resolve, reject) => {
32
+ const tx = db.transaction(STORE, 'readonly');
33
+ const request = tx.objectStore(STORE).get(docId);
34
+ request.onsuccess = (event) => {
35
+ const record = /** @type {IDBRequest} */ (event.target).result;
36
+ resolve(record ? record.snapshot : null);
37
+ };
38
+ request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Save a snapshot to IndexedDB.
44
+ * @param {string} docId
45
+ * @param {Uint8Array} snapshot
46
+ * @returns {Promise<void>}
47
+ */
48
+ export async function saveSnapshot(docId, snapshot) {
49
+ const db = await openDB();
50
+ return new Promise((resolve, reject) => {
51
+ const tx = db.transaction(STORE, 'readwrite');
52
+ const request = tx.objectStore(STORE).put({ docId, snapshot, savedAt: Date.now() });
53
+ request.onsuccess = () => resolve();
54
+ request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
55
+ });
56
+ }
57
+
58
+ /**
59
+ * Delete a snapshot from IndexedDB.
60
+ * @param {string} docId
61
+ * @returns {Promise<void>}
62
+ */
63
+ export async function deleteSnapshot(docId) {
64
+ const db = await openDB();
65
+ return new Promise((resolve, reject) => {
66
+ const tx = db.transaction(STORE, 'readwrite');
67
+ const request = tx.objectStore(STORE).delete(docId);
68
+ request.onsuccess = () => resolve();
69
+ request.onerror = (event) => reject(/** @type {IDBRequest} */ (event.target).error);
70
+ });
71
+ }
@@ -0,0 +1,48 @@
1
+ /**
2
+ * @import { Extension } from '../utils/extensions.js';
3
+ */
4
+ /**
5
+ * Create a Nabu editor instance with automatic IndexedDB persistence.
6
+ *
7
+ * Async counterpart of `createEditor()` — same `{ preset, extensions }` signature,
8
+ * extended with a required `docId` for storage.
9
+ *
10
+ * On first call, the document is empty (only the default paragraph from ParagraphExtension).
11
+ * On subsequent calls, the document state is restored from the last saved snapshot.
12
+ *
13
+ * The instance gains three extra methods:
14
+ * - `nabu.saveNow()` — force an immediate save (returns a Promise)
15
+ * - `nabu.clearPersistence()` — delete the stored snapshot (returns a Promise)
16
+ * - `nabu.isNew` — `true` if no previous snapshot was found (fresh document)
17
+ *
18
+ * @param {object} options
19
+ * @param {string} options.docId - Unique identifier for this document in IndexedDB
20
+ * @param {Extension[]} [options.preset] - Extension preset (default: FullPreset)
21
+ * @param {Extension[]} [options.extensions] - Additional extensions to append
22
+ * @param {number} [options.debounce] - Auto-save debounce delay in ms (default: 2000)
23
+ * @returns {Promise<Nabu>}
24
+ *
25
+ * @example
26
+ * // Fresh or restored editor, full preset
27
+ * const engine = await createPersistedEditor({ docId: 'my-note' });
28
+ *
29
+ * @example
30
+ * // Document preset with custom extension
31
+ * const engine = await createPersistedEditor({
32
+ * docId: 'article-42',
33
+ * preset: DocumentPreset,
34
+ * extensions: [MyCustomExtension],
35
+ * });
36
+ */
37
+ export function createPersistedEditor({ docId, preset, extensions, debounce }?: {
38
+ docId: string;
39
+ preset?: Extension[] | undefined;
40
+ extensions?: Extension[] | undefined;
41
+ debounce?: number | undefined;
42
+ }): Promise<Nabu>;
43
+ import type { Extension } from '../utils/extensions.js';
44
+ import { Nabu } from '../blocks/nabu.svelte.js';
45
+ import { loadSnapshot } from './indexeddb.js';
46
+ import { saveSnapshot } from './indexeddb.js';
47
+ import { deleteSnapshot } from './indexeddb.js';
48
+ export { loadSnapshot, saveSnapshot, deleteSnapshot };
@@ -0,0 +1,80 @@
1
+ import { Nabu } from '../blocks/nabu.svelte.js';
2
+ import { FullPreset } from '../presets.js';
3
+ import { loadSnapshot, saveSnapshot, deleteSnapshot } from './indexeddb.js';
4
+
5
+ export { loadSnapshot, saveSnapshot, deleteSnapshot };
6
+
7
+ /**
8
+ * @import { Extension } from '../utils/extensions.js';
9
+ */
10
+
11
+ /**
12
+ * Create a Nabu editor instance with automatic IndexedDB persistence.
13
+ *
14
+ * Async counterpart of `createEditor()` — same `{ preset, extensions }` signature,
15
+ * extended with a required `docId` for storage.
16
+ *
17
+ * On first call, the document is empty (only the default paragraph from ParagraphExtension).
18
+ * On subsequent calls, the document state is restored from the last saved snapshot.
19
+ *
20
+ * The instance gains three extra methods:
21
+ * - `nabu.saveNow()` — force an immediate save (returns a Promise)
22
+ * - `nabu.clearPersistence()` — delete the stored snapshot (returns a Promise)
23
+ * - `nabu.isNew` — `true` if no previous snapshot was found (fresh document)
24
+ *
25
+ * @param {object} options
26
+ * @param {string} options.docId - Unique identifier for this document in IndexedDB
27
+ * @param {Extension[]} [options.preset] - Extension preset (default: FullPreset)
28
+ * @param {Extension[]} [options.extensions] - Additional extensions to append
29
+ * @param {number} [options.debounce] - Auto-save debounce delay in ms (default: 2000)
30
+ * @returns {Promise<Nabu>}
31
+ *
32
+ * @example
33
+ * // Fresh or restored editor, full preset
34
+ * const engine = await createPersistedEditor({ docId: 'my-note' });
35
+ *
36
+ * @example
37
+ * // Document preset with custom extension
38
+ * const engine = await createPersistedEditor({
39
+ * docId: 'article-42',
40
+ * preset: DocumentPreset,
41
+ * extensions: [MyCustomExtension],
42
+ * });
43
+ */
44
+ export async function createPersistedEditor({
45
+ docId,
46
+ preset = FullPreset,
47
+ extensions = [],
48
+ debounce = 2000
49
+ } = {}) {
50
+ const snapshot = await loadSnapshot(docId);
51
+
52
+ const nabu = new Nabu({
53
+ extensions: [...preset, ...extensions],
54
+ ...(snapshot ? { snapshot } : {})
55
+ });
56
+
57
+ // Auto-save: Loro fires doc.subscribe() after every committed change
58
+ let saveTimer;
59
+ nabu.doc.subscribe(() => {
60
+ clearTimeout(saveTimer);
61
+ saveTimer = setTimeout(async () => {
62
+ const snap = nabu.doc.export({ mode: 'snapshot' });
63
+ await saveSnapshot(docId, snap);
64
+ }, debounce);
65
+ });
66
+
67
+ /** Whether this instance was created from a fresh document (no prior snapshot). */
68
+ nabu.isNew = !snapshot;
69
+
70
+ /** Force an immediate save of the current document state. @returns {Promise<void>} */
71
+ nabu.saveNow = async () => {
72
+ const snap = nabu.doc.export({ mode: 'snapshot' });
73
+ await saveSnapshot(docId, snap);
74
+ };
75
+
76
+ /** Delete the persisted snapshot for this document. @returns {Promise<void>} */
77
+ nabu.clearPersistence = () => deleteSnapshot(docId);
78
+
79
+ return nabu;
80
+ }