frontAnswerer/lib/components/ViewPublicationPage/tools/File.tsx

64 lines
2.0 KiB
TypeScript
Raw Normal View History

import { ChangeEvent, useEffect, useRef, useState } from "react";
import { Box, Button, Typography } from "@mui/material";
import type {
2024-02-02 14:35:02 +00:00
QuizQuestionFile,
UploadFileType,
} from "@model/questionTypes/file";
2024-02-02 14:35:02 +00:00
const UPLOAD_FILE_TYPES_MAP: Record<UploadFileType, string> = {
picture: "image/*",
video: "video/*",
audio: "audio/*",
document:
".doc,.docx,application/msword,application/vnd.openxmlformats-officedocument.wordprocessingml.document,.pdf",
} as const;
interface Props {
2024-02-02 14:35:02 +00:00
question: QuizQuestionFile;
}
export default function File({ question }: Props) {
2024-02-02 14:35:02 +00:00
const fileInputRef = useRef<HTMLInputElement>(null);
const [file, setFile] = useState<File | null>(null);
const [acceptedType, setAcceptedType] = useState<any>(
UPLOAD_FILE_TYPES_MAP.picture
);
2024-02-02 14:35:02 +00:00
useEffect(() => {
setAcceptedType(UPLOAD_FILE_TYPES_MAP[question.content.type]);
}, [question.content.type]);
2024-02-02 14:35:02 +00:00
function handleFileChange(event: ChangeEvent<HTMLInputElement>) {
if (!event.target.files?.[0]) return setFile(null);
setFile(event.target.files[0]);
}
2024-02-02 14:35:02 +00:00
return (
<Box
sx={{
display: "flex",
flexDirection: "column",
alignItems: "start",
gap: 1,
}}
>
<Typography variant="h6" data-cy="question-title">{question.title}</Typography>
<Button variant="contained" onClick={() => fileInputRef.current?.click()}>
Загрузить файл
<input
ref={fileInputRef}
onChange={handleFileChange}
type="file"
accept={acceptedType}
data-cy="file-upload-input"
style={{
display: "none",
}}
/>
</Button>
{file && <Typography data-cy="chosen-file-name">Выбран файл: {file.name}</Typography>}
</Box>
);
}