completed with refactoring contact form

This commit is contained in:
aleksandr-raw 2024-05-08 19:00:12 +04:00
parent afb641c382
commit 8436c4668e
3 changed files with 319 additions and 304 deletions

@ -13,346 +13,358 @@ import {quizThemes} from "@utils/themes/Publication/themePublication.ts";
import {enqueueSnackbar} from "notistack"; import {enqueueSnackbar} from "notistack";
import {useRootContainerSize} from "@contexts/RootContainerWidthContext.ts"; import {useRootContainerSize} from "@contexts/RootContainerWidthContext.ts";
import { import {
FormContactFieldData, FormContactFieldData,
FormContactFieldName, FormContactFieldName,
} from "@model/settingsData.ts"; } from "@model/settingsData.ts";
import { import {
Inputs Inputs
} from "@/components/ViewPublicationPage/ContactForm/Inputs/Inputs.tsx"; } from "@/components/ViewPublicationPage/ContactForm/Inputs/Inputs.tsx";
import {EMAIL_REGEXP} from "@utils/emailRegexp.tsx"; import {EMAIL_REGEXP} from "@utils/emailRegexp.tsx";
import { import {
ContactTextBlock ContactTextBlock
} from "@/components/ViewPublicationPage/ContactForm/ContactTextBlock/ContactTextBlock.tsx"; } from "@/components/ViewPublicationPage/ContactForm/ContactTextBlock/ContactTextBlock.tsx";
type Props = { type Props = {
currentQuestion: AnyTypedQuizQuestion; currentQuestion: AnyTypedQuizQuestion;
onShowResult: () => void; onShowResult: () => void;
}; };
export const ContactForm = ({ currentQuestion, onShowResult }: Props) => { export const ContactForm = ({currentQuestion, onShowResult}: Props) => {
const theme = useTheme(); const theme = useTheme();
const { settings, questions, quizId, show_badge, preview } = useQuizData(); const {settings, questions, quizId, show_badge, preview} = useQuizData();
const [ready, setReady] = useState(false); const [ready, setReady] = useState(false);
const [name, setName] = useState(""); const [name, setName] = useState("");
const [email, setEmail] = useState(""); const [email, setEmail] = useState("");
const [phone, setPhone] = useState(""); const [phone, setPhone] = useState("");
const [text, setText] = useState(""); const [text, setText] = useState("");
const [adress, setAdress] = useState(""); const [adress, setAdress] = useState("");
const [screenHeight, setScreenHeight] = useState<number>(window.innerHeight); const [screenHeight, setScreenHeight] = useState<number>(window.innerHeight);
const fireOnce = useRef(true); const fireOnce = useRef(true);
const [fire, setFire] = useState(false); const [fire, setFire] = useState(false);
const isMobile = useRootContainerSize() < 850; const isMobile = useRootContainerSize() < 850;
const isTablet = useRootContainerSize() < 1000; const isTablet = useRootContainerSize() < 1000;
useEffect(() => { useEffect(() => {
function handleResize() { function handleResize() {
setScreenHeight(window.innerHeight); 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"); window.addEventListener("resize", handleResize);
const inputHC = async () => { return () => {
const FC = settings.cfg.formContact.fields || settings.cfg.formContact; window.removeEventListener("resize", handleResize);
const body: SendFCParams["body"] = {}; };
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) { const resultQuestion =
try { currentQuestion.type === "result"
await sendFC({ ? currentQuestion
questionId: currentQuestion.id, : questions.find((question): question is QuizQuestionResult => {
body: body, if (settings?.cfg.haveRoot) {
qid: quizId, return (
preview, question.type === "result" &&
}); question.content.rule.parentId === currentQuestion.content.id
);
} else {
return (
question.type === "result" &&
question.content.rule.parentId === "line"
);
}
});
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}"); if (!resultQuestion) throw new Error("Result question not found");
localStorage.setItem(
"sessions",
JSON.stringify({ ...sessions, [quizId]: new Date().getTime() })
);
} catch (e) {
enqueueSnackbar("ответ не был засчитан");
}
}
};
const FCcopy: Record<FormContactFieldName, FormContactFieldData> = const inputHC = async () => {
settings.cfg.formContact.fields || settings.cfg.formContact; const FC = settings.cfg.formContact.fields || settings.cfg.formContact;
const body: SendFCParams["body"] = {};
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 filteredFC: Partial< if (Object.keys(body).length > 0) {
Record<FormContactFieldName, FormContactFieldData> try {
> = {}; await sendFC({
for (const i in FCcopy) { questionId: currentQuestion.id,
const field = FCcopy[i as keyof typeof FCcopy]; body: body,
if (field.used) { qid: quizId,
filteredFC[i as FormContactFieldName] = field; preview,
} });
}
async function handleShowResultsClick() { const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
const FC = settings.cfg.formContact.fields; localStorage.setItem(
if (FC["email"].used !== EMAIL_REGEXP.test(email)) { "sessions",
return enqueueSnackbar("введена некорректная почта"); JSON.stringify({
...sessions,
[quizId]: new Date().getTime()
})
);
} catch (e) {
enqueueSnackbar("ответ не был засчитан");
}
}
};
const FCcopy: Record<FormContactFieldName, FormContactFieldData> =
settings.cfg.formContact.fields || settings.cfg.formContact;
const filteredFC: Partial<
Record<FormContactFieldName, FormContactFieldData>
> = {};
for (const i in FCcopy) {
const field = FCcopy[i as keyof typeof FCcopy];
if (field.used) {
filteredFC[i as FormContactFieldName] = field;
}
} }
if (fireOnce.current) { async function handleShowResultsClick() {
if ( const FC = settings.cfg.formContact.fields;
name.length === 0 && if (FC["email"].used !== EMAIL_REGEXP.test(email)) {
email.length === 0 && return enqueueSnackbar("введена некорректная почта");
phone.length === 0 && }
text.length === 0 &&
adress.length === 0
)
return enqueueSnackbar("Пожалуйста, заполните поля");
//почта валидна, хоть одно поле заполнено if (fireOnce.current) {
setFire(true); if (
try { name.length === 0 &&
await inputHC(); email.length === 0 &&
fireOnce.current = false; phone.length === 0 &&
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}"); text.length === 0 &&
sessions[quizId] = Date.now(); adress.length === 0
localStorage.setItem("sessions", JSON.stringify(sessions)); )
return enqueueSnackbar("Пожалуйста, заполните поля");
//почта валидна, хоть одно поле заполнено
setFire(true);
try {
await inputHC();
fireOnce.current = false;
const sessions = JSON.parse(localStorage.getItem("sessions") || "{}");
sessions[quizId] = Date.now();
localStorage.setItem("sessions", JSON.stringify(sessions));
//@ts-ignore
const YM = window?.ym;
//@ts-ignore
const VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
"penaquiz-contacts"
);
}
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: "penaquiz-contacts"
});
}
} catch (e) {
enqueueSnackbar("повторите попытку позже");
}
if (settings.cfg.resultInfo.showResultForm === "after") {
onShowResult();
}
}
setFire(false);
}
useEffect(() => {
//@ts-ignore //@ts-ignore
const YM = window?.ym; const YM = window?.ym;
//@ts-ignore //@ts-ignore
const VP = window?._tmr; const VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) { if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM( YM(
settings.cfg.yandexMetricNumber, settings.cfg.yandexMetricNumber,
"reachGoal", "reachGoal",
"penaquiz-contacts" "penaquiz-form"
); );
} }
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) { if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({ VP.push({
type: "reachGoal", type: "reachGoal",
id: settings.cfg.vkMetricNumber, id: settings.cfg.vkMetricNumber,
goal: "penaquiz-contacts" goal: "penaquiz-form"
}); });
} }
} catch (e) { }, [])
enqueueSnackbar("повторите попытку позже");
}
if (settings.cfg.resultInfo.showResultForm === "after") {
onShowResult();
}
}
setFire(false); return (
} <Box
useEffect(() => {
//@ts-ignore
const YM = window?.ym;
//@ts-ignore
const VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
"penaquiz-form"
);
}
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: "penaquiz-form"
});
}
}, [])
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, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%), 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,
}}
>
<ContactTextBlock settings={settings} />
<Box sx={{
flexGrow: 0,
display: "flex",
alignItems: "center",
justifyContent: "space-between",
flexDirection: "column",
backgroundColor: theme.palette.background.default,
height: "auto",
}}>
<Box
sx={{
display: "flex",
alignItems: isMobile ? undefined : "center",
justifyContent: "center",
flexDirection: "column",
p: isMobile ? "0 20px" : isTablet ? "0px 40px 30px 60px" : "125px 60px 30px 60px",
}}
>
<Box
sx={{ sx={{
display: "flex", display: "flex",
flexDirection: "column", alignItems: "center",
mt: isMobile ? "10px" : "20px", justifyContent: "center",
mb: "20px" backgroundColor: theme.palette.background.default,
}} height: screenHeight > 500 ? "100%" : "auto",
> overflow: "auto",
<Inputs "&::-webkit-scrollbar": {
name={name} width: "0",
setName={setName} display: "none",
email={email} msOverflowStyle: "none",
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" }}
/>
<Typography sx={{ color: theme.palette.text.primary, lineHeight: "18.96px" }} fontSize={"16px"} >
С&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>
<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",
}, },
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, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%), url(${DESIGN_LIST[settings.cfg.theme]
})`
: null,
}}
>
<Box
sx={{
width: !isMobile ? "100%" : isMobile ? undefined : "530px",
borderRadius: "4px",
height: isMobile ? "100%" : "auto",
minHeight: "100%",
display: "flex",
flexDirection: isMobile ? "column" : "row",
background:
settings.cfg.design && !isMobile
? undefined
: theme.palette.background.default,
}}
> >
{settings.cfg.formContact?.button || "Получить результаты"} <ContactTextBlock settings={settings}/>
</Button> <Box sx={{
</Box> flexGrow: isMobile ? 1 : 0,
{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", display: "flex",
alignItems: "center", alignItems: "center",
mt: "55px", justifyContent: "space-between",
mb: isMobile? "30px": isTablet? "40px" :"50px", flexDirection: "column",
gap: "10px", backgroundColor: theme.palette.background.default,
textDecoration: "none", height: "auto",
}} }}>
> <Box
<NameplateLogo sx={{
style={{ display: "flex",
fontSize: "20px", alignItems: isMobile ? undefined : "center",
color: quizThemes[settings.cfg.theme].isLight justifyContent: "center",
? "#151515" flexDirection: "column",
: "#FFFFFF", p: isMobile ? "0 20px" : isTablet ? "105px 40px 0 60px" : "105px 60px 0 60px",
}} margin: isMobile ? "0" : "auto 0",
/> }}
</Box> >
)} <Box
sx={{
display: "flex",
flexDirection: "column",
mt: isMobile ? "10px" : "20px",
mb: "20px"
}}
>
<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"}}
/>
<Typography sx={{
color: theme.palette.text.primary,
lineHeight: "18.96px"
}} fontSize={"16px"}>
С&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>
<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>
</Box>
{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: isMobile ? "30px" : isTablet ? "40px" : "50px",
gap: "10px",
textDecoration: "none",
margitTop: "auto",
}}
>
<NameplateLogo
style={{
fontSize: "20px",
color: quizThemes[settings.cfg.theme].isLight
? "#151515"
: "#FFFFFF",
}}
/>
</Box>
)}
</Box>
</Box>
</Box> </Box>
</Box> );
</Box>
);
}; };

@ -14,7 +14,7 @@ export const ContactTextBlock: FC<ContactTextBlockProps> = ({settings}) => {
return ( return (
<Box <Box
sx={{ sx={{
flexGrow: 1, flexGrow: isMobile ? 0 : 1,
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
alignItems: "center", alignItems: "center",
@ -26,7 +26,7 @@ export const ContactTextBlock: FC<ContactTextBlockProps> = ({settings}) => {
> >
<Box <Box
sx={{ sx={{
maxWidth: isMobile? "100%" : isTablet? "410px" : "630px", maxWidth: isMobile ? "100%" : isTablet ? "410px" : "630px",
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
alignItems: "flex-start", alignItems: "flex-start",

@ -7,7 +7,7 @@ type CountrySelectorProps = {
setMask: Dispatch<SetStateAction<string>>; setMask: Dispatch<SetStateAction<string>>;
} }
export const CountrySelector:FC<CountrySelectorProps> = ({setMask}) => { export const CountrySelector: FC<CountrySelectorProps> = ({setMask}) => {
const theme = useTheme(); const theme = useTheme();
const [country, setCountry] = useState('RU'); const [country, setCountry] = useState('RU');
@ -24,6 +24,8 @@ export const CountrySelector:FC<CountrySelectorProps> = ({setMask}) => {
PaperProps: { PaperProps: {
style: { style: {
backgroundColor: theme.palette.background.default, backgroundColor: theme.palette.background.default,
borderRadius: '12px',
scrollbarWidth: "none",
}, },
}, },
}} }}
@ -55,7 +57,8 @@ export const CountrySelector:FC<CountrySelectorProps> = ({setMask}) => {
}} }}
> >
{Object.keys(phoneMasksByCountry).map((countryCode) => { {Object.keys(phoneMasksByCountry).map((countryCode) => {
return <MenuItem value={countryCode}>{phoneMasksByCountry[countryCode][0]}</MenuItem> return <MenuItem
value={countryCode}>{phoneMasksByCountry[countryCode][0]}</MenuItem>
})} })}
</Select> </Select>
); );