@aionbuilders/nabu 0.1.5 → 0.1.7

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
@@ -1,8 +1,32 @@
1
1
  # Changelog
2
2
 
3
- ## Unreleased
3
+ ## 0.1.7 (2026-11-17)
4
4
 
5
- Nothing yet.
5
+ Your own word counter, and types for `nabu.regions`.
6
+
7
+ ### Added
8
+ - **`countWords` option: your own word counter.** `createEditor({ countWords: (text, lang) => number })` replaces the rule used everywhere Nabu counts words (`wordCount` of a block, a list item, a toggle, a region, the preamble). It receives the text of one block and the editor's `lang`, and is given once at creation. The default does not change. Use it when your app has a different definition of a word, for example Word's, where a hyphenated compound is one word. The function in use is `nabu.countWords`; a value that is not a function is ignored with a warning.
9
+ - **`countWords(text, lang)` is exported** by `@aionbuilders/nabu` and by `@aionbuilders/nabu/format` (which still loads neither Loro nor Svelte): the default rule, to count words of a serialized document without the editor. The `WordCounter` type describes a counter.
10
+
11
+ ### Fixed
12
+ - **`nabu.regions` had no type.** `RegionsExtension` installs it when the editor starts, so the `Nabu` type does not have it, and an IDE offered nothing after `engine.regions`. `createFullEditor()` now returns a `RegionsEditor`, where `regions` is always typed, and the new `RegionsEditor` type annotates an editor built with your own preset. `Regions.get(nabu)` still works everywhere.
13
+
14
+ ### Tests
15
+ - `bun run test:consumer` also type-checks a file against the installed package, the way an IDE sees it.
16
+
17
+ ## 0.1.6 (2026-11-15)
18
+
19
+ Two browser fixes: IME compositions in Firefox, and typing in long documents on WebKit. No API change.
20
+
21
+ ### Fixed
22
+ - **Firefox: the text froze after an IME composition in an empty block.** Firefox puts the composed text in a new text node, and Svelte went on updating the old one: what was typed next reached the model but not the screen, and the caret jumped to the start. The block's render now goes back as Svelte left it when a composition ends, and the model shows the composed text through it. This covers every browser and every text block, including code blocks.
23
+ - **WebKit: typing in the middle of a long document with nested regions took ~400 ms per key.** In a large document every region body was skipped off screen with `content-visibility: auto`, and WebKit pays on every frame for such boxes nested inside each other. Only the innermost region bodies are skipped now, never one inside another. On a 90,000-word novel (parts, chapters, scenes), a key in the middle takes 22 ms instead of ~390 ms on WebKitGTK, and Chromium does not change.
24
+ - **Composed text ignored the bold you had switched on, and could show twice.** A composition now gets the same marks as typed text: the marks you switched on, and the rule for mark edges. At the end of a bold run, the composed text showed both in the run and after it.
25
+
26
+ ### Tests
27
+ - `bun run test:consumer` packs the package as npm would publish it, installs the tarball in a fresh SvelteKit app, builds it and checks on Chromium, Firefox and WebKit that the editor boots and takes typing on an SSR, a client-only, a lazy and a server-built page. It catches what only a consumer sees (a change to how Loro's WASM is loaded broke a client-only route on WebKit while every other test was green).
28
+ - A `firefox` Playwright project (`tests/e2e/firefox`) drives compositions on the real browser. Run `bunx playwright install firefox` once. `core` still runs on Chromium only.
29
+ - `tests/e2e/large-docs-auto-boxes.spec.ts` checks that no skipped box is ever inside another. A `perf-webkit` project, run on demand, types in the middle of a 90,000-word novel and fails above 60 ms per key at the median.
6
30
 
7
31
  ## 0.1.5 (2026-11-04)
8
32
 
@@ -42,7 +42,7 @@ export class TextBehavior {
42
42
  /**
43
43
  * Number of words in this text: segmented with `Intl.Segmenter` in the language of the editor (`nabu.lang`) when the platform
44
44
  * has it, so Chinese or Japanese text counts its words rather than one per sentence; whitespace-separated otherwise. See
45
- * `utils/words.js`. Reactive in the text and in `nabu.lang`.
45
+ * `utils/words.js`. The editor's `countWords` option replaces that rule. Reactive in the text and in `nabu.lang`.
46
46
  * @returns {number}
47
47
  * @public
48
48
  */
@@ -71,20 +71,19 @@ export class TextBehavior {
71
71
  */
72
72
  modelOffset(node: Node, offset: number, element?: HTMLElement | null): number;
73
73
  /**
74
- * IME composition starts. With a trailing render filler (`<br data-nabu-filler>`, the empty last line after a "\n")
75
- * the browser puts the composed text in a NEW text node before the filler (and may swap the filler for a `<br>` of
76
- * its own) — nodes Svelte does not know, which would stay next to the ones it updates once the model catches up
77
- * (text shown twice). Remember Svelte's nodes so {@link TextBehavior#restoreAfterComposition} can undo the browser's
78
- * additions at the end. No filler: nothing to do.
74
+ * IME composition starts. The browser owns the DOM until it ends, and what it does there is not known to Svelte: it may put the
75
+ * composed text in a NEW text node (Firefox, in an empty block), swap a node for a `<br>`, or write it into a run the model
76
+ * will not give it to (the end of a bold run). Remember the render so {@link TextBehavior#restoreAfterComposition} can put it back.
77
+ * Nested blocks and UI are not this block's render: the walk stops at them.
79
78
  */
80
79
  snapshotForComposition(): void;
81
80
  /**
82
- * End of a composition begun next to a filler, BEFORE the composed text reaches the model: remove the text nodes and
83
- * `<br>` the browser created meanwhile (the composed text is committed to the model, which the next render shows
84
- * through Svelte's own nodes); a canceled composition (`composedText` empty) gets its filler back.
85
- * @param {string} composedText
81
+ * End of a composition, BEFORE the composed text reaches the model: the render goes back as Svelte left it, and the model shows
82
+ * the composed text through it on the next render, in the run it really belongs to. Without this Svelte updates nodes that are
83
+ * no longer in the page (the DOM freezes while the model moves on), or the text shows twice.
84
+ * If the model changed meanwhile (a programmatic edit), Svelte has already rendered over the snapshot: it stays as it is.
86
85
  */
87
- restoreAfterComposition(composedText: string): void;
86
+ restoreAfterComposition(): void;
88
87
  /**
89
88
  * @param {InputEvent} event
90
89
  * @param {ReturnType<TextBehavior["getSelection"]>} [selection]
@@ -93,6 +92,12 @@ export class TextBehavior {
93
92
  public handleBeforeInput(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): any;
94
93
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
95
94
  handleInsertText(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
95
+ /**
96
+ * The marks of a run the user just typed or composed at `[from, from + length)`: the cursor's pending stored marks, then the rule
97
+ * for mark edges.
98
+ * @param {number} from @param {number} length
99
+ */
100
+ markTypedRun(from: number, length: number): void;
96
101
  /**
97
102
  * Make the run just typed at `[from, from + length)` follow Nabu's rule for mark edges (see mark-edges.js): it keeps a mark only
98
103
  * when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
@@ -90,12 +90,12 @@ export class TextBehavior {
90
90
  /**
91
91
  * Number of words in this text: segmented with `Intl.Segmenter` in the language of the editor (`nabu.lang`) when the platform
92
92
  * has it, so Chinese or Japanese text counts its words rather than one per sentence; whitespace-separated otherwise. See
93
- * `utils/words.js`. Reactive in the text and in `nabu.lang`.
93
+ * `utils/words.js`. The editor's `countWords` option replaces that rule. Reactive in the text and in `nabu.lang`.
94
94
  * @returns {number}
95
95
  * @public
96
96
  */
97
97
  get wordCount() {
98
- return countWords(this.text, this.nabu?.lang);
98
+ return (this.nabu?.countWords ?? countWords)(this.text, this.nabu?.lang);
99
99
  }
100
100
 
101
101
  /**
@@ -154,65 +154,48 @@ export class TextBehavior {
154
154
  return this.nabu.composing ? at : Math.min(at, this.text.length);
155
155
  }
156
156
 
157
- /** The render of an EMPTY block when an IME composition started (Svelte's own child nodes and their text), to put back if it is canceled. @type {{ nodes: Node[], data: string[] } | null} */
158
- #emptySnapshot = null;
159
-
160
- /** Svelte's own nodes around a trailing render filler when an IME composition started: its text nodes and the filler with its place. @type {{ texts: Set<Node>, filler: Element, parent: Node, next: Node | null } | null} */
157
+ /** The render of the block when an IME composition started: its elements with their children, its text nodes with their text, and the model text it shows. @type {{ text: string, children: Map<Node, Node[]>, data: Map<Text, string> } | null} */
161
158
  #compositionSnapshot = null;
162
159
 
163
160
  /**
164
- * IME composition starts. With a trailing render filler (`<br data-nabu-filler>`, the empty last line after a "\n")
165
- * the browser puts the composed text in a NEW text node before the filler (and may swap the filler for a `<br>` of
166
- * its own) — nodes Svelte does not know, which would stay next to the ones it updates once the model catches up
167
- * (text shown twice). Remember Svelte's nodes so {@link TextBehavior#restoreAfterComposition} can undo the browser's
168
- * additions at the end. No filler: nothing to do.
161
+ * IME composition starts. The browser owns the DOM until it ends, and what it does there is not known to Svelte: it may put the
162
+ * composed text in a NEW text node (Firefox, in an empty block), swap a node for a `<br>`, or write it into a run the model
163
+ * will not give it to (the end of a bold run). Remember the render so {@link TextBehavior#restoreAfterComposition} can put it back.
164
+ * Nested blocks and UI are not this block's render: the walk stops at them.
169
165
  */
170
166
  snapshotForComposition() {
171
167
  const element = this.block.element;
172
168
  this.#compositionSnapshot = null;
173
- this.#emptySnapshot = null;
174
- // An EMPTY block renders a lone "\n" text node: a canceled composition makes the browser swap it for a <br> (caret lost).
175
- if (element && !this.text) {
176
- const nodes = [...element.childNodes];
177
- this.#emptySnapshot = { nodes, data: nodes.map((n) => n.nodeType === Node.TEXT_NODE ? /** @type {Text} */ (n).data : '') };
178
- return;
169
+ if (!element) return;
170
+ /** @type {Map<Node, Node[]>} */
171
+ const children = new Map([[element, [...element.childNodes]]]);
172
+ /** @type {Map<Text, string>} */
173
+ const data = new Map();
174
+ const walker = document.createTreeWalker(element, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_TEXT, {
175
+ acceptNode: (n) => n.nodeType === Node.ELEMENT_NODE && (/** @type {Element} */ (n).hasAttribute('data-block-id') || /** @type {Element} */ (n).hasAttribute('data-nabu-ui')) ? NodeFilter.FILTER_REJECT : NodeFilter.FILTER_ACCEPT,
176
+ });
177
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
178
+ if (n.nodeType === Node.TEXT_NODE) data.set(/** @type {Text} */ (n), /** @type {Text} */ (n).data);
179
+ else children.set(n, [...n.childNodes]);
179
180
  }
180
- const filler = element?.querySelector('[data-nabu-filler]');
181
- if (!element || !filler?.parentNode) return;
182
- const texts = new Set();
183
- const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
184
- for (let n = walker.nextNode(); n; n = walker.nextNode()) texts.add(n);
185
- this.#compositionSnapshot = { texts, filler, parent: filler.parentNode, next: filler.nextSibling };
181
+ this.#compositionSnapshot = { text: this.text, children, data };
186
182
  }
187
183
 
188
184
  /**
189
- * End of a composition begun next to a filler, BEFORE the composed text reaches the model: remove the text nodes and
190
- * `<br>` the browser created meanwhile (the composed text is committed to the model, which the next render shows
191
- * through Svelte's own nodes); a canceled composition (`composedText` empty) gets its filler back.
192
- * @param {string} composedText
185
+ * End of a composition, BEFORE the composed text reaches the model: the render goes back as Svelte left it, and the model shows
186
+ * the composed text through it on the next render, in the run it really belongs to. Without this Svelte updates nodes that are
187
+ * no longer in the page (the DOM freezes while the model moves on), or the text shows twice.
188
+ * If the model changed meanwhile (a programmatic edit), Svelte has already rendered over the snapshot: it stays as it is.
193
189
  */
194
- restoreAfterComposition(composedText) {
190
+ restoreAfterComposition() {
195
191
  const snap = this.#compositionSnapshot;
196
192
  this.#compositionSnapshot = null;
197
- const element = this.block.element;
198
- const empty = this.#emptySnapshot;
199
- this.#emptySnapshot = null;
200
- if (empty && element && !composedText) {
201
- // Canceled in an empty block: the render text node (not a browser <br>) with its text, as Svelte left it.
202
- element.replaceChildren(...empty.nodes);
203
- empty.nodes.forEach((n, i) => { if (n.nodeType === Node.TEXT_NODE && /** @type {Text} */ (n).data !== empty.data[i]) /** @type {Text} */ (n).data = empty.data[i]; });
204
- return;
205
- }
206
- if (!snap || !element) return;
207
- /** @type {Node[]} */
208
- const stray = [];
209
- const walker = document.createTreeWalker(element, NodeFilter.SHOW_TEXT);
210
- for (let n = walker.nextNode(); n; n = walker.nextNode()) if (!snap.texts.has(n)) stray.push(n);
211
- for (const br of element.querySelectorAll('br')) if (br !== snap.filler) stray.push(br);
212
- for (const n of stray) n.parentNode?.removeChild(n);
213
- if (!composedText && !snap.filler.isConnected) {
214
- snap.parent.insertBefore(snap.filler, snap.next?.parentNode === snap.parent ? snap.next : null);
193
+ if (!snap || this.text !== snap.text) return;
194
+ for (const [parent, nodes] of snap.children) {
195
+ const now = parent.childNodes;
196
+ if (now.length !== nodes.length || nodes.some((n, i) => n !== now[i])) /** @type {Element} */ (parent).replaceChildren(...nodes);
215
197
  }
198
+ for (const [node, data] of snap.data) if (node.data !== data) node.data = data;
216
199
  }
217
200
 
218
201
  /**
@@ -323,18 +306,26 @@ export class TextBehavior {
323
306
 
324
307
  if (!selection.isCollapsed) this.delete({index: selection.from, length: selection.to - selection.from}, selection);
325
308
  this.insert(selection.from, textToInsert);
326
- // Apply the cursor's pending stored marks to the inserted text.
309
+ this.markTypedRun(selection.from, textToInsert.length);
310
+ this.block.commit();
311
+ tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
312
+ }
313
+
314
+ /**
315
+ * The marks of a run the user just typed or composed at `[from, from + length)`: the cursor's pending stored marks, then the rule
316
+ * for mark edges.
317
+ * @param {number} from @param {number} length
318
+ */
319
+ markTypedRun(from, length) {
327
320
  const stored = this.nabu.storedMarks;
328
- if (stored && textToInsert) {
329
- const range = { from: selection.from, to: selection.from + textToInsert.length, isCollapsed: false };
321
+ if (stored && length) {
322
+ const range = { from, to: from + length, isCollapsed: false };
330
323
  for (const [name, on] of Object.entries(stored)) {
331
324
  if (on) this.applyMark(name, true, range);
332
325
  else this.removeMark(name, range);
333
326
  }
334
327
  }
335
- this.settleMarkEdges(selection.from, textToInsert.length, stored);
336
- this.block.commit();
337
- tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
328
+ this.settleMarkEdges(from, length, stored);
338
329
  }
339
330
 
340
331
  /**
@@ -7,9 +7,11 @@
7
7
  * after the other, with no markup of their own. A long one (`CHUNK_ON` blocks and more) is rendered in chunks of ~64 blocks, each
8
8
  * in a wrapper that the browser may skip while it is off screen (`content-visibility: auto`), which is what keeps a keystroke
9
9
  * in a 10,000-block document within a frame (see chunks.js for the why and the how).
10
- * @type {{ blocks: import('./block.svelte.js').Block[] }}
10
+ * `chunked` (bindable, read only for the parent) reports whether the list is rendered in chunks: a region body that is, leaves
11
+ * the skipping to its chunks (Region.svelte).
12
+ * @type {{ blocks: import('./block.svelte.js').Block[], chunked?: boolean }}
11
13
  */
12
- let { blocks } = $props();
14
+ let { blocks, chunked: isChunked = $bindable(false) } = $props();
13
15
 
14
16
  // Hysteresis: switches on at CHUNK_ON blocks, off under CHUNK_OFF. (Plain variable on purpose: it is only read back by this derived.)
15
17
  let was = false;
@@ -18,6 +20,8 @@
18
20
  return was && supportsChunking();
19
21
  });
20
22
 
23
+ $effect.pre(() => { isChunked = chunked; });
24
+
21
25
  // The chunks of the last render, to hand back the unchanged ones as they were.
22
26
  let memo = new Map();
23
27
  const chunks = $derived.by(() => {
@@ -42,6 +46,12 @@
42
46
  overflow-clip-margin: var(--nb-clip-margin, 3rem);
43
47
  }
44
48
 
49
+ /* Never nested (see the large documents note in region/Region.svelte: WebKit pays for it on every keystroke): a chunk inside a chunk
50
+ (a region body of 500 blocks among the blocks of a chunk) is left visible, the outer one already skips what it holds. */
51
+ .nabu-chunk :global(.nabu-chunk) {
52
+ content-visibility: visible;
53
+ }
54
+
45
55
  @media print {
46
56
  .nabu-chunk { content-visibility: visible; }
47
57
  }
@@ -5,13 +5,17 @@ type BlockList = {
5
5
  };
6
6
  declare const BlockList: import("svelte").Component<{
7
7
  blocks: import("./block.svelte.js").Block[];
8
- }, {}, "">;
8
+ chunked?: boolean;
9
+ }, {}, "chunked">;
9
10
  /**
10
11
  * A list of sibling blocks: the root of the editor, the body of a region. Short lists are rendered as they are, one block
11
12
  * after the other, with no markup of their own. A long one (`CHUNK_ON` blocks and more) is rendered in chunks of ~64 blocks, each
12
13
  * in a wrapper that the browser may skip while it is off screen (`content-visibility: auto`), which is what keeps a keystroke
13
14
  * in a 10,000-block document within a frame (see chunks.js for the why and the how).
15
+ * `chunked` (bindable, read only for the parent) reports whether the list is rendered in chunks: a region body that is, leaves
16
+ * the skipping to its chunks (Region.svelte).
14
17
  */
15
18
  type $$ComponentProps = {
16
19
  blocks: import("./block.svelte.js").Block[];
20
+ chunked?: boolean;
17
21
  };
@@ -145,6 +145,13 @@ export class Nabu {
145
145
  * @public
146
146
  */
147
147
  public get lang(): string | undefined;
148
+ /**
149
+ * The function that counts words: the `countWords` option, or the default rule (`countWords` of `utils/words.js`, also exported
150
+ * by the package). Fixed at creation.
151
+ * @type {import('../utils/words.js').WordCounter}
152
+ * @public
153
+ */
154
+ public countWords: import("../utils/words.js").WordCounter;
148
155
  public set readonly(value: boolean);
149
156
  /**
150
157
  * Read-only mode (see the `readonly` option of NabuInit). Reactive: assign to switch it on or off at runtime. While `true`
@@ -792,6 +799,12 @@ export type NabuInit = {
792
799
  * Reactive: `nabu.lang`.
793
800
  */
794
801
  lang?: string | undefined;
802
+ /**
803
+ * - Your own word counter, `(text, lang) => number`, called with the text of
804
+ * one block and the editor's `lang`; it replaces the default rule (Unicode word breaks) everywhere Nabu counts words (`wordCount` of
805
+ * a block, a region...). Given once at creation, not reactive. Not a function: ignored (warning). Read back as `nabu.countWords`.
806
+ */
807
+ countWords?: import("../utils/words.js").WordCounter | undefined;
795
808
  /**
796
809
  * - What Tab / Shift+Tab do in a plain text block, where no block handles them
797
810
  * structurally (list indent, code indentation and region titles keep their own meaning, whatever this says; P-41).
@@ -20,6 +20,7 @@ import { closestWithin } from '../utils/dom-scope.js';
20
20
  import { captureSelection, explicitSelection, legacySelection, restoreSelection, keepSelection, makeEndpoint, resolveOffset, revealFocus } from './undo-selection.js';
21
21
  import { LARGE_DOC } from './chunks.js';
22
22
  import { revealCaret } from '../utils/reveal-caret.js';
23
+ import { countWords as defaultCountWords } from '../utils/words.js';
23
24
  import { markAtCaret } from '../behaviors/text/mark-edges.js';
24
25
  import { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
25
26
  import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
@@ -63,6 +64,9 @@ import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPositio
63
64
  * @property {string} [lang] - Language of the content, a BCP 47 tag (`'fr'`, `'en-GB'`). Set on the root as `lang`, so the browser's
64
65
  * spellchecker, hyphenation and screen readers use it. Unset: inherits the page language. An invalid tag is ignored (warning).
65
66
  * Reactive: `nabu.lang`.
67
+ * @property {import('../utils/words.js').WordCounter} [countWords] - Your own word counter, `(text, lang) => number`, called with the text of
68
+ * one block and the editor's `lang`; it replaces the default rule (Unicode word breaks) everywhere Nabu counts words (`wordCount` of
69
+ * a block, a region...). Given once at creation, not reactive. Not a function: ignored (warning). Read back as `nabu.countWords`.
66
70
  * @property {'focus' | 'stay' | 'indent'} [tab] - What Tab / Shift+Tab do in a plain text block, where no block handles them
67
71
  * structurally (list indent, code indentation and region titles keep their own meaning, whatever this says; P-41).
68
72
  * `'focus'`: the browser default, Tab leaves the editor. `'stay'`: both keys are swallowed and the caret stays; Escape then Tab
@@ -287,6 +291,17 @@ export class Nabu {
287
291
  this.placeholders = normalizePlaceholders(init.placeholders);
288
292
  this.spellcheck = init.spellcheck !== false;
289
293
  this.lang = init.lang;
294
+ /**
295
+ * The function that counts words: the `countWords` option, or the default rule (`countWords` of `utils/words.js`, also exported
296
+ * by the package). Fixed at creation.
297
+ * @type {import('../utils/words.js').WordCounter}
298
+ * @public
299
+ */
300
+ this.countWords = defaultCountWords;
301
+ if (init.countWords !== undefined) {
302
+ if (typeof init.countWords === 'function') this.countWords = init.countWords;
303
+ else this.warn(`Ignoring invalid "countWords" (not a function): ${String(init.countWords)}`);
304
+ }
290
305
  this.readonly = !!init.readonly;
291
306
  this.#tabDefault = resolveTabMode(init.tabDefault, 'focus', (message) => this.warn(message));
292
307
  this.tab = init.tab;
@@ -1480,11 +1495,10 @@ export class Nabu {
1480
1495
  if (this.#readonly && !this.#composing) return;
1481
1496
  this.#composing = false;
1482
1497
  const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
1483
- const composedBlock = this.#compositionStartBlock;
1484
1498
  this.#composingBlock = null;
1485
1499
  restoreEmptyBlocks(this.#swappedEmpties);
1486
1500
  this.#swappedEmpties = [];
1487
- /** @type {any} */ (composedIn)?.restoreAfterComposition?.(e.data || ''); // before the model catches up: no duplicate of the composed text
1501
+ /** @type {any} */ (composedIn)?.restoreAfterComposition?.(); // before the model catches up: no duplicate of the composed text
1488
1502
  try {
1489
1503
  this.#syncComposition(e);
1490
1504
  } finally {
@@ -1492,11 +1506,6 @@ export class Nabu {
1492
1506
  }
1493
1507
  this.selection.normalize(); // a dead caret must not survive the composition
1494
1508
  this.#revealSoon();
1495
- // A canceled composition in an EMPTY block: its render is back (restoreAfterComposition), so is the caret.
1496
- if (!(e.data || '') && composedBlock && composedBlock.element?.isConnected && !composedIn?.text) {
1497
- this.selection.setCursor(composedBlock, 0);
1498
- tick().then(() => { if (!this.#composing && composedBlock.element?.isConnected && !composedIn?.text) this.selection.setCursor(composedBlock, 0); });
1499
- }
1500
1509
  }
1501
1510
 
1502
1511
  /** @param {CompositionEvent} e */
@@ -1519,10 +1528,6 @@ export class Nabu {
1519
1528
  const behavior = block.behaviors?.get('text');
1520
1529
  if (!behavior) return;
1521
1530
 
1522
- // Canceled composition (Escape) fires compositionend with e.data === ''.
1523
- const composedText = e.data || '';
1524
- if (!composedText) return;
1525
-
1526
1531
  // Where the composition began NOW: the Loro cursors followed every edit of this text made meanwhile (P-101).
1527
1532
  if (anchor) {
1528
1533
  const moved = resolveOffset(this.doc, anchor, behavior.container.length);
@@ -1530,7 +1535,20 @@ export class Nabu {
1530
1535
  }
1531
1536
  startOffset = Math.max(0, Math.min(startOffset, behavior.container.length));
1532
1537
 
1538
+ // Canceled composition (Escape) fires compositionend with e.data === ''. The render is back (restoreAfterComposition), and the
1539
+ // caret with it, unless the user went to another block.
1540
+ const composedText = e.data || '';
1541
+ if (!composedText) {
1542
+ const at = startOffset;
1543
+ this.selection.sync();
1544
+ if (this.selection.anchorBlock !== block) return;
1545
+ this.selection.setCursor(block, at);
1546
+ tick().then(() => { if (!this.#composing && block.element?.isConnected && this.selection.anchorBlock === block) this.selection.setCursor(block, at); });
1547
+ return;
1548
+ }
1549
+
1533
1550
  behavior.insert(startOffset, composedText);
1551
+ behavior.markTypedRun?.(startOffset, composedText.length); // the same marks as if it had been typed
1534
1552
  block.commit();
1535
1553
  const caret = startOffset + composedText.length;
1536
1554
  tick().then(() => {
@@ -11,6 +11,10 @@
11
11
 
12
12
  // A large document (Nabu.svelte sets `data-nabu-large` on the root): the body is skipped by the browser while off screen, see the style below.
13
13
  const large = $derived(block.nabu.blocks.size >= LARGE_DOC);
14
+ // A LEAF body (no region among its direct children) is the only one the browser may skip, see the style below. Reactive: a region
15
+ // dropped into the body, or the last one taken out, flips it. A body rendered in chunks (reported by its BlockList) leaves it to them.
16
+ const leaf = $derived(!block.children.some((child) => child.type === 'region'));
17
+ let chunked = $state(false);
14
18
  const region = $derived(Regions.get(block.nabu).of(block));
15
19
  const level = $derived(Math.min(6, Math.max(1, region?.level ?? 1)));
16
20
  // The label template applied with an EMPTY title ("1.", "1.1", "Chapter 2"): the editable title follows it.
@@ -83,22 +87,27 @@
83
87
  data-block-type="region"
84
88
  data-nabu-isolated
85
89
  data-placeholder={block.placeholder}
86
- ><RichText delta={block.delta} /></div><span class="nabu-region-rule" data-nabu-ui contenteditable="false" aria-hidden="true">{#if pending}<span class="nabu-region-drain"></span>{/if}</span></div><div class="nabu-region-body" style:--nb-region-blocks={large ? block.weight : undefined}><BlockList blocks={block.children} /></div>{#if endText}<!-- Never a caret stop (not editable, not selectable) and not read as text: a separator named by the same sentence. --><div class="nabu-region-end" data-region-end data-nabu-ui contenteditable="false" role="separator" aria-label={endText}><span class="nabu-region-end-rule" aria-hidden="true"></span><span class="nabu-region-end-text" aria-hidden="true">{endText}</span></div>{/if}</div>
90
+ ><RichText delta={block.delta} /></div><span class="nabu-region-rule" data-nabu-ui contenteditable="false" aria-hidden="true">{#if pending}<span class="nabu-region-drain"></span>{/if}</span></div><div class="nabu-region-body" data-region-leaf={leaf && !chunked ? '' : undefined} style:--nb-region-blocks={large ? block.weight : undefined}><BlockList blocks={block.children} bind:chunked /></div>{#if endText}<!-- Never a caret stop (not editable, not selectable) and not read as text: a separator named by the same sentence. --><div class="nabu-region-end" data-region-end data-nabu-ui contenteditable="false" role="separator" aria-label={endText}><span class="nabu-region-end-rule" aria-hidden="true"></span><span class="nabu-region-end-text" aria-hidden="true">{endText}</span></div>{/if}</div>
87
91
 
88
92
  <style>
89
93
  /* ── Large documents ── In a large document (`data-nabu-large`, 800 blocks) the body of a region is skipped by the browser while it is off screen
90
94
  (`content-visibility: auto`): its layout, paint and selection bookkeeping no longer grow with the size of the document, which is
91
95
  what keeps a keystroke within a frame at 10,000 blocks. Until it has been shown once its height is an estimate (its number of
92
- blocks times --nb-block-estimate, 72px); `auto` then remembers the real one. A small document is left exactly as it was. */
93
- :global(.nabu-editor[data-nabu-large]) .nabu-region-body {
94
- content-visibility: auto;
95
- contain-intrinsic-block-size: auto calc(var(--nb-region-blocks, 16) * var(--nb-block-estimate, 72px));
96
- /* ...and what it contains may hang out of its box (the margin rail of a sub-region): paint containment would clip it. */
97
- overflow-clip-margin: var(--nb-clip-margin, 3rem);
98
- }
96
+ blocks times --nb-block-estimate, 72px); `auto` then remembers the real one. A small document is left exactly as it was.
99
97
 
100
- @media print {
101
- :global(.nabu-editor[data-nabu-large]) .nabu-region-body { content-visibility: visible; }
98
+ Never nested: an `auto` box must neither contain nor sit inside another one. WebKit pays for the nesting on every keystroke
99
+ (a novel of nested parts > chapters > scenes, caret mid-document: ~380 ms per key at 90,000 words with every body `auto`; 34-40 ms
100
+ with every body visible; 23-26 ms at 90k and 28-30 ms at 150k with `auto` on the LEAF bodies only, flat with the size; `auto` on the
101
+ non-leaf bodies only is as slow as all of them; Chromium is at 9-12 ms either way). So only a leaf body (`data-region-leaf`: no region
102
+ among its children, not itself rendered in chunks, whose `.nabu-chunk` boxes are the `auto` ones then) is skipped, and not when it already
103
+ sits inside a chunk, which skips what it holds. (BlockList.svelte keeps chunks out of chunks the same way.) */
104
+ @media not print {
105
+ :global(.nabu-editor[data-nabu-large] .nabu-region-body[data-region-leaf]:not(.nabu-chunk .nabu-region-body)) {
106
+ content-visibility: auto;
107
+ contain-intrinsic-block-size: auto calc(var(--nb-region-blocks, 16) * var(--nb-block-estimate, 72px));
108
+ /* ...and what it contains may hang out of its box (the margin rail of a sub-region): paint containment would clip it. */
109
+ overflow-clip-margin: var(--nb-clip-margin, 3rem);
110
+ }
102
111
  }
103
112
 
104
113
  /* ── Margin rail: the region that holds the caret (data-region-caret), from its seam to the end of its body ── */
@@ -54,5 +54,15 @@ export function createRegionsExtension(options?: {
54
54
  types?: Record<string, RegionTypeInit>;
55
55
  messages?: RegionMessages;
56
56
  }): import("../../extend.js").Extension;
57
+ /**
58
+ * An editor built with `RegionsExtension`: `nabu.regions` (the registry, same as `Regions.get(nabu)`) is installed by the
59
+ * extension's `onInit` hook, never by the engine, so the `Nabu` type does not have it. `createFullEditor()` returns this type;
60
+ * with your own preset, annotate the editor: `/** @type {RegionsEditor} *\/ (createEditor({ preset }))`, or use `Regions.get(nabu)`.
61
+ */
62
+ export type RegionsEditor = Nabu & {
63
+ readonly regions: Regions;
64
+ };
57
65
  import type { RegionTypeInit } from "./types.js";
58
66
  import type { RegionMessages } from "./messages.js";
67
+ import type { Nabu } from "../nabu.svelte.js";
68
+ import { Regions } from "./regions.svelte.js";
@@ -17,6 +17,13 @@ import { closeOnEnter } from "./close.js";
17
17
  * @import { RegionMessages } from "./messages.js";
18
18
  */
19
19
 
20
+ /**
21
+ * @typedef {Nabu & { readonly regions: Regions }} RegionsEditor
22
+ * An editor built with `RegionsExtension`: `nabu.regions` (the registry, same as `Regions.get(nabu)`) is installed by the
23
+ * extension's `onInit` hook, never by the engine, so the `Nabu` type does not have it. `createFullEditor()` returns this type;
24
+ * with your own preset, annotate the editor: `/** @type {RegionsEditor} *\/ (createEditor({ preset }))`, or use `Regions.get(nabu)`.
25
+ */
26
+
20
27
  /**
21
28
  * @param {Nabu} nabu @param {InputEvent} event @param {import("../block.svelte.js").Block} block
22
29
  */
package/dist/format.d.ts CHANGED
@@ -18,6 +18,7 @@
18
18
  export function jsonToText(json: {
19
19
  blocks?: any[];
20
20
  } | any[]): string;
21
+ export { countWords } from "./utils/words.js";
21
22
  export { deltaToHtml, deltaToMarkdown } from "./behaviors/text/delta-format.js";
22
23
  export { sanitizeUrl, escapeHtml } from "./utils/html.js";
23
24
  export { JSON_FORMAT_VERSION, isSupportedJsonVersion } from "./utils/extensions.js";
package/dist/format.js CHANGED
@@ -12,6 +12,7 @@
12
12
 
13
13
  export { deltaToHtml, deltaToMarkdown } from './behaviors/text/delta-format.js';
14
14
  export { sanitizeUrl, escapeHtml } from './utils/html.js';
15
+ export { countWords } from './utils/words.js';
15
16
  export { JSON_FORMAT_VERSION, isSupportedJsonVersion } from './utils/extensions.js';
16
17
 
17
18
  /** The text of a block's `content`: a plain string (code), or the `text` of its runs. Marks are ignored. @param {unknown} content */
package/dist/index.d.ts CHANGED
@@ -13,6 +13,11 @@ export { FileExtension } from "./blocks/file/index.js";
13
13
  export { insertMediaFromFile } from "./blocks/media/index.js";
14
14
  export { sanitizeUrl } from "./utils/html.js";
15
15
  export { formatChord } from "./utils/keys.js";
16
+ export { countWords } from "./utils/words.js";
17
+ /**
18
+ * A word counter, `(text, lang?) => number`: the `countWords` option.
19
+ */
20
+ export type WordCounter = import("./utils/words.js").WordCounter;
16
21
  /**
17
22
  * The options of an editor: `new Nabu(init)`, the factories and `createPersistedEditor`.
18
23
  */
@@ -21,6 +26,10 @@ export type NabuInit = import("./blocks/nabu.svelte.js").NabuInit;
21
26
  * The options of the editor factories (`createEditor` and the preset factories): every `NabuInit` option plus the `preset` to start from.
22
27
  */
23
28
  export type EditorOptions = import("./presets.js").EditorOptions;
29
+ /**
30
+ * An editor with `nabu.regions` typed (see `RegionsExtension`).
31
+ */
32
+ export type RegionsEditor = import("./blocks/region/region.extension.js").RegionsEditor;
24
33
  /**
25
34
  * The `files` option: uploads, limits, embedding.
26
35
  */
package/dist/index.js CHANGED
@@ -78,16 +78,19 @@ export { JSON_FORMAT_VERSION, CLIPBOARD_FORMAT_VERSION, isSupportedJsonVersion }
78
78
  export { deltaToMarkdown, deltaToHtml } from './behaviors/text/index.js';
79
79
  export { sanitizeUrl } from './utils/html.js';
80
80
  export { formatChord } from './utils/keys.js';
81
+ export { countWords } from './utils/words.js';
81
82
 
82
83
  // ---------------------------------------------------------------------------
83
84
  // Types (JSDoc typedefs, importable as `import('@aionbuilders/nabu').NabuInit`…)
84
85
  // ---------------------------------------------------------------------------
85
86
 
87
+ /** @typedef {import('./utils/words.js').WordCounter} WordCounter A word counter, `(text, lang?) => number`: the `countWords` option. */
86
88
  /** @typedef {import('./blocks/nabu.svelte.js').NabuInit} NabuInit The options of an editor: `new Nabu(init)`, the factories and `createPersistedEditor`. */
87
89
  /**
88
90
  * @typedef {import('./presets.js').EditorOptions} EditorOptions
89
91
  * The options of the editor factories (`createEditor` and the preset factories): every `NabuInit` option plus the `preset` to start from.
90
92
  */
93
+ /** @typedef {import('./blocks/region/region.extension.js').RegionsEditor} RegionsEditor An editor with `nabu.regions` typed (see `RegionsExtension`). */
91
94
  /** @typedef {import('./files/files.svelte.js').FilesConfig} FilesConfig The `files` option: uploads, limits, embedding. */
92
95
  /** @typedef {import('./files/files.svelte.js').EmbeddedAsset} EmbeddedAsset */
93
96
  /** @typedef {import('./utils/placeholders.js').PlaceholdersOption} PlaceholdersOption */
package/dist/presets.d.ts CHANGED
@@ -27,7 +27,7 @@ export function tabDefaultFor(preset: unknown): "focus" | "stay" | "indent";
27
27
  export function createMinimalEditor(options?: EditorOptions): Nabu;
28
28
  export function createTextEditor(options?: EditorOptions): Nabu;
29
29
  export function createDocumentEditor(options?: EditorOptions): Nabu;
30
- export function createFullEditor(options?: EditorOptions): Nabu;
30
+ export function createFullEditor(options?: EditorOptions): RegionsEditor;
31
31
  export { createPersistedEditor } from "./persistence/persistence.js";
32
32
  /**
33
33
  * Options of the editor factories: every `NabuInit` option (`files`, `placeholders`, `snapshot`, `keymap`, `tab`, `lang`…, forwarded to
@@ -41,3 +41,4 @@ export type EditorOptions = Omit<import("./blocks/nabu.svelte.js").NabuInit, "ex
41
41
  };
42
42
  import { Nabu } from './blocks/nabu.svelte.js';
43
43
  import type { Extension } from './utils/extensions.js';
44
+ import type { RegionsEditor } from './blocks/region/region.extension.js';
package/dist/presets.js CHANGED
@@ -1,5 +1,6 @@
1
1
  /**
2
2
  * @import { Extension } from './utils/extensions.js';
3
+ * @import { RegionsEditor } from './blocks/region/region.extension.js';
3
4
  */
4
5
 
5
6
  import { Nabu } from './blocks/nabu.svelte.js';
@@ -106,11 +107,13 @@ export const createDocumentEditor = (options = {}) =>
106
107
  createEditor({ preset: DocumentPreset, ...options });
107
108
 
108
109
  /**
109
- * All built-in blocks + rich text. The full Nabu experience.
110
+ * All built-in blocks + rich text. The full Nabu experience. It includes `RegionsExtension`, so `nabu.regions` is always there
111
+ * (typed without `undefined`).
110
112
  * @param {EditorOptions} [options] every `NabuInit` option (`files`, `snapshot`, `keymap`…) and extra `extensions`
113
+ * @returns {RegionsEditor}
111
114
  */
112
115
  export const createFullEditor = (options = {}) =>
113
- createEditor({ preset: FullPreset, ...options });
116
+ /** @type {RegionsEditor} */ (createEditor({ preset: FullPreset, ...options }));
114
117
 
115
118
  // ---------------------------------------------------------------------------
116
119
  // Persisted factory
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Number of words in a text.
2
+ * Number of words in a text (the default {@link WordCounter} of Nabu).
3
3
  * @param {string} text
4
4
  * @param {string} [lang] BCP 47 tag of the text (the editor's `lang`); unset: the platform default
5
5
  * @returns {number}
@@ -35,6 +35,11 @@ export function wordDeleteRange(text: string, caret: number, direction: "backwar
35
35
  from: number;
36
36
  to: number;
37
37
  };
38
+ /**
39
+ * A word-counting function: the text of one block and the editor's `lang`, the number of words. The `countWords` option of an
40
+ * editor replaces the default one with a function of this shape (see `NabuInit`).
41
+ */
42
+ export type WordCounter = (text: string, lang?: string) => number;
38
43
  export type WordToken = {
39
44
  start: number;
40
45
  end: number;
@@ -16,6 +16,12 @@
16
16
  * one word by the same rules).
17
17
  */
18
18
 
19
+ /**
20
+ * A word-counting function: the text of one block and the editor's `lang`, the number of words. The `countWords` option of an
21
+ * editor replaces the default one with a function of this shape (see `NabuInit`).
22
+ * @typedef {(text: string, lang?: string) => number} WordCounter
23
+ */
24
+
19
25
  /** @type {Map<string, Intl.Segmenter | null>} */
20
26
  const segmenters = new Map();
21
27
 
@@ -42,7 +48,7 @@ function segmenterFor(lang) {
42
48
  const LATIN_WORD = /^[0-9A-Za-zÀ-ÖØ-öø-ɏ]+$/;
43
49
 
44
50
  /**
45
- * Number of words in a text.
51
+ * Number of words in a text (the default {@link WordCounter} of Nabu).
46
52
  * @param {string} text
47
53
  * @param {string} [lang] BCP 47 tag of the text (the editor's `lang`); unset: the platform default
48
54
  * @returns {number}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.5",
3
+ "version": "0.1.7",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",
@@ -18,6 +18,7 @@
18
18
  "build:e2e": "npm run api:model && VITE_NABU_E2E=1 vite build",
19
19
  "test:e2e": "playwright test",
20
20
  "test:e2e:dev": "NABU_E2E_DEV=1 playwright test",
21
+ "test:consumer": "node scripts/consumer-smoke.js",
21
22
  "test": "bun run test:unit && bun run test:e2e"
22
23
  },
23
24
  "files": [