Projekt

Obecné

Profil

Stáhnout (2.49 KB) Statistiky
| Větev: | Tag: | Revize:
1
import {
2
    Button,
3
    DialogContent,
4
    DialogTitle,
5
    Link,
6
    Stack,
7
    Typography,
8
} from '@mui/material'
9
import { useFormik } from 'formik'
10
import { Fragment, useState } from 'react'
11
import * as yup from 'yup'
12
import axiosInstance from '../../../api/api'
13
import ButtonOpenableDialog from '../../Reusables/ButtonOpenableDialog'
14
import { useDispatch } from 'react-redux'
15
import { sendTextForProcessing } from '../trackingToolThunks'
16
import SingleFileSelectionForm from '../../Reusables/SingleFileSelectionForm'
17

    
18
interface UploadValues {
19
    file?: File
20
}
21

    
22
const initialValues: UploadValues = {}
23

    
24
const FileUpload = () => {
25
    const dispatch = useDispatch()
26

    
27
    const [filename, setFilename] = useState<string | undefined>(undefined)
28
    const [fileProcessing, setFileProcessing] = useState(false)
29

    
30
    const validationSchema = yup.object().shape({
31
        file: yup.mixed().required('File is required'),
32
    })
33

    
34
    const formik = useFormik({
35
        initialValues,
36
        validationSchema,
37
        onSubmit: async (values) => {
38
            setFileProcessing(true)
39
            const reader = new FileReader()
40
            reader.readAsText(values.file as File)
41
            reader.onload = async () => {
42
                dispatch(sendTextForProcessing(reader.result as string))
43
                setFileProcessing(false)
44
            }
45
        },
46
    })
47

    
48
    // Callback when user selects the file
49
    const onFileSelected = (event: any) => {
50
        const file = event.currentTarget.files[0]
51
        if (file) {
52
            setFilename(file.name)
53
            formik.setFieldValue('file', file)
54
        }
55
    }
56

    
57
    const onClose = () => {
58
        if (fileProcessing) {
59
            return
60
        }
61
        setFilename(undefined)
62
        formik.resetForm()
63
    }
64

    
65
    const onClearSelectedFile = () => {
66
        setFilename(undefined)
67
        formik.setFieldValue('file', undefined)
68
    }
69

    
70
    return (
71
        <ButtonOpenableDialog
72
            buttonText="File"
73
            buttonColor="primary"
74
            buttonVariant="contained"
75
            onCloseCallback={onClose}
76
            maxWidth="xs"
77
        >
78
            <DialogTitle>Upload New File</DialogTitle>
79
            <DialogContent>
80
                <SingleFileSelectionForm
81
                    onFileSelected={onFileSelected}
82
                    onClearSelectedFile={onClearSelectedFile}
83
                    filename={filename}
84
                    formik={formik}
85
                />
86
            </DialogContent>
87
        </ButtonOpenableDialog>
88
    )
89
}
90

    
91
export default FileUpload
(1-1/5)