mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 01:44:13 +00:00
34 lines
1.2 KiB
TypeScript
34 lines
1.2 KiB
TypeScript
export interface MotionSample {
|
|
position: number;
|
|
time: number;
|
|
}
|
|
|
|
const VELOCITY_WINDOW_MS = 80;
|
|
|
|
export function isMotionReduced(): boolean {
|
|
return (
|
|
document.documentElement.hasAttribute('data-reduce-motion') ||
|
|
(window.matchMedia?.('(prefers-reduced-motion: reduce)').matches ?? false)
|
|
);
|
|
}
|
|
|
|
export function sampleMotion(samples: MotionSample[], position: number, time: number): void {
|
|
samples.push({ position, time });
|
|
while (samples.length > 2 && time - samples[0].time > VELOCITY_WINDOW_MS) samples.shift();
|
|
}
|
|
|
|
export function releaseVelocity(samples: MotionSample[], position: number, time: number): number {
|
|
sampleMotion(samples, position, time);
|
|
const first = samples[0];
|
|
const duration = time - first.time;
|
|
return duration > 0 && duration <= VELOCITY_WINDOW_MS ? (position - first.position) / duration : 0;
|
|
}
|
|
|
|
export function currentTranslation(element: HTMLElement | null, axis: 'x' | 'y'): number {
|
|
if (!element || typeof DOMMatrixReadOnly === 'undefined') return 0;
|
|
const transform = getComputedStyle(element).transform;
|
|
if (transform === 'none' || !transform) return 0;
|
|
const matrix = new DOMMatrixReadOnly(transform);
|
|
return axis === 'x' ? matrix.m41 : matrix.m42;
|
|
}
|