@aionbuilders/nabu 0.1.3 → 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 +22 -0
- 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 +1 -20
- package/dist/behaviors/text/text.behavior.svelte.js +4 -131
- 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 +72 -6
- 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/dist/utils/reveal-caret.d.ts +13 -0
- package/dist/utils/reveal-caret.js +145 -0
- package/package.json +5 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,28 @@
|
|
|
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> </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.
|
|
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
|
+
|
|
22
|
+
## 0.1.4 (2026-11-04)
|
|
23
|
+
|
|
24
|
+
The caret stays on screen. No API change.
|
|
25
|
+
|
|
26
|
+
### Fixed
|
|
27
|
+
- **The caret could leave the visible area while typing.** Nabu cancels the native edits and renders from the model, so the browser no longer scrolled to the caret: after 20 Enter in a 220 px scroller it was 565 px below the visible area, on the plainest setup. Every scrollable ancestor and the window now follow it after an edit the user made, by the least amount, within the visual viewport when there is one. A host keeps it clear of its own sticky UI with `scroll-padding`. Nothing scrolls for a key that changed nothing (Ctrl+C, a modifier, Escape) or for a programmatic or remote change. Covered by `tests/e2e/caret-reveal.spec.ts`, and checked on Firefox, WebKit, Chromium and emulated phones through a packed build. A real virtual keyboard is not verified yet.
|
|
28
|
+
|
|
7
29
|
## 0.1.3 (2026-11-04)
|
|
8
30
|
|
|
9
31
|
Fixes found by testing the published package in a real SvelteKit app: the first thing a consumer's build, a Firefox user and a page that mounts editors on demand would hit. The API only gains two methods.
|
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 {
|
|
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
|
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';
|
|
@@ -18,6 +19,7 @@ import { moveBlocks } from './move.js';
|
|
|
18
19
|
import { closestWithin } from '../utils/dom-scope.js';
|
|
19
20
|
import { captureSelection, explicitSelection, legacySelection, restoreSelection, keepSelection, makeEndpoint, resolveOffset, revealFocus } from './undo-selection.js';
|
|
20
21
|
import { LARGE_DOC } from './chunks.js';
|
|
22
|
+
import { revealCaret } from '../utils/reveal-caret.js';
|
|
21
23
|
import { markAtCaret } from '../behaviors/text/mark-edges.js';
|
|
22
24
|
import { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
|
|
23
25
|
import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
|
|
@@ -162,6 +164,8 @@ export class Nabu {
|
|
|
162
164
|
#pulse = new Pulse();
|
|
163
165
|
/** @type {import('../utils/extensions.js').PasteInterpreter[]} */
|
|
164
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();
|
|
165
169
|
/** @type {import('../utils/extensions.js').PasteFileHandler[]} sorted by priority, highest first */
|
|
166
170
|
#pasteFileHandlers = [];
|
|
167
171
|
|
|
@@ -231,6 +235,16 @@ export class Nabu {
|
|
|
231
235
|
/** Selection where each recent action ended, by the counter end of its undo step. @type {Map<number, import('./undo-selection.js').UndoSelection>} */
|
|
232
236
|
#actionEnds = new Map();
|
|
233
237
|
|
|
238
|
+
// ── Keeping the caret visible ────────────────────────────────────────────
|
|
239
|
+
// Native edits are cancelled and the DOM is rendered from the model, so the browser no longer scrolls to the caret after an
|
|
240
|
+
// edit: the editor does (utils/reveal-caret.js), in the next frame, once per burst, and only for an edit the user made.
|
|
241
|
+
/** The pending animation frame of {@link Nabu#revealSoon}, 0 when none. */
|
|
242
|
+
#revealFrame = 0;
|
|
243
|
+
/** An edit asked for the reveal outright (an input, a paste…), not only "if something changed". */
|
|
244
|
+
#revealForced = false;
|
|
245
|
+
/** The oldest key that asks "if something changed since": the document and selection counters at its keydown. @type {{ ops: number, placed: number } | null} */
|
|
246
|
+
#revealSince = null;
|
|
247
|
+
|
|
234
248
|
/** @param {NabuInit} init */
|
|
235
249
|
constructor(init = {}) {
|
|
236
250
|
this.doc = new LoroDoc();
|
|
@@ -351,6 +365,7 @@ export class Nabu {
|
|
|
351
365
|
|
|
352
366
|
if (ext.loroTextStyles && Object.keys(ext.loroTextStyles).length) {
|
|
353
367
|
this.doc.configTextStyle(ext.loroTextStyles);
|
|
368
|
+
for (const mark of Object.keys(ext.loroTextStyles)) this.#declaredMarks.add(mark);
|
|
354
369
|
}
|
|
355
370
|
|
|
356
371
|
}
|
|
@@ -653,7 +668,10 @@ export class Nabu {
|
|
|
653
668
|
// The bytes of the `nabu-asset:` media travel with the document (same `assets` map as the clipboard format).
|
|
654
669
|
const assets = Files.get(nabu).embedAssets(blocks);
|
|
655
670
|
return { version: JSON_FORMAT_VERSION, blocks, ...(assets ? { assets } : {}) };
|
|
656
|
-
}]
|
|
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))]
|
|
657
675
|
]));
|
|
658
676
|
|
|
659
677
|
/**
|
|
@@ -678,8 +696,9 @@ export class Nabu {
|
|
|
678
696
|
}
|
|
679
697
|
|
|
680
698
|
/**
|
|
681
|
-
* Serialize the document with the root serializer registered for `format` (`'markdown'`, `'json'`, or one an extension
|
|
682
|
-
* 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).
|
|
683
702
|
* @param {string} format
|
|
684
703
|
* @returns {any}
|
|
685
704
|
* @public
|
|
@@ -1330,9 +1349,39 @@ export class Nabu {
|
|
|
1330
1349
|
}
|
|
1331
1350
|
}
|
|
1332
1351
|
|
|
1352
|
+
/**
|
|
1353
|
+
* Bring the caret into view in the next frame (utils/reveal-caret.js), after an edit the user made: native editing scrolls to
|
|
1354
|
+
* the caret, and Nabu's does not happen natively. A frame, not the keystroke itself: the layout has to happen then anyway, so
|
|
1355
|
+
* nothing is forced and the key-to-DOM latency stays as it was. Requests of one burst share the frame.
|
|
1356
|
+
* With `since` (a key the editor handled), the reveal only happens if the document or the selection changed meanwhile: a key
|
|
1357
|
+
* that did nothing (Ctrl+C, a modifier…) must not throw the user back to the caret they scrolled away from.
|
|
1358
|
+
* Programmatic edits (`insert`, `exec`, `importRemote`, a collaborator) never come through here.
|
|
1359
|
+
* @param {{ ops: number, placed: number }} [since]
|
|
1360
|
+
*/
|
|
1361
|
+
#revealSoon(since) {
|
|
1362
|
+
if (typeof requestAnimationFrame === 'undefined') return;
|
|
1363
|
+
if (since) this.#revealSince ??= since;
|
|
1364
|
+
else this.#revealForced = true;
|
|
1365
|
+
if (this.#revealFrame) return;
|
|
1366
|
+
this.#revealFrame = requestAnimationFrame(() => {
|
|
1367
|
+
this.#revealFrame = 0;
|
|
1368
|
+
const forced = this.#revealForced;
|
|
1369
|
+
const asked = this.#revealSince;
|
|
1370
|
+
this.#revealForced = false;
|
|
1371
|
+
this.#revealSince = null;
|
|
1372
|
+
if (!forced && asked && this.doc.opCount() === asked.ops && this.selection.placements === asked.placed) return;
|
|
1373
|
+
const root = this.selection.root; // null once the editor is unmounted
|
|
1374
|
+
if (!root || !root.isConnected || this.#readonly || this.#composing) return;
|
|
1375
|
+
const active = /** @type {Document | ShadowRoot} */ (root.getRootNode()).activeElement ?? document.activeElement;
|
|
1376
|
+
if (!active || !root.contains(active) || this.selection.scope() !== 'mine') return;
|
|
1377
|
+
revealCaret(root);
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
|
|
1333
1381
|
/** @param {InputEvent} e */
|
|
1334
1382
|
handleBeforeinput(e) {
|
|
1335
1383
|
if (this.#readonly) { e.preventDefault(); return; } // nothing is typed, deleted, pasted or dropped in a read-only editor
|
|
1384
|
+
this.#revealSoon();
|
|
1336
1385
|
this.selection.sync(); // selectionchange is async: don't act on a stale caret
|
|
1337
1386
|
// Ne pas interférer avec la composition IME en cours : le navigateur
|
|
1338
1387
|
// doit pouvoir muter librement le text node (insertCompositionText
|
|
@@ -1442,6 +1491,7 @@ export class Nabu {
|
|
|
1442
1491
|
this.#endCompositionGroup();
|
|
1443
1492
|
}
|
|
1444
1493
|
this.selection.normalize(); // a dead caret must not survive the composition
|
|
1494
|
+
this.#revealSoon();
|
|
1445
1495
|
// A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
|
|
1446
1496
|
if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
|
|
1447
1497
|
this.selection.setCursor(composedBlock, 0);
|
|
@@ -1492,6 +1542,16 @@ export class Nabu {
|
|
|
1492
1542
|
handleKeydown(e) {
|
|
1493
1543
|
// Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
|
|
1494
1544
|
if (this.#readonly) return;
|
|
1545
|
+
const since = { ops: this.doc.opCount(), placed: this.selection.placements };
|
|
1546
|
+
this.#keydown(e);
|
|
1547
|
+
// A key the editor took (Enter, Backspace, undo, a structural shortcut…) scrolls to the caret if it changed anything. The native
|
|
1548
|
+
// caret moves (arrows…) are not prevented: the browser scrolls for them. Select all leaves the caret where the user looks.
|
|
1549
|
+
const selectAll = (e.ctrlKey || e.metaKey) && typeof e.key === 'string' && e.key.toLowerCase() === 'a';
|
|
1550
|
+
if (e.defaultPrevented && !selectAll) this.#revealSoon(since);
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
/** @param {KeyboardEvent} e */
|
|
1554
|
+
#keydown(e) {
|
|
1495
1555
|
// Tab on a control of the editor's own UI (the language select of a code block…) is the browser's: it moves the focus on.
|
|
1496
1556
|
if (e.key === 'Tab' && e.target instanceof Element && e.target.closest('[data-nabu-ui]')) return;
|
|
1497
1557
|
this.selection.sync(); // no-op when the document capture listener already synced
|
|
@@ -1741,6 +1801,8 @@ export class Nabu {
|
|
|
1741
1801
|
e.preventDefault();
|
|
1742
1802
|
if (this.#readonly) { this.handleCopy(e); return; } // cutting a read-only text copies it and removes nothing
|
|
1743
1803
|
|
|
1804
|
+
this.#revealSoon();
|
|
1805
|
+
|
|
1744
1806
|
// 1. Copy selection to clipboard
|
|
1745
1807
|
this.handleCopy(e);
|
|
1746
1808
|
|
|
@@ -1758,6 +1820,7 @@ export class Nabu {
|
|
|
1758
1820
|
handlePaste(e) {
|
|
1759
1821
|
e.preventDefault();
|
|
1760
1822
|
if (this.#readonly) return;
|
|
1823
|
+
this.#revealSoon();
|
|
1761
1824
|
this.selection.sync();
|
|
1762
1825
|
const clipboard = e.clipboardData;
|
|
1763
1826
|
if (!clipboard) return;
|
|
@@ -2026,6 +2089,7 @@ export class Nabu {
|
|
|
2026
2089
|
if (!position) return;
|
|
2027
2090
|
// The editor takes the focus (undo, typing…) even when the drop leaves no text caret to put in it (a dropped image).
|
|
2028
2091
|
if (document.activeElement !== root) root.focus({ preventScroll: true });
|
|
2092
|
+
this.#revealSoon();
|
|
2029
2093
|
const own = !!source && dt.getData(DRAG_MARKER) === source.token;
|
|
2030
2094
|
this.dropAt(dt, position, { source: own && !wantsCopy(e) ? source : null });
|
|
2031
2095
|
}
|
|
@@ -2148,7 +2212,7 @@ export class Nabu {
|
|
|
2148
2212
|
this.selection.sync(); // public entry point: may be called outside an input event
|
|
2149
2213
|
// Every fragment (HTML / markdown / nabu JSON / API) goes through here: unsafe link & media URLs are dropped.
|
|
2150
2214
|
const files = Files.get(this);
|
|
2151
|
-
let adopted = files.adoptAssets(sanitizePasteBlocks(fragment.blocks), fragment.assets);
|
|
2215
|
+
let adopted = files.adoptAssets(sanitizePasteBlocks(dropUndeclaredMarks(fragment.blocks, this.#declaredMarks)), fragment.assets);
|
|
2152
2216
|
// Content from outside (a web page): remote images are fetched and stored, when the host asked for it (`files.importRemote`).
|
|
2153
2217
|
if (fragment.external) adopted = files.importRemote(adopted);
|
|
2154
2218
|
const blocks = this.#degradeUnknown(adopted);
|
|
@@ -2405,7 +2469,7 @@ export class Nabu {
|
|
|
2405
2469
|
* @public
|
|
2406
2470
|
*/
|
|
2407
2471
|
async importFragment(fragment) {
|
|
2408
|
-
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));
|
|
2409
2473
|
if (!blocks?.length) return;
|
|
2410
2474
|
|
|
2411
2475
|
[...this.tree.roots()].forEach(root => this.tree.delete(root.id));
|
|
@@ -2633,6 +2697,8 @@ export class Nabu {
|
|
|
2633
2697
|
* @public
|
|
2634
2698
|
*/
|
|
2635
2699
|
destroy() {
|
|
2700
|
+
if (this.#revealFrame) cancelAnimationFrame(this.#revealFrame);
|
|
2701
|
+
this.#revealFrame = 0;
|
|
2636
2702
|
for (const stop of this.#tracked) stop();
|
|
2637
2703
|
this.#tracked.clear();
|
|
2638
2704
|
for (const system of this.systems.values()) system.stop?.();
|
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
|
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
/** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
|
|
2
|
+
/**
|
|
3
|
+
* Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
|
|
4
|
+
* a usable caret (no selection, the focus is outside `root`, no layout).
|
|
5
|
+
* @param {Element} root the editor's root: the focus of the selection has to be inside it
|
|
6
|
+
*/
|
|
7
|
+
export function revealCaret(root: Element): void;
|
|
8
|
+
export type Box = {
|
|
9
|
+
top: number;
|
|
10
|
+
bottom: number;
|
|
11
|
+
left: number;
|
|
12
|
+
right: number;
|
|
13
|
+
};
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Keep the caret visible after an edit the user made. Nabu cancels the native edits and re-renders from the model, so the browser
|
|
3
|
+
* no longer scrolls to the caret by itself: `revealCaret` does it, the way a plain contenteditable would. "Nearest": nothing moves
|
|
4
|
+
* while the caret is already inside the visible area.
|
|
5
|
+
*
|
|
6
|
+
* Every scrollable ancestor is moved by the least amount that brings the caret into its padding box (shadow roots are crossed),
|
|
7
|
+
* then the window, bounded by the visual viewport when there is one (a virtual keyboard shrinks it). A host keeps the caret clear
|
|
8
|
+
* of its own sticky UI with `scroll-padding` (on the scroller, or on the root element for the window). No Svelte, no state.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Breathing room left between the caret and the edge it was scrolled to, in px (cut down when the box is too small for it). */
|
|
12
|
+
const MARGIN = 8;
|
|
13
|
+
/** The overflow values of an element that scrolls, by script or by the user (`overlay` is an alias of `auto`). */
|
|
14
|
+
const SCROLLS = new Set(['auto', 'scroll', 'hidden']);
|
|
15
|
+
|
|
16
|
+
/** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
|
|
20
|
+
* a usable caret (no selection, the focus is outside `root`, no layout).
|
|
21
|
+
* @param {Element} root the editor's root: the focus of the selection has to be inside it
|
|
22
|
+
*/
|
|
23
|
+
export function revealCaret(root) {
|
|
24
|
+
if (typeof window === 'undefined') return;
|
|
25
|
+
const live = window.getSelection();
|
|
26
|
+
const node = live?.focusNode;
|
|
27
|
+
if (!live || !node || live.rangeCount === 0 || !root.contains(node)) return;
|
|
28
|
+
const offset = live.focusOffset;
|
|
29
|
+
const holder = /** @type {Element | null} */ (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement);
|
|
30
|
+
if (!holder) return;
|
|
31
|
+
|
|
32
|
+
let caret = caretBox(node, offset, holder);
|
|
33
|
+
if (!caret) return;
|
|
34
|
+
|
|
35
|
+
for (let el = parentOf(holder); el && el !== document.documentElement; el = parentOf(el)) {
|
|
36
|
+
// The body of a page whose `overflow` went up to the viewport does not scroll: the window does.
|
|
37
|
+
if (el === document.body && getComputedStyle(document.documentElement).overflow === 'visible') continue;
|
|
38
|
+
const style = getComputedStyle(el);
|
|
39
|
+
const y = SCROLLS.has(style.overflowY) && el.scrollHeight > el.clientHeight;
|
|
40
|
+
const x = SCROLLS.has(style.overflowX) && el.scrollWidth > el.clientWidth;
|
|
41
|
+
if (y || x) {
|
|
42
|
+
const box = el.getBoundingClientRect();
|
|
43
|
+
// A transform scales the rects but not `scrollTop`: the amount to scroll is in layout px.
|
|
44
|
+
const { offsetHeight, offsetWidth } = /** @type {HTMLElement} */ (el); // undefined on an SVG element: no scale, then
|
|
45
|
+
const sy = box.height / offsetHeight || 1;
|
|
46
|
+
const sx = box.width / offsetWidth || 1;
|
|
47
|
+
const dy = y ? nudge(caret.top, caret.bottom, box.top + el.clientTop * sy, el.clientHeight * sy, padding(style.scrollPaddingTop, el.clientHeight) * sy, padding(style.scrollPaddingBottom, el.clientHeight) * sy) : 0;
|
|
48
|
+
const dx = x ? nudge(caret.left, caret.right, box.left + el.clientLeft * sx, el.clientWidth * sx, padding(style.scrollPaddingLeft, el.clientWidth) * sx, padding(style.scrollPaddingRight, el.clientWidth) * sx) : 0;
|
|
49
|
+
if (dy || dx) {
|
|
50
|
+
el.scrollBy({ top: dy / sy, left: dx / sx, behavior: 'instant' }); // instant: a `scroll-behavior: smooth` host must not lag behind the typing
|
|
51
|
+
caret = caretBox(node, offset, holder) ?? caret;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
if (style.position === 'fixed') return; // the window cannot move it
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const vv = window.visualViewport;
|
|
58
|
+
const top = vv ? vv.offsetTop : 0;
|
|
59
|
+
const left = vv ? vv.offsetLeft : 0;
|
|
60
|
+
const height = vv ? vv.height : window.innerHeight;
|
|
61
|
+
const width = vv ? vv.width : window.innerWidth;
|
|
62
|
+
const style = getComputedStyle(document.scrollingElement ?? document.documentElement);
|
|
63
|
+
const dy = nudge(caret.top, caret.bottom, top, height, padding(style.scrollPaddingTop, height), padding(style.scrollPaddingBottom, height));
|
|
64
|
+
const dx = nudge(caret.left, caret.right, left, width, padding(style.scrollPaddingLeft, width), padding(style.scrollPaddingRight, width));
|
|
65
|
+
if (dy || dx) window.scrollBy({ top: dy, left: dx, behavior: 'instant' });
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* The scroll amount, along one axis, that brings the caret `[start, end]` inside the box `[origin, origin + size]` reduced by its
|
|
70
|
+
* scroll padding and a margin: the smallest one, 0 when it is already inside. A box too small for the caret is aligned on its
|
|
71
|
+
* leading edge (always the same one, so that the next call does not scroll back).
|
|
72
|
+
* @param {number} start @param {number} end @param {number} origin @param {number} size @param {number} before @param {number} after
|
|
73
|
+
* @returns {number}
|
|
74
|
+
*/
|
|
75
|
+
function nudge(start, end, origin, size, before, after) {
|
|
76
|
+
let lo = origin + before;
|
|
77
|
+
let hi = origin + size - after;
|
|
78
|
+
const room = hi - lo - (end - start);
|
|
79
|
+
const margin = Math.max(0, Math.min(MARGIN, room / 2));
|
|
80
|
+
lo += margin;
|
|
81
|
+
hi -= margin;
|
|
82
|
+
const delta = room < 0 || start < lo ? start - lo : end > hi ? end - hi : 0;
|
|
83
|
+
return Math.abs(delta) < 0.5 ? 0 : delta;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A `scroll-padding-*` computed value ("auto", "12px", "10%") in px. @param {string} value @param {number} size what a percentage refers to */
|
|
87
|
+
function padding(value, size) {
|
|
88
|
+
const n = parseFloat(value);
|
|
89
|
+
if (!n) return 0;
|
|
90
|
+
return value.endsWith('%') ? (n * size) / 100 : n;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
/** The parent of `el` in the flat tree: a slot, else the parent element, else the host of the shadow root. @param {Element} el @returns {Element | null} */
|
|
94
|
+
function parentOf(el) {
|
|
95
|
+
if (el.assignedSlot) return el.assignedSlot;
|
|
96
|
+
if (el.parentElement) return el.parentElement;
|
|
97
|
+
const top = el.getRootNode();
|
|
98
|
+
return top instanceof ShadowRoot ? top.host : null;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* The caret as a rect, in viewport coordinates. A collapsed range may report no rect, or a zero-height one, in an empty block or at
|
|
103
|
+
* a line edge: the character after it is measured then (its left edge), then the one before (its right edge), then the top of the
|
|
104
|
+
* block with one line (never the whole rect of a tall block). Null when nothing is measurable.
|
|
105
|
+
* @param {Node} node @param {number} offset @param {Element} holder the element holding `node`
|
|
106
|
+
* @returns {Box | null}
|
|
107
|
+
*/
|
|
108
|
+
function caretBox(node, offset, holder) {
|
|
109
|
+
const measure = (/** @type {Node} */ a, /** @type {number} */ from, /** @type {number} */ to) => {
|
|
110
|
+
const range = document.createRange();
|
|
111
|
+
try {
|
|
112
|
+
range.setStart(a, from);
|
|
113
|
+
range.setEnd(a, to);
|
|
114
|
+
} catch { return null; }
|
|
115
|
+
for (const r of range.getClientRects()) if (r.height > 0) return r;
|
|
116
|
+
return null;
|
|
117
|
+
};
|
|
118
|
+
const text = (/** @type {Node | undefined} */ n) => (n && n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n) : null);
|
|
119
|
+
// The text positions on each side of the caret (it may sit between elements).
|
|
120
|
+
const isText = node.nodeType === Node.TEXT_NODE;
|
|
121
|
+
const next = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset]);
|
|
122
|
+
const nextAt = isText ? offset : 0;
|
|
123
|
+
const prev = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset - 1]);
|
|
124
|
+
const prevAt = isText ? offset : prev ? prev.length : 0;
|
|
125
|
+
|
|
126
|
+
const here = measure(node, offset, offset);
|
|
127
|
+
if (here) return { top: here.top, bottom: here.bottom, left: here.left, right: here.left };
|
|
128
|
+
if (next && nextAt < next.length) {
|
|
129
|
+
const r = measure(next, nextAt, nextAt + 1);
|
|
130
|
+
if (r) return { top: r.top, bottom: r.bottom, left: r.left, right: r.left };
|
|
131
|
+
}
|
|
132
|
+
if (prev && prevAt > 0) {
|
|
133
|
+
const r = measure(prev, prevAt - 1, prevAt);
|
|
134
|
+
if (r) return { top: r.top, bottom: r.bottom, left: r.right, right: r.right };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const block = holder.closest('[data-block-id]') ?? holder;
|
|
138
|
+
const r = block.getBoundingClientRect();
|
|
139
|
+
if (!r.width && !r.height) return null;
|
|
140
|
+
const style = getComputedStyle(block);
|
|
141
|
+
const scale = r.height / /** @type {HTMLElement} */ (block).offsetHeight || 1;
|
|
142
|
+
const line = (parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2 || 0) * scale;
|
|
143
|
+
if (!line) return null;
|
|
144
|
+
return { top: r.top, bottom: r.top + line, left: r.left, right: r.left };
|
|
145
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@aionbuilders/nabu",
|
|
3
|
-
"version": "0.1.
|
|
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"
|