import { shallowRef, onBeforeUnmount } from 'vue';
import wrapperRaf from '../../../_util/raf.mjs';

function useRaf(callback) {
  const rafRef = shallowRef();
  const removedRef = shallowRef(false);
  function trigger(...args) {
    if (!removedRef.value) {
      wrapperRaf.cancel(rafRef.value);
      rafRef.value = wrapperRaf(() => {
        callback(...args);
      });
    }
  }
  onBeforeUnmount(() => {
    removedRef.value = true;
    wrapperRaf.cancel(rafRef.value);
  });
  return trigger;
}
function useRafState(defaultState) {
  const batchRef = shallowRef([]);
  const state = shallowRef(
    typeof defaultState === "function" ? defaultState() : defaultState
  );
  const flushUpdate = useRaf(() => {
    let value = state.value;
    batchRef.value.forEach((callback) => {
      value = callback(value);
    });
    batchRef.value = [];
    state.value = value;
  });
  function updater(callback) {
    batchRef.value.push(callback);
    flushUpdate();
  }
  return [state, updater];
}

export { useRaf as default, useRafState };
//# sourceMappingURL=useRaf.mjs.map
