@aionbuilders/nabu 0.1.0-alpha.7 → 0.1.0-alpha.9

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.
@@ -0,0 +1,11 @@
1
+ export default Zone;
2
+ type Zone = {
3
+ $on?(type: string, callback: (e: any) => void): () => void;
4
+ $set?(props: Partial<$$ComponentProps>): void;
5
+ };
6
+ declare const Zone: import("svelte").Component<{
7
+ block: import("./zone.svelte.js").ZoneBlock;
8
+ }, {}, "">;
9
+ type $$ComponentProps = {
10
+ block: import("./zone.svelte.js").ZoneBlock;
11
+ };
@@ -0,0 +1,2 @@
1
+ export { ZoneExtension } from "./zone.extension.js";
2
+ export { ZoneBlock, Zones } from "./zone.svelte.js";
@@ -0,0 +1,2 @@
1
+ export { ZoneBlock, Zones } from './zone.svelte.js';
2
+ export { ZoneExtension } from './zone.extension.js';
@@ -0,0 +1,2 @@
1
+ export const ZoneExtension: Extension;
2
+ import { Extension } from '../../utils/extensions.js';
@@ -0,0 +1,221 @@
1
+ import { Extension } from '../../utils/extensions.js';
2
+ import { ZoneBlock } from './zone.svelte.js';
3
+ import ZoneComponent from './Zone.svelte';
4
+ import { findLCA, findDirectChildOf } from '../container.utils.js';
5
+
6
+ /**
7
+ * @import { Nabu } from '../nabu.svelte.js';
8
+ */
9
+
10
+ /**
11
+ * onBeforeInput hook — intercepts deleteContentBackward at the start of the
12
+ * first content block inside a Zone, before TextBehavior's findBackward() can
13
+ * traverse up and out of the Zone boundary.
14
+ *
15
+ * Fires BEFORE block routing in Nabu.dispatchEventToSelection.
16
+ *
17
+ * @param {Nabu} nabu
18
+ * @param {InputEvent} event
19
+ * @param {import('../block.svelte.js').Block} block
20
+ */
21
+ function zoneBackspaceGuard(nabu, event, block) {
22
+ if (event.inputType !== 'deleteContentBackward') return;
23
+
24
+ // Use the block's model selection (TextBehavior.selection) rather than the raw
25
+ // DOM startOffset, which varies by text node structure and is unreliable here.
26
+ const blockSel = block.selection;
27
+ if (!blockSel || !blockSel.isCollapsed || blockSel.from !== 0) return;
28
+
29
+ // Walk up from block. If every ancestor up to a Zone is the first child (index 0),
30
+ // the cursor is at the very start of the Zone — block the event.
31
+ // Stop early if a non-first-child is found (there's something to merge with inside).
32
+ let current = block;
33
+ while (current && current.parent) {
34
+ if (current.parent.type === 'zone') {
35
+ if (current.index === 0) return nabu.BREAK;
36
+ break; // Has a previous sibling inside the zone — allow normal merge
37
+ }
38
+ if (current.index !== 0) break; // Has a previous sibling in a sub-container
39
+ current = current.parent;
40
+ }
41
+ }
42
+
43
+ export const ZoneExtension = new Extension('zone', {
44
+ block: ZoneBlock,
45
+ component: ZoneComponent,
46
+
47
+ hooks: {
48
+ onBeforeInput: zoneBackspaceGuard,
49
+ onZoneFocus: null,
50
+ onZoneBlur: null,
51
+ },
52
+
53
+ actions: {
54
+ /**
55
+ * Move all children of the Zone to its parent position, then delete the Zone.
56
+ * @param {Nabu} nabu
57
+ * @param {{ zoneId: string }} data
58
+ */
59
+ 'zone:unwrap': (nabu, { zoneId }) => {
60
+ const zone = nabu.blocks.get(zoneId);
61
+ if (!zone || zone.type !== 'zone') return;
62
+
63
+ const parentNode = zone.node.parent();
64
+ const parentId = parentNode ? parentNode.id : undefined;
65
+ const zoneIndex = zone.node.index();
66
+
67
+ // Reverse so that when each child is inserted at zoneIndex, the original
68
+ // order is preserved (each insert pushes the previous one down).
69
+ // @ts-ignore — zone.children comes from MegaBlock
70
+ const children = /** @type {import('../block.svelte.js').Block[]} */ ([...zone.children]);
71
+ children.reverse().forEach(child => {
72
+ nabu.tree.move(child.node.id, parentId, zoneIndex);
73
+ });
74
+
75
+ nabu.tree.delete(zone.node.id);
76
+ nabu.commit();
77
+ },
78
+
79
+ /**
80
+ * @param {Nabu} nabu
81
+ * @param {{ zoneId: string, status: string }} data
82
+ */
83
+ 'zone:setStatus': (nabu, { zoneId, status }) => {
84
+ const zone = /** @type {import('./zone.svelte.js').ZoneBlock | undefined} */ (nabu.blocks.get(zoneId));
85
+ if (!zone || zone.type !== 'zone') return;
86
+ zone.status = status;
87
+ },
88
+
89
+ /**
90
+ * @param {Nabu} nabu
91
+ * @param {{ zoneId: string, text: string }} data
92
+ */
93
+ 'zone:setSynopsis': (nabu, { zoneId, text }) => {
94
+ const zone = /** @type {import('./zone.svelte.js').ZoneBlock | undefined} */ (nabu.blocks.get(zoneId));
95
+ if (!zone || zone.type !== 'zone') return;
96
+ zone.setSynopsis(text);
97
+ },
98
+
99
+ /**
100
+ * @param {Nabu} nabu
101
+ * @param {{ zoneId: string, target: number | null }} data
102
+ */
103
+ 'zone:setWordCountTarget': (nabu, { zoneId, target }) => {
104
+ const zone = /** @type {import('./zone.svelte.js').ZoneBlock | undefined} */ (nabu.blocks.get(zoneId));
105
+ if (!zone || zone.type !== 'zone') return;
106
+ zone.wordCountTarget = target;
107
+ },
108
+
109
+ /**
110
+ * Insert a new empty zone (with one paragraph) after the anchor block's
111
+ * root-level ancestor. Moves the cursor into the new paragraph.
112
+ * @param {Nabu} nabu
113
+ * @param {{ props?: Object }} [data]
114
+ */
115
+ 'zone:insert': (nabu, data) => {
116
+ const anchor = nabu.selection.anchorBlock;
117
+ if (!anchor) return;
118
+
119
+ // If the cursor is inside a zone, insert there; otherwise insert at root level.
120
+ let nearestZone = anchor.parent;
121
+ while (nearestZone && nearestZone.type !== 'zone') nearestZone = nearestZone.parent;
122
+
123
+ let insertIndex, parentId;
124
+ if (nearestZone) {
125
+ const directChild = findDirectChildOf(anchor, nearestZone);
126
+ insertIndex = (directChild?.index ?? 0) + 1;
127
+ parentId = nearestZone.node.id.toString();
128
+ } else {
129
+ let rootBlock = anchor;
130
+ while (rootBlock.parent) rootBlock = rootBlock.parent;
131
+ insertIndex = (nabu.children.indexOf(rootBlock)) + 1;
132
+ parentId = null;
133
+ }
134
+
135
+ // Create zone + paragraph in one transaction
136
+ const zone = ZoneBlock.create(nabu, 'zone', data?.props ?? {}, parentId, insertIndex);
137
+
138
+ const ParagraphClass = nabu.registry.get('paragraph');
139
+ let newParagraph = null;
140
+ if (ParagraphClass) {
141
+ newParagraph = ParagraphClass.create(nabu, 'paragraph', {}, zone.node.id.toString(), 0);
142
+ }
143
+
144
+ nabu.commit().then(() => {
145
+ const target = newParagraph ? nabu.blocks.get(newParagraph.id) ?? newParagraph : null;
146
+ if (target) nabu.selection.setCursor(target, 0);
147
+ });
148
+ },
149
+
150
+ /**
151
+ * Wrap the selected blocks in a new zone.
152
+ *
153
+ * - Collapsed / single block: wraps the block's direct child of its
154
+ * nearest non-zone ancestor (or the root-level block).
155
+ * - Multi-block selection: finds the LCA of startBlock/endBlock, resolves
156
+ * their direct children inside that container, and wraps the whole range.
157
+ * - No-op if every candidate is already a zone.
158
+ *
159
+ * @param {Nabu} nabu
160
+ * @param {{ props?: Object }} [data]
161
+ */
162
+ 'zone:wrap': (nabu, data) => {
163
+ const sel = nabu.selection;
164
+ const startBlock = sel.startBlock ?? sel.anchorBlock;
165
+ const endBlock = sel.endBlock ?? sel.focusBlock;
166
+ if (!startBlock) return;
167
+
168
+ const savedOffset = startBlock.behaviors?.get('text')?.selection?.from ?? 0;
169
+
170
+ /** @type {import('../block.svelte.js').Block[]} */
171
+ let toWrap;
172
+ /** @type {string | null} */
173
+ let parentId;
174
+ /** @type {number} */
175
+ let insertIndex;
176
+
177
+ if (!endBlock || startBlock === endBlock || sel.isCollapsed) {
178
+ // ── Single-block path ──────────────────────────────────────────
179
+ // Find direct child of the nearest container (zone or root level).
180
+ // The while loop stops at zone boundaries, so wrapping inside a zone
181
+ // creates a nested zone — which is now intentionally supported.
182
+ let target = startBlock;
183
+ while (target.parent && target.parent.type !== 'zone') {
184
+ target = target.parent;
185
+ }
186
+
187
+ toWrap = [target];
188
+ parentId = target.parent ? target.parent.node.id.toString() : null;
189
+ insertIndex = target.index ?? 0;
190
+ } else {
191
+ // ── Multi-block path ───────────────────────────────────────────
192
+ const lca = findLCA(startBlock, endBlock);
193
+ // Container is the LCA block, or nabu itself if blocks are root-level
194
+ const container = lca ?? nabu;
195
+
196
+ const sc = findDirectChildOf(startBlock, container);
197
+ const ec = findDirectChildOf(endBlock, container);
198
+ if (!sc || !ec) return;
199
+
200
+ const containerChildren = /** @type {import('../block.svelte.js').Block[]} */ (
201
+ lca ? /** @type {any} */ (lca).children : nabu.children
202
+ );
203
+ const si = containerChildren.indexOf(sc);
204
+ const ei = containerChildren.indexOf(ec);
205
+ if (si === -1 || ei === -1 || si > ei) return;
206
+
207
+ toWrap = containerChildren.slice(si, ei + 1);
208
+ parentId = lca ? lca.node.id.toString() : null;
209
+ insertIndex = si;
210
+ }
211
+
212
+ const zone = ZoneBlock.create(nabu, 'zone', data?.props ?? {}, parentId, insertIndex);
213
+ toWrap.forEach((block, i) => nabu.tree.move(block.node.id, zone.node.id, i));
214
+
215
+ nabu.commit().then(() => {
216
+ const fresh = nabu.blocks.get(startBlock.id);
217
+ if (fresh) nabu.selection.setCursor(fresh, savedOffset);
218
+ });
219
+ },
220
+ },
221
+ });
@@ -0,0 +1,112 @@
1
+ /**
2
+ * @import { Nabu, NabuNode } from '../nabu.svelte.js';
3
+ */
4
+ /**
5
+ * @typedef {NabuNode<{type: "zone", synopsis: LoroText, status: string, wordCountTarget: number | null, title: string}>} ZoneNode
6
+ */
7
+ export class ZoneBlock extends MegaBlock {
8
+ /**
9
+ * @param {Nabu} nabu
10
+ * @param {string} type
11
+ * @param {Object} [props]
12
+ * @param {string | null} [parentId]
13
+ * @param {number | null} [index]
14
+ */
15
+ static create(nabu: Nabu, type: string, props?: Object, parentId?: string | null, index?: number | null): ZoneBlock;
16
+ /** @param {Nabu} nabu @param {ZoneNode} node */
17
+ constructor(nabu: Nabu, node: ZoneNode);
18
+ synopsisContainer: LoroText;
19
+ /** @type {string} */
20
+ _status: string;
21
+ /** @type {number | null} */
22
+ _wordCountTarget: number | null;
23
+ /** @type {string} */
24
+ _title: string;
25
+ /** @type {string} */
26
+ synopsisText: string;
27
+ zones: Zones;
28
+ wordCount: number;
29
+ set status(value: string);
30
+ get status(): string;
31
+ set wordCountTarget(value: number | null);
32
+ get wordCountTarget(): number | null;
33
+ set title(value: string);
34
+ get title(): string;
35
+ /** Returns the LoroText container for direct CRDT mutation. */
36
+ get synopsis(): LoroText;
37
+ /**
38
+ * Replace the synopsis text entirely.
39
+ * @param {string} text
40
+ */
41
+ setSynopsis(text: string): void;
42
+ get clipboardProps(): {
43
+ status: string;
44
+ wordCountTarget: number | null;
45
+ };
46
+ /**
47
+ * Called via ascend("onSplit") when a child block's Enter key fires.
48
+ * Creates a new paragraph inside this Zone, never outside it.
49
+ *
50
+ * @param {Event | null} event
51
+ * @param {{ from: import('../block.svelte.js').Block, offset: number, delta: import('loro-crdt').Delta<string>[] }} data
52
+ */
53
+ onSplit(event: Event | null, data: {
54
+ from: import("../block.svelte.js").Block;
55
+ offset: number;
56
+ delta: import("loro-crdt").Delta<string>[];
57
+ }): {
58
+ block: import("../block.svelte.js").Block;
59
+ };
60
+ }
61
+ export class Zones {
62
+ /** @param {Nabu} nabu */
63
+ static get(nabu: Nabu): Zones;
64
+ /** @param {Nabu} nabu */
65
+ constructor(nabu: Nabu);
66
+ /**
67
+ * Flat list of all ZoneBlocks in document order (DFS traversal).
68
+ * @type {ZoneBlock[]}
69
+ */
70
+ all: ZoneBlock[];
71
+ /**
72
+ * Total number of zones.
73
+ */
74
+ count: number;
75
+ /**
76
+ * Hierarchical zone tree — zones nested inside other zones.
77
+ * @type {Array<{zone: ZoneBlock, children: any[]}>}
78
+ */
79
+ tree: Array<{
80
+ zone: ZoneBlock;
81
+ children: any[];
82
+ }>;
83
+ /**
84
+ * The innermost zone containing the current cursor, or null if outside any zone.
85
+ * @type {ZoneBlock | null}
86
+ */
87
+ current: ZoneBlock | null;
88
+ /**
89
+ * Index of the current zone in `all` (-1 if cursor is outside any zone).
90
+ */
91
+ currentIndex: number;
92
+ /**
93
+ * Navigate to the next zone (moves cursor to its first text position).
94
+ */
95
+ goToNext(): void;
96
+ /**
97
+ * Navigate to the previous zone.
98
+ */
99
+ goToPrevious(): void;
100
+ #private;
101
+ }
102
+ export type ZoneNode = NabuNode<{
103
+ type: "zone";
104
+ synopsis: LoroText;
105
+ status: string;
106
+ wordCountTarget: number | null;
107
+ title: string;
108
+ }>;
109
+ import { MegaBlock } from '../megablock.svelte.js';
110
+ import { LoroText } from 'loro-crdt';
111
+ import type { Nabu } from '../nabu.svelte.js';
112
+ import type { NabuNode } from '../nabu.svelte.js';
@@ -0,0 +1,321 @@
1
+ import { untrack } from 'svelte';
2
+ import { MegaBlock } from '../megablock.svelte.js';
3
+ import { LoroText } from 'loro-crdt';
4
+
5
+ /**
6
+ * @import { Nabu, NabuNode } from '../nabu.svelte.js';
7
+ */
8
+
9
+ /**
10
+ * @typedef {NabuNode<{type: "zone", synopsis: LoroText, status: string, wordCountTarget: number | null, title: string}>} ZoneNode
11
+ */
12
+
13
+ export class ZoneBlock extends MegaBlock {
14
+ /** @param {Nabu} nabu @param {ZoneNode} node */
15
+ constructor(nabu, node) {
16
+ super(nabu, node);
17
+
18
+ const data = node.data;
19
+
20
+ // Synopsis LoroText — get existing or create on first construction
21
+ this.synopsisContainer = /** @type {LoroText} */ (
22
+ data.get('synopsis') ?? data.setContainer('synopsis', new LoroText())
23
+ );
24
+
25
+ // Initialize $state backing fields from Loro
26
+ this._status = data.get('status') ?? 'draft';
27
+ this._wordCountTarget = data.get('wordCountTarget') ?? null;
28
+ this._title = data.get('title') ?? '';
29
+ this.synopsisText = this.synopsisContainer.toString();
30
+
31
+ // Subscribe to map changes for reactive scalar fields
32
+ data.subscribe(() => {
33
+ this._status = data.get('status') ?? 'draft';
34
+ this._wordCountTarget = data.get('wordCountTarget') ?? null;
35
+ this._title = data.get('title') ?? '';
36
+ });
37
+
38
+ // Subscribe to synopsis LoroText changes
39
+ this.synopsisContainer.subscribe(() => {
40
+ this.synopsisText = this.synopsisContainer.toString();
41
+ });
42
+
43
+ this.serializers.set('markdown', () => {
44
+ const header = `<!-- zone: ${this._status} -->`;
45
+ const body = this.children
46
+ .map(child => child.serialize('markdown'))
47
+ .filter(Boolean)
48
+ .join('\n\n');
49
+ return [header, body].filter(Boolean).join('\n');
50
+ });
51
+
52
+ this.serializers.set('json', () => ({
53
+ id: this.id,
54
+ type: 'zone',
55
+ props: { status: this._status, wordCountTarget: this._wordCountTarget },
56
+ children: this.children.map(child => child.serialize('json')).filter(Boolean),
57
+ }));
58
+
59
+ this.serializers.set('application/x-nabu+json', () => ({
60
+ type: 'zone',
61
+ props: this.clipboardProps,
62
+ children: this.children
63
+ .map(child => child.serialize('application/x-nabu+json'))
64
+ .filter(Boolean),
65
+ }));
66
+
67
+ this.zones = Zones.get(nabu);
68
+ }
69
+
70
+
71
+
72
+
73
+ // zones = $derived.by(() => {
74
+ // this.nabu.systems.has('zones');
75
+ // return untrack(() => Zones.get(this.nabu));
76
+ // });
77
+
78
+ // ── Reactive backing fields ─────────────────────────────────────────────
79
+
80
+ /** @type {string} */
81
+ _status = $state('draft');
82
+
83
+ /** @type {number | null} */
84
+ _wordCountTarget = $state(null);
85
+
86
+ /** @type {string} */
87
+ _title = $state('');
88
+
89
+ /** @type {string} */
90
+ synopsisText = $state('');
91
+
92
+ // ── Derived ─────────────────────────────────────────────────────────────
93
+
94
+ wordCount = $derived.by(() => {
95
+ let count = 0;
96
+ /** @param {import('../block.svelte.js').Block[]} blocks */
97
+ const traverse = (blocks) => {
98
+ for (const block of blocks) {
99
+ const tb = block.behaviors?.get('text');
100
+ if (tb && typeof tb.text === 'string') {
101
+ count += tb.text.trim().split(/\s+/).filter(Boolean).length;
102
+ }
103
+ // @ts-ignore — children exists on MegaBlock
104
+ if (block.children?.length) traverse(block.children);
105
+ }
106
+ };
107
+ traverse(this.children);
108
+ return count;
109
+ });
110
+
111
+ // ── Getters / setters ───────────────────────────────────────────────────
112
+
113
+ get status() { return this._status; }
114
+ set status(value) {
115
+ this._status = value;
116
+ this.node.data.set('status', value);
117
+ this.commit();
118
+ }
119
+
120
+ get wordCountTarget() { return this._wordCountTarget; }
121
+ set wordCountTarget(value) {
122
+ this._wordCountTarget = value ?? null;
123
+ this.node.data.set('wordCountTarget', value ?? null);
124
+ this.commit();
125
+ }
126
+
127
+ get title() { return this._title; }
128
+ set title(value) {
129
+ this._title = value ?? '';
130
+ /** @type {any} */ (this.node.data).set('title', value ?? '');
131
+ this.commit();
132
+ }
133
+
134
+ /** Returns the LoroText container for direct CRDT mutation. */
135
+ get synopsis() { return this.synopsisContainer; }
136
+
137
+ /**
138
+ * Replace the synopsis text entirely.
139
+ * @param {string} text
140
+ */
141
+ setSynopsis(text) {
142
+ const len = this.synopsisContainer.length;
143
+ if (len > 0) this.synopsisContainer.delete(0, len);
144
+ if (text) this.synopsisContainer.insert(0, text);
145
+ this.commit();
146
+ }
147
+
148
+ get clipboardProps() {
149
+ return { status: this._status, wordCountTarget: this._wordCountTarget };
150
+ }
151
+
152
+ // ── Container split ─────────────────────────────────────────────────────
153
+
154
+ /**
155
+ * Called via ascend("onSplit") when a child block's Enter key fires.
156
+ * Creates a new paragraph inside this Zone, never outside it.
157
+ *
158
+ * @param {Event | null} event
159
+ * @param {{ from: import('../block.svelte.js').Block, offset: number, delta: import('loro-crdt').Delta<string>[] }} data
160
+ */
161
+ onSplit(event, data) {
162
+ const { from: sourceBlock, offset, delta } = data;
163
+
164
+ // Delete content from split point to end of source block
165
+ sourceBlock.delete({ from: offset, to: -1 });
166
+
167
+ const currentIndex = sourceBlock.node.index();
168
+
169
+ // Insert new paragraph inside THIS zone (not the zone's parent)
170
+ const newParagraph = this.nabu.insert(
171
+ 'paragraph',
172
+ { delta },
173
+ this.node.id.toString(),
174
+ currentIndex + 1
175
+ );
176
+
177
+ this.nabu.commit().then(() => this.nabu.selection.setCursor(newParagraph, 0));
178
+ return { block: newParagraph };
179
+ }
180
+
181
+ // ── Static factory ──────────────────────────────────────────────────────
182
+
183
+ /**
184
+ * @param {Nabu} nabu
185
+ * @param {string} type
186
+ * @param {Object} [props]
187
+ * @param {string | null} [parentId]
188
+ * @param {number | null} [index]
189
+ */
190
+ static create(nabu, type, props = {}, parentId = null, index = null) {
191
+ const node = nabu.tree.createNode(
192
+ parentId || undefined,
193
+ index != null ? index : undefined
194
+ );
195
+
196
+ node.data.set('type', 'zone');
197
+ node.data.set('status', props.status ?? 'draft');
198
+ node.data.set('wordCountTarget', props.wordCountTarget ?? null);
199
+
200
+ const synopsisContainer = node.data.setContainer('synopsis', new LoroText());
201
+ if (props.synopsis) synopsisContainer.insert(0, props.synopsis);
202
+
203
+ return new ZoneBlock(nabu, node);
204
+ }
205
+ }
206
+
207
+ export class Zones {
208
+ /** @type {Nabu} */
209
+ #nabu;
210
+
211
+ /** @param {Nabu} nabu */
212
+ constructor(nabu) {
213
+ this.#nabu = nabu;
214
+ }
215
+
216
+ /** @param {Nabu} nabu */
217
+ static get(nabu) {
218
+ if (!nabu.systems.has('zones')) {
219
+ const zones = new Zones(nabu);
220
+ nabu.systems.set('zones', zones);
221
+ return zones;
222
+ }
223
+ return /** @type {Zones} */ (nabu.systems.get('zones'));
224
+ }
225
+
226
+ /**
227
+ * Flat list of all ZoneBlocks in document order (DFS traversal).
228
+ * @type {ZoneBlock[]}
229
+ */
230
+ all = $derived.by(() => {
231
+ /** @type {ZoneBlock[]} */
232
+ const result = [];
233
+ /** @param {import('../block.svelte.js').Block[]} blocks */
234
+ const traverse = (blocks) => {
235
+ for (const block of blocks) {
236
+ if (block.type === 'zone') result.push(/** @type {ZoneBlock} */ (block));
237
+ const children = /** @type {any} */ (block).children;
238
+ if (children?.length) traverse(children);
239
+ }
240
+ };
241
+ traverse(this.#nabu.children);
242
+ return result;
243
+ });
244
+
245
+ /**
246
+ * Total number of zones.
247
+ */
248
+ count = $derived(this.all.length);
249
+
250
+ /**
251
+ * Hierarchical zone tree — zones nested inside other zones.
252
+ * @type {Array<{zone: ZoneBlock, children: any[]}>}
253
+ */
254
+ tree = $derived.by(() => {
255
+ /** @param {import('../block.svelte.js').Block[]} blocks */
256
+ const buildTree = (blocks) => {
257
+ /** @type {Array<{zone: ZoneBlock, children: any[]}>} */
258
+ const result = [];
259
+ for (const block of blocks) {
260
+ const children = /** @type {any} */ (block).children ?? [];
261
+ if (block.type === 'zone') {
262
+ result.push({ zone: /** @type {ZoneBlock} */ (block), children: buildTree(children) });
263
+ } else if (children.length) {
264
+ result.push(...buildTree(children));
265
+ }
266
+ }
267
+ return result;
268
+ };
269
+ return buildTree(this.#nabu.children);
270
+ });
271
+
272
+ /**
273
+ * The innermost zone containing the current cursor, or null if outside any zone.
274
+ * @type {ZoneBlock | null}
275
+ */
276
+ current = $derived.by(() => {
277
+ const anchor = this.#nabu.selection.anchorBlock;
278
+ if (!anchor) return null;
279
+ let node = anchor.parent;
280
+ while (node) {
281
+ if (node.type === 'zone') return /** @type {ZoneBlock} */ (node);
282
+ node = node.parent;
283
+ }
284
+ return null;
285
+ });
286
+
287
+ /**
288
+ * Index of the current zone in `all` (-1 if cursor is outside any zone).
289
+ */
290
+ currentIndex = $derived.by(() => {
291
+ const zone = this.current;
292
+ if (!zone) return -1;
293
+ return this.all.indexOf(zone);
294
+ });
295
+
296
+ /**
297
+ * Navigate to the next zone (moves cursor to its first text position).
298
+ */
299
+ goToNext() {
300
+ const idx = this.currentIndex;
301
+ const next = idx === -1
302
+ ? this.all[0]
303
+ : this.all[idx + 1];
304
+ if (next) this.#focusZone(next);
305
+ }
306
+
307
+ /**
308
+ * Navigate to the previous zone.
309
+ */
310
+ goToPrevious() {
311
+ const idx = this.currentIndex;
312
+ if (idx <= 0) return;
313
+ this.#focusZone(this.all[idx - 1]);
314
+ }
315
+
316
+ /** @param {ZoneBlock} zone */
317
+ #focusZone(zone) {
318
+ const firstChild = /** @type {any} */ (zone).children?.[0];
319
+ if (firstChild) this.#nabu.selection.setCursor(firstChild, 0);
320
+ }
321
+ }