@aionbuilders/nabu 0.1.0-alpha.1 → 0.1.0-alpha.10

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 (108) hide show
  1. package/README.md +15 -1
  2. package/dist/behaviors/text/index.d.ts +1 -1
  3. package/dist/behaviors/text/index.js +1 -1
  4. package/dist/behaviors/text/rich-text.extension.js +96 -30
  5. package/dist/behaviors/text/text.behavior.svelte.d.ts +19 -0
  6. package/dist/behaviors/text/text.behavior.svelte.js +64 -2
  7. package/dist/blocks/Block.svelte +3 -3
  8. package/dist/blocks/BlockGap.svelte +55 -0
  9. package/dist/blocks/BlockGap.svelte.d.ts +11 -0
  10. package/dist/blocks/Nabu.svelte +8 -0
  11. package/dist/blocks/block.extension.d.ts +2 -0
  12. package/dist/blocks/block.extension.js +32 -0
  13. package/dist/blocks/block.svelte.d.ts +41 -9
  14. package/dist/blocks/block.svelte.js +55 -18
  15. package/dist/blocks/container.utils.d.ts +54 -4
  16. package/dist/blocks/container.utils.js +211 -8
  17. package/dist/blocks/dialogue/Dialogue.svelte +46 -0
  18. package/dist/blocks/dialogue/Dialogue.svelte.d.ts +11 -0
  19. package/dist/blocks/dialogue/dialogue.svelte.d.ts +41 -0
  20. package/dist/blocks/dialogue/dialogue.svelte.js +87 -0
  21. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.d.ts +3 -0
  22. package/dist/blocks/dialogue/hooks/onBeforeInput.hook.js +52 -0
  23. package/dist/blocks/dialogue/index.d.ts +7 -0
  24. package/dist/blocks/dialogue/index.js +47 -0
  25. package/dist/blocks/heading/Heading.svelte +13 -9
  26. package/dist/blocks/heading/heading.svelte.d.ts +40 -4
  27. package/dist/blocks/heading/heading.svelte.js +60 -4
  28. package/dist/blocks/heading/hooks/onBeforeInput.hook.js +1 -1
  29. package/dist/blocks/heading/index.d.ts +2 -2
  30. package/dist/blocks/heading/index.js +11 -7
  31. package/dist/blocks/index.d.ts +7 -4
  32. package/dist/blocks/index.js +7 -4
  33. package/dist/blocks/list/ListItem.svelte +6 -2
  34. package/dist/blocks/list/hooks/onBeforeInput.hook.d.ts +3 -0
  35. package/dist/blocks/list/hooks/onBeforeInput.hook.js +77 -0
  36. package/dist/blocks/list/index.d.ts +2 -2
  37. package/dist/blocks/list/index.js +17 -3
  38. package/dist/blocks/list/list-item.svelte.d.ts +59 -6
  39. package/dist/blocks/list/list-item.svelte.js +157 -89
  40. package/dist/blocks/list/list.behavior.svelte.d.ts +1 -0
  41. package/dist/blocks/list/list.behavior.svelte.js +5 -4
  42. package/dist/blocks/list/list.svelte.d.ts +60 -7
  43. package/dist/blocks/list/list.svelte.js +116 -15
  44. package/dist/blocks/megablock.svelte.d.ts +30 -5
  45. package/dist/blocks/megablock.svelte.js +113 -17
  46. package/dist/blocks/nabu.svelte.d.ts +44 -6
  47. package/dist/blocks/nabu.svelte.js +397 -15
  48. package/dist/blocks/paragraph/Paragraph.svelte +12 -16
  49. package/dist/blocks/paragraph/Paragraph.svelte.d.ts +2 -2
  50. package/dist/blocks/paragraph/index.d.ts +2 -2
  51. package/dist/blocks/paragraph/index.js +29 -8
  52. package/dist/blocks/paragraph/paragraph.svelte.d.ts +33 -5
  53. package/dist/blocks/paragraph/paragraph.svelte.js +55 -3
  54. package/dist/blocks/selection.svelte.d.ts +6 -5
  55. package/dist/blocks/selection.svelte.js +209 -18
  56. package/dist/blocks/variable.svelte.d.ts +47 -0
  57. package/dist/blocks/variable.svelte.js +51 -0
  58. package/dist/blocks/zone/TemplateEditor.svelte +308 -0
  59. package/dist/blocks/zone/TemplateEditor.svelte.d.ts +11 -0
  60. package/dist/blocks/zone/Zone.svelte +272 -0
  61. package/dist/blocks/zone/Zone.svelte.d.ts +11 -0
  62. package/dist/blocks/zone/ZoneEditor copy.svelte +118 -0
  63. package/dist/blocks/zone/ZoneEditor copy.svelte.d.ts +11 -0
  64. package/dist/blocks/zone/ZoneEditor.svelte +289 -0
  65. package/dist/blocks/zone/ZoneEditor.svelte.d.ts +11 -0
  66. package/dist/blocks/zone/ZoneTemplatesList.svelte +188 -0
  67. package/dist/blocks/zone/ZoneTemplatesList.svelte.d.ts +11 -0
  68. package/dist/blocks/zone/hooks/onBeforeInput.hook.d.ts +3 -0
  69. package/dist/blocks/zone/hooks/onBeforeInput.hook.js +30 -0
  70. package/dist/blocks/zone/index.d.ts +2 -0
  71. package/dist/blocks/zone/index.js +2 -0
  72. package/dist/blocks/zone/zone.extension.d.ts +2 -0
  73. package/dist/blocks/zone/zone.extension.js +227 -0
  74. package/dist/blocks/zone/zone.svelte.d.ts +222 -0
  75. package/dist/blocks/zone/zone.svelte.js +620 -0
  76. package/dist/index.d.ts +2 -0
  77. package/dist/index.js +3 -1
  78. package/dist/nabu-theme.css +92 -0
  79. package/dist/overlays/context/Context.svelte +179 -0
  80. package/dist/overlays/context/Context.svelte.d.ts +16 -0
  81. package/dist/overlays/context/collect.d.ts +17 -0
  82. package/dist/overlays/context/collect.js +33 -0
  83. package/dist/overlays/context/context.extension.d.ts +2 -0
  84. package/dist/overlays/context/context.extension.js +8 -0
  85. package/dist/overlays/context/context.svelte.d.ts +81 -0
  86. package/dist/overlays/context/context.svelte.js +159 -0
  87. package/dist/overlays/context/index.d.ts +3 -0
  88. package/dist/overlays/context/index.js +3 -0
  89. package/dist/paste/html.paste.d.ts +12 -0
  90. package/dist/paste/html.paste.js +192 -0
  91. package/dist/paste/index.d.ts +4 -0
  92. package/dist/paste/index.js +4 -0
  93. package/dist/paste/markdown.paste.d.ts +12 -0
  94. package/dist/paste/markdown.paste.js +140 -0
  95. package/dist/paste/nabu.paste.d.ts +2 -0
  96. package/dist/paste/nabu.paste.js +20 -0
  97. package/dist/paste/plain-text.paste.d.ts +8 -0
  98. package/dist/paste/plain-text.paste.js +42 -0
  99. package/dist/persistence/indexeddb.d.ts +19 -0
  100. package/dist/persistence/indexeddb.js +71 -0
  101. package/dist/persistence/persistence.d.ts +48 -0
  102. package/dist/persistence/persistence.js +80 -0
  103. package/dist/presets.d.ts +1 -0
  104. package/dist/presets.js +18 -4
  105. package/dist/utils/extensions.d.ts +63 -0
  106. package/dist/utils/extensions.js +33 -0
  107. package/dist/utils/selection.svelte.js +0 -5
  108. package/package.json +14 -3
@@ -0,0 +1,620 @@
1
+ import { untrack } from 'svelte';
2
+ import { MegaBlock } from '../megablock.svelte.js';
3
+ import { LoroText } from 'loro-crdt';
4
+ import { SvelteMap, SvelteSet } from 'svelte/reactivity';
5
+
6
+ /**
7
+ * @import { Nabu, NabuNode } from '../nabu.svelte.js';
8
+ */
9
+
10
+ /**
11
+ * @typedef {NabuNode<{type: "zone", synopsis: LoroText, status: string, wordCountTarget: number | null, title: string, template: string | null}>} ZoneNode
12
+ */
13
+
14
+ export class ZoneBlock extends MegaBlock {
15
+ /** @param {Nabu} nabu @param {ZoneNode} node */
16
+ constructor(nabu, node) {
17
+ super(nabu, node);
18
+
19
+ const data = node.data;
20
+
21
+ // Synopsis LoroText — get existing or create on first construction
22
+ this.synopsisContainer = /** @type {LoroText} */ (
23
+ data.get('synopsis') ?? data.setContainer('synopsis', new LoroText())
24
+ );
25
+
26
+ // Initialize $state backing fields from Loro
27
+ this._status = data.get('status') ?? 'draft';
28
+ this._wordCountTarget = data.get('wordCountTarget') ?? null;
29
+ this._title = data.get('title') ?? '';
30
+ this._template = /** @type {string | null} */ (data.get('template') ?? null);
31
+ this.synopsisText = this.synopsisContainer.toString();
32
+
33
+ // Subscribe to map changes for reactive scalar fields
34
+ data.subscribe(() => {
35
+ this._status = data.get('status') ?? 'draft';
36
+ this._wordCountTarget = data.get('wordCountTarget') ?? null;
37
+ this._title = data.get('title') ?? '';
38
+ this._template = /** @type {string | null} */ (data.get('template') ?? null);
39
+ });
40
+
41
+ // Subscribe to synopsis LoroText changes
42
+ this.synopsisContainer.subscribe(() => {
43
+ this.synopsisText = this.synopsisContainer.toString();
44
+ });
45
+
46
+ this.serializers.set('markdown', () => {
47
+ const header = `<!-- zone: ${this._status} -->`;
48
+ const body = this.children
49
+ .map(child => child.serialize('markdown'))
50
+ .filter(Boolean)
51
+ .join('\n\n');
52
+ return [header, body].filter(Boolean).join('\n');
53
+ });
54
+
55
+ this.serializers.set('json', () => ({
56
+ id: this.id,
57
+ type: 'zone',
58
+ props: { status: this._status, wordCountTarget: this._wordCountTarget },
59
+ children: this.children.map(child => child.serialize('json')).filter(Boolean),
60
+ }));
61
+
62
+ this.serializers.set('application/x-nabu+json', () => ({
63
+ type: 'zone',
64
+ props: this.clipboardProps,
65
+ children: this.children
66
+ .map(child => child.serialize('application/x-nabu+json'))
67
+ .filter(Boolean),
68
+ }));
69
+
70
+ this.zones = Zones.get(nabu);
71
+
72
+
73
+ $effect.root(() => {
74
+ $effect(() => {
75
+ const templateId = this._template;
76
+ if (!templateId) {
77
+ this.zones.counters.unsubscribe(this);
78
+ this.counter = null;
79
+ return;
80
+ }
81
+ const template = this.zones.templates.get(templateId) || this.zones.templates.new(templateId);
82
+ const counter = template?.counter;
83
+ if (!counter) {
84
+ this.zones.counters.unsubscribe(this);
85
+ this.counter = null;
86
+ return;
87
+ }
88
+ this.counter = template.getCounter(this);
89
+ });
90
+ });
91
+ }
92
+
93
+
94
+
95
+
96
+ // zones = $derived.by(() => {
97
+ // this.nabu.systems.has('zones');
98
+ // return untrack(() => Zones.get(this.nabu));
99
+ // });
100
+
101
+ // ── Reactive backing fields ─────────────────────────────────────────────
102
+
103
+ /** @type {string} */
104
+ _status = $state('draft');
105
+
106
+ /** @type {number | null} */
107
+ _wordCountTarget = $state(null);
108
+
109
+ /** @type {string} */
110
+ _title = $state('');
111
+
112
+ /** @type {string | null} */
113
+ _template = $state(null);
114
+
115
+ /** Incremented each time the title input should be focused. */
116
+ _focusTitleTick = $state(0);
117
+
118
+ /** @type {string} */
119
+ synopsisText = $state('');
120
+
121
+ // ── Derived ─────────────────────────────────────────────────────────────
122
+
123
+ wordCount = $derived.by(() => {
124
+ let count = 0;
125
+ /** @param {import('../block.svelte.js').Block[]} blocks */
126
+ const traverse = (blocks) => {
127
+ for (const block of blocks) {
128
+ const tb = block.behaviors?.get('text');
129
+ if (tb && typeof tb.text === 'string') {
130
+ count += tb.text.trim().split(/\s+/).filter(Boolean).length;
131
+ }
132
+ // @ts-ignore — children exists on MegaBlock
133
+ if (block.children?.length) traverse(block.children);
134
+ }
135
+ };
136
+ traverse(this.children);
137
+ return count;
138
+ });
139
+
140
+ // ── Getters / setters ───────────────────────────────────────────────────
141
+
142
+ get status() { return this._status; }
143
+ set status(value) {
144
+ this._status = value;
145
+ this.node.data.set('status', value);
146
+ this.commit();
147
+ }
148
+
149
+ get wordCountTarget() { return this._wordCountTarget; }
150
+ set wordCountTarget(value) {
151
+ this._wordCountTarget = value ?? null;
152
+ this.node.data.set('wordCountTarget', value ?? null);
153
+ this.commit();
154
+ }
155
+
156
+ get title() { return this._title; }
157
+ set title(value) {
158
+ this._title = value ?? '';
159
+ /** @type {any} */ (this.node.data).set('title', value ?? '');
160
+ this.commit();
161
+ }
162
+
163
+ get template() { return this._template; }
164
+ set template(value) {
165
+ this._template = value ?? null;
166
+ /** @type {any} */ (this.node.data).set('template', value ?? null);
167
+ this.commit();
168
+ }
169
+
170
+ focusTitle() { this._focusTitleTick++; }
171
+
172
+ /** Returns the LoroText container for direct CRDT mutation. */
173
+ get synopsis() { return this.synopsisContainer; }
174
+
175
+ parentZones = $derived(this.parents.filter(p => p instanceof ZoneBlock));
176
+ parentZone = $derived(this.parentZones[0] ?? null);
177
+
178
+ /** @type {Counter?} */
179
+ counter = $state(null);
180
+ count = $state(0);
181
+
182
+
183
+ /**
184
+ * Replace the synopsis text entirely.
185
+ * @param {string} text
186
+ */
187
+ setSynopsis(text) {
188
+ const len = this.synopsisContainer.length;
189
+ if (len > 0) this.synopsisContainer.delete(0, len);
190
+ if (text) this.synopsisContainer.insert(0, text);
191
+ this.commit();
192
+ }
193
+
194
+ get clipboardProps() {
195
+ return { status: this._status, wordCountTarget: this._wordCountTarget };
196
+ }
197
+
198
+ // ── Container split ─────────────────────────────────────────────────────
199
+
200
+ /**
201
+ * Called via ascend("onSplit") when a child block's Enter key fires.
202
+ * Creates a new paragraph inside this Zone, never outside it.
203
+ *
204
+ * @param {Event | null} event
205
+ * @param {{ from: import('../block.svelte.js').Block, offset: number, delta: import('loro-crdt').Delta<string>[] }} data
206
+ */
207
+ onSplit(event, data) {
208
+ const { from: sourceBlock, offset, delta } = data;
209
+
210
+ // Delete content from split point to end of source block
211
+ sourceBlock.delete({ from: offset, to: -1 });
212
+
213
+ const currentIndex = sourceBlock.node.index();
214
+
215
+ // Insert new paragraph inside THIS zone (not the zone's parent)
216
+ const newParagraph = this.nabu.insert(
217
+ 'paragraph',
218
+ { delta },
219
+ this.node.id.toString(),
220
+ currentIndex + 1
221
+ );
222
+
223
+ this.nabu.commit().then(() => this.nabu.selection.setCursor(newParagraph, 0));
224
+ return { block: newParagraph };
225
+ }
226
+
227
+ // ── Static factory ──────────────────────────────────────────────────────
228
+
229
+ /**
230
+ * @param {Nabu} nabu
231
+ * @param {string} type
232
+ * @param {Object} [props]
233
+ * @param {string | null} [parentId]
234
+ * @param {number | null} [index]
235
+ */
236
+ static create(nabu, type, props = {}, parentId = null, index = null) {
237
+ const node = nabu.tree.createNode(
238
+ parentId || undefined,
239
+ index != null ? index : undefined
240
+ );
241
+
242
+ node.data.set('type', 'zone');
243
+ node.data.set('status', props.status ?? 'draft');
244
+ node.data.set('wordCountTarget', props.wordCountTarget ?? null);
245
+ /** @type {any} */ (node.data).set('template', /** @type {any} */ (props).template ?? null);
246
+
247
+ const synopsisContainer = node.data.setContainer('synopsis', new LoroText());
248
+ if (props.synopsis) synopsisContainer.insert(0, props.synopsis);
249
+
250
+ return new ZoneBlock(nabu, node);
251
+ }
252
+ }
253
+
254
+ export class Zones {
255
+ /** @type {Nabu} */
256
+ #nabu;
257
+
258
+ /** @param {Nabu} nabu */
259
+ constructor(nabu) {
260
+ this.#nabu = nabu;
261
+ this.templates = new Templates(this.#nabu, this);
262
+ }
263
+
264
+ /** @param {Nabu} nabu */
265
+ static get(nabu) {
266
+ if (!nabu.systems.has('zones')) {
267
+ const zones = new Zones(nabu);
268
+ nabu.systems.set('zones', zones);
269
+ return zones;
270
+ }
271
+ return /** @type {Zones} */ (nabu.systems.get('zones'));
272
+ }
273
+
274
+ /**
275
+ * Flat list of all ZoneBlocks in document order (DFS traversal).
276
+ * @type {ZoneBlock[]}
277
+ */
278
+ all = $derived.by(() => {
279
+ /** @type {ZoneBlock[]} */
280
+ const result = [];
281
+ /** @param {import('../block.svelte.js').Block[]} blocks */
282
+ const traverse = (blocks) => {
283
+ for (const block of blocks) {
284
+ if (block.type === 'zone') result.push(/** @type {ZoneBlock} */ (block));
285
+ const children = /** @type {any} */ (block).children;
286
+ if (children?.length) traverse(children);
287
+ }
288
+ };
289
+ traverse(this.#nabu.children);
290
+ return result;
291
+ });
292
+
293
+ /**
294
+ * Total number of zones.
295
+ */
296
+ count = $derived(this.all.length);
297
+
298
+ /**
299
+ * Hierarchical zone tree — zones nested inside other zones.
300
+ * @type {Array<{zone: ZoneBlock, children: any[]}>}
301
+ */
302
+ tree = $derived.by(() => {
303
+ /** @param {import('../block.svelte.js').Block[]} blocks */
304
+ const buildTree = (blocks) => {
305
+ /** @type {Array<{zone: ZoneBlock, children: any[]}>} */
306
+ const result = [];
307
+ for (const block of blocks) {
308
+ const children = /** @type {any} */ (block).children ?? [];
309
+ if (block.type === 'zone') {
310
+ result.push({ zone: /** @type {ZoneBlock} */ (block), children: buildTree(children) });
311
+ } else if (children.length) {
312
+ result.push(...buildTree(children));
313
+ }
314
+ }
315
+ return result;
316
+ };
317
+ return buildTree(this.#nabu.children);
318
+ });
319
+
320
+ /**
321
+ * The innermost zone containing the current cursor, or null if outside any zone.
322
+ * @type {ZoneBlock | null}
323
+ */
324
+ current = $derived.by(() => {
325
+ const anchor = this.#nabu.selection.anchorBlock;
326
+ if (!anchor) return null;
327
+ let node = anchor.parent;
328
+ while (node) {
329
+ if (node.type === 'zone') return /** @type {ZoneBlock} */ (node);
330
+ node = node.parent;
331
+ }
332
+ return null;
333
+ });
334
+
335
+ /**
336
+ * Index of the current zone in `all` (-1 if cursor is outside any zone).
337
+ */
338
+ currentIndex = $derived.by(() => {
339
+ const zone = this.current;
340
+ if (!zone) return -1;
341
+ return this.all.indexOf(zone);
342
+ });
343
+
344
+ /**
345
+ * Navigate to the next zone (moves cursor to its first text position).
346
+ */
347
+ goToNext() {
348
+ const idx = this.currentIndex;
349
+ const next = idx === -1
350
+ ? this.all[0]
351
+ : this.all[idx + 1];
352
+ if (next) this.#focusZone(next);
353
+ }
354
+
355
+ /**
356
+ * Navigate to the previous zone.
357
+ */
358
+ goToPrevious() {
359
+ const idx = this.currentIndex;
360
+ if (idx <= 0) return;
361
+ this.#focusZone(this.all[idx - 1]);
362
+ }
363
+
364
+ /** @param {ZoneBlock} zone */
365
+ #focusZone(zone) {
366
+ const firstChild = /** @type {any} */ (zone).children?.[0];
367
+ if (firstChild) this.#nabu.selection.setCursor(firstChild, 0);
368
+ }
369
+
370
+ counters = new Counters();
371
+
372
+ }
373
+
374
+ /** @extends SvelteMap<string, Template> */
375
+ export class Templates extends SvelteMap {
376
+ /** @param {Nabu} nabu @param {Zones} zones */
377
+ constructor(nabu, zones) {
378
+ super();
379
+ this.nabu = nabu;
380
+ this.zones = zones;
381
+
382
+
383
+ this.map = this.nabu.doc.getMap('zones::templates');
384
+ Object.entries(this.map.toJSON()).forEach(([key, value]) => {
385
+ this.set(key, new Template(value, this));
386
+ });
387
+ }
388
+
389
+ /** @param {string} id @param {TemplateData} [data] */
390
+ new(id, data) {
391
+ const templateData = { id, label: id, ...data };
392
+ const template = new Template(templateData, this);
393
+ this.set(id, template);
394
+ this.map.set(id, templateData);
395
+ return template;
396
+ }
397
+ }
398
+
399
+ /**
400
+ * @typedef {Object} TemplateData
401
+ * @property {string} id - Unique identifier for the template.
402
+ * @property {string} label - The template's display name.
403
+ * @property {{
404
+ * scope: "root" | "parent",
405
+ * } | boolean | null | undefined} [counter]
406
+ */
407
+
408
+ export class Template {
409
+ /** @param {TemplateData} init @param {Templates} templates */
410
+ constructor(init, templates) {
411
+ this.templates = templates;
412
+ this.id = init.id;
413
+ this._label = init.label;
414
+ this._counter = init.counter;
415
+
416
+ }
417
+
418
+ _label = $state('');
419
+ get label() { return this._label; }
420
+ set label(value) {
421
+ this._label = value;
422
+ this.update(data => ({ ...data, label: value }));
423
+ }
424
+
425
+ renderLabel(index, title = '') {
426
+ return formatTemplateLabel(this.label, index, title);
427
+ }
428
+
429
+ /** @type {TemplateData['counter']} */
430
+ _counter = $state(null);
431
+ /**
432
+ * @returns {{scope: "root" | "parent"} | null | undefined}
433
+ */
434
+ get counter() {
435
+ if (this._counter === true) return { scope: 'root' };
436
+ if (this._counter === false) return null;
437
+ return this._counter;
438
+ }
439
+ /** @param {TemplateData['counter']} value */
440
+ set counter(value) {
441
+ this._counter = value;
442
+ this.update(data => ({ ...data, counter: value }));
443
+ }
444
+
445
+
446
+ /** @param {ZoneBlock} zone */
447
+ getCounter(zone) {
448
+ if (this.counter?.scope === 'root') {
449
+ return this.templates.zones.counters.subscribe(zone, 'root', this.id);
450
+ } else if (this.counter?.scope === 'parent') {
451
+ const parentZone = zone.parentZone;
452
+ const parentZoneId = parentZone ? parentZone.id : null;
453
+ if (!parentZoneId) return null;
454
+ return this.templates.zones.counters.subscribe(zone, parentZoneId, this.id);
455
+ }
456
+ }
457
+
458
+ /** @param {function(TemplateData): TemplateData} callback */
459
+ update(callback) {
460
+ const updatedData = callback({
461
+ id: this.id,
462
+ label: this._label,
463
+ counter: this._counter,
464
+ });
465
+ this.templates.map.set(this.id, updatedData);
466
+ }
467
+ }
468
+
469
+ export function formatTemplateLabel(formatString, index, title = '') {
470
+ if (!formatString) return '';
471
+ let text = formatString;
472
+ if (text.includes('{{1}}')) text = text.replace(/\{\{1\}\}/g, String(index));
473
+ if (text.includes('{{A}}')) text = text.replace(/\{\{A\}\}/g, toAlpha(index, true));
474
+ if (text.includes('{{a}}')) text = text.replace(/\{\{a\}\}/g, toAlpha(index, false));
475
+ if (text.includes('{{I}}')) text = text.replace(/\{\{I\}\}/g, toRoman(index, true));
476
+ if (text.includes('{{i}}')) text = text.replace(/\{\{i\}\}/g, toRoman(index, false));
477
+ if (text.includes('{{title}}')) text = text.replace(/\{\{title\}\}/g, title);
478
+ return text;
479
+ }
480
+
481
+ function toAlpha(num, upper) {
482
+ let result = '';
483
+ while (num > 0) {
484
+ num--;
485
+ result = String.fromCharCode((upper ? 65 : 97) + (num % 26)) + result;
486
+ num = Math.floor(num / 26);
487
+ }
488
+ return result || (upper ? 'A' : 'a');
489
+ }
490
+
491
+ function toRoman(num, upper) {
492
+ if (num <= 0) return String(num);
493
+ const roman = {M:1000, CM:900, D:500, CD:400, C:100, XC:90, L:50, XL:40, X:10, IX:9, V:5, IV:4, I:1};
494
+ let str = '';
495
+ for (let i of Object.keys(roman)) {
496
+ let q = Math.floor(num / roman[i]);
497
+ num -= q * roman[i];
498
+ str += i.repeat(q);
499
+ }
500
+ return upper ? str : str.toLowerCase();
501
+ }
502
+
503
+ export class Counters {
504
+ /** @type {SvelteMap<string, Counter>} */
505
+ counters = new SvelteMap();
506
+
507
+ /** @type {SvelteMap<ZoneBlock, string>} */
508
+ index = new SvelteMap();
509
+
510
+ /**
511
+ * @param {ZoneBlock} zone
512
+ */
513
+ unsubscribe(zone) {
514
+ if (this.index.has(zone)) {
515
+ const oldName = this.index.get(zone);
516
+ if (oldName) {
517
+ const set = this.counters.get(oldName);
518
+ if (set) {
519
+ set.delete(zone);
520
+ untrack(() => set.size === 0 && set.unwatch());
521
+ }
522
+ }
523
+ this.index.delete(zone);
524
+ }
525
+ }
526
+
527
+ /**
528
+ * @param {ZoneBlock} zone
529
+ * @param {"root"|string} scope
530
+ * @param {string} name
531
+ */
532
+ subscribe(zone, scope, name) {
533
+ const c = scope + ':' + name;
534
+
535
+ if (this.index.has(zone)) {
536
+ const oldName = this.index.get(zone);
537
+ if (oldName) {
538
+ if (oldName === c) return this.counters.get(c);
539
+ this.unsubscribe(zone);
540
+ }
541
+ }
542
+
543
+ this.index.set(zone, c);
544
+
545
+ if (!this.counters.has(c)) {
546
+ this.counters.set(c, new Counter(scope, name));
547
+ }
548
+ const counter = this.counters.get(c);
549
+ counter?.add(zone);
550
+ return counter;
551
+ }
552
+ }
553
+
554
+ /**
555
+ * @extends SvelteSet<ZoneBlock>
556
+ */
557
+ class Counter extends SvelteSet {
558
+ /**
559
+ * @param {"root"|string} scope
560
+ * @param {string} name
561
+ */
562
+ constructor(scope, name) {
563
+ super();
564
+ this.scope = scope;
565
+ this.name = name;
566
+
567
+ // L'effet racine qui observe les changements dans l'ensemble (Set)
568
+ // et déclenche la mise à jour des `.count` des zones.
569
+ this.watcher = $effect.root(() => {
570
+ $effect(() => {
571
+ if (this.zones) {
572
+ // console.log(`Counter "${this.name}" (${this.scope}) has ${this.size} zones.`);
573
+ // On recalcule l'index pour chaque zone du compteur
574
+ this.zones.forEach(zone => {
575
+ // untrack n'est pas strictement nécessaire ici si count n'est pas lu
576
+ // dans cet effet, mais c'est une bonne pratique pour une simple écriture.
577
+ untrack(() => zone.count = this.getIndex(zone));
578
+ });
579
+ }
580
+ })
581
+ });
582
+ }
583
+
584
+ unwatch = () => {
585
+ // console.log(`Unwatching counter "${this.name}" (${this.scope}).`);
586
+ if (this.watcher) this.watcher();
587
+ }
588
+
589
+ // 1. Correction du Tri (Utiliser l'ordre du document plat) + Filtrage des fantômes
590
+ zones = $derived.by(() => {
591
+ const zonesInSet = Array.from(this);
592
+ if (zonesInSet.length === 0) return [];
593
+
594
+ // On récupère la liste maître aplatie via n'importe quelle zone de notre Set
595
+ const allZonesInDoc = zonesInSet[0].zones.all;
596
+
597
+ // On filtre les zones qui auraient été supprimées du document (fantômes)
598
+ const activeZones = zonesInSet.filter(z => allZonesInDoc.includes(z));
599
+
600
+ // On trie en utilisant la position globale dans le document
601
+ activeZones.sort((a, b) => allZonesInDoc.indexOf(a) - allZonesInDoc.indexOf(b));
602
+ return activeZones;
603
+ });
604
+
605
+ /**
606
+ * @param {ZoneBlock} targetZone
607
+ * @returns {number}
608
+ */
609
+ getIndex(targetZone) {
610
+ const sortedZones = this.zones;
611
+ const targetIndexInList = sortedZones.indexOf(targetZone);
612
+
613
+ if (targetIndexInList === -1) return 1;
614
+
615
+ // Grâce à l'architecture du Template qui crée des compteurs isolés (un par ID de parent),
616
+ // le Set ne contient DEJA que les zones qui doivent être comptées ensemble !
617
+ // L'index est donc tout simplement sa position dans ce sous-groupe.
618
+ return targetIndexInList + 1;
619
+ }
620
+ }
package/dist/index.d.ts CHANGED
@@ -2,4 +2,6 @@ export * from "./blocks";
2
2
  export * from "./utils";
3
3
  export * from "./behaviors";
4
4
  export * from "./presets";
5
+ export * from "./paste";
6
+ export * from "./overlays/context";
5
7
  export { RichTextExtension, RichText } from "./behaviors/text";
package/dist/index.js CHANGED
@@ -3,4 +3,6 @@ export { RichTextExtension, RichText } from './behaviors/text';
3
3
  export * from './blocks';
4
4
  export * from "./utils";
5
5
  export * from './behaviors';
6
- export * from './presets';
6
+ export * from './presets';
7
+ export * from './paste';
8
+ export * from './overlays/context';