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 // drop CF7 validation errors on fields when group is hidden 306 $group.find('.wpcf7-not-valid-tip').remove(); 307 $group.find('[aria-invalid]').attr('aria-invalid', 'false'); 308 $group.find('.wpcf7-not-valid').removeClass('wpcf7-not-valid').each(function() { 309 jQuery(document.getElementById(this.getAttribute('aria-describedby'))).remove(); 310 this.removeAttribute('aria-describedby'); 311 if (typeof this.setCustomValidity === 'function') this.setCustomValidity(''); 312 }); 313 314 if ($group.prop('tagName') === 'SPAN') { 315 $group.show().trigger('wpcf7cf_show_group'); // show instantly 316 } else { 317 $group.animate(wpcf7cf_show_animation, animation_intime).trigger('wpcf7cf_show_group'); // show with animation 318 } 319 320 if($group.attr('data-disable_on_hide') !== undefined) { 321 $group.find(':input').prop('disabled', false).trigger('changedisabledprop.wpcf7cf'); 322 $group.find('.wpcf7-form-control-wrap').removeClass('wpcf7cf-disabled'); 323 } 324 325 } else if ($group.css('display') !== 'none' && $group.hasClass('wpcf7cf-hidden')) { 326 327 if ($group.attr('data-clear_on_hide') !== undefined) { 328 const $inputs = jQuery(':input', $group).not(':button, :submit, :reset, :hidden'); 329 330 $inputs.each(function(){ 331 const $this = jQuery(this); 332 $this.val(this.defaultValue); 333 $this.prop('checked', this.defaultChecked); 334 }); 335 336 jQuery('option', $group).each(function() { 337 this.selected = this.defaultSelected; 338 }); 339 340 jQuery('select', $group).each(function() { 341 const $select = jQuery(this); 342 if ($select.val() === null) { 343 $select.val(jQuery("option:first",$select).val()); 344 } 345 }); 346 347 $inputs.each(function(){this.dispatchEvent(new Event("change",{"bubbles":true}))}); 348 } 349 350 if ($group.prop('tagName') === 'SPAN') { 351 $group.hide().trigger('wpcf7cf_hide_group'); 352 } else { 353 $group.animate(wpcf7cf_hide_animation, animation_outtime).trigger('wpcf7cf_hide_group'); // hide 354 } 355 } 356 }); 357 358 form.updateHiddenFields(); 359 360 form.updateSummaryFields(); 361}; 362 363 364 365Wpcf7cfForm.prototype.updateSummaryFields = function() { 366 const form = this; 367 const $summary = form.get('.wpcf7cf-summary'); 368 369 if ($summary.length == 0 || !$summary.is(':visible')) { 370 return; 371 } 372 373 const fd = new FormData(); 374 375 const formdata = form.$form.serializeArray(); 376 jQuery.each(formdata,function(key, input){ 377 fd.append(input.name, input.value); 378 }); 379 380 // Make sure to add file fields to FormData 381 jQuery.each(form.$form.find('input[type="file"]'), function(index, el) { 382 if (! el.files.length) return true; // continue 383 const fieldName = el.name; 384 fd.append(fieldName, new Blob() , Array.from(el.files).map(file => file.name).join(', ')); 385 }); 386 387 // add file fields to form-data 388 389 jQuery.ajax({ 390 url: wpcf7cf_global_settings.ajaxurl + '?action=wpcf7cf_get_summary', 391 type: 'POST', 392 data: fd, 393 processData: false, 394 contentType: false, 395 dataType: 'json', 396 success: function(json) { 397 $summary.html(json.summaryHtml); 398 } 399 }); 400}; 401 402Wpcf7cfForm.prototype.updateHiddenFields = function() { 403 404 const form = this; 405 406 const hidden_fields = []; 407 const hidden_groups = []; 408 const visible_groups = []; 409 410 form.$groups.each(function () { 411 const $group = jQuery(this); 412 if ($group.hasClass('wpcf7cf-hidden')) { 413 hidden_groups.push($group.attr('data-id')); 414 if($group.attr('data-disable_on_hide') !== undefined) { 415 // fields inside hidden disable_on_hide group 416 $group.find('input,select,textarea').each(function(){ 417 const $this = jQuery(this); 418 if (!$this.prop('disabled')) { 419 $this.prop('disabled', true).trigger('changedisabledprop.wpcf7cf'); 420 } 421 422 // if there's no other field with the same name visible in the form 423 // then push this field to hidden_fields 424 if (form.$form.find(`[data-class="wpcf7cf_group"]:not(.wpcf7cf-hidden) [name='${$this.attr('name')}']`).length === 0) { 425 hidden_fields.push($this.attr('name')); 426 } 427 }) 428 $group.find('.wpcf7-form-control-wrap').addClass('wpcf7cf-disabled'); 429 } else { 430 // fields inside regular hidden group are all pushed to hidden_fields 431 $group.find('input,select,textarea').each(function () { 432 hidden_fields.push(jQuery(this).attr('name')); 433 }); 434 } 435 } else { 436 visible_groups.push($group.attr('data-id')); 437 } 438 }); 439 440 form.hidden_fields = hidden_fields; 441 form.hidden_groups = hidden_groups; 442 form.visible_groups = visible_groups; 443 444 form.$input_hidden_group_fields.val(JSON.stringify(hidden_fields)); 445 form.$input_hidden_groups.val(JSON.stringify(hidden_groups)); 446 form.$input_visible_groups.val(JSON.stringify(visible_groups)); 447 448 return true; 449}; 450Wpcf7cfForm.prototype.updateGroups = function() { 451 const form = this; 452 form.$groups = form.$form.find('[data-class="wpcf7cf_group"]'); 453 form.$groups.height('auto'); 454 form.conditions = window.wpcf7cf.get_nested_conditions(form); 455 456}; 457Wpcf7cfForm.prototype.updateEventListeners = function() { 458 459 const form = this; 460 461 // monitor input changes, and call displayFields() if something has changed 462 form.get('input, select, textarea, button').not('.wpcf7cf_add, .wpcf7cf_remove').off(wpcf7cf_change_events).on(wpcf7cf_change_events,form, function(e) { 463 window.wpcf7cf_updatingGroups = true; // while this is true, don't allow the form to be submitted. 464 const form = e.data; 465 clearTimeout(wpcf7cf_timeout); 466 wpcf7cf_timeout = setTimeout(function() { 467 window.wpcf7cf.updateMultistepState(form.multistep); 468 form.updateSimpleDom(); 469 form.displayFields(); 470 window.wpcf7cf_updatingGroups = false;
471 }, wpcf7cf_change_time_ms); 472 }); 473 474 475}; 476 477 478 479// matches an ISO date (YYYY-MM-DD) as submitted by CF7's [date] field 480const wpcf7cf_date_regex = /^\d{4}-\d{2}-\d{2}$/; 481function wpcf7cf_isDateString(v) { 482 return typeof v === 'string' && wpcf7cf_date_regex.test(v) && !isNaN(Date.parse(v)); 483} 484 485/** 486 * @global 487 * @namespace wpcf7cf 488 */ 489window.wpcf7cf = { 490 491 hideGroup : function($group, animate) { 492 493 }, 494 495 showGroup : function($group, animate) { 496 497 }, 498 499 updateRepeaterSubHTML : function(html, oldSuffix, newSuffix, parentRepeaters) { 500 const oldIndexes = oldSuffix.split('__'); 501 oldIndexes.shift(); // remove first empty element 502 const newIndexes = newSuffix.split('__'); 503 newIndexes.shift(); // remove first empty element 504 505 let returnHtml = html; 506 507 if ( 508 oldIndexes && newIndexes && 509 oldIndexes.length === parentRepeaters.length && 510 newIndexes.length === parentRepeaters.length 511 ) { 512 513 const parentRepeatersInfo = parentRepeaters.map((repeaterId, i) => { 514 return {[repeaterId.split('__')[0]]: [oldIndexes[i], newIndexes[i]]}; 515 }); 516 517 const length = parentRepeatersInfo.length; 518 519 let replacements = oldIndexes.map( (oldIndex, i) => { 520 return [ 521 '__'+oldIndexes.slice(0,length-i).join('__'), 522 '__'+newIndexes.slice(0,length-i).join('__'), 523 ]; 524 }); 525 526 527 for (let i=0; i<length ; i++) { 528 const id = Object.keys(parentRepeatersInfo[i])[0]; 529 const find = parentRepeatersInfo[i][id][0]; 530 const repl = parentRepeatersInfo[i][id][1]; 531 replacements.push([ 532 `<span class="wpcf7cf-index wpcf7cf__${id}">${find}<\\/span>`, 533 `<span class="wpcf7cf-index wpcf7cf__${id}">${repl}</span>` 534 ]); 535 } 536 537 replacements.forEach( ([oldSuffix, newSuffix]) => { 538 returnHtml = returnHtml.replace(new RegExp(oldSuffix,'g'), newSuffix); 539 }); 540 541 } 542 543 return returnHtml ; 544 }, 545 546 // keep this for backwards compatibility 547 initForm : function($forms) { 548 $forms.each(function(){ 549 const formElement = this; 550 // only add form is its class is "wpcf7-form" and if the form was not previously added 551 if ( 552 formElement.classList.contains('wpcf7-form') && 553 !wpcf7cf_forms.some((form)=>{ return form.$form.get(0) === formElement; }) 554 ) { 555 wpcf7cf_forms.push(new Wpcf7cfForm(formElement)); 556 } 557 }); 558 }, 559 560 getWpcf7cfForm : function ($form) { 561 const matched_forms = wpcf7cf_forms.filter((form)=>{ 562 return form.$form.get(0) === $form.get(0); 563 }); 564 if (matched_forms.length) { 565 return matched_forms[0]; 566 } 567 return false; 568 }, 569 570 get_nested_conditions : function(form) { 571 const conditions = form.initial_conditions; 572 //loop trough conditions. Then loop trough the dom, and each repeater we pass we should update all sub_values we encounter with __index 573 form.reloadSimpleDom(); 574 const groups = Object.values(form.simpleDom).filter(function(item, i) { 575 return item.type==='group'; 576 }); 577 578 let sub_conditions = []; 579 580 for(let i = 0; i < groups.length; i++) { 581 const g = groups[i]; 582 let relevant_conditions = conditions.filter(function(condition, i) { 583 return condition.then_field === g.original_name; 584 }); 585 586 relevant_conditions = relevant_conditions.map(function(item,i) { 587 return { 588 then_field : g.name, 589 and_rules : item.and_rules.map(function(and_rule, i) { 590 return { 591 if_field : and_rule.if_field+g.suffix, 592 if_value : and_rule.if_value, 593 operator : and_rule.operator
594 }; 595 }) 596 } 597 }); 598 599 sub_conditions = sub_conditions.concat(relevant_conditions); 600 } 601 return sub_conditions; 602 }, 603 604 get_simplified_dom_model : function(currentNode, simplified_dom = {}, parentGroups = [], parentRepeaters = []) { 605 606 607 const type = currentNode.classList && currentNode.classList.contains('wpcf7cf_repeater') ? 'repeater' : 608 currentNode.dataset.class == 'wpcf7cf_group' ? 'group' : 609 currentNode.className == 'wpcf7cf_step' ? 'step' : 610 currentNode.hasAttribute('name') ? 'input' : false; 611 612 let newParentRepeaters = [...parentRepeaters]; 613 let newParentGroups = [...parentGroups]; 614 615 if (type) { 616 617 const name = type === 'input' ? currentNode.getAttribute('name') : currentNode.dataset.id; 618 619 if (type === 'repeater') { 620 newParentRepeaters.push(name); 621 } 622 if (type === 'group') { 623 newParentGroups.push(name); 624 } 625 626 // skip _wpcf7 hidden fields 627 if (name.substring(0,6) === '_wpcf7') return {}; 628 629 const original_name = type === 'repeater' || type === 'group' ? currentNode.dataset.orig_data_id 630 : type === 'input' ? (currentNode.getAttribute('data-orig_name') || name) 631 : name; 632 633 const nameWithoutBrackets = name.replace('[]',''); 634 const originalNameWithoutBrackets = original_name.replace('[]',''); 635 636 const val = type === 'step' ? [currentNode.dataset.id.substring(5)] : []; 637 638 const suffix = nameWithoutBrackets.replace(originalNameWithoutBrackets, ''); 639 640 if (!simplified_dom[name]) { 641 // init entry 642 simplified_dom[name] = {name, type, original_name, suffix, val, parentGroups, parentRepeaters} 643 } 644 645 if (type === 'input') { 646 647 // skip unchecked checkboxes and radiobuttons 648 if ( (currentNode.type === 'checkbox' || currentNode.type === 'radio') && !currentNode.checked ) return {}; 649 650 // if multiselect, make sure to add all the values 651 if ( currentNode.multiple && currentNode.options ) { 652 simplified_dom[name].val = Object.values(currentNode.options).filter(o => o.selected).map(o => o.value) 653 } else { 654 simplified_dom[name].val.push(currentNode.value); 655 } 656 } 657 } 658 659 // can't use currentNode.children (because then field name cannot be "children") 660 const getter = Object.getOwnPropertyDescriptor(Element.prototype, "children").get; 661 const children = getter.call(currentNode); 662 663 Array.from(children).forEach(childNode => { 664 const dom = wpcf7cf.get_simplified_dom_model(childNode, simplified_dom, newParentGroups, newParentRepeaters); 665 simplified_dom = {...dom, ...simplified_dom} ; 666 }); 667 668 return simplified_dom; 669 }, 670 671 updateMultistepState: function (multistep) { 672 if (multistep == null) return; 673 if (multistep.form.$form.hasClass('submitting')) return; 674 675 // update hidden input field 676 677 const stepsData = { 678 currentStep : multistep.currentStep, 679 numSteps : multistep.numSteps, 680 fieldsInCurrentStep : multistep.getFieldsInStep(multistep.currentStep) 681 }; 682 multistep.form.$input_steps.val(JSON.stringify(stepsData)); 683 684 // update Buttons 685 multistep.$btn_prev.removeClass('disabled').attr('disabled', false); 686 multistep.$btn_next.removeClass('disabled').attr('disabled', false); 687 if (multistep.currentStep == multistep.numSteps) { 688 multistep.$btn_next.addClass('disabled').attr('disabled', true); 689 } 690 if (multistep.currentStep == 1) { 691 multistep.$btn_prev.addClass('disabled').attr('disabled', true); 692 } 693 694 const $current_step = multistep.$steps.eq(multistep.currentStep - 1); 695 const prev_text = $current_step.attr('data-prev-button-text'); 696 const next_text = $current_step.attr('data-next-button-text'); 697 if (prev_text !== undefined) multistep.$btn_prev.text(prev_text); 698 if (next_text !== undefined) multistep.$btn_next.text(next_text); 699 700 // replace next button with submit button on last step.
701 // TODO: make this depend on a setting 702 const $submit_button = multistep.form.$form.find('input[type="submit"]:last').eq(0); 703 const $ajax_loader = multistep.form.$form.find('.wpcf7-spinner').eq(0); 704 705 $submit_button.detach().prependTo(multistep.$btn_next.parent()); 706 $ajax_loader.detach().prependTo(multistep.$btn_next.parent()); 707 708 if (multistep.currentStep == multistep.numSteps) { 709 multistep.$btn_next.hide(); 710 $submit_button.show(); 711 } else { 712 $submit_button.hide(); 713 multistep.$btn_next.show(); 714 } 715 716 // update dots 717 const $dots = multistep.$dots.find('.dot'); 718 $dots.removeClass('active').removeClass('completed'); 719 for(let step = 1; step <= multistep.numSteps; step++) { 720 if (step < multistep.currentStep) { 721 $dots.eq(step-1).addClass('completed'); 722 } else if (step == multistep.currentStep) { 723 $dots.eq(step-1).addClass('active'); 724 } 725 } 726 727 }, 728 729 should_group_be_shown : function(condition, form) { 730 731 let show_group = true; 732 let atLeastOneFieldFound = false; 733 734 for (let and_rule_i = 0; and_rule_i < condition.and_rules.length; and_rule_i++) { 735 736 let condition_ok = false; 737 738 const condition_and_rule = condition.and_rules[and_rule_i]; 739 740 const inputField = form.getFieldByName(condition_and_rule.if_field); 741 742 if (!inputField) continue; // field not found 743 744 atLeastOneFieldFound = true; 745 746 const if_val = condition_and_rule.if_value; 747 let operator = condition_and_rule.operator; 748 749 //backwards compat 750 operator = operator === 'â¤' ? 'less than or equals' : operator; 751 operator = operator === 'â¥' ? 'greater than or equals' : operator; 752 operator = operator === '>' ? 'greater than' : operator; 753 operator = operator === '<' ? 'less than' : operator; 754 755 const $field = operator === 'function' && jQuery(`[name="${inputField.name}"]`).eq(0); 756 757 condition_ok = this.isConditionTrue(inputField.val,operator,if_val, $field); 758 759 show_group = show_group && condition_ok; 760 } 761 762 return show_group && atLeastOneFieldFound; 763 764 }, 765 766 isConditionTrue(values, operator, testValue='', $field=jQuery()) { 767 768 if (!Array.isArray(values)) { 769 values = [values]; 770 } 771 772 let condition_ok = false; // start by assuming that the condition is not met 773 774 // Considered EMPTY: [] [''] [null] ['',null] [,,''] 775 // Considered NOT EMPTY: [0] ['ab','c'] ['',0,null] 776 const valuesAreEmpty = values.length === 0 || values.every((v) => !v&&v!==0); // 0 is not considered empty 777 778 // special cases: [] equals '' => TRUE; [] not equals '' => FALSE 779 if (operator === 'equals' && testValue === '' && valuesAreEmpty) { 780 return true; 781 } 782 if (operator === 'not equals' && testValue === '' && valuesAreEmpty) { 783 return false; 784 } 785 786 if (valuesAreEmpty) { 787 if (operator === 'is empty') { 788 condition_ok = true; 789 } 790 } else { 791 if (operator === 'not empty') { 792 condition_ok = true; 793 } 794 } 795 796 const testValueNumber = isFinite(parseFloat(testValue)) ? parseFloat(testValue) : NaN; 797 const testValueIsDate = wpcf7cf_isDateString(testValue); 798 799 800 if (operator === 'not equals' || operator === 'not equals (regex)') { 801 // start by assuming that the condition is met 802 condition_ok = true; 803 } 804 805 if ( 806 operator === 'function' 807 && typeof window[testValue] == 'function' 808 && window[testValue]($field) // here we call the actual user defined function 809 ) { 810 condition_ok = true; 811 } 812 813 let regex_patt = /.*/i; // fallback regex pattern 814 let isValidRegex = true; 815 if (operator === 'equals (regex)' || operator === 'not equals (regex)') { 816 try { 817 regex_patt = new RegExp(testValue, 'i'); 818 } catch(e) { 819 isValidRegex = false;
820 } 821 } 822 823 824 for(let i = 0; i < values.length; i++) { 825 826 const value = values[i]; 827 828 const valueNumber = isFinite(parseFloat(value)) ? parseFloat(value) : NaN; 829 const valsAreNumbers = !isNaN(valueNumber) && !isNaN(testValueNumber); 830 831 // when both sides are ISO dates, compare chronologically instead of by parseFloat (which reads only the year) 832 const valueIsDate = wpcf7cf_isDateString(value); 833 const compareAsDates = testValueIsDate && valueIsDate; 834 const left = compareAsDates ? Date.parse(value) : valueNumber; 835 const right = compareAsDates ? Date.parse(testValue) : testValueNumber; 836 // a date on one side and a plain number on the other are not comparable 837 const comparable = compareAsDates || (valsAreNumbers && testValueIsDate === valueIsDate); 838 839 if ( 840 841 operator === 'equals' && value === testValue || 842 operator === 'equals (regex)' && regex_patt.test(value) || 843 operator === 'greater than' && comparable && left > right || 844 operator === 'less than' && comparable && left < right || 845 operator === 'greater than or equals' && comparable && left >= right || 846 operator === 'less than or equals' && comparable && left <= right 847 848 ) { 849 850 condition_ok = true; 851 break; 852 853 } else if ( 854 855 operator === 'not equals' && value === testValue || 856 operator === 'not equals (regex)' && regex_patt.test(value) 857 858 ) { 859 860 condition_ok = false; 861 break; 862 863 } 864 } 865 866 return condition_ok; 867 868 }, 869 870 getFormObj($form) { 871 if (typeof $form === 'string') { 872 $form = jQuery($form).eq(0); 873 } 874 return wpcf7cf.getWpcf7cfForm($form); 875 }, 876 877 getRepeaterObj($form, repeaterDataId) { 878 const form = wpcf7cf.getFormObj($form); 879 const repeater = form.repeaters.find( repeater => repeater.params.$repeater.attr('data-id') === repeaterDataId ); 880 881 return repeater; 882 883 }, 884 885 getMultiStepObj($form){ 886 const form = wpcf7cf.getFormObj($form); 887 return form.multistep; 888 }, 889 890 /** 891 * Append a new sub-entry to the repeater with the name `repeaterDataId` inside the form `$form` 892 * @memberof wpcf7cf 893 * @function wpcf7cf.repeaterAddSub 894 * @link 895 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 896 * @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) 897 */ 898 repeaterAddSub($form,repeaterDataId) { 899 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 900 repeater.updateSubs(repeater.params.$repeater.num_subs+1); 901 }, 902 903 /** 904 * Insert a new sub-entry at the given `index` of the repeater with the name `repeaterDataId` inside the form `$form` 905 * @memberof wpcf7cf 906 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 907 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 908 * @param {Number} index - position where to insert the new sub-entry within the repeater 909 */ 910 repeaterAddSubAtIndex($form,repeaterDataId,index) { 911 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 912 repeater.addSubs(1, index); 913 }, 914 915 /** 916 * Remove the sub-entry at the given `index` of the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form` 917 * @memberof wpcf7cf 918 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 919 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 920 * @param {Number} index - position where to insert the new sub-entry within the repeater 921 */ 922 repeaterRemoveSubAtIndex($form,repeaterDataId,index) { 923 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 924 repeater.removeSubs(1, index); 925 }, 926 927 /** 928 * Remove the last sub-entry from the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form` 929 * @memberof wpcf7cf 930 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 931 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 932 * @param {Number} index - position where to insert the new sub-entry within the repeater 933 */ 934 repeaterRemoveSub($form,repeaterDataId) { 935 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 936 repeater.updateSubs(repeater.params.$repeater.num_subs-1); 937 }, 938 939 /** 940 * Set the number of subs for the repeater with the *data-id* attribute of `repeaterDataId` inside the form `$form`. 941 * Subs are either appended to or removed from the end of the repeater. 942 * @memberof wpcf7cf 943 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 944 * @param {String} repeaterDataId - *data-id* attribute of the repeater. 945 * @param {Number} numberOfSubs - position where to insert the new sub-entry within the repeater 946 */ 947 repeaterSetNumberOfSubs($form, repeaterDataId, numberOfSubs) { 948 const repeater = wpcf7cf.getRepeaterObj($form, repeaterDataId); 949 repeater.updateSubs(numberOfSubs); 950 }, 951 952 /** 953 * Move to step number `step`, ignoring any validation. 954 * @memberof wpcf7cf 955 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 956 * @param {*} step 957 */ 958 multistepMoveToStep($form, step) { 959 const multistep = wpcf7cf.getMultiStepObj($form); 960 multistep.moveToStep(step); 961 }, 962 963 /** 964 * Validate the current step, and move to step number `step` if val
964idation passes. 965 * @memberof wpcf7cf 966 * @param {String|JQuery} $form - JQuery object or css-selector representing the form 967 * @param {Number} step 968 */ 969 async multistepMoveToStepWithValidation($form, step) { 970 const multistep = wpcf7cf.getMultiStepObj($form); 971 972 const result = await multistep.validateStep(multistep.currentStep); 973 if (result === 'success') { 974 multistep.moveToStep(step); 975 } 976 }, 977 978 979 980}; 981 982document.querySelectorAll('.wpcf7-form').forEach(function(formElement){ 983 wpcf7cf_forms.push(new Wpcf7cfForm(formElement)); 984}); 985 986// Call displayFields again on all forms 987// Necessary in case some theme or plugin changed a form value by the time the entire page is fully loaded. 988document.addEventListener('DOMContentLoaded', function () { 989 wpcf7cf_forms.forEach(function(f){ 990 f.displayFields(); 991 }); 992});
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.