admin/admin-editor.js 0000644 00000003040 15171647003 0010547 0 ustar 00 ;( function( $ ) { $( function() { // Close modal. var wpformsModalClose = function() { if ( $( '#wpforms-modal-select-form' ).length ) { $( '#wpforms-modal-select-form' ).get( 0 ).selectedIndex = 0; $( '#wpforms-modal-checkbox-title, #wpforms-modal-checkbox-description' ).prop( 'checked', false ); } $( '#wpforms-modal-backdrop, #wpforms-modal-wrap' ).css( 'display', 'none' ); $( document.body ).removeClass( 'modal-open' ); }; // Open modal when media button is clicked. $( document ).on( 'click', '.wpforms-insert-form-button', function( event ) { event.preventDefault(); $( '#wpforms-modal-backdrop, #wpforms-modal-wrap' ).css( 'display', 'block' ); $( document.body ).addClass( 'modal-open' ); } ); // Close modal on close or cancel links. $( document ).on( 'click', '#wpforms-modal-close, #wpforms-modal-cancel a', function( event ) { event.preventDefault(); wpformsModalClose(); } ); // Insert shortcode into TinyMCE. $( document ).on( 'click', '#wpforms-modal-submit', function( event ) { event.preventDefault(); var shortcode; shortcode = '[wpforms id="' + $( '#wpforms-modal-select-form' ).val() + '"'; if ( $( '#wpforms-modal-checkbox-title' ).is( ':checked' ) ) { shortcode = shortcode + ' title="true"'; } if ( $( '#wpforms-modal-checkbox-description' ).is( ':checked' ) ) { shortcode = shortcode + ' description="true"'; } shortcode = shortcode + ']'; wp.media.editor.insert( shortcode ); wpformsModalClose(); } ); } ); }( jQuery ) ); admin/admin-editor.min.js 0000644 00000001741 15171647003 0011337 0 ustar 00 !function(c){c(function(){function e(){c("#wpforms-modal-select-form").length&&(c("#wpforms-modal-select-form").get(0).selectedIndex=0,c("#wpforms-modal-checkbox-title, #wpforms-modal-checkbox-description").prop("checked",!1)),c("#wpforms-modal-backdrop, #wpforms-modal-wrap").css("display","none"),c(document.body).removeClass("modal-open")}c(document).on("click",".wpforms-insert-form-button",function(o){o.preventDefault(),c("#wpforms-modal-backdrop, #wpforms-modal-wrap").css("display","block"),c(document.body).addClass("modal-open")}),c(document).on("click","#wpforms-modal-close, #wpforms-modal-cancel a",function(o){o.preventDefault(),e()}),c(document).on("click","#wpforms-modal-submit",function(o){o.preventDefault(),o='[wpforms id="'+c("#wpforms-modal-select-form").val()+'"',c("#wpforms-modal-checkbox-title").is(":checked")&&(o+=' title="true"'),c("#wpforms-modal-checkbox-description").is(":checked")&&(o+=' description="true"'),o+="]",wp.media.editor.insert(o),e()})})}(jQuery); admin/admin-notifications.js 0000644 00000007504 15171647003 0012143 0 ustar 00 /* global wpforms_admin, WPFormsAdmin */ /** * WPForms Admin Notifications. * * @since 1.6.0 */ 'use strict'; var WPFormsAdminNotifications = window.WPFormsAdminNotifications || ( function( document, window, $ ) { /** * Elements holder. * * @since 1.6.0 * * @type {object} */ var el = { $notifications: $( '#wpforms-notifications' ), $nextButton: $( '#wpforms-notifications .navigation .next' ), $prevButton: $( '#wpforms-notifications .navigation .prev' ), $adminBarCounter: $( '#wp-admin-bar-wpforms-menu .wpforms-menu-notification-counter' ), $adminBarMenuItem: $( '#wp-admin-bar-wpforms-notifications' ), }; /** * Public functions and properties. * * @since 1.6.0 * * @type {object} */ var app = { /** * Start the engine. * * @since 1.6.0 */ init: function() { $( app.ready ); }, /** * Document ready. * * @since 1.6.0 */ ready: function() { app.updateNavigation(); app.events(); }, /** * Register JS events. * * @since 1.6.0 */ events: function() { el.$notifications .on( 'click', '.dismiss', app.dismiss ) .on( 'click', '.next', app.navNext ) .on( 'click', '.prev', app.navPrev ); }, /** * Click on the Dismiss notification button. * * @since 1.6.0 * * @param {object} event Event object. */ dismiss: function( event ) { if ( el.$currentMessage.length === 0 ) { return; } // Update counter. var count = parseInt( el.$adminBarCounter.text(), 10 ); if ( count > 1 ) { --count; el.$adminBarCounter.html( count ); } else { el.$adminBarCounter.remove(); el.$adminBarMenuItem.remove(); } // Remove notification. var $nextMessage = el.$nextMessage.length < 1 ? el.$prevMessage : el.$nextMessage, messageId = el.$currentMessage.data( 'message-id' ); if ( $nextMessage.length === 0 ) { el.$notifications.remove(); } else { el.$currentMessage.remove(); $nextMessage.addClass( 'current' ); app.updateNavigation(); } // AJAX call - update option. var data = { action: 'wpforms_notification_dismiss', nonce: wpforms_admin.nonce, id: messageId, }; $.post( wpforms_admin.ajax_url, data, function( res ) { if ( ! res.success ) { WPFormsAdmin.debug( res ); } } ).fail( function( xhr, textStatus, e ) { WPFormsAdmin.debug( xhr.responseText ); } ); }, /** * Click on the Next notification button. * * @since 1.6.0 * * @param {object} event Event object. */ navNext: function( event ) { if ( el.$nextButton.hasClass( 'disabled' ) ) { return; } el.$currentMessage.removeClass( 'current' ); el.$nextMessage.addClass( 'current' ); app.updateNavigation(); }, /** * Click on the Previous notification button. * * @since 1.6.0 * * @param {object} event Event object. */ navPrev: function( event ) { if ( el.$prevButton.hasClass( 'disabled' ) ) { return; } el.$currentMessage.removeClass( 'current' ); el.$prevMessage.addClass( 'current' ); app.updateNavigation(); }, /** * Update navigation buttons. * * @since 1.6.0 */ updateNavigation: function() { el.$currentMessage = el.$notifications.find( '.wpforms-notifications-message.current' ); el.$nextMessage = el.$currentMessage.next( '.wpforms-notifications-message' ); el.$prevMessage = el.$currentMessage.prev( '.wpforms-notifications-message' ); if ( el.$nextMessage.length === 0 ) { el.$nextButton.addClass( 'disabled' ); } else { el.$nextButton.removeClass( 'disabled' ); } if ( el.$prevMessage.length === 0 ) { el.$prevButton.addClass( 'disabled' ); } else { el.$prevButton.removeClass( 'disabled' ); } }, }; return app; }( document, window, jQuery ) ); // Initialize. WPFormsAdminNotifications.init(); admin/admin-notifications.min.js 0000644 00000004006 15171647003 0012717 0 ustar 00 "use strict";var WPFormsAdminNotifications=window.WPFormsAdminNotifications||function(t){var i={$notifications:t("#wpforms-notifications"),$nextButton:t("#wpforms-notifications .navigation .next"),$prevButton:t("#wpforms-notifications .navigation .prev"),$adminBarCounter:t("#wp-admin-bar-wpforms-menu .wpforms-menu-notification-counter"),$adminBarMenuItem:t("#wp-admin-bar-wpforms-notifications")},a={init:function(){t(a.ready)},ready:function(){a.updateNavigation(),a.events()},events:function(){i.$notifications.on("click",".dismiss",a.dismiss).on("click",".next",a.navNext).on("click",".prev",a.navPrev)},dismiss:function(e){var n,s;0!==i.$currentMessage.length&&(1<(s=parseInt(i.$adminBarCounter.text(),10))?i.$adminBarCounter.html(--s):(i.$adminBarCounter.remove(),i.$adminBarMenuItem.remove()),s=i.$nextMessage.length<1?i.$prevMessage:i.$nextMessage,n=i.$currentMessage.data("message-id"),0===s.length?i.$notifications.remove():(i.$currentMessage.remove(),s.addClass("current"),a.updateNavigation()),s={action:"wpforms_notification_dismiss",nonce:wpforms_admin.nonce,id:n},t.post(wpforms_admin.ajax_url,s,function(e){e.success||WPFormsAdmin.debug(e)}).fail(function(e,n,s){WPFormsAdmin.debug(e.responseText)}))},navNext:function(e){i.$nextButton.hasClass("disabled")||(i.$currentMessage.removeClass("current"),i.$nextMessage.addClass("current"),a.updateNavigation())},navPrev:function(e){i.$prevButton.hasClass("disabled")||(i.$currentMessage.removeClass("current"),i.$prevMessage.addClass("current"),a.updateNavigation())},updateNavigation:function(){i.$currentMessage=i.$notifications.find(".wpforms-notifications-message.current"),i.$nextMessage=i.$currentMessage.next(".wpforms-notifications-message"),i.$prevMessage=i.$currentMessage.prev(".wpforms-notifications-message"),0===i.$nextMessage.length?i.$nextButton.addClass("disabled"):i.$nextButton.removeClass("disabled"),0===i.$prevMessage.length?i.$prevButton.addClass("disabled"):i.$prevButton.removeClass("disabled")}};return a}((document,window,jQuery));WPFormsAdminNotifications.init(); admin/admin.js 0000644 00000230231 15171647003 0007267 0 ustar 00 /* global wpforms_admin, jconfirm, wpCookies, Choices, List, wpf */ /** * @param wpforms_admin.recreating * @param wpforms_admin.testing */ ( function( $ ) { 'use strict'; // Global settings access. var s; // Admin object. var WPFormsAdmin = { // Settings. settings: { iconActivate: '', iconDeactivate: '', iconInstall: '', iconSpinner: '', mediaFrame: false, }, /** * Start the engine. * * @since 1.3.9 */ init: function() { // Settings shortcut. s = this.settings; // Document ready. $( WPFormsAdmin.ready ); // Entries Single (Details). WPFormsAdmin.initEntriesSingle(); // Entries List. WPFormsAdmin.initEntriesList(); // Welcome activation. WPFormsAdmin.initWelcome(); // Addons List. $( document ).on( 'wpformsReady', WPFormsAdmin.initAddons ); // Settings. WPFormsAdmin.initSettings(); // Tools. WPFormsAdmin.initTools(); // Upgrades (Tools view). WPFormsAdmin.initUpgrades(); // Tab menu. WPFormsAdmin.initScrollableMenu(); }, /** * Document ready. * * @since 1.3.9 */ ready: function() { // Add `_wp_http_referer` to the data of every AJAX request. $.ajaxSetup( { data: { // eslint-disable-next-line camelcase _wp_http_referer: wpf.updateQueryString( '_wp_http_referer', null ), }, } ); // Scroll to integration. WPFormsAdmin.scrollToIntegration(); // To prevent jumping (since WP core moves the notices with js), // they are hidden initially with CSS, then revealed below with JS, // which runs after they have been moved. $( '.notice' ).show(); // If there are screen options we have to move them. $( '#screen-meta-links, #screen-meta' ).prependTo( '#wpforms-header-temp' ).show(); // Init fancy selects via choices.js. WPFormsAdmin.initChoicesJS(); // Reinit ChoicesJS after htmx swap. $( document ).on( 'htmx:afterSwap', WPFormsAdmin.initChoicesJS ); // Init checkbox multi selects columns. WPFormsAdmin.initCheckboxMultiselectColumns(); // Init color pickers via minicolors.js. $( '.wpforms-color-picker' ).each( function() { const $this = $( this ); $this.minicolors( { defaultValue: $this.data( 'fallback-color' ) || '', } ); } ); // Init fancy File Uploads. $( '.wpforms-file-upload' ).each( function() { var $input = $( this ).find( 'input[type=file]' ), $label = $( this ).find( 'label' ), labelVal = $label.html(); $input.on( 'change', function( event ) { var fileName = ''; if ( this.files && this.files.length > 1 ) { fileName = ( this.getAttribute( 'data-multiple-caption' ) || '' ).replace( '{count}', this.files.length ); } else if ( event.target.value ) { fileName = event.target.value.split( '\\' ).pop(); } if ( fileName ) { $label.find( '.fld' ).html( fileName ); } else { $label.html( labelVal ); } } ); // Firefox bug fix. $input.on( 'focus', function() { $input.addClass( 'has-focus' ); } ).on( 'blur', function() { $input.removeClass( 'has-focus' ); } ); } ); // jquery-confirm defaults. jconfirm.defaults = { closeIcon: false, backgroundDismiss: false, escapeKey: true, animationBounce: 1, useBootstrap: false, theme: 'modern', boxWidth: '400px', animateFromElement: false, content: wpforms_admin.something_went_wrong, }; // Upgrade information modal for upgrade links. $( document ).on( 'click', '.wpforms-upgrade-modal', function() { $.alert( { title: wpforms_admin.thanks_for_interest, content: wpforms_admin.upgrade_modal, icon: 'fa fa-info-circle', type: 'blue', boxWidth: '550px', buttons: { confirm: { text: wpforms_admin.ok, btnClass: 'btn-confirm', keys: [ 'enter' ], }, }, } ); } ); // Lity lightbox. WPFormsAdmin.initLity(); // Flyout Menu. WPFormsAdmin.initFlyoutMenu(); // Action available for each binding. $( document ).trigger( 'wpformsReady' ); // Start listening for screen options changes. $( '#screen-options-wrap .hide-column-tog' ).on( 'change', WPFormsAdmin.handleOnChangeScreenOptions ); }, /** * For styling purposes, we will add a dedicated class name for determining the number of visible columns. * * @since 1.8.3 */ handleOnChangeScreenOptions: function() { const $table = $( '.wpforms-table-list' ); const $columns = $table.find( 'thead .manage-column' ); const $hidden = $columns.filter( '.hidden' ); const hasManyColumns = Boolean( ( $columns.length - $hidden.length ) > 5 ); // This is used to adjust the table layout. // Add a class to the table to indicate the number of columns. $table.toggleClass( 'has-many-columns', hasManyColumns ); $table.toggleClass( 'has-few-columns', ! hasManyColumns ); }, /** * Initialize Choices JS elements. * * @since 1.4.2 */ initChoicesJS: function() { $( '.choicesjs-select' ).each( function() { var $this = $( this ), args = window.wpforms_admin_choicesjs_config ? { ...window.wpforms_admin_choicesjs_config } : {}; if ( $this.attr( 'multiple' ) ) { args.removeItemButton = typeof args.removeItemButton !== 'undefined' ? args.removeItemButton : true; } if ( $this.data( 'sorting' ) === 'off' ) { args.shouldSort = false; } if ( $this.data( 'search' ) ) { args.searchEnabled = true; } if ( $this.data( 'choices-position' ) ) { args.position = $this.data( 'choices-position' ); } // Render HTML in Choices.js. args.allowHTML = true; // Function to run once Choices initialises. // We need to reproduce a behaviour like on public-facing area for "Edit Entry" page. args.callbackOnInit = function() { const self = this; const $element = $( self.passedElement.element ); const sizeClass = $element.data( 'size-class' ); // Add CSS-class for size. if ( sizeClass ) { $( self.containerOuter.element ).addClass( sizeClass ); } wpf.initMultipleSelectWithSearch( this ); wpf.showMoreButtonForChoices( self.containerOuter.element ); }; $this.data( 'choicesjs', new Choices( $this[ 0 ], args ) ); } ); // Add ability to close the drop-down menu. $( document ).on( 'click', '.choices', function( e ) { const $choices = $( this ), choicesObj = $choices.find( 'select' ).data( 'choicesjs' ); if ( choicesObj && $choices.hasClass( 'is-open' ) && ( e.target.classList.contains( 'choices__inner' ) || e.target.classList.contains( 'choices__arrow' ) ) ) { choicesObj.hideDropdown(); } } ); wpf.initializeChoicesEventHandlers(); }, /** * Initialize checkbox multi-select columns. * * @since 1.4.2 */ initCheckboxMultiselectColumns: function() { $( document ).on( 'change', '.checkbox-multiselect-columns input', function() { var $this = $( this ), $parent = $this.parent(), $container = $this.closest( '.checkbox-multiselect-columns' ), label = $parent.text(), itemID = 'check-item-' + $this.val(), $item = $container.find( '#' + itemID ); if ( $this.prop( 'checked' ) ) { $this.parent().addClass( 'checked' ); if ( ! $item.length ) { $container.find( '.second-column ul' ).append( '
' + wpforms_admin.addon_error + '
' + wpforms_admin.plugin_error + '
' + res.data + '
${"addon"===t?wpforms_admin.addon_error:wpforms_admin.plugin_error}
`):s.append(``),"install"===d?(n=!1,p.removeSpinnerFromButton(i)):"deactivate"===d?n=!0:"activate"===d&&(n=!1)}p.setAddonState(e,d,t,function(e){var t;e.success?(t=e,"install"===d?(o=a.active,n=!0,s.attr("data-plugin",t.data.basename),t.data.is_activated||(o=a.installed,n=!1),i.hide(),i=i.closest(".wpforms-addons-list-item").find(".wpforms-toggle-control input")):"activate"===d?(s.find(".wpforms-addons-list-item-footer-settings-link").fadeIn(150),o=a.active,n=!0):"deactivate"===d&&(s.find(".wpforms-addons-list-item-footer-settings-link").fadeOut(150),o=a.installed,n=!1),s.removeClass(a.active+" "+a.incompatible+" "+a.installed+" "+a.missing).addClass(o)):r(e),p.updateAddonButtonPropertiesAndUI(i,c,s,a,n)},function(){r({data:wpforms_admin.server_error}),p.updateAddonButtonPropertiesAndUI(i,c,s,a,n)})}},addSpinnerToButton(e){var t=e.width();e.data("original-text",e.html()),e.width(t).html('')},removeSpinnerFromButton(e){e.html(e.data("original-text"))},getAddonState(e,t,n){return e.hasClass(t.active)||e.hasClass(t.incompatible)?"deactivate":e.hasClass(t.installed)?"activate":e.hasClass(t.missing)?(p.addSpinnerToButton(n),"install"):""},updateAddonButtonPropertiesAndUI(e,t,n,o,i){e.prop("checked",i),e.prop("disabled",!1),e.siblings(".wpforms-toggle-control-status").html(e.siblings(".wpforms-toggle-control-status").data(i?"on":"off")),0'+wpforms_admin.addon_error+"
'+wpforms_admin.plugin_error+"
'+e.data+"
' + wpforms_builder_providers.error_name + '
', modalContent = namePrompt + nameField + nameError; modalContent = modalContent.replace( /%type%/g, type ); $.confirm( { title: false, content: modalContent, icon: 'fa fa-info-circle', type: 'blue', buttons: { confirm: { text: wpforms_builder.ok, btnClass: 'btn-confirm', keys: [ 'enter' ], action: function() { var name = this.$content.find( 'input#provider-connection-name' ).val().trim(); var error = this.$content.find( '.error' ); if ( name === '' ) { error.show(); return false; } else { // Disable button. WPFormsProviders.inputToggle( $this, 'disable' ); // Fire AJAX. var data = { action : 'wpforms_provider_ajax_' + provider, provider: provider, task : 'new_connection', name : name, id : s.form.data( 'id' ), nonce : wpforms_builder.nonce, }; WPFormsProviders.fireAJAX( $this, data, function( res ) { if ( res.success ) { $connections.find( '.wpforms-builder-provider-connections-default' ).addClass( 'wpforms-hidden' ); $connections.find( '.wpforms-provider-connections' ).prepend( res.data.html ); // Process and load the accounts if they exist. var $connection = $connections.find( '.wpforms-provider-connection' ).first(); if ( $connection.find( '.wpforms-provider-accounts option:selected' ) ) { $connection.find( '.wpforms-provider-accounts option' ).first().prop( 'selected', true ); $connection.find( '.wpforms-provider-accounts select' ).trigger( 'change' ); } } else { WPFormsProviders.errorDisplay( res.data.error, $container ); } } ); } }, }, cancel: { text: wpforms_builder.cancel, }, }, } ); }, /** * Add and authorize provider account. * * @since 1.0.0 */ accountAdd: function( el, e ) { e.preventDefault(); var $this = $( el ), provider = $this.data( 'provider' ), $connection = $this.closest( '.wpforms-provider-connection' ), $container = $this.parent(), $fields = $container.find( ':input' ), errors = WPFormsProviders.requiredCheck( $fields, $container ); // Disable button. WPFormsProviders.inputToggle( $this, 'disable' ); // Bail if we have any errors. if ( errors ) { $this.prop( 'disabled', false ).find( 'i' ).remove(); return false; } // Fire AJAX. var data = { action : 'wpforms_provider_ajax_' + provider, provider : provider, connection_id: $connection.data( 'connection_id' ), task : 'new_account', data : WPFormsProviders.fakeSerialize( $fields ), }; WPFormsProviders.fireAJAX( $this, data, function( res ) { if ( res.success ) { $container.nextAll( '.wpforms-connection-block' ).remove(); $container.nextAll( '.wpforms-conditional-block' ).remove(); $container.after( res.data.html ); $container.slideUp(); $connection.find( '.wpforms-provider-accounts select' ).trigger( 'change' ); } else { WPFormsProviders.errorDisplay( res.data.error, $container ); } } ); }, /** * Selecting a provider account * * @since 1.0.0 */ accountSelect: function( el, e ) { e.preventDefault(); var $this = $( el ), $connection = $this.closest( '.wpforms-provider-connection' ), $container = $this.parent(), provider = $connection.data( 'provider' ); // Disable select, show loading. WPFormsProviders.inputToggle( $this, 'disable' ); // Remove any blocks that might exist as we prep for new account. $container.nextAll( '.wpforms-connection-block' ).remove(); $container.nextAll( '.wpforms-conditional-block' ).remove(); if ( ! $this.val() ) { // User selected to option to add new account. $connection.find( '.wpforms-provider-account-add input' ).val( '' ); $connection.find( '.wpforms-provider-account-add' ).slideDown(); WPFormsProviders.inputToggle( $this, 'enable' ); } else { $connection.find( '.wpforms-provider-account-add' ).slideUp(); // Fire AJAX. var data = { action : 'wpforms_provider_ajax_' + provider, provider : provider, connection_id: $connection.data( 'connection_id' ), task : 'select_account', account_id : $this.find( ':selected' ).val(), }; WPFormsProviders.fireAJAX( $this, data, function( res ) { if ( res.success ) { $container.after( res.data.html ); // Process first list found. $connection.find( '.wpforms-provider-lists option' ).first().prop( 'selected', true ); $connection.find( '.wpforms-provider-lists select' ).trigger( 'change' ); } else { WPFormsProviders.errorDisplay( res.data.error, $container ); } } ); } }, /** * Selecting a provider account list. * * @since 1.0.0 */ accountListSelect: function( el, e ) { e.preventDefault(); var $this = $( el ), $connection = $this.closest( '.wpforms-provider-connection' ), $container = $this.parent(), provider = $connection.data( 'provider' ); // Disable select, show loading. WPFormsProviders.inputToggle( $this, 'disable' ); // Remove any blocks that might exist as we prep for new account. $container.nextAll( '.wpforms-connection-block' ).remove(); $container.nextAll( '.wpforms-conditional-block' ).remove(); var data = { action : 'wpforms_provider_ajax_' + provider, provider : provider, connection_id: $connection.data( 'connection_id' ), task : 'select_list', account_id : $connection.find( '.wpforms-provider-accounts option:selected' ).val(), list_id : $this.find( ':selected' ).val(), form_id : s.form.data( 'id' ), }; WPFormsProviders.fireAJAX( $this, data, function( res ) { if ( res.success ) { $container.after( res.data.html ); // Re-init tooltips for new fields. wpf.initTooltips(); } else { WPFormsProviders.errorDisplay( res.data.error, $container ); } } ); }, /** * Confirm form save before loading Provider panel. * If confirmed, save and reload panel. * * @since 1.0.0 */ providerPanelConfirm: function( targetPanel ) { wpforms_panel_switch = true; if ( targetPanel === 'providers' && ! s.form.data( 'revision' ) ) { if ( wpf.savedState != wpf.getFormState( '#wpforms-builder-form' ) ) { wpforms_panel_switch = false; $.confirm( { title: false, content: wpforms_builder_providers.confirm_save, icon: 'fa fa-info-circle', type: 'blue', buttons: { confirm: { text: wpforms_builder.ok, btnClass: 'btn-confirm', keys: [ 'enter' ], action: function() { $( '#wpforms-save' ).trigger( 'click' ); $( document ).on( 'wpformsSaved', function() { let wpforms_builder_provider_url = wpforms_builder_providers.url; const $section = $( `#wpforms-panel-${ targetPanel } .wpforms-panel-sidebar-section.active` ); const section = $section.length && $section.data( 'section' ) !== 'default' ? $section.data( 'section' ) : null; // Adding an active section parameter. if ( section ) { wpforms_builder_provider_url += `§ion=${ section }`; } window.location.href = wpforms_builder_provider_url; } ); }, }, cancel: { text: wpforms_builder.cancel, }, }, } ); } } }, //--------------------------------------------------------------------// // Helper functions. //--------------------------------------------------------------------// /** * Fire AJAX call. * * @since 1.0.0 */ fireAJAX: function( el, d, success ) { var $this = $( el ); var data = { id : $( '#wpforms-builder-form' ).data( 'id' ), nonce : wpforms_builder.nonce, }; $.extend( data, d ); $.post( wpforms_builder.ajax_url, data, function( res ) { success( res ); WPFormsProviders.inputToggle( $this, 'enable' ); } ).fail( function( xhr, textStatus, e ) { console.log( xhr.responseText ); } ); }, /** * Toggle input with loading indicator. * * @since 1.0.0 */ inputToggle: function( el, status ) { var $this = $( el ); if ( status === 'enable' ) { if ( $this.is( 'select' ) ) { $this.prop( 'disabled', false ).next( 'i' ).remove(); } else { $this.prop( 'disabled', false ).find( 'i' ).remove(); } } else if ( status === 'disable' ) { if ( $this.is( 'select' ) ) { $this.prop( 'disabled', true ).after( s.spinner ); } else { $this.prop( 'disabled', true ).prepend( s.spinnerWhite ); } } }, /** * Display error. * * @since 1.0.0 */ errorDisplay: function( msg, location ) { location.find( '.wpforms-error-msg' ).remove(); location.prepend( '' + msg + '
' ); }, /** * Check for required fields. * * @since 1.0.0 */ requiredCheck: function( fields, location ) { var error = false; // Remove any previous errors. location.find( '.wpforms-alert-required' ).remove(); // Loop through input fields and check for values. fields.each( function( index, el ) { if ( $( el ).hasClass( 'wpforms-required' ) && $( el ).val().length === 0 ) { $( el ).addClass( 'wpforms-error' ); error = true; } else { $( el ).removeClass( 'wpforms-error' ); } } ); if ( error ) { location.prepend( '' + wpforms_builder_providers.required_field + '
' ); } return error; }, /** * Pseudo serializing. Fake it until you make it. * * @since 1.0.0 */ fakeSerialize: function( els ) { var fields = els.clone(); fields.each( function( index, el ) { if ( $( el ).data( 'name' ) ) { $( el ).attr( 'name', $( el ).data( 'name' ) ); } } ); return fields.serialize(); }, /** * Get the default name for a new connection. * * @since 1.9.3 * * @param {string} provider Current provider slug. * * @return {string} Returns the default name for a new connection. */ getDefaultConnectionName( provider ) { const providerClass = WPFormsProviders.getProviderClass( provider ); // Check if the provider has a method to set the custom connection name. if ( typeof providerClass?.setDefaultModalValue === 'function' ) { return providerClass.setDefaultModalValue(); } const providerName = $( `#${ provider }-provider` ).data( 'provider-name' ); const numberOfConnections = WPFormsProviders.getCountConnectionsOf( provider ); const defaultName = `${ providerName } ${ wpforms_builder.connection_label }`; if ( numberOfConnections === 0 ) { return defaultName; } return `${ defaultName } #${ numberOfConnections + 1 }`; }, /** * Get the number of connections for the provider. * * @since 1.9.3 * * @param {string} provider Current provider slug. * * @return {number} Returns the number of connections for the provider. */ getCountConnectionsOf( provider ) { return $( `#${ provider }-provider .wpforms-provider-connection` ).length; }, /** * Get a provider JS object. * * @since 1.9.3 * * @param {string} provider Provider name. * * @return {Object|null} Return provider object or null. */ getProviderClass( provider ) { const upperProviderPart = ( providerPart ) => ( providerPart.charAt( 0 ).toUpperCase() + providerPart.slice( 1 ) ); const getClassName = provider.split( '-' ).map( upperProviderPart ).join( '' ); if ( typeof WPForms?.Admin?.Builder?.Providers?.[ getClassName ] === 'undefined' ) { return null; } return WPForms.Admin.Builder.Providers[ getClassName ]; }, }; WPFormsProviders.init(); } )( jQuery ); admin/builder/admin-builder-providers.min.js 0000644 00000020251 15171647003 0015135 0 ustar 00 !function(c){var s,a={settings:{spinner:'',spinnerWhite:''},init:function(){s=this.settings,c(a.ready),a.bindUIActions()},ready:function(){s.form=c("#wpforms-builder-form")},bindUIActions:function(){c(document).on("click",".wpforms-provider-connection-delete",function(e){a.connectionDelete(this,e)}),c(document).on("click",".wpforms-provider-connections-add",function(e){a.connectionAdd(this,e)}),c(document).on("click",".wpforms-provider-account-add button",function(e){a.accountAdd(this,e)}),c(document).on("change",".wpforms-provider-accounts select",function(e){a.accountSelect(this,e)}),c(document).on("change",".wpforms-provider-lists select",function(e){a.accountListSelect(this,e)}),c(document).on("wpformsPanelSwitch",function(e,o){a.providerPanelConfirm(o)}),c(document).on("wpformsSaved",function(){var r=[],e=c("#wpforms-panel-providers").find(".wpforms-connection-block");e.length&&e.each(function(){var e,o,n=!1;c(this).find("table span.required").each(function(){""===c(this).parent().parent().find("select").val()&&(n=!0)}),n&&((e=c(this).closest(".wpforms-panel-content-section").find(".wpforms-panel-content-section-title").clone()).find("button").remove(),e=e.text().trim(),o=wpforms_builder.provider_required_flds,-1'+wpforms_builder_providers.error_name+"
")).replace(/%type%/g,e);c.confirm({title:!1,content:o,icon:"fa fa-info-circle",type:"blue",buttons:{confirm:{text:wpforms_builder.ok,btnClass:"btn-confirm",keys:["enter"],action:function(){var e=this.$content.find("input#provider-connection-name").val().trim(),o=this.$content.find(".error");if(""===e)return o.show(),!1;a.inputToggle(n,"disable");o={action:"wpforms_provider_ajax_"+t,provider:t,task:"new_connection",name:e,id:s.form.data("id"),nonce:wpforms_builder.nonce};a.fireAJAX(n,o,function(e){var o;e.success?(r.find(".wpforms-builder-provider-connections-default").addClass("wpforms-hidden"),r.find(".wpforms-provider-connections").prepend(e.data.html),(o=r.find(".wpforms-provider-connection").first()).find(".wpforms-provider-accounts option:selected")&&(o.find(".wpforms-provider-accounts option").first().prop("selected",!0),o.find(".wpforms-provider-accounts select").trigger("change"))):a.errorDisplay(e.data.error,i)})}},cancel:{text:wpforms_builder.cancel}}})},accountAdd:function(e,o){o.preventDefault();var o=c(e),e=o.data("provider"),n=o.closest(".wpforms-provider-connection"),r=o.parent(),i=r.find(":input"),t=a.requiredCheck(i,r);if(a.inputToggle(o,"disable"),t)return o.prop("disabled",!1).find("i").remove(),!1;t={action:"wpforms_provider_ajax_"+e,provider:e,connection_id:n.data("connection_id"),task:"new_account",data:a.fakeSerialize(i)};a.fireAJAX(o,t,function(e){e.success?(r.nextAll(".wpforms-connection-block").remove(),r.nextAll(".wpforms-conditional-block").remove(),r.after(e.data.html),r.slideUp(),n.find(".wpforms-provider-accounts select").trigger("change")):a.errorDisplay(e.data.error,r)})},accountSelect:function(e,o){o.preventDefault();var o=c(e),n=o.closest(".wpforms-provider-connection"),r=o.parent(),e=n.data("provider");a.inputToggle(o,"disable"),r.nextAll(".wpforms-connection-block").remove(),r.nextAll(".wpforms-conditional-block").remove(),o.val()?(n.find(".wpforms-provider-account-add").slideUp(),e={action:"wpforms_provider_ajax_"+e,provider:e,connection_id:n.data("connection_id"),task:"select_account",account_id:o.find(":selected").val()},a.fireAJAX(o,e,function(e){e.success?(r.after(e.data.html),n.find(".wpforms-provider-lists option").first().prop("selected",!0),n.find(".wpforms-provider-lists select").trigger("change")):a.errorDisplay(e.data.error,r)})):(n.find(".wpforms-provider-account-add input").val(""),n.find(".wpforms-provider-account-add").slideDown(),a.inputToggle(o,"enable"))},accountListSelect:function(e,o){o.preventDefault();var o=c(e),e=o.closest(".wpforms-provider-connection"),n=o.parent(),r=e.data("provider"),r=(a.inputToggle(o,"disable"),n.nextAll(".wpforms-connection-block").remove(),n.nextAll(".wpforms-conditional-block").remove(),{action:"wpforms_provider_ajax_"+r,provider:r,connection_id:e.data("connection_id"),task:"select_list",account_id:e.find(".wpforms-provider-accounts option:selected").val(),list_id:o.find(":selected").val(),form_id:s.form.data("id")});a.fireAJAX(o,r,function(e){e.success?(n.after(e.data.html),wpf.initTooltips()):a.errorDisplay(e.data.error,n)})},providerPanelConfirm:function(n){wpforms_panel_switch=!0,"providers"!==n||s.form.data("revision")||wpf.savedState!=wpf.getFormState("#wpforms-builder-form")&&(wpforms_panel_switch=!1,c.confirm({title:!1,content:wpforms_builder_providers.confirm_save,icon:"fa fa-info-circle",type:"blue",buttons:{confirm:{text:wpforms_builder.ok,btnClass:"btn-confirm",keys:["enter"],action:function(){c("#wpforms-save").trigger("click"),c(document).on("wpformsSaved",function(){let e=wpforms_builder_providers.url;var o=c(`#wpforms-panel-${n} .wpforms-panel-sidebar-section.active`),o=o.length&&"default"!==o.data("section")?o.data("section"):null;o&&(e+="§ion="+o),window.location.href=e})}},cancel:{text:wpforms_builder.cancel}}}))},fireAJAX:function(e,o,n){var r=c(e),e={id:c("#wpforms-builder-form").data("id"),nonce:wpforms_builder.nonce};c.extend(e,o),c.post(wpforms_builder.ajax_url,e,function(e){n(e),a.inputToggle(r,"enable")}).fail(function(e,o,n){console.log(e.responseText)})},inputToggle:function(e,o){e=c(e);"enable"===o?(e.is("select")?e.prop("disabled",!1).next("i"):e.prop("disabled",!1).find("i")).remove():"disable"===o&&(e.is("select")?e.prop("disabled",!0).after(s.spinner):e.prop("disabled",!0).prepend(s.spinnerWhite))},errorDisplay:function(e,o){o.find(".wpforms-error-msg").remove(),o.prepend(''+e+"
")},requiredCheck:function(e,o){var n=!1;return o.find(".wpforms-alert-required").remove(),e.each(function(e,o){c(o).hasClass("wpforms-required")&&0===c(o).val().length?(c(o).addClass("wpforms-error"),n=!0):c(o).removeClass("wpforms-error")}),n&&o.prepend(''+wpforms_builder_providers.required_field+"
"),n},fakeSerialize:function(e){e=e.clone();return e.each(function(e,o){c(o).data("name")&&c(o).attr("name",c(o).data("name"))}),e.serialize()},getDefaultConnectionName(e){var o=a.getProviderClass(e);return"function"==typeof o?.setDefaultModalValue?o.setDefaultModalValue():(o=c(`#${e}-provider`).data("provider-name"),e=a.getCountConnectionsOf(e),o=o+" "+wpforms_builder.connection_label,0===e?o:o+" #"+(e+1))},getCountConnectionsOf(e){return c(`#${e}-provider .wpforms-provider-connection`).length},getProviderClass(e){e=e.split("-").map(e=>e.charAt(0).toUpperCase()+e.slice(1)).join("");return void 0===WPForms?.Admin?.Builder?.Providers?.[e]?null:WPForms.Admin.Builder.Providers[e]}};a.init()}(jQuery); admin/builder/admin-builder.js 0000644 00001067461 15171647003 0012357 0 ustar 00 /* global wpforms_builder, wpf, jconfirm, wpforms_panel_switch, Choices, WPForms, WPFormsFormEmbedWizard, wpCookies, tinyMCE, WPFormsUtils, List, wpforms_preset_choices */ /** * @param wpforms_builder.smart_tags_disabled_for_confirmations */ /* noinspection JSUnusedLocalSymbols */ /* eslint-disable no-unused-expressions, no-shadow */ // noinspection ES6ConvertVarToLetConst var WPFormsBuilder = window.WPFormsBuilder || ( function( document, window, $ ) { // eslint-disable-line no-var let s, $builder; const elements = {}, browser = {}; /** * Whether to show the close confirmation dialog or not. * * @since 1.6.0 * * @type {boolean} */ let closeConfirmation = true; /** * A field is adding. * * @since 1.7.1 * * @type {boolean} */ let adding = false; /** * Preview tab. * * @since 1.9.4 * * @type {object|null} */ let previewTab = null; // noinspection JSUnusedGlobalSymbols const app = { /* eslint-disable camelcase */ settings: { spinner: '', spinnerInline: '', tinymceDefaults: { tinymce: { toolbar1: 'bold,italic,underline,blockquote,strikethrough,bullist,numlist,alignleft,aligncenter,alignright,undo,redo,link' }, quicktags: true, }, pagebreakTop: false, pagebreakBottom: false, upload_img_modal: false, choicesLimit: 20, // Choices limit for fields different from Dropdown. choicesLimitLong: 250, // Choices limit for Dropdown field. }, /** * Start the engine. * * @since 1.0.0 */ init() { const that = this; wpforms_panel_switch = true; s = this.settings; // Document ready. $( app.ready ); // Page load. $( window ).on( 'load', function() { // In the case of jQuery 3.+, we need to wait for a ready event first. if ( typeof $.ready.then === 'function' ) { $.ready.then( app.load ); } else { app.load(); } } ); $( window ).on( 'beforeunload', function() { if ( ! that.formIsSaved() && closeConfirmation ) { return wpforms_builder.are_you_sure_to_close; } } ); }, /** * Page load. * * @since 1.0.0 * @since 1.7.9 Added `wpformsBuilderReady` hook. * * @return {false|void} False if default event is prevented. */ load() { // Trigger initial save for new forms. if ( wpf.getQueryString( 'newform' ) ) { app.formSave( false ); } const panel = $( '#wpforms-panels-toggle .active' ).data( 'panel' ); // Render form preview on the Revisions panel if the panel is active. if ( panel === 'revisions' ) { app.updateRevisionPreview(); } // Allow callbacks to prevent making Form Builder ready... const event = WPFormsUtils.triggerEvent( $builder, 'wpformsBuilderReady' ); // ...by triggering `event.preventDefault()`. if ( event.isDefaultPrevented() ) { return false; } // Hide loading overlay and make the Form Builder ready to use. app.hideLoadingOverlay(); // Maybe display informational modal. // noinspection JSUnresolvedReference, EqualityComparisonWithCoercionJS if ( wpforms_builder.template_modal_display == '1' && 'fields' === wpf.getQueryString( 'view' ) ) { // eslint-disable-line $.alert( { title: wpforms_builder.template_modal_title, content: wpforms_builder.template_modal_msg, icon: 'fa fa-info-circle', type: 'blue', buttons: { confirm: { text: wpforms_builder.close, btnClass: 'btn-confirm', keys: [ 'enter' ], }, }, } ); } }, /** * Init elements cache. * * @since 1.9.2 */ initElementsCache() { // Cache builder element. $builder = $( '#wpforms-builder' ); browser.isWindows = /Win/.test( navigator.userAgent ); browser.isLinux = /Linux/.test( navigator.userAgent ); browser.isMac = /Mac/.test( navigator.userAgent ); // Action buttons. elements.$helpButton = $( '#wpforms-help' ); elements.$previewButton = $( '#wpforms-preview-btn' ); elements.$embedButton = $( '#wpforms-embed' ); elements.$saveButton = $( '#wpforms-save' ); elements.$exitButton = $( '#wpforms-exit' ); // Cache other elements. elements.$noFieldsOptions = $( '#wpforms-panel-fields .wpforms-no-fields-holder .no-fields' ); elements.$noFieldsPreview = $( '#wpforms-panel-fields .wpforms-no-fields-holder .no-fields-preview' ); elements.$formPreview = $( '#wpforms-panel-fields .wpforms-preview-wrap' ); elements.$revisionPreview = $( '#wpforms-panel-revisions .wpforms-panel-content' ); elements.defaultEmailSelector = '.wpforms-field-option-email .wpforms-field-option-row-default_value input'; elements.$defaultEmail = $( elements.defaultEmailSelector ); elements.$focusOutTarget = null; elements.$nextFieldId = $( '#wpforms-field-id' ); elements.$addFieldsTab = $( '#add-fields a' ); elements.$fieldOptions = $( '#wpforms-field-options' ); elements.$fieldsPreviewWrap = $( '#wpforms-panel-fields .wpforms-panel-content-wrap' ); elements.$sortableFieldsWrap = $( '#wpforms-panel-fields .wpforms-field-wrap' ); elements.$addFieldsButtons = $( '.wpforms-add-fields-button' ).not( '.not-draggable' ).not( '.warning-modal' ).not( '.education-modal' ); elements.$fieldsSidebar = $( '#wpforms-panel-fields .wpforms-add-fields' ); elements.$searchInput = $( '#wpforms-search-fields-input' ); elements.$sidebarToggle = $( '.wpforms-panels .wpforms-panel-sidebar-content .wpforms-panel-sidebar-toggle' ); }, /** * Document ready. * * @since 1.0.0 */ ready() { // eslint-disable-line max-lines-per-function if ( app.isVisitedViaBackButton() ) { location.reload(); return; } app.initElementsCache(); // Add `_wp_http_referer` to the data of every AJAX request. $.ajaxSetup( { data: { // eslint-disable-next-line camelcase _wp_http_referer: wpf.updateQueryString( '_wp_http_referer', null ), }, } ); // Remove Embed button if builder opened in the popup. if ( app.isBuilderInPopup() ) { elements.$embedButton.remove(); elements.$previewButton.addClass( 'wpforms-alone' ); } app.loadMsWinCSS(); // Bind all actions. app.bindUIActions(); // Setup/cache some vars not available before s.formID = $( '#wpforms-builder-form' ).data( 'id' ); s.pagebreakTop = $( '.wpforms-pagebreak-top' ).length; s.pagebreakBottom = $( '.wpforms-pagebreak-bottom' ).length; // Disable implicit submission for every form inside the builder. // All form values are managed by JS and should not be submitted by pressing Enter. $builder.on( 'keypress', '#wpforms-builder-form :input:not(textarea)', function( e ) { if ( e.keyCode === 13 ) { e.preventDefault(); } } ); app.determineActiveSections(); app.loadEntryPreviewFields(); // Drag and drop sortable elements. app.fieldChoiceSortable( 'select' ); app.fieldChoiceSortable( 'radio' ); app.fieldChoiceSortable( 'checkbox' ); app.fieldChoiceSortable( 'payment-multiple' ); app.fieldChoiceSortable( 'payment-checkbox' ); app.fieldChoiceSortable( 'payment-select' ); // Set field group visibility. $( '.wpforms-add-fields-group' ).each( function( index, el ) { // eslint-disable-line no-unused-vars app.fieldGroupToggle( $( this ), 'load' ); } ); app.registerTemplates(); // Trim long form titles. app.trimFormTitle(); // Load Tooltips. wpf.initTooltips(); // Load Color Pickers. app.loadColorPickers(); // Hide/Show CAPTCHA in form. app.captchaToggle(); // Confirmations' initial setup. app.confirmationsSetup(); // Notification settings. app.notificationToggle(); app.notificationsByStatusAlerts(); app.notificationsUpdateElementsVisibility(); // Secret builder hotkeys. app.builderHotkeys(); // jquery-confirm defaults. jconfirm.defaults = { closeIcon: false, backgroundDismiss: false, escapeKey: true, animationBounce: 1, useBootstrap: false, theme: 'modern', boxWidth: '400px', animateFromElement: false, content: wpforms_builder.something_went_wrong, }; app.dropdownField.init(); app.iconChoices.init(); app.disabledFields.init(); app.checkEmptyDynamicChoices(); app.initSomeFieldOptions(); app.dismissNotice(); wpf.initializeChoicesEventHandlers(); }, checkEmptyDynamicChoices() { const choices = wpf.orders.choices || {}; if ( ! Object.keys( choices ).length ) { return; } wpf.orders.fields.forEach( function( fieldId ) { // eslint-disable-line complexity const isDynamic = app.dropdownField.helpers.isDynamicChoices( fieldId ); if ( ! isDynamic ) { return; } const $fieldPreview = $( '#wpforms-field-' + fieldId ); const type = app.dropdownField.helpers.getDynamicChoicesOptionType( fieldId ); const source = app.dropdownField.helpers.getDynamicChoicesOptionSource( fieldId ); const isModern = app.dropdownField.helpers.isDynamicChoicesOptionModern( fieldId ); let isEmpty = isModern ? $fieldPreview.find( '.has-no-choices' ).length : $fieldPreview.find( '.primary-input option:not(.placeholder), .primary-input li' ).length === 0; if ( isModern && ! isEmpty ) { const placeholder = $( '#wpforms-field-option-' + fieldId + '-placeholder' ).val(); const choices = app.dropdownField.helpers.getInitialChoices( fieldId ); isEmpty = choices.length === 1 && choices[ 0 ].label === placeholder && choices[ 0 ].placeholder === true; } if ( isEmpty ) { app.emptyChoicesNotice( fieldId, source, type ); } } ); }, /** * Load Microsoft Windows specific stylesheet. * * @since 1.6.8 */ loadMsWinCSS() { // Detect OS & browsers. if ( browser.isMac ) { return; } $( '' ) .appendTo( 'head' ) .attr( { type: 'text/css', rel: 'stylesheet', href: wpforms_builder.scrollbars_css_url, } ); }, /** * Builder was visited via back button in the browser. * * @since 1.6.5 * * @return {boolean} True if the builder was visited via back button in browser. */ isVisitedViaBackButton() { if ( ! performance ) { return false; } let isVisitedViaBackButton = false; performance.getEntriesByType( 'navigation' ).forEach( function( nav ) { if ( nav.type === 'back_forward' ) { isVisitedViaBackButton = true; } } ); return isVisitedViaBackButton; }, /** * Remove loading overlay. * * @since 1.6.8 */ hideLoadingOverlay() { const $overlay = $( '#wpforms-builder-overlay' ); $overlay.addClass( 'fade-out' ); setTimeout( function() { $overlay.hide(); }, 250 ); }, /** * Show loading overlay. * * @since 1.6.8 */ showLoadingOverlay() { const $overlay = $( '#wpforms-builder-overlay' ); $overlay.removeClass( 'fade-out' ); $overlay.show(); }, /** * Initialize some fields options controls. * * @since 1.6.3 */ initSomeFieldOptions() { // Show a toggled options groups. app.toggleAllOptionGroups( $builder ); // Date/Time field Date type option. $builder.find( '.wpforms-field-option-row-date .type select' ).trigger( 'change' ); }, /** * Dropdown field component. * * @since 1.6.1 */ dropdownField: { /** * Field configuration. * * @since 1.6.1 */ config: { modernClass: 'choicesjs-select', args: { searchEnabled: false, searchChoices: false, renderChoiceLimit: 1, shouldSort: false, callbackOnInit() { const $element = $( this.containerOuter.element ), $previewSelect = $element.closest( '.wpforms-field' ).find( 'select' ); // Turn off disabled styles. if ( $element.hasClass( 'is-disabled' ) ) { $element.removeClass( 'is-disabled' ); } // Disable instances on the preview panel. if ( $previewSelect.is( '[readonly]' ) ) { this.disable(); $previewSelect.prop( 'disabled', false ); } if ( this.passedElement.element.multiple ) { // Hide a placeholder if field has selected choices. if ( this.getValue( true ).length ) { $( this.input.element ).addClass( 'choices__input--hidden' ); } } // Decode allowed HTML entities for choices. $element.find( '.choices__item--selectable' ).each( function() { const $choice = $( this ); const text = wpf.decodeAllowedHTMLEntities( $choice.text() ); $choice.text( text ); } ); }, }, }, /** * Initialization for field component. * * @since 1.6.1 */ init() { // Choices.js init. $builder.find( '.' + app.dropdownField.config.modernClass ).each( function() { app.dropdownField.events.choicesInit( $( this ) ); } ); // Multiple option. $builder.on( 'change', '.wpforms-field-option-select .wpforms-field-option-row-multiple input', app.dropdownField.events.multiple ); // Style option. $builder.on( 'change', '.wpforms-field-option-select .wpforms-field-option-row-style select, .wpforms-field-option-payment-select .wpforms-field-option-row-style select', app.dropdownField.events.applyStyle ); // Add the ability to close the drop-down menu. $builder.on( 'click', '.choices', function( e ) { const $choices = $( this ), choicesObj = $choices.find( 'select' ).data( 'choicesjs' ); if ( choicesObj && $choices.hasClass( 'is-open' ) && e.target.classList.contains( 'choices__inner' ) ) { choicesObj.hideDropdown(); } } ); }, /** * Field events. * * @since 1.6.1 */ events: { /** * Load Choices.js library. * * @since 1.6.1 * * @param {Object} $element jQuery element selector. */ choicesInit( $element ) { const useAjax = $element.data( 'choicesjs-use-ajax' ) === 1; let instance; if ( $element.data( 'choicesjs-callback-fn' ) === 'select_pages' ) { instance = WPForms.Admin.Builder.WPFormsChoicesJS.setup( $element[ 0 ], app.dropdownField.config.args, { action: 'wpforms_ajax_search_pages_for_dropdown', nonce: useAjax ? wpforms_builder.nonce : null, } ); } else { instance = new Choices( $element[ 0 ], app.dropdownField.config.args ); } app.dropdownField.helpers.setInstance( $element, instance ); app.dropdownField.helpers.addPlaceholderChoice( $element, instance ); $element.closest( '.choices' ).toggleClass( 'wpforms-hidden', ! instance.config.choices.length ); }, /** * Multiple option callback. * * @since 1.6.1 * * @param {Object} event Event object. */ multiple( event ) { const fieldId = $( this ).closest( '.wpforms-field-option-row-multiple' ).data().fieldId, $primary = app.dropdownField.helpers.getPrimarySelector( fieldId ), $optionChoicesItems = $( '#wpforms-field-option-row-' + fieldId + '-choices input.default' ), $placeholder = $primary.find( '.placeholder' ), isDynamicChoices = app.dropdownField.helpers.isDynamicChoices( fieldId ), isMultiple = event.target.checked, choicesType = isMultiple ? 'checkbox' : 'radio'; // Add/remove a `multiple` attribute. $primary.prop( 'multiple', isMultiple ); // Change a `Choices` fields type: // checkbox - needed for multiple selection // radio - needed for single selection $optionChoicesItems.prop( 'type', choicesType ); // Dynamic Choices doesn't have default choices (selected options) - make all as unselected. if ( isDynamicChoices ) { $primary.find( 'option:selected' ).prop( 'selected', false ); } // Gets default choices. const selectedChoices = $optionChoicesItems.filter( ':checked' ); if ( ! isMultiple && selectedChoices.length ) { // Uncheck all choices. $optionChoicesItems.prop( 'checked', false ); // For single selection, we can choose only one. $( selectedChoices.get( 0 ) ).prop( 'checked', true ); } // Toggle selection for a placeholder option based on a select type. if ( $placeholder.length ) { $placeholder.prop( 'selected', ! isMultiple ); } // Update a primary field. app.dropdownField.helpers.update( fieldId, isDynamicChoices ); }, /** * Apply a style to