usePercent.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. "use strict";
  2. var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard").default;
  3. Object.defineProperty(exports, "__esModule", {
  4. value: true
  5. });
  6. exports.default = usePercent;
  7. var React = _interopRequireWildcard(require("react"));
  8. const AUTO_INTERVAL = 200;
  9. const STEP_BUCKETS = [[30, 0.05], [70, 0.03], [96, 0.01]];
  10. function usePercent(spinning, percent) {
  11. const [mockPercent, setMockPercent] = React.useState(0);
  12. const mockIntervalRef = React.useRef(null);
  13. const isAuto = percent === 'auto';
  14. React.useEffect(() => {
  15. if (isAuto && spinning) {
  16. setMockPercent(0);
  17. mockIntervalRef.current = setInterval(() => {
  18. setMockPercent(prev => {
  19. const restPTG = 100 - prev;
  20. for (let i = 0; i < STEP_BUCKETS.length; i += 1) {
  21. const [limit, stepPtg] = STEP_BUCKETS[i];
  22. if (prev <= limit) {
  23. return prev + restPTG * stepPtg;
  24. }
  25. }
  26. return prev;
  27. });
  28. }, AUTO_INTERVAL);
  29. }
  30. return () => {
  31. clearInterval(mockIntervalRef.current);
  32. };
  33. }, [isAuto, spinning]);
  34. return isAuto ? mockPercent : percent;
  35. }