From 88d1d904a8edc79a6e665a5e0bea729ac963e345 Mon Sep 17 00:00:00 2001 From: IlyaDoronin Date: Wed, 17 Apr 2024 14:28:42 +0300 Subject: [PATCH] fix: layout height --- .../ViewPublicationPage/ContactForm.tsx | 904 +++++++++--------- 1 file changed, 467 insertions(+), 437 deletions(-) diff --git a/lib/components/ViewPublicationPage/ContactForm.tsx b/lib/components/ViewPublicationPage/ContactForm.tsx index 1fb9c2f..657ea51 100644 --- a/lib/components/ViewPublicationPage/ContactForm.tsx +++ b/lib/components/ViewPublicationPage/ContactForm.tsx @@ -1,21 +1,21 @@ +import { FC, useRef, useState, useEffect } from "react"; 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 { - Box, - Button, - InputAdornment, - Link, - TextField as MuiTextField, - TextFieldProps, - Typography, - useTheme + Box, + Button, + InputAdornment, + Link, + TextField as MuiTextField, + TextFieldProps, + Typography, + useTheme, } from "@mui/material"; import CustomCheckbox from "@ui_kit/CustomCheckbox"; -import { FC, useRef, useState } from "react"; import { DESIGN_LIST } from "@/utils/designList"; import { sendFC } from "@api/quizRelase"; @@ -27,468 +27,498 @@ import { quizThemes } from "@utils/themes/Publication/themePublication"; import { enqueueSnackbar } from "notistack"; import { useRootContainerSize } from "../../contexts/RootContainerWidthContext"; - const TextField = MuiTextField as unknown as FC; // temporary fix ts(2590) -const EMAIL_REGEXP = /^(([^<>()[\].,:\s@"]+(\.[^<>()[\].,:\s@"]+)*)|(".+"))@(([^<>()[\].,:\s@"]+\.)+[^<>()[\].,:\s@"]{2,})$/iu; +const EMAIL_REGEXP = + /^(([^<>()[\].,:\s@"]+(\.[^<>()[\].,:\s@"]+)*)|(".+"))@(([^<>()[\].,:\s@"]+\.)+[^<>()[\].,:\s@"]{2,})$/iu; type Props = { - currentQuestion: AnyTypedQuizQuestion; - onShowResult: () => void; + currentQuestion: AnyTypedQuizQuestion; + onShowResult: () => void; }; export const ContactForm = ({ currentQuestion, onShowResult }: Props) => { - const theme = useTheme(); - const { settings, questions, quizId, show_badge, preview } = useQuizData(); + 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 [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(window.innerHeight); - const fireOnce = useRef(true); - const [fire, setFire] = useState(false); - const isMobile = useRootContainerSize() < 850; - const isTablet = useRootContainerSize() < 1000; + const fireOnce = useRef(true); + const [fire, setFire] = useState(false); + const isMobile = useRootContainerSize() < 850; + const isTablet = useRootContainerSize() < 1000; - 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" - ); - } + useEffect(() => { + function handleResize() { + setScreenHeight(window.innerHeight); + } + + window.addEventListener("resize", handleResize); + + return () => { + window.removeEventListener("resize", handleResize); + }; + }, []); + + 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" + ); + } }); - if (!resultQuestion) throw new Error("Result question not found"); + if (!resultQuestion) throw new Error("Result question not found"); - const inputHC = async () => { - const FC = settings.cfg.formContact.fields || settings.cfg.formContact; - const body = {} as any; - 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 }; + const inputHC = async () => { + const FC = settings.cfg.formContact.fields || settings.cfg.formContact; + const body = {} as any; + 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 - }); + if (Object.keys(body).length > 0) { + try { + await sendFC({ + questionId: currentQuestion.id, + body: body, + qid: quizId, + preview, + }); - const sessions = JSON.parse(localStorage.getItem("sessions") || "{}"); - localStorage.setItem( - "sessions", - JSON.stringify({ ...sessions, [quizId]: new Date().getTime() }) - ); - } catch (e) { - enqueueSnackbar("ответ не был засчитан"); - } - } - }; - - const FCcopy: any = settings.cfg.formContact.fields || settings.cfg.formContact; - - const filteredFC: any = {}; - for (const i in FCcopy) { - const field = FCcopy[i]; - if (field.used) { - filteredFC[i] = field; - } + const sessions = JSON.parse(localStorage.getItem("sessions") || "{}"); + localStorage.setItem( + "sessions", + JSON.stringify({ ...sessions, [quizId]: new Date().getTime() }) + ); + } catch (e) { + enqueueSnackbar("ответ не был засчитан"); + } } - + }; - async function handleShowResultsClick() { - const FC: any = settings.cfg.formContact.fields; - if (FC["email"].used !== EMAIL_REGEXP.test(email)) { - return enqueueSnackbar("введена некорректная почта"); - } + const FCcopy: any = + settings.cfg.formContact.fields || settings.cfg.formContact; + const filteredFC: any = {}; + for (const i in FCcopy) { + const field = FCcopy[i]; + if (field.used) { + filteredFC[i] = field; + } + } - 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; - const sessions: any = JSON.parse( - localStorage.getItem("sessions") || "{}" - ); - sessions[quizId] = Date.now(); - localStorage.setItem( - "sessions", - JSON.stringify(sessions) - ); - enqueueSnackbar("Данные успешно отправлены"); - } catch (e) { - enqueueSnackbar("повторите попытку позже"); - } - if (settings.cfg.resultInfo.showResultForm === "after") { - onShowResult(); - } - - } - - setFire(false); + async function handleShowResultsClick() { + const FC: any = settings.cfg.formContact.fields; + if (FC["email"].used !== EMAIL_REGEXP.test(email)) { + return enqueueSnackbar("введена некорректная почта"); } - return ( + 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; + const sessions: any = JSON.parse( + localStorage.getItem("sessions") || "{}" + ); + sessions[quizId] = Date.now(); + localStorage.setItem("sessions", JSON.stringify(sessions)); + enqueueSnackbar("Данные успешно отправлены"); + } catch (e) { + enqueueSnackbar("повторите попытку позже"); + } + if (settings.cfg.resultInfo.showResultForm === "after") { + onShowResult(); + } + } + + setFire(false); + } + + return ( + 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, + }} + > + + + + {settings.cfg.formContact.title || + "Заполните форму, чтобы получить результаты теста"} + + {settings.cfg.formContact.desc && ( + + {settings.cfg.formContact.desc} + + )} + + + + + + + + + { + // resultQuestion && + // settings.cfg.resultInfo.when === "after" && + + } + + + { + setReady(target.checked); + }} + checked={ready} + colorIcon={theme.palette.primary.main} + /> + + С  + + Положением об обработке персональных данных{" "} + +  и  + + {" "} + Политикой конфиденциальности{" "} + +  ознакомлен + + + {show_badge && ( + - - - - - {settings.cfg.formContact.title || - "Заполните форму, чтобы получить результаты теста"} - - {settings.cfg.formContact.desc && ( - - {settings.cfg.formContact.desc} - - )} - - - - - - - - - - { - // resultQuestion && - // settings.cfg.resultInfo.when === "after" && - - } - - - { - setReady(target.checked); - }} - checked={ready} - colorIcon={theme.palette.primary.main} - /> - - С  - - Положением об обработке персональных данных{" "} - -  и  - - {" "} - Политикой конфиденциальности{" "} - -  ознакомлен - - - {show_badge && - - - - Сделано на PenaQuiz - - - } - - + + + Сделано на PenaQuiz + + )} - ); + + + ); }; const Inputs = ({ - name, - setName, - email, - setEmail, - phone, - setPhone, - text, - setText, - adress, - setAdress, + name, + setName, + email, + setEmail, + phone, + setPhone, + text, + setText, + adress, + setAdress, }: any) => { - const { settings } = useQuizData(); + const { settings } = useQuizData(); - const FC = settings.cfg.formContact.fields; + const FC = settings.cfg.formContact.fields; - if (!FC) return null; - console.log(email); - const Name = ( - setName(target.value)} - id={name} - title={FC["name"].innerText || "Введите имя"} - desc={FC["name"].text || "Имя"} - Icon={NameIcon} - /> - ); - const Email = ( - setEmail(target.value.replaceAll(/\s/g, ''))} - id={email} - title={FC["email"].innerText || "Введите Email"} - desc={FC["email"].text || "Email"} - Icon={EmailIcon} - /> - ); - const Phone = ( - setPhone(target.value)} - id={phone} - title={FC["phone"].innerText || "Введите номер телефона"} - desc={FC["phone"].text || "Номер телефона"} - Icon={PhoneIcon} - /> - ); - const Text = ( - setText(target.value)} - id={text} - title={FC["text"].text || "Введите фамилию"} - desc={FC["text"].innerText || "Фамилия"} - Icon={TextIcon} - /> - ); - const Adress = ( - setAdress(target.value)} - id={adress} - title={FC["address"].innerText || "Введите адрес"} - desc={FC["address"].text || "Адрес"} - Icon={AddressIcon} - /> - ); + if (!FC) return null; + console.log(email); + const Name = ( + setName(target.value)} + id={name} + title={FC["name"].innerText || "Введите имя"} + desc={FC["name"].text || "Имя"} + Icon={NameIcon} + /> + ); + const Email = ( + setEmail(target.value.replaceAll(/\s/g, ""))} + id={email} + title={FC["email"].innerText || "Введите Email"} + desc={FC["email"].text || "Email"} + Icon={EmailIcon} + /> + ); + const Phone = ( + setPhone(target.value)} + id={phone} + title={FC["phone"].innerText || "Введите номер телефона"} + desc={FC["phone"].text || "Номер телефона"} + Icon={PhoneIcon} + /> + ); + const Text = ( + setText(target.value)} + id={text} + title={FC["text"].text || "Введите фамилию"} + desc={FC["text"].innerText || "Фамилия"} + Icon={TextIcon} + /> + ); + const Adress = ( + 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 : <>} - - ); - } else { - return ( - <> - {Name} - {Email} - {Phone} - - ); - } -}; - -const CustomInput = ({ title, desc, Icon, onChange, id }: { - id: string; - title: string; - desc: string; - Icon: FC<{ color: string; backgroundColor: string; }>; - onChange: TextFieldProps["onChange"]; -}) => { - const theme = useTheme(); - const isMobile = useRootContainerSize() < 600; - const { settings } = useQuizData(); + if (Object.values(FC).some((data) => data.used)) { return ( - - - {title} - - - - - - ), - }} - /> - + <> + {FC["name"].used ? Name : <>} + {FC["email"].used ? Email : <>} + {FC["phone"].used ? Phone : <>} + {FC["text"].used ? Text : <>} + {FC["address"].used ? Adress : <>} + ); + } else { + return ( + <> + {Name} + {Email} + {Phone} + + ); + } +}; + +const CustomInput = ({ + title, + desc, + Icon, + onChange, + id, +}: { + id: string; + title: string; + desc: string; + Icon: FC<{ color: string; backgroundColor: string }>; + onChange: TextFieldProps["onChange"]; +}) => { + const theme = useTheme(); + const isMobile = useRootContainerSize() < 600; + const { settings } = useQuizData(); + return ( + + + {title} + + + + + + ), + }} + /> + + ); };