aboutsummaryrefslogtreecommitdiff
blob: 6b0473a19d480fa186f6c7895b8e9c8d80cbf052 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import { useEffect, useRef } from 'react';

import { Trip } from 'models';
import { secondsToTimeString } from 'lib/util';

import styles from './Sidebar.module.css';

interface Props {
  trips: Trip[];
  currentTrip: Trip;
  asideOpen: boolean;
  handleClose: () => void;
  setCurrentTrip: (trip: Trip) => void;
}

export default function Sidebar({
  trips,
  currentTrip,
  asideOpen,
  handleClose,
  setCurrentTrip,
}: Props): JSX.Element {
  const wrapperRef = useRef(null);

  useEffect(() => {
    function handleClickOutside(e: MouseEvent) {
      if (wrapperRef.current && !wrapperRef.current.contains(e.target)) {
        handleClose();
      }
    }

    document.addEventListener('mousedown', handleClickOutside);
    return () => {
      document.removeEventListener('mousedown', handleClickOutside);
    };
  }, [wrapperRef]);

  function handleTripChange(trip: Trip): void {
    setCurrentTrip(trip);
    handleClose();
  }

  return (
    <aside ref={wrapperRef} className={`${styles.aside} ${asideOpen && styles.asideOpen}`}>
      <h2>Trips</h2>
      <ul className={styles.list}>
        {trips.map((t) => (
          <li key={t.name}>
            <a
              onClick={() => handleTripChange(t)}
              onKeyPress={() => handleTripChange(t)}
              tabIndex={0}
              role="menuitem"
              className={`${styles.listItem} ${
                t.name === currentTrip.name && styles.listItemActive
              }`}
            >
              <b>{new Date(t.start).toDateString()}</b>
              <br />
              Total distance: {t.distance} km
              <br />
              Duration: {secondsToTimeString(t.duration)}
              <br />
              Average speed: {t.speed} km/h
            </a>
          </li>
        ))}
      </ul>
    </aside>
  );
}