@oiij/use
Version:
Som Composable Functions for Vue 3
70 lines (68 loc) • 2.27 kB
JavaScript
const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
const __vueuse_core = require_rolldown_runtime.__toESM(require("@vueuse/core"));
const vue = require_rolldown_runtime.__toESM(require("vue"));
//#region src/composables/use-number-animation.ts
const easingFns = {
linear: (t) => t,
easeIn: (t) => t * t,
easeOut: (t) => 1 - (1 - t) ** 2,
easeInOut: (t) => t < .5 ? 2 * t * t : 1 - (-2 * t + 2) ** 2 / 2
};
function useNumberAnimation(to, options) {
const { from = 0, manual = false, duration = 1 * 1e3, precision = 2, easing = "linear" } = options ?? {};
const easingFn = typeof easing === "function" ? easing : easingFns[easing] || easingFns.linear;
const currentValue = (0, vue.ref)(from);
const targetValue = (0, vue.ref)((0, vue.toValue)(to));
(0, vue.watchEffect)(() => {
if (targetValue.value !== (0, vue.toValue)(to)) {
targetValue.value = (0, vue.toValue)(to);
start();
}
});
const startTime = (0, vue.ref)(0);
const isFirst = (0, vue.ref)(true);
const onStartHook = (0, __vueuse_core.createEventHook)();
const onEndHook = (0, __vueuse_core.createEventHook)();
const onProgressHook = (0, __vueuse_core.createEventHook)();
const { pause, resume, isActive } = (0, __vueuse_core.useRafFn)(() => {
const elapsed = performance.now() - startTime.value;
if (isFirst.value) {
isFirst.value = false;
onStartHook.trigger();
}
const progress = Math.min(elapsed / duration, 1);
const easedProgress = easingFn(progress);
currentValue.value = from + (targetValue.value - from) * easedProgress;
if (progress >= 1) {
currentValue.value = targetValue.value;
pause();
onEndHook.trigger();
return;
}
onProgressHook.trigger(currentValue.value);
}, { immediate: false });
function start() {
startTime.value = performance.now();
isFirst.value = true;
resume();
}
function stop() {
pause();
onEndHook.trigger();
currentValue.value = targetValue.value;
}
if (!manual) start();
return {
value: (0, vue.readonly)((0, vue.computed)(() => currentValue.value.toFixed(precision))),
isActive,
start,
stop,
pause,
resume,
onStart: onStartHook.on,
onEnd: onEndHook.on,
onProgress: onProgressHook.on
};
}
//#endregion
exports.useNumberAnimation = useNumberAnimation;