@aionbuilders/nabu 0.1.1 → 0.1.3

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.
Files changed (40) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/README.md +7 -1
  3. package/dist/behaviors/text/mark-edges.d.ts +39 -0
  4. package/dist/behaviors/text/mark-edges.js +98 -0
  5. package/dist/behaviors/text/text.behavior.svelte.d.ts +9 -1
  6. package/dist/behaviors/text/text.behavior.svelte.js +30 -7
  7. package/dist/blocks/callout/callout.svelte.js +2 -2
  8. package/dist/blocks/code/Code.svelte +29 -1
  9. package/dist/blocks/code/code.extension.js +20 -7
  10. package/dist/blocks/code/code.svelte.d.ts +4 -1
  11. package/dist/blocks/code/code.svelte.js +121 -24
  12. package/dist/blocks/code/indent.d.ts +61 -0
  13. package/dist/blocks/code/indent.js +91 -0
  14. package/dist/blocks/heading/heading.svelte.js +2 -2
  15. package/dist/blocks/list/hooks/onBeforeInput.hook.js +2 -1
  16. package/dist/blocks/list/list-item.svelte.d.ts +1 -1
  17. package/dist/blocks/list/list-item.svelte.js +2 -2
  18. package/dist/blocks/list/list.behavior.svelte.js +2 -2
  19. package/dist/blocks/list/to-list.js +2 -1
  20. package/dist/blocks/media/media-block.svelte.js +2 -2
  21. package/dist/blocks/nabu.svelte.d.ts +53 -0
  22. package/dist/blocks/nabu.svelte.js +101 -33
  23. package/dist/blocks/region/actions.js +2 -1
  24. package/dist/blocks/region/region.svelte.d.ts +1 -1
  25. package/dist/blocks/region/region.svelte.js +4 -3
  26. package/dist/blocks/selection.svelte.d.ts +2 -1
  27. package/dist/blocks/selection.svelte.js +29 -5
  28. package/dist/blocks/text-block.svelte.d.ts +1 -1
  29. package/dist/blocks/toggle/toggle.svelte.d.ts +1 -1
  30. package/dist/blocks/toggle/toggle.svelte.js +2 -2
  31. package/dist/files/files.svelte.js +1 -1
  32. package/dist/ui/slash-menu.svelte.js +2 -1
  33. package/dist/utils/delta.d.ts +27 -0
  34. package/dist/utils/delta.js +121 -0
  35. package/dist/utils/selection.svelte.d.ts +5 -0
  36. package/dist/utils/selection.svelte.js +15 -2
  37. package/dist/utils/tab.js +1 -0
  38. package/dist/vite.d.ts +8 -0
  39. package/dist/vite.js +15 -2
  40. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -4,6 +4,33 @@
4
4
 
5
5
  Nothing yet.
6
6
 
7
+ ## 0.1.3 (2026-11-04)
8
+
9
+ Fixes found by testing the published package in a real SvelteKit app: the first thing a consumer's build, a Firefox user and a page that mounts editors on demand would hit. The API only gains two methods.
10
+
11
+ ### Added
12
+ - **`engine.destroy()`** releases an engine for good, memory included: it unsubscribes the engine and its blocks from the document, stops the subsystems, closes the persistence and the upload retries, and the engine can then be garbage collected. Idempotent. The document stays readable (`serialize()`), the engine no longer follows changes, and it must not be mounted again. Changes that are not saved yet are dropped: await `saveNow()` first when they matter.
13
+ - **`engine.track(unsubscribe)`** hands a Loro subscription or any cleanup over to `destroy()`. A custom block should pass its own, `nabu.track(node.data.subscribe(...))`: Loro keeps the callback until it is unsubscribed, so an untracked one keeps the engine in memory.
14
+
15
+ ### Fixed
16
+ - **`vite build` failed on a server-rendered page that imports Nabu**, with `Cannot find module './snippets/loro-wasm-…/inline0.js'`. The `nabu()` helper now keeps `loro-crdt` out of the SSR bundle (`ssr.external`). With pnpm, whose strict `node_modules` hides it from your app, also run `pnpm add loro-crdt`.
17
+ - **Firefox lost everything typed after Tab or `element.focus()`.** Firefox leaves the caret on the editor root, and the correction looked for text before the start of the document, found none and gave up. Such a caret now lands on the nearest text in either direction. Covered by `tests/e2e/dead-root-caret.spec.ts`, and checked on real Firefox, WebKit and Chromium through a packed build.
18
+ - **Every unmounted editor left 5 listeners on `document`.** They now exist only while an editor is mounted: unmounting is enough to release the page, and the same engine can be mounted again. Covered by `tests/e2e/lifecycle.spec.ts`, which counts the listeners and checks through the garbage collector that a destroyed engine is really gone.
19
+ - **A flaky documentation test.** The walkthrough of `docs/recipes/autosave-to-your-server.md` raced its own 10 ms timer under load.
20
+
21
+ ## 0.1.2 (2026-10-29)
22
+
23
+ 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.
24
+
25
+ ### Fixed
26
+ - **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`.
27
+ - **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`.
28
+ - **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.
29
+ - **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.
30
+ - **```` ``` ```` + 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.
31
+ - **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.
32
+ - **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.
33
+
7
34
  ## 0.1.1 (2026-10-29)
8
35
 
9
36
  Two fixes reported by users of the alpha. No API change.
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)
@@ -24,7 +26,7 @@ bun add @aionbuilders/nabu
24
26
  ### Requirements
25
27
 
26
28
  - **Svelte 5.20 or newer**.
27
- - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'`. The bundled helper does both:
29
+ - A Vite setup (SvelteKit, or Svelte + Vite) that can load WebAssembly. Loro ships as a WebAssembly module loaded with top-level `await`, so the build needs `vite-plugin-wasm` and `build.target: 'esnext'` (and, for server rendering, `loro-crdt` kept out of the SSR bundle). The bundled helper does all three:
28
30
 
29
31
  ```js
30
32
  // vite.config.js
@@ -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,7 +49,7 @@ 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;
@@ -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] */
@@ -7,6 +7,8 @@ import { tick } from "svelte";
7
7
  import { escapeHtml, escapeAttr, sanitizeUrl } from "../../utils/html.js";
8
8
  import { escapeMarkdownText, escapeBlockStart } from "./markdown-syntax.js";
9
9
  import { countWords, wordDeleteRange } from "../../utils/words.js";
10
+ import { readDelta } from "../../utils/delta.js";
11
+ import { markEdgeFixes } from "./mark-edges.js";
10
12
  import { detectPlatform } from "../../utils/keys.js";
11
13
 
12
14
  /**
@@ -198,12 +200,12 @@ export class TextBehavior {
198
200
  /** @public */
199
201
  this.text = $state(this.container.toString());
200
202
  /** @public */
201
- this.delta = $state(this.container.toDelta());
202
- this.container.subscribe(() => {
203
+ this.delta = $state(readDelta(this.container));
204
+ this.nabu.track(this.container.subscribe(() => {
203
205
  this.text = this.container.toString();
204
- this.delta = this.container.toDelta();
206
+ this.delta = readDelta(this.container);
205
207
  this.nabu.noteTextChange?.(this.block); // a selection end in this block must follow the edit (P-109)
206
- });
208
+ }));
207
209
  }
208
210
 
209
211
  /** @public */
@@ -457,9 +459,30 @@ export class TextBehavior {
457
459
  else this.removeMark(name, range);
458
460
  }
459
461
  }
462
+ this.settleMarkEdges(selection.from, textToInsert.length, stored);
460
463
  this.block.commit();
461
464
  tick().then(() => this.nabu.selection.setCursor(this.block, selection.from + textToInsert.length));
462
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
+ }
463
486
 
464
487
  /** @param {InputEvent} event @param {ReturnType<TextBehavior["getSelection"]>} [sel] */
465
488
  handleInsertLineBreak(event, sel = this.selection) {
@@ -666,7 +689,7 @@ export class TextBehavior {
666
689
  */
667
690
  #marksAt(index) {
668
691
  let offset = 0;
669
- for (const op of this.container.toDelta()) {
692
+ for (const op of readDelta(this.container)) {
670
693
  if (typeof op.insert !== 'string') continue;
671
694
  const end = offset + op.insert.length;
672
695
  if (index >= offset && index < end) return op.attributes ? { ...op.attributes } : null;
@@ -888,7 +911,7 @@ export class TextBehavior {
888
911
  */
889
912
  isMarkActive(markName, sel) {
890
913
  if (!sel || sel.isCollapsed) return false;
891
- const delta = this.container.toDelta();
914
+ const delta = readDelta(this.container);
892
915
  let offset = 0;
893
916
  for (const op of delta) {
894
917
  if (typeof op.insert !== 'string') continue;
@@ -963,7 +986,7 @@ export class TextBehavior {
963
986
  if (!otherBehavior || !(otherBehavior instanceof TextBehavior)) return false;
964
987
  this.applyDelta([
965
988
  { retain: this.container.length },
966
- ...otherBehavior.container.toDelta()
989
+ ...readDelta(otherBehavior.container)
967
990
  ]);
968
991
  // other.destroy();
969
992
  return true;
@@ -40,9 +40,9 @@ export class CalloutBlock extends TextBlock {
40
40
  );
41
41
 
42
42
  // Sync variant from Loro data changes (mirrors Heading's level sync)
43
- this.node.data.subscribe(() => {
43
+ this.nabu.track(this.node.data.subscribe(() => {
44
44
  this.variant = this.node.data.get('variant') || 'note';
45
- });
45
+ }));
46
46
  }
47
47
 
48
48
  // ── Capability flags ─────────────────────────────────────────────────────
@@ -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;
@@ -1,7 +1,7 @@
1
1
  import { tick } from "svelte";
2
2
  import { TextBehavior } from "../../behaviors/text";
3
3
  import { extension } from "../../utils/extensions";
4
- import { CodeBlock } from "./code.svelte.js";
4
+ import { CodeBlock, LANGUAGE_CHARS } from "./code.svelte.js";
5
5
  import CodeComponent from "./Code.svelte";
6
6
 
7
7
  /**
@@ -12,7 +12,7 @@ import CodeComponent from "./Code.svelte";
12
12
  * onBeforeInput hook for CodeBlock:
13
13
  * - Inside a code block: Backspace on empty → transform back to paragraph; Backspace at offset 0 of a
14
14
  * non-empty one → paragraph too (same text, language dropped, caret stays at 0).
15
- * - Inside a non-code text block: ``` + Enter → transform to code block.
15
+ * - Inside a non-code text block: ``` + Enter or ``` + Space (with an optional language) → transform to code block.
16
16
  *
17
17
  * @param {Nabu} nabu @param {InputEvent} event @param {Block} block
18
18
  */
@@ -50,14 +50,27 @@ const onBeforeInput = (nabu, event, block) => {
50
50
  return CONTINUE;
51
51
  }
52
52
 
53
- // ``` + Enter in a non-code text block → transform to code
54
- if (event.inputType === 'insertParagraph') {
55
- const m = behavior.text.match(/^```(\w*)$/);
53
+ // ``` + Enter, or ``` + Space like every other markdown shortcut (`#`, `>`, `-`), in a non-code text block → transform to code.
54
+ // Space only counts with the caret at the end of the fence (it would otherwise be a space typed inside the text).
55
+ const enter = event.inputType === 'insertParagraph';
56
+ const space = event.inputType === 'insertText' && event.data === ' ';
57
+ if (enter || space) {
58
+ const m = behavior.text.match(new RegExp('^```(' + LANGUAGE_CHARS + '*)$'));
56
59
  if (!m) return CONTINUE;
60
+ if (space && sel.from !== behavior.text.length) return CONTINUE;
57
61
  const language = m[1] || null;
58
- behavior.delete({ index: 0, length: behavior.text.length });
59
62
  const blockId = block.node.id.toString();
60
- block.transformTo('code', language ? { language } : {});
63
+ const toCode = () => block.transformTo('code', language ? { language } : {});
64
+ if (enter) {
65
+ behavior.delete({ index: 0, length: behavior.text.length });
66
+ toCode();
67
+ } else {
68
+ // Undo gives back "``` " (trigger space included): see Nabu.shortcut()
69
+ nabu.shortcut(block, ' ', (b) => {
70
+ b.delete({ index: 0, length: b.text.length });
71
+ toCode();
72
+ });
73
+ }
61
74
  tick().then(() => {
62
75
  const fresh = nabu.blocks.get(blockId);
63
76
  if (fresh) fresh.focus({ start: 0, end: 0 });
@@ -1,3 +1,5 @@
1
+ /** What a language name may hold: a word, plus what real ones use (`c++`, `c#`, `objective-c`, `vue.js`). */
2
+ export const LANGUAGE_CHARS: "[\\w#+.-]";
1
3
  export class CodeBlock extends TextBlock {
2
4
  static placeholder: string;
3
5
  /** @param {import('../../utils/extensions.js').PasteBlock} pb */
@@ -50,12 +52,13 @@ export class CodeBlock extends TextBlock {
50
52
  */
51
53
  setLanguage(lang: string | null): void;
52
54
  /**
53
- * Handle special keydown events: Tab, Shift+Tab, ArrowDown.
55
+ * Handle special keydown events: Tab, Shift+Tab (except the one that follows an Escape), Ctrl+A, ArrowUp / ArrowDown at the edges of the block.
54
56
  * Returns true if handled (engine should preventDefault).
55
57
  * @param {KeyboardEvent} event
56
58
  * @returns {boolean}
57
59
  */
58
60
  keydown(event: KeyboardEvent): boolean;
61
+ #private;
59
62
  }
60
63
  export type CodeNode = NabuNode<{
61
64
  type: "code";