/** * @typedef {Object} Step * @property {HTMLElement | undefined} element * @property {'step' | 'cover' | 'result' | 'contacts'} type */ /** @typedef {'next' | 'prev'} TransitionDirection */ /** * @typedef {(direction: 'next' | 'prev', callbacks?: AnimationCallbacks, transitionInfo?: TransitionInfo) => CurrentStepInfo} ChangeStepHandler */ /** * @typedef {{ isAutoTransition?: boolean, isOnSuccess?: boolean }} TransitionInfo */ /** * @typedef {Object} CurrentStepInfo * @property {Step['type']} type * @property {boolean} isFirst * @property {boolean} isLast - после шага нет вопросов и формы контактов * @property {boolean} isFinal - после шага нет видимых шагов, кроме сообщения об успешной отправке * @property {Step | null} step */ /** * @typedef {(direction: TransitionDirection, stepInfo: CurrentStepInfo, transitionInfo?: TransitionInfo) => boolean} TransitionGuard */ /** * @typedef {Object} ActiveStep * @property {number} index * @property {Step | null | undefined} step */ /** * @typedef {Object} Progress * @property {number} total * @property {number | null} current - если null, то счетчик не выводится */ /** @typedef {'fade' | 'fade-with-move'} AnimationType */ /** @typedef {Record} AnimationTypeConfig */ /** * @typedef {Object} AnimationCallbacks * @property {(oldStep?: Step, newStep: Step) => void} onAnimationStart функция, выполняемая перед началом анимации. * @property {(oldStep?: Step, newStep: Step) => void} onAnimationComplete функция, выполняемая после завершения анимации. * @property {(oldStep?: Step, newStep: Step) => void} onNewStepAnimationStart функция, выполняемая после начала анимации появления нового шага. */ /** * @typedef {Object} StepAnimation * @property {AnimationType | AnimationTypeConfig} type * @property {AnimationCallbacks} callbacks */ /** * @typedef {Object} StepManagerInitOptions * @property {string} recId * @property {Step[]} steps * @property {HTMLElement | null} [successStepElement] шаг с сообщением об успешной отправке, который показывается только после отправки формы * @property {string} activeStepClass * @property {string} hiddenStepClass * @property {boolean} [enableAutoStepChange] * @property {(step: Step) => void} onStepChange * @property {(progress: Progress) => void} onProgressChange * @property {(event: Event) => void} onConditionalStateChange * @property {() => void | undefined} onInit * @property {(oldStep: Step, newStep: Step) => void} handleStepAnimation * @property {StepAnimation} [animation] * @property {boolean} [enableConditionals] * @property {TransitionGuard} [checkIfCanChangeStep] функция, которая будет вызываться перед началом смены шага. Если возвращает false, смена шага не произойдет */ /** * @typedef {ReturnType} StepsManager */ /** * @typedef {ReturnType} StepsManager */ /** * @param {StepManagerInitOptions} initOptions */ function t_quiz__step_manager( initOptions = { steps: [], activeStepClass: '', } ) { const INITIAL_ACTIVE_STEP = { index: -1, step: null, }; const steps = initOptions.steps; const activeStepClass = initOptions.activeStepClass || 't-step-form__step_active'; const hiddenStepClass = initOptions.hiddenStepClass || 't-quiz-hidden'; const animation = initOptions.animation; const isConditional = initOptions.enableConditionals; const autoStepChangeEnabled = initOptions.enableAutoStepChange; let autoStepChangeInProgress = false; let autoStepChangeTimer; let autoStepChangeDuration = 300; /** @type {ActiveStep} */ let activeStep = INITIAL_ACTIVE_STEP; /** * @param {Step} step */ function activateStep(step) { step.element.classList.add(activeStepClass); step.element.classList.remove(hiddenStepClass); } /** * @param {Step} step */ function deactivateStep(step) { step.element.classList.remove(activeStepClass); step.element.classList.add(hiddenStepClass); } /** * @param {Step} step */ function isStepHidden(step) { const innerFields = step.element.querySelectorAll('.t-quiz__step__input'); const allInnerFieldsHidden = innerFields.length && Array.from(innerFields).every(function (field) { return t_quiz__isElementHidden(field); }); return t_quiz__isElementHidden(step.element) || allInnerFieldsHidden; } /** @type {() => ActiveStep} */ function getNextActiveStep() { var nextStepIndex = steps.findIndex(function (step, index) { return index > activeStep.index && !isStepHidden(step); }); var index = Math.min(steps.length, nextStepIndex); return { index: index, step: steps[index], }; } /** @type {() => ActiveStep} */ function getPrevActiveStep() { const activeIndex = activeStep.index; let prevStepIndex = activeIndex === -1 ? steps.length - 1 : activeIndex - 1; for (var i = prevStepIndex; i >= 0; i--) { var step = steps[i]; if (!isStepHidden(step)) { prevStepIndex = i; break; } } const index = Math.max(0, prevStepIndex); return { index: index, step: steps[index], }; } /** * @param {Step['type'][]} types * @returns Step[] */ function getStepsByTypes(types) { return steps.filter(function (step) { return types.indexOf(step.type) !== -1 && !isStepHidden(step); }); } function getStepsProgress() { var basicSteps = getStepsByTypes(['step', 'contacts']); var current = basicSteps.indexOf(activeStep.step); return { total: basicSteps.length, current: current === -1 ? null : current + 1, }; } /** @type {ChangeStepHandler} */ function go(direction, callbacks, transitionInfo) { var prevStep = activeStep.step; if (initOptions.checkIfCanChangeStep) { const canTransition = initOptions.checkIfCanChangeStep(direction, getCurrentStepInfo(), transitionInfo); if (!canTransition) return; } var nextStep = direction === 'next' ? getNextActiveStep() : getPrevActiveStep(); activeStep = nextStep; const info = getCurrentStepInfo(); switchSteps(prevStep, nextStep.step, callbacks); return info; } function getVisibleSteps() { // Текущий шаг может быть скрыт с помощью калькулятора, но он нужен нам всегда для правильного расчета return steps.filter(step => !isStepHidden(step) || step === activeStep.step); } function isActiveStepLast() { const visibleSteps = getVisibleSteps(); const index = visibleSteps.indexOf(activeStep.step); const nextSteps = visibleSteps.splice(index + 1); const isLastStep = nextSteps.every(step => step.type !== 'step' && step.type !== 'contacts'); return isLastStep; } /** * Шаг финальный, если дальше перейти некуда. * Шаг с сообщением об успешной отправке не учитываем, он показывается только после отправки формы. */ function isActiveStepFinal() { const nextStep = getNextActiveStep().step; return !nextStep || nextStep.element === initOptions.successStepElement; } function isActiveStepFirst() { const visibleSteps = getVisibleSteps(); const index = visibleSteps.indexOf(activeStep.step); const prevSteps = visibleSteps.splice(0, index); return prevSteps.length === 0; } function getCurrentStepInfo() { /** @type {CurrentStepInfo} */ const info = { type: activeStep.step?.type, index: activeStep.index, isFirst: isActiveStepFirst(), isLast: isActiveStepLast(), isFinal: isActiveStepFinal(), step: activeStep.step, }; return info; } function initAutoStepChange() { var typesWithSkip = ['ri', 'rd', 'rs', 'sb', 'cb']; var stepsWithAutoSkip = steps.filter(function (step) { var stepElement = step.element; var inputsWrapper = stepElement.querySelector('.t-quiz__inputs-wrapper'); if (inputsWrapper) return; var inputGroup = stepElement.querySelector('.t-input-group'); if (!inputGroup) return; var supportsAutoChange = typesWithSkip.includes(inputGroup.getAttribute('data-field-type')); var isCheckboxesVariants = inputGroup.getAttribute('data-field-radcb') === 'cb'; return supportsAutoChange && !isCheckboxesVariants; }); stepsWithAutoSkip.forEach(function (step) { var inputGroups = Array.from(step.element.querySelectorAll('.t-input-group')); inputGroups.forEach(function (inputGroup) { inputGroup.addEventListener('change', event => { const isOwnVariant = event.target.classList.contains('t-radio-ownanswer') || event.target.classList.contains('t-input-ownanswer'); if (isOwnVariant) return; handleAutoStepChange(); }); }); }); } function handleAutoStepChange() { if (autoStepChangeInProgress) return; autoStepChangeInProgress = true; autoStepChangeTimer = setTimeout(function () { go('next', {}, { isAutoTransition: true }); }, autoStepChangeDuration); } function resetAutoStepChangeProgress() { if (!autoStepChangeEnabled) return; clearTimeout(autoStepChangeTimer); autoStepChangeInProgress = false; } /** * * @param {Step | undefined} oldStep * @param {Step} newStep * @param {AnimationCallbacks} [callbacks] */ function switchSteps(oldStep, newStep, callbacks = {}) { const { onStepChange, onProgressChange } = initOptions; const { onAnimationComplete, onAnimationStart, onNewStepAnimationStart } = animation.callbacks || {}; if (!animation) { oldStep && deactivateStep(oldStep); activateStep(newStep); onStepChange && onStepChange(newStep); onProgressChange && onProgressChange(getStepsProgress()); onAnimationComplete && onAnimationComplete(oldStep, newStep); callbacks.onAnimationComplete && callbacks.onAnimationComplete(oldStep, newStep); resetAutoStepChangeProgress(); return; } t_quiz__animateSteps( oldStep, newStep, { onAnimationStart: function (oldStep, newStep) { onAnimationStart && onAnimationStart(oldStep, newStep); callbacks.onAnimationStart && callbacks.onAnimationStart(oldStep, newStep); }, onNewStepAnimationStart: function (oldStep, newStep) { onNewStepAnimationStart && onNewStepAnimationStart(oldStep, newStep); callbacks.onNewStepAnimationStart && callbacks.onNewStepAnimationStart(oldStep, newStep); onStepChange && onStepChange(newStep); onProgressChange && onProgressChange(getStepsProgress()); resetAutoStepChangeProgress(); }, onAnimationComplete: function (oldStep, newStep) { onAnimationComplete && onAnimationComplete(oldStep, newStep); callbacks.onAnimationComplete && callbacks.onAnimationComplete(oldStep, newStep); }, }, { animation: { in: getAnimationConfigForStep(newStep), out: getAnimationConfigForStep(oldStep), }, stepActiveClass: activeStepClass, stepHiddenClass: hiddenStepClass, } ); } /** * @param {Step} [step] * @returns {AnimationType} */ function getAnimationConfigForStep(step) { if (!step || typeof animation === 'string') { return animation; } return animation.type[step.type] || 'fade-with-move'; } function init() { if (isConditional) { t_onFuncLoad('t_form__conditionals_initFields', function () { var conditionalFields = t_form__conditionals_initFields(initOptions.recId); conditionalFields.addListeners(function () { initOptions.onProgressChange && initOptions.onProgressChange(getStepsProgress()); }); conditionalFields.addStateChangeListeners(function (event) { initOptions.onConditionalStateChange && initOptions.onConditionalStateChange(event); }); if (autoStepChangeEnabled) initAutoStepChange(); go('next', { onAnimationComplete: initOptions.onInit }); }); } else { if (autoStepChangeEnabled) initAutoStepChange(); go('next', { onAnimationComplete: initOptions.onInit }); } } function restart() { // Сбрасываем отображение текущего шага deactivateStep(activeStep.step); // Возвращаем состояния в первоначальный вид activeStep = INITIAL_ACTIVE_STEP; // Включаем первый шаг go('next'); } return { go, init, restart, getStepsProgress, getCurrentStepInfo, }; } /** * * @param {Step | undefined} oldStep шаг, который нужно скрыть * @param {Step} newStep шаг, который нужно показать * @param {AnimationCallbacks} callbacks * @param {{ * animation: { * in: AnimationType, * out: AnimationType, * }, * stepActiveClass: string * stepHiddenClass: string * }} options */ function t_quiz__animateSteps(oldStep, newStep, callbacks, options) { var FADE_IN_DURATION_MS = 700; var FADE_OUT_DURATION_MS = 400; /** @type {FillMode} */ var DEFAULT_FILL = 'forwards'; var DEFAULT_EASING = 'ease-in-out'; const { animation: animationConfig = { in: 'fade-with-move', out: 'fade-with-move', }, stepActiveClass, stepHiddenClass, } = options || {}; const noop = () => {}; const { onAnimationComplete = noop, onAnimationStart = noop, onNewStepAnimationStart = noop } = callbacks || {}; const supportsWebAnimationsAPI = !!document.body.animate; if (!supportsWebAnimationsAPI) { onAnimationStart(oldStep, newStep); oldStep && oldStep.element.classList.remove(stepActiveClass); oldStep && oldStep.element.classList.add(stepHiddenClass); onNewStepAnimationStart(oldStep, newStep); newStep && newStep.element.classList.add(stepActiveClass); newStep && newStep.element.classList.remove(stepHiddenClass); onAnimationComplete(oldStep, newStep); return; } /** @param {HTMLElement} element */ function fadeIn(element) { var animation = element.animate( [ { opacity: 0, pointerEvents: 'none', }, { opacity: 1, pointerEvents: 'auto', }, ], { duration: FADE_IN_DURATION_MS, fill: DEFAULT_FILL, easing: DEFAULT_EASING, } ); animation.pause(); return animation; } /** @param {HTMLElement} element */ function fadeInUp(element) { var animation = element.animate( [ { transform: 'translateY(15px)', opacity: 0, pointerEvents: 'none', }, { transform: 'translateY(0px)', opacity: 1, pointerEvents: 'auto', }, ], { duration: FADE_IN_DURATION_MS, fill: DEFAULT_FILL, easing: DEFAULT_EASING, } ); animation.pause(); return animation; } /** @param {HTMLElement} element */ function fadeOut(element) { var animation = element.animate( [ { opacity: 1, pointerEvents: 'none', }, { opacity: 0, pointerEvents: 'auto', }, ], { duration: FADE_OUT_DURATION_MS, fill: DEFAULT_FILL, easing: DEFAULT_EASING, } ); animation.pause(); return animation; } /** @param {HTMLElement} element */ function fadeOutDown(element) { var animation = element.animate( [ { transform: 'translateY(0)', opacity: 1, pointerEvents: 'none', }, { transform: 'translateY(20px)', opacity: 0, pointerEvents: 'auto', }, ], { duration: FADE_OUT_DURATION_MS, fill: DEFAULT_FILL, easing: DEFAULT_EASING, } ); animation.pause(); return animation; } function handleFadeInEnd() { onAnimationComplete(oldStep, newStep); } function handleFadeOutEnd() { oldStep.element.classList.remove(stepActiveClass); oldStep.element.classList.add(stepHiddenClass); animateStepIn(); } function animateStepIn() { if (!newStep) { onNewStepAnimationStart(oldStep, newStep); handleFadeInEnd(); return; } var animation; if (animationConfig.in === 'fade-with-move') { animation = fadeInUp(newStep.element); } else { animation = fadeIn(newStep.element); } animation.finished.then(handleFadeInEnd); newStep.element.classList.remove(stepHiddenClass); newStep.element.classList.add(stepActiveClass); animation.play(); onNewStepAnimationStart(oldStep, newStep); } function animateStepOut() { var animation; if (animationConfig.out === 'fade-with-move') { animation = fadeOutDown(oldStep.element); } else { animation = fadeOut(oldStep.element); } animation.finished.then(handleFadeOutEnd); animation.play(); } onAnimationStart(oldStep, newStep); if (oldStep) { return animateStepOut(); } return animateStepIn(); } function t_quiz__isElementHidden(element) { return element.getAttribute('data-hidden-by-condition') === 'true' || element.classList.contains('t-form__hidden'); }