usePercent.js 947 B

1234567891011121314151617181920212223242526272829
  1. import * as React from 'react';
  2. const AUTO_INTERVAL = 200;
  3. const STEP_BUCKETS = [[30, 0.05], [70, 0.03], [96, 0.01]];
  4. export default function usePercent(spinning, percent) {
  5. const [mockPercent, setMockPercent] = React.useState(0);
  6. const mockIntervalRef = React.useRef(null);
  7. const isAuto = percent === 'auto';
  8. React.useEffect(() => {
  9. if (isAuto && spinning) {
  10. setMockPercent(0);
  11. mockIntervalRef.current = setInterval(() => {
  12. setMockPercent(prev => {
  13. const restPTG = 100 - prev;
  14. for (let i = 0; i < STEP_BUCKETS.length; i += 1) {
  15. const [limit, stepPtg] = STEP_BUCKETS[i];
  16. if (prev <= limit) {
  17. return prev + restPTG * stepPtg;
  18. }
  19. }
  20. return prev;
  21. });
  22. }, AUTO_INTERVAL);
  23. }
  24. return () => {
  25. clearInterval(mockIntervalRef.current);
  26. };
  27. }, [isAuto, spinning]);
  28. return isAuto ? mockPercent : percent;
  29. }