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,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
+ }
@@ -0,0 +1,121 @@
1
+ import { useEffect, useState } from 'react';
2
+
3
+ /** Block numbers from `first` to `last`, both included. */
4
+ export interface BlockRange {
5
+ first: number;
6
+ last: number;
7
+ }
8
+
9
+ /** Where the blocks are: an element, a ref object holding one, or none yet. */
10
+ export type ContainerOption = HTMLElement | null | { readonly current: HTMLElement | null };
11
+
12
+ /** `element`'s number in `attribute`; none for a missing or non-numeric one. */
13
+ function numberOf(element: Element, attribute: string): number | undefined {
14
+ const value = element.getAttribute(attribute);
15
+ const number = value === null || value.trim() === '' ? NaN : Number(value);
16
+ return Number.isFinite(number) ? number : undefined;
17
+ }
18
+
19
+ /**
20
+ * The range of the innermost of `elements` (numbered blocks crossing the band, in any order): each
21
+ * one containing another of them is dropped, so a quote or an outer list item spanning the band
22
+ * pulls nothing back (a quote of 200 paragraphs, 150 to 153 in the band, gives 150 to 153, not 1
23
+ * to 153); the first and last of the rest's numbers. A block holding blocks only outside the band
24
+ * counts: a tight list item whose first line is in it, its nested items below. None numbered (by
25
+ * `attribute`), none. It works on a set of elements (those the observer reports crossing the band),
26
+ * not on laid-out boxes.
27
+ */
28
+ export function innermostRange(elements: Iterable<Element>, attribute: string): BlockRange | undefined {
29
+ const blocks = Array.from(elements).filter((element) => numberOf(element, attribute) !== undefined);
30
+ let range: BlockRange | undefined;
31
+ for (const block of blocks) {
32
+ if (blocks.some((other) => other !== block && block.contains(other))) continue;
33
+ const number = numberOf(block, attribute)!;
34
+ range = range ? { first: Math.min(range.first, number), last: Math.max(range.last, number) } : { first: number, last: number };
35
+ }
36
+ return range;
37
+ }
38
+
39
+ /** The visible blocks as `useVisibleBlocks` tracks them. */
40
+ export interface VisibleBlocks {
41
+ /** The range of the innermost blocks crossing the container now (`innermostRange`); none without
42
+ * an IntersectionObserver or a container, before its first report, or with none crossing. */
43
+ range(): BlockRange | undefined;
44
+ }
45
+
46
+ /** What one tracking sees: its container, the numbering's attribute, and the blocks reported
47
+ * intersecting. */
48
+ interface Seen {
49
+ root: HTMLElement | null;
50
+ attribute: string;
51
+ visible: Set<Element>;
52
+ }
53
+
54
+ /**
55
+ * The numbered blocks (`attribute`) crossing `container`, tracked with an IntersectionObserver
56
+ * whose root is the container (`rootMargin`: a sticky bar over its top, say), for the near set a
57
+ * switch takes (`useTextChanges`' `near`). Every numbered block inside the container is observed,
58
+ * those rendered later too (a MutationObserver sees them come and go). Set up in a passive effect,
59
+ * when an ancestor's ref is attached; again when the container (the ref object or the element), the
60
+ * attribute or the margin change. One object for the hook's life: read `range()` when it is needed.
61
+ * Without an IntersectionObserver (an old browser, jsdom) or a container, no range.
62
+ *
63
+ * The container is the scrolling element (the pane), the observer's root: blocks scrolled out of it
64
+ * are clipped away. Given an element that does not scroll (the content inside the pane), every block
65
+ * in it counts as crossing, and the near limit does nothing. A ref object is read when the effect
66
+ * runs, so a container that appears or changes later is given as the element (from a callback ref,
67
+ * kept in state).
68
+ */
69
+ export function useVisibleBlocks(container: ContainerOption | undefined, attribute: string, rootMargin?: string): VisibleBlocks {
70
+ const [{ seen, blocks }] = useState(() => {
71
+ const seen: Seen = { root: null, attribute, visible: new Set() };
72
+ const blocks: VisibleBlocks = {
73
+ range() {
74
+ const { root } = seen;
75
+ if (!root) return undefined;
76
+ return innermostRange(Array.from(seen.visible).filter((block) => block.isConnected && root.contains(block)), seen.attribute);
77
+ },
78
+ };
79
+ return { seen, blocks };
80
+ });
81
+ useEffect(() => {
82
+ const root = container && 'current' in container ? container.current : container ?? null;
83
+ if (!root || typeof IntersectionObserver === 'undefined') return undefined;
84
+ const selector = `[${attribute}]`;
85
+ const intersection = new IntersectionObserver((entries) => {
86
+ for (const entry of entries) {
87
+ if (entry.isIntersecting) seen.visible.add(entry.target);
88
+ else seen.visible.delete(entry.target);
89
+ }
90
+ }, { root, rootMargin });
91
+ // The numbered blocks at or under a node.
92
+ const blocksAt = (node: Node): Element[] => {
93
+ if (node.nodeType !== Node.ELEMENT_NODE) return [];
94
+ const element = node as Element;
95
+ return [...(element.matches(selector) ? [element] : []), ...element.querySelectorAll(selector)];
96
+ };
97
+ for (const block of root.querySelectorAll(selector)) intersection.observe(block);
98
+ // In order, so that a block moved (taken out, put back) stays observed.
99
+ const mutation = new MutationObserver((records) => {
100
+ for (const record of records) {
101
+ for (const node of record.removedNodes) {
102
+ for (const block of blocksAt(node)) {
103
+ intersection.unobserve(block);
104
+ seen.visible.delete(block);
105
+ }
106
+ }
107
+ for (const node of record.addedNodes) for (const block of blocksAt(node)) intersection.observe(block);
108
+ }
109
+ });
110
+ mutation.observe(root, { childList: true, subtree: true });
111
+ seen.root = root;
112
+ seen.attribute = attribute;
113
+ return () => {
114
+ intersection.disconnect();
115
+ mutation.disconnect();
116
+ seen.visible.clear();
117
+ seen.root = null;
118
+ };
119
+ }, [container, attribute, rootMargin, seen]);
120
+ return blocks;
121
+ }