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

99 lines
2.8 KiB
React
Raw Normal View History

import React, { useState, useRef } from 'react';
2021-09-09 01:47:26 -04:00
import PropTypes from 'prop-types';
import './ImageUpload.scss';
2021-09-09 01:47:26 -04:00
import initMatrix from '../../../client/initMatrix';
import Text from '../../atoms/text/Text';
2021-09-12 23:25:58 -04:00
import Avatar from '../../atoms/avatar/Avatar';
import Spinner from '../../atoms/spinner/Spinner';
import RawIcon from '../../atoms/system-icons/RawIcon';
import PlusIC from '../../../../public/res/ic/outlined/plus.svg';
2021-09-09 01:47:26 -04:00
function ImageUpload({
text, bgColor, imageSrc, onUpload, onRequestRemove,
size,
2021-09-09 01:47:26 -04:00
}) {
const [uploadPromise, setUploadPromise] = useState(null);
2021-09-09 01:47:26 -04:00
const uploadImageRef = useRef(null);
async function uploadImage(e) {
2021-09-09 01:47:26 -04:00
const file = e.target.files.item(0);
if (file === null) return;
try {
const uPromise = initMatrix.matrixClient.uploadContent(file);
setUploadPromise(uPromise);
const res = await uPromise;
if (typeof res?.content_uri === 'string') onUpload(res.content_uri);
setUploadPromise(null);
} catch {
setUploadPromise(null);
2021-09-09 01:47:26 -04:00
}
uploadImageRef.current.value = null;
}
function cancelUpload() {
initMatrix.matrixClient.cancelUpload(uploadPromise);
setUploadPromise(null);
uploadImageRef.current.value = null;
2021-09-09 01:47:26 -04:00
}
return (
<div className="img-upload__wrapper">
<button
type="button"
className="img-upload"
onClick={() => {
if (uploadPromise !== null) return;
uploadImageRef.current.click();
}}
>
2021-09-09 01:47:26 -04:00
<Avatar
imageSrc={imageSrc}
text={text}
2021-09-09 01:47:26 -04:00
bgColor={bgColor}
size={size}
2021-09-09 01:47:26 -04:00
/>
<div className={`img-upload__process ${uploadPromise === null ? ' img-upload__process--stopped' : ''}`}>
{uploadPromise === null && (
size === 'large'
? <Text variant="b3" weight="bold">Upload</Text>
: <RawIcon src={PlusIC} color="white" />
)}
{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 01:47:26 -04:00
<input onChange={uploadImage} style={{ display: 'none' }} ref={uploadImageRef} type="file" />
</div>
2021-09-09 01:47:26 -04:00
);
}
ImageUpload.defaultProps = {
text: null,
bgColor: 'transparent',
imageSrc: null,
size: 'large',
2021-09-09 01:47:26 -04:00
};
ImageUpload.propTypes = {
text: PropTypes.string,
bgColor: PropTypes.string,
imageSrc: PropTypes.string,
onUpload: PropTypes.func.isRequired,
onRequestRemove: PropTypes.func.isRequired,
size: PropTypes.oneOf(['large', 'normal']),
2021-09-09 01:47:26 -04:00
};
export default ImageUpload;