forked from dmm-com/pagoda
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathImportForm.tsx
98 lines (88 loc) · 2.94 KB
/
ImportForm.tsx
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
87
88
89
90
91
92
93
94
95
96
97
98
import { Box, Button, Input, Typography } from "@mui/material";
import Encoding from "encoding-japanese";
import { useSnackbar } from "notistack";
import React, { ChangeEvent, FC, useState } from "react";
import { useNavigate } from "react-router";
import {
isResponseError,
toReportableNonFieldErrors,
} from "../../services/AironeAPIErrorUtil";
interface Props {
handleImport: (data: string | ArrayBuffer) => Promise<void>;
handleCancel?: () => void;
}
export const ImportForm: FC<Props> = ({ handleImport, handleCancel }) => {
const navigate = useNavigate();
const [file, setFile] = useState<File>();
const [errorMessage, setErrorMessage] = useState<string>("");
const { enqueueSnackbar } = useSnackbar();
const onChange = (event: ChangeEvent<HTMLInputElement>) => {
event.target.files && setFile(event.target.files[0]);
};
const onClick = async () => {
if (file) {
// TODO its better to avoid reading file twice
const arrayBuffer = await file.arrayBuffer();
const bytes = new Uint8Array(arrayBuffer);
const encodingDetection = Encoding.detect(bytes);
const encoding =
typeof encodingDetection === "string" ? encodingDetection : "UNICODE";
const fileReader = new FileReader();
fileReader.readAsText(file, encoding);
fileReader.onload = async () => {
if (fileReader.result == null) {
return;
}
try {
await handleImport(fileReader.result);
navigate(0);
} catch (e) {
if (e instanceof Error && isResponseError(e)) {
const reportableError = await toReportableNonFieldErrors(e);
setErrorMessage(
`ファイルのアップロードに失敗しました: ${reportableError ?? ""}`,
);
enqueueSnackbar(
`ファイルのアップロードに失敗しました: ${reportableError ?? ""}`,
{
variant: "error",
},
);
} else {
setErrorMessage("ファイルのアップロードに失敗しました。");
enqueueSnackbar("ファイルのアップロードに失敗しました", {
variant: "error",
});
}
}
};
}
};
return (
<Box display="flex" flexDirection="column">
<Input type="file" onChange={onChange} data-testid="upload-import-file" />
<Typography color="error" variant="caption" my="4px">
{errorMessage}
</Typography>
<Box display="flex" justifyContent="flex-end">
<Button
type="submit"
variant="contained"
color="secondary"
onClick={onClick}
sx={{ m: "4px" }}
>
インポート
</Button>
<Button
variant="contained"
color="info"
onClick={handleCancel}
sx={{ m: "4px" }}
>
キャンセル
</Button>
</Box>
</Box>
);
};