@aionbuilders/nabu 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +27 -0
- package/README.md +7 -1
- 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 +30 -7
- package/dist/blocks/callout/callout.svelte.js +2 -2
- 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 +121 -24
- package/dist/blocks/code/indent.d.ts +61 -0
- package/dist/blocks/code/indent.js +91 -0
- package/dist/blocks/heading/heading.svelte.js +2 -2
- 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/list-item.svelte.js +2 -2
- package/dist/blocks/list/list.behavior.svelte.js +2 -2
- package/dist/blocks/list/to-list.js +2 -1
- package/dist/blocks/media/media-block.svelte.js +2 -2
- package/dist/blocks/nabu.svelte.d.ts +53 -0
- package/dist/blocks/nabu.svelte.js +101 -33
- 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 +4 -3
- package/dist/blocks/selection.svelte.d.ts +2 -1
- package/dist/blocks/selection.svelte.js +29 -5
- package/dist/blocks/text-block.svelte.d.ts +1 -1
- package/dist/blocks/toggle/toggle.svelte.d.ts +1 -1
- package/dist/blocks/toggle/toggle.svelte.js +2 -2
- package/dist/files/files.svelte.js +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/selection.svelte.d.ts +5 -0
- package/dist/utils/selection.svelte.js +15 -2
- package/dist/utils/tab.js +1 -0
- package/dist/vite.d.ts +8 -0
- package/dist/vite.js +15 -2
- package/package.json +1 -1
|
@@ -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
|
/**
|
|
@@ -258,30 +251,16 @@ export class Nabu {
|
|
|
258
251
|
this.tree = /** @type {LoroTree<NabuNodeData>} */ (this.doc.getTree("blocks"));
|
|
259
252
|
this.content = this.doc.getMap("content");
|
|
260
253
|
|
|
261
|
-
// Initialize Undo/Redo Manager
|
|
254
|
+
// Initialize Undo/Redo Manager. Loro keeps the two callbacks for as long as the manager lives and has no way to drop
|
|
255
|
+
// them: they reach the engine through `holder`, which `destroy()` clears (else the engine could never be collected).
|
|
256
|
+
const holder = { owner: /** @type {Nabu | null} */ (this) };
|
|
257
|
+
this.track(() => { holder.owner = null; });
|
|
262
258
|
this.undoManager = new UndoManager(this.doc, {
|
|
263
259
|
maxUndoSteps: 100,
|
|
264
260
|
// Background completions (e.g. a pasted file finishing its upload) are not undo steps of their own.
|
|
265
261
|
excludeOriginPrefixes: ['nabu:silent'],
|
|
266
262
|
mergeInterval: this.#mergeInterval,
|
|
267
|
-
|
|
268
|
-
if (this.#isolatedSteps > 0) this.#isolatedSteps--;
|
|
269
|
-
// The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
|
|
270
|
-
// (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
|
|
271
|
-
// an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
|
|
272
|
-
const explicit = this.#undoCursor;
|
|
273
|
-
this.#undoCursor = null;
|
|
274
|
-
const ended = !isUndo && this.#undoneEnd !== null ? this.#actionEnds.get(this.#undoneEnd) : undefined;
|
|
275
|
-
const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? this.#undoSel) ?? legacySelection(this);
|
|
276
|
-
this.#endKey = isUndo ? range?.end ?? null : null;
|
|
277
|
-
return { value: /** @type {any} */ (stored), cursors: [] };
|
|
278
|
-
},
|
|
279
|
-
onPop: (isUndo, storedValue, range) => {
|
|
280
|
-
this.#undoneEnd = isUndo ? range?.end ?? null : null;
|
|
281
|
-
this.#endKey = null;
|
|
282
|
-
const value = /** @type {any} */ (storedValue?.value);
|
|
283
|
-
if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(this, value);
|
|
284
|
-
}
|
|
263
|
+
...Nabu.#undoCallbacks(holder),
|
|
285
264
|
});
|
|
286
265
|
|
|
287
266
|
/**
|
|
@@ -401,7 +380,7 @@ export class Nabu {
|
|
|
401
380
|
// One event batch = one refresh. The affected containers are COLLECTED while the batch is read, then each is refreshed
|
|
402
381
|
// once (the root list at most once, every parent at most once): refreshing per action made an import / a mass undo / a
|
|
403
382
|
// big paste quadratic (P-104). The doc already holds the final state of the batch, so the order of the actions is moot.
|
|
404
|
-
this.tree.subscribe((event) => {
|
|
383
|
+
this.track(this.tree.subscribe((event) => {
|
|
405
384
|
let rootsDirty = false;
|
|
406
385
|
/** @type {Set<string>} */
|
|
407
386
|
const parents = new Set();
|
|
@@ -447,7 +426,7 @@ export class Nabu {
|
|
|
447
426
|
// A block retyped into a leaf (no children) in the same transaction has no updateChildren().
|
|
448
427
|
/** @type {{ updateChildren?: (retyped?: Set<string>) => void } | undefined} */ (this.blocks.get(parentId))?.updateChildren?.(retyped);
|
|
449
428
|
}
|
|
450
|
-
});
|
|
429
|
+
}));
|
|
451
430
|
|
|
452
431
|
this.init();
|
|
453
432
|
}
|
|
@@ -633,6 +612,14 @@ export class Nabu {
|
|
|
633
612
|
/** An Escape nobody consumed was the previous key: the next Tab / Shift+Tab leaves the editor (see `utils/tab.js`). */
|
|
634
613
|
#tabEscaped = false;
|
|
635
614
|
|
|
615
|
+
/**
|
|
616
|
+
* 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
|
|
617
|
+
* 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).
|
|
618
|
+
* Plain property, not state: only meaningful during `handleKeydown`.
|
|
619
|
+
* @type {boolean}
|
|
620
|
+
*/
|
|
621
|
+
tabWayOut = false;
|
|
622
|
+
|
|
636
623
|
/** Close the Escape-then-Tab way out (any other key, a click, the focus leaving). */
|
|
637
624
|
rearmTab() { this.#tabEscaped = false; }
|
|
638
625
|
|
|
@@ -1505,11 +1492,14 @@ export class Nabu {
|
|
|
1505
1492
|
handleKeydown(e) {
|
|
1506
1493
|
// Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
|
|
1507
1494
|
if (this.#readonly) return;
|
|
1495
|
+
// Tab on a control of the editor's own UI (the language select of a code block…) is the browser's: it moves the focus on.
|
|
1496
|
+
if (e.key === 'Tab' && e.target instanceof Element && e.target.closest('[data-nabu-ui]')) return;
|
|
1508
1497
|
this.selection.sync(); // no-op when the document capture listener already synced
|
|
1509
1498
|
this.selection.normalize();
|
|
1510
1499
|
// 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
1500
|
const escaped = this.#tabEscaped;
|
|
1512
1501
|
if (!isModifierKey(e)) this.#tabEscaped = false;
|
|
1502
|
+
this.tabWayOut = escaped && e.key === 'Tab';
|
|
1513
1503
|
// Commands first (ADR 017): undo / redo and every declared shortcut. What no command handles falls through to the
|
|
1514
1504
|
// legacy `onKeyDown` hooks and the block's own keydown, then to the native behavior.
|
|
1515
1505
|
if (this.commands.handleKeydown(e)) return;
|
|
@@ -1890,6 +1880,9 @@ export class Nabu {
|
|
|
1890
1880
|
const behavior = block.behaviors?.get('text');
|
|
1891
1881
|
const sel = offset === undefined ? behavior?.selection : { from: offset, to: offset };
|
|
1892
1882
|
if (!behavior || !sel) return;
|
|
1883
|
+
// Line endings are "\n" in the model, whatever the source (Windows "\r\n", old Mac "\r"): a "\r" would be a character
|
|
1884
|
+
// of the text that no line shows, and would leak into the exports.
|
|
1885
|
+
text = text.replace(/\r\n?/g, '\n');
|
|
1893
1886
|
const from = Math.min(sel.from, sel.to);
|
|
1894
1887
|
const to = Math.max(sel.from, sel.to);
|
|
1895
1888
|
if (to > from) behavior.delete({ index: from, length: to - from });
|
|
@@ -2573,6 +2566,81 @@ export class Nabu {
|
|
|
2573
2566
|
});
|
|
2574
2567
|
}
|
|
2575
2568
|
|
|
2569
|
+
/**
|
|
2570
|
+
* The `onPush` / `onPop` of the undo manager. Built HERE, out of the constructor, so that they close over `holder` and nothing
|
|
2571
|
+
* else: a closure made in the constructor would keep the constructor's scope, and `this` with it, alive.
|
|
2572
|
+
* @param {{ owner: Nabu | null }} holder
|
|
2573
|
+
*/
|
|
2574
|
+
static #undoCallbacks(holder) {
|
|
2575
|
+
return {
|
|
2576
|
+
/** @param {boolean} isUndo @param {{ end?: any } | undefined} range */
|
|
2577
|
+
onPush: (isUndo, range) => {
|
|
2578
|
+
const self = holder.owner;
|
|
2579
|
+
if (!self) return { value: null, cursors: [] };
|
|
2580
|
+
if (self.#isolatedSteps > 0) self.#isolatedSteps--;
|
|
2581
|
+
// The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
|
|
2582
|
+
// (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
|
|
2583
|
+
// an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
|
|
2584
|
+
const explicit = self.#undoCursor;
|
|
2585
|
+
self.#undoCursor = null;
|
|
2586
|
+
const ended = !isUndo && self.#undoneEnd !== null ? self.#actionEnds.get(self.#undoneEnd) : undefined;
|
|
2587
|
+
const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? self.#undoSel) ?? legacySelection(self);
|
|
2588
|
+
self.#endKey = isUndo ? range?.end ?? null : null;
|
|
2589
|
+
return { value: /** @type {any} */ (stored), cursors: [] };
|
|
2590
|
+
},
|
|
2591
|
+
/** @param {boolean} isUndo @param {any} storedValue @param {{ end?: any } | undefined} range */
|
|
2592
|
+
onPop: (isUndo, storedValue, range) => {
|
|
2593
|
+
const self = holder.owner;
|
|
2594
|
+
if (!self) return;
|
|
2595
|
+
self.#undoneEnd = isUndo ? range?.end ?? null : null;
|
|
2596
|
+
self.#endKey = null;
|
|
2597
|
+
const value = /** @type {any} */ (storedValue?.value);
|
|
2598
|
+
if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(self, value);
|
|
2599
|
+
},
|
|
2600
|
+
};
|
|
2601
|
+
}
|
|
2602
|
+
|
|
2603
|
+
/** What `destroy()` calls: the unsubscribe functions given to {@link Nabu#track}. @type {Set<() => void>} */
|
|
2604
|
+
#tracked = new Set();
|
|
2605
|
+
|
|
2606
|
+
/**
|
|
2607
|
+
* Hand over a Loro subscription (or any cleanup) that lives as long as the engine: `destroy()` calls it, once. A block or an
|
|
2608
|
+
* extension passes its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback (and what it closes over, the engine
|
|
2609
|
+
* with it) until it is unsubscribed, so one that is not tracked keeps the engine in memory after `destroy()`.
|
|
2610
|
+
* @template {() => void} T
|
|
2611
|
+
* @param {T} unsubscribe
|
|
2612
|
+
* @returns {T} what it was given
|
|
2613
|
+
* @public
|
|
2614
|
+
*/
|
|
2615
|
+
track(unsubscribe) {
|
|
2616
|
+
this.#tracked.add(unsubscribe);
|
|
2617
|
+
return unsubscribe;
|
|
2618
|
+
}
|
|
2619
|
+
|
|
2620
|
+
/**
|
|
2621
|
+
* Release the engine for good, for a host that is done with it: the memory, not only the page. Unmounting `<NabuEditor>`
|
|
2622
|
+
* releases the page listeners but not the memory (the engine can be mounted again); `destroy()` releases the memory: it
|
|
2623
|
+
* unsubscribes the engine and its blocks from the document (see {@link Nabu#track}), stops the subsystems, closes `persistence`
|
|
2624
|
+
* if the engine is persisted, releases the files (upload retries) and stops the selection tracking, so that the engine can be
|
|
2625
|
+
* garbage collected. Idempotent. Call it after `unmount()` or instead of it (e.g. `onDestroy(() => engine.destroy())`).
|
|
2626
|
+
*
|
|
2627
|
+
* Changes that are not saved yet are DROPPED, not written: `persistence.dispose()` cancels the pending autosave and removes the
|
|
2628
|
+
* `pagehide` flush. Await `saveNow()` first when they matter.
|
|
2629
|
+
*
|
|
2630
|
+
* The document stays in memory and readable as it was (`serialize()`, `doc`), but the engine no longer follows changes: no more
|
|
2631
|
+
* edits. A destroyed engine must not be mounted again.
|
|
2632
|
+
* @returns {void}
|
|
2633
|
+
* @public
|
|
2634
|
+
*/
|
|
2635
|
+
destroy() {
|
|
2636
|
+
for (const stop of this.#tracked) stop();
|
|
2637
|
+
this.#tracked.clear();
|
|
2638
|
+
for (const system of this.systems.values()) system.stop?.();
|
|
2639
|
+
/** @type {any} */ (this).persistence?.dispose?.();
|
|
2640
|
+
/** @type {any} */ (this.systems.get('files'))?.dispose?.();
|
|
2641
|
+
this.selection.destroy();
|
|
2642
|
+
}
|
|
2643
|
+
|
|
2576
2644
|
/**
|
|
2577
2645
|
* Log a diagnostic to the console when `debugging` is on. Silent otherwise.
|
|
2578
2646
|
* @param {...any} args
|
|
@@ -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";
|
|
@@ -108,7 +109,7 @@ export class RegionBlock extends MegaBlock {
|
|
|
108
109
|
|
|
109
110
|
this.#read();
|
|
110
111
|
// Local commits, imports and remote peers all end up here (the `fields` map is a child container of `data`).
|
|
111
|
-
node.data.subscribe(() => this.#read());
|
|
112
|
+
nabu.track(node.data.subscribe(() => this.#read()));
|
|
112
113
|
|
|
113
114
|
// Document export: exact round trip (`importJSON` reads `props` and `content` back, see RegionBlock.create).
|
|
114
115
|
this.serializers.set('json', () => ({
|
|
@@ -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
|
/**
|
|
@@ -16,7 +16,8 @@ export class NabuSelection extends SvelteSelection {
|
|
|
16
16
|
root: HTMLElement | null;
|
|
17
17
|
/**
|
|
18
18
|
* Declare the element that renders this engine (the `[data-nabu-root]` div). Returns the function that detaches it (only
|
|
19
|
-
* clears the reference when it is still this element: a remount may already have set the next one).
|
|
19
|
+
* clears the reference when it is still this element: a remount may already have set the next one). The page listeners
|
|
20
|
+
* (`connected`) exist only while a root is attached: an engine with no editor mounted holds nothing on the document.
|
|
20
21
|
* @param {HTMLElement} el
|
|
21
22
|
* @returns {() => void}
|
|
22
23
|
*/
|
|
@@ -36,13 +36,15 @@ export class NabuSelection extends SvelteSelection {
|
|
|
36
36
|
|
|
37
37
|
/**
|
|
38
38
|
* Declare the element that renders this engine (the `[data-nabu-root]` div). Returns the function that detaches it (only
|
|
39
|
-
* clears the reference when it is still this element: a remount may already have set the next one).
|
|
39
|
+
* clears the reference when it is still this element: a remount may already have set the next one). The page listeners
|
|
40
|
+
* (`connected`) exist only while a root is attached: an engine with no editor mounted holds nothing on the document.
|
|
40
41
|
* @param {HTMLElement} el
|
|
41
42
|
* @returns {() => void}
|
|
42
43
|
*/
|
|
43
44
|
attachRoot(el) {
|
|
44
45
|
this.root = el;
|
|
45
|
-
|
|
46
|
+
this.connected = true;
|
|
47
|
+
return () => { if (this.root === el) { this.root = null; this.connected = false; } };
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
/**
|
|
@@ -102,6 +104,7 @@ export class NabuSelection extends SvelteSelection {
|
|
|
102
104
|
constructor(nabu) {
|
|
103
105
|
super();
|
|
104
106
|
this.nabu = nabu;
|
|
107
|
+
this.connected = false; // no root yet: `attachRoot` turns the page listeners on
|
|
105
108
|
|
|
106
109
|
// Every caret the editor itself places (after an action, an undo…) is remembered for undo / redo (ADR 015): it is
|
|
107
110
|
// where that action ended. `setBaseAndExtent` is an own-property arrow function of the base class: wrap it.
|
|
@@ -114,7 +117,7 @@ export class NabuSelection extends SvelteSelection {
|
|
|
114
117
|
return done;
|
|
115
118
|
};
|
|
116
119
|
|
|
117
|
-
$effect.root(() => {
|
|
120
|
+
this.#stop = $effect.root(() => {
|
|
118
121
|
$effect(() => {
|
|
119
122
|
if (this.blocks) {
|
|
120
123
|
this.previous.forEach(block => block.clearSelection());
|
|
@@ -134,6 +137,7 @@ export class NabuSelection extends SvelteSelection {
|
|
|
134
137
|
// This is the only reliable source of direction — DOM position comparisons
|
|
135
138
|
// break when anchorNode is an ancestor of the previous position.
|
|
136
139
|
$effect(() => {
|
|
140
|
+
if (!this.connected) return;
|
|
137
141
|
/** @param {KeyboardEvent} e */
|
|
138
142
|
const onKeydown = (e) => {
|
|
139
143
|
// Capture phase on document = runs before every other keydown handler
|
|
@@ -233,8 +237,22 @@ export class NabuSelection extends SvelteSelection {
|
|
|
233
237
|
});
|
|
234
238
|
});
|
|
235
239
|
});
|
|
240
|
+
|
|
241
|
+
// Stop for good (`Nabu#destroy`): both effect roots (this one and the base class's), and the pending repair.
|
|
242
|
+
const stopBase = this.destroy;
|
|
243
|
+
this.destroy = () => {
|
|
244
|
+
this.#stop?.();
|
|
245
|
+
this.#stop = null;
|
|
246
|
+
if (this.#repairTimer !== null) clearTimeout(this.#repairTimer);
|
|
247
|
+
this.#repairTimer = null;
|
|
248
|
+
this.root = null;
|
|
249
|
+
stopBase();
|
|
250
|
+
};
|
|
236
251
|
}
|
|
237
252
|
|
|
253
|
+
/** Stops this class's effect root (see `destroy`). @type {(() => void) | null} */
|
|
254
|
+
#stop = null;
|
|
255
|
+
|
|
238
256
|
/**
|
|
239
257
|
* Move a caret / focus that sits on a NON-TEXT position to the nearest valid text position, in the
|
|
240
258
|
* direction of travel (arrow keys; a heuristic otherwise): inert blocks (dividers, images…), element
|
|
@@ -327,8 +345,14 @@ export class NabuSelection extends SvelteSelection {
|
|
|
327
345
|
}
|
|
328
346
|
|
|
329
347
|
if (anchorInvalid) {
|
|
330
|
-
|
|
331
|
-
|
|
348
|
+
let dir = explicit ?? offsetHeuristic(anchor, anchorOffset);
|
|
349
|
+
let target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
|
|
350
|
+
// No arrow key, a collapsed caret, and nothing in the guessed direction: Firefox puts the caret on (root, 0) after a Tab
|
|
351
|
+
// or `root.focus()`, a caret past the last child is the mirror case. Typing there is lost, so land on the other side.
|
|
352
|
+
if (!target && !explicit && live.isCollapsed) {
|
|
353
|
+
dir = dir === 'forward' ? 'backward' : 'forward';
|
|
354
|
+
target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
|
|
355
|
+
}
|
|
332
356
|
if (!target) {
|
|
333
357
|
// Leaving the document by keyboard with nothing to land on: the document must offer a caret there.
|
|
334
358
|
if (explicit === 'forward') this.nabu.openTrailingCaret();
|
|
@@ -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;
|
|
@@ -29,10 +29,10 @@ export class ToggleBlock extends MegaBlock {
|
|
|
29
29
|
// Initialize collapsed from Loro metadata
|
|
30
30
|
this.collapsed = !!data.get('collapsed');
|
|
31
31
|
// Subscribe to data changes to keep collapsed in sync (a change of the document wins over the read-only view state)
|
|
32
|
-
this.node.data.subscribe(() => {
|
|
32
|
+
this.nabu.track(this.node.data.subscribe(() => {
|
|
33
33
|
this.#viewState = null;
|
|
34
34
|
this.collapsed = !!this.node.data.get('collapsed');
|
|
35
|
-
});
|
|
35
|
+
}));
|
|
36
36
|
|
|
37
37
|
this.serializers.set('markdown', () => toggleMarkdown(this.#stored, this.behavior.toMarkdown(), /** @type {any} */ (this.children.map(c => c.serialize('markdown')))));
|
|
38
38
|
this.serializers.set('json', () => ({
|
|
@@ -130,7 +130,7 @@ export class Files {
|
|
|
130
130
|
forgetMissing: () => { for (const [key, value] of this.#urls) if (value === null) this.#urls.delete(key); },
|
|
131
131
|
track: (promise) => this.#track(promise),
|
|
132
132
|
});
|
|
133
|
-
nabu.doc.subscribe((event) => this.#uploads.onDocEvent(event));
|
|
133
|
+
nabu.track(nabu.doc.subscribe((event) => this.#uploads.onDocEvent(event)));
|
|
134
134
|
if (this.assets.size > 0) this.#track(this.#migrate());
|
|
135
135
|
this.#preload();
|
|
136
136
|
}
|
|
@@ -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
|
+
}
|
|
@@ -23,6 +23,11 @@
|
|
|
23
23
|
* // Utiliser selection.text, selection.isCollapsed, etc. dans vos composants
|
|
24
24
|
*/
|
|
25
25
|
export class SvelteSelection {
|
|
26
|
+
/**
|
|
27
|
+
* Whether the wrapper listens to the page (`selectionchange` on the document). On by default; a subclass tied to a part of the
|
|
28
|
+
* page turns it off while it has none, so that an unmounted owner leaves nothing behind. Reactive.
|
|
29
|
+
*/
|
|
30
|
+
connected: boolean;
|
|
26
31
|
/** @type {Selection?} */
|
|
27
32
|
raw: Selection | null;
|
|
28
33
|
/** @public */
|
|
@@ -33,13 +33,19 @@ export class SvelteSelection {
|
|
|
33
33
|
if (typeof window === 'undefined' || !window.getSelection) {
|
|
34
34
|
return;
|
|
35
35
|
}
|
|
36
|
-
|
|
36
|
+
|
|
37
|
+
// Disconnected: no listener on the page, and nothing mirrored (the wrapper would keep removed DOM nodes alive).
|
|
38
|
+
if (!this.connected) {
|
|
39
|
+
this.#sel = null;
|
|
40
|
+
this.#ranges = [];
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
43
|
+
|
|
37
44
|
document.addEventListener('selectionchange', this.#updateSelection);
|
|
38
45
|
this.#updateSelection();
|
|
39
46
|
|
|
40
47
|
return () => {
|
|
41
48
|
document.removeEventListener('selectionchange', this.#updateSelection);
|
|
42
|
-
this.#cleanup?.();
|
|
43
49
|
};
|
|
44
50
|
});
|
|
45
51
|
});
|
|
@@ -47,6 +53,12 @@ export class SvelteSelection {
|
|
|
47
53
|
|
|
48
54
|
/** @type {Function?} */
|
|
49
55
|
#cleanup = null;
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* Whether the wrapper listens to the page (`selectionchange` on the document). On by default; a subclass tied to a part of the
|
|
59
|
+
* page turns it off while it has none, so that an unmounted owner leaves nothing behind. Reactive.
|
|
60
|
+
*/
|
|
61
|
+
connected = $state(true);
|
|
50
62
|
|
|
51
63
|
/** @type {Selection?} */
|
|
52
64
|
raw = null;
|
|
@@ -649,6 +661,7 @@ export class SvelteSelection {
|
|
|
649
661
|
destroy = () => {
|
|
650
662
|
this.unobserveAll();
|
|
651
663
|
this.#cleanup?.();
|
|
664
|
+
this.#cleanup = null;
|
|
652
665
|
this.raw = null;
|
|
653
666
|
this.#sel = null;
|
|
654
667
|
this.#ranges = [];
|
package/dist/utils/tab.js
CHANGED
package/dist/vite.d.ts
CHANGED
|
@@ -16,6 +16,14 @@
|
|
|
16
16
|
* natively, so no `vite-plugin-top-level-await` transform is needed (that
|
|
17
17
|
* plugin is incompatible with Vite 8 / Rolldown).
|
|
18
18
|
*
|
|
19
|
+
* It also adds `loro-crdt` to `ssr.external`, so that a server-rendered page
|
|
20
|
+
* (SvelteKit) loads loro-crdt's Node build from `node_modules` at run time.
|
|
21
|
+
* Bundled into the SSR output, that build fails with
|
|
22
|
+
* `Cannot find module './snippets/loro-wasm-…/inline0.js'`. It is left alone
|
|
23
|
+
* when `ssr.external` is `true` (everything is already external). `noExternal`
|
|
24
|
+
* is no reason to skip it: SvelteKit sets `ssr.noExternal: true` on every build,
|
|
25
|
+
* and an entry of `ssr.external` still wins over it.
|
|
26
|
+
*
|
|
19
27
|
* @returns {Promise<import('vite').Plugin[]>}
|
|
20
28
|
*/
|
|
21
29
|
export function nabu(): Promise<import("vite").Plugin[]>;
|