@quillmark/svelte 0.33.0 → 0.35.0

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 (98) hide show
  1. package/README.md +73 -1
  2. package/THEMING.md +11 -10
  3. package/dist/core/address.d.ts +6 -0
  4. package/dist/core/address.js +16 -0
  5. package/dist/core/codec/anchor.d.ts +12 -0
  6. package/dist/core/codec/anchor.js +39 -0
  7. package/dist/core/codec/drag-move.d.ts +11 -0
  8. package/dist/core/codec/drag-move.js +143 -0
  9. package/dist/core/codec/encode.js +14 -5
  10. package/dist/core/codec/field.d.ts +44 -1
  11. package/dist/core/codec/field.js +137 -38
  12. package/dist/core/codec/index.d.ts +8 -2
  13. package/dist/core/codec/index.js +9 -2
  14. package/dist/core/codec/islands.d.ts +4 -1
  15. package/dist/core/codec/islands.js +6 -0
  16. package/dist/core/codec/keymap.d.ts +3 -0
  17. package/dist/core/codec/keymap.js +13 -12
  18. package/dist/core/codec/leave.d.ts +17 -0
  19. package/dist/core/codec/leave.js +78 -0
  20. package/dist/core/codec/prose.css +172 -0
  21. package/dist/core/codec/review-diff.d.ts +12 -0
  22. package/dist/core/codec/review-diff.js +131 -0
  23. package/dist/core/codec/review.d.ts +116 -0
  24. package/dist/core/codec/review.js +920 -0
  25. package/dist/core/codec/shortcuts.d.ts +20 -4
  26. package/dist/core/codec/shortcuts.js +27 -7
  27. package/dist/core/codec/slash.d.ts +3 -0
  28. package/dist/core/codec/slash.js +2 -1
  29. package/dist/core/codec/table-view.js +163 -25
  30. package/dist/core/codec/undo.d.ts +6 -0
  31. package/dist/core/codec/undo.js +25 -2
  32. package/dist/core/dragfollow.d.ts +18 -0
  33. package/dist/core/dragfollow.js +63 -0
  34. package/dist/core/theme.css +34 -7
  35. package/dist/preview/controller.js +16 -0
  36. package/dist/preview/strings.d.ts +4 -0
  37. package/dist/preview/strings.js +3 -1
  38. package/dist/visual/ArrayField.svelte +363 -57
  39. package/dist/visual/ArrayField.svelte.d.ts +5 -0
  40. package/dist/visual/BooleanField.svelte +60 -5
  41. package/dist/visual/BooleanField.svelte.d.ts +2 -1
  42. package/dist/visual/Card.svelte +27 -17
  43. package/dist/visual/CardControls.svelte +17 -7
  44. package/dist/visual/CardControls.svelte.d.ts +2 -0
  45. package/dist/visual/DateField.svelte +90 -39
  46. package/dist/visual/DateField.svelte.d.ts +2 -2
  47. package/dist/visual/Field.svelte +98 -6
  48. package/dist/visual/FieldHint.svelte +24 -9
  49. package/dist/visual/FieldLabel.svelte +128 -22
  50. package/dist/visual/FieldLabel.svelte.d.ts +9 -0
  51. package/dist/visual/FormatPopover.svelte +125 -20
  52. package/dist/visual/MatrixAdd.svelte +13 -6
  53. package/dist/visual/MatrixAdd.svelte.d.ts +3 -2
  54. package/dist/visual/MatrixField.svelte +36 -8
  55. package/dist/visual/NumberField.svelte +27 -6
  56. package/dist/visual/NumberField.svelte.d.ts +3 -0
  57. package/dist/visual/ObjectField.svelte +25 -1
  58. package/dist/visual/ObjectField.svelte.d.ts +6 -0
  59. package/dist/visual/ProseField.svelte +21 -0
  60. package/dist/visual/ProseField.svelte.d.ts +3 -0
  61. package/dist/visual/ProseValue.svelte +107 -17
  62. package/dist/visual/ProseValue.svelte.d.ts +18 -4
  63. package/dist/visual/ReviewProposal.svelte +149 -0
  64. package/dist/visual/ReviewProposal.svelte.d.ts +15 -0
  65. package/dist/visual/ReviewRows.svelte +43 -0
  66. package/dist/visual/ReviewRows.svelte.d.ts +11 -0
  67. package/dist/visual/SlashMenu.svelte +13 -1
  68. package/dist/visual/SlashMenu.svelte.d.ts +2 -0
  69. package/dist/visual/VisualEditor.svelte +22 -0
  70. package/dist/visual/VisualEditor.svelte.d.ts +7 -0
  71. package/dist/visual/VisualEditorInner.svelte +591 -27
  72. package/dist/visual/VisualEditorInner.svelte.d.ts +7 -0
  73. package/dist/visual/controls.css +17 -2
  74. package/dist/visual/guidance.d.ts +12 -0
  75. package/dist/visual/guidance.js +37 -2
  76. package/dist/visual/icons/nodes.d.ts +14 -2
  77. package/dist/visual/icons/nodes.js +12 -1
  78. package/dist/visual/index.d.ts +6 -0
  79. package/dist/visual/index.js +2 -0
  80. package/dist/visual/listhistory.d.ts +36 -0
  81. package/dist/visual/listhistory.js +53 -0
  82. package/dist/visual/proposals.d.ts +40 -0
  83. package/dist/visual/proposals.js +219 -0
  84. package/dist/visual/props.d.ts +36 -0
  85. package/dist/visual/removed.d.ts +20 -0
  86. package/dist/visual/removed.js +30 -0
  87. package/dist/visual/review.d.ts +135 -0
  88. package/dist/visual/review.js +227 -0
  89. package/dist/visual/review.svelte.d.ts +79 -0
  90. package/dist/visual/review.svelte.js +226 -0
  91. package/dist/visual/rowdrag.svelte.js +44 -55
  92. package/dist/visual/strings.d.ts +36 -7
  93. package/dist/visual/strings.js +26 -7
  94. package/dist/visual/structure.d.ts +5 -0
  95. package/dist/visual/structure.js +1 -1
  96. package/dist/visual/undo.svelte.d.ts +40 -7
  97. package/dist/visual/undo.svelte.js +98 -25
  98. package/package.json +1 -1
@@ -10,20 +10,28 @@
10
10
  threaded through a generation token.
11
11
 
12
12
  Reactivity across the WASM handle. The `Document` is opaque to Svelte, so a
13
- `revision` counter is bumped after every scalar/structure mutation and the card
13
+ `revision` counter is bumped after a scalar/structure mutation and the card
14
14
  tree is `$derived` by re-reading `doc.main`/`doc.cards`/`quill.schema`. Prose
15
15
  leaves are mounted once per stable leaf key (keyed `<Card>`/`<ProseField>`);
16
16
  they commit to the doc directly and do not bump `revision`, so a re-derive never
17
17
  remounts them or drops a caret. `doc.main`/`doc.cards` allocate per read: read
18
18
  once per derive.
19
+
20
+ A run of commits to one field is typing in a by-value cell, and a derive per
21
+ keystroke is a whole-document read, resolve and validate under each one. So the
22
+ run's commits past its first rebuild the one card from the one field's value
23
+ (`patched`), and the derive lands once the run rests.
19
24
  -->
20
25
  <script lang="ts">
21
26
  import { onDestroy, tick } from 'svelte';
22
27
  import { SvelteMap } from 'svelte/reactivity';
28
+ import { keydownHandler } from 'prosemirror-keymap';
23
29
  import { DropdownMenu } from 'bits-ui';
24
30
  import { isQuillmarkError, MAIN_CARD_ADDR } from '@quillmark/wasm';
25
31
  import {
26
32
  addrForFieldPath,
33
+ cardMoved,
34
+ nearestAddrForFieldPath,
27
35
  cardPath,
28
36
  nestedAddrForFieldPath,
29
37
  fieldPathForAddr,
@@ -47,9 +55,20 @@
47
55
  import type { VisualEditorProps } from './props.js';
48
56
  import type { Delta } from '../core/codec/positions.js';
49
57
  import { mergeStrings, setWording } from './strings.js';
50
- import { createStructuralUndo, setStructuralUndo } from './undo.svelte.js';
58
+ import { createStructuralUndo, setStructuralUndo, type UndoOffer } from './undo.svelte.js';
59
+ import { undoChord } from './listhistory.js';
60
+ import { removedCards, type RemovedCard } from './removed.js';
61
+ import { createReview, setReview } from './review.svelte.js';
62
+ import {
63
+ byBlocks,
64
+ onField,
65
+ valueIn,
66
+ valueWith,
67
+ type FieldProposal,
68
+ type ReviewDrawn
69
+ } from './review.js';
51
70
  import type { CardId, CardOp, ChangeSource } from './signals.js';
52
- import type { FieldController, LeafViews } from '../core/codec/index.js';
71
+ import { REVIEW_KEYS, type FieldController, type LeafViews } from '../core/codec/index.js';
53
72
  import {
54
73
  IdSeq,
55
74
  controlKind,
@@ -106,6 +125,11 @@
106
125
  fontLabels,
107
126
  strings,
108
127
  formatDiagnostic,
128
+ review,
129
+ onReview,
130
+ onReviewFocus,
131
+ onReviewDrawn,
132
+ reviewAdvance = true,
109
133
  class: className,
110
134
  style
111
135
  }: VisualEditorProps = $props();
@@ -140,6 +164,19 @@
140
164
  // Session ids, one per composable card, reordered in lockstep with structure ops.
141
165
  // svelte-ignore state_referenced_locally
142
166
  let cardIds = $state<string[]>(seq.take(doc.cardCount));
167
+ /** The card keys as they stood when the host set its review list: an item names its card by
168
+ * index into these, so it stays on that card through every card op since. */
169
+ let listed: { list: VisualEditorProps['review']; cards: readonly string[] } | undefined;
170
+ function cardsListed(): readonly string[] {
171
+ const held = listed;
172
+ if (held && held.list === review) return held.cards;
173
+ listed = { list: review, cards: cardIds };
174
+ return cardIds;
175
+ }
176
+ function setCards(next: string[]): void {
177
+ cardsListed();
178
+ cardIds = next;
179
+ }
143
180
 
144
181
  // Local commit-error diagnostics (INVARIANTS §Diagnostics, producer #2),
145
182
  // id-keyed rather than positional so an error stays pinned to its field across a
@@ -148,6 +185,11 @@
148
185
 
149
186
  const kinds = $derived(Object.keys(quill.schema.card_kinds ?? {}));
150
187
 
188
+ // The removal's step back (`undo.svelte.ts`), published so an array's row removal
189
+ // offers on the same toast a card's does.
190
+ const undo = createStructuralUndo();
191
+ setStructuralUndo(undo);
192
+
151
193
  /**
152
194
  * Re-derive the card tree and report the edit. Called for the two lanes that go
153
195
  * through this component; a prose leaf commits itself and reports through
@@ -160,14 +202,69 @@
160
202
  */
161
203
  function bump(source: ChangeSource, cardId?: CardId, at?: Addr | number, op?: CardOp): void {
162
204
  rederive();
205
+ report(source, cardId, at, op);
206
+ }
207
+ function report(source: ChangeSource, cardId?: CardId, at?: Addr | number, op?: CardOp): void {
163
208
  const path =
164
209
  at == null ? undefined : typeof at === 'number' ? cardPath(at, liveKinds()) : pathFor(at);
210
+ settled();
165
211
  onChange?.({ source, cardId, path, ...(op ? { op } : {}) });
166
212
  }
167
213
  function rederive(): void {
214
+ clearTimeout(rest);
215
+ rest = undefined;
216
+ patched = {};
168
217
  revision++;
169
218
  liveTitles = {};
170
219
  }
220
+
221
+ /** How long after a field's commit the next one to it still counts as the same run:
222
+ * the gap between two keys of slow typing. */
223
+ const RUN_MS = 2000;
224
+ /** How long after a run's last commit its derive lands: a pause in the typing. */
225
+ const REST_MS = 300;
226
+ let run: { key: string; at: number } | undefined;
227
+ let rest: ReturnType<typeof setTimeout> | undefined;
228
+ /** The cards a run rebuilt, by session key, over the derive they stand on. */
229
+ let patched = $state.raw<Record<CardId, CardModel>>({});
230
+ /**
231
+ * A field's commit, re-derived. A run's commits past its first rebuild the one card:
232
+ * the committed field's value re-read, every other value the object the last derive
233
+ * read, so no control beside the one typed in is handed anything new. Validation and
234
+ * the resolved rows hold as the last derive left them until the run rests, which is
235
+ * exact for the rows a control reads: a default's, which an authored field has none
236
+ * of before or after. A commit that sets or unsets the field moves a row, so it
237
+ * derives at once.
238
+ */
239
+ function fieldCommitted(id: CardId, isMain: boolean, name: string, value: unknown): void {
240
+ const key = fieldKeyToString({ card: isMain ? undefined : id, field: name });
241
+ const now = performance.now();
242
+ const running = run?.key === key && now - run.at < RUN_MS;
243
+ run = { key, at: now };
244
+ const at = cardIndexOf(id);
245
+ const shown = isMain ? model.main : model.cards[at];
246
+ if (!running || value === undefined || !shown || !Object.hasOwn(shown.values, name))
247
+ return rederive();
248
+ const fresh = fieldValues((isMain ? doc.main : doc.card(at)).payloadItems);
249
+ const cardSchema = isMain ? quill.schema.main : quill.schema.card_kinds?.[shown.kind];
250
+ patched = {
251
+ ...patched,
252
+ [id]: {
253
+ ...shown,
254
+ values: { ...shown.values, [name]: fresh[name] },
255
+ titlePlaceholder: cardTitle(cardSchema, shown.kind, fresh, undefined)
256
+ }
257
+ };
258
+ if (id in liveTitles) {
259
+ const titles = { ...liveTitles };
260
+ delete titles[id];
261
+ liveTitles = titles;
262
+ }
263
+ clearTimeout(rest);
264
+ rest = setTimeout(() => {
265
+ if (span.alive) rederive();
266
+ }, REST_MS);
267
+ }
171
268
  /** Read at the mutation boundary, never cached (INVARIANTS §"The address is the
172
269
  * spine"). */
173
270
  function cardIndexOf(id: string): number {
@@ -191,6 +288,8 @@
191
288
  // the span holds nothing to release.
192
289
  const span = createLifespan();
193
290
  onDestroy(() => span.end());
291
+ span.onEnd(() => clearTimeout(rest));
292
+ span.onEnd(undo.dispose);
194
293
 
195
294
  // ── Leaf registry (landing target lookup + the active-leaf seam) ────────────
196
295
  // Every mounted field is in it, prose leaf and form control alike (`leaves.ts`):
@@ -202,22 +301,322 @@
202
301
  // is Svelte's business and not something to depend on.
203
302
  span.onEnd(() => leaves.clear());
204
303
 
205
- // The removal's one step back (`undo.svelte.ts`), published so an array's row removal
206
- // offers on the same toast a card's does.
207
- const undo = createStructuralUndo();
208
- setStructuralUndo(undo);
209
- span.onEnd(undo.dispose);
210
- /** ⌘Z/Ctrl+Z takes the standing offer where the offer accepts it (`undo.accepts`).
304
+ /** ⌘Z/Ctrl+Z takes the step back where the undo accepts it (`undo.accepts`).
211
305
  * On the document, since a removal under the pointer leaves the focus on the body, and
212
306
  * captured, so a leaf the removal handed the focus to hears the key after the offer. */
213
307
  function onUndoKey(e: KeyboardEvent): void {
214
- if (e.defaultPrevented || e.isComposing || e.shiftKey || e.altKey) return;
215
- if (!(e.metaKey || e.ctrlKey) || e.key.toLowerCase() !== 'z') return;
216
- if (!undo.accepts(e.target, rootEl)) return;
308
+ if (undoChord(e) !== 'undo' || !undo.accepts(e.target, rootEl)) return;
217
309
  e.preventDefault();
218
310
  e.stopPropagation();
219
311
  undo.take();
220
312
  }
313
+ // ── Review (`review.svelte.ts`): the host's list, published to the tree ─────
314
+ // A field item's path resolves here, against the live card keys, as a diagnostic's does:
315
+ // the nearest field holding it.
316
+ const reviewed = (path: DocPath): FieldKey | undefined => {
317
+ const addr = nearestAddrForFieldPath(path);
318
+ return addr && declaredField(addr) ? resolveCardKey(addr, cardIds) : undefined;
319
+ };
320
+ /** Take a field's answer back: the value it replaced written back, if any, and the item
321
+ * reopened. */
322
+ const giveBack = (id: string, leaf: string, back?: () => void): void => {
323
+ back?.();
324
+ reviewing.heard(id, 'reopen', leaf);
325
+ };
326
+ /** The host's list with each card it names by index moved to where that card stands now. */
327
+ const reviewItems = $derived.by(() => {
328
+ const was = cardsListed();
329
+ if (!review?.length || was === cardIds) return review;
330
+ return review.map((item) => {
331
+ const field = cardMoved(item.field, was, cardIds);
332
+ return field === item.field ? item : { ...item, field };
333
+ });
334
+ });
335
+ const reviewing = createReview({
336
+ items: () => reviewItems,
337
+ keyFor: (path) => {
338
+ const key = reviewed(path);
339
+ return key && fieldKeyToString(key);
340
+ },
341
+ exact: (path) => addrForFieldPath(path) != null,
342
+ nested(path) {
343
+ const target = leafTargetFor(path);
344
+ const field = reviewed(path);
345
+ if (!target?.steps || !field?.field) return undefined;
346
+ const card =
347
+ field.card === undefined ? model.main : model.cards[cardIndexOf(field.card as CardId)];
348
+ return { key: target.key, steps: target.steps, value: card?.values[field.field] };
349
+ },
350
+ valueAt(path) {
351
+ const key = reviewed(path);
352
+ if (!key?.field) return undefined;
353
+ const card =
354
+ key.card === undefined ? model.main : model.cards[cardIndexOf(key.card as CardId)];
355
+ return card?.values[key.field];
356
+ },
357
+ leafFor(path) {
358
+ const addr = addrForFieldPath(path);
359
+ if (!addr) return undefined;
360
+ const key =
361
+ addr.field == null ? resolveCardKey({ card: addr.card }, cardIds) : reviewed(path);
362
+ return key && fieldKeyToString(key);
363
+ },
364
+ chorded(id) {
365
+ if (!reviewAdvance) return;
366
+ const index = drewOrder.indexOf(id);
367
+ void tick().then(() => {
368
+ if (span.alive) void step(1, true, index < 0 ? undefined : { id, index });
369
+ });
370
+ },
371
+ writing(on) {
372
+ writing += on ? 1 : -1;
373
+ },
374
+ answer(id, item, action, key) {
375
+ let back: (() => void) | undefined;
376
+ if (action === 'accept' && item && onField(item)) {
377
+ back = takeField(item);
378
+ if (!back) return false;
379
+ }
380
+ onReview?.({ id, action });
381
+ if (action !== 'accept' && action !== 'dismiss') return true;
382
+ const field = item && onField(item) ? reviewed(item.field) : undefined;
383
+ const leaf = key ?? (field && fieldKeyToString(field));
384
+ if (leaf === undefined) return true;
385
+ const prose = key !== undefined && !field;
386
+ record(
387
+ id,
388
+ prose
389
+ ? action === 'accept'
390
+ ? () => void leaves.prose(leaf)?.undoReview()
391
+ : () => void leaves.prose(leaf)?.reopenReview(id)
392
+ : () => giveBack(id, leaf, back),
393
+ back && merged.reviewAccepted
394
+ );
395
+ return true;
396
+ }
397
+ });
398
+
399
+ // ── The answer journal: the review answers since the reader's last edit, each undone by
400
+ // ⌘Z from anywhere in the editor, newest first, its item reopened with it. An edit that is
401
+ // not an answer empties it: an inverse is good against the document it was recorded over. An answer's own writes, and an inverse's, go down the
402
+ // lanes an edit does, so they are flagged while they are made.
403
+ interface Answered {
404
+ ids: string[];
405
+ inverses: (() => void)[];
406
+ /** The toast it stands on; none where the key alone takes it back. */
407
+ notice?: string;
408
+ }
409
+ let journal: Answered[] = [];
410
+ /** The entry a batch of answers records into. */
411
+ let batching: Answered | undefined;
412
+ let journalOffer: UndoOffer | undefined;
413
+ let writing = 0;
414
+ function settled(): void {
415
+ if (writing) return;
416
+ journal = [];
417
+ journalOffer = undefined;
418
+ undo.settle();
419
+ }
420
+ function offerJournal(): void {
421
+ const top = journal.at(-1);
422
+ journalOffer =
423
+ top &&
424
+ undo.offer(top.notice ?? '', unanswer, {
425
+ standing: true,
426
+ quiet: top.notice === undefined,
427
+ answer: true
428
+ });
429
+ }
430
+ function unanswer(): void {
431
+ const top = journal.pop();
432
+ if (!top) return;
433
+ writing++;
434
+ try {
435
+ for (const inverse of [...top.inverses].reverse()) inverse();
436
+ } finally {
437
+ writing--;
438
+ }
439
+ offerJournal();
440
+ }
441
+ function record(id: string, inverse: () => void, notice?: string): void {
442
+ if (batching) {
443
+ batching.ids.push(id);
444
+ batching.inverses.push(inverse);
445
+ return;
446
+ }
447
+ // Another step took the key since: the answers before it are no longer the last thing
448
+ // that happened.
449
+ if (!journalOffer || !undo.holds(journalOffer)) journal = [];
450
+ journal.push({ ids: [id], inverses: [inverse], notice });
451
+ offerJournal();
452
+ }
453
+
454
+ /**
455
+ * Take a field's proposal: its value down the lane the field's own control commits by, so
456
+ * the writer checks it and `onChange` reports it. A text leaf re-reads what was written. A
457
+ * place inside the field is written as the whole value with that place alone changed, down
458
+ * the lane an edit of the place takes. Returns the write back to the value it replaced,
459
+ * which the journal runs before any older answer's, or `undefined` where the writer refused
460
+ * the value, which the field then says as it says any refused commit.
461
+ */
462
+ function takeField(item: FieldProposal): (() => void) | undefined {
463
+ const key = reviewed(item.field);
464
+ if (!key?.field || typeof key.card === 'number') return undefined;
465
+ const isMain = key.card === undefined;
466
+ const id = key.card ?? model.main.id;
467
+ const name = key.field;
468
+ const leaf = fieldKeyToString(key);
469
+ const addr = makeAddr(id, isMain, name);
470
+ const write = (value: unknown): boolean => {
471
+ commitScalar(id, isMain, name, value);
472
+ if (commitErrors.has(leaf)) return false;
473
+ leaves.prose(leaf)?.applyExternal();
474
+ return true;
475
+ };
476
+ writing++;
477
+ try {
478
+ const before = doc.getStored(addr);
479
+ let after = item.after;
480
+ if (!addrForFieldPath(item.field)) {
481
+ const steps = reviewing.at(leaf).nested?.find((e) => e.item.id === item.id)?.steps;
482
+ if (!steps) return undefined;
483
+ after = valueWith(current(), steps, item.after);
484
+ }
485
+ if (!write(after)) return undefined;
486
+ return () => void write(before);
487
+ } finally {
488
+ writing--;
489
+ }
490
+
491
+ /** The field's value as its control is handed it, read anew. */
492
+ function current(): unknown {
493
+ const at = isMain ? 0 : cardIndexOf(id);
494
+ if (at < 0) return undefined;
495
+ return fieldValues((isMain ? doc.main : doc.card(at)).payloadItems)[name];
496
+ }
497
+ }
498
+ setReview(reviewing);
499
+ span.onEnd(reviewing.dispose);
500
+ // The lit item, to a host lighting its own list: each change, and not the nothing a mount
501
+ // starts from.
502
+ let reported: string | undefined;
503
+ $effect(() => {
504
+ const id = reviewing.lit;
505
+ if (id === reported) return;
506
+ reported = id;
507
+ onReviewFocus?.(id);
508
+ });
509
+ /** The open items drawn, in document order: each id's first element under the root, then
510
+ * any drawn one not yet in the DOM, in list order. */
511
+ function reviewOrder(): string[] {
512
+ const fieldUndrawn = new Set(reviewing.fieldUndrawn.map((u) => u.id));
513
+ const drawn = new Set<string>();
514
+ for (const report of reviewing.reports.values()) for (const id of report.ids) drawn.add(id);
515
+ for (const item of reviewing.items)
516
+ if (onField(item) && !fieldUndrawn.has(item.id)) drawn.add(item.id);
517
+ const order: string[] = [];
518
+ const seen = new Set<string>();
519
+ const take = (id: string | null): void => {
520
+ if (id === null || !drawn.has(id) || seen.has(id)) return;
521
+ seen.add(id);
522
+ order.push(id);
523
+ };
524
+ for (const el of rootEl?.querySelectorAll('[data-qm-review]') ?? [])
525
+ take(el.getAttribute('data-qm-review'));
526
+ for (const item of reviewing.items) take(item.id);
527
+ return order;
528
+ }
529
+ /** What the editor draws of the host's list, and why it draws what it does not. */
530
+ function reviewReport(): ReviewDrawn {
531
+ const reported = new Set<string>();
532
+ const outdated = new Set(reviewing.fieldOutdated);
533
+ const why = new Map<string, ReviewDrawn['undrawn'][number]['reason']>();
534
+ for (const report of reviewing.reports.values()) {
535
+ for (const id of report.ids) reported.add(id);
536
+ for (const id of report.outdated) outdated.add(id);
537
+ for (const { id, reason } of report.undrawn) {
538
+ reported.add(id);
539
+ why.set(id, reason);
540
+ }
541
+ }
542
+ for (const { id, reason } of reviewing.fieldUndrawn) why.set(id, reason);
543
+ for (const item of reviewing.items)
544
+ if (!reported.has(item.id) && !why.has(item.id)) {
545
+ if (byBlocks(item)) why.set(item.id, 'block');
546
+ }
547
+ const open = reviewOrder();
548
+ return {
549
+ open,
550
+ outdated: open.filter((id) => outdated.has(id)),
551
+ undrawn: reviewing.items.flatMap((item) => {
552
+ const reason = why.get(item.id);
553
+ return reason ? [{ id: item.id, reason }] : [];
554
+ })
555
+ };
556
+ }
557
+ // The report, to a host counting its own list: each change, read once the leaves the change
558
+ // mounted have drawn, so a list just handed over is not reported as anchored nowhere.
559
+ const NO_REPORT = JSON.stringify({ open: [], outdated: [], undrawn: [] } satisfies ReviewDrawn);
560
+ let drewReport = NO_REPORT;
561
+ let drewOrder: readonly string[] = [];
562
+ $effect(() => {
563
+ void reviewing.items;
564
+ void reviewing.fieldUndrawn;
565
+ for (const id of reviewing.fieldOutdated) void id;
566
+ for (const report of reviewing.reports.values()) void report;
567
+ let live = true;
568
+ void tick().then(() => {
569
+ if (!live || !span.alive) return;
570
+ const report = reviewReport();
571
+ drewOrder = report.open;
572
+ const joined = JSON.stringify(report);
573
+ if (joined === drewReport) return;
574
+ drewReport = joined;
575
+ onReviewDrawn?.(report);
576
+ });
577
+ return () => {
578
+ live = false;
579
+ };
580
+ });
581
+ /** The item a step last went to, and where it stood in the order then, so a step from an
582
+ * item since answered goes on from its place. */
583
+ let stepped: { id: string; index: number } | undefined;
584
+ async function step(
585
+ dir: 1 | -1,
586
+ focus: boolean,
587
+ from?: { id: string; index: number }
588
+ ): Promise<string | undefined> {
589
+ if (!span.alive) return undefined;
590
+ const order = reviewOrder();
591
+ if (!order.length) return undefined;
592
+ const at = from ? -1 : order.indexOf(reviewing.lit ?? stepped?.id ?? '');
593
+ const past = from ?? stepped;
594
+ const next =
595
+ at >= 0 ? at + dir : past ? (dir > 0 ? past.index : past.index - 1) : dir > 0 ? 0 : -1;
596
+ const index = ((next % order.length) + order.length) % order.length;
597
+ const id = order[index];
598
+ stepped = { id, index };
599
+ await reveal(id, focus, true);
600
+ return id;
601
+ }
602
+ const stepKeys = keydownHandler({
603
+ [REVIEW_KEYS.next]: () => {
604
+ void step(1, true);
605
+ return true;
606
+ },
607
+ [REVIEW_KEYS.previous]: () => {
608
+ void step(-1, true);
609
+ return true;
610
+ }
611
+ });
612
+ /** The step chords, from anywhere under the root, ahead of a leaf's own arrows. */
613
+ function onStepKey(e: KeyboardEvent): void {
614
+ if (e.isComposing || !reviewing.items.length) return;
615
+ // The bindings read no view: this is `prosemirror-keymap`'s chord matcher alone.
616
+ if (!stepKeys({} as never, e)) return;
617
+ e.preventDefault();
618
+ e.stopPropagation();
619
+ }
221
620
  // Card handles, for `setCaret`'s reveal hop: the one thing a leaf's own controller
222
621
  // cannot do, since which group is open is the card's state (Card §revealLeaf).
223
622
  type CardHandle = {
@@ -308,6 +707,7 @@
308
707
  const cardId = cardIdOf(plain);
309
708
  if (cardId == null) return;
310
709
  refreshTitle(plain, cardId);
710
+ settled();
311
711
  onChange?.({ source: 'prose', cardId, path: pathFor(plain) });
312
712
  }
313
713
 
@@ -375,7 +775,8 @@
375
775
  }
376
776
  }
377
777
  commitErrors.delete(keyStr);
378
- bump('field', id, makeAddr(id, isMain, name));
778
+ fieldCommitted(id, isMain, name, value);
779
+ report('field', id, makeAddr(id, isMain, name));
379
780
  } catch (e) {
380
781
  const diagnostic: Diagnostic = (isQuillmarkError(e) ? e.diagnostics[0] : undefined) ?? {
381
782
  severity: 'error',
@@ -442,7 +843,7 @@
442
843
  undo.withdraw();
443
844
  const id = seq.next();
444
845
  arm.arm();
445
- cardIds = [...cardIds.slice(0, atIndex), id, ...cardIds.slice(atIndex)];
846
+ setCards([...cardIds.slice(0, atIndex), id, ...cardIds.slice(atIndex)]);
446
847
  bump('structure', id, atIndex, { op: 'insert', at: atIndex });
447
848
  // Centred: the new card is the subject, and the neighbours it landed between
448
849
  // are what say where it went.
@@ -500,18 +901,28 @@
500
901
  if (from < 0) return;
501
902
  const to = from + dir;
502
903
  if (to < 0 || to >= doc.cardCount) return;
904
+ const focused = document.activeElement;
905
+ const held = focused instanceof HTMLElement && slotEls[from]?.contains(focused);
503
906
  arm.arm();
504
907
  doc.moveCard(from, to);
505
908
  undo.withdraw();
506
909
  const w = cardIds.slice();
507
910
  const [x] = w.splice(from, 1);
508
911
  w.splice(to, 0, x);
509
- cardIds = w;
912
+ setCards(w);
510
913
  bump('structure', id, to, { op: 'move', from, to });
914
+ if (held) void keepFocus(focused);
511
915
  // `nearest`: the card was already in view and only needs to stay there, so one
512
916
  // that never left the viewport moves it not at all.
513
917
  void scrollCardIntoView(id, 'nearest');
514
918
  }
919
+ /** Give the focus back to the control a move was made from. The reconcile reorders by
920
+ * re-inserting slots, and a re-inserted node loses the focus to the page's body with no
921
+ * blur to say so; which of two swapped slots it re-inserts is its own choice. */
922
+ async function keepFocus(el: HTMLElement): Promise<void> {
923
+ if (!(await span.resumes(tick()))) return;
924
+ if (el.isConnected && document.activeElement !== el) el.focus({ preventScroll: true });
925
+ }
515
926
  function removeCardById(id: string): void {
516
927
  const i = cardIndexOf(id);
517
928
  if (i < 0) return;
@@ -525,24 +936,35 @@
525
936
  shown?.titleOverride ||
526
937
  shown?.titlePlaceholder ||
527
938
  kindTitle(quill.schema.card_kinds?.[card.kind], card.kind);
939
+ const gone = removed.remove(id, card, cardIds, i);
528
940
  doc.removeCard(i);
529
941
  arm.arm();
530
- cardIds = cardIds.filter((_, k) => k !== i);
942
+ setCards(cardIds.filter((_, k) => k !== i));
531
943
  forget(id);
532
944
  // No addr: the removed card has none left and every survivor's shifted. The
533
945
  // stack changed, not a leaf, and the id is the only handle the removal leaves.
534
946
  bump('structure', id, undefined, { op: 'remove', at: i });
535
- undo.offer(merged.undoRemoved(name), () => restoreCard(card, i));
947
+ undo.offer(merged.undoRemoved(name), () => restoreCard(gone), {
948
+ keptAs: merged.undoRestore(name)
949
+ });
536
950
  if (held) void focusAfterRemove(i);
537
951
  }
538
- /** The removal's undo: the card back at the index it left, under a fresh session key
539
- * (ids are never reused), with the focus on its title. The document holds what it held
540
- * before the removal, so the insert is the removal's exact inverse. */
541
- function restoreCard(card: ReturnType<typeof doc.card>, at: number): void {
952
+ /** The removals not yet restored, each the step `undo` keeps for it (`removed.ts`). */
953
+ const removed = removedCards<ReturnType<typeof doc.card>>();
954
+ /** The removal's undo: the card back beside the neighbours it left, under a fresh session
955
+ * key (ids are never reused), with the focus on its title. A removal that named the
956
+ * gone card as its neighbour names the restored one. The document mints a card's `$id`
957
+ * from the ids it holds, so a card added since may hold the one this card left with,
958
+ * and the card then goes back without it and is minted another. */
959
+ function restoreCard(gone: RemovedCard<ReturnType<typeof doc.card>>): void {
542
960
  if (!span.alive) return;
543
- const i = Math.min(at, cardIds.length);
961
+ const { card } = gone;
962
+ const i = removed.place(gone, cardIds);
544
963
  try {
545
- doc.unchecked.insertCard(card, i);
964
+ const taken = card.id !== undefined && cardIds.some((_, k) => doc.card(k).id === card.id);
965
+ const back = { ...card };
966
+ if (taken) delete back.id;
967
+ doc.unchecked.insertCard(back, i);
546
968
  } catch (e) {
547
969
  reportError(onError, {
548
970
  code: 'card-op-failed',
@@ -553,8 +975,9 @@
553
975
  return;
554
976
  }
555
977
  const id = seq.next();
978
+ removed.restored(gone, id);
556
979
  arm.arm();
557
- cardIds = [...cardIds.slice(0, i), id, ...cardIds.slice(i)];
980
+ setCards([...cardIds.slice(0, i), id, ...cardIds.slice(i)]);
558
981
  bump('structure', id, i, { op: 'insert', at: i });
559
982
  void (async () => {
560
983
  if (!(await scrollCardIntoView(id, 'nearest'))) return;
@@ -738,7 +1161,7 @@
738
1161
  };
739
1162
  }
740
1163
 
741
- const model = $derived.by(() => {
1164
+ const tree = $derived.by(() => {
742
1165
  revision; // re-derive on every mutation
743
1166
  const schema = quill.schema;
744
1167
  const main = doc.main;
@@ -781,6 +1204,12 @@
781
1204
  };
782
1205
  });
783
1206
 
1207
+ const model = $derived({
1208
+ tips: tree.tips,
1209
+ main: patched.main ?? tree.main,
1210
+ cards: tree.cards.map((c) => patched[c.id] ?? c)
1211
+ });
1212
+
784
1213
  // ── Public entry points ─────────────────────────────────────────────────────
785
1214
  /**
786
1215
  * Resolve a preview {@link Landing} to a mounted leaf and land in it.
@@ -957,10 +1386,101 @@
957
1386
  else if (op.op === 'remove') forget(ids.splice(op.at, 1)[0]);
958
1387
  else ids.splice(op.to, 0, ...ids.splice(op.from, 1));
959
1388
  }
960
- cardIds = ids;
1389
+ setCards(ids);
961
1390
  rederive();
962
1391
  }
963
1392
 
1393
+ // ── Review ──────────────────────────────────────────────────────────────────
1394
+
1395
+ /**
1396
+ * Bring the review item `id` to the reader: open the panel holding it, scroll it to the
1397
+ * middle of the view, and light it. The focus stays where it is, the reader having asked
1398
+ * to look, unless `focus` asks for it: the caret then goes into the item, or the focus to
1399
+ * its field, so the chords answer it. False for an item the editor does not draw.
1400
+ */
1401
+ export function revealReview(id: string, opts: { focus?: boolean } = {}): Promise<boolean> {
1402
+ return reveal(id, opts.focus ?? false, false);
1403
+ }
1404
+ /** {@link revealReview}; a step scrolls an item only as far as its scroller must to show it,
1405
+ * so a walk down neighbouring items does not jump the page under each, and an item in a
1406
+ * pane that scrolls on its own is shown by that pane. */
1407
+ async function reveal(id: string, focus: boolean, stepping: boolean): Promise<boolean> {
1408
+ if (!span.alive) return false;
1409
+ const key = reviewing.keyOf(id);
1410
+ if (key === undefined) return false;
1411
+ mainCard?.revealLeaf(key);
1412
+ for (const card of cardRefs) card?.revealLeaf(key);
1413
+ if (!(await span.resumes(tick()))) return false;
1414
+ reviewing.reveal(id);
1415
+ if (focus && !leaves.prose(key)?.enterReview(id)) leaves.control(key)?.focus();
1416
+ // The lit item is drawn again, so its element is read once it has been.
1417
+ if (!(await span.resumes(tick()))) return false;
1418
+ const at =
1419
+ leaves.prose(key)?.reviewElements(id)[0] ??
1420
+ [...(rootEl?.querySelectorAll<HTMLElement>('[data-qm-review]') ?? [])].find(
1421
+ (el) => el.getAttribute('data-qm-review') === id
1422
+ ) ??
1423
+ leaves.control(key)?.el;
1424
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
1425
+ at?.scrollIntoView({
1426
+ behavior: reduce ? 'auto' : 'smooth',
1427
+ block: stepping ? 'nearest' : 'center'
1428
+ });
1429
+ return true;
1430
+ }
1431
+
1432
+ /**
1433
+ * Answer items as their buttons would, in document order: `'all'` is every item drawn. An
1434
+ * item that cannot be answered (a proposal that no longer writes, a value the field's writer
1435
+ * refuses) stands. `onReview` hears each answer, and neither the focus nor the caret moves.
1436
+ * The batch raises no toast, the host's to word if it wants one, and ⌘Z takes it back whole.
1437
+ * Returns the ids answered.
1438
+ */
1439
+ export function answerReview(
1440
+ ids: readonly string[] | 'all',
1441
+ action: 'accept' | 'dismiss'
1442
+ ): string[] {
1443
+ if (!span.alive) return [];
1444
+ const order = reviewOrder();
1445
+ const asked = ids === 'all' ? order : order.filter((id) => ids.includes(id));
1446
+ const out: string[] = [];
1447
+ const entry: Answered = { ids: [], inverses: [] };
1448
+ batching = entry;
1449
+ writing++;
1450
+ try {
1451
+ for (const id of asked) {
1452
+ const item = reviewing.items.find((it) => it.id === id);
1453
+ if (!item) continue;
1454
+ const key = reviewing.keyOf(id);
1455
+ // Each one is planned against the document the one before it left.
1456
+ const answered = !onField(item)
1457
+ ? key !== undefined && !!leaves.prose(key)?.answerReview(id, action)
1458
+ : reviewing.act(id, action);
1459
+ if (answered) out.push(id);
1460
+ }
1461
+ } finally {
1462
+ writing--;
1463
+ batching = undefined;
1464
+ }
1465
+ if (entry.ids.length) {
1466
+ if (!journalOffer || !undo.holds(journalOffer)) journal = [];
1467
+ journal.push(entry);
1468
+ offerJournal();
1469
+ }
1470
+ return out;
1471
+ }
1472
+
1473
+ /** Bring the next or previous open item to the reader, in document order and round from
1474
+ * either end, from the lit item or the one last stepped to: the caret in it, or the
1475
+ * focus in its field, unless `focus` is false. Resolves its id, `undefined` when none is
1476
+ * drawn. */
1477
+ export function stepReview(
1478
+ dir: 1 | -1,
1479
+ opts: { focus?: boolean } = {}
1480
+ ): Promise<string | undefined> {
1481
+ return step(dir, opts.focus ?? true);
1482
+ }
1483
+
964
1484
  function holds(cardId: CardId): boolean {
965
1485
  if (cardIndexOf(cardId) >= 0) return true;
966
1486
  missed(`no card ${cardId} in this session`);
@@ -1018,18 +1538,30 @@
1018
1538
  const card = addr.card == null ? schema.main : kind ? schema.card_kinds?.[kind] : undefined;
1019
1539
  return card?.fields?.[addr.field];
1020
1540
  }
1541
+
1542
+ /** A file dropped anywhere in the editor is refused, or the browser opens it in place
1543
+ * of the page. Text drops carry no `Files` and pass. */
1544
+ function refuseFiles(e: DragEvent): void {
1545
+ if (!e.dataTransfer?.types.includes('Files')) return;
1546
+ e.preventDefault();
1547
+ e.dataTransfer.dropEffect = 'none';
1548
+ }
1021
1549
  </script>
1022
1550
 
1023
1551
  <svelte:document onkeydowncapture={onUndoKey} />
1024
1552
 
1025
- <!-- The keydown is a control's, bubbled: the root resolves which description it raises. -->
1553
+ <!-- The keydown is a control's, bubbled: the root resolves which description it raises.
1554
+ A file dragged over or dropped is refused here, after any control has seen it. -->
1026
1555
  <!-- svelte-ignore a11y_no_static_element_interactions -->
1027
1556
  <div
1028
1557
  class="qm-editor {className ?? ''}"
1029
1558
  {style}
1030
1559
  data-qm-root
1031
1560
  bind:this={rootEl}
1561
+ onkeydowncapture={onStepKey}
1032
1562
  onkeydown={raiseGuidance}
1563
+ ondragover={refuseFiles}
1564
+ ondrop={refuseFiles}
1033
1565
  >
1034
1566
  <!-- `main` and the tips card are one block in the stack: the tips card tucks under
1035
1567
  `main`'s bottom corners, so the two share a seam rather than a gutter and the
@@ -1086,6 +1618,17 @@
1086
1618
  {@render addAffordance(i + 1)}
1087
1619
  </div>
1088
1620
  {/each}
1621
+ <!-- The way back to a removed card once its toast has gone: the newest kept step, by
1622
+ name, at the stack's foot, where the control that adds a card is looked for. -->
1623
+ {#if undo.kept}
1624
+ <div class="qm-restore">
1625
+ <button
1626
+ type="button"
1627
+ class="qm-restore-btn qm-tap-floor qm-focus-ring"
1628
+ onclick={() => undo.takeKept()}>{undo.kept.label}</button
1629
+ >
1630
+ </div>
1631
+ {/if}
1089
1632
  <!-- The removal's undo. The region stands empty between offers so the notice it takes is
1090
1633
  announced: a live region inserted along with its text is one a reader may not hear. -->
1091
1634
  <div class="qm-toast-slot" role="status">
@@ -1221,6 +1764,27 @@
1221
1764
  .qm-toast-action:hover {
1222
1765
  background: var(--_qm-accent-tint);
1223
1766
  }
1767
+ /* Words at the label ink, unboxed: the stack's foot already holds one outlined pill, and
1768
+ a second would stand as its equal. */
1769
+ .qm-restore {
1770
+ display: flex;
1771
+ justify-content: center;
1772
+ }
1773
+ .qm-restore-btn {
1774
+ min-height: var(--_qm-tap-min);
1775
+ padding-inline: var(--_qm-space-2);
1776
+ border: 0;
1777
+ border-radius: var(--_qm-radius-pill);
1778
+ background: transparent;
1779
+ font: inherit;
1780
+ font-size: var(--_qm-text-label);
1781
+ color: var(--_qm-ink-label);
1782
+ cursor: pointer;
1783
+ }
1784
+ .qm-restore-btn:hover {
1785
+ background: var(--_qm-add-fill);
1786
+ color: var(--_qm-ink);
1787
+ }
1224
1788
  /* A detached root, carrying `data-qm-root` for the derivation core/theme.css applies
1225
1789
  to one — the baseline font and colour included, so nothing here restates them.
1226
1790