frontAnswerer/lib/components/ViewPublicationPage/ContactForm.tsx

563 lines
17 KiB
TypeScript
Raw Normal View History

2024-04-24 12:53:01 +00:00
import {
FC,
useRef,
useState,
useEffect,
Dispatch,
SetStateAction,
} from "react";
import {
2024-04-17 11:28:42 +00:00
Box,
Button,
InputAdornment,
Link,
TextField as MuiTextField,
TextFieldProps,
Typography,
useTheme,
} from "@mui/material";
2024-04-24 12:53:01 +00:00
import { useIMask } from "react-imask";
import CustomCheckbox from "@ui_kit/CustomCheckbox";
2024-04-09 19:52:45 +00:00
2024-04-24 12:53:01 +00:00
import AddressIcon from "@icons/ContactFormIcon/AddressIcon";
import EmailIcon from "@icons/ContactFormIcon/EmailIcon";
import NameIcon from "@icons/ContactFormIcon/NameIcon";
import PhoneIcon from "@icons/ContactFormIcon/PhoneIcon";
import TextIcon from "@icons/ContactFormIcon/TextIcon";
import { DESIGN_LIST } from "@/utils/designList";
2024-04-24 12:53:01 +00:00
import { sendFC, SendFCParams } from "@api/quizRelase";
2024-04-09 19:52:45 +00:00
import { useQuizData } from "@contexts/QuizDataContext";
import { NameplateLogo } from "@icons/NameplateLogo";
import { QuizQuestionResult } from "@model/questionTypes/result";
import { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { enqueueSnackbar } from "notistack";
import { useRootContainerSize } from "../../contexts/RootContainerWidthContext";
2024-04-17 16:08:40 +00:00
import {
2024-04-24 12:53:01 +00:00
FormContactFieldData,
FormContactFieldName,
2024-04-17 16:08:40 +00:00
} from "@model/settingsData.ts";
2024-04-17 16:08:40 +00:00
type InputProps = {
2024-04-24 12:53:01 +00:00
title: string;
desc: string;
Icon: FC<{ color: string; backgroundColor: string }>;
onChange: TextFieldProps["onChange"];
id: string;
mask?: string;
2024-04-17 16:08:40 +00:00
};
type InputsProps = {
2024-04-24 12:53:01 +00:00
name: string;
setName: Dispatch<SetStateAction<string>>;
email: string;
setEmail: Dispatch<SetStateAction<string>>;
phone: string;
setPhone: Dispatch<SetStateAction<string>>;
text: string;
setText: Dispatch<SetStateAction<string>>;
adress: string;
setAdress: Dispatch<SetStateAction<string>>;
2024-04-17 16:08:40 +00:00
};
const TextField = MuiTextField as unknown as FC<TextFieldProps>; // temporary fix ts(2590)
2024-04-17 11:28:42 +00:00
const EMAIL_REGEXP =
/^(([^<>()[\].,:\s@"]+(\.[^<>()[\].,:\s@"]+)*)|(".+"))@(([^<>()[\].,:\s@"]+\.)+[^<>()[\].,:\s@"]{2,})$/iu;
type Props = {
2024-04-17 11:28:42 +00:00
currentQuestion: AnyTypedQuizQuestion;
onShowResult: () => void;
2023-12-16 14:55:56 +00:00
};
2024-04-09 19:52:45 +00:00
export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
2024-04-17 11:28:42 +00:00
const theme = useTheme();
const { settings, questions, quizId, show_badge, preview } = useQuizData();
const [ready, setReady] = useState(false);
const [name, setName] = useState("");
const [email, setEmail] = useState("");
const [phone, setPhone] = useState("");
const [text, setText] = useState("");
const [adress, setAdress] = useState("");
const [screenHeight, setScreenHeight] = useState<number>(window.innerHeight);
const fireOnce = useRef(true);
const [fire, setFire] = useState(false);
const isMobile = useRootContainerSize() < 850;
const isTablet = useRootContainerSize() < 1000;
useEffect(() => {
function handleResize() {
setScreenHeight(window.innerHeight);
}
2024-04-17 11:28:42 +00:00
window.addEventListener("resize", handleResize);
2024-01-31 12:57:07 +00:00
2024-04-17 11:28:42 +00:00
return () => {
window.removeEventListener("resize", handleResize);
2024-01-31 12:57:07 +00:00
};
2024-04-17 11:28:42 +00:00
}, []);
const resultQuestion =
currentQuestion.type === "result"
? currentQuestion
: questions.find((question): question is QuizQuestionResult => {
if (settings?.cfg.haveRoot) {
return (
question.type === "result" &&
question.content.rule.parentId === currentQuestion.content.id
);
} else {
return (
question.type === "result" &&
question.content.rule.parentId === "line"
);
}
});
2024-04-17 11:28:42 +00:00
if (!resultQuestion) throw new Error("Result question not found");
const inputHC = async () => {
const FC = settings.cfg.formContact.fields || settings.cfg.formContact;
2024-04-24 12:53:01 +00:00
const body: SendFCParams["body"] = {};
2024-04-17 11:28:42 +00:00
if (name.length > 0) body.name = name;
if (email.length > 0) body.email = email;
if (phone.length > 0) body.phone = phone;
if (adress.length > 0) body.address = adress;
if (text.length > 0) body.customs = { [FC.text.text || "Фамилия"]: text };
if (Object.keys(body).length > 0) {
try {
await sendFC({
questionId: currentQuestion.id,
body: body,
qid: quizId,
preview,
});
2024-04-17 11:28:42 +00:00
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
localStorage.setItem(
"sessions",
JSON.stringify({ ...sessions, [quizId]: new Date().getTime() })
);
} catch (e) {
enqueueSnackbar("ответ не был засчитан");
}
}
2024-04-17 11:28:42 +00:00
};
2024-04-24 12:53:01 +00:00
const FCcopy: Record<FormContactFieldName, FormContactFieldData> =
2024-04-17 11:28:42 +00:00
settings.cfg.formContact.fields || settings.cfg.formContact;
2024-04-24 12:53:01 +00:00
const filteredFC: Partial<
Record<FormContactFieldName, FormContactFieldData>
> = {};
2024-04-17 11:28:42 +00:00
for (const i in FCcopy) {
2024-04-19 09:44:08 +00:00
const field = FCcopy[i as keyof typeof FCcopy];
2024-04-17 11:28:42 +00:00
if (field.used) {
2024-04-19 09:44:08 +00:00
filteredFC[i as FormContactFieldName] = field;
2024-04-17 11:28:42 +00:00
}
}
2024-04-17 11:28:42 +00:00
async function handleShowResultsClick() {
2024-04-19 09:44:08 +00:00
const FC = settings.cfg.formContact.fields;
2024-04-17 11:28:42 +00:00
if (FC["email"].used !== EMAIL_REGEXP.test(email)) {
return enqueueSnackbar("введена некорректная почта");
}
2024-04-17 11:28:42 +00:00
if (fireOnce.current) {
if (
name.length === 0 &&
email.length === 0 &&
phone.length === 0 &&
text.length === 0 &&
adress.length === 0
)
return enqueueSnackbar("Пожалуйста, заполните поля");
//почта валидна, хоть одно поле заполнено
setFire(true);
try {
await inputHC();
fireOnce.current = false;
2024-04-24 12:53:01 +00:00
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
2024-04-17 11:28:42 +00:00
sessions[quizId] = Date.now();
localStorage.setItem("sessions", JSON.stringify(sessions));
enqueueSnackbar("Данные успешно отправлены");
} catch (e) {
enqueueSnackbar("повторите попытку позже");
}
if (settings.cfg.resultInfo.showResultForm === "after") {
onShowResult();
}
}
2024-04-17 11:28:42 +00:00
setFire(false);
}
return (
<Box
sx={{
display: "flex",
alignItems: "center",
justifyContent: "center",
backgroundColor: theme.palette.background.default,
height: screenHeight > 500 ? "100%" : "auto",
overflow: "auto",
"&::-webkit-scrollbar": {
width: "0",
display: "none",
msOverflowStyle: "none",
},
scrollbarWidth: "none",
msOverflowStyle: "none",
backgroundPosition: "center",
backgroundSize: "cover",
backgroundImage:
settings.cfg.design && !isMobile
? quizThemes[settings.cfg.theme].isLight
? `url(${DESIGN_LIST[settings.cfg.theme]})`
: `linear-gradient(90deg, #272626, transparent), url(${
DESIGN_LIST[settings.cfg.theme]
})`
: null,
}}
>
<Box
sx={{
width: !isMobile ? "100%" : isMobile ? undefined : "530px",
borderRadius: "4px",
height: isMobile ? "100%" : "auto",
minHeight: "100%",
display: isMobile ? undefined : "flex",
background:
settings.cfg.design && !isMobile
? undefined
: theme.palette.background.default,
}}
>
<Box
2024-04-17 11:28:42 +00:00
sx={{
width: isMobile ? undefined : "100%",
display: "flex",
flexDirection: "column",
alignItems: "center",
justifyContent: "center",
borderRight: isMobile ? undefined : "1px solid #9A9AAF80",
margin: isMobile ? 0 : "40px 0",
padding: isMobile ? "0" : "0 40px"
2024-04-17 11:28:42 +00:00
}}
>
<Box
sx={{
2024-04-17 11:28:42 +00:00
maxWidth: "630px",
width: "100%",
display: "flex",
flexDirection: "column",
alignItems: "flex-start",
justifyContent: "center",
padding: isMobile ? "40px 20px 0 20px" : "0",
mt: isMobile ? 0 : isTablet ? "-180px" : "-47px",
}}
2024-04-17 11:28:42 +00:00
>
<Typography
sx={{
textAlign: isTablet ? undefined : "center",
fontSize: "24px",
2024-04-17 11:28:42 +00:00
lineHeight: "normal",
fontWeight: 501,
color: theme.palette.text.primary,
wordBreak: "break-word",
}}
>
{settings.cfg.formContact.title ||
"Заполните форму, чтобы получить результаты теста"}
</Typography>
{settings.cfg.formContact.desc && (
<Typography
sx={{
2024-04-17 11:28:42 +00:00
color: theme.palette.text.primary,
m: "20px 0",
fontSize: "18px",
wordBreak: "break-word",
}}
2024-04-17 11:28:42 +00:00
>
{settings.cfg.formContact.desc}
</Typography>
)}
</Box>
</Box>
2024-04-17 11:28:42 +00:00
<Box
sx={{
display: "flex",
alignItems: isMobile ? undefined : "center",
2024-04-17 11:28:42 +00:00
justifyContent: "center",
flexDirection: "column",
backgroundColor: theme.palette.background.default,
p: isMobile ? "0 20px" : isTablet ? "0px 40px 30px 60px" : "125px 60px 30px 60px",
2024-04-17 11:28:42 +00:00
}}
>
<Box
sx={{
display: "flex",
flexDirection: "column",
mt: isMobile ? "10px" : "20px",
mb: "20px"
2024-04-17 11:28:42 +00:00
}}
>
<Inputs
name={name}
setName={setName}
email={email}
setEmail={setEmail}
phone={phone}
setPhone={setPhone}
text={text}
setText={setText}
adress={adress}
setAdress={setAdress}
/>
</Box>
<Box
sx={{
display: "flex",
width: isMobile ? "300px" : "390px",
}}
>
<CustomCheckbox
label=""
handleChange={({ target }) => {
setReady(target.checked);
}}
checked={ready}
colorIcon={theme.palette.primary.main}
sx={{marginRight: "0"}}
2024-04-17 11:28:42 +00:00
/>
<Typography sx={{ color: theme.palette.text.primary, lineHeight: "18.96px" }} fontSize={"16px"} >
2024-04-17 11:28:42 +00:00
С&ensp;
<Link href={"https://shub.pena.digital/ppdd"} target="_blank">
Положением об обработке персональных данных{" "}
</Link>
&ensp;и&ensp;
<Link
href={"https://shub.pena.digital/docs/privacy"}
target="_blank"
>
{" "}
Политикой конфиденциальности{" "}
</Link>
&ensp;ознакомлен
</Typography>
</Box>
{
// resultQuestion &&
// settings.cfg.resultInfo.when === "after" &&
<Button
disabled={!(ready && !fire)}
variant="contained"
onClick={handleShowResultsClick}
sx={{
border: `1px solid ${theme.palette.primary.main}`,
margin: isMobile ? "auto" : undefined,
mt: "20px",
p: "10px 20px",
"&:disabled": {
border: "1px solid #9A9AAF",
color: "#9A9AAF",
},
}}
>
{settings.cfg.formContact?.button || "Получить результаты"}
</Button>
}
2024-04-17 11:28:42 +00:00
{show_badge && (
<Box
component={Link}
target={"_blank"}
href={`https://${
window.location.hostname.includes("s") ? "s" : ""
}quiz.pena.digital/squiz/quiz/logo?q=${quizId}`}
sx={{
display: "flex",
alignItems: "center",
mt: "55px",
mb: "40px",
gap: "10px",
2024-04-17 11:28:42 +00:00
textDecoration: "none",
position: "absolute",
bottom: 0,
left: isMobile ? "28%" : undefined
2024-04-17 11:28:42 +00:00
}}
>
<NameplateLogo
style={{
fontSize: "20px",
2024-04-17 11:28:42 +00:00
color: quizThemes[settings.cfg.theme].isLight
? "#151515"
: "#FFFFFF",
}}
/>
<Typography
sx={{
fontSize: "14px",
color: quizThemes[settings.cfg.theme].isLight
? "#4D4D4D"
: "#F5F7FF",
whiteSpace: "nowrap",
}}
>
Сделано на PenaQuiz
</Typography>
2024-01-31 12:57:07 +00:00
</Box>
2024-04-17 11:28:42 +00:00
)}
</Box>
2024-04-17 11:28:42 +00:00
</Box>
</Box>
);
};
const Inputs = ({
2024-04-17 11:28:42 +00:00
name,
setName,
email,
setEmail,
phone,
setPhone,
text,
setText,
adress,
setAdress,
2024-04-17 16:08:40 +00:00
}: InputsProps) => {
2024-04-17 11:28:42 +00:00
const { settings } = useQuizData();
const FC = settings.cfg.formContact.fields;
if (!FC) return null;
console.log(email);
const Name = (
<CustomInput
onChange={({ target }) => setName(target.value)}
id={name}
title={FC["name"].innerText || "Введите имя"}
desc={FC["name"].text || "Имя"}
Icon={NameIcon}
/>
);
const Email = (
<CustomInput
onChange={({ target }) => setEmail(target.value.replaceAll(/\s/g, ""))}
id={email}
title={FC["email"].innerText || "Введите Email"}
desc={FC["email"].text || "Email"}
Icon={EmailIcon}
/>
);
const Phone = (
<CustomInput
onChange={({ target }) => setPhone(target.value)}
id={phone}
title={FC["phone"].innerText || "Введите номер телефона"}
desc={FC["phone"].text || "Номер телефона"}
Icon={PhoneIcon}
2024-04-24 12:53:01 +00:00
mask="+7 (000) 000-00-00"
2024-04-17 11:28:42 +00:00
/>
);
const Text = (
<CustomInput
onChange={({ target }) => setText(target.value)}
id={text}
title={FC["text"].text || "Введите фамилию"}
desc={FC["text"].innerText || "Фамилия"}
Icon={TextIcon}
/>
);
const Adress = (
<CustomInput
onChange={({ target }) => setAdress(target.value)}
id={adress}
title={FC["address"].innerText || "Введите адрес"}
desc={FC["address"].text || "Адрес"}
Icon={AddressIcon}
/>
);
if (Object.values(FC).some((data) => data.used)) {
return (
<>
{FC["name"].used ? Name : <></>}
{FC["email"].used ? Email : <></>}
{FC["phone"].used ? Phone : <></>}
{FC["text"].used ? Text : <></>}
{FC["address"].used ? Adress : <></>}
</>
2024-01-31 12:57:07 +00:00
);
2024-04-17 11:28:42 +00:00
} else {
return (
<>
{Name}
{Email}
{Phone}
</>
2024-01-31 12:57:07 +00:00
);
2024-04-17 11:28:42 +00:00
}
2024-01-25 07:36:45 +00:00
};
2024-04-24 12:53:01 +00:00
const CustomInput = ({ title, desc, Icon, onChange, mask }: InputProps) => {
const theme = useTheme();
const isMobile = useRootContainerSize() < 600;
const { settings } = useQuizData();
const { ref } = useIMask({ mask });
return (
<Box m="10px 0">
<Typography mb="7px" color={theme.palette.text.primary} fontSize={"16px"}>
2024-04-24 12:53:01 +00:00
{title}
</Typography>
2024-04-17 11:28:42 +00:00
<TextField
2024-04-24 12:53:01 +00:00
inputRef={ref}
2024-04-17 11:28:42 +00:00
onChange={onChange}
sx={{
width: isMobile ? "100%" : "390px",
2024-04-17 11:28:42 +00:00
backgroundColor: theme.palette.background.default,
fontSize: "16px",
2024-04-17 11:28:42 +00:00
"& .MuiOutlinedInput-notchedOutline": {
borderColor: "#9A9AAF80",
borderRadius: "12px",
},
"& .MuiInputBase-root": {
paddingLeft: 0,
},
"& .MuiOutlinedInput-input": {
paddingLeft: "10px",
},
2024-04-17 11:28:42 +00:00
"& .MuiOutlinedInput-root": {
"&:hover fieldset": {
borderColor: theme.palette.primary.main,
},
},
}}
placeholder={desc}
InputProps={{
startAdornment: (
<InputAdornment position="start">
<Icon
color="gray"
backgroundColor={
quizThemes[settings.cfg.theme].isLight
? "#F2F3F7"
: "#F2F3F71A"
}
/>
</InputAdornment>
),
}}
/>
</Box>
);
2024-01-25 07:36:45 +00:00
};