Compare commits
2 Commits
main
...
send_image
Author | SHA1 | Date | |
---|---|---|---|
8e0d066970 | |||
15434027ba |
@ -76,7 +76,52 @@ export const publicationMakeRequest = ({ url, body }: PublicationMakeRequestPara
|
||||
let globalStatus: string | null = null;
|
||||
let isFirstRequest = true;
|
||||
|
||||
export async function getData({ quizId, page }: { quizId: string; page?: number }): Promise<{
|
||||
export async function getData({ quizId }: { quizId: string }): Promise<{
|
||||
data: GetQuizDataResponse | null;
|
||||
isRecentlyCompleted: boolean;
|
||||
error?: AxiosError;
|
||||
}> {
|
||||
try {
|
||||
const { data, headers } = await axios<GetQuizDataResponse>(
|
||||
domain + `/answer/v1.0.0/settings${window.location.search}`,
|
||||
{
|
||||
method: "POST",
|
||||
headers: {
|
||||
"X-Sessionkey": SESSIONS,
|
||||
"Content-Type": "application/json",
|
||||
DeviceType: DeviceType,
|
||||
Device: Device,
|
||||
OS: OSDevice,
|
||||
Browser: userAgent,
|
||||
},
|
||||
data: {
|
||||
quiz_id: quizId,
|
||||
limit: 100,
|
||||
page: 0,
|
||||
need_config: true,
|
||||
},
|
||||
}
|
||||
);
|
||||
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
|
||||
|
||||
//Тут ещё проверка на антифрод без парса конфига. Нам не интересно время если не нужно запрещать проходить чаще чем в сутки
|
||||
if (typeof sessions[quizId] === "number" && data.settings.cfg.includes('antifraud":true')) {
|
||||
// unix время. Если меньше суток прошло - выводить ошибку, иначе пустить дальше
|
||||
if (Date.now() - sessions[quizId] < 86400000) {
|
||||
return { data, isRecentlyCompleted: true };
|
||||
}
|
||||
}
|
||||
|
||||
SESSIONS = headers["x-sessionkey"] ? headers["x-sessionkey"] : SESSIONS;
|
||||
|
||||
return { data, isRecentlyCompleted: false };
|
||||
} catch (nativeError) {
|
||||
const error = nativeError as AxiosError;
|
||||
|
||||
return { data: null, isRecentlyCompleted: false, error: error };
|
||||
}
|
||||
}
|
||||
export async function getDataSingle({ quizId, page }: { quizId: string; page?: number }): Promise<{
|
||||
data: GetQuizDataResponse | null;
|
||||
isRecentlyCompleted: boolean;
|
||||
error?: AxiosError;
|
||||
@ -179,6 +224,7 @@ export async function getData({ quizId, page }: { quizId: string; page?: number
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
export async function getQuizData({ quizId, status = "" }: { quizId: string; status?: string }) {
|
||||
if (!quizId) throw new Error("No quiz id");
|
||||
|
||||
|
@ -26,6 +26,7 @@ import type { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
|
||||
import { isProduction } from "@/utils/defineDomain";
|
||||
import { useQuizStore } from "@/stores/useQuizStore";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { isNeftyanka } from "@/ui_kit/neftyankacrutch";
|
||||
|
||||
type Props = {
|
||||
currentQuestion: AnyTypedQuizQuestion;
|
||||
@ -318,7 +319,7 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
|
||||
},
|
||||
}}
|
||||
>
|
||||
{settings.cfg.formContact?.button || t("Get results")}
|
||||
{isNeftyanka ? t("neftyanka button") : settings.cfg.formContact?.button || t("Get results")}
|
||||
</Button>
|
||||
</Box>
|
||||
{show_badge && (
|
||||
|
@ -3,6 +3,7 @@ import { useRootContainerSize } from "@contexts/RootContainerWidthContext.ts";
|
||||
import { QuizSettingsConfig } from "@model/settingsData.ts";
|
||||
import { FC } from "react";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { isNeftyanka } from "@/ui_kit/neftyankacrutch";
|
||||
|
||||
type ContactTextBlockProps = {
|
||||
settings: QuizSettingsConfig;
|
||||
@ -47,7 +48,9 @@ export const ContactTextBlock: FC<ContactTextBlockProps> = ({ settings }) => {
|
||||
wordBreak: "break-word",
|
||||
}}
|
||||
>
|
||||
{settings.cfg.formContact.title || t("Fill out the form to receive your test results")}
|
||||
{isNeftyanka
|
||||
? t("neftyanka FK")
|
||||
: settings.cfg.formContact.title || t("Fill out the form to receive your test results")}
|
||||
</Typography>
|
||||
{settings.cfg.formContact.desc && (
|
||||
<Typography
|
||||
|
@ -0,0 +1,122 @@
|
||||
import { Box, ButtonBase, Typography, useTheme } from "@mui/material";
|
||||
import { useMemo, useState } from "react";
|
||||
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { ACCEPT_SEND_FILE_TYPES_MAP } from "@/components/ViewPublicationPage/tools/fileUpload";
|
||||
import UploadIcon from "@icons/UploadIcon";
|
||||
import { uploadFile } from "@/utils/fileUpload";
|
||||
import { useQuizStore } from "@/stores/useQuizStore";
|
||||
|
||||
interface ImageCardProps {
|
||||
questionId: string;
|
||||
imageUrl: string;
|
||||
isOwn?: boolean;
|
||||
onImageUpload?: (fileUrl: string) => void;
|
||||
}
|
||||
|
||||
const useFileUpload = (questionId: string, onImageUpload?: (fileUrl: string) => void) => {
|
||||
const { t } = useTranslation();
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
const [currentImageUrl, setCurrentImageUrl] = useState<string | null>(null);
|
||||
const { quizId, preview } = useQuizStore();
|
||||
|
||||
const handleFileUpload = async (file: File | undefined) => {
|
||||
if (isSending || !file) return;
|
||||
|
||||
const result = await uploadFile({
|
||||
file,
|
||||
questionId,
|
||||
quizId,
|
||||
fileType: "picture",
|
||||
preview,
|
||||
onSuccess: (fileUrl) => {
|
||||
setCurrentImageUrl(URL.createObjectURL(file));
|
||||
onImageUpload?.(fileUrl);
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
enqueueSnackbar(t(error.message));
|
||||
},
|
||||
onProgress: () => {
|
||||
setIsSending(true);
|
||||
},
|
||||
});
|
||||
|
||||
setIsSending(false);
|
||||
};
|
||||
|
||||
return {
|
||||
isSending,
|
||||
currentImageUrl,
|
||||
handleFileUpload,
|
||||
};
|
||||
};
|
||||
|
||||
export const ImageCard = ({ questionId, imageUrl, isOwn, onImageUpload }: ImageCardProps) => {
|
||||
const theme = useTheme();
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useRootContainerSize() < 450;
|
||||
const isTablet = useRootContainerSize() < 850;
|
||||
const [isDropzoneHighlighted, setIsDropzoneHighlighted] = useState(false);
|
||||
const { currentImageUrl, handleFileUpload } = useFileUpload(questionId, onImageUpload);
|
||||
|
||||
const onDrop = (event: React.DragEvent<HTMLLabelElement>) => {
|
||||
event.preventDefault();
|
||||
setIsDropzoneHighlighted(false);
|
||||
|
||||
const file = event.dataTransfer.files[0];
|
||||
handleFileUpload(file);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box sx={{ width: "100%", height: "300px", position: "relative" }}>
|
||||
<img
|
||||
src={currentImageUrl || imageUrl}
|
||||
style={{
|
||||
display: "block",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
objectFit: "cover",
|
||||
borderRadius: "12px 12px 0 0",
|
||||
}}
|
||||
alt=""
|
||||
/>
|
||||
{isOwn && (
|
||||
<Box
|
||||
component="label"
|
||||
sx={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.5)",
|
||||
opacity: isDropzoneHighlighted ? 1 : 0,
|
||||
transition: "opacity 0.2s",
|
||||
"&:hover": {
|
||||
opacity: 1,
|
||||
},
|
||||
borderRadius: "12px 12px 0 0",
|
||||
cursor: "pointer",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
}}
|
||||
onDragEnter={() => setIsDropzoneHighlighted(true)}
|
||||
onDragLeave={() => setIsDropzoneHighlighted(false)}
|
||||
onDragOver={(event) => event.preventDefault()}
|
||||
onDrop={onDrop}
|
||||
>
|
||||
<input
|
||||
onChange={({ target }) => handleFileUpload(target.files?.[0])}
|
||||
hidden
|
||||
accept={ACCEPT_SEND_FILE_TYPES_MAP.picture.join(",")}
|
||||
type="file"
|
||||
/>
|
||||
<UploadIcon color="#FFFFFF" />
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
@ -1,14 +1,30 @@
|
||||
import { CheckboxIcon } from "@/assets/icons/Checkbox";
|
||||
import type { QuestionVariant, QuestionVariantWithEditedImages } from "@/model/questionTypes/shared";
|
||||
import { Box, Checkbox, FormControlLabel, Input, Radio, TextareaAutosize, Typography, useTheme } from "@mui/material";
|
||||
import {
|
||||
Box,
|
||||
Checkbox,
|
||||
FormControlLabel,
|
||||
Input,
|
||||
Radio,
|
||||
TextareaAutosize,
|
||||
Typography,
|
||||
useTheme,
|
||||
ButtonBase,
|
||||
} from "@mui/material";
|
||||
import { useQuizViewStore } from "@stores/quizView";
|
||||
import RadioCheck from "@ui_kit/RadioCheck";
|
||||
import RadioIcon from "@ui_kit/RadioIcon";
|
||||
import { quizThemes } from "@utils/themes/Publication/themePublication";
|
||||
import { useMemo, type MouseEvent, useRef, useEffect } from "react";
|
||||
import { useMemo, type MouseEvent, useRef, useEffect, useState } from "react";
|
||||
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
|
||||
import { useQuizStore } from "@/stores/useQuizStore";
|
||||
import { useTranslation } from "react-i18next";
|
||||
import { sendAnswer, sendFile } from "@api/quizRelase";
|
||||
import { enqueueSnackbar } from "notistack";
|
||||
import { ACCEPT_SEND_FILE_TYPES_MAP, MAX_FILE_SIZE } from "@/components/ViewPublicationPage/tools/fileUpload";
|
||||
import UploadIcon from "@icons/UploadIcon";
|
||||
import { uploadFile } from "@/utils/fileUpload";
|
||||
import { ImageCard } from "./ImageCard";
|
||||
|
||||
type ImagesProps = {
|
||||
questionId: string;
|
||||
@ -22,12 +38,11 @@ type ImagesProps = {
|
||||
};
|
||||
|
||||
interface OwnInputProps {
|
||||
questionId: string;
|
||||
variant: QuestionVariant;
|
||||
largeCheck: boolean;
|
||||
ownPlaceholder: string;
|
||||
}
|
||||
const OwnInput = ({ questionId, variant, largeCheck, ownPlaceholder }: OwnInputProps) => {
|
||||
const OwnInput = ({ variant, largeCheck, ownPlaceholder }: OwnInputProps) => {
|
||||
const theme = useTheme();
|
||||
const ownVariants = useQuizViewStore((state) => state.ownVariants);
|
||||
const { updateOwnVariant } = useQuizViewStore((state) => state);
|
||||
@ -100,13 +115,17 @@ export const ImageVariant = ({
|
||||
const answers = useQuizViewStore((state) => state.answers);
|
||||
const isMobile = useRootContainerSize() < 450;
|
||||
const isTablet = useRootContainerSize() < 850;
|
||||
const [isSending, setIsSending] = useState(false);
|
||||
|
||||
const { quizId, preview } = useQuizStore();
|
||||
|
||||
const canvasRef = useRef<HTMLCanvasElement | null>(null);
|
||||
const containerCanvasRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
const onVariantClick = async (event: MouseEvent<HTMLDivElement>) => {
|
||||
event.preventDefault();
|
||||
|
||||
if (own) return;
|
||||
|
||||
const variantId = variant.id;
|
||||
if (isMulti) {
|
||||
const currentAnswer = typeof answer !== "string" ? answer || [] : [];
|
||||
@ -127,13 +146,37 @@ export const ImageVariant = ({
|
||||
}
|
||||
};
|
||||
|
||||
const handleFileUpload = async (file: File | undefined) => {
|
||||
if (isSending || !file) return;
|
||||
|
||||
const result = await uploadFile({
|
||||
file,
|
||||
questionId,
|
||||
quizId,
|
||||
fileType: "picture",
|
||||
preview,
|
||||
onSuccess: (fileUrl) => {
|
||||
setImageUrl(URL.createObjectURL(file));
|
||||
},
|
||||
onError: (error) => {
|
||||
console.error(error);
|
||||
enqueueSnackbar(t(error.message));
|
||||
},
|
||||
onProgress: () => {
|
||||
setIsSending(true);
|
||||
},
|
||||
});
|
||||
|
||||
setIsSending(false);
|
||||
};
|
||||
|
||||
const choiceImgUrl = useMemo(() => {
|
||||
if (variant.editedUrlImagesList !== undefined && variant.editedUrlImagesList !== null) {
|
||||
return variant.editedUrlImagesList[isMobile ? "mobile" : isTablet ? "tablet" : "desktop"];
|
||||
} else {
|
||||
return variant.extendedText;
|
||||
}
|
||||
}, []);
|
||||
}, [variant.editedUrlImagesList, isMobile, isTablet, variant.extendedText]);
|
||||
|
||||
useEffect(() => {
|
||||
if (canvasRef.current !== null) {
|
||||
@ -156,11 +199,11 @@ export const ImageVariant = ({
|
||||
<Box
|
||||
sx={{
|
||||
position: "relative",
|
||||
cursor: "pointer",
|
||||
cursor: own ? "default" : "pointer",
|
||||
borderRadius: "12px",
|
||||
border: `1px solid`,
|
||||
borderColor: !!answer?.includes(variant.id) ? theme.palette.primary.main : "#9A9AAF",
|
||||
"&:hover": { borderColor: theme.palette.primary.main },
|
||||
borderColor: !own && !!answer?.includes(variant.id) ? theme.palette.primary.main : "#9A9AAF",
|
||||
"&:hover": { borderColor: !own ? theme.palette.primary.main : "#9A9AAF" },
|
||||
background:
|
||||
settings.cfg.design && !quizThemes[settings.cfg.theme].isLight
|
||||
? "rgba(255,255,255, 0.3)"
|
||||
@ -171,32 +214,13 @@ export const ImageVariant = ({
|
||||
onClick={onVariantClick}
|
||||
>
|
||||
<Box sx={{ display: "flex", alignItems: "center", gap: "10px" }}>
|
||||
<Box sx={{ width: "100%", height: "300px" }}>
|
||||
{variant.extendedText && (
|
||||
<canvas
|
||||
ref={canvasRef}
|
||||
style={{
|
||||
display: "block",
|
||||
width: "100%",
|
||||
height: "100%",
|
||||
objectFit: "cover",
|
||||
borderRadius: "12px 12px 0 0",
|
||||
}}
|
||||
/>
|
||||
|
||||
// <img
|
||||
// src={choiceImgUrl}
|
||||
// alt=""
|
||||
// style={{
|
||||
// display: "block",
|
||||
// width: "100%",
|
||||
// height: "100%",
|
||||
// objectFit: "cover",
|
||||
// borderRadius: "12px 12px 0 0",
|
||||
// }}
|
||||
// />
|
||||
)}
|
||||
</Box>
|
||||
{variant.extendedText && (
|
||||
<ImageCard
|
||||
questionId={questionId}
|
||||
imageUrl={choiceImgUrl}
|
||||
isOwn={own}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
{own && (
|
||||
<Typography
|
||||
@ -266,7 +290,6 @@ export const ImageVariant = ({
|
||||
label={
|
||||
own ? (
|
||||
<OwnInput
|
||||
questionId={questionId}
|
||||
variant={variant}
|
||||
largeCheck={questionLargeCheck}
|
||||
ownPlaceholder={ownPlaceholder || "|"}
|
||||
|
@ -0,0 +1,120 @@
|
||||
import { Box, TextField as MuiTextField, TextFieldProps, Typography, useTheme } from "@mui/material";
|
||||
|
||||
import { Answer, useQuizViewStore } from "@stores/quizView";
|
||||
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
|
||||
|
||||
import { quizThemes } from "@utils/themes/Publication/themePublication";
|
||||
|
||||
import type { ChangeEvent, FC } from "react";
|
||||
import type { QuizQuestionText } from "@model/questionTypes/text";
|
||||
import { useQuizStore } from "@/stores/useQuizStore";
|
||||
|
||||
const TextField = MuiTextField as unknown as FC<TextFieldProps>; // temporary fix ts(2590)
|
||||
|
||||
interface TextSpecialProps {
|
||||
currentQuestion: QuizQuestionText;
|
||||
answer?: Answer;
|
||||
stepNumber?: number | null;
|
||||
}
|
||||
|
||||
function highlightQuestions(text: string) {
|
||||
// Регулярка с учётом возможной точки в конце
|
||||
const regex = /(вопрос\s\d+[a-zA-Zа-яА-Я]\.?)/g;
|
||||
|
||||
// Замена на <span> с жирным текстом
|
||||
return text.replace(regex, '<span style="font-weight: bold">$1</span>');
|
||||
}
|
||||
|
||||
export const TextNeftyanka = ({ currentQuestion, answer, stepNumber }: TextSpecialProps) => {
|
||||
const { settings } = useQuizStore();
|
||||
const { updateAnswer } = useQuizViewStore((state) => state);
|
||||
const isHorizontal = true;
|
||||
const theme = useTheme();
|
||||
const isMobile = useRootContainerSize() < 650;
|
||||
|
||||
const onInputChange = async ({ target }: ChangeEvent<HTMLInputElement>) => {
|
||||
updateAnswer(currentQuestion.id, target.value, 0);
|
||||
};
|
||||
|
||||
return (
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
flexDirection: isMobile ? "column" : undefined,
|
||||
alignItems: isMobile ? "center" : undefined,
|
||||
}}
|
||||
>
|
||||
<Box
|
||||
sx={{
|
||||
display: "flex",
|
||||
width: "100%",
|
||||
marginTop: "20px",
|
||||
flexDirection: "column",
|
||||
alignItems: "center",
|
||||
gap: "20px",
|
||||
}}
|
||||
>
|
||||
{isHorizontal && currentQuestion.content.back && currentQuestion.content.back !== " " && (
|
||||
<Box
|
||||
sx={{ margin: "30px", width: "50vw", maxHeight: "550px" }}
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
<img
|
||||
key={currentQuestion.id}
|
||||
src={currentQuestion.content.back}
|
||||
style={{ width: "100%", height: "100%", objectFit: "contain" }}
|
||||
alt=""
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
<Typography
|
||||
variant="h5"
|
||||
color={theme.palette.text.primary}
|
||||
sx={{ wordBreak: "break-word" }}
|
||||
>
|
||||
{highlightQuestions(currentQuestion.title)}
|
||||
</Typography>
|
||||
{
|
||||
<TextField
|
||||
autoFocus={true}
|
||||
multiline
|
||||
maxRows={4}
|
||||
placeholder={currentQuestion.content.placeholder}
|
||||
value={answer || ""}
|
||||
onChange={onInputChange}
|
||||
inputProps={{
|
||||
maxLength: 400,
|
||||
background: settings.cfg.design
|
||||
? quizThemes[settings.cfg.theme].isLight
|
||||
? "#F2F3F7"
|
||||
: "rgba(154,154,175, 0.2)"
|
||||
: "transparent",
|
||||
}}
|
||||
sx={{
|
||||
width: "100%",
|
||||
"& .MuiOutlinedInput-root": {
|
||||
backgroundColor: settings.cfg.design ? "rgba(154,154,175, 0.2)" : "#FFFFFF",
|
||||
},
|
||||
"&:focus-visible": {
|
||||
borderColor: theme.palette.primary.main,
|
||||
},
|
||||
}}
|
||||
/>
|
||||
}
|
||||
</Box>
|
||||
{!isHorizontal && currentQuestion.content.back && currentQuestion.content.back !== " " && (
|
||||
<Box
|
||||
sx={{ margin: "15px", width: "40vw" }}
|
||||
onClick={(event) => event.preventDefault()}
|
||||
>
|
||||
<img
|
||||
key={currentQuestion.id}
|
||||
src={currentQuestion.content.back}
|
||||
style={{ width: "100%", height: "100%", objectFit: "contain" }}
|
||||
alt=""
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
};
|
@ -5,6 +5,8 @@ import { TextSpecialHorisontal } from "./TextSpecialHorisontal";
|
||||
|
||||
import type { QuizQuestionText } from "@model/questionTypes/text";
|
||||
import { useQuizStore } from "@/stores/useQuizStore";
|
||||
import { isNeftyanka } from "@/ui_kit/neftyankacrutch";
|
||||
import { TextNeftyanka } from "./TextNeftyanka";
|
||||
|
||||
type TextProps = {
|
||||
currentQuestion: QuizQuestionText;
|
||||
@ -18,7 +20,16 @@ export const Text = ({ currentQuestion, stepNumber }: TextProps) => {
|
||||
const answers = useQuizViewStore((state) => state.answers);
|
||||
const { answer } = answers.find(({ questionId }) => questionId === currentQuestion.id) ?? {};
|
||||
|
||||
if (pathOnly === "/92ed5e3e-8e6a-491e-87d0-d3197682d0e3" || pathOnly === "/cc006b40-ccbd-4600-a1d3-f902f85aa0a0")
|
||||
if (isNeftyanka)
|
||||
return (
|
||||
<TextNeftyanka
|
||||
currentQuestion={currentQuestion}
|
||||
answer={answer}
|
||||
stepNumber={stepNumber}
|
||||
/>
|
||||
);
|
||||
|
||||
if (pathOnly === "/92ed5e3e-8e6a-491e-87d0-d3197682d0e3")
|
||||
return (
|
||||
<TextSpecialHorisontal
|
||||
currentQuestion={currentQuestion}
|
||||
|
1
lib/ui_kit/neftyankacrutch.ts
Normal file
1
lib/ui_kit/neftyankacrutch.ts
Normal file
@ -0,0 +1 @@
|
||||
export const isNeftyanka = window.location.pathname === "/cc006b40-ccbd-4600-a1d3-f902f85aa0a0";
|
80
lib/utils/fileUpload.ts
Normal file
80
lib/utils/fileUpload.ts
Normal file
@ -0,0 +1,80 @@
|
||||
import { UploadFileType } from "@model/questionTypes/file";
|
||||
import { sendAnswer, sendFile } from "@api/quizRelase";
|
||||
import { ACCEPT_SEND_FILE_TYPES_MAP, MAX_FILE_SIZE } from "@/components/ViewPublicationPage/tools/fileUpload";
|
||||
|
||||
export interface UploadFileOptions {
|
||||
file: File;
|
||||
questionId: string;
|
||||
quizId: string;
|
||||
fileType: UploadFileType;
|
||||
preview: boolean;
|
||||
onSuccess?: (fileUrl: string) => void;
|
||||
onError?: (error: Error) => void;
|
||||
onProgress?: (progress: number) => void;
|
||||
}
|
||||
|
||||
export interface UploadFileResult {
|
||||
success: boolean;
|
||||
fileUrl?: string;
|
||||
error?: Error;
|
||||
}
|
||||
|
||||
export async function uploadFile({
|
||||
file,
|
||||
questionId,
|
||||
quizId,
|
||||
fileType,
|
||||
preview,
|
||||
onSuccess,
|
||||
onError,
|
||||
onProgress,
|
||||
}: UploadFileOptions): Promise<UploadFileResult> {
|
||||
try {
|
||||
// Проверка размера файла
|
||||
if (file.size > MAX_FILE_SIZE) {
|
||||
const error = new Error("File is too big. Maximum size is 50 MB");
|
||||
onError?.(error);
|
||||
return { success: false, error };
|
||||
}
|
||||
|
||||
// Проверка типа файла
|
||||
const isFileTypeAccepted = ACCEPT_SEND_FILE_TYPES_MAP[fileType].some((fileType) =>
|
||||
file.name.toLowerCase().endsWith(fileType)
|
||||
);
|
||||
|
||||
if (!isFileTypeAccepted) {
|
||||
const error = new Error("Incorrect file type selected");
|
||||
onError?.(error);
|
||||
return { success: false, error };
|
||||
}
|
||||
|
||||
// Загрузка файла
|
||||
const data = await sendFile({
|
||||
questionId,
|
||||
body: {
|
||||
file,
|
||||
name: file.name,
|
||||
preview,
|
||||
},
|
||||
qid: quizId,
|
||||
});
|
||||
|
||||
// Отправка ответа
|
||||
await sendAnswer({
|
||||
questionId,
|
||||
body: `${data!.data.fileIDMap[questionId]}`,
|
||||
qid: quizId,
|
||||
preview,
|
||||
});
|
||||
|
||||
const fileUrl = `${file.name}|${URL.createObjectURL(file)}`;
|
||||
onSuccess?.(fileUrl);
|
||||
onProgress?.(100);
|
||||
|
||||
return { success: true, fileUrl };
|
||||
} catch (error) {
|
||||
const err = error instanceof Error ? error : new Error("Unknown error occurred");
|
||||
onError?.(err);
|
||||
return { success: false, error: err };
|
||||
}
|
||||
}
|
@ -53,5 +53,7 @@
|
||||
"and": "и",
|
||||
"Get results": "Получить результаты",
|
||||
"Data sent successfully": "Данные успешно отправлены",
|
||||
"Step": "Шаг"
|
||||
"Step": "Шаг",
|
||||
"neftyanka FK": "Заполните форму, чтобы отправить ваши ответы на викторину",
|
||||
"neftyanka button": "Отправить"
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user