|
| 1 | +import React, { useEffect, useState } from 'react'; |
| 2 | +import Paper from '@mui/material/Paper'; |
| 3 | +import Box from '@mui/material/Box'; |
| 4 | +import { SxProps, Theme } from '@mui/material/styles'; |
| 5 | + |
| 6 | +interface DotsProps { |
| 7 | + count: number; |
| 8 | + index: number; |
| 9 | + sx?: SxProps<Theme>; |
| 10 | + onDotClick?: ( |
| 11 | + index: number, |
| 12 | + event: React.MouseEvent<HTMLDivElement, MouseEvent>, |
| 13 | + ) => void; |
| 14 | +} |
| 15 | + |
| 16 | +export const Dots: React.FC<DotsProps> = ({ count, index, sx, onDotClick }) => { |
| 17 | + const [previousIndex, setPreviousIndex] = useState<number>(index); |
| 18 | + |
| 19 | + useEffect(() => { |
| 20 | + if (index !== previousIndex) { |
| 21 | + const timeout = setTimeout(() => { |
| 22 | + setPreviousIndex(index); |
| 23 | + }, 400); |
| 24 | + return () => clearTimeout(timeout); |
| 25 | + } |
| 26 | + }, [index, previousIndex]); |
| 27 | + |
| 28 | + const handleDotClick = ( |
| 29 | + dotIndex: number, |
| 30 | + event: React.MouseEvent<HTMLDivElement, MouseEvent>, |
| 31 | + ) => { |
| 32 | + if (onDotClick) { |
| 33 | + onDotClick(dotIndex, event); |
| 34 | + } |
| 35 | + }; |
| 36 | + |
| 37 | + return ( |
| 38 | + <Box sx={{ width: count * 16, ...sx }}> |
| 39 | + <Box sx={{ position: 'relative', padding: '20px 0 28px' }}> |
| 40 | + {[...Array(count).keys()].map((i) => ( |
| 41 | + <Box |
| 42 | + key={i} |
| 43 | + sx={{ |
| 44 | + width: 8, |
| 45 | + height: 8, |
| 46 | + padding: 0.5, |
| 47 | + position: 'absolute', |
| 48 | + left: i * 16, |
| 49 | + cursor: onDotClick ? 'pointer' : 'inherit', |
| 50 | + }} |
| 51 | + onClick={(event) => handleDotClick(i, event)} |
| 52 | + > |
| 53 | + <Paper |
| 54 | + elevation={0} |
| 55 | + sx={{ |
| 56 | + width: 8, |
| 57 | + height: 8, |
| 58 | + background: '#fff', |
| 59 | + borderRadius: 4, |
| 60 | + transition: 'all 400ms cubic-bezier(0.4, 0.0, 0.2, 1)', |
| 61 | + opacity: |
| 62 | + i >= Math.min(previousIndex, index) && |
| 63 | + i <= Math.max(previousIndex, index) |
| 64 | + ? 0 |
| 65 | + : 0.5, |
| 66 | + }} |
| 67 | + /> |
| 68 | + </Box> |
| 69 | + ))} |
| 70 | + <Paper |
| 71 | + elevation={0} |
| 72 | + sx={{ |
| 73 | + position: 'absolute', |
| 74 | + marginTop: 0.5, |
| 75 | + left: Math.min(previousIndex, index) * 16 + 4, |
| 76 | + width: Math.abs(previousIndex - index) * 16 + 8, |
| 77 | + height: 8, |
| 78 | + background: '#fff', |
| 79 | + borderRadius: 4, |
| 80 | + transition: 'all 400ms cubic-bezier(0.4, 0.0, 0.2, 1)', |
| 81 | + }} |
| 82 | + /> |
| 83 | + </Box> |
| 84 | + </Box> |
| 85 | + ); |
| 86 | +}; |
0 commit comments