skia-motion-runtime 3.3.1 → 3.4.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.
@@ -0,0 +1,199 @@
1
+ /**
2
+ * Ink and optical centres, and the `row` layout built on them. Pure and worklet-safe (no regular expressions), so the app's draw worklet,
3
+ * the SVG preview and `skac asset check` place a row from one rule: what the check passes is what the phone draws.
4
+ */
5
+ import { CASELESS_LETTERS, DIGIT_ZEROS, LOWERCASE_LETTERS, UPPERCASE_LETTERS } from './asset-unicode';
6
+
7
+ /** left, top, right, bottom */
8
+ export type Box = readonly [number, number, number, number];
9
+ /** A text's ink box and the optical band its centre is taken from, in its paragraph's units. */
10
+ export type TextInk = { box: Box; band: readonly [number, number] };
11
+ /** One laid-out child of a row: its ink box in the row's units before it is moved, and the height its centre sits at. */
12
+ export type RowItem = { box: Box; centre: number };
13
+ export type RowAlign = 'start' | 'center' | 'end';
14
+
15
+ /** Whether a code point is in a flat, ascending [first, last, ...] range table. */
16
+ function inRanges(code: number, ranges: readonly number[]): boolean {
17
+ 'worklet';
18
+ let low = 0;
19
+ let high = ranges.length / 2 - 1;
20
+ while (low <= high) {
21
+ const mid = (low + high) >> 1;
22
+ if (code < ranges[mid * 2]!) high = mid - 1;
23
+ else if (code > ranges[mid * 2 + 1]!) low = mid + 1;
24
+ else return true;
25
+ }
26
+ return false;
27
+ }
28
+
29
+ function isDigit(code: number): boolean {
30
+ 'worklet';
31
+ for (const zero of DIGIT_ZEROS) if (code >= zero && code < zero + 10) return true;
32
+ return false;
33
+ }
34
+
35
+ /**
36
+ * How a text reads for its optical centre: 'lower' when it has lowercase letters and no capitals or digits, 'caseless' when it has
37
+ * letters with no case, as in Arabic or Devanagari (centred on the ink), else 'cased'. A cased or lower text is centred on a band from
38
+ * its x-height to its cap height by `capShare`.
39
+ */
40
+ export function textCase(text: string): 'lower' | 'caseless' | 'cased' {
41
+ 'worklet';
42
+ let lower = false;
43
+ let upperOrDigit = false;
44
+ let caseless = false;
45
+ for (let i = 0; i < text.length; i++) {
46
+ const code = text.codePointAt(i)!;
47
+ if (code > 0xffff) i++;
48
+ if (isDigit(code) || inRanges(code, UPPERCASE_LETTERS)) upperOrDigit = true;
49
+ else if (inRanges(code, LOWERCASE_LETTERS)) lower = true;
50
+ else if (inRanges(code, CASELESS_LETTERS)) caseless = true;
51
+ }
52
+ if (lower && !upperOrDigit) return 'lower';
53
+ return caseless ? 'caseless' : 'cased';
54
+ }
55
+
56
+ /**
57
+ * How much of a cased text stands at the cap height: its capitals and digits as a share of its capitals, digits and lowercase letters.
58
+ * 1 with no lowercase ("+3", "XP"), 0 with lowercase only ("correct"), and between for a mixed label: "5 of 5 correct" is 2 of 11.
59
+ */
60
+ export function capShare(text: string): number {
61
+ 'worklet';
62
+ let high = 0;
63
+ let low = 0;
64
+ for (let i = 0; i < text.length; i++) {
65
+ const code = text.codePointAt(i)!;
66
+ if (code > 0xffff) i++;
67
+ if (isDigit(code) || inRanges(code, UPPERCASE_LETTERS)) high++;
68
+ else if (inRanges(code, LOWERCASE_LETTERS)) low++;
69
+ }
70
+ return low === 0 ? 1 : high / (high + low);
71
+ }
72
+
73
+ /**
74
+ * A text's ink from its glyphs' boxes (each already at its place in the paragraph), and its band, from the first run's face: from the
75
+ * first baseline down to the last, and up from the first baseline by the x-height plus `capShare` of the step to the cap height. So
76
+ * "+3" stands on its cap height, "correct" on its x-height, and a mixed label such as "5 of 5 correct" mostly on its x-height, where most
77
+ * of its letters are; centring it by its two digits left the lowercase 1.5 pt low (O-8590). Undefined when no glyph draws.
78
+ */
79
+ export function textInk(
80
+ glyphs: readonly Box[], firstBaseline: number, lastBaseline: number, text: string, heights: { cap: number; x: number },
81
+ ): TextInk | undefined {
82
+ 'worklet';
83
+ let box: Box | undefined;
84
+ for (const [l, t, r, b] of glyphs) {
85
+ if (!(r > l && b > t)) continue; // a space draws nothing
86
+ box = box ? [Math.min(box[0], l), Math.min(box[1], t), Math.max(box[2], r), Math.max(box[3], b)] : [l, t, r, b];
87
+ }
88
+ if (!box) return undefined;
89
+ if (textCase(text) === 'caseless') return { box, band: [box[1], box[3]] };
90
+ const share = capShare(text);
91
+ // A face that gives only one of the two heights stands on that one; a text of capitals with no cap height is judged by its ink.
92
+ const low = heights.x || heights.cap;
93
+ const high = heights.cap || (share < 1 ? heights.x : 0);
94
+ const height = low && high ? low + share * (high - low) : 0;
95
+ const band: [number, number] = height ? [firstBaseline - height, lastBaseline] : [box[1], box[3]];
96
+ return { box, band };
97
+ }
98
+
99
+ /** Part way from one ink to another: a rolling count in a row is placed between its old value's ink and its new one's as it rolls. */
100
+ export function blendInk(from: TextInk | undefined, to: TextInk | undefined, progress: number): TextInk | undefined {
101
+ 'worklet';
102
+ if (!from || !to) return progress < 0.5 ? from : to;
103
+ const t = Math.min(1, Math.max(0, progress));
104
+ const mix = (a: number, b: number) => a + (b - a) * t;
105
+ return {
106
+ box: [mix(from.box[0], to.box[0]), mix(from.box[1], to.box[1]), mix(from.box[2], to.box[2]), mix(from.box[3], to.box[3])],
107
+ band: [mix(from.band[0], to.band[0]), mix(from.band[1], to.band[1])],
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Place a row: each item moves across so its ink starts `gap` after the ink before it (right to left, the first item is on the right),
113
+ * and down so its optical centre is at 0. `align` puts the row's ink start, centre or end at 0. Returns each item's move and the
114
+ * row's ink box after the moves.
115
+ */
116
+ export function rowLayout(items: readonly RowItem[], gap: number, align: RowAlign = 'start', rtl = false): { moves: [number, number][]; box: Box } {
117
+ 'worklet';
118
+ const order = items.map((_, i) => i);
119
+ if (rtl) order.reverse();
120
+ const moves: [number, number][] = items.map(() => [0, 0]);
121
+ let cursor = 0;
122
+ let top = Infinity;
123
+ let bottom = -Infinity;
124
+ for (const i of order) {
125
+ const { box, centre } = items[i]!;
126
+ moves[i] = [cursor - box[0], -centre];
127
+ cursor += box[2] - box[0] + gap;
128
+ top = Math.min(top, box[1] - centre);
129
+ bottom = Math.max(bottom, box[3] - centre);
130
+ }
131
+ const width = items.length ? cursor - gap : 0;
132
+ const shift = align === 'center' ? -width / 2 : align === 'end' ? -width : 0;
133
+ for (const move of moves) move[0] += shift;
134
+ return { moves, box: items.length ? [shift, top, shift + width, bottom] : [0, 0, 0, 0] };
135
+ }
136
+
137
+ /**
138
+ * A row's plate: around the row laid out with `widest` items (the bound texts showing their widest sample), so its width never changes
139
+ * with the value, and as tall as the tallest band or box above and below 0 plus the padding, so it never changes with descenders either.
140
+ */
141
+ export function plateBox(widest: readonly RowItem[], bands: readonly [number, number][], gap: number, align: RowAlign, rtl: boolean, padding: readonly [number, number]): Box {
142
+ 'worklet';
143
+ const { box } = rowLayout(widest, gap, align, rtl);
144
+ let half = 0;
145
+ for (const [top, bottom] of bands) half = Math.max(half, -top, bottom);
146
+ return [box[0] - padding[0], -half - padding[1], box[2] + padding[0], half + padding[1]];
147
+ }
148
+
149
+ type Scalar = number | string;
150
+ /** The children a row places: texts, images and simple shapes. */
151
+ export type RowChild =
152
+ | { kind: 'text'; x: Scalar; y: Scalar; text: string | { value: string } }
153
+ | { kind: 'image'; image: string; x: Scalar; y: Scalar; width: Scalar; height: Scalar }
154
+ | { kind: 'ellipse' | 'roundRect'; x: Scalar; y: Scalar; width: Scalar; height: Scalar };
155
+
156
+ /**
157
+ * A row's items, measured by the caller's own engine (Skia on the phone, CanvasKit in check) through one rule: a text by its ink and
158
+ * optical band (`ink`, in its paragraph's units), an image by its ink box (`imagePart`, fractions of its box; the whole box when
159
+ * unknown, as for a host image slot), a shape by its box. `widest` gives the same items with every bound text showing the plate's widest
160
+ * sample.
161
+ */
162
+ export function rowItems(
163
+ children: readonly RowChild[], read: (value: Scalar | undefined, fallback?: number) => number,
164
+ ink: (child: RowChild & { kind: 'text' }, index: number, widest: boolean) => TextInk | undefined,
165
+ imagePart: (index: number) => Box | undefined, hasWidest: boolean,
166
+ ): { items: RowItem[]; widest: RowItem[]; bands: [number, number][] } {
167
+ 'worklet';
168
+ const items: RowItem[] = [];
169
+ const widest: RowItem[] = [];
170
+ const bands: [number, number][] = [];
171
+ children.forEach((child, index) => {
172
+ const x = read(child.x);
173
+ const y = read(child.y);
174
+ if (child.kind === 'text') {
175
+ const shown = ink(child, index, false);
176
+ const wide = hasWidest && typeof child.text !== 'string' ? ink(child, index, true) : undefined;
177
+ // A bound text's band comes from the widest sample when there is one, so a script centred on its ink (no cap height) neither bobs
178
+ // nor resizes the plate as the value changes; for capitals and digits the band is the same either way.
179
+ const band = (wide ?? shown)?.band;
180
+ const place = (measured: TextInk | undefined): RowItem => (measured && band
181
+ ? { box: [x + measured.box[0], y + measured.box[1], x + measured.box[2], y + measured.box[3]], centre: y + (band[0] + band[1]) / 2 }
182
+ : { box: [x, y, x, y], centre: y });
183
+ const item = place(shown);
184
+ items.push(item);
185
+ if (band) bands.push([y + band[0] - item.centre, y + band[1] - item.centre]);
186
+ widest.push(wide ? place(wide) : item);
187
+ return;
188
+ }
189
+ const w = read(child.width);
190
+ const h = read(child.height);
191
+ const part = child.kind === 'image' ? imagePart(index) : undefined;
192
+ const box: Box = part ? [x + part[0] * w, y + part[1] * h, x + part[2] * w, y + part[3] * h] : [x, y, x + w, y + h];
193
+ const item = { box, centre: (box[1] + box[3]) / 2 };
194
+ items.push(item);
195
+ widest.push(item);
196
+ bands.push([box[1] - item.centre, box[3] - item.centre]);
197
+ });
198
+ return { items, widest, bands };
199
+ }
@@ -64,9 +64,11 @@ export async function preloadMotionAsset(
64
64
  const preloadable = image as SkImage & { makeRasterImage?: () => Promise<SkImage> };
65
65
  ready = await preloadable.makeRasterImage?.() ?? image;
66
66
  if (uploadImages) {
67
- const uploadable = ready as SkImage & { makeTextureImage?: () => SkImage };
67
+ // Uploaded with mip levels: the draw samples them, and a texture made without them (react-native-skia's default) is
68
+ // sampled at full size, so art drawn small aliases. Older versions take no options and ignore it.
69
+ const uploadable = ready as SkImage & { makeTextureImage?: (options?: { mipmapped?: boolean }) => SkImage };
68
70
  try {
69
- ready = uploadable.makeTextureImage?.() ?? ready;
71
+ ready = uploadable.makeTextureImage?.({ mipmapped: true }) ?? ready;
70
72
  } catch {
71
73
  // A reduced or unsupported backend can still upload the raster image when drawn.
72
74
  }
@@ -0,0 +1,195 @@
1
+ /**
2
+ * A rolling number: the odometer a text node with `roll` draws. Pure and worklet-safe (no regular expressions, no Intl), so the app's
3
+ * draw worklet, the SVG preview and `skac asset check` share one answer.
4
+ */
5
+
6
+ import { DIGIT_ZEROS } from './asset-unicode';
7
+
8
+ /** A value in any decimal digit system (asset-unicode.ts lists their zeros) rolls in its own glyphs. */
9
+ export { DIGIT_ZEROS };
10
+
11
+ export type RollNumber = { prefix: string; digits: number[]; suffix: string; zero: number };
12
+ /** One digit place, left to right. `current` and `next` are 0 to 9, or -1 for a blank leading place. `turn` is how far the column has
13
+ * moved from current to next, 0 to 1. `smear` is 0 while the place turns slowly enough to read, rising to 1 as it passes
14
+ * SMEAR_FULL turns a second: the app draws it as a vertical blur of its column then. */
15
+ export type RollPlace = { current: number; next: number; turn: number; smear: number };
16
+ /** How the shown value runs over the roll: 'out' (the default) slows into the new value so its last turns read; 'linear' runs evenly. */
17
+ export type RollEase = 'out' | 'linear';
18
+ /** A text's roll settings: the ease, and `ms`, the time the progress channel takes from 0 to 1 (rollSpan), when known. */
19
+ export type RollTiming = { ease?: RollEase; ms?: number };
20
+ /** A place turning faster than this many times a second cannot be read; it starts to smear here and is fully smeared at SMEAR_FULL. */
21
+ export const SMEAR_FROM = 30;
22
+ export const SMEAR_FULL = 60;
23
+ /** A fully smeared place blurs down its column by this share of the line height (the blur's sigma). */
24
+ export const SMEAR_SIGMA = 0.2;
25
+ export type RollFrame = { prefix: string; suffix: string; zero: number; places: RollPlace[] };
26
+
27
+ function digitOf(code: number): { zero: number; value: number } | undefined {
28
+ 'worklet';
29
+ for (const zero of DIGIT_ZEROS) if (code >= zero && code < zero + 10) return { zero, value: code - zero };
30
+ return undefined;
31
+ }
32
+
33
+ /** Split "+1250 XP" into a prefix, one run of digits and a suffix. Undefined when the digits are not one run, mix systems or are absent. */
34
+ export function parseRoll(text: string): RollNumber | undefined {
35
+ 'worklet';
36
+ const codes: number[] = [];
37
+ for (let i = 0; i < text.length; i++) {
38
+ const code = text.codePointAt(i)!;
39
+ codes.push(code);
40
+ if (code > 0xffff) i++;
41
+ }
42
+ let start = -1;
43
+ let end = -1;
44
+ let zero = -1;
45
+ const digits: number[] = [];
46
+ for (let i = 0; i < codes.length; i++) {
47
+ const digit = digitOf(codes[i]!);
48
+ if (!digit) continue;
49
+ if (end >= 0 && end !== i) return undefined; // a second run: "1,250" or "3 of 5"
50
+ if (zero >= 0 && digit.zero !== zero) return undefined;
51
+ if (start < 0) start = i;
52
+ end = i + 1;
53
+ zero = digit.zero;
54
+ digits.push(digit.value);
55
+ }
56
+ if (start < 0) return undefined;
57
+ const join = (list: number[]) => {
58
+ let out = '';
59
+ for (const code of list) out += String.fromCodePoint(code);
60
+ return out;
61
+ };
62
+ return { prefix: join(codes.slice(0, start)), digits, suffix: join(codes.slice(end)), zero };
63
+ }
64
+
65
+ const valueOf = (digits: readonly number[]) => {
66
+ 'worklet';
67
+ let value = 0;
68
+ for (const digit of digits) value = value * 10 + digit;
69
+ return value;
70
+ };
71
+
72
+ const easeValue = (progress: number, ease: RollEase) => {
73
+ 'worklet';
74
+ return ease === 'linear' ? progress : 1 - (1 - progress) ** 3;
75
+ };
76
+
77
+ const easeSlope = (progress: number, ease: RollEase) => {
78
+ 'worklet';
79
+ return ease === 'linear' ? 1 : 3 * (1 - progress) ** 2;
80
+ };
81
+
82
+ type ClipKeys = Readonly<Record<string, { tracks: Readonly<Record<string, readonly (readonly [number, number, ...unknown[]])[]>> }>>;
83
+
84
+ /**
85
+ * How long a roll's progress channel takes to run from 0 to 1, in ms: in each clip that keys it, the time from its last still key to the
86
+ * first key at its final value, over the change. The fastest clip wins; undefined when no clip moves the channel.
87
+ */
88
+ export function rollSpan(clips: ClipKeys, channel: string): number | undefined {
89
+ let fastest: number | undefined;
90
+ for (const { tracks } of Object.values(clips)) {
91
+ const keys = tracks[channel];
92
+ if (!keys || keys.length < 2) continue;
93
+ const first = keys[0]![1];
94
+ const last = keys[keys.length - 1]![1];
95
+ if (first === last) continue;
96
+ let from = keys[0]![0];
97
+ for (let i = 1; i < keys.length; i++) if (keys[i]![1] !== first) { from = keys[i - 1]![0]; break; }
98
+ let to = keys[keys.length - 1]![0];
99
+ for (let i = keys.length - 1; i > 0; i--) if (keys[i - 1]![1] !== last) { to = keys[i]![0]; break; }
100
+ const ms = (to - from) / Math.abs(last - first);
101
+ if (ms > 0) fastest = fastest === undefined ? ms : Math.min(fastest, ms);
102
+ }
103
+ return fastest;
104
+ }
105
+
106
+ /**
107
+ * The odometer between two values at progress 0 to 1. The shown value runs from `from` to `to` by the roll's ease; place i turns during the last
108
+ * unit of the places to its right, so the rightmost place turns fastest and a place moves only when the one below it wraps. The number of
109
+ * places is the longer of the two; a leading place is blank until the value reaches it, and opens as its first digit rolls in. Prefix, suffix and
110
+ * digit system come from `to`. Undefined when either value is not one run of digits, or they differ in prefix, suffix or digit system:
111
+ * the caller shows `from` before 0.5 and `to` after.
112
+ */
113
+ export function rollFrame(from: string, to: string, progress: number, timing: RollTiming = {}): RollFrame | undefined {
114
+ 'worklet';
115
+ const a = parseRoll(from);
116
+ const b = parseRoll(to);
117
+ if (!a || !b || a.prefix !== b.prefix || a.suffix !== b.suffix || a.zero !== b.zero) return undefined;
118
+ const p = Math.min(1, Math.max(0, progress));
119
+ const start = valueOf(a.digits);
120
+ const end = valueOf(b.digits);
121
+ const count = Math.max(a.digits.length, b.digits.length);
122
+ // A zero-padded string ("000120") writes its padding zeros, so those places are never blank; otherwise a leading place is blank until
123
+ // the value reaches it.
124
+ const padded = (digits: readonly number[]) => (digits.length > 1 && digits[0] === 0 ? digits.length : 0);
125
+ const written = p < 0.5 ? padded(a.digits) : padded(b.digits);
126
+ const ease = timing.ease ?? 'out';
127
+ const value = start + (end - start) * easeValue(p, ease);
128
+ // Place i turns once per 10^i of value, so its turns a second are the value's speed over 10^i. Before the roll starts and once it
129
+ // has ended nothing turns, so nothing smears there, whatever the ease's slope at the ends.
130
+ const speed = timing.ms && p > 0 && p < 1 ? Math.abs(end - start) * easeSlope(p, ease) * 1000 / timing.ms : 0;
131
+ const places: RollPlace[] = [];
132
+ for (let i = count - 1; i >= 0; i--) {
133
+ const unit = 10 ** i;
134
+ const base = Math.floor(value / unit + 1e-9);
135
+ const below = value - base * unit;
136
+ const turn = Math.min(1, Math.max(0, below - (unit - 1)));
137
+ const current = base === 0 && i > 0 && i >= written ? -1 : base % 10;
138
+ const next = (base + 1) % 10;
139
+ const smear = Math.min(1, Math.max(0, (speed / unit - SMEAR_FROM) / (SMEAR_FULL - SMEAR_FROM)));
140
+ places.push({ current, next, turn: turn < 1e-6 ? 0 : turn, smear });
141
+ }
142
+ return { prefix: b.prefix, suffix: b.suffix, zero: b.zero, places };
143
+ }
144
+
145
+ /** The character for a digit 0 to 9 in a digit system, or '' for a blank place. */
146
+ export function digitText(digit: number, zero: number): string {
147
+ 'worklet';
148
+ return digit < 0 ? '' : String.fromCodePoint(zero + digit);
149
+ }
150
+
151
+ // Worklets capture a helper when the function using it is defined, so helpers come first.
152
+ type Feature = { name: string; value: number };
153
+
154
+ /**
155
+ * A rolling text's style: its own, with tabular figures on, so every digit takes one advance. The app draws it this way and asset check
156
+ * measures it this way; any other node comes back unchanged.
157
+ */
158
+ export function rollTextStyle<N extends { roll?: unknown; fontFeatures?: readonly Feature[] }>(node: N): N {
159
+ 'worklet';
160
+ if (!node.roll || node.fontFeatures?.some(({ name }) => name === 'tnum')) return node;
161
+ return { ...node, fontFeatures: [...(node.fontFeatures ?? []), { name: 'tnum', value: 1 }] };
162
+ }
163
+
164
+ /**
165
+ * How far a rolling number's width has gone from its old value's to its new one's, 0 to 1: the share a row moves it by, so the gap to
166
+ * an icon holds while places open. When the two have as many places, the eased progress (the value's own share).
167
+ */
168
+ export function rollWidthShare(from: string, to: string, progress: number, timing: RollTiming = {}): number {
169
+ 'worklet';
170
+ const p = Math.min(1, Math.max(0, progress));
171
+ const frame = rollFrame(from, to, p, timing);
172
+ if (!frame) return p < 0.5 ? 0 : 1;
173
+ const width = (f: RollFrame) => {
174
+ let places = 0;
175
+ let opening = 0;
176
+ for (const { current, turn } of f.places) {
177
+ if (current >= 0) places++;
178
+ else opening = Math.max(opening, turn);
179
+ }
180
+ return places + opening;
181
+ };
182
+ const start = width(rollFrame(from, to, 0, timing)!);
183
+ const end = width(rollFrame(from, to, 1, timing)!);
184
+ if (start === end) return easeValue(p, timing.ease ?? 'out');
185
+ return Math.min(1, Math.max(0, (width(frame) - start) / (end - start)));
186
+ }
187
+
188
+ /** The text a frame shows at rest: prefix, the digits of the places that are not blank, suffix. */
189
+ export function restText(frame: RollFrame): string {
190
+ 'worklet';
191
+ let digits = '';
192
+ for (const { current } of frame.places) digits += digitText(current, frame.zero);
193
+ return frame.prefix + digits + frame.suffix;
194
+ }
195
+