aboutsummaryrefslogtreecommitdiff
blob: dfadbc05d8d6e237e1206db15a9ff1d86fb6d35c (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
72
73
74
75
76
77
78
79
80
import { useEffect, useRef } from 'react';

import { Photo } from 'models';
import useEvent from 'lib/useEvent';
import styles from './Gallery.module.css';

interface Props {
  currentPhoto: Photo;
  handleClose: () => void;
  handlePhotoChange: (direction: boolean) => void;
}

export default function Gallery({
  currentPhoto,
  handleClose,
  handlePhotoChange,
}: Props): JSX.Element {
  const wrapperRef = useRef(null);

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

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

  useEvent('keydown', (e: KeyboardEvent) => {
    if (e.key === 'ArrowLeft') {
      handlePhotoChange(false);
    } else if (e.key === 'ArrowRight') {
      handlePhotoChange(true);
    } else if (e.key === 'Escape') {
      handleClose();
    }
  });

  return (
    <div className={styles.galleryContainer} role="region">
      <button
        type="button"
        className={`${styles.arrowLeft} ${styles.btn}`}
        onClick={() => handlePhotoChange(false)}
      >
        〈
      </button>
      <div className={styles.photoContainer}>
        <img
          ref={wrapperRef}
          src={currentPhoto.src}
          alt={currentPhoto.name}
          className={styles.photo}
        />
      </div>
      <button
        type="button"
        className={`${styles.arrowRight} ${styles.btn}`}
        onClick={() => handlePhotoChange(true)}
      >
        〉
      </button>
      <button
        type="button"
        className={`${styles.closeBtn} ${styles.btn}`}
        onClick={() => handleClose()}
      >
        ×
      </button>
    </div>
  );
}