@quillmark/svelte 0.38.1 → 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.
package/README.md CHANGED
@@ -2,6 +2,8 @@
2
2
 
3
3
  Editor + live-preview components for [Quillmark](https://github.com/borb-sh/quillmark) WASM consumers. A WYSIWYG **VisualEditor**, and a canvas **Preview** that paints the compiled document and round-trips clicks to the editor, over one `@quillmark/wasm` session. Vanilla-TS cores with thin Svelte 5 wrappers.
4
4
 
5
+ Quillmark is pre-1.0. Its [stability statement](https://github.com/borb-sh/quillmark#status) says what any release can change and what every release keeps.
6
+
5
7
  ## Install
6
8
 
7
9
  ```sh
@@ -96,8 +96,7 @@ export interface CreateFieldOpts {
96
96
  onReview?(id: string, action: ReviewAction): void;
97
97
  /** The leaf is writing a taken proposal, and is done: the commit between is the answer's. */
98
98
  onReviewWriting?(on: boolean): void;
99
- /** The review item holding the caret, `undefined` once it has left. The report holds off
100
- * while the reader types inside the item. */
99
+ /** The review item the caret names, `undefined` once it has left one (`review-caret.ts`). */
101
100
  onReviewPoint?(id: string | undefined): void;
102
101
  /** What the leaf draws of the review items, on each change: the ids drawn, and the items
103
102
  * whose anchor the leaf holds that it does not draw, each with why. An item whose anchor
@@ -32,7 +32,8 @@ import { DEFAULT_LEAVE_STRINGS, leavePlugin } from './leave.js';
32
32
  import { FIELD_KEYS, markKeymap } from './shortcuts.js';
33
33
  import { remoteKey } from './remote.js';
34
34
  import { renameBlocks, reviewLayer } from './review.js';
35
- import { valueDiffPlugin } from './value-diff.js';
35
+ import { valueDiffPlugin, valueSpans } from './value-diff.js';
36
+ import { reviewCaretPlugin } from './review-caret.js';
36
37
  import { blockSchema, isBlockSchema, isInlineSchema, isParagraphsSchema, leafSchema } from './schema.js';
37
38
  import { linkPastePlugin } from './link-paste.js';
38
39
  import { dragMovePlugin } from './drag-move.js';
@@ -284,11 +285,17 @@ export function createField(opts) {
284
285
  },
285
286
  act: (id, action) => opts.onReview?.(id, action),
286
287
  writing: (on) => opts.onReviewWriting?.(on),
287
- point: (id) => opts.onReviewPoint?.(id),
288
288
  drew: (report) => opts.onReviewDrawn?.(report)
289
289
  });
290
290
  let valueProposals = [];
291
291
  const valueDiff = valueDiffPlugin(() => valueProposals, (id, state) => opts.onValuePlanned?.(id, state));
292
+ const reviewCaret = reviewCaretPlugin({
293
+ spans: (state) => [...(review?.spans(state) ?? []), ...valueSpans(state, valueProposals)],
294
+ entered: (state) => review?.entered(state),
295
+ litHere: () => valueProposals.some((p) => p.lit) ||
296
+ (reviewLit !== undefined && reviewItems.some((item) => item.id === reviewLit)),
297
+ point: (id) => opts.onReviewPoint?.(id)
298
+ });
292
299
  // The menu's report channel; the vocabulary is the codec's own constant (`slash.ts`).
293
300
  const slash = block ? opts.onSlash : undefined;
294
301
  // Judged of the value being mounted rather than read off a diagnostic: a routed set
@@ -414,7 +421,12 @@ export function createField(opts) {
414
421
  placeholder: () => placeholderText,
415
422
  placeholderUntilEdit: opts.placeholderUntilEdit,
416
423
  cap: opts.cap,
417
- afterHistory: [anchorPlugin(seededAnchors), ...(review ? [review.plugin] : []), valueDiff]
424
+ afterHistory: [
425
+ anchorPlugin(seededAnchors),
426
+ ...(review ? [review.plugin] : []),
427
+ valueDiff,
428
+ reviewCaret
429
+ ]
418
430
  })
419
431
  });
420
432
  return { state: built, index: seedIndex };
@@ -0,0 +1,30 @@
1
+ import { Plugin, type EditorState } from 'prosemirror-state';
2
+ import type { Node as PMNode } from 'prosemirror-model';
3
+ /** A change the leaf draws, by the stretch of the document the caret names it from. */
4
+ export interface CaretSpan {
5
+ id: string;
6
+ from: number;
7
+ to: number;
8
+ /** It only adds after what it covers: a rewrite of the same stretch is named first. */
9
+ adds?: boolean;
10
+ }
11
+ /** `spans` widened to the whole lines they touch, so a caret anywhere on a changed line is in
12
+ * its change. */
13
+ export declare function widened(doc: PMNode, spans: readonly CaretSpan[]): CaretSpan[];
14
+ /** The change holding `pos`: the one the caret was put into by id while it stays, else the
15
+ * narrowest, a rewrite before what only adds. */
16
+ export declare function changeAt(spans: readonly CaretSpan[], pos: number, entered?: string): CaretSpan | undefined;
17
+ /** The change nearest `pos`: the fewest lines away, then a rewrite before what only adds, then
18
+ * the fewest positions away, then the one above. */
19
+ export declare function nearestChange(doc: PMNode, spans: readonly CaretSpan[], pos: number): CaretSpan | undefined;
20
+ export interface ReviewCaret {
21
+ /** The changes the leaf draws, by the stretches they stand on. */
22
+ spans(state: EditorState): readonly CaretSpan[];
23
+ /** The item the caret was put into by its id, while it stays where it was put. */
24
+ entered(state: EditorState): string | undefined;
25
+ /** Whether the current item is one the leaf draws. */
26
+ litHere(): boolean;
27
+ /** The item the caret names, `undefined` once it has left one. */
28
+ point(id: string | undefined): void;
29
+ }
30
+ export declare function reviewCaretPlugin(caret: ReviewCaret): Plugin<number>;
@@ -0,0 +1,195 @@
1
+ // Which review item a leaf's caret names. The reader arriving in the leaf, by a press or by
2
+ // the focus coming from elsewhere on the page, names the change on the caret's line, else the
3
+ // nearest change in the leaf, unless the current item is one of the leaf's already; the caret
4
+ // moving within the leaf names a change only on arriving at one. Typing names nothing: the item
5
+ // typed in stays quiet until the caret has left it.
6
+ import { Plugin, PluginKey } from 'prosemirror-state';
7
+ import { remoteKey } from './remote.js';
8
+ /** The lines of `doc`, in order: each textblock, cut at its hard breaks. */
9
+ function linesOf(doc) {
10
+ const lines = [];
11
+ doc.descendants((node, pos) => {
12
+ if (!node.isTextblock)
13
+ return true;
14
+ let from = pos + 1;
15
+ node.forEach((child, offset) => {
16
+ if (child.type.name !== 'hard_break')
17
+ return;
18
+ lines.push({ from, to: pos + 1 + offset });
19
+ from = pos + 1 + offset + child.nodeSize;
20
+ });
21
+ lines.push({ from, to: pos + node.nodeSize - 1 });
22
+ return false;
23
+ });
24
+ return lines;
25
+ }
26
+ /** The index of the line holding `pos`, the nearest before it between lines. */
27
+ function lineAt(lines, pos) {
28
+ let at = 0;
29
+ while (at + 1 < lines.length && lines[at + 1].from <= pos)
30
+ at++;
31
+ return at;
32
+ }
33
+ /** `spans` widened to the whole lines they touch, so a caret anywhere on a changed line is in
34
+ * its change. */
35
+ export function widened(doc, spans) {
36
+ const lines = linesOf(doc);
37
+ if (!lines.length)
38
+ return [...spans];
39
+ return spans.map((s) => ({
40
+ ...s,
41
+ from: Math.min(s.from, lines[lineAt(lines, s.from)].from),
42
+ to: Math.max(s.to, lines[lineAt(lines, s.to)].to)
43
+ }));
44
+ }
45
+ /** The change holding `pos`: the one the caret was put into by id while it stays, else the
46
+ * narrowest, a rewrite before what only adds. */
47
+ export function changeAt(spans, pos, entered) {
48
+ let best;
49
+ for (const s of spans) {
50
+ if (s.from > pos || pos > s.to)
51
+ continue;
52
+ if (s.id === entered)
53
+ return s;
54
+ const size = s.to - s.from;
55
+ const held = best && best.to - best.from;
56
+ if (!best || size < held || (size === held && best.adds && !s.adds))
57
+ best = s;
58
+ }
59
+ return best;
60
+ }
61
+ /** The change nearest `pos`: the fewest lines away, then a rewrite before what only adds, then
62
+ * the fewest positions away, then the one above. */
63
+ export function nearestChange(doc, spans, pos) {
64
+ const lines = linesOf(doc);
65
+ const line = lineAt(lines, pos);
66
+ const rank = (s) => {
67
+ const first = lineAt(lines, s.from);
68
+ const last = lineAt(lines, s.to);
69
+ const away = line < first ? first - line : line > last ? line - last : 0;
70
+ const chars = pos < s.from ? s.from - pos : pos > s.to ? pos - s.to : 0;
71
+ return [away, s.adds ? 1 : 0, chars, s.from];
72
+ };
73
+ let best;
74
+ let bestRank = [];
75
+ for (const s of spans) {
76
+ const r = rank(s);
77
+ const i = r.findIndex((v, n) => v !== bestRank[n]);
78
+ if (!best || (i >= 0 && r[i] < bestRank[i])) {
79
+ best = s;
80
+ bestRank = r;
81
+ }
82
+ }
83
+ return best;
84
+ }
85
+ const caretKey = new PluginKey('qm-review-caret');
86
+ /** Whether a focus coming from `from` is the reader arriving in the leaf: from elsewhere on the
87
+ * page, not handed back from a surface floating over the text. */
88
+ const arriving = (from) => from instanceof Element && !from.closest('.qm-popover-surface');
89
+ export function reviewCaretPlugin(caret) {
90
+ /** The item last named from inside a change, `undefined` outside one. */
91
+ let named;
92
+ /** The item the reader typed in, quiet until the caret has left it. */
93
+ let muted;
94
+ /** A press is down in the leaf: the caret it places names once it is up. */
95
+ let pressing = false;
96
+ const spansOf = (state) => widened(state.doc, caret.spans(state));
97
+ /** The caret moved, or the reader typed: an arrival at a change names it. */
98
+ const follow = (view, typed) => {
99
+ const { selection } = view.state;
100
+ const at = view.hasFocus() && selection.empty
101
+ ? changeAt(spansOf(view.state), selection.head, caret.entered(view.state))?.id
102
+ : undefined;
103
+ if (at !== muted)
104
+ muted = undefined;
105
+ if (typed && at)
106
+ muted = at;
107
+ const next = at === muted ? undefined : at;
108
+ if (next === named)
109
+ return;
110
+ named = next;
111
+ caret.point(next);
112
+ };
113
+ /** The reader arrived in the leaf: the change on the caret's line, else, the current item
114
+ * being another leaf's, the nearest change here. */
115
+ const arrive = (view) => {
116
+ if (view.isDestroyed || !view.hasFocus())
117
+ return;
118
+ const { state } = view;
119
+ const spans = spansOf(state);
120
+ const head = state.selection.head;
121
+ const at = changeAt(spans, head, caret.entered(state));
122
+ muted = undefined;
123
+ if (at) {
124
+ named = at.id;
125
+ caret.point(at.id);
126
+ return;
127
+ }
128
+ named = undefined;
129
+ if (caret.litHere())
130
+ return;
131
+ const near = nearestChange(state.doc, spans, head);
132
+ if (near)
133
+ caret.point(near.id);
134
+ };
135
+ /** Hold the caret's report until the press at `view` is up, then arrive, or not where it
136
+ * was cancelled or the press was on a change, which names that change itself. */
137
+ const press = (view, onChange) => {
138
+ pressing = true;
139
+ const end = (event) => {
140
+ window.removeEventListener('pointerup', end, true);
141
+ window.removeEventListener('pointercancel', end, true);
142
+ pressing = false;
143
+ if (event.type === 'pointerup' && !onChange)
144
+ setTimeout(() => arrive(view));
145
+ };
146
+ window.addEventListener('pointerup', end, true);
147
+ window.addEventListener('pointercancel', end, true);
148
+ };
149
+ return new Plugin({
150
+ key: caretKey,
151
+ state: {
152
+ init: () => 0,
153
+ apply: (tr, edits) => (tr.docChanged && !tr.getMeta(remoteKey) ? edits + 1 : edits)
154
+ },
155
+ props: {
156
+ handleDOMEvents: {
157
+ pointerdown: (view, event) => {
158
+ if (event.button !== 0 || pressing)
159
+ return false;
160
+ const target = event.target instanceof Element ? event.target : null;
161
+ press(view, !!target?.closest('[data-qm-review]'));
162
+ return false;
163
+ },
164
+ focus: (view, event) => {
165
+ if (pressing)
166
+ return false;
167
+ if (arriving(event.relatedTarget))
168
+ arrive(view);
169
+ else
170
+ follow(view, false);
171
+ return false;
172
+ },
173
+ blur: (view) => {
174
+ // The focus has not left yet when a blur fires.
175
+ queueMicrotask(() => {
176
+ if (!view.isDestroyed)
177
+ follow(view, false);
178
+ });
179
+ return false;
180
+ }
181
+ }
182
+ },
183
+ view: () => ({
184
+ update(view, prev) {
185
+ if (pressing)
186
+ return;
187
+ follow(view, caretKey.getState(prev) !== caretKey.getState(view.state));
188
+ },
189
+ destroy() {
190
+ if (named !== undefined)
191
+ caret.point(undefined);
192
+ }
193
+ })
194
+ });
195
+ }
@@ -2,6 +2,7 @@ import { type Node as PMNode } from 'prosemirror-model';
2
2
  import { Plugin, type EditorState, type Transaction } from 'prosemirror-state';
3
3
  import { Mapping } from 'prosemirror-transform';
4
4
  import { type EditorView } from 'prosemirror-view';
5
+ import type { CaretSpan } from './review-caret.js';
5
6
  /**
6
7
  * One proposal over a prose leaf, by the blocks that place it.
7
8
  *
@@ -50,8 +51,6 @@ export interface ReviewChannel {
50
51
  act(id: string, action: ReviewAction): void;
51
52
  /** The leaf is writing a taken proposal, and is done. */
52
53
  writing?(on: boolean): void;
53
- /** The item the caret is in, `undefined` once it has left. */
54
- point(id: string | undefined): void;
55
54
  /** What the leaf draws and what it holds and does not draw, on each change of either. */
56
55
  drew(report: ReviewReport): void;
57
56
  }
@@ -99,6 +98,10 @@ export interface ReviewLayer {
99
98
  refresh(view: EditorView): void;
100
99
  /** The elements item `id` draws, in document order. */
101
100
  elements(view: EditorView, id: string): HTMLElement[];
101
+ /** What each item drawn stands on, where the caret names it from (`review-caret.ts`). */
102
+ spans(state: EditorState): readonly CaretSpan[];
103
+ /** The item the caret was put into by its id, while it stays where it was put. */
104
+ entered(state: EditorState): string | undefined;
102
105
  /** Put the caret in item `id` and take the focus. False for an item the leaf does not
103
106
  * draw. */
104
107
  enter(view: EditorView, id: string): boolean;
@@ -116,7 +119,6 @@ export interface ReviewLayer {
116
119
  }
117
120
  /**
118
121
  * The leaf's review layer. The decorations are a function of the document and the channel's
119
- * items, kept until one of them moves. The caret's report holds off while the reader
120
- * types inside an item: an item is news on arriving in it, and noise under every keystroke.
122
+ * items, kept until one of them moves.
121
123
  */
122
124
  export declare function reviewLayer(channel: ReviewChannel): ReviewLayer;
@@ -21,7 +21,6 @@ import { Plugin, PluginKey, Selection } from 'prosemirror-state';
21
21
  import { Mapping, Step, StepResult } from 'prosemirror-transform';
22
22
  import { Decoration, DecorationSet } from 'prosemirror-view';
23
23
  import { arriving, HARD_BREAK, ISLAND_SLOT } from './islands.js';
24
- import { remoteKey } from './remote.js';
25
24
  import { wordDiff } from './review-diff.js';
26
25
  const reviewKey = new PluginKey('quill-review');
27
26
  /** Tell the review layer the store took blocks under new ids, each `[was, now]`. */
@@ -78,8 +77,6 @@ function answering(state, id, to) {
78
77
  }
79
78
  function applyReview(tr, state) {
80
79
  let next = state.replayed.length ? { ...state, replayed: [] } : state;
81
- if (tr.docChanged && !tr.getMeta(remoteKey))
82
- next = { ...next, edits: next.edits + 1 };
83
80
  const history = isHistoryTransaction(tr);
84
81
  tr.steps.forEach((step) => {
85
82
  if (!(step instanceof ReviewAnswer))
@@ -681,27 +678,9 @@ function listPlace($last, last, list, nest) {
681
678
  const item = items[level];
682
679
  return $last.node(item - 1).type === list.type ? { at: $last.after(item) } : undefined;
683
680
  }
684
- /** The item the caret is in: the one it was put into by its id while it holds the caret, else
685
- * the one that holds it closest, so of a proposal that rewrites a paragraph and one that adds
686
- * after it, the one that rewrites. */
687
- function spanAt(spans, pos, entered) {
688
- let best;
689
- for (const s of spans) {
690
- if (s.from > pos || pos > s.to)
691
- continue;
692
- if (s.id === entered)
693
- return s;
694
- const size = s.to - s.from;
695
- const held = best && best.to - best.from;
696
- if (!best || size < held || (size === held && best.adds && !s.adds))
697
- best = s;
698
- }
699
- return best;
700
- }
701
681
  /**
702
682
  * The leaf's review layer. The decorations are a function of the document and the channel's
703
- * items, kept until one of them moves. The caret's report holds off while the reader
704
- * types inside an item: an item is news on arriving in it, and noise under every keystroke.
683
+ * items, kept until one of them moves.
705
684
  */
706
685
  export function reviewLayer(channel) {
707
686
  let memo;
@@ -775,30 +754,10 @@ export function reviewLayer(channel) {
775
754
  reported = joined;
776
755
  channel.drew(next);
777
756
  };
778
- let caret;
779
- /** The item the reader typed in, quiet until the caret has left it. */
780
- let muted;
781
- const follow = (view, typed) => {
782
- const { selection } = view.state;
783
- const at = view.hasFocus() && selection.empty
784
- ? spanAt(drawn(view.state).spans, selection.head, reviewKey.getState(view.state)?.entered)
785
- ?.id
786
- : undefined;
787
- if (at !== muted)
788
- muted = undefined;
789
- if (typed && at)
790
- muted = at;
791
- const next = at === muted ? undefined : at;
792
- if (next === caret)
793
- return;
794
- caret = next;
795
- channel.point(next);
796
- };
797
757
  const plugin = new Plugin({
798
758
  key: reviewKey,
799
759
  state: {
800
760
  init: () => ({
801
- edits: 0,
802
761
  answered: new Map(),
803
762
  entered: undefined,
804
763
  replayed: [],
@@ -807,21 +766,7 @@ export function reviewLayer(channel) {
807
766
  apply: applyReview
808
767
  },
809
768
  props: {
810
- decorations,
811
- handleDOMEvents: {
812
- focus: (view) => {
813
- follow(view, false);
814
- return false;
815
- },
816
- blur: (view) => {
817
- // The focus has not left yet when a blur fires.
818
- queueMicrotask(() => {
819
- if (!view.isDestroyed)
820
- follow(view, false);
821
- });
822
- return false;
823
- }
824
- }
769
+ decorations
825
770
  },
826
771
  view: (view) => {
827
772
  host = view;
@@ -833,11 +778,8 @@ export function reviewLayer(channel) {
833
778
  for (const { id, to } of review.replayed)
834
779
  channel.act(id, to ?? 'reopen');
835
780
  report(view.state);
836
- follow(view, reviewKey.getState(prev)?.edits !== reviewKey.getState(view.state)?.edits);
837
781
  },
838
782
  destroy() {
839
- if (caret !== undefined)
840
- channel.point(undefined);
841
783
  if (reported !== NOTHING)
842
784
  channel.drew({ ids: [], outdated: [], undrawn: [] });
843
785
  host = undefined;
@@ -878,6 +820,8 @@ export function reviewLayer(channel) {
878
820
  },
879
821
  undo: (view) => undo(view.state, view.dispatch),
880
822
  project: (state) => projecting(state, drawn(state), (at) => at === state ? drawn(state) : draw(at, channel, new Map(bases))),
823
+ spans: (state) => drawn(state).spans,
824
+ entered: (state) => reviewKey.getState(state)?.entered,
881
825
  enter(view, id) {
882
826
  const span = drawn(view.state).spans.find((s) => s.id === id);
883
827
  if (!span)
@@ -1,5 +1,6 @@
1
- import { Plugin, PluginKey } from 'prosemirror-state';
1
+ import { Plugin, PluginKey, type EditorState } from 'prosemirror-state';
2
2
  import type { Content } from '@quillmark/wasm';
3
+ import type { CaretSpan } from './review-caret.js';
3
4
  /** A field's proposed value as the leaf draws it. */
4
5
  export interface ValueProposal {
5
6
  id: string;
@@ -14,6 +15,8 @@ export interface ValueProposal {
14
15
  * reader's writing, or already read as proposed, so its Accept would write nothing. */
15
16
  export type ValueState = 'open' | 'outdated' | 'applied';
16
17
  export declare const valueDiffKey: PluginKey<void>;
18
+ /** What each proposal that changes the leaf stands on: from its first change to its last. */
19
+ export declare function valueSpans(state: EditorState, proposals: readonly ValueProposal[]): CaretSpan[];
17
20
  /**
18
21
  * The plugin, reading the proposals live: a caller that moves them redraws with `setProps`.
19
22
  * Each is a run of one answer or a whole value, drawn apart. `planned` hears, on each draw, how
@@ -38,6 +38,22 @@ function draw(state, proposals, planned) {
38
38
  const at = (offset) => offsetToPM(index, offset);
39
39
  return DecorationSet.create(state.doc, proposals.flatMap((p) => decorations(state, live, at, p, planned)));
40
40
  }
41
+ /** What each proposal that changes the leaf stands on: from its first change to its last. */
42
+ export function valueSpans(state, proposals) {
43
+ if (!proposals.length)
44
+ return [];
45
+ const scan = scanDoc(state.doc);
46
+ const live = scanContent(scan);
47
+ const index = lineIndexOf(scan);
48
+ return proposals.flatMap((p) => {
49
+ const changes = valueChanges(live, planValue(p.before, live, p.after).merged);
50
+ if (!changes.length)
51
+ return [];
52
+ const from = offsetToPM(index, Math.min(...changes.map((c) => c.at)));
53
+ const to = offsetToPM(index, Math.max(...changes.map((c) => c.end)));
54
+ return [{ id: p.id, from, to }];
55
+ });
56
+ }
41
57
  /** One proposal's marks over the leaf as it reads, `live`. */
42
58
  function decorations(state, live, at, p, planned) {
43
59
  const { merged, outdated } = planValue(p.before, live, p.after);
@@ -0,0 +1,27 @@
1
+ /** A vertical extent in viewport px. */
2
+ export interface Band {
3
+ top: number;
4
+ bottom: number;
5
+ }
6
+ export interface FrameOptions {
7
+ /** `nearest` moves the least that frames the target; `center` centres it where it fits. */
8
+ block: 'nearest' | 'center';
9
+ /** Room held clear at the band's foot, where it is more than the scroller's own `scroll-padding`. */
10
+ foot?: number;
11
+ behavior?: ScrollBehavior;
12
+ }
13
+ /**
14
+ * The scroll, in px down, that frames `target` in `band` with `gap` clear of each edge. `top` is
15
+ * where the field's label starts: kept in the band whenever it fits with the target, the target
16
+ * winning where it does not. Zero for a target already framed, so a landing on the field in view
17
+ * moves nothing.
18
+ */
19
+ export declare function frameDelta(band: Band, target: Band, top: number, gap: number, block: FrameOptions['block']): number;
20
+ /**
21
+ * Scroll `target` into the band its scroller shows, with the label of the field it sits in where
22
+ * the two fit (`frameDelta`). One scroller moves, the nearest: a host page around the editor stays
23
+ * where it is.
24
+ */
25
+ export declare function frame(target: HTMLElement, opts: FrameOptions): void;
26
+ /** The top a landing frames for `els`, its field's label included where it fits in `band`. */
27
+ export declare function framedTop(els: readonly HTMLElement[], band: Band): number | undefined;
@@ -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. */
@@ -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';
@@ -608,7 +609,10 @@
608
609
  const report = reviewing.report;
609
610
  drewOrder = report.open;
610
611
  drewOutdated = report.outdated;
611
- 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
+ }
612
616
  const joined = JSON.stringify(report);
613
617
  if (joined === drewReport) return;
614
618
  drewReport = joined;
@@ -734,14 +738,60 @@
734
738
  function reviewIds(el: Element | null | undefined): string[] {
735
739
  return el?.getAttribute('data-qm-review')?.split(' ').filter(Boolean) ?? [];
736
740
  }
737
- /** 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. */
738
743
  function onPick(e: PointerEvent): void {
739
- 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]'));
740
746
  const id = ids.includes(reviewing.lit ?? '') ? reviewing.lit : ids[0];
741
747
  if (id && reviewing.items.some((item) => item.id === id)) {
742
748
  typing = false;
743
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 };
744
792
  }
793
+ const id = best && reviewIds(best.el).find((id) => open.has(id));
794
+ if (id) reviewing.reveal(id);
745
795
  }
746
796
  /** What the change `id` is to: the field it is drawn in, the body, or the card it adds or
747
797
  * takes out. */
@@ -1477,7 +1527,9 @@
1477
1527
  */
1478
1528
  async function land(found: Landed, pos: number | undefined): Promise<HTMLElement> {
1479
1529
  if (found.steps && found.control.focusPath) {
1480
- 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;
1481
1533
  }
1482
1534
  if (pos != null) {
1483
1535
  const prose = leaves.prose(found.key);
@@ -1487,6 +1539,7 @@
1487
1539
  }
1488
1540
  }
1489
1541
  found.control.focus();
1542
+ frame(found.control.el, { block: 'nearest' });
1490
1543
  return found.control.el;
1491
1544
  }
1492
1545
 
@@ -1516,7 +1569,7 @@
1516
1569
  export async function revealField(field: DocPath): Promise<void> {
1517
1570
  const found = await revealLeaf(field);
1518
1571
  if (!found) return missed(`no mounted field at ${field}`, field);
1519
- found.control.el.scrollIntoView({ block: 'nearest', behavior: 'instant' });
1572
+ frame(found.control.el, { block: 'nearest' });
1520
1573
  bloom(found.control.el);
1521
1574
  }
1522
1575
  /** Play the arrival wash over the field at `field` and touch nothing else: no focus,
@@ -1624,7 +1677,7 @@
1624
1677
  (key !== undefined ? leaves.control(key)?.el : undefined);
1625
1678
  if (!at || (stepping && comfortable(els.length ? els : [at]))) return true;
1626
1679
  const reduce = window.matchMedia?.('(prefers-reduced-motion: reduce)').matches;
1627
- at.scrollIntoView({ behavior: reduce ? 'auto' : 'smooth', block: 'center' });
1680
+ frame(at, { block: 'center', foot: reviewInset, behavior: reduce ? 'instant' : 'smooth' });
1628
1681
  return true;
1629
1682
  }
1630
1683
  /** Whether the open card item `id` is drawn. */
@@ -1659,9 +1712,9 @@
1659
1712
  if (!rects.length) return false;
1660
1713
  const { top, bottom } = pane();
1661
1714
  const room = (spacePx(rootEl, 1) ?? 0) * CARD_ROOM;
1715
+ const band = { top, bottom: bottom - reviewInset - room };
1662
1716
  return (
1663
- Math.min(...rects.map((r) => r.top)) >= top &&
1664
- 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
1665
1718
  );
1666
1719
  }
1667
1720
  /** Whether any of the item `id` shows in that view, which is where its answer card stands.
@@ -1979,6 +2032,7 @@
1979
2032
  {@attach tooltips}
1980
2033
  onkeydowncapture={onTyped}
1981
2034
  onpointerdowncapture={onPick}
2035
+ onfocusin={onArrive}
1982
2036
  onkeydown={raiseGuidance}
1983
2037
  ondragover={refuseFiles}
1984
2038
  ondrop={refuseFiles}
@@ -2533,13 +2587,8 @@
2533
2587
  }
2534
2588
  .qm-review-card-add-text {
2535
2589
  margin: 0;
2536
- color: var(--_qm-ink-label);
2537
2590
  white-space: pre-line;
2538
- display: -webkit-box;
2539
- -webkit-line-clamp: 3;
2540
- line-clamp: 3;
2541
- -webkit-box-orient: vertical;
2542
- overflow: hidden;
2591
+ overflow-wrap: anywhere;
2543
2592
  }
2544
2593
  @media (forced-colors: active) {
2545
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
  /**
@@ -233,30 +233,84 @@ const addrOf = (card, field) => ({
233
233
  });
234
234
  /**
235
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.
237
- *
238
- * Of the blocks ahead of the next one `now` keeps, the first reading as the first block did is it,
239
- * or, where the block put first is of another kind, the first of the first block's kind. The block
240
- * put first then takes an id `was` does not hold, so it and those after it up to that block are
241
- * added before it.
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.
242
239
  */
243
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) {
244
258
  const first = was[0];
245
259
  if (!first || now[0]?.id !== first.id || now[0].markdown === first.markdown)
246
- return now;
260
+ return 0;
247
261
  const held = new Set(was.map((b) => b.id));
248
262
  let end = 1;
249
263
  while (end < now.length && !held.has(now[end].id))
250
264
  end++;
251
265
  const ahead = now.slice(1, end);
252
- const at = ahead.findIndex((b) => b.markdown === first.markdown) + 1 ||
253
- (now[0].kind !== first.kind && ahead.findIndex((b) => b.kind === first.kind) + 1);
254
- if (!at)
255
- return now;
256
- let added = `${first.id}+`;
257
- while (held.has(added))
258
- added += '+';
259
- return now.map((b, i) => (i === 0 ? { ...b, id: added } : i === at ? { ...b, id: first.id } : b));
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
+ });
260
314
  }
261
315
  /** The blocks of the value at `addr`, none where it holds none. */
262
316
  function blocksOf(doc, addr) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@quillmark/svelte",
3
- "version": "0.38.1",
3
+ "version": "0.39.0",
4
4
  "description": "Editor, live-preview and source surfaces over a Quillmark WASM session.",
5
5
  "repository": {
6
6
  "type": "git",