cinny/src/app/molecules/image-upload/ImageUpload.jsx

89 lines
2.5 KiB
React
Raw Normal View History

import React, { useState, useRef } from 'react';
2021-09-09 07:47:26 +02:00
import PropTypes from 'prop-types';
import './ImageUpload.scss';
2021-09-09 07:47:26 +02:00
import initMatrix from '../../../client/initMatrix';
import Text from '../../atoms/text/Text';
2021-09-13 05:25:58 +02:00
import Avatar from '../../atoms/avatar/Avatar';
import Spinner from '../../atoms/spinner/Spinner';
2021-09-09 07:47:26 +02:00
function ImageUpload({
text, bgColor, imageSrc, onUpload, onRequestRemove,
2021-09-09 07:47:26 +02:00
}) {
const [uploadPromise, setUploadPromise] = useState(null);
2021-09-09 07:47:26 +02:00
const uploadImageRef = useRef(null);
async function uploadImage(e) {
2021-09-09 07:47:26 +02:00
const file = e.target.files.item(0);
if (file === null) return;
try {
const uPromise = initMatrix.matrixClient.uploadContent(file, { onlyContentUri: false });
setUploadPromise(uPromise);
const res = await uPromise;
if (typeof res?.content_uri === 'string') onUpload(res.content_uri);
setUploadPromise(null);
} catch {
setUploadPromise(null);
2021-09-09 07:47:26 +02:00
}
uploadImageRef.current.value = null;
}
function cancelUpload() {
initMatrix.matrixClient.cancelUpload(uploadPromise);
setUploadPromise(null);
uploadImageRef.current.value = null;
2021-09-09 07:47:26 +02:00
}
return (
<div className="img-upload__wrapper">
<button
type="button"
className="img-upload"
onClick={() => {
if (uploadPromise !== null) return;
uploadImageRef.current.click();
}}
>
2021-09-09 07:47:26 +02:00
<Avatar
imageSrc={imageSrc}
text={text.slice(0, 1)}
bgColor={bgColor}
size="large"
/>
<div className={`img-upload__process ${uploadPromise === null ? ' img-upload__process--stopped' : ''}`}>
{uploadPromise === null && <Text variant="b3">Upload</Text>}
{uploadPromise !== null && <Spinner size="small" />}
</div>
</button>
{ (typeof imageSrc === 'string' || uploadPromise !== null) && (
<button
className="img-upload__btn-cancel"
type="button"
onClick={uploadPromise === null ? onRequestRemove : cancelUpload}
>
<Text variant="b3">{uploadPromise ? 'Cancel' : 'Remove'}</Text>
</button>
)}
2021-09-09 07:47:26 +02:00
<input onChange={uploadImage} style={{ display: 'none' }} ref={uploadImageRef} type="file" />
</div>
2021-09-09 07:47:26 +02:00
);
}
ImageUpload.defaultProps = {
text: null,
bgColor: 'transparent',
imageSrc: null,
};
ImageUpload.propTypes = {
text: PropTypes.string,
bgColor: PropTypes.string,
imageSrc: PropTypes.string,
onUpload: PropTypes.func.isRequired,
onRequestRemove: PropTypes.func.isRequired,
2021-09-09 07:47:26 +02:00
};
export default ImageUpload;