From df6754b0f560879db26f0a5ffc8024dcf31e7baf Mon Sep 17 00:00:00 2001 From: "vivi-the-going-merry[bot]" <308115520+vivi-the-going-merry[bot]@users.noreply.github.com> Date: Thu, 22 Oct 2026 20:13:18 -0600 Subject: [PATCH 1/7] Align inline Submit button with inputs when submit HTML uses frm_flex The ::before spacer was a flex item in the wrapping row and the button was centered against it. Make the spacer a full row and pin items to the top. Co-Authored-By: Claude Sonnet 5.5 --- css/custom_theme.css.php | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 6f2149a589..1a29a6dee3 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -733,6 +733,19 @@ 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; +} + .with_frm_style .frm_submit.frm_flex button.frm_button_submit ~ .frm_prev_page { order: -1; From e404c85f5ae120b29aab6920f89dd13005c80415 Mon Sep 17 00:00:00 2001 From: Mike Letellier Date: Thu, 29 Oct 2026 21:25:23 -0300 Subject: [PATCH 2/7] test(styles): cover inline flex submit alignment in generated CSS (#6894) Co-Authored-By: Claude Opus 5.5 --- tests/phpunit/styles/test_FrmStyle.php | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) diff --git a/tests/phpunit/styles/test_FrmStyle.php b/tests/phpunit/styles/test_FrmStyle.php index a462a5401c..bd2bfc2d6e 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -287,6 +287,24 @@ public function test_get_all() { $this->assertSame( FrmStylesController::$post_type, reset( $styles )->post_type ); } + /** + * With the default "frm_submit frm_flex" submit HTML, the inline submit label spacer must take a full row + * and the button must not be vertically centered against it. + * + * @see https://github.com/Strategy11/formidable-pro/issues/6894 + */ + public function test_generated_css_aligns_inline_flex_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'; + $spacer_selector = '.with_frm_style.frm_inline_top .frm_submit.frm_flex::before,.with_frm_style .frm_submit.frm_flex.frm_inline_submit::before'; + + $this->assertStringContainsString( $submit_selector . ' {align-items: flex-start;', $css ); + $this->assertStringContainsString( $spacer_selector . ' {flex-basis: 100%;order: -2;}', $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"). From d71c44c047728e38fc17645dd24ba52d270cdfaa Mon Sep 17 00:00:00 2001 From: "vivi-the-going-merry[bot]" <308115520+vivi-the-going-merry[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 06:32:45 -0700 Subject: [PATCH 3/7] Align inline Submit button with inputs when labels are inside With inside (floating) labels the input is offset by the container's padding-top, not a label's height, so the hidden ::before spacer pushed the Submit button about 8px below the inputs. Add a frm_inline_inside class when the last input field uses an inside label and size the spacer to that padding. Refs Strategy11/formidable-pro#6894 Co-Authored-By: Claude Sonnet 5.5 --- classes/helpers/FrmFormsHelper.php | 52 ++++++++++----------- css/custom_theme.css.php | 7 +++ tests/phpunit/forms/test_FrmFormsHelper.php | 29 ++++++++++++ tests/phpunit/styles/test_FrmStyle.php | 1 + 4 files changed, 61 insertions(+), 28 deletions(-) diff --git a/classes/helpers/FrmFormsHelper.php b/classes/helpers/FrmFormsHelper.php index 02e8038ff9..eb3bc573ab 100644 --- a/classes/helpers/FrmFormsHelper.php +++ b/classes/helpers/FrmFormsHelper.php @@ -1426,53 +1426,49 @@ private static function form_should_be_inline_and_missing_class( $form ) { * @return string */ private static function maybe_align_fields_top( $form ) { - return self::form_has_top_labels( $form ) ? ' frm_inline_top' : ''; + $label_position = self::get_last_input_label_position( $form ); + + if ( ! in_array( $label_position, array( 'top', 'inside', 'hidden' ), true ) ) { + return ''; + } + + $class = ' frm_inline_top'; + + if ( 'inside' === $label_position ) { + // Inside labels have no label above the input, so the submit button spacer needs a different height. + $class .= ' frm_inline_inside'; + } + + return $class; } /** - * Determine if a form has fields with top labels so submit button can be aligned properly + * Get the label position of the input field closest to the submit button so the submit button can be aligned properly. + * + * @since x.x * * @param array $form * - * @return bool + * @return string Empty string when the form has no fields with an input. */ - private static function form_has_top_labels( $form ) { - if ( ! isset( $form['fields'] ) ) { - return false; - } - - $fields = $form['fields']; - - if ( count( $fields ) <= 0 ) { - return false; + private static function get_last_input_label_position( $form ) { + if ( empty( $form['fields'] ) ) { + return ''; } // Start from the fields closest to the submit button. - $fields = array_reverse( $fields ); + $fields = array_reverse( $form['fields'] ); foreach ( $fields as $field ) { $type = $field['original_type'] ?? $field['type']; $has_input = FrmFieldFactory::field_has_property( $type, 'has_input' ); if ( $has_input ) { - return self::field_has_top_label( $field, $form ); + return FrmFieldsHelper::label_position( $field['label'], $field, $form ); } } - return false; - } - - /** - * Check if a field's label position is set to "top" - * - * @param array $field - * @param bool|object|string $form - * - * @return bool - */ - private static function field_has_top_label( $field, $form ) { - $label_position = FrmFieldsHelper::label_position( $field['label'], $field, $form ); - return in_array( $label_position, array( 'top', 'inside', 'hidden' ), true ); + return ''; } /** diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 847f51d7b1..81e6e21fbb 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -747,6 +747,13 @@ order: -2; } +/* Inside labels add padding above the input instead of rendering a label, so the spacer matches that padding. */ +.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before { + box-sizing: border-box; + height: calc(0.5 * var(--field-height)); + overflow: hidden; +} + .with_frm_style .frm_submit.frm_flex button.frm_button_submit ~ .frm_prev_page { order: -1; diff --git a/tests/phpunit/forms/test_FrmFormsHelper.php b/tests/phpunit/forms/test_FrmFormsHelper.php index 929857e96e..30bbab311e 100644 --- a/tests/phpunit/forms/test_FrmFormsHelper.php +++ b/tests/phpunit/forms/test_FrmFormsHelper.php @@ -632,4 +632,33 @@ public function test_count_fields_without_submit() { $this->assertSame( 2, FrmFormsHelper::count_fields_without_submit( $fields ) ); $this->assertSame( 0, FrmFormsHelper::count_fields_without_submit( array() ) ); } + + /** + * Inside labels need their own class so the inline submit spacer matches the padding above the input. + * + * @see https://github.com/Strategy11/formidable-pro/issues/6894 + */ + public function test_get_form_style_class_adds_inline_inside_class_for_inside_labels() { + $form = array( + 'submit_align' => 'inline', + 'custom_style' => 1, + 'fields' => array( + array( + 'type' => 'text', + 'label' => 'inside', + ), + ), + ); + $class = FrmFormsHelper::get_form_style_class( $form ); + + $this->assertStringContainsString( ' frm_inline_form', $class ); + $this->assertStringContainsString( ' frm_inline_top', $class ); + $this->assertStringContainsString( ' frm_inline_inside', $class ); + + $form['fields'][0]['label'] = 'top'; + $class = FrmFormsHelper::get_form_style_class( $form ); + + $this->assertStringContainsString( ' frm_inline_top', $class ); + $this->assertStringNotContainsString( 'frm_inline_inside', $class ); + } } diff --git a/tests/phpunit/styles/test_FrmStyle.php b/tests/phpunit/styles/test_FrmStyle.php index bd2bfc2d6e..9e5eabe622 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -303,6 +303,7 @@ public function test_generated_css_aligns_inline_flex_submit_with_inputs() { $this->assertStringContainsString( $submit_selector . ' {align-items: flex-start;', $css ); $this->assertStringContainsString( $spacer_selector . ' {flex-basis: 100%;order: -2;}', $css ); + $this->assertStringContainsString( '.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before {box-sizing: border-box;height: calc(0.5 * var(--field-height));overflow: hidden;}', $css ); } /** From 64497ad8460495e3ddc106286cc0149947b6993a Mon Sep 17 00:00:00 2001 From: "vivi-the-going-merry[bot]" <308115520+vivi-the-going-merry[bot]@users.noreply.github.com> Date: Tue, 3 Nov 2026 06:35:00 -0700 Subject: [PATCH 4/7] Shorten test assertion line to satisfy PHPCS line length Co-Authored-By: Claude Sonnet 5.5 --- tests/phpunit/styles/test_FrmStyle.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/tests/phpunit/styles/test_FrmStyle.php b/tests/phpunit/styles/test_FrmStyle.php index 9e5eabe622..2bf5f30f58 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -303,7 +303,9 @@ public function test_generated_css_aligns_inline_flex_submit_with_inputs() { $this->assertStringContainsString( $submit_selector . ' {align-items: flex-start;', $css ); $this->assertStringContainsString( $spacer_selector . ' {flex-basis: 100%;order: -2;}', $css ); - $this->assertStringContainsString( '.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before {box-sizing: border-box;height: calc(0.5 * var(--field-height));overflow: hidden;}', $css ); + $inside_selector = '.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before'; + + $this->assertStringContainsString( $inside_selector . ' {box-sizing: border-box;height: calc(0.5 * var(--field-height));overflow: hidden;}', $css ); } /** From 8612c0207392a0d24efbd1c2bada4eef2b61328c Mon Sep 17 00:00:00 2001 From: Mike Letellier Date: Tue, 17 Nov 2026 11:10:03 -0400 Subject: [PATCH 5/7] Line up inline submit button when a theme restyles labels The spacer above an inline submit button copies the label size from the form style. Themes like Hello Elementor and Hello Biz set label { line-height: 1 }, which the spacer never sees, so the button sat a few pixels off the inputs. formidable.js now measures the gap between the top row of buttons and the input closest to the submit button, then stores it in --frm-inline-submit-offset. The CSS applies it as a margin on the spacer. Without JS, or when the fields stack on narrow screens, the CSS spacer works as before. Co-Authored-By: Claude Opus 5.5 --- css/custom_theme.css.php | 6 ++ js/formidable.js | 102 +++++++++++++++++++++++++ js/formidable.min.js | 67 ++++++++-------- tests/phpunit/styles/test_FrmStyle.php | 5 ++ 4 files changed, 148 insertions(+), 32 deletions(-) diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 81e6e21fbb..79f24295aa 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -754,6 +754,12 @@ overflow: hidden; } +/* 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/js/formidable.js b/js/formidable.js index 897402acbc..955104a63a 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -2243,6 +2243,107 @@ 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 ); + jQuery( document ).on( 'frmPageChanged', scheduleAlignment ); + + 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( '.frm_inline_top .frm_submit, .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.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; @@ -2806,6 +2907,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 7232f8d915..6940002d2c 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -70,38 +70,41 @@ 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);jQuery(document).on("frmPageChanged",scheduleAlignment);if(document.fonts?.ready)document.fonts.ready.then(scheduleAlignment)}function alignInlineSubmitButtons(){document.querySelectorAll(".frm_inline_top .frm_submit, .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.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 +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;cassertStringContainsString( $inside_selector . ' {box-sizing: border-box;height: calc(0.5 * var(--field-height));overflow: hidden;}', $css ); + + // The JS in formidable.js sets the offset when a theme restyles the labels. + $offset_selector = '.frm_forms.with_frm_style.frm_inline_top .frm_fields_container .frm_submit::before,'; + $offset_selector .= '.frm_forms.with_frm_style .frm_fields_container .frm_submit.frm_inline_submit::before'; + $this->assertStringContainsString( $offset_selector . ' {margin-bottom: var(--frm-inline-submit-offset, 0);}', $css ); } /** From cb2638619ceeeaefd79469f8f4b446611c134b95 Mon Sep 17 00:00:00 2001 From: Mike Letellier Date: Tue, 17 Nov 2026 11:50:37 -0400 Subject: [PATCH 6/7] Line up inline submit button with CSS only Replace the ::before spacer that copied the label size with align-self: end on the inline submit cell, so the button lines up with the bottom of the inputs in its row. Themes that restyle labels no longer throw it off, so the JS measuring step and the frm_inline_inside class are no longer needed. Co-Authored-By: Claude Opus 5.5 --- classes/helpers/FrmFormsHelper.php | 52 +++++----- css/_single_theme.css.php | 20 +--- css/custom_theme.css.php | 28 +----- js/formidable.js | 102 -------------------- js/formidable.min.js | 67 ++++++------- tests/phpunit/forms/test_FrmFormsHelper.php | 29 ------ tests/phpunit/styles/test_FrmStyle.php | 22 ++--- 7 files changed, 74 insertions(+), 246 deletions(-) diff --git a/classes/helpers/FrmFormsHelper.php b/classes/helpers/FrmFormsHelper.php index e1bf716337..69340fbc9e 100644 --- a/classes/helpers/FrmFormsHelper.php +++ b/classes/helpers/FrmFormsHelper.php @@ -1426,49 +1426,53 @@ private static function form_should_be_inline_and_missing_class( $form ) { * @return string */ private static function maybe_align_fields_top( $form ) { - $label_position = self::get_last_input_label_position( $form ); - - if ( ! in_array( $label_position, array( 'top', 'inside', 'hidden' ), true ) ) { - return ''; - } - - $class = ' frm_inline_top'; - - if ( 'inside' === $label_position ) { - // Inside labels have no label above the input, so the submit button spacer needs a different height. - $class .= ' frm_inline_inside'; - } - - return $class; + return self::form_has_top_labels( $form ) ? ' frm_inline_top' : ''; } /** - * Get the label position of the input field closest to the submit button so the submit button can be aligned properly. - * - * @since x.x + * Determine if a form has fields with top labels so submit button can be aligned properly * * @param array $form * - * @return string Empty string when the form has no fields with an input. + * @return bool */ - private static function get_last_input_label_position( $form ) { - if ( empty( $form['fields'] ) ) { - return ''; + private static function form_has_top_labels( $form ) { + if ( ! isset( $form['fields'] ) ) { + return false; + } + + $fields = $form['fields']; + + if ( count( $fields ) <= 0 ) { + return false; } // Start from the fields closest to the submit button. - $fields = array_reverse( $form['fields'] ); + $fields = array_reverse( $fields ); foreach ( $fields as $field ) { $type = $field['original_type'] ?? $field['type']; $has_input = FrmFieldFactory::field_has_property( $type, 'has_input' ); if ( $has_input ) { - return FrmFieldsHelper::label_position( $field['label'], $field, $form ); + return self::field_has_top_label( $field, $form ); } } - return ''; + return false; + } + + /** + * Check if a field's label position is set to "top" + * + * @param array $field + * @param bool|object|string $form + * + * @return bool + */ + private static function field_has_top_label( $field, $form ) { + $label_position = FrmFieldsHelper::label_position( $field['label'], $field, $form ); + return in_array( $label_position, array( 'top', 'inside', 'hidden' ), true ); } /** diff --git a/css/_single_theme.css.php b/css/_single_theme.css.php index 4aa58e84fd..9f0280d60c 100644 --- a/css/_single_theme.css.php +++ b/css/_single_theme.css.php @@ -36,7 +36,9 @@ -. .form-field{ +. .form-field, +..frm_inline_top .frm_fields_container > .frm_submit, +. .frm_fields_container > .frm_submit.frm_inline_submit{ margin-bottom:var(--field-margin); } @@ -322,22 +324,6 @@ }//end if ?> -..frm_inline_top .frm_submit::before, -. .frm_submit.frm_inline_submit::before { - content:"before"; - - font-family:; - - font-size:var(--font-size); - color:var(--label-color); - font-weight:var(--weight); - margin:0; - padding:var(--label-padding); - width:auto; - display:block; - visibility:hidden; -} - ..frm_inline_form .frm_submit input, ..frm_inline_form .frm_submit button, . .frm_submit.frm_inline_submit input, diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 79f24295aa..0ca3f49801 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -734,30 +734,10 @@ 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; -} - -/* Inside labels add padding above the input instead of rendering a label, so the spacer matches that padding. */ -.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before { - box-sizing: border-box; - height: calc(0.5 * var(--field-height)); - overflow: hidden; -} - -/* 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); +/* Line up an inline submit button with the bottom of the inputs in its row, so the label height above them does not matter. */ +.with_frm_style.frm_inline_top .frm_fields_container > .frm_submit, +.with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit { + align-self: end; } diff --git a/js/formidable.js b/js/formidable.js index 955104a63a..897402acbc 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -2243,107 +2243,6 @@ 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 ); - jQuery( document ).on( 'frmPageChanged', scheduleAlignment ); - - 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( '.frm_inline_top .frm_submit, .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.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; @@ -2907,7 +2806,6 @@ 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 6940002d2c..7232f8d915 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -70,41 +70,38 @@ 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 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);jQuery(document).on("frmPageChanged",scheduleAlignment);if(document.fonts?.ready)document.fonts.ready.then(scheduleAlignment)}function alignInlineSubmitButtons(){document.querySelectorAll(".frm_inline_top .frm_submit, .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.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 -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")} +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")} 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;cassertSame( 2, FrmFormsHelper::count_fields_without_submit( $fields ) ); $this->assertSame( 0, FrmFormsHelper::count_fields_without_submit( array() ) ); } - - /** - * Inside labels need their own class so the inline submit spacer matches the padding above the input. - * - * @see https://github.com/Strategy11/formidable-pro/issues/6894 - */ - public function test_get_form_style_class_adds_inline_inside_class_for_inside_labels() { - $form = array( - 'submit_align' => 'inline', - 'custom_style' => 1, - 'fields' => array( - array( - 'type' => 'text', - 'label' => 'inside', - ), - ), - ); - $class = FrmFormsHelper::get_form_style_class( $form ); - - $this->assertStringContainsString( ' frm_inline_form', $class ); - $this->assertStringContainsString( ' frm_inline_top', $class ); - $this->assertStringContainsString( ' frm_inline_inside', $class ); - - $form['fields'][0]['label'] = 'top'; - $class = FrmFormsHelper::get_form_style_class( $form ); - - $this->assertStringContainsString( ' frm_inline_top', $class ); - $this->assertStringNotContainsString( 'frm_inline_inside', $class ); - } } diff --git a/tests/phpunit/styles/test_FrmStyle.php b/tests/phpunit/styles/test_FrmStyle.php index 99c569b61e..f04acf84cd 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -317,29 +317,21 @@ public function test_get_all() { } /** - * With the default "frm_submit frm_flex" submit HTML, the inline submit label spacer must take a full row - * and the button must not be vertically centered against it. + * An inline submit button lines up with the bottom of the inputs in its row instead of sitting under + * a spacer that copies the label size, which a theme that restyles labels throws off. * * @see https://github.com/Strategy11/formidable-pro/issues/6894 */ - public function test_generated_css_aligns_inline_flex_submit_with_inputs() { + 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'; - $spacer_selector = '.with_frm_style.frm_inline_top .frm_submit.frm_flex::before,.with_frm_style .frm_submit.frm_flex.frm_inline_submit::before'; + $submit_selector = '.with_frm_style.frm_inline_top .frm_fields_container > .frm_submit,.with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit'; - $this->assertStringContainsString( $submit_selector . ' {align-items: flex-start;', $css ); - $this->assertStringContainsString( $spacer_selector . ' {flex-basis: 100%;order: -2;}', $css ); - $inside_selector = '.with_frm_style.frm_inline_inside .frm_submit.frm_flex::before'; - - $this->assertStringContainsString( $inside_selector . ' {box-sizing: border-box;height: calc(0.5 * var(--field-height));overflow: hidden;}', $css ); - - // The JS in formidable.js sets the offset when a theme restyles the labels. - $offset_selector = '.frm_forms.with_frm_style.frm_inline_top .frm_fields_container .frm_submit::before,'; - $offset_selector .= '.frm_forms.with_frm_style .frm_fields_container .frm_submit.frm_inline_submit::before'; - $this->assertStringContainsString( $offset_selector . ' {margin-bottom: var(--frm-inline-submit-offset, 0);}', $css ); + $this->assertStringContainsString( $submit_selector . ' {align-self: end;}', $css ); + $this->assertStringNotContainsString( 'frm_submit::before', $css ); + $this->assertStringNotContainsString( 'frm_inline_submit::before', $css ); } /** From b6bca1dd18904c0d2efd84b5fca620279b54ed0e Mon Sep 17 00:00:00 2001 From: Mike Letellier Date: Tue, 17 Nov 2026 12:42:16 -0400 Subject: [PATCH 7/7] fix(forms): align inline submit with inputs --- .oxlintrc.json | 10 +- css/_single_theme.css.php | 21 +++- css/custom_theme.css.php | 21 +++- eslint.config.mjs | 2 +- js/formidable.js | 124 ++++++++++++++++++++ js/formidable.min.js | 43 ++++--- tests/js/inlineSubmitAlignment.test.mjs | 148 ++++++++++++++++++++++++ tests/phpunit/styles/test_FrmStyle.php | 11 +- 8 files changed, 338 insertions(+), 42 deletions(-) create mode 100644 tests/js/inlineSubmitAlignment.test.mjs 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 9f0280d60c..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 ); @@ -36,9 +37,7 @@ -. .form-field, -..frm_inline_top .frm_fields_container > .frm_submit, -. .frm_fields_container > .frm_submit.frm_inline_submit{ +. .form-field{ margin-bottom:var(--field-margin); } @@ -324,6 +323,22 @@ }//end if ?> +..frm_inline_top .frm_submit::before, +. .frm_submit.frm_inline_submit::before { + content:"before"; + + font-family:; + + font-size:var(--font-size); + color:var(--label-color); + font-weight:var(--weight); + margin:0; + padding:var(--label-padding); + width:auto; + display:block; + visibility:hidden; +} + ..frm_inline_form .frm_submit input, ..frm_inline_form .frm_submit button, . .frm_submit.frm_inline_submit input, diff --git a/css/custom_theme.css.php b/css/custom_theme.css.php index 0ca3f49801..994c049ca0 100644 --- a/css/custom_theme.css.php +++ b/css/custom_theme.css.php @@ -734,10 +734,23 @@ gap: 2%; } -/* Line up an inline submit button with the bottom of the inputs in its row, so the label height above them does not matter. */ -.with_frm_style.frm_inline_top .frm_fields_container > .frm_submit, -.with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit { - align-self: end; +.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); } 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 897402acbc..88d7c93b05 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -2243,6 +2243,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; @@ -2806,6 +2929,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 7232f8d915..88e22e0251 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -70,25 +70,30 @@ 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{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 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 f04acf84cd..06b7fb6018 100644 --- a/tests/phpunit/styles/test_FrmStyle.php +++ b/tests/phpunit/styles/test_FrmStyle.php @@ -317,8 +317,7 @@ public function test_get_all() { } /** - * An inline submit button lines up with the bottom of the inputs in its row instead of sitting under - * a spacer that copies the label size, which a theme that restyles labels throws off. + * Inline buttons reserve a label row without aligning to descriptions or errors below inputs. * * @see https://github.com/Strategy11/formidable-pro/issues/6894 */ @@ -327,11 +326,11 @@ public function test_generated_css_aligns_inline_submit_with_inputs() { array( new FrmStyle(), 'get_css_content' ), array( FrmAppHelper::plugin_path() . '/css/custom_theme.css.php' ) ); - $submit_selector = '.with_frm_style.frm_inline_top .frm_fields_container > .frm_submit,.with_frm_style .frm_fields_container > .frm_submit.frm_inline_submit'; + $submit_selector = '.with_frm_style.frm_inline_top .frm_submit.frm_flex,.with_frm_style .frm_submit.frm_flex.frm_inline_submit'; - $this->assertStringContainsString( $submit_selector . ' {align-self: end;}', $css ); - $this->assertStringNotContainsString( 'frm_submit::before', $css ); - $this->assertStringNotContainsString( 'frm_inline_submit::before', $css ); + \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 ); } /**