@aionbuilders/nabu 0.1.4 → 0.1.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.
- package/CHANGELOG.md +27 -2
- package/README.md +1 -0
- package/dist/behaviors/text/delta-format.d.ts +20 -0
- package/dist/behaviors/text/delta-format.js +138 -0
- package/dist/behaviors/text/text.behavior.svelte.d.ts +16 -30
- package/dist/behaviors/text/text.behavior.svelte.js +45 -181
- package/dist/blocks/BlockList.svelte +12 -2
- package/dist/blocks/BlockList.svelte.d.ts +5 -1
- package/dist/blocks/Nabu.svelte +9 -3
- package/dist/blocks/Nabu.svelte.d.ts +2 -23
- package/dist/blocks/nabu.svelte.d.ts +3 -2
- package/dist/blocks/nabu.svelte.js +28 -17
- package/dist/blocks/region/Region.svelte +19 -10
- package/dist/format.d.ts +23 -0
- package/dist/format.js +60 -0
- package/dist/paste/html.paste.js +4 -1
- package/dist/utils/extensions.d.ts +14 -0
- package/dist/utils/extensions.js +36 -0
- package/package.json +6 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,8 +1,33 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
-
##
|
|
3
|
+
## 0.1.6 (2026-11-15)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Two browser fixes: IME compositions in Firefox, and typing in long documents on WebKit. No API change.
|
|
6
|
+
|
|
7
|
+
### Fixed
|
|
8
|
+
- **Firefox: the text froze after an IME composition in an empty block.** Firefox puts the composed text in a new text node, and Svelte went on updating the old one: what was typed next reached the model but not the screen, and the caret jumped to the start. The block's render now goes back as Svelte left it when a composition ends, and the model shows the composed text through it. This covers every browser and every text block, including code blocks.
|
|
9
|
+
- **WebKit: typing in the middle of a long document with nested regions took ~400 ms per key.** In a large document every region body was skipped off screen with `content-visibility: auto`, and WebKit pays on every frame for such boxes nested inside each other. Only the innermost region bodies are skipped now, never one inside another. On a 90,000-word novel (parts, chapters, scenes), a key in the middle takes 22 ms instead of ~390 ms on WebKitGTK, and Chromium does not change.
|
|
10
|
+
- **Composed text ignored the bold you had switched on, and could show twice.** A composition now gets the same marks as typed text: the marks you switched on, and the rule for mark edges. At the end of a bold run, the composed text showed both in the run and after it.
|
|
11
|
+
|
|
12
|
+
### Tests
|
|
13
|
+
- `bun run test:consumer` packs the package as npm would publish it, installs the tarball in a fresh SvelteKit app, builds it and checks on Chromium, Firefox and WebKit that the editor boots and takes typing on an SSR, a client-only, a lazy and a server-built page. It catches what only a consumer sees (a change to how Loro's WASM is loaded broke a client-only route on WebKit while every other test was green).
|
|
14
|
+
- A `firefox` Playwright project (`tests/e2e/firefox`) drives compositions on the real browser. Run `bunx playwright install firefox` once. `core` still runs on Chromium only.
|
|
15
|
+
- `tests/e2e/large-docs-auto-boxes.spec.ts` checks that no skipped box is ever inside another. A `perf-webkit` project, run on demand, types in the middle of a 90,000-word novel and fails above 60 ms per key at the median.
|
|
16
|
+
|
|
17
|
+
## 0.1.5 (2026-11-04)
|
|
18
|
+
|
|
19
|
+
Plain text, a way to render a document without the editor, and two fixes for small editors.
|
|
20
|
+
|
|
21
|
+
### Added
|
|
22
|
+
- **`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.
|
|
23
|
+
- **`@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.
|
|
24
|
+
- **`<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.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- **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.
|
|
28
|
+
- **HTML copied in Chromium kept non-breaking spaces.** Chromium's copy writes a space at the edge of an inline element as `<span> </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 km`) stays.
|
|
29
|
+
- **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.
|
|
30
|
+
- **Three site tests depended on the load of the machine**: a race on a client-side navigation, and screenshot loops over the default timeout.
|
|
6
31
|
|
|
7
32
|
## 0.1.4 (2026-11-04)
|
|
8
33
|
|
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.
|
|
@@ -91,20 +71,19 @@ export class TextBehavior {
|
|
|
91
71
|
*/
|
|
92
72
|
modelOffset(node: Node, offset: number, element?: HTMLElement | null): number;
|
|
93
73
|
/**
|
|
94
|
-
* IME composition starts.
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
* additions at the end. No filler: nothing to do.
|
|
74
|
+
* IME composition starts. The browser owns the DOM until it ends, and what it does there is not known to Svelte: it may put the
|
|
75
|
+
* composed text in a NEW text node (Firefox, in an empty block), swap a node for a `<br>`, or write it into a run the model
|
|
76
|
+
* will not give it to (the end of a bold run). Remember the render so {@link TextBehavior#restoreAfterComposition} can put it back.
|
|
77
|
+
* Nested blocks and UI are not this block's render: the walk stops at them.
|
|
99
78
|
*/
|
|
100
79
|
snapshotForComposition(): void;
|
|
101
80
|
/**
|
|
102
|
-
* End of a composition
|
|
103
|
-
*
|
|
104
|
-
*
|
|
105
|
-
*
|
|
81
|
+
* End of a composition, BEFORE the composed text reaches the model: the render goes back as Svelte left it, and the model shows
|
|
82
|
+
* the composed text through it on the next render, in the run it really belongs to. Without this Svelte updates nodes that are
|
|
83
|
+
* no longer in the page (the DOM freezes while the model moves on), or the text shows twice.
|
|
84
|
+
* If the model changed meanwhile (a programmatic edit), Svelte has already rendered over the snapshot: it stays as it is.
|
|
106
85
|
*/
|
|
107
|
-
restoreAfterComposition(
|
|
86
|
+
restoreAfterComposition(): void;
|
|
108
87
|
/**
|
|
109
88
|
* @param {InputEvent} event
|
|
110
89
|
* @param {ReturnType<TextBehavior["getSelection"]>} [selection]
|
|
@@ -113,6 +92,12 @@ export class TextBehavior {
|
|
|
113
92
|
public handleBeforeInput(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): any;
|
|
114
93
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
|
|
115
94
|
handleInsertText(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
|
|
95
|
+
/**
|
|
96
|
+
* The marks of a run the user just typed or composed at `[from, from + length)`: the cursor's pending stored marks, then the rule
|
|
97
|
+
* for mark edges.
|
|
98
|
+
* @param {number} from @param {number} length
|
|
99
|
+
*/
|
|
100
|
+
markTypedRun(from: number, length: number): void;
|
|
116
101
|
/**
|
|
117
102
|
* Make the run just typed at `[from, from + length)` follow Nabu's rule for mark edges (see mark-edges.js): it keeps a mark only
|
|
118
103
|
* when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
|
|
@@ -292,3 +277,4 @@ import type { Block } from "../../blocks";
|
|
|
292
277
|
import { LoroText } from "loro-crdt";
|
|
293
278
|
import type { NabuSelection } from "../../blocks";
|
|
294
279
|
import type { NabuNode } from "../../blocks";
|
|
280
|
+
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 {
|
|
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
|
-
|
|
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
|
|
@@ -281,65 +154,48 @@ export class TextBehavior {
|
|
|
281
154
|
return this.nabu.composing ? at : Math.min(at, this.text.length);
|
|
282
155
|
}
|
|
283
156
|
|
|
284
|
-
/** The render of
|
|
285
|
-
#emptySnapshot = null;
|
|
286
|
-
|
|
287
|
-
/** Svelte's own nodes around a trailing render filler when an IME composition started: its text nodes and the filler with its place. @type {{ texts: Set<Node>, filler: Element, parent: Node, next: Node | null } | null} */
|
|
157
|
+
/** The render of the block when an IME composition started: its elements with their children, its text nodes with their text, and the model text it shows. @type {{ text: string, children: Map<Node, Node[]>, data: Map<Text, string> } | null} */
|
|
288
158
|
#compositionSnapshot = null;
|
|
289
159
|
|
|
290
160
|
/**
|
|
291
|
-
* IME composition starts.
|
|
292
|
-
*
|
|
293
|
-
*
|
|
294
|
-
*
|
|
295
|
-
* additions at the end. No filler: nothing to do.
|
|
161
|
+
* IME composition starts. The browser owns the DOM until it ends, and what it does there is not known to Svelte: it may put the
|
|
162
|
+
* composed text in a NEW text node (Firefox, in an empty block), swap a node for a `<br>`, or write it into a run the model
|
|
163
|
+
* will not give it to (the end of a bold run). Remember the render so {@link TextBehavior#restoreAfterComposition} can put it back.
|
|
164
|
+
* Nested blocks and UI are not this block's render: the walk stops at them.
|
|
296
165
|
*/
|
|
297
166
|
snapshotForComposition() {
|
|
298
167
|
const element = this.block.element;
|
|
299
168
|
this.#compositionSnapshot = null;
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
169
|
+
if (!element) return;
|
|
170
|
+
/** @type {Map<Node, Node[]>} */
|
|
171
|
+
const children = new Map([[element, [...element.childNodes]]]);
|
|
172
|
+
/** @type {Map<Text, string>} */
|
|
173
|
+
const data = new Map();
|
|
174
|
+
const walker = document.createTreeWalker(element, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
|
|
175
|
+
acceptNode: (n) => n.nodeType === Node.ELEMENT_NODE && (/** @type {Element} */ (n).hasAttribute('data-block-id') || /** @type {Element} */ (n).hasAttribute('data-nabu-ui')) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
|
|
176
|
+
});
|
|
177
|
+
for (let n = walker.nextNode(); n; n = walker.nextNode()) {
|
|
178
|
+
if (n.nodeType === Node.TEXT_NODE) data.set(/** @type {Text} */ (n), /** @type {Text} */ (n).data);
|
|
179
|
+
else children.set(n, [...n.childNodes]);
|
|
306
180
|
}
|
|
307
|
-
|
|
308
|
-
if (!element || !filler?.parentNode) return;
|
|
309
|
-
const texts = new Set();
|
|
310
|
-
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
|
311
|
-
for (let n = walker.nextNode(); n; n = walker.nextNode()) texts.add(n);
|
|
312
|
-
this.#compositionSnapshot = { texts, filler, parent: filler.parentNode, next: filler.nextSibling };
|
|
181
|
+
this.#compositionSnapshot = { text: this.text, children, data };
|
|
313
182
|
}
|
|
314
183
|
|
|
315
184
|
/**
|
|
316
|
-
* End of a composition
|
|
317
|
-
*
|
|
318
|
-
*
|
|
319
|
-
*
|
|
185
|
+
* End of a composition, BEFORE the composed text reaches the model: the render goes back as Svelte left it, and the model shows
|
|
186
|
+
* the composed text through it on the next render, in the run it really belongs to. Without this Svelte updates nodes that are
|
|
187
|
+
* no longer in the page (the DOM freezes while the model moves on), or the text shows twice.
|
|
188
|
+
* If the model changed meanwhile (a programmatic edit), Svelte has already rendered over the snapshot: it stays as it is.
|
|
320
189
|
*/
|
|
321
|
-
restoreAfterComposition(
|
|
190
|
+
restoreAfterComposition() {
|
|
322
191
|
const snap = this.#compositionSnapshot;
|
|
323
192
|
this.#compositionSnapshot = null;
|
|
324
|
-
|
|
325
|
-
const
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
// Canceled in an empty block: the render text node (not a browser <br>) with its text, as Svelte left it.
|
|
329
|
-
element.replaceChildren(...empty.nodes);
|
|
330
|
-
empty.nodes.forEach((n, i) => { if (n.nodeType === Node.TEXT_NODE && /** @type {Text} */ (n).data !== empty.data[i]) /** @type {Text} */ (n).data = empty.data[i]; });
|
|
331
|
-
return;
|
|
332
|
-
}
|
|
333
|
-
if (!snap || !element) return;
|
|
334
|
-
/** @type {Node[]} */
|
|
335
|
-
const stray = [];
|
|
336
|
-
const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
|
|
337
|
-
for (let n = walker.nextNode(); n; n = walker.nextNode()) if (!snap.texts.has(n)) stray.push(n);
|
|
338
|
-
for (const br of element.querySelectorAll('br')) if (br !== snap.filler) stray.push(br);
|
|
339
|
-
for (const n of stray) n.parentNode?.removeChild(n);
|
|
340
|
-
if (!composedText && !snap.filler.isConnected) {
|
|
341
|
-
snap.parent.insertBefore(snap.filler, snap.next?.parentNode === snap.parent ? snap.next : null);
|
|
193
|
+
if (!snap || this.text !== snap.text) return;
|
|
194
|
+
for (const [parent, nodes] of snap.children) {
|
|
195
|
+
const now = parent.childNodes;
|
|
196
|
+
if (now.length !== nodes.length || nodes.some((n, i) => n !== now[i])) /** @type {Element} */ (parent).replaceChildren(...nodes);
|
|
342
197
|
}
|
|
198
|
+
for (const [node, data] of snap.data) if (node.data !== data) node.data = data;
|
|
343
199
|
}
|
|
344
200
|
|
|
345
201
|
/**
|
|
@@ -450,18 +306,26 @@ export class TextBehavior {
|
|
|
450
306
|
|
|
451
307
|
if (!selection.isCollapsed) this.delete({index: selection.from, length: selection.to - selection.from}, selection);
|
|
452
308
|
this.insert(selection.from, textToInsert);
|
|
453
|
-
|
|
309
|
+
this.markTypedRun(selection.from, textToInsert.length);
|
|
310
|
+
this.block.commit();
|
|
311
|
+
tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/**
|
|
315
|
+
* The marks of a run the user just typed or composed at `[from, from + length)`: the cursor's pending stored marks, then the rule
|
|
316
|
+
* for mark edges.
|
|
317
|
+
* @param {number} from @param {number} length
|
|
318
|
+
*/
|
|
319
|
+
markTypedRun(from, length) {
|
|
454
320
|
const stored = this.nabu.storedMarks;
|
|
455
|
-
if (stored &&
|
|
456
|
-
const range = { from
|
|
321
|
+
if (stored && length) {
|
|
322
|
+
const range = { from, to: from + length, isCollapsed: false };
|
|
457
323
|
for (const [name, on] of Object.entries(stored)) {
|
|
458
324
|
if (on) this.applyMark(name, true, range);
|
|
459
325
|
else this.removeMark(name, range);
|
|
460
326
|
}
|
|
461
327
|
}
|
|
462
|
-
this.settleMarkEdges(
|
|
463
|
-
this.block.commit();
|
|
464
|
-
tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
|
|
328
|
+
this.settleMarkEdges(from, length, stored);
|
|
465
329
|
}
|
|
466
330
|
|
|
467
331
|
/**
|
|
@@ -7,9 +7,11 @@
|
|
|
7
7
|
* after the other, with no markup of their own. A long one (`CHUNK_ON` blocks and more) is rendered in chunks of ~64 blocks, each
|
|
8
8
|
* in a wrapper that the browser may skip while it is off screen (`content-visibility: auto`), which is what keeps a keystroke
|
|
9
9
|
* in a 10,000-block document within a frame (see chunks.js for the why and the how).
|
|
10
|
-
*
|
|
10
|
+
* `chunked` (bindable, read only for the parent) reports whether the list is rendered in chunks: a region body that is, leaves
|
|
11
|
+
* the skipping to its chunks (Region.svelte).
|
|
12
|
+
* @type {{ blocks: import('./block.svelte.js').Block[], chunked?: boolean }}
|
|
11
13
|
*/
|
|
12
|
-
let { blocks } = $props();
|
|
14
|
+
let { blocks, chunked: isChunked = $bindable(false) } = $props();
|
|
13
15
|
|
|
14
16
|
// Hysteresis: switches on at CHUNK_ON blocks, off under CHUNK_OFF. (Plain variable on purpose: it is only read back by this derived.)
|
|
15
17
|
let was = false;
|
|
@@ -18,6 +20,8 @@
|
|
|
18
20
|
return was && supportsChunking();
|
|
19
21
|
});
|
|
20
22
|
|
|
23
|
+
$effect.pre(() => { isChunked = chunked; });
|
|
24
|
+
|
|
21
25
|
// The chunks of the last render, to hand back the unchanged ones as they were.
|
|
22
26
|
let memo = new Map();
|
|
23
27
|
const chunks = $derived.by(() => {
|
|
@@ -42,6 +46,12 @@
|
|
|
42
46
|
overflow-clip-margin: var(--nb-clip-margin, 3rem);
|
|
43
47
|
}
|
|
44
48
|
|
|
49
|
+
/* Never nested (see the large documents note in region/Region.svelte: WebKit pays for it on every keystroke): a chunk inside a chunk
|
|
50
|
+
(a region body of 500 blocks among the blocks of a chunk) is left visible, the outer one already skips what it holds. */
|
|
51
|
+
.nabu-chunk :global(.nabu-chunk) {
|
|
52
|
+
content-visibility: visible;
|
|
53
|
+
}
|
|
54
|
+
|
|
45
55
|
@media print {
|
|
46
56
|
.nabu-chunk { content-visibility: visible; }
|
|
47
57
|
}
|
|
@@ -5,13 +5,17 @@ type BlockList = {
|
|
|
5
5
|
};
|
|
6
6
|
declare const BlockList: import("svelte").Component<{
|
|
7
7
|
blocks: import("./block.svelte.js").Block[];
|
|
8
|
-
|
|
8
|
+
chunked?: boolean;
|
|
9
|
+
}, {}, "chunked">;
|
|
9
10
|
/**
|
|
10
11
|
* A list of sibling blocks: the root of the editor, the body of a region. Short lists are rendered as they are, one block
|
|
11
12
|
* after the other, with no markup of their own. A long one (`CHUNK_ON` blocks and more) is rendered in chunks of ~64 blocks, each
|
|
12
13
|
* in a wrapper that the browser may skip while it is off screen (`content-visibility: auto`), which is what keeps a keystroke
|
|
13
14
|
* in a 10,000-block document within a frame (see chunks.js for the why and the how).
|
|
15
|
+
* `chunked` (bindable, read only for the parent) reports whether the list is rendered in chunks: a region body that is, leaves
|
|
16
|
+
* the skipping to its chunks (Region.svelte).
|
|
14
17
|
*/
|
|
15
18
|
type $$ComponentProps = {
|
|
16
19
|
blocks: import("./block.svelte.js").Block[];
|
|
20
|
+
chunked?: boolean;
|
|
17
21
|
};
|
package/dist/blocks/Nabu.svelte
CHANGED
|
@@ -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
|
-
*
|
|
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=
|
|
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
|
-
|
|
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
|
|
@@ -1472,11 +1480,10 @@ export class Nabu {
|
|
|
1472
1480
|
if (this.#readonly && !this.#composing) return;
|
|
1473
1481
|
this.#composing = false;
|
|
1474
1482
|
const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
|
|
1475
|
-
const composedBlock = this.#compositionStartBlock;
|
|
1476
1483
|
this.#composingBlock = null;
|
|
1477
1484
|
restoreEmptyBlocks(this.#swappedEmpties);
|
|
1478
1485
|
this.#swappedEmpties = [];
|
|
1479
|
-
/** @type {any} */ (composedIn)?.restoreAfterComposition?.(
|
|
1486
|
+
/** @type {any} */ (composedIn)?.restoreAfterComposition?.(); // before the model catches up: no duplicate of the composed text
|
|
1480
1487
|
try {
|
|
1481
1488
|
this.#syncComposition(e);
|
|
1482
1489
|
} finally {
|
|
@@ -1484,11 +1491,6 @@ export class Nabu {
|
|
|
1484
1491
|
}
|
|
1485
1492
|
this.selection.normalize(); // a dead caret must not survive the composition
|
|
1486
1493
|
this.#revealSoon();
|
|
1487
|
-
// A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
|
|
1488
|
-
if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
|
|
1489
|
-
this.selection.setCursor(composedBlock, 0);
|
|
1490
|
-
tick().then(() => { if (!this.#composing && composedBlock.element?.isConnected && !composedIn?.text) this.selection.setCursor(composedBlock, 0); });
|
|
1491
|
-
}
|
|
1492
1494
|
}
|
|
1493
1495
|
|
|
1494
1496
|
/** @param {CompositionEvent} e */
|
|
@@ -1511,10 +1513,6 @@ export class Nabu {
|
|
|
1511
1513
|
const behavior = block.behaviors?.get('text');
|
|
1512
1514
|
if (!behavior) return;
|
|
1513
1515
|
|
|
1514
|
-
// Canceled composition (Escape) fires compositionend with e.data === ''.
|
|
1515
|
-
const composedText = e.data || '';
|
|
1516
|
-
if (!composedText) return;
|
|
1517
|
-
|
|
1518
1516
|
// Where the composition began NOW: the Loro cursors followed every edit of this text made meanwhile (P-101).
|
|
1519
1517
|
if (anchor) {
|
|
1520
1518
|
const moved = resolveOffset(this.doc, anchor, behavior.container.length);
|
|
@@ -1522,7 +1520,20 @@ export class Nabu {
|
|
|
1522
1520
|
}
|
|
1523
1521
|
startOffset = Math.max(0, Math.min(startOffset, behavior.container.length));
|
|
1524
1522
|
|
|
1523
|
+
// Canceled composition (Escape) fires compositionend with e.data === ''. The render is back (restoreAfterComposition), and the
|
|
1524
|
+
// caret with it, unless the user went to another block.
|
|
1525
|
+
const composedText = e.data || '';
|
|
1526
|
+
if (!composedText) {
|
|
1527
|
+
const at = startOffset;
|
|
1528
|
+
this.selection.sync();
|
|
1529
|
+
if (this.selection.anchorBlock !== block) return;
|
|
1530
|
+
this.selection.setCursor(block, at);
|
|
1531
|
+
tick().then(() => { if (!this.#composing && block.element?.isConnected && this.selection.anchorBlock === block) this.selection.setCursor(block, at); });
|
|
1532
|
+
return;
|
|
1533
|
+
}
|
|
1534
|
+
|
|
1525
1535
|
behavior.insert(startOffset, composedText);
|
|
1536
|
+
behavior.markTypedRun?.(startOffset, composedText.length); // the same marks as if it had been typed
|
|
1526
1537
|
block.commit();
|
|
1527
1538
|
const caret = startOffset + composedText.length;
|
|
1528
1539
|
tick().then(() => {
|
|
@@ -2204,7 +2215,7 @@ export class Nabu {
|
|
|
2204
2215
|
this.selection.sync(); // public entry point: may be called outside an input event
|
|
2205
2216
|
// Every fragment (HTML / markdown / nabu JSON / API) goes through here: unsafe link & media URLs are dropped.
|
|
2206
2217
|
const files = Files.get(this);
|
|
2207
|
-
let adopted = files.adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets);
|
|
2218
|
+
let adopted = files.adoptAssets(sanitizePasteBlocks(dropUndeclaredMarks(fragment.blocks, this.#declaredMarks)), fragment.assets);
|
|
2208
2219
|
// Content from outside (a web page): remote images are fetched and stored, when the host asked for it (`files.importRemote`).
|
|
2209
2220
|
if (fragment.external) adopted = files.importRemote(adopted);
|
|
2210
2221
|
const blocks = this.#degradeUnknown(adopted);
|
|
@@ -2461,7 +2472,7 @@ export class Nabu {
|
|
|
2461
2472
|
* @public
|
|
2462
2473
|
*/
|
|
2463
2474
|
async importFragment(fragment) {
|
|
2464
|
-
const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets));
|
|
2475
|
+
const blocks = this.#degradeUnknown(Files.get(this).adoptAssets(sanitizePasteBlocks(dropUndeclaredMarks(fragment.blocks, this.#declaredMarks)), fragment.assets));
|
|
2465
2476
|
if (!blocks?.length) return;
|
|
2466
2477
|
|
|
2467
2478
|
[...this.tree.roots()].forEach(root => this.tree.delete(root.id));
|
|
@@ -11,6 +11,10 @@
|
|
|
11
11
|
|
|
12
12
|
// A large document (Nabu.svelte sets `data-nabu-large` on the root): the body is skipped by the browser while off screen, see the style below.
|
|
13
13
|
const large = $derived(block.nabu.blocks.size >= LARGE_DOC);
|
|
14
|
+
// A LEAF body (no region among its direct children) is the only one the browser may skip, see the style below. Reactive: a region
|
|
15
|
+
// dropped into the body, or the last one taken out, flips it. A body rendered in chunks (reported by its BlockList) leaves it to them.
|
|
16
|
+
const leaf = $derived(!block.children.some((child) => child.type === 'region'));
|
|
17
|
+
let chunked = $state(false);
|
|
14
18
|
const region = $derived(Regions.get(block.nabu).of(block));
|
|
15
19
|
const level = $derived(Math.min(6, Math.max(1, region?.level ?? 1)));
|
|
16
20
|
// The label template applied with an EMPTY title ("1.", "1.1", "Chapter 2"): the editable title follows it.
|
|
@@ -83,22 +87,27 @@
|
|
|
83
87
|
data-block-type="region"
|
|
84
88
|
data-nabu-isolated
|
|
85
89
|
data-placeholder={block.placeholder}
|
|
86
|
-
><RichText delta={block.delta} /></div><span class="nabu-region-rule" data-nabu-ui contenteditable="false" aria-hidden="true">{#if pending}<span class="nabu-region-drain"></span>{/if}</span></div><div class="nabu-region-body" style:--nb-region-blocks={large ? block.weight : undefined}><BlockList blocks={block.children} /></div>{#if endText}<!-- Never a caret stop (not editable, not selectable) and not read as text: a separator named by the same sentence. --><div class="nabu-region-end" data-region-end data-nabu-ui contenteditable="false" role="separator" aria-label={endText}><span class="nabu-region-end-rule" aria-hidden="true"></span><span class="nabu-region-end-text" aria-hidden="true">{endText}</span></div>{/if}</div>
|
|
90
|
+
><RichText delta={block.delta} /></div><span class="nabu-region-rule" data-nabu-ui contenteditable="false" aria-hidden="true">{#if pending}<span class="nabu-region-drain"></span>{/if}</span></div><div class="nabu-region-body" data-region-leaf={leaf && !chunked ? '' : undefined} style:--nb-region-blocks={large ? block.weight : undefined}><BlockList blocks={block.children} bind:chunked /></div>{#if endText}<!-- Never a caret stop (not editable, not selectable) and not read as text: a separator named by the same sentence. --><div class="nabu-region-end" data-region-end data-nabu-ui contenteditable="false" role="separator" aria-label={endText}><span class="nabu-region-end-rule" aria-hidden="true"></span><span class="nabu-region-end-text" aria-hidden="true">{endText}</span></div>{/if}</div>
|
|
87
91
|
|
|
88
92
|
<style>
|
|
89
93
|
/* ── Large documents ── In a large document (`data-nabu-large`, 800 blocks) the body of a region is skipped by the browser while it is off screen
|
|
90
94
|
(`content-visibility: auto`): its layout, paint and selection bookkeeping no longer grow with the size of the document, which is
|
|
91
95
|
what keeps a keystroke within a frame at 10,000 blocks. Until it has been shown once its height is an estimate (its number of
|
|
92
|
-
blocks times --nb-block-estimate, 72px); `auto` then remembers the real one. A small document is left exactly as it was.
|
|
93
|
-
:global(.nabu-editor[data-nabu-large]) .nabu-region-body {
|
|
94
|
-
content-visibility: auto;
|
|
95
|
-
contain-intrinsic-block-size: auto calc(var(--nb-region-blocks, 16) * var(--nb-block-estimate, 72px));
|
|
96
|
-
/* ...and what it contains may hang out of its box (the margin rail of a sub-region): paint containment would clip it. */
|
|
97
|
-
overflow-clip-margin: var(--nb-clip-margin, 3rem);
|
|
98
|
-
}
|
|
96
|
+
blocks times --nb-block-estimate, 72px); `auto` then remembers the real one. A small document is left exactly as it was.
|
|
99
97
|
|
|
100
|
-
|
|
101
|
-
|
|
98
|
+
Never nested: an `auto` box must neither contain nor sit inside another one. WebKit pays for the nesting on every keystroke
|
|
99
|
+
(a novel of nested parts > chapters > scenes, caret mid-document: ~380 ms per key at 90,000 words with every body `auto`; 34-40 ms
|
|
100
|
+
with every body visible; 23-26 ms at 90k and 28-30 ms at 150k with `auto` on the LEAF bodies only, flat with the size; `auto` on the
|
|
101
|
+
non-leaf bodies only is as slow as all of them; Chromium is at 9-12 ms either way). So only a leaf body (`data-region-leaf`: no region
|
|
102
|
+
among its children, not itself rendered in chunks, whose `.nabu-chunk` boxes are the `auto` ones then) is skipped, and not when it already
|
|
103
|
+
sits inside a chunk, which skips what it holds. (BlockList.svelte keeps chunks out of chunks the same way.) */
|
|
104
|
+
@media not print {
|
|
105
|
+
:global(.nabu-editor[data-nabu-large] .nabu-region-body[data-region-leaf]:not(.nabu-chunk .nabu-region-body)) {
|
|
106
|
+
content-visibility: auto;
|
|
107
|
+
contain-intrinsic-block-size: auto calc(var(--nb-region-blocks, 16) * var(--nb-block-estimate, 72px));
|
|
108
|
+
/* ...and what it contains may hang out of its box (the margin rail of a sub-region): paint containment would clip it. */
|
|
109
|
+
overflow-clip-margin: var(--nb-clip-margin, 3rem);
|
|
110
|
+
}
|
|
102
111
|
}
|
|
103
112
|
|
|
104
113
|
/* ── Margin rail: the region that holds the caret (data-region-caret), from its seam to the end of its body ── */
|
package/dist/format.d.ts
ADDED
|
@@ -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
|
+
}
|
package/dist/paste/html.paste.js
CHANGED
|
@@ -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
|
-
|
|
207
|
+
// Chromium writes every space at the edge of an inline element as `<span> </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";
|
package/dist/utils/extensions.js
CHANGED
|
@@ -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.
|
|
3
|
+
"version": "0.1.6",
|
|
4
4
|
"scripts": {
|
|
5
5
|
"dev": "vite dev",
|
|
6
6
|
"predev": "npm run api:model:ensure",
|
|
@@ -18,6 +18,7 @@
|
|
|
18
18
|
"build:e2e": "npm run api:model && VITE_NABU_E2E=1 vite build",
|
|
19
19
|
"test:e2e": "playwright test",
|
|
20
20
|
"test:e2e:dev": "NABU_E2E_DEV=1 playwright test",
|
|
21
|
+
"test:consumer": "node scripts/consumer-smoke.js",
|
|
21
22
|
"test": "bun run test:unit && bun run test:e2e"
|
|
22
23
|
},
|
|
23
24
|
"files": [
|
|
@@ -45,6 +46,10 @@
|
|
|
45
46
|
"types": "./dist/extend.d.ts",
|
|
46
47
|
"svelte": "./dist/extend.js"
|
|
47
48
|
},
|
|
49
|
+
"./format": {
|
|
50
|
+
"types": "./dist/format.d.ts",
|
|
51
|
+
"default": "./dist/format.js"
|
|
52
|
+
},
|
|
48
53
|
"./vite": {
|
|
49
54
|
"types": "./dist/vite.d.ts",
|
|
50
55
|
"default": "./dist/vite.js"
|