@quillmark/svelte 0.33.0 → 0.35.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (98) hide show
  1. package/README.md +73 -1
  2. package/THEMING.md +11 -10
  3. package/dist/core/address.d.ts +6 -0
  4. package/dist/core/address.js +16 -0
  5. package/dist/core/codec/anchor.d.ts +12 -0
  6. package/dist/core/codec/anchor.js +39 -0
  7. package/dist/core/codec/drag-move.d.ts +11 -0
  8. package/dist/core/codec/drag-move.js +143 -0
  9. package/dist/core/codec/encode.js +14 -5
  10. package/dist/core/codec/field.d.ts +44 -1
  11. package/dist/core/codec/field.js +137 -38
  12. package/dist/core/codec/index.d.ts +8 -2
  13. package/dist/core/codec/index.js +9 -2
  14. package/dist/core/codec/islands.d.ts +4 -1
  15. package/dist/core/codec/islands.js +6 -0
  16. package/dist/core/codec/keymap.d.ts +3 -0
  17. package/dist/core/codec/keymap.js +13 -12
  18. package/dist/core/codec/leave.d.ts +17 -0
  19. package/dist/core/codec/leave.js +78 -0
  20. package/dist/core/codec/prose.css +172 -0
  21. package/dist/core/codec/review-diff.d.ts +12 -0
  22. package/dist/core/codec/review-diff.js +131 -0
  23. package/dist/core/codec/review.d.ts +116 -0
  24. package/dist/core/codec/review.js +920 -0
  25. package/dist/core/codec/shortcuts.d.ts +20 -4
  26. package/dist/core/codec/shortcuts.js +27 -7
  27. package/dist/core/codec/slash.d.ts +3 -0
  28. package/dist/core/codec/slash.js +2 -1
  29. package/dist/core/codec/table-view.js +163 -25
  30. package/dist/core/codec/undo.d.ts +6 -0
  31. package/dist/core/codec/undo.js +25 -2
  32. package/dist/core/dragfollow.d.ts +18 -0
  33. package/dist/core/dragfollow.js +63 -0
  34. package/dist/core/theme.css +34 -7
  35. package/dist/preview/controller.js +16 -0
  36. package/dist/preview/strings.d.ts +4 -0
  37. package/dist/preview/strings.js +3 -1
  38. package/dist/visual/ArrayField.svelte +363 -57
  39. package/dist/visual/ArrayField.svelte.d.ts +5 -0
  40. package/dist/visual/BooleanField.svelte +60 -5
  41. package/dist/visual/BooleanField.svelte.d.ts +2 -1
  42. package/dist/visual/Card.svelte +27 -17
  43. package/dist/visual/CardControls.svelte +17 -7
  44. package/dist/visual/CardControls.svelte.d.ts +2 -0
  45. package/dist/visual/DateField.svelte +90 -39
  46. package/dist/visual/DateField.svelte.d.ts +2 -2
  47. package/dist/visual/Field.svelte +98 -6
  48. package/dist/visual/FieldHint.svelte +24 -9
  49. package/dist/visual/FieldLabel.svelte +128 -22
  50. package/dist/visual/FieldLabel.svelte.d.ts +9 -0
  51. package/dist/visual/FormatPopover.svelte +125 -20
  52. package/dist/visual/MatrixAdd.svelte +13 -6
  53. package/dist/visual/MatrixAdd.svelte.d.ts +3 -2
  54. package/dist/visual/MatrixField.svelte +36 -8
  55. package/dist/visual/NumberField.svelte +27 -6
  56. package/dist/visual/NumberField.svelte.d.ts +3 -0
  57. package/dist/visual/ObjectField.svelte +25 -1
  58. package/dist/visual/ObjectField.svelte.d.ts +6 -0
  59. package/dist/visual/ProseField.svelte +21 -0
  60. package/dist/visual/ProseField.svelte.d.ts +3 -0
  61. package/dist/visual/ProseValue.svelte +107 -17
  62. package/dist/visual/ProseValue.svelte.d.ts +18 -4
  63. package/dist/visual/ReviewProposal.svelte +149 -0
  64. package/dist/visual/ReviewProposal.svelte.d.ts +15 -0
  65. package/dist/visual/ReviewRows.svelte +43 -0
  66. package/dist/visual/ReviewRows.svelte.d.ts +11 -0
  67. package/dist/visual/SlashMenu.svelte +13 -1
  68. package/dist/visual/SlashMenu.svelte.d.ts +2 -0
  69. package/dist/visual/VisualEditor.svelte +22 -0
  70. package/dist/visual/VisualEditor.svelte.d.ts +7 -0
  71. package/dist/visual/VisualEditorInner.svelte +591 -27
  72. package/dist/visual/VisualEditorInner.svelte.d.ts +7 -0
  73. package/dist/visual/controls.css +17 -2
  74. package/dist/visual/guidance.d.ts +12 -0
  75. package/dist/visual/guidance.js +37 -2
  76. package/dist/visual/icons/nodes.d.ts +14 -2
  77. package/dist/visual/icons/nodes.js +12 -1
  78. package/dist/visual/index.d.ts +6 -0
  79. package/dist/visual/index.js +2 -0
  80. package/dist/visual/listhistory.d.ts +36 -0
  81. package/dist/visual/listhistory.js +53 -0
  82. package/dist/visual/proposals.d.ts +40 -0
  83. package/dist/visual/proposals.js +219 -0
  84. package/dist/visual/props.d.ts +36 -0
  85. package/dist/visual/removed.d.ts +20 -0
  86. package/dist/visual/removed.js +30 -0
  87. package/dist/visual/review.d.ts +135 -0
  88. package/dist/visual/review.js +227 -0
  89. package/dist/visual/review.svelte.d.ts +79 -0
  90. package/dist/visual/review.svelte.js +226 -0
  91. package/dist/visual/rowdrag.svelte.js +44 -55
  92. package/dist/visual/strings.d.ts +36 -7
  93. package/dist/visual/strings.js +26 -7
  94. package/dist/visual/structure.d.ts +5 -0
  95. package/dist/visual/structure.js +1 -1
  96. package/dist/visual/undo.svelte.d.ts +40 -7
  97. package/dist/visual/undo.svelte.js +98 -25
  98. package/package.json +1 -1
@@ -0,0 +1,920 @@
1
+ // Review, drawn in the leaf's own flow: what a writer other than the reader proposes to change
2
+ // here. An item names blocks by the ids the leaf's nodes carry, so its place is the document's and
3
+ // rides every edit; nothing is measured from outside the view.
4
+ //
5
+ // A proposal is the paragraph it would rewrite, read as an edit of itself: the words that would go
6
+ // struck, the words that would come tinted in their place, and what it adds beyond the paragraph
7
+ // set in flow under it. None of it enters the document while it is proposed: the struck words are
8
+ // the leaf's own text under a decoration, and every added word is a widget. A proposal taken is
9
+ // plain text, the leaf's like any other.
10
+ //
11
+ // A proposal is an edit of the paragraph as its writer read it, or as it stood when it arrived. What the reader
12
+ // writes in the paragraph since is theirs: the proposal's stretches ride past it, and only the
13
+ // words it would rewrite are struck, as the reader has them now.
14
+ //
15
+ // Taking a proposal is the leaf's own edit, made from the plan the drawing was made from, so the
16
+ // words that land are the words that were drawn. It goes down the lane a keystroke takes: one
17
+ // transaction, one undo step, one commit.
18
+ import { closeHistory, isHistoryTransaction, undo } from 'prosemirror-history';
19
+ import { DOMSerializer, Fragment, Mark } from 'prosemirror-model';
20
+ import { keydownHandler } from 'prosemirror-keymap';
21
+ import { Plugin, PluginKey, Selection } from 'prosemirror-state';
22
+ import { Step, StepResult } from 'prosemirror-transform';
23
+ import { Decoration, DecorationSet } from 'prosemirror-view';
24
+ import { arriving, HARD_BREAK, ISLAND_SLOT } from './islands.js';
25
+ import { remoteKey } from './remote.js';
26
+ import { wordDiff } from './review-diff.js';
27
+ import { REVIEW_KEYS } from './shortcuts.js';
28
+ export const DEFAULT_REVIEW_STRINGS = {
29
+ reviewAccept: 'Accept',
30
+ reviewDismiss: 'Dismiss',
31
+ reviewAcceptTitle: 'Accept',
32
+ reviewDismissTitle: 'Dismiss',
33
+ reviewProposal: 'Proposed change',
34
+ reviewOutdated: 'Edited since'
35
+ };
36
+ const reviewKey = new PluginKey('quill-review');
37
+ /** Tell the review layer the store took blocks under new ids, each `[was, now]`. */
38
+ export function renameBlocks(tr, renamed) {
39
+ if (renamed.length)
40
+ tr.setMeta(reviewKey, { renamed });
41
+ }
42
+ /** The id the block once named `id` stands under now. */
43
+ function nowOf(renamed, id) {
44
+ for (let hops = 0; hops < renamed.size && renamed.has(id); hops++)
45
+ id = renamed.get(id);
46
+ return id;
47
+ }
48
+ /**
49
+ * Taking a proposal, as a step of the transaction that writes it. It changes no content, and it
50
+ * is a step and not a transaction's meta so that the leaf's history carries the answer with the
51
+ * words: undoing the accept inverts it and the proposal draws again, and a redo, an undo event
52
+ * grown by typing, the depth cap and a rebase over a remote edit each move it with its words.
53
+ */
54
+ class ReviewAnswer extends Step {
55
+ id;
56
+ to;
57
+ constructor(id, to) {
58
+ super();
59
+ this.id = id;
60
+ this.to = to;
61
+ }
62
+ apply(doc) {
63
+ return StepResult.ok(doc);
64
+ }
65
+ invert() {
66
+ return new ReviewAnswer(this.id, this.to ? undefined : 'accept');
67
+ }
68
+ map() {
69
+ return this;
70
+ }
71
+ toJSON() {
72
+ return { stepType: 'quillReviewAnswer', id: this.id, to: this.to ?? null };
73
+ }
74
+ static fromJSON(_schema, json) {
75
+ return new ReviewAnswer(json.id, json.to ?? undefined);
76
+ }
77
+ }
78
+ Step.jsonID('quillReviewAnswer', ReviewAnswer);
79
+ function answering(state, id, to) {
80
+ if (state.answered.get(id) === to)
81
+ return state;
82
+ const answered = new Map(state.answered);
83
+ if (to)
84
+ answered.set(id, to);
85
+ else
86
+ answered.delete(id);
87
+ return { ...state, answered };
88
+ }
89
+ function applyReview(tr, state) {
90
+ let next = state.replayed.length ? { ...state, replayed: [] } : state;
91
+ if (tr.docChanged && !tr.getMeta(remoteKey))
92
+ next = { ...next, edits: next.edits + 1 };
93
+ const history = isHistoryTransaction(tr);
94
+ tr.steps.forEach((step) => {
95
+ if (!(step instanceof ReviewAnswer))
96
+ return;
97
+ next = answering(next, step.id, step.to);
98
+ // Reported whether or not the answer is still held: the host's list may have dropped it.
99
+ if (history)
100
+ next = { ...next, replayed: [...next.replayed, { id: step.id, to: step.to }] };
101
+ });
102
+ const meta = tr.getMeta(reviewKey);
103
+ if (meta?.answer)
104
+ next = answering(next, meta.answer.id, meta.answer.to);
105
+ for (const id of meta?.prune ?? [])
106
+ next = answering(next, id, undefined);
107
+ if (meta?.renamed)
108
+ next = { ...next, renamed: new Map([...next.renamed, ...meta.renamed]) };
109
+ if (meta?.entered !== undefined)
110
+ next = { ...next, entered: meta.entered };
111
+ else if (next.entered !== undefined && (tr.docChanged || tr.selectionSet))
112
+ next = { ...next, entered: undefined };
113
+ return next;
114
+ }
115
+ function leavesOf(doc) {
116
+ const out = [];
117
+ const walk = (node, start, chain) => {
118
+ node.forEach((child, offset) => {
119
+ const pos = start + offset;
120
+ if (child.isTextblock || child.isAtom)
121
+ out.push({ node: child, pos, chain });
122
+ else
123
+ walk(child, pos + 1, `${chain}/${child.type.name}`);
124
+ });
125
+ };
126
+ walk(doc, 0, '');
127
+ return out;
128
+ }
129
+ /** A textblock's text with one character a leaf node, so an offset in it is a position in it. */
130
+ function textOf(block) {
131
+ return block.textBetween(0, block.content.size, undefined, (leaf) => leaf.type.name === 'hard_break' ? HARD_BREAK : ISLAND_SLOT);
132
+ }
133
+ /** Whether `b` is `a` rewritten in place: one kind of block, in the nesting `a` stands in as far
134
+ * as `b` spells one, so their difference is their words'. A block proposed bare keeps the
135
+ * containers it is in. Two atoms are in place only where they are equal. */
136
+ function inPlace(a, b) {
137
+ if (a.node.type !== b.node.type || !a.chain.endsWith(b.chain))
138
+ return false;
139
+ const { id: _a, block: _ab, ...x } = a.node.attrs;
140
+ const { id: _b, block: _bb, ...y } = b.node.attrs;
141
+ return JSON.stringify(x) === JSON.stringify(y);
142
+ }
143
+ /** The span of `leaf` a caret can stand in: a textblock's content, an atom's two sides. */
144
+ function reach(leaf) {
145
+ return leaf.node.isTextblock
146
+ ? [leaf.pos + 1, leaf.pos + leaf.node.nodeSize - 1]
147
+ : [leaf.pos, leaf.pos + leaf.node.nodeSize];
148
+ }
149
+ /** `doc`'s blocks from its `from`th leaf on, in the containers they sat in. A numbered list
150
+ * that lost its head keeps counting from where the kept items stood. */
151
+ function tail(doc, from) {
152
+ let seen = 0;
153
+ const keep = (node) => {
154
+ if (node.isTextblock || node.isAtom)
155
+ return seen++ >= from ? node : undefined;
156
+ const kids = [];
157
+ let dropped = 0;
158
+ node.forEach((child) => {
159
+ const kept = keep(child);
160
+ if (kept)
161
+ kids.push(kept);
162
+ else if (!kids.length)
163
+ dropped++;
164
+ });
165
+ if (!kids.length)
166
+ return undefined;
167
+ const attrs = node.type.name === 'ordered_list'
168
+ ? { ...node.attrs, start: node.attrs.start + dropped }
169
+ : node.attrs;
170
+ return node.type.create(attrs, kids);
171
+ };
172
+ const out = [];
173
+ doc.forEach((child) => {
174
+ const kept = keep(child);
175
+ if (kept)
176
+ out.push(kept);
177
+ });
178
+ return out;
179
+ }
180
+ /** The edit that takes a proposal: its pieces, last first, so each still stands where it was
181
+ * read. `undefined` where the pieces no longer make a document the schema holds. */
182
+ function taking(state, plan) {
183
+ const tr = state.tr;
184
+ try {
185
+ for (const piece of [...plan].sort((a, b) => b.from - a.from)) {
186
+ let { from, to } = piece;
187
+ if (piece.lift) {
188
+ const $at = tr.doc.resolve(from);
189
+ for (let d = $at.depth; d > 0 && $at.node(d).childCount === 1; d--) {
190
+ from = $at.before(d);
191
+ to = $at.after(d);
192
+ }
193
+ // A leaf holds a block at the least: its last one is emptied where it stands.
194
+ if (from === 0 && to === tr.doc.content.size) {
195
+ tr.replaceWith(from, to, tr.doc.type.createAndFill().content);
196
+ continue;
197
+ }
198
+ }
199
+ tr.replaceWith(from, to, arriving(tr.doc, piece.content));
200
+ }
201
+ tr.doc.check();
202
+ }
203
+ catch {
204
+ return undefined;
205
+ }
206
+ return tr.docChanged ? closeHistory(tr) : undefined;
207
+ }
208
+ /** The marks on each offset of a textblock's content. */
209
+ function marksOf(block) {
210
+ const out = [];
211
+ block.forEach((child) => {
212
+ for (let k = 0; k < child.nodeSize; k++)
213
+ out.push(child.marks);
214
+ });
215
+ return out;
216
+ }
217
+ /** The runs of `[at, end)` in `a` whose marks differ from the same words in `b`, which stand
218
+ * `shift` further on. */
219
+ function formatRuns(a, b, at, end, shift, after) {
220
+ const out = [];
221
+ let run = -1;
222
+ for (let i = at; i <= end; i++) {
223
+ const differs = i < end && !Mark.sameSet(a[i], b[i + shift]);
224
+ if (differs && run < 0)
225
+ run = i;
226
+ else if (!differs && run >= 0) {
227
+ out.push({ at: run, end: i, insert: after.slice(run + shift, i + shift), format: true });
228
+ run = -1;
229
+ }
230
+ }
231
+ return out;
232
+ }
233
+ /** A value of two nodes, kept while both are: a node an edit leaves alone is the same object
234
+ * after it, so a paragraph the reader did not touch is not diffed again. */
235
+ function byPair(of) {
236
+ const kept = new WeakMap();
237
+ return (a, b) => {
238
+ let row = kept.get(a);
239
+ if (!row)
240
+ kept.set(a, (row = new WeakMap()));
241
+ if (row.has(b))
242
+ return row.get(b);
243
+ const value = of(a, b);
244
+ row.set(b, value);
245
+ return value;
246
+ };
247
+ }
248
+ /** The hunks between two paired textblocks: their words', and inside the words they keep,
249
+ * each run whose formatting differs. */
250
+ const hunksOf = byPair((a, b) => {
251
+ const before = textOf(a);
252
+ const after = textOf(b);
253
+ const words = before === after ? [] : wordDiff(before, after);
254
+ const ma = marksOf(a);
255
+ const mb = marksOf(b);
256
+ const out = [];
257
+ let kept = 0;
258
+ let shift = 0;
259
+ for (const hunk of words) {
260
+ out.push(...formatRuns(ma, mb, kept, hunk.at, shift, after), hunk);
261
+ shift += hunk.insert.length - (hunk.end - hunk.at);
262
+ kept = hunk.end;
263
+ }
264
+ out.push(...formatRuns(ma, mb, kept, before.length, shift, after));
265
+ return out;
266
+ });
267
+ /** What the reader wrote in a block since a proposal arrived over it. */
268
+ const sinceOf = byPair((was, now) => was === now ? [] : wordDiff(textOf(was), textOf(now)));
269
+ /**
270
+ * What `to` rewrites of a block that read `was` when the proposal was made and reads `now`. Each
271
+ * stretch the proposal changes in `was` is carried through what was written since: words typed
272
+ * at its edge stay outside it, and where a word it would rewrite was itself rewritten, the stretch
273
+ * covers the rewriting. A stretch that already reads as proposed is left out.
274
+ *
275
+ * The block is `outdated` where the reader's writing meets a stretch the proposal changes, since
276
+ * taking it would write over words the reader wrote. Where that writing reaches past the stretch,
277
+ * the stretch carried onto words it was never computed against would write a sentence nobody
278
+ * proposed, so the whole block as it now reads gives way to the whole proposed one.
279
+ */
280
+ function rewrites(was, now, to) {
281
+ const since = sinceOf(was, now);
282
+ const hunks = hunksOf(was, to);
283
+ const meets = (s, h) => s.at === s.end
284
+ ? h.at < s.at && s.at < h.end
285
+ : h.at === h.end
286
+ ? s.at < h.at && h.at < s.end
287
+ : s.at < h.end && h.at < s.end;
288
+ const past = since.some((s) => hunks.some((h) => s.at < h.end && h.at < s.end && !(h.at <= s.at && s.end <= h.end)));
289
+ if (past)
290
+ return {
291
+ outdated: true,
292
+ stretches: [{ at: 0, end: now.content.size, content: to.content }]
293
+ };
294
+ const outdated = since.some((s) => hunks.some((h) => meets(s, h)));
295
+ const text = since.length ? textOf(now) : '';
296
+ const nowMarks = since.length ? marksOf(now) : [];
297
+ const toMarks = since.length ? marksOf(to) : [];
298
+ const formatted = (at, end, start) => nowMarks.slice(at, end).every((marks, i) => Mark.sameSet(marks, toMarks[start + i]));
299
+ const through = (pos, edge) => {
300
+ let moved = pos;
301
+ for (const hunk of since) {
302
+ const grew = hunk.insert.length - (hunk.end - hunk.at);
303
+ if (hunk.at === hunk.end ? (edge === 'start' ? hunk.at <= pos : hunk.at < pos) : hunk.end <= pos)
304
+ moved += grew;
305
+ else if (hunk.at < pos && pos < hunk.end)
306
+ return hunk.at + (moved - pos) + (edge === 'end' ? hunk.insert.length : 0);
307
+ }
308
+ return moved;
309
+ };
310
+ const out = [];
311
+ // Where each insert starts in the proposed block: its hunk's start in the block it was
312
+ // made on, moved by what the hunks before it added and took.
313
+ let shift = 0;
314
+ for (const hunk of hunks) {
315
+ const start = hunk.at + shift;
316
+ shift += hunk.insert.length - (hunk.end - hunk.at);
317
+ const at = through(hunk.at, 'start');
318
+ const end = Math.max(at, through(hunk.end, 'end'));
319
+ if (since.length &&
320
+ text.slice(at, end) === hunk.insert &&
321
+ (!hunk.format || formatted(at, end, start)))
322
+ continue;
323
+ out.push({ at, end, content: to.content.cut(start, start + hunk.insert.length) });
324
+ }
325
+ return { outdated, stretches: out };
326
+ }
327
+ /** {@link rewrites}, kept while its three blocks are. */
328
+ const rewritten = (() => {
329
+ const kept = byPair(() => new WeakMap());
330
+ return (was, now, to) => {
331
+ const row = kept(was, now);
332
+ let out = row.get(to);
333
+ if (!out)
334
+ row.set(to, (out = rewrites(was, now, to)));
335
+ return out;
336
+ };
337
+ })();
338
+ /** A chord as `aria-keyshortcuts` spells it, `Mod` as either platform's. */
339
+ const ariaKeys = (chord) => ['Meta', 'Control'].map((mod) => chord.replace('Mod', mod).replaceAll('-', '+')).join(' ');
340
+ function button(act, id, action, label, title, keys) {
341
+ const el = document.createElement('button');
342
+ el.type = 'button';
343
+ el.tabIndex = -1;
344
+ el.className = `qm-review-act qm-review-${action}`;
345
+ el.textContent = label;
346
+ el.title = title;
347
+ el.setAttribute('aria-keyshortcuts', ariaKeys(keys));
348
+ // The press keeps the caret where it is: the answer is about the text, not a move off it.
349
+ el.addEventListener('mousedown', (e) => e.preventDefault());
350
+ el.addEventListener('click', (e) => {
351
+ e.preventDefault();
352
+ act(id, action);
353
+ });
354
+ return el;
355
+ }
356
+ /** A proposal's two buttons: a run at the end of its last line, or a row of their own under a
357
+ * block that has no line to end. */
358
+ function chip(strings, act, id, row, outdated) {
359
+ const el = document.createElement(row ? 'div' : 'span');
360
+ el.className = ['qm-review-chip', row && 'qm-review-chip-row', outdated && 'qm-review-outdated']
361
+ .filter(Boolean)
362
+ .join(' ');
363
+ el.contentEditable = 'false';
364
+ el.setAttribute('data-qm-review', id);
365
+ el.setAttribute('role', 'group');
366
+ el.setAttribute('aria-label', strings.reviewProposal);
367
+ const acts = document.createElement('span');
368
+ acts.className = 'qm-review-acts';
369
+ if (outdated) {
370
+ const label = document.createElement('span');
371
+ label.className = 'qm-review-outdated-label';
372
+ label.textContent = strings.reviewOutdated;
373
+ acts.append(label);
374
+ }
375
+ acts.append(button(act, id, 'accept', strings.reviewAccept, strings.reviewAcceptTitle, REVIEW_KEYS.accept), button(act, id, 'dismiss', strings.reviewDismiss, strings.reviewDismissTitle, REVIEW_KEYS.dismiss));
376
+ // The space a run of answers stands off its line by, which a wrapped run leaves behind.
377
+ el.append(row ? '' : ' ', acts);
378
+ return el;
379
+ }
380
+ /** The last textblock's element under `el`, where a run can be appended to its last line. */
381
+ function lastLine(el) {
382
+ let at = el;
383
+ for (;;) {
384
+ if (/^(P|H[1-6]|CODE)$/.test(at.tagName))
385
+ return at;
386
+ const last = at.lastElementChild;
387
+ if (!(last instanceof HTMLElement))
388
+ return undefined;
389
+ at = last;
390
+ }
391
+ }
392
+ /** The id of the stored block a leaf decodes from: a block island's own, any other's `id`. */
393
+ function blockOf(node) {
394
+ return String((node.type.name === 'island_block' ? node.attrs.block : node.attrs.id) ?? '');
395
+ }
396
+ function placeOf(item, leaves, now) {
397
+ const index = (id) => leaves.findIndex((leaf) => blockOf(leaf.node) === now(id));
398
+ if ('replace' in item) {
399
+ const named = new Set(item.replace.map(now));
400
+ const cover = leaves.flatMap((leaf, i) => (named.has(blockOf(leaf.node)) ? [i] : []));
401
+ if (!cover.length)
402
+ return 'gone';
403
+ const found = new Set(cover.map((i) => blockOf(leaves[i].node)));
404
+ return { cover, beside: -1, ahead: false, missing: found.size < named.size };
405
+ }
406
+ const at = item.insert;
407
+ let beside = leaves.length - 1;
408
+ let ahead = false;
409
+ if (at !== 'end') {
410
+ const i = index('after' in at ? at.after : at.before);
411
+ if (i < 0)
412
+ return 'gone';
413
+ if ('after' in at)
414
+ beside = i;
415
+ else if (i === 0)
416
+ [beside, ahead] = [0, true];
417
+ else
418
+ beside = i - 1;
419
+ }
420
+ if (beside < 0)
421
+ return 'gone';
422
+ // A leaf of one empty paragraph is filled by what is added to it.
423
+ const leaf = leaves[beside];
424
+ if (leaves.length === 1 && leaf.node.isTextblock && !leaf.node.content.size)
425
+ return { cover: [beside], beside, ahead: false, missing: false };
426
+ return { cover: [], beside, ahead, missing: false };
427
+ }
428
+ /** The blocks a proposal's writer read, by the id each was read under; `undefined` where
429
+ * `before` does not read as one block for each id. */
430
+ const reads = new WeakMap();
431
+ function readOf(ids, before, channel) {
432
+ let row = reads.get(ids);
433
+ if (!row)
434
+ reads.set(ids, (row = new Map()));
435
+ if (row.has(before))
436
+ return row.get(before);
437
+ const doc = before.trim() ? channel.parse(before) : undefined;
438
+ const blocks = doc ? leavesOf(doc) : [];
439
+ const out = blocks.length === ids.length ? new Map(ids.map((id, k) => [id, blocks[k].node])) : undefined;
440
+ row.set(before, out);
441
+ return out;
442
+ }
443
+ function draw(state, channel, act, bases) {
444
+ const { answered, renamed } = reviewKey.getState(state);
445
+ const now = (id) => nowOf(renamed, id);
446
+ const listed = channel.items();
447
+ // A base outlives its item's answer and its leaving the list while a block it covered
448
+ // stands, so a proposal brought back by an undo draws against the paragraph it first drew over.
449
+ if (bases.size) {
450
+ const ids = new Set(listed.map((item) => item.id));
451
+ let blocks;
452
+ const stands = (place) => {
453
+ blocks ??= new Set(leavesOf(state.doc).map((leaf) => blockOf(leaf.node)));
454
+ return place.some((id) => blocks.has(id));
455
+ };
456
+ for (const [id, base] of bases)
457
+ if (!ids.has(id) && !stands(base.place))
458
+ bases.delete(id);
459
+ }
460
+ const items = answered.size ? listed.filter((item) => !answered.has(item.id)) : listed;
461
+ const plans = new Map();
462
+ const undrawn = [];
463
+ const outdated = [];
464
+ const decos = [];
465
+ const lighting = new Set();
466
+ if (!items.length)
467
+ return { decos, lighting, spans: [], plans, outdated, undrawn };
468
+ const { doc } = state;
469
+ const strings = channel.strings();
470
+ const serializer = DOMSerializer.fromSchema(state.schema);
471
+ const lights = (id, make) => {
472
+ lighting.add(id);
473
+ decos.push({ id, make });
474
+ };
475
+ const spans = [];
476
+ let leaves;
477
+ /** The paragraphs a proposal rewrites, and the places a proposal that only adds adds at:
478
+ * a paragraph's end, or `-1` for the head of the leaf. */
479
+ const taken = new Set();
480
+ const adding = new Set();
481
+ for (const item of items) {
482
+ const name = { 'data-qm-review': item.id };
483
+ leaves ??= leavesOf(doc);
484
+ const at = placeOf(item, leaves, now);
485
+ if (at === 'gone') {
486
+ undrawn.push({ id: item.id, reason: 'block' });
487
+ continue;
488
+ }
489
+ const { cover, beside, ahead } = at;
490
+ const place = ahead ? -1 : beside;
491
+ if (cover.length ? cover.some((i) => taken.has(i)) : adding.has(place)) {
492
+ undrawn.push({ id: item.id, reason: 'taken' });
493
+ continue;
494
+ }
495
+ const proposed = item.after.trim() ? channel.parse(item.after) : undefined;
496
+ if (item.after.trim() && !proposed) {
497
+ undrawn.push({ id: item.id, reason: 'parse' });
498
+ continue;
499
+ }
500
+ const next = proposed ? leavesOf(proposed) : [];
501
+ const covered = cover.map((i) => leaves[i]);
502
+ let paired = 0;
503
+ while (paired < covered.length &&
504
+ paired < next.length &&
505
+ inPlace(covered[paired], next[paired]))
506
+ paired++;
507
+ const added = proposed && paired < next.length ? tail(proposed, paired) : [];
508
+ if (!covered.length && !added.length)
509
+ continue;
510
+ const plan = [];
511
+ const mark = decos.length;
512
+ let stale = at.missing;
513
+ let base;
514
+ if ('replace' in item && item.before !== undefined) {
515
+ const read = readOf(item.replace, item.before, channel);
516
+ const named = new Map(item.replace.map((id) => [now(id), id]));
517
+ const was = covered.map((leaf) => read?.get(named.get(blockOf(leaf.node)) ?? ''));
518
+ stale ||= was.some((node) => !node);
519
+ base = was.map((node, k) => node ?? covered[k].node);
520
+ }
521
+ else {
522
+ const seen = bases.get(item.id);
523
+ base =
524
+ seen?.after === item.after && seen.blocks.length === covered.length
525
+ ? seen.blocks
526
+ : covered.map((leaf) => leaf.node);
527
+ bases.set(item.id, {
528
+ after: item.after,
529
+ place: covered.map((l) => blockOf(l.node)),
530
+ blocks: base
531
+ });
532
+ }
533
+ covered.forEach((leaf, k) => {
534
+ const [lo, hi] = reach(leaf);
535
+ const whole = k >= paired;
536
+ lights(item.id, (on) => Decoration.node(leaf.pos, leaf.pos + leaf.node.nodeSize, {
537
+ class: ['qm-review-held', whole && 'qm-review-out', on && 'qm-review-lit']
538
+ .filter(Boolean)
539
+ .join(' ')
540
+ }));
541
+ if (whole) {
542
+ // Taking it removes what the reader wrote in the block since it was read.
543
+ stale ||= !base[k].content.eq(leaf.node.content);
544
+ plan.push({
545
+ from: leaf.pos,
546
+ to: leaf.pos + leaf.node.nodeSize,
547
+ content: Fragment.empty,
548
+ lift: true
549
+ });
550
+ }
551
+ if (!leaf.node.isTextblock)
552
+ return;
553
+ const strike = (from, to) => {
554
+ if (to > from)
555
+ decos.push(Decoration.inline(from, to, { nodeName: 'del', class: 'qm-review-del', ...name }));
556
+ };
557
+ if (whole)
558
+ return strike(lo, hi);
559
+ const to = next[k].node;
560
+ const read = base[k].type === leaf.node.type;
561
+ stale ||= !read;
562
+ const { outdated: past, stretches } = rewritten(read ? base[k] : leaf.node, leaf.node, to);
563
+ stale ||= past;
564
+ stretches.forEach(({ at, end, content }, n) => {
565
+ strike(lo + at, lo + end);
566
+ plan.push({ from: lo + at, to: lo + end, content });
567
+ if (!content.size)
568
+ return;
569
+ decos.push(Decoration.widget(lo + end, () => {
570
+ const el = document.createElement('ins');
571
+ el.className = 'qm-review-ins';
572
+ el.contentEditable = 'false';
573
+ el.setAttribute('data-qm-review', item.id);
574
+ el.append(serializer.serializeFragment(content));
575
+ return el;
576
+ }, { side: -1, key: `ins:${item.id}:${n}:${content.toString()}` }));
577
+ });
578
+ });
579
+ if (!plan.length && !added.length) {
580
+ decos.length = mark;
581
+ lighting.delete(item.id);
582
+ undrawn.push({ id: item.id, reason: 'applied' });
583
+ continue;
584
+ }
585
+ if (cover.length)
586
+ for (const i of cover)
587
+ taken.add(i);
588
+ else
589
+ adding.add(place);
590
+ plans.set(item.id, plan);
591
+ if (stale)
592
+ outdated.push(item.id);
593
+ const last = covered.at(-1) ?? leaves[beside];
594
+ const $last = doc.resolve(last.pos);
595
+ /** Past the outermost block holding the last one, or the head of the leaf. */
596
+ const outer = ahead ? 0 : $last.depth ? $last.after(1) : last.pos + last.node.nodeSize;
597
+ const row = () => {
598
+ decos.push(Decoration.widget(outer, () => chip(strings, act, item.id, true, stale), {
599
+ side: ahead ? -1 : 9999,
600
+ key: `chip:${item.id}:row:${stale}`,
601
+ stopEvent: () => true
602
+ }));
603
+ };
604
+ if (added.length) {
605
+ // A proposal that continues the list its paragraph is in adds items to that list.
606
+ const listed = !ahead &&
607
+ $last.parent.type.name === 'list_item' &&
608
+ added[0].type === $last.node($last.depth - 1).type;
609
+ const pieces = [];
610
+ if (listed) {
611
+ const at = $last.after($last.depth);
612
+ added[0].forEach((li) => pieces.push({ at, node: li }));
613
+ }
614
+ for (const node of listed ? added.slice(1) : added)
615
+ pieces.push({ at: outer, node });
616
+ for (const piece of pieces) {
617
+ const held = plan.at(-1);
618
+ if (held && !held.lift && held.from === piece.at && held.to === piece.at)
619
+ held.content = held.content.addToEnd(piece.node);
620
+ else
621
+ plan.push({ from: piece.at, to: piece.at, content: Fragment.from(piece.node) });
622
+ }
623
+ const closing = pieces.length - 1;
624
+ const chipped = endsInLine(pieces[closing].node);
625
+ pieces.forEach((piece, n) => {
626
+ const holds = chipped && n === closing;
627
+ lights(item.id, (on) => Decoration.widget(piece.at, () => {
628
+ const el = serializer.serializeNode(piece.node);
629
+ el.classList.add('qm-review-add');
630
+ if (on)
631
+ el.classList.add('qm-review-lit');
632
+ el.contentEditable = 'false';
633
+ el.setAttribute('data-qm-review', item.id);
634
+ if (holds)
635
+ lastLine(el)?.append(chip(strings, act, item.id, false, stale));
636
+ return el;
637
+ }, {
638
+ side: ahead ? -1000 + n : 1 + n,
639
+ key: `add:${item.id}:${n}:${on}:${piece.node.toString()}`,
640
+ stopEvent: (e) => e.target?.closest?.('.qm-review-chip') != null
641
+ }));
642
+ });
643
+ if (!chipped)
644
+ row();
645
+ }
646
+ else if (last.node.isTextblock) {
647
+ decos.push(Decoration.widget(reach(last)[1], () => chip(strings, act, item.id, false, stale), {
648
+ side: 1,
649
+ key: `chip:${item.id}:${stale}`,
650
+ stopEvent: () => true
651
+ }));
652
+ }
653
+ else
654
+ row();
655
+ // What a proposal only adds to has the caret anywhere in the block it adds from.
656
+ spans.push({
657
+ id: item.id,
658
+ adds: !covered.length,
659
+ from: reach(covered[0] ?? last)[0],
660
+ to: reach(last)[1]
661
+ });
662
+ }
663
+ return { decos, lighting, spans, plans, outdated, undrawn };
664
+ }
665
+ /** Whether a block's last leaf is a textblock, so its last line can carry a run. */
666
+ function endsInLine(node) {
667
+ let at = node;
668
+ while (!at.isTextblock && !at.isAtom && at.lastChild)
669
+ at = at.lastChild;
670
+ return at.isTextblock;
671
+ }
672
+ /** The item the caret is in: the one it was put into by its id while it holds the caret, else
673
+ * the one that holds it closest, so of a proposal that rewrites a paragraph and one that adds
674
+ * after it, the one that rewrites. */
675
+ function spanAt(spans, pos, entered) {
676
+ let best;
677
+ for (const s of spans) {
678
+ if (s.from > pos || pos > s.to)
679
+ continue;
680
+ if (s.id === entered)
681
+ return s;
682
+ const size = s.to - s.from;
683
+ const held = best && best.to - best.from;
684
+ if (!best || size < held || (size === held && best.adds && !s.adds))
685
+ best = s;
686
+ }
687
+ return best;
688
+ }
689
+ /**
690
+ * The leaf's review layer. The decorations are a function of the document and the channel's
691
+ * items, kept until one of them moves. The caret's report holds off while the reader
692
+ * types inside an item: an item is news on arriving in it, and noise under every keystroke.
693
+ */
694
+ export function reviewLayer(channel) {
695
+ let memo;
696
+ /** The decorations of what is drawn, with the lit item they were made for. */
697
+ let shown;
698
+ const NOTHING = JSON.stringify({ ids: [], outdated: [], undrawn: [] });
699
+ let reported = NOTHING;
700
+ let host;
701
+ const bases = new Map();
702
+ /** Answer an item. Taking a proposal writes it first, and one that can no longer be written
703
+ * stays as it is. A proposal taken by a press while the focus is elsewhere leaves the caret
704
+ * after what landed, in a focused leaf: the edit is the reader's, and so is its undo. */
705
+ const act = (id, action, how = {}) => {
706
+ const view = host;
707
+ if (!view || !drawn(view.state).spans.some((span) => span.id === id))
708
+ return false;
709
+ if (action === 'accept') {
710
+ const plan = drawn(view.state).plans.get(id);
711
+ const tr = plan && taking(view.state, plan);
712
+ if (!tr || !plan)
713
+ return false;
714
+ const away = !how.quiet && !view.hasFocus();
715
+ if (away) {
716
+ const end = tr.mapping.map(Math.max(...plan.map((piece) => piece.to)), 1);
717
+ tr.setSelection(Selection.near(tr.doc.resolve(Math.min(end, tr.doc.content.size)), -1));
718
+ }
719
+ channel.writing?.(true);
720
+ try {
721
+ view.dispatch(tr.step(new ReviewAnswer(id, 'accept')));
722
+ }
723
+ finally {
724
+ channel.writing?.(false);
725
+ }
726
+ if (away)
727
+ view.focus();
728
+ }
729
+ else {
730
+ view.dispatch(view.state.tr
731
+ .setMeta(reviewKey, { answer: { id, to: 'dismiss' } })
732
+ .setMeta('addToHistory', false));
733
+ }
734
+ channel.act(id, action, how.chord);
735
+ return true;
736
+ };
737
+ const drawn = (state) => {
738
+ const review = reviewKey.getState(state);
739
+ const items = channel.items();
740
+ const strings = channel.strings();
741
+ if (memo &&
742
+ memo.doc === state.doc &&
743
+ memo.review === review &&
744
+ memo.items === items &&
745
+ memo.strings === strings)
746
+ return memo.drawn;
747
+ const next = draw(state, channel, act, bases);
748
+ memo = { doc: state.doc, review, items, strings, drawn: next };
749
+ return next;
750
+ };
751
+ /** Whether the lit item moving to `lit` changes how anything here reads. */
752
+ const relit = (lit) => !shown ||
753
+ (shown.lit !== lit &&
754
+ ((shown.lit !== undefined && shown.drawn.lighting.has(shown.lit)) ||
755
+ (lit !== undefined && shown.drawn.lighting.has(lit))));
756
+ const decorations = (state) => {
757
+ const now = drawn(state);
758
+ const lit = channel.lit();
759
+ if (shown?.drawn === now && !relit(lit)) {
760
+ shown.lit = lit;
761
+ return shown.set;
762
+ }
763
+ const set = DecorationSet.create(state.doc, now.decos.map((d) => ('make' in d ? d.make(d.id === lit) : d)));
764
+ shown = { drawn: now, lit, set };
765
+ return set;
766
+ };
767
+ /** Tell the channel what the leaf draws, where that moved. */
768
+ const report = (state) => {
769
+ const { spans, outdated, undrawn } = drawn(state);
770
+ const next = { ids: spans.map((s) => s.id), outdated, undrawn };
771
+ const joined = JSON.stringify(next);
772
+ if (joined === reported)
773
+ return;
774
+ reported = joined;
775
+ channel.drew(next);
776
+ };
777
+ let hovered;
778
+ const hover = (id) => {
779
+ if (id === hovered)
780
+ return;
781
+ hovered = id;
782
+ channel.point(id, 'pointer');
783
+ };
784
+ const idAt = (target) => (target instanceof Element ? target.closest('[data-qm-review]') : null)?.getAttribute('data-qm-review') ?? undefined;
785
+ let caret;
786
+ /** The item the reader typed in, quiet until the caret has left it. */
787
+ let muted;
788
+ const follow = (view, typed) => {
789
+ const { selection } = view.state;
790
+ const at = view.hasFocus() && selection.empty
791
+ ? spanAt(drawn(view.state).spans, selection.head, reviewKey.getState(view.state)?.entered)
792
+ ?.id
793
+ : undefined;
794
+ if (at !== muted)
795
+ muted = undefined;
796
+ if (typed && at)
797
+ muted = at;
798
+ const next = at === muted ? undefined : at;
799
+ if (next === caret)
800
+ return;
801
+ caret = next;
802
+ channel.point(next, 'caret');
803
+ };
804
+ const answer = (action) => (state) => {
805
+ const span = spanAt(drawn(state).spans, state.selection.head, reviewKey.getState(state)?.entered);
806
+ if (!span)
807
+ return false;
808
+ act(span.id, action, { chord: true });
809
+ return true;
810
+ };
811
+ const plugin = new Plugin({
812
+ key: reviewKey,
813
+ state: {
814
+ init: () => ({
815
+ edits: 0,
816
+ answered: new Map(),
817
+ entered: undefined,
818
+ replayed: [],
819
+ renamed: new Map()
820
+ }),
821
+ apply: applyReview
822
+ },
823
+ props: {
824
+ decorations,
825
+ handleKeyDown: keydownHandler({
826
+ [REVIEW_KEYS.accept]: answer('accept'),
827
+ [REVIEW_KEYS.dismiss]: answer('dismiss')
828
+ }),
829
+ handleDOMEvents: {
830
+ mouseover: (_view, e) => {
831
+ hover(idAt(e.target));
832
+ return false;
833
+ },
834
+ mouseleave: () => {
835
+ hover(undefined);
836
+ return false;
837
+ },
838
+ focus: (view) => {
839
+ follow(view, false);
840
+ return false;
841
+ },
842
+ blur: (view) => {
843
+ // The focus has not left yet when a blur fires.
844
+ queueMicrotask(() => {
845
+ if (!view.isDestroyed)
846
+ follow(view, false);
847
+ });
848
+ return false;
849
+ }
850
+ }
851
+ },
852
+ view: (view) => {
853
+ host = view;
854
+ report(view.state);
855
+ return {
856
+ update(view, prev) {
857
+ const review = reviewKey.getState(view.state);
858
+ if (review && review !== reviewKey.getState(prev))
859
+ for (const { id, to } of review.replayed)
860
+ channel.act(id, to ?? 'reopen');
861
+ report(view.state);
862
+ follow(view, reviewKey.getState(prev)?.edits !== reviewKey.getState(view.state)?.edits);
863
+ },
864
+ destroy() {
865
+ if (hovered !== undefined)
866
+ channel.point(undefined, 'pointer');
867
+ if (caret !== undefined)
868
+ channel.point(undefined, 'caret');
869
+ if (reported !== NOTHING)
870
+ channel.drew({ ids: [], outdated: [], undrawn: [] });
871
+ host = undefined;
872
+ }
873
+ };
874
+ }
875
+ });
876
+ return {
877
+ plugin,
878
+ refresh(view) {
879
+ // Only the lit item moved, and nothing here reads it: the leaf is left alone.
880
+ const lit = channel.lit();
881
+ if (memo?.items === channel.items() && memo.strings === channel.strings() && !relit(lit)) {
882
+ if (shown)
883
+ shown.lit = lit;
884
+ return;
885
+ }
886
+ // An answer is held until a list arrives without its item.
887
+ const answered = reviewKey.getState(view.state)?.answered;
888
+ const listed = new Set(channel.items().map((item) => item.id));
889
+ const prune = [...(answered?.keys() ?? [])].filter((id) => !listed.has(id));
890
+ if (!prune.length)
891
+ return view.setProps({});
892
+ view.dispatch(view.state.tr
893
+ .setMeta(reviewKey, { prune })
894
+ .setMeta('addToHistory', false));
895
+ },
896
+ elements(view, id) {
897
+ return [...view.dom.querySelectorAll('[data-qm-review]')].filter((el) => el.getAttribute('data-qm-review') === id);
898
+ },
899
+ answer: (id, action) => act(id, action, { quiet: true }),
900
+ reopen(view, id) {
901
+ if (reviewKey.getState(view.state)?.answered.get(id) === 'dismiss')
902
+ view.dispatch(view.state.tr
903
+ .setMeta(reviewKey, { answer: { id, to: undefined } })
904
+ .setMeta('addToHistory', false));
905
+ channel.act(id, 'reopen');
906
+ },
907
+ undo: (view) => undo(view.state, view.dispatch),
908
+ enter(view, id) {
909
+ const span = drawn(view.state).spans.find((s) => s.id === id);
910
+ if (!span)
911
+ return false;
912
+ const { doc, tr } = view.state;
913
+ view.dispatch(tr
914
+ .setSelection(Selection.near(doc.resolve(span.to), -1))
915
+ .setMeta(reviewKey, { entered: id }));
916
+ view.focus();
917
+ return true;
918
+ }
919
+ };
920
+ }