useFrame.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. import raf from '../../_util/raf';
  2. import { onBeforeUnmount, ref, shallowRef } from 'vue';
  3. export function useLayoutState(defaultState) {
  4. const stateRef = shallowRef(defaultState);
  5. let rafId;
  6. const updateBatchRef = shallowRef([]);
  7. function setFrameState(updater) {
  8. updateBatchRef.value.push(updater);
  9. raf.cancel(rafId);
  10. rafId = raf(() => {
  11. const prevBatch = updateBatchRef.value;
  12. // const prevState = stateRef.value;
  13. updateBatchRef.value = [];
  14. prevBatch.forEach(batchUpdater => {
  15. stateRef.value = batchUpdater(stateRef.value);
  16. });
  17. });
  18. }
  19. onBeforeUnmount(() => {
  20. raf.cancel(rafId);
  21. });
  22. return [stateRef, setFrameState];
  23. }
  24. /** Lock frame, when frame pass reset the lock. */
  25. export function useTimeoutLock(defaultState) {
  26. const frameRef = ref(defaultState || null);
  27. const timeoutRef = ref();
  28. function cleanUp() {
  29. clearTimeout(timeoutRef.value);
  30. }
  31. function setState(newState) {
  32. frameRef.value = newState;
  33. cleanUp();
  34. timeoutRef.value = setTimeout(() => {
  35. frameRef.value = null;
  36. timeoutRef.value = undefined;
  37. }, 100);
  38. }
  39. function getState() {
  40. return frameRef.value;
  41. }
  42. onBeforeUnmount(() => {
  43. cleanUp();
  44. });
  45. return [setState, getState];
  46. }