@glpecile/norph 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +22 -0
- package/README.md +71 -2
- package/package.json +37 -4
- package/src/diff.ts +467 -0
- package/src/index.tsx +377 -0
- package/src/plan.ts +102 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Gian Luca Pecile
|
|
4
|
+
Copyright (c) 2025 Lochie Axon (torph, https://github.com/lochie/torph)
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
7
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
8
|
+
in the Software without restriction, including without limitation the rights
|
|
9
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
10
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
11
|
+
furnished to do so, subject to the following conditions:
|
|
12
|
+
|
|
13
|
+
The above copyright notice and this permission notice shall be included in all
|
|
14
|
+
copies or substantial portions of the Software.
|
|
15
|
+
|
|
16
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
17
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
18
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
19
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
20
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
21
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
22
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,72 @@
|
|
|
1
|
-
#
|
|
1
|
+
# norph
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Text that morphs into its next value, on iOS, Android, and web. It is a
|
|
4
|
+
Reanimated port of [torph](https://github.com/lochie/torph)'s React component.
|
|
5
|
+
One implementation runs everywhere, on the web through react-native-web.
|
|
6
|
+
|
|
7
|
+
[Try the live demo](https://glpecile.github.io/norph/).
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
In an Expo app, `expo install` picks the Reanimated version that matches your SDK:
|
|
12
|
+
|
|
13
|
+
```sh
|
|
14
|
+
npx expo install @glpecile/norph react-native-reanimated react-native-worklets # npm
|
|
15
|
+
bunx expo install @glpecile/norph react-native-reanimated react-native-worklets # bun
|
|
16
|
+
pnpm expo install @glpecile/norph react-native-reanimated react-native-worklets # pnpm
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Outside Expo, add the same three packages with your package manager.
|
|
20
|
+
|
|
21
|
+
## Use
|
|
22
|
+
|
|
23
|
+
```tsx
|
|
24
|
+
import { MorphText } from '@glpecile/norph';
|
|
25
|
+
|
|
26
|
+
<MorphText className="text-2xl text-foreground self-start">{count}</MorphText>;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## Behavior
|
|
30
|
+
|
|
31
|
+
- Words and characters that the old and new text share slide to their new
|
|
32
|
+
places. New ones enter, dropped ones exit, and the box animates its width.
|
|
33
|
+
- Numbers match digits by place value and align on the decimal point. A
|
|
34
|
+
changed digit rolls in a clipped slot. Other characters crossfade.
|
|
35
|
+
- The first render does not animate. At rest, and with reduced motion or
|
|
36
|
+
`numberOfLines`, it renders one plain `Text`.
|
|
37
|
+
- Screen readers read the whole string once.
|
|
38
|
+
- Timing is torph's: 400 ms on `cubic-bezier(0.19, 1, 0.22, 1)`.
|
|
39
|
+
|
|
40
|
+
## Props
|
|
41
|
+
|
|
42
|
+
| Prop | Type | |
|
|
43
|
+
| --- | --- | --- |
|
|
44
|
+
| `children` | `string \| number` | The current text. |
|
|
45
|
+
| `className` | `string` | Text classes reach every glyph. Layout classes reach the outer box. Needs an app that resolves `className` on core components, such as Uniwind. |
|
|
46
|
+
| `style` | `TextStyle` | Split the same way as `className`. |
|
|
47
|
+
| `numberOfLines` | `number` | Opts out of the morph. |
|
|
48
|
+
|
|
49
|
+
## Limits
|
|
50
|
+
|
|
51
|
+
- One line. The text never wraps: at rest, text too long for its box ends in
|
|
52
|
+
an ellipsis. Newlines are not supported.
|
|
53
|
+
- While it morphs, the text sits at the start edge. Shrink-wrap it
|
|
54
|
+
(`alignSelf`) when alignment matters.
|
|
55
|
+
- One node per glyph loses kerning pairs during a morph.
|
|
56
|
+
- Unlike torph, the digit slot has a hard edge (no gradient mask) and a morph
|
|
57
|
+
that is interrupted does not carry its velocity over.
|
|
58
|
+
|
|
59
|
+
## Peer dependencies
|
|
60
|
+
|
|
61
|
+
`react`, `react-native`, `react-native-reanimated` 4, and `react-native-worklets`.
|
|
62
|
+
The package ships TypeScript source for Metro to compile.
|
|
63
|
+
|
|
64
|
+
## Develop
|
|
65
|
+
|
|
66
|
+
`bun test` runs the diff tests and `bun run typecheck` checks types. The demo
|
|
67
|
+
lives in `example/`: `cd example && bun install && bun web` runs it, and
|
|
68
|
+
`bun run export` builds it into `site/demo/` for the site in `site/`.
|
|
69
|
+
|
|
70
|
+
## License
|
|
71
|
+
|
|
72
|
+
MIT. Includes code from torph, copyright (c) 2025 Lochie Axon.
|
package/package.json
CHANGED
|
@@ -1,6 +1,39 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glpecile/norph",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "Text that morphs into its next value, on iOS, Android, and web. A Reanimated port of torph.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"author": "Gian Luca Pecile",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/glpecile/norph.git"
|
|
10
|
+
},
|
|
11
|
+
"keywords": ["react-native", "reanimated", "text", "animation", "morph"],
|
|
12
|
+
"sideEffects": false,
|
|
13
|
+
"publishConfig": {
|
|
14
|
+
"access": "public"
|
|
15
|
+
},
|
|
16
|
+
"main": "src/index.tsx",
|
|
17
|
+
"types": "src/index.tsx",
|
|
18
|
+
"react-native": "src/index.tsx",
|
|
19
|
+
"files": ["src", "!src/**/*.test.ts"],
|
|
20
|
+
"scripts": {
|
|
21
|
+
"test": "bun test",
|
|
22
|
+
"typecheck": "tsc --noEmit"
|
|
23
|
+
},
|
|
24
|
+
"peerDependencies": {
|
|
25
|
+
"react": ">=19",
|
|
26
|
+
"react-native": ">=0.80",
|
|
27
|
+
"react-native-reanimated": ">=4",
|
|
28
|
+
"react-native-worklets": ">=0.5"
|
|
29
|
+
},
|
|
30
|
+
"devDependencies": {
|
|
31
|
+
"@types/bun": "latest",
|
|
32
|
+
"@types/react": "~19.3.0",
|
|
33
|
+
"react": "19.3.0",
|
|
34
|
+
"react-native": "0.88.1",
|
|
35
|
+
"react-native-reanimated": "4.7.1",
|
|
36
|
+
"react-native-worklets": "0.13.0",
|
|
37
|
+
"typescript": "~6.0.3"
|
|
38
|
+
}
|
|
39
|
+
}
|
package/src/diff.ts
ADDED
|
@@ -0,0 +1,467 @@
|
|
|
1
|
+
// Ported from torph 0.1.3 (MIT, Lochie Axon): `segmentText`, `diffSegments`
|
|
2
|
+
// and `segmentNumber`, without `cursorIndex`. Newlines are not supported: the
|
|
3
|
+
// component renders one line.
|
|
4
|
+
|
|
5
|
+
export type SegmentKind = 'digit' | 'symbol';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* One rendered node. A segment whose `id` survives a text change keeps its
|
|
9
|
+
* node and slides; a new `id` enters and a dropped one exits. Only characters
|
|
10
|
+
* of a number carry a `kind`, and only they roll.
|
|
11
|
+
*/
|
|
12
|
+
export interface Segment {
|
|
13
|
+
id: string;
|
|
14
|
+
string: string;
|
|
15
|
+
kind?: SegmentKind;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface Diff {
|
|
19
|
+
segments: Segment[];
|
|
20
|
+
/**
|
|
21
|
+
* Old single-segment words that the diff morphs character by character.
|
|
22
|
+
* Before measuring, the previous layout replaces each with these pieces.
|
|
23
|
+
*/
|
|
24
|
+
splits: Map<string, Segment[]>;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const NBSP = ' ';
|
|
28
|
+
const SEPARATORS = `.,'${NBSP} `;
|
|
29
|
+
const LEADING = '+-−(#';
|
|
30
|
+
const TRAILING = `%.,!?:;)"'”’`;
|
|
31
|
+
const CURRENCY = /\p{Sc}/u;
|
|
32
|
+
const NUMBER_KEY = '\0#';
|
|
33
|
+
// Above this many fuzzy word pairs, unmatched words enter fresh.
|
|
34
|
+
const MAX_FUZZY_PAIRS = 2500;
|
|
35
|
+
const MAX_WORD_PAIRS = 1e6;
|
|
36
|
+
const MIN_SIMILARITY = 0.4;
|
|
37
|
+
// Integer parts this far apart in length don't share digits.
|
|
38
|
+
const MAX_DIGIT_GAP = 3;
|
|
39
|
+
|
|
40
|
+
let freshCount = 0;
|
|
41
|
+
const freshId = () => `\0n${freshCount++}`;
|
|
42
|
+
|
|
43
|
+
const isDigit = (char: string) => char >= '0' && char <= '9';
|
|
44
|
+
const hasDigit = (text: string) => Array.from(text).some(isDigit);
|
|
45
|
+
const kindOf = (char: string): SegmentKind => (isDigit(char) ? 'digit' : 'symbol');
|
|
46
|
+
const affix = (char: string, list: string) => list.includes(char) || CURRENCY.test(char);
|
|
47
|
+
|
|
48
|
+
/** The text without digits and digit separators, so `S01E04` and `S01E05` compare equal. */
|
|
49
|
+
const letters = (text: string) =>
|
|
50
|
+
Array.from(text)
|
|
51
|
+
.filter((char) => !isDigit(char) && !SEPARATORS.includes(char))
|
|
52
|
+
.join('');
|
|
53
|
+
|
|
54
|
+
/** Index pairs of a longest common subsequence, in order. */
|
|
55
|
+
export function lcs<T>(a: T[], b: T[]): [number[], number[]] {
|
|
56
|
+
const suffix = Array.from({ length: a.length + 1 }, () => Array<number>(b.length + 1).fill(0));
|
|
57
|
+
for (let i = a.length - 1; i >= 0; i--) {
|
|
58
|
+
for (let j = b.length - 1; j >= 0; j--) {
|
|
59
|
+
suffix[i][j] =
|
|
60
|
+
a[i] === b[j] ? suffix[i + 1][j + 1] + 1 : Math.max(suffix[i + 1][j], suffix[i][j + 1]);
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
const from: number[] = [];
|
|
64
|
+
const to: number[] = [];
|
|
65
|
+
let i = 0;
|
|
66
|
+
let j = 0;
|
|
67
|
+
while (i < a.length && j < b.length) {
|
|
68
|
+
if (a[i] === b[j]) {
|
|
69
|
+
from.push(i++);
|
|
70
|
+
to.push(j++);
|
|
71
|
+
} else if (suffix[i + 1][j] >= suffix[i][j + 1]) {
|
|
72
|
+
i++;
|
|
73
|
+
} else {
|
|
74
|
+
j++;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return [from, to];
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** A number with optional sign, currency, and trailing punctuation: `-$1,234.50`, `42%`. */
|
|
81
|
+
export function isNumericWord(word: string) {
|
|
82
|
+
let start = 0;
|
|
83
|
+
let end = word.length;
|
|
84
|
+
while (start < end && affix(word[start], LEADING)) start++;
|
|
85
|
+
while (end > start && affix(word[end - 1], TRAILING)) end--;
|
|
86
|
+
if (start >= end || !isDigit(word[start]) || !isDigit(word[end - 1])) return false;
|
|
87
|
+
for (let i = start; i < end; i++) {
|
|
88
|
+
if (!isDigit(word[i]) && !SEPARATORS.includes(word[i])) return false;
|
|
89
|
+
}
|
|
90
|
+
return true;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
const separatorCache = new Map<string, string>();
|
|
94
|
+
export function decimalSeparator(locale: string) {
|
|
95
|
+
let separator = separatorCache.get(locale);
|
|
96
|
+
if (separator) return separator;
|
|
97
|
+
separator = '.';
|
|
98
|
+
try {
|
|
99
|
+
separator =
|
|
100
|
+
new Intl.NumberFormat(locale).formatToParts(1.1).find((part) => part.type === 'decimal')
|
|
101
|
+
?.value ?? '.';
|
|
102
|
+
} catch {}
|
|
103
|
+
separatorCache.set(locale, separator);
|
|
104
|
+
return separator;
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function idAllocator() {
|
|
108
|
+
const used = new Set<string>();
|
|
109
|
+
return {
|
|
110
|
+
reserve: (id: string) => void used.add(id),
|
|
111
|
+
has: (id: string) => used.has(id),
|
|
112
|
+
take(id: string) {
|
|
113
|
+
if (!used.has(id)) {
|
|
114
|
+
used.add(id);
|
|
115
|
+
return id;
|
|
116
|
+
}
|
|
117
|
+
let n = 1;
|
|
118
|
+
while (used.has(`${id}~${n}`)) n++;
|
|
119
|
+
used.add(`${id}~${n}`);
|
|
120
|
+
return `${id}~${n}`;
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Maps each new character index to the old index it keeps, matching digits
|
|
127
|
+
* by place value: the integer part right-aligned on the decimal separator,
|
|
128
|
+
* the fraction left-aligned after it.
|
|
129
|
+
*/
|
|
130
|
+
function matchNumber(old: string[], next: string[], decimal: string) {
|
|
131
|
+
const matches = new Map<number, number>();
|
|
132
|
+
let start = 0;
|
|
133
|
+
while (start < old.length && start < next.length && old[start] === next[start] && !isDigit(old[start])) {
|
|
134
|
+
matches.set(start, start);
|
|
135
|
+
start++;
|
|
136
|
+
}
|
|
137
|
+
let oldEnd = old.length;
|
|
138
|
+
let nextEnd = next.length;
|
|
139
|
+
while (
|
|
140
|
+
oldEnd > start &&
|
|
141
|
+
nextEnd > start &&
|
|
142
|
+
old[oldEnd - 1] === next[nextEnd - 1] &&
|
|
143
|
+
!isDigit(old[oldEnd - 1])
|
|
144
|
+
) {
|
|
145
|
+
matches.set(nextEnd - 1, oldEnd - 1);
|
|
146
|
+
oldEnd--;
|
|
147
|
+
nextEnd--;
|
|
148
|
+
}
|
|
149
|
+
const pointIn = (chars: string[], end: number) => {
|
|
150
|
+
for (let i = end - 1; i >= start; i--) if (chars[i] === decimal) return i;
|
|
151
|
+
return end;
|
|
152
|
+
};
|
|
153
|
+
const oldPoint = pointIn(old, oldEnd);
|
|
154
|
+
const nextPoint = pointIn(next, nextEnd);
|
|
155
|
+
|
|
156
|
+
const digitsIn = (chars: string[], from: number, to: number) => {
|
|
157
|
+
const positions: number[] = [];
|
|
158
|
+
for (let i = from; i < to; i++) if (isDigit(chars[i])) positions.push(i);
|
|
159
|
+
return positions;
|
|
160
|
+
};
|
|
161
|
+
const oldDigits = digitsIn(old, start, oldPoint).length;
|
|
162
|
+
const nextDigits = digitsIn(next, start, nextPoint).length;
|
|
163
|
+
if (oldDigits > 0 && nextDigits > 0 && Math.abs(oldDigits - nextDigits) >= MAX_DIGIT_GAP) {
|
|
164
|
+
return matches;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const matchSymbol = (o: number, n: number) => {
|
|
168
|
+
if (!isDigit(old[o]) && old[o] === next[n]) matches.set(n, o);
|
|
169
|
+
};
|
|
170
|
+
/** Returns whether an unequal-length integer part shared any digit. */
|
|
171
|
+
const matchDigits = (o0: number, o1: number, n0: number, n1: number, integer: boolean) => {
|
|
172
|
+
const from = digitsIn(old, o0, o1);
|
|
173
|
+
const to = digitsIn(next, n0, n1);
|
|
174
|
+
if (from.length === to.length || !integer) {
|
|
175
|
+
for (let i = 0; i < Math.min(from.length, to.length); i++) {
|
|
176
|
+
if (old[from[i]] === next[to[i]]) matches.set(to[i], from[i]);
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
}
|
|
180
|
+
const [a, b] = lcs(
|
|
181
|
+
from.map((i) => old[i]).reverse(),
|
|
182
|
+
to.map((i) => next[i]).reverse(),
|
|
183
|
+
);
|
|
184
|
+
for (let i = 0; i < a.length; i++) {
|
|
185
|
+
matches.set(to[to.length - 1 - b[i]], from[from.length - 1 - a[i]]);
|
|
186
|
+
}
|
|
187
|
+
return a.length > 0;
|
|
188
|
+
};
|
|
189
|
+
|
|
190
|
+
if (!matchDigits(start, oldPoint, start, nextPoint, true)) {
|
|
191
|
+
for (let h = 1; oldPoint - h >= start && nextPoint - h >= start; h++) {
|
|
192
|
+
matchSymbol(oldPoint - h, nextPoint - h);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (oldPoint < oldEnd && nextPoint < nextEnd) {
|
|
196
|
+
matches.set(nextPoint, oldPoint);
|
|
197
|
+
for (let h = 1; oldPoint + h < oldEnd && nextPoint + h < nextEnd; h++) {
|
|
198
|
+
matchSymbol(oldPoint + h, nextPoint + h);
|
|
199
|
+
}
|
|
200
|
+
matchDigits(oldPoint + 1, oldEnd, nextPoint + 1, nextEnd, false);
|
|
201
|
+
}
|
|
202
|
+
return matches;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** One kinded segment per character of a numeric word, keeping ids from `previous` by place value. */
|
|
206
|
+
export function segmentNumber(text: string, previous?: Segment[], decimal = '.'): Segment[] {
|
|
207
|
+
const chars = text.split('');
|
|
208
|
+
const toSegment = (char: string, id: string): Segment => ({
|
|
209
|
+
id,
|
|
210
|
+
string: char === ' ' ? NBSP : char,
|
|
211
|
+
kind: kindOf(char),
|
|
212
|
+
});
|
|
213
|
+
if (!previous || previous.length === 0) return chars.map((char) => toSegment(char, freshId()));
|
|
214
|
+
const matches = matchNumber(
|
|
215
|
+
previous.map((segment) => (segment.string === NBSP ? ' ' : segment.string)),
|
|
216
|
+
chars,
|
|
217
|
+
decimal,
|
|
218
|
+
);
|
|
219
|
+
const used = new Set(Array.from(matches.values(), (index) => previous[index].id));
|
|
220
|
+
return chars.map((char, index) => {
|
|
221
|
+
const kept = matches.get(index);
|
|
222
|
+
if (kept !== undefined) return toSegment(char, previous[kept].id);
|
|
223
|
+
let id = freshId();
|
|
224
|
+
while (used.has(id)) id = freshId();
|
|
225
|
+
used.add(id);
|
|
226
|
+
return toSegment(char, id);
|
|
227
|
+
});
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
interface Word {
|
|
231
|
+
word: string;
|
|
232
|
+
segments: Segment[];
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function words(segments: Segment[]): Word[] {
|
|
236
|
+
const result: Word[] = [];
|
|
237
|
+
let current: Segment[] = [];
|
|
238
|
+
const flush = () => {
|
|
239
|
+
if (current.length === 0) return;
|
|
240
|
+
result.push({ word: current.map((segment) => segment.string).join(''), segments: current });
|
|
241
|
+
current = [];
|
|
242
|
+
};
|
|
243
|
+
for (const segment of segments) {
|
|
244
|
+
if (segment.string === NBSP) flush();
|
|
245
|
+
else current.push(segment);
|
|
246
|
+
}
|
|
247
|
+
flush();
|
|
248
|
+
return result;
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
/**
|
|
252
|
+
* First render: one segment per word when the text has spaces, else per
|
|
253
|
+
* character, with numeric words split into kinded characters. A repeated
|
|
254
|
+
* string takes its offset as id, so `0` and `0-4` stay apart.
|
|
255
|
+
*/
|
|
256
|
+
export function segmentText(text: string): Segment[] {
|
|
257
|
+
const wordMode = text.includes(' ');
|
|
258
|
+
const ids = idAllocator();
|
|
259
|
+
const parts = wordMode ? text.split(' ') : Array.from(text);
|
|
260
|
+
const segments: Segment[] = [];
|
|
261
|
+
let offset = 0;
|
|
262
|
+
parts.forEach((part, index) => {
|
|
263
|
+
if (wordMode && index > 0) {
|
|
264
|
+
segments.push({ id: ids.take(`space-${offset}`), string: NBSP });
|
|
265
|
+
offset += 1;
|
|
266
|
+
}
|
|
267
|
+
if (part.length > 0) {
|
|
268
|
+
segments.push({ id: ids.take(ids.has(part) ? `${part}-${offset}` : part), string: part });
|
|
269
|
+
}
|
|
270
|
+
offset += part.length;
|
|
271
|
+
});
|
|
272
|
+
return splitNumbers(segments);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
function splitNumbers(segments: Segment[]) {
|
|
276
|
+
const result: Segment[] = [];
|
|
277
|
+
let current: Segment[] = [];
|
|
278
|
+
const flush = () => {
|
|
279
|
+
if (current.length === 0) return;
|
|
280
|
+
const word = current.map((segment) => segment.string).join('');
|
|
281
|
+
result.push(...(isNumericWord(word) ? segmentNumber(word) : current));
|
|
282
|
+
current = [];
|
|
283
|
+
};
|
|
284
|
+
for (const segment of segments) {
|
|
285
|
+
if (segment.string === NBSP) {
|
|
286
|
+
flush();
|
|
287
|
+
result.push(segment);
|
|
288
|
+
} else {
|
|
289
|
+
current.push(segment);
|
|
290
|
+
}
|
|
291
|
+
}
|
|
292
|
+
flush();
|
|
293
|
+
return result;
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
/** Splits a one-segment word into characters with derived ids, recording the split. */
|
|
297
|
+
function splitWord(word: Word, splits: Map<string, Segment[]>): Segment[] {
|
|
298
|
+
if (word.segments.length !== 1 || Array.from(word.word).length <= 1) return word.segments;
|
|
299
|
+
const [segment] = word.segments;
|
|
300
|
+
const pieces = Array.from(word.word).map((string, index) => ({ id: `${segment.id}:${index}`, string }));
|
|
301
|
+
splits.set(segment.id, pieces);
|
|
302
|
+
return pieces;
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
function lcsRatio(a: string, b: string) {
|
|
306
|
+
if (a.length === 0 || b.length === 0) return 0;
|
|
307
|
+
return lcs(a.split(''), b.split(''))[0].length / Math.max(a.length, b.length);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const similarity = (a: string, b: string) =>
|
|
311
|
+
(hasDigit(a) || hasDigit(b)) && letters(a) === letters(b) ? 1 : lcsRatio(a, b);
|
|
312
|
+
|
|
313
|
+
/** For each index, how many matched indices come before it. */
|
|
314
|
+
function rankBefore(length: number, matched: Set<number>) {
|
|
315
|
+
const ranks: number[] = [];
|
|
316
|
+
let rank = 0;
|
|
317
|
+
for (let i = 0; i < length; i++) {
|
|
318
|
+
ranks.push(rank);
|
|
319
|
+
if (matched.has(i)) rank++;
|
|
320
|
+
}
|
|
321
|
+
return ranks;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
type WordPlan =
|
|
325
|
+
| { mode: 'fresh' }
|
|
326
|
+
| { mode: 'reuse' | 'number' | 'morph'; from: number };
|
|
327
|
+
|
|
328
|
+
/**
|
|
329
|
+
* Re-segments `text` against the segments on screen. Words pair up by LCS,
|
|
330
|
+
* then by exact match, then by similarity at the same position. A kept word
|
|
331
|
+
* keeps its segments, a number keeps digits by place value, a similar word
|
|
332
|
+
* morphs per character, and the rest enter fresh.
|
|
333
|
+
*/
|
|
334
|
+
export function diffSegments(previous: Segment[], text: string, locale = 'en'): Diff {
|
|
335
|
+
if (previous.length === 0) return { segments: segmentText(text), splits: new Map() };
|
|
336
|
+
const oldWords = words(previous);
|
|
337
|
+
const key = (word: string) => (isNumericWord(word) ? NUMBER_KEY : word);
|
|
338
|
+
const anyDigits = hasDigit(text) || oldWords.some((word) => hasDigit(word.word));
|
|
339
|
+
if (oldWords.length <= 1 && !text.includes(' ') && !anyDigits) {
|
|
340
|
+
return { segments: segmentText(text), splits: new Map() };
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const newWords: string[] = [];
|
|
344
|
+
const gaps: number[] = [];
|
|
345
|
+
let gap = 0;
|
|
346
|
+
for (const part of text.split(/( )/)) {
|
|
347
|
+
if (part === ' ') {
|
|
348
|
+
gap++;
|
|
349
|
+
} else if (part.length > 0) {
|
|
350
|
+
gaps.push(gap);
|
|
351
|
+
newWords.push(part);
|
|
352
|
+
gap = 0;
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
const trailingGap = gap;
|
|
356
|
+
const old = oldWords.map((word) => word.word);
|
|
357
|
+
if (old.length * newWords.length > MAX_WORD_PAIRS) {
|
|
358
|
+
return { segments: segmentText(text), splits: new Map() };
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
const [oldMatched, newMatched] = lcs(old.map(key), newWords.map(key));
|
|
362
|
+
const exact = new Map<number, number>();
|
|
363
|
+
newMatched.forEach((n, i) => exact.set(n, oldMatched[i]));
|
|
364
|
+
let oldLeft = old.map((_, i) => i).filter((i) => !oldMatched.includes(i));
|
|
365
|
+
let newLeft = newWords.map((_, i) => i).filter((i) => !newMatched.includes(i));
|
|
366
|
+
const taken = new Set<number>();
|
|
367
|
+
for (const n of newLeft) {
|
|
368
|
+
const o = oldLeft.find((o) => !taken.has(o) && key(newWords[n]) === key(old[o]));
|
|
369
|
+
if (o !== undefined) {
|
|
370
|
+
exact.set(n, o);
|
|
371
|
+
taken.add(o);
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
oldLeft = oldLeft.filter((o) => !taken.has(o));
|
|
375
|
+
newLeft = newLeft.filter((n) => !exact.has(n));
|
|
376
|
+
|
|
377
|
+
const fuzzy = new Map<number, number>();
|
|
378
|
+
const oldRank = rankBefore(old.length, new Set(oldMatched));
|
|
379
|
+
const newRank = rankBefore(newWords.length, new Set(newMatched));
|
|
380
|
+
if (oldLeft.length * newLeft.length <= MAX_FUZZY_PAIRS) {
|
|
381
|
+
const used = new Set<number>();
|
|
382
|
+
for (const n of newLeft) {
|
|
383
|
+
let best = -1;
|
|
384
|
+
let bestScore = MIN_SIMILARITY;
|
|
385
|
+
for (const o of oldLeft) {
|
|
386
|
+
if (used.has(o) || oldRank[o] !== newRank[n]) continue;
|
|
387
|
+
const score = similarity(old[o], newWords[n]);
|
|
388
|
+
if (score > bestScore) {
|
|
389
|
+
bestScore = score;
|
|
390
|
+
best = o;
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
if (best >= 0) {
|
|
394
|
+
fuzzy.set(n, best);
|
|
395
|
+
used.add(best);
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
const plans = newWords.map((word, n): WordPlan => {
|
|
401
|
+
const kept = exact.get(n);
|
|
402
|
+
const from = kept ?? fuzzy.get(n);
|
|
403
|
+
if (from === undefined) return { mode: 'fresh' };
|
|
404
|
+
if (isNumericWord(word)) return { mode: 'number', from };
|
|
405
|
+
return { mode: kept !== undefined ? 'reuse' : 'morph', from };
|
|
406
|
+
});
|
|
407
|
+
|
|
408
|
+
const ids = idAllocator();
|
|
409
|
+
for (const plan of plans) {
|
|
410
|
+
if (plan.mode === 'fresh') continue;
|
|
411
|
+
const word = oldWords[plan.from];
|
|
412
|
+
if (plan.mode !== 'reuse' && word.segments.length === 1) {
|
|
413
|
+
for (let i = 0; i < Array.from(word.word).length; i++) ids.reserve(`${word.segments[0].id}:${i}`);
|
|
414
|
+
} else {
|
|
415
|
+
for (const segment of word.segments) ids.reserve(segment.id);
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
const segments: Segment[] = [];
|
|
420
|
+
const splits = new Map<string, Segment[]>();
|
|
421
|
+
const decimal = decimalSeparator(locale);
|
|
422
|
+
let offset = 0;
|
|
423
|
+
const pushSpaces = (count: number) => {
|
|
424
|
+
for (let i = 0; i < count; i++) {
|
|
425
|
+
segments.push({ id: ids.take(`space-${offset}`), string: NBSP });
|
|
426
|
+
offset++;
|
|
427
|
+
}
|
|
428
|
+
};
|
|
429
|
+
newWords.forEach((word, n) => {
|
|
430
|
+
pushSpaces(gaps[n]);
|
|
431
|
+
const plan = plans[n];
|
|
432
|
+
switch (plan.mode) {
|
|
433
|
+
case 'reuse':
|
|
434
|
+
segments.push(...oldWords[plan.from].segments);
|
|
435
|
+
break;
|
|
436
|
+
case 'number': {
|
|
437
|
+
const pieces = splitWord(oldWords[plan.from], splits).map((segment) => ({
|
|
438
|
+
...segment,
|
|
439
|
+
kind: segment.kind ?? kindOf(segment.string),
|
|
440
|
+
}));
|
|
441
|
+
segments.push(...segmentNumber(word, pieces, decimal));
|
|
442
|
+
break;
|
|
443
|
+
}
|
|
444
|
+
case 'morph': {
|
|
445
|
+
const from = oldWords[plan.from];
|
|
446
|
+
const pieces = splitWord(from, splits);
|
|
447
|
+
const chars = Array.from(word);
|
|
448
|
+
const [a, b] = lcs(Array.from(from.word), chars);
|
|
449
|
+
const kept = new Map<number, Segment>();
|
|
450
|
+
b.forEach((to, i) => {
|
|
451
|
+
if (pieces[a[i]]) kept.set(to, pieces[a[i]]);
|
|
452
|
+
});
|
|
453
|
+
chars.forEach((string, i) => {
|
|
454
|
+
segments.push({ id: kept.get(i)?.id ?? ids.take(`${word}~${i}`), string });
|
|
455
|
+
});
|
|
456
|
+
break;
|
|
457
|
+
}
|
|
458
|
+
case 'fresh':
|
|
459
|
+
if (isNumericWord(word)) segments.push(...segmentNumber(word));
|
|
460
|
+
else segments.push({ id: ids.take(word), string: word });
|
|
461
|
+
break;
|
|
462
|
+
}
|
|
463
|
+
offset += word.length;
|
|
464
|
+
});
|
|
465
|
+
pushSpaces(trailingGap);
|
|
466
|
+
return { segments, splits };
|
|
467
|
+
}
|
package/src/index.tsx
ADDED
|
@@ -0,0 +1,377 @@
|
|
|
1
|
+
import { type ReactNode, useRef, useState } from 'react';
|
|
2
|
+
import {
|
|
3
|
+
type LayoutRectangle,
|
|
4
|
+
type StyleProp,
|
|
5
|
+
StyleSheet,
|
|
6
|
+
Text,
|
|
7
|
+
type TextStyle,
|
|
8
|
+
View,
|
|
9
|
+
} from 'react-native';
|
|
10
|
+
import Animated, {
|
|
11
|
+
Easing,
|
|
12
|
+
makeMutable,
|
|
13
|
+
type SharedValue,
|
|
14
|
+
useAnimatedStyle,
|
|
15
|
+
useReducedMotion,
|
|
16
|
+
withDelay,
|
|
17
|
+
withTiming,
|
|
18
|
+
} from 'react-native-reanimated';
|
|
19
|
+
import { scheduleOnRN } from 'react-native-worklets';
|
|
20
|
+
|
|
21
|
+
import { diffSegments, type Segment, segmentText } from './diff';
|
|
22
|
+
import { type Box, planMoves } from './plan';
|
|
23
|
+
|
|
24
|
+
export { diffSegments, segmentText, type Segment } from './diff';
|
|
25
|
+
|
|
26
|
+
// `className` reaches the core components when the app resolves it (Uniwind
|
|
27
|
+
// redirects `react-native` imports to components that read it). Elsewhere it
|
|
28
|
+
// is ignored. Declared here, not in a .d.ts, so it loads with every import.
|
|
29
|
+
declare module 'react-native' {
|
|
30
|
+
interface TextProps {
|
|
31
|
+
className?: string;
|
|
32
|
+
}
|
|
33
|
+
interface ViewProps {
|
|
34
|
+
className?: string;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export interface MorphTextProps {
|
|
39
|
+
/** The current text. A change morphs in place. */
|
|
40
|
+
children: string | number;
|
|
41
|
+
/**
|
|
42
|
+
* Classes for the text (font, size, color) and the outer box (margins,
|
|
43
|
+
* alignment). Works where `Text` resolves `className`, as with Uniwind.
|
|
44
|
+
*/
|
|
45
|
+
className?: string;
|
|
46
|
+
/** Same split as `className`: text styles reach every glyph, the rest the outer box. */
|
|
47
|
+
style?: StyleProp<TextStyle>;
|
|
48
|
+
/** Line cap, as on `Text`. Setting it opts out of the morph. */
|
|
49
|
+
numberOfLines?: number;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// torph's defaults.
|
|
53
|
+
const DURATION = 400;
|
|
54
|
+
const EASE = Easing.bezier(0.19, 1, 0.22, 1);
|
|
55
|
+
const EMPTY: Segment = { id: 'empty', string: '' };
|
|
56
|
+
|
|
57
|
+
const glide = (to: number) => withTiming(to, { duration: DURATION, easing: EASE });
|
|
58
|
+
/** A linear fade over `share` of the duration, after `delay` of it. */
|
|
59
|
+
const fade = (to: number, share: number, delay = 0) => {
|
|
60
|
+
const timing = withTiming(to, { duration: DURATION * share, easing: Easing.linear });
|
|
61
|
+
return delay > 0 ? withDelay(DURATION * delay, timing) : timing;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
interface Glyph {
|
|
65
|
+
/** React key: unique per node, while `id` can return before its old node finishes exiting. */
|
|
66
|
+
key: number;
|
|
67
|
+
id: string;
|
|
68
|
+
string: string;
|
|
69
|
+
/** A character of a number: it rolls in a clipped slot instead of fading in place. */
|
|
70
|
+
rolls: boolean;
|
|
71
|
+
width: number;
|
|
72
|
+
exiting: boolean;
|
|
73
|
+
x: SharedValue<number>;
|
|
74
|
+
scale: SharedValue<number>;
|
|
75
|
+
opacity: SharedValue<number>;
|
|
76
|
+
/** Group scale pivot, as an offset from the glyph's centre. */
|
|
77
|
+
origin: SharedValue<number>;
|
|
78
|
+
rollY: SharedValue<number>;
|
|
79
|
+
rollOpacity: SharedValue<number>;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
interface Motion {
|
|
83
|
+
glyphs: Glyph[];
|
|
84
|
+
width: SharedValue<number>;
|
|
85
|
+
height: number;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
interface Measures {
|
|
89
|
+
text: string;
|
|
90
|
+
done: boolean;
|
|
91
|
+
before: Map<string, LayoutRectangle>;
|
|
92
|
+
after: Map<string, LayoutRectangle>;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
let glyphKey = 0;
|
|
96
|
+
const newGlyph = (segment: Segment, width: number, x: number, from: Partial<Record<'scale' | 'opacity' | 'rollY' | 'rollOpacity', number>> = {}): Glyph => ({
|
|
97
|
+
key: glyphKey++,
|
|
98
|
+
id: segment.id,
|
|
99
|
+
string: segment.string,
|
|
100
|
+
rolls: segment.kind != null,
|
|
101
|
+
width,
|
|
102
|
+
exiting: false,
|
|
103
|
+
x: makeMutable(x),
|
|
104
|
+
scale: makeMutable(from.scale ?? 1),
|
|
105
|
+
opacity: makeMutable(from.opacity ?? 1),
|
|
106
|
+
origin: makeMutable(0),
|
|
107
|
+
rollY: makeMutable(from.rollY ?? 0),
|
|
108
|
+
rollOpacity: makeMutable(from.rollOpacity ?? 1),
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
const widthOf = (boxes: Map<string, Box>) =>
|
|
112
|
+
Math.max(0, ...Array.from(boxes.values(), (box) => box.x + box.width));
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Text that morphs into its next value, as torph does on the web: segments
|
|
116
|
+
* the old and new text share slide to their new places, new ones enter,
|
|
117
|
+
* dropped ones exit, digits of a number roll by place value, and the box
|
|
118
|
+
* animates its width. The first render, reduced motion, and `numberOfLines`
|
|
119
|
+
* render plain `Text`, and so does the text at rest once a morph ends.
|
|
120
|
+
*
|
|
121
|
+
* Runs one line that never wraps: at rest, text too long for its box ends in
|
|
122
|
+
* an ellipsis. While it moves, the text sits at the start edge, so
|
|
123
|
+
* shrink-wrap it (`alignSelf`) when alignment matters.
|
|
124
|
+
*/
|
|
125
|
+
export function MorphText({ children, className, style, numberOfLines }: MorphTextProps) {
|
|
126
|
+
const text = String(children);
|
|
127
|
+
const reduceMotion = useReducedMotion();
|
|
128
|
+
const [shown, setShown] = useState(() => ({ text, segments: segmentText(text) }));
|
|
129
|
+
const [motion, setMotion] = useState<Motion | null>(null);
|
|
130
|
+
const measures = useRef<Measures | null>(null);
|
|
131
|
+
const generation = useRef(0);
|
|
132
|
+
|
|
133
|
+
if (reduceMotion || numberOfLines != null) {
|
|
134
|
+
if (shown.text !== text) {
|
|
135
|
+
setShown({ text, segments: segmentText(text) });
|
|
136
|
+
setMotion(null);
|
|
137
|
+
}
|
|
138
|
+
return (
|
|
139
|
+
<Text className={className} style={style} numberOfLines={numberOfLines}>
|
|
140
|
+
{text}
|
|
141
|
+
</Text>
|
|
142
|
+
);
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const pending = shown.text !== text;
|
|
146
|
+
const diff = pending ? diffSegments(shown.segments, text) : null;
|
|
147
|
+
const before = diff
|
|
148
|
+
? shown.segments.flatMap((segment) => diff.splits.get(segment.id) ?? [segment])
|
|
149
|
+
: [];
|
|
150
|
+
const after = diff ? (diff.segments.length > 0 ? diff.segments : [EMPTY]) : [];
|
|
151
|
+
|
|
152
|
+
const settle = (done: number) => {
|
|
153
|
+
if (generation.current === done) setMotion(null);
|
|
154
|
+
};
|
|
155
|
+
|
|
156
|
+
const start = ({ before: previous, after: next }: Measures) => {
|
|
157
|
+
const moves = planMoves(
|
|
158
|
+
before.map((segment) => segment.id),
|
|
159
|
+
after,
|
|
160
|
+
previous,
|
|
161
|
+
next,
|
|
162
|
+
);
|
|
163
|
+
const live = new Map(motion?.glyphs.filter((glyph) => !glyph.exiting).map((glyph) => [glyph.id, glyph]));
|
|
164
|
+
const height = Math.max(0, ...Array.from(next.values(), (box) => box.height));
|
|
165
|
+
// Exits sit under the live glyphs. Exits already underway keep going; the
|
|
166
|
+
// morph ends before they could show.
|
|
167
|
+
const glyphs: Glyph[] = motion?.glyphs.filter((glyph) => glyph.exiting) ?? [];
|
|
168
|
+
|
|
169
|
+
for (const segment of before) {
|
|
170
|
+
const move = moves.get(segment.id);
|
|
171
|
+
if (move?.type !== 'exit') continue;
|
|
172
|
+
const box = previous.get(segment.id)!;
|
|
173
|
+
const glyph = { ...(live.get(segment.id) ?? newGlyph(segment, box.width, box.x)), exiting: true };
|
|
174
|
+
if (move.origin != null) {
|
|
175
|
+
glyph.origin.set(move.origin);
|
|
176
|
+
glyph.scale.set(glide(0.8));
|
|
177
|
+
glyph.opacity.set(fade(0, 0.45));
|
|
178
|
+
} else if (glyph.rolls) {
|
|
179
|
+
glyph.x.set(glide(move.x));
|
|
180
|
+
glyph.rollY.set(glide(height));
|
|
181
|
+
glyph.rollOpacity.set(fade(0, 0.45));
|
|
182
|
+
} else {
|
|
183
|
+
glyph.x.set(glide(move.x));
|
|
184
|
+
glyph.scale.set(glide(0.95));
|
|
185
|
+
glyph.opacity.set(fade(0, 0.25));
|
|
186
|
+
}
|
|
187
|
+
glyphs.push(glyph);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
for (const segment of after) {
|
|
191
|
+
const box = next.get(segment.id)!;
|
|
192
|
+
const move = moves.get(segment.id)!;
|
|
193
|
+
const prior = live.get(segment.id);
|
|
194
|
+
if (move.type === 'stay') {
|
|
195
|
+
const glyph = prior
|
|
196
|
+
? { ...prior, width: box.width }
|
|
197
|
+
: newGlyph(segment, box.width, previous.get(segment.id)!.x);
|
|
198
|
+
glyph.x.set(glide(box.x));
|
|
199
|
+
if (!glyph.rolls) {
|
|
200
|
+
glyph.scale.set(glide(1));
|
|
201
|
+
glyph.opacity.set(fade(1, 0.25));
|
|
202
|
+
}
|
|
203
|
+
glyphs.push(glyph);
|
|
204
|
+
} else if (move.type === 'enter' && move.origin != null) {
|
|
205
|
+
const glyph = newGlyph(segment, box.width, box.x, { scale: 0.8, opacity: 0 });
|
|
206
|
+
glyph.origin.set(move.origin);
|
|
207
|
+
glyph.scale.set(glide(1));
|
|
208
|
+
glyph.opacity.set(fade(1, 0.35));
|
|
209
|
+
glyphs.push(glyph);
|
|
210
|
+
} else if (segment.kind) {
|
|
211
|
+
// Digits drop in from above, symbols rise from below.
|
|
212
|
+
const rollY = segment.kind === 'digit' ? -height : height;
|
|
213
|
+
const glyph = newGlyph(segment, box.width, move.x, { rollY, rollOpacity: 0 });
|
|
214
|
+
glyph.x.set(glide(box.x));
|
|
215
|
+
glyph.rollY.set(glide(0));
|
|
216
|
+
glyph.rollOpacity.set(fade(1, 0.25));
|
|
217
|
+
glyphs.push(glyph);
|
|
218
|
+
} else {
|
|
219
|
+
const glyph = newGlyph(segment, box.width, move.x, { scale: 0.95, opacity: 0 });
|
|
220
|
+
glyph.x.set(glide(box.x));
|
|
221
|
+
glyph.scale.set(glide(1));
|
|
222
|
+
glyph.opacity.set(fade(1, 0.5, 0.25));
|
|
223
|
+
glyphs.push(glyph);
|
|
224
|
+
}
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
const width = motion?.width ?? makeMutable(widthOf(previous));
|
|
228
|
+
const from = width.get();
|
|
229
|
+
const to = diff!.segments.length === 0 ? from : widthOf(next);
|
|
230
|
+
width.set(from === 0 ? to : glide(to));
|
|
231
|
+
const done = ++generation.current;
|
|
232
|
+
const clock = makeMutable(0);
|
|
233
|
+
clock.set(
|
|
234
|
+
withTiming(1, { duration: DURATION }, (finished) => {
|
|
235
|
+
'worklet';
|
|
236
|
+
if (finished) scheduleOnRN(settle, done);
|
|
237
|
+
}),
|
|
238
|
+
);
|
|
239
|
+
setMotion({ glyphs, width, height });
|
|
240
|
+
setShown({ text, segments: after });
|
|
241
|
+
};
|
|
242
|
+
|
|
243
|
+
const measure = (row: 'before' | 'after', id: string, layout: LayoutRectangle) => {
|
|
244
|
+
if (measures.current?.text !== text) {
|
|
245
|
+
measures.current = { text, done: false, before: new Map(), after: new Map() };
|
|
246
|
+
}
|
|
247
|
+
const current = measures.current;
|
|
248
|
+
current[row].set(id, layout);
|
|
249
|
+
if (!current.done && current.before.size === before.length && current.after.size === after.length) {
|
|
250
|
+
current.done = true;
|
|
251
|
+
start(current);
|
|
252
|
+
}
|
|
253
|
+
};
|
|
254
|
+
|
|
255
|
+
// One line at rest too, so a morph never unwraps the text. While the glyphs
|
|
256
|
+
// move, a copy of it in the sizer is the reader, so the box keeps its baseline.
|
|
257
|
+
const label = (
|
|
258
|
+
<Text className={className} style={[style, RESET, motion && styles.reader]} numberOfLines={1}>
|
|
259
|
+
{shown.text}
|
|
260
|
+
</Text>
|
|
261
|
+
);
|
|
262
|
+
|
|
263
|
+
return (
|
|
264
|
+
<View className={className} style={style}>
|
|
265
|
+
{motion ? (
|
|
266
|
+
<Sizer width={motion.width} height={motion.height}>
|
|
267
|
+
{label}
|
|
268
|
+
{motion.glyphs.map((glyph) => (
|
|
269
|
+
<GlyphView
|
|
270
|
+
key={glyph.key}
|
|
271
|
+
glyph={glyph}
|
|
272
|
+
height={motion.height}
|
|
273
|
+
className={className}
|
|
274
|
+
style={style}
|
|
275
|
+
/>
|
|
276
|
+
))}
|
|
277
|
+
</Sizer>
|
|
278
|
+
) : label}
|
|
279
|
+
{pending ? (
|
|
280
|
+
<View key={text} style={styles.measure} aria-hidden>
|
|
281
|
+
{(['before', 'after'] as const).map((row) => (
|
|
282
|
+
<View key={row} style={styles.row}>
|
|
283
|
+
{(row === 'before' ? before : after).map((segment) => (
|
|
284
|
+
<Text
|
|
285
|
+
key={segment.id}
|
|
286
|
+
className={className}
|
|
287
|
+
style={[style, RESET]}
|
|
288
|
+
onLayout={(event) => measure(row, segment.id, event.nativeEvent.layout)}
|
|
289
|
+
>
|
|
290
|
+
{segment.string}
|
|
291
|
+
</Text>
|
|
292
|
+
))}
|
|
293
|
+
</View>
|
|
294
|
+
))}
|
|
295
|
+
</View>
|
|
296
|
+
) : null}
|
|
297
|
+
</View>
|
|
298
|
+
);
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function Sizer({ width, height, children }: { width: SharedValue<number>; height: number; children: ReactNode }) {
|
|
302
|
+
const animated = useAnimatedStyle(() => ({ width: width.value }));
|
|
303
|
+
return (
|
|
304
|
+
<Animated.View style={[{ height }, animated]}>
|
|
305
|
+
{children}
|
|
306
|
+
</Animated.View>
|
|
307
|
+
);
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
function GlyphView({
|
|
311
|
+
glyph: { x, scale, opacity, origin, rollY, rollOpacity, rolls, width, string },
|
|
312
|
+
height,
|
|
313
|
+
className,
|
|
314
|
+
style,
|
|
315
|
+
}: {
|
|
316
|
+
glyph: Glyph;
|
|
317
|
+
height: number;
|
|
318
|
+
className?: string;
|
|
319
|
+
style?: StyleProp<TextStyle>;
|
|
320
|
+
}) {
|
|
321
|
+
const outer = useAnimatedStyle(() => ({
|
|
322
|
+
opacity: opacity.value,
|
|
323
|
+
transform: [{ translateX: x.value + origin.value * (1 - scale.value) }, { scale: scale.value }],
|
|
324
|
+
}));
|
|
325
|
+
const inner = useAnimatedStyle(() => ({
|
|
326
|
+
opacity: rollOpacity.value,
|
|
327
|
+
transform: [{ translateY: rollY.value }],
|
|
328
|
+
}));
|
|
329
|
+
return (
|
|
330
|
+
// One spare point of width, so rounding never wraps the glyph.
|
|
331
|
+
<Animated.View aria-hidden style={[styles.glyph, { width: width + 1, height }, rolls && styles.slot, outer]}>
|
|
332
|
+
<Animated.View style={inner}>
|
|
333
|
+
<Text className={className} style={[style, RESET]}>
|
|
334
|
+
{string}
|
|
335
|
+
</Text>
|
|
336
|
+
</Animated.View>
|
|
337
|
+
</Animated.View>
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/**
|
|
342
|
+
* The outer box owns margins and padding, so the glyphs inside drop them.
|
|
343
|
+
* Longhands, because a class's `marginTop` beats a `margin` shorthand.
|
|
344
|
+
*/
|
|
345
|
+
const RESET: TextStyle = {
|
|
346
|
+
marginTop: 0,
|
|
347
|
+
marginBottom: 0,
|
|
348
|
+
marginLeft: 0,
|
|
349
|
+
marginRight: 0,
|
|
350
|
+
marginStart: 0,
|
|
351
|
+
marginEnd: 0,
|
|
352
|
+
marginHorizontal: 0,
|
|
353
|
+
marginVertical: 0,
|
|
354
|
+
paddingTop: 0,
|
|
355
|
+
paddingBottom: 0,
|
|
356
|
+
paddingLeft: 0,
|
|
357
|
+
paddingRight: 0,
|
|
358
|
+
paddingStart: 0,
|
|
359
|
+
paddingEnd: 0,
|
|
360
|
+
paddingHorizontal: 0,
|
|
361
|
+
paddingVertical: 0,
|
|
362
|
+
};
|
|
363
|
+
|
|
364
|
+
const styles = StyleSheet.create({
|
|
365
|
+
glyph: { position: 'absolute', left: 0, top: 0 },
|
|
366
|
+
// A rolling digit slides a full line, so its slot clips it.
|
|
367
|
+
slot: { overflow: 'hidden' },
|
|
368
|
+
// The whole string once, unseen, while the glyphs move. Screen readers read
|
|
369
|
+
// it, and it is the box's only text in the layout flow, so it gives the box
|
|
370
|
+
// the baseline the text at rest has. Not `transparent`: Android reads that
|
|
371
|
+
// value as no color and draws the text in the default one. A shadow and an
|
|
372
|
+
// underline keep their own color, so they go too.
|
|
373
|
+
reader: { color: '#00000001', textShadowRadius: 0, textShadowOffset: { width: 0, height: 0 }, textDecorationLine: 'none' },
|
|
374
|
+
// Lays both rows out unconstrained and unseen; the wide row never wraps a word.
|
|
375
|
+
measure: { position: 'absolute', width: 0, height: 0, overflow: 'hidden' },
|
|
376
|
+
row: { position: 'absolute', top: 0, left: 0, width: 10000, flexDirection: 'row', alignItems: 'flex-start' },
|
|
377
|
+
});
|
package/src/plan.ts
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import type { Segment } from './diff';
|
|
2
|
+
|
|
3
|
+
export interface Box {
|
|
4
|
+
x: number;
|
|
5
|
+
width: number;
|
|
6
|
+
}
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* How one segment moves. `x` is where it starts (enter) or ends (exit), in
|
|
10
|
+
* the root's coordinates. `origin` is set for a group: the offset from the
|
|
11
|
+
* segment's centre to the group's centre, which the scale pivots on.
|
|
12
|
+
*/
|
|
13
|
+
export type Move =
|
|
14
|
+
| { type: 'stay' }
|
|
15
|
+
| { type: 'enter'; x: number; origin?: number }
|
|
16
|
+
| { type: 'exit'; x: number; origin?: number };
|
|
17
|
+
|
|
18
|
+
// torph scales a run of this many entering or exiting segments as one block.
|
|
19
|
+
const GROUP = 6;
|
|
20
|
+
|
|
21
|
+
/** Runs of at least `GROUP` consecutive ids that are in `members`. */
|
|
22
|
+
function groups(ids: string[], members: Set<string>) {
|
|
23
|
+
const result: string[][] = [];
|
|
24
|
+
let run: string[] = [];
|
|
25
|
+
const flush = () => {
|
|
26
|
+
if (run.length >= GROUP) result.push(run);
|
|
27
|
+
run = [];
|
|
28
|
+
};
|
|
29
|
+
for (const id of ids) {
|
|
30
|
+
if (members.has(id)) run.push(id);
|
|
31
|
+
else flush();
|
|
32
|
+
}
|
|
33
|
+
flush();
|
|
34
|
+
return result;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The nearest id in `alive` on the preferred side of `index`, else the other side. */
|
|
38
|
+
function anchor(index: number, ids: string[], alive: Set<string>, forwardFirst: boolean) {
|
|
39
|
+
const back = () => ids.slice(0, index).findLast((id) => alive.has(id));
|
|
40
|
+
const ahead = () => ids.slice(index + 1).find((id) => alive.has(id));
|
|
41
|
+
return (forwardFirst ? (ahead() ?? back()) : (back() ?? ahead())) ?? null;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** Each group member's offset from its own centre to the group's centre. */
|
|
45
|
+
function origins(run: string[], boxes: Map<string, Box>, into: Map<string, number>) {
|
|
46
|
+
const left = Math.min(...run.map((id) => boxes.get(id)!.x));
|
|
47
|
+
const right = Math.max(...run.map((id) => boxes.get(id)!.x + boxes.get(id)!.width));
|
|
48
|
+
for (const id of run) {
|
|
49
|
+
const box = boxes.get(id)!;
|
|
50
|
+
into.set(id, (left + right) / 2 - (box.x + box.width / 2));
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Plans a change from the `before` layout to the `after` one. A new segment
|
|
56
|
+
* starts offset by how far its nearest surviving neighbour moved, so it rides
|
|
57
|
+
* in with it, and a dropped one drifts with its neighbour as it fades.
|
|
58
|
+
*/
|
|
59
|
+
export function planMoves(
|
|
60
|
+
before: string[],
|
|
61
|
+
after: Segment[],
|
|
62
|
+
previous: Map<string, Box>,
|
|
63
|
+
next: Map<string, Box>,
|
|
64
|
+
) {
|
|
65
|
+
const afterIds = after.map((segment) => segment.id);
|
|
66
|
+
const kept = new Set(afterIds);
|
|
67
|
+
const moves = new Map<string, Move>();
|
|
68
|
+
|
|
69
|
+
const entering = new Set(afterIds.filter((id) => !previous.has(id)));
|
|
70
|
+
const enterOrigins = new Map<string, number>();
|
|
71
|
+
for (const run of groups(afterIds, entering)) origins(run, next, enterOrigins);
|
|
72
|
+
const known = new Set(afterIds.filter((id) => previous.has(id)));
|
|
73
|
+
afterIds.forEach((id, index) => {
|
|
74
|
+
const box = next.get(id)!;
|
|
75
|
+
if (!entering.has(id)) {
|
|
76
|
+
moves.set(id, { type: 'stay' });
|
|
77
|
+
} else if (enterOrigins.has(id)) {
|
|
78
|
+
moves.set(id, { type: 'enter', x: box.x, origin: enterOrigins.get(id) });
|
|
79
|
+
} else {
|
|
80
|
+
const neighbour = anchor(index, afterIds, known, false);
|
|
81
|
+
const shift = neighbour ? previous.get(neighbour)!.x - next.get(neighbour)!.x : 0;
|
|
82
|
+
moves.set(id, { type: 'enter', x: box.x + shift });
|
|
83
|
+
}
|
|
84
|
+
});
|
|
85
|
+
|
|
86
|
+
const exiting = new Set(before.filter((id) => !kept.has(id)));
|
|
87
|
+
const exitOrigins = new Map<string, number>();
|
|
88
|
+
for (const run of groups(before, exiting)) origins(run, previous, exitOrigins);
|
|
89
|
+
const survivors = new Set(before.filter((id) => kept.has(id)));
|
|
90
|
+
before.forEach((id, index) => {
|
|
91
|
+
if (!exiting.has(id)) return;
|
|
92
|
+
const box = previous.get(id)!;
|
|
93
|
+
if (exitOrigins.has(id)) {
|
|
94
|
+
moves.set(id, { type: 'exit', x: box.x, origin: exitOrigins.get(id) });
|
|
95
|
+
return;
|
|
96
|
+
}
|
|
97
|
+
const neighbour = anchor(index, before, survivors, true);
|
|
98
|
+
const shift = neighbour ? next.get(neighbour)!.x - previous.get(neighbour)!.x : 0;
|
|
99
|
+
moves.set(id, { type: 'exit', x: box.x + shift });
|
|
100
|
+
});
|
|
101
|
+
return moves;
|
|
102
|
+
}
|