1 | "use strict";
|
2 |
|
3 | var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
|
4 | Object.defineProperty(exports, "__esModule", {
|
5 | value: true
|
6 | });
|
7 | exports.useLayoutState = useLayoutState;
|
8 | exports.useTimeoutLock = useTimeoutLock;
|
9 | var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
|
10 | var _react = require("react");
|
11 |
|
12 |
|
13 |
|
14 | function useLayoutState(defaultState) {
|
15 | var stateRef = (0, _react.useRef)(defaultState);
|
16 | var _useState = (0, _react.useState)({}),
|
17 | _useState2 = (0, _slicedToArray2.default)(_useState, 2),
|
18 | forceUpdate = _useState2[1];
|
19 | var lastPromiseRef = (0, _react.useRef)(null);
|
20 | var updateBatchRef = (0, _react.useRef)([]);
|
21 | function setFrameState(updater) {
|
22 | updateBatchRef.current.push(updater);
|
23 | var promise = Promise.resolve();
|
24 | lastPromiseRef.current = promise;
|
25 | promise.then(function () {
|
26 | if (lastPromiseRef.current === promise) {
|
27 | var prevBatch = updateBatchRef.current;
|
28 | var prevState = stateRef.current;
|
29 | updateBatchRef.current = [];
|
30 | prevBatch.forEach(function (batchUpdater) {
|
31 | stateRef.current = batchUpdater(stateRef.current);
|
32 | });
|
33 | lastPromiseRef.current = null;
|
34 | if (prevState !== stateRef.current) {
|
35 | forceUpdate({});
|
36 | }
|
37 | }
|
38 | });
|
39 | }
|
40 | (0, _react.useEffect)(function () {
|
41 | return function () {
|
42 | lastPromiseRef.current = null;
|
43 | };
|
44 | }, []);
|
45 | return [stateRef.current, setFrameState];
|
46 | }
|
47 |
|
48 |
|
49 | function useTimeoutLock(defaultState) {
|
50 | var frameRef = (0, _react.useRef)(defaultState || null);
|
51 | var timeoutRef = (0, _react.useRef)();
|
52 | function cleanUp() {
|
53 | window.clearTimeout(timeoutRef.current);
|
54 | }
|
55 | function setState(newState) {
|
56 | frameRef.current = newState;
|
57 | cleanUp();
|
58 | timeoutRef.current = window.setTimeout(function () {
|
59 | frameRef.current = null;
|
60 | timeoutRef.current = undefined;
|
61 | }, 100);
|
62 | }
|
63 | function getState() {
|
64 | return frameRef.current;
|
65 | }
|
66 | (0, _react.useEffect)(function () {
|
67 | return cleanUp;
|
68 | }, []);
|
69 | return [setState, getState];
|
70 | } |
\ | No newline at end of file |