source: imaps-frontend/node_modules/react-use/lib/useStateList.js

main
Last change on this file was d565449, checked in by stefan toskovski <stefantoska84@…>, 4 weeks ago

Update repo after prototype presentation

  • Property mode set to 100644
File size: 2.6 KB
Line 
1"use strict";
2Object.defineProperty(exports, "__esModule", { value: true });
3var tslib_1 = require("tslib");
4var react_1 = require("react");
5var useMountedState_1 = tslib_1.__importDefault(require("./useMountedState"));
6var useUpdate_1 = tslib_1.__importDefault(require("./useUpdate"));
7var useUpdateEffect_1 = tslib_1.__importDefault(require("./useUpdateEffect"));
8function useStateList(stateSet) {
9 if (stateSet === void 0) { stateSet = []; }
10 var isMounted = useMountedState_1.default();
11 var update = useUpdate_1.default();
12 var index = react_1.useRef(0);
13 // If new state list is shorter that before - switch to the last element
14 useUpdateEffect_1.default(function () {
15 if (stateSet.length <= index.current) {
16 index.current = stateSet.length - 1;
17 update();
18 }
19 }, [stateSet.length]);
20 var actions = react_1.useMemo(function () { return ({
21 next: function () { return actions.setStateAt(index.current + 1); },
22 prev: function () { return actions.setStateAt(index.current - 1); },
23 setStateAt: function (newIndex) {
24 // do nothing on unmounted component
25 if (!isMounted())
26 return;
27 // do nothing on empty states list
28 if (!stateSet.length)
29 return;
30 // in case new index is equal current - do nothing
31 if (newIndex === index.current)
32 return;
33 // it gives the ability to travel through the left and right borders.
34 // 4ex: if list contains 5 elements, attempt to set index 9 will bring use to 5th element
35 // in case of negative index it will start counting from the right, so -17 will bring us to 4th element
36 index.current =
37 newIndex >= 0
38 ? newIndex % stateSet.length
39 : stateSet.length + (newIndex % stateSet.length);
40 update();
41 },
42 setState: function (state) {
43 // do nothing on unmounted component
44 if (!isMounted())
45 return;
46 var newIndex = stateSet.length ? stateSet.indexOf(state) : -1;
47 if (newIndex === -1) {
48 throw new Error("State '" + state + "' is not a valid state (does not exist in state list)");
49 }
50 index.current = newIndex;
51 update();
52 },
53 }); }, [stateSet]);
54 return tslib_1.__assign({ state: stateSet[index.current], currentIndex: index.current, isFirst: index.current === 0, isLast: index.current === stateSet.length - 1 }, actions);
55}
56exports.default = useStateList;
Note: See TracBrowser for help on using the repository browser.