@studiometa/js-toolkit
Version:
A set of useful little bits of JavaScript to boost your project! 🚀
57 lines (56 loc) • 1.67 kB
JavaScript
import { damp } from "./damp.js";
import { spring } from "./spring.js";
import { isFunction, isDefined } from "../is.js";
function smoothTo(start = 0, options = {}) {
const fns = /* @__PURE__ */ new Set();
let damping = options.damping ?? 0.6;
let precision = options.precision ?? 1 / 1e8;
let stiffness = options.stiffness ?? 0.1;
let mass = options.mass ?? 1;
let isSpring = options.spring === true || isDefined(options.stiffness) || isDefined(options.mass);
let value = start;
let smoothed = start;
let velocity = 0;
function tick() {
if (isSpring) {
[smoothed, velocity] = spring(value, smoothed, velocity, stiffness, damping, mass, precision);
} else {
smoothed = damp(value, smoothed, damping, precision);
}
for (const fn of fns) {
fn(smoothed);
}
if (smoothed !== value) requestAnimationFrame(tick);
}
function subscribe(fn) {
if (isFunction(fn)) {
fns.add(fn);
}
return () => unsubscribe(fn);
}
function unsubscribe(fn) {
return fns.delete(fn);
}
function update(newValue) {
if (!isDefined(newValue)) {
return smoothed;
}
value = newValue;
tick();
return smoothed;
}
update.subscribe = subscribe;
update.unsubscribe = unsubscribe;
update.raw = () => value;
update.add = (val) => update(value + val);
update.damping = (val) => damping = val ?? damping;
update.precision = (val) => precision = val ?? precision;
update.stiffness = (val) => stiffness = val ?? stiffness;
update.spring = (val) => isSpring = val ?? isSpring;
update(start);
return update;
}
export {
smoothTo
};
//# sourceMappingURL=smoothTo.js.map