@aionbuilders/nabu 0.1.4 → 0.1.5

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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,21 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
+ ## 0.1.5 (2026-11-04)
8
+
9
+ Plain text, a way to render a document without the editor, and two fixes for small editors.
10
+
11
+ ### Added
12
+ - **`serialize('text')`** gives the text as it was typed: no escaping, no markup. Blocks are separated by a blank line, list items by a single line break, and blocks with no text add nothing. `jsonToText(json)` does the same from a JSON export, so the browser and a server get the identical string.
13
+ - **`@aionbuilders/nabu/format`**, a new entry that loads neither Loro nor Svelte and works in plain Node and Bun: `deltaToHtml`, `deltaToMarkdown`, `jsonToText`, `sanitizeUrl`, `escapeHtml`, `JSON_FORMAT_VERSION`, `isSupportedJsonVersion`. A test walks its import graph.
14
+ - **`<NabuEditor>` passes other attributes to its root** (`id`, `class`, `style`, `aria-describedby`, `inputmode`, `enterkeyhint`, `autocapitalize`, `data-*`). `class` is added to `nabu-editor`. The editor's own attributes and handlers always win.
15
+
16
+ ### Fixed
17
+ - **An editor without marks accepted them.** `MinimalPreset` kept bold, italic, code and links from pasted HTML, with no way to see them as a feature or remove them. A mark now exists only if an extension declares it in `loroTextStyles`: any other mark in pasted or imported content is dropped, and the text stays. So `importJSON` or `importMarkdown` into a narrower preset drops marks too, and a custom mark must be declared to survive a paste, as the docs already asked. Remote updates and snapshots are not affected.
18
+ - **HTML copied in Chromium kept non-breaking spaces.** Chromium's copy writes a space at the edge of an inline element as `<span>&nbsp;</span>`, so pasted text like `Bold and link` no longer wrapped at those places and differed from what Firefox gave. Such a span is now a plain space. A real non-breaking space (`10&nbsp;km`) stays.
19
+ - **The read-only viewer recipe claimed to avoid WebAssembly**, while importing `deltaToHtml` from the main entry loaded it. It now imports from `/format`. The main entry still exports these helpers.
20
+ - **Three site tests depended on the load of the machine**: a race on a client-side navigation, and screenshot loops over the default timeout.
21
+
7
22
  ## 0.1.4 (2026-11-04)
8
23
 
9
24
  The caret stays on screen. No API change.
package/README.md CHANGED
@@ -107,6 +107,7 @@ The public API is these entry points; everything else is internal and may change
107
107
  | `@aionbuilders/nabu` | Using the editor: `NabuEditor`, the factories and presets, the built-in extensions, `createPersistedEditor`, `Files`, `Regions`, `Todos`, `deltaToMarkdown`... |
108
108
  | `@aionbuilders/nabu/ui` | The optional UI: `FloatingToolbar`, `SlashMenu`, `DragHandle`, `CommandInvite`, `CommandChooser` |
109
109
  | `@aionbuilders/nabu/extend` | Writing your own blocks and extensions: `extension`, `Block`, `TextBlock`, `MegaBlock`, `TextBehavior`, `RichText`, key-chord helpers |
110
+ | `@aionbuilders/nabu/format` | Reading a document without the editor (no WebAssembly, works in Node and Bun): `jsonToText`, `deltaToHtml`, `deltaToMarkdown`, `sanitizeUrl` |
110
111
  | `@aionbuilders/nabu/vite` | The Vite helper `nabu()` shown above |
111
112
 
112
113
  ## Presets
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Converts a Loro text delta to inline HTML.
3
+ * Marks are rendered as semantic HTML tags.
4
+ * @param {import('loro-crdt').Delta<string>[]} delta
5
+ * @returns {string}
6
+ */
7
+ export function deltaToHtml(delta: import("loro-crdt").Delta<string>[]): string;
8
+ /**
9
+ * Converts a Loro text delta to inline Markdown.
10
+ * A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
11
+ * (a block that re-reads its own lines, like a callout body, keeps the plain newline).
12
+ * @param {import('loro-crdt').Delta<string>[]} delta
13
+ * @param {{ rawBreaks?: boolean }} [options]
14
+ * @returns {string}
15
+ */
16
+ export function deltaToMarkdown(delta: import("loro-crdt").Delta<string>[], { rawBreaks }?: {
17
+ rawBreaks?: boolean;
18
+ }): string;
19
+ /** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
20
+ export function markdownDestination(href: string): string;
@@ -0,0 +1,138 @@
1
+ /**
2
+ * A Loro text delta as HTML or markdown. Pure functions: no Loro, no Svelte, no DOM, so the integrator's read-only pages and
3
+ * servers reach them through `@aionbuilders/nabu/format` without loading the WebAssembly (see `src/lib/format.js`).
4
+ * `text.behavior.svelte.js` re-exports them: the editor and the main entry keep their old import path.
5
+ */
6
+
7
+ import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
8
+ import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
9
+
10
+ /**
11
+ * Converts a Loro text delta to inline HTML.
12
+ * Marks are rendered as semantic HTML tags.
13
+ * @param {import('loro-crdt').Delta<string>[]} delta
14
+ * @returns {string}
15
+ */
16
+ export function deltaToHtml(delta) {
17
+ return delta.map(op => {
18
+ if (typeof op.insert !== 'string') return '';
19
+ let text = escapeHtml(op.insert);
20
+ const attrs = op.attributes || {};
21
+ if (attrs.code) text = `<code>${text}</code>`;
22
+ if (attrs.bold) text = `<strong>${text}</strong>`;
23
+ if (attrs.italic) text = `<em>${text}</em>`;
24
+ if (attrs.underline) text = `<u>${text}</u>`;
25
+ if (attrs.strikethrough) text = `<s>${text}</s>`;
26
+ if (attrs.link) {
27
+ // An unsafe href (javascript:, data:…) never becomes a live link: the label survives, the <a> does not.
28
+ const href = sanitizeUrl(attrs.link, { kind: 'link' });
29
+ if (href !== null) text = `<a href="${escapeAttr(href)}">${text}</a>`;
30
+ }
31
+ return text;
32
+ }).join('');
33
+ }
34
+
35
+ /**
36
+ * Converts a Loro text delta to inline Markdown.
37
+ * A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
38
+ * (a block that re-reads its own lines, like a callout body, keeps the plain newline).
39
+ * @param {import('loro-crdt').Delta<string>[]} delta
40
+ * @param {{ rawBreaks?: boolean }} [options]
41
+ * @returns {string}
42
+ */
43
+ export function deltaToMarkdown(delta, { rawBreaks = false } = {}) {
44
+ const ops = delta.filter((op) => typeof op.insert === 'string' && op.insert);
45
+ let out = '';
46
+ for (let i = 0; i < ops.length;) {
47
+ const link = ops[i].attributes?.link;
48
+ let j = i + 1;
49
+ while (j < ops.length && ops[j].attributes?.link === link) j++;
50
+ const run = markdownRuns(ops.slice(i, j), rawBreaks); // same href (or none): ONE `[…](href)`, marks inside
51
+ out += link ? `[${run}](${markdownDestination(String(link))})` : run;
52
+ i = j;
53
+ }
54
+ return escapeBlockStart(out);
55
+ }
56
+
57
+ /** Mark delimiters, outermost first (nesting order). Code is not here: a code span takes no other mark. */
58
+ const MARK_DELIMITERS = /** @type {const} */ ([
59
+ ['underline', '<u>', '</u>'],
60
+ ['strikethrough', '~~', '~~'],
61
+ ['bold', '**', '**'],
62
+ ['italic', '*', '*'],
63
+ ]);
64
+
65
+ /**
66
+ * Runs of text (no link boundary inside) as markdown. A mark spanning several runs is ONE delimiter pair
67
+ * (`**a *b* c**`); whitespace at the edge of a span moves outside the delimiters (`**a **` would not parse).
68
+ * @param {any[]} ops
69
+ * @param {boolean} rawBreaks
70
+ * @returns {string}
71
+ */
72
+ function markdownRuns(ops, rawBreaks) {
73
+ /** @type {Array<{ text?: string, raw?: boolean, open?: string, close?: string }>} */
74
+ let tokens = [];
75
+ /** @type {number[]} */
76
+ let active = [];
77
+ const closeFrom = (/** @type {number} */ k) => {
78
+ for (let j = active.length - 1; j >= k; j--) tokens.push({ close: MARK_DELIMITERS[active[j]][2] });
79
+ active = active.slice(0, k);
80
+ };
81
+ for (const op of ops) {
82
+ const attrs = op.attributes || {};
83
+ if (attrs.code) { closeFrom(0); tokens.push({ text: markdownCodeSpan(op.insert), raw: true }); continue; }
84
+ const want = MARK_DELIMITERS.map((m, idx) => (attrs[m[0]] ? idx : -1)).filter((idx) => idx >= 0);
85
+ let k = 0;
86
+ while (k < active.length && k < want.length && active[k] === want[k]) k++;
87
+ closeFrom(k);
88
+ for (let j = k; j < want.length; j++) tokens.push({ open: MARK_DELIMITERS[want[j]][1] });
89
+ active = want;
90
+ tokens.push({ text: op.insert });
91
+ }
92
+ closeFrom(0);
93
+
94
+ // Whitespace at the inner edge of a delimiter run moves outside it.
95
+ for (let t = 0; t < tokens.length; t++) {
96
+ if (tokens[t].open !== undefined && tokens[t - 1]?.open === undefined) {
97
+ let j = t;
98
+ while (tokens[j + 1]?.open !== undefined) j++;
99
+ const next = tokens[j + 1];
100
+ const m = next && next.text !== undefined && !next.raw ? /^\s+/.exec(next.text) : null;
101
+ if (next && m) { next.text = /** @type {string} */ (next.text).slice(m[0].length); tokens.splice(t, 0, { text: m[0] }); t += 1; }
102
+ } else if (tokens[t].close !== undefined && tokens[t - 1]?.close === undefined) {
103
+ let j = t;
104
+ while (tokens[j + 1]?.close !== undefined) j++;
105
+ const prev = tokens[t - 1];
106
+ const m = prev && prev.text !== undefined && !prev.raw ? /\s+$/.exec(prev.text) : null;
107
+ if (prev && m) { prev.text = /** @type {string} */ (prev.text).slice(0, -m[0].length); tokens.splice(j + 1, 0, { text: m[0] }); }
108
+ }
109
+ }
110
+ // Drop the delimiter pairs left empty.
111
+ tokens = tokens.filter((tk) => tk.text !== '');
112
+ for (let t = 0; t < tokens.length - 1;) {
113
+ if (tokens[t].open !== undefined && tokens[t + 1].close !== undefined) { tokens.splice(t, 2); t = Math.max(0, t - 1); } else t++;
114
+ }
115
+ return tokens.map((tk) => tk.open ?? tk.close ?? (tk.raw ? tk.text : escapeMarkdownText(/** @type {string} */ (tk.text)).replace(/\n/g, rawBreaks ? '\n' : '\\\n'))).join('');
116
+ }
117
+
118
+ /** A code span: a backtick fence longer than any run inside, padded when the text touches a backtick or is space-wrapped. */
119
+ function markdownCodeSpan(/** @type {string} */ text) {
120
+ const runs = new Set((text.match(/`+/g) || []).map((r) => r.length));
121
+ let n = 1;
122
+ while (runs.has(n)) n++;
123
+ const fence = '`'.repeat(n);
124
+ const pad = /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : '';
125
+ return fence + pad + text + pad + fence;
126
+ }
127
+
128
+ /** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
129
+ export function markdownDestination(/** @type {string} */ href) {
130
+ let depth = 0;
131
+ let balanced = true;
132
+ for (const ch of href) {
133
+ if (ch === '(') depth++;
134
+ else if (ch === ')' && --depth < 0) balanced = false;
135
+ }
136
+ if (!href || depth !== 0 || !balanced || /[\s<>\u0000-\u001f]/.test(href)) return '<' + href.replace(/[<>\\]/g, (m) => '\\' + m) + '>';
137
+ return href.replace(/\\/g, '\\\\');
138
+ }
@@ -1,23 +1,3 @@
1
- /**
2
- * Converts a Loro text delta to inline HTML.
3
- * Marks are rendered as semantic HTML tags.
4
- * @param {import('loro-crdt').Delta<string>[]} delta
5
- * @returns {string}
6
- */
7
- export function deltaToHtml(delta: import("loro-crdt").Delta<string>[]): string;
8
- /**
9
- * Converts a Loro text delta to inline Markdown.
10
- * A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
11
- * (a block that re-reads its own lines, like a callout body, keeps the plain newline).
12
- * @param {import('loro-crdt').Delta<string>[]} delta
13
- * @param {{ rawBreaks?: boolean }} [options]
14
- * @returns {string}
15
- */
16
- export function deltaToMarkdown(delta: import("loro-crdt").Delta<string>[], { rawBreaks }?: {
17
- rawBreaks?: boolean;
18
- }): string;
19
- /** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
20
- export function markdownDestination(href: string): string;
21
1
  /**
22
2
  * Length (UTF-16 units) of the user-perceived character starting at `index` — the unit one Delete press removes.
23
3
  * `Intl.Segmenter` handles ZWJ sequences, flags and combining marks; without it a surrogate pair is kept whole.
@@ -292,3 +272,4 @@ import type { Block } from "../../blocks";
292
272
  import { LoroText } from "loro-crdt";
293
273
  import type { NabuSelection } from "../../blocks";
294
274
  import type { NabuNode } from "../../blocks";
275
+ export { deltaToHtml, deltaToMarkdown, markdownDestination } from "./delta-format.js";
@@ -4,142 +4,15 @@
4
4
 
5
5
  import { LoroText } from "loro-crdt";
6
6
  import { tick } from "svelte";
7
- import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
8
- import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
7
+ import { sanitizeUrl } from "../../utils/html.js";
9
8
  import { countWords, wordDeleteRange } from "../../utils/words.js";
10
9
  import { readDelta } from "../../utils/delta.js";
11
10
  import { markEdgeFixes } from "./mark-edges.js";
12
11
  import { detectPlatform } from "../../utils/keys.js";
12
+ import { deltaToMarkdown } from "./delta-format.js";
13
13
 
14
- /**
15
- * Converts a Loro text delta to inline HTML.
16
- * Marks are rendered as semantic HTML tags.
17
- * @param {import('loro-crdt').Delta<string>[]} delta
18
- * @returns {string}
19
- */
20
- export function deltaToHtml(delta) {
21
- return delta.map(op => {
22
- if (typeof op.insert !== 'string') return '';
23
- let text = escapeHtml(op.insert);
24
- const attrs = op.attributes || {};
25
- if (attrs.code) text = `<code>${text}</code>`;
26
- if (attrs.bold) text = `<strong>${text}</strong>`;
27
- if (attrs.italic) text = `<em>${text}</em>`;
28
- if (attrs.underline) text = `<u>${text}</u>`;
29
- if (attrs.strikethrough) text = `<s>${text}</s>`;
30
- if (attrs.link) {
31
- // An unsafe href (javascript:, data:…) never becomes a live link: the label survives, the <a> does not.
32
- const href = sanitizeUrl(attrs.link, { kind: 'link' });
33
- if (href !== null) text = `<a href="${escapeAttr(href)}">${text}</a>`;
34
- }
35
- return text;
36
- }).join('');
37
- }
38
-
39
- /**
40
- * Converts a Loro text delta to inline Markdown.
41
- * A line break (`\n` in the text) is exported as a markdown hard break (backslash + newline), unless `rawBreaks`
42
- * (a block that re-reads its own lines, like a callout body, keeps the plain newline).
43
- * @param {import('loro-crdt').Delta<string>[]} delta
44
- * @param {{ rawBreaks?: boolean }} [options]
45
- * @returns {string}
46
- */
47
- export function deltaToMarkdown(delta, { rawBreaks = false } = {}) {
48
- const ops = delta.filter((op) => typeof op.insert === 'string' && op.insert);
49
- let out = '';
50
- for (let i = 0; i < ops.length;) {
51
- const link = ops[i].attributes?.link;
52
- let j = i + 1;
53
- while (j < ops.length && ops[j].attributes?.link === link) j++;
54
- const run = markdownRuns(ops.slice(i, j), rawBreaks); // same href (or none): ONE `[…](href)`, marks inside
55
- out += link ? `[${run}](${markdownDestination(String(link))})` : run;
56
- i = j;
57
- }
58
- return escapeBlockStart(out);
59
- }
60
-
61
- /** Mark delimiters, outermost first (nesting order). Code is not here: a code span takes no other mark. */
62
- const MARK_DELIMITERS = /** @type {const} */ ([
63
- ['underline', '<u>', '</u>'],
64
- ['strikethrough', '~~', '~~'],
65
- ['bold', '**', '**'],
66
- ['italic', '*', '*'],
67
- ]);
68
-
69
- /**
70
- * Runs of text (no link boundary inside) as markdown. A mark spanning several runs is ONE delimiter pair
71
- * (`**a *b* c**`); whitespace at the edge of a span moves outside the delimiters (`**a **` would not parse).
72
- * @param {any[]} ops
73
- * @param {boolean} rawBreaks
74
- * @returns {string}
75
- */
76
- function markdownRuns(ops, rawBreaks) {
77
- /** @type {Array<{ text?: string, raw?: boolean, open?: string, close?: string }>} */
78
- let tokens = [];
79
- /** @type {number[]} */
80
- let active = [];
81
- const closeFrom = (/** @type {number} */ k) => {
82
- for (let j = active.length - 1; j >= k; j--) tokens.push({ close: MARK_DELIMITERS[active[j]][2] });
83
- active = active.slice(0, k);
84
- };
85
- for (const op of ops) {
86
- const attrs = op.attributes || {};
87
- if (attrs.code) { closeFrom(0); tokens.push({ text: markdownCodeSpan(op.insert), raw: true }); continue; }
88
- const want = MARK_DELIMITERS.map((m, idx) => (attrs[m[0]] ? idx : -1)).filter((idx) => idx >= 0);
89
- let k = 0;
90
- while (k < active.length && k < want.length && active[k] === want[k]) k++;
91
- closeFrom(k);
92
- for (let j = k; j < want.length; j++) tokens.push({ open: MARK_DELIMITERS[want[j]][1] });
93
- active = want;
94
- tokens.push({ text: op.insert });
95
- }
96
- closeFrom(0);
97
-
98
- // Whitespace at the inner edge of a delimiter run moves outside it.
99
- for (let t = 0; t < tokens.length; t++) {
100
- if (tokens[t].open !== undefined && tokens[t - 1]?.open === undefined) {
101
- let j = t;
102
- while (tokens[j + 1]?.open !== undefined) j++;
103
- const next = tokens[j + 1];
104
- const m = next && next.text !== undefined && !next.raw ? /^\s+/.exec(next.text) : null;
105
- if (next && m) { next.text = /** @type {string} */ (next.text).slice(m[0].length); tokens.splice(t, 0, { text: m[0] }); t += 1; }
106
- } else if (tokens[t].close !== undefined && tokens[t - 1]?.close === undefined) {
107
- let j = t;
108
- while (tokens[j + 1]?.close !== undefined) j++;
109
- const prev = tokens[t - 1];
110
- const m = prev && prev.text !== undefined && !prev.raw ? /\s+$/.exec(prev.text) : null;
111
- if (prev && m) { prev.text = /** @type {string} */ (prev.text).slice(0, -m[0].length); tokens.splice(j + 1, 0, { text: m[0] }); }
112
- }
113
- }
114
- // Drop the delimiter pairs left empty.
115
- tokens = tokens.filter((tk) => tk.text !== '');
116
- for (let t = 0; t < tokens.length - 1;) {
117
- if (tokens[t].open !== undefined && tokens[t + 1].close !== undefined) { tokens.splice(t, 2); t = Math.max(0, t - 1); } else t++;
118
- }
119
- return tokens.map((tk) => tk.open ?? tk.close ?? (tk.raw ? tk.text : escapeMarkdownText(/** @type {string} */ (tk.text)).replace(/\n/g, rawBreaks ? '\n' : '\\\n'))).join('');
120
- }
121
-
122
- /** A code span: a backtick fence longer than any run inside, padded when the text touches a backtick or is space-wrapped. */
123
- function markdownCodeSpan(/** @type {string} */ text) {
124
- const runs = new Set((text.match(/`+/g) || []).map((r) => r.length));
125
- let n = 1;
126
- while (runs.has(n)) n++;
127
- const fence = '`'.repeat(n);
128
- const pad = /^`|`$/.test(text) || (text.startsWith(' ') && text.endsWith(' ') && text.trim()) ? ' ' : '';
129
- return fence + pad + text + pad + fence;
130
- }
131
-
132
- /** A link destination: raw when plain, `<…>` when it holds whitespace, angle brackets or unbalanced parentheses. */
133
- export function markdownDestination(/** @type {string} */ href) {
134
- let depth = 0;
135
- let balanced = true;
136
- for (const ch of href) {
137
- if (ch === '(') depth++;
138
- else if (ch === ')' && --depth < 0) balanced = false;
139
- }
140
- if (!href || depth !== 0 || !balanced || /[\s<>\u0000-\u001f]/.test(href)) return '<' + href.replace(/[<>\\]/g, (m) => '\\' + m) + '>';
141
- return href.replace(/\\/g, '\\\\');
142
- }
14
+ // The delta formatters live in a pure file (no Loro, no Svelte); every existing import path keeps working through this re-export.
15
+ export { deltaToHtml, deltaToMarkdown, markdownDestination } from "./delta-format.js";
143
16
 
144
17
  /**
145
18
  * @typedef {NabuNode<{type: "paragraph", text: LoroText}>} TextNode
@@ -10,9 +10,14 @@
10
10
  * assistive technology when both are set. No `role` is ever set on an editable root: it would flatten the headings inside.
11
11
  * - `readonly`: show the document without letting anyone edit it. Reactive (toggle it live). When omitted, the editor follows
12
12
  * `engine.readonly` (the `readonly` option of the engine); when given, it sets `engine.readonly`.
13
- * @type {{ engine: Nabu, label?: string, labelledby?: string, readonly?: boolean }}
13
+ * - Any other attribute (`id`, `class`, `style`, `aria-describedby`, `inputmode`, `enterkeyhint`, `autocapitalize`, `data-*`...) goes
14
+ * to the root element, and `class` is added to `nabu-editor`. The editor's own attributes and handlers come after them and always
15
+ * win: `contenteditable`, `role`, `spellcheck`, `lang`, `translate`, `aria-label`, `aria-labelledby`, `data-nabu-*` and every `on*`
16
+ * handler cannot be overridden (use `label` / `labelledby`, `readonly`, and the engine options). Events bubble: listen to them on a
17
+ * parent element of the editor.
18
+ * @type {{ engine: Nabu, label?: string, labelledby?: string, readonly?: boolean } & import('svelte/elements').HTMLAttributes<HTMLDivElement>}
14
19
  */
15
- let { engine = new Nabu(), label = undefined, labelledby = undefined, readonly = undefined } = $props();
20
+ let { engine = new Nabu(), label = undefined, labelledby = undefined, readonly = undefined, class: className = undefined, ...rest } = $props();
16
21
 
17
22
  // The prop drives the engine (set now, so that the first render and the server render already agree, then kept in sync live):
18
23
  // the engine is where every guard reads it. `isReadonly` is what this component draws.
@@ -58,8 +63,9 @@
58
63
  <!-- With spellcheck off, the data-gramm* attributes are the documented opt-out hints of the Grammarly extension (it would
59
64
  otherwise inject its own DOM into the editor, which Nabu does not support). Code blocks set spellcheck="false" themselves. -->
60
65
  <div
66
+ {...rest}
61
67
  contenteditable={isReadonly ? 'false' : 'true'}
62
- class="nabu-editor"
68
+ class={['nabu-editor', className]}
63
69
  aria-label={label}
64
70
  aria-labelledby={labelledby}
65
71
  role={isReadonly ? 'document' : undefined}
@@ -1,25 +1,4 @@
1
1
  export default Nabu;
2
- type Nabu = {
3
- $on?(type: string, callback: (e: any) => void): () => void;
4
- $set?(props: Partial<$$ComponentProps>): void;
5
- };
6
- declare const Nabu: import("svelte").Component<{
7
- engine: Nabu;
8
- label?: string;
9
- labelledby?: string;
10
- readonly?: boolean;
11
- }, {}, "">;
2
+ type Nabu = any;
3
+ declare const Nabu: any;
12
4
  import { Nabu } from "./nabu.svelte.js";
13
- /**
14
- * - `label`: the accessible name of the editor (`aria-label` on the contenteditable root), e.g. "Chapter text".
15
- * - `labelledby`: the id of the element that names it (`aria-labelledby`), for a visible `<label>`. Wins over `label` for
16
- * assistive technology when both are set. No `role` is ever set on an editable root: it would flatten the headings inside.
17
- * - `readonly`: show the document without letting anyone edit it. Reactive (toggle it live). When omitted, the editor follows
18
- * `engine.readonly` (the `readonly` option of the engine); when given, it sets `engine.readonly`.
19
- */
20
- type $$ComponentProps = {
21
- engine: Nabu;
22
- label?: string;
23
- labelledby?: string;
24
- readonly?: boolean;
25
- };
@@ -307,8 +307,9 @@ export class Nabu {
307
307
  */
308
308
  public get isEmpty(): boolean;
309
309
  /**
310
- * Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, or one an extension
311
- * adds with `serializers`); `null` (and a warning) for an unknown format.
310
+ * Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, `'text'`, or one an extension
311
+ * adds with `serializers`); `null` (and a warning) for an unknown format. `'text'` is the plain text a person typed: no
312
+ * escaping, no markup (see `jsonToText` in `@aionbuilders/nabu/format` for the exact rule).
312
313
  * @param {string} format
313
314
  * @returns {any}
314
315
  * @public
@@ -4,8 +4,9 @@ import { Block } from './block.svelte.js';
4
4
  import { MegaBlock } from './megablock.svelte.js';
5
5
  import { NabuSelection } from './selection.svelte.js';
6
6
  import { handleContainerBeforeInput, wrapOrphan, deleteSelectionContent, deleteRange, selectionRange, findDirectChildOf, findLCA, textBlocksInOrder } from './container.utils.js';
7
- import { jsonToPasteBlocks, degradeUnknownBlocks, CLIPBOARD_FORMAT_VERSION, JSON_FORMAT_VERSION, isSupportedJsonVersion } from '../utils/extensions.js';
7
+ import { jsonToPasteBlocks, degradeUnknownBlocks, dropUndeclaredMarks, CLIPBOARD_FORMAT_VERSION, JSON_FORMAT_VERSION, isSupportedJsonVersion } from '../utils/extensions.js';
8
8
  import { escapeHtml, sanitizePasteBlocks } from '../utils/html.js';
9
+ import { jsonToText } from '../format.js';
9
10
  import { tick, flushSync } from 'svelte';
10
11
  import { Files } from '../files/files.svelte.js';
11
12
  import { Pulse } from '@aionbuilders/pulse';
@@ -163,6 +164,8 @@ export class Nabu {
163
164
  #pulse = new Pulse();
164
165
  /** @type {import('../utils/extensions.js').PasteInterpreter[]} */
165
166
  #pasteInterpreters = [];
167
+ /** The marks of this editor: those its extensions declare in `loroTextStyles`. Any other attribute of a pasted / imported text is dropped. @type {Set<string>} */
168
+ #declaredMarks = new Set();
166
169
  /** @type {import('../utils/extensions.js').PasteFileHandler[]} sorted by priority, highest first */
167
170
  #pasteFileHandlers = [];
168
171
 
@@ -362,6 +365,7 @@ export class Nabu {
362
365
 
363
366
  if (ext.loroTextStyles && Object.keys(ext.loroTextStyles).length) {
364
367
  this.doc.configTextStyle(ext.loroTextStyles);
368
+ for (const mark of Object.keys(ext.loroTextStyles)) this.#declaredMarks.add(mark);
365
369
  }
366
370
 
367
371
  }
@@ -664,7 +668,10 @@ export class Nabu {
664
668
  // The bytes of the `nabu-asset:` media travel with the document (same `assets` map as the clipboard format).
665
669
  const assets = Files.get(nabu).embedAssets(blocks);
666
670
  return { version: JSON_FORMAT_VERSION, blocks, ...(assets ? { assets } : {}) };
667
- }]
671
+ }],
672
+ // The text as typed (see `jsonToText`), computed from the same blocks as 'json' but without the embedded assets:
673
+ // the bytes of a file are of no use to a text. A server that holds the JSON export gets the identical string.
674
+ ['text', (nabu) => jsonToText(nabu.children.map(b => b.serialize('json')).filter(Boolean))]
668
675
  ]));
669
676
 
670
677
  /**
@@ -689,8 +696,9 @@ export class Nabu {
689
696
  }
690
697
 
691
698
  /**
692
- * Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, or one an extension
693
- * adds with `serializers`); `null` (and a warning) for an unknown format.
699
+ * Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, `'text'`, or one an extension
700
+ * adds with `serializers`); `null` (and a warning) for an unknown format. `'text'` is the plain text a person typed: no
701
+ * escaping, no markup (see `jsonToText` in `@aionbuilders/nabu/format` for the exact rule).
694
702
  * @param {string} format
695
703
  * @returns {any}
696
704
  * @public
@@ -2204,7 +2212,7 @@ export class Nabu {
2204
2212
  this.selection.sync(); // public entry point: may be called outside an input event
2205
2213
  // Every fragment (HTML / markdown / nabu JSON / API) goes through here: unsafe link & media URLs are dropped.
2206
2214
  const files = Files.get(this);
2207
- let adopted = files.adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets);
2215
+ let adopted = files.adoptAssets(sanitizePasteBlocks(dropUndeclaredMarks(fragment.blocks, this.#declaredMarks)), fragment.assets);
2208
2216
  // Content from outside (a web page): remote images are fetched and stored, when the host asked for it (`files.importRemote`).
2209
2217
  if (fragment.external) adopted = files.importRemote(adopted);
2210
2218
  const blocks = this.#degradeUnknown(adopted);
@@ -2461,7 +2469,7 @@ export class Nabu {
2461
2469
  * @public
2462
2470
  */
2463
2471
  async importFragment(fragment) {
2464
- const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets));
2472
+ const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(dropUndeclaredMarks(fragment.blocks, this.#declaredMarks)), fragment.assets));
2465
2473
  if (!blocks?.length) return;
2466
2474
 
2467
2475
  [...this.tree.roots()].forEach(root => this.tree.delete(root.id));
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The plain text of a document: what a person typed, without markup. Takes a `serialize('json')` export, or its `blocks`
3
+ * array, and is what `serialize('text')` computes, so the browser and a server working from the same JSON get the identical string.
4
+ *
5
+ * The rule:
6
+ * - A block's text is its characters as typed: no escaping, no markup, marks and links ignored, a line break inside the block
7
+ * kept as `\n`. Nothing is trimmed.
8
+ * - Blocks are separated by a blank line (`\n\n`). The items of a list and their nested items are separated by a single `\n`,
9
+ * with no bullet or number.
10
+ * - A block without text (divider, image, video, file) and an empty block contribute nothing, so no blank lines pile up.
11
+ * - A container (toggle, callout, region...) gives its own text (a region: its title), then its children's, in order.
12
+ * - It reads the `content` of any block, so a block from an extension is covered without registering anything.
13
+ *
14
+ * To keep proof of what a person wrote, store the string you received: do not recompute it later with a newer version of the library.
15
+ * @param {{ blocks?: any[] } | any[]} json a `serialize('json')` export or its `blocks`
16
+ * @returns {string}
17
+ */
18
+ export function jsonToText(json: {
19
+ blocks?: any[];
20
+ } | any[]): string;
21
+ export { deltaToHtml, deltaToMarkdown } from "./behaviors/text/delta-format.js";
22
+ export { sanitizeUrl, escapeHtml } from "./utils/html.js";
23
+ export { JSON_FORMAT_VERSION, isSupportedJsonVersion } from "./utils/extensions.js";
package/dist/format.js ADDED
@@ -0,0 +1,60 @@
1
+ /**
2
+ * @module @aionbuilders/nabu/format
3
+ *
4
+ * Reading a document without the editor: turn the `serialize('json')` export (or a Loro-style delta) into HTML, markdown or
5
+ * plain text. Pure JavaScript: nothing here imports Loro, Svelte or the DOM, so a read-only page or a server loads this entry
6
+ * without the WebAssembly (importing the same names from `@aionbuilders/nabu` does load it), and plain Node and Bun can import it.
7
+ * The import graph of this file is pinned by `tests/unit/format.test.js`.
8
+ *
9
+ * @example
10
+ * import { jsonToText, deltaToHtml } from '@aionbuilders/nabu/format';
11
+ */
12
+
13
+ export { deltaToHtml, deltaToMarkdown } from './behaviors/text/delta-format.js';
14
+ export { sanitizeUrl, escapeHtml } from './utils/html.js';
15
+ export { JSON_FORMAT_VERSION, isSupportedJsonVersion } from './utils/extensions.js';
16
+
17
+ /** The text of a block's `content`: a plain string (code), or the `text` of its runs. Marks are ignored. @param {unknown} content */
18
+ function contentText(content) {
19
+ if (typeof content === 'string') return content;
20
+ if (!Array.isArray(content)) return '';
21
+ return content.map((run) => (typeof run?.text === 'string' ? run.text : '')).join('');
22
+ }
23
+
24
+ /** @param {any} blocks @returns {string[]} the non-empty texts of `blocks` */
25
+ function textsOf(blocks) {
26
+ return (Array.isArray(blocks) ? blocks : []).map(blockText).filter((text) => text !== '');
27
+ }
28
+
29
+ /**
30
+ * One block: its own text, then its children's, in order. A list and a list item join with a single newline, anything else
31
+ * with a blank line.
32
+ * @param {any} block
33
+ * @returns {string}
34
+ */
35
+ function blockText(block) {
36
+ if (!block || typeof block !== 'object') return '';
37
+ const parts = [contentText(block.content), ...textsOf(block.children)].filter((text) => text !== '');
38
+ return parts.join(block.type === 'list' || block.type === 'list-item' ? '\n' : '\n\n');
39
+ }
40
+
41
+ /**
42
+ * The plain text of a document: what a person typed, without markup. Takes a `serialize('json')` export, or its `blocks`
43
+ * array, and is what `serialize('text')` computes, so the browser and a server working from the same JSON get the identical string.
44
+ *
45
+ * The rule:
46
+ * - A block's text is its characters as typed: no escaping, no markup, marks and links ignored, a line break inside the block
47
+ * kept as `\n`. Nothing is trimmed.
48
+ * - Blocks are separated by a blank line (`\n\n`). The items of a list and their nested items are separated by a single `\n`,
49
+ * with no bullet or number.
50
+ * - A block without text (divider, image, video, file) and an empty block contribute nothing, so no blank lines pile up.
51
+ * - A container (toggle, callout, region...) gives its own text (a region: its title), then its children's, in order.
52
+ * - It reads the `content` of any block, so a block from an extension is covered without registering anything.
53
+ *
54
+ * To keep proof of what a person wrote, store the string you received: do not recompute it later with a newer version of the library.
55
+ * @param {{ blocks?: any[] } | any[]} json a `serialize('json')` export or its `blocks`
56
+ * @returns {string}
57
+ */
58
+ export function jsonToText(json) {
59
+ return textsOf(Array.isArray(json) ? json : json?.blocks).join('\n\n');
60
+ }
@@ -204,7 +204,9 @@ export function resolveLinkHref(href) {
204
204
  function collect(el, marks, preserve, verbatim, out) {
205
205
  for (const child of el.childNodes) {
206
206
  if (child.nodeType === Node.TEXT_NODE) {
207
- const s = child.textContent;
207
+ // Chromium writes every space at the edge of an inline element as `<span>&nbsp;</span>` on copy: not a typographic choice.
208
+ const converted = !verbatim && child.textContent === '\u00a0' && /** @type {Element} */ (el).tagName === 'SPAN' && el.childNodes.length === 1;
209
+ const s = converted ? ' ' : child.textContent;
208
210
  if (s) out.push({ s, marks, preserve, verbatim });
209
211
  } else if (child.nodeType === Node.ELEMENT_NODE) {
210
212
  const el2 = /** @type {Element} */ (child);
@@ -252,6 +254,7 @@ const HTML_WS = /^[ \t\n\r\f]$/;
252
254
  * `white-space: pre | pre-wrap | break-spaces` where it is kept; `<br>` is a line break;
253
255
  * - U+00A0 between two visible characters is KEPT ("10 km", "Bonjour :"); next to another space or at the edge of a
254
256
  * line / block it is a regular space (then collapsed like any space);
257
+ * - a `<span>` holding nothing but one U+00A0 is a regular space: what Chromium's copy makes of a plain space (see `collect`);
255
258
  * - every other character (U+202F, U+2007, U+2060, U+00AD, ZWJ, ZWNJ…) is left untouched.
256
259
  * @param {Token[]} tokens
257
260
  * @param {{ keepEdges?: boolean }} [options] `keepEdges`: keep one collapsed space at the edges (a fragment of a line)
@@ -14,6 +14,16 @@
14
14
  * @returns {PasteBlock[]}
15
15
  */
16
16
  export function degradeUnknownBlocks(blocks: PasteBlock[], isKnown: (type: string) => boolean, fallbackType: string | null | undefined): PasteBlock[];
17
+ /**
18
+ * Drops from the text of the blocks (and of their children, at any depth) every attribute that is not a mark the receiving editor
19
+ * declares (`loroTextStyles` of its extensions): the text stays, only the formatting goes. A fragment that comes in (paste, import)
20
+ * carries the marks of where it was written; an editor without the matching extension has no way to show or remove them.
21
+ * Pure: returns new objects where something changed, never mutates the input.
22
+ * @param {PasteBlock[]} blocks
23
+ * @param {ReadonlySet<string>} declared the mark names of the editor
24
+ * @returns {PasteBlock[]}
25
+ */
26
+ export function dropUndeclaredMarks(blocks: PasteBlock[], declared: ReadonlySet<string>): PasteBlock[];
17
27
  /**
18
28
  * Whether `importJSON` can read a document export of this `version` (see {@link JSON_FORMAT_VERSION}). A missing version is
19
29
  * read as the current one; the number `1` and the string `'1'` are the same version.
@@ -223,6 +233,8 @@ export function jsonToPasteBlocks(blocks: Array<{
223
233
  * Loro text style configuration required by this extension.
224
234
  * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
225
235
  * `applyDelta` with these attributes works correctly.
236
+ * These are the marks of the editor: a mark exists only if an extension declares it here, and any other attribute of a pasted or
237
+ * imported text is dropped (the text stays).
226
238
  */
227
239
  /**
228
240
  * A named bundle of editor behaviour (see {@link ExtensionInit}); the built-in blocks and behaviours are extensions. Build one with
@@ -571,6 +583,8 @@ export type ExtensionInit = {
571
583
  * Loro text style configuration required by this extension.
572
584
  * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
573
585
  * `applyDelta` with these attributes works correctly.
586
+ * These are the marks of the editor: a mark exists only if an extension declares it here, and any other attribute of a pasted or
587
+ * imported text is dropped (the text stays).
574
588
  */
575
589
  loroTextStyles?: Record<string, {
576
590
  expand: "after" | "before" | "both" | "none";
@@ -196,6 +196,8 @@
196
196
  * Loro text style configuration required by this extension.
197
197
  * Passed to `LoroDoc.configTextStyle()` during Nabu initialization so that
198
198
  * `applyDelta` with these attributes works correctly.
199
+ * These are the marks of the editor: a mark exists only if an extension declares it here, and any other attribute of a pasted or
200
+ * imported text is dropped (the text stays).
199
201
  */
200
202
 
201
203
  /**
@@ -313,6 +315,40 @@ export function degradeUnknownBlocks(blocks, isKnown, fallbackType) {
313
315
  return walk(blocks);
314
316
  }
315
317
 
318
+ /**
319
+ * Drops from the text of the blocks (and of their children, at any depth) every attribute that is not a mark the receiving editor
320
+ * declares (`loroTextStyles` of its extensions): the text stays, only the formatting goes. A fragment that comes in (paste, import)
321
+ * carries the marks of where it was written; an editor without the matching extension has no way to show or remove them.
322
+ * Pure: returns new objects where something changed, never mutates the input.
323
+ * @param {PasteBlock[]} blocks
324
+ * @param {ReadonlySet<string>} declared the mark names of the editor
325
+ * @returns {PasteBlock[]}
326
+ */
327
+ export function dropUndeclaredMarks(blocks, declared) {
328
+ if (!Array.isArray(blocks)) return blocks;
329
+ return blocks.map((pb) => {
330
+ if (!pb || typeof pb !== 'object') return pb;
331
+ let out = pb;
332
+ if (Array.isArray(pb.delta)) {
333
+ let changed = false;
334
+ const delta = pb.delta.map((op) => {
335
+ if (!op?.attributes || typeof op.attributes !== 'object') return op;
336
+ const kept = Object.entries(op.attributes).filter(([name]) => declared.has(name));
337
+ if (kept.length === Object.keys(op.attributes).length) return op;
338
+ changed = true;
339
+ const { attributes: _drop, ...rest } = op;
340
+ return kept.length ? { ...rest, attributes: Object.fromEntries(kept) } : rest;
341
+ });
342
+ if (changed) out = { ...out, delta };
343
+ }
344
+ if (Array.isArray(pb.children) && pb.children.length) {
345
+ const children = dropUndeclaredMarks(pb.children, declared);
346
+ if (children.some((c, i) => c !== pb.children?.[i])) out = { ...out, children };
347
+ }
348
+ return out;
349
+ });
350
+ }
351
+
316
352
  /** Version written by `serialize('json')` (document export). `importJSON` reads this one (a missing version is read as it). */
317
353
  export const JSON_FORMAT_VERSION = '1';
318
354
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.4",
3
+ "version": "0.1.5",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",
@@ -45,6 +45,10 @@
45
45
  "types": "./dist/extend.d.ts",
46
46
  "svelte": "./dist/extend.js"
47
47
  },
48
+ "./format": {
49
+ "types": "./dist/format.d.ts",
50
+ "default": "./dist/format.js"
51
+ },
48
52
  "./vite": {
49
53
  "types": "./dist/vite.d.ts",
50
54
  "default": "./dist/vite.js"