/* global wpforms_builder, wpforms_builder_providers, wpf */ // noinspection ES6ConvertVarToLetConst var WPForms = window.WPForms || {}; // eslint-disable-line no-var WPForms.Admin = WPForms.Admin || {}; WPForms.Admin.Builder = WPForms.Admin.Builder || {}; /** * @param wpforms_builder_providers.custom_fields_placeholder */ /** * WPForms Providers module. * * @since 1.4.7 */ WPForms.Admin.Builder.Providers = WPForms.Admin.Builder.Providers || ( function( document, window, $ ) { /** * Private functions and properties. * * @since 1.4.7 * * @type {Object} */ const __private = { /** * Internal cache storage. * Do not use it directly, but app.cache.{(get|set|delete|clear)()} instead. * Key is the provider slug, value is a Map, that will have its own key as a connection id (or not). * * @since 1.4.7 * * @type {Object.} */ cache: {}, /** * Config contains all configuration properties. * * @since 1.4.7 * * @type {Object.} */ config: { /** * List of default templates that should be compiled. * * @since 1.4.7 * * @type {string[]} */ templates: [ 'wpforms-providers-builder-content-connection-fields', 'wpforms-providers-builder-content-connection-conditionals', ], }, /** * Form fields for the current state. * * @since 1.6.1.2 * * @type {Object} */ fields: {}, }; /** * Public functions and properties. * * @since 1.4.7 * * @type {Object} */ const app = { /** * Panel holder. * * @since 1.5.9 * * @type {Object} */ panelHolder: {}, /** * Form holder. * * @since 1.4.7 * * @type {Object} */ form: $( '#wpforms-builder-form' ), /** * Spinner HTML. * * @since 1.4.7 * * @type {Object} */ spinner: '', /** * All ajax requests are grouped together with own properties. * * @since 1.4.7 */ ajax: { /** * Merge a custom AJAX data object with defaults. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider * * @param {string} provider Current provider slug. * @param {Object} custom Ajax data object with custom settings. * * @return {Object} Ajax data. */ _mergeData( provider, custom ) { const data = { id: app.form.data( 'id' ), // eslint-disable-next-line camelcase revision_id: app.form.data( 'revision' ), nonce: wpforms_builder.nonce, action: 'wpforms_builder_provider_ajax_' + provider, }; $.extend( data, custom ); return data; }, /** * Make an AJAX request. It's basically a wrapper around jQuery.ajax, but with some defaults. * * @since 1.4.7 * * @param {string} provider Current provider slug. * @param {*} custom Object of user-defined $.ajax()-compatible parameters. * * @return {Promise} Promise. */ request( provider, custom ) { const $holder = app.getProviderHolder( provider ), $lock = $holder.find( '.wpforms-builder-provider-connections-save-lock' ), $error = $holder.find( '.wpforms-builder-provider-connections-error' ); const params = { url: wpforms_builder.ajax_url, type: 'post', dataType: 'json', beforeSend() { $holder.addClass( 'loading' ); $lock.val( 1 ); $error.hide(); }, }; // Hidden class is used only for initial get connections request when connections are not set yet. if ( custom.data.task !== 'connections_get' ) { $holder.find( '.wpforms-builder-provider-title-spinner' ).removeClass( 'wpforms-hidden' ); } custom.data = app.ajax._mergeData( provider, custom.data || {} ); $.extend( params, custom ); // noinspection SpellCheckingInspection, JSUnusedLocalSymbols return $.ajax( params ) .fail( function( jqXHR, textStatus, errorThrown ) { // eslint-disable-line no-unused-vars /* * Right now we are logging into the browser console. * In the future, that might be better. */ console.error( 'provider:', provider ); // eslint-disable-line no-console console.error( jqXHR ); // eslint-disable-line no-console console.error( textStatus ); // eslint-disable-line no-console $lock.val( 1 ); $error.show(); } ) .always( function( dataOrjqXHR, textStatus, jqXHROrerrorThrown ) { // eslint-disable-line no-unused-vars $holder.removeClass( 'loading' ); if ( 'success' === textStatus ) { $lock.val( 0 ); // Update the form state when the provider data is unlocked. // We need to do it on the next tick to ensure that provider fields are already initialized. setTimeout( function() { wpf.savedState = wpf.getFormState( '#wpforms-builder-form' ); }, 0 ); } } ); }, }, /** * Temporary in-memory cache handling for all providers. * * @since 1.4.7 */ cache: { /** * Get the value from cache by key. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @param {string} provider Current provider slug. * @param {string} key Cache key. * * @return {*} Null if some error occurs. */ get( provider, key ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { return null; } return __private.cache[ provider ].get( key ); }, /** * Get the value from cache by key and an ID. * Useful when an Object is stored under a key, and we need specific value. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @param {string} provider Current provider slug. * @param {string} key Cache key. * @param {string} id Cached object ID. * * @return {*} Null if some error occurs. */ getById( provider, key, id ) { if ( typeof this.get( provider, key ) === 'undefined' || typeof this.get( provider, key )[ id ] === 'undefined' ) { return null; } return this.get( provider, key )[ id ]; }, /** * Save the data to cache. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @param {string} provider Current provider slug. * @param {string} key Intended to be a string, but can be everything that Map supports as a key. * @param {*} value Data you want to save in cache. * * @return {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ set( provider, key, value ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { __private.cache[ provider ] = new Map(); } return __private.cache[ provider ].set( key, value ); }, /** * Add the data to cache to a particular key. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @example app.cache.as('provider').addTo('connections', connection_id, connection); * * @param {string} provider Current provider slug. * @param {string} key Intended to be a string, but can be everything that Map supports as a key. * @param {string} id ID for a value that should be added to a certain key. * @param {*} value Data you want to save in cache. * * @return {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ addTo( provider, key, id, value ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { __private.cache[ provider ] = new Map(); this.set( provider, key, {} ); } const data = this.get( provider, key ); data[ id ] = value; return this.set( provider, key, data ); }, /** * Delete the cache by key. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @param {string} provider Current provider slug. * @param {string} key Cache key. * * @return {boolean|null} True on success, null on data holder failure, false on error. */ delete( provider, key ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { return null; } return __private.cache[ provider ].delete( key ); }, /** * Delete particular data from a certain key. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @example app.cache.as('provider').deleteFrom('connections', connection_id); * * @param {string} provider Current provider slug. * @param {string} key Intended to be a string, but can be everything that Map supports as a key. * @param {string} id ID for a value that should be deleted from a certain key. * * @return {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ deleteFrom( provider, key, id ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { return null; } const data = this.get( provider, key ); delete data[ id ]; return this.set( provider, key, data ); }, /** * Clear all the cache data. * * @since 1.4.7 * @since 1.5.9 Added a new parameter - provider. * * @param {string} provider Current provider slug. */ clear( provider ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { return; } __private.cache[ provider ].clear(); }, }, /** * Start the engine. DOM is not ready yet, use only to init something. * * @since 1.4.7 */ init() { // Do that when DOM is ready. $( app.ready ); }, /** * DOM is fully loaded. * Should be hooked into in addons; that need to work with DOM, templates, etc. * * @since 1.4.7 * @since 1.6.1.2 Added initialization for `__private.fields` property. */ ready() { // Save a current form fields state. __private.fields = $.extend( {}, wpf.getFields( false, true ) ); app.panelHolder = $( '#wpforms-panel-providers, #wpforms-panel-settings' ); app.Templates = WPForms.Admin.Builder.Templates; app.Templates.add( __private.config.templates ); app.bindActions(); app.ui.bindActions(); app.panelHolder.trigger( 'WPForms.Admin.Builder.Providers.ready' ); }, /** * Process all generic actions/events, mostly custom that were fired by our API. * * @since 1.4.7 * @since 1.6.1.2 Added a calling `app.updateMapSelects()` method. */ bindActions() { // On Form save - notify user about required fields. $( document ).on( 'wpformsSaved', function() { const $connectionBlocks = app.panelHolder.find( '.wpforms-builder-provider-connection' ); if ( ! $connectionBlocks.length ) { return; } // We need to show him "Required fields empty" popup only once. let isShownOnce = false; $connectionBlocks.each( function() { let isRequiredEmpty = false; // Do actually require fields checking. $( this ).find( 'input.wpforms-required, select.wpforms-required, textarea.wpforms-required' ).each( function() { const $this = $( this ), value = $this.val(); if ( _.isEmpty( value ) && ! $this.closest( '.wpforms-builder-provider-connection-block' ).hasClass( 'wpforms-hidden' ) ) { $( this ).addClass( 'wpforms-error' ); isRequiredEmpty = true; return; } $( this ).removeClass( 'wpforms-error' ); } ); // Notify user. if ( isRequiredEmpty && ! isShownOnce ) { const $titleArea = $( this ).closest( '.wpforms-builder-provider' ).find( '.wpforms-builder-provider-title' ).clone(); $titleArea.find( 'button' ).remove(); const msg = wpforms_builder.provider_required_flds; $.alert( { title: wpforms_builder.heads_up, content: msg.replace( '{provider}', '' + $titleArea.text().trim() + '' ), icon: 'fa fa-exclamation-circle', type: 'red', buttons: { confirm: { text: wpforms_builder.ok, btnClass: 'btn-confirm', keys: [ 'enter' ], }, }, } ); // Save that we have already showed the user, so we won't bug it anymore. isShownOnce = true; } } ); // On the "Fields" page additional update provider's field mapped items. if ( 'fields' === wpf.getQueryString( 'view' ) ) { app.updateMapSelects( $connectionBlocks ); } } ); /* * Update form state when each connection is loaded into the DOM. * This will prevent a please-save-prompt to appear when navigating * out and back to Marketing tab without doing any changes anywhere. */ app.panelHolder.on( 'connectionRendered', function() { if ( wpf.initialSave === true ) { wpf.savedState = wpf.getFormState( '#wpforms-builder-form' ); } } ); }, /** * Update selects for mapping if any form fields were added, deleted or changed. * * @since 1.6.1.2 * * @param {Object} $connections jQuery selector for active connections. */ // eslint-disable-next-line max-lines-per-function,complexity updateMapSelects( $connections ) { const fields = $.extend( {}, wpf.getFields() ); // We should detect changes for labels only. // noinspection JSUnusedLocalSymbols const currentSaveFields = _.mapObject( fields, function( field, key ) { // eslint-disable-line no-unused-vars return field.label; } ); // noinspection JSUnusedLocalSymbols const prevSaveFields = _.mapObject( __private.fields, function( field, key ) { // eslint-disable-line no-unused-vars return field.label; } ); // Check if a form has any fields and if they have changed labels after a previous saving process. if ( ( _.isEmpty( currentSaveFields ) && _.isEmpty( prevSaveFields ) ) || ( JSON.stringify( currentSaveFields ) === JSON.stringify( prevSaveFields ) ) ) { return; } // Prepare a current form field IDs. const fieldIds = Object.keys( currentSaveFields ) .map( function( id ) { return parseInt( id, 10 ); } ); // Determine deleted field IDs - it's a diff between previous and current form state. const deleted = Object.keys( prevSaveFields ) .map( function( id ) { return parseInt( id, 10 ); } ) .filter( function( id ) { return ! fieldIds.includes( id ); } ); // Remove from mapping selects "deleted" fields. for ( let index = 0; index < deleted.length; index++ ) { $( '.wpforms-builder-provider-connection-fields-table .wpforms-builder-provider-connection-field-value option[value="' + deleted[ index ] + '"]', $connections ).remove(); } const options = []; const optionsWithSubfields = []; for ( const orderNumber in fields ) { const field = fields[ orderNumber ]; const id = field.id; const type = field.type; const label = wpf.sanitizeHTML( field.label?.toString().trim() || wpforms_builder.field + ' #' + id ); options.push( { value: id, text: label, type } ); if ( 'name' !== field.type || ! field.format ) { optionsWithSubfields.push( { value: id, text: label } ); continue; } $.each( wpforms_builder.name_field_formats, function( valueSlug, formatLabel ) { if ( -1 !== field.format.indexOf( valueSlug ) || valueSlug === 'full' ) { optionsWithSubfields.push( { value: field.id + '.' + valueSlug, text: label + ' (' + formatLabel + ')' } ); } } ); } // Add ability to filter options for providers before rendering them. app.panelHolder.trigger( 'WPForms.Admin.Builder.Providers.FilterOptions', [ options ] ); app.panelHolder.trigger( 'WPForms.Admin.Builder.Providers.FilterOptionsWithSubfields', [ optionsWithSubfields ] ); $( '.wpforms-builder-provider-connection-fields-table .wpforms-builder-provider-connection-field-value' ).each( function() { const $select = $( this ); const value = $select.val(); const $newSelect = $select.clone().empty(); // Some providers have their own implementation of first/last name subfields // and don't have the support-subfields attribute. const isSupportSubfields = $select.data( 'support-subfields' ) || Boolean( $select.find( 'option[value$=".first"]' ).length ); const newOptions = isSupportSubfields ? optionsWithSubfields : options; const placeholder = $select.data( 'placeholder' ) && $select.data( 'placeholder' ).length ? $select.data( 'placeholder' ) : wpforms_builder_providers.custom_fields_placeholder; $newSelect.append( $( '