/** * В данном скрипте генерируется форма, которая в последствии добавляется в .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