@quillmark/svelte 0.33.0 → 0.34.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/codec/anchor.d.ts +12 -0
  4. package/dist/core/codec/anchor.js +39 -0
  5. package/dist/core/codec/drag-move.d.ts +11 -0
  6. package/dist/core/codec/drag-move.js +143 -0
  7. package/dist/core/codec/encode.js +14 -5
  8. package/dist/core/codec/field.d.ts +47 -1
  9. package/dist/core/codec/field.js +147 -38
  10. package/dist/core/codec/index.d.ts +8 -2
  11. package/dist/core/codec/index.js +9 -2
  12. package/dist/core/codec/islands.d.ts +4 -1
  13. package/dist/core/codec/islands.js +6 -0
  14. package/dist/core/codec/keymap.d.ts +3 -0
  15. package/dist/core/codec/keymap.js +13 -12
  16. package/dist/core/codec/leave.d.ts +17 -0
  17. package/dist/core/codec/leave.js +78 -0
  18. package/dist/core/codec/prose.css +217 -0
  19. package/dist/core/codec/review-diff.d.ts +12 -0
  20. package/dist/core/codec/review-diff.js +131 -0
  21. package/dist/core/codec/review.d.ts +131 -0
  22. package/dist/core/codec/review.js +1077 -0
  23. package/dist/core/codec/shortcuts.d.ts +20 -4
  24. package/dist/core/codec/shortcuts.js +27 -7
  25. package/dist/core/codec/slash.d.ts +3 -0
  26. package/dist/core/codec/slash.js +2 -1
  27. package/dist/core/codec/table-view.js +163 -25
  28. package/dist/core/codec/undo.d.ts +6 -0
  29. package/dist/core/codec/undo.js +25 -2
  30. package/dist/core/dragfollow.d.ts +18 -0
  31. package/dist/core/dragfollow.js +63 -0
  32. package/dist/core/theme.css +36 -7
  33. package/dist/preview/controller.js +16 -0
  34. package/dist/preview/strings.d.ts +4 -0
  35. package/dist/preview/strings.js +3 -1
  36. package/dist/visual/ArrayField.svelte +363 -57
  37. package/dist/visual/ArrayField.svelte.d.ts +5 -0
  38. package/dist/visual/BooleanField.svelte +60 -5
  39. package/dist/visual/BooleanField.svelte.d.ts +2 -1
  40. package/dist/visual/Card.svelte +27 -17
  41. package/dist/visual/CardControls.svelte +17 -7
  42. package/dist/visual/CardControls.svelte.d.ts +2 -0
  43. package/dist/visual/DateField.svelte +90 -39
  44. package/dist/visual/DateField.svelte.d.ts +2 -2
  45. package/dist/visual/Field.svelte +126 -6
  46. package/dist/visual/FieldHint.svelte +24 -9
  47. package/dist/visual/FieldLabel.svelte +128 -22
  48. package/dist/visual/FieldLabel.svelte.d.ts +9 -0
  49. package/dist/visual/FormatPopover.svelte +125 -20
  50. package/dist/visual/MatrixAdd.svelte +13 -6
  51. package/dist/visual/MatrixAdd.svelte.d.ts +3 -2
  52. package/dist/visual/MatrixField.svelte +36 -8
  53. package/dist/visual/NumberField.svelte +27 -6
  54. package/dist/visual/NumberField.svelte.d.ts +3 -0
  55. package/dist/visual/ObjectField.svelte +25 -1
  56. package/dist/visual/ObjectField.svelte.d.ts +6 -0
  57. package/dist/visual/ProseField.svelte +23 -0
  58. package/dist/visual/ProseField.svelte.d.ts +3 -0
  59. package/dist/visual/ProseValue.svelte +107 -17
  60. package/dist/visual/ProseValue.svelte.d.ts +18 -4
  61. package/dist/visual/ReviewPopover.svelte +179 -0
  62. package/dist/visual/ReviewPopover.svelte.d.ts +16 -0
  63. package/dist/visual/ReviewProposal.svelte +149 -0
  64. package/dist/visual/ReviewProposal.svelte.d.ts +15 -0
  65. package/dist/visual/ReviewRows.svelte +68 -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 +23 -0
  70. package/dist/visual/VisualEditor.svelte.d.ts +7 -0
  71. package/dist/visual/VisualEditorInner.svelte +671 -22
  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 +35 -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 +170 -0
  88. package/dist/visual/review.js +269 -0
  89. package/dist/visual/review.svelte.d.ts +106 -0
  90. package/dist/visual/review.svelte.js +356 -0
  91. package/dist/visual/rowdrag.svelte.js +44 -55
  92. package/dist/visual/strings.d.ts +48 -7
  93. package/dist/visual/strings.js +32 -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,27 @@
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
+ nearestAddrForFieldPath,
27
34
  cardPath,
28
35
  nestedAddrForFieldPath,
29
36
  fieldPathForAddr,
@@ -47,9 +54,30 @@
47
54
  import type { VisualEditorProps } from './props.js';
48
55
  import type { Delta } from '../core/codec/positions.js';
49
56
  import { mergeStrings, setWording } from './strings.js';
50
- import { createStructuralUndo, setStructuralUndo } from './undo.svelte.js';
57
+ import { createStructuralUndo, setStructuralUndo, type UndoOffer } from './undo.svelte.js';
58
+ import { undoChord } from './listhistory.js';
59
+ import { removedCards, type RemovedCard } from './removed.js';
60
+ import { createReview, setReview } from './review.svelte.js';
61
+ import {
62
+ byBlocks,
63
+ isChange,
64
+ onField,
65
+ sameValue,
66
+ valueIn,
67
+ valueWith,
68
+ valueWithInserted,
69
+ besideOf,
70
+ type FieldChange,
71
+ type FieldProposal,
72
+ type ReviewDrawn
73
+ } from './review.js';
51
74
  import type { CardId, CardOp, ChangeSource } from './signals.js';
52
- import type { FieldController, LeafViews } from '../core/codec/index.js';
75
+ import {
76
+ markAnchor,
77
+ REVIEW_KEYS,
78
+ type FieldController,
79
+ type LeafViews
80
+ } from '../core/codec/index.js';
53
81
  import {
54
82
  IdSeq,
55
83
  controlKind,
@@ -88,6 +116,7 @@
88
116
  import Card from './Card.svelte';
89
117
  import TipsCard from './TipsCard.svelte';
90
118
  import FormatPopover from './FormatPopover.svelte';
119
+ import ReviewPopover, { type ReviewTarget } from './ReviewPopover.svelte';
91
120
  // The add trigger and the kind menu draw shared recipes; a component carrying a
92
121
  // shared class without also pulling its rule ships unstyled (controls.css).
93
122
  import './controls.css';
@@ -106,6 +135,11 @@
106
135
  fontLabels,
107
136
  strings,
108
137
  formatDiagnostic,
138
+ review,
139
+ onReview,
140
+ onReviewFocus,
141
+ onReviewDrawn,
142
+ reviewAdvance = true,
109
143
  class: className,
110
144
  style
111
145
  }: VisualEditorProps = $props();
@@ -148,6 +182,11 @@
148
182
 
149
183
  const kinds = $derived(Object.keys(quill.schema.card_kinds ?? {}));
150
184
 
185
+ // The removal's step back (`undo.svelte.ts`), published so an array's row removal
186
+ // offers on the same toast a card's does.
187
+ const undo = createStructuralUndo();
188
+ setStructuralUndo(undo);
189
+
151
190
  /**
152
191
  * Re-derive the card tree and report the edit. Called for the two lanes that go
153
192
  * through this component; a prose leaf commits itself and reports through
@@ -160,14 +199,69 @@
160
199
  */
161
200
  function bump(source: ChangeSource, cardId?: CardId, at?: Addr | number, op?: CardOp): void {
162
201
  rederive();
202
+ report(source, cardId, at, op);
203
+ }
204
+ function report(source: ChangeSource, cardId?: CardId, at?: Addr | number, op?: CardOp): void {
163
205
  const path =
164
206
  at == null ? undefined : typeof at === 'number' ? cardPath(at, liveKinds()) : pathFor(at);
207
+ settled();
165
208
  onChange?.({ source, cardId, path, ...(op ? { op } : {}) });
166
209
  }
167
210
  function rederive(): void {
211
+ clearTimeout(rest);
212
+ rest = undefined;
213
+ patched = {};
168
214
  revision++;
169
215
  liveTitles = {};
170
216
  }
217
+
218
+ /** How long after a field's commit the next one to it still counts as the same run:
219
+ * the gap between two keys of slow typing. */
220
+ const RUN_MS = 2000;
221
+ /** How long after a run's last commit its derive lands: a pause in the typing. */
222
+ const REST_MS = 300;
223
+ let run: { key: string; at: number } | undefined;
224
+ let rest: ReturnType<typeof setTimeout> | undefined;
225
+ /** The cards a run rebuilt, by session key, over the derive they stand on. */
226
+ let patched = $state.raw<Record<CardId, CardModel>>({});
227
+ /**
228
+ * A field's commit, re-derived. A run's commits past its first rebuild the one card:
229
+ * the committed field's value re-read, every other value the object the last derive
230
+ * read, so no control beside the one typed in is handed anything new. Validation and
231
+ * the resolved rows hold as the last derive left them until the run rests, which is
232
+ * exact for the rows a control reads: a default's, which an authored field has none
233
+ * of before or after. A commit that sets or unsets the field moves a row, so it
234
+ * derives at once.
235
+ */
236
+ function fieldCommitted(id: CardId, isMain: boolean, name: string, value: unknown): void {
237
+ const key = fieldKeyToString({ card: isMain ? undefined : id, field: name });
238
+ const now = performance.now();
239
+ const running = run?.key === key && now - run.at < RUN_MS;
240
+ run = { key, at: now };
241
+ const at = cardIndexOf(id);
242
+ const shown = isMain ? model.main : model.cards[at];
243
+ if (!running || value === undefined || !shown || !Object.hasOwn(shown.values, name))
244
+ return rederive();
245
+ const fresh = fieldValues((isMain ? doc.main : doc.card(at)).payloadItems);
246
+ const cardSchema = isMain ? quill.schema.main : quill.schema.card_kinds?.[shown.kind];
247
+ patched = {
248
+ ...patched,
249
+ [id]: {
250
+ ...shown,
251
+ values: { ...shown.values, [name]: fresh[name] },
252
+ titlePlaceholder: cardTitle(cardSchema, shown.kind, fresh, undefined)
253
+ }
254
+ };
255
+ if (id in liveTitles) {
256
+ const titles = { ...liveTitles };
257
+ delete titles[id];
258
+ liveTitles = titles;
259
+ }
260
+ clearTimeout(rest);
261
+ rest = setTimeout(() => {
262
+ if (span.alive) rederive();
263
+ }, REST_MS);
264
+ }
171
265
  /** Read at the mutation boundary, never cached (INVARIANTS §"The address is the
172
266
  * spine"). */
173
267
  function cardIndexOf(id: string): number {
@@ -191,6 +285,8 @@
191
285
  // the span holds nothing to release.
192
286
  const span = createLifespan();
193
287
  onDestroy(() => span.end());
288
+ span.onEnd(() => clearTimeout(rest));
289
+ span.onEnd(undo.dispose);
194
290
 
195
291
  // ── Leaf registry (landing target lookup + the active-leaf seam) ────────────
196
292
  // Every mounted field is in it, prose leaf and form control alike (`leaves.ts`):
@@ -202,22 +298,401 @@
202
298
  // is Svelte's business and not something to depend on.
203
299
  span.onEnd(() => leaves.clear());
204
300
 
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`).
301
+ /** ⌘Z/Ctrl+Z takes the step back where the undo accepts it (`undo.accepts`).
211
302
  * On the document, since a removal under the pointer leaves the focus on the body, and
212
303
  * captured, so a leaf the removal handed the focus to hears the key after the offer. */
213
304
  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;
305
+ if (undoChord(e) !== 'undo' || !undo.accepts(e.target, rootEl)) return;
217
306
  e.preventDefault();
218
307
  e.stopPropagation();
219
308
  undo.take();
220
309
  }
310
+ // ── Review (`review.svelte.ts`): the host's list, published to the tree ─────
311
+ // A field item's path resolves here, against the live card keys, as a diagnostic's does:
312
+ // the nearest field holding it.
313
+ const reviewed = (path: DocPath): FieldKey | undefined => {
314
+ const addr = nearestAddrForFieldPath(path);
315
+ return addr && declaredField(addr) ? resolveCardKey(addr, cardIds) : undefined;
316
+ };
317
+ /** The field proposals accepted here: the change each made, the leaf it is at, the write
318
+ * back, and whether the value is still the one written. */
319
+ const taken = new SvelteMap<
320
+ string,
321
+ { change: FieldChange; leaf: string; back: () => void; holds: () => boolean }
322
+ >();
323
+ const takenChanges = $derived(new Map([...taken].map(([id, t]) => [id, t.change])));
324
+ /** Take a field's answer back: the value it replaced written back, if any, and the item
325
+ * reopened. */
326
+ const giveBack = (id: string, leaf: string, back?: () => void): void => {
327
+ back?.();
328
+ reviewing.heard(id, 'reopen', leaf);
329
+ };
330
+ const reviewing = createReview({
331
+ items: () => review,
332
+ taken: () => takenChanges,
333
+ putBack(id) {
334
+ const field = taken.get(id);
335
+ if (field) {
336
+ giveBack(id, field.leaf, field.back);
337
+ return true;
338
+ }
339
+ const key = reviewing.keyOf(id);
340
+ return key !== undefined && !!leaves.prose(key)?.answerReview(id, 'reopen');
341
+ },
342
+ keyFor: (path) => {
343
+ const key = reviewed(path);
344
+ return key && fieldKeyToString(key);
345
+ },
346
+ exact: (path) => addrForFieldPath(path) != null,
347
+ nested(path) {
348
+ const target = leafTargetFor(path);
349
+ const field = reviewed(path);
350
+ if (!target?.steps || !field?.field) return undefined;
351
+ const card =
352
+ field.card === undefined ? model.main : model.cards[cardIndexOf(field.card as CardId)];
353
+ return { key: target.key, steps: target.steps, value: card?.values[field.field] };
354
+ },
355
+ valueAt(path) {
356
+ const key = reviewed(path);
357
+ if (!key?.field) return undefined;
358
+ const card =
359
+ key.card === undefined ? model.main : model.cards[cardIndexOf(key.card as CardId)];
360
+ return card?.values[key.field];
361
+ },
362
+ leafFor(path) {
363
+ const addr = addrForFieldPath(path);
364
+ if (!addr) return undefined;
365
+ const key =
366
+ addr.field == null ? resolveCardKey({ card: addr.card }, cardIds) : reviewed(path);
367
+ return key && fieldKeyToString(key);
368
+ },
369
+ chorded(id) {
370
+ if (!reviewAdvance) return;
371
+ const index = drewOrder.indexOf(id);
372
+ void tick().then(() => {
373
+ if (span.alive) void step(1, true, index < 0 ? undefined : { id, index });
374
+ });
375
+ },
376
+ writing(on) {
377
+ writing += on ? 1 : -1;
378
+ },
379
+ answer(id, item, action, key) {
380
+ let back: (() => void) | undefined;
381
+ if (action === 'reopen') taken.delete(id);
382
+ if (action === 'accept' && item && !isChange(item) && onField(item)) {
383
+ const took = takeField(item);
384
+ if (!took) return false;
385
+ back = took.back;
386
+ taken.set(id, {
387
+ ...took,
388
+ change: { id, state: 'changed', field: item.field, before: took.before }
389
+ });
390
+ }
391
+ onReview?.({ id, action });
392
+ if (action !== 'accept' && action !== 'dismiss') return true;
393
+ const field = item && onField(item) ? reviewed(item.field) : undefined;
394
+ const leaf = key ?? (field && fieldKeyToString(field));
395
+ if (leaf === undefined) return true;
396
+ const prose = key !== undefined && !field;
397
+ record(
398
+ id,
399
+ prose
400
+ ? action === 'accept'
401
+ ? () => void leaves.prose(leaf)?.undoReview()
402
+ : () => void leaves.prose(leaf)?.reopenReview(id)
403
+ : () => giveBack(id, leaf, back),
404
+ back && merged.reviewAccepted
405
+ );
406
+ return true;
407
+ }
408
+ });
409
+
410
+ // ── The answer journal: the review answers since the reader's last edit, each undone by
411
+ // ⌘Z from anywhere in the editor, newest first, its item reopened with it. An edit that is
412
+ // 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
413
+ // lanes an edit does, so they are flagged while they are made.
414
+ interface Answered {
415
+ ids: string[];
416
+ inverses: (() => void)[];
417
+ /** The toast it stands on; none where the key alone takes it back. */
418
+ notice?: string;
419
+ }
420
+ let journal: Answered[] = [];
421
+ /** The entry a batch of answers records into. */
422
+ let batching: Answered | undefined;
423
+ let journalOffer: UndoOffer | undefined;
424
+ let writing = 0;
425
+ function settled(): void {
426
+ if (writing) return;
427
+ // A field set to another value since it was accepted no longer shows that change.
428
+ for (const [id, field] of taken) if (!field.holds()) taken.delete(id);
429
+ journal = [];
430
+ journalOffer = undefined;
431
+ undo.settle();
432
+ }
433
+ function offerJournal(): void {
434
+ const top = journal.at(-1);
435
+ journalOffer =
436
+ top &&
437
+ undo.offer(top.notice ?? '', unanswer, {
438
+ standing: true,
439
+ quiet: top.notice === undefined,
440
+ answer: true
441
+ });
442
+ }
443
+ function unanswer(): void {
444
+ const top = journal.pop();
445
+ if (!top) return;
446
+ writing++;
447
+ try {
448
+ for (const inverse of [...top.inverses].reverse()) inverse();
449
+ } finally {
450
+ writing--;
451
+ }
452
+ offerJournal();
453
+ }
454
+ function record(id: string, inverse: () => void, notice?: string): void {
455
+ if (batching) {
456
+ batching.ids.push(id);
457
+ batching.inverses.push(inverse);
458
+ return;
459
+ }
460
+ // Another step took the key since: the answers before it are no longer the last thing
461
+ // that happened.
462
+ if (!journalOffer || !undo.holds(journalOffer)) journal = [];
463
+ journal.push({ ids: [id], inverses: [inverse], notice });
464
+ offerJournal();
465
+ }
466
+
467
+ /**
468
+ * Take a field's proposal: its value down the lane the field's own control commits by, so
469
+ * the writer checks it and `onChange` reports it. A text leaf re-reads what was written.
470
+ * Returns the value it replaced, the write back to it, and whether the field still holds
471
+ * what was written, or `undefined` where the writer refused the value, which the field then
472
+ * says as it says any refused commit.
473
+ */
474
+ function takeField(
475
+ item: FieldProposal
476
+ ): { leaf: string; before: unknown; back: () => void; holds: () => boolean } | undefined {
477
+ const key = reviewed(item.field);
478
+ if (!key?.field || typeof key.card === 'number') return undefined;
479
+ const isMain = key.card === undefined;
480
+ const id = key.card ?? model.main.id;
481
+ const name = key.field;
482
+ const leaf = fieldKeyToString(key);
483
+ const addr = makeAddr(id, isMain, name);
484
+ const write = (value: unknown): boolean => {
485
+ commitScalar(id, isMain, name, value);
486
+ if (commitErrors.has(leaf)) return false;
487
+ leaves.prose(leaf)?.applyExternal();
488
+ return true;
489
+ };
490
+ writing++;
491
+ try {
492
+ if (!addrForFieldPath(item.field)) return takeInside(item, leaf, write);
493
+ const before = doc.getStored(addr);
494
+ if (!write(item.after)) return undefined;
495
+ const written = JSON.stringify(doc.getStored(addr));
496
+ return {
497
+ leaf,
498
+ before,
499
+ back: () => void write(before),
500
+ holds: () => JSON.stringify(doc.getStored(addr)) === written
501
+ };
502
+ } finally {
503
+ writing--;
504
+ }
505
+
506
+ /** The field's value as its control is handed it, read anew. */
507
+ function current(): unknown {
508
+ const at = isMain ? 0 : cardIndexOf(id);
509
+ if (at < 0) return undefined;
510
+ return fieldValues((isMain ? doc.main : doc.card(at)).payloadItems)[name];
511
+ }
512
+ /**
513
+ * A proposal for a place inside the field: the whole value written with that place
514
+ * changed, down the lane an edit of the place takes, and taken back by writing that
515
+ * place alone back, so another place accepted since keeps its change.
516
+ */
517
+ function takeInside(
518
+ item: FieldProposal,
519
+ leaf: string,
520
+ write: (value: unknown) => boolean
521
+ ): { leaf: string; before: unknown; back: () => void; holds: () => boolean } | undefined {
522
+ const steps = reviewing.at(leaf).nested?.find((e) => e.item.id === item.id)?.steps;
523
+ if (!steps) return undefined;
524
+ const value = current();
525
+ const last = steps.at(-1);
526
+ const list = typeof last === 'number' ? valueIn(value, steps.slice(0, -1)) : undefined;
527
+ const length = Array.isArray(list) ? list.length : 0;
528
+ const adds = typeof last === 'number' && last >= length && item.after !== undefined;
529
+ const removes = typeof last === 'number' && !adds && item.after === undefined;
530
+ const landed = adds ? [...steps.slice(0, -1), length] : steps;
531
+ const before = valueIn(value, steps);
532
+ const beside = removes ? besideOf(value, steps) : {};
533
+ if (!write(valueWith(value, steps, item.after))) return undefined;
534
+ return {
535
+ leaf,
536
+ before,
537
+ back: () =>
538
+ void write(
539
+ removes
540
+ ? valueWithInserted(current(), steps, before, beside)
541
+ : valueWith(current(), landed, adds ? undefined : before)
542
+ ),
543
+ holds: () => removes || sameValue(valueIn(current(), landed), item.after)
544
+ };
545
+ }
546
+ }
547
+ setReview(reviewing);
548
+ span.onEnd(reviewing.dispose);
549
+ // The lit item, to a host lighting its own list: each change, and not the nothing a mount
550
+ // starts from.
551
+ let reported: string | undefined;
552
+ $effect(() => {
553
+ const id = reviewing.lit;
554
+ if (id === reported) return;
555
+ reported = id;
556
+ onReviewFocus?.(id);
557
+ });
558
+ /** The open items drawn, in document order: each id's first element under the root, then
559
+ * any drawn one not yet in the DOM, in list order. */
560
+ function reviewOrder(): string[] {
561
+ const fieldUndrawn = new Set(reviewing.fieldUndrawn.map((u) => u.id));
562
+ const drawn = new Set<string>();
563
+ for (const report of reviewing.reports.values()) for (const id of report.ids) drawn.add(id);
564
+ for (const item of reviewing.items)
565
+ if (onField(item) && !fieldUndrawn.has(item.id)) drawn.add(item.id);
566
+ const order: string[] = [];
567
+ const seen = new Set<string>();
568
+ const take = (id: string | null): void => {
569
+ if (id === null || !drawn.has(id) || seen.has(id)) return;
570
+ seen.add(id);
571
+ order.push(id);
572
+ };
573
+ for (const el of rootEl?.querySelectorAll('[data-qm-review]') ?? [])
574
+ take(el.getAttribute('data-qm-review'));
575
+ for (const item of reviewing.items) take(item.id);
576
+ return order;
577
+ }
578
+ /** What the editor draws of the host's list, and why it draws what it does not. */
579
+ function reviewReport(): ReviewDrawn {
580
+ const reported = new Set<string>();
581
+ const outdated = new Set(reviewing.fieldOutdated);
582
+ const why = new Map<string, ReviewDrawn['undrawn'][number]['reason']>();
583
+ for (const report of reviewing.reports.values()) {
584
+ for (const id of report.ids) reported.add(id);
585
+ for (const id of report.outdated) outdated.add(id);
586
+ for (const { id, reason } of report.undrawn) {
587
+ reported.add(id);
588
+ why.set(id, reason);
589
+ }
590
+ }
591
+ for (const { id, reason } of reviewing.fieldUndrawn) why.set(id, reason);
592
+ for (const item of reviewing.items)
593
+ if (!reported.has(item.id) && !why.has(item.id)) {
594
+ if (byBlocks(item)) why.set(item.id, 'block');
595
+ }
596
+ const order = reviewOrder();
597
+ return {
598
+ order,
599
+ accepted: order.filter((id) => reviewing.accepted.has(id)),
600
+ open: order.filter((id) => !reviewing.accepted.has(id)),
601
+ outdated: order.filter((id) => outdated.has(id) && !reviewing.accepted.has(id)),
602
+ undrawn: reviewing.items.flatMap((item) => {
603
+ const reason = why.get(item.id);
604
+ return reason ? [{ id: item.id, reason }] : [];
605
+ })
606
+ };
607
+ }
608
+ // The report, to a host counting its own list: each change, read once the leaves the change
609
+ // mounted have drawn, so a list just handed over is not reported as anchored nowhere.
610
+ const NO_REPORT = JSON.stringify({
611
+ order: [],
612
+ accepted: [],
613
+ open: [],
614
+ outdated: [],
615
+ undrawn: []
616
+ } satisfies ReviewDrawn);
617
+ let drewReport = NO_REPORT;
618
+ let drewOrder: readonly string[] = [];
619
+ $effect(() => {
620
+ void reviewing.items;
621
+ void reviewing.accepted;
622
+ void reviewing.fieldUndrawn;
623
+ for (const id of reviewing.fieldOutdated) void id;
624
+ for (const report of reviewing.reports.values()) void report;
625
+ let live = true;
626
+ void tick().then(() => {
627
+ if (!live || !span.alive) return;
628
+ const report = reviewReport();
629
+ drewOrder = report.order;
630
+ const joined = JSON.stringify(report);
631
+ if (joined === drewReport) return;
632
+ drewReport = joined;
633
+ onReviewDrawn?.(report);
634
+ });
635
+ return () => {
636
+ live = false;
637
+ };
638
+ });
639
+ /** The item a step last went to, and where it stood in the order then, so a step from an
640
+ * item since answered goes on from its place. */
641
+ let stepped: { id: string; index: number } | undefined;
642
+ async function step(
643
+ dir: 1 | -1,
644
+ focus: boolean,
645
+ from?: { id: string; index: number }
646
+ ): Promise<string | undefined> {
647
+ if (!span.alive) return undefined;
648
+ const order = reviewOrder();
649
+ if (!order.length) return undefined;
650
+ const at = from ? -1 : order.indexOf(reviewing.lit ?? stepped?.id ?? '');
651
+ const past = from ?? stepped;
652
+ const next =
653
+ at >= 0 ? at + dir : past ? (dir > 0 ? past.index : past.index - 1) : dir > 0 ? 0 : -1;
654
+ const index = ((next % order.length) + order.length) % order.length;
655
+ const id = order[index];
656
+ stepped = { id, index };
657
+ await reveal(id, focus, true);
658
+ return id;
659
+ }
660
+ const stepKeys = keydownHandler({
661
+ [REVIEW_KEYS.next]: () => {
662
+ void step(1, true);
663
+ return true;
664
+ },
665
+ [REVIEW_KEYS.previous]: () => {
666
+ void step(-1, true);
667
+ return true;
668
+ }
669
+ });
670
+ /** The step chords, from anywhere under the root, ahead of a leaf's own arrows. */
671
+ function onStepKey(e: KeyboardEvent): void {
672
+ if (e.isComposing || !reviewing.items.length) return;
673
+ // The bindings read no view: this is `prosemirror-keymap`'s chord matcher alone.
674
+ if (!stepKeys({} as never, e)) return;
675
+ e.preventDefault();
676
+ e.stopPropagation();
677
+ }
678
+ /** Where item `id` is drawn, for the card that hangs off it. */
679
+ function reviewTarget(id: string): ReviewTarget | undefined {
680
+ const key = reviewing.keyOf(id);
681
+ if (key === undefined) return undefined;
682
+ const prose = leaves.prose(key);
683
+ const mark = prose?.reviewElements(id)[0];
684
+ if (prose && mark)
685
+ return {
686
+ anchor: markAnchor(prose.el, () => prose.reviewElements(id)[0]),
687
+ removed: mark.classList.contains('qm-review-gone')
688
+ };
689
+ const control = leaves.control(key);
690
+ const own = [...(control?.el.querySelectorAll<HTMLElement>('[data-qm-review]') ?? [])].find(
691
+ (el) => el.getAttribute('data-qm-review') === id
692
+ );
693
+ return control && { anchor: own ?? control.el, removed: false };
694
+ }
695
+
221
696
  // Card handles, for `setCaret`'s reveal hop: the one thing a leaf's own controller
222
697
  // cannot do, since which group is open is the card's state (Card §revealLeaf).
223
698
  type CardHandle = {
@@ -308,6 +783,7 @@
308
783
  const cardId = cardIdOf(plain);
309
784
  if (cardId == null) return;
310
785
  refreshTitle(plain, cardId);
786
+ settled();
311
787
  onChange?.({ source: 'prose', cardId, path: pathFor(plain) });
312
788
  }
313
789
 
@@ -375,7 +851,8 @@
375
851
  }
376
852
  }
377
853
  commitErrors.delete(keyStr);
378
- bump('field', id, makeAddr(id, isMain, name));
854
+ fieldCommitted(id, isMain, name, value);
855
+ report('field', id, makeAddr(id, isMain, name));
379
856
  } catch (e) {
380
857
  const diagnostic: Diagnostic = (isQuillmarkError(e) ? e.diagnostics[0] : undefined) ?? {
381
858
  severity: 'error',
@@ -500,6 +977,8 @@
500
977
  if (from < 0) return;
501
978
  const to = from + dir;
502
979
  if (to < 0 || to >= doc.cardCount) return;
980
+ const focused = document.activeElement;
981
+ const held = focused instanceof HTMLElement && slotEls[from]?.contains(focused);
503
982
  arm.arm();
504
983
  doc.moveCard(from, to);
505
984
  undo.withdraw();
@@ -508,10 +987,18 @@
508
987
  w.splice(to, 0, x);
509
988
  cardIds = w;
510
989
  bump('structure', id, to, { op: 'move', from, to });
990
+ if (held) void keepFocus(focused);
511
991
  // `nearest`: the card was already in view and only needs to stay there, so one
512
992
  // that never left the viewport moves it not at all.
513
993
  void scrollCardIntoView(id, 'nearest');
514
994
  }
995
+ /** Give the focus back to the control a move was made from. The reconcile reorders by
996
+ * re-inserting slots, and a re-inserted node loses the focus to the page's body with no
997
+ * blur to say so; which of two swapped slots it re-inserts is its own choice. */
998
+ async function keepFocus(el: HTMLElement): Promise<void> {
999
+ if (!(await span.resumes(tick()))) return;
1000
+ if (el.isConnected && document.activeElement !== el) el.focus({ preventScroll: true });
1001
+ }
515
1002
  function removeCardById(id: string): void {
516
1003
  const i = cardIndexOf(id);
517
1004
  if (i < 0) return;
@@ -525,6 +1012,7 @@
525
1012
  shown?.titleOverride ||
526
1013
  shown?.titlePlaceholder ||
527
1014
  kindTitle(quill.schema.card_kinds?.[card.kind], card.kind);
1015
+ const gone = removed.remove(id, card, cardIds, i);
528
1016
  doc.removeCard(i);
529
1017
  arm.arm();
530
1018
  cardIds = cardIds.filter((_, k) => k !== i);
@@ -532,17 +1020,27 @@
532
1020
  // No addr: the removed card has none left and every survivor's shifted. The
533
1021
  // stack changed, not a leaf, and the id is the only handle the removal leaves.
534
1022
  bump('structure', id, undefined, { op: 'remove', at: i });
535
- undo.offer(merged.undoRemoved(name), () => restoreCard(card, i));
1023
+ undo.offer(merged.undoRemoved(name), () => restoreCard(gone), {
1024
+ keptAs: merged.undoRestore(name)
1025
+ });
536
1026
  if (held) void focusAfterRemove(i);
537
1027
  }
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 {
1028
+ /** The removals not yet restored, each the step `undo` keeps for it (`removed.ts`). */
1029
+ const removed = removedCards<ReturnType<typeof doc.card>>();
1030
+ /** The removal's undo: the card back beside the neighbours it left, under a fresh session
1031
+ * key (ids are never reused), with the focus on its title. A removal that named the
1032
+ * gone card as its neighbour names the restored one. The document mints a card's `$id`
1033
+ * from the ids it holds, so a card added since may hold the one this card left with,
1034
+ * and the card then goes back without it and is minted another. */
1035
+ function restoreCard(gone: RemovedCard<ReturnType<typeof doc.card>>): void {
542
1036
  if (!span.alive) return;
543
- const i = Math.min(at, cardIds.length);
1037
+ const { card } = gone;
1038
+ const i = removed.place(gone, cardIds);
544
1039
  try {
545
- doc.unchecked.insertCard(card, i);
1040
+ const taken = card.id !== undefined && cardIds.some((_, k) => doc.card(k).id === card.id);
1041
+ const back = { ...card };
1042
+ if (taken) delete back.id;
1043
+ doc.unchecked.insertCard(back, i);
546
1044
  } catch (e) {
547
1045
  reportError(onError, {
548
1046
  code: 'card-op-failed',
@@ -553,6 +1051,7 @@
553
1051
  return;
554
1052
  }
555
1053
  const id = seq.next();
1054
+ removed.restored(gone, id);
556
1055
  arm.arm();
557
1056
  cardIds = [...cardIds.slice(0, i), id, ...cardIds.slice(i)];
558
1057
  bump('structure', id, i, { op: 'insert', at: i });
@@ -738,7 +1237,7 @@
738
1237
  };
739
1238
  }
740
1239
 
741
- const model = $derived.by(() => {
1240
+ const tree = $derived.by(() => {
742
1241
  revision; // re-derive on every mutation
743
1242
  const schema = quill.schema;
744
1243
  const main = doc.main;
@@ -781,6 +1280,12 @@
781
1280
  };
782
1281
  });
783
1282
 
1283
+ const model = $derived({
1284
+ tips: tree.tips,
1285
+ main: patched.main ?? tree.main,
1286
+ cards: tree.cards.map((c) => patched[c.id] ?? c)
1287
+ });
1288
+
784
1289
  // ── Public entry points ─────────────────────────────────────────────────────
785
1290
  /**
786
1291
  * Resolve a preview {@link Landing} to a mounted leaf and land in it.
@@ -961,6 +1466,105 @@
961
1466
  rederive();
962
1467
  }
963
1468
 
1469
+ // ── Review ──────────────────────────────────────────────────────────────────
1470
+
1471
+ /**
1472
+ * Bring the review item `id` to the reader: open the panel holding it, scroll it to the
1473
+ * middle of the view, light it, and raise its card where it has one. The focus stays
1474
+ * where it is, the reader having asked to look, unless `focus` asks for it: the caret
1475
+ * then goes into the item, or the focus to its field, so the chords answer it. False for
1476
+ * an item the editor does not draw.
1477
+ */
1478
+ export function revealReview(id: string, opts: { focus?: boolean } = {}): Promise<boolean> {
1479
+ return reveal(id, opts.focus ?? false, false);
1480
+ }
1481
+ /** {@link revealReview}; a step scrolls an item only as far as its scroller must to show it,
1482
+ * so a walk down neighbouring items does not jump the page under each, and an item in a
1483
+ * pane that scrolls on its own is shown by that pane. */
1484
+ async function reveal(id: string, focus: boolean, stepping: boolean): Promise<boolean> {
1485
+ if (!span.alive) return false;
1486
+ const key = reviewing.keyOf(id);
1487
+ if (key === undefined) return false;
1488
+ mainCard?.revealLeaf(key);
1489
+ for (const card of cardRefs) card?.revealLeaf(key);
1490
+ if (!(await span.resumes(tick()))) return false;
1491
+ reviewing.reveal(id);
1492
+ if (focus && !leaves.prose(key)?.enterReview(id)) leaves.control(key)?.focus();
1493
+ // The lit item is drawn again, so its element is read once it has been.
1494
+ if (!(await span.resumes(tick()))) return false;
1495
+ const at =
1496
+ leaves.prose(key)?.reviewElements(id)[0] ??
1497
+ [...(rootEl?.querySelectorAll<HTMLElement>('[data-qm-review]') ?? [])].find(
1498
+ (el) => el.getAttribute('data-qm-review') === id
1499
+ ) ??
1500
+ leaves.control(key)?.el;
1501
+ const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
1502
+ at?.scrollIntoView({
1503
+ behavior: reduce ? 'auto' : 'smooth',
1504
+ block: stepping ? 'nearest' : 'center'
1505
+ });
1506
+ return true;
1507
+ }
1508
+
1509
+ /**
1510
+ * Answer items as their buttons would, in document order: `'all'` is every item drawn. An
1511
+ * accept or a dismissal passes over a change, which has neither button, and over a proposal
1512
+ * already accepted, and an item that cannot be answered (a proposal that no longer writes, a
1513
+ * value the field's writer refuses) stands. `'reopen'` takes back each accepted proposal
1514
+ * named, as its card's Undo does. `onReview` hears each answer, and neither the focus nor the
1515
+ * caret moves. The batch raises no toast, the host's to word if it wants one, and ⌘Z takes
1516
+ * it back whole. Returns the ids answered.
1517
+ */
1518
+ export function answerReview(
1519
+ ids: readonly string[] | 'all',
1520
+ action: 'accept' | 'dismiss' | 'reopen'
1521
+ ): string[] {
1522
+ if (!span.alive) return [];
1523
+ const order = reviewOrder();
1524
+ const asked = ids === 'all' ? order : order.filter((id) => ids.includes(id));
1525
+ const out: string[] = [];
1526
+ if (action === 'reopen') {
1527
+ for (const id of asked)
1528
+ if (reviewing.accepted.has(id) && reviewing.act(id, 'reopen')) out.push(id);
1529
+ return out;
1530
+ }
1531
+ const entry: Answered = { ids: [], inverses: [] };
1532
+ batching = entry;
1533
+ writing++;
1534
+ try {
1535
+ for (const id of asked) {
1536
+ const item = reviewing.items.find((it) => it.id === id);
1537
+ if (!item || reviewing.accepted.has(id)) continue;
1538
+ const key = reviewing.keyOf(id);
1539
+ // Each one is planned against the document the one before it left.
1540
+ const answered = !onField(item)
1541
+ ? key !== undefined && !!leaves.prose(key)?.answerReview(id, action)
1542
+ : reviewing.act(id, action);
1543
+ if (answered) out.push(id);
1544
+ }
1545
+ } finally {
1546
+ writing--;
1547
+ batching = undefined;
1548
+ }
1549
+ if (entry.ids.length) {
1550
+ if (!journalOffer || !undo.holds(journalOffer)) journal = [];
1551
+ journal.push(entry);
1552
+ offerJournal();
1553
+ }
1554
+ return out;
1555
+ }
1556
+
1557
+ /** Bring the next or previous open item to the reader, in document order and round from
1558
+ * either end, from the lit item or the one last stepped to: the caret in it, or the
1559
+ * focus in its field, unless `focus` is false. Resolves its id, `undefined` when none is
1560
+ * drawn. */
1561
+ export function stepReview(
1562
+ dir: 1 | -1,
1563
+ opts: { focus?: boolean } = {}
1564
+ ): Promise<string | undefined> {
1565
+ return step(dir, opts.focus ?? true);
1566
+ }
1567
+
964
1568
  function holds(cardId: CardId): boolean {
965
1569
  if (cardIndexOf(cardId) >= 0) return true;
966
1570
  missed(`no card ${cardId} in this session`);
@@ -1018,18 +1622,30 @@
1018
1622
  const card = addr.card == null ? schema.main : kind ? schema.card_kinds?.[kind] : undefined;
1019
1623
  return card?.fields?.[addr.field];
1020
1624
  }
1625
+
1626
+ /** A file dropped anywhere in the editor is refused, or the browser opens it in place
1627
+ * of the page. Text drops carry no `Files` and pass. */
1628
+ function refuseFiles(e: DragEvent): void {
1629
+ if (!e.dataTransfer?.types.includes('Files')) return;
1630
+ e.preventDefault();
1631
+ e.dataTransfer.dropEffect = 'none';
1632
+ }
1021
1633
  </script>
1022
1634
 
1023
1635
  <svelte:document onkeydowncapture={onUndoKey} />
1024
1636
 
1025
- <!-- The keydown is a control's, bubbled: the root resolves which description it raises. -->
1637
+ <!-- The keydown is a control's, bubbled: the root resolves which description it raises.
1638
+ A file dragged over or dropped is refused here, after any control has seen it. -->
1026
1639
  <!-- svelte-ignore a11y_no_static_element_interactions -->
1027
1640
  <div
1028
1641
  class="qm-editor {className ?? ''}"
1029
1642
  {style}
1030
1643
  data-qm-root
1031
1644
  bind:this={rootEl}
1645
+ onkeydowncapture={onStepKey}
1032
1646
  onkeydown={raiseGuidance}
1647
+ ondragover={refuseFiles}
1648
+ ondrop={refuseFiles}
1033
1649
  >
1034
1650
  <!-- `main` and the tips card are one block in the stack: the tips card tucks under
1035
1651
  `main`'s bottom corners, so the two share a seam rather than a gutter and the
@@ -1086,6 +1702,17 @@
1086
1702
  {@render addAffordance(i + 1)}
1087
1703
  </div>
1088
1704
  {/each}
1705
+ <!-- The way back to a removed card once its toast has gone: the newest kept step, by
1706
+ name, at the stack's foot, where the control that adds a card is looked for. -->
1707
+ {#if undo.kept}
1708
+ <div class="qm-restore">
1709
+ <button
1710
+ type="button"
1711
+ class="qm-restore-btn qm-tap-floor qm-focus-ring"
1712
+ onclick={() => undo.takeKept()}>{undo.kept.label}</button
1713
+ >
1714
+ </div>
1715
+ {/if}
1089
1716
  <!-- The removal's undo. The region stands empty between offers so the notice it takes is
1090
1717
  announced: a live region inserted along with its text is one a reader may not hear. -->
1091
1718
  <div class="qm-toast-slot" role="status">
@@ -1112,6 +1739,7 @@
1112
1739
  </div>
1113
1740
 
1114
1741
  <FormatPopover {getActiveLeaf} families={fontFamilies} {fontLabels} />
1742
+ <ReviewPopover review={reviewing} targetFor={reviewTarget} />
1115
1743
 
1116
1744
  <!-- The add affordance is gated on the schema declaring `card_kinds`, there being
1117
1745
  nothing to seed otherwise. Cards render regardless: a kind with no schema degrades to
@@ -1221,6 +1849,27 @@
1221
1849
  .qm-toast-action:hover {
1222
1850
  background: var(--_qm-accent-tint);
1223
1851
  }
1852
+ /* Words at the label ink, unboxed: the stack's foot already holds one outlined pill, and
1853
+ a second would stand as its equal. */
1854
+ .qm-restore {
1855
+ display: flex;
1856
+ justify-content: center;
1857
+ }
1858
+ .qm-restore-btn {
1859
+ min-height: var(--_qm-tap-min);
1860
+ padding-inline: var(--_qm-space-2);
1861
+ border: 0;
1862
+ border-radius: var(--_qm-radius-pill);
1863
+ background: transparent;
1864
+ font: inherit;
1865
+ font-size: var(--_qm-text-label);
1866
+ color: var(--_qm-ink-label);
1867
+ cursor: pointer;
1868
+ }
1869
+ .qm-restore-btn:hover {
1870
+ background: var(--_qm-add-fill);
1871
+ color: var(--_qm-ink);
1872
+ }
1224
1873
  /* A detached root, carrying `data-qm-root` for the derivation core/theme.css applies
1225
1874
  to one — the baseline font and colour included, so nothing here restates them.
1226
1875