@aionbuilders/nabu 0.1.0 → 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 +44 -23
- 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 +23 -26
- package/dist/behaviors/text/text.behavior.svelte.js +46 -61
- 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 +2 -2
- package/dist/blocks/list/to-list.js +2 -1
- package/dist/blocks/nabu.svelte.d.ts +7 -0
- package/dist/blocks/nabu.svelte.js +26 -12
- package/dist/blocks/region/actions.js +2 -1
- package/dist/blocks/region/region.svelte.d.ts +2 -2
- package/dist/blocks/region/region.svelte.js +3 -2
- package/dist/blocks/text-block.svelte.d.ts +2 -2
- package/dist/blocks/toggle/toggle.svelte.d.ts +2 -2
- package/dist/ui/slash-menu.svelte.js +2 -1
- package/dist/utils/composition.d.ts +28 -0
- package/dist/utils/composition.js +51 -0
- package/dist/utils/delta.d.ts +27 -0
- package/dist/utils/delta.js +121 -0
- package/dist/utils/selection.svelte.d.ts +1 -1
- package/dist/utils/tab.js +1 -0
- package/dist/utils/words.d.ts +35 -0
- package/dist/utils/words.js +85 -0
- package/package.json +3 -1
|
@@ -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();
|
|
@@ -77,12 +77,12 @@ export class ListItem extends MegaBlock {
|
|
|
77
77
|
*/
|
|
78
78
|
toggleChecked(): void;
|
|
79
79
|
get text(): string;
|
|
80
|
-
get delta(): import("
|
|
80
|
+
get delta(): import("../../utils/delta.js").DeltaOp[];
|
|
81
81
|
selection: {
|
|
82
82
|
from: number;
|
|
83
83
|
to: number;
|
|
84
84
|
isCollapsed: boolean;
|
|
85
|
-
direction: "
|
|
85
|
+
direction: "backward" | "forward" | "none";
|
|
86
86
|
} | null;
|
|
87
87
|
/** Every sublist, in order: an item may hold several, of different types (`a > [ul[…], ol[…], ul[…]]`). */
|
|
88
88
|
sublists: Block[];
|
|
@@ -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,8 @@ 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';
|
|
22
|
+
import { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
|
|
21
23
|
import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
|
|
22
24
|
|
|
23
25
|
|
|
@@ -82,22 +84,14 @@ import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPositio
|
|
|
82
84
|
*/
|
|
83
85
|
|
|
84
86
|
/**
|
|
85
|
-
* Whether the
|
|
86
|
-
*
|
|
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.
|
|
87
90
|
* @param {any} behavior @param {number} pos @param {string} name
|
|
88
91
|
* @returns {boolean}
|
|
89
92
|
*/
|
|
90
93
|
function inheritedMarkAt(behavior, pos, name) {
|
|
91
|
-
|
|
92
|
-
const delta = behavior.delta;
|
|
93
|
-
let offset = 0;
|
|
94
|
-
for (const op of delta) {
|
|
95
|
-
if (typeof op.insert !== 'string') continue;
|
|
96
|
-
const end = offset + op.insert.length;
|
|
97
|
-
if (pos <= end) return !!(op.attributes && op.attributes[name]);
|
|
98
|
-
offset = end;
|
|
99
|
-
}
|
|
100
|
-
return false;
|
|
94
|
+
return markAtCaret(behavior.delta, pos, name) !== undefined;
|
|
101
95
|
}
|
|
102
96
|
|
|
103
97
|
/**
|
|
@@ -190,6 +184,8 @@ export class Nabu {
|
|
|
190
184
|
* @type {import('./undo-selection.js').Endpoint | null}
|
|
191
185
|
*/
|
|
192
186
|
#compositionAnchor = null;
|
|
187
|
+
/** Empty blocks before the composing one, their "\n" placeholder swapped for a `<br>` meanwhile (Chromium offset drift, issue #6). @type {Array<{ br: Element, text: Text }>} */
|
|
188
|
+
#swappedEmpties = [];
|
|
193
189
|
/** The block a composition runs in, reactive: its placeholder is hidden meanwhile (P-103). @type {Block | null} */
|
|
194
190
|
#composingBlock = $state.raw(null);
|
|
195
191
|
/**
|
|
@@ -630,6 +626,14 @@ export class Nabu {
|
|
|
630
626
|
/** An Escape nobody consumed was the previous key: the next Tab / Shift+Tab leaves the editor (see `utils/tab.js`). */
|
|
631
627
|
#tabEscaped = false;
|
|
632
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
|
+
|
|
633
637
|
/** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
|
|
634
638
|
rearmTab() { this.#tabEscaped = false; }
|
|
635
639
|
|
|
@@ -1395,6 +1399,8 @@ export class Nabu {
|
|
|
1395
1399
|
this.#compositionStartOffset = sel?.from ?? 0;
|
|
1396
1400
|
this.#compositionAnchor = behavior ? makeEndpoint(anchor, sel?.from ?? 0, 'end') : null;
|
|
1397
1401
|
this.#composingBlock = anchor;
|
|
1402
|
+
restoreEmptyBlocks(this.#swappedEmpties); // (a composition that never ended)
|
|
1403
|
+
this.#swappedEmpties = swapEmptyBlocks(anchor.element);
|
|
1398
1404
|
/** @type {any} */ (behavior)?.snapshotForComposition?.();
|
|
1399
1405
|
}
|
|
1400
1406
|
|
|
@@ -1441,6 +1447,8 @@ export class Nabu {
|
|
|
1441
1447
|
const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
|
|
1442
1448
|
const composedBlock = this.#compositionStartBlock;
|
|
1443
1449
|
this.#composingBlock = null;
|
|
1450
|
+
restoreEmptyBlocks(this.#swappedEmpties);
|
|
1451
|
+
this.#swappedEmpties = [];
|
|
1444
1452
|
/** @type {any} */ (composedIn)?.restoreAfterComposition?.(e.data || ''); // before the model catches up: no duplicate of the composed text
|
|
1445
1453
|
try {
|
|
1446
1454
|
this.#syncComposition(e);
|
|
@@ -1498,11 +1506,14 @@ export class Nabu {
|
|
|
1498
1506
|
handleKeydown(e) {
|
|
1499
1507
|
// Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
|
|
1500
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;
|
|
1501
1511
|
this.selection.sync(); // no-op when the document capture listener already synced
|
|
1502
1512
|
this.selection.normalize();
|
|
1503
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.
|
|
1504
1514
|
const escaped = this.#tabEscaped;
|
|
1505
1515
|
if (!isModifierKey(e)) this.#tabEscaped = false;
|
|
1516
|
+
this.tabWayOut = escaped && e.key === 'Tab';
|
|
1506
1517
|
// Commands first (ADR 017): undo / redo and every declared shortcut. What no command handles falls through to the
|
|
1507
1518
|
// legacy `onKeyDown` hooks and the block's own keydown, then to the native behavior.
|
|
1508
1519
|
if (this.commands.handleKeydown(e)) return;
|
|
@@ -1883,6 +1894,9 @@ export class Nabu {
|
|
|
1883
1894
|
const behavior = block.behaviors?.get('text');
|
|
1884
1895
|
const sel = offset === undefined ? behavior?.selection : { from: offset, to: offset };
|
|
1885
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');
|
|
1886
1900
|
const from = Math.min(sel.from, sel.to);
|
|
1887
1901
|
const to = Math.max(sel.from, sel.to);
|
|
1888
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,12 +120,12 @@ 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;
|
|
127
127
|
isCollapsed: boolean;
|
|
128
|
-
direction: "
|
|
128
|
+
direction: "backward" | "forward" | "none";
|
|
129
129
|
} | null;
|
|
130
130
|
/** @type {number} */
|
|
131
131
|
weight: 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
|
/**
|