aboutsummaryrefslogtreecommitdiff
path: root/src/components/AvatarCrop/AvatarCrop.tsx
blob: ef6d9c82b9aee68445ba15f7fea923044d9a3fed (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
import React, {useCallback, useContext, useState} from 'react';
import Cropper from 'react-easy-crop';
import {makeStyles} from '@material-ui/core/styles';
import SendIcon from "@material-ui/icons/Send";
import ModalScreen from "../ModalScreen/ModalScreen";
import { getCroppedImg } from './canvasUtils'

interface PropTypes {
  avatarToCrop: string;
  setAvatarToCrop: (src: string) => void;
  callback: (file: File) => void;
}

const useStyles = makeStyles(theme => ({
  cropContainer: {
    position: 'relative',
    width: '100%',
    height: '100vh',
    background: '#333',
    [theme.breakpoints.up('sm')]: {
      height: 400,
    },
  }
}));

const AvatarCrop: React.FC<PropTypes> = ({ avatarToCrop, setAvatarToCrop, callback }) => {
  const classes = useStyles();
  const [crop, setCrop] = useState({x: 0, y: 0});
  const [zoom, setZoom] = useState(1);
  const [croppedAreaPixels, setCroppedAreaPixels] = useState(null);

  const onCropComplete = useCallback((croppedArea, croppedAreaPixels) => {
    setCroppedAreaPixels(croppedAreaPixels)
  }, []);

  const handleLoadCroppedImage = useCallback(async () => {
    try {
      const croppedImage = await getCroppedImg(avatarToCrop, croppedAreaPixels);
      callback(croppedImage);
    } catch (e) {
      console.error(e)
    }
  }, [avatarToCrop, croppedAreaPixels]);

  const handleCloseModal = useCallback( () => {
    setAvatarToCrop('');
  },[]);

  return (
    <ModalScreen
      title="Choose area"
      actionIcon={<SendIcon />}
      handleAction={handleLoadCroppedImage}
      isActionDisabled={false}
      handleCloseModal={handleCloseModal}
    >
      <div className={classes.cropContainer}>
        <Cropper
          image={avatarToCrop}
          crop={crop}
          zoom={zoom}
          aspect={1}
          cropShape="round"
          showGrid={false}
          onCropChange={setCrop}
          onCropComplete={onCropComplete}
          onZoomChange={setZoom}
        />
      </div>
    </ModalScreen>
  )
};

export default AvatarCrop;