import React, { useEffect, useRef, useReducer, useCallback } from 'react'; import ChevronRightIcon from '@moda/icons/chevron-right-16'; import ChevronLeftIcon from '@moda/icons/chevron-left-16'; import './Size.scss'; import { Inventory } from '../types/VariantTypes'; const numberOfCellsViewableAtATime = 2; const sizes = (props: Partial): Array => props.sizesArr.map((sizeObj: Inventory) => ( )); interface Props { sizesArr: Inventory[]; selectedSize?: Inventory | null; initialSize?: Inventory | null; onSetSize(size: Inventory): void; expand?: boolean; } interface State { currentCell: number; maxCells: number; } type Action = | { type: 'SetCurrentCell'; payload: number } | { type: 'SetMaxCells'; payload: number }; const reducer = (state: State, action: Action): State => { switch (action.type) { case 'SetCurrentCell': return { ...state, currentCell: action.payload, }; case 'SetMaxCells': return { ...state, maxCells: action.payload }; } }; const initialState: State = { currentCell: 0, maxCells: 0, }; export const Size: React.FC = ({ sizesArr = [], selectedSize = null, onSetSize, }) => { const tracksRef = useRef(null); const [state, dispatch] = useReducer(reducer, initialState); const setTrack = useCallback((cell: number) => { dispatch({ type: 'SetCurrentCell', payload: cell, }); }, []); const handlePrev = useCallback(() => { state.currentCell >= numberOfCellsViewableAtATime ? setTrack(state.currentCell - numberOfCellsViewableAtATime) : setTrack(0); }, [setTrack, state.currentCell]); const handleNext = useCallback(() => { state.maxCells - (state.currentCell + numberOfCellsViewableAtATime - 1) > numberOfCellsViewableAtATime ? setTrack(state.currentCell + numberOfCellsViewableAtATime) : setTrack(state.maxCells - numberOfCellsViewableAtATime); }, [setTrack, state.currentCell, state.maxCells]); useEffect(() => { if (tracksRef.current) { dispatch({ type: 'SetMaxCells', payload: tracksRef.current.childNodes.length, }); } }, [tracksRef]); return (
{state.maxCells > 0 && ( )}
{sizes({ sizesArr, selectedSize, onSetSize, }).map((size: JSX.Element, index: number) => (
{size}
))}
{state.maxCells > 0 && ( )}
); };