const t_quiz__hashMap = new Map(); /** * @typedef {{ * viewStep: (stepOrder: number) => void, * openPopup: (virtPage: string, hook: string) => void * restart: () => void * }} QuizAnalytics */ /** * @typedef {typeof t_quiz__adjustStepToHeight | typeof t_quiz__addConsultantClamp} DebouncableFunction */ /** * @param {DebouncableFunction} func * @param {string} hashKey * @param {number=} timeoutMs * @returns */ const t_quiz__getDebouncedFunc = function (func, hashKey, timeoutMs = 200) { if (t_quiz__hashMap.has(hashKey)) { return t_quiz__hashMap.get(hashKey); } const debounced = t_quiz__debounce(func, timeoutMs); t_quiz__hashMap.set(hashKey, debounced); return debounced; }; function t_quiz__init(recid, onInitCallback) { var rec = document.querySelector('#rec' + recid); if (!rec) { throw new Error('rec not found. id: ' + recid); } var quiz = rec.querySelector('.t-quiz'); if (!quiz) { throw new Error('quiz wrapper not found. recid: ' + recid); } var form = rec.querySelector('.t-form'); if (!form) { throw new Error('form wrapper not found. recid: ' + recid); } var quizMain = rec.querySelector('.t-quiz__main'); var quizWrapper = rec.querySelector('.t-quiz__quiz-wrapper'); var inputs = rec.querySelectorAll('.t-input-group'); var nextBtns = rec.querySelectorAll('.t-quiz__btn_next'); var submitBtns = rec.querySelectorAll('.t-quiz__btn_submit'); var prevBtns = rec.querySelectorAll('.t-quiz__btn_prev'); // Для кнопок результата нужно использовать селектор через отрицание, чтобы не сломать обратную совместимость. var resultNextBtns = rec.querySelectorAll( '.t-quiz__result-btn:not(.t-result-btn_link):not(.t-result-btn_restart):not(.t-result-btn_prevstep)' ); const resultRestartBtns = rec.querySelectorAll('.t-result-btn_restart'); var startBtns = rec.querySelectorAll('.t-quiz__btn_start'); var panel = rec.querySelector('.t-quiz__panel'); var footer = rec.querySelector('.t-quiz__footer'); var btnWrapperMobile = rec.querySelector('.t-quiz__btn-wrapper_mobile'); var progressBar = rec.querySelector('.t-quiz__progressbar'); var footerTextContainer = rec.querySelector('.js-footer-text-container'); var consultantHolder = rec.querySelector('.t-quiz__consultant'); var defaultConsultantMessage = quizWrapper.getAttribute('data-consultant-msg'); var descriptionInsideMain = rec.querySelector('.t-quiz__main__description-container'); var popup = rec.querySelector('.t-popup'); var popupContainer = rec.querySelector('.t-popup__container'); var errorBoxMiddle = rec.querySelector('.t-form__errorbox-middle'); if (errorBoxMiddle) t_quiz__hide(errorBoxMiddle); form.addEventListener('tildaform:aftererror', () => { // Обрабатываем только те ошибки, которые возвращаются с бэка при отправке формы if (form.classList.contains('js-send-form-error')) { t_quiz__show(errorBoxMiddle); } }); form.classList.remove('js-form-proccess'); t_quiz__workWithAnswerCode(rec); const isPublishMode = quizWrapper.classList.contains('t-quiz__quiz-published'); const isFixedHeight = quizWrapper.classList.contains('t-quiz__quiz-wrapper_fixed-height'); if (!isFixedHeight) { const SPECIAL_STEP_HEIGHT = '500px'; const coverSteps = rec.querySelectorAll('.t-quiz__cover'); coverSteps.forEach(function (cover) { cover.style.height = SPECIAL_STEP_HEIGHT; }); } const consultantClampLines = { desktop: quizWrapper.getAttribute('data-clamp-consultant-desktop'), mobile: quizWrapper.getAttribute('data-clamp-consultant-mobile'), }; const shouldClampConsultant = Boolean(consultantClampLines.desktop || consultantClampLines.mobile); const steps = Array.from(rec.querySelectorAll('.t-quiz__screen-wrapper:not(.t-form__hidden)')); const successBoxResult = rec.querySelector('.t-quiz__result_ordinary'); const preparedSteps = [...steps, successBoxResult].map(function (step) { return { type: t_quiz__getStepType(step), element: step, }; }); const analyticsEnabled = Boolean(quizWrapper.getAttribute('data-analytics-enabled')); const autoStepChangeEnabled = Boolean(quizWrapper.getAttribute('data-auto-step-change')); const isConditionalForm = !!form.querySelector('.t-conditional'); const StepsManager = t_quiz__step_manager({ recId: recid, steps: preparedSteps, successStepElement: successBoxResult, activeStepClass: 't-step-form__step_active', hiddenStepClass: 't-quiz-hidden', enableAutoStepChange: autoStepChangeEnabled, enableConditionals: isConditionalForm, onProgressChange: onProgressChange, onConditionalStateChange: onConditionalStateChange, animation: getAnimationConfig(), onInit: function () { onInitCallback && onInitCallback(); t_quiz__adjustStepToHeight({ rec }); }, checkIfCanChangeStep: canChangeStep, }); // Инициализация analyticsEnabled && initAnalytics(); initForm(); StepsManager.init(); quizWrapper.StepsManager = StepsManager; /** @type {TransitionGuard} */ function canChangeStep(direction, stepInfo, transitionInfo = {}) { // Появление первого шага, когда активного еще нет. if (!stepInfo || !stepInfo.step || !stepInfo.step.element) { return true; } // При переходе назад нет валидации, просто скрываем ошибку if (direction === 'prev') { hideStepErrors(stepInfo.step.element); return true; } // Блокируем автопереход с последнего шага if (stepInfo.isLast && transitionInfo.isAutoTransition) { return false; } // Если переход с последнего шага после отправки формы, то разрешаем if (stepInfo.isLast && transitionInfo.isOnSuccess) { return true; } if (stepInfo.isFinal && stepInfo.type === 'result') { return false; } const hasStepErrors = validateCurrentStep(); // Если на шаге есть ошибки, то переход блокируется if (hasStepErrors) { return false; } hideStepErrors(stepInfo.step.element); return true; } function onProgressChange(progress) { // Прогресс квиза может измениться без переключения шага. // Пример: изменение списка из-за условий видимости. t_quiz__setProgress(rec, progress.current, progress.total); if (progress.current) { t_quiz__showCounter(rec, progress.current, progress.total); } requestAnimationFrame(() => { t_quiz__adjustStepToHeight({ rec }); }); } function onConditionalStateChange(event) { const conditionalElement = event.target; const isHidden = event.detail && event.detail.hidden === true; const currentStep = StepsManager.getCurrentStepInfo(); // Работаем только с теми видео, которые видны на текущем шаге. const isPartOfCurrentStep = currentStep.step.element.contains(conditionalElement); if (isHidden && isPartOfCurrentStep) { t_quiz__pauseVideos(conditionalElement); } checkIfShouldSubmitForm(); showOrHideButtons(); if (isCurrentStepFirst()) { prevBtns.forEach(btn => (btn.disabled = true)); } else { prevBtns.forEach(btn => (btn.disabled = false)); } } function initForm() { rec.setAttribute('data-animationappear', 'off'); rec.style.opacity = 1; prevBtns.forEach(function (btn) { btn.addEventListener('click', function () { handleGoPrevStep(); }); }); nextBtns.forEach(function (btn) { btn.addEventListener('click', function () { handleGoNextStep(); }); }); resultNextBtns.forEach(function (btn) { btn.addEventListener('click', function () { handleGoNextStep(); }); }); Array.prototype.forEach.call(inputs, function (input) { input.addEventListener('keypress', function (event) { const isEnterKey = event.code === 'Enter' || event.keyCode === 13; const isTextArea = event.target instanceof HTMLTextAreaElement; const shouldSubmitForm = form.classList.contains('js-form-proccess'); if (isEnterKey && !shouldSubmitForm && !isTextArea) { handleGoNextStep(); } }); }); submitBtns.forEach(function (btn) { btn.addEventListener('click', function () { handleValidateOnSubmit(); }); }); startBtns.forEach(function (btn) { btn.addEventListener('click', function () { handleGoNextStep(); }); }); resultRestartBtns.forEach(btn => { btn.addEventListener('click', () => { handleRestartQuiz(); }); }); // BF920A if (quiz.classList.contains('popup')) { t_quiz__openToHook(rec); } if (shouldClampConsultant) { // включает сворачивание текста консультанта в мобильной версии t_quiz__updateConsultantClampOnResize(rec, recid, consultantClampLines); } // пересчитывает высоту на изменения ширины экрана t_quiz__adjustHeightOnResize(rec, recid); t_quiz__applyTranslation(rec); } function handleGoPrevStep() { StepsManager.go('prev'); } function handleGoNextStep() { StepsManager.go('next'); } function handleRestartQuiz() { quizHeightCaches.delete(rec.id); t_onFuncLoad('t_forms__clearForm', () => { window .t_forms__clearForm(form) .then(() => { StepsManager.restart(); restartAnalytics(); window.t_forms__updateAllVariables(form); }) .catch(err => { console.error('Failed to restart Quiz: ', err); }); }); } function handleValidateOnSubmit() { validateCurrentStep(); validateForm(); } function isCurrentStepLast() { return StepsManager.getCurrentStepInfo().isLast; } function isCurrentStepFirst() { return StepsManager.getCurrentStepInfo().isFirst; } function showOrHideButtons() { if (isCurrentStepLast()) { // шаг последний - показываем кнопку отправки формы nextBtns.forEach(function (btn) { t_quiz__hide(btn); }); submitBtns.forEach(function (btn) { t_quiz__show(btn); btn.disabled = false; }); return; } nextBtns.forEach(function (btn) { t_quiz__show(btn); }); submitBtns.forEach(function (btn) { t_quiz__hide(btn); // Блокируем submit, чтоб он не вызывался скриптом форм при нажатии на enter btn.disabled = true; }); } function getAnimationConfig() { return { type: { cover: 'fade', result: 'fade', contacts: 'fade-with-move', step: 'fade-with-move', }, callbacks: { onNewStepAnimationStart: function (oldStep, newStep) { if (!newStep) return; const { isLast: isNewStepLast, isFinal: isNewStepFinal } = StepsManager.getCurrentStepInfo(); const shouldRedirect = newStep.element && newStep.element.classList.contains('t-quiz__result_redirect'); checkIfShouldSubmitForm(); t_quiz__runLazyLoad(); if (oldStep) { t_quiz__pauseVideos(oldStep.element); } t_quiz__initStepVideos(newStep.element); t_quiz__updateRangeSlider(newStep.element); if (shouldClampConsultant) { t_quiz__addConsultantClamp({ rec, recId: recid, lines: consultantClampLines }); } changeConsultantMessage(newStep); setSpecImageRatio(); if (newStep.type === 'step' || newStep.type === 'contacts') { t_quiz__show(progressBar); t_quiz__show(footer); t_quiz__show(btnWrapperMobile); showPanelAndDescription(); } if (newStep.type === 'cover' || newStep.type === 'result') { t_quiz__hide(footer); t_quiz__hide(btnWrapperMobile); hidePanelAndDescription(); t_quiz__hide(progressBar); } if (newStep.type === 'contacts') { changeSubmitName(newStep.element); } toggleStepFooterText(newStep); showOrHideButtons(); // если обложка последний шаг, то значит она заменяет результат и была показана после отправки формы if (newStep.type === 'cover' && isNewStepLast) { disableButtons(); } else if (newStep.type === 'result' && isNewStepLast) { prevBtns.forEach(btn => (btn.disabled = true)); // Если после результата есть другие результаты, то разрешаем перейти к ним if (!isNewStepFinal && !shouldRedirect) { resultNextBtns.forEach(btn => (btn.disabled = false)); } } else { enableButtons(); } // Обработка редиректа при переходе на шаг результата с редиректом if (shouldRedirect) { setTimeout(() => { t_quiz__handleRedirectResult(newStep.element); }, 500); } // Скролл страницы происходит только после явной смены шага, а не при инициализации if (oldStep) { t_quiz__scrollPageToTopOf(quizWrapper); } scrollContentToTop(); }, onAnimationStart: function () { disableButtons(); }, }, }; } /** @param {Step} step */ function toggleStepFooterText(step) { if (!footerTextContainer) return; var text = step.element.getAttribute('data-step-footer-text'); if (!text) { t_quiz__hide(footerTextContainer); return; } if (!footerTextContainer) return; var textContainer = footerTextContainer.querySelector('.js-footer-text'); if (!textContainer) return; t_quiz__show(footerTextContainer); textContainer.textContent = text; } function disableButtons() { startBtns.forEach(function (btn) { btn.disabled = true; }); prevBtns.forEach(function (btn) { btn.disabled = true; }); nextBtns.forEach(function (btn) { btn.disabled = true; }); submitBtns.forEach(function (btn) { btn.disabled = true; }); resultNextBtns.forEach(function (btn) { btn.disabled = true; }); } function enableButtons() { startBtns.forEach(function (btn) { btn.disabled = false; }); nextBtns.forEach(function (btn) { btn.disabled = false; }); if (!isCurrentStepFirst()) { prevBtns.forEach(function (btn) { btn.disabled = false; }); } submitBtns.forEach(function (btn) { btn.disabled = false; }); resultNextBtns.forEach(function (btn) { btn.disabled = false; }); } /** Добавляет флаг, который разрешает отправку формы */ function checkIfShouldSubmitForm() { form.classList.toggle('js-form-proccess', isCurrentStepLast()); } /** * Переопределяет название кнопки submit, * если оно задано на шаге Форма Контактов * @param {HTMLElement} step */ function changeSubmitName(step) { if (!step) return; if (!isCurrentStepLast()) return; var submitBtnTitle = step.getAttribute('data-submit-title'); if (submitBtnTitle) { submitBtns.forEach(function (btn) { var submitBtnSpan = btn.querySelector('span'); submitBtnSpan.innerHTML = submitBtnTitle; t_onFuncLoad('t_forms__parseVariables', () => { t_forms__parseVariables(submitBtnSpan); }); }); } } function hidePanelAndDescription() { t_quiz__hide(panel); t_quiz__hide(descriptionInsideMain); quizWrapper.classList.add('panel-hidden'); } function showPanelAndDescription() { t_quiz__show(panel); t_quiz__show(descriptionInsideMain); quizWrapper.classList.remove('panel-hidden'); } function changeConsultantMessage(step) { if (!consultantHolder) return; var consultantContainer = consultantHolder.querySelector('.t-quiz__consultant__container'); var msgContainer = consultantHolder.querySelector('.js-consultant-msg'); if (!consultantContainer) return; var stepMessage = step.element.getAttribute('data-consultant-msg'); if (!stepMessage && !defaultConsultantMessage) { t_quiz__hide(consultantContainer); return; } var clampInnerContainer = msgContainer.querySelector('.t-text-clamp__inner'); if (clampInnerContainer) { msgContainer = clampInnerContainer; } msgContainer.innerHTML = stepMessage || defaultConsultantMessage; t_onFuncLoad('t_forms__parseVariables', () => { t_forms__parseVariables(msgContainer).finally(() => { t_quiz__show(consultantContainer); }); }); } /* Функции для обработки и вывода ошибок */ function hideStepErrors(currentStep) { if (!currentStep) return; const allInputs = currentStep.querySelectorAll('.t-input-group'); allInputs.forEach(function (input) { input.classList.remove('js-error-control-box'); }); t_quiz__hide(errorBoxMiddle); const inputErrorWrapper = currentStep.querySelector('.t-input-error'); if (inputErrorWrapper) inputErrorWrapper.innerHTML = ''; } function validateForm() { if (!isPublishMode) return false; if (typeof window.tildaForm !== 'object') return false; t_quiz__hide(errorBoxMiddle); const formErrors = window.tildaForm.validate(form); const hasFormErrors = formErrors && formErrors.length > 0; if (hasFormErrors) { t_quiz__show(errorBoxMiddle); requestAnimationFrame(() => { t_quiz__adjustStepToHeight({ rec }, true); }); } // Не вызываем showErrors, так как он вызовется при нажатии на кнопку submit через скрипт формы return hasFormErrors; } function validateCurrentStep() { if (!isPublishMode) return; const stepInfo = StepsManager.getCurrentStepInfo(); const currentElement = stepInfo.step?.element; if (!currentElement) return false; if (typeof window.tildaForm !== 'object') return false; hideStepErrors(currentElement); const errors = window.tildaForm.validate(currentElement); if (!errors || errors.length === 0) return false; const stepErrors = filterStepRelatedErrors(errors); const hasStepErrors = !!stepErrors.length; // Нужно показать ошибки руками, тк они показываются скриптом формы только при нажатии на submit. if (hasStepErrors) { window.tildaForm.showErrors(currentElement, stepErrors, { inputBoxSelector: '.t-input-group' }); requestAnimationFrame(() => { t_quiz__adjustStepToHeight({ rec }, true); }); } return hasStepErrors; } /** * Возвращает ошибки, которые относятся тллько к текущему шагу. * Ошибка emptyfill актуальна только при отправке формы. * @param {Array} stepErrors */ function filterStepRelatedErrors(stepErrors) { return stepErrors.filter(error => error.type.some(errorType => errorType !== 'emptyfill')); } function setSpecImageRatio() { const specImage = rec.querySelector( '.t-step-form__step_active .t-quiz__cover__side-cover .t-quiz__cover__img, .t-step-form__step_active .t-quiz__result-img-wrapper' ); if (!specImage) return; const specImageUrl = window.getComputedStyle(specImage).getPropertyValue('background-image').slice(5, -2); // Создаем временный элемент изображения для определения размеров const img = document.createElement('img'); img.src = specImageUrl; img.onload = function () { const imageWidth = img.width; const imageHeight = img.height; const imageRatio = (imageWidth / imageHeight).toFixed(1); const specImageRatio = Math.max(imageRatio, 1); changeSpecImageRatio(specImage, specImageRatio); function handleSpecImageRatioResize() { t_quiz__getDebouncedFunc(changeSpecImageRatio, `${recid}_spec-ratio`)(specImage, specImageRatio); } window.addEventListener('resize', handleSpecImageRatioResize); }; } function changeSpecImageRatio(specImage, ratio) { let aspectRatio = ratio; if (t_quiz__isMobile()) { aspectRatio = ratio; } else if (specImage.classList.contains('t-quiz__cover__img')) { aspectRatio = 'unset'; } else if (specImage.classList.contains('t-quiz__result-img-wrapper')) { aspectRatio = '16/9'; } specImage.style.aspectRatio = aspectRatio; } /** * @returns {QuizAnalytics | undefined} */ function initAnalytics() { try { const analytics = t_quiz__analytics({ rec }); if (!analytics) return; if ('IntersectionObserver' in window) { const stepObserver = new IntersectionObserver(function (entries, observer) { entries.forEach(function (entry) { if (!entry.isIntersecting) return; const target = entry.target; const currentStep = StepsManager.getCurrentStepInfo(); if (currentStep.step && target !== currentStep.step.element) return; const stepIndex = currentStep.step.element.getAttribute('data-step-index') || currentStep.index; const stepOrder = Number(stepIndex) + 1; analytics.viewStep(stepOrder); observer.unobserve(target); }); }); preparedSteps.forEach(step => { stepObserver.observe(step.element); }); } } catch (e) { console.warn(e); } } function restartAnalytics() { const analytics = t_quiz__analytics({ rec }); if (!analytics) return; // Очищаем все просмотренные шаги analytics.restart(); // TODO: проверить, чтобы IntersectionObserver удалялись // Запускаем аналитику заново initAnalytics(); } function scrollContentToTop() { const isSaticPopup = popupContainer && popupContainer.classList.contains('t-popup__container-static'); if (isSaticPopup) { popup.scrollTo(0, 0); } else { quizMain.scrollTo(0, 0); } } t_quiz__displayStickyBtnWrapper(rec); if (!quiz.classList.contains('.popup')) { t_onFuncLoad('t_throttle', function () { window.addEventListener( 'scroll', t_throttle(function () { t_quiz__displayStickyBtnWrapper(rec); }) ); }); } } function t_quiz__hide(element) { var CN_HIDDEN = 't-quiz-hidden'; element && element.classList.add(CN_HIDDEN); } function t_quiz__show(element) { var CN_HIDDEN = 't-quiz-hidden'; element && element.classList.remove(CN_HIDDEN); } /** * @param {HTMLElement} step * @returns {"cover" | "contacts" | "result" | "step"} */ function t_quiz__getStepType(step) { if (step.classList.contains('t-quiz__cover')) { return 'cover'; } if (step.classList.contains('t-quiz__contact-form')) { return 'contacts'; } if (step.classList.contains('t-quiz__result')) { return 'result'; } return 'step'; } /** * Отображает btn wrapper на мобильных устройствах * btn wrapper фиксированный и появляется с определённой координаты при скролле * в попапе отображается сразу * @param {HTMLElement} rec * @returns */ function t_quiz__displayStickyBtnWrapper(rec) { if (!t_quiz__isMobile()) return; const quiz = rec.querySelector('.t-quiz__quiz'); if (!quiz) return; const btnWrapper = rec.querySelector('.t-quiz__btn-wrapper_mobile'); if (!btnWrapper) return; const isPopup = quiz.closest('.popup') !== null; const position = quiz.getBoundingClientRect(); const topShift = 500; const bottomShift = -30; const heightCoordinate = window.innerHeight - topShift; if (isPopup || (!isPopup && position.top < heightCoordinate && position.bottom >= bottomShift)) { btnWrapper.classList.add('t-quiz__btn-wrapper_visible'); btnWrapper.classList.remove('t-quiz__btn-wrapper_hidden'); } if (!isPopup && position.top >= heightCoordinate) { btnWrapper.classList.remove('t-quiz__btn-wrapper_visible'); btnWrapper.classList.add('t-quiz__btn-wrapper_hidden'); } } /** * Иницилизирует или отключает сворачивание текста в сообщении консультанта * @param {{ rec: HTMLElement, recId: string, lines: { desktop: number | null, mobile: number | null } }} options */ function t_quiz__addConsultantClamp(options) { const { recId, rec, lines } = options; const consultantHolder = rec.querySelector('.t-quiz__consultant'); if (!consultantHolder) return; const ANY_MSG_SELECTOR = '.js-consultant-msg'; const CURRENT_STEP_MSG_SELECTOR = '.t-step-form__step_active .js-consultant-msg,.t-quiz__panel .js-consultant-msg'; const isMobile = t_quiz__isMobile(); const isDesktop = !isMobile; const hasOnlyMobileSetting = lines.mobile && !lines.desktop; const hasOnlyDesktopSetting = lines.desktop && !lines.mobile; const hasBothSettings = lines.desktop && lines.mobile; const shouldResetClamp = (hasOnlyMobileSetting && isDesktop) || (hasOnlyDesktopSetting && isMobile); const shouldUseMobileSetting = Boolean(lines.mobile && isMobile); // настройка для десктопа применяется для десктопа и для мобилки if (hasOnlyDesktopSetting) { if (lines.desktop <= 0) return; t_onFuncLoad('t_textClamp__init', () => { t_textClamp__init(recId, lines.desktop, CURRENT_STEP_MSG_SELECTOR); }); return; } // настройка для мобилки применяется только для нее if (hasOnlyMobileSetting && shouldUseMobileSetting) { if (lines.mobile <= 0) return; t_onFuncLoad('t_textClamp__init', () => { t_textClamp__init(recId, lines.mobile, CURRENT_STEP_MSG_SELECTOR); }); return; } // если указаны обе настройки, то инициализируем настройки и обновляем количество свернутых строк, если нужно if (hasBothSettings) { const numOfLines = shouldUseMobileSetting ? lines.mobile : lines.desktop; t_onFuncLoad('t_textClamp__init', () => { t_textClamp__init(recId, numOfLines, CURRENT_STEP_MSG_SELECTOR); t_onFuncLoad('t_textClamp__updateClampLines', () => { t_textClamp__updateClampLines(recId, numOfLines, CURRENT_STEP_MSG_SELECTOR); }); }); } // убираем сворачивание если изменили размер экрана, но для него нет настройки if (shouldResetClamp) { t_onFuncLoad('t_textClamp__reset', () => { t_textClamp__reset(recId, ANY_MSG_SELECTOR); }); } } function t_quiz__workWithAnswerCode(rec) { // Декодируем HTML-сущности в заголовках вопросов var inputTitles = rec.querySelectorAll('.t-input-title'); Array.prototype.forEach.call(inputTitles, function (title) { var decoded = t_quiz__decodeHtmlEntities(title.textContent); if (decoded !== title.textContent) { title.textContent = decoded; } }); var inputGroupRi = rec.querySelector('.t-input-group_ri'); if (inputGroupRi) { var inputsRi = inputGroupRi.querySelectorAll('input'); Array.prototype.forEach.call(inputsRi, function (input) { var value = input.value; if (value.indexOf('value::') !== -1) { t_quiz__setAnswerCode(input); var inputParent = input.parentNode; var label = inputParent.querySelector('.t-img-select__text'); label.textContent = label.textContent.split('value::')[0].trim(); } }); } var inputGroupRd = rec.querySelector('.t-input-group_rd'); if (inputGroupRd) { var inputsRd = inputGroupRd.querySelectorAll('input'); Array.prototype.forEach.call(inputsRd, function (input) { var value = input.value; if (value.indexOf('value::') !== -1) { t_quiz__setAnswerCode(input); var label = input.parentNode; label.innerHTML = function () { var html = input.innerHTML.split('value::')[0].trim(); return html; }; } }); } var inputGroupSb = rec.querySelector('.t-input-group_sb'); if (inputGroupSb) { var options = inputGroupSb.querySelectorAll('option'); Array.prototype.forEach.call(options, function (option) { var value = option.value; if (value.indexOf('value::') !== -1) { t_quiz__setAnswerCode(option); option.textContent = option.textContent.split('value::')[0].trim(); } }); } } function t_quiz__decodeHtmlEntities(text) { var textarea = document.createElement('textarea'); textarea.innerHTML = text; return textarea.value; } function t_quiz__runLazyLoad() { var records = document.querySelector('.t-records:not([data-tilda-mode])'); if (records) { var allRecs = document.querySelector('#allrecords'); if (window.lazy === 'y' || allRecs.getAttribute('data-tilda-lazy') === 'yes') { t_onFuncLoad('t_lazyload_update', function () { t_lazyload_update(); }); } } } function t_quiz__setAnswerCode(option) { var parameter = option.value.split('value::')[1].trim(); option.value = parameter; } function t_quiz__showCounter(rec, quizStepIndex, allStepsLength) { var counters = rec.querySelectorAll('.t-quiz__counter'); if (!counters) return; counters.forEach(function (counter) { counter.innerHTML = quizStepIndex + '/' + allStepsLength; }); } function t_quiz__setProgress(rec, index, allStepsLength) { var progressBar = rec.querySelector('.t-quiz__progressbar'); if (!progressBar || index == null) return; var progressbarWidth = parseFloat(getComputedStyle(progressBar).width); var progress = rec.querySelector('.t-quiz__progress'); var progressStep = progressbarWidth / allStepsLength; var percentProgressWidth = Math.abs((index * progressStep) / progressbarWidth) * 100 + '%'; if (progress) progress.style.width = percentProgressWidth; } function t_quiz__scrollPageToTopOf(quizFormWrapper) { var topCoordinateForm = quizFormWrapper.getBoundingClientRect().top; var quiz = quizFormWrapper.closest('.t-quiz'); var isDisabled = quiz.classList.contains('t-quiz_scroll-disabled'); if (topCoordinateForm >= 0 || isDisabled) return; quizFormWrapper.scrollIntoView({ block: 'start', }); } function t_quiz__adjustHeightOnResize(rec, recId) { window.addEventListener('resize', function () { t_quiz__getDebouncedFunc(t_quiz__adjustStepToHeight, `${recId}_step-height`)({ rec }); }); } function t_quiz__updateConsultantClampOnResize(rec, recId, lines) { window.addEventListener('resize', function () { t_quiz__getDebouncedFunc(t_quiz__addConsultantClamp, `${recId}_cons-clamp`)({ rec, recId, lines }); }); } // создаём Map как кэш со значениями высоты для каждого шага, // чтобы не было дополнительного пересчёта при движении назад по квизу, // и шаги принимали ту же высоту, что была рассчитана при движении вперёд const quizHeightCaches = new Map(); function t_quiz__getStepsHeightFromCache(recId) { if (!quizHeightCaches.has(recId)) { quizHeightCaches.set(recId, new Map()); } return quizHeightCaches.get(recId); } /** * Пересчитывает высоту шагов, если задана динамическая высота * @param {{ rec: HTMLElement }} options * @param {boolean} forceRecalculate - пересчёт высоты вместо значения из мапы */ function t_quiz__adjustStepToHeight(options, forceRecalculate = false) { var { rec } = options; var quiz = rec.querySelector('.t-quiz'); var quizWrapper = rec.querySelector('.t-quiz__quiz-wrapper'); var activeStep = rec.querySelector('.t-step-form__step_active'); var isResultActive = activeStep && activeStep.classList.contains('t-quiz__result'); var isPopup = quiz.classList.contains('popup'); // Попап // Если нет контейнера с динамической высотой, то значит это блок с фиксированной высотой. // в этом случае просто делаем resize. var isFixedHeight = quiz.classList.contains('fixed-height'); var isFullScreen = quiz.classList.contains('fullscreen'); if (isFixedHeight || isFullScreen) { if (isPopup) t_quiz__resizePopup(rec); return; } // Для мобильных устройств высота не устанавливается if (t_quiz__isMobile()) { return; } // Для десктопа используем автоматическую высоту quizWrapper.style.height = 'auto'; // Для popup нужно пересчитать позиционирование if (isPopup) { t_quiz__resizePopup(rec); } return; const stepsHeightCacheKey = `${rec.id}_step${activeStep.getAttribute('data-step-index')}`; let newHeight; const stepsHeightCache = t_quiz__getStepsHeightFromCache(rec.id); if (forceRecalculate || !stepsHeightCache.has(stepsHeightCacheKey)) { newHeight = calculateNewHeight(); stepsHeightCache.set(stepsHeightCacheKey, newHeight); } else { newHeight = stepsHeightCache.get(stepsHeightCacheKey); } if (isPopup) t_quiz__resizePopup(rec, newHeight); // Устанавливаем новую высоту с плавным переходом quizWrapper.style.overflow = 'hidden'; setTimeout(function () { quizWrapper.style.overflow = ''; }, 300); if (isResultActive) { // Для правильного расчета высоты внутри результата (100%), // нужно чтобы у самого шага была явно указана высота applyHeightToElement(activeStep, newHeight); } if (!t_quiz__isMobile()) { applyHeightToElement(quizWrapper, newHeight); } function calculateNewHeight() { var MIN_HEIGHT = 500; var quizStyle = getComputedStyle(quiz); var main = rec.querySelector('.t-quiz__main'); var panel = rec.querySelector('.t-quiz__panel'); // Учитывается только НЕ sticky footer. var footer = rec.querySelector('.t-quiz__content-wrapper > .t-quiz__footer'); var panelType = quizStyle.getPropertyValue('--panel-type'); var shouldIncludeHeader = panelType === 'header'; var hasSidebar = panelType === 'sidebar'; var mainHeight = main ? main.offsetHeight : 0; var headerHeight = shouldIncludeHeader ? panel.offsetHeight : 0; var footerHeight = footer ? footer.offsetHeight : 0; // top + bottom var contentPadding = parseInt(quizStyle.getPropertyValue('--content-padding'), 10) * 2; if (mainHeight <= 0) return MIN_HEIGHT; var newHeight = mainHeight + headerHeight + footerHeight + contentPadding; if (hasSidebar) { newHeight = Math.max(calculateSidebarHeight(panel), newHeight); } var oldHeight = parseInt(getComputedStyle(quizWrapper).height, 10); if (oldHeight <= MIN_HEIGHT && newHeight <= oldHeight) { newHeight = oldHeight; } if (isResultActive) { newHeight = Math.max(newHeight, MIN_HEIGHT); } return newHeight; } function calculateSidebarHeight(panel) { // высчитываем высоту таким образом, так как offsetHeight включает только видимую часть элемента var panelMain = rec.querySelector('.t-quiz__panel__main'); var panelExtraText = rec.querySelector('.t-quiz__text-extra'); var panelMainHeight = panelMain ? panelMain.offsetHeight : 0; var panelExtraTextHeight = panelExtraText ? panelExtraText.offsetHeight : 0; var sidebarStyle = getComputedStyle(panel); var sidebarPaddingTop = parseInt(sidebarStyle.getPropertyValue('--sidebar-padding-top'), 10); var sidebarPaddingBottom = parseInt(sidebarStyle.getPropertyValue('--sidebar-padding-bottom'), 10); var sidebarGap = panelExtraText ? parseInt(sidebarStyle.getPropertyValue('--sidebar-gap'), 10) : 0; var sidebarHeight = panelMainHeight + panelExtraTextHeight + sidebarPaddingTop + sidebarPaddingBottom + sidebarGap; return sidebarHeight; } function applyHeightToElement(element, newHeight) { element.style.height = newHeight + 'px'; } } /** * Метод нужен для явной типизации менеджера шагов. * @param {Element} quizWrapper элемент с классом .t-quiz__quiz-wrapper */ function t_quiz__getStepsManager(quizWrapper) { /** @type {StepsManager} */ const StepsManager = quizWrapper.StepsManager; return StepsManager; } /** * Функция, которая вызывается после успешной отправки формы. * @param {HTMLFormElement} form */ function t_quiz__onSuccess(form) { if (!(form instanceof Element)) form = form[0]; const quizWrapper = form.querySelector('.t-quiz__quiz-wrapper'); const StepsManager = t_quiz__getStepsManager(quizWrapper); const prevStep = StepsManager.getCurrentStepInfo(); if (!prevStep.isLast) return; const prevStepElem = prevStep.step?.element; prevStepElem && t_quiz__pauseVideos(prevStepElem); StepsManager.go( 'next', { onNewStepAnimationStart: (_, newStep) => { const { element } = newStep; const shouldRedirect = element && element.classList.contains('t-quiz__result_redirect'); if (shouldRedirect) { const successStep = form.querySelector('.t-quiz__result_ordinary'); // Показываем вместо пустого редиректа сообщение об успешной отправке element.classList.remove('t-step-form__step_active'); successStep.classList.add('t-step-form__step_active'); t_quiz__show(successStep); setTimeout(() => { t_quiz__handleRedirectResult(element); }, 500); } }, }, { isOnSuccess: true } ); } function t_quiz__handleRedirectResult(redirectStep) { if (!redirectStep) return; const allrecords = document.getElementById('allrecords'); const mode = allrecords.getAttribute('data-tilda-mode'); if (mode === 'edit') return; const successUrlResult = redirectStep.getAttribute('data-result-url'); window.location.href = successUrlResult; } // #region POPUP /** * Инициализирует попап * @param {HTMLElement} rec */ function t_quiz__openToHook(rec) { var popup = rec.querySelector('.t-popup'); var popupCloseBtns = rec.querySelectorAll('.t-popup__close'); var hook = popup.getAttribute('data-tooltip-hook'); var virtPage = popup.getAttribute('data-track-popup'); // It is necessary to save the function call through the bind, for deletion later var escapeEvent = escClosePopup.bind(popup, rec); if (hook) { document.addEventListener('click', function (event) { var href = event.target.closest('a[href="' + hook + '"]'); if (href) { event.preventDefault(); showPopup(rec, escapeEvent); setTimeout(function () { t_quiz__adjustStepToHeight({ rec }, true); }, 50); t_quiz__runLazyLoad(); t_quiz__displayStickyBtnWrapper(rec); processUrlsInsidePopup(); if (virtPage) { sendOpenPopupToAnalytics(virtPage, hook); } } }); // a11y: добавляет необходимые классы для кнопки-тригера t_onFuncLoad('t_popup__addClassOnTriggerButton', function () { t_popup__addClassOnTriggerButton(document, hook); }); // a11y: добавляет необходимые атрибуты для кнопки-тригера t_onFuncLoad('t_popup__addAttributesForAccessibility', function () { t_popup__addAttributesForAccessibility(hook); }); } // Закрываем попап по клику вне контейнера popup.addEventListener('click', function (event) { if (event.target === this) closePopup(rec, escapeEvent); }); if (popupCloseBtns.length > 0) { popupCloseBtns.forEach(function (closeBtn) { closeBtn.addEventListener('click', function () { closePopup(rec, escapeEvent); }); }); } /** Отправляет событие открытия попапа */ function sendOpenPopupToAnalytics(virtPage, hook) { const analytics = t_quiz__analytics({ rec }); analytics && analytics.openPopup(virtPage, hook); } /** * Обрабатывает урлы внутри попапа */ function processUrlsInsidePopup() { var hrefs = rec.querySelectorAll('a[href*="#"]'); hrefs.forEach(function (href) { href.addEventListener('click', function () { var url = this.getAttribute('href'); if (!url || (url.substring(0, 7) != '#price:' && url.substring(0, 7) != '#order:')) { closePopup(rec, escapeEvent); if (!url || url.substring(0, 7) == '#popup:') { setTimeout(function () { if (typeof t_triggerEvent === 'function') t_triggerEvent(document.body, 'popupShowed'); document.body.classList.add('t-body_popupshowed'); }, 300); } } }); }); var submitBtn = popup.querySelector('.t-submit'); var submitHref = submitBtn && submitBtn.getAttribute('href'); if (submitHref && submitHref.substring(0, 7) === '#order:') { submitBtn.addEventListener('click', function () { closePopup(rec, escapeEvent); }); } } /** * Открывает попап * @param {HTMLElement} rec * @param {EventListener} escapeEvent */ function showPopup(rec, escapeEvent) { var popup = rec.querySelector('.t-popup'); popup.style.display = 'block'; var body = document.body; t_triggerEvent(body, 'popupShowed'); body.classList.add('t-body_popupshowed'); body.classList.add('t-quiz__body_popupshowed'); t_quiz__runLazyLoad(); var range = rec.querySelector('.t-range'); if (range) t_triggerEvent(range, 'popupOpened'); setTimeout(function () { popup.focus(); popup.classList.add('t-popup_show'); var popupContainer = popup.querySelector('.t-popup__container'); popupContainer.classList.add('t-popup__container-animated'); // Добавляем класс, чтобы при переключении шагов // не было дерганой анимации при увеличении высоты попапа popupContainer.classList.add('t-popup__container_no-transform'); // a11y: добавляем ловушку для фокуса при взаимодействии с клавиатуры t_onFuncLoad('t_popup__trapFocus', function () { t_popup__trapFocus(popup); }); var windowWidth = window.innerWidth; if (windowWidth <= 640) setMobileHeight(); showJivo('1', '1'); }, 50); // Фикс для iOS11: проблемы с курсором и прокруткой фона if (/iPhone|iPad|iPod/i.test(navigator.userAgent) && !window.MSStream) { setTimeout(function () { lockScroll(); }, 500); } document.addEventListener('keydown', escapeEvent); } /** * Закрывает попап * @param {HTMLElement} rec * @param {EventListener} escapeEvent */ function closePopup(rec, escapeEvent) { var popup = rec.querySelector('.t-popup'); var popupContainer = popup.querySelector('.t-popup__container'); var popupActive = document.querySelector('.t-popup.t-popup_show'); const activeStep = rec.querySelector('.t-step-form__step_active'); if (activeStep) { t_quiz__pauseVideos(activeStep); } if (popup === popupActive) { var body = document.body; t_triggerEvent(body, 'popupHidden'); body.classList.remove('t-body_popupshowed'); body.classList.remove('t-quiz__body_popupshowed'); } popup.classList.remove('t-popup_show'); popupContainer.style.removeProperty('transition'); popupContainer.classList.remove('t-popup__container_no-transform'); // Фикс для iOS11: проблемы с курсором и прокруткой фона if (/iPhone|iPad|iPod/i.test(navigator.userAgent) && !window.MSStream) { unlockScroll(); } // a11y: возвращаем фокус на кнопку-триггер t_onFuncLoad('t_popup__addFocusOnTriggerButton', function () { t_popup__addFocusOnTriggerButton(); }); showJivo('2147483647', '2147483648'); setTimeout(function () { var popupsHide = document.querySelectorAll('.t-popup:not(.t-popup_show)'); popupsHide.forEach(function (popup) { popup.style.display = 'none'; }); }, 300); document.removeEventListener('keydown', escapeEvent); } /** * Устанавливает высоту на мобильных устройствах в vh */ function setMobileHeight() { calculateVH(); window.addEventListener('resize', calculateVH); } /** * Вычисляет значение vh в зависимости от высоты окна */ function calculateVH() { var vh = window.innerHeight * 0.01; document.documentElement.style.setProperty('--vh', vh + 'px'); } /** * Блокирует скролл и фиксирует его позицию */ function lockScroll() { var documentBody = document.body; if (!documentBody.classList.contains('t-body_scroll-locked')) { var bodyScrollTop = window.scrollY || documentBody.scrollTop; documentBody.classList.add('t-body_scroll-locked'); documentBody.style.top = '-' + bodyScrollTop + 'px'; documentBody.setAttribute('data-popup-scrolltop', bodyScrollTop); } } /** * Убирает блокировку скролаа */ function unlockScroll() { var documentBody = document.body; if (documentBody.classList.contains('t-body_scroll-locked')) { var bodyScrollTop = documentBody.getAttribute('data-popup-scrolltop'); documentBody.classList.remove('t-body_scroll-locked'); documentBody.style.top = ''; documentBody.removeAttribute('data-popup-scrolltop'); window.scrollTo(0, parseInt(bodyScrollTop)); } } /** * Закрывает попап по нажатию на Esc * @param {HTMLElement} rec * @param {EventListener} escapeEvent */ function escClosePopup(rec, escapeEvent) { if (escapeEvent.key === 'Escape') { closePopup(rec, escapeEvent); } } /** * Показывает виджет JivoChat * @param {number} indexMobile * @param {number} indexDesktop */ function showJivo(indexMobile, indexDesktop) { var jivoBtn = document.querySelectorAll('._show_1e.wrap_mW.__jivoMobileButton'); for (var i = 0; i < jivoBtn.length; i++) { jivoBtn[i].style.zIndex = indexMobile; } var jivoLabel = document.querySelectorAll('.label_39#jvlabelWrap'); for (var i = 0; i < jivoLabel.length; i++) { jivoLabel[i].style.zIndex = indexDesktop; } } } /** * Изменяет позиционирование попапа при его ресайзе * @param {HTMLElement} rec * @param {number} newHeight */ function t_quiz__resizePopup(rec, newHeight) { // margin 65px, берем 60, чтобы не было краевых кейсов var STATIC_POPUP_VERTICAL_PADDING = 60 * 2; var availableWindowHeight = window.innerHeight - STATIC_POPUP_VERTICAL_PADDING; var popupContainer = rec.querySelector('.t-popup__container'); var popupContainerStyle = getComputedStyle(popupContainer, null); var popupContainerPaddingTop = parseInt(popupContainerStyle.paddingTop) || 0; var popupContainerPaddingBottom = parseInt(popupContainerStyle.paddingBottom) || 0; var popupContainerHeight = popupContainer.clientHeight - (popupContainerPaddingTop + popupContainerPaddingBottom); var height = newHeight || popupContainerHeight; // Проверяем, помещается ли попап в доступное пространство окна var fitsInWindow = height <= availableWindowHeight; if (fitsInWindow) { popupContainer.classList.remove('t-popup__container-static'); } else { popupContainer.classList.add('t-popup__container-static'); } } //#endregion function t_quiz__isMobile() { return window.isMobile || window.innerWidth <= 640; } /** * * @param {HTMLElement} step */ function t_quiz__updateRangeSlider(step) { var ranges = step.querySelectorAll('.t-range'); if (ranges.length > 0) { ranges.forEach(function (range) { t_triggerEvent(range, 'displayChanged'); }); } } // Функция временно продублирована из tilda-scrits для избежания проблем с кэшем function t_triggerEvent(el, eventName) { var event; if (document.createEvent) { event = document.createEvent('HTMLEvents'); event.initEvent(eventName, true, false); } else if (document.createEventObject) { event = document.createEventObject(); event.eventType = eventName; } event.eventName = eventName; if (el.dispatchEvent) { el.dispatchEvent(event); } else if (el.fireEvent) { el.fireEvent('on' + event.eventType, event); } else if (el[eventName]) { el[eventName](); } else if (el['on' + eventName]) { el['on' + eventName](); } } function t_quiz__debounce(callee, timeoutMs) { var timeoutId; return function () { var args = Array.prototype.slice.call(arguments); clearTimeout(timeoutId); timeoutId = setTimeout(function () { callee.apply(null, args); }, timeoutMs); }; } /** * * @param {Element} videoContainer * @return {Promise} */ function t_quiz__proccessVideo(videoContainer) { return new Promise((resolve, reject) => { t_onFuncLoad('t_video__createPlayer', () => { t_video__createPlayer(videoContainer, { videoBlockId: t_quiz__getVideoId(videoContainer), jsApi: true, playsinline: true, }) .then(player => resolve(player)) .catch(reason => reject(reason)); }); }); } /** * * @param {Element} currentStep */ function t_quiz__initStepVideos(currentStep) { const PROCCESS_ATTR = 'data-qz-video-processed'; const wrappers = currentStep.querySelectorAll('.t-quiz__step__video-wrapper'); if (!wrappers.length) return; wrappers.forEach(videoWrapper => { if (videoWrapper.hasAttribute(PROCCESS_ATTR)) return; videoWrapper.setAttribute(PROCCESS_ATTR, 'true'); t_quiz__proccessVideo(videoWrapper).catch(() => { videoWrapper.removeAttribute(PROCCESS_ATTR); }); }); } /** * @param {Element} wrapper элемент, внутри которого происходит поиск видео * @param {string} [videoSelector] по умолчанию - .t-quiz__step__video-wrapper */ function t_quiz__pauseVideos(wrapper, videoSelector = '.t-quiz__step__video-wrapper') { const wrappers = wrapper.querySelectorAll(videoSelector); if (!wrappers.length) return; t_quiz__media__handlePauseVideos(wrappers); } /** * @param {Element[] | NodeListOf} videos */ function t_quiz__media__handlePauseVideos(videos) { t_onFuncLoad('t_video__getPlayer', () => { videos.forEach(videoWrapper => { const player = t_video__getPlayer(videoWrapper); if (player) { player.pause(); } else { t_quiz__proccessVideo(videoWrapper).then(player => player.pause()); } }); }); } /** * @param {Element} videoContainer */ function t_quiz__getVideoId(videoContainer) { const inputGroup = videoContainer.closest('.t-input-group'); if (!inputGroup) return t_quiz__uniqueId(); const lid = inputGroup.getAttribute('data-input-lid'); return lid; } function t_quiz__uniqueId() { return `${Date.now() - Math.floor(Math.random() * 1000) + 10}`; } /** * Объект аналитики должен создаваться только один раз, чтобы правильно работала очередь. * * Если для блока уже инициализровали аналитику, то вернется ранее добавленный инстанс. Если аналитики еще нет, то она будет создана. * * Очередь используется для того, чтобы события отправлялись в правильно порядке. * @param {{ rec: Element }} params * @returns {QuizAnalytics | undefined} */ function t_quiz__analytics(params) { const { rec } = params; if ('QuizAnalytics' in rec) { return rec.QuizAnalytics; } // если по какой-то причине не доступны методы аналитики, то скипаем if (!window.Tilda || !window.Tilda.sendEventToStatistics) return; const formId = rec.querySelector('.t-form').id; const queue = t_quiz__analyitcs__tildaStatQueue(); const viewedSteps = new Set(); /** @type {QuizAnalytics} */ const events = { viewStep: stepOrder => { const stepVirtPage = `/tilda/${formId}/step${stepOrder}`; if (viewedSteps.has(stepVirtPage)) return; viewedSteps.add(stepVirtPage); queue.add(() => { window.Tilda.sendEventToStatistics(stepVirtPage); }); }, openPopup: (virtPage, hook) => { const title = hook.startsWith('#popup:') ? hook.replace('#popup:', '') : hook; queue.add(() => { window.Tilda.sendEventToStatistics(virtPage, title); }); }, restart: () => { viewedSteps.clear(); }, }; rec.QuizAnalytics = events; return events; } /** * Создает очередь для работы с tilda-stat. * * - Если tilda-stat готов к работе, то события отправляются сразу после добавления. * - Если tilda-stat не готов, то события добавляются в очередь и будут отправлены после инициализвции tilda-stat. */ function t_quiz__analyitcs__tildaStatQueue() { const queue = []; let waitForStatInterval; const isStatReady = () => window.tildastatload === true; const runQueue = () => { while (queue.length > 0) { // first-in-first-out const cb = queue.shift(); cb(); } }; const runQueueWhenReady = () => { if (isStatReady()) { return runQueue(); } if (waitForStatInterval) return; waitForStatInterval = setInterval(() => { if (isStatReady()) { clearInterval(waitForStatInterval); runQueue(); } }, 300); }; const addToQueue = cb => { queue.push(cb); runQueueWhenReady(); }; return { add: addToQueue, }; } /** * * @param {Element} quiz */ function t_quiz__applyTranslation(quiz) { const stepCounter = quiz.querySelector('.t-quiz__counter-title'); if (stepCounter) { stepCounter.textContent = t_quiz__translate('step'); } } /** * @param {string} key */ function t_quiz__translate(key) { const dict = { step: { RU: 'Шаг: ', EN: 'Step: ', DE: 'Schritt: ', ES: 'Paso: ', PT: 'Passo: ', FR: 'Étape: ', JA: 'ステップ:', ZH: '步骤:', UK: 'Крок: ', PL: 'Krok: ', KK: 'Қадам: ', IT: 'Passo: ', LV: 'Solis: ', }, }; if (!dict[key]) return key; const lang = t_quiz__getLang() || 'EN'; return dict[key][lang]; } function t_quiz__getLang() { const allrecords = document.getElementById('allrecords'); const projectLang = allrecords.getAttribute('data-tilda-project-lang'); if (projectLang) { return projectLang; } const browserLang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2); return browserLang; }