@aionbuilders/nabu 0.1.3 → 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,13 @@
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
+
7
14
  ## 0.1.3 (2026-11-04)
8
15
 
9
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.
@@ -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();
@@ -1330,9 +1341,39 @@ export class Nabu {
1330
1341
  }
1331
1342
  }
1332
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
+
1333
1373
  /** @param {InputEvent} e */
1334
1374
  handleBeforeinput(e) {
1335
1375
  if (this.#readonly) { e.preventDefault(); return; } // nothing is typed, deleted, pasted or dropped in a read-only editor
1376
+ this.#revealSoon();
1336
1377
  this.selection.sync(); // selectionchange is async: don't act on a stale caret
1337
1378
  // Ne pas interférer avec la composition IME en cours : le navigateur
1338
1379
  // doit pouvoir muter librement le text node (insertCompositionText
@@ -1442,6 +1483,7 @@ export class Nabu {
1442
1483
  this.#endCompositionGroup();
1443
1484
  }
1444
1485
  this.selection.normalize(); // a dead caret must not survive the composition
1486
+ this.#revealSoon();
1445
1487
  // A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
1446
1488
  if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
1447
1489
  this.selection.setCursor(composedBlock, 0);
@@ -1492,6 +1534,16 @@ export class Nabu {
1492
1534
  handleKeydown(e) {
1493
1535
  // Read-only: no command, hook or block sees the key. The browser keeps its own keys (selection, copy, scrolling).
1494
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) {
1495
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.
1496
1548
  if (e.key === 'Tab' && e.target instanceof Element && e.target.closest('[data-nabu-ui]')) return;
1497
1549
  this.selection.sync(); // no-op when the document capture listener already synced
@@ -1741,6 +1793,8 @@ export class Nabu {
1741
1793
  e.preventDefault();
1742
1794
  if (this.#readonly) { this.handleCopy(e); return; } // cutting a read-only text copies it and removes nothing
1743
1795
 
1796
+ this.#revealSoon();
1797
+
1744
1798
  // 1. Copy selection to clipboard
1745
1799
  this.handleCopy(e);
1746
1800
 
@@ -1758,6 +1812,7 @@ export class Nabu {
1758
1812
  handlePaste(e) {
1759
1813
  e.preventDefault();
1760
1814
  if (this.#readonly) return;
1815
+ this.#revealSoon();
1761
1816
  this.selection.sync();
1762
1817
  const clipboard = e.clipboardData;
1763
1818
  if (!clipboard) return;
@@ -2026,6 +2081,7 @@ export class Nabu {
2026
2081
  if (!position) return;
2027
2082
  // The editor takes the focus (undo, typing…) even when the drop leaves no text caret to put in it (a dropped image).
2028
2083
  if (document.activeElement !== root) root.focus({ preventScroll: true });
2084
+ this.#revealSoon();
2029
2085
  const own = !!source && dt.getData(DRAG_MARKER) === source.token;
2030
2086
  this.dropAt(dt, position, { source: own && !wantsCopy(e) ? source : null });
2031
2087
  }
@@ -2633,6 +2689,8 @@ export class Nabu {
2633
2689
  * @public
2634
2690
  */
2635
2691
  destroy() {
2692
+ if (this.#revealFrame) cancelAnimationFrame(this.#revealFrame);
2693
+ this.#revealFrame = 0;
2636
2694
  for (const stop of this.#tracked) stop();
2637
2695
  this.#tracked.clear();
2638
2696
  for (const system of this.systems.values()) system.stop?.();
@@ -0,0 +1,13 @@
1
+ /** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
2
+ /**
3
+ * Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
4
+ * a usable caret (no selection, the focus is outside `root`, no layout).
5
+ * @param {Element} root the editor's root: the focus of the selection has to be inside it
6
+ */
7
+ export function revealCaret(root: Element): void;
8
+ export type Box = {
9
+ top: number;
10
+ bottom: number;
11
+ left: number;
12
+ right: number;
13
+ };
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Keep the caret visible after an edit the user made. Nabu cancels the native edits and re-renders from the model, so the browser
3
+ * no longer scrolls to the caret by itself: `revealCaret` does it, the way a plain contenteditable would. "Nearest": nothing moves
4
+ * while the caret is already inside the visible area.
5
+ *
6
+ * Every scrollable ancestor is moved by the least amount that brings the caret into its padding box (shadow roots are crossed),
7
+ * then the window, bounded by the visual viewport when there is one (a virtual keyboard shrinks it). A host keeps the caret clear
8
+ * of its own sticky UI with `scroll-padding` (on the scroller, or on the root element for the window). No Svelte, no state.
9
+ */
10
+
11
+ /** Breathing room left between the caret and the edge it was scrolled to, in px (cut down when the box is too small for it). */
12
+ const MARGIN = 8;
13
+ /** The overflow values of an element that scrolls, by script or by the user (`overlay` is an alias of `auto`). */
14
+ const SCROLLS = new Set(['auto', 'scroll', 'hidden']);
15
+
16
+ /** @typedef {{ top: number, bottom: number, left: number, right: number }} Box */
17
+
18
+ /**
19
+ * Scroll everything between the caret and the window so that the caret of the live selection is visible. Does nothing without
20
+ * a usable caret (no selection, the focus is outside `root`, no layout).
21
+ * @param {Element} root the editor's root: the focus of the selection has to be inside it
22
+ */
23
+ export function revealCaret(root) {
24
+ if (typeof window === 'undefined') return;
25
+ const live = window.getSelection();
26
+ const node = live?.focusNode;
27
+ if (!live || !node || live.rangeCount === 0 || !root.contains(node)) return;
28
+ const offset = live.focusOffset;
29
+ const holder = /** @type {Element | null} */ (node.nodeType === Node.ELEMENT_NODE ? node : node.parentElement);
30
+ if (!holder) return;
31
+
32
+ let caret = caretBox(node, offset, holder);
33
+ if (!caret) return;
34
+
35
+ for (let el = parentOf(holder); el && el !== document.documentElement; el = parentOf(el)) {
36
+ // The body of a page whose `overflow` went up to the viewport does not scroll: the window does.
37
+ if (el === document.body && getComputedStyle(document.documentElement).overflow === 'visible') continue;
38
+ const style = getComputedStyle(el);
39
+ const y = SCROLLS.has(style.overflowY) && el.scrollHeight > el.clientHeight;
40
+ const x = SCROLLS.has(style.overflowX) && el.scrollWidth > el.clientWidth;
41
+ if (y || x) {
42
+ const box = el.getBoundingClientRect();
43
+ // A transform scales the rects but not `scrollTop`: the amount to scroll is in layout px.
44
+ const { offsetHeight, offsetWidth } = /** @type {HTMLElement} */ (el); // undefined on an SVG element: no scale, then
45
+ const sy = box.height / offsetHeight || 1;
46
+ const sx = box.width / offsetWidth || 1;
47
+ const dy = y ? nudge(caret.top, caret.bottom, box.top + el.clientTop * sy, el.clientHeight * sy, padding(style.scrollPaddingTop, el.clientHeight) * sy, padding(style.scrollPaddingBottom, el.clientHeight) * sy) : 0;
48
+ const dx = x ? nudge(caret.left, caret.right, box.left + el.clientLeft * sx, el.clientWidth * sx, padding(style.scrollPaddingLeft, el.clientWidth) * sx, padding(style.scrollPaddingRight, el.clientWidth) * sx) : 0;
49
+ if (dy || dx) {
50
+ el.scrollBy({ top: dy / sy, left: dx / sx, behavior: 'instant' }); // instant: a `scroll-behavior: smooth` host must not lag behind the typing
51
+ caret = caretBox(node, offset, holder) ?? caret;
52
+ }
53
+ }
54
+ if (style.position === 'fixed') return; // the window cannot move it
55
+ }
56
+
57
+ const vv = window.visualViewport;
58
+ const top = vv ? vv.offsetTop : 0;
59
+ const left = vv ? vv.offsetLeft : 0;
60
+ const height = vv ? vv.height : window.innerHeight;
61
+ const width = vv ? vv.width : window.innerWidth;
62
+ const style = getComputedStyle(document.scrollingElement ?? document.documentElement);
63
+ const dy = nudge(caret.top, caret.bottom, top, height, padding(style.scrollPaddingTop, height), padding(style.scrollPaddingBottom, height));
64
+ const dx = nudge(caret.left, caret.right, left, width, padding(style.scrollPaddingLeft, width), padding(style.scrollPaddingRight, width));
65
+ if (dy || dx) window.scrollBy({ top: dy, left: dx, behavior: 'instant' });
66
+ }
67
+
68
+ /**
69
+ * The scroll amount, along one axis, that brings the caret `[start, end]` inside the box `[origin, origin + size]` reduced by its
70
+ * scroll padding and a margin: the smallest one, 0 when it is already inside. A box too small for the caret is aligned on its
71
+ * leading edge (always the same one, so that the next call does not scroll back).
72
+ * @param {number} start @param {number} end @param {number} origin @param {number} size @param {number} before @param {number} after
73
+ * @returns {number}
74
+ */
75
+ function nudge(start, end, origin, size, before, after) {
76
+ let lo = origin + before;
77
+ let hi = origin + size - after;
78
+ const room = hi - lo - (end - start);
79
+ const margin = Math.max(0, Math.min(MARGIN, room / 2));
80
+ lo += margin;
81
+ hi -= margin;
82
+ const delta = room < 0 || start < lo ? start - lo : end > hi ? end - hi : 0;
83
+ return Math.abs(delta) < 0.5 ? 0 : delta;
84
+ }
85
+
86
+ /** A `scroll-padding-*` computed value ("auto", "12px", "10%") in px. @param {string} value @param {number} size what a percentage refers to */
87
+ function padding(value, size) {
88
+ const n = parseFloat(value);
89
+ if (!n) return 0;
90
+ return value.endsWith('%') ? (n * size) / 100 : n;
91
+ }
92
+
93
+ /** The parent of `el` in the flat tree: a slot, else the parent element, else the host of the shadow root. @param {Element} el @returns {Element | null} */
94
+ function parentOf(el) {
95
+ if (el.assignedSlot) return el.assignedSlot;
96
+ if (el.parentElement) return el.parentElement;
97
+ const top = el.getRootNode();
98
+ return top instanceof ShadowRoot ? top.host : null;
99
+ }
100
+
101
+ /**
102
+ * The caret as a rect, in viewport coordinates. A collapsed range may report no rect, or a zero-height one, in an empty block or at
103
+ * a line edge: the character after it is measured then (its left edge), then the one before (its right edge), then the top of the
104
+ * block with one line (never the whole rect of a tall block). Null when nothing is measurable.
105
+ * @param {Node} node @param {number} offset @param {Element} holder the element holding `node`
106
+ * @returns {Box | null}
107
+ */
108
+ function caretBox(node, offset, holder) {
109
+ const measure = (/** @type {Node} */ a, /** @type {number} */ from, /** @type {number} */ to) => {
110
+ const range = document.createRange();
111
+ try {
112
+ range.setStart(a, from);
113
+ range.setEnd(a, to);
114
+ } catch { return null; }
115
+ for (const r of range.getClientRects()) if (r.height > 0) return r;
116
+ return null;
117
+ };
118
+ const text = (/** @type {Node | undefined} */ n) => (n && n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n) : null);
119
+ // The text positions on each side of the caret (it may sit between elements).
120
+ const isText = node.nodeType === Node.TEXT_NODE;
121
+ const next = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset]);
122
+ const nextAt = isText ? offset : 0;
123
+ const prev = isText ? /** @type {Text} */ (node) : text(node.childNodes[offset - 1]);
124
+ const prevAt = isText ? offset : prev ? prev.length : 0;
125
+
126
+ const here = measure(node, offset, offset);
127
+ if (here) return { top: here.top, bottom: here.bottom, left: here.left, right: here.left };
128
+ if (next && nextAt < next.length) {
129
+ const r = measure(next, nextAt, nextAt + 1);
130
+ if (r) return { top: r.top, bottom: r.bottom, left: r.left, right: r.left };
131
+ }
132
+ if (prev && prevAt > 0) {
133
+ const r = measure(prev, prevAt - 1, prevAt);
134
+ if (r) return { top: r.top, bottom: r.bottom, left: r.right, right: r.right };
135
+ }
136
+
137
+ const block = holder.closest('[data-block-id]') ?? holder;
138
+ const r = block.getBoundingClientRect();
139
+ if (!r.width && !r.height) return null;
140
+ const style = getComputedStyle(block);
141
+ const scale = r.height / /** @type {HTMLElement} */ (block).offsetHeight || 1;
142
+ const line = (parseFloat(style.lineHeight) || parseFloat(style.fontSize) * 1.2 || 0) * scale;
143
+ if (!line) return null;
144
+ return { top: r.top, bottom: r.top + line, left: r.left, right: r.left };
145
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.3",
3
+ "version": "0.1.4",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",