@aionbuilders/nabu 0.1.0 → 0.1.1

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,7 +4,15 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
- ## 0.1.0 — 2026-10-29
7
+ ## 0.1.1 (2026-10-29)
8
+
9
+ Two fixes reported by users of the alpha. No API change.
10
+
11
+ ### Fixed
12
+ - **Japanese (and other IME) input after empty paragraphs** ([#6](https://github.com/aionbuilders/nabu/issues/6)). A composition that started after one or more empty paragraphs could land in an earlier block, or leave the editor stuck in a composing state: the text was lost and Enter stopped working. Chromium locates a composition by plain-text offsets and miscounts the line-break node of each empty block before it; during a composition those nodes are now presented as `<br>` and restored when it ends (nothing changes in the document or the rendering). Covered by `tests/e2e/ime-audit.spec.ts`, section 9.
13
+ - **Word deletion follows the platform conventions** ([#4](https://github.com/aionbuilders/nabu/issues/4)). Alt+Backspace (macOS) and Ctrl+Backspace (Windows, Linux) no longer delete the space before the word: `this is a sentence |` now gives `this is a |`. Word boundaries come from `Intl.Segmenter` (accents, CJK), punctuation is its own stop (`end.|` gives `end|`), and Alt/Ctrl+Delete deletes forward the way each platform does (to the end of the next word on macOS, up to the next word on Windows). Covered by `tests/unit/delete-word.test.js` and `tests/e2e/word-delete.spec.ts`.
14
+
15
+ ## 0.1.0 (2026-10-29)
8
16
 
9
17
  Nabu is in **public beta**: a `0.` version means the API can still change before 1.0. Versioning policy:
10
18
 
@@ -187,7 +195,7 @@ What matters if you upgrade from `0.1.0-beta.0` or an alpha:
187
195
 
188
196
  ### Persistence, files and drag and drop
189
197
 
190
- #### Files — behavior change (ADR 014, lot 1)
198
+ #### Files: behavior change (ADR 014, lot 1)
191
199
  - **Files are no longer stored inside the Loro document.** The bytes of an image / video / file go to a separate **asset store**; the document only holds a reference and a small metadata index. Ref format: `nabu-asset:sha256-<64 hex>` (SHA-256 of the bytes), so the same file added twice (picker, paste, import) is stored ONCE and gets the same ref. The Loro map `assetIndex` holds `hash -> { mime, name, size, url? }` (never bytes; `url` is reserved for the host location, lot 2). Before, every upload stayed forever in the saved snapshot (Loro keeps history), even after the block was deleted.
192
200
  - Stores (`files/store.js`, `persistence/asset-store.js`): `MemoryAssetStore` for `createEditor()` / `new Nabu()` (lost with the page, like the document); `IndexedDBAssetStore` for `createPersistedEditor()` (database `nabu`, object store `assets`, shared by all the documents of the origin). New option `files.store` to plug your own (`has`, `get`, `put`, `delete`, `keys`, optional `stat`). The IndexedDB store also keeps `docRefs[docId] -> hashes`, refreshed on every save (used by the later cleanup).
193
201
  - **IndexedDB schema 1 -> 2**: the `nabu` database goes to version 2 and gains the `assets` and `docRefs` object stores; the upgrade only adds stores, existing snapshots are untouched. Open connections close themselves on a version change, so another tab never blocks the upgrade.
@@ -199,7 +207,7 @@ What matters if you upgrade from `0.1.0-beta.0` or an alpha:
199
207
  - Dev dependency: `fake-indexeddb` (unit tests of the IndexedDB store and schema upgrade).
200
208
  - TODO(ADR-014 lot 3), marked in the code: history modes / compaction / cleanup of unreferenced files, drag and drop (the lot 2 items of this list are done, see below).
201
209
 
202
- #### Files — host mode, outbox, upload state (ADR 014, lot 2)
210
+ #### Files: host mode, outbox, upload state (ADR 014, lot 2)
203
211
  - **Host mode (`files.onBeforePersist`) no longer swaps the ref.** The bytes are ingested into the local store first, the block keeps its `nabu-asset:sha256-…` ref FOREVER (status `pending`), the upload runs in the background with `{ signal, onProgress }`, and on success `assetIndex[hash].url = <ref returned by the hook>` and the block becomes `ready` in a silent commit (not an undo step). On failure: status `error`, local copy kept. Display resolves the local bytes first, then the index `url` (through `files.resolve`). Documents whose blocks hold plain host URLs keep working unchanged. Pasting (`stage`, `adoptAssets`, `importRemote`, beta clipboards) follows the same model: the hash ref is kept, the block is `pending` until the host has the file. **Behaviour change** for hosts: the block ref is no longer the one you return; read it from `assetIndex[hash].url` (the display layer does it for you). `Files#persist(file)` now resolves with the hash ref right after the local write and starts the upload in the background.
204
212
  - The upload queue is driven by the document (new `files/uploads.svelte.js`): a `pending` hash-ref block with local bytes and no host `url` starts an upload (this is also how it resumes after a reload, and how an undo that brings a deleted block back restarts it); an upload whose last block is deleted is aborted through the `AbortSignal`. Only media ref/status changes (and a node deletion while an upload runs) trigger a pass: typing costs nothing.
205
213
  - **Outbox with resume**: the pending uploads (`{ hash, attempts, state }`, per document) are kept next to the asset store, never inside the Loro doc: `IndexedDBOutbox` (`persistence/outbox.js`) for `createPersistedEditor`, `MemoryOutbox` otherwise, `files.outbox` to plug your own (`list`, `put`, `delete`, optional `clear`). **IndexedDB schema 2 -> 3**: new object store `outbox` (keyPath `[docId, hash]`, index `docId`); the upgrade only adds the store, snapshots / assets / docRefs are untouched. On open, pending uploads for files the document references resume automatically; an upload that FAILED is not retried on its own (`block.retry()`); entries for files the document no longer references, already hosted or without a local copy are dropped. A document opened where neither the bytes nor a host url exist (another device, upload not finished) shows `missing` with the reason `interrupted`.
@@ -320,7 +328,7 @@ Reference: `docs/design/import-export.md` (JSON schema with version, markdown ma
320
328
 
321
329
  ### Editing behaviour
322
330
 
323
- #### Editor options — `spellcheck` and `lang`
331
+ #### Editor options: `spellcheck` and `lang`
324
332
  - New init options (accepted by `new Nabu()`, `createEditor` / the factories and `createPersistedEditor`), both reactive at runtime (`nabu.spellcheck`, `nabu.lang`). `spellcheck` (default `true`) drives the root's `spellcheck` attribute; when `false` the root also gets `data-gramm="false"`, `data-gramm_editor="false"` and `data-enable-grammarly="false"` (opt-out hints of the Grammarly extension). Code blocks always stay `spellcheck="false"`. `lang` (BCP 47 tag, invalid -> ignored with `nabu.warn`) sets `lang` on the root for the browser's spellchecker / hyphenation / screen readers; unset = inherit the page language. See the README ("Spellcheck & language", including a privacy note about Chrome's enhanced spell check).
325
333
 
326
334
  #### Multi-block deletion
@@ -428,7 +436,7 @@ Reference: `docs/design/import-export.md` (JSON schema with version, markdown ma
428
436
 
429
437
  ## 0.1.0-beta.0
430
438
 
431
- First beta. The library is feature-complete for the beta milestone: everything beyond the stability baseline is **opt-in** — a dedicated extension or a mounted UI component — so `MinimalPreset` stays paragraph-only. 287/287 unit tests, `prepack` + `publint` clean.
439
+ First beta. The library is feature-complete for the beta milestone: everything beyond the stability baseline is **opt-in** (a dedicated extension or a mounted UI component), so `MinimalPreset` stays paragraph-only. 287/287 unit tests, `prepack` + `publint` clean.
432
440
 
433
441
  ### Stability & packaging
434
442
  - **Beta cut**: version `0.1.0-beta.0`; corrected `repository.url` to the `git+https://….git` form (publint suggestion).
@@ -442,18 +450,18 @@ First beta. The library is feature-complete for the beta milestone: everything b
442
450
  - New declarative **input rules** system: extensions can register `inputRules` (`pattern` tested against the text before the cursor + `handler`). The `--` → `—` substitution moved from `TextBehavior` into the new `TypographyExtension`.
443
451
  - `nabu.transact(mutateFn, cursorIntent?)` centralizes the mutate → commit → setCursor dance. Migrated `mark:*`, `block:transform` and `zone:set*` actions.
444
452
  - Incremental `wordCount`: every block exposes `wordCount` ($derived); containers sum their children. `ZoneBlock` no longer re-traverses its whole subtree on each keystroke.
445
- - **Capability flags** on `Block` — `splitsOnEnter`, `transformsEnabled`, `marksEnabled` (all default `true`): declarative engine opt-outs so a block can shape core behavior without overriding handlers (Code disables inline transforms, void blocks disable Enter-splitting).
453
+ - **Capability flags** on `Block`: `splitsOnEnter`, `transformsEnabled`, `marksEnabled` (all default `true`): declarative engine opt-outs so a block can shape core behavior without overriding handlers (Code disables inline transforms, void blocks disable Enter-splitting).
446
454
 
447
455
  ### Native behavior audit
448
- - Implemented `deleteWordBackward` / `deleteWordForward` / `deleteSoftLineBackward` / `historyUndo` / `historyRedo` inputTypes. Word deletion now removes the whitespace surrounding the word — closes issue #4 (Alt+Delete orphan space).
456
+ - Implemented `deleteWordBackward` / `deleteWordForward` / `deleteSoftLineBackward` / `historyUndo` / `historyRedo` inputTypes. Word deletion now removes the whitespace surrounding the word, which closes issue #4 (Alt+Delete orphan space).
449
457
  - **IME composition support** (closes issue #6): `compositionstart/update/end` are now handled. During composition the browser mutates the DOM freely (`insertCompositionText` is no longer blocked); the composed text is synced into Loro at `compositionend`, with guards for canceled compositions and destroyed blocks.
450
458
 
451
459
  ### New blocks & features
452
460
  - **Blockquote** block (`> ` shortcut, Backspace/Enter de-transformations, markdown/HTML paste rules).
453
- - **Divider** block — first non-textual block (`--- ` shortcut, `<hr>` rendering, markdown `---`).
454
- - **Code** block — multi-line monospace, ```` ``` ```` shortcut, stores plain text only (pluggable syntax highlighting deferred — see `docs/adr/013`).
455
- - **Callout** block — `note` / `tip` / `important` / `warning` / `caution` variants, `! ` shortcut.
456
- - **Toggle** block — collapsible (hybrid MegaBlock: own text + child blocks, collapsed state in metadata; Enter spawns a body child, Backspace de-transforms).
461
+ - **Divider** block: first non-textual block (`--- ` shortcut, `<hr>` rendering, markdown `---`).
462
+ - **Code** block: multi-line monospace, ```` ``` ```` shortcut, stores plain text only (pluggable syntax highlighting deferred, see `docs/adr/013`).
463
+ - **Callout** block: `note` / `tip` / `important` / `warning` / `caution` variants, `! ` shortcut.
464
+ - **Toggle** block: collapsible (hybrid MegaBlock: own text + child blocks, collapsed state in metadata; Enter spawns a body child, Backspace de-transforms).
457
465
  - **Checklist / to-do lists** (`listType: 'todo'`) with interactive checkboxes, plus a reactive **`Todos`** registry (`Todos.get(nabu)`) that mirrors the Zones system for document-wide task tracking.
458
466
  - **Image / Video / File** void media blocks on a shared `MediaBlock` base, with an optimistic local preview while the asset persists.
459
467
  - **Link mark**: `link:set` / `link:remove` / `link:toggle` actions, `<a>` rendering, `[text](href)` markdown and `<a href>` HTML serialization, link parsing on HTML paste.
@@ -465,10 +473,10 @@ First beta. The library is feature-complete for the beta milestone: everything b
465
473
  - **File handling**: by default an uploaded file is stored as a blob in a separate Loro `assets` map (the document stays the single source of truth); a `files.onBeforePersist` hook lets the host redirect uploads to its own backend; `Files.get(nabu).resolve(ref)` turns a stored ref into a display URL. Warns above a 2 MB inline threshold.
466
474
 
467
475
  ### Editor UX
468
- - **Slash menu** (`ui/SlashMenu.svelte`) — opt-in command palette: type `/` to open, filter by typing, `↑`/`↓`+`Enter` to run, `Esc` to close. Built-ins cover Text, Headings 1–3, bulleted / numbered / to-do lists, Code, Callout, Quote, Toggle, Divider, Image, Video, File; extend or override via the `commands` prop.
469
- - **Inline markdown shortcuts** (`MarkdownShortcutsExtension`) — `**bold**`, `__bold__`, `*italic*`, `_italic_`, `` `code` ``, `~~strike~~` transform as you type.
470
- - **Stored marks** (ProseMirror-style active formatting) — toggling a mark at a collapsed cursor (e.g. Ctrl+B) starts formatting for the next typed text; marks now use `expand: 'none'` so they no longer leak past their range; cleared on cursor navigation.
471
- - **Drag handles** (`ui/DragHandle.svelte`) — opt-in overlay: hover a block to reveal a `⠿` grip and drag to reorder. Pointer-events based, custom drop indicator, reorder by proximity via `moveBefore` / `moveAfter` on the Loro tree (single transaction → collaborative & undo-safe), `wrapOrphan` structural repair, and an anti-cycle guard.
476
+ - **Slash menu** (`ui/SlashMenu.svelte`): opt-in command palette: type `/` to open, filter by typing, `↑`/`↓`+`Enter` to run, `Esc` to close. Built-ins cover Text, Headings 1–3, bulleted / numbered / to-do lists, Code, Callout, Quote, Toggle, Divider, Image, Video, File; extend or override via the `commands` prop.
477
+ - **Inline markdown shortcuts** (`MarkdownShortcutsExtension`): `**bold**`, `__bold__`, `*italic*`, `_italic_`, `` `code` ``, `~~strike~~` transform as you type.
478
+ - **Stored marks** (ProseMirror-style active formatting): toggling a mark at a collapsed cursor (e.g. Ctrl+B) starts formatting for the next typed text; marks now use `expand: 'none'` so they no longer leak past their range; cleared on cursor navigation.
479
+ - **Drag handles** (`ui/DragHandle.svelte`): opt-in overlay: hover a block to reveal a `⠿` grip and drag to reorder. Pointer-events based, custom drop indicator, reorder by proximity via `moveBefore` / `moveAfter` on the Loro tree (single transaction → collaborative & undo-safe), `wrapOrphan` structural repair, and an anti-cycle guard.
472
480
 
473
481
  ## alpha.10
474
482
 
@@ -498,23 +506,23 @@ Complete rewrite of `findNearestTextNode` in `selection.svelte.js`. The previous
498
506
  - Shift+arrow into an inert element now corrects only the focus, preserving the anchor (non-collapsed selection)
499
507
  - `data-nabu-ui` elements (zone title input, etc.) bypass normalization entirely
500
508
 
501
- ### Zones — nested zones
509
+ ### Zones: nested zones
502
510
 
503
511
  `zone:insert` and `zone:wrap` now support zones inside zones.
504
512
 
505
513
  - `zone:insert` detects the nearest zone ancestor and inserts inside it rather than always jumping to root level
506
- - `zone:wrap` (single-block) no longer bails when wrapping inside a zone — creates a nested zone at the correct position
514
+ - `zone:wrap` (single-block) no longer bails when wrapping inside a zone, and creates a nested zone at the correct position
507
515
  - `zone:wrap` (multi-block) allows wrapping a selection of zones into a new zone
508
516
 
509
- ### Zones — UI
517
+ ### Zones: UI
510
518
 
511
- - **Breadcrumb (top)** — when a zone is nested, the title area shows the full ancestor chain: `› Partie II › Chapitre 7`
512
- - **Closing chevrons (bottom)** — replaces the plain bottom boundary line with `‹ Partie II ‹ Chapitre 7` right-aligned, indicating zone exit context
513
- - **Word count** — now displayed on all zones, not only nested ones
519
+ - **Breadcrumb (top)**: when a zone is nested, the title area shows the full ancestor chain: `› Partie II › Chapitre 7`
520
+ - **Closing chevrons (bottom)**: replaces the plain bottom boundary line with `‹ Partie II ‹ Chapitre 7` right-aligned, indicating zone exit context
521
+ - **Word count**: now displayed on all zones, not only nested ones
514
522
 
515
- ### BlockGap — inter-block gap system
523
+ ### BlockGap: inter-block gap system
516
524
 
517
- New `BlockGap.svelte` component rendered after every block via `Block.svelte`. Hovering the gap between two blocks reveals a subtle `+` line. Clicking emits `gap:click` via `nabu.exec` with `{ parentId, insertIndex }` — completely agnostic, any extension can handle it.
525
+ New `BlockGap.svelte` component rendered after every block via `Block.svelte`. Hovering the gap between two blocks reveals a subtle `+` line. Clicking emits `gap:click` via `nabu.exec` with `{ parentId, insertIndex }`. It is completely agnostic: any extension can handle it.
518
526
 
519
527
  `ParagraphExtension` registers a `gap:click` handler that inserts a paragraph at the gap position and moves the cursor there. This solves the "two consecutive zones with no way to insert content between them" problem.
520
528
 
@@ -55,7 +55,7 @@ export class TextBehavior {
55
55
  from: number;
56
56
  to: number;
57
57
  isCollapsed: boolean;
58
- direction: "forward" | "backward" | "none";
58
+ direction: "backward" | "forward" | "none";
59
59
  } | null;
60
60
  /** @public */
61
61
  public positions: number;
@@ -75,7 +75,7 @@ export class TextBehavior {
75
75
  from: number;
76
76
  to: number;
77
77
  isCollapsed: boolean;
78
- direction: "forward" | "backward" | "none";
78
+ direction: "backward" | "forward" | "none";
79
79
  } | null;
80
80
  /**
81
81
  * Calcule l'offset textuel d'un point DOM par rapport au début de ce bloc
@@ -120,35 +120,24 @@ export class TextBehavior {
120
120
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
121
121
  handleDeleteContentForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
122
122
  /**
123
- * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux,
124
- * Option+Delete on Mac), including the whitespace that precedes it
125
- * so no orphan space is left behind (issue #4).
123
+ * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux, Option+Backspace on Mac): the whitespace between the
124
+ * caret and the word goes with it, and the caret lands where the word started ("one two |" -> "one |", issue #4).
126
125
  *
127
- * For a collapsed selection the range is always computed from the model
128
- * text, never from `event.getTargetRanges()`: browsers disagree on it
129
- * (Chromium stops right after the previous space, leaving "one two " from
130
- * "one two three"), so the behavior would differ per engine.
131
- * Rule: remove `\s* \S+ \s*` ending at the cursor ("one two three|" -> "one two").
126
+ * For a collapsed selection the range is computed from the model text, never from `event.getTargetRanges()`: browsers
127
+ * disagree on it (Chromium stops right after the previous space, leaving "one two " from "one two three"), so the
128
+ * behavior would differ per engine. The rules (words by `Intl.Segmenter`, punctuation, line breaks) are in
129
+ * {@link wordDeleteRange}. A selection is deleted whole.
132
130
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
133
131
  */
134
- handleDeleteWordBackward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
132
+ handleDeleteWordBackward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): boolean | undefined;
135
133
  /**
136
- * Deletes the word after the cursor (Ctrl+Delete / Option+Fn+Delete).
137
- *
138
- * Like backward deletion, a collapsed selection is resolved from the model
139
- * text only (`getTargetRanges()` is ignored: it is engine-dependent).
140
- * Rule, so that the result never has a double space nor glued words:
141
- * - the cursor is right before the word ("one |two three") -> remove the
142
- * word and its trailing whitespace -> "one three";
143
- * - whitespace sits between the cursor and the word ("one| two three")
144
- * -> remove that leading whitespace and the word, keep the trailing
145
- * whitespace -> "one three";
146
- * - last word of the text -> remove it with its leading whitespace
147
- * ("one two| three" -> "one two").
148
- * If only whitespace remains after the cursor, it is all removed.
134
+ * Deletes the word after the cursor (Ctrl+Delete on Win/Linux, Option+Fn+Delete on Mac). Like the backward deletion it is
135
+ * resolved from the model text only (`getTargetRanges()` is engine-dependent). macOS deletes up to the end of the next
136
+ * word ("one |two three" -> "one | three"), Windows up to the start of the one after ("one |two three" -> "one |three");
137
+ * see {@link wordDeleteRange}. A selection is deleted whole.
149
138
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
150
139
  */
151
- handleDeleteWordForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
140
+ handleDeleteWordForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): boolean | undefined;
152
141
  /**
153
142
  * Deletes from the start of the current line to the cursor (Cmd+Backspace on Mac; `deleteHardLineBackward`).
154
143
  * A selection inside the block is deleted whole.
@@ -6,7 +6,8 @@ import { LoroText } from "loro-crdt";
6
6
  import { tick } from "svelte";
7
7
  import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
8
8
  import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
9
- import { countWords } from "../../utils/words.js";
9
+ import { countWords, wordDeleteRange } from "../../utils/words.js";
10
+ import { detectPlatform } from "../../utils/keys.js";
10
11
 
11
12
  /**
12
13
  * Converts a Loro text delta to inline HTML.
@@ -559,73 +560,34 @@ export class TextBehavior {
559
560
  }
560
561
 
561
562
  /**
562
- * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux,
563
- * Option+Delete on Mac), including the whitespace that precedes it
564
- * so no orphan space is left behind (issue #4).
563
+ * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux, Option+Backspace on Mac): the whitespace between the
564
+ * caret and the word goes with it, and the caret lands where the word started ("one two |" -> "one |", issue #4).
565
565
  *
566
- * For a collapsed selection the range is always computed from the model
567
- * text, never from `event.getTargetRanges()`: browsers disagree on it
568
- * (Chromium stops right after the previous space, leaving "one two " from
569
- * "one two three"), so the behavior would differ per engine.
570
- * Rule: remove `\s* \S+ \s*` ending at the cursor ("one two three|" -> "one two").
566
+ * For a collapsed selection the range is computed from the model text, never from `event.getTargetRanges()`: browsers
567
+ * disagree on it (Chromium stops right after the previous space, leaving "one two " from "one two three"), so the
568
+ * behavior would differ per engine. The rules (words by `Intl.Segmenter`, punctuation, line breaks) are in
569
+ * {@link wordDeleteRange}. A selection is deleted whole.
571
570
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
572
571
  */
573
572
  handleDeleteWordBackward(event, sel = this.selection) {
574
573
  if (!sel) return;
575
- if (!sel.isCollapsed) {
576
- this.delete({ index: sel.from, length: sel.to - sel.from });
577
- this.block.commit();
578
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
579
- return true;
580
- }
581
- const textBefore = this.text.slice(0, sel.from);
582
- // \s* leading : l'espace qui précède le mot est supprimé aussi (comportement Mac)
583
- const wordMatch = textBefore.match(/(\s*\S+\s*)$/);
584
- const deleteFrom = wordMatch ? sel.from - wordMatch[0].length : 0;
585
- const len = sel.from - deleteFrom;
586
- if (len > 0) this.delete({ index: deleteFrom, length: len });
587
- this.block.commit();
588
- tick().then(() => this.nabu.selection.setCursor(this.block, deleteFrom));
589
- return true;
574
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
575
+ const { from } = wordDeleteRange(this.text, sel.from, 'backward', { lang: this.nabu?.lang });
576
+ return this.#deleteSpan(from, sel.from);
590
577
  }
591
578
 
592
579
  /**
593
- * Deletes the word after the cursor (Ctrl+Delete / Option+Fn+Delete).
594
- *
595
- * Like backward deletion, a collapsed selection is resolved from the model
596
- * text only (`getTargetRanges()` is ignored: it is engine-dependent).
597
- * Rule, so that the result never has a double space nor glued words:
598
- * - the cursor is right before the word ("one |two three") -> remove the
599
- * word and its trailing whitespace -> "one three";
600
- * - whitespace sits between the cursor and the word ("one| two three")
601
- * -> remove that leading whitespace and the word, keep the trailing
602
- * whitespace -> "one three";
603
- * - last word of the text -> remove it with its leading whitespace
604
- * ("one two| three" -> "one two").
605
- * If only whitespace remains after the cursor, it is all removed.
580
+ * Deletes the word after the cursor (Ctrl+Delete on Win/Linux, Option+Fn+Delete on Mac). Like the backward deletion it is
581
+ * resolved from the model text only (`getTargetRanges()` is engine-dependent). macOS deletes up to the end of the next
582
+ * word ("one |two three" -> "one | three"), Windows up to the start of the one after ("one |two three" -> "one |three");
583
+ * see {@link wordDeleteRange}. A selection is deleted whole.
606
584
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
607
585
  */
608
586
  handleDeleteWordForward(event, sel = this.selection) {
609
587
  if (!sel) return;
610
- if (!sel.isCollapsed) {
611
- this.delete({ index: sel.from, length: sel.to - sel.from });
612
- this.block.commit();
613
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
614
- return true;
615
- }
616
- const textAfter = this.text.slice(sel.from);
617
- const wordMatch = textAfter.match(/^(\s*)(\S+)(\s*)/);
618
- let len;
619
- if (!wordMatch) len = textAfter.length;
620
- else {
621
- const [, leading, word, trailing] = wordMatch;
622
- // Leading whitespace present: keep the trailing one as the separator.
623
- len = leading ? leading.length + word.length : word.length + trailing.length;
624
- }
625
- if (len > 0) this.delete({ index: sel.from, length: len });
626
- this.block.commit();
627
- tick().then(() => this.nabu.selection.setCursor(this.block, sel.from));
628
- return true;
588
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
589
+ const { to } = wordDeleteRange(this.text, sel.from, 'forward', { platform: detectPlatform(), lang: this.nabu?.lang });
590
+ return this.#deleteSpan(sel.from, to);
629
591
  }
630
592
 
631
593
  /**
@@ -82,7 +82,7 @@ export class ListItem extends MegaBlock {
82
82
  from: number;
83
83
  to: number;
84
84
  isCollapsed: boolean;
85
- direction: "forward" | "backward" | "none";
85
+ direction: "backward" | "forward" | "none";
86
86
  } | null;
87
87
  /** Every sublist, in order: an item may hold several, of different types (`a > [ul[…], ol[…], ul[…]]`). */
88
88
  sublists: Block[];
@@ -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 { swapEmptyBlocks, restoreEmptyBlocks } from '../utils/composition.js';
21
22
  import { transferKind, wantsCopy, pickDropEffect, sameTarget, resolveDropPosition, documentEnd, positionInRange, positionAfterRemoval, DRAG_MARKER, NABU_FORMAT } from '../utils/drop.js';
22
23
 
23
24
 
@@ -190,6 +191,8 @@ export class Nabu {
190
191
  * @type {import('./undo-selection.js').Endpoint | null}
191
192
  */
192
193
  #compositionAnchor = null;
194
+ /** Empty blocks before the composing one, their "\n" placeholder swapped for a `<br>` meanwhile (Chromium offset drift, issue #6). @type {Array<{ br: Element, text: Text }>} */
195
+ #swappedEmpties = [];
193
196
  /** The block a composition runs in, reactive: its placeholder is hidden meanwhile (P-103). @type {Block | null} */
194
197
  #composingBlock = $state.raw(null);
195
198
  /**
@@ -1395,6 +1398,8 @@ export class Nabu {
1395
1398
  this.#compositionStartOffset = sel?.from ?? 0;
1396
1399
  this.#compositionAnchor = behavior ? makeEndpoint(anchor, sel?.from ?? 0, 'end') : null;
1397
1400
  this.#composingBlock = anchor;
1401
+ restoreEmptyBlocks(this.#swappedEmpties); // (a composition that never ended)
1402
+ this.#swappedEmpties = swapEmptyBlocks(anchor.element);
1398
1403
  /** @type {any} */ (behavior)?.snapshotForComposition?.();
1399
1404
  }
1400
1405
 
@@ -1441,6 +1446,8 @@ export class Nabu {
1441
1446
  const composedIn = this.#compositionStartBlock?.behaviors?.get('text');
1442
1447
  const composedBlock = this.#compositionStartBlock;
1443
1448
  this.#composingBlock = null;
1449
+ restoreEmptyBlocks(this.#swappedEmpties);
1450
+ this.#swappedEmpties = [];
1444
1451
  /** @type {any} */ (composedIn)?.restoreAfterComposition?.(e.data || ''); // before the model catches up: no duplicate of the composed text
1445
1452
  try {
1446
1453
  this.#syncComposition(e);
@@ -125,7 +125,7 @@ export class RegionBlock extends MegaBlock {
125
125
  from: number;
126
126
  to: number;
127
127
  isCollapsed: boolean;
128
- direction: "forward" | "backward" | "none";
128
+ direction: "backward" | "forward" | "none";
129
129
  } | null;
130
130
  /** @type {number} */
131
131
  weight: number;
@@ -40,7 +40,7 @@ export class TextBlock extends Block {
40
40
  from: number;
41
41
  to: number;
42
42
  isCollapsed: boolean;
43
- direction: "forward" | "backward" | "none";
43
+ direction: "backward" | "forward" | "none";
44
44
  } | null;
45
45
  /**
46
46
  * @param {Block} block
@@ -89,7 +89,7 @@ export class ToggleBlock extends MegaBlock {
89
89
  from: number;
90
90
  to: number;
91
91
  isCollapsed: boolean;
92
- direction: "forward" | "backward" | "none";
92
+ direction: "backward" | "forward" | "none";
93
93
  } | null;
94
94
  /**
95
95
  * Set the collapsed state and persist to Loro (in a read-only editor: only what the reader sees, see {@link ToggleBlock#collapsed}).
@@ -0,0 +1,28 @@
1
+ /**
2
+ * Chromium workaround for IME compositions that start after an EMPTY block (issue #6).
3
+ *
4
+ * An empty block renders a lone "\n" text node (one line, see RichText.svelte). Chromium locates the running composition by
5
+ * PLAIN-TEXT offsets from the editable root, and the two directions of that mapping disagree on such a node: every lone "\n"
6
+ * block BEFORE the composition drifts its start back by one, so the composed text lands in the wrong (previous) block and the
7
+ * next `compositionupdate` deletes the blocks in between — the commit never lands. A `<br>` in the same place maps cleanly.
8
+ *
9
+ * So for the duration of a composition the lone "\n" nodes before the composing block are swapped for a `<br>` (same single
10
+ * line), and put back at its end, before the model catches up. Nothing in the model or the Svelte-owned nodes changes.
11
+ */
12
+ /**
13
+ * Swap, in the document before `element`, every empty block's lone "\n" text node for a `<br>`.
14
+ * @param {Element | null | undefined} element the block holding the composition
15
+ * @returns {Array<{ br: Element, text: Text }>} what {@link restoreEmptyBlocks} puts back
16
+ */
17
+ export function swapEmptyBlocks(element: Element | null | undefined): Array<{
18
+ br: Element;
19
+ text: Text;
20
+ }>;
21
+ /**
22
+ * Put the "\n" text nodes back (Svelte keeps references to them). A `<br>` the browser or Svelte already removed is skipped.
23
+ * @param {Array<{ br: Element, text: Text }>} swapped
24
+ */
25
+ export function restoreEmptyBlocks(swapped: Array<{
26
+ br: Element;
27
+ text: Text;
28
+ }>): void;
@@ -0,0 +1,51 @@
1
+ /**
2
+ * Chromium workaround for IME compositions that start after an EMPTY block (issue #6).
3
+ *
4
+ * An empty block renders a lone "\n" text node (one line, see RichText.svelte). Chromium locates the running composition by
5
+ * PLAIN-TEXT offsets from the editable root, and the two directions of that mapping disagree on such a node: every lone "\n"
6
+ * block BEFORE the composition drifts its start back by one, so the composed text lands in the wrong (previous) block and the
7
+ * next `compositionupdate` deletes the blocks in between — the commit never lands. A `<br>` in the same place maps cleanly.
8
+ *
9
+ * So for the duration of a composition the lone "\n" nodes before the composing block are swapped for a `<br>` (same single
10
+ * line), and put back at its end, before the model catches up. Nothing in the model or the Svelte-owned nodes changes.
11
+ */
12
+
13
+ /**
14
+ * Swap, in the document before `element`, every empty block's lone "\n" text node for a `<br>`.
15
+ * @param {Element | null | undefined} element the block holding the composition
16
+ * @returns {Array<{ br: Element, text: Text }>} what {@link restoreEmptyBlocks} puts back
17
+ */
18
+ export function swapEmptyBlocks(element) {
19
+ /** @type {Array<{ br: Element, text: Text }>} */
20
+ const swapped = [];
21
+ const root = element?.closest('[data-nabu-root]');
22
+ if (!element || !root) return swapped;
23
+ const walker = document.createTreeWalker(root, NodeFilter.SHOW_TEXT);
24
+ /** @type {Text[]} */
25
+ const lone = [];
26
+ for (let n = /** @type {Text | null} */ (walker.nextNode()); n; n = /** @type {Text | null} */ (walker.nextNode())) {
27
+ if (!(element.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_PRECEDING)) break; // reached the composing block
28
+ if (n.data !== '\n' || !n.parentNode) continue;
29
+ // Only an empty block's placeholder: nothing but Svelte's anchors (comments, empty text nodes) beside it (no filler <br>, no other text).
30
+ let alone = true;
31
+ for (const s of n.parentNode.childNodes) {
32
+ if (s === n || s.nodeType === Node.COMMENT_NODE || (s.nodeType === Node.TEXT_NODE && !/** @type {Text} */ (s).data)) continue;
33
+ alone = false; break;
34
+ }
35
+ if (alone) lone.push(n);
36
+ }
37
+ for (const text of lone) {
38
+ const br = document.createElement('br');
39
+ text.replaceWith(br);
40
+ swapped.push({ br, text });
41
+ }
42
+ return swapped;
43
+ }
44
+
45
+ /**
46
+ * Put the "\n" text nodes back (Svelte keeps references to them). A `<br>` the browser or Svelte already removed is skipped.
47
+ * @param {Array<{ br: Element, text: Text }>} swapped
48
+ */
49
+ export function restoreEmptyBlocks(swapped) {
50
+ for (const { br, text } of swapped) if (br.parentNode) br.replaceWith(text);
51
+ }
@@ -39,7 +39,7 @@ export class SvelteSelection {
39
39
  public isCollapsed: boolean;
40
40
  rangeCount: number;
41
41
  type: string;
42
- direction: "forward" | "backward" | "none";
42
+ direction: "backward" | "forward" | "none";
43
43
  startNode: Node | null;
44
44
  endNode: Node | null;
45
45
  /** @public */
@@ -5,3 +5,38 @@
5
5
  * @returns {number}
6
6
  */
7
7
  export function countWords(text: string, lang?: string): number;
8
+ /**
9
+ * Word deletion (`deleteWordBackward` / `deleteWordForward`: Ctrl+Backspace / Ctrl+Delete, Option+Backspace / Option+Delete).
10
+ *
11
+ * The text is cut into tokens: a word (`Intl.Segmenter` word granularity, so CJK and accented words are cut as the reader would),
12
+ * a run of punctuation (`...`, `?!`), a run of horizontal whitespace, a line break (`\n`), or any other single
13
+ * segment (an emoji, a symbol). The rules follow what Chromium does in a native `contenteditable` / `<textarea>`:
14
+ *
15
+ * - Backward (same on macOS and Windows): the whitespace before the caret goes with the token before it, and the caret lands at
16
+ * the start of that token: `"this is a sentence |"` -> `"this is a |"`, `"hello world|"` -> `"hello |"`, `"word, |"` -> `"word|"`,
17
+ * `"end.|"` -> `"end|"`. Only whitespace before the caret: all of it, and the token before it.
18
+ * - Forward on macOS (and Linux): up to the END of the next token, whitespace in between included: `"hello| world"` -> `"hello|"`,
19
+ * `"one |two three"` -> `"one | three"`.
20
+ * - Forward on Windows: the next token and the whitespace after it, up to the START of the following one (Chromium's
21
+ * `ShouldSkipSpaceWhenMovingRight`): `"one |two three"` -> `"one |three"`. At whitespace, that whitespace only.
22
+ * - A caret inside a token deletes to the token's edge (`"th|ree"` backward -> `"|ree"`). A line break is deleted by itself, and
23
+ * whitespace never reaches across one. Nothing at the start (backward) or the end (forward) of the text.
24
+ *
25
+ * @param {string} text
26
+ * @param {number} caret offset in `text`
27
+ * @param {'backward' | 'forward'} direction
28
+ * @param {{ platform?: 'mac' | 'other', lang?: string }} [options] `platform`: `'mac'` for the macOS forward rule, anything else is Windows / Linux-as-Windows
29
+ * @returns {{ from: number, to: number }} the span to delete (empty when there is nothing to delete)
30
+ */
31
+ export function wordDeleteRange(text: string, caret: number, direction: "backward" | "forward", { platform, lang }?: {
32
+ platform?: "mac" | "other";
33
+ lang?: string;
34
+ }): {
35
+ from: number;
36
+ to: number;
37
+ };
38
+ export type WordToken = {
39
+ start: number;
40
+ end: number;
41
+ kind: "word" | "punct" | "space" | "break" | "other";
42
+ };
@@ -60,3 +60,88 @@ export function countWords(text, lang) {
60
60
  }
61
61
  return count;
62
62
  }
63
+
64
+ /**
65
+ * Word deletion (`deleteWordBackward` / `deleteWordForward`: Ctrl+Backspace / Ctrl+Delete, Option+Backspace / Option+Delete).
66
+ *
67
+ * The text is cut into tokens: a word (`Intl.Segmenter` word granularity, so CJK and accented words are cut as the reader would),
68
+ * a run of punctuation (`...`, `?!`), a run of horizontal whitespace, a line break (`\n`), or any other single
69
+ * segment (an emoji, a symbol). The rules follow what Chromium does in a native `contenteditable` / `<textarea>`:
70
+ *
71
+ * - Backward (same on macOS and Windows): the whitespace before the caret goes with the token before it, and the caret lands at
72
+ * the start of that token: `"this is a sentence |"` -> `"this is a |"`, `"hello world|"` -> `"hello |"`, `"word, |"` -> `"word|"`,
73
+ * `"end.|"` -> `"end|"`. Only whitespace before the caret: all of it, and the token before it.
74
+ * - Forward on macOS (and Linux): up to the END of the next token, whitespace in between included: `"hello| world"` -> `"hello|"`,
75
+ * `"one |two three"` -> `"one | three"`.
76
+ * - Forward on Windows: the next token and the whitespace after it, up to the START of the following one (Chromium's
77
+ * `ShouldSkipSpaceWhenMovingRight`): `"one |two three"` -> `"one |three"`. At whitespace, that whitespace only.
78
+ * - A caret inside a token deletes to the token's edge (`"th|ree"` backward -> `"|ree"`). A line break is deleted by itself, and
79
+ * whitespace never reaches across one. Nothing at the start (backward) or the end (forward) of the text.
80
+ *
81
+ * @param {string} text
82
+ * @param {number} caret offset in `text`
83
+ * @param {'backward' | 'forward'} direction
84
+ * @param {{ platform?: 'mac' | 'other', lang?: string }} [options] `platform`: `'mac'` for the macOS forward rule, anything else is Windows / Linux-as-Windows
85
+ * @returns {{ from: number, to: number }} the span to delete (empty when there is nothing to delete)
86
+ */
87
+ export function wordDeleteRange(text, caret, direction, { platform = 'other', lang } = {}) {
88
+ const empty = { from: caret, to: caret };
89
+ if (direction === 'backward' ? caret <= 0 : caret >= text.length) return empty;
90
+ const tokens = wordTokens(text, lang);
91
+ const i = tokens.findIndex((t) => direction === 'backward' ? t.start < caret && caret <= t.end : t.start <= caret && caret < t.end);
92
+ if (i === -1) return empty;
93
+ const token = tokens[i];
94
+ if (direction === 'backward') {
95
+ let from = token.start;
96
+ if (token.kind === 'space' && i > 0 && tokens[i - 1].kind !== 'break') from = tokens[i - 1].start;
97
+ return { from, to: caret };
98
+ }
99
+ let to = token.end;
100
+ const next = tokens[i + 1];
101
+ if (next && next.kind !== 'break') {
102
+ // macOS: whitespace then the word after it; Windows: the word then the whitespace after it.
103
+ if (platform === 'mac' ? token.kind === 'space' : token.kind !== 'space' && token.kind !== 'break' && next.kind === 'space') to = next.end;
104
+ }
105
+ return { from: caret, to };
106
+ }
107
+
108
+ /** @typedef {{ start: number, end: number, kind: 'word' | 'punct' | 'space' | 'break' | 'other' }} WordToken */
109
+
110
+ const PUNCT = /^\p{P}+$/u;
111
+ const WORDISH = /^[\p{L}\p{N}\p{M}_]+$/u;
112
+
113
+ /**
114
+ * @param {string} text @param {string | undefined} lang
115
+ * @returns {WordToken[]}
116
+ */
117
+ function wordTokens(text, lang) {
118
+ /** @type {WordToken[]} */
119
+ const tokens = [];
120
+ /** @param {number} start @param {string} piece @param {boolean | undefined} wordLike */
121
+ const push = (start, piece, wordLike) => {
122
+ /** @type {WordToken['kind']} */
123
+ let kind;
124
+ if (piece === '\n') kind = 'break';
125
+ else if (/^[^\S\n]+$/.test(piece)) kind = 'space';
126
+ else if (wordLike ?? WORDISH.test(piece)) kind = 'word';
127
+ else if (PUNCT.test(piece)) kind = 'punct';
128
+ else kind = 'other';
129
+ const last = tokens[tokens.length - 1];
130
+ // Runs of punctuation (`...`, `?!`) and of whitespace are one token; words are not merged (the segmenter decided).
131
+ if (last && last.end === start && last.kind === kind && (kind === 'punct' || kind === 'space')) last.end = start + piece.length;
132
+ else tokens.push({ start, end: start + piece.length, kind });
133
+ };
134
+ const segmenter = segmenterFor(lang);
135
+ if (segmenter) {
136
+ for (const part of segmenter.segment(text)) {
137
+ // UAX #29 keeps `foo.bar` whole (a dot between letters); an editor stops at the dot, as Chromium does.
138
+ if (part.isWordLike && part.segment.includes('.')) {
139
+ let at = part.index;
140
+ for (const piece of part.segment.split(/(?<=\p{L})(\.)(?=\p{L})/u)) { push(at, piece, piece !== '.'); at += piece.length; }
141
+ } else push(part.index, part.segment, part.isWordLike);
142
+ }
143
+ } else {
144
+ for (const m of text.matchAll(/[\p{L}\p{N}\p{M}_]+|\p{P}+|[^\S\n]+|\n|[\s\S]/gu)) push(m.index, m[0], undefined);
145
+ }
146
+ return tokens;
147
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aionbuilders/nabu",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "scripts": {
5
5
  "dev": "vite dev",
6
6
  "predev": "npm run api:model:ensure",
@@ -12,6 +12,7 @@
12
12
  "prepack": "bunx svelte-kit sync && bunx svelte-package && bunx publint",
13
13
  "check": "npm run api:model:ensure && svelte-kit sync && svelte-check --tsconfig ./jsconfig.json",
14
14
  "check:watch": "svelte-kit sync && svelte-check --tsconfig ./jsconfig.json --watch",
15
+ "history": "node scripts/history.js",
15
16
  "test:unit": "vitest run",
16
17
  "test:unit:watch": "vitest",
17
18
  "build:e2e": "npm run api:model && VITE_NABU_E2E=1 vite build",
@@ -61,6 +62,7 @@
61
62
  "devDependencies": {
62
63
  "@fontsource/inter": "^5.3.0",
63
64
  "@fontsource/jetbrains-mono": "^5.3.0",
65
+ "@fontsource/newsreader": "^5.3.0",
64
66
  "@fontsource/syne": "^5.3.0",
65
67
  "@playwright/test": "^1.58.2",
66
68
  "@sveltejs/adapter-node": "^6.0.0",