@aionbuilders/nabu 0.1.1 → 0.1.2
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 +13 -0
- package/README.md +6 -0
- package/dist/behaviors/text/mark-edges.d.ts +39 -0
- package/dist/behaviors/text/mark-edges.js +98 -0
- package/dist/behaviors/text/text.behavior.svelte.d.ts +9 -1
- package/dist/behaviors/text/text.behavior.svelte.js +28 -5
- package/dist/blocks/code/Code.svelte +29 -1
- package/dist/blocks/code/code.extension.js +20 -7
- package/dist/blocks/code/code.svelte.d.ts +4 -1
- package/dist/blocks/code/code.svelte.js +119 -22
- package/dist/blocks/code/indent.d.ts +61 -0
- package/dist/blocks/code/indent.js +91 -0
- package/dist/blocks/list/hooks/onBeforeInput.hook.js +2 -1
- package/dist/blocks/list/list-item.svelte.d.ts +1 -1
- package/dist/blocks/list/to-list.js +2 -1
- package/dist/blocks/nabu.svelte.d.ts +7 -0
- package/dist/blocks/nabu.svelte.js +19 -12
- package/dist/blocks/region/actions.js +2 -1
- package/dist/blocks/region/region.svelte.d.ts +1 -1
- package/dist/blocks/region/region.svelte.js +3 -2
- package/dist/blocks/text-block.svelte.d.ts +1 -1
- package/dist/blocks/toggle/toggle.svelte.d.ts +1 -1
- package/dist/ui/slash-menu.svelte.js +2 -1
- package/dist/utils/delta.d.ts +27 -0
- package/dist/utils/delta.js +121 -0
- package/dist/utils/tab.js +1 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -4,6 +4,19 @@
|
|
|
4
4
|
|
|
5
5
|
Nothing yet.
|
|
6
6
|
|
|
7
|
+
## 0.1.2 (2026-10-29)
|
|
8
|
+
|
|
9
|
+
Fixes from the first days of the beta: rich text that stayed split after removing a mark, mark edges, Ctrl+B at the edge of a word, and code block editing. No API change.
|
|
10
|
+
|
|
11
|
+
### Fixed
|
|
12
|
+
- **A mark removed over exactly the range it was applied to left the text in two pieces.** Bolding `[18, 21)` then un-bolding `[18, 21)` gave `The ford is upstre` + `am.` in the JSON export, the HTML and the DOM (two text nodes: a spellcheck squiggle, a double-click or a word delete could stop at the seam). The cause is in Loro: `LoroText.toDelta()` keeps the split in that case (a wider unmark merges it), and it is stored in snapshots. Every read of a text delta now goes through one canonical form (`readDelta`: adjacent runs with the same marks are merged, an off mark is an absent mark), so documents saved with the split are read right too. Covered by `tests/unit/delta.test.js`, `tests/unit/marks-canonical.test.js` (seeded fuzz) and `tests/e2e/marks-canonical.spec.ts`.
|
|
13
|
+
- **Code block editing.** The slash menu no longer opens inside a code block (`/` is text there, and Enter after it turned the block into a list). Tab and Shift+Tab indent and outdent every line of a multi-line selection and keep the selection; Shift+Tab also removes a tab character. Enter keeps the indentation of the line. A long line scrolls to keep the caret visible. Ctrl/Cmd+A selects the code first, the whole document on the second press. ArrowUp on the first line of a code block that starts the document creates a paragraph before it, as ArrowDown already did after it. Pasted `\r\n` and `\r` line endings become `\n`. Covered by `tests/e2e/code-editing.spec.ts` and `tests/unit/code-indent.test.js`.
|
|
14
|
+
- **Code block languages.** Names such as `c++`, `c#` or `objective-c` work in the ```` ``` ```` + Enter shortcut and on paste; the language select shows a language that is not in its list (`ts`, `js`) instead of a blank; the HTML export writes `<pre><code class="language-js">` (it dropped the language); the HTML import also reads `lang-`, `data-language` and GitHub's `highlight-source-*` wrapper, and turns `<br>` inside `<pre>` into line breaks. The inline-code style no longer tints the code block.
|
|
15
|
+
- **A code block was a keyboard trap.** Tab always indented, so a keyboard user could neither leave the block nor reach its language select (WCAG 2.1.2). Escape then Tab now moves the focus out of the editor, and Escape then Shift+Tab focuses the language select, the same convention as CodeMirror and GitHub. Any other key or a click closes the way out, a plain Tab still indents, and Tab elsewhere is unchanged. The select no longer sits in the Tab order of the page, where it would have caught the Tab of every block above it.
|
|
16
|
+
- **```` ``` ```` + Space makes a code block.** Like `#`, `>` and `-`, the fence shortcut now fires on Space as well as Enter, with a language too (```` ```js ````), when the paragraph is exactly the fence and the caret is at its end. One undo gives back what was typed.
|
|
17
|
+
- **Where marks end no longer depends on the history of the text.** Two texts that look the same could behave differently when typed into at the edge of a mark: a sentence in bold with a word then un-bolded made the character typed at the start of that word bold, the same text made of two bold ranges did not (a Loro quirk, [loro-dev/loro#1240](https://github.com/loro-dev/loro/issues/1240)). Typed text now always follows one rule: it keeps a mark only when the characters on both sides have it (a mark armed with Ctrl+B still wins). The correction is part of the typing step, so one undo removes the text. Canary tests in `tests/unit/loro-quirks.test.js` fail when Loro fixes this and the correction can go.
|
|
18
|
+
- **Ctrl+B (and Ctrl+I, Ctrl+E…) at the end of a marked word could not extend the mark.** With the caret right after a bold word, the shortcut read the bold of the character before the caret as "active" and armed bold off, although text typed there is plain: the first press did nothing visible and you needed a second one. At a caret, "active" now means what typing there would produce (the same rule as the edges of a mark: the characters on both sides have it), so at the end or the start of a bold word the first press arms bold on, and inside the word it arms it off. A selection range, and a mark that was already armed, behave as before.
|
|
19
|
+
|
|
7
20
|
## 0.1.1 (2026-10-29)
|
|
8
21
|
|
|
9
22
|
Two fixes reported by users of the alpha. No API change.
|
package/README.md
CHANGED
|
@@ -4,6 +4,8 @@ Nabu is a modular, local-first block editor for **Svelte 5**. It combines the cr
|
|
|
4
4
|
|
|
5
5
|
**Website, documentation and live demos: [nabu.aion.builders](https://nabu.aion.builders)**
|
|
6
6
|
|
|
7
|
+
Community: [join the Discord](https://discord.gg/gKkyqRRuWe)
|
|
8
|
+
|
|
7
9
|
> **Status: public beta** (`0.1.0`). The editing core is complete and tested, but the API may still change before 1.0. Breaking changes are listed in the [changelog](https://nabu.aion.builders/changelog) ([CHANGELOG.md](CHANGELOG.md)). Known gaps (mobile keyboards, Firefox and Safari, tables, real-time collaboration between machines) are listed honestly on the [limits page](https://nabu.aion.builders/architecture/limits).
|
|
8
10
|
|
|
9
11
|
### Versioning (0.x)
|
|
@@ -133,6 +135,10 @@ Everything is on the website: **[nabu.aion.builders/docs](https://nabu.aion.buil
|
|
|
133
135
|
|
|
134
136
|
In the repository: [architecture decisions](docs/adr), [design notes](docs/design), [tests](tests/README.md).
|
|
135
137
|
|
|
138
|
+
## Contributing
|
|
139
|
+
|
|
140
|
+
Bug reports, fixes, docs and tests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). Questions go to `#help` on the [Discord](https://discord.gg/gKkyqRRuWe).
|
|
141
|
+
|
|
136
142
|
## License
|
|
137
143
|
|
|
138
144
|
MIT, as declared in `package.json`.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @typedef {{ start: number, end: number, name: string, value: any }} MarkFix `value` null: remove the mark over the range
|
|
3
|
+
*/
|
|
4
|
+
/**
|
|
5
|
+
* The value text typed between two characters takes for the mark `name`, or `undefined`: the mark must be on both neighbours with the
|
|
6
|
+
* same value (typing inside a run). The one place that says it, for the correction of a typed run and for what Ctrl+B reads.
|
|
7
|
+
* @param {Record<string, any> | undefined} left effective attributes of the character before (undefined: none)
|
|
8
|
+
* @param {Record<string, any> | undefined} right effective attributes of the character after (undefined: none)
|
|
9
|
+
* @param {string} name
|
|
10
|
+
*/
|
|
11
|
+
export function sharedMark(left: Record<string, any> | undefined, right: Record<string, any> | undefined, name: string): any;
|
|
12
|
+
/**
|
|
13
|
+
* What typing at the collapsed caret `pos` would produce for the mark `name`, read from a delta (the canonical one a behavior holds):
|
|
14
|
+
* the value the typed text would carry, or `undefined`. This is what "the mark is active at the caret" means.
|
|
15
|
+
* @param {import('loro-crdt').Delta<string>[]} delta
|
|
16
|
+
* @param {number} pos
|
|
17
|
+
* @param {string} name
|
|
18
|
+
*/
|
|
19
|
+
export function markAtCaret(delta: import("loro-crdt").Delta<string>[], pos: number, name: string): any;
|
|
20
|
+
/**
|
|
21
|
+
* The corrections for a run just inserted at `[from, end)`.
|
|
22
|
+
* @param {import('loro-crdt').Delta<string>[]} ops `sliceDelta(lo, hi)` of the text, where `lo <= from - 1` (when `from > 0`) and `hi >= end + 1` (when there is a character after)
|
|
23
|
+
* @param {number} lo where `ops` start in the text
|
|
24
|
+
* @param {number} from start of the typed run
|
|
25
|
+
* @param {number} end end of the typed run (exclusive)
|
|
26
|
+
* @param {number} total length of the text
|
|
27
|
+
* @param {Record<string, boolean> | null | undefined} armed the stored marks (explicit on / off), not touched
|
|
28
|
+
* @returns {MarkFix[]}
|
|
29
|
+
*/
|
|
30
|
+
export function markEdgeFixes(ops: import("loro-crdt").Delta<string>[], lo: number, from: number, end: number, total: number, armed: Record<string, boolean> | null | undefined): MarkFix[];
|
|
31
|
+
/**
|
|
32
|
+
* `value` null: remove the mark over the range
|
|
33
|
+
*/
|
|
34
|
+
export type MarkFix = {
|
|
35
|
+
start: number;
|
|
36
|
+
end: number;
|
|
37
|
+
name: string;
|
|
38
|
+
value: any;
|
|
39
|
+
};
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Mark edges of typed text: the rule is Nabu's, not Loro's.
|
|
3
|
+
*
|
|
4
|
+
* Nabu's marks are exact (`expand: 'none'`): a character typed at the edge of a mark does not take it, and one typed inside a mark
|
|
5
|
+
* (the same value on the character before and the one after) keeps it. That is what the user sees, whatever the history of the
|
|
6
|
+
* document. Loro, however, decides from the anchors of the style operations that happened, so two texts that look identical can
|
|
7
|
+
* differ: `[012]3456[789]` made by two `mark` calls takes nothing when "X" is typed at 3, the same text made by `mark [0,10)` then
|
|
8
|
+
* `unmark [3,7)` makes "X" bold (and two `mark` calls that meet at the insertion point make it plain although both sides are bold).
|
|
9
|
+
*
|
|
10
|
+
* {@link markEdgeFixes} reads the typed run and its two neighbours and returns the marks to add or remove so that the typed run
|
|
11
|
+
* follows the rule. A mark the user armed (a stored mark, Ctrl+B with a collapsed caret) is explicit and left alone, on or off.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { effective, sameValue } from '../../utils/delta.js';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* @typedef {{ start: number, end: number, name: string, value: any }} MarkFix `value` null: remove the mark over the range
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The value text typed between two characters takes for the mark `name`, or `undefined`: the mark must be on both neighbours with the
|
|
22
|
+
* same value (typing inside a run). The one place that says it, for the correction of a typed run and for what Ctrl+B reads.
|
|
23
|
+
* @param {Record<string, any> | undefined} left effective attributes of the character before (undefined: none)
|
|
24
|
+
* @param {Record<string, any> | undefined} right effective attributes of the character after (undefined: none)
|
|
25
|
+
* @param {string} name
|
|
26
|
+
*/
|
|
27
|
+
export function sharedMark(left, right, name) {
|
|
28
|
+
return left && right && name in left && name in right && sameValue(left[name], right[name]) ? left[name] : undefined;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* What typing at the collapsed caret `pos` would produce for the mark `name`, read from a delta (the canonical one a behavior holds):
|
|
33
|
+
* the value the typed text would carry, or `undefined`. This is what "the mark is active at the caret" means.
|
|
34
|
+
* @param {import('loro-crdt').Delta<string>[]} delta
|
|
35
|
+
* @param {number} pos
|
|
36
|
+
* @param {string} name
|
|
37
|
+
*/
|
|
38
|
+
export function markAtCaret(delta, pos, name) {
|
|
39
|
+
/** @type {Record<string, any> | undefined} */
|
|
40
|
+
let left;
|
|
41
|
+
/** @type {Record<string, any> | undefined} */
|
|
42
|
+
let right;
|
|
43
|
+
let offset = 0;
|
|
44
|
+
for (const op of delta) {
|
|
45
|
+
const length = typeof op.insert === 'string' ? op.insert.length : 1;
|
|
46
|
+
const end = offset + length;
|
|
47
|
+
if (pos > 0 && offset <= pos - 1 && pos - 1 < end) left = effective(op.attributes) ?? {};
|
|
48
|
+
if (offset <= pos && pos < end) { right = effective(op.attributes) ?? {}; break; }
|
|
49
|
+
offset = end;
|
|
50
|
+
}
|
|
51
|
+
return sharedMark(left, right, name);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* The corrections for a run just inserted at `[from, end)`.
|
|
56
|
+
* @param {import('loro-crdt').Delta<string>[]} ops `sliceDelta(lo, hi)` of the text, where `lo <= from - 1` (when `from > 0`) and `hi >= end + 1` (when there is a character after)
|
|
57
|
+
* @param {number} lo where `ops` start in the text
|
|
58
|
+
* @param {number} from start of the typed run
|
|
59
|
+
* @param {number} end end of the typed run (exclusive)
|
|
60
|
+
* @param {number} total length of the text
|
|
61
|
+
* @param {Record<string, boolean> | null | undefined} armed the stored marks (explicit on / off), not touched
|
|
62
|
+
* @returns {MarkFix[]}
|
|
63
|
+
*/
|
|
64
|
+
export function markEdgeFixes(ops, lo, from, end, total, armed) {
|
|
65
|
+
// Fast path (almost every keystroke): no mark anywhere around the typed run.
|
|
66
|
+
if (!ops.some((op) => op.attributes)) return [];
|
|
67
|
+
/** @type {Record<string, any>} */
|
|
68
|
+
let left = {};
|
|
69
|
+
/** @type {Record<string, any>} */
|
|
70
|
+
let right = {};
|
|
71
|
+
/** @type {{ start: number, end: number, attrs: Record<string, any> }[]} */
|
|
72
|
+
const typed = [];
|
|
73
|
+
let pos = lo;
|
|
74
|
+
for (const op of ops) {
|
|
75
|
+
if (typeof op.insert !== 'string') { pos += 1; continue; }
|
|
76
|
+
const stop = pos + op.insert.length;
|
|
77
|
+
const attrs = effective(op.attributes) ?? {};
|
|
78
|
+
if (from > 0 && pos <= from - 1 && from - 1 < stop) left = attrs;
|
|
79
|
+
if (end < total && pos <= end && end < stop) right = attrs;
|
|
80
|
+
const s = Math.max(pos, from), e = Math.min(stop, end);
|
|
81
|
+
if (s < e) typed.push({ start: s, end: e, attrs });
|
|
82
|
+
pos = stop;
|
|
83
|
+
}
|
|
84
|
+
/** @type {MarkFix[]} */
|
|
85
|
+
const fixes = [];
|
|
86
|
+
for (const { start, end: stop, attrs } of typed) {
|
|
87
|
+
for (const name of new Set([...Object.keys(attrs), ...Object.keys(left)])) {
|
|
88
|
+
if (armed && name in armed) continue;
|
|
89
|
+
const want = sharedMark(left, right, name);
|
|
90
|
+
if (want === undefined) {
|
|
91
|
+
if (name in attrs) fixes.push({ start, end: stop, name, value: null });
|
|
92
|
+
} else if (!(name in attrs) || !sameValue(attrs[name], want)) {
|
|
93
|
+
fixes.push({ start, end: stop, name, value: want });
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
return fixes;
|
|
98
|
+
}
|
|
@@ -49,7 +49,7 @@ export class TextBehavior {
|
|
|
49
49
|
/** @public */
|
|
50
50
|
public text: string;
|
|
51
51
|
/** @public */
|
|
52
|
-
public delta: import("
|
|
52
|
+
public delta: import("../../utils/delta.js").DeltaOp[];
|
|
53
53
|
/** @public */
|
|
54
54
|
public selection: {
|
|
55
55
|
from: number;
|
|
@@ -113,6 +113,14 @@ export class TextBehavior {
|
|
|
113
113
|
public handleBeforeInput(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): any;
|
|
114
114
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
|
|
115
115
|
handleInsertText(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
|
|
116
|
+
/**
|
|
117
|
+
* 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
|
+
* when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
|
|
119
|
+
* (one undo step) as the insertion. Marks in `armed` (stored marks) are the user's explicit choice and stay as they are.
|
|
120
|
+
* Costs one small slice of the text; nothing is written unless a correction is needed.
|
|
121
|
+
* @param {number} from @param {number} length @param {Record<string, boolean> | null} [armed]
|
|
122
|
+
*/
|
|
123
|
+
settleMarkEdges(from: number, length: number, armed?: Record<string, boolean> | null): void;
|
|
116
124
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
|
|
117
125
|
handleInsertLineBreak(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): void;
|
|
118
126
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
|
|
@@ -7,6 +7,8 @@ import { tick } from "svelte";
|
|
|
7
7
|
import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
|
|
8
8
|
import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
|
|
9
9
|
import { countWords, wordDeleteRange } from "../../utils/words.js";
|
|
10
|
+
import { readDelta } from "../../utils/delta.js";
|
|
11
|
+
import { markEdgeFixes } from "./mark-edges.js";
|
|
10
12
|
import { detectPlatform } from "../../utils/keys.js";
|
|
11
13
|
|
|
12
14
|
/**
|
|
@@ -198,10 +200,10 @@ export class TextBehavior {
|
|
|
198
200
|
/** @public */
|
|
199
201
|
this.text = $state(this.container.toString());
|
|
200
202
|
/** @public */
|
|
201
|
-
this.delta = $state(this.container
|
|
203
|
+
this.delta = $state(readDelta(this.container));
|
|
202
204
|
this.container.subscribe(() => {
|
|
203
205
|
this.text = this.container.toString();
|
|
204
|
-
this.delta = this.container
|
|
206
|
+
this.delta = readDelta(this.container);
|
|
205
207
|
this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
|
|
206
208
|
});
|
|
207
209
|
}
|
|
@@ -457,9 +459,30 @@ export class TextBehavior {
|
|
|
457
459
|
else this.removeMark(name, range);
|
|
458
460
|
}
|
|
459
461
|
}
|
|
462
|
+
this.settleMarkEdges(selection.from, textToInsert.length, stored);
|
|
460
463
|
this.block.commit();
|
|
461
464
|
tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
|
|
462
465
|
}
|
|
466
|
+
|
|
467
|
+
/**
|
|
468
|
+
* 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
|
|
469
|
+
* when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
|
|
470
|
+
* (one undo step) as the insertion. Marks in `armed` (stored marks) are the user's explicit choice and stay as they are.
|
|
471
|
+
* Costs one small slice of the text; nothing is written unless a correction is needed.
|
|
472
|
+
* @param {number} from @param {number} length @param {Record<string, boolean> | null} [armed]
|
|
473
|
+
*/
|
|
474
|
+
settleMarkEdges(from, length, armed = null) {
|
|
475
|
+
if (length <= 0 || this.block.marksEnabled === false) return;
|
|
476
|
+
const total = this.container.length;
|
|
477
|
+
const lo = Math.max(0, from - 1);
|
|
478
|
+
const ops = this.container.sliceDelta(lo, Math.min(total, from + length + 1));
|
|
479
|
+
// Loro: the anchors of a mark decide where text typed at its edge lands, not what the text looks like.
|
|
480
|
+
// https://github.com/loro-dev/loro/issues/1240 (canary: tests/unit/loro-quirks.test.js)
|
|
481
|
+
for (const { start, end, name, value } of markEdgeFixes(ops, lo, from, from + length, total, armed)) {
|
|
482
|
+
if (value === null) this.container.unmark({ start, end }, name);
|
|
483
|
+
else this.container.mark({ start, end }, name, value);
|
|
484
|
+
}
|
|
485
|
+
}
|
|
463
486
|
|
|
464
487
|
/** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
|
|
465
488
|
handleInsertLineBreak(event, sel = this.selection) {
|
|
@@ -666,7 +689,7 @@ export class TextBehavior {
|
|
|
666
689
|
*/
|
|
667
690
|
#marksAt(index) {
|
|
668
691
|
let offset = 0;
|
|
669
|
-
for (const op of this.container
|
|
692
|
+
for (const op of readDelta(this.container)) {
|
|
670
693
|
if (typeof op.insert !== 'string') continue;
|
|
671
694
|
const end = offset + op.insert.length;
|
|
672
695
|
if (index >= offset && index < end) return op.attributes ? { ...op.attributes } : null;
|
|
@@ -888,7 +911,7 @@ export class TextBehavior {
|
|
|
888
911
|
*/
|
|
889
912
|
isMarkActive(markName, sel) {
|
|
890
913
|
if (!sel || sel.isCollapsed) return false;
|
|
891
|
-
const delta = this.container
|
|
914
|
+
const delta = readDelta(this.container);
|
|
892
915
|
let offset = 0;
|
|
893
916
|
for (const op of delta) {
|
|
894
917
|
if (typeof op.insert !== 'string') continue;
|
|
@@ -963,7 +986,7 @@ export class TextBehavior {
|
|
|
963
986
|
if (!otherBehavior || !(otherBehavior instanceof TextBehavior)) return false;
|
|
964
987
|
this.applyDelta([
|
|
965
988
|
{ retain: this.container.length },
|
|
966
|
-
...otherBehavior.container
|
|
989
|
+
...readDelta(otherBehavior.container)
|
|
967
990
|
]);
|
|
968
991
|
// other.destroy();
|
|
969
992
|
return true;
|
|
@@ -2,18 +2,43 @@
|
|
|
2
2
|
/** @type {{ block: import('./code.svelte.js').CodeBlock }} */
|
|
3
3
|
let { block } = $props();
|
|
4
4
|
const LANGS = ['plaintext', 'javascript', 'typescript', 'html', 'css', 'json', 'python', 'rust', 'bash', 'markdown', 'sql', 'go'];
|
|
5
|
+
// A language the list does not know (`ts`, `c++`, from a fence, a paste or the API) is listed too: the select shows what the block holds.
|
|
6
|
+
const langs = $derived(block.language && !LANGS.includes(block.language) ? [...LANGS, block.language] : LANGS);
|
|
7
|
+
|
|
8
|
+
// A long line scrolls sideways: the browser does not bring a caret the editor places itself (after typing, Enter, Tab…) into view.
|
|
9
|
+
$effect(() => {
|
|
10
|
+
const el = block.element;
|
|
11
|
+
if (!el) return;
|
|
12
|
+
const keepCaretVisible = () => {
|
|
13
|
+
const sel = getSelection();
|
|
14
|
+
if (!sel || !sel.isCollapsed || !sel.anchorNode || !el.contains(sel.anchorNode) || el.scrollWidth <= el.clientWidth) return;
|
|
15
|
+
const range = document.createRange();
|
|
16
|
+
range.setStart(sel.anchorNode, sel.anchorOffset);
|
|
17
|
+
const caret = range.getClientRects()[0];
|
|
18
|
+
if (!caret) return;
|
|
19
|
+
const box = el.getBoundingClientRect();
|
|
20
|
+
const margin = 24;
|
|
21
|
+
if (caret.right > box.right - margin) el.scrollLeft += caret.right - box.right + margin;
|
|
22
|
+
else if (caret.left < box.left + margin) el.scrollLeft -= box.left + margin - caret.left;
|
|
23
|
+
};
|
|
24
|
+
document.addEventListener('selectionchange', keepCaretVisible);
|
|
25
|
+
return () => document.removeEventListener('selectionchange', keepCaretVisible);
|
|
26
|
+
});
|
|
27
|
+
// The select is out of the Tab order (tabindex -1): inside the editor it would catch the Tab of every block above it.
|
|
28
|
+
// Escape then Shift+Tab, in the code, focuses it (CodeBlock#keydown).
|
|
5
29
|
</script>
|
|
6
30
|
|
|
7
31
|
<div class="nabu-code-wrapper"><select
|
|
8
32
|
class="nabu-code-lang"
|
|
9
33
|
data-nabu-ui
|
|
10
34
|
contenteditable="false"
|
|
35
|
+
tabindex="-1"
|
|
11
36
|
value={block.language ?? 'plaintext'}
|
|
12
37
|
disabled={block.nabu.readonly}
|
|
13
38
|
aria-label="Code language"
|
|
14
39
|
onchange={(e) => block.setLanguage(e.currentTarget.value === 'plaintext' ? null : e.currentTarget.value)}
|
|
15
40
|
>
|
|
16
|
-
{#each
|
|
41
|
+
{#each langs as lang}<option value={lang}>{lang}</option>{/each}
|
|
17
42
|
</select><pre
|
|
18
43
|
bind:this={block.element}
|
|
19
44
|
data-block-id={block.id}
|
|
@@ -64,6 +89,9 @@
|
|
|
64
89
|
line-height: 1.6;
|
|
65
90
|
padding: 0.75em 1em;
|
|
66
91
|
margin: 0;
|
|
92
|
+
/* The library's inline-code rule (`.nabu-code`, RichText) also matches this <pre>: its tint is not wanted here. */
|
|
93
|
+
background: none;
|
|
94
|
+
border-radius: 0;
|
|
67
95
|
overflow-x: auto;
|
|
68
96
|
color: var(--nb-text-primary, rgba(255, 255, 255, 0.85));
|
|
69
97
|
outline: none;
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { tick } from "svelte";
|
|
2
2
|
import { TextBehavior } from "../../behaviors/text";
|
|
3
3
|
import { extension } from "../../utils/extensions";
|
|
4
|
-
import { CodeBlock } from "./code.svelte.js";
|
|
4
|
+
import { CodeBlock, LANGUAGE_CHARS } from "./code.svelte.js";
|
|
5
5
|
import CodeComponent from "./Code.svelte";
|
|
6
6
|
|
|
7
7
|
/**
|
|
@@ -12,7 +12,7 @@ import CodeComponent from "./Code.svelte";
|
|
|
12
12
|
* onBeforeInput hook for CodeBlock:
|
|
13
13
|
* - Inside a code block: Backspace on empty → transform back to paragraph; Backspace at offset 0 of a
|
|
14
14
|
* non-empty one → paragraph too (same text, language dropped, caret stays at 0).
|
|
15
|
-
* - Inside a non-code text block: ``` + Enter → transform to code block.
|
|
15
|
+
* - Inside a non-code text block: ``` + Enter or ``` + Space (with an optional language) → transform to code block.
|
|
16
16
|
*
|
|
17
17
|
* @param {Nabu} nabu @param {InputEvent} event @param {Block} block
|
|
18
18
|
*/
|
|
@@ -50,14 +50,27 @@ const onBeforeInput = (nabu, event, block) => {
|
|
|
50
50
|
return CONTINUE;
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
-
// ``` + Enter in a non-code text block → transform to code
|
|
54
|
-
|
|
55
|
-
|
|
53
|
+
// ``` + Enter, or ``` + Space like every other markdown shortcut (`#`, `>`, `-`), in a non-code text block → transform to code.
|
|
54
|
+
// Space only counts with the caret at the end of the fence (it would otherwise be a space typed inside the text).
|
|
55
|
+
const enter = event.inputType === 'insertParagraph';
|
|
56
|
+
const space = event.inputType === 'insertText' && event.data === ' ';
|
|
57
|
+
if (enter || space) {
|
|
58
|
+
const m = behavior.text.match(new RegExp('^```(' + LANGUAGE_CHARS + '*)$'));
|
|
56
59
|
if (!m) return CONTINUE;
|
|
60
|
+
if (space && sel.from !== behavior.text.length) return CONTINUE;
|
|
57
61
|
const language = m[1] || null;
|
|
58
|
-
behavior.delete({ index: 0, length: behavior.text.length });
|
|
59
62
|
const blockId = block.node.id.toString();
|
|
60
|
-
block.transformTo('code', language ? { language } : {});
|
|
63
|
+
const toCode = () => block.transformTo('code', language ? { language } : {});
|
|
64
|
+
if (enter) {
|
|
65
|
+
behavior.delete({ index: 0, length: behavior.text.length });
|
|
66
|
+
toCode();
|
|
67
|
+
} else {
|
|
68
|
+
// Undo gives back "``` " (trigger space included): see Nabu.shortcut()
|
|
69
|
+
nabu.shortcut(block, ' ', (b) => {
|
|
70
|
+
b.delete({ index: 0, length: b.text.length });
|
|
71
|
+
toCode();
|
|
72
|
+
});
|
|
73
|
+
}
|
|
61
74
|
tick().then(() => {
|
|
62
75
|
const fresh = nabu.blocks.get(blockId);
|
|
63
76
|
if (fresh) fresh.focus({ start: 0, end: 0 });
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
/** What a language name may hold: a word, plus what real ones use (`c++`, `c#`, `objective-c`, `vue.js`). */
|
|
2
|
+
export const LANGUAGE_CHARS: "[\\w#+.-]";
|
|
1
3
|
export class CodeBlock extends TextBlock {
|
|
2
4
|
static placeholder: string;
|
|
3
5
|
/** @param {import('../../utils/extensions.js').PasteBlock} pb */
|
|
@@ -50,12 +52,13 @@ export class CodeBlock extends TextBlock {
|
|
|
50
52
|
*/
|
|
51
53
|
setLanguage(lang: string | null): void;
|
|
52
54
|
/**
|
|
53
|
-
* Handle special keydown events: Tab, Shift+Tab, ArrowDown.
|
|
55
|
+
* Handle special keydown events: Tab, Shift+Tab (except the one that follows an Escape), Ctrl+A, ArrowUp / ArrowDown at the edges of the block.
|
|
54
56
|
* Returns true if handled (engine should preventDefault).
|
|
55
57
|
* @param {KeyboardEvent} event
|
|
56
58
|
* @returns {boolean}
|
|
57
59
|
*/
|
|
58
60
|
keydown(event: KeyboardEvent): boolean;
|
|
61
|
+
#private;
|
|
59
62
|
}
|
|
60
63
|
export type CodeNode = NabuNode<{
|
|
61
64
|
type: "code";
|
|
@@ -3,6 +3,7 @@ import { LoroText } from "loro-crdt";
|
|
|
3
3
|
import CodeComponent from "./Code.svelte";
|
|
4
4
|
import { tick } from "svelte";
|
|
5
5
|
import { escapeHtml } from "../../utils/html.js";
|
|
6
|
+
import { INDENT, leadingIndent, indentLines, outdentLines, lineStart } from "./indent.js";
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* @import { Nabu, NabuNode } from "../nabu.svelte.js";
|
|
@@ -21,6 +22,31 @@ function pbText(pb) {
|
|
|
21
22
|
return (pb.delta || []).map(op => typeof op.insert === 'string' ? op.insert : '').join('');
|
|
22
23
|
}
|
|
23
24
|
|
|
25
|
+
/** What a language name may hold: a word, plus what real ones use (`c++`, `c#`, `objective-c`, `vue.js`). */
|
|
26
|
+
export const LANGUAGE_CHARS = '[\\w#+.-]';
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* The language a `<pre>` (or its `<code>`, or the wrapper of a highlighter) declares: `language-js` / `lang-js` classes (Markdown
|
|
30
|
+
* renderers, Prism, highlight.js, Shiki), GitHub's `highlight-source-js` wrapper, a `data-language` / `data-lang` attribute.
|
|
31
|
+
* @param {Element} pre
|
|
32
|
+
* @returns {string | null}
|
|
33
|
+
*/
|
|
34
|
+
function languageOf(pre) {
|
|
35
|
+
const code = pre.querySelector('code');
|
|
36
|
+
const own = new RegExp('(?:^|\\s)(?:language|lang)-(' + LANGUAGE_CHARS + '+)');
|
|
37
|
+
for (const el of [code, pre]) {
|
|
38
|
+
const m = el && own.exec(el.getAttribute('class') || '');
|
|
39
|
+
if (m) return m[1];
|
|
40
|
+
}
|
|
41
|
+
for (const el of [code, pre]) {
|
|
42
|
+
const attr = el?.getAttribute('data-language') || el?.getAttribute('data-lang');
|
|
43
|
+
if (attr && new RegExp('^' + LANGUAGE_CHARS + '+$').test(attr)) return attr;
|
|
44
|
+
}
|
|
45
|
+
// The wrapper of a highlighter: only its explicit names (a `lang-selector` class there would not be a language).
|
|
46
|
+
const wrapper = new RegExp('(?:^|\\s)(?:language-(' + LANGUAGE_CHARS + '+)|highlight-source-([\\w-]+))').exec(pre.parentElement?.getAttribute('class') || '');
|
|
47
|
+
return wrapper ? (wrapper[1] || wrapper[2]) : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
24
50
|
/** The opening fence of a code block: indent, fence characters, info string. */
|
|
25
51
|
const FENCE_OPEN = /^( {0,3})(`{3,}|~{3,})(.*)$/;
|
|
26
52
|
|
|
@@ -100,7 +126,53 @@ export class CodeBlock extends TextBlock {
|
|
|
100
126
|
}
|
|
101
127
|
|
|
102
128
|
/**
|
|
103
|
-
*
|
|
129
|
+
* Put the selection back on model offsets once the edit is rendered (`backward`: the focus is the start).
|
|
130
|
+
* @param {number} from @param {number} to @param {boolean} [backward]
|
|
131
|
+
*/
|
|
132
|
+
#select(from, to, backward = false) {
|
|
133
|
+
tick().then(() => {
|
|
134
|
+
if (from === to) return this.nabu.selection.setCursor(this, from);
|
|
135
|
+
const a = this.getDOMPoint(backward ? to : from);
|
|
136
|
+
const f = this.getDOMPoint(backward ? from : to);
|
|
137
|
+
if (a && f) this.nabu.selection.setBaseAndExtent(a.node, a.offset, f.node, f.offset);
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* Enter keeps the indentation of the line (auto-indent): the new line starts with the same spaces / tabs, up to the caret.
|
|
143
|
+
* Every other input is the text behavior's (Enter without indentation inserts a plain "\n").
|
|
144
|
+
* @param {InputEvent} event
|
|
145
|
+
*/
|
|
146
|
+
beforeinput(event) {
|
|
147
|
+
if (event.inputType === 'insertParagraph' || event.inputType === 'insertLineBreak') {
|
|
148
|
+
const sel = this.behavior.selection;
|
|
149
|
+
const indent = sel ? leadingIndent(this.text, sel.from) : '';
|
|
150
|
+
if (sel && indent) {
|
|
151
|
+
if (!sel.isCollapsed) this.behavior.delete({ index: sel.from, length: sel.to - sel.from });
|
|
152
|
+
this.behavior.insert(sel.from, '\n' + indent);
|
|
153
|
+
this.commit();
|
|
154
|
+
this.#select(sel.from + 1 + indent.length, sel.from + 1 + indent.length);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return super.beforeinput(event);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* Apply an indent plan (see indent.js) as one commit and keep the selection on the same characters.
|
|
163
|
+
* @param {import('./indent.js').IndentPlan} plan @param {boolean} backward
|
|
164
|
+
*/
|
|
165
|
+
#apply(plan, backward) {
|
|
166
|
+
for (const { index, remove, insert } of plan.edits) {
|
|
167
|
+
if (remove) this.behavior.delete({ index, length: remove });
|
|
168
|
+
if (insert) this.behavior.insert(index, insert);
|
|
169
|
+
}
|
|
170
|
+
this.commit();
|
|
171
|
+
this.#select(plan.from, plan.to, backward);
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
/**
|
|
175
|
+
* Handle special keydown events: Tab, Shift+Tab (except the one that follows an Escape), Ctrl+A, ArrowUp / ArrowDown at the edges of the block.
|
|
104
176
|
* Returns true if handled (engine should preventDefault).
|
|
105
177
|
* @param {KeyboardEvent} event
|
|
106
178
|
* @returns {boolean}
|
|
@@ -108,35 +180,55 @@ export class CodeBlock extends TextBlock {
|
|
|
108
180
|
keydown(event) {
|
|
109
181
|
const sel = this.behavior.selection;
|
|
110
182
|
if (!sel) return false;
|
|
183
|
+
const plain = !event.ctrlKey && !event.metaKey && !event.altKey && !event.shiftKey;
|
|
184
|
+
const backward = sel.direction === 'backward';
|
|
185
|
+
|
|
186
|
+
// The way out (WCAG 2.1.2): Tab / Shift+Tab right after an Escape nobody consumed is not the code's. Forward, the browser moves the
|
|
187
|
+
// focus out of the editor. Backward, it would go before the editor and never reach the language select, so the focus goes there.
|
|
188
|
+
if (event.key === 'Tab' && this.nabu.tabWayOut) {
|
|
189
|
+
if (!event.shiftKey) return false;
|
|
190
|
+
const select = /** @type {HTMLSelectElement | null | undefined} */ (this.element?.parentElement?.querySelector('select.nabu-code-lang'));
|
|
191
|
+
if (!select || select.disabled) return false;
|
|
192
|
+
select.focus();
|
|
193
|
+
return true;
|
|
194
|
+
}
|
|
111
195
|
|
|
112
|
-
// Tab without shift
|
|
196
|
+
// Tab without shift: over several lines, indent every line; else insert 2 spaces (replacing a selection within one line)
|
|
113
197
|
if (event.key === 'Tab' && !event.shiftKey) {
|
|
198
|
+
const plan = indentLines(this.text, sel.from, sel.to);
|
|
199
|
+
if (plan) { this.#apply(plan, backward); return true; }
|
|
114
200
|
if (!sel.isCollapsed) this.behavior.delete({ index: sel.from, length: sel.to - sel.from });
|
|
115
|
-
this.behavior.insert(sel.from,
|
|
201
|
+
this.behavior.insert(sel.from, INDENT);
|
|
116
202
|
this.commit();
|
|
117
|
-
|
|
203
|
+
this.#select(sel.from + INDENT.length, sel.from + INDENT.length);
|
|
118
204
|
return true;
|
|
119
205
|
}
|
|
120
206
|
|
|
121
|
-
// Shift+Tab
|
|
207
|
+
// Shift+Tab: outdent every line the selection touches (the caret's own line when collapsed)
|
|
122
208
|
if (event.key === 'Tab' && event.shiftKey) {
|
|
123
|
-
const
|
|
124
|
-
|
|
125
|
-
while (n < 2 && this.text[ls + n] === ' ') n++;
|
|
126
|
-
if (n > 0) {
|
|
127
|
-
this.behavior.delete({ index: ls, length: n });
|
|
128
|
-
this.commit();
|
|
129
|
-
tick().then(() => this.nabu.selection.setCursor(this, Math.max(ls, sel.from - n)));
|
|
130
|
-
}
|
|
209
|
+
const plan = outdentLines(this.text, sel.from, sel.to);
|
|
210
|
+
if (plan) this.#apply(plan, backward);
|
|
131
211
|
return true;
|
|
132
212
|
}
|
|
133
213
|
|
|
134
|
-
//
|
|
135
|
-
if (event.
|
|
136
|
-
const
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
214
|
+
// Ctrl/Cmd+A: the code first, the whole document with the next press (the browser's own Select All)
|
|
215
|
+
if ((event.ctrlKey || event.metaKey) && !event.shiftKey && !event.altKey && typeof event.key === 'string' && event.key.toLowerCase() === 'a') {
|
|
216
|
+
const length = this.text.length;
|
|
217
|
+
if (length && !(sel.from === 0 && sel.to === length)) {
|
|
218
|
+
this.nabu.selection.selectBlockText(this);
|
|
219
|
+
return true;
|
|
220
|
+
}
|
|
221
|
+
return false;
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// ArrowDown from the last line / ArrowUp from the first one, with no text block beyond: a paragraph is created there, so
|
|
225
|
+
// that a code block at the end (start) of the document, or before a divider, can be left with the keyboard.
|
|
226
|
+
if ((event.key === 'ArrowDown' || event.key === 'ArrowUp') && plain && sel.isCollapsed) {
|
|
227
|
+
const down = event.key === 'ArrowDown';
|
|
228
|
+
const onEdge = down ? this.text.indexOf('\n', sel.from) === -1 : lineStart(this.text, sel.from) === 0;
|
|
229
|
+
const hasNeighbour = !!(down ? this.findForward(b => b.behaviors?.has('text')) : this.findBackward(b => b.behaviors?.has('text')));
|
|
230
|
+
if (onEdge && !hasNeighbour) {
|
|
231
|
+
const p = this.nabu.insert('paragraph', {}, this.node.parent()?.id.toString() || null, (this.node.index() ?? 0) + (down ? 1 : 0));
|
|
140
232
|
this.nabu.commit().then(() => {
|
|
141
233
|
const fresh = this.nabu.blocks.get(p.id);
|
|
142
234
|
if (fresh) this.nabu.selection.setCursor(fresh, 0);
|
|
@@ -158,7 +250,9 @@ export class CodeBlock extends TextBlock {
|
|
|
158
250
|
|
|
159
251
|
/** @param {import('../../utils/extensions.js').PasteBlock} pb */
|
|
160
252
|
static toHtml(pb) {
|
|
161
|
-
|
|
253
|
+
const language = String(pb.props?.language || '');
|
|
254
|
+
const cls = new RegExp('^' + LANGUAGE_CHARS + '+$').test(language) ? ` class="language-${language}"` : '';
|
|
255
|
+
return `<pre><code${cls}>${escapeHtml(pbText(pb))}</code></pre>`;
|
|
162
256
|
}
|
|
163
257
|
|
|
164
258
|
/**
|
|
@@ -222,8 +316,11 @@ export class CodeBlock extends TextBlock {
|
|
|
222
316
|
* @returns {import('../../utils/extensions.js').PasteBlock | null}
|
|
223
317
|
*/
|
|
224
318
|
static fromHTML(el) {
|
|
225
|
-
|
|
226
|
-
const
|
|
319
|
+
// A <br> in a <pre> is a line break (old sites, some editors); textContent alone would glue the lines.
|
|
320
|
+
const copy = /** @type {Element} */ (el.cloneNode(true));
|
|
321
|
+
for (const br of copy.querySelectorAll('br')) br.replaceWith('\n');
|
|
322
|
+
const text = copy.textContent || '';
|
|
323
|
+
const language = languageOf(el);
|
|
227
324
|
return {
|
|
228
325
|
type: 'code',
|
|
229
326
|
props: { language },
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The offset where the line holding `pos` starts.
|
|
3
|
+
* @param {string} text @param {number} pos
|
|
4
|
+
*/
|
|
5
|
+
export function lineStart(text: string, pos: number): number;
|
|
6
|
+
/**
|
|
7
|
+
* The whitespace (spaces and tabs) at the start of the line, up to the caret: what a new line typed with Enter starts with.
|
|
8
|
+
* @param {string} text @param {number} pos
|
|
9
|
+
*/
|
|
10
|
+
export function leadingIndent(text: string, pos: number): string;
|
|
11
|
+
/**
|
|
12
|
+
* The start offsets of the lines a selection touches. A selection that ends at the very start of a line does not touch that
|
|
13
|
+
* line (as in every code editor); a collapsed caret touches its own line.
|
|
14
|
+
* @param {string} text @param {number} from @param {number} to
|
|
15
|
+
* @returns {number[]}
|
|
16
|
+
*/
|
|
17
|
+
export function touchedLines(text: string, from: number, to: number): number[];
|
|
18
|
+
/**
|
|
19
|
+
* @typedef {Object} IndentPlan
|
|
20
|
+
* @property {{ index: number, remove: number, insert: string }[]} edits from the END of the text to its start (apply in order)
|
|
21
|
+
* @property {number} from the selection start after the edits
|
|
22
|
+
* @property {number} to the selection end after the edits
|
|
23
|
+
*/
|
|
24
|
+
/**
|
|
25
|
+
* Tab over a selection that spans several lines: one indentation level is inserted at the start of every non-empty line.
|
|
26
|
+
* `null` when the selection is within one line (Tab then replaces it by an indentation, like VS Code).
|
|
27
|
+
* @param {string} text @param {number} from @param {number} to
|
|
28
|
+
* @returns {IndentPlan | null}
|
|
29
|
+
*/
|
|
30
|
+
export function indentLines(text: string, from: number, to: number): IndentPlan | null;
|
|
31
|
+
/**
|
|
32
|
+
* Shift+Tab: one indentation level (a tab character, or up to two spaces) is removed from the start of every line the
|
|
33
|
+
* selection touches (the caret's own line when it is collapsed). `null` when no line has anything to remove.
|
|
34
|
+
* @param {string} text @param {number} from @param {number} to
|
|
35
|
+
* @returns {IndentPlan | null}
|
|
36
|
+
*/
|
|
37
|
+
export function outdentLines(text: string, from: number, to: number): IndentPlan | null;
|
|
38
|
+
/**
|
|
39
|
+
* Pure text helpers of the code block (no DOM, no Loro): where a line starts, what indentation it has, which lines a Tab /
|
|
40
|
+
* Shift+Tab touches and the edits that indent / outdent them. `CodeBlock` applies the edits to its Loro text.
|
|
41
|
+
*/
|
|
42
|
+
/** One level of indentation: two spaces (never a tab character: the code is not re-indented by the host's tab width). */
|
|
43
|
+
export const INDENT: " ";
|
|
44
|
+
export type IndentPlan = {
|
|
45
|
+
/**
|
|
46
|
+
* from the END of the text to its start (apply in order)
|
|
47
|
+
*/
|
|
48
|
+
edits: {
|
|
49
|
+
index: number;
|
|
50
|
+
remove: number;
|
|
51
|
+
insert: string;
|
|
52
|
+
}[];
|
|
53
|
+
/**
|
|
54
|
+
* the selection start after the edits
|
|
55
|
+
*/
|
|
56
|
+
from: number;
|
|
57
|
+
/**
|
|
58
|
+
* the selection end after the edits
|
|
59
|
+
*/
|
|
60
|
+
to: number;
|
|
61
|
+
};
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure text helpers of the code block (no DOM, no Loro): where a line starts, what indentation it has, which lines a Tab /
|
|
3
|
+
* Shift+Tab touches and the edits that indent / outdent them. `CodeBlock` applies the edits to its Loro text.
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
/** One level of indentation: two spaces (never a tab character: the code is not re-indented by the host's tab width). */
|
|
7
|
+
export const INDENT = ' ';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* The offset where the line holding `pos` starts.
|
|
11
|
+
* @param {string} text @param {number} pos
|
|
12
|
+
*/
|
|
13
|
+
export function lineStart(text, pos) {
|
|
14
|
+
return pos <= 0 ? 0 : text.lastIndexOf('\n', pos - 1) + 1;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The whitespace (spaces and tabs) at the start of the line, up to the caret: what a new line typed with Enter starts with.
|
|
19
|
+
* @param {string} text @param {number} pos
|
|
20
|
+
*/
|
|
21
|
+
export function leadingIndent(text, pos) {
|
|
22
|
+
const start = lineStart(text, pos);
|
|
23
|
+
return /^[ \t]*/.exec(text.slice(start, pos))?.[0] ?? '';
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* The start offsets of the lines a selection touches. A selection that ends at the very start of a line does not touch that
|
|
28
|
+
* line (as in every code editor); a collapsed caret touches its own line.
|
|
29
|
+
* @param {string} text @param {number} from @param {number} to
|
|
30
|
+
* @returns {number[]}
|
|
31
|
+
*/
|
|
32
|
+
export function touchedLines(text, from, to) {
|
|
33
|
+
const end = to > from && text[to - 1] === '\n' ? to - 1 : to;
|
|
34
|
+
/** @type {number[]} */
|
|
35
|
+
const starts = [];
|
|
36
|
+
let s = lineStart(text, from);
|
|
37
|
+
for (;;) {
|
|
38
|
+
starts.push(s);
|
|
39
|
+
const next = text.indexOf('\n', s);
|
|
40
|
+
if (next === -1 || next >= end) break;
|
|
41
|
+
s = next + 1;
|
|
42
|
+
}
|
|
43
|
+
return starts;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/**
|
|
47
|
+
* @typedef {Object} IndentPlan
|
|
48
|
+
* @property {{ index: number, remove: number, insert: string }[]} edits from the END of the text to its start (apply in order)
|
|
49
|
+
* @property {number} from the selection start after the edits
|
|
50
|
+
* @property {number} to the selection end after the edits
|
|
51
|
+
*/
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Tab over a selection that spans several lines: one indentation level is inserted at the start of every non-empty line.
|
|
55
|
+
* `null` when the selection is within one line (Tab then replaces it by an indentation, like VS Code).
|
|
56
|
+
* @param {string} text @param {number} from @param {number} to
|
|
57
|
+
* @returns {IndentPlan | null}
|
|
58
|
+
*/
|
|
59
|
+
export function indentLines(text, from, to) {
|
|
60
|
+
const lines = touchedLines(text, from, to);
|
|
61
|
+
if (lines.length < 2) return null;
|
|
62
|
+
const targets = lines.filter((s) => s < text.length && text[s] !== '\n');
|
|
63
|
+
let nextFrom = from;
|
|
64
|
+
let nextTo = to;
|
|
65
|
+
for (const s of targets) {
|
|
66
|
+
if (from > s) nextFrom += INDENT.length;
|
|
67
|
+
if (to > s) nextTo += INDENT.length;
|
|
68
|
+
}
|
|
69
|
+
return { edits: targets.reverse().map((index) => ({ index, remove: 0, insert: INDENT })), from: nextFrom, to: nextTo };
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Shift+Tab: one indentation level (a tab character, or up to two spaces) is removed from the start of every line the
|
|
74
|
+
* selection touches (the caret's own line when it is collapsed). `null` when no line has anything to remove.
|
|
75
|
+
* @param {string} text @param {number} from @param {number} to
|
|
76
|
+
* @returns {IndentPlan | null}
|
|
77
|
+
*/
|
|
78
|
+
export function outdentLines(text, from, to) {
|
|
79
|
+
/** @type {{ index: number, remove: number }[]} */
|
|
80
|
+
const cuts = [];
|
|
81
|
+
for (const s of touchedLines(text, from, to)) {
|
|
82
|
+
let n = 0;
|
|
83
|
+
if (text[s] === '\t') n = 1;
|
|
84
|
+
else while (n < INDENT.length && text[s + n] === ' ') n++;
|
|
85
|
+
if (n) cuts.push({ index: s, remove: n });
|
|
86
|
+
}
|
|
87
|
+
if (!cuts.length) return null;
|
|
88
|
+
/** @param {number} p */
|
|
89
|
+
const map = (p) => cuts.reduce((q, c) => q - Math.min(Math.max(p - c.index, 0), c.remove), p);
|
|
90
|
+
return { edits: [...cuts].reverse().map((c) => ({ ...c, insert: '' })), from: map(from), to: map(to) };
|
|
91
|
+
}
|
|
@@ -3,6 +3,7 @@ import { TextBehavior } from "../../../behaviors/text";
|
|
|
3
3
|
import { List } from "../list.svelte.js";
|
|
4
4
|
import { ListItem } from "../list-item.svelte.js";
|
|
5
5
|
import { stepBack } from "../step-back.js";
|
|
6
|
+
import { readDelta } from "../../../utils/delta.js";
|
|
6
7
|
|
|
7
8
|
/**
|
|
8
9
|
* @import { Nabu, Block } from "../..";
|
|
@@ -77,7 +78,7 @@ export const onBeforeInput = (nabu, event, block) => {
|
|
|
77
78
|
b.delete({ index: 0, length: prefixLength + 1 });
|
|
78
79
|
|
|
79
80
|
// Capture remaining text delta (everything after the prefix)
|
|
80
|
-
const delta = b.container
|
|
81
|
+
const delta = readDelta(b.container);
|
|
81
82
|
|
|
82
83
|
// Get current tree position from live Loro state (pre-commit)
|
|
83
84
|
const parentNode = block.node.parent();
|
|
@@ -10,6 +10,7 @@
|
|
|
10
10
|
import { List } from "./list.svelte.js";
|
|
11
11
|
import { ListItem } from "./list-item.svelte.js";
|
|
12
12
|
import { convertItemToListType } from "./convert.js";
|
|
13
|
+
import { readDelta } from "../../utils/delta.js";
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* @param {Nabu} nabu
|
|
@@ -30,7 +31,7 @@ export async function convertToList(nabu, listType) {
|
|
|
30
31
|
}
|
|
31
32
|
|
|
32
33
|
const beh = block.behaviors?.get("text");
|
|
33
|
-
const delta = beh ? beh.container
|
|
34
|
+
const delta = beh ? readDelta(beh.container) : [];
|
|
34
35
|
const parentNode = block.node.parent();
|
|
35
36
|
const parentId = parentNode?.id.toString() ?? null;
|
|
36
37
|
const index = block.node.index();
|
|
@@ -244,6 +244,13 @@ export class Nabu {
|
|
|
244
244
|
public slashCommands: import("../ui/slash-menu.svelte.js").SlashCommand[];
|
|
245
245
|
/** What the editor root exposes as `aria-description`: the hint, only while the mode keeps the focus in. */
|
|
246
246
|
get tabDescription(): string | undefined;
|
|
247
|
+
/**
|
|
248
|
+
* True while a keydown is being handled and it is the Tab / Shift+Tab that follows an Escape nobody consumed: the way out is open
|
|
249
|
+
* for it. A block that gives Tab a meaning of its own (the code block's indentation) lets this one go to the browser (WCAG 2.1.2).
|
|
250
|
+
* Plain property, not state: only meaningful during `handleKeydown`.
|
|
251
|
+
* @type {boolean}
|
|
252
|
+
*/
|
|
253
|
+
tabWayOut: boolean;
|
|
247
254
|
/** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
|
|
248
255
|
rearmTab(): void;
|
|
249
256
|
/**
|
|
@@ -18,6 +18,7 @@ import { moveBlocks } from './move.js';
|
|
|
18
18
|
import { closestWithin } from '../utils/dom-scope.js';
|
|
19
19
|
import { captureSelection, explicitSelection, legacySelection, restoreSelection, keepSelection, makeEndpoint, resolveOffset, revealFocus } from './undo-selection.js';
|
|
20
20
|
import { LARGE_DOC } from './chunks.js';
|
|
21
|
+
import { markAtCaret } from '../behaviors/text/mark-edges.js';
|
|
21
22
|
import { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
|
|
22
23
|
import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
|
|
23
24
|
|
|
@@ -83,22 +84,14 @@ import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPositio
|
|
|
83
84
|
*/
|
|
84
85
|
|
|
85
86
|
/**
|
|
86
|
-
* Whether the
|
|
87
|
-
*
|
|
87
|
+
* Whether typing at the collapsed caret `pos` of a text behavior would carry the mark `name`: the Nabu mark-edge rule (the character
|
|
88
|
+
* before AND the one after have it, with the same value), see mark-edges.js. Decides the direction of the stored-mark toggle
|
|
89
|
+
* (Ctrl+B at a caret): at the end of a bold word typing is plain, so Ctrl+B arms bold ON.
|
|
88
90
|
* @param {any} behavior @param {number} pos @param {string} name
|
|
89
91
|
* @returns {boolean}
|
|
90
92
|
*/
|
|
91
93
|
function inheritedMarkAt(behavior, pos, name) {
|
|
92
|
-
|
|
93
|
-
const delta = behavior.delta;
|
|
94
|
-
let offset = 0;
|
|
95
|
-
for (const op of delta) {
|
|
96
|
-
if (typeof op.insert !== 'string') continue;
|
|
97
|
-
const end = offset + op.insert.length;
|
|
98
|
-
if (pos <= end) return !!(op.attributes && op.attributes[name]);
|
|
99
|
-
offset = end;
|
|
100
|
-
}
|
|
101
|
-
return false;
|
|
94
|
+
return markAtCaret(behavior.delta, pos, name) !== undefined;
|
|
102
95
|
}
|
|
103
96
|
|
|
104
97
|
/**
|
|
@@ -633,6 +626,14 @@ export class Nabu {
|
|
|
633
626
|
/** An Escape nobody consumed was the previous key: the next Tab / Shift+Tab leaves the editor (see `utils/tab.js`). */
|
|
634
627
|
#tabEscaped = false;
|
|
635
628
|
|
|
629
|
+
/**
|
|
630
|
+
* True while a keydown is being handled and it is the Tab / Shift+Tab that follows an Escape nobody consumed: the way out is open
|
|
631
|
+
* for it. A block that gives Tab a meaning of its own (the code block's indentation) lets this one go to the browser (WCAG 2.1.2).
|
|
632
|
+
* Plain property, not state: only meaningful during `handleKeydown`.
|
|
633
|
+
* @type {boolean}
|
|
634
|
+
*/
|
|
635
|
+
tabWayOut = false;
|
|
636
|
+
|
|
636
637
|
/** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
|
|
637
638
|
rearmTab() { this.#tabEscaped = false; }
|
|
638
639
|
|
|
@@ -1505,11 +1506,14 @@ export class Nabu {
|
|
|
1505
1506
|
handleKeydown(e) {
|
|
1506
1507
|
// Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
|
|
1507
1508
|
if (this.#readonly) return;
|
|
1509
|
+
// 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.
|
|
1510
|
+
if (e.key === 'Tab' && e.target instanceof Element && e.target.closest('[data-nabu-ui]')) return;
|
|
1508
1511
|
this.selection.sync(); // no-op when the document capture listener already synced
|
|
1509
1512
|
this.selection.normalize();
|
|
1510
1513
|
// The Escape-then-Tab way out of the `tab` option (utils/tab.js): any key but a lone modifier closes it, whoever handles the key.
|
|
1511
1514
|
const escaped = this.#tabEscaped;
|
|
1512
1515
|
if (!isModifierKey(e)) this.#tabEscaped = false;
|
|
1516
|
+
this.tabWayOut = escaped && e.key === 'Tab';
|
|
1513
1517
|
// Commands first (ADR 017): undo / redo and every declared shortcut. What no command handles falls through to the
|
|
1514
1518
|
// legacy `onKeyDown` hooks and the block's own keydown, then to the native behavior.
|
|
1515
1519
|
if (this.commands.handleKeydown(e)) return;
|
|
@@ -1890,6 +1894,9 @@ export class Nabu {
|
|
|
1890
1894
|
const behavior = block.behaviors?.get('text');
|
|
1891
1895
|
const sel = offset === undefined ? behavior?.selection : { from: offset, to: offset };
|
|
1892
1896
|
if (!behavior || !sel) return;
|
|
1897
|
+
// Line endings are "\n" in the model, whatever the source (Windows "\r\n", old Mac "\r"): a "\r" would be a character
|
|
1898
|
+
// of the text that no line shows, and would leak into the exports.
|
|
1899
|
+
text = text.replace(/\r\n?/g, '\n');
|
|
1893
1900
|
const from = Math.min(sel.from, sel.to);
|
|
1894
1901
|
const to = Math.max(sel.from, sel.to);
|
|
1895
1902
|
if (to > from) behavior.delete({ index: from, length: to - from });
|
|
@@ -17,6 +17,7 @@ import { tick } from "svelte";
|
|
|
17
17
|
import { Regions } from "./regions.svelte.js";
|
|
18
18
|
import { createRegion } from "./insert.js";
|
|
19
19
|
import { hasText, isBodyTextBlock, mergePlan, neighbourOf, siblingsOf } from "./facts.js";
|
|
20
|
+
import { readDelta } from "../../utils/delta.js";
|
|
20
21
|
|
|
21
22
|
/** @typedef {{ block: Block, offset: number }} Caret */
|
|
22
23
|
|
|
@@ -248,7 +249,7 @@ export async function unwrapRegion(nabu, region, caret = null) {
|
|
|
248
249
|
/** @type {NabuNode} */
|
|
249
250
|
let anchor = node;
|
|
250
251
|
if (region.block.title.length) {
|
|
251
|
-
const paragraph = createDefaultBlock(nabu, { delta: region.block.container
|
|
252
|
+
const paragraph = createDefaultBlock(nabu, { delta: readDelta(region.block.container) }, parentIdOf(node), node.index() ?? 0);
|
|
252
253
|
anchor = paragraph.node;
|
|
253
254
|
if (caret && caret.block === region.block) landing = { block: paragraph, offset: caret.offset };
|
|
254
255
|
}
|
|
@@ -120,7 +120,7 @@ export class RegionBlock extends MegaBlock {
|
|
|
120
120
|
block: import("./region.svelte.js").RegionBlock;
|
|
121
121
|
}, {}, "">;
|
|
122
122
|
get text(): string;
|
|
123
|
-
get delta(): import("
|
|
123
|
+
get delta(): import("../../utils/delta.js").DeltaOp[];
|
|
124
124
|
selection: {
|
|
125
125
|
from: number;
|
|
126
126
|
to: number;
|
|
@@ -6,6 +6,7 @@ import { resolveConfig, fieldSpec, validateField } from "./types.js";
|
|
|
6
6
|
import { scanRegion, parseRegionComment, parseRegionHtml, sanitizeFieldDelta, levelOfType } from "./format.js";
|
|
7
7
|
import { regionBlockToMarkdown, regionBlockToHtml, closingNeeded, followOf, regionTypeOf } from "./serialize.js";
|
|
8
8
|
import { createMessages } from "./messages.js";
|
|
9
|
+
import { readDelta } from "../../utils/delta.js";
|
|
9
10
|
|
|
10
11
|
/**
|
|
11
12
|
* @import { Nabu, NabuNode } from "../nabu.svelte.js";
|
|
@@ -252,7 +253,7 @@ export class RegionBlock extends MegaBlock {
|
|
|
252
253
|
for (const key of map.keys()) {
|
|
253
254
|
if (key === 'title') continue;
|
|
254
255
|
const v = map.get(key);
|
|
255
|
-
out[key] = isContainer(v) ? (v.kind() === 'Text' ? /** @type {any} */ (v)
|
|
256
|
+
out[key] = isContainer(v) ? (v.kind() === 'Text' ? readDelta(/** @type {any} */ (v)) : v.toJSON()) : v;
|
|
256
257
|
}
|
|
257
258
|
return out;
|
|
258
259
|
}
|
|
@@ -280,7 +281,7 @@ export class RegionBlock extends MegaBlock {
|
|
|
280
281
|
if (text.length) text.delete(0, text.length);
|
|
281
282
|
if (value) text.insert(0, oneLine(value));
|
|
282
283
|
this.behavior.text = text.toString();
|
|
283
|
-
this.behavior.delta = text
|
|
284
|
+
this.behavior.delta = readDelta(text);
|
|
284
285
|
}
|
|
285
286
|
|
|
286
287
|
/**
|
|
@@ -34,7 +34,7 @@ export class TextBlock extends Block {
|
|
|
34
34
|
/** The plain text of the block (reactive). @public */
|
|
35
35
|
public get text(): string;
|
|
36
36
|
/** The text with its marks, as a Loro delta (reactive). @public */
|
|
37
|
-
public get delta(): import("
|
|
37
|
+
public get delta(): import("../utils/delta.js").DeltaOp[];
|
|
38
38
|
/** The selection inside this block, `{ from, to, direction }` in text offsets, or `null` (reactive). @public */
|
|
39
39
|
public selection: {
|
|
40
40
|
from: number;
|
|
@@ -84,7 +84,7 @@ export class ToggleBlock extends MegaBlock {
|
|
|
84
84
|
block: import("./toggle.svelte.js").ToggleBlock;
|
|
85
85
|
}, {}, "">;
|
|
86
86
|
get text(): string;
|
|
87
|
-
get delta(): import("
|
|
87
|
+
get delta(): import("../../utils/delta.js").DeltaOp[];
|
|
88
88
|
selection: {
|
|
89
89
|
from: number;
|
|
90
90
|
to: number;
|
|
@@ -80,7 +80,8 @@ export class SlashMenuController {
|
|
|
80
80
|
match = $derived.by(() => {
|
|
81
81
|
const sel = this.#engine.selection;
|
|
82
82
|
const block = sel?.anchorBlock;
|
|
83
|
-
|
|
83
|
+
// A verbatim buffer (the code block) has no commands: `/` is text there, and Enter must stay a newline.
|
|
84
|
+
if (!block || block.pastesAsPlainText) return null;
|
|
84
85
|
const beh = block.behaviors?.get('text');
|
|
85
86
|
const bsel = beh?.selection;
|
|
86
87
|
if (!beh || !bsel || !bsel.isCollapsed) return null;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The attributes of an op without the ones that are off, `undefined` when none is left.
|
|
3
|
+
* @param {Record<string, any> | undefined} attrs
|
|
4
|
+
* @returns {Record<string, any> | undefined}
|
|
5
|
+
*/
|
|
6
|
+
export function effective(attrs: Record<string, any> | undefined): Record<string, any> | undefined;
|
|
7
|
+
/**
|
|
8
|
+
* Whether two mark values are the same (links compare by href; an object value by its content).
|
|
9
|
+
* @param {any} a @param {any} b
|
|
10
|
+
*/
|
|
11
|
+
export function sameValue(a: any, b: any): boolean;
|
|
12
|
+
/**
|
|
13
|
+
* The canonical form of a delta (see the top of this file). One linear pass; when the delta already is canonical (the usual
|
|
14
|
+
* case, this runs on every keystroke) the SAME array is returned, nothing is allocated.
|
|
15
|
+
* @param {DeltaOp[]} delta
|
|
16
|
+
* @returns {DeltaOp[]}
|
|
17
|
+
*/
|
|
18
|
+
export function normalizeDelta(delta: DeltaOp[]): DeltaOp[];
|
|
19
|
+
/**
|
|
20
|
+
* The canonical delta of a Loro text: the only way the engine reads `toDelta()`.
|
|
21
|
+
* @param {{ toDelta: () => DeltaOp[] }} container
|
|
22
|
+
* @returns {DeltaOp[]}
|
|
23
|
+
*/
|
|
24
|
+
export function readDelta(container: {
|
|
25
|
+
toDelta: () => DeltaOp[];
|
|
26
|
+
}): DeltaOp[];
|
|
27
|
+
export type DeltaOp = import("loro-crdt").Delta<string>;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Workaround for a Loro quirk (the raw delta keeps a split after an exact unmark). https://github.com/loro-dev/loro/issues/1241
|
|
2
|
+
// Canary: tests/unit/loro-quirks.test.js.
|
|
3
|
+
/**
|
|
4
|
+
* The canonical form of a rich-text delta.
|
|
5
|
+
*
|
|
6
|
+
* `LoroText.toDelta()` keeps a split where a mark was removed over exactly the range it was applied to: bolding `[18, 21)` then
|
|
7
|
+
* un-bolding `[18, 21)` leaves `[{ insert: 'The ford is upstre' }, { insert: 'am.' }]` instead of one run (an unmark over a wider
|
|
8
|
+
* range merges, which is why it looked random). The split lives in the document, snapshots included, and is not repaired there:
|
|
9
|
+
* every read of a delta goes through {@link readDelta}, so that the engine only ever sees runs that differ.
|
|
10
|
+
*
|
|
11
|
+
* Canonical means: no empty insert, no attribute whose value is `null`, `undefined` or `false` (a mark that is off is an absent
|
|
12
|
+
* mark, the way the renderers and `isMarkActive` read it), no `attributes` object when none is left, and no two adjacent text
|
|
13
|
+
* runs with the same attributes. An embed (a non-string insert) is kept untouched and never merged.
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @typedef {import('loro-crdt').Delta<string>} DeltaOp */
|
|
17
|
+
|
|
18
|
+
/**
|
|
19
|
+
* Whether a mark value counts as "off".
|
|
20
|
+
* @param {unknown} value
|
|
21
|
+
*/
|
|
22
|
+
const isOff = (value) => value === null || value === undefined || value === false;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Whether an op carries an attribute that is off, or an empty attribute object (it must be rewritten).
|
|
26
|
+
* @param {Record<string, any> | undefined} attrs
|
|
27
|
+
*/
|
|
28
|
+
function isDirty(attrs) {
|
|
29
|
+
if (!attrs) return false;
|
|
30
|
+
let any = false;
|
|
31
|
+
for (const key in attrs) {
|
|
32
|
+
if (isOff(attrs[key])) return true;
|
|
33
|
+
any = true;
|
|
34
|
+
}
|
|
35
|
+
return !any;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* The attributes of an op without the ones that are off, `undefined` when none is left.
|
|
40
|
+
* @param {Record<string, any> | undefined} attrs
|
|
41
|
+
* @returns {Record<string, any> | undefined}
|
|
42
|
+
*/
|
|
43
|
+
export function effective(attrs) {
|
|
44
|
+
if (!attrs) return undefined;
|
|
45
|
+
/** @type {Record<string, any> | undefined} */
|
|
46
|
+
let out;
|
|
47
|
+
for (const key in attrs) if (!isOff(attrs[key])) (out ??= {})[key] = attrs[key];
|
|
48
|
+
return out;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Whether two mark values are the same (links compare by href; an object value by its content).
|
|
53
|
+
* @param {any} a @param {any} b
|
|
54
|
+
*/
|
|
55
|
+
export function sameValue(a, b) {
|
|
56
|
+
if (a === b) return true;
|
|
57
|
+
if (a && b && typeof a === 'object' && typeof b === 'object') return JSON.stringify(a) === JSON.stringify(b);
|
|
58
|
+
return false;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Whether two EFFECTIVE attribute sets (no off value) are equal.
|
|
63
|
+
* @param {Record<string, any> | undefined} a @param {Record<string, any> | undefined} b
|
|
64
|
+
*/
|
|
65
|
+
function sameAttributes(a, b) {
|
|
66
|
+
if (a === b) return true;
|
|
67
|
+
if (!a || !b) return false;
|
|
68
|
+
let count = 0;
|
|
69
|
+
for (const key in a) {
|
|
70
|
+
if (!(key in b) || !sameValue(a[key], b[key])) return false;
|
|
71
|
+
count++;
|
|
72
|
+
}
|
|
73
|
+
for (const _ in b) count--;
|
|
74
|
+
return count === 0;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The canonical form of a delta (see the top of this file). One linear pass; when the delta already is canonical (the usual
|
|
79
|
+
* case, this runs on every keystroke) the SAME array is returned, nothing is allocated.
|
|
80
|
+
* @param {DeltaOp[]} delta
|
|
81
|
+
* @returns {DeltaOp[]}
|
|
82
|
+
*/
|
|
83
|
+
export function normalizeDelta(delta) {
|
|
84
|
+
const n = delta.length;
|
|
85
|
+
// First pass: is there anything to do?
|
|
86
|
+
let canonical = true;
|
|
87
|
+
for (let i = 0; i < n && canonical; i++) {
|
|
88
|
+
const op = delta[i];
|
|
89
|
+
if (typeof op.insert !== 'string') continue;
|
|
90
|
+
if (op.insert === '' || isDirty(op.attributes)) { canonical = false; break; }
|
|
91
|
+
const next = delta[i + 1];
|
|
92
|
+
if (next && typeof next.insert === 'string' && sameAttributes(op.attributes, next.attributes)) canonical = false;
|
|
93
|
+
}
|
|
94
|
+
if (canonical) return delta;
|
|
95
|
+
|
|
96
|
+
/** @type {DeltaOp[]} */
|
|
97
|
+
const out = [];
|
|
98
|
+
/** @type {DeltaOp | null} */
|
|
99
|
+
let last = null; // the run being built (a copy, never an op of the input)
|
|
100
|
+
for (const op of delta) {
|
|
101
|
+
if (typeof op.insert !== 'string') { out.push(op); last = null; continue; }
|
|
102
|
+
if (op.insert === '') continue;
|
|
103
|
+
const attrs = effective(op.attributes);
|
|
104
|
+
if (last && sameAttributes(/** @type {any} */ (last.attributes), attrs)) {
|
|
105
|
+
last.insert = /** @type {string} */ (last.insert) + op.insert;
|
|
106
|
+
continue;
|
|
107
|
+
}
|
|
108
|
+
last = attrs ? { insert: op.insert, attributes: attrs } : { insert: op.insert };
|
|
109
|
+
out.push(last);
|
|
110
|
+
}
|
|
111
|
+
return out;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* The canonical delta of a Loro text: the only way the engine reads `toDelta()`.
|
|
116
|
+
* @param {{ toDelta: () => DeltaOp[] }} container
|
|
117
|
+
* @returns {DeltaOp[]}
|
|
118
|
+
*/
|
|
119
|
+
export function readDelta(container) {
|
|
120
|
+
return normalizeDelta(container.toDelta());
|
|
121
|
+
}
|
package/dist/utils/tab.js
CHANGED