(props)
| 48 | const getInitialState = (numItems: number): CarouselState => ({ pos: numItems - 1, sliding: false, dir: NEXT }); |
| 49 | |
| 50 | const Carousel: FunctionComponent<{children: ReactNode}> = (props) => { |
| 51 | const numItems = React.Children.count(props.children); |
| 52 | const [state, dispatch] = React.useReducer(reducer, getInitialState(numItems)); |
| 53 | |
| 54 | const slide = (dir: Direction) => { |
| 55 | dispatch({ type: dir, numItems }); |
| 56 | setTimeout(() => { |
| 57 | dispatch({ type: 'stopSliding' }); |
| 58 | }, 50); |
| 59 | }; |
| 60 | |
| 61 | const [pIdx, setPIdx] = React.useState(0); |
| 62 | |
| 63 | const handleSwiped = (eventData: SwipeEventData) => { |
| 64 | if (eventData.dir === pattern[pIdx]) { |
| 65 | // user successfully got to the end of the pattern! |
| 66 | if (pIdx + 1 === pattern.length) { |
| 67 | setPIdx(pattern.length); |
| 68 | slide(NEXT); |
| 69 | setTimeout(() => { |
| 70 | setPIdx(0); |
| 71 | }, 50); |
| 72 | } else { |
| 73 | // user is cont. with the pattern |
| 74 | setPIdx((i) => (i += 1)); |
| 75 | } |
| 76 | } else { |
| 77 | // user got the next pattern step wrong, reset pattern |
| 78 | setPIdx(0); |
| 79 | } |
| 80 | }; |
| 81 | |
| 82 | const handlers = useSwipeable({ |
| 83 | onSwiped: handleSwiped, |
| 84 | onTouchStartOrOnMouseDown: (({ event }) => event.preventDefault()), |
| 85 | touchEventOptions: { passive: false }, |
| 86 | preventScrollOnSwipe: true, |
| 87 | trackMouse: true |
| 88 | }); |
| 89 | |
| 90 | return ( |
| 91 | <> |
| 92 | <PatternBox {...handlers}> |
| 93 | Within this text area container, swipe the pattern seen below to make |
| 94 | the carousel navigate to the next slide. |
| 95 | {`\n`} |
| 96 | <p style={{textAlign: 'center', paddingTop: '15px'}}> |
| 97 | Swipe: |
| 98 | <D><UpArrow active={pIdx > 0} /></D> |
| 99 | <D><DownArrow active={pIdx > 1} /></D> |
| 100 | <D><UpArrow active={pIdx > 2} /></D> |
| 101 | <D><DownArrow active={pIdx > 3} /></D> |
| 102 | </p> |
| 103 | </PatternBox> |
| 104 | <div style={{paddingBottom: '15px'}}> |
| 105 | <Wrapper> |
| 106 | <CarouselContainer dir={state.dir} sliding={state.sliding}> |
| 107 | {React.Children.map(props.children, (child, index) => ( |
nothing calls this directly
no test coverage detected
searching dependent graphs…