SummaryMap.jsx 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import { useEffect, useRef, useState } from 'react';
  2. import flagLookup from '../../../../domain/flagLookup';
  3. import useMap from '../../../../hooks/useMap';
  4. import useMarkersFromGuesses from '../../../../hooks/useMarkersFromGuesses';
  5. import styles from './SummaryMap.module.css';
  6. const RoundSelect = ({ rounds, coords, selected, onSelect }) => (
  7. <div className={styles.tabs}>
  8. {// fun fact: es6 doesn't have a range(x) function
  9. Array.from(Array(rounds).keys()).map((r) => (r + 1).toString()).map((r) => (
  10. <div
  11. className={`${styles.tab} ${r === selected ? styles['tab--active'] : ''}`}
  12. key={r}
  13. onClick={() => onSelect(r)}
  14. >
  15. { r } - { flagLookup(coords[r].country) }
  16. </div>
  17. ))}
  18. <div className={styles.tab} onClick={() => onSelect('0')}>
  19. X
  20. </div>
  21. </div>
  22. );
  23. const SummaryMap = ({ players, coords }) => {
  24. const rounds = Object.keys(coords).length;
  25. const singleRound = rounds === 1;
  26. // create the map
  27. const mapDivRef = useRef(null);
  28. const mapRef = useMap(mapDivRef, 0, 0, 1);
  29. // set up round number selection
  30. const [ roundNum, setRoundNum ] = useState('0');
  31. const roundActive = singleRound ? '1' : roundNum;
  32. // get the target point
  33. const targetPoint = coords?.[roundActive] ?? null;
  34. // put the markers on the map
  35. useMarkersFromGuesses(mapRef, players, roundActive, targetPoint);
  36. // scroll the map to the target point
  37. useEffect(
  38. () => {
  39. mapRef.current && mapRef.current.panTo(targetPoint ?? { lat: 0, lng: 0 });
  40. },
  41. [ mapRef, targetPoint ]
  42. );
  43. return (
  44. <div className={styles.container}>
  45. <div className={styles.map} ref={mapDivRef} />
  46. {singleRound || <RoundSelect rounds={rounds} coords={coords} selected={roundNum} onSelect={setRoundNum} />}
  47. </div>
  48. );
  49. };
  50. export default SummaryMap;