diff --git a/.oxlintrc.json b/.oxlintrc.json index 50de46019c..45a24af0c1 100644 --- a/.oxlintrc.json +++ b/.oxlintrc.json @@ -29,14 +29,6 @@ "frm_admin_js": "readonly", "ajaxurl": "readonly" }, - "overrides": [ - { - "files": ["tests/js/*.test.mjs"], - "rules": { - "import/no-nodejs-modules": "off" - } - } - ], "rules": { // Turn off rules that conflict with your codebase patterns. "no-unused-vars": "off", @@ -192,7 +184,7 @@ "rules": { "import/no-nodejs-modules": [ "error", - { "allow": ["node:test", "node:assert/strict"] } + { "allow": ["node:test", "node:assert/strict", "node:fs", "node:vm", "node:module"] } ] } } diff --git a/css/_single_theme.css.php b/css/_single_theme.css.php index 4aa58e84fd..ccc0a74af2 100644 --- a/css/_single_theme.css.php +++ b/css/_single_theme.css.php @@ -5,6 +5,7 @@ $settings = FrmStylesHelper::get_settings_for_output( $style ); extract( $settings ); // phpcs:ignore WordPress.PHP.DontExtract +$style_class = $settings['style_class']; $is_loaded_via_ajax = $is_loaded_via_ajax ?? false; FrmStylesPreviewHelper::get_additional_preview_style( $settings, $is_loaded_via_ajax ); diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 602c84d96c..9e64f2be47 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -735,6 +735,25 @@ gap: 2%; } +.with_frm_style.frm_inline_top .frm_submit.frm_flex, +.with_frm_style .frm_submit.frm_flex.frm_inline_submit { + align-items: flex-start; + align-content: flex-start; + row-gap: 0; +} + +.with_frm_style.frm_inline_top .frm_submit.frm_flex::before, +.with_frm_style .frm_submit.frm_flex.frm_inline_submit::before { + flex-basis: 100%; + order: -2; +} + +/* formidable.js sets the offset when a theme restyles the labels and the spacer no longer matches them. It must outrank the margin in each style's spacer rule. */ +.frm_forms.with_frm_style.frm_inline_top .frm_fields_container .frm_submit::before, +.frm_forms.with_frm_style .frm_fields_container .frm_submit.frm_inline_submit::before { + margin-bottom: var(--frm-inline-submit-offset, 0); +} + .with_frm_style .frm_submit.frm_flex button.frm_button_submit ~ .frm_prev_page { order: -1; diff --git a/eslint.config.mjs b/eslint.config.mjs index f329079b7c..c2bacf42f4 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -445,7 +445,7 @@ export default [ }, }, { - files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs' ], + files: [ 'tests/js/style-live-preview.test.mjs', 'tests/js/paypalBootstrap.test.mjs', 'tests/js/inlineSubmitAlignment.test.mjs' ], rules: { // The harnesses execute only checked-in scripts. 'sonarjs/code-eval': 'off', diff --git a/js/formidable.js b/js/formidable.js index 1a41843c24..0afcdd86b2 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -2287,6 +2287,129 @@ function frmFrontFormJS() { } } + /** + * Line up inline submit buttons with the inputs in the same row, then keep them lined up. + * + * @since x.x + * + * @return {void} + */ + function initInlineSubmitAlignment() { + let frameRequested = false; + const scheduleAlignment = function() { + if ( frameRequested ) { + return; + } + frameRequested = true; + window.requestAnimationFrame( function() { + frameRequested = false; + alignInlineSubmitButtons(); + } ); + }; + + alignInlineSubmitButtons(); + window.addEventListener( 'load', scheduleAlignment ); + window.addEventListener( 'resize', scheduleAlignment ); + // Observe field sizes as well as the viewport, including forms revealed in popups. + const observed = new Set(); + const resizeObserver = new ResizeObserver( scheduleAlignment ); + const observeFields = () => { + for ( const element of observed ) { + if ( ! element.isConnected ) { + resizeObserver.unobserve( element ); + observed.delete( element ); + } + } + document.querySelectorAll( '.frm_inline_form .frm_fields_container > *' ).forEach( element => { + if ( ! observed.has( element ) ) { + observed.add( element ); + resizeObserver.observe( element ); + } + } ); + scheduleAlignment(); + }; + + observeFields(); + // AJAX validation and pagination replace nodes. Newly inserted forms need observers too. + const mutationObserver = new MutationObserver( observeFields ); + mutationObserver.observe( document.body, { childList: true, subtree: true } ); + + if ( document.fonts?.ready ) { + document.fonts.ready.then( scheduleAlignment ); + } + } + + /** + * The ::before spacer above an inline submit button copies the label size from the form style. + * A theme that restyles labels (for example `label { line-height: 1 }`) makes the real label + * taller or shorter than the spacer, so measure the difference and correct the spacer with it. + * + * @since x.x + * + * @return {void} + */ + function alignInlineSubmitButtons() { + document.querySelectorAll( '.with_frm_style.frm_inline_top .frm_fields_container > .frm_submit, .with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit' ).forEach( alignInlineSubmitButton ); + } + + /** + * @since x.x + * + * @param {HTMLElement} submitContainer The .frm_submit element. + * @return {void} + */ + function alignInlineSubmitButton( submitContainer ) { + submitContainer.style.removeProperty( '--frm-inline-submit-offset' ); + + const input = getInlineSubmitRowInput( submitContainer ); + + if ( ! input ) { + return; + } + + // Previous and Submit can wrap onto two rows in a narrow cell, so line up the top row. + const buttonTops = Array.from( submitContainer.children ) + .filter( child => child.matches( 'button, input[type="submit"], input[type="button"], .frm_prev_page' ) && child.getClientRects().length ) + .map( child => child.getBoundingClientRect().top ); + + if ( ! buttonTops.length ) { + return; + } + + const offset = Math.round( ( input.getBoundingClientRect().top - Math.min( ...buttonTops ) ) * 100 ) / 100; + + if ( Math.abs( offset ) >= 0.5 ) { + submitContainer.style.setProperty( '--frm-inline-submit-offset', `${ offset }px` ); + } + } + + /** + * Get the input closest to the submit button when it sits in the same row as the button. + * + * @since x.x + * + * @param {HTMLElement} submitContainer The .frm_submit element. + * @return {HTMLElement|null} The input, or null when the closest field is on another row. + */ + function getInlineSubmitRowInput( submitContainer ) { + const submitTop = submitContainer.getBoundingClientRect().top; + let sibling = submitContainer.previousElementSibling; + + while ( sibling ) { + if ( sibling.classList.contains( 'frm_form_field' ) && sibling.getClientRects().length ) { + const input = sibling.querySelector( 'input:not([type="hidden"]), select, textarea' ); + + if ( input && input.getClientRects().length ) { + // Fields wrap onto their own row on narrow screens, and then there is nothing to line up with. + return Math.abs( sibling.getBoundingClientRect().top - submitTop ) < 1 ? input : null; + } + } + sibling = sibling.previousElementSibling; + } + + return null; + } + function maybeShowNewTabFallbackMessage() { if ( ! window.frmShowNewTabFallback ) { return; @@ -2852,6 +2975,7 @@ function frmFrontFormJS() { documentOn( 'click', '.frm_error_link', focusFieldFromErrorLink ); initFloatingLabels(); + initInlineSubmitAlignment(); maybeShowNewTabFallbackMessage(); jQuery( document ).on( 'frmAfterAddRow', setCustomValidityMessage ); diff --git a/js/formidable.min.js b/js/formidable.min.js index cbdc39fb9a..c11c6c33a9 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -71,38 +71,43 @@ target!=this;target=target.parentNode)if(target.matches&&target.matches(selector input;container.classList.toggle(floatClass,shouldFloatTop);if("SELECT"===input.tagName){const firstOpt=input.querySelector("option:first-child");if(shouldFloatTop){if(firstOpt.hasAttribute("data-label")){firstOpt.textContent=firstOpt.getAttribute("data-label");firstOpt.removeAttribute("data-label")}}else if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}}};const checkDropdownLabel=function(){document.querySelectorAll(`.frm-show-form .frm_inside_container:not(.${floatClass}) select`).forEach(function(input){const firstOpt= input.querySelector("option:first-child");if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}})};["focus","blur","change"].forEach(function(eventName){documentOn(eventName,selector,function(event){checkFloatLabel(event.target)},true)});const runOnLoad=function(firstLoad){if(firstLoad&&document.activeElement&&["INPUT","SELECT","TEXTAREA"].includes(document.activeElement.tagName))checkFloatLabel(document.activeElement);else if(firstLoad)document.querySelectorAll(".frm_inside_container").forEach(function(container){const input= container.querySelector("input, select, textarea");if(input&&""!==input.value)checkFloatLabel(input)});checkDropdownLabel();calcProductsTotal()};runOnLoad(true);jQuery(document).on("frmPageChanged",function(event){runOnLoad()});document.addEventListener("frm_after_start_over",function(event){runOnLoad()})}function shouldUpdateValidityMessage(target){if("INPUT"!==target.nodeName)return false;if(!target.dataset.invmsg)return false;if("text"!==target.getAttribute("type"))return false;if(target.classList.contains("frm_verify"))return false; -return true}function maybeClearCustomValidityMessage(event,field){let key;let isInvalid=false;if(!shouldUpdateValidityMessage(field))return;for(key in field.validity){if("customError"===key)continue;if("valid"!==key&&field.validity[key]===true){isInvalid=true;break}}if(!isInvalid)field.setCustomValidity("")}function maybeShowNewTabFallbackMessage(){if(!window.frmShowNewTabFallback)return;const messageEl=document.querySelector(`#frm_form_${frmShowNewTabFallback.formId}_container .frm_message`);if(!messageEl)return; -messageEl.insertAdjacentHTML("beforeend",` ${frmShowNewTabFallback.message}`)}function setCustomValidityMessage(){const forms=document.getElementsByClassName("frm-show-form");const {length}=forms;for(let index=0;indexb.toString(16).padStart(2,"0")).join("");const timestamp=Date.now().toString(16);return`${uniqueKey}-${timestamp}`}function animateScroll(start,end,duration){if(!window.hasOwnProperty("performance")||!window.hasOwnProperty("requestAnimationFrame")){document.documentElement.scrollTop= -end;return}const startTime=performance.now();const step=currentTime=>{const progress=Math.min((currentTime-startTime)/duration,1);document.documentElement.scrollTop=start+(end-start)*progress;if(progress<1)requestAnimationFrame(step)};requestAnimationFrame(step)}function maybeFixCaptchaLabel(captcha){const form=captcha.closest("form");if(!form)return;const label=form.querySelector('label[for="g-recaptcha-response"], label[for="cf-turnstile-response"]');const captchaResponse=form.querySelector('[name="g-recaptcha-response"], [name="cf-turnstile-response"]'); -if(label&&captchaResponse)label.htmlFor=captchaResponse.id}function checkQuantityFieldMinMax(input){if(""===input.value)return 0;const val=parseFloat(input.value?input.value.trim():0);if(isNaN(val))return 0;let max=input.hasAttribute("max")?parseFloat(input.getAttribute("max")):0;let min=input.hasAttribute("min")?parseFloat(input.getAttribute("min")):0;max=isNaN(max)?0:max;min=isNaN(min)?0:Math.max(0,min);if(valmax){input.value=max;return max}return val} -function triggerChange(input,fieldKey){if(fieldKey===undefined)fieldKey="dependent";jQuery(input).trigger({type:"change",selfTriggered:true,frmTriggered:fieldKey})}function calcProductsTotal(e){if("object"===typeof frmProForm)return;if(typeof __FRMCURR==="undefined")return;const totalFields=document.querySelectorAll("[data-frmtotal]");if(!totalFields.length)return;const formTotals=[];totalFields.forEach(totalField=>{let total=0;const form=totalField.closest("form");if(!form)return;const formId=form.querySelector('input[name="form_id"]').value; -const currency=getCurrency(formId);if(undefined!==formTotals[formId])total=formTotals[formId];else{form.querySelectorAll("input[data-frmprice],select:has([data-frmprice])").forEach(function(input){let quantity=0;let price=0;const isSingle="hidden"===input.type;if(input.tagName==="SELECT"){if(input.selectedIndex!==-1)price=input.options[input.selectedIndex].getAttribute("data-frmprice")}else{if(!isSingle&&!input.matches(":checked"))return;price=input.getAttribute("data-frmprice")}if(!price)price=0; -else{price=preparePrice(price,currency);quantity=getQuantity(input);price=parseFloat(quantity)*parseFloat(price)}if("true"===input.getAttribute("data-frmdiscount"))price=price*-1;total+=price});formTotals[formId]=total}total=isNaN(total)?0:total;currency.decimal_separator=currency.decimal_separator.trim();if(!currency.decimal_separator.length)currency.decimal_separator=".";totalField.value=roundTotal(total,currency);total=normalizeTotal(total,currency);triggerChange(totalField);total=formatCurrency(total, -currency);const formatted=totalField.previousElementSibling;if(formatted?.matches(".frm_total_formatted")){formatted.innerHTML=total;return}const formattedEls=totalField.closest(".frm_form_field").querySelectorAll(".frm_total_formatted");formattedEls.forEach(formattedEl=>{formattedEl.innerHTML=total})})}function normalizeTotal(total,currency){const isLargeTotal=total>Number.MAX_SAFE_INTEGER;total=roundTotal(total,currency);return maybeAddTrailingZeroToPrice(total,currency,isLargeTotal)}function roundTotal(total, -currency){const isLargeTotal=total>Number.MAX_SAFE_INTEGER;if(!isLargeTotal){const {decimals}=currency;total=decimals>0?round10(total,decimals):Math.ceil(total)}return total}function round10(value,decimals){return Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`)}function formatCurrency(total,currency){total=maybeAddTrailingZeroToPrice(total,currency);if(total.length&&(total[total.length-1]==="."||total[total.length-1]===currency.decimal_separator))total=total.substr(0,total.length-1); -total=maybeRemoveTrailingZerosFromPrice(total,currency);total=addThousands(total,currency);const leftSymbol=currency.symbol_left?currency.symbol_left+currency.symbol_padding:"";const rightSymbol=currency.symbol_right?currency.symbol_padding+currency.symbol_right:"";return`${leftSymbol}${total}${rightSymbol}`}function getCurrency(formId){if(undefined!==window.__FRMCURR&&undefined!==window.__FRMCURR[formId])return window.__FRMCURR[formId];return{symbol_left:"$",symbol_right:"",symbol_padding:"",thousand_separator:",", -decimal_separator:".",decimals:2}}function getQuantity(field){const fieldID=frmFrontForm.getFieldId(field,false);if(!fieldID)return 0;const quantityField=getQuantityField(field,fieldID);if(!quantityField)return 1;return checkQuantityFieldMinMax(quantityField)}function getQuantityField(element,fieldID){const quantityFields=element.closest("form").querySelectorAll("[data-frmproduct]");if(!quantityFields.length)return null;fieldID=fieldID.toString();return Array.from(quantityFields).find(element=>{let ids; -ids=JSON.parse(element.getAttribute("data-frmproduct").trim());if(""===ids)return false;ids="string"===typeof ids?[ids]:ids;return ids.includes(fieldID)})}function preparePrice(price,currency){if(!price)return 0;price=`${price}`;const regex=getRegexForPrice(currency);const matches=price.match(regex);if(null===matches)return 0;price=matches.length?matches[matches.length-1]:0;price=price.trim();if(currency.decimal_separator==="."&&3===price.split(".").length&&price[0]===".")price=price.substr(1);if(price){price= -maybeUseDecimal(price,currency);price=price.split(currency.thousand_separator).join("").replace(currency.decimal_separator,".")}return price}function getRegexForPrice(currency){let regexString="[0-9,.";if(currency.thousand_separator!=="."&¤cy.thousand_separator!==",")regexString+=currency.thousand_separator;if(currency.decimal_separator!=="."&¤cy.decimal_separator!==",")regexString+=currency.decimal_separator;regexString+="]*\\.?\\,?[0-9]+";return new RegExp(regexString,"g")}function maybeUseDecimal(price, -currency){let usedForDecimal;let priceParts;if("."===currency.thousand_separator){priceParts=price.split(".");usedForDecimal=2===priceParts.length&&2===priceParts[1].length;if(usedForDecimal)price=price.replace(".",currency.decimal_separator)}return price}function maybeAddTrailingZeroToPrice(price,currency,force=false){if("number"!==typeof price&&!force)return price;price=String(price);const pos=price.indexOf(".");if(pos===-1){price=`${price}.`;for(let n=0;n -!!input.value).length;if(hasFileFields<1){const actionInput=object.querySelector('input[name="frm_action"]');const action=actionInput?actionInput.value:"";frmFrontForm.checkFormErrors(object,action)}else object.submit()}else object.submit()},validateFormSubmit(object){const form=object instanceof jQuery?object.get(0):object;if(typeof tinyMCE!=="undefined"&&form?.querySelector(".wp-editor-wrap"))tinyMCE.triggerSave();jsErrors=[];if(shouldJSValidate(object)){frmFrontForm.getAjaxFormErrors(object);if(Object.keys(jsErrors).length)frmFrontForm.addAjaxFormErrors(object)}return jsErrors}, -getAjaxFormErrors(object){let customErrors;let key;const form=object instanceof jQuery?object.get(0):object;jsErrors=validateForm(object);if(typeof frmThemeOverride_jsErrors==="function"){const actionInput=form?form.querySelector('input[name="frm_action"]'):null;const action=actionInput?actionInput.value:"";customErrors=frmThemeOverride_jsErrors(action,object);if(Object.keys(customErrors).length)for(key in customErrors)jsErrors[key]=customErrors[key]}triggerCustomEvent(document,"frm_get_ajax_form_errors", -{formEl:object,errors:jsErrors});return jsErrors},addAjaxFormErrors(object){let key;const form=object instanceof jQuery?object.get(0):object;removeAllErrors();for(key in jsErrors){const fieldCont=form?getFieldContainerForErrorKey(form,key):null;if(fieldCont)addFieldError(fieldCont,key,jsErrors);else delete jsErrors[key]}scrollToFirstField(object);checkForErrorsAndMaybeSetFocus()},checkFormErrors:getFormErrors,checkRequiredField,showSubmitLoading,removeSubmitLoading,scrollToID(id){const object=jQuery(document.getElementById(id)); -frmFrontForm.scrollMsg(object,false)},scrollMsg(id,object,animate){let newPos;let screenTop;let screenBottom;let scrollObj="";if(object===undefined){scrollObj=jQuery(document.getElementById(`frm_form_${id}_container`));if(scrollObj.length<1)return}else if(typeof id==="string"){const formEl=object instanceof jQuery?object.get(0):object;const fieldEl=formEl?formEl.querySelector(`#frm_field_${id}_container`):null;scrollObj=fieldEl?jQuery(fieldEl):jQuery()}else scrollObj=id;const scrollElement=scrollObj instanceof -jQuery?scrollObj.get(0):scrollObj;if(!scrollElement?.hasAttribute("data-frm-error-summary")||getErrorConfigForForm(scrollElement.closest(".frm-show-form")).focusErrorSummary)jQuery(scrollObj).trigger("focus");newPos=scrollObj.offset().top;if(!newPos||frm_js.offset==="-1")return;newPos=newPos-frm_js.offset;const docMarginTop=getComputedStyle(document.documentElement).marginTop;const bodyMarginTop=getComputedStyle(document.body).marginTop;if(docMarginTop||bodyMarginTop)newPos=newPos-parseInt(docMarginTop)- -parseInt(bodyMarginTop);if(newPos&&window.innerHeight){screenTop=document.documentElement.scrollTop||document.body.scrollTop;screenBottom=screenTop+window.innerHeight;if(newPos>screenBottom||newPos/g,">").replace(/"/g,""").replace(/'/g,"'")},triggerCustomEvent,documentOn}}window.frmFrontForm=frmFrontFormJS();jQuery(document).ready(function(){frmFrontForm.init()});function frmRecaptcha(){frmCaptcha(".frm-g-recaptcha")} -function frmHcaptcha(){frmCaptcha(".h-captcha")}function frmTurnstile(){frmCaptcha(".frm-cf-turnstile")} +return true}function maybeClearCustomValidityMessage(event,field){let key;let isInvalid=false;if(!shouldUpdateValidityMessage(field))return;for(key in field.validity){if("customError"===key)continue;if("valid"!==key&&field.validity[key]===true){isInvalid=true;break}}if(!isInvalid)field.setCustomValidity("")}function initInlineSubmitAlignment(){let frameRequested=false;const scheduleAlignment=function(){if(frameRequested)return;frameRequested=true;window.requestAnimationFrame(function(){frameRequested= +false;alignInlineSubmitButtons()})};alignInlineSubmitButtons();window.addEventListener("load",scheduleAlignment);window.addEventListener("resize",scheduleAlignment);const observed=new Set;const resizeObserver=new ResizeObserver(scheduleAlignment);const observeFields=()=>{for(const element of observed)if(!element.isConnected){resizeObserver.unobserve(element);observed.delete(element)}document.querySelectorAll(".frm_inline_form .frm_fields_container > *").forEach(element=>{if(!observed.has(element)){observed.add(element); +resizeObserver.observe(element)}});scheduleAlignment()};observeFields();const mutationObserver=new MutationObserver(observeFields);mutationObserver.observe(document.body,{childList:true,subtree:true});if(document.fonts?.ready)document.fonts.ready.then(scheduleAlignment)}function alignInlineSubmitButtons(){document.querySelectorAll(".with_frm_style.frm_inline_top .frm_fields_container > .frm_submit, .with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit").forEach(alignInlineSubmitButton)} +function alignInlineSubmitButton(submitContainer){submitContainer.style.removeProperty("--frm-inline-submit-offset");const input=getInlineSubmitRowInput(submitContainer);if(!input)return;const buttonTops=Array.from(submitContainer.children).filter(child=>child.matches('button, input[type="submit"], input[type="button"], .frm_prev_page')&&child.getClientRects().length).map(child=>child.getBoundingClientRect().top);if(!buttonTops.length)return;const offset=Math.round((input.getBoundingClientRect().top- +Math.min(...buttonTops))*100)/100;if(Math.abs(offset)>=.5)submitContainer.style.setProperty("--frm-inline-submit-offset",`${offset}px`)}function getInlineSubmitRowInput(submitContainer){const submitTop=submitContainer.getBoundingClientRect().top;let sibling=submitContainer.previousElementSibling;while(sibling){if(sibling.classList.contains("frm_form_field")&&sibling.getClientRects().length){const input=sibling.querySelector('input:not([type="hidden"]), select, textarea');if(input&&input.getClientRects().length)return Math.abs(sibling.getBoundingClientRect().top- +submitTop)<1?input:null}sibling=sibling.previousElementSibling}return null}function maybeShowNewTabFallbackMessage(){if(!window.frmShowNewTabFallback)return;const messageEl=document.querySelector(`#frm_form_${frmShowNewTabFallback.formId}_container .frm_message`);if(!messageEl)return;messageEl.insertAdjacentHTML("beforeend",` ${frmShowNewTabFallback.message}`)}function setCustomValidityMessage(){const forms=document.getElementsByClassName("frm-show-form");const {length}=forms;for(let index=0;index< +length;++index)forms[index].addEventListener("invalid",function(event){const {target}=event;if(shouldUpdateValidityMessage(target))target.setCustomValidity(target.dataset.invmsg)},true)}function enableSubmitButtonOnBackButtonPress(){window.addEventListener("pageshow",function(event){if(event.persisted){document.querySelectorAll(".frm_loading_form").forEach(function(form){enableSubmitButton(form)});removeSubmitLoading()}})}function destroyhCaptcha(){if(!window.hasOwnProperty("hcaptcha")||!document.querySelector(".frm-show-form .h-captcha"))return; +window.hcaptcha=null}function getUniqueKey(){const uniqueKey=Array.from(window.crypto.getRandomValues(new Uint8Array(8))).map(b=>b.toString(16).padStart(2,"0")).join("");const timestamp=Date.now().toString(16);return`${uniqueKey}-${timestamp}`}function animateScroll(start,end,duration){if(!window.hasOwnProperty("performance")||!window.hasOwnProperty("requestAnimationFrame")){document.documentElement.scrollTop=end;return}const startTime=performance.now();const step=currentTime=>{const progress=Math.min((currentTime- +startTime)/duration,1);document.documentElement.scrollTop=start+(end-start)*progress;if(progress<1)requestAnimationFrame(step)};requestAnimationFrame(step)}function maybeFixCaptchaLabel(captcha){const form=captcha.closest("form");if(!form)return;const label=form.querySelector('label[for="g-recaptcha-response"], label[for="cf-turnstile-response"]');const captchaResponse=form.querySelector('[name="g-recaptcha-response"], [name="cf-turnstile-response"]');if(label&&captchaResponse)label.htmlFor=captchaResponse.id} +function checkQuantityFieldMinMax(input){if(""===input.value)return 0;const val=parseFloat(input.value?input.value.trim():0);if(isNaN(val))return 0;let max=input.hasAttribute("max")?parseFloat(input.getAttribute("max")):0;let min=input.hasAttribute("min")?parseFloat(input.getAttribute("min")):0;max=isNaN(max)?0:max;min=isNaN(min)?0:Math.max(0,min);if(valmax){input.value=max;return max}return val}function triggerChange(input,fieldKey){if(fieldKey=== +undefined)fieldKey="dependent";jQuery(input).trigger({type:"change",selfTriggered:true,frmTriggered:fieldKey})}function calcProductsTotal(e){if("object"===typeof frmProForm)return;if(typeof __FRMCURR==="undefined")return;const totalFields=document.querySelectorAll("[data-frmtotal]");if(!totalFields.length)return;const formTotals=[];totalFields.forEach(totalField=>{let total=0;const form=totalField.closest("form");if(!form)return;const formId=form.querySelector('input[name="form_id"]').value;const currency= +getCurrency(formId);if(undefined!==formTotals[formId])total=formTotals[formId];else{form.querySelectorAll("input[data-frmprice],select:has([data-frmprice])").forEach(function(input){let quantity=0;let price=0;const isSingle="hidden"===input.type;if(input.tagName==="SELECT"){if(input.selectedIndex!==-1)price=input.options[input.selectedIndex].getAttribute("data-frmprice")}else{if(!isSingle&&!input.matches(":checked"))return;price=input.getAttribute("data-frmprice")}if(!price)price=0;else{price=preparePrice(price, +currency);quantity=getQuantity(input);price=parseFloat(quantity)*parseFloat(price)}if("true"===input.getAttribute("data-frmdiscount"))price=price*-1;total+=price});formTotals[formId]=total}total=isNaN(total)?0:total;currency.decimal_separator=currency.decimal_separator.trim();if(!currency.decimal_separator.length)currency.decimal_separator=".";totalField.value=roundTotal(total,currency);total=normalizeTotal(total,currency);triggerChange(totalField);total=formatCurrency(total,currency);const formatted= +totalField.previousElementSibling;if(formatted?.matches(".frm_total_formatted")){formatted.innerHTML=total;return}const formattedEls=totalField.closest(".frm_form_field").querySelectorAll(".frm_total_formatted");formattedEls.forEach(formattedEl=>{formattedEl.innerHTML=total})})}function normalizeTotal(total,currency){const isLargeTotal=total>Number.MAX_SAFE_INTEGER;total=roundTotal(total,currency);return maybeAddTrailingZeroToPrice(total,currency,isLargeTotal)}function roundTotal(total,currency){const isLargeTotal= +total>Number.MAX_SAFE_INTEGER;if(!isLargeTotal){const {decimals}=currency;total=decimals>0?round10(total,decimals):Math.ceil(total)}return total}function round10(value,decimals){return Number(`${Math.round(`${value}e${decimals}`)}e-${decimals}`)}function formatCurrency(total,currency){total=maybeAddTrailingZeroToPrice(total,currency);if(total.length&&(total[total.length-1]==="."||total[total.length-1]===currency.decimal_separator))total=total.substr(0,total.length-1);total=maybeRemoveTrailingZerosFromPrice(total, +currency);total=addThousands(total,currency);const leftSymbol=currency.symbol_left?currency.symbol_left+currency.symbol_padding:"";const rightSymbol=currency.symbol_right?currency.symbol_padding+currency.symbol_right:"";return`${leftSymbol}${total}${rightSymbol}`}function getCurrency(formId){if(undefined!==window.__FRMCURR&&undefined!==window.__FRMCURR[formId])return window.__FRMCURR[formId];return{symbol_left:"$",symbol_right:"",symbol_padding:"",thousand_separator:",",decimal_separator:".",decimals:2}} +function getQuantity(field){const fieldID=frmFrontForm.getFieldId(field,false);if(!fieldID)return 0;const quantityField=getQuantityField(field,fieldID);if(!quantityField)return 1;return checkQuantityFieldMinMax(quantityField)}function getQuantityField(element,fieldID){const quantityFields=element.closest("form").querySelectorAll("[data-frmproduct]");if(!quantityFields.length)return null;fieldID=fieldID.toString();return Array.from(quantityFields).find(element=>{let ids;ids=JSON.parse(element.getAttribute("data-frmproduct").trim()); +if(""===ids)return false;ids="string"===typeof ids?[ids]:ids;return ids.includes(fieldID)})}function preparePrice(price,currency){if(!price)return 0;price=`${price}`;const regex=getRegexForPrice(currency);const matches=price.match(regex);if(null===matches)return 0;price=matches.length?matches[matches.length-1]:0;price=price.trim();if(currency.decimal_separator==="."&&3===price.split(".").length&&price[0]===".")price=price.substr(1);if(price){price=maybeUseDecimal(price,currency);price=price.split(currency.thousand_separator).join("").replace(currency.decimal_separator, +".")}return price}function getRegexForPrice(currency){let regexString="[0-9,.";if(currency.thousand_separator!=="."&¤cy.thousand_separator!==",")regexString+=currency.thousand_separator;if(currency.decimal_separator!=="."&¤cy.decimal_separator!==",")regexString+=currency.decimal_separator;regexString+="]*\\.?\\,?[0-9]+";return new RegExp(regexString,"g")}function maybeUseDecimal(price,currency){let usedForDecimal;let priceParts;if("."===currency.thousand_separator){priceParts=price.split("."); +usedForDecimal=2===priceParts.length&&2===priceParts[1].length;if(usedForDecimal)price=price.replace(".",currency.decimal_separator)}return price}function maybeAddTrailingZeroToPrice(price,currency,force=false){if("number"!==typeof price&&!force)return price;price=String(price);const pos=price.indexOf(".");if(pos===-1){price=`${price}.`;for(let n=0;n!!input.value).length;if(hasFileFields<1){const actionInput=object.querySelector('input[name="frm_action"]');const action=actionInput?actionInput.value:"";frmFrontForm.checkFormErrors(object,action)}else object.submit()}else object.submit()},validateFormSubmit(object){const form=object instanceof jQuery?object.get(0):object;if(typeof tinyMCE!== +"undefined"&&form?.querySelector(".wp-editor-wrap"))tinyMCE.triggerSave();jsErrors=[];if(shouldJSValidate(object)){frmFrontForm.getAjaxFormErrors(object);if(Object.keys(jsErrors).length)frmFrontForm.addAjaxFormErrors(object)}return jsErrors},getAjaxFormErrors(object){let customErrors;let key;const form=object instanceof jQuery?object.get(0):object;jsErrors=validateForm(object);if(typeof frmThemeOverride_jsErrors==="function"){const actionInput=form?form.querySelector('input[name="frm_action"]'):null; +const action=actionInput?actionInput.value:"";customErrors=frmThemeOverride_jsErrors(action,object);if(Object.keys(customErrors).length)for(key in customErrors)jsErrors[key]=customErrors[key]}triggerCustomEvent(document,"frm_get_ajax_form_errors",{formEl:object,errors:jsErrors});return jsErrors},addAjaxFormErrors(object){let key;const form=object instanceof jQuery?object.get(0):object;removeAllErrors();for(key in jsErrors){const fieldCont=form?getFieldContainerForErrorKey(form,key):null;if(fieldCont)addFieldError(fieldCont, +key,jsErrors);else delete jsErrors[key]}scrollToFirstField(object);checkForErrorsAndMaybeSetFocus()},checkFormErrors:getFormErrors,checkRequiredField,showSubmitLoading,removeSubmitLoading,scrollToID(id){const object=jQuery(document.getElementById(id));frmFrontForm.scrollMsg(object,false)},scrollMsg(id,object,animate){let newPos;let screenTop;let screenBottom;let scrollObj="";if(object===undefined){scrollObj=jQuery(document.getElementById(`frm_form_${id}_container`));if(scrollObj.length<1)return}else if(typeof id=== +"string"){const formEl=object instanceof jQuery?object.get(0):object;const fieldEl=formEl?formEl.querySelector(`#frm_field_${id}_container`):null;scrollObj=fieldEl?jQuery(fieldEl):jQuery()}else scrollObj=id;const scrollElement=scrollObj instanceof jQuery?scrollObj.get(0):scrollObj;if(!scrollElement?.hasAttribute("data-frm-error-summary")||getErrorConfigForForm(scrollElement.closest(".frm-show-form")).focusErrorSummary)jQuery(scrollObj).trigger("focus");newPos=scrollObj.offset().top;if(!newPos||frm_js.offset=== +"-1")return;newPos=newPos-frm_js.offset;const docMarginTop=getComputedStyle(document.documentElement).marginTop;const bodyMarginTop=getComputedStyle(document.body).marginTop;if(docMarginTop||bodyMarginTop)newPos=newPos-parseInt(docMarginTop)-parseInt(bodyMarginTop);if(newPos&&window.innerHeight){screenTop=document.documentElement.scrollTop||document.body.scrollTop;screenBottom=screenTop+window.innerHeight;if(newPos>screenBottom||newPos/g,">").replace(/"/g,""").replace(/'/g, +"'")},triggerCustomEvent,documentOn}}window.frmFrontForm=frmFrontFormJS();jQuery(document).ready(function(){frmFrontForm.init()});function frmRecaptcha(){frmCaptcha(".frm-g-recaptcha")}function frmHcaptcha(){frmCaptcha(".h-captcha")}function frmTurnstile(){frmCaptcha(".frm-cf-turnstile")} function frmCaptcha(captchaSelector){if(".h-captcha"===captchaSelector){const captchaLabels=document.querySelectorAll('label[for="h-captcha-response"]');if(captchaLabels.length)captchaLabels.forEach(label=>{const captchaResponse=label.closest("form")?.querySelector('[name="h-captcha-response"]');if(captchaResponse)label.htmlFor=captchaResponse.id});return}let c;const captchas=document.querySelectorAll(captchaSelector);const cl=captchas.length;for(c=0;c node.id?.name === 'frmFrontFormJS' ); +const names = [ 'initInlineSubmitAlignment', 'alignInlineSubmitButtons', 'alignInlineSubmitButton', 'getInlineSubmitRowInput' ]; +const functions = names.map( name => { + const declaration = frontend.body.body.find( node => node.id?.name === name ); + assert.ok( declaration, `${ name } must exist in the frontend` ); + return source.slice( declaration.start, declaration.end ); +} ).join( '\n' ); +const property = '--frm-inline-submit-offset'; + +/** + * Create independently measurable elements and load the production alignment functions. + * + * @return {Object} The elements, scheduling callbacks and production functions. + */ +function setup() { + const styles = new Map(); + const input = { getClientRects: () => [ {} ], getBoundingClientRect: () => ( { top: 128 } ) }; + const field = { + isConnected: true, + classList: { contains: () => true }, + getClientRects: () => [ {} ], + getBoundingClientRect: () => ( { top: 100, bottom: 250 } ), + querySelector: () => input, + previousElementSibling: null + }; + const button = { matches: () => true, getClientRects: () => [ {} ], getBoundingClientRect: () => ( { top: 132 } ) }; + const submit = { + isConnected: true, + style: { removeProperty: key => styles.delete( key ), setProperty: ( key, value ) => styles.set( key, value ) }, + getBoundingClientRect: () => ( { top: 100 } ), + children: [ button ], + previousElementSibling: field + }; + const frames = []; + const listeners = new Map(); + const observed = new Set(); + const state = { styles, input, field, button, submit, frames, listeners, observed, fields: [ field, submit ] }; + const document = { + body: {}, + querySelectorAll: selector => selector.includes( '> *' ) ? state.fields : [ submit ] + }; + const functionsToLoad = `${ functions }\n({ initInlineSubmitAlignment, alignInlineSubmitButton, getInlineSubmitRowInput })`; + Object.assign( state, runInNewContext( functionsToLoad, { + document, + window: { + requestAnimationFrame: callback => frames.push( callback ), + addEventListener: ( event, callback ) => listeners.set( event, callback ) + }, + ResizeObserver: class { + constructor( callback ) { + state.resize = callback; + } + observe( element ) { + observed.add( element ); + } + unobserve( element ) { + observed.delete( element ); + } + }, + MutationObserver: class { + constructor( callback ) { + state.mutate = callback; + } + observe() {} + } + } ) ); + return state; +} + +test( 'alignment follows the input instead of descriptions or validation errors', () => { + for ( const bottom of [ 164, 188, 250 ] ) { + const state = setup(); + state.field.getBoundingClientRect = () => ( { top: 100, bottom } ); + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.get( property ), '-4px' ); + } +} ); + +test( 'Previous and Submit align the first row when the buttons wrap', () => { + const state = setup(); + state.submit.children.unshift( { matches: () => true, getClientRects: () => [ {} ], getBoundingClientRect: () => ( { top: 168 } ) } ); + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.get( property ), '-4px' ); +} ); + +test( 'stacked fields clear a previous desktop offset', () => { + const state = setup(); + state.styles.set( property, '-4px' ); + state.submit.getBoundingClientRect = () => ( { top: 300 } ); + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.has( property ), false ); +} ); + +test( 'hidden fields are skipped when finding the closest input', () => { + const state = setup(); + state.submit.previousElementSibling = { ...state.field, getClientRects: () => [], previousElementSibling: state.field }; + assert.equal( state.getInlineSubmitRowInput( state.submit ), state.input ); +} ); + +test( 'hidden controls and empty submit areas do not keep stale offsets', () => { + const state = setup(); + state.input.getClientRects = () => []; + state.styles.set( property, '12px' ); + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.has( property ), false ); + state.input.getClientRects = () => [ {} ]; + state.submit.children = []; + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.has( property ), false ); +} ); + +test( 'resizing and DOM changes share a single animation frame', () => { + const state = setup(); + state.initInlineSubmitAlignment(); + state.listeners.get( 'resize' )(); + state.resize(); + state.mutate(); + assert.equal( state.frames.length, 1 ); + state.frames.shift()(); + assert.equal( state.styles.get( property ), '-4px' ); +} ); + +test( 'new forms are observed and detached fields are released after AJAX replacement', () => { + const state = setup(); + state.initInlineSubmitAlignment(); + assert.equal( state.observed.has( state.field ), true ); + const inserted = { isConnected: true }; + state.field.isConnected = false; + state.fields = [ inserted, state.submit ]; + state.mutate(); + assert.equal( state.observed.has( state.field ), false ); + assert.equal( state.observed.has( inserted ), true ); +} ); + +test( 'loading indicators do not move the buttons away from the input', () => { + const state = setup(); + state.submit.children.unshift( { matches: () => false, getClientRects: () => [ {} ], getBoundingClientRect: () => ( { top: 100 } ) } ); + state.alignInlineSubmitButton( state.submit ); + assert.equal( state.styles.get( property ), '-4px' ); +} ); diff --git a/tests/phpunit/styles/test_FrmStyle.php b/tests/phpunit/styles/test_FrmStyle.php index 70cd7e1935..06b7fb6018 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -316,6 +316,23 @@ public function test_get_all() { $this->assertSame( FrmStylesController::$post_type, reset( $styles )->post_type ); } + /** + * Inline buttons reserve a label row without aligning to descriptions or errors below inputs. + * + * @see https://github.com/Strategy11/formidable-pro/issues/6894 + */ + public function test_generated_css_aligns_inline_submit_with_inputs() { + $css = $this->run_private_method( + array( new FrmStyle(), 'get_css_content' ), + array( FrmAppHelper::plugin_path() . '/css/custom_theme.css.php' ) + ); + $submit_selector = '.with_frm_style.frm_inline_top .frm_submit.frm_flex,.with_frm_style .frm_submit.frm_flex.frm_inline_submit'; + + \PHPUnit\Framework\Assert::assertStringContainsString( $submit_selector . ' {align-items: flex-start;align-content: flex-start;row-gap: 0;}', $css ); + \PHPUnit\Framework\Assert::assertStringContainsString( 'flex-basis: 100%;order: -2;', $css ); + \PHPUnit\Framework\Assert::assertStringContainsString( 'margin-bottom: var(--frm-inline-submit-offset, 0);', $css ); + } + /** * The CSS version must be a zero-padded timestamp so distinct save times * never collide (e.g. 1 Jan 10:59 and 11 Jan 00:59 both produced "111059").