@quillmark/svelte 0.38.0 → 0.39.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.
@@ -0,0 +1,108 @@
1
+ // How a landing frames its target: the target in the band its scroller shows, and the label of the
2
+ // field it sits in with it wherever the two fit together, since a box without its label is a box
3
+ // the reader has to scroll to name. Where they do not fit, the target alone is framed.
4
+ import { spacePx } from './rungs.js';
5
+ /**
6
+ * The scroll, in px down, that frames `target` in `band` with `gap` clear of each edge. `top` is
7
+ * where the field's label starts: kept in the band whenever it fits with the target, the target
8
+ * winning where it does not. Zero for a target already framed, so a landing on the field in view
9
+ * moves nothing.
10
+ */
11
+ export function frameDelta(band, target, top, gap, block) {
12
+ const room = band.bottom - band.top - 2 * gap;
13
+ const high = band.top + gap;
14
+ const low = band.bottom - gap;
15
+ const tall = target.bottom - target.top > room;
16
+ let delta = 0;
17
+ if (tall)
18
+ delta = target.top - high;
19
+ else if (block === 'center')
20
+ delta = (target.top + target.bottom) / 2 - (high + low) / 2;
21
+ else if (target.top < high)
22
+ delta = target.top - high;
23
+ else if (target.bottom > low)
24
+ delta = target.bottom - low;
25
+ if (top < target.top && target.bottom - top <= room && top - delta < high)
26
+ delta = top - high;
27
+ return delta;
28
+ }
29
+ /** The nearest ancestor of `el` that scrolls vertically, or `undefined` where the page does. */
30
+ function scrollerOf(el) {
31
+ for (let at = el.parentElement; at; at = at.parentElement) {
32
+ if (at === el.ownerDocument.documentElement || at === el.ownerDocument.body)
33
+ return undefined;
34
+ const { overflowY } = getComputedStyle(at);
35
+ if ((overflowY === 'auto' || overflowY === 'scroll') && at.scrollHeight > at.clientHeight)
36
+ return at;
37
+ }
38
+ return undefined;
39
+ }
40
+ function px(value) {
41
+ const n = Number.parseFloat(value);
42
+ return Number.isFinite(n) ? n : 0;
43
+ }
44
+ /** The band `scroller` shows, less its `scroll-padding` and at least `foot` at its foot. */
45
+ function bandOf(scroller, foot) {
46
+ const doc = document.documentElement;
47
+ const style = getComputedStyle(scroller ?? doc);
48
+ let top = 0;
49
+ let bottom = window.innerHeight;
50
+ if (scroller) {
51
+ const box = scroller.getBoundingClientRect();
52
+ top = Math.max(box.top + scroller.clientTop, 0);
53
+ bottom = Math.min(top + scroller.clientHeight, bottom);
54
+ }
55
+ return {
56
+ top: top + px(style.scrollPaddingTop),
57
+ bottom: bottom - Math.max(px(style.scrollPaddingBottom), foot)
58
+ };
59
+ }
60
+ /** Scroll the box `target` scrolls in sideways, a table's, the least that shows it. */
61
+ function frameInline(target, stop, behavior) {
62
+ for (let at = target.parentElement; at && at !== stop; at = at.parentElement) {
63
+ const { overflowX } = getComputedStyle(at);
64
+ if ((overflowX !== 'auto' && overflowX !== 'scroll') || at.scrollWidth <= at.clientWidth)
65
+ continue;
66
+ const port = at.getBoundingClientRect();
67
+ const style = getComputedStyle(at);
68
+ const left = port.left + at.clientLeft + px(style.scrollPaddingLeft);
69
+ const right = port.left + at.clientLeft + at.clientWidth - px(style.scrollPaddingRight);
70
+ const box = target.getBoundingClientRect();
71
+ const dx = box.left < left || box.right - box.left > right - left
72
+ ? box.left - left
73
+ : Math.max(box.right - right, 0);
74
+ if (Math.abs(dx) >= 1)
75
+ at.scrollBy({ left: dx, behavior });
76
+ return;
77
+ }
78
+ }
79
+ /**
80
+ * Scroll `target` into the band its scroller shows, with the label of the field it sits in where
81
+ * the two fit (`frameDelta`). One scroller moves, the nearest: a host page around the editor stays
82
+ * where it is.
83
+ */
84
+ export function frame(target, opts) {
85
+ const box = target.getBoundingClientRect();
86
+ if (!box.width && !box.height)
87
+ return;
88
+ const field = target.closest('.qm-field');
89
+ const top = Math.min(field?.getBoundingClientRect().top ?? box.top, box.top);
90
+ const scroller = scrollerOf(target);
91
+ frameInline(target, scroller, opts.behavior ?? 'instant');
92
+ const delta = frameDelta(bandOf(scroller, opts.foot ?? 0), box, top, spacePx(target, 3) ?? 0, opts.block);
93
+ if (Math.abs(delta) < 1)
94
+ return;
95
+ (scroller ?? window).scrollBy({ top: delta, behavior: opts.behavior ?? 'instant' });
96
+ }
97
+ /** The top a landing frames for `els`, its field's label included where it fits in `band`. */
98
+ export function framedTop(els, band) {
99
+ const rects = els.map((el) => el.getBoundingClientRect()).filter((r) => r.width || r.height);
100
+ if (!rects.length)
101
+ return undefined;
102
+ const top = Math.min(...rects.map((r) => r.top));
103
+ const bottom = Math.max(...rects.map((r) => r.bottom));
104
+ const label = els[0]?.closest('.qm-field')?.getBoundingClientRect().top;
105
+ if (label === undefined || label >= top)
106
+ return top;
107
+ return bottom - label <= band.bottom - band.top ? label : top;
108
+ }
@@ -539,6 +539,16 @@
539
539
  --_qm-ink-label: var(--_qm-ink);
540
540
  }
541
541
 
542
+ /* A card a proposal adds is filled with the review tint, which takes back that distance too, so
543
+ over it the rung steps to `default`, and over the lit tint to the ink: each holds 4.5:1 at
544
+ both poles, where the label rung over the dark pole's lit tint stands near 2.4:1. */
545
+ :where(.qm-review-card-add) {
546
+ --_qm-ink-label: var(--_qm-ink-default);
547
+ }
548
+ :where(.qm-review-card-add.qm-review-lit) {
549
+ --_qm-ink-label: var(--_qm-ink);
550
+ }
551
+
542
552
  /* More contrast steps the two rungs that identify a control rather than a list of
543
553
  selectors: the well's edge to 3:1 against the card at both poles (WCAG 1.4.11),
544
554
  which half the ink over the well clears, and the ring a pixel wider. */
@@ -117,6 +117,7 @@
117
117
  import {
118
118
  numberProposal,
119
119
  putsIn,
120
+ membersOf,
120
121
  textsOf,
121
122
  type TextProposal,
122
123
  splitReview,
@@ -264,20 +265,18 @@
264
265
  unrouted(routed, (step) => typeof step === 'number' && step >= 0 && step < arr.length)
265
266
  );
266
267
  const reviewed = $derived(splitReview(review));
267
- /** An item on a row that adds members in front of it, which the row does not draw. */
268
- const inserting = (e: DeepReview): boolean => !e.steps.length && putsIn(e.item);
268
+ /** An item on a row that adds members in front of it, which the row does not draw. Its
269
+ * steps are past the row's, which is a member's index. */
270
+ const inserting = (e: DeepReview): boolean => !e.steps.length && putsIn(e.item, [0]);
269
271
  /** A row's review items: the member's own, and those inside it. */
270
272
  const rowReview = (k: number): DeepReview[] =>
271
273
  k < arr.length ? (reviewed.below.get(k) ?? []).filter((e) => !inserting(e)) : [];
272
274
  /** The members a review would put in front of row `k`, each with the item that adds it. */
273
275
  const insertedAt = (k: number): { item: FieldProposal; after: unknown }[] =>
274
276
  k < arr.length
275
- ? (reviewed.below.get(k) ?? []).filter(inserting).flatMap(({ item }) =>
276
- (Array.isArray(item.after) ? item.after : [item.after]).map((after) => ({
277
- item,
278
- after
279
- }))
280
- )
277
+ ? (reviewed.below.get(k) ?? [])
278
+ .filter(inserting)
279
+ .flatMap(({ item }) => membersOf(item).map((after) => ({ item, after })))
281
280
  : [];
282
281
  const ownReview = (k: number): DeepReview[] => rowReview(k).filter((e) => !e.steps.length);
283
282
  /** A row's own removal: the proposal that takes the member out, drawn on the whole row. */
@@ -354,7 +353,7 @@
354
353
  e.steps.length === 1 &&
355
354
  typeof e.steps[0] === 'number' &&
356
355
  e.steps[0] >= arr.length &&
357
- !putsIn(e.item) &&
356
+ !('ahead' in e.item) &&
358
357
  e.item.after !== undefined
359
358
  )
360
359
  );
@@ -384,6 +383,8 @@
384
383
  let adding = $state(false);
385
384
  const pending = $derived(adding && control === 'number' && ids.length > 0 && !atCap);
386
385
  const rowIds = $derived(onStanding ? [standingId] : pending ? [...ids, standingId] : ids);
386
+ /** Whether the rows draw nothing: no row, standing or held, and no member a review adds. */
387
+ const rowless = $derived(rowIds.length === 0 && !added.length);
387
388
  /** Whether the element's keys are its control's own, the row wiring none. */
388
389
  const scalar = $derived(
389
390
  control === 'number' || control === 'enum' || control === 'boolean' || control === 'date'
@@ -1034,7 +1035,7 @@
1034
1035
  each block's one child: a branch inside the block would stand between them. -->
1035
1036
  {#if table}
1036
1037
  <div
1037
- class={['qm-array-rows qm-array-table qm-wash', { empty: ids.length === 0 }]}
1038
+ class={['qm-array-rows qm-array-table qm-wash', { empty: rowless }]}
1038
1039
  data-default={defaulted ? '' : undefined}
1039
1040
  bind:this={rowsEl}
1040
1041
  >
@@ -1109,7 +1110,7 @@
1109
1110
  </div>
1110
1111
  {:else if control === 'object'}
1111
1112
  <div
1112
- class={['qm-array-rows qm-wash', { empty: ids.length === 0 }]}
1113
+ class={['qm-array-rows qm-wash', { empty: rowless }]}
1113
1114
  data-default={defaulted ? '' : undefined}
1114
1115
  bind:this={rowsEl}
1115
1116
  >
@@ -1200,7 +1201,7 @@
1200
1201
  </div>
1201
1202
  {:else}
1202
1203
  <div
1203
- class={['qm-array-rows qm-wash', { empty: rowIds.length === 0 && !added.length }]}
1204
+ class={['qm-array-rows qm-wash', { empty: rowless }]}
1204
1205
  data-default={defaulted ? '' : undefined}
1205
1206
  bind:this={rowsEl}
1206
1207
  >
@@ -382,7 +382,7 @@
382
382
  {@attach registerControl}
383
383
  onfocusin={(e) => {
384
384
  reportFocus?.(e);
385
- if (proposed) reviewing.point(proposed.id);
385
+ if (proposed && field.control !== 'prose') reviewing.point(proposed.id);
386
386
  }}
387
387
  >
388
388
  {#if field.control === 'prose'}
@@ -42,6 +42,7 @@
42
42
  } from '../core/address.js';
43
43
  import { errorMessage, reportError } from '../core/errors.js';
44
44
  import { bloom } from '../core/bloom.js';
45
+ import { frame, framedTop } from '../core/frame.js';
45
46
  import { createLifespan } from '../core/teardown.js';
46
47
  import { spacePx } from '../core/rungs.js';
47
48
  import { tooltips } from '../core/tooltip.js';
@@ -68,6 +69,7 @@
68
69
  byCard,
69
70
  locate,
70
71
  putsIn,
72
+ membersOf,
71
73
  onField,
72
74
  reviewText,
73
75
  valueIn,
@@ -472,8 +474,8 @@
472
474
  const steps = reviewing.at(leaf).nested?.find((e) => e.item.id === item.id)?.steps;
473
475
  if (!steps) return undefined;
474
476
  const value = current();
475
- after = putsIn(item)
476
- ? valueInserting(value, steps, item.after)
477
+ after = putsIn(item, steps)
478
+ ? valueInserting(value, steps, membersOf(item))
477
479
  : valueWith(value, steps, to(valueIn(value, steps)));
478
480
  } else after = to(current());
479
481
  if (!write(after)) return undefined;
@@ -607,7 +609,10 @@
607
609
  const report = reviewing.report;
608
610
  drewOrder = report.open;
609
611
  drewOutdated = report.outdated;
610
- if (reviewing.lit === undefined && report.open.length) reviewing.reveal(report.open[0]);
612
+ if (reviewing.lit === undefined && report.open.length) {
613
+ reviewing.reveal(report.open[0]);
614
+ void reveal(report.open[0], false, true);
615
+ }
611
616
  const joined = JSON.stringify(report);
612
617
  if (joined === drewReport) return;
613
618
  drewReport = joined;
@@ -733,14 +738,60 @@
733
738
  function reviewIds(el: Element | null | undefined): string[] {
734
739
  return el?.getAttribute('data-qm-review')?.split(' ').filter(Boolean) ?? [];
735
740
  }
736
- /** A press on a change makes it current at once. */
741
+ /** A press on a change makes it current at once, and a press elsewhere in a field the
742
+ * nearest change in it, the current item being another field's. */
737
743
  function onPick(e: PointerEvent): void {
738
- const ids = reviewIds((e.target as Element | null)?.closest?.('[data-qm-review]'));
744
+ const target = e.target instanceof Element ? e.target : null;
745
+ const ids = reviewIds(target?.closest('[data-qm-review]'));
739
746
  const id = ids.includes(reviewing.lit ?? '') ? reviewing.lit : ids[0];
740
747
  if (id && reviewing.items.some((item) => item.id === id)) {
741
748
  typing = false;
742
749
  reviewing.reveal(id);
750
+ } else if (target) pickNear(target);
751
+ }
752
+ /** The reader arrived at `target` from outside its field, not handed back from a surface
753
+ * floating over it: the nearest change in the field becomes current. */
754
+ function onArrive(e: FocusEvent): void {
755
+ const target = e.target instanceof Element ? e.target : null;
756
+ const from = e.relatedTarget instanceof Element ? e.relatedTarget : null;
757
+ if (!target || !from || from.closest('.qm-popover-surface')) return;
758
+ const field = outerField(target);
759
+ if (field && !field.contains(from) && !target.closest('[data-qm-review]')) pickNear(target);
760
+ }
761
+ /** The outermost field holding `el`: the one a list's rows and a record's cells are of. */
762
+ function outerField(el: Element): Element | undefined {
763
+ let field: Element | undefined;
764
+ for (let at = el.closest('.qm-field'); at; at = at.parentElement?.closest('.qm-field') ?? null)
765
+ field = at;
766
+ return field;
767
+ }
768
+ /** Make the change in `target`'s field nearest it current, the fewest rows away and then the
769
+ * fewest pixels across, the current item being another field's. A leaf of words that draws
770
+ * changes of its own names them from its caret (`review-caret.ts`). */
771
+ function pickNear(target: Element): void {
772
+ if (target.closest('.ProseMirror')?.querySelector('[data-qm-review]')) return;
773
+ const field = outerField(target);
774
+ if (!field) return;
775
+ const open = new Set(reviewing.order);
776
+ const marks = [...field.querySelectorAll('[data-qm-review]')].filter((el) =>
777
+ reviewIds(el).some((id) => open.has(id))
778
+ );
779
+ if (!marks.length) return;
780
+ if (reviewing.lit !== undefined && marks.some((el) => reviewIds(el).includes(reviewing.lit!)))
781
+ return;
782
+ const at = target.getBoundingClientRect();
783
+ const gap = (a: number, b: number, c: number, d: number): number =>
784
+ b < c ? c - b : d < a ? a - d : 0;
785
+ let best: { el: Element; down: number; across: number } | undefined;
786
+ for (const el of marks) {
787
+ const r = el.getBoundingClientRect();
788
+ const down = gap(at.top, at.bottom, r.top, r.bottom);
789
+ const across = gap(at.left, at.right, r.left, r.right);
790
+ if (!best || down < best.down || (down === best.down && across < best.across))
791
+ best = { el, down, across };
743
792
  }
793
+ const id = best && reviewIds(best.el).find((id) => open.has(id));
794
+ if (id) reviewing.reveal(id);
744
795
  }
745
796
  /** What the change `id` is to: the field it is drawn in, the body, or the card it adds or
746
797
  * takes out. */
@@ -1476,7 +1527,9 @@
1476
1527
  */
1477
1528
  async function land(found: Landed, pos: number | undefined): Promise<HTMLElement> {
1478
1529
  if (found.steps && found.control.focusPath) {
1479
- return (await found.control.focusPath(found.steps, pos)) ?? found.control.el;
1530
+ const box = (await found.control.focusPath(found.steps, pos)) ?? found.control.el;
1531
+ if (pos == null) frame(box, { block: 'nearest' });
1532
+ return box;
1480
1533
  }
1481
1534
  if (pos != null) {
1482
1535
  const prose = leaves.prose(found.key);
@@ -1486,6 +1539,7 @@
1486
1539
  }
1487
1540
  }
1488
1541
  found.control.focus();
1542
+ frame(found.control.el, { block: 'nearest' });
1489
1543
  return found.control.el;
1490
1544
  }
1491
1545
 
@@ -1515,7 +1569,7 @@
1515
1569
  export async function revealField(field: DocPath): Promise<void> {
1516
1570
  const found = await revealLeaf(field);
1517
1571
  if (!found) return missed(`no mounted field at ${field}`, field);
1518
- found.control.el.scrollIntoView({ block: 'nearest', behavior: 'instant' });
1572
+ frame(found.control.el, { block: 'nearest' });
1519
1573
  bloom(found.control.el);
1520
1574
  }
1521
1575
  /** Play the arrival wash over the field at `field` and touch nothing else: no focus,
@@ -1623,7 +1677,7 @@
1623
1677
  (key !== undefined ? leaves.control(key)?.el : undefined);
1624
1678
  if (!at || (stepping && comfortable(els.length ? els : [at]))) return true;
1625
1679
  const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
1626
- at.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'center' });
1680
+ frame(at, { block: 'center', foot: reviewInset, behavior: reduce ? 'instant' : 'smooth' });
1627
1681
  return true;
1628
1682
  }
1629
1683
  /** Whether the open card item `id` is drawn. */
@@ -1658,9 +1712,9 @@
1658
1712
  if (!rects.length) return false;
1659
1713
  const { top, bottom } = pane();
1660
1714
  const room = (spacePx(rootEl, 1) ?? 0) * CARD_ROOM;
1715
+ const band = { top, bottom: bottom - reviewInset - room };
1661
1716
  return (
1662
- Math.min(...rects.map((r) => r.top)) >= top &&
1663
- Math.max(...rects.map((r) => r.bottom)) <= bottom - reviewInset - room
1717
+ (framedTop(els, band) ?? top) >= top && Math.max(...rects.map((r) => r.bottom)) <= band.bottom
1664
1718
  );
1665
1719
  }
1666
1720
  /** Whether any of the item `id` shows in that view, which is where its answer card stands.
@@ -1849,15 +1903,21 @@
1849
1903
  const path =
1850
1904
  other === item ? steps : leafTargetFor((other as FieldProposal).field)?.steps;
1851
1905
  if (!otherKey || fieldKeyToString(otherKey) !== leaf || !path) continue;
1852
- const located = locate(held.value, path, other as FieldProposal, claimed);
1906
+ const located = locate(
1907
+ held.value,
1908
+ path,
1909
+ other as FieldProposal,
1910
+ claimed,
1911
+ reviewing.later(other.id)
1912
+ );
1853
1913
  if (other === item) {
1854
1914
  found = located.steps;
1855
1915
  break;
1856
1916
  }
1857
1917
  }
1858
1918
  if (!found) continue;
1859
- held.value = putsIn(item as FieldProposal)
1860
- ? valueInserting(held.value, found, (item as FieldProposal).after)
1919
+ held.value = putsIn(item as FieldProposal, found)
1920
+ ? valueInserting(held.value, found, membersOf(item as FieldProposal))
1861
1921
  : valueWith(held.value, found, reviewing.writes(item, valueIn(held.value, found)));
1862
1922
  }
1863
1923
  held.ids.push(id);
@@ -1972,6 +2032,7 @@
1972
2032
  {@attach tooltips}
1973
2033
  onkeydowncapture={onTyped}
1974
2034
  onpointerdowncapture={onPick}
2035
+ onfocusin={onArrive}
1975
2036
  onkeydown={raiseGuidance}
1976
2037
  ondragover={refuseFiles}
1977
2038
  ondrop={refuseFiles}
@@ -2526,13 +2587,8 @@
2526
2587
  }
2527
2588
  .qm-review-card-add-text {
2528
2589
  margin: 0;
2529
- color: var(--_qm-ink-label);
2530
2590
  white-space: pre-line;
2531
- display: -webkit-box;
2532
- -webkit-line-clamp: 3;
2533
- line-clamp: 3;
2534
- -webkit-box-orient: vertical;
2535
- overflow: hidden;
2591
+ overflow-wrap: anywhere;
2536
2592
  }
2537
2593
  @media (forced-colors: active) {
2538
2594
  .qm-review-card-add {
@@ -9,7 +9,7 @@ export { editorShortcuts } from '../core/codec/index.js';
9
9
  export type { EditorShortcut, ShortcutScope } from '../core/codec/index.js';
10
10
  export type { BlockProposal, CardProposal, FieldProposal, ReviewDrawn, ReviewEvent, ReviewItem, ReviewLabel, ReviewProjection, ReviewUndrawn } from './review.js';
11
11
  export type { BlockPlace } from '../core/codec/index.js';
12
- export { proposalsBetween } from './proposals.js';
12
+ export { proposalsBetween, reviewRevised } from './proposals.js';
13
13
  export type { Proposed, ProposalsOpts } from './proposals.js';
14
14
  export type { ReviewAction } from '../core/codec/index.js';
15
15
  export { REVIEW_KEYS } from '../core/codec/index.js';
@@ -25,7 +25,7 @@ export { DEFAULT_VISUAL_STRINGS } from './strings.js';
25
25
  // The prose leaf's shortcuts, for a host's shortcut list: read off the keymaps' own tables and
26
26
  // worded by the same `strings` (pass the editor's, or none for the package's English).
27
27
  export { editorShortcuts } from '../core/codec/index.js';
28
- export { proposalsBetween } from './proposals.js';
28
+ export { proposalsBetween, reviewRevised } from './proposals.js';
29
29
  export { REVIEW_KEYS } from '../core/codec/index.js';
30
30
  // The `$ext.editor` write unit. A consumer seeding editor-side chrome
31
31
  // state (a card title, the tips channel) goes through this rather than `storeExt`,
@@ -42,3 +42,12 @@ export interface ProposalsOpts {
42
42
  mint?: () => string;
43
43
  label?: (item: Readonly<ReviewItem>) => ReviewLabel | undefined;
44
44
  }
45
+ /**
46
+ * `items` naming the blocks of `now`, a whole-document revise of `was`, such as a return from
47
+ * editing the document as Markdown. A revise keeps a field's first id on whichever block it puts
48
+ * first, so a block written above the first takes its id and the first block moves under a new
49
+ * one. An item naming that id, to rewrite the block or to add beside it, names the new one, where
50
+ * the first block stands as {@link proposalsBetween} reads a block put above it. Every other item
51
+ * is as it was, and so is every id a revise keeps on its block.
52
+ */
53
+ export declare function reviewRevised(items: readonly ReviewItem[], was: Document, now: Document): ReviewItem[];
@@ -1,6 +1,6 @@
1
- import { fieldPathForAddr } from '../core/address.js';
1
+ import { addrForFieldPath, fieldPathForAddr } from '../core/address.js';
2
2
  import { asContent, lineRuns } from '../core/codec/value-plan.js';
3
- import { sameValue } from './review.js';
3
+ import { byBlocks, sameValue } from './review.js';
4
4
  import { VARIANT_DISCRIMINANT, baseType, fieldValues, textKind } from './structure.js';
5
5
  let minted = 0;
6
6
  /**
@@ -59,7 +59,7 @@ export function proposalsBetween(quill, base, answer, opts = {}) {
59
59
  };
60
60
  const blocks = (field, from, fromAddr, to, toAddr) => {
61
61
  const was = blocksOf(from, fromAddr);
62
- const now = blocksOf(to, toAddr);
62
+ const now = leading(was, blocksOf(to, toAddr));
63
63
  const nowById = new Map(now.map((b) => [b.id, b]));
64
64
  for (const b of was) {
65
65
  const next = nowById.get(b.id);
@@ -231,6 +231,87 @@ const addrOf = (card, field) => ({
231
231
  ...(card !== undefined && { card }),
232
232
  ...(field !== undefined && { field })
233
233
  });
234
+ /**
235
+ * `now` with the first block's id on the block that is the first block read: a rewrite keeps that
236
+ * id on whichever block it puts first, so blocks added above the first read as its rewrite. The
237
+ * block put first then takes an id `was` does not hold, so it and those after it up to that block
238
+ * are added before it.
239
+ */
240
+ function leading(was, now) {
241
+ const at = heir(was, now);
242
+ if (!at)
243
+ return now;
244
+ const first = was[0].id;
245
+ const held = new Set(was.map((b) => b.id));
246
+ let added = `${first}+`;
247
+ while (held.has(added))
248
+ added += '+';
249
+ return now.map((b, i) => (i === 0 ? { ...b, id: added } : i === at ? { ...b, id: first } : b));
250
+ }
251
+ /**
252
+ * The index in `now` of the block that is `was`'s first block where a rewrite put others above it,
253
+ * `0` where it stands first. Of the blocks ahead of the next one `now` keeps, the first reading as
254
+ * the first block did is it, or, where the block put first is of another kind, the first of the
255
+ * first block's kind.
256
+ */
257
+ function heir(was, now) {
258
+ const first = was[0];
259
+ if (!first || now[0]?.id !== first.id || now[0].markdown === first.markdown)
260
+ return 0;
261
+ const held = new Set(was.map((b) => b.id));
262
+ let end = 1;
263
+ while (end < now.length && !held.has(now[end].id))
264
+ end++;
265
+ const ahead = now.slice(1, end);
266
+ return (ahead.findIndex((b) => b.markdown === first.markdown) + 1 ||
267
+ (now[0].kind !== first.kind && ahead.findIndex((b) => b.kind === first.kind) + 1) ||
268
+ 0);
269
+ }
270
+ /**
271
+ * `items` naming the blocks of `now`, a whole-document revise of `was`, such as a return from
272
+ * editing the document as Markdown. A revise keeps a field's first id on whichever block it puts
273
+ * first, so a block written above the first takes its id and the first block moves under a new
274
+ * one. An item naming that id, to rewrite the block or to add beside it, names the new one, where
275
+ * the first block stands as {@link proposalsBetween} reads a block put above it. Every other item
276
+ * is as it was, and so is every id a revise keeps on its block.
277
+ */
278
+ export function reviewRevised(items, was, now) {
279
+ const moves = new Map();
280
+ const moveOf = (item) => {
281
+ const key = `${item.card ?? ''} ${item.field}`;
282
+ if (moves.has(key))
283
+ return moves.get(key);
284
+ let move;
285
+ const addr = addrForFieldPath(item.field);
286
+ if (addr) {
287
+ const at = item.card === undefined ? addr : { ...addr, card: item.card };
288
+ const before = blocksOf(was, at);
289
+ const after = blocksOf(now, at);
290
+ const k = heir(before, after);
291
+ if (k)
292
+ move = [before[0].id, after[k].id];
293
+ }
294
+ moves.set(key, move);
295
+ return move;
296
+ };
297
+ return items.map((item) => {
298
+ if (!byBlocks(item))
299
+ return item;
300
+ const move = moveOf(item);
301
+ if (!move)
302
+ return item;
303
+ const moved = (id) => (id === move[0] ? move[1] : id);
304
+ if ('replace' in item)
305
+ return { ...item, replace: item.replace.map(moved) };
306
+ const at = item.insert;
307
+ if (at === 'end')
308
+ return item;
309
+ return {
310
+ ...item,
311
+ insert: 'after' in at ? { after: moved(at.after) } : { before: moved(at.before) }
312
+ };
313
+ });
314
+ }
234
315
  /** The blocks of the value at `addr`, none where it holds none. */
235
316
  function blocksOf(doc, addr) {
236
317
  try {
@@ -18,7 +18,9 @@ import { type BlockPlace, type ReviewAction } from '../core/codec/index.js';
18
18
  * its writer read. A path to a place inside a record or a
19
19
  * list names that place: a cell, or a member by its index, which `after` absent takes out
20
20
  * and an index past the last appends. One with `ahead` puts the members `after` holds in
21
- * front of `ahead`, the member its writer read at that index.
21
+ * front of `ahead`, the member its writer read at that index. A member named with no `before`
22
+ * read nothing there, so it is new: it appends, and the appends of one list stand in their
23
+ * indices' order whichever is taken first.
22
24
  * - `add` or `remove`: a whole card, proposed new or proposed taken out (`CardProposal`).
23
25
  *
24
26
  * A `field` on a card names the card by its index, read against the cards as they stood when
@@ -157,8 +159,11 @@ export type FieldProposal = {
157
159
  * read the list at the path's index; `after` then holds the members, in order. */
158
160
  ahead?: unknown;
159
161
  };
160
- /** Whether a field item puts new members into a list in front of one it holds. */
161
- export declare const putsIn: (item: FieldProposal) => boolean;
162
+ /** Whether a field item at `steps` puts new members into a list: in front of one it holds
163
+ * (`ahead`), or as a member it names by an index and read nothing at, which appends. */
164
+ export declare const putsIn: (item: FieldProposal, steps: readonly PathStep[]) => boolean;
165
+ /** The members an item that puts some into a list adds, in order. */
166
+ export declare const membersOf: (item: FieldProposal) => unknown[];
162
167
  /** A field item routed past its field: the steps from the rung it is handed to down to the
163
168
  * value it names, a member of a list by its index, a cell of a record by its key. */
164
169
  export interface DeepReview {
@@ -178,15 +183,19 @@ export declare function valueIn(value: unknown, steps: readonly PathStep[]): unk
178
183
  export declare function valueWith(value: unknown, steps: readonly PathStep[], to: unknown): unknown;
179
184
  /** `value` with `members` put into the list `steps` reach, in front of the member at its last
180
185
  * step, or at its end past the last. */
181
- export declare function valueInserting(value: unknown, steps: readonly PathStep[], members: unknown): unknown;
186
+ export declare function valueInserting(value: unknown, steps: readonly PathStep[], members: readonly unknown[]): unknown;
182
187
  /**
183
188
  * Where a field proposal's steps land in `value` as it stands. A list's member is found by its
184
189
  * index where it holds `before`, else as the nearest member holding `before` that `claimed`
185
190
  * does not already hold, so one member taken out does not move another's proposal onto the
186
191
  * wrong row. An insert lands in front of the nearest member holding its `ahead`, and claims
187
192
  * none. `found` is false where the proposal has a `before` or an `ahead` nothing holds.
193
+ *
194
+ * An append lands at the list's end, in front of the members at its end that `later` holds in
195
+ * order: what the appends of its run at higher indices add, so appends taken in any order
196
+ * stand in their indices' order.
188
197
  */
189
- export declare function locate(value: unknown, steps: readonly PathStep[], item: FieldProposal, claimed: Set<string>): {
198
+ export declare function locate(value: unknown, steps: readonly PathStep[], item: FieldProposal, claimed: Set<string>, later?: readonly unknown[]): {
190
199
  steps: readonly PathStep[];
191
200
  found: boolean;
192
201
  };
@@ -11,8 +11,12 @@ export const NO_PROJECTION = {
11
11
  toProjection: (at) => at,
12
12
  toLive: (at) => at
13
13
  };
14
- /** Whether a field item puts new members into a list in front of one it holds. */
15
- export const putsIn = (item) => 'ahead' in item;
14
+ /** Whether a field item at `steps` puts new members into a list: in front of one it holds
15
+ * (`ahead`), or as a member it names by an index and read nothing at, which appends. */
16
+ export const putsIn = (item, steps) => 'ahead' in item ||
17
+ (typeof steps.at(-1) === 'number' && !('before' in item) && item.after !== undefined);
18
+ /** The members an item that puts some into a list adds, in order. */
19
+ export const membersOf = (item) => 'ahead' in item && Array.isArray(item.after) ? item.after : [item.after];
16
20
  /** One rung of a nested item's walk: the items naming this rung's own value, and the rest by
17
21
  * the step they take next, that step consumed. */
18
22
  export function splitReview(list) {
@@ -73,7 +77,7 @@ export function valueInserting(value, steps, members) {
73
77
  const held = valueIn(value, head);
74
78
  const list = Array.isArray(held) ? [...held] : [];
75
79
  const at = steps.at(-1);
76
- list.splice(typeof at === 'number' ? Math.min(at, list.length) : list.length, 0, ...(Array.isArray(members) ? members : [members]));
80
+ list.splice(typeof at === 'number' ? Math.min(at, list.length) : list.length, 0, ...members);
77
81
  return valueWith(value, head, list);
78
82
  }
79
83
  /**
@@ -82,8 +86,12 @@ export function valueInserting(value, steps, members) {
82
86
  * does not already hold, so one member taken out does not move another's proposal onto the
83
87
  * wrong row. An insert lands in front of the nearest member holding its `ahead`, and claims
84
88
  * none. `found` is false where the proposal has a `before` or an `ahead` nothing holds.
89
+ *
90
+ * An append lands at the list's end, in front of the members at its end that `later` holds in
91
+ * order: what the appends of its run at higher indices add, so appends taken in any order
92
+ * stand in their indices' order.
85
93
  */
86
- export function locate(value, steps, item, claimed) {
94
+ export function locate(value, steps, item, claimed, later = []) {
87
95
  const read = 'before' in item;
88
96
  const before = read ? item.before : undefined;
89
97
  const at = steps.at(-1);
@@ -93,7 +101,15 @@ export function locate(value, steps, item, claimed) {
93
101
  claimed.add(JSON.stringify(out));
94
102
  return out;
95
103
  };
96
- if (putsIn(item)) {
104
+ if (putsIn(item, steps) && !('ahead' in item)) {
105
+ const members = Array.isArray(list) ? list : [];
106
+ let i = members.length;
107
+ for (const member of [...later].reverse())
108
+ if (i > 0 && sameValue(members[i - 1], member))
109
+ i--;
110
+ return { steps: [...head, i], found: true };
111
+ }
112
+ if ('ahead' in item) {
97
113
  if (typeof at !== 'number' || !Array.isArray(list))
98
114
  return { steps, found: false };
99
115
  for (let d = 0; d <= Math.max(at, list.length - 1 - at); d++)
@@ -52,6 +52,8 @@ export interface Review {
52
52
  more?: readonly FieldProposal[];
53
53
  nested?: readonly DeepReview[];
54
54
  };
55
+ /** What the appends of item `id`'s run at higher indices add, in index order (`locate`). */
56
+ later(id: string): readonly unknown[];
55
57
  /** Whether anything draws at leaf `key`: a field's own item, or a text item in its leaf. */
56
58
  marks(key: string): boolean;
57
59
  /** The leaf drawing item `id`, where one does. */