UNPKG

web-ui-pack

Version:
39 lines (38 loc) 1.18 kB
import { mathScaleValue } from "./math"; export default function animate(from, to, ms, callback, force) { let isFinished = ms < 10 || (!force && !isAnimEnabled()); let frameId; let resMe; const p = new Promise((res) => { resMe = res; let start = 0; const step = (t) => { if (start === 0) { start = t; } const elapsed = Math.min(t - start, ms); const isLast = isFinished || elapsed === ms; const v = isLast ? to : mathScaleValue(elapsed, 0, ms, from, to); if (!isLast) { frameId = window.requestAnimationFrame(step); } callback(v, elapsed, isLast, t); isLast && res(true); }; frameId = window.requestAnimationFrame(step); }); p.stop = (isFinish = true) => { if (!isFinish) { frameId && window.cancelAnimationFrame(frameId); resMe(false); } else { isFinished = true; } return p; }; return p; } export function isAnimEnabled() { return !window.matchMedia("(prefers-reduced-motion)").matches; }