fix: metrics using

This commit is contained in:
IlyaDoronin 2024-05-06 16:47:19 +03:00
parent a900035409
commit c15516344a
13 changed files with 1067 additions and 913 deletions

@ -1,154 +1,180 @@
import { getQuizData } from "@/api/quizRelase"; import {
import { QuizViewContext, createQuizViewStore } from "@/stores/quizView"; startTransition,
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton"; useEffect,
import { QuizDataContext } from "@contexts/QuizDataContext"; useLayoutEffect,
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext"; useRef,
import { QuizSettings } from "@model/settingsData"; useState,
import { Box, CssBaseline, ThemeProvider } from "@mui/material"; } from "react";
import ScopedCssBaseline from "@mui/material/ScopedCssBaseline"; import { ErrorBoundary } from "react-error-boundary";
import useSWR from "swr";
import { SnackbarProvider } from "notistack";
import moment from "moment";
import {
Box,
ScopedCssBaseline,
CssBaseline,
ThemeProvider,
} from "@mui/material";
import { LocalizationProvider } from "@mui/x-date-pickers"; import { LocalizationProvider } from "@mui/x-date-pickers";
import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment"; import { AdapterMoment } from "@mui/x-date-pickers/AdapterMoment";
import { ruRU } from "@mui/x-date-pickers/locales"; import { ruRU } from "@mui/x-date-pickers/locales";
import ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import { ApologyPage } from "./ViewPublicationPage/ApologyPage";
import { QuizViewContext, createQuizViewStore } from "@/stores/quizView";
import { getQuizData } from "@/api/quizRelase";
import { QuizDataContext } from "@contexts/QuizDataContext";
import { RootContainerWidthContext } from "@contexts/RootContainerWidthContext";
import LoadingSkeleton from "@/ui_kit/LoadingSkeleton";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import { handleComponentError } from "@utils/handleComponentError"; import { handleComponentError } from "@utils/handleComponentError";
import lightTheme from "@utils/themes/light"; import lightTheme from "@utils/themes/light";
import moment from "moment";
import { SnackbarProvider } from "notistack";
import { startTransition, useEffect, useLayoutEffect, useRef, useState } from "react";
import { ErrorBoundary } from "react-error-boundary";
import useSWR from "swr";
import { ApologyPage } from "./ViewPublicationPage/ApologyPage";
import ViewPublicationPage from "./ViewPublicationPage/ViewPublicationPage";
import type { QuizSettings } from "@model/settingsData";
moment.locale("ru"); moment.locale("ru");
const localeText = ruRU.components.MuiLocalizationProvider.defaultProps.localeText; const localeText =
ruRU.components.MuiLocalizationProvider.defaultProps.localeText;
type Props = { type Props = {
quizSettings?: QuizSettings; quizSettings?: QuizSettings;
quizId: string; quizId: string;
preview?: boolean; preview?: boolean;
changeFaviconAndTitle?: boolean; changeFaviconAndTitle?: boolean;
className?: string; className?: string;
disableGlobalCss?: boolean; disableGlobalCss?: boolean;
}; };
function QuizAnswererInner({ quizSettings, quizId, preview = false, changeFaviconAndTitle = true, className, disableGlobalCss = false }: Props) { function QuizAnswererInner({
const [quizViewStore] = useState(createQuizViewStore); quizSettings,
const [rootContainerWidth, setRootContainerWidth] = useState<number>(() => window.innerWidth); quizId,
const rootContainerRef = useRef<HTMLDivElement>(null); preview = false,
const { data, error, isLoading } = useSWR(quizSettings ? null : ["quizData", quizId], params => getQuizData(params[1]), { changeFaviconAndTitle = true,
revalidateOnFocus: false, className,
revalidateOnReconnect: false, disableGlobalCss = false,
shouldRetryOnError: false, }: Props) {
refreshInterval: 0, const [quizViewStore] = useState(createQuizViewStore);
}); const [rootContainerWidth, setRootContainerWidth] = useState<number>(
() => window.innerWidth
);
const rootContainerRef = useRef<HTMLDivElement>(null);
const { data, error, isLoading } = useSWR(
quizSettings ? null : ["quizData", quizId],
(params) => getQuizData(params[1]),
{
revalidateOnFocus: false,
revalidateOnReconnect: false,
shouldRetryOnError: false,
refreshInterval: 0,
}
);
const vkMetrics = useVkMetricsGoals(
quizSettings?.settings.cfg.vkMetricsNumber
);
const yandexMetrics = useYandexMetricsGoals(
quizSettings?.settings.cfg.yandexMetricsNumber
);
useEffect(() => {
setTimeout(() => {
vkMetrics.quizOpened();
yandexMetrics.quizOpened();
}, 4000);
}, []);
useEffect(() => { useLayoutEffect(() => {
setTimeout(() => { if (rootContainerRef.current)
//@ts-ignore setRootContainerWidth(rootContainerRef.current.clientWidth);
let YM = window?.ym; }, []);
//@ts-ignore
let VP = window?._tmr;
if (YM !== undefined && quizSettings?.settings.cfg.yandexMetricNumber !== undefined) {
YM(
quizSettings.settings.cfg.yandexMetricNumber,
"reachGoal",
"penaquiz-start"
);
};
if (VP !== undefined && quizSettings?.settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: quizSettings.settings.cfg.vkMetricNumber,
goal: "penaquiz-start"
});
};
}, 4000)
}, [])
useLayoutEffect(() => { useEffect(() => {
if (rootContainerRef.current) setRootContainerWidth(rootContainerRef.current.clientWidth); const handleWindowResize = () => {
}, []); startTransition(() => {
if (rootContainerRef.current)
setRootContainerWidth(rootContainerRef.current.clientWidth);
});
};
window.addEventListener("resize", handleWindowResize);
useEffect(() => { return () => {
const handleWindowResize = () => { window.removeEventListener("resize", handleWindowResize);
startTransition(() => { };
if (rootContainerRef.current) setRootContainerWidth(rootContainerRef.current.clientWidth); }, []);
});
};
window.addEventListener("resize", handleWindowResize);
return () => { if (isLoading) return <LoadingSkeleton />;
window.removeEventListener("resize", handleWindowResize); if (error) return <ApologyPage error={error} />;
};
}, []);
if (isLoading) return <LoadingSkeleton />; quizSettings ??= data;
if (error) return <ApologyPage error={error} />; if (!quizSettings) throw new Error("Quiz data is null");
quizSettings ??= data; if (quizSettings.questions.length === 0)
if (!quizSettings) throw new Error("Quiz data is null"); return <ApologyPage error={new Error("No questions found")} />;
if (!quizId) return <ApologyPage error={new Error("No quiz id")} />;
if (quizSettings.questions.length === 0) return <ApologyPage error={new Error("No questions found")} />; const quizContainer = (
if (!quizId) return <ApologyPage error={new Error("No quiz id")} />; <Box
ref={rootContainerRef}
className={className}
sx={{
width: "100%",
height: "100%",
position: "relative",
}}
>
<ErrorBoundary
FallbackComponent={ApologyPage}
onError={handleComponentError}
>
<ViewPublicationPage />
</ErrorBoundary>
</Box>
);
const quizContainer = ( return (
<Box <QuizViewContext.Provider value={quizViewStore}>
ref={rootContainerRef} <RootContainerWidthContext.Provider value={rootContainerWidth}>
className={className} <QuizDataContext.Provider
sx={{ value={{ ...quizSettings, quizId, preview, changeFaviconAndTitle }}
width: "100%",
height: "100%",
position: "relative",
}}
> >
<ErrorBoundary {disableGlobalCss ? (
FallbackComponent={ApologyPage} <ScopedCssBaseline
onError={handleComponentError} sx={{
height: "100%",
width: "100%",
backgroundColor: "transparent",
}}
> >
<ViewPublicationPage /> {quizContainer}
</ErrorBoundary> </ScopedCssBaseline>
</Box> ) : (
); <CssBaseline>{quizContainer}</CssBaseline>
)}
return ( </QuizDataContext.Provider>
<QuizViewContext.Provider value={quizViewStore}> </RootContainerWidthContext.Provider>
<RootContainerWidthContext.Provider value={rootContainerWidth}> </QuizViewContext.Provider>
<QuizDataContext.Provider value={{ ...quizSettings, quizId, preview, changeFaviconAndTitle }}> );
{disableGlobalCss ? (
<ScopedCssBaseline
sx={{
height: "100%",
width: "100%",
backgroundColor: "transparent",
}}
>
{quizContainer}
</ScopedCssBaseline>
) : (
<CssBaseline>
{quizContainer}
</CssBaseline>
)}
</QuizDataContext.Provider>
</RootContainerWidthContext.Provider>
</QuizViewContext.Provider>
);
} }
export default function QuizAnswerer(props: Props) { export default function QuizAnswerer(props: Props) {
return (
return ( <LocalizationProvider
<LocalizationProvider dateAdapter={AdapterMoment} adapterLocale="ru" localeText={localeText}> dateAdapter={AdapterMoment}
<ThemeProvider theme={lightTheme}> adapterLocale="ru"
<SnackbarProvider localeText={localeText}
preventDuplicate={true} >
style={{ backgroundColor: lightTheme.palette.brightPurple.main }} <ThemeProvider theme={lightTheme}>
> <SnackbarProvider
<QuizAnswererInner {...props} /> preventDuplicate={true}
</SnackbarProvider> style={{ backgroundColor: lightTheme.palette.brightPurple.main }}
</ThemeProvider> >
</LocalizationProvider> <QuizAnswererInner {...props} />
); </SnackbarProvider>
</ThemeProvider>
</LocalizationProvider>
);
} }

@ -1,26 +1,31 @@
import { useEffect, useRef, useState, } from "react"; import { useEffect, useRef, useState } from "react";
import { Box, Button, Link, Typography, useTheme, } from "@mui/material"; import { Box, Button, Link, Typography, useTheme } from "@mui/material";
import CustomCheckbox from "@ui_kit/CustomCheckbox.tsx";
import { DESIGN_LIST } from "@utils/designList.ts";
import { sendFC, SendFCParams } from "@api/quizRelase.ts";
import { useQuizData } from "@contexts/QuizDataContext.ts";
import { NameplateLogo } from "@icons/NameplateLogo.tsx";
import { QuizQuestionResult } from "@model/questionTypes/result.ts";
import { AnyTypedQuizQuestion } from "@model/questionTypes/shared.ts";
import { quizThemes } from "@utils/themes/Publication/themePublication.ts";
import { enqueueSnackbar } from "notistack"; import { enqueueSnackbar } from "notistack";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext.ts";
import { import CustomCheckbox from "@ui_kit/CustomCheckbox";
import { Inputs } from "@/components/ViewPublicationPage/ContactForm/Inputs/Inputs";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import { useQuizData } from "@contexts/QuizDataContext";
import { sendFC, SendFCParams } from "@api/quizRelase";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import { EMAIL_REGEXP } from "@utils/emailRegexp";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { DESIGN_LIST } from "@utils/designList";
import { NameplateLogo } from "@icons/NameplateLogo";
import type {
FormContactFieldData, FormContactFieldData,
FormContactFieldName, FormContactFieldName,
} from "@model/settingsData.ts"; } from "@model/settingsData";
import { import type { QuizQuestionResult } from "@model/questionTypes/result";
Inputs import type { AnyTypedQuizQuestion } from "@model/questionTypes/shared";
} from "@/components/ViewPublicationPage/ContactForm/Inputs/Inputs.tsx";
import { EMAIL_REGEXP } from "@utils/emailRegexp.tsx";
type Props = { type Props = {
currentQuestion: AnyTypedQuizQuestion; currentQuestion: AnyTypedQuizQuestion;
@ -44,6 +49,9 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
const isMobile = useRootContainerSize() < 850; const isMobile = useRootContainerSize() < 850;
const isTablet = useRootContainerSize() < 1000; const isTablet = useRootContainerSize() < 1000;
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
useEffect(() => { useEffect(() => {
function handleResize() { function handleResize() {
setScreenHeight(window.innerHeight); setScreenHeight(window.innerHeight);
@ -60,18 +68,18 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
currentQuestion.type === "result" currentQuestion.type === "result"
? currentQuestion ? currentQuestion
: questions.find((question): question is QuizQuestionResult => { : questions.find((question): question is QuizQuestionResult => {
if (settings?.cfg.haveRoot) { if (settings?.cfg.haveRoot) {
return ( return (
question.type === "result" && question.type === "result" &&
question.content.rule.parentId === currentQuestion.content.id question.content.rule.parentId === currentQuestion.content.id
); );
} else { } else {
return ( return (
question.type === "result" && question.type === "result" &&
question.content.rule.parentId === "line" question.content.rule.parentId === "line"
); );
} }
}); });
if (!resultQuestion) throw new Error("Result question not found"); if (!resultQuestion) throw new Error("Result question not found");
@ -142,24 +150,8 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
sessions[quizId] = Date.now(); sessions[quizId] = Date.now();
localStorage.setItem("sessions", JSON.stringify(sessions)); localStorage.setItem("sessions", JSON.stringify(sessions));
//@ts-ignore vkMetrics.contactsFormFilled();
let YM = window?.ym; yandexMetrics.contactsFormFilled();
//@ts-ignore
let 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) { } catch (e) {
enqueueSnackbar("повторите попытку позже"); enqueueSnackbar("повторите попытку позже");
} }
@ -171,25 +163,9 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
setFire(false); setFire(false);
} }
useEffect(() => { useEffect(() => {
//@ts-ignore vkMetrics.contactsFormOpened();
let YM = window?.ym; yandexMetrics.contactsFormOpened();
//@ts-ignore }, []);
let 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 ( return (
<Box <Box
@ -213,8 +189,9 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
settings.cfg.design && !isMobile settings.cfg.design && !isMobile
? quizThemes[settings.cfg.theme].isLight ? quizThemes[settings.cfg.theme].isLight
? `url(${DESIGN_LIST[settings.cfg.theme]})` ? `url(${DESIGN_LIST[settings.cfg.theme]})`
: `linear-gradient(90deg, #272626, transparent), url(${DESIGN_LIST[settings.cfg.theme] : `linear-gradient(90deg, #272626, transparent), url(${
})` DESIGN_LIST[settings.cfg.theme]
})`
: null, : null,
}} }}
> >
@ -240,7 +217,7 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
justifyContent: "center", justifyContent: "center",
borderRight: isMobile ? undefined : "1px solid #9A9AAF80", borderRight: isMobile ? undefined : "1px solid #9A9AAF80",
margin: isMobile ? 0 : "40px 0", margin: isMobile ? 0 : "40px 0",
padding: isMobile ? "0" : "0 40px" padding: isMobile ? "0" : "0 40px",
}} }}
> >
<Box <Box
@ -290,7 +267,11 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
justifyContent: "center", justifyContent: "center",
flexDirection: "column", flexDirection: "column",
backgroundColor: theme.palette.background.default, backgroundColor: theme.palette.background.default,
p: isMobile ? "0 20px" : isTablet ? "0px 40px 30px 60px" : "125px 60px 30px 60px", p: isMobile
? "0 20px"
: isTablet
? "0px 40px 30px 60px"
: "125px 60px 30px 60px",
}} }}
> >
<Box <Box
@ -298,7 +279,7 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
display: "flex", display: "flex",
flexDirection: "column", flexDirection: "column",
mt: isMobile ? "10px" : "20px", mt: isMobile ? "10px" : "20px",
mb: "20px" mb: "20px",
}} }}
> >
<Inputs <Inputs
@ -329,7 +310,10 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
colorIcon={theme.palette.primary.main} colorIcon={theme.palette.primary.main}
sx={{ marginRight: "0" }} sx={{ marginRight: "0" }}
/> />
<Typography sx={{ color: theme.palette.text.primary, lineHeight: "18.96px" }} fontSize={"16px"} > <Typography
sx={{ color: theme.palette.text.primary, lineHeight: "18.96px" }}
fontSize={"16px"}
>
С&ensp; С&ensp;
<Link href={"https://shub.pena.digital/ppdd"} target="_blank"> <Link href={"https://shub.pena.digital/ppdd"} target="_blank">
Положением об обработке персональных данных{" "} Положением об обработке персональных данных{" "}
@ -361,7 +345,6 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
border: "1px solid #9A9AAF", border: "1px solid #9A9AAF",
color: "#9A9AAF", color: "#9A9AAF",
}, },
}} }}
> >
{settings.cfg.formContact?.button || "Получить результаты"} {settings.cfg.formContact?.button || "Получить результаты"}
@ -371,8 +354,9 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
<Box <Box
component={Link} component={Link}
target={"_blank"} target={"_blank"}
href={`https://${window.location.hostname.includes("s") ? "s" : "" href={`https://${
}quiz.pena.digital/squiz/quiz/logo?q=${quizId}`} window.location.hostname.includes("s") ? "s" : ""
}quiz.pena.digital/squiz/quiz/logo?q=${quizId}`}
sx={{ sx={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
@ -382,7 +366,7 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
textDecoration: "none", textDecoration: "none",
position: "absolute", position: "absolute",
bottom: 0, bottom: 0,
left: isMobile ? "28%" : undefined left: isMobile ? "28%" : undefined,
}} }}
> >
<NameplateLogo <NameplateLogo
@ -411,4 +395,3 @@ export const ContactForm = ({ currentQuestion, onShowResult }: Props) => {
</Box> </Box>
); );
}; };

@ -1,15 +1,21 @@
import { useEffect } from "react";
import { Box, Button, Link, Typography, useTheme } from "@mui/material"; import { Box, Button, Link, Typography, useTheme } from "@mui/material";
import { NameplateLogo } from "@icons/NameplateLogo"; import { useQuizViewStore } from "@/stores/quizView";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
import { useQuizData } from "@contexts/QuizDataContext";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import { DESIGN_LIST } from "@/utils/designList";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import YoutubeEmbedIframe from "./tools/YoutubeEmbedIframe"; import YoutubeEmbedIframe from "./tools/YoutubeEmbedIframe";
import { useQuizData } from "@contexts/QuizDataContext"; import { NameplateLogo } from "@icons/NameplateLogo";
import { quizThemes } from "@utils/themes/Publication/themePublication";
import { useRootContainerSize } from "../../contexts/RootContainerWidthContext"; import type { QuizQuestionResult } from "@/model/questionTypes/result";
import type { QuizQuestionResult } from "../../model/questionTypes/result";
import { useQuizViewStore } from "@/stores/quizView";
import { DESIGN_LIST } from "@/utils/designList";
import { useEffect } from "react";
type ResultFormProps = { type ResultFormProps = {
resultQuestion: QuizQuestionResult; resultQuestion: QuizQuestionResult;
@ -24,27 +30,13 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
(state) => state.setCurrentQuizStep (state) => state.setCurrentQuizStep
); );
const spec = settings.cfg.spec; const spec = settings.cfg.spec;
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
useEffect(() => { useEffect(() => {
//@ts-ignore vkMetrics.resultShown(resultQuestion.id);
let YM = window?.ym; yandexMetrics.resultShown(resultQuestion.id);
//@ts-ignore }, []);
let VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
`penaquiz-result-{${resultQuestion.id}}`
);
};
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: `penaquiz-result-{${resultQuestion.id}}`
});
};
}, [])
return ( return (
<Box <Box
@ -197,8 +189,9 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
<Box <Box
component={Link} component={Link}
target={"_blank"} target={"_blank"}
href={`https://${window.location.hostname.includes("s") ? "s" : "" href={`https://${
}quiz.pena.digital/squiz/quiz/logo?q=${quizId}`} window.location.hostname.includes("s") ? "s" : ""
}quiz.pena.digital/squiz/quiz/logo?q=${quizId}`}
sx={{ sx={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
@ -216,7 +209,6 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
: "#F5F7FF", : "#F5F7FF",
}} }}
/> />
</Box> </Box>
)} )}
</Box> </Box>
@ -233,8 +225,8 @@ export const ResultForm = ({ resultQuestion }: ResultFormProps) => {
p: p:
(settings.cfg.resultInfo.showResultForm === "before" && (settings.cfg.resultInfo.showResultForm === "before" &&
!settings.cfg.score) || !settings.cfg.score) ||
(settings.cfg.resultInfo.showResultForm === "after" && (settings.cfg.resultInfo.showResultForm === "after" &&
resultQuestion.content.redirect) resultQuestion.content.redirect)
? "20px" ? "20px"
: "0", : "0",
}} }}

@ -1,15 +1,14 @@
import { import {
Box, Box,
Button, Button,
ButtonBase, ButtonBase,
Link, Link,
Paper, Paper,
Typography, Typography,
useTheme, useTheme,
} from "@mui/material"; } from "@mui/material";
import { QuizPreviewLayoutByType } from "./QuizPreviewLayoutByType"; import { QuizPreviewLayoutByType } from "./QuizPreviewLayoutByType";
import YoutubeEmbedIframe from "../tools/YoutubeEmbedIframe";
import { useQuizData } from "@contexts/QuizDataContext"; import { useQuizData } from "@contexts/QuizDataContext";
import { useRootContainerSize } from "@contexts/RootContainerWidthContext"; import { useRootContainerSize } from "@contexts/RootContainerWidthContext";
@ -21,450 +20,509 @@ import { NameplateLogo } from "@icons/NameplateLogo";
import { useQuizViewStore } from "@/stores/quizView"; import { useQuizViewStore } from "@/stores/quizView";
import { DESIGN_LIST } from "@/utils/designList"; import { DESIGN_LIST } from "@/utils/designList";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
import YoutubeEmbedIframe from "../tools/YoutubeEmbedIframe";
export const StartPageViewPublication = () => { export const StartPageViewPublication = () => {
const theme = useTheme(); const theme = useTheme();
const { settings, show_badge, quizId, questions } = useQuizData(); const { settings, show_badge, quizId, questions } = useQuizData();
const { isMobileDevice } = useUADevice(); const { isMobileDevice } = useUADevice();
const setCurrentQuizStep = useQuizViewStore(state => state.setCurrentQuizStep); const setCurrentQuizStep = useQuizViewStore(
(state) => state.setCurrentQuizStep
);
const size = useRootContainerSize(); const size = useRootContainerSize();
const isMobile = size < 700; const isMobile = size < 700;
const isTablet = size >= 700 && size < 1100; const isTablet = size >= 700 && size < 1100;
console.log(settings)
const handleCopyNumber = () => {
navigator.clipboard.writeText(settings.cfg.info.phonenumber);
//@ts-ignore
let YM = window?.ym;
//@ts-ignore
let VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
"penaquiz-phone"
);
};
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: "penaquiz-phone"
});
};
};
const background = const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
settings.cfg.startpage.background.type === "image" ? ( const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
<img
src={
settings.cfg.startpage.background.desktop ||
DESIGN_LIST[settings.cfg.theme] ||
""
}
alt=""
style={{
display: "block",
width:
isMobile || settings.cfg.startpageType === "expanded"
? "100%"
: undefined,
height: "100%",
minWidth: "100%",
maxHeight: "100%",
objectFit: "cover",
overflow: "hidden",
}}
/>
) : settings.cfg.startpage.background.type === "video" ? (
settings.cfg.startpage.background.video ? (
<YoutubeEmbedIframe
videoUrl={settings.cfg.startpage.background.video}
containerSX={{
width: settings.cfg.startpageType === "centered" ? "550px" : "100%",
height:
settings.cfg.startpageType === "centered" ? "275px" : "100%",
borderRadius:
settings.cfg.startpageType === "centered" ? "10px" : "0",
overflow: "hidden",
"& iframe": {
width: "100%",
height: "100%",
transform:
settings.cfg.startpageType === "centered"
? ""
: settings.cfg.startpageType === "expanded"
? "scale(1.5)"
: "scale(2.4)",
},
}}
/>
) : null
) : null;
const quizHeaderBlock = (<Box const handleCopyNumber = () => {
sx={{ navigator.clipboard.writeText(settings.cfg.info.phonenumber);
margin:
settings.cfg.startpageType === "centered" ? "0 auto" : null, vkMetrics.phoneNumberOpened();
yandexMetrics.phoneNumberOpened();
};
const background =
settings.cfg.startpage.background.type === "image" ? (
<img
src={
settings.cfg.startpage.background.desktop ||
DESIGN_LIST[settings.cfg.theme] ||
""
}
alt=""
style={{
display: "block",
width:
isMobile || settings.cfg.startpageType === "expanded"
? "100%"
: undefined,
height: "100%",
minWidth: "100%",
maxHeight: "100%",
objectFit: "cover",
overflow: "hidden",
}} }}
/>
) : settings.cfg.startpage.background.type === "video" ? (
settings.cfg.startpage.background.video ? (
<YoutubeEmbedIframe
videoUrl={settings.cfg.startpage.background.video}
containerSX={{
width: settings.cfg.startpageType === "centered" ? "550px" : "100%",
height:
settings.cfg.startpageType === "centered" ? "275px" : "100%",
borderRadius:
settings.cfg.startpageType === "centered" ? "10px" : "0",
overflow: "hidden",
"& iframe": {
width: "100%",
height: "100%",
transform:
settings.cfg.startpageType === "centered"
? ""
: settings.cfg.startpageType === "expanded"
? "scale(1.5)"
: "scale(2.4)",
},
}}
/>
) : null
) : null;
const quizHeaderBlock = (
<Box
sx={{
margin: settings.cfg.startpageType === "centered" ? "0 auto" : null,
}}
> >
<Box <Box
sx={{ sx={{
display: "flex", display: "flex",
alignItems: "center", alignItems: "center",
flexWrap: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "nowrap" : "wrap", flexWrap:
gap: isMobile ? "20px" : "30px", settings.cfg.startpageType === "expanded" &&
mb: settings.cfg.startpageType === "centered" ? isMobile ? "20px" : "25px" : settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && !isMobile ? 0 : "7px", settings.cfg.startpage.position === "center"
justifyContent: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && isMobile ? "center" : undefined ? "nowrap"
: "wrap",
gap: isMobile ? "20px" : "30px",
mb:
settings.cfg.startpageType === "centered"
? isMobile
? "20px"
: "25px"
: settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center" &&
!isMobile
? 0
: "7px",
justifyContent:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center" &&
isMobile
? "center"
: undefined,
}}
>
{settings.cfg.startpage.logo && (
<img
src={settings.cfg.startpage.logo}
style={{
maxHeight: isMobile ? "30px" : "40px",
maxWidth: isMobile ? "100px" : "110px",
objectFit: "cover",
}} }}
alt=""
/>
)}
<Typography
sx={{
fontSize: "12px",
color:
settings.cfg.startpageType === "expanded"
? "white"
: theme.palette.text.primary,
wordBreak:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center"
? "normal"
: "break-word",
}}
> >
{settings.cfg.startpage.logo && {settings.cfg.info.orgname}
<img </Typography>
src={settings.cfg.startpage.logo} </Box>
style={{ </Box>
maxHeight: isMobile ? "30px" : "40px", );
maxWidth: isMobile ? "100px" : "110px",
objectFit: "cover", const PenaBadge = (
}} <Box
alt="" component={Link}
/> target={"_blank"}
} href={`https://${
<Typography window.location.hostname.includes("s") ? "s" : ""
sx={{ }quiz.pena.digital/squiz/quiz/logo?q=${quizId}`}
fontSize: "12px", sx={{
color: display: "flex",
settings.cfg.startpageType === "expanded" alignItems: "center",
? "white" gap: "7px",
: theme.palette.text.primary, textDecoration: "none",
wordBreak: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "normal" : "break-word", marginLeft:
}} settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center" &&
!isTablet &&
!isMobile
? "61px"
: undefined,
}}
>
<NameplateLogo
style={{
fontSize: "23px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: quizThemes[settings.cfg.theme].isLight
? "#151515"
: "#FFFFFF",
}}
/>
{/*<Typography*/}
{/* sx={{*/}
{/* fontSize: "13px",*/}
{/* color:*/}
{/* settings.cfg.startpageType === "expanded"*/}
{/* ? "#F5F7FF"*/}
{/* : quizThemes[settings.cfg.theme].isLight*/}
{/* ? "#4D4D4D"*/}
{/* : "#F5F7FF",*/}
{/* whiteSpace: "nowrap",*/}
{/* }}*/}
{/*>*/}
{/* Сделано на PenaQuiz*/}
{/*</Typography>*/}
</Box>
);
const realQuestionsCount = questions.filter(
(question) => question.type !== null && question.type !== "result"
).length;
const onQuizStart = () => {
setCurrentQuizStep("question");
vkMetrics.firstPageOpened();
yandexMetrics.firstPageOpened();
};
const onSiteClick = () => {
vkMetrics.emailOpened();
yandexMetrics.emailOpened();
location.href = (
settings.cfg.info.site.includes("https")
? settings.cfg.info.site
: `https://${settings.cfg.info.site}`
).replace(/\s+/g, "");
};
return (
<Paper
className="settings-preview-draghandle"
sx={{
borderRadius: 0,
height: "100%",
width: "100%",
background:
settings.cfg.startpageType === "expanded"
? settings.cfg.startpage.position === "left" ||
(isMobile && settings.cfg.startpage.position === "right")
? "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%)"
: settings.cfg.startpage.position === "center"
? "linear-gradient(0deg, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%)"
: "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%)"
: theme.palette.background.default,
color: settings.cfg.startpageType === "expanded" ? "white" : "black",
}}
>
<QuizPreviewLayoutByType
quizHeaderBlock={quizHeaderBlock}
quizMainBlock={
<>
<Box
sx={{
display: "flex",
flexDirection: "column",
justifyContent:
settings.cfg.startpageType === "standard" && isMobile
? "start"
: "center",
flexGrow: settings.cfg.startpageType === "centered" ? 0 : 1,
alignItems:
settings.cfg.startpageType === "centered"
? "center"
: settings.cfg.startpageType === "expanded"
? settings.cfg.startpage.position === "center"
? "center"
: "start"
: "start",
marginTop:
settings.cfg.startpageType === "centered"
? "30px"
: isMobile
? "0px"
: "5px",
maxWidth: isMobile
? "100%"
: settings.cfg.startpageType === "centered"
? "700px"
: isTablet &&
settings.cfg.startpageType !== "expanded" &&
settings.cfg.startpage.position !== "center"
? "380px"
: "531px",
}}
> >
{settings.cfg.info.orgname} <Typography
</Typography> sx={{
</Box> fontWeight: "700",
</Box>) fontSize: isMobile ? "24px" : "27px",
fontStyle: "normal",
const PenaBadge = ( fontStretch: "normal",
<Box lineHeight: isMobile ? "26.4px" : "normal",
component={Link} overflowWrap: "break-word",
target={"_blank"} width: "100%",
href={ textAlign:
`https://${window.location.hostname.includes("s") ? "s" : ""}quiz.pena.digital/squiz/quiz/logo?q=${quizId}` settings.cfg.startpageType === "centered" ||
} settings.cfg.startpage.position === "center"
sx={{ ? "center"
display: "flex", : "-moz-initial",
alignItems: "center", color:
gap: "7px",
textDecoration: "none",
marginLeft: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && !isTablet && !isMobile ? "61px" : undefined
}}
>
<NameplateLogo
style={{
fontSize: "23px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: quizThemes[settings.cfg.theme].isLight
? "#151515"
: "#FFFFFF",
}}
/>
{/*<Typography*/}
{/* sx={{*/}
{/* fontSize: "13px",*/}
{/* color:*/}
{/* settings.cfg.startpageType === "expanded"*/}
{/* ? "#F5F7FF"*/}
{/* : quizThemes[settings.cfg.theme].isLight*/}
{/* ? "#4D4D4D"*/}
{/* : "#F5F7FF",*/}
{/* whiteSpace: "nowrap",*/}
{/* }}*/}
{/*>*/}
{/* Сделано на PenaQuiz*/}
{/*</Typography>*/}
</Box>)
const realQuestionsCount = questions.filter((question) => question.type !== null && question.type !== "result").length;
return (
<Paper
className="settings-preview-draghandle"
sx={{
borderRadius: 0,
height: "100%",
width: "100%",
background:
settings.cfg.startpageType === "expanded" settings.cfg.startpageType === "expanded"
? settings.cfg.startpage.position === "left" || isMobile && settings.cfg.startpage.position === "right" ? "white"
? "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%)" : theme.palette.text.primary,
: settings.cfg.startpage.position === "center" }}
? "linear-gradient(0deg, rgba(39, 38, 38, 0.95) 7.66%, rgba(42, 42, 46, 0.85) 42.12%, rgba(51, 54, 71, 0.4) 100%)" >
: "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%)" {settings.name}
: theme.palette.background.default, </Typography>
<Typography
color: settings.cfg.startpageType === "expanded" ? "white" : "black", sx={{
}} fontSize: isMobile ? "16px" : "17px",
> fontWeight: "400",
<QuizPreviewLayoutByType lineHeight: isMobile ? "19.2px" : "normal",
quizHeaderBlock={quizHeaderBlock margin: "12px 0 30px",
overflowWrap: "break-word",
width: "100%",
textAlign:
settings.cfg.startpageType === "centered" ||
settings.cfg.startpage.position === "center"
? "center"
: "-moz-initial",
color:
settings.cfg.startpageType === "expanded"
? "white"
: theme.palette.text.primary,
}}
>
{settings.cfg.startpage.description}
</Typography>
<Box
width={
settings.cfg.startpageType === "standard" ? "100%" : "auto"
} }
quizMainBlock={ >
<> <Button
<Box variant="contained"
sx={{ disabled={realQuestionsCount === 0}
display: "flex", sx={{
flexDirection: "column", fontSize: "18px",
justifyContent: settings.cfg.startpageType === "standard" && isMobile ? "start" : "center", padding: "10px 20px",
flexGrow: settings.cfg.startpageType === "centered" ? 0 : 1, width: "auto",
alignItems: background: theme.palette.primary.main,
settings.cfg.startpageType === "centered" borderRadius: "12px",
? "center" }}
: settings.cfg.startpageType === "expanded" onClick={onQuizStart}
? settings.cfg.startpage.position === "center" >
? "center" {settings.cfg.startpage.button.trim()
: "start" ? settings.cfg.startpage.button
: "start", : "Пройти тест"}
marginTop: settings.cfg.startpageType === "centered" ? "30px" : isMobile ? "0px" : "5px", </Button>
maxWidth: isMobile ? "100%" : settings.cfg.startpageType === "centered" ? "700px" : isTablet && settings.cfg.startpageType !== "expanded" && settings.cfg.startpage.position !== "center" ? "380px" : "531px", </Box>
}} </Box>
> <Box
<Typography sx={{
sx={{ display: "flex",
fontWeight: "700", flexGrow:
fontSize: isMobile ? "24px" : "27px", settings.cfg.startpageType === "centered"
fontStyle: "normal", ? isMobile
fontStretch: "normal", ? 0
lineHeight: isMobile ? "26.4px" : "normal", : 1
overflowWrap: "break-word", : 0,
width: "100%", gap: isMobile ? "30px" : "40px",
textAlign: alignItems: "flex-end",
settings.cfg.startpageType === "centered" || justifyContent:
settings.cfg.startpage.position === "center" (settings.cfg.startpageType === "expanded" &&
? "center" settings.cfg.startpage.position === "center" &&
: "-moz-initial", isMobile) ||
color: (settings.cfg.startpageType === "centered" && isMobile)
settings.cfg.startpageType === "expanded" ? "center"
? "white" : "space-between",
: theme.palette.text.primary, width: "100%",
}} flexWrap:
> settings.cfg.startpageType === "expanded" &&
{settings.name} settings.cfg.startpage.position === "center"
</Typography> ? isMobile
<Typography ? "wrap-reverse"
sx={{ : "nowrap"
fontSize: isMobile ? "16px" : "17px", : "wrap",
fontWeight: "400", }}
lineHeight: isMobile ? "19.2px" : "normal", >
margin: "12px 0 30px", {settings.cfg.startpageType === "expanded" &&
overflowWrap: "break-word", settings.cfg.startpage.position === "center" &&
width: "100%", !isMobile &&
textAlign: quizHeaderBlock}
settings.cfg.startpageType === "centered" || <Box
settings.cfg.startpage.position === "center" sx={{
? "center" maxWidth: "300px",
: "-moz-initial", display:
color: (settings.cfg.startpageType === "centered" && isMobile) ||
settings.cfg.startpageType === "expanded" (settings.cfg.startpageType === "expanded" &&
? "white" settings.cfg.startpage.position === "center" &&
: theme.palette.text.primary, isMobile)
}} ? "flex"
> : "block",
{settings.cfg.startpage.description} flexDirection: "column",
</Typography> alignItems: "center",
<Box order:
width={ settings.cfg.startpageType === "expanded" &&
settings.cfg.startpageType === "standard" ? "100%" : "auto" settings.cfg.startpage.position === "center"
} ? "2"
> : "0",
<Button }}
variant="contained" >
disabled={realQuestionsCount === 0} {settings.cfg.info.site && (
sx={{ <ButtonBase onClick={onSiteClick}>
fontSize: "18px", <Typography
padding: "10px 20px", sx={{
width: "auto", lineHeight: "19px",
background: theme.palette.primary.main, fontSize: "16px",
borderRadius: "12px", textAlign:
}} settings.cfg.startpageType === "expanded" &&
onClick={() => { settings.cfg.startpage.position === "center" &&
setCurrentQuizStep("question") !isMobile
? "end"
: "none",
color: theme.palette.primary.main,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{settings.cfg.info.site}
</Typography>
</ButtonBase>
)}
{settings.cfg.info.clickable ? (
isMobileDevice ? (
<Link href={`tel:${settings.cfg.info.phonenumber}`}>
<Typography
sx={{
lineHeight: "19px",
textAlign:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center"
? "end"
: "none",
fontSize: "16px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
</Link>
) : (
<ButtonBase onClick={handleCopyNumber}>
<Typography
sx={{
textAlign:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center"
? "end"
: "none",
fontSize: "16px",
lineHeight: "19px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
</ButtonBase>
)
) : (
<Typography
sx={{
lineHeight: "19px",
textAlign:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center"
? "end"
: "none",
fontSize: "16px",
marginTop: "10px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
)}
<Typography
sx={{
lineHeight: "14px",
width: "100%",
overflowWrap: "break-word",
fontSize: "12px",
textAlign:
settings.cfg.startpageType === "expanded" &&
settings.cfg.startpage.position === "center"
? "end"
: "none",
maxHeight: "120px",
overflow: "auto",
marginTop: "10px",
"&::-webkit-scrollbar": { width: 0 },
color:
settings.cfg.startpageType === "expanded"
? "white"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.law}
</Typography>
</Box>
{show_badge && PenaBadge}
//@ts-ignore </Box>
let YM = window?.ym; </>
//@ts-ignore }
let VP = window?._tmr; backgroundBlock={background}
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) { startpageType={settings.cfg.startpageType}
YM( alignType={settings.cfg.startpage.position}
settings.cfg.yandexMetricNumber, />
"reachGoal", </Paper>
"penaquiz-startquiz" );
);
};
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: "penaquiz-startquiz"
});
};
}}
>
{settings.cfg.startpage.button.trim()
? settings.cfg.startpage.button
: "Пройти тест"}
</Button>
</Box>
</Box>
<Box
sx={{
display: "flex",
flexGrow:
settings.cfg.startpageType === "centered"
? isMobile
? 0
: 1
: 0,
gap: isMobile ? "30px" : "40px",
alignItems: "flex-end",
justifyContent: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && isMobile || settings.cfg.startpageType === "centered" && isMobile ? "center" : "space-between",
width: "100%",
flexWrap: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? isMobile ? "wrap-reverse" : "nowrap" : "wrap",
}}
>
{settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && !isMobile && quizHeaderBlock}
<Box sx={{
maxWidth: "300px",
display: settings.cfg.startpageType === "centered" && isMobile || settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && isMobile ? "flex" : "block",
flexDirection: "column",
alignItems: "center",
order: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "2" : "0"
}}>
{settings.cfg.info.site && (
<ButtonBase
onClick={async () => {
//@ts-ignore
let YM = window?.ym;
//@ts-ignore
let VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
await YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
"penaquiz-email"
);
};
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
await VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: "penaquiz-email"
});
};
location.href = (
settings.cfg.info.site.includes("https")
? settings.cfg.info.site
: `https://${settings.cfg.info.site}`
).replace(/\s+/g, '')
}}
>
<Typography
sx={{
lineHeight: "19px",
fontSize: "16px",
textAlign: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" && !isMobile ? "end" : "none",
color: theme.palette.primary.main,
overflow: "hidden",
textOverflow: "ellipsis",
whiteSpace: "nowrap",
}}
>
{settings.cfg.info.site}
</Typography>
</ButtonBase>
)}
{settings.cfg.info.clickable ? (
isMobileDevice ? (
<Link href={`tel:${settings.cfg.info.phonenumber}`}>
<Typography
sx={{
lineHeight: "19px",
textAlign: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "end" : "none",
fontSize: "16px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
</Link>
) : (
<ButtonBase onClick={handleCopyNumber}>
<Typography
sx={{
textAlign: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "end" : "none",
fontSize: "16px",
lineHeight: "19px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
</ButtonBase>
)
) : (
<Typography
sx={{
lineHeight: "19px",
textAlign: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "end" : "none",
fontSize: "16px",
marginTop: "10px",
color:
settings.cfg.startpageType === "expanded"
? "#FFFFFF"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.phonenumber}
</Typography>
)}
<Typography
sx={{
lineHeight: "14px",
width: "100%",
overflowWrap: "break-word",
fontSize: "12px",
textAlign: settings.cfg.startpageType === "expanded" && settings.cfg.startpage.position === "center" ? "end" : "none",
maxHeight: "120px",
overflow: "auto",
marginTop: "10px",
"&::-webkit-scrollbar": { width: 0 },
color:
settings.cfg.startpageType === "expanded"
? "white"
: theme.palette.text.primary,
}}
>
{settings.cfg.info.law}
</Typography>
</Box>
{show_badge && PenaBadge}
</Box>
</>
}
backgroundBlock={background}
startpageType={settings.cfg.startpageType}
alignType={settings.cfg.startpage.position}
/>
</Paper>
);
}; };

@ -1,23 +1,21 @@
import {sendAnswer} from "@api/quizRelase"; import { sendAnswer } from "@api/quizRelase";
import {useQuizData} from "@contexts/QuizDataContext"; import { useQuizData } from "@contexts/QuizDataContext";
import {ThemeProvider, Typography} from "@mui/material"; import { ThemeProvider, Typography } from "@mui/material";
import {useQuizViewStore} from "@stores/quizView"; import { useQuizViewStore } from "@stores/quizView";
import {useQuestionFlowControl} from "@utils/hooks/useQuestionFlowControl"; import { useQuestionFlowControl } from "@utils/hooks/useQuestionFlowControl";
import {notReachable} from "@utils/notReachable"; import { notReachable } from "@utils/notReachable";
import {quizThemes} from "@utils/themes/Publication/themePublication"; import { quizThemes } from "@utils/themes/Publication/themePublication";
import {enqueueSnackbar} from "notistack"; import { enqueueSnackbar } from "notistack";
import {ReactElement, useEffect} from "react"; import { ReactElement, useEffect } from "react";
import {Question} from "./Question"; import { Question } from "./Question";
import {ResultForm} from "./ResultForm"; import { ResultForm } from "./ResultForm";
import {StartPageViewPublication} from "./StartPageViewPublication"; import { StartPageViewPublication } from "./StartPageViewPublication";
import NextButton from "./tools/NextButton"; import NextButton from "./tools/NextButton";
import PrevButton from "./tools/PrevButton"; import PrevButton from "./tools/PrevButton";
import QuestionSelect from "./QuestionSelect"; import QuestionSelect from "./QuestionSelect";
import {useYandexMetrics} from "@/utils/hooks/useYandexMetrics"; import { useYandexMetrics } from "@/utils/hooks/metrics/useYandexMetrics";
import {useVKMetrics} from "@/utils/hooks/useVKMetrics"; import { useVKMetrics } from "@/utils/hooks/metrics/useVKMetrics";
import { import { ContactForm } from "@/components/ViewPublicationPage/ContactForm/ContactForm.tsx";
ContactForm
} from "@/components/ViewPublicationPage/ContactForm/ContactForm.tsx";
export default function ViewPublicationPage() { export default function ViewPublicationPage() {
const { const {
@ -39,8 +37,8 @@ export default function ViewPublicationPage() {
showResultAfterContactForm, showResultAfterContactForm,
setQuestion, setQuestion,
} = useQuestionFlowControl(); } = useQuestionFlowControl();
useYandexMetrics(settings?.cfg?.yandexMetricNumber); useYandexMetrics(settings?.cfg?.yandexMetricsNumber);
useVKMetrics(settings?.cfg?.vkMetricNumber); useVKMetrics(settings?.cfg?.vkMetricsNumber);
const isAnswer = answers.some( const isAnswer = answers.some(
(ans) => ans.questionId === currentQuestion?.id (ans) => ans.questionId === currentQuestion?.id
@ -75,7 +73,6 @@ export default function ViewPublicationPage() {
</ThemeProvider> </ThemeProvider>
); );
let quizStepElement: ReactElement; let quizStepElement: ReactElement;
switch (currentQuizStep) { switch (currentQuizStep) {
case "startpage": { case "startpage": {

8
lib/model/metrics.ts Normal file

@ -0,0 +1,8 @@
export type MetricsMessengers =
| "telegram"
| "viber"
| "whatsapp"
| "vkontakte"
| "messenger"
| "skype"
| "instagram";

@ -108,8 +108,8 @@ export interface QuizConfig {
law?: string; law?: string;
}; };
meta: string; meta: string;
yandexMetricNumber: number | undefined; yandexMetricsNumber: number | undefined;
vkMetricNumber: number | undefined; vkMetricsNumber: number | undefined;
} }
export type FormContactFieldName = export type FormContactFieldName =

@ -1,17 +1,17 @@
import { useEffect } from "react"; import { useEffect } from "react";
export const useVKMetrics = (vkMetricNumber: number | undefined) => { export const useVKMetrics = (vkMetricsNumber: number | undefined) => {
useEffect(() => { useEffect(() => {
if ( if (
vkMetricNumber && vkMetricsNumber &&
typeof vkMetricNumber === "number" && typeof vkMetricsNumber === "number" &&
!Number.isNaN(vkMetricNumber) !Number.isNaN(vkMetricsNumber)
) { ) {
const script = document.createElement("script"); const script = document.createElement("script");
script.type = "text/javascript"; script.type = "text/javascript";
script.innerHTML = ` script.innerHTML = `
var _tmr = window._tmr || (window._tmr = []); var _tmr = window._tmr || (window._tmr = []);
_tmr.push({id: "${vkMetricNumber}", type: "pageView", start: (new Date()).getTime()}); _tmr.push({id: "${vkMetricsNumber}", type: "pageView", start: (new Date()).getTime()});
(function (d, w, id) { (function (d, w, id) {
if (d.getElementById(id)) return; if (d.getElementById(id)) return;
var ts = d.createElement("script"); ts.type = "text/javascript"; ts.async = true; ts.id = id; var ts = d.createElement("script"); ts.type = "text/javascript"; ts.async = true; ts.id = id;
@ -23,8 +23,8 @@ export const useVKMetrics = (vkMetricNumber: number | undefined) => {
document.body.appendChild(script); document.body.appendChild(script);
const noscript = document.createElement("noscript"); const noscript = document.createElement("noscript");
noscript.innerHTML = `<div><img src="https://top-fwz1.mail.ru/counter?id=${vkMetricNumber};js=na" style="position:absolute;left:-9999px;" alt="Top.Mail.Ru" /></div>`; noscript.innerHTML = `<div><img src="https://top-fwz1.mail.ru/counter?id=${vkMetricsNumber};js=na" style="position:absolute;left:-9999px;" alt="Top.Mail.Ru" /></div>`;
document.body.appendChild(noscript); document.body.appendChild(noscript);
} }
}, [vkMetricNumber]); }, [vkMetricsNumber]);
}; };

@ -1,21 +1,14 @@
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
type VkMetric = { import type { MetricsMessengers } from "@model/metrics";
type MetricsGoal = {
type: "reachGoal"; type: "reachGoal";
id: number; id: number;
goal: string; goal: string;
}; };
type ExtendedWindow = Window & { _tmp?: VkMetric[] }; type ExtendedWindow = Window & { _tmp?: MetricsGoal[] };
type Messenger =
| "telegram"
| "viber"
| "whatsapp"
| "vkontakte"
| "messenger"
| "skype"
| "instagram";
const sendMetrics = (vkPixelId: number | undefined, goal: string) => { const sendMetrics = (vkPixelId: number | undefined, goal: string) => {
if (vkPixelId) { if (vkPixelId) {
@ -27,7 +20,7 @@ const sendMetrics = (vkPixelId: number | undefined, goal: string) => {
} }
}; };
export const useVkMetricGoals = (vkPixelId: number | undefined) => { export const useVkMetricsGoals = (vkPixelId: number | undefined) => {
const [vkId, setVkId] = useState<number | undefined>(undefined); const [vkId, setVkId] = useState<number | undefined>(undefined);
useEffect(() => { useEffect(() => {
@ -46,16 +39,17 @@ export const useVkMetricGoals = (vkPixelId: number | undefined) => {
// Посетитель кликнул по email на стартовой странице // Посетитель кликнул по email на стартовой странице
emailOpened: () => sendMetrics(vkId, "penaquiz-email"), emailOpened: () => sendMetrics(vkId, "penaquiz-email"),
// Посетитель увидел определенный результат (id - айдишник вопроса с типом result) // Посетитель увидел определенный результат (id - айдишник вопроса с типом result)
resultShown: (resultId: string) => sendMetrics(vkId, `penaquiz-result-${resultId}`), resultShown: (resultId: string) =>
sendMetrics(vkId, `penaquiz-result-${resultId}`),
// Посетитель дошёл до формы контактов // Посетитель дошёл до формы контактов
contactsFormOpened: () => sendMetrics(vkId, "penaquiz-form"), contactsFormOpened: () => sendMetrics(vkId, "penaquiz-form"),
// Посетитель заполнил форму контактов // Посетитель заполнил форму контактов
contactsFormFilled: () => sendMetrics(vkId, "penaquiz-contacts"), contactsFormFilled: () => sendMetrics(vkId, "penaquiz-contacts"),
// Посетитель отправил заявку с мессенджером // Посетитель отправил заявку с мессенджером
messengerRequestSended: (messenger: Messenger) => messengerRequestSended: (messenger: MetricsMessengers) =>
sendMetrics(vkId, `marquiz-messengers-${messenger}`), sendMetrics(vkId, `penaquiz-messengers-${messenger}`),
// Посетитель прошёл вопрос // Посетитель прошёл вопрос
questionPassed: (questionId: string) => questionPassed: (questionId: string) =>
sendMetrics(vkId, `marquiz-step${questionId}`), sendMetrics(vkId, `penaquiz-step${questionId}`),
}; };
}; };

@ -1,11 +1,11 @@
import { useEffect } from "react"; import { useEffect } from "react";
export const useYandexMetrics = (yandexMetricNumber: number | undefined) => { export const useYandexMetrics = (yandexMetricsNumber: number | undefined) => {
useEffect(() => { useEffect(() => {
if ( if (
yandexMetricNumber && yandexMetricsNumber &&
typeof yandexMetricNumber === "number" && typeof yandexMetricsNumber === "number" &&
!Number.isNaN(yandexMetricNumber) !Number.isNaN(yandexMetricsNumber)
) { ) {
const script = document.createElement("script"); const script = document.createElement("script");
script.type = "text/javascript"; script.type = "text/javascript";
@ -16,7 +16,7 @@ export const useYandexMetrics = (yandexMetricNumber: number | undefined) => {
k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)}) k=e.createElement(t),a=e.getElementsByTagName(t)[0],k.async=1,k.src=r,a.parentNode.insertBefore(k,a)})
(window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym"); (window, document, "script", "https://mc.yandex.ru/metrika/tag.js", "ym");
ym(${yandexMetricNumber}, "init", { ym(${yandexMetricsNumber}, "init", {
clickmap:true, clickmap:true,
trackLinks:true, trackLinks:true,
accurateTrackBounce:true, accurateTrackBounce:true,
@ -27,8 +27,8 @@ export const useYandexMetrics = (yandexMetricNumber: number | undefined) => {
document.body.appendChild(script); document.body.appendChild(script);
const noscript = document.createElement("noscript"); const noscript = document.createElement("noscript");
noscript.innerHTML = `<div><img src="https://mc.yandex.ru/watch/${yandexMetricNumber}" style="position:absolute; left:-9999px;" alt="" /></div>`; noscript.innerHTML = `<div><img src="https://mc.yandex.ru/watch/${yandexMetricsNumber}" style="position:absolute; left:-9999px;" alt="" /></div>`;
document.body.appendChild(noscript); document.body.appendChild(noscript);
} }
}, [yandexMetricNumber]); }, [yandexMetricsNumber]);
}; };

@ -0,0 +1,47 @@
import { useEffect, useState } from "react";
import type { MetricsMessengers } from "@model/metrics";
type ExtendedWindow = Window & {
ym?: (id: number, type: string, goal: string) => void;
};
const sendMetrics = (yandexMetricsId: number | undefined, goal: string) => {
if (yandexMetricsId) {
(window as ExtendedWindow).ym?.(yandexMetricsId, "reachGoal", goal);
}
};
export const useYandexMetricsGoals = (yandexMetricsId: number | undefined) => {
const [id, setId] = useState<number | undefined>(undefined);
useEffect(() => {
if (yandexMetricsId) {
setId(yandexMetricsId);
}
}, [yandexMetricsId]);
return {
// Посетитель открыл квиз
quizOpened: () => sendMetrics(id, "penaquiz-start"),
// Посетитель нажал на кнопку стартовой страницы
firstPageOpened: () => sendMetrics(id, "penaquiz-startquiz"),
// Посетитель кликнул по номеру телефона на стартовой странице
phoneNumberOpened: () => sendMetrics(id, "penaquiz-phone"),
// Посетитель кликнул по email на стартовой странице
emailOpened: () => sendMetrics(id, "penaquiz-email"),
// Посетитель увидел определенный результат (id - айдишник вопроса с типом result)
resultShown: (resultId: string) =>
sendMetrics(id, `penaquiz-result-${resultId}`),
// Посетитель дошёл до формы контактов
contactsFormOpened: () => sendMetrics(id, "penaquiz-form"),
// Посетитель заполнил форму контактов
contactsFormFilled: () => sendMetrics(id, "penaquiz-contacts"),
// Посетитель отправил заявку с мессенджером
messengerRequestSended: (messenger: MetricsMessengers) =>
sendMetrics(id, `penaquiz-messengers-${messenger}`),
// Посетитель прошёл вопрос
questionPassed: (questionId: string) =>
sendMetrics(id, `penaquiz-step${questionId}`),
};
};

@ -1,213 +1,262 @@
import { useQuizViewStore } from "@stores/quizView";
import { useCallback, useDebugValue, useMemo, useState } from "react"; import { useCallback, useDebugValue, useMemo, useState } from "react";
import { isResultQuestionEmpty } from "../../components/ViewPublicationPage/tools/checkEmptyData";
import moment from "moment";
import { useQuizData } from "@contexts/QuizDataContext";
import { enqueueSnackbar } from "notistack"; import { enqueueSnackbar } from "notistack";
import moment from "moment";
import { isResultQuestionEmpty } from "@/components/ViewPublicationPage/tools/checkEmptyData";
import { useQuizData } from "@contexts/QuizDataContext";
import { useQuizViewStore } from "@stores/quizView";
import { useVkMetricsGoals } from "@/utils/hooks/metrics/useVkMetricsGoals";
import { useYandexMetricsGoals } from "@/utils/hooks/metrics/useYandexMetricsGoals";
export function useQuestionFlowControl() { export function useQuestionFlowControl() {
const { settings, questions } = useQuizData(); const { settings, questions } = useQuizData();
const sortedQuestions = useMemo(() => { const sortedQuestions = useMemo(() => {
return [...questions].sort((a, b) => a.page - b.page); return [...questions].sort((a, b) => a.page - b.page);
}, [questions]); }, [questions]);
const [currentQuestionId, setCurrentQuestionId] = useState<string | null>(getFirstQuestionId); const [currentQuestionId, setCurrentQuestionId] = useState<string | null>(
const answers = useQuizViewStore(state => state.answers); getFirstQuestionId
const pointsSum = useQuizViewStore(state => state.pointsSum); );
const setCurrentQuizStep = useQuizViewStore(state => state.setCurrentQuizStep); const answers = useQuizViewStore((state) => state.answers);
const pointsSum = useQuizViewStore((state) => state.pointsSum);
const setCurrentQuizStep = useQuizViewStore(
(state) => state.setCurrentQuizStep
);
const vkMetrics = useVkMetricsGoals(settings.cfg.vkMetricsNumber);
const yandexMetrics = useYandexMetricsGoals(settings.cfg.yandexMetricsNumber);
const currentQuestion = sortedQuestions.find(question => question.id === currentQuestionId) ?? sortedQuestions[0]; const currentQuestion =
console.log("currentQuestion", currentQuestion) sortedQuestions.find((question) => question.id === currentQuestionId) ??
sortedQuestions[0];
console.log("currentQuestion", currentQuestion);
const linearQuestionIndex = currentQuestion && sortedQuestions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled const linearQuestionIndex =
? sortedQuestions.indexOf(currentQuestion) currentQuestion &&
: null; sortedQuestions.every(({ content }) => content.rule.parentId !== "root") // null when branching enabled
? sortedQuestions.indexOf(currentQuestion)
: null;
function getFirstQuestionId() { function getFirstQuestionId() {
if (sortedQuestions.length === 0) return null; if (sortedQuestions.length === 0) return null;
if (settings.cfg.haveRoot) { if (settings.cfg.haveRoot) {
const nextQuestion = sortedQuestions.find( const nextQuestion = sortedQuestions.find(
question => question.id === settings.cfg.haveRoot || question.content.id === settings.cfg.haveRoot (question) =>
); question.id === settings.cfg.haveRoot ||
if (!nextQuestion) return null; question.content.id === settings.cfg.haveRoot
);
if (!nextQuestion) return null;
return nextQuestion.id; return nextQuestion.id;
}
return sortedQuestions[0].id;
} }
const nextQuestionIdPointsLogic = useCallback(() => { return sortedQuestions[0].id;
return sortedQuestions.find(question => }
question.type === "result" && question.content.rule.parentId === "line"
);
}, [sortedQuestions]);
const nextQuestionIdMainLogic = useCallback(() => { const nextQuestionIdPointsLogic = useCallback(() => {
const questionAnswer = answers.find(({ questionId }) => questionId === currentQuestion.id); return sortedQuestions.find(
(question) =>
question.type === "result" && question.content.rule.parentId === "line"
);
}, [sortedQuestions]);
if (questionAnswer && !moment.isMoment(questionAnswer.answer)) { const nextQuestionIdMainLogic = useCallback(() => {
const userAnswers = Array.isArray(questionAnswer.answer) ? questionAnswer.answer : [questionAnswer.answer]; const questionAnswer = answers.find(
({ questionId }) => questionId === currentQuestion.id
);
for (const branchingRule of currentQuestion.content.rule.main) { if (questionAnswer && !moment.isMoment(questionAnswer.answer)) {
if (userAnswers.some(answer => branchingRule.rules[0].answers.includes(answer))) { const userAnswers = Array.isArray(questionAnswer.answer)
return branchingRule.next; ? questionAnswer.answer
} : [questionAnswer.answer];
}
}
if (!currentQuestion.required) { for (const branchingRule of currentQuestion.content.rule.main) {
const defaultNextQuestionId = currentQuestion.content.rule.default;
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ") return defaultNextQuestionId;
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
//Кинуть на ребёнка надо даже если там нет дефолта
if (
["date", "page", "text", "number"].includes(currentQuestion.type)
&& currentQuestion.content.rule.children.length === 1
) return currentQuestion.content.rule.children[0];
}
//ничё не нашли, ищем резулт
return sortedQuestions.find(q => {
return q.type === "result" && q.content.rule.parentId === currentQuestion.content.id;
})?.id;
}, [answers, currentQuestion, sortedQuestions]);
const nextQuestionId = useMemo(() => {
if (settings.cfg.score) {
return nextQuestionIdPointsLogic();
}
return nextQuestionIdMainLogic();
}, [nextQuestionIdMainLogic, nextQuestionIdPointsLogic, settings.cfg.score]);
const prevQuestion = linearQuestionIndex !== null
? sortedQuestions[linearQuestionIndex - 1]
: sortedQuestions.find(q =>
q.id === currentQuestion?.content.rule.parentId
|| q.content.id === currentQuestion?.content.rule.parentId
);
const findResultPointsLogic = useCallback(() => {
const results = sortedQuestions.filter(
e => e.type === "result" && e.content.rule.minScore !== undefined && e.content.rule.minScore <= pointsSum
);
const numbers = results.map(
e => e.type === "result" && e.content.rule.minScore !== undefined ? e.content.rule.minScore : 0
);
const indexOfNext = Math.max(...numbers);
return results[numbers.indexOf(indexOfNext)];
}, [pointsSum, sortedQuestions]);
const nextQuestion = useMemo(() => {
let next;
if (settings.cfg.score) {
if (linearQuestionIndex !== null) {
next = sortedQuestions[linearQuestionIndex + 1];
if (next?.type === "result" || next == undefined) next = findResultPointsLogic();
}
} else {
if (linearQuestionIndex !== null) {
next = sortedQuestions[linearQuestionIndex + 1] ?? sortedQuestions.find(question =>
question.type === "result" && question.content.rule.parentId === "line"
);
} else {
next = sortedQuestions.find(q => q.id === nextQuestionId || q.content.id === nextQuestionId);
}
}
return next;
}, [nextQuestionId, findResultPointsLogic, linearQuestionIndex, sortedQuestions, settings.cfg.score]);
const showResult = useCallback(() => {
if (nextQuestion?.type !== "result") throw new Error("Current question is not result");
setCurrentQuestionId(nextQuestion.id);
if ( if (
settings.cfg.resultInfo.showResultForm === "after" userAnswers.some((answer) =>
|| isResultQuestionEmpty(nextQuestion) branchingRule.rules[0].answers.includes(answer)
) setCurrentQuizStep("contactform"); )
}, [nextQuestion, setCurrentQuizStep, settings.cfg.resultInfo.showResultForm]); ) {
return branchingRule.next;
const showResultAfterContactForm = useCallback(() => {
if (currentQuestion?.type !== "result") throw new Error("Current question is not result");
if (isResultQuestionEmpty(currentQuestion)) {
enqueueSnackbar("Данные отправлены");
return;
} }
}
}
setCurrentQuizStep("question"); if (!currentQuestion.required) {
}, [currentQuestion, setCurrentQuizStep]); const defaultNextQuestionId = currentQuestion.content.rule.default;
if (defaultNextQuestionId.length > 1 && defaultNextQuestionId !== " ")
return defaultNextQuestionId;
//Вопросы типа страница, ползунок, своё поле для ввода и дата не могут иметь больше 1 ребёнка. Пользователь не может настроить там дефолт
//Кинуть на ребёнка надо даже если там нет дефолта
if (
["date", "page", "text", "number"].includes(currentQuestion.type) &&
currentQuestion.content.rule.children.length === 1
)
return currentQuestion.content.rule.children[0];
}
const moveToPrevQuestion = useCallback(() => { //ничё не нашли, ищем резулт
if (!prevQuestion) throw new Error("Previous question not found"); return sortedQuestions.find((q) => {
return (
q.type === "result" &&
q.content.rule.parentId === currentQuestion.content.id
);
})?.id;
}, [answers, currentQuestion, sortedQuestions]);
setCurrentQuestionId(prevQuestion.id); const nextQuestionId = useMemo(() => {
}, [prevQuestion]); if (settings.cfg.score) {
return nextQuestionIdPointsLogic();
}
return nextQuestionIdMainLogic();
}, [nextQuestionIdMainLogic, nextQuestionIdPointsLogic, settings.cfg.score]);
const moveToNextQuestion = useCallback(() => { const prevQuestion =
if (!nextQuestion) throw new Error("Next question not found"); linearQuestionIndex !== null
? sortedQuestions[linearQuestionIndex - 1]
: sortedQuestions.find(
(q) =>
q.id === currentQuestion?.content.rule.parentId ||
q.content.id === currentQuestion?.content.rule.parentId
);
if (nextQuestion.type === "result") return showResult(); const findResultPointsLogic = useCallback(() => {
//засчитываем переход с вопроса дальше const results = sortedQuestions.filter(
(e) =>
e.type === "result" &&
e.content.rule.minScore !== undefined &&
e.content.rule.minScore <= pointsSum
);
const numbers = results.map((e) =>
e.type === "result" && e.content.rule.minScore !== undefined
? e.content.rule.minScore
: 0
);
const indexOfNext = Math.max(...numbers);
//@ts-ignore return results[numbers.indexOf(indexOfNext)];
let YM = window?.ym; }, [pointsSum, sortedQuestions]);
//@ts-ignore
let VP = window?._tmr;
if (YM !== undefined && settings.cfg.yandexMetricNumber !== undefined) {
YM(
settings.cfg.yandexMetricNumber,
"reachGoal",
`penaquiz-step{${currentQuestion.id}}`
);
};
if (VP !== undefined && settings.cfg.vkMetricNumber !== undefined) {
VP.push({
type: "reachGoal",
id: settings.cfg.vkMetricNumber,
goal: `penaquiz-step{${currentQuestion.id}}`
});
};
setCurrentQuestionId(nextQuestion.id); const nextQuestion = useMemo(() => {
}, [nextQuestion, showResult]); let next;
if (settings.cfg.score) {
if (linearQuestionIndex !== null) {
next = sortedQuestions[linearQuestionIndex + 1];
if (next?.type === "result" || next == undefined)
next = findResultPointsLogic();
}
} else {
if (linearQuestionIndex !== null) {
next =
sortedQuestions[linearQuestionIndex + 1] ??
sortedQuestions.find(
(question) =>
question.type === "result" &&
question.content.rule.parentId === "line"
);
} else {
next = sortedQuestions.find(
(q) => q.id === nextQuestionId || q.content.id === nextQuestionId
);
}
}
const setQuestion = useCallback((questionId: string) => { return next;
const question = sortedQuestions.find(q => q.id === questionId); }, [
if (!question) return; nextQuestionId,
findResultPointsLogic,
linearQuestionIndex,
sortedQuestions,
settings.cfg.score,
]);
setCurrentQuestionId(question.id); const showResult = useCallback(() => {
}, [sortedQuestions]); if (nextQuestion?.type !== "result")
throw new Error("Current question is not result");
const isPreviousButtonEnabled = Boolean(prevQuestion); setCurrentQuestionId(nextQuestion.id);
if (
settings.cfg.resultInfo.showResultForm === "after" ||
isResultQuestionEmpty(nextQuestion)
)
setCurrentQuizStep("contactform");
}, [
nextQuestion,
setCurrentQuizStep,
settings.cfg.resultInfo.showResultForm,
]);
const isNextButtonEnabled = useMemo(() => { const showResultAfterContactForm = useCallback(() => {
const hasAnswer = answers.some(({ questionId }) => questionId === currentQuestion.id); if (currentQuestion?.type !== "result")
throw new Error("Current question is not result");
if (isResultQuestionEmpty(currentQuestion)) {
enqueueSnackbar("Данные отправлены");
return;
}
if ("required" in currentQuestion.content && currentQuestion.content.required) { setCurrentQuizStep("question");
return hasAnswer; }, [currentQuestion, setCurrentQuizStep]);
}
return Boolean(nextQuestion); const moveToPrevQuestion = useCallback(() => {
}, [answers, currentQuestion, nextQuestion]); if (!prevQuestion) throw new Error("Previous question not found");
useDebugValue({ setCurrentQuestionId(prevQuestion.id);
linearQuestionIndex, }, [prevQuestion]);
currentQuestion: currentQuestion,
prevQuestion: prevQuestion,
nextQuestion: nextQuestion,
});
return { const moveToNextQuestion = useCallback(() => {
currentQuestion, if (!nextQuestion) throw new Error("Next question not found");
currentQuestionStepNumber: linearQuestionIndex === null ? null : linearQuestionIndex + 1,
isNextButtonEnabled, if (nextQuestion.type === "result") return showResult();
isPreviousButtonEnabled, // Засчитываем переход с вопроса дальше
moveToPrevQuestion, vkMetrics.questionPassed(currentQuestion.id);
moveToNextQuestion, yandexMetrics.questionPassed(currentQuestion.id);
showResultAfterContactForm,
setQuestion, setCurrentQuestionId(nextQuestion.id);
}; }, [nextQuestion, showResult]);
}
const setQuestion = useCallback(
(questionId: string) => {
const question = sortedQuestions.find((q) => q.id === questionId);
if (!question) return;
setCurrentQuestionId(question.id);
},
[sortedQuestions]
);
const isPreviousButtonEnabled = Boolean(prevQuestion);
const isNextButtonEnabled = useMemo(() => {
const hasAnswer = answers.some(
({ questionId }) => questionId === currentQuestion.id
);
if (
"required" in currentQuestion.content &&
currentQuestion.content.required
) {
return hasAnswer;
}
return Boolean(nextQuestion);
}, [answers, currentQuestion, nextQuestion]);
useDebugValue({
linearQuestionIndex,
currentQuestion: currentQuestion,
prevQuestion: prevQuestion,
nextQuestion: nextQuestion,
});
return {
currentQuestion,
currentQuestionStepNumber:
linearQuestionIndex === null ? null : linearQuestionIndex + 1,
isNextButtonEnabled,
isPreviousButtonEnabled,
moveToPrevQuestion,
moveToNextQuestion,
showResultAfterContactForm,
setQuestion,
};
}