/* * Copyright (c) Facebook, Inc. and its affiliates. */ import {useRef, useCallback, useEffect, createRef} from 'react'; import cn from 'classnames'; import {IconChevron} from 'components/Icon/IconChevron'; import {ChallengeContents} from './Challenges'; import {debounce} from 'debounce'; export function Navigation({ challenges, handleChange, currentChallenge, isRecipes, }: { challenges: ChallengeContents[]; handleChange: (index: number) => void; currentChallenge: ChallengeContents; isRecipes?: boolean; }) { const containerRef = useRef(null); const challengesNavRef = useRef( challenges.map(() => createRef()) ); const scrollPos = currentChallenge.order - 1; const canScrollLeft = scrollPos > 0; const canScrollRight = scrollPos < challenges.length - 1; const handleScrollRight = () => { if (scrollPos < challenges.length - 1) { const currentNavRef = challengesNavRef.current[scrollPos + 1].current; if (!currentNavRef) { return; } if (containerRef.current) { containerRef.current.scrollLeft = currentNavRef.offsetLeft; } handleChange(scrollPos + 1); } }; const handleScrollLeft = () => { if (scrollPos > 0) { const currentNavRef = challengesNavRef.current[scrollPos - 1].current; if (!currentNavRef) { return; } if (containerRef.current) { containerRef.current.scrollLeft = currentNavRef.offsetLeft; } handleChange(scrollPos - 1); } }; const handleSelectNav = (index: number) => { const currentNavRef = challengesNavRef.current[index].current; if (containerRef.current) { containerRef.current.scrollLeft = currentNavRef?.offsetLeft || 0; } handleChange(index); }; const handleResize = useCallback(() => { if (containerRef.current) { const el = containerRef.current; el.scrollLeft = challengesNavRef.current[scrollPos].current?.offsetLeft || 0; } }, [containerRef, challengesNavRef, scrollPos]); useEffect(() => { handleResize(); const debouncedHandleResize = debounce(handleResize, 200); window.addEventListener('resize', debouncedHandleResize); return () => { window.removeEventListener('resize', debouncedHandleResize); }; }, [handleResize]); return (
{challenges.map(({name, id, order}, index) => ( ))}
); }