vultus-core 0.5.7 → 0.5.9

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 (77) hide show
  1. package/README.md +199 -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/action-core.d.ts +1 -0
  6. package/dist/action-core.d.ts.map +1 -1
  7. package/dist/action-core.js +3 -0
  8. package/dist/action-core.js.map +1 -1
  9. package/dist/changes/ChangeMark.d.ts +85 -0
  10. package/dist/changes/ChangeMark.d.ts.map +1 -0
  11. package/dist/changes/ChangeMark.js +113 -0
  12. package/dist/changes/ChangeMark.js.map +1 -0
  13. package/dist/changes/ChangingText.d.ts +20 -0
  14. package/dist/changes/ChangingText.d.ts.map +1 -0
  15. package/dist/changes/ChangingText.js +31 -0
  16. package/dist/changes/ChangingText.js.map +1 -0
  17. package/dist/changes/FallbackMark.d.ts +20 -0
  18. package/dist/changes/FallbackMark.d.ts.map +1 -0
  19. package/dist/changes/FallbackMark.js +53 -0
  20. package/dist/changes/FallbackMark.js.map +1 -0
  21. package/dist/changes/blocks.d.ts +15 -0
  22. package/dist/changes/blocks.d.ts.map +1 -0
  23. package/dist/changes/blocks.js +24 -0
  24. package/dist/changes/blocks.js.map +1 -0
  25. package/dist/changes/changeDurations.d.ts +21 -0
  26. package/dist/changes/changeDurations.d.ts.map +1 -0
  27. package/dist/changes/changeDurations.js +18 -0
  28. package/dist/changes/changeDurations.js.map +1 -0
  29. package/dist/changes/changesIn.d.ts +88 -0
  30. package/dist/changes/changesIn.d.ts.map +1 -0
  31. package/dist/changes/changesIn.js +470 -0
  32. package/dist/changes/changesIn.js.map +1 -0
  33. package/dist/changes/readText.d.ts +45 -0
  34. package/dist/changes/readText.d.ts.map +1 -0
  35. package/dist/changes/readText.js +99 -0
  36. package/dist/changes/readText.js.map +1 -0
  37. package/dist/changes/rehypeChanges.d.ts +81 -0
  38. package/dist/changes/rehypeChanges.d.ts.map +1 -0
  39. package/dist/changes/rehypeChanges.js +268 -0
  40. package/dist/changes/rehypeChanges.js.map +1 -0
  41. package/dist/changes/useTextChanges.d.ts +93 -0
  42. package/dist/changes/useTextChanges.d.ts.map +1 -0
  43. package/dist/changes/useTextChanges.js +154 -0
  44. package/dist/changes/useTextChanges.js.map +1 -0
  45. package/dist/changes/visibleBlocks.d.ts +42 -0
  46. package/dist/changes/visibleBlocks.d.ts.map +1 -0
  47. package/dist/changes/visibleBlocks.js +104 -0
  48. package/dist/changes/visibleBlocks.js.map +1 -0
  49. package/dist/changes.d.ts +9 -0
  50. package/dist/changes.d.ts.map +1 -0
  51. package/dist/changes.js +10 -0
  52. package/dist/changes.js.map +1 -0
  53. package/dist/index.d.ts +3 -1
  54. package/dist/index.d.ts.map +1 -1
  55. package/dist/index.js.map +1 -1
  56. package/dist/types.d.ts +4 -0
  57. package/dist/types.d.ts.map +1 -1
  58. package/dist/useAction.d.ts.map +1 -1
  59. package/dist/useAction.js +1 -0
  60. package/dist/useAction.js.map +1 -1
  61. package/package.json +13 -1
  62. package/src/Components.tsx +45 -0
  63. package/src/action-core.ts +4 -0
  64. package/src/changes/ChangeMark.tsx +165 -0
  65. package/src/changes/ChangingText.tsx +46 -0
  66. package/src/changes/FallbackMark.tsx +59 -0
  67. package/src/changes/blocks.ts +25 -0
  68. package/src/changes/changeDurations.ts +31 -0
  69. package/src/changes/changesIn.ts +479 -0
  70. package/src/changes/readText.ts +123 -0
  71. package/src/changes/rehypeChanges.ts +302 -0
  72. package/src/changes/useTextChanges.ts +239 -0
  73. package/src/changes/visibleBlocks.ts +121 -0
  74. package/src/changes.ts +14 -0
  75. package/src/index.ts +4 -0
  76. package/src/types.ts +4 -0
  77. package/src/useAction.ts +1 -0
@@ -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
+ }
@@ -0,0 +1,302 @@
1
+ import type { Element, ElementContent, Root, Text } from 'hast';
2
+ import { BLOCK_ELEMENTS, HOLDS_BLOCKS, NUMBERED_BLOCKS } from './blocks.js';
3
+ import { changesIn, type ChangeLevel } from './changesIn.js';
4
+ import { isSkipped, readText, type Reading, type ReadTextOptions } from './readText.js';
5
+
6
+ /** The attribute the plugin numbers the blocks with (`NUMBERED_BLOCKS`), unless it is given an
7
+ * existing numbering's (`blockAttribute`). */
8
+ export const BLOCK_NUMBER_ATTRIBUTE = 'data-vultus-block';
9
+
10
+ /** A data attribute holding a block's number. */
11
+ export type BlockAttribute = `data-${string}`;
12
+
13
+ /** 'data-block' → 'dataBlock', 'data-vultus-block' → 'dataVultusBlock': hast's property for the
14
+ * attribute (property-information's rule: each dash before a lowercase letter goes, the letter
15
+ * capitalised). */
16
+ export function blockProperty(attribute: BlockAttribute): string {
17
+ const rest = attribute.slice(5).replace(/-[a-z]/g, (dash) => dash.charAt(1).toUpperCase());
18
+ return `data${rest.charAt(0).toUpperCase()}${rest.slice(1)}`;
19
+ }
20
+
21
+ /** The property the plugin's own numbering sets. */
22
+ const OWN_PROPERTY = blockProperty(BLOCK_NUMBER_ATTRIBUTE);
23
+
24
+ /** What one run of the plugin read (`onRead`): the part's reading (`readText`'s text), taken
25
+ * before any mark; and whether it cut in a removed mark (`ins[data-change=removed]`). */
26
+ export interface ReadReport {
27
+ reading: string;
28
+ removals: boolean;
29
+ }
30
+
31
+ export interface ChangesPluginOptions {
32
+ /** The part's previous reading; none: read and report only. */
33
+ from?: string;
34
+ /** The frozen near set, by block number; none: all marked. */
35
+ near?: (block: number) => boolean;
36
+ /** An existing numbering's attribute; none: the plugin numbers as `data-vultus-block`. */
37
+ blockAttribute?: BlockAttribute;
38
+ /** What the reading leaves out besides `data-vultus-change-skip` (`readText`). */
39
+ skip?: (element: Element) => boolean;
40
+ /** Called once per run, with what it read. */
41
+ onRead?: (report: ReadReport) => void;
42
+ }
43
+
44
+ /** A span of the source (`readText`'s), `start`-`end`. */
45
+ interface Span {
46
+ start: number;
47
+ end: number;
48
+ }
49
+
50
+ /** A piece's part of a span, `from`-`to` in its own text; `goesOn`, whether the span goes on past
51
+ * the piece's end. */
52
+ interface Cut {
53
+ from: number;
54
+ to: number;
55
+ goesOn: boolean;
56
+ }
57
+
58
+ /** Where old letters went (`removed`), in the source or a piece's own, and those letters. */
59
+ interface Gone {
60
+ at: number;
61
+ text: string;
62
+ }
63
+
64
+ /**
65
+ * A rehype plugin marking in a hast tree what changed from its part's previous reading,
66
+ * `from`. Each run of its transformer:
67
+ * - numbers the blocks (`NUMBERED_BLOCKS`, pre-order from 1, as `data-vultus-block`), a skipped
68
+ * element and all it holds left out, unless `blockAttribute` names an existing numbering;
69
+ * - reads the tree (`readText`, with `skip`) before any mark is cut in, so the reading never holds
70
+ * removed text, on a re-parse during the light-up too, and the same tree gives the same reading;
71
+ * - without `from`, reports it (`onRead`) and is done;
72
+ * - with it, compares the two (`changesIn`), maps the spans back to the text nodes through the
73
+ * reading's `places`, cuts the marks in, and reports the reading and whether it cut in a removed
74
+ * mark (for the switch's timeline: removals anywhere put every part on `removals`).
75
+ *
76
+ * Each piece's part of a changed word goes in an `<ins data-change="word">`, inside its own element
77
+ * (an emphasis, a link, a code token: a word split over elements is marked piece by piece, `*hí*vei`
78
+ * gives two), and its part of the word's changed letters in an `<ins data-change="letters">` inside
79
+ * that. Never a piece between blocks (remark-rehype's line ends, where a mark would draw an empty
80
+ * line: `between`). The reading's line feeds are hard boundaries for `changesIn`, so nothing is lit
81
+ * across a block's edge, a `br` or a code line's end, and a word removed at a paragraph's end stays
82
+ * in that paragraph.
83
+ *
84
+ * The old letters that went are put in at their place, as text in an `<ins data-change="removed">`
85
+ * inside their word's mark, before the letters there; at a place where two pieces of the word meet,
86
+ * in the earlier. A word removed altogether is a word mark of its own holding only them, in the
87
+ * piece where its place is (where two meet, at the end of the earlier: the text before it, not an
88
+ * emphasis starting after it), so removed text never gets a block of its own. A line feed in a
89
+ * `letters` or `removed` mark is put in as a space: the lent mark may keep the white space of their
90
+ * pieces, and would break the line there.
91
+ *
92
+ * A replacement, old letters and the new ones that took their place ("hivei" → "hívei": the "i"
93
+ * and the "í"; "t. i." → "tudniillik", whole), is one `<ins data-change="replaced">` around the
94
+ * two, inside their word's mark, holding nothing else (the lent mark's `change-replaced`). Only when
95
+ * both are in one piece and the new letters end there: one split over pieces (an emphasis between
96
+ * the old letters and the new, "*h*ívei", or among the new ones, "*tudni*illik") is left as two, as
97
+ * is a pure removal or insertion.
98
+ *
99
+ * `ins`, not `mark`: a tag of their own, which `changeComponents`' `ins` entry draws (as the lent
100
+ * mark, or vultus's fallback, a `<mark>`). react-markdown keys an element by its tag's count among
101
+ * its siblings (`mark-0`, `mark-1`), so a search hit put in before a change mark (a search typed
102
+ * during the light-up) would change its key, and React would draw it anew, its fade starting over;
103
+ * counted apart, it keeps its key and its element.
104
+ *
105
+ * With `near` (the switch's frozen near set), only the pieces whose nearest numbered block (by
106
+ * `blockAttribute`, or the own numbering: the innermost holding them) has a number it takes are
107
+ * marked; the others show the new text as it is. The whole text is still compared, so what is
108
+ * marked is what it would be without it. A piece in no numbered block is marked.
109
+ *
110
+ * **Plugin order (a contract, not enforced):** after any plugin that reads or marks text first (a
111
+ * passage's marks: a change is then marked inside the passage's mark), and before plugins that add
112
+ * search marks, which must skip `[data-change=removed]` (the removed letters are no text of the
113
+ * page's).
114
+ */
115
+ export function changesPlugin(options: ChangesPluginOptions): () => (tree: Root) => void {
116
+ return () => (tree) => {
117
+ const { from, near, blockAttribute, skip, onRead } = options;
118
+ const reads: ReadTextOptions = { skip };
119
+ if (blockAttribute === undefined) numbered(tree, reads);
120
+ const reading = readText(tree, reads);
121
+ if (from === undefined) {
122
+ onRead?.({ reading: reading.text, removals: false });
123
+ return;
124
+ }
125
+ const far = near ? outside(tree, near, blockProperty(blockAttribute ?? BLOCK_NUMBER_ATTRIBUTE)) : new Set<Text>();
126
+ const removals = marked(reading, from, far);
127
+ onRead?.({ reading: reading.text, removals });
128
+ };
129
+ }
130
+
131
+ /** `tree`'s `NUMBERED_BLOCKS`, numbered in pre-order from 1 as `data-vultus-block`; a skipped element
132
+ * (`isSkipped`) and all it holds left out. */
133
+ function numbered(tree: Root, options: ReadTextOptions): void {
134
+ let n = 0;
135
+ const visit = (parent: Root | Element) => {
136
+ for (const child of parent.children) {
137
+ if (child.type !== 'element' || isSkipped(child, options)) continue;
138
+ if (NUMBERED_BLOCKS.has(child.tagName)) child.properties[OWN_PROPERTY] = ++n;
139
+ visit(child);
140
+ }
141
+ };
142
+ visit(tree);
143
+ }
144
+
145
+ /** The text of `tree` whose nearest numbered block (`property`, the innermost holding it) has a
146
+ * number `near` refuses; none of the text in no numbered block. */
147
+ function outside(tree: Root, near: (block: number) => boolean, property: string): Set<Text> {
148
+ const found = new Set<Text>();
149
+ const visit = (parent: Root | Element, block: number | undefined) => {
150
+ for (const child of parent.children) {
151
+ if (child.type === 'text') {
152
+ if (block !== undefined && !near(block)) found.add(child);
153
+ } else if (child.type === 'element') {
154
+ const own = child.properties[property];
155
+ visit(child, own === undefined || own === null || own === false ? block : Number(own));
156
+ }
157
+ }
158
+ };
159
+ visit(tree, undefined);
160
+ return found;
161
+ }
162
+
163
+ /** The changes from `old` marked in the tree `reading` was read from: its `text`, and its `places`
164
+ * (the text nodes, `pieces`, and each character's source offset, `map`); `far`, the text not to
165
+ * mark (`outside`). Whether it cut in a removed mark. */
166
+ function marked({ text, places: { pieces, offsets: map } }: Reading, old: string, far: Set<Text>): boolean {
167
+ const changes = changesIn(old, text);
168
+ if (!changes.length) return false;
169
+ // A span maps from its first character to its last: a space at its edge (a new word's), or all
170
+ // of it (a split's), is one of the source's, of a run the one beside the word; a space inside it
171
+ // (a split's word), the run. A place (no width) maps to the character after it.
172
+ const spans = (level: ChangeLevel) => changes
173
+ .filter((change) => change.level === level && change.start < change.end)
174
+ .map(({ start, end }): Span => ({ start: start + 1 < end ? map[start + 1]! - 1 : map[start]!, end: map[end - 1]! + 1 }));
175
+ const places = (level: ChangeLevel) => changes
176
+ .filter((change) => change.level === level && change.start === change.end)
177
+ .map(({ start, text: went }): Gone => ({ at: map[start]!, text: went ?? '' }));
178
+ const words = cutter(spans('word'));
179
+ const letters = cutter(spans('letters'));
180
+ const lone = places('word');
181
+ const gone = places('removed');
182
+ let removals = false;
183
+ // The cutters and the places' pointers go on past a piece left out, to the next one's.
184
+ let w = 0;
185
+ let r = 0;
186
+ for (const { node, parent, start } of pieces) {
187
+ if (between(node, parent) || far.has(node)) continue;
188
+ const end = start + node.value.length;
189
+ const own = words(start, end);
190
+ // A word removed altogether in the first piece reaching its place.
191
+ for (; w < lone.length && lone[w]!.at <= end; w++) {
192
+ if (lone[w]!.at >= start) own.push({ from: lone[w]!.at - start, to: lone[w]!.at - start, goesOn: false });
193
+ }
194
+ if (!own.length) continue;
195
+ own.sort((a, b) => a.from - b.from);
196
+ // The old letters in each word's cut, at its edges too, in the first piece reaching them.
197
+ const removed: Gone[] = [];
198
+ for (const word of own) {
199
+ for (; r < gone.length && gone[r]!.at - start <= word.to; r++) {
200
+ if (gone[r]!.at - start >= word.from) removed.push({ at: gone[r]!.at - start, text: gone[r]!.text });
201
+ }
202
+ }
203
+ const i = parent.children.indexOf(node);
204
+ if (i < 0) continue;
205
+ parent.children.splice(i, 1, ...markedPiece(node.value, own, letters(start, end), removed));
206
+ if (removed.length) removals = true;
207
+ }
208
+ return removals;
209
+ }
210
+
211
+ /** Whether the text `node`, in `parent`, is between blocks (`changesPlugin`): white space whose
212
+ * parent holds blocks (`HOLDS_BLOCKS`, or the root), or white space right before or after a
213
+ * block (a loose list item's or a note's line ends around its paragraph, a tight item's before
214
+ * its nested list). The white space between two inline elements is not, in an item holding a
215
+ * nested list too. Text that is more than white space never is, even directly in a block
216
+ * holder (raw HTML, an app's own tree): it is read, so it is marked. */
217
+ function between(node: Text, parent: Element | Root): boolean {
218
+ if (/\S/.test(node.value)) return false;
219
+ if (parent.type === 'root' || HOLDS_BLOCKS.has(parent.tagName)) return true;
220
+ const i = parent.children.indexOf(node);
221
+ return [parent.children[i - 1], parent.children[i + 1]]
222
+ .some((sibling) => sibling?.type === 'element' && BLOCK_ELEMENTS.has(sibling.tagName));
223
+ }
224
+
225
+ /** For the pieces in document order, each piece's cuts of `spans` (in order, none overlapping): a
226
+ * function of the piece's place in the source, `start`-`end`, called in that order. */
227
+ function cutter(spans: Span[]): (start: number, end: number) => Cut[] {
228
+ let first = 0;
229
+ return (start, end) => {
230
+ while (first < spans.length && spans[first]!.end <= start) first++;
231
+ const cuts: Cut[] = [];
232
+ for (let i = first; i < spans.length && spans[i]!.start < end; i++) {
233
+ const from = Math.max(spans[i]!.start, start) - start;
234
+ const to = Math.min(spans[i]!.end, end) - start;
235
+ if (from < to) cuts.push({ from, to, goesOn: spans[i]!.end > end });
236
+ }
237
+ return cuts;
238
+ };
239
+ }
240
+
241
+ /** `value` as text, its `words` (in order) each in an `<ins data-change="word">`, and its
242
+ * `letters` (each inside one of them) in an `<ins data-change="letters">` inside it, and the old
243
+ * letters that went (`removed`, each inside one of them, at an edge too) in an `<ins
244
+ * data-change="removed">` at their place, before the letters there; a word of no width holds
245
+ * only those. A replacement, old letters and the letters right after them at their place (no
246
+ * other old letters there in between) whose span ends in this piece, is one `<ins
247
+ * data-change="replaced">` around the two (`changesPlugin`). */
248
+ function markedPiece(value: string, words: Cut[], letters: Cut[], removed: Gone[]): ElementContent[] {
249
+ const out: ElementContent[] = [];
250
+ let pos = 0;
251
+ let l = 0;
252
+ let g = 0;
253
+ for (const word of words) {
254
+ if (word.from > pos) out.push(textNode(value.slice(pos, word.from)));
255
+ const inside: ElementContent[] = [];
256
+ let at = word.from;
257
+ const textTo = (to: number) => {
258
+ if (to > at) inside.push(textNode(value.slice(at, to)));
259
+ at = Math.max(at, to);
260
+ };
261
+ // The next letters' mark, the word's text and its letters going on past them.
262
+ const takeLetters = (letter: Cut) => {
263
+ at = letter.to;
264
+ l++;
265
+ return changeMark('letters', [textNode(spaced(value.slice(letter.from, letter.to)))]);
266
+ };
267
+ for (;;) {
268
+ const gone = g < removed.length && removed[g]!.at <= word.to ? removed[g]! : undefined;
269
+ const letter = l < letters.length && letters[l]!.from < word.to ? letters[l]! : undefined;
270
+ if (gone && (!letter || gone.at <= letter.from)) {
271
+ textTo(gone.at);
272
+ const old = changeMark('removed', [textNode(spaced(gone.text))]);
273
+ g++;
274
+ const replaced = letter?.from === gone.at && removed[g]?.at !== gone.at && !letter.goesOn;
275
+ inside.push(replaced ? changeMark('replaced', [old, takeLetters(letter)]) : old);
276
+ } else if (letter) {
277
+ textTo(letter.from);
278
+ inside.push(takeLetters(letter));
279
+ } else break;
280
+ }
281
+ textTo(word.to);
282
+ out.push(changeMark('word', inside));
283
+ pos = word.to;
284
+ }
285
+ if (pos < value.length) out.push(textNode(value.slice(pos)));
286
+ return out;
287
+ }
288
+
289
+ /** A text node of `value`. */
290
+ function textNode(value: string): Text {
291
+ return { type: 'text', value };
292
+ }
293
+
294
+ /** `text` with each line feed in it a space (`changesPlugin`). */
295
+ function spaced(text: string): string {
296
+ return text.replace(/\r\n?|\n/g, ' ');
297
+ }
298
+
299
+ /** A change's mark at `level`, around `children`: an `ins` (see `changesPlugin`). */
300
+ function changeMark(level: ChangeLevel, children: ElementContent[]): Element {
301
+ return { type: 'element', tagName: 'ins', properties: { dataChange: level }, children };
302
+ }
@@ -0,0 +1,239 @@
1
+ import type { Element, Root } from 'hast';
2
+ import { useEffect, useLayoutEffect, useRef, useState } from 'react';
3
+ import { useVultusComponents } from '../Components.js';
4
+ import { changeComponents, changeStore, type ChangeComponents, type ChangeStore, type ChangeTimeline } from './ChangeMark.js';
5
+ import { changeDurations, type ChangeSpeed } from './changeDurations.js';
6
+ import { BLOCK_NUMBER_ATTRIBUTE, changesPlugin, type BlockAttribute, type ReadReport } from './rehypeChanges.js';
7
+ import { useVisibleBlocks, type ContainerOption, type VisibleBlocks } from './visibleBlocks.js';
8
+
9
+ /** `near` as the blocks on screen: those crossing `container` (the scrolling pane) as a switch
10
+ * starts, `blocks` more on each side; `rootMargin`, the observer's (a sticky bar over the pane's
11
+ * top). A ref object is read once, after mount: a pane that mounts later or is replaced is given
12
+ * as the element (a callback ref kept in state), or `near` limits nothing. */
13
+ export interface NearBlocks {
14
+ container: ContainerOption;
15
+ blocks: number;
16
+ rootMargin?: string;
17
+ }
18
+
19
+ export interface TextChangesOptions {
20
+ /** The content's identity: same key, new text animates; a new key swaps plainly. */
21
+ key: string;
22
+ /** `false`: swap plainly once, under the same key too, replacing the reading. */
23
+ animate?: boolean;
24
+ /** The blocks a switch marks, by number: a function, or the blocks on screen (`NearBlocks`);
25
+ * none, all. Frozen per switch. */
26
+ near?: ((block: number) => boolean) | NearBlocks;
27
+ /** An existing numbering's attribute; none: the plugin numbers as `data-vultus-block`. */
28
+ blockAttribute?: BlockAttribute;
29
+ /** What the reading leaves out besides `data-vultus-change-skip`. */
30
+ skip?: (element: Element) => boolean;
31
+ /** How fast a switch's marks run (the lent mark's `speed`): `normal` by default. Taken as a
32
+ * switch starts and held for it, marks and timer alike. */
33
+ speed?: ChangeSpeed;
34
+ }
35
+
36
+ /** One tree's plugin and drawing: `rehypePlugin` for its Markdown's `rehypePlugins`, `components`
37
+ * merged into its `components`. */
38
+ export interface TextChangesPart {
39
+ rehypePlugin: () => (tree: Root) => void;
40
+ components: ChangeComponents;
41
+ }
42
+
43
+ /** The default part's plugin and drawing, the other parts (`part`), and whether a switch's marks
44
+ * are shown (`active`). */
45
+ export interface TextChanges extends TextChangesPart {
46
+ part(name: string): TextChangesPart;
47
+ active: boolean;
48
+ }
49
+
50
+ /** The part `rehypePlugin` and `components` on the result belong to. */
51
+ export const DEFAULT_PART = 'default';
52
+
53
+ /** A switch: its number, each part's previous reading (by part), the near set frozen as it
54
+ * started (none: all marked), and the speed taken then. */
55
+ interface Switch {
56
+ number: number;
57
+ from: Map<string, string>;
58
+ near: ((block: number) => boolean) | undefined;
59
+ speed: ChangeSpeed;
60
+ }
61
+
62
+ /** The text shown, under its key; the switches so far (`count`); the switch running, if any. */
63
+ interface Shown {
64
+ key: string;
65
+ text: string;
66
+ count: number;
67
+ current: Switch | undefined;
68
+ }
69
+
70
+ /** A part's last report: what its plugin read, for which content text, in which switch (0: none). */
71
+ interface Report extends ReadReport {
72
+ text: string;
73
+ number: number;
74
+ }
75
+
76
+ /** The objects of one phase (a switch, or the idle text): its parts, made on demand, and the result. */
77
+ interface Phase {
78
+ key: Switch | string;
79
+ parts: Map<string, TextChangesPart>;
80
+ result: TextChanges;
81
+ }
82
+
83
+ /** What the hook keeps for its life. */
84
+ interface Kept {
85
+ store: ChangeStore;
86
+ components: ChangeComponents;
87
+ reports: Map<string, Report>;
88
+ /** The content text of the render, for the reports. */
89
+ holder: { text: string };
90
+ phase: Phase | undefined;
91
+ }
92
+
93
+ // `useLayoutEffect` warns when it does nothing on the server; fall back to a plain effect there.
94
+ const useIsomorphicLayoutEffect = typeof window !== 'undefined' ? useLayoutEffect : useEffect;
95
+
96
+ /**
97
+ * What changed between two versions of a text, lit up. `text` is the whole content, all
98
+ * its parts; `key` its identity, the app's decision of which changes are related:
99
+ * - same key, new text: a switch. Each part diffs its previous reading against this one, and the
100
+ * switch animates;
101
+ * - a new key: the text appears plainly, and a running switch stops at once (its marks go in that
102
+ * render). This text is the start for the next related change;
103
+ * - same key, same text (`===`): nothing;
104
+ * - `animate: false`: swaps plainly once, under the same key too, and replaces the reading.
105
+ * The first render has nothing read before it, so nothing animates.
106
+ *
107
+ * Parts: `part(name)` gives one tree's `{ rehypePlugin, components }`; `rehypePlugin` and
108
+ * `components` on the result are the default part's. Each part keeps its own previous reading (the
109
+ * one its plugin reported for the text shown before; none, a part new in this version, all new
110
+ * against `''`) and diffs on its own. One switch has one number, one timer and one timeline over
111
+ * all its parts.
112
+ *
113
+ * A switch's timeline is decided after its parts render, before the paint: in a layout effect,
114
+ * from the plugins' reports (a removed mark cut in anywhere: `removals`; else `plain`), set in the
115
+ * hook's store, from which the marks re-render alone: the trees are not parsed again. The timer
116
+ * starts there, for `changeDurations()` on that timeline: the lent mark's `durations` (the
117
+ * `ChangeMark` in `VultusComponents` as the switch starts), at `near`'s container (else none) and
118
+ * the switch's speed, or vultus's defaults; at its end, the text renders without marks. A second
119
+ * switch within one diffs the text shown against the next, in marks of its own, and its timer
120
+ * replaces the first's.
121
+ *
122
+ * `speed` (`normal` by default; the lent mark's, which gives each one's times) is taken as a switch
123
+ * starts and held for that switch, like the near set: every mark of it (through the store) and its
124
+ * timer run at that speed, so they always agree. A new speed counts from the next switch on; it
125
+ * changes no identity and parses nothing.
126
+ *
127
+ * Identities: `rehypePlugin`, `components` and each part's object are kept while nothing changes:
128
+ * an app's Markdown memoises on them, and a big section takes 0.1 s or more to parse. They change as
129
+ * a switch starts and as it ends, and with a plain swap (a new text shown plainly): every part shown
130
+ * then parses again and reports its reading of the new text. A memo'd part whose own text did not
131
+ * change would otherwise keep its report of an older text, and diff all of itself as new at the
132
+ * next switch. `components` never changes. Inline `skip` and `near` functions, `near` objects and a
133
+ * new `speed` change nothing: `skip` and `blockAttribute` are read as a plugin runs, `near` and
134
+ * `speed` as a switch starts.
135
+ *
136
+ * `near`: a function of the block number, as it is; or `{ container, blocks, rootMargin? }`, the
137
+ * innermost blocks crossing the container (`useVisibleBlocks`) as the switch starts, `blocks` more
138
+ * each way. Frozen for the switch: a re-parse during the light-up keeps it. With no range (no
139
+ * IntersectionObserver, nothing reported yet), none: all of it marked.
140
+ *
141
+ * `active`: whether a switch's marks are shown.
142
+ */
143
+ export function useTextChanges(text: string, options: TextChangesOptions): TextChanges {
144
+ const [kept] = useState<Kept>(() => {
145
+ const store = changeStore();
146
+ return { store, components: changeComponents(store), reports: new Map(), holder: { text }, phase: undefined };
147
+ });
148
+ // The options as this render has them, for the plugins as they run and the switch's effect.
149
+ const latest = useRef(options);
150
+ latest.current = options;
151
+ const { key, animate, near, blockAttribute, speed = 'normal' } = options;
152
+ // The lent mark, whose `durations` time a switch; the switch's effect reads the one of the render
153
+ // that starts it.
154
+ const { ChangeMark: mark } = useVultusComponents();
155
+ const nearBlocks = typeof near === 'object' ? near : undefined;
156
+ const visible = useVisibleBlocks(nearBlocks?.container, blockAttribute ?? BLOCK_NUMBER_ATTRIBUTE, nearBlocks?.rootMargin);
157
+
158
+ // Worked out as the text changes, in the render that shows it, so it never shows unlit first.
159
+ const [stored, setShown] = useState<Shown>(() => ({ key, text, count: 0, current: undefined }));
160
+ let shown = stored;
161
+ if (key !== shown.key || text !== shown.text) {
162
+ const number = shown.count + 1;
163
+ shown = key === shown.key && animate !== false
164
+ ? { key, text, count: number, current: { number, from: readings(kept.reports, shown.text), near: frozen(near, visible), speed } }
165
+ : { key, text, count: shown.count, current: undefined };
166
+ setShown(shown);
167
+ }
168
+ kept.holder.text = shown.text;
169
+ const { current } = shown;
170
+ // The new switch's marks drawn with its number and speed, plain until its timeline is decided.
171
+ if (current && kept.store.getSnapshot().number !== current.number) {
172
+ kept.store.set({ number: current.number, timeline: undefined, speed: current.speed }, false);
173
+ }
174
+ const phaseKey = current ?? shown.text;
175
+ let made = kept.phase;
176
+ if (!made || made.key !== phaseKey) {
177
+ made = phase(phaseKey, current, kept, latest);
178
+ kept.phase = made;
179
+ }
180
+
181
+ useIsomorphicLayoutEffect(() => {
182
+ if (!current) return undefined;
183
+ const { number, speed: switchSpeed } = current;
184
+ const removals = Array.from(kept.reports.values()).some((report) => report.number === number && report.removals);
185
+ const timeline: ChangeTimeline = removals ? 'removals' : 'plain';
186
+ kept.store.set({ number, timeline, speed: switchSpeed }, true);
187
+ const now = latest.current.near;
188
+ const container = now && typeof now === 'object' ? now.container : undefined;
189
+ const element = container && 'current' in container ? container.current : container;
190
+ const timer = setTimeout(() => {
191
+ setShown((then) => (then.current?.number === number ? { ...then, current: undefined } : then));
192
+ }, changeDurations(element ?? undefined, switchSpeed, mark)[timeline]);
193
+ return () => clearTimeout(timer);
194
+ }, [current]);
195
+
196
+ return made.result;
197
+ }
198
+
199
+ /** Each part's reading of `text`: the reports read for it (a part absent from it has none). */
200
+ function readings(reports: Map<string, Report>, text: string): Map<string, string> {
201
+ const from = new Map<string, string>();
202
+ for (const [name, report] of reports) if (report.text === text) from.set(name, report.reading);
203
+ return from;
204
+ }
205
+
206
+ /** The near set a switch takes now: a function as it is; the blocks on screen, `blocks` more each
207
+ * way; none without a range. */
208
+ function frozen(near: TextChangesOptions['near'], visible: VisibleBlocks): ((block: number) => boolean) | undefined {
209
+ if (typeof near !== 'object') return near;
210
+ const range = visible.range();
211
+ if (!range) return undefined;
212
+ const { blocks } = near;
213
+ return (block) => range.first - blocks <= block && block <= range.last + blocks;
214
+ }
215
+
216
+ /** The objects of a phase, `key` (a switch, `current`, or the idle text): each part's plugin, with
217
+ * the switch's previous reading, near set and number in it, reporting to `kept`; and the result. */
218
+ function phase(key: Switch | string, current: Switch | undefined, kept: Kept, latest: { readonly current: TextChangesOptions }): Phase {
219
+ const parts = new Map<string, TextChangesPart>();
220
+ const number = current?.number ?? 0;
221
+ const part = (name: string): TextChangesPart => {
222
+ let made = parts.get(name);
223
+ if (!made) {
224
+ const from = current ? current.from.get(name) ?? '' : undefined;
225
+ const skip = (element: Element) => latest.current.skip?.(element) ?? false;
226
+ const onRead = (report: ReadReport) => {
227
+ kept.reports.set(name, { ...report, text: kept.holder.text, number });
228
+ };
229
+ made = {
230
+ rehypePlugin: () => changesPlugin({ from, near: current?.near, blockAttribute: latest.current.blockAttribute, skip, onRead })(),
231
+ components: kept.components,
232
+ };
233
+ parts.set(name, made);
234
+ }
235
+ return made;
236
+ };
237
+ const { rehypePlugin, components } = part(DEFAULT_PART);
238
+ return { key, parts, result: { rehypePlugin, components, part, active: current !== undefined } };
239
+ }