2021-12-27 15:59:32 +01:00
|
|
|
import { Button, ButtonProps, chakra } from '@chakra-ui/react'
|
2022-01-20 16:14:47 +01:00
|
|
|
import React, { ChangeEvent, useState } from 'react'
|
|
|
|
import { compressFile, uploadFile } from 'services/utils'
|
2021-12-27 15:59:32 +01:00
|
|
|
|
2022-01-20 16:14:47 +01:00
|
|
|
type UploadButtonProps = {
|
|
|
|
filePath: string
|
|
|
|
includeFileName?: boolean
|
|
|
|
onFileUploaded: (url: string) => void
|
|
|
|
} & ButtonProps
|
2021-12-27 15:59:32 +01:00
|
|
|
|
|
|
|
export const UploadButton = ({
|
2022-01-20 16:14:47 +01:00
|
|
|
filePath,
|
|
|
|
includeFileName,
|
|
|
|
onFileUploaded,
|
2021-12-27 15:59:32 +01:00
|
|
|
...props
|
|
|
|
}: UploadButtonProps) => {
|
2022-01-20 16:14:47 +01:00
|
|
|
const [isUploading, setIsUploading] = useState(false)
|
|
|
|
|
|
|
|
const handleInputChange = async (e: ChangeEvent<HTMLInputElement>) => {
|
2021-12-27 15:59:32 +01:00
|
|
|
if (!e.target?.files) return
|
2022-01-20 16:14:47 +01:00
|
|
|
setIsUploading(true)
|
|
|
|
const file = e.target.files[0]
|
|
|
|
const { url } = await uploadFile(
|
|
|
|
await compressFile(file),
|
|
|
|
filePath + (includeFileName ? `/${file.name}` : '')
|
|
|
|
)
|
|
|
|
if (url) onFileUploaded(url)
|
|
|
|
setIsUploading(false)
|
2021-12-27 15:59:32 +01:00
|
|
|
}
|
2022-01-20 16:14:47 +01:00
|
|
|
|
2021-12-27 15:59:32 +01:00
|
|
|
return (
|
|
|
|
<>
|
|
|
|
<chakra.input
|
2022-01-20 16:14:47 +01:00
|
|
|
data-testid="file-upload-input"
|
2021-12-27 15:59:32 +01:00
|
|
|
type="file"
|
|
|
|
id="file-input"
|
|
|
|
display="none"
|
|
|
|
onChange={handleInputChange}
|
|
|
|
accept=".jpg, .jpeg, .png"
|
|
|
|
/>
|
|
|
|
<Button
|
|
|
|
as="label"
|
|
|
|
size="sm"
|
|
|
|
htmlFor="file-input"
|
|
|
|
cursor="pointer"
|
2022-01-20 16:14:47 +01:00
|
|
|
isLoading={isUploading}
|
2021-12-27 15:59:32 +01:00
|
|
|
{...props}
|
|
|
|
>
|
|
|
|
{props.children}
|
|
|
|
</Button>
|
|
|
|
</>
|
|
|
|
)
|
|
|
|
}
|