@aionbuilders/nabu 0.1.2 → 0.1.4

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 CHANGED
@@ -4,6 +4,27 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
+ ## 0.1.4 (2026-11-04)
8
+
9
+ The caret stays on screen. No API change.
10
+
11
+ ### Fixed
12
+ - **The caret could leave the visible area while typing.** Nabu cancels the native edits and renders from the model, so the browser no longer scrolled to the caret: after 20 Enter in a 220 px scroller it was 565 px below the visible area, on the plainest setup. Every scrollable ancestor and the window now follow it after an edit the user made, by the least amount, within the visual viewport when there is one. A host keeps it clear of its own sticky UI with `scroll-padding`. Nothing scrolls for a key that changed nothing (Ctrl+C, a modifier, Escape) or for a programmatic or remote change. Covered by `tests/e2e/caret-reveal.spec.ts`, and checked on Firefox, WebKit, Chromium and emulated phones through a packed build. A real virtual keyboard is not verified yet.
13
+
14
+ ## 0.1.3 (2026-11-04)
15
+
16
+ Fixes found by testing the published package in a real SvelteKit app: the first thing a consumer's build, a Firefox user and a page that mounts editors on demand would hit. The API only gains two methods.
17
+
18
+ ### Added
19
+ - **`engine.destroy()`** releases an engine for good, memory included: it unsubscribes the engine and its blocks from the document, stops the subsystems, closes the persistence and the upload retries, and the engine can then be garbage collected. Idempotent. The document stays readable (`serialize()`), the engine no longer follows changes, and it must not be mounted again. Changes that are not saved yet are dropped: await `saveNow()` first when they matter.
20
+ - **`engine.track(unsubscribe)`** hands a Loro subscription or any cleanup over to `destroy()`. A custom block should pass its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback until it is unsubscribed, so an untracked one keeps the engine in memory.
21
+
22
+ ### Fixed
23
+ - **`vite build` failed on a server-rendered page that imports Nabu**, with `Cannot find module './snippets/loro-wasm-…/inline0.js'`. The `nabu()` helper now keeps `loro-crdt` out of the SSR bundle (`ssr.external`). With pnpm, whose strict `node_modules` hides it from your app, also run `pnpm add loro-crdt`.
24
+ - **Firefox lost everything typed after Tab or `element.focus()`.** Firefox leaves the caret on the editor root, and the correction looked for text before the start of the document, found none and gave up. Such a caret now lands on the nearest text in either direction. Covered by `tests/e2e/dead-root-caret.spec.ts`, and checked on real Firefox, WebKit and Chromium through a packed build.
25
+ - **Every unmounted editor left 5 listeners on `document`.** They now exist only while an editor is mounted: unmounting is enough to release the page, and the same engine can be mounted again. Covered by `tests/e2e/lifecycle.spec.ts`, which counts the listeners and checks through the garbage collector that a destroyed engine is really gone.
26
+ - **A flaky documentation test.** The walkthrough of `docs/recipes/autosave-to-your-server.md` raced its own 10 ms timer under load.
27
+
7
28
  ## 0.1.2 (2026-10-29)
8
29
 
9
30
  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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ bun add @aionbuilders/nabu
26
26
  ### Requirements
27
27
 
28
28
  - **Svelte 5.20 or newer**.
29
- - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'`. The bundled helper does both:
29
+ - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'` (and, for server rendering, `loro-crdt` kept out of the SSR bundle). The bundled helper does all three:
30
30
 
31
31
  ```js
32
32
  // vite.config.js
@@ -201,11 +201,11 @@ export class TextBehavior {
201
201
  this.text = $state(this.container.toString());
202
202
  /** @public */
203
203
  this.delta = $state(readDelta(this.container));
204
- this.container.subscribe(() => {
204
+ this.nabu.track(this.container.subscribe(() => {
205
205
  this.text = this.container.toString();
206
206
  this.delta = readDelta(this.container);
207
207
  this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
208
- });
208
+ }));
209
209
  }
210
210
 
211
211
  /** @public */
@@ -40,9 +40,9 @@ export class CalloutBlock extends TextBlock {
40
40
  );
41
41
 
42
42
  // Sync variant from Loro data changes (mirrors Heading's level sync)
43
- this.node.data.subscribe(() => {
43
+ this.nabu.track(this.node.data.subscribe(() => {
44
44
  this.variant = this.node.data.get('variant') || 'note';
45
- });
45
+ }));
46
46
  }
47
47
 
48
48
  // ── Capability flags ─────────────────────────────────────────────────────
@@ -93,9 +93,9 @@ export class CodeBlock extends TextBlock {
93
93
  );
94
94
 
95
95
  // Sync language from Loro data changes (mirrors Heading's level sync)
96
- this.node.data.subscribe(() => {
96
+ this.nabu.track(this.node.data.subscribe(() => {
97
97
  this.language = this.node.data.get('language') || null;
98
- });
98
+ }));
99
99
  }
100
100
 
101
101
  // ── Capability flags ─────────────────────────────────────────────────────
@@ -49,9 +49,9 @@ export class Heading extends TextBlock {
49
49
  this.serializers.set('application/x-nabu+json', (ctx) => this.behavior.toClipboardBlock({ ...ctx, props: { level: this.level } }));
50
50
 
51
51
  // Synchronisation du niveau
52
- this.node.data.subscribe(() => {
52
+ this.nabu.track(this.node.data.subscribe(() => {
53
53
  this.level = this.node.data.get("level") || 1;
54
- });
54
+ }));
55
55
  }
56
56
 
57
57
  /** @type {number} */
@@ -60,9 +60,9 @@ export class ListItem extends MegaBlock {
60
60
  // Initialize checked from Loro metadata
61
61
  this.checked = !!node.data.get('checked');
62
62
  // Subscribe to data changes to keep checked in sync
63
- this.node.data.subscribe(() => {
63
+ this.nabu.track(this.node.data.subscribe(() => {
64
64
  this.checked = !!this.node.data.get('checked');
65
- });
65
+ }));
66
66
 
67
67
  // One item (and its sublists), indented under the items that hold it. A whole list is rendered by the List.
68
68
  this.serializers.set('markdown', () => {
@@ -17,10 +17,10 @@ export class ListBehavior {
17
17
  this.node = /** @type {ListNode} */ (block.node);
18
18
  this.listType = /** @type {"bullet" | "ordered" | "todo"} */ (this.node.data.get("listType") || "bullet");
19
19
  this.start = /** @type {any} */ (this.node.data.get("start")) ?? null;
20
- this.node.data.subscribe(() => {
20
+ this.nabu.track(this.node.data.subscribe(() => {
21
21
  this.listType = /** @type {"bullet" | "ordered" | "todo"} */ (this.node.data.get("listType") || "bullet");
22
22
  this.start = /** @type {any} */ (this.node.data.get("start")) ?? null;
23
- });
23
+ }));
24
24
  }
25
25
 
26
26
  /** Raw `start` number from the node (null = unset); List.start normalizes it. @type {number | null} */
@@ -29,7 +29,7 @@ export class MediaBlock extends Block {
29
29
  this.status = data.get('status') || 'ready';
30
30
  this.#reason = normalizeReason(data.get('reason'));
31
31
  this.name = data.get('name') || '';
32
- data.subscribe(() => {
32
+ this.nabu.track(data.subscribe(() => {
33
33
  this.ref = data.get('ref') || '';
34
34
  this.alt = data.get('alt') || '';
35
35
  this.status = data.get('status') || 'ready';
@@ -41,7 +41,7 @@ export class MediaBlock extends Block {
41
41
  if (this.previewUrl.startsWith('blob:')) URL.revokeObjectURL(this.previewUrl);
42
42
  this.previewUrl = null;
43
43
  }
44
- });
44
+ }));
45
45
  }
46
46
 
47
47
  /** @type {string} */ ref = $state('');
@@ -66,6 +66,26 @@ export class Nabu {
66
66
  * @public
67
67
  */
68
68
  public static CONTINUE: symbol;
69
+ /**
70
+ * The `onPush` / `onPop` of the undo manager. Built HERE, out of the constructor, so that they close over `holder` and nothing
71
+ * else: a closure made in the constructor would keep the constructor's scope, and `this` with it, alive.
72
+ * @param {{ owner: Nabu | null }} holder
73
+ */
74
+ static #undoCallbacks(holder: {
75
+ owner: Nabu | null;
76
+ }): {
77
+ /** @param {boolean} isUndo @param {{ end?: any } | undefined} range */
78
+ onPush: (isUndo: boolean, range: {
79
+ end?: any;
80
+ } | undefined) => {
81
+ value: any;
82
+ cursors: never[];
83
+ };
84
+ /** @param {boolean} isUndo @param {any} storedValue @param {{ end?: any } | undefined} range */
85
+ onPop: (isUndo: boolean, storedValue: any, range: {
86
+ end?: any;
87
+ } | undefined) => void;
88
+ };
69
89
  /** @param {NabuInit} init */
70
90
  constructor(init?: NabuInit);
71
91
  /**
@@ -691,6 +711,32 @@ export class Nabu {
691
711
  * @unstable
692
712
  */
693
713
  public get internals(): NabuInternals;
714
+ /**
715
+ * Hand over a Loro subscription (or any cleanup) that lives as long as the engine: `destroy()` calls it, once. A block or an
716
+ * extension passes its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback (and what it closes over, the engine
717
+ * with it) until it is unsubscribed, so one that is not tracked keeps the engine in memory after `destroy()`.
718
+ * @template {() => void} T
719
+ * @param {T} unsubscribe
720
+ * @returns {T} what it was given
721
+ * @public
722
+ */
723
+ public track<T extends () => void>(unsubscribe: T): T;
724
+ /**
725
+ * Release the engine for good, for a host that is done with it: the memory, not only the page. Unmounting `<NabuEditor>`
726
+ * releases the page listeners but not the memory (the engine can be mounted again); `destroy()` releases the memory: it
727
+ * unsubscribes the engine and its blocks from the document (see {@link Nabu#track}), stops the subsystems, closes `persistence`
728
+ * if the engine is persisted, releases the files (upload retries) and stops the selection tracking, so that the engine can be
729
+ * garbage collected. Idempotent. Call it after `unmount()` or instead of it (e.g. `onDestroy(() => engine.destroy())`).
730
+ *
731
+ * Changes that are not saved yet are DROPPED, not written: `persistence.dispose()` cancels the pending autosave and removes the
732
+ * `pagehide` flush. Await `saveNow()` first when they matter.
733
+ *
734
+ * The document stays in memory and readable as it was (`serialize()`, `doc`), but the engine no longer follows changes: no more
735
+ * edits. A destroyed engine must not be mounted again.
736
+ * @returns {void}
737
+ * @public
738
+ */
739
+ public destroy(): void;
694
740
  /**
695
741
  * Log a diagnostic to the console when `debugging` is on. Silent otherwise.
696
742
  * @param {...any} args
@@ -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 { revealCaret } from '../utils/reveal-caret.js';
21
22
  import { markAtCaret } from '../behaviors/text/mark-edges.js';
22
23
  import { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
23
24
  import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
@@ -231,6 +232,16 @@ export class Nabu {
231
232
  /** Selection where each recent action ended, by the counter end of its undo step. @type {Map<number, import('./undo-selection.js').UndoSelection>} */
232
233
  #actionEnds = new Map();
233
234
 
235
+ // ── Keeping the caret visible ────────────────────────────────────────────
236
+ // Native edits are cancelled and the DOM is rendered from the model, so the browser no longer scrolls to the caret after an
237
+ // edit: the editor does (utils/reveal-caret.js), in the next frame, once per burst, and only for an edit the user made.
238
+ /** The pending animation frame of {@link Nabu#revealSoon}, 0 when none. */
239
+ #revealFrame = 0;
240
+ /** An edit asked for the reveal outright (an input, a paste…), not only "if something changed". */
241
+ #revealForced = false;
242
+ /** The oldest key that asks "if something changed since": the document and selection counters at its keydown. @type {{ ops: number, placed: number } | null} */
243
+ #revealSince = null;
244
+
234
245
  /** @param {NabuInit} init */
235
246
  constructor(init = {}) {
236
247
  this.doc = new LoroDoc();
@@ -251,30 +262,16 @@ export class Nabu {
251
262
  this.tree = /** @type {LoroTree<NabuNodeData>} */ (this.doc.getTree("blocks"));
252
263
  this.content = this.doc.getMap("content");
253
264
 
254
- // Initialize Undo/Redo Manager
265
+ // Initialize Undo/Redo Manager. Loro keeps the two callbacks for as long as the manager lives and has no way to drop
266
+ // them: they reach the engine through `holder`, which `destroy()` clears (else the engine could never be collected).
267
+ const holder = { owner: /** @type {Nabu | null} */ (this) };
268
+ this.track(() => { holder.owner = null; });
255
269
  this.undoManager = new UndoManager(this.doc, {
256
270
  maxUndoSteps: 100,
257
271
  // Background completions (e.g. a pasted file finishing its upload) are not undo steps of their own.
258
272
  excludeOriginPrefixes: ['nabu:silent'],
259
273
  mergeInterval: this.#mergeInterval,
260
- onPush: (isUndo, range) => {
261
- if (this.#isolatedSteps > 0) this.#isolatedSteps--;
262
- // The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
263
- // (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
264
- // an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
265
- const explicit = this.#undoCursor;
266
- this.#undoCursor = null;
267
- const ended = !isUndo && this.#undoneEnd !== null ? this.#actionEnds.get(this.#undoneEnd) : undefined;
268
- const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? this.#undoSel) ?? legacySelection(this);
269
- this.#endKey = isUndo ? range?.end ?? null : null;
270
- return { value: /** @type {any} */ (stored), cursors: [] };
271
- },
272
- onPop: (isUndo, storedValue, range) => {
273
- this.#undoneEnd = isUndo ? range?.end ?? null : null;
274
- this.#endKey = null;
275
- const value = /** @type {any} */ (storedValue?.value);
276
- if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(this, value);
277
- }
274
+ ...Nabu.#undoCallbacks(holder),
278
275
  });
279
276
 
280
277
  /**
@@ -394,7 +391,7 @@ export class Nabu {
394
391
  // One event batch = one refresh. The affected containers are COLLECTED while the batch is read, then each is refreshed
395
392
  // once (the root list at most once, every parent at most once): refreshing per action made an import / a mass undo / a
396
393
  // big paste quadratic (P-104). The doc already holds the final state of the batch, so the order of the actions is moot.
397
- this.tree.subscribe((event) => {
394
+ this.track(this.tree.subscribe((event) => {
398
395
  let rootsDirty = false;
399
396
  /** @type {Set<string>} */
400
397
  const parents = new Set();
@@ -440,7 +437,7 @@ export class Nabu {
440
437
  // A block retyped into a leaf (no children) in the same transaction has no updateChildren().
441
438
  /** @type {{ updateChildren?: (retyped?: Set<string>) => void } | undefined} */ (this.blocks.get(parentId))?.updateChildren?.(retyped);
442
439
  }
443
- });
440
+ }));
444
441
 
445
442
  this.init();
446
443
  }
@@ -1344,9 +1341,39 @@ export class Nabu {
1344
1341
  }
1345
1342
  }
1346
1343
 
1344
+ /**
1345
+ * Bring the caret into view in the next frame (utils/reveal-caret.js), after an edit the user made: native editing scrolls to
1346
+ * the caret, and Nabu's does not happen natively. A frame, not the keystroke itself: the layout has to happen then anyway, so
1347
+ * nothing is forced and the key-to-DOM latency stays as it was. Requests of one burst share the frame.
1348
+ * With `since` (a key the editor handled), the reveal only happens if the document or the selection changed meanwhile: a key
1349
+ * that did nothing (Ctrl+C, a modifier…) must not throw the user back to the caret they scrolled away from.
1350
+ * Programmatic edits (`insert`, `exec`, `importRemote`, a collaborator) never come through here.
1351
+ * @param {{ ops: number, placed: number }} [since]
1352
+ */
1353
+ #revealSoon(since) {
1354
+ if (typeof requestAnimationFrame === 'undefined') return;
1355
+ if (since) this.#revealSince ??= since;
1356
+ else this.#revealForced = true;
1357
+ if (this.#revealFrame) return;
1358
+ this.#revealFrame = requestAnimationFrame(() => {
1359
+ this.#revealFrame = 0;
1360
+ const forced = this.#revealForced;
1361
+ const asked = this.#revealSince;
1362
+ this.#revealForced = false;
1363
+ this.#revealSince = null;
1364
+ if (!forced && asked && this.doc.opCount() === asked.ops && this.selection.placements === asked.placed) return;
1365
+ const root = this.selection.root; // null once the editor is unmounted
1366
+ if (!root || !root.isConnected || this.#readonly || this.#composing) return;
1367
+ const active = /** @type {Document | ShadowRoot} */ (root.getRootNode()).activeElement ?? document.activeElement;
1368
+ if (!active || !root.contains(active) || this.selection.scope() !== 'mine') return;
1369
+ revealCaret(root);
1370
+ });
1371
+ }
1372
+
1347
1373
  /** @param {InputEvent} e */
1348
1374
  handleBeforeinput(e) {
1349
1375
  if (this.#readonly) { e.preventDefault(); return; } // nothing is typed, deleted, pasted or dropped in a read-only editor
1376
+ this.#revealSoon();
1350
1377
  this.selection.sync(); // selectionchange is async: don't act on a stale caret
1351
1378
  // Ne pas interférer avec la composition IME en cours : le navigateur
1352
1379
  // doit pouvoir muter librement le text node (insertCompositionText
@@ -1456,6 +1483,7 @@ export class Nabu {
1456
1483
  this.#endCompositionGroup();
1457
1484
  }
1458
1485
  this.selection.normalize(); // a dead caret must not survive the composition
1486
+ this.#revealSoon();
1459
1487
  // A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
1460
1488
  if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
1461
1489
  this.selection.setCursor(composedBlock, 0);
@@ -1506,6 +1534,16 @@ export class Nabu {
1506
1534
  handleKeydown(e) {
1507
1535
  // Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
1508
1536
  if (this.#readonly) return;
1537
+ const since = { ops: this.doc.opCount(), placed: this.selection.placements };
1538
+ this.#keydown(e);
1539
+ // A key the editor took (Enter, Backspace, undo, a structural shortcut…) scrolls to the caret if it changed anything. The native
1540
+ // caret moves (arrows…) are not prevented: the browser scrolls for them. Select all leaves the caret where the user looks.
1541
+ const selectAll = (e.ctrlKey || e.metaKey) && typeof e.key === 'string' && e.key.toLowerCase() === 'a';
1542
+ if (e.defaultPrevented && !selectAll) this.#revealSoon(since);
1543
+ }
1544
+
1545
+ /** @param {KeyboardEvent} e */
1546
+ #keydown(e) {
1509
1547
  // 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
1548
  if (e.key === 'Tab' && e.target instanceof Element && e.target.closest('[data-nabu-ui]')) return;
1511
1549
  this.selection.sync(); // no-op when the document capture listener already synced
@@ -1755,6 +1793,8 @@ export class Nabu {
1755
1793
  e.preventDefault();
1756
1794
  if (this.#readonly) { this.handleCopy(e); return; } // cutting a read-only text copies it and removes nothing
1757
1795
 
1796
+ this.#revealSoon();
1797
+
1758
1798
  // 1. Copy selection to clipboard
1759
1799
  this.handleCopy(e);
1760
1800
 
@@ -1772,6 +1812,7 @@ export class Nabu {
1772
1812
  handlePaste(e) {
1773
1813
  e.preventDefault();
1774
1814
  if (this.#readonly) return;
1815
+ this.#revealSoon();
1775
1816
  this.selection.sync();
1776
1817
  const clipboard = e.clipboardData;
1777
1818
  if (!clipboard) return;
@@ -2040,6 +2081,7 @@ export class Nabu {
2040
2081
  if (!position) return;
2041
2082
  // The editor takes the focus (undo, typing…) even when the drop leaves no text caret to put in it (a dropped image).
2042
2083
  if (document.activeElement !== root) root.focus({ preventScroll: true });
2084
+ this.#revealSoon();
2043
2085
  const own = !!source && dt.getData(DRAG_MARKER) === source.token;
2044
2086
  this.dropAt(dt, position, { source: own && !wantsCopy(e) ? source : null });
2045
2087
  }
@@ -2580,6 +2622,83 @@ export class Nabu {
2580
2622
  });
2581
2623
  }
2582
2624
 
2625
+ /**
2626
+ * The `onPush` / `onPop` of the undo manager. Built HERE, out of the constructor, so that they close over `holder` and nothing
2627
+ * else: a closure made in the constructor would keep the constructor's scope, and `this` with it, alive.
2628
+ * @param {{ owner: Nabu | null }} holder
2629
+ */
2630
+ static #undoCallbacks(holder) {
2631
+ return {
2632
+ /** @param {boolean} isUndo @param {{ end?: any } | undefined} range */
2633
+ onPush: (isUndo, range) => {
2634
+ const self = holder.owner;
2635
+ if (!self) return { value: null, cursors: [] };
2636
+ if (self.#isolatedSteps > 0) self.#isolatedSteps--;
2637
+ // The selection to give back when this step is popped. An undo step: the selection right BEFORE the change
2638
+ // (it is pushed after the commit, but the captured selection predates the change). The redo step pushed by
2639
+ // an undo: where the undone action ENDED. A caret decided by the caller (block shortcut) wins.
2640
+ const explicit = self.#undoCursor;
2641
+ self.#undoCursor = null;
2642
+ const ended = !isUndo && self.#undoneEnd !== null ? self.#actionEnds.get(self.#undoneEnd) : undefined;
2643
+ const stored = (explicit ? explicitSelection(explicit.block, explicit.offset) : ended ?? self.#undoSel) ?? legacySelection(self);
2644
+ self.#endKey = isUndo ? range?.end ?? null : null;
2645
+ return { value: /** @type {any} */ (stored), cursors: [] };
2646
+ },
2647
+ /** @param {boolean} isUndo @param {any} storedValue @param {{ end?: any } | undefined} range */
2648
+ onPop: (isUndo, storedValue, range) => {
2649
+ const self = holder.owner;
2650
+ if (!self) return;
2651
+ self.#undoneEnd = isUndo ? range?.end ?? null : null;
2652
+ self.#endKey = null;
2653
+ const value = /** @type {any} */ (storedValue?.value);
2654
+ if (value && typeof value === 'object' && 'anchor' in value) restoreSelection(self, value);
2655
+ },
2656
+ };
2657
+ }
2658
+
2659
+ /** What `destroy()` calls: the unsubscribe functions given to {@link Nabu#track}. @type {Set<() => void>} */
2660
+ #tracked = new Set();
2661
+
2662
+ /**
2663
+ * Hand over a Loro subscription (or any cleanup) that lives as long as the engine: `destroy()` calls it, once. A block or an
2664
+ * extension passes its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback (and what it closes over, the engine
2665
+ * with it) until it is unsubscribed, so one that is not tracked keeps the engine in memory after `destroy()`.
2666
+ * @template {() => void} T
2667
+ * @param {T} unsubscribe
2668
+ * @returns {T} what it was given
2669
+ * @public
2670
+ */
2671
+ track(unsubscribe) {
2672
+ this.#tracked.add(unsubscribe);
2673
+ return unsubscribe;
2674
+ }
2675
+
2676
+ /**
2677
+ * Release the engine for good, for a host that is done with it: the memory, not only the page. Unmounting `<NabuEditor>`
2678
+ * releases the page listeners but not the memory (the engine can be mounted again); `destroy()` releases the memory: it
2679
+ * unsubscribes the engine and its blocks from the document (see {@link Nabu#track}), stops the subsystems, closes `persistence`
2680
+ * if the engine is persisted, releases the files (upload retries) and stops the selection tracking, so that the engine can be
2681
+ * garbage collected. Idempotent. Call it after `unmount()` or instead of it (e.g. `onDestroy(() => engine.destroy())`).
2682
+ *
2683
+ * Changes that are not saved yet are DROPPED, not written: `persistence.dispose()` cancels the pending autosave and removes the
2684
+ * `pagehide` flush. Await `saveNow()` first when they matter.
2685
+ *
2686
+ * The document stays in memory and readable as it was (`serialize()`, `doc`), but the engine no longer follows changes: no more
2687
+ * edits. A destroyed engine must not be mounted again.
2688
+ * @returns {void}
2689
+ * @public
2690
+ */
2691
+ destroy() {
2692
+ if (this.#revealFrame) cancelAnimationFrame(this.#revealFrame);
2693
+ this.#revealFrame = 0;
2694
+ for (const stop of this.#tracked) stop();
2695
+ this.#tracked.clear();
2696
+ for (const system of this.systems.values()) system.stop?.();
2697
+ /** @type {any} */ (this).persistence?.dispose?.();
2698
+ /** @type {any} */ (this.systems.get('files'))?.dispose?.();
2699
+ this.selection.destroy();
2700
+ }
2701
+
2583
2702
  /**
2584
2703
  * Log a diagnostic to the console when `debugging` is on. Silent otherwise.
2585
2704
  * @param {...any} args
@@ -109,7 +109,7 @@ export class RegionBlock extends MegaBlock {
109
109
 
110
110
  this.#read();
111
111
  // Local commits, imports and remote peers all end up here (the `fields` map is a child container of `data`).
112
- node.data.subscribe(() => this.#read());
112
+ nabu.track(node.data.subscribe(() => this.#read()));
113
113
 
114
114
  // Document export: exact round trip (`importJSON` reads `props` and `content` back, see RegionBlock.create).
115
115
  this.serializers.set('json', () => ({
@@ -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
- return () => { if (this.root === el) this.root = null; };
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
- const dir = explicit ?? offsetHeuristic(anchor, anchorOffset);
331
- const target = findNearestTextNode(anchor, anchorOffset, dir, filter, this.root);
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();
@@ -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
  }
@@ -0,0 +1,13 @@
1
+ /** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
2
+ /**
3
+ * Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
4
+ * a usable caret (no selection, the focus is outside `root`, no layout).
5
+ * @param {Element} root the editor's root: the focus of the selection has to be inside it
6
+ */
7
+ export function revealCaret(root: Element): void;
8
+ export type Box = {
9
+ top: number;
10
+ bottom: number;
11
+ left: number;
12
+ right: number;
13
+ };
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Keep the caret visible after an edit the user made. Nabu cancels the native edits and re-renders from the model, so the browser
3
+ * no longer scrolls to the caret by itself: `revealCaret` does it, the way a plain contenteditable would. "Nearest": nothing moves
4
+ * while the caret is already inside the visible area.
5
+ *
6
+ * Every scrollable ancestor is moved by the least amount that brings the caret into its padding box (shadow roots are crossed),
7
+ * then the window, bounded by the visual viewport when there is one (a virtual keyboard shrinks it). A host keeps the caret clear
8
+ * of its own sticky UI with `scroll-padding` (on the scroller, or on the root element for the window). No Svelte, no state.
9
+ */
10
+
11
+ /** Breathing room left between the caret and the edge it was scrolled to, in px (cut down when the box is too small for it). */
12
+ const MARGIN = 8;
13
+ /** The overflow values of an element that scrolls, by script or by the user (`overlay` is an alias of `auto`). */
14
+ const SCROLLS = new Set(['auto', 'scroll', 'hidden']);
15
+
16
+ /** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
17
+
18
+ /**
19
+ * Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
20
+ * a usable caret (no selection, the focus is outside `root`, no layout).
21
+ * @param {Element} root the editor's root: the focus of the selection has to be inside it
22
+ */
23
+ export function revealCaret(root) {
24
+ if (typeof window === 'undefined') return;
25
+ const live = window.getSelection();
26
+ const node = live?.focusNode;
27
+ if (!live || !node || live.rangeCount === 0 || !root.contains(node)) return;
28
+ const offset = live.focusOffset;
29
+ const holder = /** @type {Element | null} */ (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement);
30
+ if (!holder) return;
31
+
32
+ let caret = caretBox(node, offset, holder);
33
+ if (!caret) return;
34
+
35
+ for (let el = parentOf(holder); el && el !== document.documentElement; el = parentOf(el)) {
36
+ // The body of a page whose `overflow` went up to the viewport does not scroll: the window does.
37
+ if (el === document.body && getComputedStyle(document.documentElement).overflow === 'visible') continue;
38
+ const style = getComputedStyle(el);
39
+ const y = SCROLLS.has(style.overflowY) && el.scrollHeight > el.clientHeight;
40
+ const x = SCROLLS.has(style.overflowX) && el.scrollWidth > el.clientWidth;
41
+ if (y || x) {
42
+ const box = el.getBoundingClientRect();
43
+ // A transform scales the rects but not `scrollTop`: the amount to scroll is in layout px.
44
+ const { offsetHeight, offsetWidth } = /** @type {HTMLElement} */ (el); // undefined on an SVG element: no scale, then
45
+ const sy = box.height / offsetHeight || 1;
46
+ const sx = box.width / offsetWidth || 1;
47
+ const dy = y ? nudge(caret.top, caret.bottom, box.top + el.clientTop * sy, el.clientHeight * sy, padding(style.scrollPaddingTop, el.clientHeight) * sy, padding(style.scrollPaddingBottom, el.clientHeight) * sy) : 0;
48
+ const dx = x ? nudge(caret.left, caret.right, box.left + el.clientLeft * sx, el.clientWidth * sx, padding(style.scrollPaddingLeft, el.clientWidth) * sx, padding(style.scrollPaddingRight, el.clientWidth) * sx) : 0;
49
+ if (dy || dx) {
50
+ el.scrollBy({ top: dy / sy, left: dx / sx, behavior: 'instant' }); // instant: a `scroll-behavior: smooth` host must not lag behind the typing
51
+ caret = caretBox(node, offset, holder) ?? caret;
52
+ }
53
+ }
54
+ if (style.position === 'fixed') return; // the window cannot move it
55
+ }
56
+
57
+ const vv = window.visualViewport;
58
+ const top = vv ? vv.offsetTop : 0;
59
+ const left = vv ? vv.offsetLeft : 0;
60
+ const height = vv ? vv.height : window.innerHeight;
61
+ const width = vv ? vv.width : window.innerWidth;
62
+ const style = getComputedStyle(document.scrollingElement ?? document.documentElement);
63
+ const dy = nudge(caret.top, caret.bottom, top, height, padding(style.scrollPaddingTop, height), padding(style.scrollPaddingBottom, height));
64
+ const dx = nudge(caret.left, caret.right, left, width, padding(style.scrollPaddingLeft, width), padding(style.scrollPaddingRight, width));
65
+ if (dy || dx) window.scrollBy({ top: dy, left: dx, behavior: 'instant' });
66
+ }
67
+
68
+ /**
69
+ * The scroll amount, along one axis, that brings the caret `[start, end]` inside the box `[origin, origin + size]` reduced by its
70
+ * scroll padding and a margin: the smallest one, 0 when it is already inside. A box too small for the caret is aligned on its
71
+ * leading edge (always the same one, so that the next call does not scroll back).
72
+ * @param {number} start @param {number} end @param {number} origin @param {number} size @param {number} before @param {number} after
73
+ * @returns {number}
74
+ */
75
+ function nudge(start, end, origin, size, before, after) {
76
+ let lo = origin + before;
77
+ let hi = origin + size - after;
78
+ const room = hi - lo - (end - start);
79
+ const margin = Math.max(0, Math.min(MARGIN, room / 2));
80
+ lo += margin;
81
+ hi -= margin;
82
+ const delta = room < 0 || start < lo ? start - lo : end > hi ? end - hi : 0;
83
+ return Math.abs(delta) < 0.5 ? 0 : delta;
84
+ }
85
+
86
+ /** A `scroll-padding-*` computed value ("auto", "12px", "10%") in px. @param {string} value @param {number} size what a percentage refers to */
87
+ function padding(value, size) {
88
+ const n = parseFloat(value);
89
+ if (!n) return 0;
90
+ return value.endsWith('%') ? (n * size) / 100 : n;
91
+ }
92
+
93
+ /** The parent of `el` in the flat tree: a slot, else the parent element, else the host of the shadow root. @param {Element} el @returns {Element | null} */
94
+ function parentOf(el) {
95
+ if (el.assignedSlot) return el.assignedSlot;
96
+ if (el.parentElement) return el.parentElement;
97
+ const top = el.getRootNode();
98
+ return top instanceof ShadowRoot ? top.host : null;
99
+ }
100
+
101
+ /**
102
+ * The caret as a rect, in viewport coordinates. A collapsed range may report no rect, or a zero-height one, in an empty block or at
103
+ * a line edge: the character after it is measured then (its left edge), then the one before (its right edge), then the top of the
104
+ * block with one line (never the whole rect of a tall block). Null when nothing is measurable.
105
+ * @param {Node} node @param {number} offset @param {Element} holder the element holding `node`
106
+ * @returns {Box | null}
107
+ */
108
+ function caretBox(node, offset, holder) {
109
+ const measure = (/** @type {Node} */ a, /** @type {number} */ from, /** @type {number} */ to) => {
110
+ const range = document.createRange();
111
+ try {
112
+ range.setStart(a, from);
113
+ range.setEnd(a, to);
114
+ } catch { return null; }
115
+ for (const r of range.getClientRects()) if (r.height > 0) return r;
116
+ return null;
117
+ };
118
+ const text = (/** @type {Node | undefined} */ n) => (n && n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n) : null);
119
+ // The text positions on each side of the caret (it may sit between elements).
120
+ const isText = node.nodeType === Node.TEXT_NODE;
121
+ const next = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset]);
122
+ const nextAt = isText ? offset : 0;
123
+ const prev = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset - 1]);
124
+ const prevAt = isText ? offset : prev ? prev.length : 0;
125
+
126
+ const here = measure(node, offset, offset);
127
+ if (here) return { top: here.top, bottom: here.bottom, left: here.left, right: here.left };
128
+ if (next && nextAt < next.length) {
129
+ const r = measure(next, nextAt, nextAt + 1);
130
+ if (r) return { top: r.top, bottom: r.bottom, left: r.left, right: r.left };
131
+ }
132
+ if (prev && prevAt > 0) {
133
+ const r = measure(prev, prevAt - 1, prevAt);
134
+ if (r) return { top: r.top, bottom: r.bottom, left: r.right, right: r.right };
135
+ }
136
+
137
+ const block = holder.closest('[data-block-id]') ?? holder;
138
+ const r = block.getBoundingClientRect();
139
+ if (!r.width && !r.height) return null;
140
+ const style = getComputedStyle(block);
141
+ const scale = r.height / /** @type {HTMLElement} */ (block).offsetHeight || 1;
142
+ const line = (parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2 || 0) * scale;
143
+ if (!line) return null;
144
+ return { top: r.top, bottom: r.top + line, left: r.left, right: r.left };
145
+ }
@@ -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/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[]>;
package/dist/vite.js 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 async function nabu() {
@@ -23,9 +31,14 @@ export async function nabu() {
23
31
  return [
24
32
  wasm(),
25
33
  {
26
- name: 'nabu:esnext-target',
34
+ name: 'nabu:config',
27
35
  config(config) {
28
- if (config.build?.target === undefined) return { build: { target: 'esnext' } };
36
+ /** @type {import('vite').UserConfig} */
37
+ const patch = {};
38
+ if (config.build?.target === undefined) patch.build = { target: 'esnext' };
39
+ // Arrays merge in Vite's `mergeConfig`, so the consumer's own `ssr.external` entries are kept.
40
+ if (config.ssr?.external !== true) patch.ssr = { external: ['loro-crdt'] };
41
+ return Object.keys(patch).length ? patch : undefined;
29
42
  },
30
43
  },
31
44
  ];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",