index.tsx 2.67 KB
import { get, getOr, isEqual, keyBy, sortBy, findIndex } from 'lodash/fp';
import { View } from 'native-base';
import React from 'react';
import { ViewProps } from 'react-native';
import { StackActions, useNavigation } from '@react-navigation/native';
import { TouchableOpacity } from 'react-native-gesture-handler';
import { ABBREV, POSITIONS } from '../../constants/roster-position';
import BenchDivider from '../BenchDivider';
import DefaultPlayerRow from '../DefaultPlayerRow';
import ListGrid from '../ListGrid';
import { TAB } from '../../constants/tab';
import { TabNavigation, StackNavigation } from '../../types/navigation';

interface ComponentProps {
  players: FranchisePlayer[];
  rosterSpots: string[];
  // eslint-disable-next-line react/require-default-props
  showMarketTrend?: boolean;
}

type Props = ComponentProps & ViewProps;

const RosterList: React.FC<Props> = ({
  players,
  rosterSpots,
  showMarketTrend = false,
  ...props
}: Props) => {
  const navigation = useNavigation<TabNavigation | StackNavigation>();
  const benchIndex = rosterSpots.indexOf('BENCH');
  const franchisePlayers = keyBy('rosterSpotIndex', players);
  const sortedPlayersSpots = sortBy('rosterSpotIndex', players);

  const navigateToProfile = (index: number) => {
    navigation.dispatch(
      StackActions.push('PlayerView', {
        players: sortedPlayersSpots,
        selectedIndex: index
      })
    );
  };

  const handleOnPressItem = (index: number) => () => {
    const rosterSpotIndex = get(
      [`${index}`, 'rosterSpotIndex'],
      franchisePlayers
    );
    const playerIndex = findIndex({ rosterSpotIndex }, sortedPlayersSpots);
    if (playerIndex > -1) {
      navigateToProfile(playerIndex);
    } else {
      const position = getOr('', rosterSpots[index], ABBREV);
      navigation.navigate(TAB.Market, {
        position: rosterSpots[index] !== POSITIONS.BENCH ? position : null
      });
    }
  };

  return (
    <ListGrid {...props}>
      {rosterSpots.map(
        (position: string, index: number) => (
          <TouchableOpacity
            // eslint-disable-next-line react/no-array-index-key
            key={`player-${position}-${index}`}
            onPress={handleOnPressItem(index)}
          >
            <View>
              {index === benchIndex && <BenchDivider />}
              <DefaultPlayerRow
                active={!isEqual(rosterSpots[index], POSITIONS.BENCH)}
                position={get(position, ABBREV)}
                player={get(index, franchisePlayers)}
                showMarketTrend={showMarketTrend}
              />
            </View>
          </TouchableOpacity>
        ),
        rosterSpots
      )}
    </ListGrid>
  );
};

export default RosterList;