/** * В данном скрипте генерируется форма, которая в последствии добавляется в .tn-atom зеро-блока. * Элементы генерируются при помощи document.createElement. * Форма, которая находится за пределами видимости, или внутри скрытого зеро-блока, не рендерится. * Зеро-форма используется некоторые скрипты и стили из других библиотек Тильды, например, * tilda-phone-mask, tilda-calc, и тд. * * Все сгенерированные скрипты и стили добавляются вниз тега . * * Строки формируются в функции t_zeroForms__parseIntoElement, при помощи условий внутри * конструкции switch...case, где при итерации объекта проверяется определенное условие и если оно * true, создаётся HTML-элементы, сопутствующие к нему стили и скрипты (если они нужны). */ import { t396__decodeHtmlText, t396__getZeroBlocks, t396_elem__getFormInputsValue, t396__initScaleFactorFlags, t396__isGlobalStyleCSSVar, t396__parseGlobalStyleCSSVar, } from './tilda-zero-shared.module'; // Стили поля "Способ связи" встраиваются в скрипт, чтобы поле не отображалось без стилей, пока они загружаются import '../css/tilda-contact-method-1.0.css'; // Стили поля "Рейтинг" есть в tilda-forms-1.0.css, но в редакторе Zero Block он не подключается import '../src/tilda-forms/ratescale/styles.css'; // Стили кнопочного вида поля "Вопрос с вариантами ответа" в Zero Block, в редакторе tilda-forms-1.0.css тоже нет import '../src/tilda-forms/zero-variants-button/styles.css'; // Формы с разбиением на шаги. Общие стили шагов – те же, что в обычных блоках: в редакторе Zero Block их нет, // а на сайте tilda-step-form-1.1 подключает их только для обычных блоков import '../css/tilda-step-form-1.1.css'; // Дополнения только для Zero-форм: раскладка кнопок шагов и счетчика, скрытие шагов до инициализации import '../src/tilda-forms/zero-stepform/styles.css'; /** * Main property of this object - is li_type. * It's meat what type of form element user use: * 'em' - email * 'ph' - phone * 'nm' - name * 'in' - input (one line input field) * 'ta' - textarea * 'sb' - select box (dropdown) * 'rd' - radio (question with answers) * 'ri' - radio image (question with img answers) * 'cb' - checkbox * 'uw' - upload widget (file) * 'uc' - uploadcare plugin (file) * 'da' - date * 'tm' - time * 'qn' - plus/minus btn (quantity) * 'rg' - range slider (quantity) * 'ur' - website url * 'tx' - text comment * 'ws' - white space * 'hd' - hidden * 'fr' - formula (calculation field) * 'contact_method' - contact method (phone, telegram, whatsapp, etc.) * 'rs' - rating scale (numbers or icons) * * li_ph - placeholder value * li_name and li_nm in many types of elements contains same value - variable name * lid - id of current element * ls - index of current element * 10 (10, 20, 30, etc.) * loff - field is switched off, or not * * li_rule - validation rule, used in one line input field * li_rows used only in textarea and white space * li_value used in quantity (range, plus/minus btn) and hidden input * * properties for selects: * li_defselitem - default selected item * li_variants - list of options * li_selfirstvar - selected first option * * properties for 'question with img answers': * li_gallery - objects with img url, alts * li_imgratio - image ratio * in this type element value of 'li_name' can be different with 'li_nm' * * properties for 'checkbox': * li_checked - is checkbox checked by default * li_belowsubmit - is checkbox show below button * * properties for 'upload widget': * li_multiupl - can upload more than one file * li_uwkey - uplad widget public key * * properties for 'uploadcare': * li_inp - local lang * li_uckey - upladcare public key * * properties for 'date': * li_dateUnavailFr - unavailable Friday * li_dateUnavailToday - unavailable Today * li_dateUnavailFuture - unavailable Future * li_dateUnavailMo - unavailable Monday * li_dateUnavailPast - unavailable Past * li_dateUnavailSa - unavailable Saturday * li_dateUnavailSu - unavailable Sunday * li_dateUnavailTh - unavailable Thursday * li_dateUnavailTu - unavailable Tuesday * li_dateUnavailWe - unavailable Wednesday * li_datediv - separator value * li_dateformat: "DD-MM-YYYY" * li_datemask: "99/99/9999" * in this type element value of 'li_name' can be different with 'li_nm' * * properties for 'range slider': * li_step * li_vmax - max value * li_vmin - min value * * property for 'text comment': * li_text - text value * * properties for 'calculation field': * li_expr - expression * li_postfix * li_prefix * * properties for 'rating scale': * li_ratetype - 'numbers' | 'icons' * li_ratemin - first number: '0' | '1' * li_ratemax - last number (2-10) * li_rateiconsquantity - icons quantity (3-10) * li_ratetextstart, li_ratetextend - captions under the scale * * properties for 'contact method': * li_contact_methods - list of available contact methods ([{value: 'phone'}, {value: 'telegram'}]) * li_default_contact_method - default selected contact method * li_contact_method_type_nm - variable name for contact method type * li_contact_method_id_nm - variable name for contact method value * li_maskcountry - country code in phone mask * * @typedef { * { * li_name: string | undefined, * li_nm: string | undefined, * li_ph: string | undefined, * li_req: 'y' | undefined, * li_title: string | undefined, * li_subtitle: string | undefined, * li_type: 'em' | 'ph' | 'nm' | 'in' | 'ta' | 'sb' | 'rd' | 'ri' | 'cb' | 'uw' | 'uc' | 'da' | 'tm' | 'qn' | 'rg' | 'ur' | 'tx' * | 'ws' | 'hd' | 'fr' | 'contact_method' | 'rs', lid: string, loff: 'y' | '', * * li_rule: string | undefined, * * li_rows: string | undefined, * * li_value: string | undefined, * * li_defselitem: string | undefined, * li_variants: string | undefined, * li_isownvariant: 'y' | undefined, * li_ownvariant: string | undefined, * li_ownvariantph: string | undefined, * li_radiostyle: 'button' | undefined, * li_selfirstvar: string | undefined, * * li_gallery: string | undefined, * li_imgratio: string | undefined, * * li_img_fill_mode: string | undefined, * li_imgs_in_row_mob: string | undefined, * li_imgs_in_row: string | undefined, * * li_checked: 'y' | undefined, * li_belowsubmit: 'y' | undefined, * * li_multiupl: string | undefined, * li_uwkey: string | undefined, * * li_inp: string | undefined, * li_uckey: string | undefined, * * li_dateUnavailFr: 'y' | undefined, * li_dateUnavailFuture: 'y' | undefined, * li_dateUnavailMo: 'y' | undefined, * li_dateUnavailPast: 'y' | undefined, * li_dateUnavailSa: 'y' | undefined, * li_dateUnavailSu: 'y' | undefined, * li_dateUnavailTh: 'y' | undefined, * li_dateUnavailTu: 'y' | undefined, * li_dateUnavailWe: 'y' | undefined, * li_dateUnavailToday: 'y' | undefined, * li_datediv: 'slash' | 'dot' | 'dash' | undefined, * li_dateformat: 'DD-MM-YYYY' | 'MM-DD-YYYY' | 'YYYY-MM-DD' | undefined, * li_datemask: '99/99/9999' | '99.99.9999' | '99-99-9999' | '9999/99/99' | '9999.99.99' | '9999-99-99' | undefined, * * li_step: string | undefined, * li_vmax: string | undefined, * li_vmin: string | undefined, * * li_text: string | undefined, * * li_expr: string | undefined, * li_postfix: string | undefined, * li_prefix: string | undefined, * * li_mask: string | undefined, * li_masktype: 'a' | 'b' | undefined, * li_maskcountry: string | undefined, * * li_radcb: 'cb' | 'rb' | undefined, * li_label: string | undefined, * li_addtocart: string | undefined, * li_prod_title: string | undefined, * li_prod_img: string | undefined, * li_prod_options: string | undefined, * li_visually_hidden: 'y' | undefined, * * li_contact_methods: Array<{value: string}> | string | undefined, * li_default_contact_method: string | undefined, * li_contact_method_type_nm: string | undefined, * li_contact_method_id_nm: string | undefined, * * li_ratetype: 'numbers' | 'icons' | undefined, * li_ratemin: string | undefined, * li_ratemax: string | undefined, * li_rateiconsquantity: string | undefined, * li_ratetextstart: string | undefined, * li_ratetextend: string | undefined, * } * } FormObjectEl */ /** * In this object contains information about styles of current form, * and some information need to data transfer (name, success event, etc.) * @typedef { * { * inputpos: string | undefined, * fieldfontfamily: string | undefined, * inputfontfamily: string | undefined, * togglefontfamily: string | undefined, * inputfontsize: string | undefined, * inputfontweight: string | undefined, * inputvariationweight: string | undefined, * inputcolor: string | undefined, * inputbgcolor: string | undefined, * inputaccentcolor: string | undefined, * inputbordercolor: string | undefined, * inputbordersize: string | undefined, * inputradius: string | undefined, * inputheight: string | undefined, * inputmargbottom: string | undefined, * inputmargright: string | undefined, * inputtitlefontsize: string | undefined, * inputtitlefontweight: string | undefined, * inputtitlevariationweight: string | undefined, * inputtitlecolor: string | undefined, * togglelabelcolor: string | undefined, * inputelscolor: string | undefined, * inputelsfontsize: string | undefined, * inputelsfontweight: string | undefined, * inputelsvariationweight: string | undefined, * inputtitlemargbottom: string | undefined, * inputsstyle: string | undefined, * inputsstyle2: string | undefined, * togglesize: string | undefined, * togglebordersize: string | undefined, * checkboxborderradius: string | undefined, * buttontitle: string | undefined, * buttonalign: string | undefined, * buttoncolor: string | undefined, * uploadbuttonbgcolor: string | undefined, * uploadbuttontextcolor: string | undefined, * uploadbuttonbordercolor: string | undefined, * uploadbuttonbordersize: string | undefined, * buttonbgcolor: string | undefined, * buttonbordercolor: string | undefined, * buttonbordersize: string | undefined, * buttonradius: string | undefined, * buttonmargtop: string | undefined, * buttonwidth: string | undefined, * buttonwidthstretch: Boolean, * buttonheight: string | undefined, * buttonshadowsize: string | undefined, * buttonshadowopacity: string | undefined, * buttonfontfamily: string | undefined, * buttonfontsize: string | undefined, * buttonfontweight: string | undefined, * buttonvariationweight: string | undefined, * buttonuppercase: string | undefined, * buttonbgcolorhover: string | undefined, * buttoncolorhover: string | undefined, * buttonbordercolorhover: string | undefined, * buttonshadowsizehover: string | undefined, * buttonshadowopacityhover: string | undefined, * buttonspeedhover: string | undefined, * formmsgsuccess: string | undefined, * formmsgurl: string | undefined, * formerrreq: string | undefined, * formerremail: string | undefined, * formerrphone: string | undefined, * formerrname: string | undefined, * formbottomtext: string | undefined, * formbottomcb: string | undefined, * formname: string | undefined, * receivers: string | undefined, * inputfrbgcolor: string | undefined, * buttonhovercolor: string | undefined, * buttonhoverbgcolor: string | undefined, * buttonhoverbordercolor: string | undefined, * buttonhovershadowsize: string | undefined, * shouldUseTwoColumnRadioImg: Boolean * } * } formObj */ // prettier-ignore window.t_zeroForms__browserLang = (window.navigator.userLanguage || window.navigator.language).toUpperCase().slice(0, 2); // prettier-ignore window.t_zeroForms__isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent); window.t_zeroForms__isSafari = /^((?!chrome|android).)*safari/i.test(navigator.userAgent); window.t_zeroForms__isiOS = /iPhone|iPad|iPod/i.test(navigator.userAgent); window.t_zeroForms__iOSMajorVersion = ''; if (window.t_zeroForms__isiOS) { var version = navigator.appVersion.match(/OS (\d+)_(\d+)_?(\d+)?/); if (version !== null) { window.t_zeroForms__iOSMajorVersion = parseInt(version[1], 10); } } window.t_zeroForms__formIdMap = null; window.t_zeroForms__resourcesQueue = {}; /** * Language override based on attribute */ t_zeroForms__onReady(function () { var allrecords = document.getElementById('allrecords'); if (!allrecords) return; var projectLang = allrecords.getAttribute('data-tilda-project-lang'); if (projectLang) window.t_zeroForms__browserLang = projectLang; }); t_zeroForms__onReady(t_zeroForms__prepareFormsIds); /** * get formObject and init zeroForm * * @param {number| string} recid - record ID * @param {string} elemid - element ID * @param {{FormObjectEl}} formObjectEls */ function t_zeroForms__init(recid, elemid, formObjectEls) { var rec = document.getElementById('rec' + recid); const selector = `.tn-elem[data-fe-elem-id="${elemid}"], .tn-elem[data-elem-id="${elemid}"]`; var zeroForm = rec ? rec.querySelector(selector) : null; if (!zeroForm?.isConnected) return; var tildamode = t_zeroForms__getTildaMode(); var isOldPage = document.querySelector('script[src*="tilda-blocks-2.7"]'); t_zeroForms__waitForTN(function () { if (!zeroForm?.isConnected) return; t_zeroForms__renderForm(zeroForm, formObjectEls, recid, tildamode); // Обновляем позицию формы после того, как она приняла окончательный размер t_zeroForms__waitForFormReady(zeroForm, recid).then(() => { t396_elem__renderViewOneField(isOldPage ? $(zeroForm) : zeroForm, 'left'); t396_elem__renderViewOneField(isOldPage ? $(zeroForm) : zeroForm, 'top'); zeroForm.setAttribute('data-form-ready', true); }); }); } function t_zeroForms__waitForTN(cb) { if (window.tn && window.tn.curResolution) { cb(); } else { setTimeout(function () { t_zeroForms__waitForTN(cb); }, 300); } } /** * * @param {HTMLElement} zeroForm - current zero-block element (in our case - form) * @param {{FormObjectEl} | string} formObjectEls * @param {number | string | undefined} recid - record ID * @param {'edit' | 'preview' | 'published' | undefined} tildamode */ function t_zeroForms__renderForm(zeroForm, formObjectEls, recid, tildamode) { zeroForm = t_zeroForms__getEl(zeroForm); if (!tildamode) tildamode = t_zeroForms__getTildaMode(); if (!recid) recid = t_zeroForms__getRecID(zeroForm); var record = document.querySelector('.t-records'); var isEditMode = record ? record.getAttribute('data-tilda-mode') === 'edit' : false; if (!isEditMode) isEditMode = tildamode !== 'published'; if (zeroForm.classList.contains('zero-form-rendered') && !isEditMode) return; if (tildamode === 'published') t396__initScaleFactorFlags(); var rec = zeroForm.closest('.r'); if ((t_zeroForms__isRecordHidden(rec) || t_zeroForms__isFormOutside(zeroForm)) && tildamode === 'published') return; // if function inited from zero-block script, check typeof of formObjectEls, and update it, if it neseccary if (typeof formObjectEls === 'string') { try { formObjectEls = JSON.parse(formObjectEls); } catch (err) {} } if (!formObjectEls) { formObjectEls = t396_elem__getFormInputsValue(zeroForm); } /** * early versions of zero-editor create formObject as Objects inside Object, like this: * {0: {li_name: 'name', li_type: 'nm'}, 10: {li_name: 'phone', li_type: 'ph'}} * * Current version create Array with Objects, like this: * [{li_name: 'name', li_type: 'nm'}, {li_name: 'phone', li_type: 'ph'}] * * But we need to support both. For this we convert Object to Array * in function t_zeroForms__fromObjToArray. */ var arrayOfElements = t_zeroForms__fromObjToArray(formObjectEls); var zeroFormAtom = zeroForm.querySelector('.tn-atom'); if (tildamode === 'zero' || tildamode === 'edit') { zeroFormAtom.innerHTML = ''; } else if (zeroFormAtom.querySelector('.t-form')) return; var form = t_zeroForms__createForm(recid, tildamode, arrayOfElements, zeroForm); if (!form) return; zeroFormAtom.insertAdjacentElement('beforeend', form); t_zeroForms__placeFormIntoColumns(zeroForm); if (tildamode === 'published') { t_zeroForms__onFuncLoad('t_forms__initFormFields', function () { t_forms__initFormFields(zeroForm); }); } // Условия в форме с шагами инициализирует t_form__initStepForm var hasSteps = t_zeroForms__hasSteps(form); if (form.classList.contains('t-conditional-form')) { if (tildamode === 'zero') { // внутри скрипта t_form__conditionals_initFields вызывается t_onFuncLoad что недоступен в зиро t_zeroForms__onFuncLoad('t_form__conditionals_syncFields', function () { t_form__conditionals_syncFields(zeroForm, { shouldPreventSubmit: false, }); }); } else { t_zeroForms__onFuncLoad('t_form__conditionals_initFields', function () { const artBoard = document.querySelector('.t396__artboard'); if (artBoard) { const updateAutoHeight = t_debounce(() => { t396__updateAutoHeight(artBoard); }, 100); t_form__conditionals_addConditionalStateListeners(zeroForm, updateAutoHeight); } if (!hasSteps) t_form__conditionals_initFields(zeroForm); }); } } t_zeroForms__initSteps(zeroForm, recid, tildamode); var customElEvent = document.createEvent('Event'); customElEvent.initEvent('render', true, true); zeroForm.dispatchEvent(customElEvent); zeroForm.classList.add('zero-form-rendered'); // Сообщаем, что форма приняла окончательный размер. Например, редактор Zero Block пересчитывает по нему размер элемента t_zeroForms__waitForFormReady(zeroForm, recid).then(() => { zeroForm.dispatchEvent(new CustomEvent('zero:form-ready')); }); t_zeroForms__initMaskAfterRender(zeroForm); t_zeroForms__updateTopPosition(zeroForm); } /** * mask inited after DOMContentLoaded, but hidden forms not render. * We should initing them again, when hidden forms will be rendered. * * @param {HTMLElement} form */ function t_zeroForms__initMaskAfterRender(form) { t_zeroForms__onRender(form, true, function () { var hasMask = form.querySelector('.js-tilda-mask'); if (hasMask) { t_zeroForms__onFuncLoad('tildaForm_initMasks', function () { setTimeout(function () { var hasNotInitedMask = form.querySelector('.js-tilda-mask:not([data-tilda-mask-init="1"])'); if (hasNotInitedMask) { tildaForm_initMasks(); } }, 500); }); } }); } /** * Генерирует уникальные ID для форм внутри зероблоков. * ID генерируются по правилу: * 1) первая форма на странице имеет старый формат ID: `form` * 2) остальные формы используются составной уникальный ID: `form_` * * Для первой формы используется старый формат потому что при наличии одной формы в блоке нет проблем с уникальностью. * Во всех обучающих материалах и гайдах упоминается, что ID любой формы – `form`. * Чтобы не нарушать это правило и не ломать обратную совместимость в блоке всегда будет "главная форма" – первая. * * Благодаря такому решению мы сохраняем обратную совместимость и исправляем ситуацию с конфликтующими ID. */ function t_zeroForms__prepareFormsIds() { try { if (t_zeroForms__getTildaMode() === 'zero') { t_zeroForm__prepareFormIds__editor(); return; } if (window.t_zeroForms__formIdMap) return; const zeroBlocks = t396__getZeroBlocks(); const zeroBlocksWithForms = zeroBlocks .map(({ record, artboard }) => { const forms = Array.from(record.querySelectorAll('.tn-elem[data-elem-type="form"]')); if (!forms.length) return null; const recId = artboard.getAttribute('data-artboard-recid'); const idsMap = t_zeroForms__prepareFormIds__buildFormsIdsMap(recId, forms); return [recId, idsMap]; }) .filter(Boolean); window.t_zeroForms__formIdMap = Object.fromEntries(zeroBlocksWithForms); } catch (e) { console.error('Failed to generate form ids for zero forms', e); } } /** * @param {string} recId * @param {Element[]} forms * @returns {Record} */ function t_zeroForms__prepareFormIds__buildFormsIdsMap(recId, forms) { return forms .map(form => form.getAttribute('data-elem-id')) .filter(Boolean) .sort() // сортируем id для определения первой формы .reduce((acc, elementId, index) => { if (index === 0) { // Для первой формы на странице используется простой id acc[elementId] = `form${recId}`; } else { // Для остальных форм на странице используется составной id для уникальности acc[elementId] = `form${recId}_${elementId}`; } return acc; }, {}); } /** * Специальная функция получения ID форм внутри редактора зеро. * В редакторе не выполняется кэширования ID. * Пересчет значений выполняется для каждой формы отдельно из-за особенность рендеринга. */ function t_zeroForm__prepareFormIds__editor() { const recId = window.tn ? window.tn.artboard_id : document.querySelector('.tn-artboard')?.getAttribute('data-record-id'); const forms = Array.from(document.querySelectorAll('.tn-elem[data-elem-type="form"]')); if (!forms.length || !recId) return; window.t_zeroForms__formIdMap = { [recId]: t_zeroForms__prepareFormIds__buildFormsIdsMap(recId, forms), }; } function t_zeroForms__getFormId(recId, elementId) { const DEFAULT_ID = `form${recId}`; try { if (!t_zeroForms__getFormId__isOpenForRec(recId)) { return DEFAULT_ID; } t_zeroForms__prepareFormsIds(); return window.t_zeroForms__formIdMap[recId][elementId] || DEFAULT_ID; } catch (e) { return DEFAULT_ID; } } function t_zeroForms__getFormId__isOpenForRec(recId) { const userRole = t396_zeroForms__getUserRole(); const requiredRecId = { team: 1244968076, tester: 1335496281, basic: 1524873151, }[userRole]; return requiredRecId ? Number(recId) >= requiredRecId : false; } function t_zeroForms__createForm(recid, tildamode, arrayOfElements, zeroForm) { if (!tildamode) tildamode = t_zeroForms__getTildaMode(); var formObj = t_zeroForms__createFormObj(recid, zeroForm); var isPublished = tildamode === 'published'; var arrayOfElsWithoutHiddenFiels = arrayOfElements.filter(function (field) { return field.loff !== 'y' && field.li_type !== 'hd'; }); var form = document.createElement(isPublished ? 'form' : 'div'); var elementId = zeroForm.getAttribute('data-elem-id'); form.classList.add('t-form'); form.classList.add('t-form_inputs-total_' + arrayOfElsWithoutHiddenFiels.length); // .t-form_bbonly class append, when in zero-editor set for form input style: only border-bottom if (formObj.inputsstyle) form.classList.add('t-form_bbonly'); // append horizontal styles, if them sets to current form if (formObj.inputpos === 'h') form.classList.add('tn-form_horiz'); // for published version set more data and values, then for editor, or preview if (isPublished) { const formId = t_zeroForms__getFormId(recid, elementId); form.id = formId; form.name = formId; form.action = 'https://forms.tildacdn.com/procces/'; form.method = 'POST'; form.classList.add('js-form-proccess'); form.setAttribute('role', 'form'); form.setAttribute('data-formactiontype', '2'); form.setAttribute('data-inputbox', '.t-input-group'); form.setAttribute('data-success-callback', 't396_onSuccess'); form.setAttribute('data-success-popup', 'y'); form.setAttribute('data-error-popup', 'y'); if (formObj.formmsgurl) form.setAttribute('data-success-url', formObj.formmsgurl); } // append to form hidden inputs var formReceiversArr = formObj.receivers ? formObj.receivers.split(',') : []; formReceiversArr.forEach(function (receiverValue) { var hiddenInput = t_zeroForms__createHiddenField(receiverValue, 'formservices[]', 'js-formaction-services'); form.insertAdjacentElement('beforeend', hiddenInput); }); // append hidden input with form name value, if it exists if (formObj.formname) { var formNameInput = t_zeroForms__createHiddenField(formObj.formname, 'tildaspec-formname', ''); form.insertAdjacentElement('beforeend', formNameInput); } // append hidden input with zero-elem ID value, in case several forms are in 1 Zero Block if (elementId) { var formElemIdInput = t_zeroForms__createHiddenField(elementId, 'tildaspec-elemid', ''); form.insertAdjacentElement('beforeend', formElemIdInput); } // create success box var successBox = document.createElement('div'); successBox.classList.add('js-successbox'); successBox.classList.add('t-form__successbox'); successBox.classList.add('t-text'); successBox.classList.add('t-text_sm'); successBox.style.display = 'none'; successBox.innerHTML = formObj.formmsgsuccess; form.insertAdjacentElement('beforeend', successBox); var titleStyles = { color: formObj.inputtitlecolor || '', fontWeight: formObj.inputtitlefontweight || '', fontFamily: formObj.inputfontfamily || '', fontSize: formObj.inputtitlefontsize || '', paddingBottom: formObj.inputtitlemargbottom || '', }; const hasConditionalFields = arrayOfElements.some(elementObj => !!elementObj.li_conditionals); if (hasConditionalFields) { form.classList.add('t-conditional-form'); t_zeroForms__addResource({ recId: recid, id: 't-zero-conditional-form', path: 'tilda-conditional-form-1.0.min.js', type: 'script', }); } var inputsBlock = t_zeroForms__generateInputsBlock(recid, zeroForm, arrayOfElements, formObj, titleStyles); form.insertAdjacentElement('beforeend', inputsBlock); var formBottomText = formObj.formbottomtext && formObj.formbottomtext.trim(); if (formBottomText) { var bottomText = document.createElement('div'); bottomText.style.textAlign = formObj.buttonalign === 'center' ? 'center' : 'left'; bottomText.style.color = titleStyles.color; bottomText.style.fontWeight = titleStyles.fontWeight; bottomText.style.fontFamily = titleStyles.fontFamily; bottomText.style.marginTop = '15px'; bottomText.style.fontSize = '13px'; var bottomBLock = t_zeroForms__getBottomText(elementId, formObj, recid, zeroForm, formBottomText); bottomText.appendChild(bottomBLock); form.insertAdjacentElement('beforeend', bottomText); } form.insertAdjacentElement('beforeend', t_zeroForms__createErrorBox(recid, formObj, 'bottom')); form.insertAdjacentElement('beforeend', t_zeroForms__createCommentField()); t_zeroForms__createInputPlaceholderStyles(elementId, formObj, recid, zeroForm); if (formObj.inputpos === 'h' || tildamode === 'zero') { var horizontalStylesID = 't-zero-form-h-styles'; t_zeroForms__addResource({ recId: recid, id: horizontalStylesID, path: 'tilda-zero-form-horizontal.min.css', type: 'link', }); var horizontalStyles = document.getElementById(horizontalStylesID); if (horizontalStyles) { horizontalStyles.addEventListener('load', function () { t_zeroForms__updateTopPosition(zeroForm); }); } } var commonStyle = '.tn-atom .t-input-block {position: relative;}'; t_zeroForms__addInlineTag({ tag: 'style', id: 't-zero-form-c-styles', content: commonStyle, zeroForm }); if (formObj.inputsstyle2 === 'y') { t_zeroForms__onRender(zeroForm, false, function () { // Данный код вызывается асинхронно, поэтому formObj может оказаться не тем чем кажется; // Нужно заного его создать, с учётом новых вводных (например переключение брейкпоинта). if (window.tildamode === 'zero') { formObj = t_zeroForms__createFormObj(recid, zeroForm); } t_zeroForms__animateInputs(zeroForm, formObj, recid, elementId); }); } var fieldFontFamilyID = 't-zero-form-font-family-' + recid + '-' + elementId; if (formObj.fieldfontfamily) { var fontFamilySelector = t_zeroForms__createSelector(recid, elementId, ''); var selectorList = [ 'input[type="text"]', 'input[type="tel"]', 'input[type="url"]', 'input[type="email"]', '.t-input-phonemask__select', 'textarea', 'select', '.t-input__vis-ph', '.t-rate__wrapper_numbers .t-rate__indicator', ]; selectorList = selectorList.reduce(function (prev, next, i) { prev += fontFamilySelector + '.t-input-block ' + next; if (i !== selectorList.length - 1) prev += ', '; return prev; }, ''); var fontFamilyStyles; if (/var\(/.test(formObj.fieldfontfamily)) { fontFamilyStyles = selectorList + ' {font-family: ' + formObj.fieldfontfamily + ';}'; } else { fontFamilyStyles = selectorList + ' {font-family: "' + formObj.fieldfontfamily + '";}'; } t_zeroForms__addInlineTag({ tag: 'style', id: fieldFontFamilyID, content: fontFamilyStyles, zeroForm }); } else { var fieldFontFamilyStyles = document.getElementById(fieldFontFamilyID); if (fieldFontFamilyStyles && fieldFontFamilyStyles.parentElement) { fieldFontFamilyStyles.parentElement.removeChild(fieldFontFamilyStyles); } } if (tildamode === 'preview' || tildamode === 'published') { t_zeroForms__onFuncLoad('tildaForm_initMasks', function () { tildaForm_initMasks(); }); } if (tildamode === 'published') { var multiLandingBlocks = document.querySelectorAll('[data-record-type="803"], [data-parenttplid="803"]'); Array.prototype.forEach.call(multiLandingBlocks, function (multiLandingBlock) { var multiLandingID = multiLandingBlock.id.replace('rec', ''); t_zeroForms__onFuncLoad('t803_init', function () { t803_init(multiLandingID); }); }); } // update styles for parsed form while resizing var tildaMode = t_zeroForms__getTildaMode(); var onResize = function () { t_zeroForms__updateCurrentResolution(recid, tildaMode); t_zeroForms__updateStylesOnResize(recid, zeroForm); }; // tilda-zero-1.1+ кеширует ширину окна и обновляет её в своём обработчике ресайза, // поэтому ждём его события, иначе t396_detectResolution вернёт разрешение по устаревшей ширине if (typeof window.t396__revalidateDimensions === 'function') { document.addEventListener('zero:window-width-changed', onResize); } else { var event = window.t_zeroForms__isMobile || 'ontouchend' in document ? 'orientationchange' : 'resize'; var timerID = 0; window.addEventListener(event, function () { clearTimeout(timerID); timerID = setTimeout(onResize, 600); }); } return form; } function t_zeroForms__updateCurrentResolution(recid, tildaMode) { if ( typeof window.t396_detectResolution === 'undefined' || typeof window.t396_switchResolution === 'undefined' || tildaMode === 'edit' ) { return; } var resolution = t396_detectResolution(recid); t396_switchResolution(recid, resolution); } function t_zeroForms__updateStylesOnResize(recid, zeroForm) { var formObj = t_zeroForms__createFormObj(recid, zeroForm); var formID = zeroForm.getAttribute('data-elem-id'); var formEl = zeroForm.querySelector('.t-form'); var inputFontWeight = formObj.inputfontweight === 'variation' ? formObj.inputvariationweight : formObj.inputfontweight; var phoneMaskInputs = document.querySelectorAll('.t-input-phonemask__wrap'); Array.prototype.forEach.call(phoneMaskInputs, function (phoneMaskInput) { phoneMaskInput.classList.add('t-input-inline-styles'); }); if (formObj.inputpos === 'h') { if (formEl) formEl.classList.add('tn-form_horiz'); t_zeroForms__addResource({ recId: recid, id: 't-zero-form-h-styles', type: 'link', path: 'tilda-zero-form-horizontal.min.css', }); var formWrapper = zeroForm.querySelector('.t-form__inputsbox'); if (formWrapper) formWrapper.classList.remove('t-form__inputsbox_flex'); if (formWrapper) formWrapper.classList.remove('t-form__inputsbox_inrow'); } else if (formEl) { formEl.classList.remove('tn-form_horiz'); t_zeroForms__placeFormIntoColumns(zeroForm); } // update inputs styles var inputStyles = t_zeroForms__initInputStyles(formObj, inputFontWeight); var inputs = zeroForm.querySelectorAll('.t-input-inline-styles:not(.t-input__own-answer)'); Array.prototype.forEach.call(inputs, function (input) { t_zeroForms__appendStylesToField(input, inputStyles); // property resize for textarea var rows = input.getAttribute('data-rows'); if (rows) { var textAreaRowHeight = 25; var textAreaPadding = 10; input.style.height = rows * textAreaRowHeight + textAreaPadding + 'px'; } }); // update title and subtitle styles var titleStyles = { color: formObj.inputtitlecolor || '', fontWeight: formObj.inputtitlefontweight || '', fontFamily: formObj.inputfontfamily || '', fontSize: formObj.inputtitlefontsize || '', paddingBottom: formObj.inputtitlemargbottom || '', }; var titleFontWeight = formObj.inputtitlefontweight === 'variation' ? formObj.inputtitlevariationweight : formObj.inputtitlefontweight; var titleList = zeroForm.querySelectorAll('.t-input-title'); Array.prototype.forEach.call(titleList, function (title) { t_zeroForms__setTitleStyles(title, titleStyles, titleFontWeight); }); // update styles for input group var inputGroupList = Array.prototype.slice.call(zeroForm.querySelectorAll('.t-input-group')); Array.prototype.forEach.call(inputGroupList, function (inputGroup) { t_zeroForms__setStylesForFormGroup(formObj, inputGroup); }); // update rate scale sizes and fonts Array.from(zeroForm.querySelectorAll('.t-rate__wrapper_icons')).forEach(rateWrapper => { t_zeroForms__setRateScaleIconsSize(rateWrapper, formObj); }); if (zeroForm.querySelector('.t-rate__wrapper_numbers')) { t_zeroForms__setRateScaleNumbersStyles(recid, formID, formObj, zeroForm); } // update submit btn styles var submitBtn = zeroForm.querySelector('.t-submit'); if (!submitBtn) return; // prettier-ignore t_zeroForms__setBtnInlineStyles(formObj, submitBtn); t_zeroForms__generateBtnStyles(submitBtn, recid, formID, formObj, zeroForm); t_zeroForms__addButtonShadowStyles(formObj, submitBtn); t_zeroForms__addButtonHoverShadowStyles(formObj, submitBtn); // кнопки шагов повторяют кнопку отправки zeroForm.querySelectorAll('.t-form__screen-btn').forEach(stepBtn => { t_zeroForms__setBtnInlineStyles(formObj, stepBtn); t_zeroForms__addButtonShadowStyles(formObj, stepBtn); t_zeroForms__addButtonHoverShadowStyles(formObj, stepBtn); stepBtn.classList.toggle('tn-form__btn-gradient', submitBtn.classList.contains('tn-form__btn-gradient')); }); t_zeroForms__setStepsStyles(zeroForm, formObj); // update submit btn wrapper var submitBtnWrapper = submitBtn.closest('.tn-form__submit'); if (!submitBtnWrapper) return; submitBtnWrapper.style.textAlign = formObj.buttonalign; submitBtnWrapper.style.marginTop = formObj.buttonmargtop + 'px'; t_zeroForms__updateTopPosition(zeroForm); } /** * while user used relative position on Y axis with bottom or middle property, should update top position * * @param {HTMLElement} zeroForm */ function t_zeroForms__updateTopPosition(zeroForm) { if ( typeof window.t396_elem__getFieldValue === 'undefined' || typeof window.t396_elem__renderViewOneField === 'undefined' ) { return; } if (!zeroForm?.isConnected) return; var axisY = t396_elem__getFieldValue(zeroForm, 'axisy'); if (axisY === 'top') return; t396_elem__renderViewOneField(zeroForm, 'top'); } function t_zeroForms__createCommentField() { var commentField = document.createElement('div'); commentField.style.position = 'absolute'; commentField.style.left = '-5000px'; commentField.style.bottom = '0'; commentField.style.display = 'none'; var commentInput = document.createElement('input'); commentInput.type = 'text'; commentInput.name = 'form-spec-comments'; commentInput.value = 'Its good'; commentInput.classList.add('js-form-spec-comments'); commentInput.tabIndex = -1; commentField.insertAdjacentElement('beforeend', commentInput); return commentField; } function t_zeroForms__generateInputsBlock(recid, zeroForm, arrayOfElements, formObj, titleStyles) { var formID = zeroForm.getAttribute('data-elem-id'); var filteredArrayOfEls = arrayOfElements.filter(function (elementObj) { return elementObj.loff !== 'y' && elementObj.li_type; // remove from list hidden or switch off fields }); var inputsBlock = document.createElement('div'); inputsBlock.classList.add('t-form__inputsbox'); filteredArrayOfEls = t396_zeroForms__markElementsUsedInCalculator(filteredArrayOfEls); filteredArrayOfEls.forEach(function (elementObj) { // prettier-ignore var parsedHTMLElement = t_zeroForms__parseIntoElement(recid, zeroForm, elementObj, formObj, titleStyles, formID); if (parsedHTMLElement) inputsBlock.insertAdjacentElement('beforeend', parsedHTMLElement); }); inputsBlock.insertAdjacentElement('beforeend', t_zeroForms__createErrorBox(recid, formObj, 'middle')); var submitWrapper = t_zeroForms__createFormButton(recid, zeroForm, formID, formObj); // tilda-step-form-1.1 добавляет кнопки шагов в .t-form__submit, на этот же класс завязаны его стили if (t_zeroForms__hasSteps(inputsBlock)) submitWrapper.classList.add('t-form__submit'); inputsBlock.insertAdjacentElement('beforeend', submitWrapper); return inputsBlock; } /** * parse from into HTML * * @param {string} recid - record ID * @param {HTMLElement} zeroForm - current form * @param {FormObjectEl} elementObj - object item * @param {formObj} formObj * @param {object} titleStyles * @param {string} formID * @returns {HTMLElement | void} */ function t_zeroForms__parseIntoElement(recid, zeroForm, elementObj, formObj, titleStyles, formID) { var isHiddenInput = elementObj.li_type === 'hd'; if (isHiddenInput) { return t_zeroForms__createHiddenField( t396__decodeHtmlText(elementObj.li_value), t396__decodeHtmlText(elementObj.li_nm), '' ); } var inputGroup = document.createElement('div'); inputGroup.classList.add('t-input-group'); inputGroup.classList.add('t-input-group_' + elementObj.li_type); // Скрытый калькулятор продолжает считать и отправлять значение, но не отображается var isVisuallyHiddenCalc = elementObj.li_type === 'fr' && elementObj.li_visually_hidden === 'y'; if (isVisuallyHiddenCalc) inputGroup.classList.add('t-form__hidden'); inputGroup.setAttribute('data-input-lid', elementObj.lid); inputGroup.setAttribute('data-field-type', elementObj.li_type); inputGroup.setAttribute('data-field-name', t_zeroForms__getFieldName(elementObj)); const defaultValue = t396_zeroForms__getDefaultOption(elementObj); if (defaultValue) inputGroup.setAttribute('data-default-value', defaultValue); if (elementObj.li_conditionals) { inputGroup.classList.add('t-conditional'); inputGroup.setAttribute('data-conditionals', elementObj.li_conditionals); } if (elementObj.li_type === 'st') return t_zeroForms__createStepDivider(elementObj, inputGroup); t_zeroForms__setStylesForFormGroup(formObj, inputGroup); // prettier-ignore var inputFontWeight = formObj.inputfontweight === 'variation' ? formObj.inputvariationweight : formObj.inputfontweight; // prettier-ignore var textFontWeight = formObj.inputelsfontweight === 'variation' ? formObj.inputelsvariationweight : formObj.inputelsfontweight; // prettier-ignore var titleFontWeight = formObj.inputtitlefontweight === 'variation' ? formObj.inputtitlevariationweight : formObj.inputtitlefontweight; if (elementObj.li_title) t_zeroForms__generateTitle(elementObj, titleStyles, inputGroup, titleFontWeight); if (elementObj.li_subtitle) t_zeroForms__generateSubtitle(elementObj, titleStyles, inputGroup); var inputStyles = t_zeroForms__initInputStyles(formObj, inputFontWeight); var labelStyles = { fontSize: formObj.inputelsfontsize || '', fontWeight: textFontWeight || '', }; var inputPreferences = { name: t396__decodeHtmlText(elementObj.li_nm), placeholder: t396__decodeHtmlText(elementObj.li_ph), secondaryClassName: formObj.inputsstyle ? 't-input_bbonly' : '', require: elementObj.li_req === 'y', rule: elementObj.li_rule || '', mask: elementObj.li_mask || '', inputWidth: elementObj.li_inputwidth, inputInRow: elementObj.li_inputinrow, radioPosition: elementObj.li_radioposition, radioPositionMobile: elementObj.li_radiowidthmobile, }; var inputBlock = document.createElement('div'); inputBlock.classList.add('t-input-block'); var generatedField; switch (elementObj.li_type) { case 'em': // email generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'email'); break; case 'ph': // phone generatedField = t_zeroForms__createPhoneInput(recid, elementObj, inputStyles, inputPreferences); if (elementObj.li_masktype === 'a') { t_zeroForms__addResource({ recId: recid, id: 't-zero-phonemask', path: 'tilda-phone-mask-1.1.min.js', type: 'script', }); t_zeroForms__onRender(zeroForm, true, function () { t_zeroForms__onFuncLoad('t_form_phonemask_load', function () { // prettier-ignore var selector = '#rec' + recid + ' .js-phonemask-input[data-phonemask-lid="' + elementObj.lid + '"]'; var currentPhoneInput = document.querySelector(selector); if (currentPhoneInput) t_form_phonemask_load(currentPhoneInput); }); }); } break; case 'nm': // name generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'name'); break; case 'in': // input (one line input field) generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'oneline'); break; case 'ta': // textarea generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'textarea'); break; case 'sb': // select box (dropdown) var hasBBOnly = formObj.inputsstyle === 'y'; generatedField = t_zeroForms__createSelect(elementObj, inputStyles, inputPreferences, hasBBOnly); if ((formObj.inputsstyle && formObj.inputelscolor) || inputStyles.color) { var styles = document.createElement('style'); var selector = t_zeroForms__createSelector(recid, formID, '.t-select__wrapper:after'); var selectorWrapperColor = formObj.inputsstyle ? formObj.inputelscolor : inputStyles.color; styles.textContent = selector + '{border-top-color:' + selectorWrapperColor + ';}'; generatedField.insertAdjacentElement('beforeend', styles); } break; case 'rd': // radio (question with answers) var inputType = elementObj.li_radcb === 'cb' ? 'checkbox' : 'radio'; inputGroup.setAttribute('data-field-radcb', elementObj.li_radcb); generatedField = t_zeroForms__createRadio( elementObj, formObj, inputPreferences, labelStyles, inputType, recid, formID ); t_zeroForms__setIndicatorStyles(recid, formID, formObj.inputelscolor, inputType, generatedField); var fieldSetStyles = recid ? '#rec' + recid + ' ' : ''; fieldSetStyles += 'fieldset {padding: 0; margin: 0; border: none;}'; t_zeroForms__addInlineTag({ tag: 'style', id: 't-zero-form-fieldset-' + recid, content: fieldSetStyles, zeroForm, }); if (inputType === 'checkbox') { t_zeroForms__onRender(zeroForm, false, function () { var inputWrapper = zeroForm.querySelector('[data-input-lid="' + elementObj.lid + '"]'); if (!inputWrapper) return; var checkboxList = Array.prototype.slice.call(inputWrapper.querySelectorAll('.t-checkbox')); checkboxList.forEach(function (checkbox) { checkbox.addEventListener('input', t_zeroForms__updateCheckboxesValues); }); }); } break; case 'ri': // radio image (question with img answers) generatedField = t_zeroForms__createRadioImage(elementObj, formObj, inputPreferences); inputGroup.setAttribute('data-field-radcb', elementObj.li_radcb); t_zeroForms__setIndicatorStyles(recid, formID, formObj.inputelscolor, 'img-select', generatedField); t_zeroForms__addResource({ recId: recid, id: 't-zero-img-select-styles', path: 'tilda-img-select-1.0.min.css', type: 'link', }); t_zeroForms__addResource({ recId: recid, id: 't-zero-img-select-script', path: 'tilda-img-select-1.0.min.js', type: 'script', }); t_zeroForms__onRender(zeroForm, false, function () { t_zeroForms__onFuncLoad('t_input_imgselect_init', function () { t_input_imgselect_init(recid, elementObj.lid); t_input_imgselect_invertColor(recid); }); }); break; case 'cb': // checkbox generatedField = t_zeroForms__createCheckbox(elementObj, labelStyles, formObj, inputPreferences); t_zeroForms__setIndicatorStyles(recid, formID, formObj.inputelscolor, 'checkbox', generatedField); // только для вертикальных форм if (elementObj.li_belowsubmit && formObj.inputpos === 'v') { inputGroup.style.order = 10; inputGroup.style.marginTop = '20px'; inputGroup.style.marginBottom = '0px'; } break; case 'uw': // upload widget (file) generatedField = t_zeroForms__createUploadField( recid, elementObj, inputPreferences, 'uw', formObj, zeroForm ); if (window.tildamode === 'published') { t_zeroForms__onRender(zeroForm, true, function () { t_zeroForms__onFuncLoad('t_upwidget__init', function () { t_upwidget__init(); }); }); } break; case 'uc': // uploadcare plugin (file) generatedField = t_zeroForms__createUploadField( recid, elementObj, inputPreferences, 'uc', formObj, zeroForm ); var scriptContent = 'UPLOADCARE_LOCALE ="' + elementObj.li_inp + '";'; scriptContent += 'UPLOADCARE_TABS = "all";'; t_zeroForms__addInlineTag({ tag: 'script', id: 't-zero-uploadcare-' + formID, content: scriptContent, zeroForm, }); break; case 'da': // date generatedField = t_zeroForms__createDateField(recid, elementObj, inputPreferences, inputStyles, formObj); t_zeroForms__onRender(zeroForm, true, function () { t_zeroForms__onFuncLoad('t_datepicker_init', function () { t_datepicker_init(recid, elementObj.lid, formID); }); }); break; case 'tm': // time generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'time'); break; case 'qn': // plus/minus btn (quantity) // prettier-ignore generatedField = t_zeroForms__createQuantityField(elementObj, inputStyles, formObj.inputelscolor, inputPreferences); zeroForm.removeEventListener('click', t_zeroForms__initQuanityClickCount); zeroForm.addEventListener('click', t_zeroForms__initQuanityClickCount); break; case 'rg': // range slider (quantity) // prettier-ignore generatedField = t_zeroForms__createQuantityRange(recid, elementObj, inputStyles, formObj, inputPreferences); if (formObj.inputelscolor) { var rangeStyles = document.createElement('style'); var rangeSelector = t_zeroForms__createSelector(recid, formID, '.t-range'); var rangePostfix = ['::-webkit-slider-thumb', '::-moz-range-thumb', '::-ms-thumb']; rangePostfix.forEach(function (postfix) { rangeStyles.textContent += rangeSelector + postfix + '{background:' + formObj.inputelscolor + ';}'; }); generatedField.insertAdjacentElement('beforeend', rangeStyles); } t_zeroForms__onRender(zeroForm, false, function () { t_zeroForms__onFuncLoad('t_input_range_init', function () { try { t_input_range_init(recid, elementObj.lid); } catch (err) { console.log(err); } }); }); break; case 'ur': // website url generatedField = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'url'); break; case 'tx': // text comment generatedField = document.createElement('div'); generatedField.classList.add('t-text'); generatedField.setAttribute('field', 'li_text__' + elementObj.lid); generatedField.style.fontWeight = labelStyles.fontWeight; generatedField.style.fontSize = labelStyles.fontSize + 'px'; generatedField.style.fontFamily = titleStyles.fontFamily; generatedField.style.color = titleStyles.color; generatedField.innerHTML = elementObj.li_text || ''; break; case 'ws': // white space generatedField = document.createElement('div'); generatedField.innerHTML = ' '; var WhiteSpaceRowHeight = 34; if (elementObj.li_rows) generatedField.style.height = elementObj.li_rows * WhiteSpaceRowHeight + 'px'; break; case 'fr': // formula (calculation field) generatedField = t_zeroForms__createCalculation( recid, elementObj, inputStyles, inputPreferences, titleStyles ); if (formObj.inputfrbgcolor) { var calcStyles = document.createElement('style'); var calcSelector = t_zeroForms__createSelector(recid, formID, '.t-input-group_fr'); calcStyles.textContent = calcSelector + '{background-color:' + formObj.inputfrbgcolor + '; padding: 20px 30px 25px;}'; generatedField.insertAdjacentElement('beforeend', calcStyles); } // калькулятор в зиро блоке не работает if (tildamode !== 'zero') { t_zeroForms__onRender(zeroForm, false, function () { t_zeroForms__onFuncLoad('tcalc__init', function () { t_zeroForms__waitCalcFields(recid, elementObj, zeroForm); }); }); } break; case 'contact_method': // способ связи var contactMethods = t_zeroForms__getContactMethods(elementObj); generatedField = t_zeroForms__createContactMethod(recid, { formID, elementObj, contactMethods, formObj, inputStyles, inputPreferences, }); if (!generatedField) break; // Поле считается готовым только после инициализации скрипта, который отправит событие inputReady inputGroup.setAttribute('data-field-async', 'true'); // В редакторе Zero Block нет tilda-scripts (t_loadJsFile), поэтому скрипт маски подключаем сами if (contactMethods.some(method => method.hasPhone)) { t_zeroForms__addResource({ recId: recid, id: 't-zero-phonemask', path: 'tilda-phone-mask-1.1.min.js', type: 'script', }); } t_zeroForms__addResource({ recId: recid, id: 't-zero-contact-method-script', path: 'tilda-contact-method-1.0.min.js', type: 'script', }); // Поле инициализируется во всех режимах, включая редакторы, чтобы маска телефона выглядела как на сайте t_zeroForms__onNextRender(zeroForm, function () { t_zeroForms__onFuncLoad('t_contactMethod__init', function () { t_contactMethod__init(recid, elementObj.lid); }); }); break; case 'rs': // rating scale var rateScaleSettings = t_zeroForms__getRateScaleSettings(elementObj); generatedField = t_zeroForms__createRateScale({ elementObj, formObj, inputPreferences, settings: rateScaleSettings, }); if (rateScaleSettings.type === 'numbers') { t_zeroForms__setRateScaleNumbersStyles(recid, formID, formObj, zeroForm); } // Поле считается готовым только после инициализации скрипта, который отправит событие inputReady inputGroup.setAttribute('data-field-async', 'true'); t_zeroForms__addResource({ recId: recid, id: 't-zero-ratescale-script', path: 'tilda-ratescale-1.0.min.js', type: 'script', }); // Поле инициализируется во всех режимах, чтобы в редакторах работало так же, как на сайте t_zeroForms__onNextRender(zeroForm, function () { t_zeroForms__onFuncLoad('t_rateScale__init', function () { t_rateScale__init(recid, elementObj.lid, rateScaleSettings.type); }); }); break; } if (generatedField) inputBlock.appendChild(generatedField); var errorBox = document.createElement('div'); errorBox.classList.add('t-input-error'); inputBlock.insertAdjacentElement('beforeend', errorBox); inputGroup.insertAdjacentElement('beforeend', inputBlock); if (formObj.inputpos !== 'h') { var liType = elementObj.li_type; if ( liType === 'em' || liType === 'ph' || liType === 'nm' || liType === 'in' || liType === 'ta' || liType === 'sb' || liType === 'cb' || liType === 'uw' || liType === 'da' || liType === 'tm' || liType === 'qn' || liType === 'rg' || liType === 'ur' || liType === 'tx' || liType === 'contact_method' || liType === 'rs' ) { t_zeroForms__setFieldsRowClasses(inputPreferences, inputGroup); } if (elementObj.li_type === 'rd') { t_zeroForms__setRadioRowClasses(inputPreferences, inputBlock); } } return inputGroup; } /** * Some users create calculation field outside the forms that work with it. * If these forms were previously hidden, whe should check if the fields are rendered, * before init calculation. * * @param {FormObjectEl} elementObj * @param {HTMLElement} zeroForm */ function t_zeroForms__waitCalcFields(recId, elementObj, zeroForm) { var inputNameList = t_zeroForms__getListOfFieldsInFormula(elementObj.li_expr); if (!inputNameList) return; var isFieldsInsideCurrentForm = inputNameList.every(function (name) { return zeroForm.querySelector('[name="' + name + '"]'); }); if (isFieldsInsideCurrentForm) { tcalc__init(recId, elementObj.lid); } else { setTimeout(function () { tcalc__init(recId, elementObj.lid); }, 500); } } /** * Возвращает список названий использованных в формуле полей. Возвращает undefined, если в формуле не нашлось подходящих полей. * @param {string} formula * @returns {string[] | undefined} */ function t_zeroForms__getListOfFieldsInFormula(formula) { if (!formula) return; var inputNameList = t_zeroForms__removeStringQuotes(formula).match(/[A-z0-9_]+/gi); if (!inputNameList) return; // if we have expression a + b * 2, we shouldn't use 2 as a name for input field return inputNameList.filter(function (name) { return isNaN(parseInt(name, 10)); }); } /** * * @param {formObj} formObj * @param {HTMLElement} inputGroup */ function t_zeroForms__setStylesForFormGroup(formObj, inputGroup) { // разделитель шагов не занимает места в форме if (!inputGroup || inputGroup.classList.contains('t-input-group_st')) return; var isHorizontalForm = formObj.inputpos === 'h'; var inputPosStyles = ''; if (isHorizontalForm && formObj.inputmargright) { inputPosStyles += 'padding-right:' + formObj.inputmargright + 'px;'; } else if (!isHorizontalForm && formObj.inputmargbottom) { inputPosStyles += 'margin-bottom:' + formObj.inputmargbottom + 'px;'; } if (inputPosStyles) inputGroup.style = inputPosStyles; } function t_zeroForms__generateSubtitle(elementObj, titleStyles, inputGroup) { var exceptTypes = ['rd', 'ri', 'uw', 'uc', 'fr', 'cb', 'rs']; var isExceptType = exceptTypes.some(function (type) { return type === elementObj.li_type; }); var text = document.createElement(elementObj.li_title || isExceptType ? 'div' : 'label'); if (text.tagName === 'LABEL') text.style.display = 'block'; if (text.tagName === 'LABEL') text.setAttribute('for', 'input_' + elementObj.lid); text.classList.add('t-input-subtitle'); text.classList.add('t-descr'); text.classList.add('t-descr_xxs'); text.classList.add('t-opacity_70'); text.setAttribute('field', 'nullli_subtitle__' + elementObj.lid); t_zeroForms__setTitleStyles(text, titleStyles, ''); text.innerHTML = elementObj.li_subtitle; inputGroup.insertAdjacentElement('beforeend', text); } function t_zeroForms__generateTitle(elementObj, titleStyles, inputGroup, titleFontWeight) { var exceptTypes = ['rd', 'ri', 'uw', 'uc', 'fr', 'cb', 'rs']; var isExceptType = exceptTypes.some(function (type) { return type === elementObj.li_type; }); var title = document.createElement(isExceptType ? 'div' : 'label'); if (title.tagName === 'LABEL') title.style.display = 'block'; if (title.tagName === 'LABEL') title.setAttribute('for', 'input_' + elementObj.lid); title.classList.add('t-input-title'); title.setAttribute('data-redactor-toolbar', 'no'); title.setAttribute('field', 'nullli_title__' + elementObj.lid); t_zeroForms__setTitleStyles(title, titleStyles, titleFontWeight); title.innerHTML = elementObj.li_title; inputGroup.insertAdjacentElement('beforeend', title); } function t_zeroForms__createPhoneInput(recid, elementObj, inputStyles, inputPreferences) { var maskType = elementObj.li_masktype; var input = document.createElement('input'); if (!elementObj.li_title && !elementObj.li_subtitle) { input.ariaLabel = 'phone'; } else { input.id = 'input_' + elementObj.lid; } t_zeroForms__appendMainSettingToField(input, inputPreferences, 'tel', ''); if (maskType === 'a') { input.classList.add('js-phonemask-input'); } else if (elementObj.li_mask) input.classList.add('js-tilda-mask'); if (maskType === 'a') { var browserLangCode = window.t_zeroForms__browserLang === 'RU' ? '+7' : '+1'; input.placeholder = browserLangCode + '(000)000-0000'; input.setAttribute('data-phonemask-init', 'no'); input.setAttribute('data-phonemask-id', recid); input.setAttribute('data-phonemask-lid', elementObj.lid); if (elementObj.li_maskcountry) input.setAttribute('data-phonemask-maskcountry', elementObj.li_maskcountry); if (inputPreferences.secondaryClassName) input.classList.add(inputPreferences.secondaryClassName); if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); } else { t_zeroForms__appendAttributes(input, inputPreferences); input.setAttribute('data-tilda-rule', 'phone'); if (inputPreferences.mask) input.setAttribute('data-tilda-mask', inputPreferences.mask); } t_zeroForms__appendStylesToField(input, inputStyles); return input; } /* ============= contact method field ============= */ // Разметка повторяет tpl_input_contact_method.tpl, логика поля находится в tilda-contact-method-1.0.js /** * @typedef {{ * type: string, * title: string, * hasPhone: boolean, * hasText: boolean, * placeholder?: string, * }} ContactMethod */ /** * Настройки способов связи: * - hasPhone – есть поле для ввода телефона, * - hasText – есть текстовое поле. Если есть оба поля, способ связи гибридный (см. tilda-contact-method-1.0.js), * - placeholder – плейсхолдер текстового поля. Переводится скриптом tilda-contact-method после инициализации. * @returns {Record>} */ function t_zeroForms__getContactMethodsConfig() { return { phone: { title: 'Phone', hasPhone: true, hasText: false }, whatsapp: { title: 'WhatsApp', hasPhone: true, hasText: false }, viber: { title: 'Viber', hasPhone: true, hasText: false }, telegram: { title: 'Telegram', hasPhone: true, hasText: true, placeholder: 'Username or phone number' }, max_messenger: { title: 'Max', hasPhone: true, hasText: true, placeholder: 'Link or phone number' }, vk: { title: 'VK', hasPhone: false, hasText: true, placeholder: 'Username, ID or link' }, fb_messenger: { title: 'Messenger', hasPhone: false, hasText: true, placeholder: 'Username, ID or link' }, skype: { title: 'Skype', hasPhone: false, hasText: true, placeholder: 'Username, email or phone number' }, }; } /** * Возвращает разметку иконки способа связи. Иконки взяты из tpl_socials_*.tpl * (iconshape="circle-filled-logo", размер 18px, цвета из tpl_socials_colors.tpl) * @param {string} type * @returns {string} */ function t_zeroForms__getContactMethodIcon(type) { // prettier-ignore const icons = { phone: '', vk: '', telegram: '', whatsapp: '', viber: '', max_messenger: '', skype: '', fb_messenger: '', }; return icons[type] || ''; } /** * Возвращает имя поля для data-field-name. У способа связи две переменные: тип и значение, они записываются через `;` * @param {FormObjectEl} elementObj * @returns {string} */ function t_zeroForms__getFieldName(elementObj) { if (elementObj.li_type === 'contact_method') { const { typeName, valueName } = t_zeroForms__getContactMethodVarNames(elementObj); return `${typeName};${valueName}`; } return t396__decodeHtmlText(elementObj.li_nm); } /** * Возвращает имена переменных способа связи: тип (phone, telegram, ...) и значение (номер, имя пользователя, ...) * @param {FormObjectEl} elementObj * @returns {{ typeName: string, valueName: string }} */ function t_zeroForms__getContactMethodVarNames(elementObj) { return { typeName: t396__decodeHtmlText(elementObj.li_contact_method_type_nm || ''), valueName: t396__decodeHtmlText(elementObj.li_contact_method_id_nm || ''), }; } /** * Возвращает список доступных способов связи без дублей и неизвестных значений * @param {FormObjectEl} elementObj * @returns {ContactMethod[]} */ function t_zeroForms__getContactMethods(elementObj) { let contactMethods = elementObj.li_contact_methods; if (typeof contactMethods === 'string') { try { contactMethods = JSON.parse(contactMethods); } catch (err) { contactMethods = []; } } if (!Array.isArray(contactMethods)) return []; const config = t_zeroForms__getContactMethodsConfig(); const types = contactMethods .map(contactMethod => contactMethod && contactMethod.value) .filter((type, index, list) => type && config[type] && list.indexOf(type) === index); return types.map(type => Object.assign({ type }, config[type])); } /** * Создает поле "Способ связи" * * @param {string} recid * @param {{ * formID: string, * elementObj: FormObjectEl, * contactMethods: ContactMethod[], * formObj: formObj, * inputStyles: Object, * inputPreferences: Object, * }} options * @returns {HTMLDivElement | null} */ function t_zeroForms__createContactMethod(recid, options) { const { formID, elementObj, contactMethods, formObj, inputStyles, inputPreferences } = options; if (!contactMethods.length) return null; const defaultMethod = contactMethods.find(method => method.type === elementObj.li_default_contact_method) || contactMethods[0]; const { typeName, valueName } = t_zeroForms__getContactMethodVarNames(elementObj); const container = t_zeroForms__createWrapper('t-contact-method__container'); const typesContainer = t_zeroForms__createWrapper('t-contact-method__types-container'); const valueContainer = t_zeroForms__createWrapper('t-contact-method__value-container'); // способ связи по умолчанию всегда располагается в начале списка const sortedMethods = [defaultMethod].concat(contactMethods.filter(method => method !== defaultMethod)); sortedMethods.forEach((contactMethod, index) => { const radio = t_zeroForms__createContactMethodRadio(contactMethod, { inputId: `contact-method-${elementObj.lid}-${index}`, inputName: typeName, isRequired: inputPreferences.require, isChecked: contactMethod === defaultMethod, }); typesContainer.appendChild(radio); }); contactMethods.forEach(contactMethod => { const valueGroup = t_zeroForms__createContactMethodValueGroup(recid, { elementObj, contactMethod, inputName: valueName, inputStyles, inputPreferences, isDefault: contactMethod === defaultMethod, }); valueContainer.appendChild(valueGroup); }); container.appendChild(typesContainer); container.appendChild(valueContainer); const styles = t_zeroForms__getContactMethodStyles(recid, formID, formObj); if (styles) { const stylesEl = document.createElement('style'); stylesEl.textContent = styles; container.appendChild(stylesEl); } return container; } /** * Создает кнопку выбора способа связи * * @param {ContactMethod} contactMethod * @param {{ inputId: string, inputName: string, isRequired: boolean, isChecked: boolean }} options * @returns {HTMLDivElement} */ function t_zeroForms__createContactMethodRadio(contactMethod, options) { const { inputId, inputName, isRequired, isChecked } = options; const wrapper = t_zeroForms__createWrapper(['t-radio__item', 't-contact-method__type', 't-text', 't-text_xs']); wrapper.setAttribute('data-method-type', contactMethod.type); const label = document.createElement('label'); label.classList.add('t-contact-method__type-label'); label.htmlFor = inputId; label.insertAdjacentHTML('beforeend', t_zeroForms__getContactMethodIcon(contactMethod.type)); const title = document.createElement('span'); title.classList.add('t-contact-method__title'); title.setAttribute('data-contact-method', contactMethod.type); title.textContent = contactMethod.title; label.appendChild(title); const input = document.createElement('input'); input.id = inputId; input.type = 'radio'; input.classList.add('t-radio', 'js-tilda-rule', 't-contact-method__type-input'); input.name = inputName; input.value = contactMethod.type; if (isRequired) { input.setAttribute('data-tilda-req', '1'); input.setAttribute('aria-required', 'true'); } // атрибут, а не свойство checked: от него зависит состояние после сброса формы if (isChecked) input.setAttribute('checked', ''); wrapper.appendChild(label); wrapper.appendChild(input); return wrapper; } /** * Создает группу полей для ввода значения способа связи (телефон и/или текстовое поле) * * @param {string} recid * @param {{ * elementObj: FormObjectEl, * contactMethod: ContactMethod, * inputName: string, * inputStyles: Object, * inputPreferences: Object, * isDefault: boolean, * }} options * @returns {HTMLDivElement} */ function t_zeroForms__createContactMethodValueGroup(recid, options) { const { elementObj, contactMethod, inputName, inputStyles, inputPreferences, isDefault } = options; const { type, hasPhone, hasText } = contactMethod; // При выборе способа связи показывается текстовое поле, если оно есть. // Повторяет t_contactMethod__getDefaultInputTypeForContactMethod const defaultInputType = hasText ? 'text' : 'phone'; // Сразу рендерим состояние, в котором поле будет после инициализации tilda-contact-method: // видно только поле способа связи по умолчанию, остальные скрыты и отключены. Иначе до инициализации // в форме видны поля всех способов связи, и форма "прыгает". const group = document.createElement('div'); group.classList.add(`t-contact-method__${type}-value`); if (hasPhone) group.classList.add('t-phonemask-input-group'); if (hasPhone && hasText) group.classList.add('t-contact-method__hybrid'); if (!isDefault) group.classList.add('t-contact-method__hidden'); const createInputBlock = (input, inputType) => { const isActive = isDefault && inputType === defaultInputType; input.name = inputName; input.classList.add('t-input'); if (inputPreferences.secondaryClassName) input.classList.add(inputPreferences.secondaryClassName); if (inputPreferences.require) { input.setAttribute('data-tilda-req', '1'); input.setAttribute('aria-required', 'true'); } // Неактивные поля отключаем так же, как t_contactMethod__disable: они не валидируются и не отправляются if (isActive) { input.classList.add('js-tilda-rule'); // label заголовка поля ссылается на input_, привязываем его к полю, которое видно по умолчанию input.id = 'input_' + elementObj.lid; } else { input.disabled = true; } t_zeroForms__appendStylesToField(input, inputStyles); const inputBlock = t_zeroForms__createWrapper('t-input-block'); if (isDefault && !isActive) inputBlock.classList.add('t-contact-method__hidden'); inputBlock.appendChild(input); return inputBlock; }; if (hasPhone) { const phoneInput = document.createElement('input'); phoneInput.type = 'tel'; phoneInput.autocomplete = 'tel'; phoneInput.classList.add('js-phonemask-input', 't-input-phonemask__wrap'); phoneInput.setAttribute('data-phonemask-init', 'no'); phoneInput.setAttribute('data-phonemask-id', recid); phoneInput.setAttribute('data-phonemask-lid', elementObj.lid); phoneInput.setAttribute('data-phonemask-skip-auto-init', 'true'); if (elementObj.li_maskcountry) phoneInput.setAttribute('data-phonemask-maskcountry', elementObj.li_maskcountry); group.appendChild(createInputBlock(phoneInput, 'phone')); } if (hasText) { const textInput = document.createElement('input'); textInput.type = 'text'; textInput.classList.add('js-username-input'); textInput.setAttribute('data-contact-method', type); textInput.placeholder = contactMethod.placeholder || ''; group.appendChild(createInputBlock(textInput, 'text')); } return group; } /** * Стили для выбранного способа связи и заголовков способов связи * * @param {string} recid * @param {string} formID * @param {formObj} formObj * @returns {string} */ function t_zeroForms__getContactMethodStyles(recid, formID, formObj) { let styles = ''; // Выбранный способ связи красится в цвет переключателей и иконок, без него – стили по умолчанию из CSS const accentColor = formObj.inputaccentcolor; if (accentColor) { const selector = t_zeroForms__createSelector(recid, formID, '.t-contact-method__type:has(> .t-radio:checked)'); const getColorWithOpacity = opacity => t_zeroForms__fromHEXtoRGBA(accentColor, opacity) || `color-mix(in srgb, ${accentColor} ${opacity * 100}%, transparent)`; styles += `${selector} {background-color: ${getColorWithOpacity(0.1)}; border-color: ${getColorWithOpacity(0.4)};}`; } const labelColor = formObj.inputtitlecolor; if (labelColor) { const selector = t_zeroForms__createSelector(recid, formID, '.t-contact-method__title'); styles += `${selector} {color: ${labelColor};}`; } return styles; } /* ============= rating scale field ============= */ // Разметка повторяет tpl_input_rate.tpl, логика поля находится в tilda-ratescale-1.0.js /** * Размеры поля "Рейтинг" при высоте полей формы по умолчанию (.t-input в tilda-forms-1.0.css). * Ширина иконок – из src/tilda-forms/ratescale/styles.css, шкала в зеро-форме по высоте как обычное поле. * При другой высоте полей поле "Рейтинг" масштабируется пропорционально */ const RATE_SCALE_SIZES = { inputHeight: 60, numbersHeight: 60, iconWidth: 40, }; /** * @typedef {{ * type: 'numbers' | 'icons', * min: number, * max: number, * iconsAmount: number, * }} RateScaleSettings */ /** * Возвращает настройки поля "Рейтинг" * @param {FormObjectEl} elementObj * @returns {RateScaleSettings} */ function t_zeroForms__getRateScaleSettings(elementObj) { return { type: elementObj.li_ratetype === 'icons' ? 'icons' : 'numbers', // Как в tpl_input_rate.tpl: шкала начинается с 0, только если это явно указано min: elementObj.li_ratemin === '0' ? 0 : 1, // При пустом значении редактор показывает выбранными 10 чисел и 5 иконок max: parseInt(elementObj.li_ratemax, 10) || 10, iconsAmount: parseInt(elementObj.li_rateiconsquantity, 10) || 5, }; } /** * Создает поле "Рейтинг" * * @param {{ * elementObj: FormObjectEl, * formObj: formObj, * inputPreferences: Object, * settings: RateScaleSettings, * }} options * @returns {HTMLDivElement} */ function t_zeroForms__createRateScale(options) { const { elementObj, formObj, inputPreferences, settings } = options; const isIcons = settings.type === 'icons'; const wrapper = t_zeroForms__createWrapper('t-rate__wrapper'); const createInput = value => { const input = document.createElement('input'); input.type = 'radio'; input.name = inputPreferences.name; input.value = String(value); input.classList.add('t-rate', 'js-tilda-rule'); if (inputPreferences.require) { input.setAttribute('data-tilda-req', '1'); input.setAttribute('aria-required', 'true'); } return input; }; const createControl = () => { const control = document.createElement('label'); control.classList.add('t-rate__control'); if (formObj.inputtitlecolor) control.style.color = formObj.inputtitlecolor; return control; }; if (isIcons) { wrapper.classList.add('t-rate__wrapper_icons', `t-rate__wrapper_icons-${settings.iconsAmount}`); const icons = t_zeroForms__createWrapper('t-rate__icons'); for (let value = 1; value <= settings.iconsAmount; value++) { const input = createInput(value); input.id = `rate_${value}_${elementObj.lid}`; const control = createControl(); control.htmlFor = input.id; const indicator = t_zeroForms__createWrapper('t-rate__indicator'); indicator.appendChild(t_zeroForms__createRateScaleIcon(formObj.inputaccentcolor)); control.appendChild(indicator); icons.appendChild(input); icons.appendChild(control); } wrapper.appendChild(icons); } else { // В tpl_input_rate.tpl цвет выбранного значения берется из inputelscolor и передается в data-active-color. // В зеро-форме inputelscolor – это цвет обводки переключателей (по умолчанию черный), поэтому для рейтинга // используется цвет переключателей и иконок полей, а без него – цвета по умолчанию. // По data-active-color tilda-ratescale подбирает контрастный цвет цифры. wrapper.classList.add('t-rate__wrapper_numbers'); if (formObj.inputaccentcolor) wrapper.setAttribute('data-active-color', formObj.inputaccentcolor); for (let value = settings.min; value <= settings.max; value++) { const control = createControl(); const indicator = t_zeroForms__createWrapper(['t-rate__indicator', 't-text', 't-text_xs']); if (formObj.inputcolor) indicator.style.color = formObj.inputcolor; indicator.textContent = String(value); control.appendChild(createInput(value)); control.appendChild(indicator); wrapper.appendChild(control); } } const textStart = elementObj.li_ratetextstart; const textEnd = elementObj.li_ratetextend; if (textStart || textEnd) { const textWrapper = t_zeroForms__createWrapper('t-rate__text-wrapper'); const createText = (text, position) => { const textElement = t_zeroForms__createWrapper([ 't-rate__text', `t-rate__text_${position}`, 't-text', 't-text_xs', ]); if (formObj.inputtitlecolor) textElement.style.color = formObj.inputtitlecolor; textElement.innerHTML = text; return textElement; }; if (textStart) textWrapper.appendChild(createText(textStart, 'start')); if (textEnd) textWrapper.appendChild(createText(textEnd, 'end')); wrapper.appendChild(textWrapper); } if (isIcons) t_zeroForms__setRateScaleIconsSize(wrapper, formObj); return wrapper; } /** * Добавляет в форму стили шкалы с числами из настроек полей формы – один тег на форму. * Вызывается и при смене брейкпоинта, потому что высота и шрифт полей формы адаптивные: * старые стили удаляются, чтобы не остались стили от другого разрешения * * @param {string} recid * @param {string} formID * @param {formObj} formObj * @param {HTMLElement} zeroForm */ function t_zeroForms__setRateScaleNumbersStyles(recid, formID, formObj, zeroForm) { const id = `t-zero-form-rate-styles-${formID}-${recid}`; document.getElementById(id)?.remove(); t_zeroForms__addInlineTag({ tag: 'style', id, content: t_zeroForms__getRateScaleNumbersStyles(recid, formID, formObj), zeroForm, }); } /** * Коэффициент, на который размер поля "Рейтинг" отличается от размера по умолчанию: * во столько же раз, во сколько высота полей формы отличается от высоты по умолчанию * * @param {formObj} formObj * @returns {number} */ function t_zeroForms__getRateScaleSizeRatio(formObj) { const inputHeight = parseFloat(formObj.inputheight); if (!inputHeight || inputHeight <= 0) return 1; return inputHeight / RATE_SCALE_SIZES.inputHeight; } /** * Задает размер иконок рейтинга по высоте полей формы. Ширина иконки ограничивается max-width индикатора, * а svg растягивается на всю ширину индикатора, поэтому на узких экранах иконки по-прежнему сжимаются * * @param {HTMLElement} wrapper - .t-rate__wrapper_icons * @param {formObj} formObj */ function t_zeroForms__setRateScaleIconsSize(wrapper, formObj) { const iconWidth = RATE_SCALE_SIZES.iconWidth * t_zeroForms__getRateScaleSizeRatio(formObj); const indicators = wrapper.querySelectorAll('.t-rate__indicator'); Array.prototype.forEach.call(indicators, indicator => { indicator.style.maxWidth = `${iconWidth}px`; const svg = indicator.querySelector('svg'); if (svg) t_zeroForms__setRateScaleIconSize(svg, iconWidth); }); } /** * @param {SVGSVGElement} svg * @param {number} iconWidth */ function t_zeroForms__setRateScaleIconSize(svg, iconWidth) { // Пропорции svg как в tpl_input_rate.tpl: 41x40 svg.setAttribute('width', String((iconWidth * 41) / 40)); svg.setAttribute('height', String(iconWidth)); } /** * Создает иконку-звезду для рейтинга. Звезда цвета переключателей и иконок полей, а без него – как в * tpl_input_rate.tpl при пустом цвете элементов формы * (inputelscolor в зеро-форме – цвет обводки переключателей, для звезд он не подходит) * * @param {string=} color - цвет звезды * @returns {SVGSVGElement} */ function t_zeroForms__createRateScaleIcon(color) { const SVG_NS = 'http://www.w3.org/2000/svg'; const svg = document.createElementNS(SVG_NS, 'svg'); t_zeroForms__setRateScaleIconSize(svg, RATE_SCALE_SIZES.iconWidth); svg.setAttribute('viewBox', '0 0 36 35'); svg.setAttribute('fill', 'none'); const path = document.createElementNS(SVG_NS, 'path'); path.setAttribute( 'd', 'M17.1896 1.355L12.3578 11.0877L1.65872 12.6753C0.692348 12.8134 0.347217 13.9868 1.03748 14.608L8.76842 22.2009L6.97373 32.969C6.83568 33.8664 7.80205 34.6256 8.63036 34.2115L18.4321 29.2416L27.8197 34.2115C28.648 34.6256 29.6143 33.9354 29.4763 32.969L27.6126 22.339L35.3435 14.7461C35.9648 14.1249 35.6886 12.9514 34.7223 12.8134L23.9542 11.2948L19.1224 1.56208C18.8462 0.59571 17.6038 0.595711 17.1896 1.355Z' ); path.setAttribute('fill', color || '#ffcf03'); svg.appendChild(path); return svg; } /** * Стили шкалы с числами. Повторяют стили из tpl_input_rate.tpl, но цвет выбранного значения и при наведении – * из цвета переключателей и иконок полей, а не из inputelscolor: в зеро-форме это цвет обводки переключателей * (см. t_zeroForms__createRateScale). Высота и шрифт – из настроек полей формы, размер шрифта цифр на 1px меньше * * @param {string} recid * @param {string} formID * @param {formObj} formObj * @returns {string} */ function t_zeroForms__getRateScaleNumbersStyles(recid, formID, formObj) { const selector = part => t_zeroForms__createSelector(recid, formID, `.t-rate__wrapper_numbers ${part}`); const activeSelector = `${selector('.t-rate:checked + .t-rate__indicator')}, ${selector('.t-rate__control:hover .t-rate__indicator')}`; const accentColor = formObj.inputaccentcolor; const sizeRatio = t_zeroForms__getRateScaleSizeRatio(formObj); const inputFontSize = parseFloat(formObj.inputfontsize); const fontSize = inputFontSize > 1 ? `${inputFontSize - 1}px` : ''; // prettier-ignore const fontWeight = formObj.inputfontweight === 'variation' ? formObj.inputvariationweight : formObj.inputfontweight; let styles = `${selector('.t-rate__control')} {height: ${RATE_SCALE_SIZES.numbersHeight * sizeRatio}px;}`; if (fontSize || fontWeight) { styles += `${selector('.t-rate__indicator')} {`; if (fontSize) styles += `font-size: ${fontSize};`; if (fontWeight) styles += `font-weight: ${fontWeight};`; styles += '}'; } if (accentColor) styles += `${activeSelector} {background-color: ${accentColor};}`; const bgColor = formObj.inputbgcolor; const borderSize = t_zeroForms__toPx(formObj.inputbordersize); const borderColor = formObj.inputbordercolor; const borderRadius = t_zeroForms__toPx(formObj.inputradius); if (!bgColor && !borderSize && !borderColor && !borderRadius) return styles; const radius = borderRadius || '0'; const isWithoutBorder = borderSize === '0px'; const sideBorderWidth = isWithoutBorder ? '0' : borderSize; styles += `${selector('.t-rate__control:first-of-type .t-rate__indicator')} {border-top-left-radius: ${radius}; border-bottom-left-radius: ${radius};}`; styles += `${selector('.t-rate__control:last-of-type .t-rate__indicator')} {border-top-right-radius: ${radius}; border-bottom-right-radius: ${radius};}`; if (!accentColor) styles += `${activeSelector} {background-color: #e5e5e5;}`; styles += `${selector('.t-rate__indicator')} {`; if (bgColor) styles += `background-color: ${bgColor};`; styles += `border-top-width: ${borderSize || '1px'}; border-bottom-width: ${borderSize || '1px'};`; if (sideBorderWidth) styles += `border-right-width: ${sideBorderWidth}; border-left-width: ${sideBorderWidth};`; styles += `border-style: solid; border-color: ${borderColor || '#000000'};}`; if (isWithoutBorder) { styles += `${selector('.t-rate__control')} {margin-right: 1px;}`; styles += `${selector('.t-rate__control:last-of-type')} {margin-right: 0;}`; styles += `${selector('.t-rate__control:first-of-type .t-rate__indicator')} {border-left: none;}`; styles += `${selector('.t-rate__control:last-of-type .t-rate__indicator')} {border-right: none;}`; } return styles; } /** * @param {string | undefined} value * @returns {string} число из настроек формы с px, остальное – как есть */ function t_zeroForms__toPx(value) { const isNumber = /^\d+(\.\d+)?$/.test(value); if (isNumber) return `${value}px`; if (!value) return ''; return value; } /** * Стили вариантов-кнопок поля "Вопрос с вариантами ответа" из настроек полей формы, как в tpl_input_variants.tpl. * Высота – из высоты полей формы, чтобы кнопки были вровень с остальными полями, без нее – 60px как в шаблоне * (src/tilda-forms/zero-variants-button/styles.css). Через min-height, чтобы длинный вариант переносился внутри кнопки. * * @param {string} recid * @param {string} formID * @param {formObj} formObj * @returns {string} */ function t_zeroForms__getVariantButtonStyles(recid, formID, formObj) { const bgColor = formObj.inputbgcolor; const borderSize = t_zeroForms__toPx(formObj.inputbordersize); const borderColor = formObj.inputbordercolor; const borderRadius = t_zeroForms__toPx(formObj.inputradius); const height = t_zeroForms__toPx(formObj.inputheight); if (!bgColor && !borderSize && !borderColor && !borderRadius && !height) return ''; const selector = [ '.t-radio__wrapper_button > fieldset > .t-radio__control', '.t-radio__wrapper_button > fieldset > .t-input__own-answer-wrapper', '.t-checkboxes__wrapper_button > fieldset > .t-checkbox__control', '.t-checkboxes__wrapper_button > fieldset > .t-input__own-answer-wrapper', ] .map(item => t_zeroForms__createSelector(recid, formID, item)) .join(', '); let styles = `${selector} {`; if (bgColor) styles += `background-color: ${bgColor};`; styles += `border: ${borderSize || '1px'} solid ${borderColor || '#000000'};`; if (borderRadius) styles += `border-radius: ${borderRadius};`; if (height) styles += `min-height: ${height};`; styles += '}'; return styles; } function t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, type) { var input = document.createElement(type === 'textarea' ? 'textarea' : 'input'); if (!elementObj.li_title && !elementObj.li_subtitle) { input.ariaLabel = type; } else { input.id = 'input_' + elementObj.lid; } t_zeroForms__appendMainSettingToField(input, inputPreferences, type, ''); var tildaRuleTypes = ['name', 'time', 'url', 'email']; var isTildaRuleType = tildaRuleTypes.some(function (tildaRuleType) { return tildaRuleType === type; }); if (isTildaRuleType) input.setAttribute('data-tilda-rule', type); if (type === 'time') { input.setAttribute('data-tilda-mask', '99:99'); input.classList.add('t-inputtime'); } if (type === 'time' || (type === 'oneline' && elementObj.li_mask)) input.classList.add('js-tilda-mask'); if (type === 'oneline') { if (inputPreferences.rule) input.setAttribute('data-tilda-rule', inputPreferences.rule); if (inputPreferences.mask) input.setAttribute('data-tilda-mask', inputPreferences.mask); } t_zeroForms__appendAttributes(input, inputPreferences); t_zeroForms__appendStylesToField(input, inputStyles); if (type === 'textarea') { var textAreaStyleContent = '.t396__elem .t-input-group_ta textarea.t-input {padding-top:10px; vertical-align: bottom; resize: none; overflow-x: hidden;}'; t_zeroForms__addInlineTag({ tag: 'style', id: 'zero-forms-textarea-styles', content: textAreaStyleContent, zeroForm: null, }); t_zeroForms__setTextareaHeight(elementObj, input); } return input; } /** * * @param {FormObjectEl} elementObj * @param {HTMLTextAreaElement} textarea */ function t_zeroForms__setTextareaHeight(elementObj, textarea) { var textAreaRowHeight = 25; var textAreaPadding = 10; if (elementObj.li_rows > 1) { textarea.style.height = elementObj.li_rows * textAreaRowHeight + textAreaPadding + 'px'; textarea.setAttribute('data-rows', elementObj.li_rows); } textarea.rows = parseInt(elementObj.li_rows, 10) || 3; } function t_zeroForms__createSelect(elementObj, inputStyles, inputPreferences, hasBBOnly) { var options = elementObj.li_variants ? elementObj.li_variants.split('\n') : []; var selectedOption = parseInt(elementObj.li_defselitem, 10); var inputWrapper = document.createElement('div'); inputWrapper.classList.add('t-select__wrapper'); if (inputPreferences.secondaryClassName) inputWrapper.classList.add('t-select__wrapper_bbonly'); var input = document.createElement('select'); input.id = 'input_' + elementObj.lid; t_zeroForms__appendMainSettingToField(input, inputPreferences, '', 't-select'); if (inputPreferences.secondaryClassName) input.classList.add('t-select_bbonly'); if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); t_zeroForms__appendStylesToField(input, inputStyles); var optionHasColor = inputStyles && inputStyles.color && !hasBBOnly; if (elementObj.li_selfirstvar) { var firstOption = document.createElement('option'); firstOption.innerHTML = elementObj.li_selfirstvar; firstOption.setAttribute('value', ''); if (optionHasColor) firstOption.style.color = inputStyles.color; input.insertAdjacentElement('beforeend', firstOption); } var optionHasColor = inputStyles && inputStyles.color && !hasBBOnly; options.forEach(function (option, i) { var optionEl = document.createElement('option'); const { label, labelText, calcValue } = t396_zeroForms__prepareCalcValue(elementObj, option); if (calcValue) { t396_zeroForms__setCalcValue(optionEl, calcValue); } optionEl.value = labelText; optionEl.innerHTML = label; if (optionHasColor) optionEl.style.color = inputStyles.color; if (selectedOption && selectedOption === i + 1) optionEl.selected = true; input.insertAdjacentElement('beforeend', optionEl); }); inputWrapper.insertAdjacentElement('beforeend', input); return inputWrapper; } function t_zeroForms__createRadio(elementObj, formObj, inputPreferences, labelStyles, inputType, recid, formID) { var radioOptions = elementObj.li_variants ? elementObj.li_variants.split('\n') : []; var hasOwnAnswer = elementObj.li_isownvariant === 'y'; if (hasOwnAnswer && elementObj.li_ownvariant && elementObj.li_ownvariant.trim()) { radioOptions.push(elementObj.li_ownvariant.trim()); } var isCheckbox = elementObj.li_radcb === 'cb'; var selectedOption = parseInt(elementObj.li_defselitem, 10); var fragment = document.createDocumentFragment(); var wrapperClassName = (isCheckbox ? 't-checkboxes' : 't-radio') + '__wrapper'; var wrapper = t_zeroForms__createWrapper(wrapperClassName); if (elementObj.li_radiostyle === 'button') { wrapper.classList.add(wrapperClassName + '_button'); const buttonStyles = t_zeroForms__getVariantButtonStyles(recid, formID, formObj); if (buttonStyles) { const stylesEl = document.createElement('style'); stylesEl.textContent = buttonStyles; wrapper.appendChild(stylesEl); } } if (isCheckbox) { fragment.appendChild(t_zeroForms__createNameFieldForCheckbox(inputPreferences, wrapper, 'checkboxes')); } fragment.appendChild(wrapper); var fieldSet = document.createElement('fieldset'); wrapper.insertAdjacentElement('beforeend', fieldSet); var inputList = []; radioOptions.forEach(function (radioOption, i) { var labelElement = t_zeroForms__createLabel(inputType, labelStyles, formObj); var input = document.createElement('input'); input.type = inputType; const { label, labelText, calcValue } = t396_zeroForms__prepareCalcValue(elementObj, radioOption); if (calcValue) { t396_zeroForms__setCalcValue(input, calcValue); } input.value = labelText; input.classList.add('t-' + inputType); if (!isCheckbox) input.classList.add('js-tilda-rule'); if (!isCheckbox) input.name = inputPreferences.name; var inputDescription = t396__decodeHtmlText(elementObj.li_title || elementObj.li_subtitle); if (!isCheckbox && inputDescription) input.ariaLabel = inputDescription; if (selectedOption && selectedOption === i + 1) { input.checked = true; var hiddenInput = fragment.querySelector('.t-checkboxes__hiddeninput'); if (hiddenInput) hiddenInput.value = input.value; } if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); inputList.push(input); labelElement.insertAdjacentElement('beforeend', input); var indicator = t_zeroForms__createIndicator(inputType, formObj.inputelscolor, { size: formObj.togglesize, borderSize: formObj.togglebordersize, }); labelElement.insertAdjacentElement('beforeend', indicator); var textValue = document.createElement('span'); textValue.innerHTML = label; labelElement.insertAdjacentElement('beforeend', textValue); var ownVariant = elementObj.li_ownvariant && elementObj.li_ownvariant.trim() ? elementObj.li_ownvariant.trim() : elementObj.li_ownvariant; if (radioOption === ownVariant) { var inputStyles = t_zeroForms__createStyleObjectForOwnAnswer(labelStyles, formObj); var ownAnswerWrapper = t_zeroForms__createOwnAnswer( input, labelElement, elementObj, inputStyles, inputPreferences, recid, formID ); fieldSet.insertAdjacentElement('beforeend', ownAnswerWrapper); } else { fieldSet.insertAdjacentElement('beforeend', labelElement); } }); if (hasOwnAnswer && elementObj.li_ownvariant) t_zeroForms__updateOwnAnswerVisibility(inputList, fieldSet); return fragment; } /** * Создаются стили для поля ввода своего варианта ответа, * их специфика заключается в том, что стили наследуются от заголовков, * а не других полей ввода * * @param {Object} labelStyles * @param {formObj} formObj * @return {Object} */ function t_zeroForms__createStyleObjectForOwnAnswer(labelStyles, formObj) { var inputStyles = Object.create(labelStyles); if (inputStyles && inputStyles.fontSize) inputStyles.fontSize += 'px'; if (formObj.inputfontfamily) inputStyles.fontFamily = formObj.inputfontfamily; if (formObj.inputtitlecolor) { inputStyles.color = formObj.inputtitlecolor; inputStyles.borderColor = formObj.inputtitlecolor; } return inputStyles; } /** * Оборачиваем поле ввода своего варианта ответа и радиокнопку/чекбокс в общий
. * Создаём само поле ввода. Устанавливаем слушатели на изменение поля ввода. * Задаём дополнительные настройки на связанную с полем радиокнопку/чекбокс. * * @param {HTMLInputElement & {defaultRadioValue: string}} input - чекбокс или радиокнопка * @param {HTMLLabelElement} label - текстовое содержание чекбокса или радиокнопки * @param {FormObjectEl} elementObj * @param inputStyles * @param inputPreferences * @param {string} recid * @param {string} formID * @return {HTMLDivElement} */ function t_zeroForms__createOwnAnswer(input, label, elementObj, inputStyles, inputPreferences, recid, formID) { input.classList.add('t-input__own-answer-input'); // поддержка логики из t_formsApi__waitForFieldReadyState if (input.type === 'checkbox') { input.classList.add('t-checkbox-ownanswer'); } else { input.classList.add('t-radio-ownanswer'); } input.setAttribute('data-own-variant-title', elementObj.li_ownvariant); input.defaultRadioValue = input.value; var ownAnswerWrapper = document.createElement('div'); ownAnswerWrapper.classList.add('t-input__own-answer-wrapper'); if (input.type === 'checkbox') ownAnswerWrapper.classList.add('t-input__own-answer-wrapper-checkbox'); var ownAnswerInput = t_zeroForms__createOwnAnswerInput(elementObj, inputStyles, inputPreferences, input.checked); t_zeroForms__processOwnAnswerPlaceholder( t396__decodeHtmlText(elementObj.li_ownvariantph), ownAnswerInput, inputStyles, recid, formID, input ); ownAnswerWrapper.insertAdjacentElement('beforeend', label); ownAnswerWrapper.insertAdjacentElement('beforeend', ownAnswerInput); t_zeroForms__setListenersForOwnAnswer(input, ownAnswerInput); return ownAnswerWrapper; } /** * Задаём placeholder для поля ввода своего варианта ответа, если он выбран * * @param {string | undefined} placeholderValue * @param {HTMLInputElement} ownAnswerInput * @param inputStyles * @param {string} recid * @param {string} formID * @param {HTMLInputElement} input - чекбокс или радиокнопка */ function t_zeroForms__processOwnAnswerPlaceholder(placeholderValue, ownAnswerInput, inputStyles, recid, formID, input) { if (!placeholderValue) return; ownAnswerInput.placeholder = placeholderValue; if (!inputStyles.color) return; var styles = document.createElement('style'); var selector = t_zeroForms__createSelector(recid, formID, '.t-input__own-answer::placeholder'); styles.textContent = selector + '{color:' + inputStyles.color + ';}'; input.insertAdjacentElement('afterend', styles); } /** * Обрабатываем изменение поля ввода своего варианта ответа. * Сохраняем полученное значение в радиокнопку/чекбокс, для * дальнейшей отправки данных на сервер. * * @param {HTMLInputElement & {defaultRadioValue: string}} radioInput - здесь может быть как радиокнопка, так и чекбокс * @param {HTMLInputElement} ownAnswerInput */ function t_zeroForms__setListenersForOwnAnswer(radioInput, ownAnswerInput) { ownAnswerInput.addEventListener('blur', function (e) { var currentValue = ownAnswerInput.value && ownAnswerInput.value.trim(); var updatedValue = radioInput.defaultRadioValue || ''; if (currentValue) updatedValue += ': ' + currentValue; radioInput.value = updatedValue; radioInput.dispatchEvent(new Event('change', { bubbles: true, cancelable: true })); if (radioInput.type === 'checkbox') t_zeroForms__updateCheckboxesValues(e); }); } function t_zeroForms__createOwnAnswerInput(elementObj, inputStyles, inputPreferences, isSelected) { var ownAnswerInput = t_zeroForms__createInput(elementObj, inputStyles, inputPreferences, 'oneline'); ownAnswerInput.classList.add('t-input__own-answer'); ownAnswerInput.classList.add('t-input_bbonly'); ownAnswerInput.removeAttribute('data-tilda-req'); ownAnswerInput.removeAttribute('name'); var currentMode = t_zeroForms__getTildaMode(); if (isSelected || currentMode === 'zero') ownAnswerInput.classList.add('t-input__own-answer--active'); return ownAnswerInput; } function t_zeroForms__updateOwnAnswerVisibility(inputList, fieldSet) { inputList.forEach(function (input) { input.addEventListener('click', function () { var ownAnswer = fieldSet.querySelector('.t-input__own-answer'); var ownAnswerInput = fieldSet.querySelector('.t-input__own-answer-input'); if (!ownAnswer || !ownAnswerInput) return; var isActive = ownAnswerInput.checked; var classListAction = isActive ? 'add' : 'remove'; ownAnswer.classList[classListAction]('t-input__own-answer--active'); if (isActive && input === ownAnswerInput) ownAnswer.focus(); }); }); } function t_zeroForms__createRadioImage(elementObj, formObj, inputPreferences) { var isCheckbox = elementObj.li_radcb === 'cb'; var galleryOptions; if (elementObj.li_gallery) { try { galleryOptions = typeof elementObj.li_gallery === 'string' ? JSON.parse(elementObj.li_gallery) : elementObj.li_gallery; } catch (err) {} } if (!galleryOptions) return; var arrayOfOptions = t_zeroForms__fromObjToArray(galleryOptions); var selectedOption = parseInt(elementObj.li_defselitem, 10); var fragment = document.createDocumentFragment(); var wrapper = t_zeroForms__createWrapper('t-img-select__container'); if (elementObj.li_imgs_in_row_mob) { wrapper.classList.add(`t-img-select__container__mobile_${elementObj.li_imgs_in_row_mob}-in-row`); } else if (formObj.shouldUseTwoColumnRadioImg) { wrapper.classList.add('t-img-select__container__mobile_2-in-row'); } if (elementObj.li_imgs_in_row) { wrapper.classList.add(`t-img-select__container_${elementObj.li_imgs_in_row}-in-row`); } wrapper.setAttribute('data-check-bgcolor', formObj.inputelscolor || '#000'); if (isCheckbox) { fragment.appendChild(t_zeroForms__createNameFieldForCheckbox(inputPreferences, wrapper, 'img-select')); } fragment.appendChild(wrapper); var inputType = isCheckbox ? 'checkbox' : 'radio'; var ratio = elementObj.li_imgratio ? elementObj.li_imgratio.replace('_', '-') : '1-1'; var imgRatioClass = 't-img-select__indicator_' + ratio; arrayOfOptions.forEach(function (imgOption, i) { var labelElement = t_zeroForms__createLabel('img-select', '', false); var input = document.createElement('input'); const { label, labelText, calcValue } = t396_zeroForms__prepareCalcValue(elementObj, imgOption.alt); if (calcValue) { t396_zeroForms__setCalcValue(input, calcValue); } input.type = inputType; input.value = labelText || imgOption.img; input.classList.add('t-img-select'); if (!isCheckbox) input.name = inputPreferences.name; if (!isCheckbox) input.classList.add('js-tilda-rule'); if (selectedOption && selectedOption === i + 1) input.checked = true; if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); labelElement.insertAdjacentElement('beforeend', input); var indicator = t_zeroForms__createIndicator('img-select', false, { ratio: imgRatioClass, img: imgOption.img }); indicator.classList.add('t-bgimg'); indicator.classList.add('t-img-select__indicator'); if (elementObj.li_img_fill_mode) indicator.classList.add(`t-img-select__indicator_fillmode-${elementObj.li_img_fill_mode}`); if (formObj.inputtitlecolor) indicator.style.borderColor = t_zeroForms__fromHEXtoRGBA(formObj.inputtitlecolor, 0.1); indicator.classList.add(imgRatioClass); indicator.setAttribute('data-original', imgOption.img); indicator.style.backgroundImage = 'url("' + imgOption.img + '")'; labelElement.insertAdjacentElement('beforeend', indicator); if (label) { var textElement = document.createElement('div'); textElement.classList.add('t-img-select__text'); textElement.classList.add('t-text'); textElement.classList.add('t-text_xs'); textElement.innerHTML = label; const labelColor = formObj && formObj.togglelabelcolor; if (labelColor) textElement.style.color = labelColor; labelElement.insertAdjacentElement('beforeend', textElement); } wrapper.insertAdjacentElement('beforeend', labelElement); }); return fragment; } function t_zeroForms__fromHEXtoRGBA(hex, opacityOption) { if (!hex) return ''; if (!opacityOption) opacityOption = 1; // Расширяет значение до 6 значений var shorthandRegex = /^#?([a-f\d])([a-f\d])([a-f\d])$/i; hex = hex.replace(shorthandRegex, function (r, g, b) { return r + r + g + g + b + b; }); var result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex); if (!result) return ''; return `rgba(${parseInt(result[1], 16)}, ${parseInt(result[2], 16)}, ${parseInt(result[3], 16)}, ${opacityOption})`; } function t_zeroForms__createCheckbox(elementObj, labelStyles, formObj, inputPreferences) { var labelElement = t_zeroForms__createLabel('checkbox', labelStyles, formObj); labelElement.classList.add('t-checkbox__control_flex'); var input = document.createElement('input'); t_zeroForms__appendMainSettingToField(input, inputPreferences, 'checkbox', 't-checkbox'); input.value = 'yes'; if (elementObj.li_checked) input.checked = true; if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); labelElement.insertAdjacentElement('beforeend', input); var indicator = t_zeroForms__createIndicator('checkbox', formObj.inputelscolor, { size: formObj.togglesize, borderSize: formObj.togglebordersize, checkboxBorderRadius: formObj.checkboxborderradius, }); labelElement.insertAdjacentElement('beforeend', indicator); var labelText = document.createElement('span'); labelText.classList.add('t-checkbox__labeltext'); const { label, calcValue } = t396_zeroForms__prepareCalcValue(elementObj, elementObj.li_label); if (calcValue) { t396_zeroForms__setCalcValue(input, calcValue); } labelText.innerHTML = label; labelElement.insertAdjacentElement('beforeend', labelText); return labelElement; } function t_zeroForms__createUploadField(recId, elementObj, inputPreferences, type, formObj, zeroForm) { var isUpldWidget = type === 'uw'; if (window.tildamode !== 'published') { var styles = 'color:#fff;background-color:#000; padding:10px 20px; display:inline-block;'; var editorFileInput = document.createElement('div'); editorFileInput.setAttribute('style', styles); var isNeedKey = isUpldWidget && elementObj.li_uwkey === ''; editorFileInput.textContent = isNeedKey ? 'Please set the key' : 'Upload button will be here'; return editorFileInput; } var selector = isUpldWidget ? 't-upwidget' : 't-uploadcare'; var wrapper = t_zeroForms__createWrapper(selector); var wrapperStyles = isUpldWidget ? 'margin-bottom:5px;min-height:38px;' : 'margin-bottom:10px;'; wrapper.setAttribute('style', wrapperStyles); var input = document.createElement('input'); t_zeroForms__appendMainSettingToField(input, inputPreferences, 'hidden', ''); input.setAttribute('role', isUpldWidget ? 'upwidget-uploader' : 'uploadcare-uploader'); if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); input.style.display = 'none'; if (isUpldWidget) { input.setAttribute('data-tilda-upwidget-key', elementObj.li_uwkey || ''); if (elementObj.li_multiupl === 'y') input.setAttribute('data-tilda-upwidget-multiple', '1'); } else { input.setAttribute('data-public-key', elementObj.li_uckey || 'demopublickey'); } wrapper.insertAdjacentElement('beforeend', input); var path = isUpldWidget ? 'tilda-upwidget-1.1.min.js' : 'uploadcare-3.x.min.js'; if (path === 'uploadcare-3.x.min.js' && !window.jQuery) path = 'uploadcare-3.x.full.min.js'; if (isUpldWidget || (!isUpldWidget && !document.querySelector('script[src*="uploadcare-3.x"]'))) { t_zeroForms__addResource({ recId, id: selector + '-zero-form', path, type: 'script' }); } const formId = zeroForm.getAttribute('data-elem-id'); const baseSelector = t_zeroForms__createSelector(recId, formId, ''); const uploadCareSelector = '.uploadcare--widget__button.uploadcare--widget__button_type_open'; const uploadWidget = '.t-upwidget-container__button'; const uploadBtnSelector = isUpldWidget ? uploadWidget : uploadCareSelector; let styleValue = ''; const uploadButtonFontStyles = t_zeroForms__getUploadButtonFontStyles(formObj, baseSelector + uploadBtnSelector); if (uploadButtonFontStyles) styleValue += uploadButtonFontStyles; const uploadButtonColorStyles = t_zeroForms__getUploadButtonColorStyles(formObj, baseSelector + uploadBtnSelector); if (uploadButtonColorStyles) styleValue += uploadButtonColorStyles; const gradientSelector = isUpldWidget ? `.t-upwidget.tn-form__btn-gradient ${uploadWidget}` : `.t-uploadcare.tn-form__btn-gradient ${uploadCareSelector}`; const uploadBtnGradientStyles = t_zeroForms__getGradientUploadButtonBGStyles( formObj, baseSelector + gradientSelector ); if (uploadBtnGradientStyles) { styleValue += uploadBtnGradientStyles; wrapper.classList.add('tn-form__btn-gradient'); } if (styleValue) { const uploadBtnStylesID = (isUpldWidget ? 't-zero-form-uploadwidget-btn-styles-' : 't-zero-form-uploadcare-btn-styles-') + formId + '-' + recId; t_zeroForms__addInlineTag({ tag: 'style', id: uploadBtnStylesID, content: styleValue, zeroForm, }); } return wrapper; } function t_zeroForms__createDateField(recId, elementObj, inputPreferences, inputStyles, formObj) { var wrapper = t_zeroForms__createWrapper('t-datepicker__wrapper'); var input = document.createElement('input'); var datepickerRestrictions = (elementObj.li_dateUnavailPast ? 'past,' : '') + (elementObj.li_dateUnavailMo ? 'mo,' : '') + (elementObj.li_dateUnavailTu ? 'tu,' : '') + (elementObj.li_dateUnavailWe ? 'we,' : '') + (elementObj.li_dateUnavailTh ? 'th,' : '') + (elementObj.li_dateUnavailFr ? 'fr,' : '') + (elementObj.li_dateUnavailSa ? 'sa,' : '') + (elementObj.li_dateUnavailSu ? 'su,' : '') + (elementObj.li_dateUnavailFuture ? 'future,' : '') + (elementObj.li_dateUnavailToday ? 'today,' : ''); if (datepickerRestrictions.length && datepickerRestrictions[datepickerRestrictions.length - 1] === ',') { datepickerRestrictions = datepickerRestrictions.slice(0, -1); } t_zeroForms__appendMainSettingToField(input, inputPreferences, 'text', [ 't-input', 't-datepicker', 'js-tilda-mask', ]); t_zeroForms__appendAttributes(input, inputPreferences); t_zeroForms__appendStylesToField(input, inputStyles); input.setAttribute('data-tilda-rule', 'date'); input.setAttribute('data-tilda-dateformat', elementObj.li_dateformat); input.setAttribute('data-tilda-datediv', elementObj.li_datediv); input.setAttribute('data-tilda-mask', elementObj.li_datemask); input.setAttribute('data-tilda-dateunvailable', datepickerRestrictions); input.id = 'input_' + elementObj.lid; wrapper.insertAdjacentElement('beforeend', input); var svgIconColor = formObj.inputsstyle ? formObj.inputelscolor : inputStyles.color; var svgIcon = ''; wrapper.insertAdjacentHTML('beforeend', svgIcon); t_zeroForms__addResource({ recId, id: 't-zero-date-styles', path: 'tilda-date-picker-1.0.min.css', type: 'link' }); t_zeroForms__addResource({ recId, id: 't-zero-date-script', path: 'tilda-date-picker-1.0.min.js', type: 'script' }); return wrapper; } function t_zeroForms__createQuantityField(elementObj, inputStyles, color, inputPreferences) { var wrapper = t_zeroForms__createWrapper('t-inputquantity__wrapper'); var minusBtn = t_zeroForms__createQuantityBtn('minus', color); var plusBtn = t_zeroForms__createQuantityBtn('plus', color); var input = document.createElement('input'); t_zeroForms__appendMainSettingToField(input, inputPreferences, 'number', ['t-input', 't-inputquantity']); t_zeroForms__appendAttributes(input, inputPreferences); t_zeroForms__appendStylesToField(input, inputStyles); input.value = elementObj.li_value || ''; input.id = 'input_' + elementObj.lid; input.setAttribute('data-tilda-rule', 'number'); wrapper.insertAdjacentElement('beforeend', minusBtn); wrapper.insertAdjacentElement('beforeend', input); wrapper.insertAdjacentElement('beforeend', plusBtn); return wrapper; } function t_zeroForms__createQuantityBtn(type, color) { var btn = document.createElement('span'); btn.classList.add('t-inputquantity__btn'); btn.classList.add('t-inputquantity__btn-' + type); if (color) btn.style.color = color; btn.innerHTML = type === 'minus' ? '–' : '+'; return btn; } /** * Валидирует числовые значения поля формы, убирает пробелы из значений и может возвращать значение по умолчанию * * @param {string} value * @param {string} defaultValue * @returns {string} */ function t_zeroForms__validateNumericValue(value, defaultValue) { if (!value && defaultValue !== undefined) return defaultValue; if (value === undefined) return value; return value.replace(/\s/g, ''); } function t_zeroForms__createQuantityRange(recId, elementObj, inputStyles, formObj, inputPreferences) { var wrapper = t_zeroForms__createWrapper('t-range__wrapper'); var input = document.createElement('input'); t_zeroForms__appendMainSettingToField(input, inputPreferences, 'range', 't-range'); if (formObj.inputelscolor) input.setAttribute('data-range-color', formObj.inputelscolor); input.min = t_zeroForms__validateNumericValue(elementObj.li_vmin, '0'); input.max = t_zeroForms__validateNumericValue(elementObj.li_vmax, '10'); input.step = t_zeroForms__validateNumericValue(elementObj.li_step, '1'); input.value = t_zeroForms__validateNumericValue(elementObj.li_value); input.style.width = '100%'; if (!elementObj.li_title && !elementObj.li_subtitle) { input.ariaLabel = 'range'; } else { input.id = 'input_' + elementObj.lid; } wrapper.insertAdjacentElement('beforeend', input); var textField = document.createElement('div'); textField.classList.add('t-range__value-txt'); textField.classList.add('t-descr'); textField.classList.add('t-descr_xxs'); textField.style.display = 'none'; wrapper.insertAdjacentElement('beforeend', textField); var textWrapper = document.createElement('div'); textWrapper.classList.add('t-range__interval-txt-wrapper'); const valueFieldColor = formObj.togglelabelcolor; var minValueField = t_zeroForms__createRangeField('min', valueFieldColor, elementObj.li_vmin || '0'); var maxValueField = t_zeroForms__createRangeField('max', valueFieldColor, elementObj.li_vmax || '10'); textWrapper.insertAdjacentElement('beforeend', minValueField); textWrapper.insertAdjacentElement('beforeend', maxValueField); wrapper.insertAdjacentElement('beforeend', textWrapper); t_zeroForms__addResource({ recId, id: 't-zero-range-script', path: 'tilda-range-1.0.min.js', type: 'script', }); t_zeroForms__addResource({ recId, id: 't-zero-range-styles', path: 'tilda-range-1.0.min.css', type: 'link', }); return wrapper; } function t_zeroForms__createRangeField(type, color, value) { var textField = document.createElement('div'); textField.classList.add('t-range__interval-txt'); textField.classList.add('t-range__interval-txt_' + type); textField.classList.add('t-descr'); textField.classList.add('t-descr_xxs'); if (color) textField.style.color = color; textField.innerHTML = value; return textField; } function t_zeroForms__createCalculation(recId, elementObj, inputStyles, inputPreferences, titleStyles) { var fragment = document.createDocumentFragment(); var hiddenInput = document.createElement('input'); t_zeroForms__appendMainSettingToField(hiddenInput, inputPreferences, 'hidden', 't-calc__hiddeninput'); hiddenInput.tabIndex = -1; hiddenInput.value = '0'; fragment.appendChild(hiddenInput); var wrapper = t_zeroForms__createWrapper(['t-calc__wrapper', 't-name', 't-name_md']); wrapper.style.color = inputStyles.color; wrapper.style.fontFamily = titleStyles.fontFamily; wrapper.style.fontSize = inputStyles.fontSize; wrapper.style.fontWeight = inputStyles.fontWeight; t_zeroForms__createCalcTextField(elementObj.li_prefix, 'prefix', wrapper); var valueField = document.createElement('span'); valueField.classList.add('t-calc'); valueField.setAttribute('data-calc-expr', t_zeroForms__removeStringQuotes(elementObj.li_expr)); valueField.textContent = '0'; wrapper.insertAdjacentElement('beforeend', valueField); t_zeroForms__createCalcTextField(elementObj.li_postfix, 'postfix', wrapper); t_zeroForms__addResource({ recId, id: 't-zero-calc', path: 'tilda-calc-1.0.min.js', type: 'script' }); fragment.appendChild(wrapper); if (elementObj.li_addtocart !== 'y') return fragment; if (elementObj.li_prod_title) { // prettier-ignore var titleInput = t_zeroForms__createHiddenField(elementObj.li_prod_title, 'prod_title', 't-calc__hidden__prod_title'); wrapper.insertAdjacentElement('beforeend', titleInput); } if (elementObj.li_prod_img) { // prettier-ignore var productIMG = t_zeroForms__createHiddenField(elementObj.li_prod_img, 'prod_img', 't-calc__hidden__prod_img'); wrapper.insertAdjacentElement('beforeend', productIMG); } if (elementObj.li_prod_options) { // prettier-ignore var productOptions = t_zeroForms__createHiddenField(elementObj.li_prod_options, 'prod_options', 't-calc__hidden__prod_options'); wrapper.insertAdjacentElement('beforeend', productOptions); } return fragment; } function t_zeroForms__createCalcTextField(value, type, wrapper) { if (!value) return; var postfix = document.createElement('span'); postfix.classList.add('t-calc__' + type + '-text'); postfix.innerHTML = value; wrapper.insertAdjacentElement('beforeend', postfix); } // Для рендера анимации иконки кнопки на артборде const ICON_ANIMATIONS = { rotate15: 'tn-icon-animation-rotate15 2s linear infinite', rotate360: 'tn-icon-animation-rotate360 3s linear infinite', scale: 'tn-icon-animation-scale 2s linear infinite', scaleX: 'tn-icon-animation-scaleX 2s linear infinite', scaleY: 'tn-icon-animation-scaleY 2s linear infinite', moveX: 'tn-icon-animation-moveX 2s linear infinite', moveY: 'tn-icon-animation-moveY 2s linear infinite', opacity50: 'tn-icon-animation-opacity50 2s linear infinite', opacity100: 'tn-icon-animation-opacity100 2s linear infinite', }; /** * @param {HTMLElement} iconElement - элемент иконки кнопки * @param {string} value - значение анимации из списка ICON_ANIMATIONS */ function t_zeroForms__applyIconAnimation(iconElement, value) { iconElement.style.transformOrigin = 'center'; iconElement.style.backfaceVisibility = 'hidden'; iconElement.style.animation = ICON_ANIMATIONS[value] || ''; } function t_zeroForms__createButtonIcon(formObj, btn) { const btnIconValue = formObj.form_btn_icon; const btnIconHoverValue = formObj.form_btn_iconhover; const btnContent = btn.querySelector('.t-submit__content'); if (!btnIconValue && !btnIconHoverValue) return null; const iconElement = document.createElement('span'); iconElement.classList.add('t-submit__icon'); if (btnIconValue) { iconElement.style.setProperty('--icon', `url(${btnIconValue})`); const isArrow = btnIconValue?.match(/^https:\/\/static\.tildacdn\.[a-z]+\/lib\/icons\/button\/.+/i); if (isArrow) iconElement.classList.add('t-submit__icon-arrow'); } if (btnIconHoverValue) { iconElement.style.setProperty('--icon-hover', `url(${btnIconHoverValue})`); const isArrow = btnIconHoverValue?.match(/^https:\/\/static\.tildacdn\.[a-z]+\/lib\/icons\/button\/.+/i); if (isArrow) iconElement.classList.add('t-submit__icon-hover-arrow'); } else { iconElement.classList.add('t-submit__icon-no-hover'); } let btnIconPositionValue = formObj.form_btn_iconposition || 'left'; const btnIconPositionCssVarData = t396__parseGlobalStyleCSSVar(btnIconPositionValue); if (btnIconPositionCssVarData) btnIconPositionValue = btnIconPositionCssVarData.fallback === 'row-reverse' ? 'right' : 'left'; if (btnIconPositionValue === 'left') { iconElement.style.order = 0; } else if (btnIconPositionValue === 'right') { iconElement.style.order = 1; } const btnIconSizeValue = formObj.form_btn_iconsize; if (t396__isGlobalStyleCSSVar(btnIconSizeValue)) { iconElement.style.setProperty('--icon-size', btnIconSizeValue); } else { const parsedBtnIconSizeValue = parseInt(btnIconSizeValue || '0', 10); const btnIconSize = btnIconSizeValue && !Number.isNaN(parsedBtnIconSizeValue) ? parsedBtnIconSizeValue : 20; iconElement.style.setProperty('--icon-size', `${btnIconSize}px`); } if (btnContent) { const btnIconMarginValue = formObj.form_btn_iconmargin ?? ''; if (t396__isGlobalStyleCSSVar(btnIconMarginValue)) { btnContent.style.setProperty('--button-content-gap', btnIconMarginValue); } else { const parsedBtnIconMarginValue = parseInt(btnIconMarginValue, 10); const gapValue = Number.isNaN(parsedBtnIconMarginValue) ? 0 : parsedBtnIconMarginValue; btnContent.style.setProperty('--button-content-gap', `${gapValue}px`); } } let btnIconAnimationValue = formObj.form_btn_iconanimation; const btnIconAnimationCssVarData = t396__parseGlobalStyleCSSVar(btnIconAnimationValue); if (btnIconAnimationCssVarData) btnIconAnimationValue = btnIconAnimationCssVarData.fallback; if (btnIconAnimationValue) t_zeroForms__applyIconAnimation(iconElement, btnIconAnimationValue); return iconElement; } /** * create submit button for current form * * @param {string} recid - record ID * @param {HTMLElement} zeroForm - current zeroForm * @param {string} formID - form ID * @param {formObj} formObj - obj with params * @returns {HTMLElement} */ function t_zeroForms__createFormButton(recid, zeroForm, formID, formObj) { const btnWrapper = document.createElement('div'); btnWrapper.classList.add('tn-form__submit'); btnWrapper.style.textAlign = formObj.buttonalign; btnWrapper.style.marginTop = formObj.buttonmargtop + 'px'; const btn = document.createElement('button'); btn.type = 'submit'; btn.classList.add('t-submit'); const btnContent = document.createElement('div'); btnContent.classList.add('t-submit__content'); btn.append(btnContent); var title = formObj.buttontitle; if (title) { const btnTitleElement = document.createElement('span'); btnTitleElement.classList.add('t-submit__text'); btnTitleElement.innerHTML = title; btnContent.append(btnTitleElement); } t_zeroForms__setBtnInlineStyles(formObj, btn); const btnIconElement = t_zeroForms__createButtonIcon(formObj, btn); if (btnIconElement) btnContent.prepend(btnIconElement); t_zeroForms__addButtonBorder(formObj, btn); t_zeroForms__addButtonShadowStyles(formObj, btn); t_zeroForms__addButtonHoverShadowStyles(formObj, btn); btnWrapper.insertAdjacentElement('beforeend', btn); if (window.tildamode === 'zero' || window.tildamode === 'edit') { // fix for correctly view submit btn in editor if (window.tn && window.tn.curResolution < 640) btn.style.whiteSpace = 'normal'; t_zeroForms__generateBtnStyles(btn, recid, formID, formObj, zeroForm); } else { t_zeroForms__onRender(zeroForm, true, function () { t_zeroForms__generateBtnStyles(btn, recid, formID, formObj, zeroForm); }); } return btnWrapper; } /** * Формы, разбитые на шаги: zeroForm -> результат t_form__initStepForm. * В редакторе форма перерисовывается при каждом изменении настроек, и шаги инициализируются заново. * По этой записи перед повторной инициализацией вызывается destroy, чтобы снять слушатель resize прошлых шагов. * WeakMap – чтобы удаленные со страницы формы не держались в памяти. */ window.t_zeroForms__stepForms = window.t_zeroForms__stepForms || new WeakMap(); /** * Есть ли в форме поле «Разбиение на шаги» * * @param {HTMLElement} container - форма или ее блок полей * @returns {boolean} */ function t_zeroForms__hasSteps(container) { return Boolean(container.querySelector('.t-input-group_st')); } /** * Создает разделитель шагов (поле «Разбиение на шаги») в том же виде, что и в обычных блоках * * @param {FormObjectEl} elementObj * @param {HTMLElement} inputGroup * @returns {HTMLElement} */ function t_zeroForms__createStepDivider(elementObj, inputGroup) { const divider = document.createElement('div'); divider.classList.add('t-form-step-divider'); // проверка полей шага работает только на сайте, где форма –
(см. t_zeroForms__createForm) if (t_zeroForms__getTildaMode() !== 'published') divider.classList.add('t-form-step-divider_novalidate'); if (elementObj.li_btntitle) { divider.setAttribute('data-tilda-form-step-btn-next', t396__decodeHtmlText(elementObj.li_btntitle)); } if (elementObj.li_btntitle2) { divider.setAttribute('data-tilda-form-step-btn-prev', t396__decodeHtmlText(elementObj.li_btntitle2)); } inputGroup.append(divider); return inputGroup; } /** * Разбивает форму на шаги, если в ней есть поле «Разбиение на шаги». * В редакторе форма перерисовывается при каждом изменении, поэтому текущий шаг хранится в атрибуте элемента * и восстанавливается после перерисовки. * При каждой смене шага на элементе формы вызывается событие 'zero:form-step-change'. * * @param {HTMLElement} zeroForm * @param {string} recid * @param {string} tildamode */ function t_zeroForms__initSteps(zeroForm, recid, tildamode) { const prevStepForm = window.t_zeroForms__stepForms.get(zeroForm); if (prevStepForm) { prevStepForm.destroy(); window.t_zeroForms__stepForms.delete(zeroForm); } const inputsBox = zeroForm.querySelector('.t-form__inputsbox'); if (!inputsBox || !t_zeroForms__hasSteps(inputsBox)) { zeroForm.removeAttribute('data-form-step'); return; } // форма примет окончательный размер только после разбиения на шаги inputsBox.setAttribute('data-field-async', 'true'); // Пока шаги не инициализированы, показываем только поля первого шага, чтобы не мелькали остальные. // Класс снимается сразу после разбиения на шаги (initStepForm ниже): если скрипты уже загружены – в этом же // вызове, и он не успеет отрисоваться. Если скрипт не загрузился, показываем все поля, чтобы форму можно было отправить. const STEPS_PENDING_CLASS = 't-form__inputsbox_steps-pending'; const showAllFields = () => inputsBox.classList.remove(STEPS_PENDING_CLASS); inputsBox.classList.add(STEPS_PENDING_CLASS); const isConditional = Boolean(zeroForm.querySelector('.t-conditional-form')); if (typeof window.t_form__initStepForm !== 'function') { t_zeroForms__addResource({ recId: recid, id: 't-zero-step-form-script', path: 'tilda-step-form-1.1.min.js', type: 'script', onError: showAllFields, }); } // скрипт условий уже добавлен при создании формы, здесь только подписываемся на ошибку его загрузки if (isConditional && typeof window.t_form__conditionals__initStepForm !== 'function') { t_zeroForms__addResource({ recId: recid, id: 't-zero-conditional-form', path: 'tilda-conditional-form-1.0.min.js', type: 'script', onError: showAllFields, }); } const isEditor = tildamode === 'zero' || tildamode === 'edit'; // в редакторе размер элемента пересчитывает сам редактор по событию смены шага const artBoard = isEditor ? null : zeroForm.closest('.t396__artboard'); const initStepForm = () => { // пока загружался скрипт, форму могли перерисовать if (!inputsBox.isConnected) return; const stepForm = window.t_form__initStepForm(zeroForm, { recId: recid, buttonTemplate: t_zeroForms__createStepButton(zeroForm), scrollOnChange: !isEditor, // на холсте поля не редактируются, а слушатели условных полей требуют t_onFuncLoad listenConditionalFields: tildamode !== 'zero', initialStep: parseInt(zeroForm.getAttribute('data-form-step'), 10), lang: window.t_forms__lang || window.t_zeroForms__browserLang, onStepChange: state => { zeroForm.setAttribute('data-form-step', state.index); if (artBoard && typeof window.t396__updateAutoHeight === 'function') { window.t396__updateAutoHeight(artBoard); } zeroForm.dispatchEvent( new CustomEvent('zero:form-step-change', { bubbles: true, detail: { step: state.step, total: state.total }, }) ); }, onReady: () => { inputsBox.setAttribute('data-input-ready', 'true'); inputsBox.dispatchEvent(new CustomEvent('inputReady')); }, }); showAllFields(); if (stepForm) window.t_zeroForms__stepForms.set(zeroForm, stepForm); t_zeroForms__setStepsStyles(zeroForm, t_zeroForms__createFormObj(recid, zeroForm)); }; t_zeroForms__onFuncLoad('t_form__initStepForm', () => { // tilda-step-form ждет скрипт условий без запаса по времени и падает, если страница уже загрузилась if (isConditional) { t_zeroForms__onFuncLoad('t_form__conditionals__initStepForm', initStepForm); } else { initStepForm(); } }); } /** * Кнопка для шаблона кнопок «Назад» и «Далее»: копия кнопки отправки, чтобы у кнопок шагов были те же настройки * * @param {HTMLElement} zeroForm * @returns {HTMLElement | null} */ function t_zeroForms__createStepButton(zeroForm) { const submitBtn = zeroForm.querySelector('.tn-form__submit .t-submit'); if (!submitBtn) return null; const btn = submitBtn.cloneNode(true); btn.type = 'button'; btn.classList.add('t-form__screen-btn'); btn.querySelectorAll('.t-submit__icon').forEach(icon => icon.remove()); let btnText = btn.querySelector('.t-submit__text'); if (!btnText) { btnText = document.createElement('span'); btnText.classList.add('t-submit__text'); btn.querySelector('.t-submit__content').append(btnText); } // в .js-btn-txt tilda-step-form записывает текст кнопки btnText.classList.add('js-btn-txt'); return btn; } /** * Красит счетчик шагов в цвет заголовков полей, а прогресс — в цвет кнопки, как в обычных блоках * * @param {HTMLElement} zeroForm * @param {formObj} formObj */ function t_zeroForms__setStepsStyles(zeroForm, formObj) { const titleColor = formObj.inputtitlecolor || ''; const isGradient = t_zeroForms__isColorContainsGradient(formObj.buttonbgcolor); const progressColor = isGradient ? '' : formObj.buttonbgcolor || ''; zeroForm.querySelectorAll('.t-form__screen-number-container').forEach(el => { el.style.color = titleColor; // в обычных блоках счетчик берет шрифт проекта через .t-name, в зеро-форме шрифт задается в настройках el.style.fontFamily = formObj.inputfontfamily || ''; }); zeroForm.querySelectorAll('.t-form__screen-progress-circle').forEach(el => { el.style.stroke = titleColor; }); zeroForm.querySelectorAll('.t-form__screen-progress-bar').forEach(el => { el.style.stroke = progressColor; }); } function t_zeroForms__setBtnInlineStyles(formObj, btn) { // prettier-ignore var btnFontWeight = formObj.buttonfontweight === 'variation' ? formObj.buttonvariationweight : formObj.buttonfontweight; var isStretched = (formObj.inputpos === 'v' && formObj.buttonwidthstretch === 'y') || !formObj.buttonwidth; btn.style.width = isStretched ? '100%' : formObj.buttonwidth + 'px'; // поверх растянутой кнопки счетчик шагов не поместится, ему нужно свое место в ряду btn.classList.toggle('tn-form__btn-stretch', isStretched); if (btnFontWeight) btn.style.fontWeight = btnFontWeight; if (formObj.buttonheight) btn.style.height = formObj.buttonheight + 'px'; if (formObj.buttonalign === 'center') { btn.style.marginLeft = 'auto'; btn.style.marginRight = 'auto'; } else { btn.style.marginLeft = ''; btn.style.marginRight = ''; } } function t_zeroForms__generateBtnStyles(btn, recid, formID, formObj, zeroForm) { const btnFontFamily = window.getComputedStyle(btn).fontFamily; const buttonStyles = t_zeroForms__generateButtonStyles(formObj, btnFontFamily); const buttonHoverStyles = t_zeroForms__processButtonBG(formObj, true); const baseSelector = t_zeroForms__createSelector(recid, formID, ''); const selector = baseSelector + '.t-submit'; let styleValue = selector + '{' + buttonStyles + '}'; const buttonGradientStyles = t_zeroForms__getGradientButtonBGStyles(formObj, selector + '.tn-form__btn-gradient'); if (buttonGradientStyles) styleValue += buttonGradientStyles; btn.classList.toggle('tn-form__btn-gradient', Boolean(buttonGradientStyles)); const submitTextColorStyles = t_zeroForms__getButtonColorStyles(formObj, baseSelector + '.t-submit'); if (submitTextColorStyles) styleValue += submitTextColorStyles; const btnStylesID = 't-zero-form-btn-styles-' + formID + '-' + recid; const btnStyles = document.getElementById(btnStylesID); if (btnStyles && btnStyles.parentElement) btnStyles.parentElement.removeChild(btnStyles); t_zeroForms__addInlineTag({ tag: 'style', id: btnStylesID, content: styleValue, zeroForm }); // удаляем hover-стили до проверки, чтобы при ресайзе не остались стили от другого разрешения const btnHoverStylesID = 't-zero-form-btn-hover-styles-' + formID + '-' + recid; const btnHoverStyles = document.getElementById(btnHoverStylesID); if (btnHoverStyles && btnHoverStyles.parentElement) btnHoverStyles.parentElement.removeChild(btnHoverStyles); if (buttonHoverStyles) { let hoverSelector = selector.split(', ').map(function (selectorPart) { return selectorPart + ':hover'; }); hoverSelector = hoverSelector.join(', '); const styleHoverValue = hoverSelector + '{' + buttonHoverStyles + '}'; t_zeroForms__addInlineTag({ tag: 'style', id: btnHoverStylesID, content: styleHoverValue, zeroForm }); } } /** * create styles in string for submit and upload buttons * in t_zeroForms__createFormButton() * * @param {formObj} formObj * @param {string} btnFontFamily * @returns {string} */ function t_zeroForms__generateButtonStyles(formObj, btnFontFamily) { var buttonStyles = { // prettier-ignore 'border-radius': formObj.buttonradius || '0', 'font-size': formObj.buttonfontsize || '', 'font-family': formObj.buttonfontfamily || btnFontFamily, cursor: 'pointer', }; var stylesString = ''; var pxValues = ['height']; if (!t396__isGlobalStyleCSSVar(buttonStyles['border-radius'])) pxValues.push('border-radius'); if (!t396__isGlobalStyleCSSVar(buttonStyles['font-size'])) pxValues.push('font-size'); for (var k in buttonStyles) { if (buttonStyles[k]) { var isPxContains = pxValues.some(function (key) { return key === k.toString(); }); if (isPxContains) buttonStyles[k] += 'px'; stylesString += k + ':' + buttonStyles[k] + ';'; } } stylesString += t_zeroForms__processButtonBG(formObj, false); return stylesString; } function t_zeroForms__processButtonBG(formObj, isHover) { var buttonBGObj = t_zeroForms__getButtonBGObj(formObj); var currentBG = isHover ? buttonBGObj.buttonHoverBG : buttonBGObj.buttonBG; if (buttonBGObj.buttonBGHasGradient || buttonBGObj.buttonHoverBGHasGradient) return ''; if (!currentBG) return isHover ? '' : 'background-color: transparent;'; return 'background-color: ' + currentBG + ';'; } function t_zeroForms__getButtonBGObj(formObj) { var buttonBG = formObj.buttonbgcolor; var buttonHoverBG = formObj.buttonhoverbgcolor; var buttonBGHasGradient = t_zeroForms__isColorContainsGradient(buttonBG); var buttonHoverBGHasGradient = t_zeroForms__isColorContainsGradient(buttonHoverBG); return { buttonBG: buttonBG, buttonHoverBG: buttonHoverBG, buttonBGHasGradient: buttonBGHasGradient, buttonHoverBGHasGradient: buttonHoverBGHasGradient, }; } function t_zeroForms__isColorContainsGradient(string) { return string && string.indexOf('-gradient(') !== -1; } function t_zeroForms__getGradientButtonBGStyles(formObj, selector) { var buttonBGObj = t_zeroForms__getButtonBGObj(formObj); var buttonBGHasGradient = buttonBGObj.buttonBGHasGradient; var buttonHoverBGHasGradient = buttonBGObj.buttonHoverBGHasGradient; var buttonBG = buttonBGObj.buttonBG; var buttonHoverBG = buttonBGObj.buttonHoverBG; if (!buttonBGHasGradient && !buttonHoverBGHasGradient) return ''; var styles = ''; styles += selector + '::before {'; styles += t_zeroForms__generateButtonBGStyle(buttonBG, buttonBGHasGradient); styles += '}'; styles += selector + '::after {'; styles += t_zeroForms__generateButtonBGStyle(buttonHoverBG, buttonHoverBGHasGradient); styles += '}'; return styles; } function t_zeroForms__getGradientUploadButtonBGStyles(formObj, selector) { const uploadButtonBG = formObj.uploadbuttonbgcolor; const uploadButtonBGHasGradient = t_zeroForms__isColorContainsGradient(uploadButtonBG); if (!uploadButtonBGHasGradient) return ''; let styles = ''; styles += selector + '::before {'; styles += t_zeroForms__generateButtonBGStyle(uploadButtonBG, uploadButtonBGHasGradient); styles += '}'; return styles; } function t_zeroForms__generateButtonBGStyle(buttonBG, hasGradient) { if (!buttonBG) buttonBG = hasGradient ? 'none' : 'transparent'; return hasGradient ? 'background-image: ' + buttonBG + ';' : 'background-color: ' + buttonBG + ';'; } function t_zeroForms__getButtonColorStyles(formObj, selector) { const buttonTextColor = formObj.buttoncolor; const buttonTextColorHasGradient = t_zeroForms__isColorContainsGradient(formObj.buttoncolor); let buttonHoverTextColor; let buttonHoverTextColorHasGradient; if (formObj.buttonhovercolor) { buttonHoverTextColor = formObj.buttonhovercolor; buttonHoverTextColorHasGradient = t_zeroForms__isColorContainsGradient(formObj.buttonhovercolor); } else { buttonHoverTextColor = buttonTextColor; buttonHoverTextColorHasGradient = buttonTextColorHasGradient; } let styles = ''; styles += `${selector} .t-submit__text {${t_zeroForms__generateButtonTextColorStyles(buttonTextColor, buttonTextColorHasGradient)}}`; styles += `${selector}:hover .t-submit__text {${t_zeroForms__generateButtonTextColorStyles(buttonHoverTextColor, buttonHoverTextColorHasGradient)}}`; styles += `${selector} .t-submit__icon::before {${t_zeroForms__generateButtonIconColorStyles(buttonTextColor, buttonTextColorHasGradient)}}`; styles += `${selector} .t-submit__icon::after {${t_zeroForms__generateButtonIconColorStyles(buttonHoverTextColor, buttonHoverTextColorHasGradient)}}`; return styles; } function t_zeroForms__getUploadButtonFontStyles(formObj, selector) { const fontSize = formObj.buttonfontsize || ''; // наследуем от кнопки сабмита const fontFamily = formObj.buttonfontfamily || 'inherit'; // наследуем от кнопки сабмита let styles = ''; styles += `${selector} { font-size: ${fontSize}px; font-family: ${fontFamily}; }`; return styles; } function t_zeroForms__getUploadButtonColorStyles(formObj, selector) { const uploadButtonBgColor = formObj.uploadbuttonbgcolor; const uploadButtonTextColor = formObj.uploadbuttontextcolor; const uploadButtonBorderColor = formObj.uploadbuttonbordercolor; const uploadButtonBorderSize = formObj.uploadbuttonbordersize; const uploadButtonRaduis = formObj.buttonradius || 0; let styles = ''; styles += `${selector} { background-color: ${uploadButtonBgColor}; color: ${uploadButtonTextColor}; border: ${uploadButtonBorderSize}px solid ${uploadButtonBorderColor}; border-radius: ${uploadButtonRaduis}px; }`; return styles; } function t_zeroForms__generateButtonTextColorStyles(textColor, hasGradient) { let styles = ''; if (hasGradient) { styles = ` color: transparent; background-image: ${textColor}; background-clip: text; `; } else { styles = ` color: ${textColor}; `; } return styles; } function t_zeroForms__generateButtonIconColorStyles(textColor, hasGradient) { let styles = ''; if (hasGradient) { styles = ` background-image: ${textColor}; `; } else { styles = ` color: ${textColor}; `; } return styles; } function t_zeroForms__addButtonBorder(formObj, btnElement) { const buttonBorderColor = formObj.buttonbordercolor; const buttonBorderSize = formObj.buttonbordersize || 0; const buttonHoverBorderColor = formObj.buttonhoverbordercolor || buttonBorderColor; btnElement.style.setProperty('--border-color', buttonBorderColor); btnElement.style.setProperty( '--border-size', t396__isGlobalStyleCSSVar(buttonBorderSize) ? buttonBorderSize : `${buttonBorderSize}px` ); btnElement.style.setProperty('--hover-border-color', buttonHoverBorderColor); const borderColorHasGradient = t_zeroForms__isColorContainsGradient(buttonBorderColor); const hoverBorderColorHasGradient = t_zeroForms__isColorContainsGradient(buttonHoverBorderColor); if (borderColorHasGradient || hoverBorderColorHasGradient) { const gradientBorderElement = document.createElement('span'); gradientBorderElement.classList.add('t-submit__gradient-border'); btnElement.append(gradientBorderElement); } if (borderColorHasGradient) btnElement.classList.add('t-submit--border-gradient'); if (hoverBorderColorHasGradient) btnElement.classList.add('t-submit--border-gradient-hover'); } function t_zeroForms__addButtonShadowStyles(formObj, btnElement) { // В версии 3 тень стали многослойными и поля для их формирования изменились, поэтому для обратной совместимости // проверяем наличие поля или версию формы if (formObj.version >= 3 || formObj.form_btn_shadows) { btnElement.style.setProperty('--button-shadow', formObj.form_btn_shadows || 'none'); return; } const offsetX = formObj.form_btn_shadow_x || 0; const offsetY = formObj.form_btn_shadow_y || 0; const blurRadius = formObj.form_btn_shadow_blur || 0; const spreadRadius = formObj.form_btn_shadow_spread || 0; const colorRgb = formObj.form_btn_shadow_color || '0, 0, 0'; const colorOpacity = formObj.form_btn_shadow_opacity || 0; const btnShadowValue = `${offsetX}px ${offsetY}px ${blurRadius}px ${spreadRadius}px rgba(${colorRgb}, ${colorOpacity / 100})`; btnElement.style.setProperty('--button-shadow', btnShadowValue); } function t_zeroForms__addButtonHoverShadowStyles(formObj, btnElement) { // В версии 3 тень стали многослойными и поля для их формирования изменились, поэтому для обратной совместимости // проверяем наличие поля или версию формы if (formObj.version >= 3 || formObj.form_btn_shadows_hover) { btnElement.style.setProperty('--button-hover-shadow', formObj.form_btn_shadows_hover); const duration = formObj.form_btn_shadows_hover_speed || 0.3; // значение может прийти числом или CSS-выражением (например, var(...)), единицы добавляем только к числу const durationValue = isFinite(duration) ? `${duration}s` : duration; btnElement.style.setProperty('--button-hover-shadow-duration', durationValue); return; } const fields = [ 'form_btn_hover_shadow_x', 'form_btn_hover_shadow_y', 'form_btn_hover_shadow_blur', 'form_btn_hover_shadow_spread', 'form_btn_hover_shadow_color', 'form_btn_hover_shadow_opacity', ]; const allEmpty = fields.every(key => !formObj[key]); if (allEmpty) { // при ресайзе на брейкпоинте без hover-тени сбрасываем значение, оставшееся от другого разрешения btnElement.style.removeProperty('--button-hover-shadow'); btnElement.style.removeProperty('--button-hover-shadow-duration'); return; } const offsetX = formObj.form_btn_hover_shadow_x || 0; const offsetY = formObj.form_btn_hover_shadow_y || 0; const blurRadius = formObj.form_btn_hover_shadow_blur || 0; const spreadRadius = formObj.form_btn_hover_shadow_spread || 0; const colorRgb = formObj.form_btn_hover_shadow_color || '0, 0, 0'; const colorOpacity = formObj.form_btn_hover_shadow_opacity || 0; const btnHoverShadowValue = `${offsetX}px ${offsetY}px ${blurRadius}px ${spreadRadius}px rgba(${colorRgb}, ${colorOpacity / 100})`; btnElement.style.setProperty('--button-hover-shadow', btnHoverShadowValue); const duration = formObj.form_btn_hover_shadow_duration || 0.3; btnElement.style.setProperty('--button-hover-shadow-duration', `${duration}s`); } /** * create error box * * @param {string} recId - id of the record * @param {formObj} formObj - obj * @param {'bottom' | 'middle'} direction * @returns {HTMLElement} */ function t_zeroForms__createErrorBox(recId, formObj, direction) { // В Zero редакторе нет способа вызвать ошибку, так что мы отдаем заглушку и не подключаем стили if (window.tildamode === 'zero') { return document.createElement('div'); } var errorBox = document.createElement('div'); errorBox.classList.add('t-form__errorbox-' + direction); var wrapper = document.createElement('div'); wrapper.classList.add('js-errorbox-all'); wrapper.classList.add('t-form__errorbox-wrapper'); wrapper.style.display = 'none'; errorBox.insertAdjacentElement('beforeend', wrapper); var textWrapper = document.createElement('div'); textWrapper.classList.add('t-form__errorbox-text'); textWrapper.classList.add('t-text_xs'); textWrapper.classList.add('t-text'); var fields = ['all', 'req', 'email', 'name', 'phone', 'string']; fields.forEach(function (field) { var text = document.createElement('p'); text.classList.add('t-form__errorbox-item'); text.classList.add('js-rule-error'); text.classList.add('js-rule-error-' + field); if (field !== 'all' && field !== 'string') text.textContent = formObj['formerr' + field]; textWrapper.insertAdjacentElement('beforeend', text); }); wrapper.insertAdjacentElement('beforeend', textWrapper); var errorBoxCloseBtn = document.createElement('div'); errorBoxCloseBtn.classList.add('tn-form__errorbox-close'); errorBoxCloseBtn.classList.add('js-errorbox-close'); errorBoxCloseBtn.insertAdjacentElement('beforeend', t_zeroForms__createErrorBoxBtn('left')); errorBoxCloseBtn.insertAdjacentElement('beforeend', t_zeroForms__createErrorBoxBtn('right')); wrapper.insertAdjacentElement('beforeend', errorBoxCloseBtn); document.removeEventListener('click', t_zeroForms__initErrorBoxClose); document.addEventListener('click', t_zeroForms__initErrorBoxClose); t_zeroForms__addResource({ recId, id: 't-zero-form-errorbox-styles', path: 'tilda-zero-form-errorbox.min.css', type: 'link', }); return errorBox; } /** * @param {'left' | 'right'} position * @returns {HTMLDivElement} */ function t_zeroForms__createErrorBoxBtn(position) { var errorBoxEl = document.createElement('div'); errorBoxEl.classList.add('tn-form__errorbox-close-line'); errorBoxEl.classList.add('tn-form__errorbox-close-line-' + position); return errorBoxEl; } /** * * @param {string} formID - current formID * @param {formObj} formObj - object with params * @param {string} recid - record ID * @param {HTMLElement} zeroForm * @param {string} formBottomText * @returns {HTMLElement} - bottom text as HTMLElement */ function t_zeroForms__getBottomText(formID, formObj, recid, zeroForm, formBottomText) { var checkboxList = ['cb', 'cbx']; var isCheckbox = checkboxList.some(function (cb) { return formObj.formbottomcb === cb; }); if (!isCheckbox) { var span = document.createElement('span'); span.innerHTML = formBottomText; return span; } else { var label = t_zeroForms__createLabel('checkbox', '', false); label.classList.add('t-text'); label.classList.add('t-text_xxs'); if (formObj.inputtitlecolor) label.style.color = formObj.inputtitlecolor; var input = document.createElement('input'); var inputPreferences = { name: 'form_bottom_checkbox' }; t_zeroForms__appendMainSettingToField(input, inputPreferences, 'checkbox', 't-checkbox'); input.setAttribute('data-tilda-req', '1'); if (formObj.formbottomcb === 'cbx') input.checked = true; label.insertAdjacentElement('beforeend', input); var indicator = t_zeroForms__createIndicator('checkbox', formObj.inputelscolor, { size: formObj.togglesize, borderSize: formObj.togglebordersize, checkboxBorderRadius: formObj.checkboxborderradius, }); indicator.style.width = '15px'; indicator.style.height = '15px'; indicator.style.marginRight = '5px'; label.insertAdjacentElement('beforeend', indicator); var labelText = document.createElement('span'); labelText.classList.add('t-checkbox__labeltext'); labelText.innerHTML = formBottomText; label.insertAdjacentElement('beforeend', labelText); var selector = t_zeroForms__createSelector(recid, formID, '.t-form__bottom-text .t-checkbox__indicator:after'); var styles = formObj.inputelscolor ? 'color: ' + formObj.inputelscolor + ';' : ''; styles += 'left:3px;top:0;height:6px;'; t_zeroForms__addInlineTag({ tag: 'style', id: 't-zero-form-btn-styles-' + formID, content: selector + '{' + styles + '}', zeroForm, }); return label; } } /** * animate inputs * * @param {HTMLElement} zeroForm - current form element * @param {formObj} formObj - object with params * @param {string} recid - record ID * @param {string} formID - form ID */ function t_zeroForms__animateInputs(zeroForm, formObj, recid, formID) { var mainSelector = t_zeroForms__createSelector(recid, formID, ''); if (formObj.inputcolor) { var selectors = [ '.t-input-group:not(.t-input-group_da):not(.t-input-group_ph):not(.t-input-group_uw):not(.t-input-group_ri):not(.t-input-group_cb):not(.t-input-group_rg) .t-input', '.t-datepicker__wrapper', '.t-input__vis-ph', ]; var styles = selectors.map(selector => `${mainSelector} ${selector}`).join(', '); styles += `{ color: ${formObj.inputcolor}; }`; t_zeroForms__addInlineTag({ tag: 'style', id: 't-zero-form-anim-styles-' + recid + '-' + formID, content: styles, zeroForm, }); } var topOffset = (Number(formObj.inputheight) - Number(formObj.inputfontsize)) / 2; var fontWeight = formObj.inputfontweight === 'variation' ? formObj.inputvariationweight : formObj.inputfontweight; var selector = mainSelector + '.t-input:not(.t-inputquantity):not(.t-input-phonemask__wrap):not(.t-input-phonemask):not(.t-input__own-answer)'; var inputList = Array.prototype.slice.call(document.querySelectorAll(selector)); inputList.forEach(function (input) { input.classList.add('t-input_pvis'); input.addEventListener('blur', function (e) { if (e.target.getAttribute('data-tilda-mask-init') === '1') { // setTimeout is need for correctly clear input value, after end of focus setTimeout(function () { e.target.value ? e.target.classList.add('t-input_has-content') : e.target.classList.remove('t-input_has-content'); }); } else { e.target.value ? e.target.classList.add('t-input_has-content') : e.target.classList.remove('t-input_has-content'); } }); var placeholder = input.getAttribute('placeholder'); if (!placeholder) return; var animField = document.createElement('div'); animField.classList.add('t-input__vis-ph'); if (topOffset) animField.style.top = topOffset + 'px'; if (fontWeight) animField.style.fontWeight = fontWeight; if (formObj.inputfontsize) { animField.style.fontSize = formObj.inputfontsize + 'px'; // increase height for 1 px, to prevent cutting animField.style.height = parseInt(formObj.inputfontsize, 10) + 1 + 'px'; } // placeholder-атрибут — чистый текст, animField лишь его визуальная копия animField.textContent = placeholder; input.insertAdjacentElement('afterend', animField); input.removeAttribute('placeholder'); }); if (window.t_zeroForms__isiOS && window.t_zeroForms__iOSMajorVersion < 13) { //BBOnly - border-bottom only (input style: only border-bottom) var textareaNotBBOnly = zeroForm.querySelectorAll('textarea:not(.t-input_bbonly)'); var textareaBBOnly = zeroForm.querySelectorAll('textarea.t-input_bbonly'); Array.prototype.forEach.call(textareaNotBBOnly, function (textarea) { textarea.style.paddingLeft = '17px'; }); Array.prototype.forEach.call(textareaBBOnly, function (textarea) { textarea.style.textIndent = '-3px'; }); } } /* ============= support functions for help create elements ============= */ function t_zeroForms__appendAttributes(input, inputPreferences) { if (inputPreferences.secondaryClassName) input.classList.add(inputPreferences.secondaryClassName); if (inputPreferences.placeholder) input.placeholder = inputPreferences.placeholder; if (inputPreferences.require) input.setAttribute('data-tilda-req', '1'); } /** * set inputStyles params to input styles * * @param {HTMLInputElement | HTMLSelectElement} input * @param {Object} inputStyles */ function t_zeroForms__appendStylesToField(input, inputStyles) { if (!input.classList.contains('t-input-inline-styles')) input.classList.add('t-input-inline-styles'); for (var k in inputStyles) { input.style[k] = inputStyles[k]; } if (!input.classList.contains('t-input-phonemask__wrap')) return; var phoneMaskSelect = input.querySelector('.t-input-phonemask__select-code'); if (phoneMaskSelect) phoneMaskSelect.style.fontSize = inputStyles.fontSize; if (phoneMaskSelect) phoneMaskSelect.style.fontWeight = inputStyles.fontWeight; var phoneMaskInput = input.querySelector('.t-input-phonemask'); if (phoneMaskInput) phoneMaskInput.style.fontSize = inputStyles.fontSize; if (phoneMaskInput) phoneMaskInput.style.fontWeight = inputStyles.fontWeight; } /** * set styles for indicator inside checkbox, radio or img-select * * @param {string} recid - record ID * @param {string} formID - current form ID * @param {string} color - color for current style * @param {'checkbox' | 'radio' | 'img-select'} type * @param field */ function t_zeroForms__setIndicatorStyles(recid, formID, color, type, field) { if (!color || !field) return; var selector = '.t-' + type + '__indicator:after'; var currentStyle = type === 'checkbox' ? 'border-color' : 'background-color'; var styles = document.createElement('style'); var mainSelector = t_zeroForms__createSelector(recid, formID, selector); styles.textContent = mainSelector + '{' + currentStyle + ':' + color + ';}'; field.appendChild(styles); } /** * get input placeholder styles * * @param {string} formID - current form * @param {formObj} formObj * @param {string} recid - record ID * @param {HTMLElement} zeroForm * @returns {string} */ function t_zeroForms__createInputPlaceholderStyles(formID, formObj, recid, zeroForm) { var postfixList = [ '::-webkit-input-placeholder', '::-moz-placeholder', ':-moz-placeholder', ':-ms-input-placeholder', ]; var elements = ['input', 'textarea']; var selector = t_zeroForms__createSelector(recid, formID, ''); var styles = ''; elements.forEach(function (element) { postfixList.forEach(function (postfix) { styles += selector + element + postfix + '{color:' + formObj.inputcolor + ';opacity:0.5;}'; }); }); var stylesID = 't-zero-placeholder-' + recid + '-' + formID; t_zeroForms__addInlineTag({ tag: 'style', id: stylesID, content: styles, zeroForm }); } /** * Загружает tilda-ресурс по переданному пути. * onError вызывается, если ресурс не загрузился, в том числе когда его раньше добавила другая форма. * @param {{ recId: string, id: string, path: string, type: 'script' | 'link', onError?: () => void }} options */ function t_zeroForms__addResource(options) { const { id, path, type, recId, onError } = options || {}; const addedElement = document.getElementById(id); if (addedElement) { if (onError && addedElement.getAttribute('data-load-error') === 'true') { onError(); } else if (onError) { addedElement.addEventListener('error', onError); } return; } t_zeroForms__isInWhiteList(path); const allRecords = document.getElementById('allrecords'); const isExport = allRecords && allRecords.getAttribute('data-tilda-export') === 'yes'; const zeroFormScript = document.querySelector('script[src*="tilda-zero-forms"]'); const scriptSrc = zeroFormScript ? zeroFormScript.src : ''; let location = 'https://static.tildacdn.' + t_zeroForms__getRootZone(); if (!isExport && scriptSrc && scriptSrc.indexOf('https://') !== -1) { location = scriptSrc.split('/js/')[0]; } const element = document.createElement(type); element.id = id; if (type === 'script') { element.src = location + '/js/' + path; element.async = true; } else if (type === 'link') { element.href = location + '/css/' + path; element.rel = 'stylesheet'; } element.addEventListener('error', () => { t_zeroForms__onFuncLoad('t_fallback__reloadSRC', function () { t_fallback__reloadSRC(element); }); element.setAttribute('data-loaded', 'true'); element.setAttribute('data-load-error', 'true'); }); if (onError) element.addEventListener('error', onError); element.addEventListener('load', () => { element.setAttribute('data-loaded', 'true'); }); t_zeroForms__addResourceToQueue(recId, element); document.head.insertAdjacentElement('beforeend', element); } /** * Добавляет inline HTML элемент с переданным контентом. Используется для добавляения на страницу inline скрипта или стиля. * @param {{ id: string, content: string, zeroForm: HTMLElement | null, tag: 'script' | 'style' }} options */ function t_zeroForms__addInlineTag(options) { const { id, content, zeroForm, tag } = options || {}; if (document.getElementById(id)) return; if (!content) return; const element = document.createElement(tag); element.id = id; element.textContent = content; const appendParent = zeroForm ? zeroForm.querySelector('.tn-atom') : document.head; appendParent.insertAdjacentElement('beforeend', element); } /** * Проверяет, был ли добавлен указанный файл в зависимости zero-form для экспорта страницы. * При добавлении нового скрипта или стиля необходимо добавить его упоминание в tpl_zero_form_export.tpl, чтобы он подключался на экспортированных сайтах. * * Такой подход – ограничение, связанное с логикой работы сервиса для экспорта. Сервис экспорта проверяет только html и не выполняет скрипты. * Чтобы все файлы появлялись при экспорте, необходимо добавить их явное упоминание в html (tpl). * @param {string} path */ function t_zeroForms__isInWhiteList(path) { if (!path || !t_zeroForms__isTeam()) return; const isAllowed = [ 'tilda-zero-form-errorbox.min.css', 'tilda-zero-form-horizontal.min.css', 'tilda-phone-mask-1.1.min.js', 'tilda-date-picker-1.0.min.css', 'tilda-date-picker-1.0.min.js', 'tilda-calc-1.0.min.js', 'tilda-upwidget-1.1.min.js', 'uploadcare-3.x.full.min.js', 'uploadcare-3.x.min.js', 'tilda-range-1.0.min.js', 'tilda-range-1.0.min.css', 'tilda-img-select-1.0.min.js', 'tilda-img-select-1.0.min.css', 'tilda-conditional-form-1.0.min.js', 'tilda-contact-method-1.0.min.js', 'tilda-ratescale-1.0.min.js', 'tilda-step-form-1.1.min.js', ].includes(path); if (!isAllowed) { throw new Error( `${path} is not allowed. Make sure the file is included in form export dependencies and then add it to the white list.` ); } } /** * create label for checkboxes, radio or img-select * * @param {'checkbox' | 'radio' | 'img-select'} type * @param {Object} labelStyles * @param {formObj | false} formObj * @returns {HTMLLabelElement} */ function t_zeroForms__createLabel(type, labelStyles, formObj) { var label = document.createElement('label'); label.classList.add('t-' + type + '__control'); if (labelStyles && labelStyles.fontSize) label.style.fontSize = labelStyles.fontSize + 'px'; if (labelStyles) label.style.fontWeight = labelStyles.fontWeight; const labelColor = formObj && formObj.togglelabelcolor; if (labelColor) label.style.color = labelColor; const fontFamily = formObj && formObj.togglefontfamily; if (fontFamily) { label.style.fontFamily = fontFamily; if (!label.style.fontFamily) label.style.fontFamily = '"' + fontFamily + '"'; } const size = formObj.togglesize; if (size) { label.style.setProperty('--size', `${size}px`); } const borderSize = formObj.togglebordersize; if (borderSize) { label.style.setProperty('--border-width', `${borderSize}px`); } const checkboxBorderRadius = formObj.checkboxborderradius; if (type === 'checkbox' && checkboxBorderRadius) { label.style.setProperty('--border-radius', `${checkboxBorderRadius}px`); } return label; } /** * create indicator for radio, checkbox and img-select fields * * @param {'checkbox' | 'radio' | 'img-select'} type * @param {string | undefined | false} colorStyle * @param {{ratio: string, img: string, size: string, borderSize: string, checkboxBorderRadius: string} | false} options * @returns {HTMLDivElement} */ function t_zeroForms__createIndicator(type, colorStyle, options) { var indicator = document.createElement('div'); indicator.classList.add('t-' + type + '__indicator'); if (colorStyle) indicator.style.borderColor = colorStyle; if (type === 'img-select') { indicator.classList.add('t-bgimg'); indicator.classList.add(options.ratio); indicator.setAttribute('data-original', options.img); indicator.style.backgroundImage = options.img; } return indicator; } /** * create hidden input to contain checked checkboxes values * * @param {Object} inputPreferences * @param {HTMLDivElement} wrapper * @param {'img-select' | 'checkboxes'} type * @returns {HTMLInputElement} */ function t_zeroForms__createNameFieldForCheckbox(inputPreferences, wrapper, type) { var hiddenInput = document.createElement('input'); t_zeroForms__appendMainSettingToField(hiddenInput, inputPreferences, 'hidden', 't-' + type + '__hiddeninput'); hiddenInput.tabIndex = -1; if (inputPreferences.require) hiddenInput.setAttribute('data-tilda-req', '1'); return hiddenInput; } /** * create hidden input * * @param {string} value * @param {string} name * @param {string} fieldClass * @returns {HTMLInputElement} */ function t_zeroForms__createHiddenField(value, name, fieldClass) { var input = document.createElement('input'); input.type = 'hidden'; input.tabIndex = -1; if (value) input.value = value; if (name) input.name = name; if (fieldClass) input.classList.add(fieldClass); return input; } /** * create wrapper of input fields * * @param {string | Array} ListOfClasses * @returns {HTMLDivElement} */ function t_zeroForms__createWrapper(ListOfClasses) { var wrapper = document.createElement('div'); if (typeof ListOfClasses === 'string') { wrapper.classList.add(ListOfClasses); } else { ListOfClasses.forEach(function (className) { wrapper.classList.add(className); }); } return wrapper; } /** * set for input type, name, and className * * @param {HTMLInputElement | HTMLSelectElement} input * @param {Object} inputPreferences * @param {string} type * @param {Array | string} supportClassList */ function t_zeroForms__appendMainSettingToField(input, inputPreferences, type, supportClassList) { var inputTypes = { email: 'email', time: 'text', textarea: '', checkbox: 'checkbox', number: 'number', range: 'range', tel: 'tel', url: 'url', hidden: 'hidden', }; var inputType = inputTypes[type]; if (typeof inputType === 'undefined') inputType = 'text'; if (type && type !== 'select') input.type = inputType; input.name = inputPreferences.name || ''; if (!supportClassList) input.classList.add('t-input'); if (supportClassList) { if (typeof supportClassList === 'object') { supportClassList.forEach(function (className) { input.classList.add(className); }); } else if (typeof supportClassList === 'string') { input.classList.add(supportClassList); } } input.classList.add('js-tilda-rule'); } /** * create object with input styles, remove empty values and append px, if it necessary * @param {formObj} formObj * @param {string} inputFontWeight * @returns {{border: (string|string), backgroundColor: (string|string), * color: (string|string), borderRadius: (string|string), * fontSize: (string|string), fontWeight: string, height: (string|string)}} */ function t_zeroForms__initInputStyles(formObj, inputFontWeight) { var inputStyles = { color: formObj.inputcolor || '', // prettier-ignore border: formObj.inputbordersize ? formObj.inputbordersize + 'px solid ' + (formObj.inputbordercolor || '#000') : '', backgroundColor: formObj.inputbgcolor || 'transparent', borderRadius: formObj.inputradius || '', fontSize: formObj.inputfontsize || '', fontWeight: inputFontWeight || '', height: formObj.inputheight || '', }; var pxValues = ['fontSize', 'height', 'borderRadius']; for (var k in inputStyles) { if (!inputStyles[k]) { delete inputStyles[k]; } else { var isPxContains = pxValues.some(function (key) { return key === k.toString(); }); if (isPxContains) inputStyles[k] += 'px'; } } return inputStyles; } /** * set styles for title and subtitle * * @param {HTMLDivElement | HTMLLabelElement} textEl * @param titleStyles * @param {string} titleFontWeight */ function t_zeroForms__setTitleStyles(textEl, titleStyles, titleFontWeight) { var isTitle = textEl.classList.contains('t-input-title'); textEl.style.color = titleStyles.color || ''; textEl.style.fontFamily = titleStyles.fontFamily || ''; if (!textEl.style.fontFamily && titleStyles.fontFamily) { textEl.style.fontFamily = '"' + titleStyles.fontFamily + '"'; } textEl.style.paddingBottom = titleStyles.paddingBottom ? titleStyles.paddingBottom + 'px' : ''; if (isTitle) textEl.style.fontSize = titleStyles.fontSize ? titleStyles.fontSize + 'px' : ''; if (isTitle && titleFontWeight) textEl.style.fontWeight = titleFontWeight; } /* ============== support functions ============== */ /** * if zeroblock placed inside innactive tab, don't render it * * @param {HTMLElement} rec * @returns {boolean} */ function t_zeroForms__isRecordHidden(rec) { if (!rec) return false; if (rec.getAttribute('data-connect-with-tab') !== 'yes') return false; var classList = ['t397__off', 't395__off', 't400__off']; return classList.some(function (className) { return rec.classList.contains(className); }); } /** * if form placed outsize zeroblock (left/right), don't render it. * Don't necessary use form bottom pos, because non-render form will have 0px height. * * @param {HTMLElement} form * @returns {boolean} */ function t_zeroForms__isFormOutside(form) { var animationAttributes = ['data-animate-sbs-opts', 'data-animate-style']; var hasAnimation = animationAttributes.some(function (attribute) { return form.hasAttribute(attribute); }); var artBoard = form.closest('.t396__artboard'); if (!artBoard || hasAnimation) return false; var overflow = t396_ab__getFieldValue(artBoard, 'ovrflw'); var isOverflow = overflow === 'auto' || overflow === 'custom'; if (isOverflow) return false; var artBoardPos = artBoard.getBoundingClientRect(); var formPos = form.getBoundingClientRect(); var artBoardRightPos = artBoardPos.right + window.pageXOffset; if (formPos.right < 0 && artBoardRightPos > 0) return true; var overflowValue = artBoard ? artBoard.getAttribute('data-artboard-ovrflw') : false; var isOverflowNotHidden = overflowValue === 'auto' || overflowValue === 'visible'; if (isOverflowNotHidden) return false; var formScaleFactor = t396_zeroForms__getScaleFactor(form); var formLeftPos = t_zeroForms__setScaleFactor(formPos.left, formScaleFactor); var formTopPos = t_zeroForms__setScaleFactor(parseInt(form.style.top, 10), formScaleFactor) || 0; // если форма не сильно выше верхней границы артборда - не скрывать её if (formTopPos < 0 && formTopPos > -50) formTopPos = 0; var hasFixedAnimation = form.hasAttribute('data-animate-fix'); var hasParallax = form.getAttribute('data-animate-prx') === 'scroll'; var isVerticalTopOutside = formTopPos < 0 && !hasFixedAnimation && !hasParallax; var isVerticalBotttomOutside = artBoardPos.height > 0 && formTopPos > artBoardPos.height && !hasParallax; return isVerticalTopOutside || isVerticalBotttomOutside || formLeftPos > artBoardRightPos; } function t_zeroForms__setScaleFactor(value, scaleFactor) { if (window.shouldUseScaleFactor) return value * scaleFactor; return value; } function t_zeroForms__getFieldValue(element, attrName, prop) { if (!element || typeof window.tn === 'undefined') return; var artBoard = element.closest('.t396__artboard, .tn-artboard'); var abResObj = t_zeroForms__getResOpts(artBoard); var postfix = attrName === 'data-field' ? '-value' : ''; var desktopAttr = t_zeroForms__generateAttribute(attrName, prop, postfix, false); if (abResObj.res === abResObj.resMax) return element.getAttribute(desktopAttr); var responsiveAttr = t_zeroForms__generateAttribute(attrName, prop, postfix, abResObj.res); var currentValue = element.getAttribute(responsiveAttr); if (typeof currentValue === 'string') return currentValue; abResObj.breakpoints.forEach(function (breakpoint) { if (breakpoint <= abResObj.res || typeof currentValue === 'string') return; var curBreakpointAttr = t_zeroForms__generateAttribute(attrName, prop, postfix, breakpoint); currentValue = element.getAttribute(curBreakpointAttr); }); return typeof currentValue === 'string' ? currentValue : element.getAttribute(desktopAttr) || ''; } /** * get element, if in function provide jQuery el * * @param {jQuery | HTMLElement }el * @returns {HTMLElement} */ function t_zeroForms__getEl(el) { if (window.jQuery && el instanceof jQuery && el.length) return el.get(0); return el; } /** * * @param {'data-field' | 'data-artboard'} preffix * @param {string} value * @param {'-value' | ''} postfix * @param {Boolean | number} res * @return {string} */ function t_zeroForms__generateAttribute(preffix, value, postfix, res) { var attribute = preffix + '-' + value; if (res) attribute += '-res-' + res; attribute += postfix; return attribute; } /** * generate object with responsive options for three versions: * 1. recid && window.tn['ab' + recid] - for published sites with support custom breakpoints * 2. window.tn.screens - for zero-editor * 3. other - for published pages without custom breakpoints (tilda-zero-1.0.min.js version) * * window.tn.topResolution - property from zero-editor * * @param artBoard * @return {{res: number, resMax: number, breakpoints: number[]}} */ function t_zeroForms__getResOpts(artBoard) { var recid = t_zeroForms__getRecID(artBoard); if (recid && window.tn['ab' + recid]) { return { res: window.t396_detectResolution ? t396_detectResolution(recid) : window.tn['ab' + recid].curResolution, resMax: window.tn['ab' + recid].curResolution_max, breakpoints: window.tn['ab' + recid].screens.slice(0, -1), }; } else if (window.tn.screens) { return { res: window.tn.curResolution, resMax: window.tn.topResolution, breakpoints: window.tn.screens.slice(0, -1), }; } else { return { res: window.tn.curResolution, resMax: 1200, breakpoints: [320, 480, 640, 960] }; } } function t_zeroForms__getRecID(elem) { if (!elem) return ''; var artBoard = elem.closest('.t396__artboard, .tn-artboard'); return artBoard ? artBoard.getAttribute('data-artboard-recid') || artBoard.getAttribute('data-record-id') : ''; } function t_zeroForms__createSelector(recid, formID, selector) { var recIdSelector = window.tildamode === 'zero' ? '[data-record-id="' + recid + '"]' : '#rec' + recid; return recIdSelector + ' [data-elem-id="' + formID + '"] ' + selector; } /** * remove single and double quotes from string * * @param {string} str - current string * @returns {string} */ function t_zeroForms__removeStringQuotes(str) { return str ? str.replace(/"/g, '"').replace(/'/g, ''') : ''; } /** * transform parsed object with objects to array with objects to simplify work * * @param {Object | Array} object * @returns {Array} */ function t_zeroForms__fromObjToArray(object) { if (Array.isArray(object)) return object; var isSupportedObjValues = typeof Object.values !== 'undefined'; if (isSupportedObjValues) return Object.values(object); var arrayOfOptions = []; for (var k in object) { arrayOfOptions.push(object[k]); } return arrayOfOptions; } /** * support function to update hidden input value, * after trigger checkboxes */ function t_zeroForms__updateCheckboxesValues(e) { var inputWrapper = e.target.closest('[data-input-lid]'); var checkedCheckboxes = Array.prototype.slice.call(inputWrapper.querySelectorAll('.t-checkbox:checked')); var value = ''; checkedCheckboxes.forEach(function (checkbox) { if (value) value += '; '; value += checkbox.value; }); var hiddenInput = inputWrapper.querySelector('.t-checkboxes__hiddeninput'); if (hiddenInput) { hiddenInput.value = value; hiddenInput.dispatchEvent(new Event('change', { bubbles: true, cancelable: true })); } } /** * support function to update quanity count by click. * we should trigger input event to correct update calculation field * * @param e */ function t_zeroForms__initQuanityClickCount(e) { const quantityBtn = e.target.closest('.t-inputquantity__btn'); if (!quantityBtn) return; const currentParent = quantityBtn.closest('[data-input-lid]'); const currentInput = currentParent.querySelector('.t-inputquantity'); const isMinusBtn = quantityBtn.closest('.t-inputquantity__btn-minus'); const inputEvent = new Event('input', { bubbles: true, cancelable: true, }); const changeEvent = new Event('change', { bubbles: true, cancelable: true, }); if (isMinusBtn) { if (currentInput.value > 0) { currentInput.value = Number(currentInput.value) - 1; currentInput.dispatchEvent(inputEvent); currentInput.dispatchEvent(changeEvent); } } else if (currentInput.value >= 0) { currentInput.value = Number(currentInput.value) + 1; currentInput.dispatchEvent(inputEvent); currentInput.dispatchEvent(changeEvent); } } /** * support function to close errorbox * * @param e */ function t_zeroForms__initErrorBoxClose(e) { var closeBtn = e.target.closest('.js-errorbox-close'); if (closeBtn) closeBtn.parentElement.style.display = 'none'; } function t_zeroForms__onReady(func) { document.readyState !== 'loading' ? func() : document.addEventListener('DOMContentLoaded', func); } /** * run callback function after render zero-form * * @param {HTMLElement} form * @param {Boolean} modeChecked * @param {Function} callback */ function t_zeroForms__onRender(form, modeChecked, callback) { if ((window.tildamode === 'edit' || window.tildamode === 'zero') && modeChecked) return; t_zeroForms__onReady(function () { form.classList.contains('zero-form-rendered') ? callback() : form.addEventListener('render', callback); }); } /** * Вызывает callback после текущего рендера формы, когда сгенерированные поля уже находятся в DOM. Работает во всех режимах. * В отличие от t_zeroForms__onRender, не вызывает callback сразу, если форма уже была отрендерена: * при повторном рендере (например, в редакторе) callback вызвался бы до того, как новые поля попадут в DOM. * * @param {HTMLElement} form * @param {Function} callback */ function t_zeroForms__onNextRender(form, callback) { form.addEventListener('render', callback, { once: true }); } /** * get tildamode * * @returns {'edit' | 'preview'| 'published' | 'zero' | undefined} - void if attr in switch case cannot find current options */ function t_zeroForms__getTildaMode() { if (typeof window.tildamode !== 'undefined') { return window.tildamode; } var allRec = document.getElementById('allrecords'); if (allRec) { switch (allRec.getAttribute('data-tilda-mode')) { case 'edit': window.tildamode = 'edit'; break; case 'preview': window.tildamode = 'preview'; break; default: window.tildamode = 'published'; break; } } return window.tildamode; } /** * * @param recid * @param zeroForm * @returns {formObj} */ function t_zeroForms__createFormObj(recid, zeroForm) { let formObj = {}; // prettier-ignore const fields = [ 'version', 'inputpos', 'inputfontfamily', 'togglefontfamily', 'fieldfontfamily', 'inputfontsize', 'inputfontweight', 'inputvariationweight', 'inputcolor', 'inputbgcolor', 'inputbordercolor', 'inputbordersize', 'inputradius', 'inputheight', 'inputmargbottom', 'inputmargright', 'inputtitlefontsize', 'inputtitlefontweight', 'inputtitlevariationweight', 'inputtitlecolor', 'togglelabelcolor', 'inputelscolor', 'inputelsfontsize', 'inputelsfontweight', 'inputelsvariationweight', 'inputtitlemargbottom', 'inputsstyle', 'inputsstyle2', 'togglesize', 'togglebordersize', 'checkboxborderradius', 'inputaccentcolor', 'buttontitle', 'buttonalign', 'buttoncolor', 'buttonbgcolor', 'buttonbordercolor', 'buttonbordersize', 'buttonradius', 'buttonmargtop', 'buttonwidth', 'buttonwidthstretch', 'buttonheight', 'buttonshadowsize', 'buttonshadowopacity', 'buttonfontfamily', 'buttonfontsize', 'buttonfontweight', 'buttonvariationweight', 'buttonuppercase', 'buttonbgcolorhover', 'buttoncolorhover', 'buttonbordercolorhover', 'buttonshadowsizehover', 'buttonshadowopacityhover', 'buttonspeedhover', 'formmsgsuccess', 'formmsgurl', 'formerrreq', 'formerremail', 'formerrphone', 'formerrname', 'formbottomtext', 'formbottomcb', 'formname', 'receivers', 'buttonhovercolor', 'buttonhoverbgcolor', 'buttonhoverbordercolor', 'buttonhovershadowsize', 'form_btn_icon', 'form_btn_iconposition', 'form_btn_iconanimation', 'form_btn_iconsize', 'form_btn_iconmargin', 'form_btn_iconhover', 'form_btn_shadow_x', 'form_btn_shadow_y', 'form_btn_shadow_blur', 'form_btn_shadow_color', 'form_btn_shadow_opacity', 'form_btn_shadow_spread', 'form_btn_hover_shadow_x', 'form_btn_hover_shadow_y', 'form_btn_hover_shadow_blur', 'form_btn_hover_shadow_color', 'form_btn_hover_shadow_opacity', 'form_btn_hover_shadow_spread', 'form_btn_hover_shadow_duration', 'form_btn_shadows', 'form_btn_shadows_hover', 'form_btn_shadows_hover_speed', 'uploadbuttonbgcolor','uploadbuttontextcolor', 'uploadbuttonbordercolor', 'uploadbuttonbordersize', ]; fields.forEach(function (field) { formObj[field] = t_zeroForms__getFieldValue(zeroForm, 'data-field', field); }); // проверяем на новые блоки, где будет использовать двухколоночные радио-изображения (ri) в моб. версии formObj.shouldUseTwoColumnRadioImg = recid > 799505628; formObj = t_zeroForms__supportMigrations(formObj); return formObj; } /** * Функция необходима чтобы поддержать новые филды для старых версий формы(над которыми еще не была проведена миграция полей в zero-редакторе) */ function t_zeroForms__supportMigrations(formObj) { /** * Во второй версии формы для настроек лейбла у тогглов повились свои поля для шрифта и цвета * а также свои настройки цветов и бордера для аплоад кнопки (hover теперь у них нет) */ if (formObj.version < 2) { formObj.togglefontfamily = formObj.inputfontfamily; formObj.togglelabelcolor = formObj.inputtitlecolor; formObj.uploadbuttonbgcolor = formObj.buttonbgcolor; formObj.uploadbuttontextcolor = formObj.buttoncolor; formObj.uploadbuttonbordercolor = formObj.buttonbordercolor; formObj.uploadbuttonbordersize = formObj.buttonbordersize; // проставляем дефолтные значения при их отсутствии как раньше // если есть только одно из полей, то другому проставляем дефолтное значение if (formObj.buttonshadowsize || formObj.buttonshadowopacity) { formObj.form_btn_shadow_blur = formObj.buttonshadowsize || 10; formObj.form_btn_shadow_opacity = formObj.buttonshadowopacity || 30; } if (formObj.buttonhovershadowsize || formObj.buttonshadowopacity) { formObj.form_btn_hover_shadow_blur = formObj.buttonhovershadowsize || 10; formObj.form_btn_hover_shadow_opacity = formObj.buttonshadowopacity || 30; } } return formObj; } /** * we would use t_onFuncLoad, but this function doesn't work in zero-editor * * @param {string} funcName * @param {Function} okFunc */ function t_zeroForms__onFuncLoad(funcName, okFunc) { if (typeof window[funcName] === 'function') { okFunc(); } else { var startTime = Date.now(); var error = new Error(funcName + ' is undefined'); var callbackError = function () { throw error; }; setTimeout(function checkFuncExist() { var currentTime = Date.now(); if (typeof window[funcName] === 'function') { okFunc(); return; } if ( document.readyState === 'complete' && currentTime - startTime > 7000 && typeof window[funcName] !== 'function' ) { callbackError(); } setTimeout(checkFuncExist, 100); }); } } /** * Sets up classes and handles various cases for rendering a form in columns * * @param {Object} zeroForm */ function t_zeroForms__placeFormIntoColumns(zeroForm) { var formPosition = t_zeroForms__getFieldValue(zeroForm, 'data-field', 'inputpos'); if (formPosition === 'h') return; var formWrapper = zeroForm.querySelector('.t-form__inputsbox'); if (!formWrapper) return; var fields = zeroForm.querySelectorAll('.t-input-group_widthdef, .t-input-group_inrow'); if (fields.length === 0) return; formWrapper.classList.add('t-form__inputsbox_flex'); formWrapper.classList.add('t-form__inputsbox_inrow'); Array.prototype.forEach.call(fields, function (field) { var fieldsType = ['rd', 'ri', 'uc', 'ws', 'hd', 'fr', 'st']; if (field && field.classList.contains('t-input-group_inrow-withsibling')) { var nextField = field.nextElementSibling; var incorrectType = fieldsType.filter(function (type) { return nextField.classList.contains('t-input-group_' + type); }); if ( nextField && incorrectType.length === 0 && ((nextField.classList.contains('t-input-group_inrow') && !field.classList.contains('t-input-group_widthdef')) || (field.classList.contains('t-input-group_widthdef') && nextField.classList.contains('t-input-group') && !nextField.classList.contains('t-input-group_inrow'))) ) { // Если у поля включено объединение в один ряд и // задана ширина у него и соседнего, либо // ширина по умолчанию у него и соседнего nextField.classList.add('t-input-group_inonerow'); } else { field.classList.remove('t-input-group_inrow-withsibling'); field.classList.add('t-input-group_inrow-last'); return; } } else { // Если нет следующего поля для объединения в ряд field.classList.add('t-input-group_inrow-last'); } if ( nextField && field.classList.contains('t-input-group_widthdef') && field.classList.contains('t-input-group_inrow-withsibling') && nextField.classList.contains('t-input-group_inonerow') && !nextField.classList.contains('t-input-group_inrow') ) { // Если у поля ширина по умолчанию, включено объединение в один ряд // и следующее поле так же с шириной по умолчанию nextField.classList.add('t-input-group_widthdef'); if (!nextField.classList.contains('t-input-group_inrow-withsibling')) { // Если нет следующего поля для объединения в ряд nextField.classList.add('t-input-group_inrow-last'); } if (nextField.classList.contains('t-input-group_inrow')) { field.classList.add('t-input-group_inrow-last'); } } }); var allLastFieldsWithCertainWidth = zeroForm.querySelectorAll( '.t-input-group_inrow.t-input-group_inonerow.t-input-group_inrow-last' ); if (allLastFieldsWithCertainWidth.length > 0) { t_zeroForms__moveFieldToNextRow(allLastFieldsWithCertainWidth); } var allLastFieldsWithDefWidth = zeroForm.querySelectorAll('.t-input-group_widthdef.t-input-group_inrow-last'); if (allLastFieldsWithDefWidth.length > 0) { t_zeroForms__combineFieldsWithDefWidth(allLastFieldsWithDefWidth); } } /** * Adds margin-right to the last field in row if common width of fields in row > 100% * @param {Object} allLastFields */ function t_zeroForms__moveFieldToNextRow(allLastFields) { var rows = t_zeroForms__createArrWithAllRows(allLastFields, 't-input-group_inrow'); rows.forEach(function (row) { var isLongNextField = false; row.forEach(function (field) { if ( field.classList.contains('t-input-group_inrow-last') && field.nextElementSibling && !field.nextElementSibling.classList.contains('t-input-group_inonerow') ) { isLongNextField = true; } }); if (isLongNextField) return; // Считаем общую ширину всех полей в ряду var commonWidth = row.reduce(function (sum, field) { var fieldClasses = field.classList.value.split(' '); var widthClass = fieldClasses.filter(function (fieldClass) { return fieldClass.indexOf('t-input-group_width') !== -1; }); widthClass = widthClass[0]; var characterQuantity = 2; if (widthClass.indexOf('100') !== -1) { characterQuantity = 3; } var fieldWidth = Number(widthClass.substr(widthClass.length - 2, characterQuantity)); return sum + fieldWidth; }, 0); if (commonWidth <= 100) return; // Если ширина > 100, добавляем отступ к последнему полю, // чтобы следующее за ним короткое поле переносилось в следующий ряд row.forEach(function (field) { if (field.classList.contains('t-input-group_inrow-last')) { field.style.marginRight = 'calc(100% - (' + (commonWidth - 100) + '%)'; field.style.flex = '0 0 auto'; } }); }); } /** * Combine fields with default width into row * @param {Object} allLastFields */ function t_zeroForms__combineFieldsWithDefWidth(allLastFields) { var allRowsWithDefWidth = []; var rows = t_zeroForms__createArrWithAllRows(allLastFields, 't-input-group_widthdef'); rows.forEach(function (row) { var maxRowLength = 4; if (row.length > maxRowLength) { for (var i = 0; i < row.length; i += maxRowLength) { var newRow = row.slice(i, i + maxRowLength); allRowsWithDefWidth.push(newRow); } } else { allRowsWithDefWidth.push(row); } }); allRowsWithDefWidth.forEach(function (row) { var rowWidth = { 4: '25', 3: '33', 2: '50', }; var widthClass = 't-input-group_width' + (rowWidth[row.length] || '100'); row.forEach(function (field) { field.classList.add(widthClass); }); }); } /** * Creates array with every row in form * @param {Object} allLastFields * @param {String} certainClass * @returns {Array} */ function t_zeroForms__createArrWithAllRows(allLastFields, certainClass) { var allSequences = []; var oneSequence = []; // Создаём массив с подмассивами из всех последовательностей // с полями в одном ряду Array.prototype.forEach.call(allLastFields, function (field) { oneSequence.push(field); while ( field.previousElementSibling && field.previousElementSibling.classList.contains(certainClass) && !field.previousElementSibling.classList.contains('t-input-group_inrow-last') ) { field = field.previousElementSibling; oneSequence.push(field); } allSequences.push(oneSequence.reverse()); oneSequence = []; }); return allSequences; } /** * Set classes for fields in a row * @param {Object} inputPreferences * @param {HTMLElement} inputGroup */ function t_zeroForms__setFieldsRowClasses(inputPreferences, inputGroup) { var inputWidth = inputPreferences.inputWidth; if (typeof inputWidth != 'undefined') { inputGroup.classList.add('t-input-group_inrow'); var fieldWidthClass = { '1_4': 't-input-group_width25', '1_3': 't-input-group_width33', '1_2': 't-input-group_width50', 1: 't-input-group_width100', }; inputGroup.classList.add(fieldWidthClass[inputWidth]); } if (typeof inputPreferences.inputInRow !== 'undefined' && inputPreferences.inputInRow === 'y') { inputGroup.classList.add('t-input-group_inonerow'); inputGroup.classList.add('t-input-group_inrow-withsibling'); if (!inputPreferences.inputWidth) { inputGroup.classList.add('t-input-group_widthdef'); } } } /** * Set classes for radiobuttons in a row * @param {Object} inputPreferences * @param {HTMLElement} inputBlock */ function t_zeroForms__setRadioRowClasses(inputPreferences, inputBlock) { var radioPosition = inputPreferences.radioPosition; if (typeof radioPosition !== 'undefined' && radioPosition !== '' && radioPosition !== '1_1') { inputBlock.classList.add('t-input-block_rd-flex'); var radiobuttonsColClass = { hor: '', '1_4': 't-input-block_rd-width25', '1_3': 't-input-block_rd-width33', '1_2': 't-input-block_rd-width50', }; var certainClass = radiobuttonsColClass[radioPosition]; if (certainClass) inputBlock.classList.add(certainClass); } var radioPositionMobile = inputPreferences.radioPositionMobile; if ( typeof radioPositionMobile !== 'undefined' && radioPositionMobile === 'y' && (radioPosition === '1_2' || radioPosition === '1_3' || radioPosition === '1_4') ) { inputBlock.classList.add('t-input-block_rd-mobile-half'); } } function t_zeroForms__getRootZone() { const allrecords = document.getElementById('allrecords'); const rootZone = allrecords && allrecords.getAttribute('data-tilda-root-zone'); return rootZone || 'com'; } function t_zeroForms__isTeam() { const allRecords = document.getElementById('allrecords'); return allRecords && allRecords.getAttribute('data-tilda-te') === 'y'; } function t396_zeroForms__getScaleFactor(element) { if (!element) return 1; if (typeof element.scaleFactor !== 'undefined') return element.scaleFactor; var artboard = element.closest('.t396__artboard'); if (!artboard || !artboard.classList.contains('t396__artboard_scale')) return 1; var abID = artboard.getAttribute('data-artboard-recid'); var artboardScaleFactor = abID && window.tn['ab' + abID] && window.tn['ab' + abID].scaleFactor; return artboardScaleFactor || window.tn_scale_factor || 1; } /** * Помечает поля, которые используются в калькуляторе. Значения таких полей нужно предварительно обработать, * чтобы скрыть момент загрузки скрипта калькулятора. * @param {Array>} elements * @returns {Array>} */ function t396_zeroForms__markElementsUsedInCalculator(elements) { const calculators = elements.filter(element => element.li_type === 'fr'); if (calculators.length === 0) return elements; // prettier-ignore const fieldsUsedInCalculator = calculators .flatMap(calculatorData => t_zeroForms__getListOfFieldsInFormula(calculatorData.li_expr)) .filter(Boolean); return elements.map(element => { if (fieldsUsedInCalculator.includes(element.li_nm)) { element._usedInCalculator = true; } return element; }); } /** * @param {Record} elementObj * @param {string} value */ function t396_zeroForms__prepareCalcValue(elementObj, value) { if (!elementObj._usedInCalculator || !value) { const rawLabel = value || ''; return { label: rawLabel, labelText: t396__decodeHtmlText(rawLabel), calcValue: null }; } const [label, calcValue] = value.split('='); return { label, // label идёт в innerHTML, labelText — в input.value/option.value labelText: t396__decodeHtmlText(label), calcValue, }; } function t396_zeroForms__setCalcValue(input, value) { if (!value || !input) return; input.setAttribute('data-calc-value', value); } function t396_zeroForms__getDefaultOption(elementObj) { if (!elementObj) return null; if (['sb', 'ri', 'rd'].includes(elementObj.li_type)) { return elementObj.li_defselitem || null; } if (['cb'].includes(elementObj.li_type)) { return elementObj.li_checked || null; } if (['qn', 'rg'].includes(elementObj.li_type)) { return elementObj.li_value || null; } } function t396_zeroForms__getProjectId() { if (t_zeroForms__getTildaMode() === 'zero') { return window.projectid; } const allRecords = document.getElementById('allrecords'); const projectId = allRecords.getAttribute('data-tilda-project-id'); return projectId; } function t396_zeroForms__getUserRole() { if (t_zeroForms__getTildaMode() !== 'published') { let userStatus = 'basic'; if (window.$oplan === '99') { userStatus = 'team'; } else if (window.userrole) { userStatus = 'tester'; } return userStatus; } const allRecords = document.getElementById('allrecords'); if (!allRecords) return 'basic'; const isOwnerTester = allRecords.getAttribute('data-tilda-ts') === 'y'; const isOwnerTeam = allRecords.getAttribute('data-tilda-te') === 'y'; let userStatus = 'basic'; if (isOwnerTeam) { userStatus = 'team'; } else if (isOwnerTester) { userStatus = 'tester'; } return userStatus; } /** * Промис резолвится после того, как все ресурсы для блока так или иначе завершили загрузку. * @param {string} recId ID блока, чьи ресусурсы нужно дождаться */ async function t_zeroForms__waitForResources(recId) { await Promise.allSettled(window.t_zeroForms__resourcesQueue[recId] || []); } /** * Промис резолвится, когда форма приняла окончательный размер: загрузились стили и скрипты полей * и инициализировались поля, которым нужен сторонний скрипт (data-field-async, например, способ связи). * До этого размер формы может меняться, поэтому пересчитывать позицию и размер элемента нужно после. * @param {HTMLElement} zeroForm * @param {string} recId */ async function t_zeroForms__waitForFormReady(zeroForm, recId) { const MAX_WAITING_TIME = 5000; // Максимальное время ожидания инициализации поля await t_zeroForms__waitForResources(recId); const asyncFields = Array.from(zeroForm.querySelectorAll('[data-field-async="true"]')); const notReadyFields = asyncFields.filter(field => field.getAttribute('data-input-ready') !== 'true'); await Promise.all( notReadyFields.map( field => new Promise(resolve => { field.addEventListener('inputReady', resolve, { once: true }); setTimeout(resolve, MAX_WAITING_TIME); }) ) ); } /** * Добавляет нужный для блока ресурс в очередь ожидания. Сама очередь нужна, чтобы пересчитать позицию формы после стабилизации стилей. * Решает проблему, когда пересчет высоты формы вызывался до того, как в ней отрендерятся все поля. * @param {string} recId ID блока для которого загружается ресурс * @param {HTMLScriptElement | HTMLLinkElement} element */ function t_zeroForms__addResourceToQueue(recId, element) { const MAX_WAITING_TIME = 5000; // Максимальное время ожидания загрузки ресурса window.t_zeroForms__resourcesQueue[recId] = window.t_zeroForms__resourcesQueue[recId] || []; window.t_zeroForms__resourcesQueue[recId].push( new Promise((resolve, reject) => { if (element.getAttribute('data-loaded') === 'true') { resolve(element); return; } const timeout = setTimeout(() => { resolve(element); }, MAX_WAITING_TIME); element.addEventListener('load', () => { clearTimeout(timeout); resolve(element); }); element.addEventListener('error', error => { clearTimeout(timeout); reject(error); }); }) ); }