@aionbuilders/nabu 0.1.0 → 0.1.2

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,28 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
- ## 0.1.0 — 2026-10-29
7
+ ## 0.1.2 (2026-10-29)
8
+
9
+ Fixes from the first days of the beta: rich text that stayed split after removing a mark, mark edges, Ctrl+B at the edge of a word, and code block editing. No API change.
10
+
11
+ ### Fixed
12
+ - **A mark removed over exactly the range it was applied to left the text in two pieces.** Bolding `[18, 21)` then un-bolding `[18, 21)` gave `The ford is upstre` + `am.` in the JSON export, the HTML and the DOM (two text nodes: a spellcheck squiggle, a double-click or a word delete could stop at the seam). The cause is in Loro: `LoroText.toDelta()` keeps the split in that case (a wider unmark merges it), and it is stored in snapshots. Every read of a text delta now goes through one canonical form (`readDelta`: adjacent runs with the same marks are merged, an off mark is an absent mark), so documents saved with the split are read right too. Covered by `tests/unit/delta.test.js`, `tests/unit/marks-canonical.test.js` (seeded fuzz) and `tests/e2e/marks-canonical.spec.ts`.
13
+ - **Code block editing.** The slash menu no longer opens inside a code block (`/` is text there, and Enter after it turned the block into a list). Tab and Shift+Tab indent and outdent every line of a multi-line selection and keep the selection; Shift+Tab also removes a tab character. Enter keeps the indentation of the line. A long line scrolls to keep the caret visible. Ctrl/Cmd+A selects the code first, the whole document on the second press. ArrowUp on the first line of a code block that starts the document creates a paragraph before it, as ArrowDown already did after it. Pasted `\r\n` and `\r` line endings become `\n`. Covered by `tests/e2e/code-editing.spec.ts` and `tests/unit/code-indent.test.js`.
14
+ - **Code block languages.** Names such as `c++`, `c#` or `objective-c` work in the ```` ``` ```` + Enter shortcut and on paste; the language select shows a language that is not in its list (`ts`, `js`) instead of a blank; the HTML export writes `<pre><code class="language-js">` (it dropped the language); the HTML import also reads `lang-`, `data-language` and GitHub's `highlight-source-*` wrapper, and turns `<br>` inside `<pre>` into line breaks. The inline-code style no longer tints the code block.
15
+ - **A code block was a keyboard trap.** Tab always indented, so a keyboard user could neither leave the block nor reach its language select (WCAG 2.1.2). Escape then Tab now moves the focus out of the editor, and Escape then Shift+Tab focuses the language select, the same convention as CodeMirror and GitHub. Any other key or a click closes the way out, a plain Tab still indents, and Tab elsewhere is unchanged. The select no longer sits in the Tab order of the page, where it would have caught the Tab of every block above it.
16
+ - **```` ``` ```` + Space makes a code block.** Like `#`, `>` and `-`, the fence shortcut now fires on Space as well as Enter, with a language too (```` ```js ````), when the paragraph is exactly the fence and the caret is at its end. One undo gives back what was typed.
17
+ - **Where marks end no longer depends on the history of the text.** Two texts that look the same could behave differently when typed into at the edge of a mark: a sentence in bold with a word then un-bolded made the character typed at the start of that word bold, the same text made of two bold ranges did not (a Loro quirk, [loro-dev/loro#1240](https://github.com/loro-dev/loro/issues/1240)). Typed text now always follows one rule: it keeps a mark only when the characters on both sides have it (a mark armed with Ctrl+B still wins). The correction is part of the typing step, so one undo removes the text. Canary tests in `tests/unit/loro-quirks.test.js` fail when Loro fixes this and the correction can go.
18
+ - **Ctrl+B (and Ctrl+I, Ctrl+E…) at the end of a marked word could not extend the mark.** With the caret right after a bold word, the shortcut read the bold of the character before the caret as "active" and armed bold off, although text typed there is plain: the first press did nothing visible and you needed a second one. At a caret, "active" now means what typing there would produce (the same rule as the edges of a mark: the characters on both sides have it), so at the end or the start of a bold word the first press arms bold on, and inside the word it arms it off. A selection range, and a mark that was already armed, behave as before.
19
+
20
+ ## 0.1.1 (2026-10-29)
21
+
22
+ Two fixes reported by users of the alpha. No API change.
23
+
24
+ ### Fixed
25
+ - **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.
26
+ - **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`.
27
+
28
+ ## 0.1.0 (2026-10-29)
8
29
 
9
30
  Nabu is in **public beta**: a `0.` version means the API can still change before 1.0. Versioning policy:
10
31
 
@@ -187,7 +208,7 @@ What matters if you upgrade from `0.1.0-beta.0` or an alpha:
187
208
 
188
209
  ### Persistence, files and drag and drop
189
210
 
190
- #### Files — behavior change (ADR 014, lot 1)
211
+ #### Files: behavior change (ADR 014, lot 1)
191
212
  - **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
213
  - 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
214
  - **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 +220,7 @@ What matters if you upgrade from `0.1.0-beta.0` or an alpha:
199
220
  - Dev dependency: `fake-indexeddb` (unit tests of the IndexedDB store and schema upgrade).
200
221
  - 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
222
 
202
- #### Files — host mode, outbox, upload state (ADR 014, lot 2)
223
+ #### Files: host mode, outbox, upload state (ADR 014, lot 2)
203
224
  - **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
225
  - 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
226
  - **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 +341,7 @@ Reference: `docs/design/import-export.md` (JSON schema with version, markdown ma
320
341
 
321
342
  ### Editing behaviour
322
343
 
323
- #### Editor options — `spellcheck` and `lang`
344
+ #### Editor options: `spellcheck` and `lang`
324
345
  - 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
346
 
326
347
  #### Multi-block deletion
@@ -428,7 +449,7 @@ Reference: `docs/design/import-export.md` (JSON schema with version, markdown ma
428
449
 
429
450
  ## 0.1.0-beta.0
430
451
 
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.
452
+ 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
453
 
433
454
  ### Stability & packaging
434
455
  - **Beta cut**: version `0.1.0-beta.0`; corrected `repository.url` to the `git+https://….git` form (publint suggestion).
@@ -442,18 +463,18 @@ First beta. The library is feature-complete for the beta milestone: everything b
442
463
  - 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
464
  - `nabu.transact(mutateFn, cursorIntent?)` centralizes the mutate → commit → setCursor dance. Migrated `mark:*`, `block:transform` and `zone:set*` actions.
444
465
  - 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).
466
+ - **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
467
 
447
468
  ### 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).
469
+ - 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
470
  - **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
471
 
451
472
  ### New blocks & features
452
473
  - **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).
474
+ - **Divider** block: first non-textual block (`--- ` shortcut, `<hr>` rendering, markdown `---`).
475
+ - **Code** block: multi-line monospace, ```` ``` ```` shortcut, stores plain text only (pluggable syntax highlighting deferred, see `docs/adr/013`).
476
+ - **Callout** block: `note` / `tip` / `important` / `warning` / `caution` variants, `! ` shortcut.
477
+ - **Toggle** block: collapsible (hybrid MegaBlock: own text + child blocks, collapsed state in metadata; Enter spawns a body child, Backspace de-transforms).
457
478
  - **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
479
  - **Image / Video / File** void media blocks on a shared `MediaBlock` base, with an optimistic local preview while the asset persists.
459
480
  - **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 +486,10 @@ First beta. The library is feature-complete for the beta milestone: everything b
465
486
  - **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
487
 
467
488
  ### 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.
489
+ - **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.
490
+ - **Inline markdown shortcuts** (`MarkdownShortcutsExtension`): `**bold**`, `__bold__`, `*italic*`, `_italic_`, `` `code` ``, `~~strike~~` transform as you type.
491
+ - **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.
492
+ - **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
493
 
473
494
  ## alpha.10
474
495
 
@@ -498,23 +519,23 @@ Complete rewrite of `findNearestTextNode` in `selection.svelte.js`. The previous
498
519
  - Shift+arrow into an inert element now corrects only the focus, preserving the anchor (non-collapsed selection)
499
520
  - `data-nabu-ui` elements (zone title input, etc.) bypass normalization entirely
500
521
 
501
- ### Zones — nested zones
522
+ ### Zones: nested zones
502
523
 
503
524
  `zone:insert` and `zone:wrap` now support zones inside zones.
504
525
 
505
526
  - `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
527
+ - `zone:wrap` (single-block) no longer bails when wrapping inside a zone, and creates a nested zone at the correct position
507
528
  - `zone:wrap` (multi-block) allows wrapping a selection of zones into a new zone
508
529
 
509
- ### Zones — UI
530
+ ### Zones: UI
510
531
 
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
532
+ - **Breadcrumb (top)**: when a zone is nested, the title area shows the full ancestor chain: `› Partie II › Chapitre 7`
533
+ - **Closing chevrons (bottom)**: replaces the plain bottom boundary line with `‹ Partie II ‹ Chapitre 7` right-aligned, indicating zone exit context
534
+ - **Word count**: now displayed on all zones, not only nested ones
514
535
 
515
- ### BlockGap — inter-block gap system
536
+ ### BlockGap: inter-block gap system
516
537
 
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.
538
+ 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
539
 
519
540
  `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
541
 
package/README.md CHANGED
@@ -4,6 +4,8 @@ Nabu is a modular, local-first block editor for **Svelte 5**. It combines the cr
4
4
 
5
5
  **Website, documentation and live demos: [nabu.aion.builders](https://nabu.aion.builders)**
6
6
 
7
+ Community: [join the Discord](https://discord.gg/gKkyqRRuWe)
8
+
7
9
  > **Status: public beta** (`0.1.0`). The editing core is complete and tested, but the API may still change before 1.0. Breaking changes are listed in the [changelog](https://nabu.aion.builders/changelog) ([CHANGELOG.md](CHANGELOG.md)). Known gaps (mobile keyboards, Firefox and Safari, tables, real-time collaboration between machines) are listed honestly on the [limits page](https://nabu.aion.builders/architecture/limits).
8
10
 
9
11
  ### Versioning (0.x)
@@ -133,6 +135,10 @@ Everything is on the website: **[nabu.aion.builders/docs](https://nabu.aion.buil
133
135
 
134
136
  In the repository: [architecture decisions](docs/adr), [design notes](docs/design), [tests](tests/README.md).
135
137
 
138
+ ## Contributing
139
+
140
+ Bug reports, fixes, docs and tests are welcome: see [CONTRIBUTING.md](CONTRIBUTING.md). Questions go to `#help` on the [Discord](https://discord.gg/gKkyqRRuWe).
141
+
136
142
  ## License
137
143
 
138
144
  MIT, as declared in `package.json`.
@@ -0,0 +1,39 @@
1
+ /**
2
+ * @typedef {{ start: number, end: number, name: string, value: any }} MarkFix `value` null: remove the mark over the range
3
+ */
4
+ /**
5
+ * The value text typed between two characters takes for the mark `name`, or `undefined`: the mark must be on both neighbours with the
6
+ * same value (typing inside a run). The one place that says it, for the correction of a typed run and for what Ctrl+B reads.
7
+ * @param {Record<string, any> | undefined} left effective attributes of the character before (undefined: none)
8
+ * @param {Record<string, any> | undefined} right effective attributes of the character after (undefined: none)
9
+ * @param {string} name
10
+ */
11
+ export function sharedMark(left: Record<string, any> | undefined, right: Record<string, any> | undefined, name: string): any;
12
+ /**
13
+ * What typing at the collapsed caret `pos` would produce for the mark `name`, read from a delta (the canonical one a behavior holds):
14
+ * the value the typed text would carry, or `undefined`. This is what "the mark is active at the caret" means.
15
+ * @param {import('loro-crdt').Delta<string>[]} delta
16
+ * @param {number} pos
17
+ * @param {string} name
18
+ */
19
+ export function markAtCaret(delta: import("loro-crdt").Delta<string>[], pos: number, name: string): any;
20
+ /**
21
+ * The corrections for a run just inserted at `[from, end)`.
22
+ * @param {import('loro-crdt').Delta<string>[]} ops `sliceDelta(lo, hi)` of the text, where `lo <= from - 1` (when `from > 0`) and `hi >= end + 1` (when there is a character after)
23
+ * @param {number} lo where `ops` start in the text
24
+ * @param {number} from start of the typed run
25
+ * @param {number} end end of the typed run (exclusive)
26
+ * @param {number} total length of the text
27
+ * @param {Record<string, boolean> | null | undefined} armed the stored marks (explicit on / off), not touched
28
+ * @returns {MarkFix[]}
29
+ */
30
+ export function markEdgeFixes(ops: import("loro-crdt").Delta<string>[], lo: number, from: number, end: number, total: number, armed: Record<string, boolean> | null | undefined): MarkFix[];
31
+ /**
32
+ * `value` null: remove the mark over the range
33
+ */
34
+ export type MarkFix = {
35
+ start: number;
36
+ end: number;
37
+ name: string;
38
+ value: any;
39
+ };
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Mark edges of typed text: the rule is Nabu's, not Loro's.
3
+ *
4
+ * Nabu's marks are exact (`expand: 'none'`): a character typed at the edge of a mark does not take it, and one typed inside a mark
5
+ * (the same value on the character before and the one after) keeps it. That is what the user sees, whatever the history of the
6
+ * document. Loro, however, decides from the anchors of the style operations that happened, so two texts that look identical can
7
+ * differ: `[012]3456[789]` made by two `mark` calls takes nothing when "X" is typed at 3, the same text made by `mark [0,10)` then
8
+ * `unmark [3,7)` makes "X" bold (and two `mark` calls that meet at the insertion point make it plain although both sides are bold).
9
+ *
10
+ * {@link markEdgeFixes} reads the typed run and its two neighbours and returns the marks to add or remove so that the typed run
11
+ * follows the rule. A mark the user armed (a stored mark, Ctrl+B with a collapsed caret) is explicit and left alone, on or off.
12
+ */
13
+
14
+ import { effective, sameValue } from '../../utils/delta.js';
15
+
16
+ /**
17
+ * @typedef {{ start: number, end: number, name: string, value: any }} MarkFix `value` null: remove the mark over the range
18
+ */
19
+
20
+ /**
21
+ * The value text typed between two characters takes for the mark `name`, or `undefined`: the mark must be on both neighbours with the
22
+ * same value (typing inside a run). The one place that says it, for the correction of a typed run and for what Ctrl+B reads.
23
+ * @param {Record<string, any> | undefined} left effective attributes of the character before (undefined: none)
24
+ * @param {Record<string, any> | undefined} right effective attributes of the character after (undefined: none)
25
+ * @param {string} name
26
+ */
27
+ export function sharedMark(left, right, name) {
28
+ return left && right && name in left && name in right && sameValue(left[name], right[name]) ? left[name] : undefined;
29
+ }
30
+
31
+ /**
32
+ * What typing at the collapsed caret `pos` would produce for the mark `name`, read from a delta (the canonical one a behavior holds):
33
+ * the value the typed text would carry, or `undefined`. This is what "the mark is active at the caret" means.
34
+ * @param {import('loro-crdt').Delta<string>[]} delta
35
+ * @param {number} pos
36
+ * @param {string} name
37
+ */
38
+ export function markAtCaret(delta, pos, name) {
39
+ /** @type {Record<string, any> | undefined} */
40
+ let left;
41
+ /** @type {Record<string, any> | undefined} */
42
+ let right;
43
+ let offset = 0;
44
+ for (const op of delta) {
45
+ const length = typeof op.insert === 'string' ? op.insert.length : 1;
46
+ const end = offset + length;
47
+ if (pos > 0 && offset <= pos - 1 && pos - 1 < end) left = effective(op.attributes) ?? {};
48
+ if (offset <= pos && pos < end) { right = effective(op.attributes) ?? {}; break; }
49
+ offset = end;
50
+ }
51
+ return sharedMark(left, right, name);
52
+ }
53
+
54
+ /**
55
+ * The corrections for a run just inserted at `[from, end)`.
56
+ * @param {import('loro-crdt').Delta<string>[]} ops `sliceDelta(lo, hi)` of the text, where `lo <= from - 1` (when `from > 0`) and `hi >= end + 1` (when there is a character after)
57
+ * @param {number} lo where `ops` start in the text
58
+ * @param {number} from start of the typed run
59
+ * @param {number} end end of the typed run (exclusive)
60
+ * @param {number} total length of the text
61
+ * @param {Record<string, boolean> | null | undefined} armed the stored marks (explicit on / off), not touched
62
+ * @returns {MarkFix[]}
63
+ */
64
+ export function markEdgeFixes(ops, lo, from, end, total, armed) {
65
+ // Fast path (almost every keystroke): no mark anywhere around the typed run.
66
+ if (!ops.some((op) => op.attributes)) return [];
67
+ /** @type {Record<string, any>} */
68
+ let left = {};
69
+ /** @type {Record<string, any>} */
70
+ let right = {};
71
+ /** @type {{ start: number, end: number, attrs: Record<string, any> }[]} */
72
+ const typed = [];
73
+ let pos = lo;
74
+ for (const op of ops) {
75
+ if (typeof op.insert !== 'string') { pos += 1; continue; }
76
+ const stop = pos + op.insert.length;
77
+ const attrs = effective(op.attributes) ?? {};
78
+ if (from > 0 && pos <= from - 1 && from - 1 < stop) left = attrs;
79
+ if (end < total && pos <= end && end < stop) right = attrs;
80
+ const s = Math.max(pos, from), e = Math.min(stop, end);
81
+ if (s < e) typed.push({ start: s, end: e, attrs });
82
+ pos = stop;
83
+ }
84
+ /** @type {MarkFix[]} */
85
+ const fixes = [];
86
+ for (const { start, end: stop, attrs } of typed) {
87
+ for (const name of new Set([...Object.keys(attrs), ...Object.keys(left)])) {
88
+ if (armed && name in armed) continue;
89
+ const want = sharedMark(left, right, name);
90
+ if (want === undefined) {
91
+ if (name in attrs) fixes.push({ start, end: stop, name, value: null });
92
+ } else if (!(name in attrs) || !sameValue(attrs[name], want)) {
93
+ fixes.push({ start, end: stop, name, value: want });
94
+ }
95
+ }
96
+ }
97
+ return fixes;
98
+ }
@@ -49,13 +49,13 @@ export class TextBehavior {
49
49
  /** @public */
50
50
  public text: string;
51
51
  /** @public */
52
- public delta: import("loro-crdt").Delta<string>[];
52
+ public delta: import("../../utils/delta.js").DeltaOp[];
53
53
  /** @public */
54
54
  public selection: {
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
@@ -113,6 +113,14 @@ export class TextBehavior {
113
113
  public handleBeforeInput(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): any;
114
114
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [selection] */
115
115
  handleInsertText(event: InputEvent, selection?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
116
+ /**
117
+ * 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
118
+ * when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
119
+ * (one undo step) as the insertion. Marks in `armed` (stored marks) are the user's explicit choice and stay as they are.
120
+ * Costs one small slice of the text; nothing is written unless a correction is needed.
121
+ * @param {number} from @param {number} length @param {Record<string, boolean> | null} [armed]
122
+ */
123
+ settleMarkEdges(from: number, length: number, armed?: Record<string, boolean> | null): void;
116
124
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
117
125
  handleInsertLineBreak(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): void;
118
126
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
@@ -120,35 +128,24 @@ export class TextBehavior {
120
128
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
121
129
  handleDeleteContentForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
122
130
  /**
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).
131
+ * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux, Option+Backspace on Mac): the whitespace between the
132
+ * caret and the word goes with it, and the caret lands where the word started ("one two |" -> "one |", issue #4).
126
133
  *
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").
134
+ * For a collapsed selection the range is computed from the model text, never from `event.getTargetRanges()`: browsers
135
+ * disagree on it (Chromium stops right after the previous space, leaving "one two " from "one two three"), so the
136
+ * behavior would differ per engine. The rules (words by `Intl.Segmenter`, punctuation, line breaks) are in
137
+ * {@link wordDeleteRange}. A selection is deleted whole.
132
138
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
133
139
  */
134
- handleDeleteWordBackward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
140
+ handleDeleteWordBackward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): boolean | undefined;
135
141
  /**
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.
142
+ * Deletes the word after the cursor (Ctrl+Delete on Win/Linux, Option+Fn+Delete on Mac). Like the backward deletion it is
143
+ * resolved from the model text only (`getTargetRanges()` is engine-dependent). macOS deletes up to the end of the next
144
+ * word ("one |two three" -> "one | three"), Windows up to the start of the one after ("one |two three" -> "one |three");
145
+ * see {@link wordDeleteRange}. A selection is deleted whole.
149
146
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
150
147
  */
151
- handleDeleteWordForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): true | undefined;
148
+ handleDeleteWordForward(event: InputEvent, sel?: ReturnType<TextBehavior["getSelection"]>): boolean | undefined;
152
149
  /**
153
150
  * Deletes from the start of the current line to the cursor (Cmd+Backspace on Mac; `deleteHardLineBackward`).
154
151
  * A selection inside the block is deleted whole.
@@ -6,7 +6,10 @@ 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 { readDelta } from "../../utils/delta.js";
11
+ import { markEdgeFixes } from "./mark-edges.js";
12
+ import { detectPlatform } from "../../utils/keys.js";
10
13
 
11
14
  /**
12
15
  * Converts a Loro text delta to inline HTML.
@@ -197,10 +200,10 @@ export class TextBehavior {
197
200
  /** @public */
198
201
  this.text = $state(this.container.toString());
199
202
  /** @public */
200
- this.delta = $state(this.container.toDelta());
203
+ this.delta = $state(readDelta(this.container));
201
204
  this.container.subscribe(() => {
202
205
  this.text = this.container.toString();
203
- this.delta = this.container.toDelta();
206
+ this.delta = readDelta(this.container);
204
207
  this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
205
208
  });
206
209
  }
@@ -456,9 +459,30 @@ export class TextBehavior {
456
459
  else this.removeMark(name, range);
457
460
  }
458
461
  }
462
+ this.settleMarkEdges(selection.from, textToInsert.length, stored);
459
463
  this.block.commit();
460
464
  tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
461
465
  }
466
+
467
+ /**
468
+ * 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
469
+ * when the character before and the one after both carry it. The corrections are made now, so they belong to the same commit
470
+ * (one undo step) as the insertion. Marks in `armed` (stored marks) are the user's explicit choice and stay as they are.
471
+ * Costs one small slice of the text; nothing is written unless a correction is needed.
472
+ * @param {number} from @param {number} length @param {Record<string, boolean> | null} [armed]
473
+ */
474
+ settleMarkEdges(from, length, armed = null) {
475
+ if (length <= 0 || this.block.marksEnabled === false) return;
476
+ const total = this.container.length;
477
+ const lo = Math.max(0, from - 1);
478
+ const ops = this.container.sliceDelta(lo, Math.min(total, from + length + 1));
479
+ // Loro: the anchors of a mark decide where text typed at its edge lands, not what the text looks like.
480
+ // https://github.com/loro-dev/loro/issues/1240 (canary: tests/unit/loro-quirks.test.js)
481
+ for (const { start, end, name, value } of markEdgeFixes(ops, lo, from, from + length, total, armed)) {
482
+ if (value === null) this.container.unmark({ start, end }, name);
483
+ else this.container.mark({ start, end }, name, value);
484
+ }
485
+ }
462
486
 
463
487
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
464
488
  handleInsertLineBreak(event, sel = this.selection) {
@@ -559,73 +583,34 @@ export class TextBehavior {
559
583
  }
560
584
 
561
585
  /**
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).
586
+ * Deletes the word before the cursor (Ctrl+Backspace on Win/Linux, Option+Backspace on Mac): the whitespace between the
587
+ * caret and the word goes with it, and the caret lands where the word started ("one two |" -> "one |", issue #4).
565
588
  *
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").
589
+ * For a collapsed selection the range is computed from the model text, never from `event.getTargetRanges()`: browsers
590
+ * disagree on it (Chromium stops right after the previous space, leaving "one two " from "one two three"), so the
591
+ * behavior would differ per engine. The rules (words by `Intl.Segmenter`, punctuation, line breaks) are in
592
+ * {@link wordDeleteRange}. A selection is deleted whole.
571
593
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
572
594
  */
573
595
  handleDeleteWordBackward(event, sel = this.selection) {
574
596
  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;
597
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
598
+ const { from } = wordDeleteRange(this.text, sel.from, 'backward', { lang: this.nabu?.lang });
599
+ return this.#deleteSpan(from, sel.from);
590
600
  }
591
601
 
592
602
  /**
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.
603
+ * Deletes the word after the cursor (Ctrl+Delete on Win/Linux, Option+Fn+Delete on Mac). Like the backward deletion it is
604
+ * resolved from the model text only (`getTargetRanges()` is engine-dependent). macOS deletes up to the end of the next
605
+ * word ("one |two three" -> "one | three"), Windows up to the start of the one after ("one |two three" -> "one |three");
606
+ * see {@link wordDeleteRange}. A selection is deleted whole.
606
607
  * @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel]
607
608
  */
608
609
  handleDeleteWordForward(event, sel = this.selection) {
609
610
  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;
611
+ if (!sel.isCollapsed) return this.#deleteSpan(sel.from, sel.to);
612
+ const { to } = wordDeleteRange(this.text, sel.from, 'forward', { platform: detectPlatform(), lang: this.nabu?.lang });
613
+ return this.#deleteSpan(sel.from, to);
629
614
  }
630
615
 
631
616
  /**
@@ -704,7 +689,7 @@ export class TextBehavior {
704
689
  */
705
690
  #marksAt(index) {
706
691
  let offset = 0;
707
- for (const op of this.container.toDelta()) {
692
+ for (const op of readDelta(this.container)) {
708
693
  if (typeof op.insert !== 'string') continue;
709
694
  const end = offset + op.insert.length;
710
695
  if (index >= offset && index < end) return op.attributes ? { ...op.attributes } : null;
@@ -926,7 +911,7 @@ export class TextBehavior {
926
911
  */
927
912
  isMarkActive(markName, sel) {
928
913
  if (!sel || sel.isCollapsed) return false;
929
- const delta = this.container.toDelta();
914
+ const delta = readDelta(this.container);
930
915
  let offset = 0;
931
916
  for (const op of delta) {
932
917
  if (typeof op.insert !== 'string') continue;
@@ -1001,7 +986,7 @@ export class TextBehavior {
1001
986
  if (!otherBehavior || !(otherBehavior instanceof TextBehavior)) return false;
1002
987
  this.applyDelta([
1003
988
  { retain: this.container.length },
1004
- ...otherBehavior.container.toDelta()
989
+ ...readDelta(otherBehavior.container)
1005
990
  ]);
1006
991
  // other.destroy();
1007
992
  return true;
@@ -2,18 +2,43 @@
2
2
  /** @type {{ block: import('./code.svelte.js').CodeBlock }} */
3
3
  let { block } = $props();
4
4
  const LANGS = ['plaintext', 'javascript', 'typescript', 'html', 'css', 'json', 'python', 'rust', 'bash', 'markdown', 'sql', 'go'];
5
+ // A language the list does not know (`ts`, `c++`, from a fence, a paste or the API) is listed too: the select shows what the block holds.
6
+ const langs = $derived(block.language && !LANGS.includes(block.language) ? [...LANGS, block.language] : LANGS);
7
+
8
+ // A long line scrolls sideways: the browser does not bring a caret the editor places itself (after typing, Enter, Tab…) into view.
9
+ $effect(() => {
10
+ const el = block.element;
11
+ if (!el) return;
12
+ const keepCaretVisible = () => {
13
+ const sel = getSelection();
14
+ if (!sel || !sel.isCollapsed || !sel.anchorNode || !el.contains(sel.anchorNode) || el.scrollWidth <= el.clientWidth) return;
15
+ const range = document.createRange();
16
+ range.setStart(sel.anchorNode, sel.anchorOffset);
17
+ const caret = range.getClientRects()[0];
18
+ if (!caret) return;
19
+ const box = el.getBoundingClientRect();
20
+ const margin = 24;
21
+ if (caret.right > box.right - margin) el.scrollLeft += caret.right - box.right + margin;
22
+ else if (caret.left < box.left + margin) el.scrollLeft -= box.left + margin - caret.left;
23
+ };
24
+ document.addEventListener('selectionchange', keepCaretVisible);
25
+ return () => document.removeEventListener('selectionchange', keepCaretVisible);
26
+ });
27
+ // The select is out of the Tab order (tabindex -1): inside the editor it would catch the Tab of every block above it.
28
+ // Escape then Shift+Tab, in the code, focuses it (CodeBlock#keydown).
5
29
  </script>
6
30
 
7
31
  <div class="nabu-code-wrapper"><select
8
32
  class="nabu-code-lang"
9
33
  data-nabu-ui
10
34
  contenteditable="false"
35
+ tabindex="-1"
11
36
  value={block.language ?? 'plaintext'}
12
37
  disabled={block.nabu.readonly}
13
38
  aria-label="Code language"
14
39
  onchange={(e) => block.setLanguage(e.currentTarget.value === 'plaintext' ? null : e.currentTarget.value)}
15
40
  >
16
- {#each LANGS as lang}<option value={lang}>{lang}</option>{/each}
41
+ {#each langs as lang}<option value={lang}>{lang}</option>{/each}
17
42
  </select><pre
18
43
  bind:this={block.element}
19
44
  data-block-id={block.id}
@@ -64,6 +89,9 @@
64
89
  line-height: 1.6;
65
90
  padding: 0.75em 1em;
66
91
  margin: 0;
92
+ /* The library's inline-code rule (`.nabu-code`, RichText) also matches this <pre>: its tint is not wanted here. */
93
+ background: none;
94
+ border-radius: 0;
67
95
  overflow-x: auto;
68
96
  color: var(--nb-text-primary, rgba(255, 255, 255, 0.85));
69
97
  outline: none;