@krate/motion 0.0.0-bootstrap.0 → 0.5.0-rc.17

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,508 @@
1
+ // Value types (numbers, units, colors, complex strings), mixers and
2
+ // interpolation. Ported from motion-dom (MIT, Copyright (c) 2018 Framer
3
+ // B.V.), see NOTICE.
4
+
5
+ import { clamp, MotionGlobalConfig, mixNumber, noop, pipe, progress, warnOnce, type Easing } from './utils.js';
6
+
7
+ export interface ValueType {
8
+ test: (v: any) => boolean;
9
+ parse: (v: any) => any;
10
+ transform?: (v: any) => any;
11
+ createTransformer?: (template: string) => (v: any) => string;
12
+ default?: any;
13
+ getAnimatableNone?: (v: any) => any;
14
+ }
15
+
16
+ export interface RGBA {
17
+ red: number;
18
+ green: number;
19
+ blue: number;
20
+ alpha: number;
21
+ }
22
+
23
+ export interface HSLA {
24
+ hue: number;
25
+ saturation: number;
26
+ lightness: number;
27
+ alpha: number;
28
+ }
29
+
30
+ export const floatRegex = /-?(?:\d+(?:\.\d+)?|\.\d+)/gu;
31
+ export const colorRegex = /(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;
32
+ const singleColorRegex = /^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu;
33
+
34
+ /** Rounds to five decimals to avoid exponents in CSS. */
35
+ export const sanitize = (v: number): number => Math.round(v * 100000) / 100000;
36
+
37
+ export const number: ValueType = { test: (v) => typeof v === 'number', parse: parseFloat, transform: (v) => v };
38
+ export const alpha: ValueType = { ...number, transform: (v) => clamp(0, 1, v) };
39
+ export const scale: ValueType = { ...number, default: 1 };
40
+ export const int: ValueType = { ...number, transform: Math.round };
41
+
42
+ const createUnitType = (unit: string): ValueType => ({
43
+ test: (v) => typeof v === 'string' && v.endsWith(unit) && v.split(' ').length === 1,
44
+ parse: parseFloat,
45
+ transform: (v) => `${v}${unit}`,
46
+ });
47
+ export const degrees: ValueType = /*@__PURE__*/ createUnitType('deg');
48
+ export const percent: ValueType = /*@__PURE__*/ createUnitType('%');
49
+ export const px: ValueType = /*@__PURE__*/ createUnitType('px');
50
+ export const vh: ValueType = /*@__PURE__*/ createUnitType('vh');
51
+ export const vw: ValueType = /*@__PURE__*/ createUnitType('vw');
52
+ export const progressPercentage: ValueType = {
53
+ ...percent,
54
+ parse: (v) => percent.parse(v) / 100,
55
+ transform: (v) => percent.transform!(v * 100),
56
+ };
57
+ export const auto: ValueType = { test: (v) => v === 'auto', parse: (v) => v };
58
+
59
+ const isColorString =
60
+ (type: string, testProp?: string) =>
61
+ (v: any): boolean =>
62
+ Boolean((typeof v === 'string' && singleColorRegex.test(v) && v.startsWith(type)) || (testProp && v != null && Object.prototype.hasOwnProperty.call(v, testProp)));
63
+
64
+ const splitColor =
65
+ (a: string, b: string, c: string) =>
66
+ (v: any): any => {
67
+ if (typeof v !== 'string') return v;
68
+ const [x, y, z, al] = v.match(floatRegex) as string[];
69
+ return { [a]: parseFloat(x), [b]: parseFloat(y), [c]: parseFloat(z), alpha: al !== undefined ? parseFloat(al) : 1 };
70
+ };
71
+
72
+ const rgbUnit = (v: number): number => Math.round(clamp(0, 255, v));
73
+
74
+ export const rgba: ValueType = {
75
+ test: isColorString('rgb', 'red'),
76
+ parse: splitColor('red', 'green', 'blue'),
77
+ transform: ({ red, green, blue, alpha: a = 1 }: RGBA) =>
78
+ 'rgba(' + rgbUnit(red) + ', ' + rgbUnit(green) + ', ' + rgbUnit(blue) + ', ' + sanitize(clamp(0, 1, a)) + ')',
79
+ };
80
+
81
+ function parseHex(v: string): RGBA {
82
+ let r = '';
83
+ let g = '';
84
+ let b = '';
85
+ let a = '';
86
+ if (v.length > 5) {
87
+ r = v.substring(1, 3);
88
+ g = v.substring(3, 5);
89
+ b = v.substring(5, 7);
90
+ a = v.substring(7, 9);
91
+ } else {
92
+ r = v.substring(1, 2);
93
+ g = v.substring(2, 3);
94
+ b = v.substring(3, 4);
95
+ a = v.substring(4, 5);
96
+ r += r;
97
+ g += g;
98
+ b += b;
99
+ a += a;
100
+ }
101
+ return { red: parseInt(r, 16), green: parseInt(g, 16), blue: parseInt(b, 16), alpha: a ? parseInt(a, 16) / 255 : 1 };
102
+ }
103
+
104
+ export const hex: ValueType = { test: isColorString('#'), parse: parseHex, transform: rgba.transform };
105
+
106
+ export const hsla: ValueType = {
107
+ test: isColorString('hsl', 'hue'),
108
+ parse: splitColor('hue', 'saturation', 'lightness'),
109
+ transform: ({ hue, saturation, lightness, alpha: a = 1 }: HSLA) =>
110
+ 'hsla(' + Math.round(hue) + ', ' + percent.transform!(sanitize(saturation)) + ', ' + percent.transform!(sanitize(lightness)) + ', ' + sanitize(clamp(0, 1, a)) + ')',
111
+ };
112
+
113
+ export const color: ValueType = {
114
+ test: (v) => rgba.test(v) || hex.test(v) || hsla.test(v),
115
+ parse: (v) => (rgba.test(v) ? rgba.parse(v) : hsla.test(v) ? hsla.parse(v) : hex.parse(v)),
116
+ transform: (v) => (typeof v === 'string' ? v : Object.prototype.hasOwnProperty.call(v, 'red') ? rgba.transform!(v) : hsla.transform!(v)),
117
+ getAnimatableNone: (v) => {
118
+ const parsed = color.parse(v);
119
+ parsed.alpha = 0;
120
+ return color.transform!(parsed);
121
+ },
122
+ };
123
+
124
+ function hueToRgb(p: number, q: number, t: number): number {
125
+ if (t < 0) t += 1;
126
+ if (t > 1) t -= 1;
127
+ if (t < 1 / 6) return p + (q - p) * 6 * t;
128
+ if (t < 1 / 2) return q;
129
+ if (t < 2 / 3) return p + (q - p) * (2 / 3 - t) * 6;
130
+ return p;
131
+ }
132
+
133
+ export function hslaToRgba({ hue, saturation, lightness, alpha: a }: HSLA): RGBA {
134
+ hue /= 360;
135
+ saturation /= 100;
136
+ lightness /= 100;
137
+ let red = 0;
138
+ let green = 0;
139
+ let blue = 0;
140
+ if (!saturation) {
141
+ red = green = blue = lightness;
142
+ } else {
143
+ const q = lightness < 0.5 ? lightness * (1 + saturation) : lightness + saturation - lightness * saturation;
144
+ const p = 2 * lightness - q;
145
+ red = hueToRgb(p, q, hue + 1 / 3);
146
+ green = hueToRgb(p, q, hue);
147
+ blue = hueToRgb(p, q, hue - 1 / 3);
148
+ }
149
+ return { red: Math.round(red * 255), green: Math.round(green * 255), blue: Math.round(blue * 255), alpha: a };
150
+ }
151
+
152
+ const NUMBER = 'number';
153
+ const COLOR = 'color';
154
+ const VAR = 'var';
155
+ const SPLIT = '$' + '{}';
156
+ const complexRegex =
157
+ /var\s*\(\s*--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)|#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\)|-?(?:\d+(?:\.\d+)?|\.\d+)/giu;
158
+
159
+ export interface ComplexInfo {
160
+ values: any[];
161
+ split: string[];
162
+ indexes: { color: number[]; number: number[]; var: number[] };
163
+ types: string[];
164
+ }
165
+
166
+ export function analyseComplexValue(value: string | number): ComplexInfo {
167
+ const original = value.toString();
168
+ const values: any[] = [];
169
+ const indexes = { color: [] as number[], number: [] as number[], var: [] as number[] };
170
+ const types: string[] = [];
171
+ let i = 0;
172
+ const tokenised = original.replace(complexRegex, (parsed) => {
173
+ if (color.test(parsed)) {
174
+ indexes.color.push(i);
175
+ types.push(COLOR);
176
+ values.push(color.parse(parsed));
177
+ } else if (parsed.startsWith('var(')) {
178
+ indexes.var.push(i);
179
+ types.push(VAR);
180
+ values.push(parsed);
181
+ } else {
182
+ indexes.number.push(i);
183
+ types.push(NUMBER);
184
+ values.push(parseFloat(parsed));
185
+ }
186
+ ++i;
187
+ return SPLIT;
188
+ });
189
+ return { values, split: tokenised.split(SPLIT), indexes, types };
190
+ }
191
+
192
+ function createTransformer(source: string): (v: any[]) => string {
193
+ const { split, types } = analyseComplexValue(source);
194
+ const n = split.length;
195
+ return (v) => {
196
+ let out = '';
197
+ for (let i = 0; i < n; i++) {
198
+ out += split[i];
199
+ if (v[i] !== undefined) {
200
+ const type = types[i];
201
+ if (type === NUMBER) out += sanitize(v[i]);
202
+ else if (type === COLOR) out += color.transform!(v[i]);
203
+ else out += v[i];
204
+ }
205
+ }
206
+ return out;
207
+ };
208
+ }
209
+
210
+ const convertNumbersToZero = (v: any): any => (typeof v === 'number' ? 0 : color.test(v) ? color.getAnimatableNone!(v) : v);
211
+
212
+ export const complex: ValueType = {
213
+ test: (v) => isNaN(v) && typeof v === 'string' && (v.match(floatRegex)?.length || 0) + (v.match(colorRegex)?.length || 0) > 0,
214
+ parse: (v) => analyseComplexValue(v).values,
215
+ createTransformer,
216
+ getAnimatableNone: (v) => createTransformer(v)(analyseComplexValue(v).values.map(convertNumbersToZero)),
217
+ };
218
+
219
+ const maxDefaults = new Set(['brightness', 'contrast', 'saturate', 'opacity']);
220
+ function applyDefaultFilter(v: string): string {
221
+ const [name, value] = v.slice(0, -1).split('(');
222
+ if (name === 'drop-shadow') return v;
223
+ const [num] = value.match(floatRegex) || [];
224
+ if (!num) return v;
225
+ const unit = value.replace(num, '');
226
+ let dflt = maxDefaults.has(name) ? 1 : 0;
227
+ if (num !== value) dflt *= 100;
228
+ return name + '(' + dflt + unit + ')';
229
+ }
230
+ const functionRegex = /\b([a-z-]*)\(.*?\)/gu;
231
+
232
+ export const filter: ValueType = {
233
+ ...complex,
234
+ getAnimatableNone: (v: string) => {
235
+ const fns = v.match(functionRegex);
236
+ return fns ? fns.map(applyDefaultFilter).join(' ') : v;
237
+ },
238
+ };
239
+
240
+ export const transformValueTypes: Record<string, ValueType> = {
241
+ rotate: degrees,
242
+ rotateX: degrees,
243
+ rotateY: degrees,
244
+ rotateZ: degrees,
245
+ scale,
246
+ scaleX: scale,
247
+ scaleY: scale,
248
+ scaleZ: scale,
249
+ skew: degrees,
250
+ skewX: degrees,
251
+ skewY: degrees,
252
+ distance: px,
253
+ translateX: px,
254
+ translateY: px,
255
+ translateZ: px,
256
+ x: px,
257
+ y: px,
258
+ z: px,
259
+ perspective: px,
260
+ transformPerspective: px,
261
+ opacity: alpha,
262
+ originX: progressPercentage,
263
+ originY: progressPercentage,
264
+ originZ: px,
265
+ };
266
+
267
+ export const numberValueTypes: Record<string, ValueType> = {
268
+ borderWidth: px,
269
+ borderTopWidth: px,
270
+ borderRightWidth: px,
271
+ borderBottomWidth: px,
272
+ borderLeftWidth: px,
273
+ borderRadius: px,
274
+ radius: px,
275
+ borderTopLeftRadius: px,
276
+ borderTopRightRadius: px,
277
+ borderBottomRightRadius: px,
278
+ borderBottomLeftRadius: px,
279
+ width: px,
280
+ maxWidth: px,
281
+ height: px,
282
+ maxHeight: px,
283
+ top: px,
284
+ right: px,
285
+ bottom: px,
286
+ left: px,
287
+ padding: px,
288
+ paddingTop: px,
289
+ paddingRight: px,
290
+ paddingBottom: px,
291
+ paddingLeft: px,
292
+ margin: px,
293
+ marginTop: px,
294
+ marginRight: px,
295
+ marginBottom: px,
296
+ marginLeft: px,
297
+ backgroundPositionX: px,
298
+ backgroundPositionY: px,
299
+ ...transformValueTypes,
300
+ zIndex: int,
301
+ fillOpacity: alpha,
302
+ strokeOpacity: alpha,
303
+ numOctaves: int,
304
+ };
305
+
306
+ export const defaultValueTypes: Record<string, ValueType> = {
307
+ ...numberValueTypes,
308
+ color,
309
+ backgroundColor: color,
310
+ outlineColor: color,
311
+ fill: color,
312
+ stroke: color,
313
+ borderColor: color,
314
+ borderTopColor: color,
315
+ borderRightColor: color,
316
+ borderBottomColor: color,
317
+ borderLeftColor: color,
318
+ filter,
319
+ WebkitFilter: filter,
320
+ };
321
+
322
+ export const getDefaultValueType = (key: string): ValueType | undefined => defaultValueTypes[key];
323
+
324
+ const testValueType = (v: any) => (type: ValueType) => type.test(v);
325
+ export const dimensionValueTypes: ValueType[] = [number, px, percent, degrees, vw, vh, auto];
326
+ export const findDimensionValueType = (v: any): ValueType | undefined => dimensionValueTypes.find(testValueType(v));
327
+ const valueTypes: ValueType[] = [...dimensionValueTypes, color, complex];
328
+ export const findValueType = (v: any): ValueType | undefined => valueTypes.find(testValueType(v));
329
+
330
+ /** Returns `value` as the type's CSS string (a number gets its unit). */
331
+ export const getValueAsType = (value: any, type?: ValueType): any => (type && type.transform && typeof value === 'number' ? type.transform(value) : value);
332
+
333
+ /** A zero-ish version of a value ("none" to animate from). */
334
+ export function getAnimatableNone(key: string, value: any): any {
335
+ let t = getDefaultValueType(key);
336
+ if (t !== filter) t = complex;
337
+ return t.getAnimatableNone ? t.getAnimatableNone(value) : undefined;
338
+ }
339
+
340
+ const isCSSVariableToken = (v: unknown): boolean => typeof v === 'string' && v.trim().startsWith('var(--');
341
+
342
+ export type Mixer<T = any> = (p: number) => T;
343
+
344
+ export function mixImmediate<T>(a: T, b: T): Mixer<T> {
345
+ return (p) => (p > 0 ? b : a);
346
+ }
347
+
348
+ const invisibleValues = new Set(['none', 'hidden']);
349
+
350
+ function mixVisibility(origin: string, target: string): Mixer<string> {
351
+ if (invisibleValues.has(origin)) return (p) => (p <= 0 ? origin : target);
352
+ return (p) => (p >= 1 ? target : origin);
353
+ }
354
+
355
+ const mixLinearColor = (from: number, to: number, v: number): number => {
356
+ const fromExpo = from * from;
357
+ const expo = v * (to * to - fromExpo) + fromExpo;
358
+ return expo < 0 ? 0 : Math.sqrt(expo);
359
+ };
360
+
361
+ function asRGBA(c: any): RGBA | false {
362
+ const type = [hex, rgba, hsla].find((t) => t.test(c));
363
+ warnOnce(Boolean(type), `'${c}' is not an animatable color. Use the equivalent color code instead.`);
364
+ if (!type) return false;
365
+ let model = type.parse(c);
366
+ if (type === hsla) model = hslaToRgba(model);
367
+ return model;
368
+ }
369
+
370
+ /** Mixes two colors in linear RGB space. */
371
+ export function mixColor(from: any, to: any): Mixer<string> {
372
+ const a = asRGBA(from);
373
+ const b = asRGBA(to);
374
+ if (!a || !b) return mixImmediate(from, to);
375
+ const blended = { ...a };
376
+ return (v) => {
377
+ blended.red = mixLinearColor(a.red, b.red, v);
378
+ blended.green = mixLinearColor(a.green, b.green, v);
379
+ blended.blue = mixLinearColor(a.blue, b.blue, v);
380
+ blended.alpha = mixNumber(a.alpha, b.alpha, v);
381
+ return rgba.transform!(blended);
382
+ };
383
+ }
384
+
385
+ function numberMixer(a: number, b: number): Mixer<number> {
386
+ return (p) => mixNumber(a, b, p);
387
+ }
388
+
389
+ export function getMixer(a: any): (a: any, b: any) => Mixer {
390
+ if (typeof a === 'number') return numberMixer;
391
+ if (typeof a === 'string') return isCSSVariableToken(a) ? mixImmediate : color.test(a) ? mixColor : mixComplex;
392
+ if (Array.isArray(a)) return mixArray;
393
+ if (typeof a === 'object') return color.test(a) ? mixColor : mixObject;
394
+ return mixImmediate;
395
+ }
396
+
397
+ export function mixArray(a: any[], b: any[]): Mixer<any[]> {
398
+ const out = [...a];
399
+ const n = out.length;
400
+ const blend = a.map((v, i) => getMixer(v)(v, b[i]));
401
+ return (p) => {
402
+ for (let i = 0; i < n; i++) out[i] = blend[i](p);
403
+ return out;
404
+ };
405
+ }
406
+
407
+ export function mixObject(a: Record<string, any>, b: Record<string, any>): Mixer<Record<string, any>> {
408
+ const out = { ...a, ...b };
409
+ const blend: Record<string, Mixer> = {};
410
+ for (const key in out) {
411
+ if (a[key] !== undefined && b[key] !== undefined) blend[key] = getMixer(a[key])(a[key], b[key]);
412
+ }
413
+ return (v) => {
414
+ for (const key in blend) out[key] = blend[key](v);
415
+ return out;
416
+ };
417
+ }
418
+
419
+ function matchOrder(origin: ComplexInfo, target: ComplexInfo): any[] {
420
+ const ordered: any[] = [];
421
+ const pointers: Record<string, number> = { color: 0, var: 0, number: 0 };
422
+ for (let i = 0; i < target.values.length; i++) {
423
+ const type = target.types[i] as 'color' | 'var' | 'number';
424
+ const idx = origin.indexes[type][pointers[type]];
425
+ ordered[i] = origin.values[idx] ?? 0;
426
+ pointers[type]++;
427
+ }
428
+ return ordered;
429
+ }
430
+
431
+ /** Mixes two strings that hold the same sequence of numbers and colors (shadows, gradients, filters). */
432
+ export function mixComplex(origin: string, target: string): Mixer<string> {
433
+ const template = createTransformer(target);
434
+ const o = analyseComplexValue(origin);
435
+ const t = analyseComplexValue(target);
436
+ const ok = o.indexes.var.length === t.indexes.var.length && o.indexes.color.length === t.indexes.color.length && o.indexes.number.length >= t.indexes.number.length;
437
+ if (ok) {
438
+ if ((invisibleValues.has(origin) && !t.values.length) || (invisibleValues.has(target) && !o.values.length)) return mixVisibility(origin, target);
439
+ return pipe(mixArray(matchOrder(o, t), t.values), template);
440
+ }
441
+ warnOnce(false, `Complex values '${origin}' and '${target}' too different to mix. Falling back to instant transition.`);
442
+ return mixImmediate(origin, target);
443
+ }
444
+
445
+ /** `mix(from, to, p)` for numbers, or `mix(from, to)` returning a mixer for any animatable value. */
446
+ export function mix<T>(from: T, to: T): Mixer<T>;
447
+ export function mix(from: number, to: number, p: number): number;
448
+ export function mix(from: any, to: any, p?: number): any {
449
+ if (typeof from === 'number' && typeof to === 'number' && typeof p === 'number') return mixNumber(from, to, p);
450
+ return getMixer(from)(from, to);
451
+ }
452
+
453
+ export interface InterpolateOptions<T> {
454
+ clamp?: boolean;
455
+ ease?: Easing | Easing[];
456
+ mixer?: (from: T, to: T) => Mixer<T>;
457
+ }
458
+
459
+ function createMixers(output: any[], ease?: Easing | Easing[], custom?: (a: any, b: any) => Mixer): Mixer[] {
460
+ const mixers: Mixer[] = [];
461
+ const factory = custom || MotionGlobalConfig.mix || mix;
462
+ for (let i = 0; i < output.length - 1; i++) {
463
+ let m = factory(output[i], output[i + 1]) as Mixer;
464
+ if (ease) {
465
+ const e = Array.isArray(ease) ? ease[i] || noop : ease;
466
+ m = pipe(e, m);
467
+ }
468
+ mixers.push(m);
469
+ }
470
+ return mixers;
471
+ }
472
+
473
+ /** Maps a numeric input range to an output range of numbers, colors or complex strings. */
474
+ export function interpolate<T>(input: number[], output: T[], { clamp: isClamp = true, ease, mixer }: InterpolateOptions<T> = {}): (v: number) => T {
475
+ const n = input.length;
476
+ if (n !== output.length) throw new Error('@krate/motion: both input and output ranges must be the same length');
477
+ if (n === 1) return () => output[0];
478
+ if (n === 2 && output[0] === output[1]) return () => output[1];
479
+ const zeroDelta = input[0] === input[1];
480
+ if (input[0] > input[n - 1]) {
481
+ input = [...input].reverse();
482
+ output = [...output].reverse();
483
+ }
484
+ const mixers = createMixers(output, ease, mixer as any);
485
+ const numMixers = mixers.length;
486
+ const interpolator = (v: number): T => {
487
+ if (zeroDelta && v < input[0]) return output[0];
488
+ let i = 0;
489
+ if (numMixers > 1) {
490
+ for (; i < input.length - 2; i++) if (v < input[i + 1]) break;
491
+ }
492
+ return mixers[i](progress(input[i], input[i + 1], v));
493
+ };
494
+ return isClamp ? (v) => interpolator(clamp(input[0], input[n - 1], v)) : interpolator;
495
+ }
496
+
497
+ /**
498
+ * `transform(value, input, output, options)` maps one value; `transform(input,
499
+ * output, options)` returns the mapping function.
500
+ */
501
+ export function transform<T>(input: number[], output: T[], options?: InterpolateOptions<T>): (v: number) => T;
502
+ export function transform<T>(value: number, input: number[], output: T[], options?: InterpolateOptions<T>): T;
503
+ export function transform(...args: any[]): any {
504
+ const immediate = !Array.isArray(args[0]);
505
+ const off = immediate ? 0 : -1;
506
+ const fn = interpolate(args[1 + off], args[2 + off], args[3 + off]);
507
+ return immediate ? fn(args[0]) : fn;
508
+ }
package/src/hooks.ts ADDED
@@ -0,0 +1,191 @@
1
+ // Motion's hooks for Krate components. A Krate component runs once, so a hook
2
+ // runs once: it creates its motion values and subscriptions and releases them
3
+ // when the component unmounts. Motion values never re-render anything; the
4
+ // elements that use them subscribe directly. Hooks whose React version
5
+ // returns a changing plain value (useInView, useCycle) return a signal getter
6
+ // here; createMotionValue / motionValueSignal / signalMotionValue bridge
7
+ // signals and motion values.
8
+
9
+ import { createEffect, onCleanup, onMount, untrack } from '@krate/runtime';
10
+ import {
11
+ animationControls,
12
+ animationFrame,
13
+ createScopedAnimate,
14
+ createScrollMotionValues,
15
+ motionTemplate,
16
+ motionValue,
17
+ prefersReducedMotion,
18
+ initPrefersReducedMotion,
19
+ hasReducedMotionListener,
20
+ springMotionValue,
21
+ timeMotionValue,
22
+ trackScroll,
23
+ transformMotionValue,
24
+ velocityMotionValue,
25
+ WillChangeMotionValue,
26
+ type AnimateFunction,
27
+ type AnimationScope,
28
+ type InterpolateOptions,
29
+ type LegacyAnimationControls,
30
+ type MotionValue,
31
+ type MotionValueEventCallbacks,
32
+ type ScrollMotionValues,
33
+ type ScrollOffset,
34
+ type SpringOptions,
35
+ } from '@krate/motion/engine';
36
+ import { createDragControls, type DragControls } from '@krate/motion/engine/drag';
37
+
38
+ export type { UseInViewOptions } from '@krate/motion/engine';
39
+
40
+ type RefLike<T = Element> = { current: T | null } | (() => T | null | undefined) | T | null | undefined;
41
+
42
+ function resolveRef<T>(ref: RefLike<T>): T | null | undefined {
43
+ if (ref == null) return ref as null | undefined;
44
+ if (typeof ref === 'function') return (ref as () => T | null | undefined)();
45
+ if (typeof ref === 'object' && 'current' in (ref as object)) return (ref as { current: T | null }).current;
46
+ return ref as T;
47
+ }
48
+
49
+ /** A motion value; read it with .get(), write it with .set(). */
50
+ export function useMotionValue<T>(initial: T): MotionValue<T> {
51
+ return motionValue(initial);
52
+ }
53
+
54
+ /** Krate-style name of useMotionValue. */
55
+ export const createMotionValue: <T>(initial: T) => MotionValue<T> = useMotionValue;
56
+
57
+ export function useTransform<I, O>(value: MotionValue<I>, inputRange: number[], outputRange: O[], options?: InterpolateOptions<O>): MotionValue<O>;
58
+ export function useTransform<I, O>(value: MotionValue<I>, transformer: (v: I) => O): MotionValue<O>;
59
+ export function useTransform<O>(values: MotionValue<any>[], transformer: (v: any[]) => O): MotionValue<O>;
60
+ export function useTransform<O>(compute: () => O): MotionValue<O>;
61
+ /** A motion value mapped from others: by range, by function, or computed from the values it reads. */
62
+ export function useTransform(input: any, rangeOrFn?: any, outputRange?: any[], options?: any): MotionValue<any> {
63
+ const value = transformMotionValue(input, rangeOrFn, outputRange, options);
64
+ onCleanup(() => value.destroy());
65
+ return value;
66
+ }
67
+
68
+ /** A motion value that springs to the values set on it (or that `source` takes). */
69
+ export function useSpring(source: MotionValue<any> | number | string, options?: SpringOptions): MotionValue<any> {
70
+ const value = springMotionValue(source, options);
71
+ onCleanup(() => value.destroy());
72
+ return value;
73
+ }
74
+
75
+ /** A motion value of another one's velocity. */
76
+ export function useVelocity(value: MotionValue<number>): MotionValue<number> {
77
+ const v = velocityMotionValue(value);
78
+ onCleanup(() => v.destroy());
79
+ return v;
80
+ }
81
+
82
+ /** A string motion value from a template of motion values: useMotionTemplate`blur(${blur}px)`. */
83
+ export function useMotionTemplate(fragments: TemplateStringsArray, ...values: Array<MotionValue<any> | string | number>): MotionValue<string> {
84
+ const v = motionTemplate(fragments, ...values);
85
+ onCleanup(() => v.destroy());
86
+ return v;
87
+ }
88
+
89
+ /** Calls `callback` on an event of a motion value ("change", "animationStart", ...) until unmount. */
90
+ export function useMotionValueEvent<V, E extends keyof MotionValueEventCallbacks<V>>(value: MotionValue<V>, event: E, callback: MotionValueEventCallbacks<V>[E]): void {
91
+ onCleanup(value.on(event, callback));
92
+ }
93
+
94
+ /** Time in ms since the component mounted, updated every frame. */
95
+ export function useTime(): MotionValue<number> {
96
+ const [t, stop] = timeMotionValue();
97
+ onCleanup(stop);
98
+ return t;
99
+ }
100
+
101
+ /** Calls `callback(time, delta)` every frame while the component is mounted. */
102
+ export function useAnimationFrame(callback: (time: number, delta: number) => void): void {
103
+ onMount(() => {
104
+ onCleanup(animationFrame(callback));
105
+ });
106
+ }
107
+
108
+ /** Krate-style name of useAnimationFrame. */
109
+ export const createAnimationFrame: (callback: (time: number, delta: number) => void) => void = useAnimationFrame;
110
+
111
+ export interface UseScrollOptions {
112
+ container?: RefLike;
113
+ target?: RefLike;
114
+ offset?: ScrollOffset;
115
+ axis?: 'x' | 'y';
116
+ }
117
+
118
+ /** Scroll position and progress of the page or of `container`, tracking `target` through `offset`. */
119
+ export function useScroll({ container, target, ...options }: UseScrollOptions = {}): ScrollMotionValues {
120
+ const values = createScrollMotionValues();
121
+ onMount(() => {
122
+ onCleanup(trackScroll(values, { ...options, container: (resolveRef(container) as Element) || undefined, target: (resolveRef(target) as Element) || undefined }));
123
+ });
124
+ return values;
125
+ }
126
+
127
+ /** `useAnimate()`: a scope ref and `animate` limited to it (selectors match inside the scope). */
128
+ export function useAnimate<T extends Element = any>(): [AnimationScope<T>, AnimateFunction] {
129
+ const scope = { current: null as unknown as T, animations: [] as any[] };
130
+ const animate = createScopedAnimate(scope);
131
+ onCleanup(() => {
132
+ for (const a of scope.animations) a.stop();
133
+ scope.animations.length = 0;
134
+ });
135
+ return [scope, animate];
136
+ }
137
+
138
+ /** Controls for the `animate` prop of one or more elements: controls.start(...). */
139
+ export function useAnimationControls(): LegacyAnimationControls {
140
+ const controls = animationControls();
141
+ onMount(() => {
142
+ onCleanup(controls.mount());
143
+ });
144
+ return controls;
145
+ }
146
+
147
+ export const useAnimation: () => LegacyAnimationControls = useAnimationControls;
148
+
149
+ /** Controls that start a drag of the elements they are passed to, from any pointerdown. */
150
+ export function useDragControls(): DragControls {
151
+ return createDragControls();
152
+ }
153
+
154
+ /** Whether the device asks for reduced motion (null on the server). */
155
+ export function useReducedMotion(): boolean | null {
156
+ if (!hasReducedMotionListener.current) initPrefersReducedMotion();
157
+ return prefersReducedMotion.current;
158
+ }
159
+
160
+ /** A will-change motion value for `style={{ willChange }}`: "transform" once a transform animates. */
161
+ export function useWillChange(): WillChangeMotionValue {
162
+ return new WillChangeMotionValue('auto');
163
+ }
164
+
165
+ /**
166
+ * Whether the component is present. In a Krate page an exit is driven by the
167
+ * motion elements themselves, so this is always true; see the docs.
168
+ */
169
+ export function useIsPresent(): boolean {
170
+ return true;
171
+ }
172
+
173
+ /** `[isPresent, safeToRemove]`; see useIsPresent. */
174
+ export function usePresence(): [boolean, () => void] {
175
+ return [true, () => {}];
176
+ }
177
+
178
+ /** A motion value that follows a signal getter (or any expression reading signals). */
179
+ export function signalMotionValue<V>(read: () => V): MotionValue<V> {
180
+ const value = motionValue(untrack(read));
181
+ const dispose = createEffect(() => {
182
+ const v = read();
183
+ untrack(() => value.set(v));
184
+ });
185
+ onCleanup(() => {
186
+ dispose();
187
+ value.destroy();
188
+ });
189
+ return value;
190
+ }
191
+