vultus-core 0.5.7 → 0.5.8

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 (65) hide show
  1. package/README.md +191 -5
  2. package/dist/Components.d.ts +41 -0
  3. package/dist/Components.d.ts.map +1 -1
  4. package/dist/Components.js.map +1 -1
  5. package/dist/changes/ChangeMark.d.ts +85 -0
  6. package/dist/changes/ChangeMark.d.ts.map +1 -0
  7. package/dist/changes/ChangeMark.js +113 -0
  8. package/dist/changes/ChangeMark.js.map +1 -0
  9. package/dist/changes/ChangingText.d.ts +20 -0
  10. package/dist/changes/ChangingText.d.ts.map +1 -0
  11. package/dist/changes/ChangingText.js +31 -0
  12. package/dist/changes/ChangingText.js.map +1 -0
  13. package/dist/changes/FallbackMark.d.ts +20 -0
  14. package/dist/changes/FallbackMark.d.ts.map +1 -0
  15. package/dist/changes/FallbackMark.js +53 -0
  16. package/dist/changes/FallbackMark.js.map +1 -0
  17. package/dist/changes/blocks.d.ts +15 -0
  18. package/dist/changes/blocks.d.ts.map +1 -0
  19. package/dist/changes/blocks.js +24 -0
  20. package/dist/changes/blocks.js.map +1 -0
  21. package/dist/changes/changeDurations.d.ts +21 -0
  22. package/dist/changes/changeDurations.d.ts.map +1 -0
  23. package/dist/changes/changeDurations.js +18 -0
  24. package/dist/changes/changeDurations.js.map +1 -0
  25. package/dist/changes/changesIn.d.ts +88 -0
  26. package/dist/changes/changesIn.d.ts.map +1 -0
  27. package/dist/changes/changesIn.js +470 -0
  28. package/dist/changes/changesIn.js.map +1 -0
  29. package/dist/changes/readText.d.ts +45 -0
  30. package/dist/changes/readText.d.ts.map +1 -0
  31. package/dist/changes/readText.js +99 -0
  32. package/dist/changes/readText.js.map +1 -0
  33. package/dist/changes/rehypeChanges.d.ts +81 -0
  34. package/dist/changes/rehypeChanges.d.ts.map +1 -0
  35. package/dist/changes/rehypeChanges.js +268 -0
  36. package/dist/changes/rehypeChanges.js.map +1 -0
  37. package/dist/changes/useTextChanges.d.ts +93 -0
  38. package/dist/changes/useTextChanges.d.ts.map +1 -0
  39. package/dist/changes/useTextChanges.js +154 -0
  40. package/dist/changes/useTextChanges.js.map +1 -0
  41. package/dist/changes/visibleBlocks.d.ts +42 -0
  42. package/dist/changes/visibleBlocks.d.ts.map +1 -0
  43. package/dist/changes/visibleBlocks.js +104 -0
  44. package/dist/changes/visibleBlocks.js.map +1 -0
  45. package/dist/changes.d.ts +9 -0
  46. package/dist/changes.d.ts.map +1 -0
  47. package/dist/changes.js +10 -0
  48. package/dist/changes.js.map +1 -0
  49. package/dist/index.d.ts +3 -1
  50. package/dist/index.d.ts.map +1 -1
  51. package/dist/index.js.map +1 -1
  52. package/package.json +13 -1
  53. package/src/Components.tsx +45 -0
  54. package/src/changes/ChangeMark.tsx +165 -0
  55. package/src/changes/ChangingText.tsx +46 -0
  56. package/src/changes/FallbackMark.tsx +59 -0
  57. package/src/changes/blocks.ts +25 -0
  58. package/src/changes/changeDurations.ts +31 -0
  59. package/src/changes/changesIn.ts +479 -0
  60. package/src/changes/readText.ts +123 -0
  61. package/src/changes/rehypeChanges.ts +302 -0
  62. package/src/changes/useTextChanges.ts +239 -0
  63. package/src/changes/visibleBlocks.ts +121 -0
  64. package/src/changes.ts +14 -0
  65. package/src/index.ts +4 -0
@@ -0,0 +1,25 @@
1
+ /**
2
+ * The block elements: a hard feed before and after each in the reading (`readText`), so that no
3
+ * change runs across one's edge.
4
+ */
5
+ export const BLOCK_ELEMENTS: ReadonlySet<string> = new Set([
6
+ 'address', 'article', 'aside', 'blockquote', 'caption', 'dd', 'details', 'div', 'dl', 'dt', 'fieldset',
7
+ 'figcaption', 'figure', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'header', 'hgroup', 'hr',
8
+ 'li', 'main', 'nav', 'ol', 'p', 'pre', 'section', 'summary', 'table', 'tbody', 'td', 'tfoot', 'th',
9
+ 'thead', 'tr', 'ul',
10
+ ]);
11
+
12
+ /** Elements holding blocks, not text: the white space among their children (remark-rehype's line
13
+ * ends) is never marked (a mark there would draw an empty line). */
14
+ export const HOLDS_BLOCKS: ReadonlySet<string> = new Set([
15
+ 'blockquote', 'ul', 'ol', 'table', 'thead', 'tbody', 'tfoot', 'tr', 'section', 'div',
16
+ ]);
17
+
18
+ /**
19
+ * The blocks the changes plugin numbers by default (`data-vultus-block`, pre-order from 1), which a
20
+ * near set names: what the reader's eye rests on. A quote and the paragraph in it, a list item and
21
+ * a nested item, are each one.
22
+ */
23
+ export const NUMBERED_BLOCKS: ReadonlySet<string> = new Set([
24
+ 'p', 'li', 'blockquote', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'pre', 'td', 'th',
25
+ ]);
@@ -0,0 +1,31 @@
1
+ import type { ChangeMarkComponent } from '../Components.js';
2
+
3
+ /** How fast a switch's marks run (the lent mark's `speed`, `useTextChanges`' `speed`): `normal` by
4
+ * default. What each speed's times are is the lent mark's: its look, and its `durations`. */
5
+ export type ChangeSpeed = 'slow' | 'normal' | 'fast';
6
+
7
+ /** When a switch's marks may go, in ms from the commit that shows the new text: on the `plain`
8
+ * timeline (no removed letters) and on `removals`. */
9
+ export interface ChangeDurations {
10
+ plain: number;
11
+ removals: number;
12
+ }
13
+
14
+ /** vultus's timings, in ms, for a page whose mark gives none: a change highlight's at normal
15
+ * speed, as a style library's lent mark runs it, the end of its timeline plus 0.5 s. `plain`:
16
+ * hold 0.3 s and fade 0.75 s; `removals`: remove-hold 0.15 s, squeeze 0.3 s and grow 0.3 s before
17
+ * them. */
18
+ const DEFAULTS: Readonly<ChangeDurations> = { plain: 1550, removals: 2300 };
19
+
20
+ /**
21
+ * When a switch's marks may go: the lent mark's (`mark`, the `ChangeMark` an app lends through
22
+ * `VultusComponents`) `durations(element, speed)`, the timings of its look, read at `element` (the
23
+ * near container, else none) at `speed` (`normal` by default).
24
+ *
25
+ * Without a mark, or one that gives no `durations`, vultus's defaults: 1.55 s on the plain timeline
26
+ * and 2.3 s on removals, at every speed, so a page without a look still ends a switch and its marks
27
+ * go. A new object each call.
28
+ */
29
+ export function changeDurations(element?: Element, speed: ChangeSpeed = 'normal', mark?: ChangeMarkComponent): ChangeDurations {
30
+ return mark?.durations ? mark.durations(element, speed) : { ...DEFAULTS };
31
+ }
@@ -0,0 +1,479 @@
1
+ import { DIFF_DELETE, DIFF_EQUAL, DIFF_INSERT, diff_match_patch } from 'diff-match-patch';
2
+
3
+ /** How much of a change is marked: the changed word whole, or only its changed letters; or the
4
+ * old letters that went (`removed`), at their place. And, a mark's alone (`rehypeChanges`'s; no
5
+ * `Change` has it), a replacement (`replaced`): the old letters and the new ones that took their
6
+ * place, in one mark around the two. */
7
+ export type ChangeLevel = 'word' | 'letters' | 'removed' | 'replaced';
8
+
9
+ /** A span of the new text (UTF-16 offsets, `end` exclusive) that differs from the old one; a
10
+ * `removed` one has no width (`start === end`), its place in the new text. */
11
+ export interface Change {
12
+ start: number;
13
+ end: number;
14
+ level: ChangeLevel;
15
+ /** The old letters that went at this place: a `removed` change's alone. */
16
+ text?: string;
17
+ }
18
+
19
+ /** A word, or one punctuation character, of a text, by its offsets. */
20
+ export interface Token {
21
+ start: number;
22
+ end: number;
23
+ word: boolean;
24
+ }
25
+
26
+ /** diff-match-patch's time budget for one call, in seconds: the diff runs in the render that shows
27
+ * the new text, so a long text must not hold that render up. Past it the diff is coarser, not
28
+ * wrong. */
29
+ const DIFF_TIMEOUT_S = 0.2;
30
+
31
+ /**
32
+ * The share of letters past which something is replaced whole rather than letter by letter. A
33
+ * change is replaced whole, its old run removed whole before its new one, lit whole, when more than
34
+ * this share of the new run's letters were put in or of the old run's letters removed, both ways
35
+ * alike ("t. i." to "tudniillik": `[-t. i.][+tudniillik]`; back: `[-tudniillik][+t. i.]`). In a
36
+ * change that is not, a word more than this share of whose letters were put in is marked whole.
37
+ * This is the one place to change it.
38
+ */
39
+ const WHOLE_WORD_SHARE = 0.5;
40
+
41
+ /**
42
+ * The longest new run (UTF-16 units, first token to last) a change replaced whole is lit as: one
43
+ * piece of the lent mark's, which may not wrap, so no longer than fits a phone's line with room to
44
+ * spare. A longer one is lit word by word (each word with more than `WHOLE_WORD_SHARE` of its
45
+ * letters put in, whole).
46
+ */
47
+ const WHOLE_RUN_LENGTH = 24;
48
+
49
+ const WORD_RUN = /[\p{L}\p{M}\p{N}]+|\S/gu;
50
+
51
+ /**
52
+ * Splits a text into the units the comparison works on: a word is a run of letters, combining
53
+ * marks and digits, every other run of non-space characters is punctuation, one token per
54
+ * character, white space is no token. So "napról-napra" is a word, a hyphen and a word, and the
55
+ * hyphen's going is a change of its own that marks no word.
56
+ */
57
+ export function tokens(text: string): Token[] {
58
+ return Array.from(text.matchAll(WORD_RUN), (match) => ({
59
+ start: match.index,
60
+ end: match.index + match[0].length,
61
+ word: /^[\p{L}\p{M}\p{N}]/u.test(match[0]),
62
+ }));
63
+ }
64
+
65
+ /**
66
+ * Whether the character at an offset of `text` is white space that ends a line: each character of
67
+ * a white-space run holding '\n' or '\r' (a hard boundary, `changesIn`). Computed once per text.
68
+ */
69
+ export function lineEnds(text: string): (at: number) => boolean {
70
+ const ends = new Set<number>();
71
+ for (const run of text.matchAll(/\s+/g)) {
72
+ if (!/[\n\r]/.test(run[0])) continue;
73
+ for (let at = run.index; at < run.index + run[0].length; at++) ends.add(at);
74
+ }
75
+ return (at) => ends.has(at);
76
+ }
77
+
78
+ /**
79
+ * What changed between two versions of a text, as spans of the new one at two levels (GitHub-diff
80
+ * style): `word` spans, the changed words whole, never overlapping; and inside them `letters`
81
+ * spans, the changed letters. Compared word by word (each distinct token one character of an
82
+ * alphabet, so diff-match-patch's line-of-characters speed carries over to words), then, per
83
+ * change, letter by letter. A change that only inserts marks its words at both levels; one that
84
+ * replaces words is compared letter by letter, only the letters that differ marked ("Ferencz" to
85
+ * "Ferenc": the "z" removed and nothing lit).
86
+ * A change replaced whole (`WHOLE_WORD_SHARE` of the new run's letters put in, or of the old
87
+ * run's removed: "t. i." to "tudniillik" and back) is one span, its new run lit whole and the old
88
+ * one removed whole before it, when short (`WHOLE_RUN_LENGTH`); otherwise a word more than
89
+ * `WHOLE_WORD_SHARE` of whose letters are new is marked whole at the letter level, the old text it
90
+ * stands for removed before it. A split, one old word become several ("jóhirű" to "jó
91
+ * hírű": a space put in between two old letters), is one `word` span over the new run, the space
92
+ * among its letters, growing in as they do. Punctuation alone is never
93
+ * marked: a change of punctuation alone marks nothing ("napról-napra" to "napról napra").
94
+ *
95
+ * A changed word's `word` span runs from white space to white space, on every switch: the
96
+ * punctuation touching it (a comma, an opening quote)
97
+ * is inside its mark, lit lightly with it ("hivei," to "hívei,": "hívei,"), never at the letter
98
+ * level; a line may break around the lent mark's removal pieces, so a comma outside the mark could
99
+ * start the next line. The changed words of one run of non-space characters share one span. A new
100
+ * word in place of nothing (put in, or marked whole with no old text before it) holds one space
101
+ * beside it in both its spans, the one between it and the next token (at the end, the one between
102
+ * the token before and it: "a b" to "a b új", " új"), so that growing in from no width it leaves
103
+ * one space between its neighbours, not two.
104
+ *
105
+ * A line feed in `to` is a hard boundary (`lineEnds`: every character of a white-space run holding
106
+ * '\n' or '\r'). The reading (`readText`) puts one exactly where a line really ends: between
107
+ * blocks, at a `br`, at a code line's end. A line feed in a mark would be written as a space and
108
+ * join the lines, so a new word takes no such space, and neither a split nor a run replaced whole
109
+ * is one span across one (the run is lit word by word, as a long one is). Only hard boundaries
110
+ * moved (a paragraph split or joined) is no change: white space is no token.
111
+ *
112
+ * And what went: the old letters each change removed, as `removed` changes of no width at their
113
+ * place in the new text, carrying them (`text`, its white space collapsed: never a line feed,
114
+ * which the lent mark's pieces may keep as a break). Inside a changed word, before the letters
115
+ * that replaced them ("hivei" to "hívei": the "i" before the "í"; "katholikus" to "katolikus": the
116
+ * "h" between "t" and "o"), white space and punctuation too (a space joined away: "szent
117
+ * áldozásban" to "szentáldozásban"), never between a letter and its combining mark; at a word
118
+ * marked whole, the old text it replaced, whole, before it ("t. i." before "tudniillik"). What
119
+ * went outside every word's span is not shown. A change that removed
120
+ * words and put in none (a word removed altogether) gets a `word` span of no width at the start
121
+ * of the token after it (past the last one, at the end of the text), holding the run with the
122
+ * space that separated it: after it ("a b c" to "a c": "b "), or before it where nothing separates
123
+ * the place from the token before it (at the end: "a b c" to "a b", " c"; before punctuation:
124
+ * "mondta ő, hogy" to "mondta, hogy", " ő"), so it sits between its neighbours as it did. A run
125
+ * that touched the token before it (punctuation first) goes at that token's end instead, with no
126
+ * space after it ("Péter, a halász, mondta" to "Péter mondta": ", a halász,"). So does a run that
127
+ * ended its line, where the new text keeps that line end, with the space before it: a word removed
128
+ * at a paragraph's end stays in that paragraph ("a b\nc d" to "a\nc d": " b"); a line end only the
129
+ * old text had places nothing ("a b\nc d" to "a d": "b c "). More distinct tokens than there are
130
+ * code units to stand for them gives `[]`: no marks rather than a wrong or a slow diff.
131
+ */
132
+ export function changesIn(from: string, to: string): Change[] {
133
+ const fromTokens = tokens(from);
134
+ const toTokens = tokens(to);
135
+
136
+ const alphabet = new Map<string, string>();
137
+ let next = 1;
138
+ const unitFor = (text: string): string | undefined => {
139
+ const known = alphabet.get(text);
140
+ if (known !== undefined) return known;
141
+ if (next === 0xd800) next = 0xe000;
142
+ if (next > 0xffff) return undefined;
143
+ const unit = String.fromCharCode(next++);
144
+ alphabet.set(text, unit);
145
+ return unit;
146
+ };
147
+ const encode = (source: string, list: Token[]): string | undefined => {
148
+ let encoded = '';
149
+ for (const token of list) {
150
+ const unit = unitFor(source.slice(token.start, token.end));
151
+ if (unit === undefined) return undefined;
152
+ encoded += unit;
153
+ }
154
+ return encoded;
155
+ };
156
+ const a = encode(from, fromTokens);
157
+ const b = a === undefined ? undefined : encode(to, toTokens);
158
+ if (a === undefined || b === undefined) return [];
159
+
160
+ const dmp = new diff_match_patch();
161
+ dmp.Diff_Timeout = DIFF_TIMEOUT_S;
162
+ // One deadline for the whole call, shared by every diff in it.
163
+ const deadline = Date.now() + DIFF_TIMEOUT_S * 1000;
164
+ const diffs = dmp.diff_main(a, b, false, deadline);
165
+ const lineEnd = lineEnds(to);
166
+ const fromLineEnd = lineEnds(from);
167
+
168
+ const changes: Change[] = [];
169
+ let i = 0;
170
+ let j = 0;
171
+ let k = 0;
172
+ while (k < diffs.length) {
173
+ const [op, text] = diffs[k];
174
+ if (op === DIFF_EQUAL) {
175
+ i += text.length;
176
+ j += text.length;
177
+ k++;
178
+ continue;
179
+ }
180
+ const deletedFrom = i;
181
+ const insertedFrom = j;
182
+ while (k < diffs.length && diffs[k][0] !== DIFF_EQUAL) {
183
+ if (diffs[k][0] === DIFF_DELETE) i += diffs[k][1].length;
184
+ else j += diffs[k][1].length;
185
+ k++;
186
+ }
187
+ const deleted = fromTokens.slice(deletedFrom, i);
188
+ const inserted = toTokens.slice(insertedFrom, j);
189
+ if (inserted.some((token) => token.word)) addChange(changes, from, deleted, to, inserted, toTokens[j], lineEnd, dmp, deadline);
190
+ else if (deleted.some((token) => token.word)) {
191
+ addRemoval(changes, from, deleted, toTokens[insertedFrom - 1], toTokens[insertedFrom], lineEnd, fromLineEnd);
192
+ }
193
+ }
194
+ return toWhiteSpace(changes, to);
195
+ }
196
+
197
+ /**
198
+ * `changes` (in the order `addChange` and `addRemoval` give them, each level's in place order)
199
+ * with each word's span widened from white space to white space in `to` (`changesIn`), an edge
200
+ * that holds a space already left as it is, and the words of one run of non-space characters
201
+ * merged into one span; a word removed altogether inside one of them (beside a changed word) is
202
+ * no word of its own there, and what went outside every word's span is dropped.
203
+ */
204
+ function toWhiteSpace(changes: Change[], to: string): Change[] {
205
+ const spans: Change[] = [];
206
+ for (const change of changes) {
207
+ if (change.level !== 'word' || change.start === change.end) continue;
208
+ let { start, end } = change;
209
+ if (!/\s/.test(to.charAt(start))) while (start > 0 && !/\s/.test(to.charAt(start - 1))) start--;
210
+ if (!/\s/.test(to.charAt(end - 1))) while (end < to.length && !/\s/.test(to.charAt(end))) end++;
211
+ const last = spans[spans.length - 1];
212
+ if (last && start < last.end) last.end = Math.max(last.end, end);
213
+ else spans.push({ start, end, level: 'word' });
214
+ }
215
+ // The places come in order: one pointer finds the span each is in, at an edge too.
216
+ let s = 0;
217
+ const inSpan = (at: number) => {
218
+ while (s < spans.length && spans[s]!.end < at) s++;
219
+ return s < spans.length && spans[s]!.start <= at;
220
+ };
221
+ const out: Change[] = [];
222
+ let next = 0;
223
+ let lone: number | undefined;
224
+ for (const change of changes) {
225
+ if (change.level === 'letters') out.push(change);
226
+ else if (change.level === 'word' && change.start < change.end) {
227
+ // Its widened span, put in at the first of its words.
228
+ if (next < spans.length && spans[next]!.start <= change.start) out.push(spans[next++]!);
229
+ } else if (change.level === 'word') {
230
+ lone = inSpan(change.start) ? undefined : change.start;
231
+ if (lone !== undefined) out.push(change);
232
+ } else if (change.start === lone || inSpan(change.start)) out.push(change);
233
+ }
234
+ return out;
235
+ }
236
+
237
+ /**
238
+ * One change that put in a word: the old tokens it removed, the new ones it inserted (`after`, the
239
+ * token of `to` after them), appended to `changes` as `word` spans (on the words alone, widened
240
+ * later: `toWhiteSpace`), their `letters` and what went (`removed`, in place order, before the
241
+ * letters at the same place); `lineEnd`, `to`'s line ends (`lineEnds`). Appends one by one: a
242
+ * change of a hundred thousand words must not become a call's arguments.
243
+ */
244
+ function addChange(
245
+ changes: Change[],
246
+ from: string,
247
+ deleted: Token[],
248
+ to: string,
249
+ inserted: Token[],
250
+ after: Token | undefined,
251
+ lineEnd: (at: number) => boolean,
252
+ dmp: InstanceType<typeof diff_match_patch>,
253
+ deadline: number,
254
+ ): void {
255
+ // Whether a token comes after the inserted one at `n`, for the space a new word takes.
256
+ const followed = (n: number) => (inserted[n + 1] ?? after) !== undefined;
257
+ // Whether `to`'s `start`-`end` holds a line end that must stay one (`changesIn`).
258
+ const crossesLineEnd = (start: number, end: number) => {
259
+ for (let at = start; at < end; at++) if (/\s/.test(to.charAt(at)) && lineEnd(at)) return true;
260
+ return false;
261
+ };
262
+ if (deleted.length === 0) {
263
+ let taken = 0;
264
+ for (let n = 0; n < inserted.length; n++) {
265
+ const word = inserted[n]!;
266
+ if (!word.word) continue;
267
+ const { start, end } = withSpace(word, followed(n), to, taken, lineEnd);
268
+ changes.push({ start, end, level: 'word' });
269
+ changes.push({ start, end, level: 'letters' });
270
+ taken = end;
271
+ }
272
+ return;
273
+ }
274
+
275
+ // The old run's text as it stands, its white space collapsed, so what went reads as it was
276
+ // ("t. i.", not "t . i ."); the new run's tokens joined by single spaces, as the offsets below
277
+ // count them (where the new text joins a word and a comma, the diff sees a space put in, which
278
+ // marks nothing). For each character of the new side, whether the letter diff inserted it; for
279
+ // each place of it, where the old side is there, past what went at it; and what went at a place.
280
+ const oldText = from.slice(deleted[0]!.start, deleted[deleted.length - 1]!.end).replace(/\s+/g, ' ');
281
+ const newText = inserted.map((token) => to.slice(token.start, token.end)).join(' ');
282
+ const diffs = dmp.diff_main(oldText, newText, false, deadline);
283
+ const isNew: boolean[] = new Array<boolean>(newText.length).fill(false);
284
+ const oldAt: number[] = [];
285
+ const went = new Map<number, { start: number; end: number }>();
286
+ let position = 0;
287
+ let old = 0;
288
+ for (const [op, text] of diffs) {
289
+ if (op === DIFF_DELETE) {
290
+ const there = went.get(position);
291
+ if (there) there.end += text.length;
292
+ else went.set(position, { start: old, end: old + text.length });
293
+ old += text.length;
294
+ continue;
295
+ }
296
+ for (let c = 0; c < text.length; c++) oldAt.push(op === DIFF_EQUAL ? old + c : old);
297
+ if (op === DIFF_INSERT) isNew.fill(true, position, position + text.length);
298
+ else old += text.length;
299
+ position += text.length;
300
+ }
301
+ oldAt.push(old);
302
+
303
+ // Replaced whole, a short run on one line: the old run removed whole before the new one, lit
304
+ // whole.
305
+ const first = inserted[0]!;
306
+ const last = inserted[inserted.length - 1]!;
307
+ if (last.end - first.start <= WHOLE_RUN_LENGTH && !crossesLineEnd(first.start, last.end) && replacedWhole(diffs)) {
308
+ changes.push({ start: first.start, end: last.end, level: 'word' });
309
+ changes.push({ start: first.start, end: first.start, level: 'removed', text: oldText });
310
+ changes.push({ start: first.start, end: last.end, level: 'letters' });
311
+ return;
312
+ }
313
+
314
+ // Letters lit, `start`-`end`, run on from the ones just before them, in one word's span (a word
315
+ // marked whole has letters of its own: one piece over several words could not wrap).
316
+ const addLetters = (start: number, end: number) => {
317
+ const last = changes[changes.length - 1]!;
318
+ if (last.level === 'letters' && last.end === start && span !== undefined && last.start >= span.start) last.end = end;
319
+ else changes.push({ start, end, level: 'letters' });
320
+ };
321
+
322
+ // A place of the joined new side belongs to the token it is in or at an edge of (the space
323
+ // joining two tokens has a place at each end).
324
+ let offset = 0;
325
+ let taken = 0;
326
+ let span: Change | undefined;
327
+ for (let n = 0; n < inserted.length; n++) {
328
+ const token = inserted[n]!;
329
+ const length = token.end - token.start;
330
+ if (token.word) {
331
+ const word = to.slice(token.start, token.end);
332
+ const marked = wholeCharacters(word, isNew.slice(offset, offset + length));
333
+ const count = marked.filter(Boolean).length;
334
+ const whole = count > length * WHOLE_WORD_SHARE;
335
+ // A new word: the old text it stands for, from before what went at its start to past what
336
+ // went at its end, removed before it whole; with none, it holds the space beside it, as a
337
+ // word put in does.
338
+ const text = whole ? oldText.slice(went.get(offset)?.start ?? oldAt[offset]!, oldAt[offset + length]!) : '';
339
+ const { start, end } = whole && !text ? withSpace(token, followed(n), to, taken, lineEnd) : token;
340
+ // A split ("jóhirű" to "jó hírű"): the space between this word and the one before was put in
341
+ // between two old letters (on one line); the span before goes on over both, the space among
342
+ // its letters.
343
+ const previous = inserted[n - 1];
344
+ const joint = offset - 1;
345
+ if (previous?.word && span?.end === previous.end && isNew[joint] && !isNew[joint - 1] && !isNew[offset]
346
+ && !crossesLineEnd(previous.end, token.start)) {
347
+ span.end = end;
348
+ addLetters(previous.end, token.start);
349
+ } else changes.push(span = { start, end, level: 'word' });
350
+ taken = end;
351
+ if (whole) {
352
+ if (text) changes.push({ start, end: start, level: 'removed', text });
353
+ changes.push({ start, end, level: 'letters' });
354
+ } else {
355
+ // What went inside the word, each at the start of the character it went in.
356
+ const removed = new Map<number, string>();
357
+ for (let c = 0; c <= length; c++) {
358
+ const gone = went.get(offset + c);
359
+ if (!gone) continue;
360
+ const at = characterStart(word, c);
361
+ removed.set(at, (removed.get(at) ?? '') + oldText.slice(gone.start, gone.end));
362
+ }
363
+ for (let c = 0; c <= length; c++) {
364
+ const lost = removed.get(c);
365
+ if (lost) changes.push({ start: token.start + c, end: token.start + c, level: 'removed', text: lost });
366
+ if (c < length && marked[c]) addLetters(token.start + c, token.start + c + 1);
367
+ }
368
+ }
369
+ } else {
370
+ // Punctuation: what went at it shows where it touches a changed word, inside the word's span.
371
+ for (let c = 0; c <= length; c++) {
372
+ const gone = went.get(offset + c);
373
+ if (gone) changes.push({ start: token.start + c, end: token.start + c, level: 'removed', text: oldText.slice(gone.start, gone.end) });
374
+ }
375
+ }
376
+ offset += length + 1;
377
+ }
378
+ }
379
+
380
+ /**
381
+ * One change that removed words and put in none (punctuation at most), appended to `changes`: a
382
+ * `word` span of no width where it went, holding the run `removed` with the space that separated
383
+ * it, its white space collapsed (`changesIn`). `before` and `after` are the tokens of the new text
384
+ * around the place: the start of `after`, or at the end the end of `before`; the end of `before`
385
+ * too where the run touched it, or where it ended its line (`fromLineEnd` after it) and the new
386
+ * text keeps a line end after `before` (`toLineEnd`). The space after the run unless the place is
387
+ * at the end, the run touched `before` or ended its line; the space before it where no space
388
+ * separates the place from `before` (at the end, before punctuation, at a line's end).
389
+ */
390
+ function addRemoval(
391
+ changes: Change[],
392
+ from: string,
393
+ deleted: Token[],
394
+ before: Token | undefined,
395
+ after: Token | undefined,
396
+ toLineEnd: (at: number) => boolean,
397
+ fromLineEnd: (at: number) => boolean,
398
+ ): void {
399
+ const first = deleted[0]!;
400
+ const last = deleted[deleted.length - 1]!;
401
+ // A run that touched the token before it in the old text (punctuation: "Péter, a halász,
402
+ // mondta" to "Péter mondta") goes at that token's end, the space after it left where it is.
403
+ const touching = before !== undefined && !first.word && first.start > 0 && !/\s/.test(from.charAt(first.start - 1));
404
+ // A run that ended its line stays on it where the new text keeps the line end: a word removed at
405
+ // a paragraph's end shows in that paragraph, not at the next one's start.
406
+ const endedLine = !touching && before !== undefined && after !== undefined
407
+ && toLineEnd(before.end) && fromLineEnd(last.end);
408
+ const place = touching || endedLine ? before!.end : after?.start ?? before?.end ?? 0;
409
+ const glued = before !== undefined && before.end === place;
410
+ const spaceBefore = glued && /\s/.test(from.charAt(first.start - 1)) ? ' ' : '';
411
+ const spaceAfter = !touching && !endedLine && after !== undefined && /\s/.test(from.charAt(last.end)) ? ' ' : '';
412
+ const run = from.slice(first.start, last.end).replace(/\s+/g, ' ');
413
+ changes.push({ start: place, end: place, level: 'word' });
414
+ changes.push({ start: place, end: place, level: 'removed', text: spaceBefore + run + spaceAfter });
415
+ }
416
+
417
+ /** Whether a letter diff replaced its texts whole: more than `WHOLE_WORD_SHARE` of the new side's
418
+ * letters (letters, marks, digits) put in, or of the old side's removed. */
419
+ function replacedWhole(diffs: [number, string][]): boolean {
420
+ let old = 0;
421
+ let removed = 0;
422
+ let now = 0;
423
+ let put = 0;
424
+ for (const [op, text] of diffs) {
425
+ let letters = 0;
426
+ for (const character of text) if (/[\p{L}\p{M}\p{N}]/u.test(character)) letters++;
427
+ if (op === DIFF_DELETE) removed += letters;
428
+ else now += letters;
429
+ if (op === DIFF_INSERT) put += letters;
430
+ else old += letters;
431
+ }
432
+ return put > now * WHOLE_WORD_SHARE || removed > old * WHOLE_WORD_SHARE;
433
+ }
434
+
435
+ /** `word`'s span with the space beside it (`changesIn`): the one between it and the next token when
436
+ * one comes after it (`followed`), else the one between the token before and it, unless a span
437
+ * before took that one (`taken`, the end of the last); none where the word touches punctuation,
438
+ * nor where that space is a line end that must stay one (`lineEnd`). */
439
+ function withSpace(word: Token, followed: boolean, to: string, taken: number, lineEnd: (at: number) => boolean): { start: number; end: number } {
440
+ const space = (at: number) => /\s/.test(to.charAt(at)) && !lineEnd(at);
441
+ if (followed) return { start: word.start, end: space(word.end) ? word.end + 1 : word.end };
442
+ const before = word.start - 1 >= taken && space(word.start - 1);
443
+ return { start: before ? word.start - 1 : word.start, end: word.end };
444
+ }
445
+
446
+ /** The start of the character `word`'s offset `c` is in: `c` moved back past a combining mark or
447
+ * the second half of a surrogate pair, so a removal there never cuts a character. */
448
+ function characterStart(word: string, c: number): number {
449
+ let at = c;
450
+ while (at > 0 && at < word.length) {
451
+ const unit = word.charCodeAt(at);
452
+ if (!(unit >= 0xdc00 && unit <= 0xdfff) && !/^\p{M}/u.test(word.slice(at, at + 2))) break;
453
+ at--;
454
+ }
455
+ return at;
456
+ }
457
+
458
+ /**
459
+ * `marked` (one flag per UTF-16 unit of `word`) widened to whole characters: a surrogate pair is
460
+ * marked whole, and a combining mark goes with the letter before it, so a span never cuts a
461
+ * character ("o" + U+0308 is lit together).
462
+ */
463
+ function wholeCharacters(word: string, marked: boolean[]): boolean[] {
464
+ const widened = marked.slice();
465
+ let clusterStart = 0;
466
+ let position = 0;
467
+ const close = (end: number) => {
468
+ if (marked.slice(clusterStart, end).some(Boolean)) widened.fill(true, clusterStart, end);
469
+ };
470
+ for (const character of word) {
471
+ if (position > 0 && !/^\p{M}/u.test(character)) {
472
+ close(position);
473
+ clusterStart = position;
474
+ }
475
+ position += character.length;
476
+ }
477
+ close(position);
478
+ return widened;
479
+ }
@@ -0,0 +1,123 @@
1
+ import type { Element, Root, Text } from 'hast';
2
+ import { BLOCK_ELEMENTS } from './blocks.js';
3
+
4
+ /** What the reading leaves out besides `data-vultus-change-skip`: the app's choice, since only it
5
+ * knows which elements hold no text of its own (a footnote's mark and back link, a notes heading
6
+ * for screen readers, rendered math). */
7
+ export interface ReadTextOptions {
8
+ /** Whether an element is left out of the reading, with all it holds. */
9
+ skip?: (element: Element) => boolean;
10
+ }
11
+
12
+ /** A text node read; `start`: where its value begins in the source (the nodes' values in document
13
+ * order, one '\n' per feed). */
14
+ export interface TextPiece {
15
+ node: Text;
16
+ parent: Element | Root;
17
+ start: number;
18
+ }
19
+
20
+ /** `offsets[i]`: the source offset of `text[i]` (a collapsed run's, its first); one more entry,
21
+ * the source offset after the last character. */
22
+ export interface TextPlaces {
23
+ pieces: TextPiece[];
24
+ offsets: number[];
25
+ }
26
+
27
+ /** A tree's text as `readText` reads it, and the map back to its text nodes. */
28
+ export interface Reading {
29
+ text: string;
30
+ places: TextPlaces;
31
+ }
32
+
33
+ /**
34
+ * The reading of a hast tree, which both sides of a diff use: its text nodes' values in
35
+ * document order, prose white space collapsed to one space (soft line breaks too, so a source line
36
+ * end inside "t. i." does not split it), and a line feed, a hard boundary for `changesIn`, exactly
37
+ * where a line really ends: before and after every block element (`BLOCK_ELEMENTS`), at a `br`, and
38
+ * at each line feed inside a `pre`. A run of white space becomes one '\n' where it holds a hard
39
+ * feed, else one ' '; the text is trimmed. An element `isSkipped` names is left out with all it
40
+ * holds, adding not even a feed. An element given as the tree reads as its children; a `pre`
41
+ * given as the tree keeps its line feeds hard.
42
+ *
43
+ * `places` maps the text back: `pieces`, the text nodes read, each with its parent and where its
44
+ * value begins in the source (the values joined in document order, one '\n' per feed); `offsets`,
45
+ * each character's source offset, then the one after the last.
46
+ */
47
+ export function readText(tree: Root | Element, options?: ReadTextOptions): Reading {
48
+ const pieces: TextPiece[] = [];
49
+ const chunks: string[] = [];
50
+ // The source offsets of the hard feeds: those put in, and a `pre`'s line feeds.
51
+ const hard = new Set<number>();
52
+ let length = 0;
53
+ const feed = () => {
54
+ hard.add(length);
55
+ chunks.push('\n');
56
+ length += 1;
57
+ };
58
+ const visit = (parent: Root | Element, inPre: boolean) => {
59
+ for (const child of parent.children) {
60
+ if (child.type === 'text') {
61
+ pieces.push({ node: child, parent, start: length });
62
+ if (inPre) {
63
+ for (let c = 0; c < child.value.length; c++) {
64
+ const unit = child.value.charAt(c);
65
+ if (unit === '\n' || unit === '\r') hard.add(length + c);
66
+ }
67
+ }
68
+ chunks.push(child.value);
69
+ length += child.value.length;
70
+ } else if (child.type === 'element') {
71
+ if (isSkipped(child, options)) continue;
72
+ if (child.tagName === 'br') {
73
+ feed();
74
+ continue;
75
+ }
76
+ const block = BLOCK_ELEMENTS.has(child.tagName);
77
+ if (block) feed();
78
+ visit(child, inPre || child.tagName === 'pre');
79
+ if (block) feed();
80
+ }
81
+ }
82
+ };
83
+ visit(tree, tree.type === 'element' && tree.tagName === 'pre');
84
+ const source = chunks.join('');
85
+
86
+ // Each white-space run one character, '\n' where it holds a hard feed; each character's source
87
+ // offset (a run's, its first), then the source's length.
88
+ let text = '';
89
+ const offsets: number[] = [];
90
+ let pos = 0;
91
+ for (const run of source.matchAll(/\s+/g)) {
92
+ for (let i = pos; i < run.index; i++) offsets.push(i);
93
+ const end = run.index + run[0].length;
94
+ let feeds = false;
95
+ for (let at = run.index; at < end && !feeds; at++) feeds = hard.has(at);
96
+ text += `${source.slice(pos, run.index)}${feeds ? '\n' : ' '}`;
97
+ offsets.push(run.index);
98
+ pos = end;
99
+ }
100
+ for (let i = pos; i < source.length; i++) offsets.push(i);
101
+ text += source.slice(pos);
102
+ offsets.push(source.length);
103
+
104
+ // Trimmed: a run at the start goes with its offset; one at the end leaves its offset, its run's
105
+ // first, as the one after the last character kept.
106
+ if (/^\s/.test(text)) {
107
+ text = text.slice(1);
108
+ offsets.shift();
109
+ }
110
+ if (/\s$/.test(text)) {
111
+ text = text.slice(0, -1);
112
+ offsets.pop();
113
+ }
114
+ return { text, places: { pieces, offsets } };
115
+ }
116
+
117
+ /** Whether `element` is left out of the reading, with all it holds: `data-vultus-change-skip`
118
+ * present (hast `dataVultusChangeSkip`, an empty string too), or `options.skip(element)`. */
119
+ export function isSkipped(element: Element, options?: ReadTextOptions): boolean {
120
+ const flag = element.properties.dataVultusChangeSkip;
121
+ if (flag !== undefined && flag !== null && flag !== false) return true;
122
+ return options?.skip?.(element) ?? false;
123
+ }