1"use strict"; 2 3let cf7signature_resized = 0; // for compatibility with contact-form-7-signature-addon 4 5let wpcf7cf_timeout; 6let wpcf7cf_change_time_ms = 100; // the timeout after a change in the form is detected 7 8// needed for multistep validation 9if (window.wpcf7 && !wpcf7.setStatus) { 10 wpcf7.setStatus = ( form, status ) => { 11 form = form.length ? form[0] : form; // if form is a jQuery object, only grab te html-element 12 const defaultStatuses = new Map( [ 13 // 0: Status in API response, 1: Status in HTML class 14 [ 'init', 'init' ], 15 [ 'validation_failed', 'invalid' ], 16 [ 'acceptance_missing', 'unaccepted' ], 17 [ 'spam', 'spam' ], 18 [ 'aborted', 'aborted' ], 19 [ 'mail_sent', 'sent' ], 20 [ 'mail_failed', 'failed' ], 21 [ 'submitting', 'submitting' ], 22 [ 'resetting', 'resetting' ], 23 ] ); 24 25 if ( defaultStatuses.has( status ) ) { 26 status = defaultStatuses.get( status ); 27 } 28 29 if ( ! Array.from( defaultStatuses.values() ).includes( status ) ) { 30 status = status.replace( /[^0-9a-z]+/i, ' ' ).trim(); 31 status = status.replace( /\s+/, '-' ); 32 status = `custom-${ status }`; 33 } 34 35 const prevStatus = form.getAttribute( 'data-status' ); 36 37 form.wpcf7.status = status; 38 form.setAttribute( 'data-status', status ); 39 form.classList.add( status ); 40 41 if ( prevStatus && prevStatus !== status ) { 42 form.classList.remove( prevStatus ); 43 } 44 45 return status; 46 }; 47} 48 49if (window.wpcf7cf_running_tests) { 50 document.querySelectorAll('input[name="_wpcf7cf_options"]').forEach(input => { 51 const opt = JSON.parse(input.value); 52 opt.settings.animation_intime = 0; 53 opt.settings.animation_outtime = 0; 54 input.value = JSON.stringify(opt); 55 }); 56 wpcf7cf_change_time_ms = 0; 57} 58 59const wpcf7cf_show_animation = { "height": "show", "marginTop": "show", "marginBottom": "show", "paddingTop": "show", "paddingBottom": "show" }; 60const wpcf7cf_hide_animation = { "height": "hide", "marginTop": "hide", "marginBottom": "hide", "paddingTop": "hide", "paddingBottom": "hide" }; 61 62const wpcf7cf_show_step_animation = { "opacity": "show" }; 63const wpcf7cf_hide_step_animation = { "opacity": "hide" }; 64 65const wpcf7cf_change_events = 'input.wpcf7cf paste.wpcf7cf change.wpcf7cf click.wpcf7cf propertychange.wpcf7cf changedisabledprop.wpcf7cf'; 66 67const wpcf7cf_forms = []; 68 69const Wpcf7cfForm = function(formElement) { 70 71 const $form = jQuery(formElement); 72 73 const options_element = $form.find('input[name="_wpcf7cf_options"]').eq(0); 74 if (!options_element.length || !options_element.val()) { 75 // doesn't look like a CF7 form created with conditional fields plugin enabled. 76 return false; 77 } 78 79 const form = this; 80 81 // always wait until groups are updated before submitting the form 82 formElement.addEventListener('submit', function(e) { 83 if (window.wpcf7cf_updatingGroups) { 84 e.preventDefault(); 85 e.stopImmediatePropagation(); 86 87 // Wait until updatingGroups is false, then submit again 88 const retry = () => { 89 if (!window.wpcf7cf_updatingGroups) { 90 $form.off('.wpcf7cf-autosubmit'); // prevent duplicates 91 formElement.requestSubmit(); // safe submit 92 } else { 93 requestAnimationFrame(retry); 94 } 95 }; 96 97 // Attach listener to prevent loop if user resubmits manually 98 $form.on('submit.wpcf7cf-autosubmit', (e) => e.preventDefault()); 99 100 retry(); // start retry loop 101 return false; 102 } 103 }, true); // use capture to run before WP's own handler 104 105 // Disable submit buttons only during the actual submit, then restore prior state â don't clobber CF7's acceptance gating or any custom disabling (#136) 106 const submitButtons = formElement.querySelectorAll('button[type=submit], input[type=submit]'); 107 const prevDisabled = new WeakMap(); 108 let wasSubmitting = formElement.classList.contains('submitting'); 109 const observer = new MutationObserver(() => { 110 const isSubmitting = formElement.classList.contains('submitting'); 111 if (isSubmitting === wasSubmitting) return; // only act on the submitting transition 112 wasSubmitting = isSubmitting; 113 114 submitButtons.forEach(button => { 115 if (isSubmitting) { 116 prevDisabled.set(button, button.disabled); 117 button.disabled = true; 118 button.classList.add('is-disabled'); 119 } else { 120 button.disabled = prevDisabled.get(button) || false; 121 button.classList.remove('is-disabled'); 122 } 123 }); 124 }); 125 observer.observe(formElement, { attributes: true, attributeFilter: ['class'] }); 126 127 const form_options = JSON.parse(options_element.val()); 128 129 form.$form = $form; 130 form.formElement = formElement; 131 form.$input_hidden_group_fields = $form.find('[name="_wpcf7cf_hidden_group_fields"]'); 132 form.$input_hidden_groups = $form.find('[name="_wpcf7cf_hidden_groups"]'); 133 form.$input_visible_groups = $form.find('[name="_wpcf7cf_visible_groups"]'); 134 form.$input_repeaters = $form.find('[name="_wpcf7cf_repeaters"]'); 135 form.$input_steps = $form.find('[name="_wpcf7cf_steps"]'); 136 137 form.unit_tag = $form.closest('.wpcf7').attr('id'); 138 form.conditions = form_options['conditions']; 139 140 form.simpleDom = null; 141 142 form.reloadSimpleDom = function() { 143 form.simpleDom = wpcf7cf.get_simplified_dom_model(form.formElement); 144 } 145 146 // quicker than reloading the simpleDom completely with reloadSimpleDom 147 form.updateSimpleDom = function() { 148 if (!form.simpleDom) { 149 form.reloadSimpleDom(); 150 } 151 const inputs = Object.values(form.simpleDom).filter(item => item.type === 'input'); 152 const formdata = new FormData(form.formElement); 153
154 let formdataEntries = [... formdata.entries()].map(entry => [ entry[0], entry[1].name ?? entry[1] ]); 155 const buttonEntries = Array.from(form.formElement.querySelectorAll('button'), b => [b.name, b.value]); 156 formdataEntries = formdataEntries.concat(buttonEntries); 157 158 inputs.forEach(simpleDomItem => { 159 const newValue = form.getNewDomValueIfChanged(simpleDomItem, formdataEntries); 160 if (newValue !== null) { 161 form.simpleDom[simpleDomItem.name].val = newValue; 162 } 163 }); 164 165 } 166 167 form.isDomMatch = function(simpleDomItem, formDataEntries) { 168 const simpleDomItemName = simpleDomItem.name; 169 const simpleDomItemValues = simpleDomItem.val; 170 const currentValues = formDataEntries.filter(entry => entry[0] === simpleDomItemName).map(entry => entry[1]); 171 return currentValues.join('|') === simpleDomItemValues.join('|'); 172 } 173 174 /** 175 * 176 * @param {*} simpleDomItem 177 * @param {*} formDataEntries 178 * @returns the new value, or NULL if no change 179 */ 180 form.getNewDomValueIfChanged = function(simpleDomItem, formDataEntries) { 181 const simpleDomItemName = simpleDomItem.name; 182 const simpleDomItemValues = simpleDomItem.val; 183 const currentValues = formDataEntries.filter(entry => entry[0] === simpleDomItemName).map(entry => entry[1]); 184 return currentValues.join('|') === simpleDomItemValues.join('|') ? null : currentValues; 185 } 186 187 // Wrapper around jQuery(selector, form.$form) 188 form.get = function (selector) { 189 // TODO: implement some caching here. 190 return jQuery(selector, form.$form); 191 } 192 193 form.getFieldByName = function(name) { 194 return form.simpleDom[name] || form.simpleDom[name+'[]']; 195 } 196 197 // compatibility with conditional forms created with older versions of the plugin ( < 1.4 ) 198 for (let i=0; i < form.conditions.length; i++) { 199 const condition = form.conditions[i]; 200 if (!('and_rules' in condition)) { 201 condition.and_rules = [{'if_field':condition.if_field,'if_value':condition.if_value,'operator':condition.operator}]; 202 } 203 } 204 205 form.initial_conditions = form.conditions; 206 form.settings = form_options['settings']; 207 208 form.$groups = jQuery(); // empty jQuery set 209 form.repeaters = []; 210 form.multistep = null; 211 form.fields = []; 212 213 form.settings.animation_intime = parseInt(form.settings.animation_intime); 214 form.settings.animation_outtime = parseInt(form.settings.animation_outtime); 215 216 if (form.settings.animation === 'no') { 217 form.settings.animation_intime = 0; 218 form.settings.animation_outtime = 0; 219 } 220 221 form.updateGroups(); 222 form.updateEventListeners(); 223 form.displayFields(); 224 225 // bring form in initial state if the reset event is fired on it. 226 // (CF7 triggers the 'reset' event by default on each successfully submitted form) 227 form.$form.on('reset.wpcf7cf', form, function(e) { 228 const form = e.data; 229 setTimeout(function(){ 230 form.reloadSimpleDom(); 231 form.displayFields(); 232 form.resetRepeaters(); 233 if (form.multistep != null) { 234 form.multistep.moveToStep(1, false); 235 } 236 setTimeout(function(){ 237 if (form.$form.hasClass('sent')) { 238 jQuery('.wpcf7-response-output', form.$form)[0].scrollIntoView({behavior: "smooth", block:"nearest", inline:"nearest"}); 239 } 240 }, 400); 241 },200); 242 }); 243 244 245 246} 247 248/** 249 * reset initial number of subs for each repeater. 250 * (does not clear values) 251 */ 252Wpcf7cfForm.prototype.resetRepeaters = function() { 253 const form = this; 254 form.repeaters.forEach(repeater => { 255 repeater.updateSubs( repeater.params.$repeater.initial_subs ); 256 }); 257} 258 259Wpcf7cfForm.prototype.displayFields = function() { 260 261 const form = this; 262 263 const wpcf7cf_conditions = this.conditions; 264 const wpcf7cf_settings = this.settings; 265 266 //for compatibility with contact-form-7-signature-addon 267 if (cf7signature_resized === 0 && typeof signatures !== 'undefined' && signatures.constructor === Array && signatures.length > 0 ) { 268 for (let i = 0; i < signatures.length; i++) { 269 if (signatures[i].canvas.width === 0) { 270 271 const $sig_canvas = jQuery(".wpcf7-form-control-signature-body>canvas"); 272 const $sig_wrap = jQuery(".wpcf7-form-control-signature-wrap"); 273 $sig_canvas.eq(i).attr('width', $sig_wrap.width()); 274 $sig_canvas.eq(i).attr('height', $sig_wrap.height()); 275 276 cf7signature_resized = 1; 277 } 278 } 279 } 280 281 // 'novalidate' makes CF7 skip inline validation inside hidden groups (issue #137) 282 form.$groups.addClass('wpcf7cf-hidden novalidate'); 283 284 for (let i=0; i < wpcf7cf_conditions.length; i++) { 285 286 const condition = wpcf7cf_conditions[i]; 287 288 const show_group = window.wpcf7cf.should_group_be_shown(condition, form); 289 290 if (show_group) { 291 form.get('[data-id="'+condition.then_field+'"]').removeClass('wpcf7cf-hidden novalidate'); 292 } 293 } 294 295 296 const animation_intime = wpcf7cf_settings.animation_intime;
297 const animation_outtime = wpcf7cf_settings.animation_outtime; 298 299 form.$groups.each(function (index) { 300 const $group = jQuery(this); 301 if ($group.is(':animated')) { 302 $group.finish(); // stop any current animations on the group 303 } 304 if ($group.css('display') === 'none' && !$group.hasClass('wpcf7cf-hidden')) { 305 if ($group.prop('tagName') === 'SPAN') { 306 $group.show().trigger('wpcf7cf_show_group'); // show instantly 307 } else { 308 $group.animate(wpcf7cf_show_animation, animation_intime).trigger('wpcf7cf_show_group'); // show with animation 309 } 310 311 if($group.attr('data-disable_on_hide') !== undefined) { 312 $group.find(':input').prop('disabled', false).trigger('changedisabledprop.wpcf7cf'); 313 $group.find('.wpcf7-form-control-wrap').removeClass('wpcf7cf-disabled'); 314 } 315 316 } else if ($group.css('display') !== 'none' && $group.hasClass('wpcf7cf-hidden')) { 317 318 if ($group.attr('data-clear_on_hide') !== undefined) { 319 const $inputs = jQuery(':input', $group).not(':button, :submit, :reset, :hidden'); 320 321 $inputs.each(function(){ 322 const $this = jQuery(this); 323 $this.val(this.defaultValue); 324 $this.prop('checked', this.defaultChecked); 325 }); 326 327 jQuery('option', $group).each(function() { 328 this.selected = this.defaultSelected; 329 }); 330 331 jQuery('select', $group).each(function() { 332 const $select = jQuery(this); 333 if ($select.val() === null) { 334 $select.val(jQuery("option:first",$select).val()); 335 } 336 }); 337 338 $inputs.each(function(){this.dispatchEvent(new Event("change",{"bubbles":true}))}); 339 } 340 341 if ($group.prop('tagName') === 'SPAN') { 342 $group.hide().trigger('wpcf7cf_hide_group'); 343 } else { 344 $group.animate(wpcf7cf_hide_animation, animation_outtime).trigger('wpcf7cf_hide_group'); // hide 345 } 346 } 347 }); 348 349 form.updateHiddenFields(); 350 351 form.updateSummaryFields(); 352}; 353 354 355 356Wpcf7cfForm.prototype.updateSummaryFields = function() { 357 const form = this; 358 const $summary = form.get('.wpcf7cf-summary'); 359 360 if ($summary.length == 0 || !$summary.is(':visible')) { 361 return; 362 } 363 364 const fd = new FormData(); 365 366 const formdata = form.$form.serializeArray(); 367 jQuery.each(formdata,function(key, input){ 368 fd.append(input.name, input.value); 369 }); 370 371 // Make sure to add file fields to FormData 372 jQuery.each(form.$form.find('input[type="file"]'), function(index, el) { 373 if (! el.files.length) return true; // continue 374 const fieldName = el.name; 375 fd.append(fieldName, new Blob() , Array.from(el.files).map(file => file.name).join(', ')); 376 }); 377 378 // add file fields to form-data 379 380 jQuery.ajax({ 381 url: wpcf7cf_global_settings.ajaxurl + '?action=wpcf7cf_get_summary', 382 type: 'POST', 383 data: fd, 384 processData: false, 385 contentType: false, 386 dataType: 'json', 387 success: function(json) { 388 $summary.html(json.summaryHtml); 389 } 390 }); 391}; 392 393Wpcf7cfForm.prototype.updateHiddenFields = function() { 394 395 const form = this; 396 397 const hidden_fields = []; 398 const hidden_groups = []; 399 const visible_groups = []; 400 401 form.$groups.each(function () { 402 const $group = jQuery(this); 403 if ($group.hasClass('wpcf7cf-hidden')) { 404 hidden_groups.push($group.attr('data-id')); 405 if($group.attr('data-disable_on_hide') !== undefined) { 406 // fields inside hidden disable_on_hide group 407 $group.find('input,select,textarea').each(function(){ 408 const $this = jQuery(this); 409 if (!$this.prop('disabled')) { 410 $this.prop('disabled', true).trigger('changedisabledprop.wpcf7cf'); 411 } 412 413 // if there's no other field with the same name visible in the form 414 // then push this field to hidden_fields 415 if (form.$form.find(`[data-class="wpcf7cf_group"]:not(.wpcf7cf-hidden) [name='${$this.attr('name')}']`).length === 0) { 416 hidden_fields.push($this.attr('name')); 417 } 418 }) 419 $group.find('.wpcf7-form-control-wrap').addClass('wpcf7cf-disabled'); 420 } else { 421 // fields inside regular hidden group are all pushed to hidden_fields 422 $group.find('input,select,textarea').each(function () { 423 hidden_fields.push(jQuery(this).attr('name')); 424 }); 425 } 426 } else { 427 visible_groups.push($group.attr('data-id')); 428 } 429 }); 430 431 form.hidden_fields = hidden_fields; 432 form.hidden_groups = hidden_groups; 433 form.visible_groups = visible_groups; 434 435 form.$input_hidden_group_fields.val(JSON.stringify(hidden_fields)); 436 form.$input_hidden_groups.val(JSON.stringify(hidden_groups)); 437 form.$input_visible_groups.val(JSON.stringify(visible_groups)); 438 439 return true; 440}; 441Wpcf7cfForm.prototype.updateGroups = function() { 442 const form = this; 443 form.$groups = form.$form.find('[data-class="wpcf7cf_group"]'); 444 form.$groups.height('auto'); 445 form.conditions = window.wpcf7cf.get_nested_conditions(form); 446 447}; 448Wpcf7cfForm.prototype.updateEventListeners = function() { 449 450 const form = this; 451 452 // monitor input changes, and call displayFields() if something has changed 453 form.get('input, select, textarea, button').not('.wpcf7cf_add, .wpcf7cf_remove').off(wpcf7cf_change_events).on(wpcf7cf_change_events,form, function(e) { 454 window.wpcf7cf_updatingGroups = true; // while this is true, don't allow the form to be submitted. 455 const form = e.data; 456 clearTimeout(wpcf7cf_timeout); 457 wpcf7cf_timeout = setTimeout(function() { 458 window.wpcf7cf.updateMultistepState(form.multistep); 459 form.updateSimpleDom(); 460 form.displayFields(); 461 window.wpcf7cf_updatingGroups = false;
462 }, wpcf7cf_change_time_ms); 463 }); 464 465 466}; 467 468 469 470// matches an ISO date (YYYY-MM-DD) as submitted by CF7's [date] field 471const wpcf7cf_date_regex = /^\d{4}-\d{2}-\d{2}$/; 472function wpcf7cf_isDateString(v) { 473 return typeof v === 'string' && wpcf7cf_date_regex.test(v) && !isNaN(Date.parse(v)); 474} 475 476/** 477 * @global 478 * @namespace wpcf7cf 479 */ 480window.wpcf7cf = { 481 482 hideGroup : function($group, animate) { 483 484 }, 485 486 showGroup : function($group, animate) { 487 488 }, 489 490 updateRepeaterSubHTML : function(html, oldSuffix, newSuffix, parentRepeaters) { 491 const oldIndexes = oldSuffix.split('__'); 492 oldIndexes.shift(); // remove first empty element 493 const newIndexes = newSuffix.split('__'); 494 newIndexes.shift(); // remove first empty element 495 496 let returnHtml = html; 497 498 if ( 499 oldIndexes && newIndexes && 500 oldIndexes.length === parentRepeaters.length && 501 newIndexes.length === parentRepeaters.length 502 ) { 503 504 const parentRepeatersInfo = parentRepeaters.map((repeaterId, i) => { 505 return {[repeaterId.split('__')[0]]: [oldIndexes[i], newIndexes[i]]}; 506 }); 507 508 const length = parentRepeatersInfo.length; 509 510 let replacements = oldIndexes.map( (oldIndex, i) => { 511 return [ 512 '__'+oldIndexes.slice(0,length-i).join('__'), 513 '__'+newIndexes.slice(0,length-i).join('__'), 514 ]; 515 }); 516 517 518 for (let i=0; i<length ; i++) { 519 const id = Object.keys(parentRepeatersInfo[i])[0]; 520 const find = parentRepeatersInfo[i][id][0]; 521 const repl = parentRepeatersInfo[i][id][1]; 522 replacements.push([ 523 `<span class="wpcf7cf-index wpcf7cf__${id}">${find}<\\/span>`, 524 `<span class="wpcf7cf-index wpcf7cf__${id}">${repl}</span>` 525 ]); 526 } 527 528 replacements.forEach( ([oldSuffix, newSuffix]) => { 529 returnHtml = returnHtml.replace(new RegExp(oldSuffix,'g'), newSuffix); 530 }); 531 532 } 533 534 return returnHtml ; 535 }, 536 537 // keep this for backwards compatibility 538 initForm : function($forms) { 539 $forms.each(function(){ 540 const formElement = this; 541 // only add form is its class is "wpcf7-form" and if the form was not previously added 542 if ( 543 formElement.classList.contains('wpcf7-form') && 544 !wpcf7cf_forms.some((form)=>{ return form.$form.get(0) === formElement; }) 545 ) { 546 wpcf7cf_forms.push(new Wpcf7cfForm(formElement)); 547 } 548 }); 549 }, 550 551 getWpcf7cfForm : function ($form) { 552 const matched_forms = wpcf7cf_forms.filter((form)=>{ 553 return form.$form.get(0) === $form.get(0); 554 }); 555 if (matched_forms.length) { 556 return matched_forms[0]; 557 } 558 return false; 559 }, 560 561 get_nested_conditions : function(form) { 562 const conditions = form.initial_conditions; 563 //loop trough conditions. Then loop trough the dom, and each repeater we pass we should update all sub_values we encounter with __index 564 form.reloadSimpleDom(); 565 const groups = Object.values(form.simpleDom).filter(function(item, i) { 566 return item.type==='group'; 567 }); 568 569 let sub_conditions = []; 570 571 for(let i = 0; i < groups.length; i++) { 572 const g = groups[i]; 573 let relevant_conditions = conditions.filter(function(condition, i) { 574 return condition.then_field === g.original_name; 575 }); 576 577 relevant_conditions = relevant_conditions.map(function(item,i) { 578 return { 579 then_field : g.name, 580 and_rules : item.and_rules.map(function(and_rule, i) { 581 return { 582 if_field : and_rule.if_field+g.suffix, 583 if_value : and_rule.if_value, 584 operator : and_rule.operator
585 }; 586 }) 587 } 588 }); 589 590 sub_conditions = sub_conditions.concat(relevant_conditions); 591 } 592 return sub_conditions; 593 }, 594 595 get_simplified_dom_model : function(currentNode, simplified_dom = {}, parentGroups = [], parentRepeaters = []) { 596 597 598 const type = currentNode.classList && currentNode.classList.contains('wpcf7cf_repeater') ? 'repeater' : 599 currentNode.dataset.class == 'wpcf7cf_group' ? 'group' : 600 currentNode.className == 'wpcf7cf_step' ? 'step' : 601 currentNode.hasAttribute('name') ? 'input' : false; 602 603 let newParentRepeaters = [...parentRepeaters]; 604 let newParentGroups = [...parentGroups]; 605 606 if (type) { 607 608 const name = type === 'input' ? currentNode.getAttribute('name') : currentNode.dataset.id; 609 610 if (type === 'repeater') { 611 newParentRepeaters.push(name); 612 } 613 if (type === 'group') { 614 newParentGroups.push(name); 615 } 616 617 // skip _wpcf7 hidden fields 618 if (name.substring(0,6) === '_wpcf7') return {}; 619 620 const original_name = type === 'repeater' || type === 'group' ? currentNode.dataset.orig_data_id 621 : type === 'input' ? (currentNode.getAttribute('data-orig_name') || name) 622 : name; 623 624 const nameWithoutBrackets = name.replace('[]',''); 625 const originalNameWithoutBrackets = original_name.replace('[]',''); 626 627 const val = type === 'step' ? [currentNode.dataset.id.substring(5)] : []; 628 629 const suffix = nameWithoutBrackets.replace(originalNameWithoutBrackets, ''); 630 631 if (!simplified_dom[name]) { 632 // init entry 633 simplified_dom[name] = {name, type, original_name, suffix, val, parentGroups, parentRepeaters} 634 } 635 636 if (type === 'input') { 637 638 // skip unchecked checkboxes and radiobuttons 639 if ( (currentNode.type === 'checkbox' || currentNode.type === 'radio') && !currentNode.checked ) return {}; 640 641 // if multiselect, make sure to add all the values 642 if ( currentNode.multiple && currentNode.options ) { 643 simplified_dom[name].val = Object.values(currentNode.options).filter(o => o.selected).map(o => o.value) 644 } else { 645 simplified_dom[name].val.push(currentNode.value); 646 } 647 } 648 } 649 650 // can't use currentNode.children (because then field name cannot be "children") 651 const getter = Object.getOwnPropertyDescriptor(Element.prototype, "children").get; 652 const children = getter.call(currentNode); 653 654 Array.from(children).forEach(childNode => { 655 const dom = wpcf7cf.get_simplified_dom_model(childNode, simplified_dom, newParentGroups, newParentRepeaters); 656 simplified_dom = {...dom, ...simplified_dom} ; 657 }); 658 659 return simplified_dom; 660 }, 661 662 updateMultistepState: function (multistep) { 663 if (multistep == null) return; 664 if (multistep.form.$form.hasClass('submitting')) return; 665 666 // update hidden input field 667 668 const stepsData = { 669 currentStep : multistep.currentStep, 670 numSteps : multistep.numSteps, 671 fieldsInCurrentStep : multistep.getFieldsInStep(multistep.currentStep) 672 }; 673 multistep.form.$input_steps.val(JSON.stringify(stepsData)); 674 675 // update Buttons 676 multistep.$btn_prev.removeClass('disabled').attr('disabled', false); 677 multistep.$btn_next.removeClass('disabled').attr('disabled', false); 678 if (multistep.currentStep == multistep.numSteps) { 679 multistep.$btn_next.addClass('disabled').attr('disabled', true); 680 } 681 if (multistep.currentStep == 1) { 682 multistep.$btn_prev.addClass('disabled').attr('disabled', true); 683 } 684 685 const $current_step = multistep.$steps.eq(multistep.currentStep - 1); 686 const prev_text = $current_step.attr('data-prev-button-text'); 687 const next_text = $current_step.attr('data-next-button-text'); 688 if (prev_text !== undefined) multistep.$btn_prev.text(prev_text); 689 if (next_text !== undefined) multistep.$btn_next.text(next_text); 690 691 // replace next button with submit button on last step.
692 // TODO: make this depend on a setting 693 const $submit_button = multistep.form.$form.find('input[type="submit"]:last').eq(0); 694 const $ajax_loader = multistep.form.$form.find('.wpcf7-spinner').eq(0); 695 696 $submit_button.detach().prependTo(multistep.$btn_next.parent()); 697 $ajax_loader.detach().prependTo(multistep.$btn_next.parent()); 698 699 if (multistep.currentStep == multistep.numSteps) { 700 multistep.$btn_next.hide(); 701 $submit_button.show(); 702 } else { 703 $submit_button.hide(); 704 multistep.$btn_next.show(); 705 } 706 707 // update dots 708 const $dots = multistep.$dots.find('.dot'); 709 $dots.removeClass('active').removeClass('completed'); 710 for(let step = 1; step <= multistep.numSteps; step++) { 711 if (step < multistep.currentStep) { 712 $dots.eq(step-1).addClass('completed'); 713 } else if (step == multistep.currentStep) { 714 $dots.eq(step-1).addClass('active'); 715 } 716 } 717 718 }, 719 720 should_group_be_shown : function(condition, form) { 721 722 let show_group = true; 723 let atLeastOneFieldFound = false; 724 725 for (let and_rule_i = 0; and_rule_i < condition.and_rules.length; and_rule_i++) { 726 727 let condition_ok = false; 728 729 const condition_and_rule = condition.and_rules[and_rule_i]; 730 731 const inputField = form.getFieldByName(condition_and_rule.if_field); 732 733 if (!inputField) continue; // field not found 734 735 atLeastOneFieldFound = true; 736 737 const if_val = condition_and_rule.if_value; 738 let operator = condition_and_rule.operator; 739 740 //backwards compat 741 operator = operator === 'â¤' ? 'less than or equals' : operator; 742 operator = operator === 'â¥' ? 'greater than or equals' : operator; 743 operator = operator === '>' ? 'greater than' : operator; 744 operator = operator === '<' ? 'less than' : operator; 745 746 const $field = operator === 'function' && jQuery(`[name="${inputField.name}"]`).eq(0); 747 748 condition_ok = this.isConditionTrue(inputField.val,operator,if_val, $field); 749 750 show_group = show_group && condition_ok; 751 } 752 753 return show_group && atLeastOneFieldFound; 754 755 }, 756 757 isConditionTrue(values, operator, testValue='', $field=jQuery()) { 758 759 if (!Array.isArray(values)) { 760 values = [values]; 761 } 762 763 let condition_ok = false; // start by assuming that the condition is not met 764 765 // Considered EMPTY: [] [''] [null] ['',null] [,,''] 766 // Considered NOT EMPTY: [0] ['ab','c'] ['',0,null] 767 const valuesAreEmpty = values.length === 0 || values.every((v) => !v&&v!==0); // 0 is not considered empty 768 769 // special cases: [] equals '' => TRUE; [] not equals '' => FALSE 770 if (operator === 'equals' && testValue === '' && valuesAreEmpty) { 771 return true; 772 } 773 if (operator === 'not equals' && testValue === '' && valuesAreEmpty) { 774 return false; 775 } 776 777 if (valuesAreEmpty) { 778 if (operator === 'is empty') { 779 condition_ok = true; 780 } 781 } else { 782 if (operator === 'not empty') { 783 condition_ok = true; 784 } 785 } 786 787 const testValueNumber = isFinite(parseFloat(testValue)) ? parseFloat(testValue) : NaN; 788 const testValueIsDate = wpcf7cf_isDateString(testValue); 789 790 791 if (operator === 'not equals' || operator === 'not equals (regex)') { 792 // start by assuming that the condition is met 793 condition_ok = true; 794 } 795 796 if ( 797 operator === 'function' 798 && typeof window[testValue] == 'function' 799 && window[testValue]($field) // here we call the actual user defined function 800 ) { 801 condition_ok = true; 802 } 803 804 let regex_patt = /.*/i; // fallback regex pattern 805 let isValidRegex = true; 806 if (operator === 'equals (regex)' || operator === 'not equals (regex)') { 807 try { 808 regex_patt = new RegExp(testValue, 'i'); 809 } catch(e) { 810 isValidRegex = false;
811 } 812 } 813 814 815 for(let i = 0; i < values.length; i++) { 816 817 const value = values[i]; 818 819 const valueNumber = isFinite(parseFloat(value)) ? parseFloat(value) : NaN; 820 const valsAreNumbers = !isNaN(valueNumber) && !isNaN(testValueNumber); 821 822 // when both sides are ISO dates, compare chronologically instead of by parseFloat (which reads only the year) 823 const valueIsDate = wpcf7cf_isDateString(value); 824 const compareAsDates = testValueIsDate && valueIsDate; 825 const left = compareAsDates ? Date.parse(value) : valueNumber; 826 const right = compareAsDates ? Date.parse(testValue) : testValueNumber; 827 // a date on one side and a plain number on the other are not comparable 828 const comparable = compareAsDates || (valsAreNumbers && testValueIsDate === valueIsDate); 829 830 if ( 831 832 operator === 'equals' && value === testValue || 833 operator === 'equals (regex)' && regex_patt.test(value) || 834 operator === 'greater than' && comparable && left > right || 835 operator === 'less than' && comparable && left < right || 836 operator === 'greater than or equals' && comparable && left >= right || 837 operator === 'less than or equals' && comparable && left <= right 838 839 ) { 840 841 condition_ok = true; 842 break; 843 844 } else if ( 845 846 operator === 'not equals' && value === testValue || 847 operator === 'not equals (regex)' && regex_patt.test(value) 848 849 ) { 850 851 condition_ok = false; 852 break; 853 854 } 855 } 856 857 return condition_ok; 858 859 }, 860 861 getFormObj($form) { 862 if (typeof $form === 'string') { 863 $form = jQuery($form).eq(0); 864 } 865 return wpcf7cf.getWpcf7cfForm($form); 866 }, 867 868 getRepeaterObj($form, repeaterDataId) { 869 const form = wpcf7cf.getFormObj($form); 870 const repeater = form.repeaters.find( repeater => repeater.params.$repeater.attr('data-id') === repeaterDataId ); 871 872 return repeater; 873 874 }, 875 876 getMultiStepObj($form){ 877 const form = wpcf7cf.getFormObj($form); 878 return form.multistep; 879 }, 880 881 /** 882 * Append a new sub-entry to the repeater with the name `repeaterDataId` inside the form `$form` 883 * @memberof wpcf7cf 884 * @function wpcf7cf.repeaterAddSub 885 * @link 886 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 887 * @param {String} repeaterDataId - *data-id* attribute of the repeater. Normally this is simply the name of the repeater. However, in case of a nested repeater you need to append the name with the correct suffix. For example `my-nested-repeater__1__3`. Hint (check the `data-id` attribute in the HTML code to find the correct suffix) 888 */ 889 repeaterAddSub($form,repeaterDataId) { 890 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 891 repeater.updateSubs(repeater.params.$repeater.num_subs+1); 892 }, 893 894 /** 895 * Insert a new sub-entry at the given `index` of the repeater with the name `repeaterDataId` inside the form `$form` 896 * @memberof wpcf7cf 897 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 898 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 899 * @param {Number} index - position where to insert the new sub-entry within the repeater 900 */ 901 repeaterAddSubAtIndex($form,repeaterDataId,index) { 902 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 903 repeater.addSubs(1, index); 904 }, 905 906 /** 907 * Remove the sub-entry at the given `index` of the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form` 908 * @memberof wpcf7cf 909 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 910 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 911 * @param {Number} index - position where to insert the new sub-entry within the repeater 912 */ 913 repeaterRemoveSubAtIndex($form,repeaterDataId,index) { 914 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 915 repeater.removeSubs(1, index); 916 }, 917 918 /** 919 * Remove the last sub-entry from the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form` 920 * @memberof wpcf7cf 921 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 922 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 923 * @param {Number} index - position where to insert the new sub-entry within the repeater 924 */ 925 repeaterRemoveSub($form,repeaterDataId) { 926 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 927 repeater.updateSubs(repeater.params.$repeater.num_subs-1); 928 }, 929 930 /** 931 * Set the number of subs for the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`. 932 * Subs are either appended to or removed from the end of the repeater. 933 * @memberof wpcf7cf 934 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 935 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 936 * @param {Number} numberOfSubs - position where to insert the new sub-entry within the repeater 937 */ 938 repeaterSetNumberOfSubs($form, repeaterDataId, numberOfSubs) { 939 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 940 repeater.updateSubs(numberOfSubs); 941 }, 942 943 /** 944 * Move to step number `step`, ignoring any validation. 945 * @memberof wpcf7cf 946 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 947 * @param {*} step 948 */ 949 multistepMoveToStep($form, step) { 950 const multistep = wpcf7cf.getMultiStepObj($form); 951 multistep.moveToStep(step); 952 }, 953 954 /** 955 * Validate the current step, and move to step number `step` if val
955idation passes. 956 * @memberof wpcf7cf 957 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 958 * @param {Number} step 959 */ 960 async multistepMoveToStepWithValidation($form, step) { 961 const multistep = wpcf7cf.getMultiStepObj($form); 962 963 const result = await multistep.validateStep(multistep.currentStep); 964 if (result === 'success') { 965 multistep.moveToStep(step); 966 } 967 }, 968 969 970 971}; 972 973document.querySelectorAll('.wpcf7-form').forEach(function(formElement){ 974 wpcf7cf_forms.push(new Wpcf7cfForm(formElement)); 975}); 976 977// Call displayFields again on all forms 978// Necessary in case some theme or plugin changed a form value by the time the entire page is fully loaded. 979document.addEventListener('DOMContentLoaded', function () { 980 wpcf7cf_forms.forEach(function(f){ 981 f.displayFields(); 982 }); 983});
Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.