/* global wpforms_builder, wpforms_builder_providers, wpf */ var WPForms = window.WPForms || {}; WPForms.Admin = WPForms.Admin || {}; WPForms.Admin.Builder = WPForms.Admin.Builder || {}; /** * WPForms Providers module. * * @since 1.4.7 */ WPForms.Admin.Builder.Providers = WPForms.Admin.Builder.Providers || ( function( document, window, $ ) { 'use strict'; /** * Private functions and properties. * * @since 1.4.7 * * @type {Object} */ var __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} */ var 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 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. * * @returns {object} Ajax data. */ _mergeData: function( provider, custom ) { var 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} */ request: function( provider, custom ) { var $holder = app.getProviderHolder( provider ), $lock = $holder.find( '.wpforms-builder-provider-connections-save-lock' ), $error = $holder.find( '.wpforms-builder-provider-connections-error' ); var params = { url: wpforms_builder.ajax_url, type: 'post', dataType: 'json', beforeSend: function() { $holder.addClass( 'loading' ); $lock.val( 1 ); $error.hide(); }, }; custom.data = app.ajax._mergeData( provider, custom.data || {} ); $.extend( params, custom ); return $.ajax( params ) .fail( function( jqXHR, textStatus, errorThrown ) { /* * Right now we are logging into browser console. * In future that might be something better. */ console.error( 'provider:', provider ); console.error( jqXHR ); console.error( textStatus ); $lock.val( 1 ); $error.show(); } ) .always( function( dataOrjqXHR, textStatus, jqXHROrerrorThrown ) { $holder.removeClass( 'loading' ); if ( 'success' === textStatus ) { $lock.val( 0 ); // Update the cache when the provider data is unlocked. wpf.savedState = wpf.getFormState( '#wpforms-builder-form' ); } } ); }, }, /** * 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. * * @returns {*} Null if some error occurs. */ get: function( 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 Object is stored under 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. * * @returns {*} Null if some error occurs. */ getById: function( provider, key, id ) { if ( 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. * * @returns {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ set: function( 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. * * @returns {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ addTo: function( provider, key, id, value ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { __private.cache[ provider ] = new Map(); this.set( provider, key, {} ); } var 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. * * @returns boolean|null True on success, null on data holder failure, false on error. */ delete: function( 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. * * @returns {Map} All the cache for the provider. IE11 returns 'undefined' for an undefined reason. */ deleteFrom: function( provider, key, id ) { if ( typeof __private.cache[ provider ] === 'undefined' || ! ( __private.cache[ provider ] instanceof Map ) ) { return null; } var 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: function( 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: function() { // 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: function() { // 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: function() { // On Form save - notify user about required fields. $( document ).on( 'wpformsSaved', function() { var $connectionBlocks = app.panelHolder.find( '.wpforms-builder-provider-connection' ); if ( ! $connectionBlocks.length ) { return; } // We need to show him "Required fields empty" popup only once. var isShownOnce = false; $connectionBlocks.each( function() { var isRequiredEmpty = false; // Do the actual required fields check. $( 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 ) { var $titleArea = $( this ).closest( '.wpforms-builder-provider' ).find( '.wpforms-builder-provider-title' ).clone(); $titleArea.find( 'button' ).remove(); var 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: 'orange', 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 "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 was added, deleted or changed. * * @since 1.6.1.2 * * @param {object} $connections jQuery selector for active connections. */ updateMapSelects: function( $connections ) { var fields = $.extend( {}, wpf.getFields() ), currentSaveFields, prevSaveFields; // We should to detect changes for labels only. currentSaveFields = _.mapObject( fields, function( field, key ) { return field.label; } ); prevSaveFields = _.mapObject( __private.fields, function( field, key ) { return field.label; } ); // Check if form has any fields and if they have changed labels after previous saving process. if ( ( _.isEmpty( currentSaveFields ) && _.isEmpty( prevSaveFields ) ) || ( JSON.stringify( currentSaveFields ) === JSON.stringify( prevSaveFields ) ) ) { return; } // Prepare a current form field IDs. var 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. var 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 ( var index = 0; index < deleted.length; index++ ) { $( '.wpforms-builder-provider-connection-fields-table .wpforms-builder-provider-connection-field-value option[value="' + deleted[ index ] + '"]', $connections ).remove(); } var label, $exists; for ( var id in fields ) { // Prepare the label. if ( typeof fields[ id ].label !== 'undefined' && fields[ id ].label.toString().trim() !== '' ) { label = wpf.sanitizeHTML( fields[ id ].label.toString().trim() ); } else { label = wpforms_builder.field + ' #' + id; } // Try to find all select options by value. $exists = $( '.wpforms-builder-provider-connection-fields-table .wpforms-builder-provider-connection-field-value option[value="' + id + '"]', $connections ); // If no option was found - add a new one for all selects. if ( ! $exists.length ) { $( '.wpforms-builder-provider-connection-fields-table .wpforms-builder-provider-connection-field-value', $connections ).append( $( '