aboutsummaryrefslogtreecommitdiff
path: root/src/hooks/useS3Preupload.tsx
blob: 22f251345524dc84c2f941c9f50d4c2faffb67a9 (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
81
82
83
84
85
86
import { useState, useCallback, useMemo } from 'react';
import axios from 'axios';
import Bluebird from 'bluebird';
import Compressor from 'compressorjs';
import { get } from '../requests';


interface ProgressEvent {
  loaded: number;
  total: number;
}

interface Hook {
  setValue: (value: File | string | undefined) => void;
  isReady: boolean;
  resolve: () => Promise<string>;
  progress: number;
}


const compressFile = (file: File, quality = 0.6): Promise<Blob> => {
  return new Promise((resolve, reject) => {
    // eslint-disable-next-line no-new
    new Compressor(file, {
      success: result => resolve(result),
      error: err => reject(err),
      quality,
    });
  });
};

export default (): Hook => {
  const [url, setUrl] = useState<string>();
  const [file, setFile] = useState<File>();
  const [progress, setProgress] = useState<number>(0);

  const isReady = useMemo(() => Boolean(file || url), [file, url]);

  const setValue: Hook['setValue'] = useCallback(value => {
    if (value instanceof File) {
      setFile(value);
      setUrl(undefined);
    } else {
      setUrl(value);
      setFile(undefined);
    }
  }, [setUrl, setFile]);

  const handleUploadProgress = useCallback((progressEvent: ProgressEvent): void => {
    // Only allow upload progress reach 95%, and set 100% when request is resolved
    setProgress(Math.round((progressEvent.loaded * 95) / progressEvent.total));
  }, [setProgress]);

  const resolve = useCallback(async (quality?: number): Promise<string> => {
    if (file) {
      const config = {
        headers: { 'Content-Type': 'image/png' },
        onUploadProgress: handleUploadProgress
      };

      setProgress(0.01);

      // Add querystring to avoid caching request in some browsers, see
      // https://stackoverflow.com/questions/59339561/safari-skipping-xmlhttprequests
      return Bluebird.all([get(`/files?key=${file.name}`), compressFile(file, quality)])
        .then(([response, compressedFile]) => {
          const uploadUrl = response.data;
          return axios.put(uploadUrl, compressedFile, config);
        })
        .then(response => {
          setProgress(100);
          const uri = response.config.url;
          return uri ? uri.slice(0, uri.indexOf('?')) : '';
        });
    }
    setProgress(100);
    return url || '';
  }, [file, handleUploadProgress, url]);

  return {
    setValue,
    isReady,
    resolve,
    progress
  };
};