"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.useLayoutState = useLayoutState;
exports.useTimeoutLock = useTimeoutLock;

var _vue = require("vue");

/**
 * Execute code before next frame but async
 */
function useLayoutState(defaultState) {
  var stateRef = (0, _vue.ref)(defaultState); // const [, forceUpdate] = useState({});

  var lastPromiseRef = (0, _vue.ref)(null);
  var updateBatchRef = (0, _vue.ref)([]);

  function setFrameState(updater) {
    updateBatchRef.value.push(updater);
    var promise = Promise.resolve();
    lastPromiseRef.value = promise;
    promise.then(function () {
      if (lastPromiseRef.value === promise) {
        var prevBatch = updateBatchRef.value; // const prevState = stateRef.value;

        updateBatchRef.value = [];
        prevBatch.forEach(function (batchUpdater) {
          stateRef.value = batchUpdater(stateRef.value);
        });
        lastPromiseRef.value = null;
      }
    });
  }

  (0, _vue.onBeforeUnmount)(function () {
    lastPromiseRef.value = null;
  });
  return [stateRef, setFrameState];
}
/** Lock frame, when frame pass reset the lock. */


function useTimeoutLock(defaultState) {
  var frameRef = (0, _vue.ref)(defaultState || null);
  var timeoutRef = (0, _vue.ref)();

  function cleanUp() {
    window.clearTimeout(timeoutRef.value);
  }

  function setState(newState) {
    frameRef.value = newState;
    cleanUp();
    timeoutRef.value = window.setTimeout(function () {
      frameRef.value = null;
      timeoutRef.value = undefined;
    }, 100);
  }

  function getState() {
    return frameRef.value;
  }

  (0, _vue.onBeforeUnmount)(function () {
    cleanUp();
  });
  return [setState, getState];
}