From f67491afe88a5851d791727f8fcb65671d9f0b27 Mon Sep 17 00:00:00 2001 From: David Stone Date: Mon, 18 May 2026 16:59:34 -0600 Subject: [PATCH] wip: add loading spinner and disable submit button on checkout form submission --- assets/js/activity-stream.js | 22 +- assets/js/addons.js | 210 +++--- assets/js/admin-notices.js | 58 +- assets/js/admin-screen.js | 28 +- assets/js/admin.js | 16 +- assets/js/ajax-button.js | 46 +- assets/js/app.js | 2 +- assets/js/checkout-form-editor-modal.js | 16 +- assets/js/checkout-forms-editor.js | 354 ++++----- assets/js/checkout.js | 26 +- assets/js/color-field.js | 2 +- assets/js/command-palette.js | 157 ++-- assets/js/cookie-helpers.js | 70 +- assets/js/coupon-code.js | 390 +++++----- assets/js/customizer.js | 82 +-- assets/js/dashboard-statistics.js | 374 +++++----- assets/js/dns-management.js | 75 +- assets/js/dns-table.js | 70 +- assets/js/domain-logs.js | 2 +- assets/js/edit-placeholders.js | 288 ++++---- assets/js/email-edit-page.js | 108 +-- assets/js/fields.js | 80 +- assets/js/functions.js | 32 +- assets/js/gutenberg-support.js | 46 +- assets/js/integration-test.js | 10 +- assets/js/legacy-signup.js | 22 +- assets/js/list-tables.js | 710 +++++++++--------- assets/js/network-activate.js | 16 +- assets/js/payment-status-poll.js | 110 +-- assets/js/paypal-setup-wizard.js | 14 +- assets/js/pricing-table.js | 2 +- assets/js/screenshot-scraper.js | 62 +- assets/js/setup-wizard-extra.js | 68 +- assets/js/site-maintenance.js | 58 +- assets/js/tax-rates.js | 536 +++++++------- assets/js/template-library.js | 260 +++---- assets/js/template-previewer.js | 296 ++++---- assets/js/template-switching.js | 18 +- assets/js/thank-you.js | 446 ++++++------ assets/js/toolbox.js | 2 +- assets/js/tours.js | 26 +- assets/js/url-preview.js | 46 +- assets/js/view-logs.js | 130 ++-- assets/js/visits-counter.js | 90 +-- assets/js/vue-apps.js | 474 ++++++------ assets/js/webhook-page.js | 70 +- assets/js/wu-password-reset.js | 15 +- assets/js/wu-password-toggle.js | 16 +- assets/js/wubox.js | 927 ++++++++++++------------ inc/checkout/class-checkout.php | 1 + package-lock.json | 4 +- 51 files changed, 3509 insertions(+), 3474 deletions(-) diff --git a/assets/js/activity-stream.js b/assets/js/activity-stream.js index e4c0bf7b8..62daf2e35 100644 --- a/assets/js/activity-stream.js +++ b/assets/js/activity-stream.js @@ -14,32 +14,32 @@ document.addEventListener('DOMContentLoaded', function() { error: false, errorMessage: "", }, - mounted: function() { + mounted() { this.pullQuery(); }, watch: { - queried: function(value) {}, + queried(value) {}, }, methods: { - hasMore: function() { + hasMore() { return this.queried.count > (this.page * 5) }, - refresh: function() { + refresh() { this.loading = true; this.pullQuery(); }, - navigatePrev: function() { + navigatePrev() { this.page = this.page <= 1 ? 1 : this.page - 1; this.loading = true; this.pullQuery(); }, - navigateNext: function() { + navigateNext() { this.page = this.page + 1; this.loading = true; this.pullQuery(); }, - pullQuery: function() { - var that = this; + pullQuery() { + const that = this; jQuery.ajax({ url: ajaxurl, data: { @@ -47,7 +47,7 @@ document.addEventListener('DOMContentLoaded', function() { action: 'wu_fetch_activity', page: this.page, }, - success: function(data) { + success(data) { that.loading = false; Vue.set(wuActivityStream, 'loading', false); @@ -55,14 +55,14 @@ document.addEventListener('DOMContentLoaded', function() { Vue.set(wuActivityStream, 'queried', data.data); } }, - error: function(jqXHR) { + error(jqXHR) { that.loading = false; Vue.set(wuActivityStream, 'loading', false); wu_ajax_error(jqXHR); }, }) }, - get_color_event: function(type) {}, + get_color_event(type) {}, } }); }); diff --git a/assets/js/addons.js b/assets/js/addons.js index a0e7f7c4d..d36bc96bb 100644 --- a/assets/js/addons.js +++ b/assets/js/addons.js @@ -1,161 +1,161 @@ /* global Vue, wu_addons, ajaxurl, _ */ (function($) { - const search_addon = new Vue({ - el: '#search-addons', - data: { - search: wu_addons.search, - }, - }); + const search_addon = new Vue({ + el: '#search-addons', + data: { + search: wu_addons.search, + }, + }); - const wu_main_addon_app = new Vue({ - el: '#wu-addon', - data() { + const wu_main_addon_app = new Vue({ + el: '#wu-addon', + data() { - return { - loading: true, - category: wu_addons.category, - addons: [], - }; + return { + loading: true, + category: wu_addons.category, + addons: [], + }; - }, - mounted() { + }, + mounted() { - this.fetch_addons_list(); + this.fetch_addons_list(); - }, - computed: { - search() { + }, + computed: { + search() { - return search_addon.search; + return search_addon.search; - }, - i18n() { + }, + i18n() { - return window.wu_addons.i18n; + return window.wu_addons.i18n; - }, - categories() { + }, + categories() { - let categories = []; + let categories = []; - _.each(this.addons, function(addon) { + _.each(this.addons, function(addon) { - categories = categories.concat(addon.categories); + categories = categories.concat(addon.categories); - }); + }); - return _.unique(categories); + return _.unique(categories); - }, - addons_list() { + }, + addons_list() { - const app = this; + const app = this; - return _.filter(app.addons, function(addon, slug) { + return _.filter(app.addons, function(addon, slug) { - if (app.category !== 'all' && ! addon.categories.some(cat => cat.slug === app.category) ) { + if (app.category !== 'all' && ! addon.categories.some((cat) => cat.slug === app.category) ) { - return false; + return false; - } // end if; + } // end if; - if (! app.search) { + if (! app.search) { - return true; + return true; - } // end if; + } // end if; - const search = [ - addon.slug, - addon.name, - addon.categories, - addon.description, - ]; + const search = [ + addon.slug, + addon.name, + addon.categories, + addon.description, + ]; - return search.join('').toLowerCase().indexOf(app.search.toLowerCase()) > -1; + return search.join('').toLowerCase().indexOf(app.search.toLowerCase()) > -1; - }); + }); - }, - }, - methods: { - fetch_addons_list() { + }, + }, + methods: { + fetch_addons_list() { - const app = this; + const app = this; - $.ajax({ - method: 'GET', - url: ajaxurl, - data: { - action: 'serve_addons_list', - }, - success(data) { + $.ajax({ + method: 'GET', + url: ajaxurl, + data: { + action: 'serve_addons_list', + }, + success(data) { - app.addons = data.data; + app.addons = data.data; - app.loading = false; + app.loading = false; - }, - error(jqXHR) { + }, + error(jqXHR) { - app.loading = false; + app.loading = false; - // eslint-disable-next-line no-undef - wu_ajax_error(jqXHR); + // eslint-disable-next-line no-undef + wu_ajax_error(jqXHR); - }, - }); + }, + }); - }, - }, - }); + }, + }, + }); - new Vue({ - el: '.wp-heading-inline', - data: {}, - computed: { - count() { + new Vue({ + el: '.wp-heading-inline', + data: {}, + computed: { + count() { - return wu_main_addon_app.addons_list.length; + return wu_main_addon_app.addons_list.length; - }, - }, - }); + }, + }, + }); - new Vue({ - el: '#addons-menu', - data: {}, - methods: { - set_category(category) { + new Vue({ + el: '#addons-menu', + data: {}, + methods: { + set_category(category) { - this.main_app.category = category; + this.main_app.category = category; - const url = new URL(window.location.href); + const url = new URL(window.location.href); - url.searchParams.set('tab', category); // setting your param + url.searchParams.set('tab', category); // setting your param - history.pushState({}, null, url); + history.pushState({}, null, url); - }, - }, - computed: { - main_app() { + }, + }, + computed: { + main_app() { - return wu_main_addon_app; + return wu_main_addon_app; - }, - category() { + }, + category() { - return wu_main_addon_app.category; + return wu_main_addon_app.category; - }, - available_categories() { + }, + available_categories() { - return wu_main_addon_app.categories; + return wu_main_addon_app.categories; - }, - }, - }); + }, + }, + }); }(jQuery)); diff --git a/assets/js/admin-notices.js b/assets/js/admin-notices.js index 26bff0f1a..014cd1cc2 100644 --- a/assets/js/admin-notices.js +++ b/assets/js/admin-notices.js @@ -1,43 +1,43 @@ (function($) { - $(document).ready(function() { + $(document).ready(function() { - /** - * Prevent notices from jumping around. - */ - $('.notice.wu-hidden').removeClass('wu-hidden'); + /** + * Prevent notices from jumping around. + */ + $('.notice.wu-hidden').removeClass('wu-hidden'); - /** - * Dismisses a WP Ultimo notice - * - * When a notice is dismissable, we save the key of that notice after the dismiss - * button is clicked to avoid showing that notice again for that customer in the future. - */ - $('.notice.wu-admin-notice').on('click', '.notice-dismiss', function(e) { + /** + * Dismisses a WP Ultimo notice + * + * When a notice is dismissable, we save the key of that notice after the dismiss + * button is clicked to avoid showing that notice again for that customer in the future. + */ + $('.notice.wu-admin-notice').on('click', '.notice-dismiss', function(e) { - e.preventDefault(); + e.preventDefault(); - const $this = $(this); + const $this = $(this); - const $notice = $this.parents('.notice'); + const $notice = $this.parents('.notice'); - if ($notice.find('[name="notice_id"]').val()) { + if ($notice.find('[name="notice_id"]').val()) { - $.ajax({ - method: 'post', - // eslint-disable-next-line no-undef - url: ajaxurl, - data: { - action: 'wu_dismiss_admin_notice', - nonce: $notice.find('[name="nonce"]').val(), - notice_id: $notice.find('[name="notice_id"]').val(), - }, - }); + $.ajax({ + method: 'post', + // eslint-disable-next-line no-undef + url: ajaxurl, + data: { + action: 'wu_dismiss_admin_notice', + nonce: $notice.find('[name="nonce"]').val(), + notice_id: $notice.find('[name="notice_id"]').val(), + }, + }); - } // end if; + } // end if; - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/admin-screen.js b/assets/js/admin-screen.js index 98181ed64..6c99a2e7d 100644 --- a/assets/js/admin-screen.js +++ b/assets/js/admin-screen.js @@ -2,32 +2,32 @@ /* global wu_admin_screen, wu_block_ui */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - $('body').on('click', '#wu-admin-screen-customize', function() { + $('body').on('click', '#wu-admin-screen-customize', function() { - wu_block_ui('#wpcontent'); + wu_block_ui('#wpcontent'); - }); + }); - const is_edit_mode = $('body').hasClass('wu-customize-admin-screen'); + const is_edit_mode = $('body').hasClass('wu-customize-admin-screen'); - let $elem = `${ wu_admin_screen.i18n.customize_label }`; + let $elem = `${ wu_admin_screen.i18n.customize_label }`; - const $page_elem = `${ wu_admin_screen.i18n.page_customize_label }`; + const $page_elem = `${ wu_admin_screen.i18n.page_customize_label }`; - if (is_edit_mode) { + if (is_edit_mode) { - $elem = `${ wu_admin_screen.i18n.close_label }`; + $elem = `${ wu_admin_screen.i18n.close_label }`; - } else { + } else { - $($page_elem).prependTo('#screen-options-link-wrap'); + $($page_elem).prependTo('#screen-options-link-wrap'); - } // end if; + } // end if; - $($elem).appendTo('#screen-options-link-wrap'); + $($elem).appendTo('#screen-options-link-wrap'); - }); + }); }(jQuery)); diff --git a/assets/js/admin.js b/assets/js/admin.js index a0e4e1c4e..66b06ffba 100644 --- a/assets/js/admin.js +++ b/assets/js/admin.js @@ -1,16 +1,16 @@ /* global wu_on_load */ (function($) { - // eslint-disable-next-line no-undef - wu = { - tables: {}, - configs: {}, - }; + // eslint-disable-next-line no-undef + wu = { + tables: {}, + configs: {}, + }; - $(document).ready(function() { + $(document).ready(function() { - wu_on_load(); + wu_on_load(); - }); + }); }(jQuery)); diff --git a/assets/js/ajax-button.js b/assets/js/ajax-button.js index 9ac56ca3d..0be4b791c 100644 --- a/assets/js/ajax-button.js +++ b/assets/js/ajax-button.js @@ -6,34 +6,34 @@ function (e) { e.preventDefault(); - var $this = $(this); - var default_label = $this.html(); - var action_url = $this.data('action-url'); + const $this = $(this); + const default_label = $this.html(); + const action_url = $this.data('action-url'); $this.html('...').attr('disabled', 'disabled'); - $.ajax( - { - url: action_url, - dataType: 'json', - success: function (response) { - $this.html(response.message); + $.ajax( + { + url: action_url, + dataType: 'json', + success (response) { + $this.html(response.message); - setTimeout( - function () { - $this.html(default_label).removeAttr('disabled'); - }, - 4000 - ); - }, - error: function (jqXHR) { - $this.html(default_label).removeAttr('disabled'); - wu_ajax_error(jqXHR); - }, - } - ); + setTimeout( + function () { + $this.html(default_label).removeAttr('disabled'); + }, + 4000 + ); + }, + error (jqXHR) { + $this.html(default_label).removeAttr('disabled'); + wu_ajax_error(jqXHR); + }, + } + ); } ); } ); -})(jQuery); \ No newline at end of file +}(jQuery)); \ No newline at end of file diff --git a/assets/js/app.js b/assets/js/app.js index 625ec2638..14efdc916 100644 --- a/assets/js/app.js +++ b/assets/js/app.js @@ -1,3 +1,3 @@ (() => { -"use strict"; + "use strict"; })() \ No newline at end of file diff --git a/assets/js/checkout-form-editor-modal.js b/assets/js/checkout-form-editor-modal.js index 034a72af1..ce438ad32 100644 --- a/assets/js/checkout-form-editor-modal.js +++ b/assets/js/checkout-form-editor-modal.js @@ -1,24 +1,24 @@ /* global wubox */ wp.hooks.addAction('wu_add_checkout_form_field_mounted', 'nextpress/wp-ultimo', function(data) { - if (data.type === '') { + if (data.type === '') { - wubox.width(600); + wubox.width(600); - } // end if; + } // end if; }); wp.hooks.addAction('wu_add_checkout_form_field_changed', 'nextpress/wp-ultimo', function(val, data) { - if (data.type === '') { + if (data.type === '') { - wubox.width(600); + wubox.width(600); - } else { + } else { - wubox.width(400); + wubox.width(400); - }// end if; + }// end if; }); diff --git a/assets/js/checkout-forms-editor.js b/assets/js/checkout-forms-editor.js index a57b4a97b..41176a4af 100644 --- a/assets/js/checkout-forms-editor.js +++ b/assets/js/checkout-forms-editor.js @@ -1,287 +1,287 @@ /* global vuedraggable, Vue, wu_checkout_forms_editor_app, wu_checkout_form, _, ajaxurl, wu_initialize_tooltip, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - const draggable_table = { - components: { - vuedraggable, - }, - template: '#wu-table', - props: ['list', 'headers', 'step_name'], - name: 'wu-draggable-table', - data() { + const draggable_table = { + components: { + vuedraggable, + }, + template: '#wu-table', + props: [ 'list', 'headers', 'step_name' ], + name: 'wu-draggable-table', + data() { - return { - delete_field_id: '', - }; + return { + delete_field_id: '', + }; - }, - methods: { - remove_field(field) { + }, + methods: { + remove_field(field) { - wu_checkout_forms_editor_app.remove_field(this.step_name, field); + wu_checkout_forms_editor_app.remove_field(this.step_name, field); - this.delete_field_id = ''; + this.delete_field_id = ''; - }, - }, - }; + }, + }, + }; - wu_checkout_forms_editor_app = new Vue({ - el: '#wu-checkout-editor-app', - name: 'CheckoutEditor', - data() { + wu_checkout_forms_editor_app = new Vue({ + el: '#wu-checkout-editor-app', + name: 'CheckoutEditor', + data() { - return Object.assign({}, { - dragging: false, - search: '', - delete_step_id: '', - preview_error: false, - preview: false, - loading_preview: false, - preview_content: '', - iframe_preview_url: '', - }, wu_checkout_form); + return Object.assign({}, { + dragging: false, + search: '', + delete_step_id: '', + preview_error: false, + preview: false, + loading_preview: false, + preview_content: '', + iframe_preview_url: '', + }, wu_checkout_form); - }, - components: { - vuedraggable, - 'wu-draggable-table': draggable_table, - }, - computed: { - field_count() { + }, + components: { + vuedraggable, + 'wu-draggable-table': draggable_table, + }, + computed: { + field_count() { - return _.reduce(this.steps, function(memo, step) { + return _.reduce(this.steps, function(memo, step) { - return memo + step.fields.length; + return memo + step.fields.length; - }, 0); + }, 0); - }, - }, - watch: { - steps: { + }, + }, + watch: { + steps: { - handler() { + handler() { - this.update_session(); + this.update_session(); - }, + }, - deep: true, + deep: true, - }, - }, - mounted() { + }, + }, + mounted() { - this.update_session(); + this.update_session(); - }, - methods: { - get_preview(type = null) { + }, + methods: { + get_preview(type = null) { - if (type === null) { + if (type === null) { - this.preview = ! this.preview; + this.preview = ! this.preview; - } else { + } else { - this.preview = true; + this.preview = true; - } // end if; + } // end if; - if (this.preview) { + if (this.preview) { - this.loading_preview = true; + this.loading_preview = true; - const that = this; + const that = this; - const preview_type = type !== null ? type : 'user'; + const preview_type = type !== null ? type : 'user'; - // eslint-disable-next-line max-len - that.iframe_preview_url = that.register_page + '?action=wu_generate_checkout_form_preview' + '&form_id=' + that.form_id + '&type=' + preview_type + '&uniq=' + (Math.random() * 1000); + // eslint-disable-next-line max-len + that.iframe_preview_url = that.register_page + '?action=wu_generate_checkout_form_preview' + '&form_id=' + that.form_id + '&type=' + preview_type + '&uniq=' + (Math.random() * 1000); - $('#wp-ultimo-checkout-preview').off('load').one('load', function() { + $('#wp-ultimo-checkout-preview').off('load').one('load', function() { - that.loading_preview = false; + that.loading_preview = false; - setTimeout(() => { + setTimeout(() => { - const height = document.getElementById('wp-ultimo-checkout-preview').contentWindow.document.body.scrollHeight; + const height = document.getElementById('wp-ultimo-checkout-preview').contentWindow.document.body.scrollHeight; - $('#wp-ultimo-checkout-preview').animate({ - height, - }); + $('#wp-ultimo-checkout-preview').animate({ + height, + }); - }, 1000); + }, 1000); - }); + }); - } // end if; + } // end if; - }, - add_step(data, cb = null) { + }, + add_step(data, cb = null) { - const existing_step = data.original_id ? this.find_step(data.original_id) : this.find_step(data.id) ; + const existing_step = data.original_id ? this.find_step(data.original_id) : this.find_step(data.id); - delete data.original_id; + delete data.original_id; - if (typeof existing_step !== 'undefined') { + if (typeof existing_step !== 'undefined') { - const index = _.indexOf(this.steps, existing_step); + const index = _.indexOf(this.steps, existing_step); - data = Object.assign({}, existing_step, data); + data = Object.assign({}, existing_step, data); - data.fields = existing_step.fields; + data.fields = existing_step.fields; - Vue.set(this.steps, index, data); + Vue.set(this.steps, index, data); - } else { + } else { - this.steps.push(data); + this.steps.push(data); - } // end if; + } // end if; - this.$nextTick(function() { + this.$nextTick(function() { - if (typeof cb === 'function') { + if (typeof cb === 'function') { - cb(); + cb(); - this.scroll_to(`wp-ultimo-list-table-${ data.id }`); + this.scroll_to(`wp-ultimo-list-table-${ data.id }`); - } // end if; + } // end if; - }); + }); - }, - add_field(data, cb = null) { + }, + add_field(data, cb = null) { - const step = _.findWhere(this.steps, { - id: data.step, - }); + const step = _.findWhere(this.steps, { + id: data.step, + }); - let existing_field = this.find_field(data.step, data.id); + let existing_field = this.find_field(data.step, data.id); - if (typeof existing_field === 'undefined') { + if (typeof existing_field === 'undefined') { - existing_field = this.find_field(data.step, data.original_id); + existing_field = this.find_field(data.step, data.original_id); - delete data.original_id; + delete data.original_id; - } // end if; + } // end if; - if (typeof existing_field !== 'undefined') { + if (typeof existing_field !== 'undefined') { - const index = _.indexOf(step.fields, existing_field); + const index = _.indexOf(step.fields, existing_field); - Vue.set(step.fields, index, data); + Vue.set(step.fields, index, data); - } else { + } else { - step.fields.push(data); + step.fields.push(data); - } // end if; + } // end if; - this.$nextTick(function() { + this.$nextTick(function() { - if (typeof cb === 'function') { + if (typeof cb === 'function') { - cb(); + cb(); - this.scroll_to(`wp-ultimo-field-${ data.id }`); + this.scroll_to(`wp-ultimo-field-${ data.id }`); - } // end if; + } // end if; - }); + }); - }, - scroll_to(element_id) { + }, + scroll_to(element_id) { - this.$nextTick(function() { + this.$nextTick(function() { - setTimeout(() => { + setTimeout(() => { - const element = document.getElementById(element_id); + const element = document.getElementById(element_id); - element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' }); + element.scrollIntoView({ behavior: 'smooth', block: 'center', inline: 'nearest' }); - }, 500); + }, 500); - }); + }); - }, - find_step(step_name) { + }, + find_step(step_name) { - return _.findWhere(this.steps, { - id: step_name, - }); + return _.findWhere(this.steps, { + id: step_name, + }); - }, - find_field(step_name, field_name) { + }, + find_field(step_name, field_name) { - const step = _.findWhere(this.steps, { - id: step_name, - }); + const step = _.findWhere(this.steps, { + id: step_name, + }); - const field = _.findWhere(step.fields, { - id: field_name, - }); + const field = _.findWhere(step.fields, { + id: field_name, + }); - return field; + return field; - }, - remove_step(step_name) { + }, + remove_step(step_name) { - this.steps = _.reject(this.steps, function(item) { + this.steps = _.reject(this.steps, function(item) { - return item.id === step_name; + return item.id === step_name; - }); + }); - this.delete_step_id = ''; + this.delete_step_id = ''; - }, - remove_field(step_name, field_name) { + }, + remove_field(step_name, field_name) { - const step = _.findWhere(this.steps, { - id: step_name, - }); + const step = _.findWhere(this.steps, { + id: step_name, + }); - step.fields = _.reject(step.fields, function(item) { + step.fields = _.reject(step.fields, function(item) { - return item.id === field_name; + return item.id === field_name; - }); + }); - }, - update_session() { + }, + update_session() { - wu_initialize_tooltip(); + wu_initialize_tooltip(); - const that = this; + const that = this; - $.ajax({ - method: 'post', - url: ajaxurl, - data: { - action: 'wu_save_editor_session', - settings: that.steps, - form_id: that.form_id, - }, - success() { }, - error(jqXHR) { + $.ajax({ + method: 'post', + url: ajaxurl, + data: { + action: 'wu_save_editor_session', + settings: that.steps, + form_id: that.form_id, + }, + success() { }, + error(jqXHR) { - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, - }); + }, + }); - }, - }, - }); + }, + }, + }); - }); + }); }(jQuery)); diff --git a/assets/js/checkout.js b/assets/js/checkout.js index 902ebd026..2ff45a357 100644 --- a/assets/js/checkout.js +++ b/assets/js/checkout.js @@ -1031,19 +1031,24 @@ this.create_order(); }, - block() { + block(message) { /* - * Get the first bg color from a parent. - */ + * Get the first bg color from a parent. + */ const bg_color = jQuery(this.$el).parents().filter(function () { return $(this).css('backgroundColor') !== 'rgba(0, 0, 0, 0)'; }).first().css('backgroundColor'); + // Default message if none provided + if (! message) { + message = '
'; + } + jQuery(this.$el).wu_block({ - message: '
', + message, overlayCSS: { backgroundColor: bg_color ? bg_color : '#ffffff', opacity: 0.6, @@ -1622,7 +1627,18 @@ } // end if; - that.block(); + // Disable all submit buttons to prevent double-clicks + jQuery(this).find('button[type="submit"]').prop('disabled', true); + + // Show loading message with status text + const loadingMessage = '
' + + '
' + + '
' + + (wu_checkout.i18n.provisioning_site || 'Provisioning your site — this can take up to 60 seconds.') + + '
' + + '
'; + + that.block(loadingMessage); try { diff --git a/assets/js/color-field.js b/assets/js/color-field.js index 79f12fe03..1cf3d7e12 100644 --- a/assets/js/color-field.js +++ b/assets/js/color-field.js @@ -7,4 +7,4 @@ }); } }); -})(jQuery); \ No newline at end of file +}(jQuery)); \ No newline at end of file diff --git a/assets/js/command-palette.js b/assets/js/command-palette.js index 281f6de3b..8c66e200a 100644 --- a/assets/js/command-palette.js +++ b/assets/js/command-palette.js @@ -11,7 +11,8 @@ * Icons use wp.primitives (SVG/Path) when available — the same approach WordPress * core uses in @wordpress/core-commands. There is no global wp.icons package. * - * @package WP_Ultimo + * @param wp + * @package * @since 2.1.0 */ @@ -19,30 +20,30 @@ 'use strict'; // Bail if the minimum required APIs are not available (WP 6.4+). - if (!wp || !wp.commands || !wp.element || !wp.data) { + if (! wp || ! wp.commands || ! wp.element || ! wp.data) { return; } - var createElement = wp.element.createElement; - var useState = wp.element.useState; - var useEffect = wp.element.useEffect; - var useRef = wp.element.useRef; - var __ = wp.i18n.__; - var apiFetch = wp.apiFetch; + const createElement = wp.element.createElement; + const useState = wp.element.useState; + const useEffect = wp.element.useEffect; + const useRef = wp.element.useRef; + const __ = wp.i18n.__; + const apiFetch = wp.apiFetch; // Progressive enhancement: wp.primitives for SVG icons (WP 6.1+). - var SVG = wp.primitives ? wp.primitives.SVG : null; - var Path = wp.primitives ? wp.primitives.Path : null; + const SVG = wp.primitives ? wp.primitives.SVG : null; + const Path = wp.primitives ? wp.primitives.Path : null; // Progressive enhancement: wp.compose.useDebounce (WP 6.1+). - var useDebounce = wp.compose && wp.compose.useDebounce ? wp.compose.useDebounce : null; + const useDebounce = wp.compose && wp.compose.useDebounce ? wp.compose.useDebounce : null; // Get configuration from localized script. - var config = window.wuCommandPalette || {}; - var entities = config.entities || {}; - var restUrl = config.restUrl || ''; - var networkAdminUrl = config.networkAdminUrl || ''; - var customLinks = config.customLinks || []; + const config = window.wuCommandPalette || {}; + const entities = config.entities || {}; + const restUrl = config.restUrl || ''; + const networkAdminUrl = config.networkAdminUrl || ''; + const customLinks = config.customLinks || []; /** * SVG icon definitions using wp.primitives. @@ -57,7 +58,7 @@ * * @type {Object|null} */ - var icons = (SVG && Path) ? { + const icons = (SVG && Path) ? { 'admin-users': createElement(SVG, { xmlns: 'http://www.w3.org/2000/svg', viewBox: '0 0 24 24' @@ -171,11 +172,11 @@ * @return {Object|undefined} React element or undefined. */ function getIcon(name) { - if (!icons) { + if (! icons) { return undefined; } - return icons[name] || undefined; + return icons[ name ] || undefined; } /** @@ -189,25 +190,25 @@ * @param {string} value The value to debounce. * @return {string} The debounced value. */ - var useDebouncedValue = useDebounce + const useDebouncedValue = useDebounce ? function useDebouncedValueCompose(value) { - var _state = useState(''), - debouncedValue = _state[0], - setDebouncedValue = _state[1]; - var debounced = useDebounce(setDebouncedValue, 250); + const _state = useState(''), + debouncedValue = _state[ 0 ], + setDebouncedValue = _state[ 1 ]; + const debounced = useDebounce(setDebouncedValue, 250); useEffect(function () { debounced(value); return function () { debounced.cancel(); }; - }, [value, debounced]); + }, [ value, debounced ]); return debouncedValue; } : function useDebouncedValueFallback(value) { - var _state = useState(''), - debouncedValue = _state[0], - setDebouncedValue = _state[1]; - var timeoutRef = useRef(null); + const _state = useState(''), + debouncedValue = _state[ 0 ], + setDebouncedValue = _state[ 1 ]; + const timeoutRef = useRef(null); useEffect(function () { if (timeoutRef.current) { clearTimeout(timeoutRef.current); @@ -220,7 +221,7 @@ clearTimeout(timeoutRef.current); } }; - }, [value]); + }, [ value ]); return debouncedValue; }; @@ -231,48 +232,48 @@ * search input, caches results, and returns commands with proper * categories and icons when available. * - * @param {Object} params Parameters object. + * @param {Object} params Parameters object. * @param {string} params.search The search term. * @return {Object} Commands and loading state. */ function useEntitySearch({ search }) { - var _useState = useState([]), - commands = _useState[0], - setCommands = _useState[1]; - var _useLoading = useState(false), - isLoading = _useLoading[0], - setIsLoading = _useLoading[1]; - var cacheRef = useRef({}); + const _useState = useState([]), + commands = _useState[ 0 ], + setCommands = _useState[ 1 ]; + const _useLoading = useState(false), + isLoading = _useLoading[ 0 ], + setIsLoading = _useLoading[ 1 ]; + const cacheRef = useRef({}); - var debouncedSearch = useDebouncedValue(search || ''); + const debouncedSearch = useDebouncedValue(search || ''); // Fetch results when debounced search changes. useEffect(function () { - if (!debouncedSearch || debouncedSearch.length < 2) { + if (! debouncedSearch || debouncedSearch.length < 2) { setCommands([]); setIsLoading(false); return; } // Check cache. - if (cacheRef.current[debouncedSearch]) { - setCommands(cacheRef.current[debouncedSearch]); + if (cacheRef.current[ debouncedSearch ]) { + setCommands(cacheRef.current[ debouncedSearch ]); setIsLoading(false); return; } setIsLoading(true); - var searchUrl = restUrl + '?' + new URLSearchParams({ + const searchUrl = restUrl + '?' + new URLSearchParams({ query: debouncedSearch, limit: 15 }).toString(); apiFetch({ url: searchUrl }) .then(function (response) { - var results = response.results || []; + const results = response.results || []; - var cmds = results.map(function (result) { + const cmds = results.map(function (result) { return { name: 'ultimate-multisite/' + result.type + '-' + result.id, label: result.title, @@ -281,14 +282,14 @@ // WP 7+: category label shown in palette UI. // WP 6.x: ignored safely, defaults to 'action' internally. category: 'action', - callback: function ({ close }) { + callback ({ close }) { close(); window.location.href = result.url; } }; }); - cacheRef.current[debouncedSearch] = cmds; + cacheRef.current[ debouncedSearch ] = cmds; setCommands(cmds); setIsLoading(false); }) @@ -296,11 +297,11 @@ setCommands([]); setIsLoading(false); }); - }, [debouncedSearch]); + }, [ debouncedSearch ]); return { - commands: commands, - isLoading: isLoading + commands, + isLoading }; } @@ -311,11 +312,11 @@ * searches entities via the REST API as the user types. */ function registerEntitySearchLoader() { - if (!wp.commands.store) { + if (! wp.commands.store) { return; } - var dispatch = wp.data.dispatch(wp.commands.store); + const dispatch = wp.data.dispatch(wp.commands.store); dispatch.registerCommandLoader({ name: 'ultimate-multisite/entity-search', @@ -329,11 +330,11 @@ * These are user-defined links configured in Ultimate Multisite settings. */ function registerCustomLinks() { - if (!customLinks || customLinks.length === 0 || !wp.commands.store) { + if (! customLinks || customLinks.length === 0 || ! wp.commands.store) { return; } - var dispatch = wp.data.dispatch(wp.commands.store); + const dispatch = wp.data.dispatch(wp.commands.store); customLinks.forEach(function (link, index) { dispatch.registerCommand({ @@ -342,7 +343,7 @@ icon: getIcon('external'), // WP 7+: shows "View" category label. WP 6.x: ignored safely. category: 'view', - callback: function ({ close }) { + callback ({ close }) { close(); window.location.href = link.url; } @@ -364,11 +365,11 @@ * - keywords: WP 7+ uses these for additional search matching */ function registerStaticCommands() { - if (!wp.commands.store) { + if (! wp.commands.store) { return; } - var dispatch = wp.data.dispatch(wp.commands.store); + const dispatch = wp.data.dispatch(wp.commands.store); // Dashboard command with keywords for discoverability. dispatch.registerCommand({ @@ -376,8 +377,8 @@ label: __('Ultimate Multisite Dashboard', 'ultimate-multisite'), icon: getIcon('dashboard'), category: 'view', - keywords: ['waas', 'multisite', 'network', 'overview'], - callback: function ({ close }) { + keywords: [ 'waas', 'multisite', 'network', 'overview' ], + callback ({ close }) { close(); window.location.href = networkAdminUrl + 'admin.php?page=wp-ultimo'; } @@ -389,8 +390,8 @@ label: __('Ultimate Multisite Settings', 'ultimate-multisite'), icon: getIcon('admin-settings'), category: 'view', - keywords: ['configuration', 'options', 'setup'], - callback: function ({ close }) { + keywords: [ 'configuration', 'options', 'setup' ], + callback ({ close }) { close(); window.location.href = networkAdminUrl + 'admin.php?page=wp-ultimo-settings'; } @@ -402,38 +403,38 @@ label: __('System Information', 'ultimate-multisite'), icon: getIcon('info'), category: 'view', - keywords: ['debug', 'status', 'health', 'diagnostics'], - callback: function ({ close }) { + keywords: [ 'debug', 'status', 'health', 'diagnostics' ], + callback ({ close }) { close(); window.location.href = networkAdminUrl + 'admin.php?page=wp-ultimo-system-info'; } }); // Entity-specific keywords for better search matching (WP 7+). - var entityKeywords = { - customer: ['users', 'subscribers', 'clients', 'accounts'], - site: ['subsites', 'blogs', 'websites', 'domains'], - membership: ['subscriptions', 'plans', 'recurring'], - payment: ['transactions', 'invoices', 'billing', 'revenue'], - product: ['plans', 'pricing', 'packages', 'offers'], - domain: ['domains', 'mapping', 'dns', 'urls'], - discount_code: ['coupons', 'promotions', 'discounts', 'vouchers'], - webhook: ['hooks', 'integrations', 'api', 'notifications'], - broadcast: ['emails', 'messages', 'announcements', 'notifications'], - checkout_form: ['forms', 'registration', 'signup', 'onboarding'] + const entityKeywords = { + customer: [ 'users', 'subscribers', 'clients', 'accounts' ], + site: [ 'subsites', 'blogs', 'websites', 'domains' ], + membership: [ 'subscriptions', 'plans', 'recurring' ], + payment: [ 'transactions', 'invoices', 'billing', 'revenue' ], + product: [ 'plans', 'pricing', 'packages', 'offers' ], + domain: [ 'domains', 'mapping', 'dns', 'urls' ], + discount_code: [ 'coupons', 'promotions', 'discounts', 'vouchers' ], + webhook: [ 'hooks', 'integrations', 'api', 'notifications' ], + broadcast: [ 'emails', 'messages', 'announcements', 'notifications' ], + checkout_form: [ 'forms', 'registration', 'signup', 'onboarding' ] }; // Register list pages for each entity type. Object.keys(entities).forEach(function (slug) { - var entity = entities[slug]; + const entity = entities[ slug ]; dispatch.registerCommand({ name: 'ultimate-multisite/list-' + slug, label: entity.label_plural || entity.label + 's', icon: getIcon(entity.icon), category: 'view', - keywords: entityKeywords[slug] || [], - callback: function ({ close }) { + keywords: entityKeywords[ slug ] || [], + callback ({ close }) { close(); window.location.href = networkAdminUrl + 'admin.php?page=wu-' + slug.replaceAll('_', '-') + 's'; } @@ -457,4 +458,4 @@ init(); -})(window.wp); +}(window.wp)); diff --git a/assets/js/cookie-helpers.js b/assets/js/cookie-helpers.js index 72cc361f2..604ad6fac 100644 --- a/assets/js/cookie-helpers.js +++ b/assets/js/cookie-helpers.js @@ -1,30 +1,30 @@ /** * Create a new cookie. * - * @param {string} name The cookie name. - * @param {*} value The cookie value. - * @param {number} days The expiration, in days. + * @param {string} name The cookie name. + * @param {*} value The cookie value. + * @param {number} days The expiration, in days. * @return {void} */ window.wu_create_cookie = function(name, value, days) { - let expires; + let expires; - if (days) { + if (days) { - const date = new Date(); + const date = new Date(); - date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); + date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000)); - expires = '; expires=' + date.toGMTString(); + expires = '; expires=' + date.toGMTString(); - } else { + } else { - expires = ''; + expires = ''; - } // end if; + } // end if; - document.cookie = name + '=' + value + expires + '; path=/'; + document.cookie = name + '=' + value + expires + '; path=/'; }; @@ -36,29 +36,29 @@ window.wu_create_cookie = function(name, value, days) { */ window.wu_read_cookie = function(name) { - const nameEQ = name + '='; + const nameEQ = name + '='; - const ca = document.cookie.split(';'); + const ca = document.cookie.split(';'); - for (let i = 0; i < ca.length; i++) { + for (let i = 0; i < ca.length; i++) { - let c = ca[i]; + let c = ca[ i ]; - while (c.charAt(0) === ' ') { + while (c.charAt(0) === ' ') { - c = c.substring(1, c.length); + c = c.substring(1, c.length); - } // end while; + } // end while; - if (c.indexOf(nameEQ) === 0) { + if (c.indexOf(nameEQ) === 0) { - return c.substring(nameEQ.length, c.length); + return c.substring(nameEQ.length, c.length); - } // end if; + } // end if; - } // end for; + } // end for; - return null; + return null; }; @@ -69,33 +69,33 @@ window.wu_read_cookie = function(name) { */ window.wu_erase_cookie = function(name) { - window.wu_create_cookie(name, '', -1); + window.wu_create_cookie(name, '', -1); }; /** * Listens to a particular cookie to catch a change in value. * - * @param {string} name The cookie name. + * @param {string} name The cookie name. * @param {Function} callback The callback to call when a change is detected. */ window.wu_listen_to_cookie_change = function(name, callback) { - let cookie_value = window.wu_read_cookie(name); + let cookie_value = window.wu_read_cookie(name); - setInterval(function() { + setInterval(function() { - const new_cookie_value = window.wu_read_cookie(name); + const new_cookie_value = window.wu_read_cookie(name); - if (new_cookie_value !== cookie_value) { + if (new_cookie_value !== cookie_value) { - // update registry so we dont get triggered again - cookie_value = new_cookie_value; + // update registry so we dont get triggered again + cookie_value = new_cookie_value; - callback(cookie_value); + callback(cookie_value); - } // end if; + } // end if; - }, 100); + }, 100); }; diff --git a/assets/js/coupon-code.js b/assets/js/coupon-code.js index 6e0707d55..955362414 100644 --- a/assets/js/coupon-code.js +++ b/assets/js/coupon-code.js @@ -1,330 +1,326 @@ (function($) { -var coupon_app = new Vue({ - el: "#coupon-code-app", - data: { - coupon_id: '', - coupon: wu_coupon_data.coupon, - type: wu_coupon_data.type, - value: parseFloat(wu_coupon_data.value), - applies_to_setup_fee: wu_coupon_data.applies_to_setup_fee, - setup_fee_discount_value: parseFloat(wu_coupon_data.setup_fee_discount_value), - setup_fee_discount_type: wu_coupon_data.setup_fee_discount_type, - allowed_plans: wu_coupon_data.allowed_plans, - allowed_freqs: wu_coupon_data.allowed_freqs, - success: false, - }, - mounted: function() { + var coupon_app = new Vue({ + el: "#coupon-code-app", + data: { + coupon_id: '', + coupon: wu_coupon_data.coupon, + type: wu_coupon_data.type, + value: parseFloat(wu_coupon_data.value), + applies_to_setup_fee: wu_coupon_data.applies_to_setup_fee, + setup_fee_discount_value: parseFloat(wu_coupon_data.setup_fee_discount_value), + setup_fee_discount_type: wu_coupon_data.setup_fee_discount_type, + allowed_plans: wu_coupon_data.allowed_plans, + allowed_freqs: wu_coupon_data.allowed_freqs, + success: false, + }, + mounted() { - this.apply_coupon(); - this.add_event_tabs(); + this.apply_coupon(); + this.add_event_tabs(); - }, - methods: { + }, + methods: { - remove_coupon: function() { + remove_coupon() { - // Clear current coupon and re-apply pricing without discounts - this.coupon = false; - this.apply_coupon(); + // Clear current coupon and re-apply pricing without discounts + this.coupon = false; + this.apply_coupon(); - }, + }, - add_event_tabs: function() { + add_event_tabs() { - $('.wu-plans-frequency-selector li a').each(function() { + $('.wu-plans-frequency-selector li a').each(function() { - this.addEventListener('click',function() { - coupon_app.apply_coupon(); - }); + this.addEventListener('click', function() { + coupon_app.apply_coupon(); + }); - }); + }); + }, - }, + apply_coupon() { - apply_coupon: function() { + if (this.coupon) { - if(this.coupon) { + $("body").block({ + message: null, + overlayCSS: { + background: "#F1F1F1", + opacity: 0.6 + } + }); - $("body").block({ - message: null, - overlayCSS: { - background: "#F1F1F1", - opacity: 0.6 - } - }); + this.coupon_id = this.coupon.id; - this.coupon_id = this.coupon.id; + const coupon_type = this.type; - var coupon_type = this.type; + const coupon_value = this.value; - var coupon_value = this.value; + const applies_to_setup_fee = this.applies_to_setup_fee; + const setup_fee_discount_value = this.setup_fee_discount_value; + const setup_fee_discount_type = this.setup_fee_discount_type; + const allowed_plans = $.parseJSON(this.allowed_plans); + const allowed_freqs = $.parseJSON(this.allowed_freqs); - var applies_to_setup_fee = this.applies_to_setup_fee; - var setup_fee_discount_value = this.setup_fee_discount_value; - var setup_fee_discount_type = this.setup_fee_discount_type; - var allowed_plans = $.parseJSON(this.allowed_plans); - var allowed_freqs = $.parseJSON(this.allowed_freqs); + //$('#signupform').append($('#coupon_id')); - //$('#signupform').append($('#coupon_id')); + $('.superscript').show(); + $('h5 sub').show(); - $('.superscript').show(); - $('h5 sub').show(); + setTimeout( function() { + $('.wu-plan').each(function() { - setTimeout( function() { $('.wu-plan').each(function() { + if (! $(this).find('.old-price').get(0)) { - if (!$(this).find('.old-price').get(0)) { + $(this).find('h4').after('
--
'); - $(this).find('h4').after('
--
'); + } - } + const plan_id = $(this).data('plan'); - let plan_id = $(this).data('plan'); + let is_allowed_plan = false; - let is_allowed_plan = false; + let is_allowed_freq = false; - let is_allowed_freq = false; + // check plan is_allowed + if (typeof allowed_plans === 'object'){ - // check plan is_allowed - if (typeof allowed_plans === 'object'){ + for (const each_plan of allowed_plans) { - for (var each_plan of allowed_plans) { + if (parseInt(each_plan) == plan_id) { + is_allowed_plan = true; + } - if (parseInt(each_plan) == plan_id) { - is_allowed_plan = true; - } + } - } + } else { + is_allowed_plan = true; + } - } else { - is_allowed_plan = true; - } + // check freq is_allowed - // check freq is_allowed + if (typeof allowed_freqs === 'object'){ - if (typeof allowed_freqs === 'object'){ + for (const each_freq of allowed_freqs) { - for (var each_freq of allowed_freqs) { + if (each_freq == $('#wu_plan_freq').val()) { + is_allowed_freq = true; + } - if (each_freq == $('#wu_plan_freq').val()) { - is_allowed_freq = true; - } + } - } + } else { + is_allowed_freq = true; + } - } else { - is_allowed_freq = true; - } + if (! is_allowed_plan) { - if (!is_allowed_plan) { + $("body").unblock(); + return; - $("body").unblock(); - return; + } - } + if (! is_allowed_freq) { - if (!is_allowed_freq) { + $("body").unblock(); + $(".old-price").hide(); + $(".off-value").hide(); + return; - $("body").unblock(); - $(".old-price").hide(); - $(".off-value").hide(); - return; + } - } else { + $(".old-price").show(); + $(".off-value").show(); - $(".old-price").show(); - $(".off-value").show(); + let old_price = $(this).data('price-' + $('#wu_plan_freq').val()); - } + old_price = wu_fix_money_string(old_price); - let old_price = $(this).data('price-' + $('#wu_plan_freq').val()); + let new_price = 0; - old_price = wu_fix_money_string(old_price); + const old_yearly_value = old_price * jQuery('#wu_plan_freq').val(); - let new_price = 0; + let new_yearly_value = 0; - let old_yearly_value = old_price * jQuery('#wu_plan_freq').val(); + const old_setupfee = $(this).find('.pricing-table-setupfee') ? $(this).find('.pricing-table-setupfee').attr('data-value') : 0; - let new_yearly_value = 0; + let new_setupfee = 0; - let old_setupfee = $(this).find('.pricing-table-setupfee') ? $(this).find('.pricing-table-setupfee').attr('data-value') : 0; + let off_with_symbol = ''; - let new_setupfee = 0; + // OFF RENDER + if (coupon_type != '"absolute"') { + off_with_symbol = ''.concat(coupon_value, '%'); + } else { + off_with_symbol = accounting.formatMoney(parseFloat(coupon_value)); + } - let off_with_symbol = ''; + $(this).find('.old-price').html(accounting.formatMoney(parseFloat(old_price))); + if (! $(this).find('.off-value').get(0)) { - // OFF RENDER - if (coupon_type != '"absolute"') - off_with_symbol = ''.concat(coupon_value, '%'); - else - off_with_symbol = accounting.formatMoney(parseFloat(coupon_value)); + $(this).find('.old-price').after('
(' + off_with_symbol + ' ' + wu_coupon_data.off_text + ')
'); - $(this).find('.old-price').html(accounting.formatMoney(parseFloat(old_price))); - if (!$(this).find('.off-value').get(0)) { + } - $(this).find('.old-price').after('
(' + off_with_symbol + ' ' + wu_coupon_data.off_text + ')
'); + if (applies_to_setup_fee) { - } - - if(applies_to_setup_fee) { + if (setup_fee_discount_type != '"absolute"') { + setupfee_off_with_symbol = ''.concat(setup_fee_discount_value, '%'); + } else { + setupfee_off_with_symbol = accounting.formatMoney(parseFloat(setup_fee_discount_value)); + } - if (setup_fee_discount_type != '"absolute"') - setupfee_off_with_symbol = ''.concat(setup_fee_discount_value, '%'); - else - setupfee_off_with_symbol = accounting.formatMoney(parseFloat(setup_fee_discount_value)); + if (! $(this).find('.setupfee-off-value').get(0)) { - if (!$(this).find('.setupfee-off-value').get(0)) { + $(this).find('.pricing-table-setupfee').after(' (' + setupfee_off_with_symbol + ' ' + wu_coupon_data.off_text + ')'); - $(this).find('.pricing-table-setupfee').after(' (' + setupfee_off_with_symbol + ' ' + wu_coupon_data.off_text + ')'); + } - } - - } + } - // END OFF RENDER + // END OFF RENDER - if(coupon_type != '"absolute"') { + if (coupon_type != '"absolute"') { - new_price = old_price * ((100 - coupon_value) / 100); + new_price = old_price * ((100 - coupon_value) / 100); - new_yearly_value = old_yearly_value * ((100 - coupon_value) / 100); + new_yearly_value = old_yearly_value * ((100 - coupon_value) / 100); - } else { + } else if (jQuery('#wu_plan_freq').val() > 1){ - if(jQuery('#wu_plan_freq').val() > 1){ + new_price = ((old_price * jQuery('#wu_plan_freq').val()) - parseFloat(coupon_value)) / jQuery('#wu_plan_freq').val(); - new_price = ((old_price * jQuery('#wu_plan_freq').val()) - parseFloat(coupon_value)) / jQuery('#wu_plan_freq').val(); + new_yearly_value = old_yearly_value - parseFloat(coupon_value); - new_yearly_value = old_yearly_value - parseFloat(coupon_value); + } else { - } else { + new_price = old_price - parseFloat(coupon_value); - new_price = old_price - parseFloat(coupon_value); + new_yearly_value = old_yearly_value - parseFloat(coupon_value); - new_yearly_value = old_yearly_value - parseFloat(coupon_value); + } - } + if (applies_to_setup_fee) { - } + if (setup_fee_discount_type != '"absolute"') { - if (applies_to_setup_fee) { + new_setupfee = old_setupfee * ((100 - setup_fee_discount_value) / 100); - if (setup_fee_discount_type != '"absolute"') { + } else { - new_setupfee = old_setupfee * ((100 - setup_fee_discount_value) / 100); + new_setupfee = old_setupfee - parseFloat(setup_fee_discount_value); - } else { + } - new_setupfee = old_setupfee - parseFloat(setup_fee_discount_value); + } else { - } + new_setupfee = old_setupfee; - } else { + } - new_setupfee = old_setupfee; + if (new_yearly_value > 0) { - } + wu_set_yearly_value(this, new_yearly_value); - if (new_yearly_value > 0) { + } else { - wu_set_yearly_value(this, new_yearly_value); + $(this).find('.total-price.total-price-' + $('#wu_plan_freq').val() ).html(' ' + wu_coupon_data.free_text); - } else { + } - $(this).find('.total-price.total-price-' + $('#wu_plan_freq').val() ).html(' ' + wu_coupon_data.free_text); + if (new_setupfee > 0) { - } + wu_set_setupfee_value(this, new_setupfee); - if (new_setupfee > 0) { + } else { - wu_set_setupfee_value(this, new_setupfee); + $(this).find('.pricing-table-setupfee').html(' ' + wu_coupon_data.no_setup_fee_text); - } else { + } - $(this).find('.pricing-table-setupfee').html(' ' + wu_coupon_data.no_setup_fee_text); + if (new_price > 0) { - } + $(this).find('.plan-price').html( accounting.formatMoney( parseFloat(new_price) ) ); - if (new_price > 0) { + if ( $(this).find('.plan-price').html().indexOf(wpu.currency_symbol) !== -1 ) { - $(this).find('.plan-price').html( accounting.formatMoney( parseFloat(new_price) ) ); + $(this).find('.plan-price').html($(this).find('.plan-price').html().replace(wpu.currency_symbol, '')); - if ( $(this).find('.plan-price').html().indexOf(wpu.currency_symbol) !== -1 ) { + } - $(this).find('.plan-price').html($(this).find('.plan-price').html().replace(wpu.currency_symbol, '')); + } else { - } + const plan_price = $(this).find('.plan-price'); + plan_price.html(' ' + wu_coupon_data.free_text); + const hagacinco = $(this).find('h5'); + hagacinco.find('sub').hide(); + hagacinco.find('.superscript').hide(); - } else { + } - let plan_price = $(this).find('.plan-price'); - plan_price.html(' ' + wu_coupon_data.free_text); - let hagacinco = $(this).find('h5'); - hagacinco.find('sub').hide(); - hagacinco.find('.superscript').hide(); + $("body").unblock(); - } + }); + }, 400); - $("body").unblock(); + } else { - }); }, 400); + $('.old-price').hide(); + $('.off-value').hide(); + $('.setupfee-off-value').hide(); + this.coupon_id = ''; - } else { + $('.wu-plan').each(function() { - $('.old-price').hide(); - $('.off-value').hide(); - $('.setupfee-off-value').hide(); + const price = $(this).data('price-' + $('#wu_plan_freq').val()); - this.coupon_id = ''; + $(this).find('.plan-price').html( price ); - $('.wu-plan').each(function() { + }); - var price = $(this).data('price-' + $('#wu_plan_freq').val()); + } - $(this).find('.plan-price').html( price ); + } + } + }); - }); + function wu_fix_money_string(value) { + if (typeof value === 'number'){ + value = value.toString(); } - } - } -}); - -function wu_fix_money_string(value) { + return parseFloat(value.replace(wpu.thousand_separator, '').replace(wpu.decimal_separator, '.')); - if(typeof value == 'number'){ - value = value.toString(); } - return parseFloat(value.replace(wpu.thousand_separator, '').replace(wpu.decimal_separator, '.')); - -} + function wu_set_setupfee_value(list, value) { -function wu_set_setupfee_value(list, value) { + jQuery(list).find('.pricing-table-setupfee').html( accounting.formatMoney(value)); - jQuery(list).find('.pricing-table-setupfee').html( accounting.formatMoney(value)); + } -} + function wu_set_yearly_value(list, value) { -function wu_set_yearly_value(list, value) { + const current_freq = jQuery('#wu_plan_freq').val(); - var current_freq = jQuery('#wu_plan_freq').val(); + const string = jQuery(list).find('.total-price.total-price-' + current_freq).html(); - var string = jQuery(list).find('.total-price.total-price-' + current_freq).html(); + if (string) { - if (string) { + const parts = string.split(','); - var parts = string.split(','); + const result = accounting.formatMoney(parseFloat(value)) + ', ' + parts[ 1 ]; - var result = accounting.formatMoney(parseFloat(value)) + ', ' + parts[1]; + jQuery(list).find('.total-price.total-price-' + current_freq).html(result); - jQuery(list).find('.total-price.total-price-' + current_freq).html(result); + } } -} - -})(jQuery); \ No newline at end of file +}(jQuery)); \ No newline at end of file diff --git a/assets/js/customizer.js b/assets/js/customizer.js index 337ab186d..f66773f8a 100644 --- a/assets/js/customizer.js +++ b/assets/js/customizer.js @@ -1,74 +1,74 @@ /* global Vue, wu_block_ui */ (function($) { - /** - * If we detect the preview changed, we add a loader. - */ - window.addEventListener('message', function(message) { + /** + * If we detect the preview changed, we add a loader. + */ + window.addEventListener('message', function(message) { - let block; + let block; - if (message.data === 'wu_preview_changed') { + if (message.data === 'wu_preview_changed') { - block = wu_block_ui('#preview_content'); + block = wu_block_ui('#preview_content'); - } // end if; + } // end if; - /** - * Unblocks when the loading is finished. - */ - $('#preview-stage-iframe').on('load', function() { + /** + * Unblocks when the loading is finished. + */ + $('#preview-stage-iframe').on('load', function() { - if (block) { + if (block) { - block.unblock(); + block.unblock(); - } // end if; + } // end if; - }); + }); - }, false); + }, false); - $(document).ready(function() { + $(document).ready(function() { - // eslint-disable-next-line no-unused-vars - const wu_preview_stage = new Vue({ - el: '#preview-stage', - data() { + // eslint-disable-next-line no-unused-vars + const wu_preview_stage = new Vue({ + el: '#preview-stage', + data() { - return { - preview: false, - }; + return { + preview: false, + }; - }, - }); + }, + }); - $('[data-wu-customizer-panel]').each(function() { + $('[data-wu-customizer-panel]').each(function() { - const app = $(this); + const app = $(this); - const app_name = 'wu_' + app.data('wu-app'); + const app_name = 'wu_' + app.data('wu-app'); - wp.hooks.addAction(app_name + '_changed', 'nextpress/wp-ultimo', function(prop) { + wp.hooks.addAction(app_name + '_changed', 'nextpress/wp-ultimo', function(prop) { - if (prop === 'tab') { + if (prop === 'tab') { - return; + return; - } // end if; + } // end if; - const param = jQuery.param(window[app_name].$data); + const param = jQuery.param(window[ app_name ].$data); - const param2 = app.find('input').serialize(); + const param2 = app.find('input').serialize(); - const url = $('#preview-stage-iframe').attr('data-src'); + const url = $('#preview-stage-iframe').attr('data-src'); - $('#preview-stage-iframe').attr('src', url + '&' + param + '&' + param2); + $('#preview-stage-iframe').attr('src', url + '&' + param + '&' + param2); - }); + }); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/dashboard-statistics.js b/assets/js/dashboard-statistics.js index d202e8daa..283689ff8 100644 --- a/assets/js/dashboard-statistics.js +++ b/assets/js/dashboard-statistics.js @@ -1,232 +1,232 @@ /* global wu_dashboard_statistics_vars, wu_format_money, Vue, wu_block_ui, moment, ajaxurl */ (function() { - const graph = document.getElementById('wp-ultimo-mrr-growth'); - - if (! graph) { - - return; - - } // end if; - - // eslint-disable-next-line no-undef - mrr_graph = new Vue({ - el: '#wp-ultimo-mrr-growth', - components: { - apexchart: window.VueApexCharts, - }, - data: { - start_date: wu_dashboard_statistics_vars.start_date, - end_date: wu_dashboard_statistics_vars.end_date, - chart_options: { - mrr_growth: { - series: [ - { - name: wu_dashboard_statistics_vars.i18n.new_mrr, - data: [ - wu_dashboard_statistics_vars.mrr_array.january.total, - wu_dashboard_statistics_vars.mrr_array.february.total, - wu_dashboard_statistics_vars.mrr_array.march.total, - wu_dashboard_statistics_vars.mrr_array.april.total, - wu_dashboard_statistics_vars.mrr_array.may.total, - wu_dashboard_statistics_vars.mrr_array.june.total, - wu_dashboard_statistics_vars.mrr_array.july.total, - wu_dashboard_statistics_vars.mrr_array.august.total, - wu_dashboard_statistics_vars.mrr_array.september.total, - wu_dashboard_statistics_vars.mrr_array.october.total, - wu_dashboard_statistics_vars.mrr_array.november.total, - wu_dashboard_statistics_vars.mrr_array.december.total, - ], - }, - { - name: wu_dashboard_statistics_vars.i18n.cancellations, - data: [ - -wu_dashboard_statistics_vars.mrr_array.january.cancelled, - -wu_dashboard_statistics_vars.mrr_array.february.cancelled, - -wu_dashboard_statistics_vars.mrr_array.march.cancelled, - -wu_dashboard_statistics_vars.mrr_array.april.cancelled, - -wu_dashboard_statistics_vars.mrr_array.may.cancelled, - -wu_dashboard_statistics_vars.mrr_array.june.cancelled, - -wu_dashboard_statistics_vars.mrr_array.july.cancelled, - -wu_dashboard_statistics_vars.mrr_array.august.cancelled, - -wu_dashboard_statistics_vars.mrr_array.september.cancelled, - -wu_dashboard_statistics_vars.mrr_array.october.cancelled, - -wu_dashboard_statistics_vars.mrr_array.november.cancelled, - -wu_dashboard_statistics_vars.mrr_array.december.cancelled, - ], - }, - ], - chartOptions: { - chart: { - type: 'bar', - height: 300, - stacked: true, - toolbar: { - show: false, - }, - zoom: { - enabled: true, - }, - }, - dataLabels: { - enabled: false, - maxItems: 0, - }, - responsive: [{ - breakpoint: 480, - options: { - legend: { - position: 'bottom', - offsetX: -10, - offsetY: 0, - }, - }, - }], - colors: ['#3498db', '#e74c3c'], - plotOptions: { - bar: { - horizontal: false, - columnWidth: '40%', - endingShape: 'rounded', - startingShape: 'rounded', - }, - }, - xaxis: { - categories: wu_dashboard_statistics_vars.month_list, - position: 'bottom', - axisBorder: { - show: true, - }, - axisTicks: { - show: true, - }, - crosshairs: { - fill: { - type: 'gradient', - gradient: { - colorFrom: '#D8E3F0', - colorTo: '#BED1E6', - stops: [0, 100], - opacityFrom: 0.4, - opacityTo: 0.5, - }, - }, - }, - tooltip: { - enabled: true, - }, - }, - yaxis: { - labels: { - formatter(y) { - - return y >= 0 ? wu_format_money(y) : '-' + wu_format_money(y); - - }, - }, - }, - legend: { - position: 'top', - offsetY: 0, - }, - fill: { - opacity: 1, - }, - }, - }, - }, - }, - }); + const graph = document.getElementById('wp-ultimo-mrr-growth'); + + if (! graph) { + + return; + + } // end if; + + // eslint-disable-next-line no-undef + mrr_graph = new Vue({ + el: '#wp-ultimo-mrr-growth', + components: { + apexchart: window.VueApexCharts, + }, + data: { + start_date: wu_dashboard_statistics_vars.start_date, + end_date: wu_dashboard_statistics_vars.end_date, + chart_options: { + mrr_growth: { + series: [ + { + name: wu_dashboard_statistics_vars.i18n.new_mrr, + data: [ + wu_dashboard_statistics_vars.mrr_array.january.total, + wu_dashboard_statistics_vars.mrr_array.february.total, + wu_dashboard_statistics_vars.mrr_array.march.total, + wu_dashboard_statistics_vars.mrr_array.april.total, + wu_dashboard_statistics_vars.mrr_array.may.total, + wu_dashboard_statistics_vars.mrr_array.june.total, + wu_dashboard_statistics_vars.mrr_array.july.total, + wu_dashboard_statistics_vars.mrr_array.august.total, + wu_dashboard_statistics_vars.mrr_array.september.total, + wu_dashboard_statistics_vars.mrr_array.october.total, + wu_dashboard_statistics_vars.mrr_array.november.total, + wu_dashboard_statistics_vars.mrr_array.december.total, + ], + }, + { + name: wu_dashboard_statistics_vars.i18n.cancellations, + data: [ + -wu_dashboard_statistics_vars.mrr_array.january.cancelled, + -wu_dashboard_statistics_vars.mrr_array.february.cancelled, + -wu_dashboard_statistics_vars.mrr_array.march.cancelled, + -wu_dashboard_statistics_vars.mrr_array.april.cancelled, + -wu_dashboard_statistics_vars.mrr_array.may.cancelled, + -wu_dashboard_statistics_vars.mrr_array.june.cancelled, + -wu_dashboard_statistics_vars.mrr_array.july.cancelled, + -wu_dashboard_statistics_vars.mrr_array.august.cancelled, + -wu_dashboard_statistics_vars.mrr_array.september.cancelled, + -wu_dashboard_statistics_vars.mrr_array.october.cancelled, + -wu_dashboard_statistics_vars.mrr_array.november.cancelled, + -wu_dashboard_statistics_vars.mrr_array.december.cancelled, + ], + }, + ], + chartOptions: { + chart: { + type: 'bar', + height: 300, + stacked: true, + toolbar: { + show: false, + }, + zoom: { + enabled: true, + }, + }, + dataLabels: { + enabled: false, + maxItems: 0, + }, + responsive: [ { + breakpoint: 480, + options: { + legend: { + position: 'bottom', + offsetX: -10, + offsetY: 0, + }, + }, + } ], + colors: [ '#3498db', '#e74c3c' ], + plotOptions: { + bar: { + horizontal: false, + columnWidth: '40%', + endingShape: 'rounded', + startingShape: 'rounded', + }, + }, + xaxis: { + categories: wu_dashboard_statistics_vars.month_list, + position: 'bottom', + axisBorder: { + show: true, + }, + axisTicks: { + show: true, + }, + crosshairs: { + fill: { + type: 'gradient', + gradient: { + colorFrom: '#D8E3F0', + colorTo: '#BED1E6', + stops: [ 0, 100 ], + opacityFrom: 0.4, + opacityTo: 0.5, + }, + }, + }, + tooltip: { + enabled: true, + }, + }, + yaxis: { + labels: { + formatter(y) { + + return y >= 0 ? wu_format_money(y) : '-' + wu_format_money(y); + + }, + }, + }, + legend: { + position: 'top', + offsetY: 0, + }, + fill: { + opacity: 1, + }, + }, + }, + }, + }, + }); }()); (function($) { - $(document).ready(function() { + $(document).ready(function() { - $('.wu-loader').on('click', function() { + $('.wu-loader').on('click', function() { - wu_block_ui('#wpcontent'); + wu_block_ui('#wpcontent'); - }); + }); - $('#wu-date-range').flatpickr({ - mode: 'range', - dateFormat: 'Y-m-d', - maxDate: wu_dashboard_statistics_vars.today, - defaultDate: [ - wu_dashboard_statistics_vars.start_date, - wu_dashboard_statistics_vars.end_date, - ], - onClose(selectedDates) { + $('#wu-date-range').flatpickr({ + mode: 'range', + dateFormat: 'Y-m-d', + maxDate: wu_dashboard_statistics_vars.today, + defaultDate: [ + wu_dashboard_statistics_vars.start_date, + wu_dashboard_statistics_vars.end_date, + ], + onClose(selectedDates) { - const redirect = new URL(window.location.href); + const redirect = new URL(window.location.href); - redirect.searchParams.set('start_date', moment(selectedDates[0]).format('YYYY-MM-DD')); + redirect.searchParams.set('start_date', moment(selectedDates[ 0 ]).format('YYYY-MM-DD')); - redirect.searchParams.set('end_date', moment(selectedDates[1]).format('YYYY-MM-DD')); + redirect.searchParams.set('end_date', moment(selectedDates[ 1 ]).format('YYYY-MM-DD')); - window.location.href = redirect.toString(); + window.location.href = redirect.toString(); - wu_block_ui('#wpcontent'); + wu_block_ui('#wpcontent'); - }, - }); + }, + }); - }); + }); }(jQuery)); (function($) { - $(document).ready(function() { + $(document).ready(function() { - $('.wu-export-button').on('click', function(e) { + $('.wu-export-button').on('click', function(e) { - e.preventDefault(); + e.preventDefault(); - const slug = e.target.getAttribute('attr-slug-csv'); + const slug = e.target.getAttribute('attr-slug-csv'); - const headers = $('#csv_headers_' + slug).val(); + const headers = $('#csv_headers_' + slug).val(); - const data = $('#csv_data_' + slug).val(); + const data = $('#csv_data_' + slug).val(); - const action = $('#csv_action_' + slug).val(); + const action = $('#csv_action_' + slug).val(); - const date_range = wu_dashboard_statistics_vars.start_date + '_to_' + wu_dashboard_statistics_vars.end_date; + const date_range = wu_dashboard_statistics_vars.start_date + '_to_' + wu_dashboard_statistics_vars.end_date; - const block = wu_block_ui('#wpcontent'); + const block = wu_block_ui('#wpcontent'); - setTimeout(() => { + setTimeout(() => { - block.unblock(); + block.unblock(); - }, 2000); + }, 2000); - // eslint-disable-next-line max-len - $('body').append(''); + // eslint-disable-next-line max-len + $('body').append(''); - $('').attr('type', 'hidden') - .attr('name', 'headers') - .attr('value', headers) - .appendTo('#export_csv'); + $('').attr('type', 'hidden') + .attr('name', 'headers') + .attr('value', headers) + .appendTo('#export_csv'); - $('').attr('type', 'hidden') - .attr('name', 'data') - .attr('value', data) - .appendTo('#export_csv'); + $('').attr('type', 'hidden') + .attr('name', 'data') + .attr('value', data) + .appendTo('#export_csv'); - $('').attr('type', 'hidden') - .attr('name', 'date_range') - .attr('value', date_range) - .appendTo('#export_csv'); + $('').attr('type', 'hidden') + .attr('name', 'date_range') + .attr('value', date_range) + .appendTo('#export_csv'); - $('#export_csv').submit(); + $('#export_csv').submit(); - $('#export_csv').remove(); + $('#export_csv').remove(); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/dns-management.js b/assets/js/dns-management.js index 2cb968405..5841796d0 100644 --- a/assets/js/dns-management.js +++ b/assets/js/dns-management.js @@ -4,6 +4,7 @@ * * Handles DNS record display and management in the Ultimate Multisite UI. * + * @param $ * @since 2.3.0 */ (function($) { @@ -22,7 +23,7 @@ function initDNSManagement() { const container = document.getElementById('wu-dns-records-table'); - if (!container || typeof Vue === 'undefined') { + if (! container || typeof Vue === 'undefined') { return; } @@ -42,22 +43,22 @@ domainId: '', canManage: false, provider: '', - recordTypes: ['A', 'AAAA', 'CNAME', 'MX', 'TXT'], + recordTypes: [ 'A', 'AAAA', 'CNAME', 'MX', 'TXT' ], selectedRecords: [], }, computed: { - hasRecords: function() { + hasRecords() { return this.records && this.records.length > 0; }, - sortedRecords: function() { - if (!this.records) { + sortedRecords() { + if (! this.records) { return []; } // Sort by type, then by name - return [...this.records].sort(function(a, b) { + return [ ...this.records ].sort(function(a, b) { if (a.type !== b.type) { return a.type.localeCompare(b.type); } @@ -66,7 +67,7 @@ }, }, - mounted: function() { + mounted() { const el = this.$el; this.domain = el.dataset.domain || ''; @@ -82,7 +83,7 @@ /** * Load DNS records from the server. */ - loadRecords: function() { + loadRecords() { const self = this; this.loading = true; @@ -96,7 +97,7 @@ nonce: wu_dns_config.nonce, domain: this.domain, }, - success: function(response) { + success(response) { self.loading = false; if (response.success) { @@ -115,7 +116,7 @@ self.error = (response.data && response.data.message) || 'Failed to load DNS records.'; } }, - error: function(xhr, status, errorMsg) { + error(xhr, status, errorMsg) { self.loading = false; self.error = 'Network error: ' + errorMsg; }, @@ -125,7 +126,7 @@ /** * Refresh the records list. */ - refresh: function() { + refresh() { this.loadRecords(); }, @@ -135,16 +136,16 @@ * @param {string} type The record type. * @return {string} CSS classes. */ - getTypeClass: function(type) { + getTypeClass(type) { const classes = { - 'A': 'wu-bg-blue-100 wu-text-blue-800', - 'AAAA': 'wu-bg-purple-100 wu-text-purple-800', - 'CNAME': 'wu-bg-green-100 wu-text-green-800', - 'MX': 'wu-bg-orange-100 wu-text-orange-800', - 'TXT': 'wu-bg-gray-100 wu-text-gray-800', + A: 'wu-bg-blue-100 wu-text-blue-800', + AAAA: 'wu-bg-purple-100 wu-text-purple-800', + CNAME: 'wu-bg-green-100 wu-text-green-800', + MX: 'wu-bg-orange-100 wu-text-orange-800', + TXT: 'wu-bg-gray-100 wu-text-gray-800', }; - return classes[type] || 'wu-bg-gray-100 wu-text-gray-800'; + return classes[ type ] || 'wu-bg-gray-100 wu-text-gray-800'; }, /** @@ -153,7 +154,7 @@ * @param {number} seconds TTL in seconds. * @return {string} Formatted TTL. */ - formatTTL: function(seconds) { + formatTTL(seconds) { if (seconds === 1) { return 'Auto'; } @@ -176,14 +177,14 @@ /** * Truncate content for display. * - * @param {string} content The content to truncate. + * @param {string} content The content to truncate. * @param {number} maxLength Maximum length. * @return {string} Truncated content. */ - truncateContent: function(content, maxLength) { + truncateContent(content, maxLength) { maxLength = maxLength || 40; - if (!content || content.length <= maxLength) { + if (! content || content.length <= maxLength) { return content; } @@ -196,8 +197,8 @@ * @param {Object} record The record object. * @return {string} Edit URL. */ - getEditUrl: function(record) { - if (!wu_dns_config.edit_url) { + getEditUrl(record) { + if (! wu_dns_config.edit_url) { return '#'; } @@ -212,8 +213,8 @@ * @param {Object} record The record object. * @return {string} Delete URL. */ - getDeleteUrl: function(record) { - if (!wu_dns_config.delete_url) { + getDeleteUrl(record) { + if (! wu_dns_config.delete_url) { return '#'; } @@ -227,7 +228,7 @@ * * @param {string} recordId The record ID. */ - toggleSelection: function(recordId) { + toggleSelection(recordId) { const index = this.selectedRecords.indexOf(recordId); if (index > -1) { @@ -243,14 +244,14 @@ * @param {string} recordId The record ID. * @return {boolean} True if selected. */ - isSelected: function(recordId) { + isSelected(recordId) { return this.selectedRecords.indexOf(recordId) > -1; }, /** * Select all records. */ - selectAll: function() { + selectAll() { const self = this; this.selectedRecords = this.records.map(function(record) { @@ -261,19 +262,19 @@ /** * Deselect all records. */ - deselectAll: function() { + deselectAll() { this.selectedRecords = []; }, /** * Delete selected records (admin bulk operation). */ - deleteSelected: function() { - if (!this.selectedRecords.length) { + deleteSelected() { + if (! this.selectedRecords.length) { return; } - if (!confirm('Are you sure you want to delete ' + this.selectedRecords.length + ' selected records?')) { + if (! confirm('Are you sure you want to delete ' + this.selectedRecords.length + ' selected records?')) { return; } @@ -289,7 +290,7 @@ operation: 'delete', records: this.selectedRecords, }, - success: function(response) { + success(response) { if (response.success) { self.selectedRecords = []; self.loadRecords(); @@ -297,7 +298,7 @@ alert('Error: ' + ((response.data && response.data.message) || 'Failed to delete records.')); } }, - error: function() { + error() { alert('Network error occurred.'); }, }); @@ -309,7 +310,7 @@ * @param {Object} record The record object. * @return {string} Proxied status HTML. */ - getProxiedStatus: function(record) { + getProxiedStatus(record) { if (this.provider !== 'cloudflare') { return ''; } @@ -334,4 +335,4 @@ }, 100); }); -})(jQuery); +}(jQuery)); diff --git a/assets/js/dns-table.js b/assets/js/dns-table.js index 445e81007..a519b49e9 100644 --- a/assets/js/dns-table.js +++ b/assets/js/dns-table.js @@ -1,53 +1,53 @@ /* global ajaxurl, Vue, wu_dns_table_config, wu_ajax_error */ (function($) { - wu_dns_table = new Vue({ - el: '#wu-dns-table', - data: { - error: null, - results: {}, - loading: true, - }, - updated() { - this.$nextTick(function() { + wu_dns_table = new Vue({ + el: '#wu-dns-table', + data: { + error: null, + results: {}, + loading: true, + }, + updated() { + this.$nextTick(function() { - window.wu_initialize_tooltip(); + window.wu_initialize_tooltip(); - }); - } - }) + }); + } + }) - $(document).ready(function() { + $(document).ready(function() { - $.ajax({ - url: ajaxurl, - data: { - action: 'wu_get_dns_records', - domain: window.wu_dns_table_config.domain, - }, - success: function(data) { + $.ajax({ + url: ajaxurl, + data: { + action: 'wu_get_dns_records', + domain: window.wu_dns_table_config.domain, + }, + success(data) { - Vue.set(wu_dns_table, 'loading', false); + Vue.set(wu_dns_table, 'loading', false); - if (data.success) { + if (data.success) { - Vue.set(wu_dns_table, 'results', data.data); + Vue.set(wu_dns_table, 'results', data.data); - } else { + } else { - Vue.set(wu_dns_table, 'error', data.data); + Vue.set(wu_dns_table, 'error', data.data); - } + } - }, - error: function(jqXHR) { + }, + error(jqXHR) { - Vue.set(wu_dns_table, 'loading', false); + Vue.set(wu_dns_table, 'loading', false); - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, - }) + }, + }) - }); -})(jQuery); + }); +}(jQuery)); diff --git a/assets/js/domain-logs.js b/assets/js/domain-logs.js index 9321505d7..24c1119e9 100644 --- a/assets/js/domain-logs.js +++ b/assets/js/domain-logs.js @@ -49,4 +49,4 @@ ); } ); -})(jQuery); \ No newline at end of file +}(jQuery)); \ No newline at end of file diff --git a/assets/js/edit-placeholders.js b/assets/js/edit-placeholders.js index de8d062a3..4c92963b6 100644 --- a/assets/js/edit-placeholders.js +++ b/assets/js/edit-placeholders.js @@ -2,230 +2,230 @@ /* global Vue, wu_block_ui, ajaxurl, wu_placeholdersl10n */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - /** - * Vue - */ - if ($('#wu-template-placeholders').length) { + /** + * Vue + */ + if ($('#wu-template-placeholders').length) { - window.wu_placeholders = new Vue({ - el: '#wu-template-placeholders', - data: { - tax_category: 'default', - switching: false, - creating: false, - create_name: '', - toggle: false, - loading: true, - saving: false, - initialLoading: true, - error: false, - changed: false, - data: { - placeholders: [], - }, - delete: [], - saveMessage: '', - errorMessage: '', - rate_type: 'standard_rate', - }, - watch: { - data: { - deep: true, - handler() { + window.wu_placeholders = new Vue({ + el: '#wu-template-placeholders', + data: { + tax_category: 'default', + switching: false, + creating: false, + create_name: '', + toggle: false, + loading: true, + saving: false, + initialLoading: true, + error: false, + changed: false, + data: { + placeholders: [], + }, + delete: [], + saveMessage: '', + errorMessage: '', + rate_type: 'standard_rate', + }, + watch: { + data: { + deep: true, + handler() { - if (this.initialLoading) { + if (this.initialLoading) { - this.initialLoading = false; + this.initialLoading = false; - return; + return; - } + } - this.changed = true; + this.changed = true; - }, - }, - loading(new_value) { + }, + }, + loading(new_value) { - if (new_value === true) { + if (new_value === true) { - window.wu_blocked_table = wu_block_ui('table.wp-list-table'); + window.wu_blocked_table = wu_block_ui('table.wp-list-table'); - } else { + } else { - if (typeof window.wu_blocked_table !== 'undefined') { + if (typeof window.wu_blocked_table !== 'undefined') { - window.wu_blocked_table.unblock(); + window.wu_blocked_table.unblock(); - } // end if; + } // end if; - } // end if; + } // end if; - }, - }, - mounted() { + }, + }, + mounted() { - this.loading = true; + this.loading = true; - this.pull_data(true); + this.pull_data(true); - $('.wu-tooltip-vue').tipTip(); + $('.wu-tooltip-vue').tipTip(); - }, - created() { + }, + created() { - // Create the event. - const event = document.createEvent('Event'); + // Create the event. + const event = document.createEvent('Event'); - // Define that the event name is 'build'. - event.initEvent('vue_loaded', true, true); + // Define that the event name is 'build'. + event.initEvent('vue_loaded', true, true); - event.vue = this; + event.vue = this; - // target can be any Element or other EventTarget. - window.dispatchEvent(event); + // target can be any Element or other EventTarget. + window.dispatchEvent(event); - }, - computed: { - selected() { + }, + computed: { + selected() { - return $(this.data.placeholders).filter(function(index, item) { + return $(this.data.placeholders).filter(function(index, item) { - return item.selected; + return item.selected; - }); + }); - }, - }, - methods: { - refresh(e) { + }, + }, + methods: { + refresh(e) { - e.preventDefault(); + e.preventDefault(); - this.loading = true; + this.loading = true; - this.pull_data(); + this.pull_data(); - }, - select_all(event) { + }, + select_all(event) { - const toggle = $(event.target).is(':checked'); + const toggle = $(event.target).is(':checked'); - this.data.placeholders = $.map(this.data.placeholders, function(item) { + this.data.placeholders = $.map(this.data.placeholders, function(item) { - item.selected = toggle; + item.selected = toggle; - return item; + return item; - }); + }); - }, - pull_data() { + }, + pull_data() { - const that = this; + const that = this; - jQuery.getJSON(ajaxurl + '?action=wu_get_placeholders').done(function(response) { + jQuery.getJSON(ajaxurl + '?action=wu_get_placeholders').done(function(response) { - that.loading = false; + that.loading = false; - that.data = response.data; + that.data = response.data; - }) - .fail(function(error) { + }) + .fail(function(error) { - that.loading = false; + that.loading = false; - that.error = true; + that.error = true; - that.errorMessage = error.statusText; + that.errorMessage = error.statusText; - }); + }); - }, - add_row() { + }, + add_row() { - Vue.set(this.data, 'placeholders', this.data.placeholders.concat([ - { - placeholder: '', - content: '', - selected: false, - }, - ])); + Vue.set(this.data, 'placeholders', this.data.placeholders.concat([ + { + placeholder: '', + content: '', + selected: false, + }, + ])); - this.$forceUpdate(); + this.$forceUpdate(); - }, - delete_rows() { + }, + delete_rows() { - this.delete = this.delete.concat(this.selected.get()); + this.delete = this.delete.concat(this.selected.get()); - // eslint-disable-next-line no-alert - const are_you_sure = confirm(wu_placeholdersl10n.confirm_message); + // eslint-disable-next-line no-alert + const are_you_sure = confirm(wu_placeholdersl10n.confirm_message); - if (are_you_sure) { + if (are_you_sure) { - const cleaned_list = $(this.data.placeholders).filter(function(index, item) { + const cleaned_list = $(this.data.placeholders).filter(function(index, item) { - return ! item.selected; + return ! item.selected; - }); + }); - Vue.set(this.data, 'placeholders', cleaned_list.get()); + Vue.set(this.data, 'placeholders', cleaned_list.get()); - this.$forceUpdate(); + this.$forceUpdate(); - } // end if + } // end if - }, - save() { + }, + save() { - const that = this; + const that = this; - that.saving = true; + that.saving = true; - $.post({ - url: ajaxurl + '?action=wu_save_placeholders&' + $('#nonce_form').serialize(), - data: JSON.stringify({ - placeholders: that.data.placeholders, - }), - dataType: 'json', - contentType: 'application/json; charset=utf-8', - }).success(function(data) { + $.post({ + url: ajaxurl + '?action=wu_save_placeholders&' + $('#nonce_form').serialize(), + data: JSON.stringify({ + placeholders: that.data.placeholders, + }), + dataType: 'json', + contentType: 'application/json; charset=utf-8', + }).success(function(data) { - that.saving = false; + that.saving = false; - that.changed = false; + that.changed = false; - that.delete = []; + that.delete = []; - that.saveMessage = data.message; + that.saveMessage = data.message; - if (data.code === 'success') { + if (data.code === 'success') { - that.loading = true; + that.loading = true; - that.initialLoading = true; + that.initialLoading = true; - that.pull_data(); + that.pull_data(); - } + } - setInterval(function() { + setInterval(function() { - that.saveMessage = ''; + that.saveMessage = ''; - }, 6000); + }, 6000); - }); + }); - }, - }, - }); + }, + }, + }); - } // end if; + } // end if; - }); + }); }(jQuery)); diff --git a/assets/js/email-edit-page.js b/assets/js/email-edit-page.js index 0e1d37a3d..a74b8ea31 100644 --- a/assets/js/email-edit-page.js +++ b/assets/js/email-edit-page.js @@ -1,88 +1,88 @@ /* global ajaxurl, Vue, wu_event_payload_placeholders, _, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - wu_event_payload_placeholders = new Vue({ - el: '#wu_event_payload_placeholders', - data() { + wu_event_payload_placeholders = new Vue({ + el: '#wu_event_payload_placeholders', + data() { - return { - placeholders: [], - event: $("select[name='event']").val(), - search: '', - loading: true, - }; + return { + placeholders: [], + event: $("select[name='event']").val(), + search: '', + loading: true, + }; - }, - computed: { - filtered_placeholders() { + }, + computed: { + filtered_placeholders() { - const search = this.search.toLowerCase(); + const search = this.search.toLowerCase(); - return _.filter(this.placeholders, function(item) { + return _.filter(this.placeholders, function(item) { - return item.name.toLowerCase().indexOf(search) > -1 || item.placeholder.toLowerCase().indexOf(search) > -1; + return item.name.toLowerCase().indexOf(search) > -1 || item.placeholder.toLowerCase().indexOf(search) > -1; - }); + }); - }, - }, - watch: { - event() { + }, + }, + watch: { + event() { - this.get_event_payload(); + this.get_event_payload(); - }, - }, - methods: { - get_event_payload() { + }, + }, + methods: { + get_event_payload() { - const app = this; + const app = this; - app.loading = true; + app.loading = true; - $.ajax({ - method: 'post', - url: ajaxurl, - data: { - action: 'wu_get_event_payload_placeholders', - email_event: app.event, - }, - success(response) { + $.ajax({ + method: 'post', + url: ajaxurl, + data: { + action: 'wu_get_event_payload_placeholders', + email_event: app.event, + }, + success(response) { - app.placeholders = response; + app.placeholders = response; - app.loading = false; + app.loading = false; - }, - error(jqXHR) { + }, + error(jqXHR) { - app.loading = false; + app.loading = false; - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, + }, - }); + }); - }, + }, - }, - mounted() { + }, + mounted() { - this.get_event_payload(); + this.get_event_payload(); - }, + }, - }); + }); - $(document).on('change', 'select[name="event"]', function() { + $(document).on('change', 'select[name="event"]', function() { - wu_event_payload_placeholders.event = $("select[name='event']").val(); + wu_event_payload_placeholders.event = $("select[name='event']").val(); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/fields.js b/assets/js/fields.js index 3ff0bc2d1..523912a0b 100644 --- a/assets/js/fields.js +++ b/assets/js/fields.js @@ -2,45 +2,45 @@ if (typeof window.Vue !== 'undefined') { - /** - * Registers the ColorPicker component. - * - * @since 2.0.0 - */ - Vue.component('colorPicker', { - props: ['value'], - template: '', - mounted() { - - const vm = this; - - $(this.$el) - .val(this.value) - .wpColorPicker({ - width: 200, - defaultColor: this.value, - change(event, ui) { - - // emit change event on color change using mouse - vm.$emit('input', ui.color.toString()); - - }, - }); - - }, - watch: { - value(value) { - - // update value - $(this.$el).wpColorPicker('color', value); - - }, - }, - destroyed() { - - $(this.$el).off().wpColorPicker('destroy'); // (!) Not tested - - }, - }); + /** + * Registers the ColorPicker component. + * + * @since 2.0.0 + */ + Vue.component('colorPicker', { + props: [ 'value' ], + template: '', + mounted() { + + const vm = this; + + $(this.$el) + .val(this.value) + .wpColorPicker({ + width: 200, + defaultColor: this.value, + change(event, ui) { + + // emit change event on color change using mouse + vm.$emit('input', ui.color.toString()); + + }, + }); + + }, + watch: { + value(value) { + + // update value + $(this.$el).wpColorPicker('color', value); + + }, + }, + destroyed() { + + $(this.$el).off().wpColorPicker('destroy'); // (!) Not tested + + }, + }); } // end if; diff --git a/assets/js/functions.js b/assets/js/functions.js index fa293e49f..5b51c5038 100644 --- a/assets/js/functions.js +++ b/assets/js/functions.js @@ -8,28 +8,28 @@ * Uses SweetAlert2 when available (most admin pages load it), otherwise * injects a standard WordPress admin notice at the top of #wpbody-content. * - * @param {Object|string} jqXHR The jQuery XHR object or a plain error string. - * @param {string} context Optional human-readable context label (e.g. "loading logs"). + * @param {Object|string} jqXHR The jQuery XHR object or a plain error string. + * @param {string} context Optional human-readable context label (e.g. "loading logs"). * @return {void} */ window.wu_ajax_error = function( jqXHR, context ) { - var i18n = ( typeof wu_ajax_errors !== 'undefined' ) ? wu_ajax_errors : {}; + const i18n = ( typeof wu_ajax_errors !== 'undefined' ) ? wu_ajax_errors : {}; - var title = i18n.error_title || 'Request Failed'; - var generic = i18n.error_message || 'An unexpected error occurred. Please try again or contact support if the problem persists.'; - var suffix = context ? ( ' ' + ( i18n.while_prefix || 'while' ) + ' ' + context + '.' ) : ''; + const title = i18n.error_title || 'Request Failed'; + const generic = i18n.error_message || 'An unexpected error occurred. Please try again or contact support if the problem persists.'; + const suffix = context ? ( ' ' + ( i18n.while_prefix || 'while' ) + ' ' + context + '.' ) : ''; - var message = generic + suffix; + let message = generic + suffix; // Try to extract a more specific message from the response body. if ( jqXHR && typeof jqXHR === 'object' ) { - var status = jqXHR.status; + const status = jqXHR.status; if ( jqXHR.responseJSON ) { - var rj = jqXHR.responseJSON; + const rj = jqXHR.responseJSON; if ( rj.data && rj.data[ 0 ] && rj.data[ 0 ].message ) { @@ -65,7 +65,7 @@ window.wu_ajax_error = function( jqXHR, context ) { if ( typeof Swal !== 'undefined' ) { Swal.fire({ - title: title, + title, icon: 'error', text: message, showCloseButton: true, @@ -77,7 +77,7 @@ window.wu_ajax_error = function( jqXHR, context ) { } // end if; // Fallback: inject a standard WP admin notice. - var $notice = jQuery( + const $notice = jQuery( '
' + '

' + jQuery( '' ).text( title ).html() + ': ' + jQuery( '' ).text( message ).html() + '

' + '' + @@ -86,11 +86,13 @@ window.wu_ajax_error = function( jqXHR, context ) { $notice.find( '.notice-dismiss' ).on( 'click', function() { - $notice.fadeOut( 200, function() { $notice.remove(); } ); + $notice.fadeOut( 200, function() { + $notice.remove(); + } ); } ); - var $target = jQuery( '#wpbody-content' ).first(); + let $target = jQuery( '#wpbody-content' ).first(); if ( ! $target.length ) { @@ -103,7 +105,9 @@ window.wu_ajax_error = function( jqXHR, context ) { // Auto-dismiss after 8 seconds. setTimeout( function() { - $notice.fadeOut( 400, function() { $notice.remove(); } ); + $notice.fadeOut( 400, function() { + $notice.remove(); + } ); }, 8000 ); diff --git a/assets/js/gutenberg-support.js b/assets/js/gutenberg-support.js index 6f1cabd62..9463994aa 100644 --- a/assets/js/gutenberg-support.js +++ b/assets/js/gutenberg-support.js @@ -2,22 +2,22 @@ /* global wu_gutenberg */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - /** - * Filter that receives the content from the preview markup and make modifications to it. - * - * @param {*} content - */ - const custom_gutenberg_preview_message = function(content) { + /** + * Filter that receives the content from the preview markup and make modifications to it. + * + * @param {*} content + */ + const custom_gutenberg_preview_message = function(content) { - content = content.replace(wp.i18n.__('Generating preview…'), wu_gutenberg.replacement_message); + content = content.replace(wp.i18n.__('Generating preview…'), wu_gutenberg.replacement_message); - const img = '

'; + const img = '

'; - content = content.replace('

', img); + content = content.replace('

', img); - content += ''; - return content; + return content; - }; + }; - /** - * Check if the hooks are set to avoid bugs and breaking other scripts. - */ - if (typeof wp === 'object' && typeof wp.hooks === 'object') { + /** + * Check if the hooks are set to avoid bugs and breaking other scripts. + */ + if (typeof wp === 'object' && typeof wp.hooks === 'object') { - /** - * Pass as a wp hook - */ - wp.hooks.addFilter('editor.PostPreview.interstitialMarkup', 'wp-ultimo/custom-preview-message', custom_gutenberg_preview_message); + /** + * Pass as a wp hook + */ + wp.hooks.addFilter('editor.PostPreview.interstitialMarkup', 'wp-ultimo/custom-preview-message', custom_gutenberg_preview_message); - } // end if; + } // end if; - }); + }); }(jQuery)); diff --git a/assets/js/integration-test.js b/assets/js/integration-test.js index 68711d17a..0c0dcec0f 100644 --- a/assets/js/integration-test.js +++ b/assets/js/integration-test.js @@ -7,8 +7,8 @@ loading: false, results: wu_integration_test_data.waiting_message, }, - mounted: function() { - var that = this; + mounted() { + const that = this; this.loading = true; setTimeout(() => { @@ -19,12 +19,12 @@ action: 'wu_test_hosting_integration', integration: wu_integration_test_data.integration_id, }, - success: function(response) { + success(response) { that.loading = false; that.success = response.success; that.results = response.data; }, - error: function() { + error() { that.loading = false; that.success = false; that.results = wu_integration_test_data.error_message || 'Connection test failed. Please try again.'; @@ -34,4 +34,4 @@ }, }); }); -})(jQuery); +}(jQuery)); diff --git a/assets/js/legacy-signup.js b/assets/js/legacy-signup.js index 9bec288ce..690fb79bb 100644 --- a/assets/js/legacy-signup.js +++ b/assets/js/legacy-signup.js @@ -1,13 +1,13 @@ (() => { -"use strict"; -const { addFilter } = window.wp.hooks; -document.addEventListener("DOMContentLoaded", () => { - addFilter("wu_before_form_init", "nextpress/wp-ultimo", (data) => { - if (typeof data !== "undefined") { - data.billing_option = 1; - data.default_billing_option = 12; - } - return data; - }); -}); + "use strict"; + const { addFilter } = window.wp.hooks; + document.addEventListener("DOMContentLoaded", () => { + addFilter("wu_before_form_init", "nextpress/wp-ultimo", (data) => { + if (typeof data !== "undefined") { + data.billing_option = 1; + data.default_billing_option = 12; + } + return data; + }); + }); })() \ No newline at end of file diff --git a/assets/js/list-tables.js b/assets/js/list-tables.js index 73045a571..0ac20dbbb 100644 --- a/assets/js/list-tables.js +++ b/assets/js/list-tables.js @@ -1,557 +1,557 @@ /* eslint-disable no-undef */ (function($, hooks) { - /** - * Fixes the value of the action for deleting pending sites. - */ - hooks.addAction('wu_list_table_update', 'nextpress/wp-ultimo', function(results, data, $parent) { + /** + * Fixes the value of the action for deleting pending sites. + */ + hooks.addAction('wu_list_table_update', 'nextpress/wp-ultimo', function(results, data, $parent) { - if (results.type === 'pending' && data.table_id === 'site_list_table') { + if (results.type === 'pending' && data.table_id === 'site_list_table') { - $parent.find('select[name^=action] > option[value=delete]').attr('value', 'delete-pending'); + $parent.find('select[name^=action] > option[value=delete]').attr('value', 'delete-pending'); - } else { + } else { - $parent.find('select[name^=action] > option[value=delete-pending]').attr('value', 'delete'); + $parent.find('select[name^=action] > option[value=delete-pending]').attr('value', 'delete'); - } // end if; + } // end if; - }); + }); - /** - * Select All - */ - $(document).on('click', '#cb-select-all-grid', function(e) { + /** + * Select All + */ + $(document).on('click', '#cb-select-all-grid', function(e) { - e.preventDefault(); + e.preventDefault(); - const checkboxes = jQuery(this) - .parents('form') - .find('#the-list') - .find('input[type=checkbox]'); + const checkboxes = jQuery(this) + .parents('form') + .find('#the-list') + .find('input[type=checkbox]'); - const checked = checkboxes.prop('checked'); + const checked = checkboxes.prop('checked'); - checkboxes.parents('.wu-grid-item') - .toggleClass('wu-grid-item-selected', ! checked); + checkboxes.parents('.wu-grid-item') + .toggleClass('wu-grid-item-selected', ! checked); - checkboxes.prop('checked', ! checked); + checkboxes.prop('checked', ! checked); - }); + }); - $(document).on('change', '.wu-grid-item input[type=checkbox]', function() { + $(document).on('change', '.wu-grid-item input[type=checkbox]', function() { - const checked = $(this).prop('checked'); + const checked = $(this).prop('checked'); - $(this).parents('.wu-grid-item') - .toggleClass('wu-grid-item-selected', checked); + $(this).parents('.wu-grid-item') + .toggleClass('wu-grid-item-selected', checked); - }); + }); - /** - * Function that creates the code to handle the AJAX functionality of the WU List Tables. - * - * @param id - * @param count - * @param filters - * @param date_filters - */ - // eslint-disable-next-line no-undef - wu_create_list = function(id) { + /** + * Function that creates the code to handle the AJAX functionality of the WU List Tables. + * + * @param id + * @param count + * @param filters + * @param date_filters + */ + // eslint-disable-next-line no-undef + wu_create_list = function(id) { - return { + return { - /** - * Table element ID - */ - el: '#' + id, + /** + * Table element ID + */ + el: '#' + id, - /** - * Filters ID - */ - filters_el: '#' + id + '-filters', + /** + * Filters ID + */ + filters_el: '#' + id + '-filters', - /** - * Wether or not the table was initialized. - */ - initialized: false, + /** + * Wether or not the table was initialized. + */ + initialized: false, - /** - * Register our triggers - * - * We want to capture clicks on specific links, but also value change in - * the pagination input field. The links contain all the information we - * need concerning the wanted page number or ordering, so we'll just - * parse the URL to extract these variables. - * - * The page number input is trickier: it has no URL so we have to find a - * way around. We'll use the hidden inputs added in TT_Example_List_Table::display() - * to recover the ordering variables, and the default paged input added - * automatically by WordPress. - */ - init() { + /** + * Register our triggers + * + * We want to capture clicks on specific links, but also value change in + * the pagination input field. The links contain all the information we + * need concerning the wanted page number or ordering, so we'll just + * parse the URL to extract these variables. + * + * The page number input is trickier: it has no URL so we have to find a + * way around. We'll use the hidden inputs added in TT_Example_List_Table::display() + * to recover the ordering variables, and the default paged input added + * automatically by WordPress. + */ + init() { - const table = this; + const table = this; - const $table_parent = $('#wu-' + id); + const $table_parent = $('#wu-' + id); - // This will have its utility when dealing with the page number input - let timer; + // This will have its utility when dealing with the page number input + let timer; - const delay = 500; + const delay = 500; - /* + /* * Handles bulk-delete. */ - jQuery('body').on('click', '#doaction, #doaction2', function(event) { + jQuery('body').on('click', '#doaction, #doaction2', function(event) { - const form = jQuery(event.target).parents('form'); + const form = jQuery(event.target).parents('form'); - const form_data = form.serialize(); + const form_data = form.serialize(); - const params = new URL('https://example.com?' + form_data); + const params = new URL('https://example.com?' + form_data); - const action = params.searchParams.get('action') || params.searchParams.get('action2'); + const action = params.searchParams.get('action') || params.searchParams.get('action2'); - const ids = params.searchParams.getAll('bulk-delete[]'); + const ids = params.searchParams.getAll('bulk-delete[]'); - if (action !== '-1' && ids.length) { + if (action !== '-1' && ids.length) { - event.preventDefault(); + event.preventDefault(); - } else { + } else { - return; + return; - }// end if; + }// end if; - params.searchParams.set('bulk_action', action); + params.searchParams.set('bulk_action', action); - params.searchParams.forEach((value, key) => { + params.searchParams.forEach((value, key) => { - if (key !== 'bulk_action' && key !== 'bulk-delete[]') { + if (key !== 'bulk_action' && key !== 'bulk-delete[]') { - params.searchParams.delete(key); + params.searchParams.delete(key); - } // end if; + } // end if; - }); + }); - params.searchParams.set('model', wu_list_table.model); + params.searchParams.set('model', wu_list_table.model); - wubox.show(wu_list_table.i18n.confirm, wu_list_table.base_url + '&' + params.searchParams.toString()); + wubox.show(wu_list_table.i18n.confirm, wu_list_table.base_url + '&' + params.searchParams.toString()); - }); + }); - // Pagination links, sortable link - $table_parent.on('click', '.tablenav-pages a, .manage-column.sortable a, .manage-column.sorted a', function(e) { + // Pagination links, sortable link + $table_parent.on('click', '.tablenav-pages a, .manage-column.sortable a, .manage-column.sorted a', function(e) { - // We don't want to actually follow these links - e.preventDefault(); + // We don't want to actually follow these links + e.preventDefault(); - // Simple way: use the URL to extract our needed variables - const query = this.search.substring(1); + // Simple way: use the URL to extract our needed variables + const query = this.search.substring(1); - const data = $.extend({}, table.__get_query(query), { - order: table.__query(query, 'order') || 'DESC', - paged: table.__query(query, 'paged') || '1', - s: table.__query(query, 's') || '', - }); + const data = $.extend({}, table.__get_query(query), { + order: table.__query(query, 'order') || 'DESC', + paged: table.__query(query, 'paged') || '1', + s: table.__query(query, 's') || '', + }); - table.update(data); + table.update(data); - }); + }); - // Page number input - $table_parent.on('keyup', 'input[name=paged]', function(e) { + // Page number input + $table_parent.on('keyup', 'input[name=paged]', function(e) { - // If user hit enter, we don't want to submit the form - // We don't preventDefault() for all keys because it would - // also prevent to get the page number! - if (13 === e.which) { + // If user hit enter, we don't want to submit the form + // We don't preventDefault() for all keys because it would + // also prevent to get the page number! + if (13 === e.which) { - e.preventDefault(); + e.preventDefault(); - } // end if; + } // end if; - // This time we fetch the variables in inputs - const data = { - paged: parseInt($('input[name=paged]').val()) || '1', - s: $('input[name=s]').val() || '', - }; + // This time we fetch the variables in inputs + const data = { + paged: parseInt($('input[name=paged]').val()) || '1', + s: $('input[name=s]').val() || '', + }; - // Now the timer comes to use: we wait half a second after - // the user stopped typing to actually send the call. If - // we don't, the keyup event will trigger instantly and - // thus may cause duplicate calls before sending the intended - // value - window.clearTimeout(timer); + // Now the timer comes to use: we wait half a second after + // the user stopped typing to actually send the call. If + // we don't, the keyup event will trigger instantly and + // thus may cause duplicate calls before sending the intended + // value + window.clearTimeout(timer); - timer = window.setTimeout(function() { + timer = window.setTimeout(function() { - table.update(data); + table.update(data); - }, delay); + }, delay); - }); + }); - /** - * Initializes filters - */ - if (table.initialized === false && $(table.filters_el).get(0)) { + /** + * Initializes filters + */ + if (table.initialized === false && $(table.filters_el).get(0)) { - table.filters = table.init_filters(); + table.filters = table.init_filters(); - } // end if; + } // end if; - table.initialized = true; + table.initialized = true; - return table; + return table; - }, + }, - /** - * Copy a object - * - * @param {Object} obj - */ - copy: function copy(obj) { + /** + * Copy a object + * + * @param {Object} obj + */ + copy: function copy(obj) { - return JSON.parse(JSON.stringify(obj)); + return JSON.parse(JSON.stringify(obj)); - }, + }, - /** - * Setup up the filters - */ - init_filters() { + /** + * Setup up the filters + */ + init_filters() { - if (typeof window.Vue === 'undefined') { + if (typeof window.Vue === 'undefined') { - return; + return; - } // end if; + } // end if; - const table = this; + const table = this; - const available_filters = table.copy(window[id + '_config'].filters); + const available_filters = table.copy(window[ id + '_config' ].filters); - // eslint-disable-next-line no-undef - return new Vue({ - el: table.filters_el, - data() { + // eslint-disable-next-line no-undef + return new Vue({ + el: table.filters_el, + data() { - return { - open: true, - view: false, - // relation: 'and', - available_filters: [], // table.copy(available_filters), - filters: [], //[_.first(table.copy(available_filters))], - }; + return { + open: true, + view: false, + // relation: 'and', + available_filters: [], // table.copy(available_filters), + filters: [], //[_.first(table.copy(available_filters))], + }; - }, - computed: { - }, - mounted() { + }, + computed: { + }, + mounted() { - let timer; + let timer; - const delay = 500; + const delay = 500; - wu_on_load(); + wu_on_load(); - $(table.filters_el + ' form.search-form').on('submit', function(e) { + $(table.filters_el + ' form.search-form').on('submit', function(e) { - e.preventDefault(); + e.preventDefault(); - }); + }); - // Page number input - $(table.filters_el + ' input[name=s]').on('input keyup', function(e) { + // Page number input + $(table.filters_el + ' input[name=s]').on('input keyup', function(e) { - // If user hit enter, we don't want to submit the form - // We don't preventDefault() for all keys because it would - // also prevent to get the page number! - if (13 === e.which) { + // If user hit enter, we don't want to submit the form + // We don't preventDefault() for all keys because it would + // also prevent to get the page number! + if (13 === e.which) { - e.preventDefault(); + e.preventDefault(); - } // end if; + } // end if; - // This time we fetch the variables in inputs - const data = { - paged: parseInt($('input[name=paged]').val()) || '1', - s: $('input[name=s]').val() || '', - }; + // This time we fetch the variables in inputs + const data = { + paged: parseInt($('input[name=paged]').val()) || '1', + s: $('input[name=s]').val() || '', + }; - // Fix paged - if ($('input[name=s]').val() !== '') { + // Fix paged + if ($('input[name=s]').val() !== '') { - data.paged = '1'; + data.paged = '1'; - } // end if; + } // end if; - // Now the timer comes to use: we wait half a second after - // the user stopped typing to actually send the call. If - // we don't, the keyup event will trigger instantly and - // thus may cause duplicate calls before sending the intended - // value - window.clearTimeout(timer); + // Now the timer comes to use: we wait half a second after + // the user stopped typing to actually send the call. If + // we don't, the keyup event will trigger instantly and + // thus may cause duplicate calls before sending the intended + // value + window.clearTimeout(timer); - timer = window.setTimeout(function() { + timer = window.setTimeout(function() { - table.update(data); + table.update(data); - }, delay); + }, delay); - }); + }); - }, - methods: { - set_view(type, value) { + }, + methods: { + set_view(type, value) { - const query = window.location.href.split('?')[1]; + const query = window.location.href.split('?')[ 1 ]; - const data = $.extend({}, table.__get_query(query), { - paged: table.__query(query, 'paged') || '1', - s: table.__query(query, 's') || '', - }); + const data = $.extend({}, table.__get_query(query), { + paged: table.__query(query, 'paged') || '1', + s: table.__query(query, 's') || '', + }); - this.view = value; + this.view = value; - data[type] = value; + data[ type ] = value; - jQuery('.wu-filter .current').removeClass('current'); + jQuery('.wu-filter .current').removeClass('current'); - table.update(data); + table.update(data); - }, - get_filter_type(field) { + }, + get_filter_type(field) { - const available_filter = _.findWhere(available_filters, { - field, - }); + const available_filter = _.findWhere(available_filters, { + field, + }); - return available_filter.type; + return available_filter.type; - }, - get_filter_rule(field) { + }, + get_filter_rule(field) { - const available_filter = _.findWhere(available_filters, { - field, - }); + const available_filter = _.findWhere(available_filters, { + field, + }); - return available_filter.rule; + return available_filter.rule; - }, - remove_filter(index) { + }, + remove_filter(index) { - this.filters.splice(index, 1); + this.filters.splice(index, 1); - }, - add_new_filter() { + }, + add_new_filter() { - this.filters.push(_.first(table.copy(this.available_filters))); + this.filters.push(_.first(table.copy(this.available_filters))); - }, - open_filters() { + }, + open_filters() { - this.open = true; + this.open = true; - }, - close_filters() { + }, + close_filters() { - this.open = false; + this.open = false; - }, - }, - }); + }, + }, + }); - }, + }, - set_history(data) { + set_history(data) { - if (window[id + '_config'].context !== 'page') { + if (window[ id + '_config' ].context !== 'page') { - return; + return; - } + } - /** Update History */ - try { + /** Update History */ + try { - const history_vars = _.omit(data, function(value, key) { + const history_vars = _.omit(data, function(value, key) { - return key === 'action' || + return key === 'action' || key === 'table_id' || ! value || key.indexOf('_') === 0; - }); + }); - history.pushState({}, null, '?' + $.param(history_vars)); + history.pushState({}, null, '?' + $.param(history_vars)); - } catch (err) { + } catch (err) { - // eslint-disable-next-line no-console - console.warn('Browser does not support pushState.', err); + // eslint-disable-next-line no-console + console.warn('Browser does not support pushState.', err); - } // end try; + } // end try; - }, + }, - /** - * AJAX call - * - * Send the call and replace table parts with updated version! - * - * @param {Object} data The data to pass through AJAX - */ - update(data) { + /** + * AJAX call + * + * Send the call and replace table parts with updated version! + * + * @param {Object} data The data to pass through AJAX + */ + update(data) { - const table = this; + const table = this; - const $table_parent = $('#wu-' + id); + const $table_parent = $('#wu-' + id); - const default_data = { - action: 'wu_list_table_fetch_ajax_results', - table_id: id, - id: $('input#id').val(), - }; + const default_data = { + action: 'wu_list_table_fetch_ajax_results', + table_id: id, + id: $('input#id').val(), + }; - default_data['_ajax_' + id + '_nonce'] = $('#_ajax_' + id + '_nonce').val(); + default_data[ '_ajax_' + id + '_nonce' ] = $('#_ajax_' + id + '_nonce').val(); - const form_data = $.extend( - {}, - default_data, - // $($table_parent).find('input').serializeObject(), - // $(table.filters_el).find('input').serializeObject(), - data, - ); + const form_data = $.extend( + {}, + default_data, + // $($table_parent).find('input').serializeObject(), + // $(table.filters_el).find('input').serializeObject(), + data, + ); - const $content = $table_parent.find('tbody, .wu-grid-content'); + const $content = $table_parent.find('tbody, .wu-grid-content'); - $content.animate({ opacity: 0.4 }, 300); + $content.animate({ opacity: 0.4 }, 300); - $.ajax({ - // eslint-disable-next-line no-undef - url: ajaxurl, - // Add action and nonce to our collected data - data: form_data, - // Handle the successful result - statusCode: { - 403() { + $.ajax({ + // eslint-disable-next-line no-undef + url: ajaxurl, + // Add action and nonce to our collected data + data: form_data, + // Handle the successful result + statusCode: { + 403() { - $content.animate({ opacity: 1 }, 300); + $content.animate({ opacity: 1 }, 300); - }, - }, - success(response) { + }, + }, + success(response) { - table.set_history(form_data, default_data); + table.set_history(form_data, default_data); - $content.animate({ opacity: 1 }, 300); + $content.animate({ opacity: 1 }, 300); - // Add the requested rows - if (typeof response.rows !== 'undefined') { + // Add the requested rows + if (typeof response.rows !== 'undefined') { - $content.html(response.rows); + $content.html(response.rows); - } // end if; + } // end if; - // Add the requested rows - if (typeof response.count !== 'undefined') { + // Add the requested rows + if (typeof response.count !== 'undefined') { - // table.filters.count = response.count; + // table.filters.count = response.count; - } // end if; + } // end if; - // Update column headers for sorting - if (response.column_headers.length) { + // Update column headers for sorting + if (response.column_headers.length) { - $table_parent.find('thead tr, tfoot tr').html(response.column_headers); + $table_parent.find('thead tr, tfoot tr').html(response.column_headers); - } // end if; + } // end if; - // Update pagination for navigation - if (response.pagination.top.length) { + // Update pagination for navigation + if (response.pagination.top.length) { - $table_parent.find('.tablenav.top .tablenav-pages').html($(response.pagination.top).html()); + $table_parent.find('.tablenav.top .tablenav-pages').html($(response.pagination.top).html()); - } // end if; + } // end if; - if (response.pagination.bottom.length) { + if (response.pagination.bottom.length) { - $table_parent.find('.tablenav.bottom .tablenav-pages').html($(response.pagination.bottom).html()); + $table_parent.find('.tablenav.bottom .tablenav-pages').html($(response.pagination.bottom).html()); - } // end if; + } // end if; - hooks.doAction('wu_list_table_update', response, form_data, $table_parent); + hooks.doAction('wu_list_table_update', response, form_data, $table_parent); - // Init back our event handlers - // table.init(); + // Init back our event handlers + // table.init(); - }, - error(jqXHR) { + }, + error(jqXHR) { - $content.animate({ opacity: 1 }, 300); + $content.animate({ opacity: 1 }, 300); - // eslint-disable-next-line no-undef - wu_ajax_error(jqXHR); + // eslint-disable-next-line no-undef + wu_ajax_error(jqXHR); - }, - }); + }, + }); - }, + }, - /** - * Filter the URL Query to extract variables - * - * @see http://css-tricks.com/snippets/javascript/get-url-variables/ - * @param {string} query The URL query part containing the variables - * @param {string} variable The URL query part containing the variables - * @return {string|boolean} The variable value if available, false else. - */ - __query(query, variable) { + /** + * Filter the URL Query to extract variables + * + * @see http://css-tricks.com/snippets/javascript/get-url-variables/ + * @param {string} query The URL query part containing the variables + * @param {string} variable The URL query part containing the variables + * @return {string|boolean} The variable value if available, false else. + */ + __query(query, variable) { - const vars = query.split('&'); + const vars = query.split('&'); - for (let i = 0; i < vars.length; i++) { + for (let i = 0; i < vars.length; i++) { - const pair = vars[i].split('='); + const pair = vars[ i ].split('='); - if (pair[0] === variable) { + if (pair[ 0 ] === variable) { - return pair[1]; + return pair[ 1 ]; - } // end if; + } // end if; - } // end for; + } // end for; - return false; + return false; - }, + }, - __get_query(query) { + __get_query(query) { - const vars = query.split('&'); + const vars = query.split('&'); - const _query = {}; + const _query = {}; - for (let i = 0; i < vars.length; i++) { + for (let i = 0; i < vars.length; i++) { - const pair = vars[i].split('='); + const pair = vars[ i ].split('='); - _query[pair[0]] = pair[1]; + _query[ pair[ 0 ] ] = pair[ 1 ]; - } // end for; + } // end for; - return _query; + return _query; - }, + }, - }; + }; - }; // end wu_create_list; + }; // end wu_create_list; }(jQuery, wp.hooks)); diff --git a/assets/js/network-activate.js b/assets/js/network-activate.js index e5bad69db..79f3ad2b4 100644 --- a/assets/js/network-activate.js +++ b/assets/js/network-activate.js @@ -5,7 +5,7 @@ * reloads the page on success or shows an error message with a fallback * help link on failure. * - * @package WP_Ultimo + * @package * @subpackage Assets * @since 2.6.0 */ @@ -15,12 +15,12 @@ jQuery(function($) { $(document).on('click', '.wu-network-activate-btn', function() { - var $btn = $(this); - var $wrapper = $btn.closest('div'); - var nonce = $btn.data('ajax-nonce'); - var $spinner = $wrapper.find('.wu-network-activate-spinner'); - var $message = $wrapper.find('.wu-network-activate-message'); - var $fallback = $wrapper.find('.wu-network-activate-fallback'); + const $btn = $(this); + const $wrapper = $btn.closest('div'); + const nonce = $btn.data('ajax-nonce'); + const $spinner = $wrapper.find('.wu-network-activate-spinner'); + const $message = $wrapper.find('.wu-network-activate-message'); + const $fallback = $wrapper.find('.wu-network-activate-fallback'); $btn.prop('disabled', true); $spinner.addClass('is-active'); @@ -43,7 +43,7 @@ jQuery(function($) { $btn.hide(); $fallback.show(); - var errorMsg = wu_network_activate.error_message; + let errorMsg = wu_network_activate.error_message; if (response.data) { if (Array.isArray(response.data) && response.data.length > 0 && response.data[ 0 ] && response.data[ 0 ].message) { diff --git a/assets/js/payment-status-poll.js b/assets/js/payment-status-poll.js index 425cc5c44..dbecd7139 100644 --- a/assets/js/payment-status-poll.js +++ b/assets/js/payment-status-poll.js @@ -1,72 +1,76 @@ (() => { -"use strict"; + "use strict"; -const config = window.wu_payment_poll; + const config = window.wu_payment_poll; -if (!config || !config.should_poll) { - return; -} - -let attempts = 0; -const max_attempts = parseInt(config.max_attempts, 10) || 20; -const poll_interval = parseInt(config.poll_interval, 10) || 3000; - -function show_status(message, css_class) { - const el = document.querySelector(config.status_selector); - if (!el) { + if (! config || ! config.should_poll) { return; } - el.textContent = message; - el.className = "wu-payment-status wu-p-3 wu-rounded wu-mt-3 wu-block wu-text-sm " + (css_class || ""); - el.style.display = "block"; -} -async function check_payment_status() { - attempts++; + let attempts = 0; + const max_attempts = parseInt(config.max_attempts, 10) || 20; + const poll_interval = parseInt(config.poll_interval, 10) || 3000; - if (attempts > max_attempts) { - show_status(config.messages.timeout, "wu-bg-yellow-100 wu-text-yellow-800"); - return; + function show_status(message, css_class) { + const el = document.querySelector(config.status_selector); + if (! el) { + return; + } + el.textContent = message; + el.className = "wu-payment-status wu-p-3 wu-rounded wu-mt-3 wu-block wu-text-sm " + (css_class || ""); + el.style.display = "block"; } - show_status(config.messages.checking, "wu-bg-gray-100 wu-text-gray-600"); + async function check_payment_status() { + attempts++; + + if (attempts > max_attempts) { + show_status(config.messages.timeout, "wu-bg-yellow-100 wu-text-yellow-800"); + return; + } - try { - const params = new URLSearchParams({ - action: "wu_check_payment_status", - nonce: config.nonce, - payment_hash: config.payment_hash, - }); + show_status(config.messages.checking, "wu-bg-gray-100 wu-text-gray-600"); - const response = await fetch(config.ajax_url, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded" }, - body: params.toString(), - }); + try { + const params = new URLSearchParams({ + action: "wu_check_payment_status", + nonce: config.nonce, + payment_hash: config.payment_hash, + }); - const data = await response.json(); + const response = await fetch(config.ajax_url, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: params.toString(), + }); - if (data.success && data.data.status === "completed") { - show_status(config.messages.completed, "wu-bg-green-100 wu-text-green-800"); - if (config.success_redirect) { - setTimeout(() => { window.location.href = config.success_redirect; }, 1500); - } else { - setTimeout(() => { window.location.reload(); }, 1500); + const data = await response.json(); + + if (data.success && data.data.status === "completed") { + show_status(config.messages.completed, "wu-bg-green-100 wu-text-green-800"); + if (config.success_redirect) { + setTimeout(() => { + window.location.href = config.success_redirect; + }, 1500); + } else { + setTimeout(() => { + window.location.reload(); + }, 1500); + } + return; } - return; - } - // Still pending — continue polling - show_status(config.messages.pending, "wu-bg-blue-100 wu-text-blue-800"); - setTimeout(check_payment_status, poll_interval); + // Still pending — continue polling + show_status(config.messages.pending, "wu-bg-blue-100 wu-text-blue-800"); + setTimeout(check_payment_status, poll_interval); - } catch (_e) { - show_status(config.messages.error, "wu-bg-red-100 wu-text-red-800"); - setTimeout(check_payment_status, poll_interval); + } catch (_e) { + show_status(config.messages.error, "wu-bg-red-100 wu-text-red-800"); + setTimeout(check_payment_status, poll_interval); + } } -} -document.addEventListener("DOMContentLoaded", () => { - setTimeout(check_payment_status, poll_interval); -}); + document.addEventListener("DOMContentLoaded", () => { + setTimeout(check_payment_status, poll_interval); + }); })(); diff --git a/assets/js/paypal-setup-wizard.js b/assets/js/paypal-setup-wizard.js index a5d1b6f7c..6332b136a 100644 --- a/assets/js/paypal-setup-wizard.js +++ b/assets/js/paypal-setup-wizard.js @@ -11,7 +11,7 @@ return; } - var data = wu_paypal_setup_wizard; + const data = wu_paypal_setup_wizard; new Vue( { el: '#wu-paypal-setup-wizard-test', @@ -22,12 +22,12 @@ errorMessage: data.error_message, rawResponse: data.waiting_message, }, - mounted: function () { + mounted () { this.runTest(); }, methods: { - runTest: function () { - var that = this; + runTest () { + const that = this; this.loading = true; this.success = false; this.rawResponse = data.waiting_message; @@ -40,7 +40,7 @@ nonce: data.nonce, sandbox_mode: data.sandbox_mode, }, - success: function ( response ) { + success ( response ) { that.loading = false; that.rawResponse = JSON.stringify( response, null, 2 ); @@ -54,7 +54,7 @@ data.error_message; } }, - error: function ( xhr ) { + error ( xhr ) { that.loading = false; that.success = false; that.errorMessage = data.error_message; @@ -67,4 +67,4 @@ }, } ); } ); -} )( jQuery ); +}( jQuery )); diff --git a/assets/js/pricing-table.js b/assets/js/pricing-table.js index 0567d5940..412084fc2 100644 --- a/assets/js/pricing-table.js +++ b/assets/js/pricing-table.js @@ -7,4 +7,4 @@ $('[data-frequency-selector="' + wu_default_pricing_option + '"]').click(); }, 100); }); -})(jQuery); \ No newline at end of file +}(jQuery)); \ No newline at end of file diff --git a/assets/js/screenshot-scraper.js b/assets/js/screenshot-scraper.js index 23243c513..6c84f2013 100644 --- a/assets/js/screenshot-scraper.js +++ b/assets/js/screenshot-scraper.js @@ -1,56 +1,56 @@ /* global wu_block_ui, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - $('#scraper').on('click', function(e) { + $('#scraper').on('click', function(e) { - e.preventDefault(); + e.preventDefault(); - const block = wu_block_ui('#wp-ultimo-image-widget'); + const block = wu_block_ui('#wp-ultimo-image-widget'); - $('.wu-scraper-note, .wu-scraper-error').hide(); + $('.wu-scraper-note, .wu-scraper-error').hide(); - jQuery.ajax({ - // eslint-disable-next-line no-undef - url: ajaxurl, - type: 'POST', - data: { - action: 'wu_get_screenshot', - site_id: $('#id').val(), - }, - error(jqXHR) { + jQuery.ajax({ + // eslint-disable-next-line no-undef + url: ajaxurl, + type: 'POST', + data: { + action: 'wu_get_screenshot', + site_id: $('#id').val(), + }, + error(jqXHR) { - block.unblock(); + block.unblock(); - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, - success(res) { + }, + success(res) { - block.unblock(); + block.unblock(); - if (res.success) { + if (res.success) { - $('#wp-ultimo-image-widget img').attr('src', res.data.attachment_url); + $('#wp-ultimo-image-widget img').attr('src', res.data.attachment_url); - $('#wp-ultimo-image-widget input').val(res.data.attachment_id); + $('#wp-ultimo-image-widget input').val(res.data.attachment_id); - $('.wu-scraper-note').show(); + $('.wu-scraper-note').show(); - } else { + } else { - $('.wu-scraper-error').show(); + $('.wu-scraper-error').show(); - $('.wu-scraper-error-message').text(res.data.pop().message); + $('.wu-scraper-error-message').text(res.data.pop().message); - } // end if; + } // end if; - }, - }); + }, + }); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/setup-wizard-extra.js b/assets/js/setup-wizard-extra.js index 7c19a5fc6..96c1711e6 100644 --- a/assets/js/setup-wizard-extra.js +++ b/assets/js/setup-wizard-extra.js @@ -2,49 +2,49 @@ // eslint-disable-next-line prefer-const let wu_block_ui_polyfill = function(el) { - jQuery(el).wu_block({ - message: '', - overlayCSS: { - backgroundColor: '#FFF', - opacity: 0.6, - }, - css: { - padding: 0, - margin: 0, - width: '50%', - fontSize: '14px !important', - top: '40%', - left: '35%', - textAlign: 'center', - color: '#000', - border: 'none', - backgroundColor: 'none', - cursor: 'wait', - }, - }); - - const el_instance = jQuery(el); - - el_instance.unblock = jQuery(el).wu_unblock; - - return el_instance; + jQuery(el).wu_block({ + message: '', + overlayCSS: { + backgroundColor: '#FFF', + opacity: 0.6, + }, + css: { + padding: 0, + margin: 0, + width: '50%', + fontSize: '14px !important', + top: '40%', + left: '35%', + textAlign: 'center', + color: '#000', + border: 'none', + backgroundColor: 'none', + cursor: 'wait', + }, + }); + + const el_instance = jQuery(el); + + el_instance.unblock = jQuery(el).wu_unblock; + + return el_instance; }; (function($) { - $(document).ready(function() { + $(document).ready(function() { - jQuery('[role="tooltip"]').tipTip({ - attribute: 'aria-label', - }); + jQuery('[role="tooltip"]').tipTip({ + attribute: 'aria-label', + }); - $('#poststuff').on('submit', 'form', function() { + $('#poststuff').on('submit', 'form', function() { - wu_block_ui_polyfill($(this)); + wu_block_ui_polyfill($(this)); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/site-maintenance.js b/assets/js/site-maintenance.js index b2057147f..0037d8436 100644 --- a/assets/js/site-maintenance.js +++ b/assets/js/site-maintenance.js @@ -1,53 +1,53 @@ /* global wu_site_maintenance, wu_block_ui, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - $('#wu-tg-maintenance_mode').change(function() { + $('#wu-tg-maintenance_mode').change(function() { - const blocked = wu_block_ui('#wp-ultimo-site-maintenance-element .inside'); + const blocked = wu_block_ui('#wp-ultimo-site-maintenance-element .inside'); - jQuery.ajax({ - url: wu_site_maintenance.ajaxurl, - type: 'post', - data: { - action: 'toggle_maintenance_mode', - maintenance_status: $('#wu-tg-maintenance_mode').is(':checked'), - site_hash: $('[name=site_hash]').val(), - _wpnonce: wu_site_maintenance.nonce, - }, - success(response) { + jQuery.ajax({ + url: wu_site_maintenance.ajaxurl, + type: 'post', + data: { + action: 'toggle_maintenance_mode', + maintenance_status: $('#wu-tg-maintenance_mode').is(':checked'), + site_hash: $('[name=site_hash]').val(), + _wpnonce: wu_site_maintenance.nonce, + }, + success(response) { - blocked.unblock(); + blocked.unblock(); - if (response.success) { + if (response.success) { - if (response.data.value) { + if (response.data.value) { - $('#wp-admin-bar-wu-maintenance-mode').show(); + $('#wp-admin-bar-wu-maintenance-mode').show(); - } else { + } else { - $('#wp-admin-bar-wu-maintenance-mode').hide(); + $('#wp-admin-bar-wu-maintenance-mode').hide(); - } // end if; + } // end if; - } + } - }, // end success; + }, // end success; - error(jqXHR) { + error(jqXHR) { - blocked.unblock(); + blocked.unblock(); - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, // end error; + }, // end error; - }); // end ajax; + }); // end ajax; - }); //end checked + }); //end checked - }); + }); }(jQuery)); diff --git a/assets/js/tax-rates.js b/assets/js/tax-rates.js index 65e060923..65cba0033 100644 --- a/assets/js/tax-rates.js +++ b/assets/js/tax-rates.js @@ -2,392 +2,392 @@ /* global _, vuedraggable, Vue, wu_block_ui, ajaxurl, wu_tax_ratesl10n, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - /** - * Vue - */ - if ($('#wu-tax-rates').length) { - - Vue.component('selectizer', { - props: [ - 'value', - 'id', - 'name', - 'model', - 'country', - 'state', - 'selected', - 'options', - 'placeholder', - ], - template: '', - updated() { - - this.$nextTick(function() { - - const options = jQuery(this.$el).data('__options'); - - if (options.data.country !== this.country) { - - options.data.country = this.country; - - jQuery(this.$el).data('__options', options); - - this.$el.selectize.clear(); - - this.$el.selectize.clearOptions(); - - } // end if; - - if (options.data.state !== this.state) { - - options.data.state = this.state; - - jQuery(this.$el).data('__options', options); - - } // end if; + /** + * Vue + */ + if ($('#wu-tax-rates').length) { + + Vue.component('selectizer', { + props: [ + 'value', + 'id', + 'name', + 'model', + 'country', + 'state', + 'selected', + 'options', + 'placeholder', + ], + template: '', + updated() { + + this.$nextTick(function() { + + const options = jQuery(this.$el).data('__options'); + + if (options.data.country !== this.country) { + + options.data.country = this.country; + + jQuery(this.$el).data('__options', options); + + this.$el.selectize.clear(); + + this.$el.selectize.clearOptions(); + + } // end if; + + if (options.data.state !== this.state) { + + options.data.state = this.state; + + jQuery(this.$el).data('__options', options); + + } // end if; - }); + }); - }, - mounted() { + }, + mounted() { - const that = this; + const that = this; - const item = this.$el; + const item = this.$el; - window.wu_selector({ - el: item, - maxItems: 1000, - options: this.options, - valueField: 'slug', - labelField: 'name', - searchField: ['slug', 'name'], - create: true, - templateName: 'checkout_form', - data: { - action: 'wu_search', - model: this.model, - country: this.country, - state: this.state, - number: 10, - }, - }); + window.wu_selector({ + el: item, + maxItems: 1000, + options: this.options, + valueField: 'slug', + labelField: 'name', + searchField: [ 'slug', 'name' ], + create: true, + templateName: 'checkout_form', + data: { + action: 'wu_search', + model: this.model, + country: this.country, + state: this.state, + number: 10, + }, + }); - this.$el.selectize.on('change', function(value) { + this.$el.selectize.on('change', function(value) { - that.$emit('input', value); + that.$emit('input', value); - }); + }); - }, - }); + }, + }); - window.wu_tax_rates = new Vue({ - el: '#wu-tax-rates', - components: { - vuedraggable, - }, - data() { + window.wu_tax_rates = new Vue({ + el: '#wu-tax-rates', + components: { + vuedraggable, + }, + data() { - return { - dragging: false, - tax_category: 'default', - switching: false, - creating: false, - create_name: '', - toggle: false, - loading: true, - saving: false, - initialLoading: true, - error: false, - changed: false, - data: { - default: { - name: 'Default', - rates: [], - }, - }, - delete: [], - saveMessage: '', - errorMessage: '', - rate_type: 'standard_rate', - editing: 0, - item: { - title: wu_tax_ratesl10n.name, - country: '', - state: '', - tax_rate: '', - type: 'regular', - compound: false, - }, - }; + return { + dragging: false, + tax_category: 'default', + switching: false, + creating: false, + create_name: '', + toggle: false, + loading: true, + saving: false, + initialLoading: true, + error: false, + changed: false, + data: { + default: { + name: 'Default', + rates: [], + }, + }, + delete: [], + saveMessage: '', + errorMessage: '', + rate_type: 'standard_rate', + editing: 0, + item: { + title: wu_tax_ratesl10n.name, + country: '', + state: '', + tax_rate: '', + type: 'regular', + compound: false, + }, + }; - }, - watch: { - loading(new_value) { + }, + watch: { + loading(new_value) { - if (new_value === true) { + if (new_value === true) { - window.wu_blocked_table = wu_block_ui('table.wp-list-table'); + window.wu_blocked_table = wu_block_ui('table.wp-list-table'); - } else { + } else { - if (typeof window.wu_blocked_table !== 'undefined') { + if (typeof window.wu_blocked_table !== 'undefined') { - window.wu_blocked_table.unblock(); + window.wu_blocked_table.unblock(); - } // end if; + } // end if; - } // end if; + } // end if; - }, - }, - mounted() { + }, + }, + mounted() { - this.loading = true; + this.loading = true; - this.pull_data(true); + this.pull_data(true); - $('.wu-tooltip-vue').tipTip(); + $('.wu-tooltip-vue').tipTip(); - const vm = this; + const vm = this; - this.$watch('data', function() { + this.$watch('data', function() { - if (vm.initialLoading) { + if (vm.initialLoading) { - vm.initialLoading = false; + vm.initialLoading = false; - return; + return; - } + } - vm.changed = true; + vm.changed = true; - }, { - deep: true, - }); + }, { + deep: true, + }); - }, - created() { + }, + created() { - // Create the event. - const event = document.createEvent('Event'); + // Create the event. + const event = document.createEvent('Event'); - // Define that the event name is 'build'. - event.initEvent('vue_loaded', true, true); + // Define that the event name is 'build'. + event.initEvent('vue_loaded', true, true); - event.vue = this; + event.vue = this; - // target can be any Element or other EventTarget. - window.dispatchEvent(event); + // target can be any Element or other EventTarget. + window.dispatchEvent(event); - }, - computed: { - selected() { + }, + computed: { + selected() { - return $(this.data[this.tax_category].rates).filter(function(index, item) { + return $(this.data[ this.tax_category ].rates).filter(function(index, item) { - return item.selected; + return item.selected; - }); + }); - }, - }, - methods: { - refresh(e) { + }, + }, + methods: { + refresh(e) { - e.preventDefault(); + e.preventDefault(); - this.loading = true; + this.loading = true; - this.pull_data(); + this.pull_data(); - }, - select_all(event) { + }, + select_all(event) { - const toggle = $(event.target).is(':checked'); + const toggle = $(event.target).is(':checked'); - this.data[this.tax_category].rates = $.map(this.data[this.tax_category].rates, function(item) { + this.data[ this.tax_category ].rates = $.map(this.data[ this.tax_category ].rates, function(item) { - item.selected = toggle; + item.selected = toggle; - return item; + return item; - }); + }); - }, - pull_data() { + }, + pull_data() { - const that = this; + const that = this; - jQuery.getJSON(ajaxurl + '?action=wu_get_tax_rates').done(function(response) { + jQuery.getJSON(ajaxurl + '?action=wu_get_tax_rates').done(function(response) { - that.loading = false; + that.loading = false; - that.data = response.data; + that.data = response.data; - }) - .fail(function(jqXHR) { + }) + .fail(function(jqXHR) { - that.loading = false; + that.loading = false; - that.error = true; + that.error = true; - that.errorMessage = jqXHR.statusText; + that.errorMessage = jqXHR.statusText; - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }); + }); - }, - add_tax_category() { + }, + add_tax_category() { - this.data[this.create_name] = { - name: this.create_name, - rates: [], - }; + this.data[ this.create_name ] = { + name: this.create_name, + rates: [], + }; - this.creating = false; + this.creating = false; - this.tax_category = this.create_name; + this.tax_category = this.create_name; - }, - add_row() { + }, + add_row() { - Vue.set(this.data[this.tax_category], 'rates', this.data[this.tax_category].rates.concat([ - { - title: wu_tax_ratesl10n.name, - country: '', - state: '', - tax_rate: '', - type: 'regular', - compound: false, - }, - ])); + Vue.set(this.data[ this.tax_category ], 'rates', this.data[ this.tax_category ].rates.concat([ + { + title: wu_tax_ratesl10n.name, + country: '', + state: '', + tax_rate: '', + type: 'regular', + compound: false, + }, + ])); - this.$forceUpdate(); + this.$forceUpdate(); - }, - delete_tax_category() { + }, + delete_tax_category() { - // eslint-disable-next-line no-alert - const are_you_sure = confirm(wu_tax_ratesl10n.confirm_delete_tax_category_message); + // eslint-disable-next-line no-alert + const are_you_sure = confirm(wu_tax_ratesl10n.confirm_delete_tax_category_message); - const that = this; + const that = this; - if (are_you_sure) { + if (are_you_sure) { - const cleaned_list = _.filter(this.data, function(item, index) { + const cleaned_list = _.filter(this.data, function(item, index) { - return index !== that.tax_category; + return index !== that.tax_category; - }); + }); - that.data = cleaned_list.length ? cleaned_list : { - default: { - name: 'Default', - rates: [], - }, - }; + that.data = cleaned_list.length ? cleaned_list : { + default: { + name: 'Default', + rates: [], + }, + }; - that.tax_category = Object.keys(that.data).shift(); + that.tax_category = Object.keys(that.data).shift(); - } // end if + } // end if - }, - delete_rows() { + }, + delete_rows() { - this.delete = this.delete.concat(this.selected.get()); + this.delete = this.delete.concat(this.selected.get()); - // eslint-disable-next-line no-alert - const are_you_sure = confirm(wu_tax_ratesl10n.confirm_message); + // eslint-disable-next-line no-alert + const are_you_sure = confirm(wu_tax_ratesl10n.confirm_message); - if (are_you_sure) { + if (are_you_sure) { - const cleaned_list = $(this.data[this.tax_category].rates).filter(function(index, item) { + const cleaned_list = $(this.data[ this.tax_category ].rates).filter(function(index, item) { - return ! item.selected; + return ! item.selected; - }); + }); - Vue.set(this.data[this.tax_category], 'rates', cleaned_list.get()); + Vue.set(this.data[ this.tax_category ], 'rates', cleaned_list.get()); - this.$forceUpdate(); + this.$forceUpdate(); - } // end if + } // end if - }, - save() { + }, + save() { - const that = this; + const that = this; - that.saving = true; + that.saving = true; - if (typeof that.data[that.tax_category].rates !== 'undefined') { + if (typeof that.data[ that.tax_category ].rates !== 'undefined') { - _.map(that.data[that.tax_category].rates, (item, index) => { + _.map(that.data[ that.tax_category ].rates, (item, index) => { - item.priority = index * 10; + item.priority = index * 10; - return item; + return item; - }); + }); - } + } - $.post({ - url: ajaxurl + '?action=wu_save_tax_rates&' + $('#nonce_form').serialize(), - data: JSON.stringify({ - tax_rates: that.data, - tax_category: that.tax_category, - }), - dataType: 'json', - contentType: 'application/json; charset=utf-8', - }).success(function(data) { + $.post({ + url: ajaxurl + '?action=wu_save_tax_rates&' + $('#nonce_form').serialize(), + data: JSON.stringify({ + tax_rates: that.data, + tax_category: that.tax_category, + }), + dataType: 'json', + contentType: 'application/json; charset=utf-8', + }).success(function(data) { - that.saving = false; + that.saving = false; - that.changed = false; + that.changed = false; - that.delete = []; + that.delete = []; - that.saveMessage = data.message; + that.saveMessage = data.message; - if (data.code === 'success') { + if (data.code === 'success') { - that.loading = true; + that.loading = true; - that.initialLoading = true; + that.initialLoading = true; - that.pull_data(); + that.pull_data(); - that.tax_category = data.tax_category; + that.tax_category = data.tax_category; - } + } - setInterval(function() { + setInterval(function() { - that.saveMessage = ''; + that.saveMessage = ''; - }, 6000); + }, 6000); - }).fail(function(jqXHR) { + }).fail(function(jqXHR) { - that.saving = false; + that.saving = false; - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }); + }); - }, - }, - }); + }, + }, + }); - } // end if; + } // end if; - }); + }); }(jQuery)); diff --git a/assets/js/template-library.js b/assets/js/template-library.js index 295e55fb0..a69e077a3 100644 --- a/assets/js/template-library.js +++ b/assets/js/template-library.js @@ -1,187 +1,187 @@ /* global Vue, wu_template_library, ajaxurl, _ */ (function($) { - const search_template = new Vue({ - el: '#search-templates', - data: { - search: wu_template_library.search, - }, - }); + const search_template = new Vue({ + el: '#search-templates', + data: { + search: wu_template_library.search, + }, + }); - const wu_main_template_app = new Vue({ - el: '#wu-template-library', - data() { + const wu_main_template_app = new Vue({ + el: '#wu-template-library', + data() { - return { - loading: true, - category: wu_template_library.category, - templates: [], - }; + return { + loading: true, + category: wu_template_library.category, + templates: [], + }; - }, - mounted() { + }, + mounted() { - this.fetch_templates_list(); + this.fetch_templates_list(); - }, - computed: { - search() { + }, + computed: { + search() { - return search_template.search; + return search_template.search; - }, - i18n() { + }, + i18n() { - return window.wu_template_library.i18n; + return window.wu_template_library.i18n; - }, - categories() { + }, + categories() { - let categories = []; + let categories = []; - _.each(this.templates, function(template) { + _.each(this.templates, function(template) { - if (template.categories && Array.isArray(template.categories)) { - categories = categories.concat(template.categories); - } + if (template.categories && Array.isArray(template.categories)) { + categories = categories.concat(template.categories); + } - }); + }); - return _.unique(categories, function(cat) { - return cat.slug; - }); + return _.unique(categories, function(cat) { + return cat.slug; + }); - }, - templates_list() { + }, + templates_list() { - const app = this; + const app = this; - return _.filter(app.templates, function(template) { + return _.filter(app.templates, function(template) { - // Filter by category - if (app.category !== 'all') { - const hasCategory = template.categories && template.categories.some(cat => cat.slug === app.category); - if (!hasCategory) { - return false; - } - } + // Filter by category + if (app.category !== 'all') { + const hasCategory = template.categories && template.categories.some((cat) => cat.slug === app.category); + if (! hasCategory) { + return false; + } + } - // Filter by search - if (!app.search) { + // Filter by search + if (! app.search) { - return true; + return true; - } + } - const search_fields = [ - template.slug || '', - template.name || '', - template.description || '', - template.short_description || '', - template.author || '', - template.industry_type || '', - ]; + const search_fields = [ + template.slug || '', + template.name || '', + template.description || '', + template.short_description || '', + template.author || '', + template.industry_type || '', + ]; - // Add category names to search - if (template.categories && Array.isArray(template.categories)) { - template.categories.forEach(function(cat) { - search_fields.push(cat.name || cat.slug || ''); - }); - } + // Add category names to search + if (template.categories && Array.isArray(template.categories)) { + template.categories.forEach(function(cat) { + search_fields.push(cat.name || cat.slug || ''); + }); + } - return search_fields.join(' ').toLowerCase().indexOf(app.search.toLowerCase()) > -1; + return search_fields.join(' ').toLowerCase().indexOf(app.search.toLowerCase()) > -1; - }); + }); - }, - count() { + }, + count() { - return this.templates_list.length; + return this.templates_list.length; - }, - }, - methods: { - fetch_templates_list() { + }, + }, + methods: { + fetch_templates_list() { - const app = this; + const app = this; - $.ajax({ - method: 'GET', - url: ajaxurl, - data: { - action: 'serve_templates_list', - }, - success(data) { + $.ajax({ + method: 'GET', + url: ajaxurl, + data: { + action: 'serve_templates_list', + }, + success(data) { - if (data.success && data.data) { - app.templates = data.data; - } else { - app.templates = []; - } + if (data.success && data.data) { + app.templates = data.data; + } else { + app.templates = []; + } - app.loading = false; + app.loading = false; - }, - error(jqXHR) { + }, + error(jqXHR) { - app.templates = []; - app.loading = false; + app.templates = []; + app.loading = false; - // eslint-disable-next-line no-undef - wu_ajax_error(jqXHR); + // eslint-disable-next-line no-undef + wu_ajax_error(jqXHR); - }, - }); + }, + }); - }, - }, - }); + }, + }, + }); - new Vue({ - el: '.wp-heading-inline', - data: {}, - computed: { - count() { + new Vue({ + el: '.wp-heading-inline', + data: {}, + computed: { + count() { - return wu_main_template_app.count; + return wu_main_template_app.count; - }, - }, - }); + }, + }, + }); - new Vue({ - el: '#templates-menu', - data: {}, - methods: { - set_category(category) { + new Vue({ + el: '#templates-menu', + data: {}, + methods: { + set_category(category) { - this.main_app.category = category; + this.main_app.category = category; - const url = new URL(window.location.href); + const url = new URL(window.location.href); - url.searchParams.set('tab', category); + url.searchParams.set('tab', category); - history.pushState({}, null, url); + history.pushState({}, null, url); - }, - }, - computed: { - main_app() { + }, + }, + computed: { + main_app() { - return wu_main_template_app; + return wu_main_template_app; - }, - category() { + }, + category() { - return wu_main_template_app.category; + return wu_main_template_app.category; - }, - available_categories() { + }, + available_categories() { - return wu_main_template_app.categories; + return wu_main_template_app.categories; - }, - }, - }); + }, + }, + }); }(jQuery)); diff --git a/assets/js/template-previewer.js b/assets/js/template-previewer.js index 0181bcce6..bca98e68d 100644 --- a/assets/js/template-previewer.js +++ b/assets/js/template-previewer.js @@ -1,150 +1,150 @@ (() => { -"use strict"; -const CreateCookie = (name, value, days) => { - let expires; - if (days) { - const date = /* @__PURE__ */ new Date(); - date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3); - expires = "; expires=" + date.toUTCString(); - } else { - expires = ""; - } - document.cookie = name + "=" + value + expires + "; path=/"; -}; -const ReadCookie = (name) => { - const nameEQ = name + "="; - const ca = document.cookie.split(";"); - for (let i = 0; i < ca.length; i++) { - let c = ca[i]; - while (c.charAt(0) === " ") { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) === 0) { - return c.substring(nameEQ.length, c.length); - } - } - return null; -}; -const ListenToCookieChange = (name, callback) => { - let cookie_value = ReadCookie(name); - setInterval(function() { - const new_cookie_value = ReadCookie(name); - if (new_cookie_value !== cookie_value) { - cookie_value = new_cookie_value; - callback(cookie_value); - } - }, 100); -}; -window.addEventListener("beforeunload", () => { - var _a; - return (_a = window.top) == null ? void 0 : _a.postMessage("wu_preview_changed", "*"); -}); -CreateCookie("wu_template", ""); -const isIOS = () => { - var _a; - window.addEventListener("touchstart", () => { - }); - const iDevices = [ - "iPad Simulator", - "iPhone Simulator", - "iPod Simulator", - "iPad", - "iPhone", - "iPod" - ]; - const platform = ((_a = navigator == null ? void 0 : navigator.userAgentData) == null ? void 0 : _a.platform) || (navigator == null ? void 0 : navigator.platform) || ""; - return iDevices.includes(platform); -}; -document.addEventListener("DOMContentLoaded", () => { - var _a; - ListenToCookieChange("wu_selected_products", () => document.location.reload()); - const iframe = document.getElementById("iframe"); - const wn = iframe == null ? void 0 : iframe.contentWindow; - wn == null ? void 0 : wn.postMessage("Hello to iframe from parent!", "https://" + location.hostname); - const elements = document.querySelectorAll("#action-select, #action-select2"); - elements.forEach((element) => element.addEventListener("click", (event) => { - event.preventDefault(); - const value = document.getElementById("template-selector").value; - CreateCookie("wu_template", value); - window.close(); - })); - const loadingIndicator = document.getElementById("wu-loading-indicator"); - iframe == null ? void 0 : iframe.addEventListener("load", () => { - var _a2; - if (loadingIndicator) { - loadingIndicator.style.display = "none"; - } - if (isIOS()) { - const body = (_a2 = document.getElementById("iframe")) == null ? void 0 : _a2.getElementsByTagName("body")[0]; - body == null ? void 0 : body.classList.add("wu-fix-safari-preview"); - (body == null ? void 0 : body.style) && Object.assign(body.style, { - position: "fixed", - top: 0, - right: 0, - bottom: 0, - left: 0, - "overflow-y": "scroll", - "-webkit-overflow-scrolling": "touch" - }); - } - }); - const adjustIframeHeight = () => { - var _a2; - const ee = ((_a2 = document.getElementById("switcher")) == null ? void 0 : _a2.offsetHeight) || 0; - iframe.style.height = document.body.offsetHeight - ee + "px"; - }; - window.addEventListener("resize", adjustIframeHeight); - adjustIframeHeight(); - const toggleList = () => { - const list = document.querySelectorAll("#theme_list ul"); - list.forEach((element) => element.style.display = element.style.display === "none" ? "block" : "none"); - }; - toggleList(); - (_a = document.getElementById("template_selector")) == null ? void 0 : _a.addEventListener("click", (event) => { - event.preventDefault(); - toggleList(); - }); - document.querySelectorAll("#theme_list ul li a").forEach((element) => element.addEventListener("click", (event) => { - event.preventDefault(); - toggleList(); - const target = event.currentTarget; - const href = target.getAttribute("href") || ""; - if (loadingIndicator) { - loadingIndicator.style.display = "flex"; - } - iframe.src = target.getAttribute("data-frame") || ""; - const selector = document.getElementById("template_selector"); - const selectorText = selector.firstChild; - selectorText.nodeValue = target.getAttribute("data-title") || ""; - window.history.pushState({}, "", href); - })); - const headerBar = document.getElementById("header-bar"); - if (headerBar) { - headerBar.style.display = "none"; - } - const screenSizes = { - desktop: "100%", - tabletlandscape: "1040px", - tabletportrait: "788px", - mobilelandscape: "815px", - mobileportrait: "375px", - placebo: "0px" - }; - document.querySelectorAll(".responsive a").forEach((element) => element.addEventListener("click", (event) => { - const target = event.currentTarget; - const width = Array.from(target.classList).reduce((acc, cur) => { - if (screenSizes[cur]) { - acc = screenSizes[cur]; - } - return acc; - }, ""); - iframe.style.width = width; - iframe.style.transition = "200ms"; - document.querySelectorAll(".responsive a").forEach((element2) => element2.classList.remove("active")); - target.classList.add("active"); - })); - if (navigator.userAgent.match(/iPad/i) !== null) { - iframe.style.height = "100%"; - } -}); + "use strict"; + const CreateCookie = (name, value, days) => { + let expires; + if (days) { + const date = /* @__PURE__ */ new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3); + expires = "; expires=" + date.toUTCString(); + } else { + expires = ""; + } + document.cookie = name + "=" + value + expires + "; path=/"; + }; + const ReadCookie = (name) => { + const nameEQ = name + "="; + const ca = document.cookie.split(";"); + for (let i = 0; i < ca.length; i++) { + let c = ca[ i ]; + while (c.charAt(0) === " ") { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) === 0) { + return c.substring(nameEQ.length, c.length); + } + } + return null; + }; + const ListenToCookieChange = (name, callback) => { + let cookie_value = ReadCookie(name); + setInterval(function() { + const new_cookie_value = ReadCookie(name); + if (new_cookie_value !== cookie_value) { + cookie_value = new_cookie_value; + callback(cookie_value); + } + }, 100); + }; + window.addEventListener("beforeunload", () => { + let _a; + return (_a = window.top) == null ? void 0 : _a.postMessage("wu_preview_changed", "*"); + }); + CreateCookie("wu_template", ""); + const isIOS = () => { + let _a; + window.addEventListener("touchstart", () => { + }); + const iDevices = [ + "iPad Simulator", + "iPhone Simulator", + "iPod Simulator", + "iPad", + "iPhone", + "iPod" + ]; + const platform = ((_a = navigator == null ? void 0 : navigator.userAgentData) == null ? void 0 : _a.platform) || (navigator == null ? void 0 : navigator.platform) || ""; + return iDevices.includes(platform); + }; + document.addEventListener("DOMContentLoaded", () => { + let _a; + ListenToCookieChange("wu_selected_products", () => document.location.reload()); + const iframe = document.getElementById("iframe"); + const wn = iframe == null ? void 0 : iframe.contentWindow; + wn == null ? void 0 : wn.postMessage("Hello to iframe from parent!", "https://" + location.hostname); + const elements = document.querySelectorAll("#action-select, #action-select2"); + elements.forEach((element) => element.addEventListener("click", (event) => { + event.preventDefault(); + const value = document.getElementById("template-selector").value; + CreateCookie("wu_template", value); + window.close(); + })); + const loadingIndicator = document.getElementById("wu-loading-indicator"); + iframe == null ? void 0 : iframe.addEventListener("load", () => { + let _a2; + if (loadingIndicator) { + loadingIndicator.style.display = "none"; + } + if (isIOS()) { + const body = (_a2 = document.getElementById("iframe")) == null ? void 0 : _a2.getElementsByTagName("body")[ 0 ]; + body == null ? void 0 : body.classList.add("wu-fix-safari-preview"); + (body == null ? void 0 : body.style) && Object.assign(body.style, { + position: "fixed", + top: 0, + right: 0, + bottom: 0, + left: 0, + "overflow-y": "scroll", + "-webkit-overflow-scrolling": "touch" + }); + } + }); + const adjustIframeHeight = () => { + let _a2; + const ee = ((_a2 = document.getElementById("switcher")) == null ? void 0 : _a2.offsetHeight) || 0; + iframe.style.height = document.body.offsetHeight - ee + "px"; + }; + window.addEventListener("resize", adjustIframeHeight); + adjustIframeHeight(); + const toggleList = () => { + const list = document.querySelectorAll("#theme_list ul"); + list.forEach((element) => element.style.display = element.style.display === "none" ? "block" : "none"); + }; + toggleList(); + (_a = document.getElementById("template_selector")) == null ? void 0 : _a.addEventListener("click", (event) => { + event.preventDefault(); + toggleList(); + }); + document.querySelectorAll("#theme_list ul li a").forEach((element) => element.addEventListener("click", (event) => { + event.preventDefault(); + toggleList(); + const target = event.currentTarget; + const href = target.getAttribute("href") || ""; + if (loadingIndicator) { + loadingIndicator.style.display = "flex"; + } + iframe.src = target.getAttribute("data-frame") || ""; + const selector = document.getElementById("template_selector"); + const selectorText = selector.firstChild; + selectorText.nodeValue = target.getAttribute("data-title") || ""; + window.history.pushState({}, "", href); + })); + const headerBar = document.getElementById("header-bar"); + if (headerBar) { + headerBar.style.display = "none"; + } + const screenSizes = { + desktop: "100%", + tabletlandscape: "1040px", + tabletportrait: "788px", + mobilelandscape: "815px", + mobileportrait: "375px", + placebo: "0px" + }; + document.querySelectorAll(".responsive a").forEach((element) => element.addEventListener("click", (event) => { + const target = event.currentTarget; + const width = Array.from(target.classList).reduce((acc, cur) => { + if (screenSizes[ cur ]) { + acc = screenSizes[ cur ]; + } + return acc; + }, ""); + iframe.style.width = width; + iframe.style.transition = "200ms"; + document.querySelectorAll(".responsive a").forEach((element2) => element2.classList.remove("active")); + target.classList.add("active"); + })); + if (navigator.userAgent.match(/iPad/i) !== null) { + iframe.style.height = "100%"; + } + }); })() \ No newline at end of file diff --git a/assets/js/template-switching.js b/assets/js/template-switching.js index 51d867e12..8b25a76e4 100644 --- a/assets/js/template-switching.js +++ b/assets/js/template-switching.js @@ -286,8 +286,8 @@ } // end if; - this.template_id = this.original_template_id; - this.confirm_active = true; + this.template_id = this.original_template_id; + this.confirm_active = true; /* * Scroll the confirm panel into view. The current- @@ -321,8 +321,8 @@ cancel_switch() { this.confirm_active = false; - this.template_id = this.original_template_id; - this.error_message = ''; + this.template_id = this.original_template_id; + this.error_message = ''; }, @@ -341,15 +341,15 @@ * directly inside the panel where the click happened. * * @param {string|null} message Human-readable failure - * reason. Pass null to delegate copy to wu_ajax_error - * (used for network errors where we do not have a - * server-supplied string). + * reason. Pass null to delegate copy to wu_ajax_error + * (used for network errors where we do not have a + * server-supplied string). */ show_error(message) { this.unblock(); this.confirm_switch = false; - this.ready = false; + this.ready = false; /* * Keep confirm_active true so the panel — which now @@ -357,7 +357,7 @@ */ this.confirm_active = true; - this.error_message = message || 'An error occurred while switching templates.'; + this.error_message = message || 'An error occurred while switching templates.'; /* * Belt-and-braces: also show the global notice in case diff --git a/assets/js/thank-you.js b/assets/js/thank-you.js index dd693d623..6d1550ce6 100644 --- a/assets/js/thank-you.js +++ b/assets/js/thank-you.js @@ -1,125 +1,125 @@ (() => { -"use strict"; -const TransitionText = (element, has_icon = false) => { - return { - classes: [], - has_icon: false, - original_value: element.innerHTML, - get_icon() { - return this.has_icon ? '' : ""; - }, - clear_classes() { - element.classList.remove(...this.classes); - }, - add_classes(classes) { - this.classes = classes; - element.classList.add(...classes); - }, - text(text, classes, toggle_icon = false) { - this.clear_classes(); - if (toggle_icon) { - this.has_icon = !this.has_icon; - } - element.animate([ - { - opacity: "1" - }, - { - opacity: "0.75" - } - ], { - duration: 300, - iterations: 1 - }); - setTimeout(() => { - this.add_classes(classes ?? []); - element.innerHTML = this.get_icon() + text; - element.style.opacity = "0.75"; - }, 300); - return this; - }, - done(timeout = 5e3) { - setTimeout(() => { - element.animate([ - { - opacity: "0.75" - }, - { - opacity: "1" - } - ], { - duration: 300, - iterations: 1 - }); - setTimeout(() => { - this.clear_classes(); - element.innerHTML = this.original_value; - element.style.opacity = "1"; - }, 300); - }, timeout); - return this; - } - }; -}; -document.addEventListener("DOMContentLoaded", () => { - document.querySelectorAll(".wu-resend-verification-email").forEach((element) => element.addEventListener("click", async (event) => { - event.preventDefault(); - const transitional_text = TransitionText(element, true).text(wu_thank_you.i18n.resending_verification_email, ["wu-text-gray-400"]); - const request = await fetch( - wu_thank_you.ajaxurl, - { - method: "POST", - headers: { - "Content-Type": "application/x-www-form-urlencoded", - }, - body: new URLSearchParams({ - action: "wu_resend_verification_email", - _ajax_nonce: wu_thank_you.resend_verification_email_nonce - }), - } - ); - const response = await request.json(); - if (response.success) { - transitional_text.text(wu_thank_you.i18n.email_sent, ["wu-text-green-700"], true).done(); - } else { - transitional_text.text(response.data[0].message, ["wu-text-red-600"], true).done(); - } - })); - if (!document.getElementById("wu-sites")) { - return; - } - const { Vue, defineComponent } = window.wu_vue; - window.wu_sites = new Vue(defineComponent({ - el: "#wu-sites", - data() { - return { - creating: wu_thank_you.creating, - next_queue: parseInt(wu_thank_you.next_queue, 10) + 5, - random: 0, - progress_in_seconds: 0, - stopped_count: 0, - running_count: 0, - site_ready: false, - // True when the URL already carries a _t= cache-bust param added by a - // prior completion redirect. Used to prevent any second full-page - // navigation and break the infinite-reload loop that occurred when the - // "stopped" branch fired window.location.reload() on every page load - // after site creation had already finished. - is_post_redirect: new URLSearchParams(window.location.search).has("_t"), - // One-time guard for the Case 1 "stopped" reload. Multiple - // check_site_created() callbacks can be queued before the first reload - // fires (async polling overlap), so we set this flag before calling - // window.location.reload() and bail out of subsequent calls. - _reload_done: false - }; - }, - computed: { - progress() { - return Math.round(this.progress_in_seconds / this.next_queue * 100); - } - }, - mounted() { - /* + "use strict"; + const TransitionText = (element, has_icon = false) => { + return { + classes: [], + has_icon: false, + original_value: element.innerHTML, + get_icon() { + return this.has_icon ? '' : ""; + }, + clear_classes() { + element.classList.remove(...this.classes); + }, + add_classes(classes) { + this.classes = classes; + element.classList.add(...classes); + }, + text(text, classes, toggle_icon = false) { + this.clear_classes(); + if (toggle_icon) { + this.has_icon = ! this.has_icon; + } + element.animate([ + { + opacity: "1" + }, + { + opacity: "0.75" + } + ], { + duration: 300, + iterations: 1 + }); + setTimeout(() => { + this.add_classes(classes ?? []); + element.innerHTML = this.get_icon() + text; + element.style.opacity = "0.75"; + }, 300); + return this; + }, + done(timeout = 5e3) { + setTimeout(() => { + element.animate([ + { + opacity: "0.75" + }, + { + opacity: "1" + } + ], { + duration: 300, + iterations: 1 + }); + setTimeout(() => { + this.clear_classes(); + element.innerHTML = this.original_value; + element.style.opacity = "1"; + }, 300); + }, timeout); + return this; + } + }; + }; + document.addEventListener("DOMContentLoaded", () => { + document.querySelectorAll(".wu-resend-verification-email").forEach((element) => element.addEventListener("click", async (event) => { + event.preventDefault(); + const transitional_text = TransitionText(element, true).text(wu_thank_you.i18n.resending_verification_email, [ "wu-text-gray-400" ]); + const request = await fetch( + wu_thank_you.ajaxurl, + { + method: "POST", + headers: { + "Content-Type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ + action: "wu_resend_verification_email", + _ajax_nonce: wu_thank_you.resend_verification_email_nonce + }), + } + ); + const response = await request.json(); + if (response.success) { + transitional_text.text(wu_thank_you.i18n.email_sent, [ "wu-text-green-700" ], true).done(); + } else { + transitional_text.text(response.data[ 0 ].message, [ "wu-text-red-600" ], true).done(); + } + })); + if (! document.getElementById("wu-sites")) { + return; + } + const { Vue, defineComponent } = window.wu_vue; + window.wu_sites = new Vue(defineComponent({ + el: "#wu-sites", + data() { + return { + creating: wu_thank_you.creating, + next_queue: parseInt(wu_thank_you.next_queue, 10) + 5, + random: 0, + progress_in_seconds: 0, + stopped_count: 0, + running_count: 0, + site_ready: false, + // True when the URL already carries a _t= cache-bust param added by a + // prior completion redirect. Used to prevent any second full-page + // navigation and break the infinite-reload loop that occurred when the + // "stopped" branch fired window.location.reload() on every page load + // after site creation had already finished. + is_post_redirect: new URLSearchParams(window.location.search).has("_t"), + // One-time guard for the Case 1 "stopped" reload. Multiple + // check_site_created() callbacks can be queued before the first reload + // fires (async polling overlap), so we set this flag before calling + // window.location.reload() and bail out of subsequent calls. + _reload_done: false + }; + }, + computed: { + progress() { + return Math.round(this.progress_in_seconds / this.next_queue * 100); + } + }, + mounted() { + /* * Kick wp-cron immediately to start the async site creation ASAP. * * Always start polling regardless of has_pending_site. The page may @@ -129,106 +129,106 @@ document.addEventListener("DOMContentLoaded", () => { * * @since 2.4.13 */ - fetch("/wp-cron.php?doing_wp_cron"); - this.check_site_created(); - }, - methods: { - async check_site_created() { - const url = new URL(wu_thank_you.ajaxurl); - url.searchParams.set("action", "wu_check_pending_site_created"); - url.searchParams.set("membership_hash", wu_thank_you.membership_hash); - let response; - try { - response = await fetch(url).then((request) => request.json()); - } catch (e) { - // Network error or non-JSON response -- retry in 3s without stopping. - this.stopped_count++; - setTimeout(this.check_site_created, 3000); - return; - } - if (response.publish_status === "completed") { - this.creating = false; - this.site_ready = true; - // Cache-bust redirect only when we actually watched the site transition - // through "running" during THIS page load, AND we have not already done - // a redirect (is_post_redirect). Both guards are required: - // • running_count === 0 → gateway completed before page loaded; the PHP - // template already has the correct state, no reload needed. - // • is_post_redirect === true → we already navigated once; a second - // redirect would start an infinite loop (completed page → redirect → - // completed again → redirect …). - if (this.running_count > 0 && !this.is_post_redirect) { - setTimeout(() => { - var sep = window.location.href.indexOf("?") > -1 ? "&" : "?"; - window.location.href = window.location.href.split("#")[0] + sep + "_t=" + Date.now(); - }, 1500); - } - } else if (response.publish_status === "running") { - this.creating = true; - this.stopped_count = 0; - this.running_count++; - // Kick cron every 3 polls to keep Action Scheduler active during site creation. - if (this.running_count % 3 === 0) { - fetch("/wp-cron.php?doing_wp_cron"); - } - if (this.running_count > 60) { - fetch("/wp-cron.php?doing_wp_cron"); - if (!this.is_post_redirect) { - // Use the _t cache-bust redirect (not location.reload) so the next - // page load sets is_post_redirect = true, preventing a second redirect - // if creation is still running on that page. - setTimeout(() => { - var sep = window.location.href.indexOf("?") > -1 ? "&" : "?"; - window.location.href = window.location.href.split("#")[0] + sep + "_t=" + Date.now(); - }, 3e3); - } else { - // Already did one redirect this cycle; slow-poll instead of looping. - setTimeout(this.check_site_created, 5000); - } - } else { - // Adaptive polling: 1.5s for first 30s, then 3s - var wait = this.running_count < 20 ? 1500 : 3000; - setTimeout(this.check_site_created, wait); - } - } else { - // status === "stopped": async job not started yet OR site already created. - // - // NEVER call window.location.reload() unconditionally here — doing so - // causes an infinite refresh loop: a finished site always returns "stopped" - // (the job is no longer running), so every page load would cycle through - // 3 stopped polls → reload → 3 stopped polls → reload endlessly. - // - // Intent-aware strategy: - // 1. running_count > 0 → we watched creation run this session but it - // stopped unexpectedly; do one location.reload() for fresh server state. - // The reloaded page will have running_count = 0, so this branch can - // only fire once before falling through to case 2 or 3. - // 2. wu_thank_you.creating === false (PHP already reports site done) → - // mark ready and stop polling; no navigation needed. - // 3. wu_thank_you.creating === true but never saw "running" (webhook - // delay, job not started yet) → keep slow-polling; do NOT reload. - this.creating = false; - this.stopped_count++; - if (this.stopped_count >= 3) { - if (this.running_count > 0 && !this._reload_done) { - // Case 1: was running this session, now stopped — one-time reload. - // _reload_done guards against multiple queued callbacks all firing - // reload before the first navigation clears the page. - this._reload_done = true; - window.location.reload(); - } else if (!wu_thank_you.creating) { - // Case 2: PHP already reported creation complete — mark ready. - this.site_ready = true; - } else { - // Case 3: still waiting for job to start — keep slow-polling. - setTimeout(this.check_site_created, 3e3); - } - } else { - setTimeout(this.check_site_created, 3e3); - } - } - } - } - })); -}); + fetch("/wp-cron.php?doing_wp_cron"); + this.check_site_created(); + }, + methods: { + async check_site_created() { + const url = new URL(wu_thank_you.ajaxurl); + url.searchParams.set("action", "wu_check_pending_site_created"); + url.searchParams.set("membership_hash", wu_thank_you.membership_hash); + let response; + try { + response = await fetch(url).then((request) => request.json()); + } catch (e) { + // Network error or non-JSON response -- retry in 3s without stopping. + this.stopped_count++; + setTimeout(this.check_site_created, 3000); + return; + } + if (response.publish_status === "completed") { + this.creating = false; + this.site_ready = true; + // Cache-bust redirect only when we actually watched the site transition + // through "running" during THIS page load, AND we have not already done + // a redirect (is_post_redirect). Both guards are required: + // • running_count === 0 → gateway completed before page loaded; the PHP + // template already has the correct state, no reload needed. + // • is_post_redirect === true → we already navigated once; a second + // redirect would start an infinite loop (completed page → redirect → + // completed again → redirect …). + if (this.running_count > 0 && ! this.is_post_redirect) { + setTimeout(() => { + const sep = window.location.href.indexOf("?") > -1 ? "&" : "?"; + window.location.href = window.location.href.split("#")[ 0 ] + sep + "_t=" + Date.now(); + }, 1500); + } + } else if (response.publish_status === "running") { + this.creating = true; + this.stopped_count = 0; + this.running_count++; + // Kick cron every 3 polls to keep Action Scheduler active during site creation. + if (this.running_count % 3 === 0) { + fetch("/wp-cron.php?doing_wp_cron"); + } + if (this.running_count > 60) { + fetch("/wp-cron.php?doing_wp_cron"); + if (! this.is_post_redirect) { + // Use the _t cache-bust redirect (not location.reload) so the next + // page load sets is_post_redirect = true, preventing a second redirect + // if creation is still running on that page. + setTimeout(() => { + const sep = window.location.href.indexOf("?") > -1 ? "&" : "?"; + window.location.href = window.location.href.split("#")[ 0 ] + sep + "_t=" + Date.now(); + }, 3e3); + } else { + // Already did one redirect this cycle; slow-poll instead of looping. + setTimeout(this.check_site_created, 5000); + } + } else { + // Adaptive polling: 1.5s for first 30s, then 3s + const wait = this.running_count < 20 ? 1500 : 3000; + setTimeout(this.check_site_created, wait); + } + } else { + // status === "stopped": async job not started yet OR site already created. + // + // NEVER call window.location.reload() unconditionally here — doing so + // causes an infinite refresh loop: a finished site always returns "stopped" + // (the job is no longer running), so every page load would cycle through + // 3 stopped polls → reload → 3 stopped polls → reload endlessly. + // + // Intent-aware strategy: + // 1. running_count > 0 → we watched creation run this session but it + // stopped unexpectedly; do one location.reload() for fresh server state. + // The reloaded page will have running_count = 0, so this branch can + // only fire once before falling through to case 2 or 3. + // 2. wu_thank_you.creating === false (PHP already reports site done) → + // mark ready and stop polling; no navigation needed. + // 3. wu_thank_you.creating === true but never saw "running" (webhook + // delay, job not started yet) → keep slow-polling; do NOT reload. + this.creating = false; + this.stopped_count++; + if (this.stopped_count >= 3) { + if (this.running_count > 0 && ! this._reload_done) { + // Case 1: was running this session, now stopped — one-time reload. + // _reload_done guards against multiple queued callbacks all firing + // reload before the first navigation clears the page. + this._reload_done = true; + window.location.reload(); + } else if (! wu_thank_you.creating) { + // Case 2: PHP already reported creation complete — mark ready. + this.site_ready = true; + } else { + // Case 3: still waiting for job to start — keep slow-polling. + setTimeout(this.check_site_created, 3e3); + } + } else { + setTimeout(this.check_site_created, 3e3); + } + } + } + } + })); + }); })() \ No newline at end of file diff --git a/assets/js/toolbox.js b/assets/js/toolbox.js index db486a8dd..c87e44418 100644 --- a/assets/js/toolbox.js +++ b/assets/js/toolbox.js @@ -5,5 +5,5 @@ if (typeof jQuery !== 'undefined') { $(this).parents('#wu-toolbox').toggleClass('wu-toolbox-closed'); }); }); - })(jQuery); + }(jQuery)); } \ No newline at end of file diff --git a/assets/js/tours.js b/assets/js/tours.js index 6d589f165..27674ac3a 100644 --- a/assets/js/tours.js +++ b/assets/js/tours.js @@ -41,28 +41,28 @@ import Shepherd from 'shepherd.js'; }, }); - const markTourFinished = function() { + const markTourFinished = function() { - const data = new URLSearchParams({ - action: 'wu_mark_tour_as_finished', - tour_id, - nonce: wu_tours_vars.nonce, - }); + const data = new URLSearchParams({ + action: 'wu_mark_tour_as_finished', + tour_id, + nonce: wu_tours_vars.nonce, + }); - /* + /* * sendBeacon() queues the request at the OS/browser level and * survives page navigation — so the setting is saved even if the * user refreshes immediately after closing the tour (which would * cancel an in-flight $.ajax() request). Falls back to $.ajax() * for browsers without sendBeacon support. */ - if (navigator.sendBeacon) { - navigator.sendBeacon(ajaxurl, data); - } else { - $.ajax({ url: ajaxurl, data: Object.fromEntries(data) }); - } + if (navigator.sendBeacon) { + navigator.sendBeacon(ajaxurl, data); + } else { + $.ajax({ url: ajaxurl, data: Object.fromEntries(data) }); + } - }; + }; window[ tour_id ].on('complete', markTourFinished); window[ tour_id ].on('cancel', markTourFinished); diff --git a/assets/js/url-preview.js b/assets/js/url-preview.js index a730a7b96..3fa171011 100644 --- a/assets/js/url-preview.js +++ b/assets/js/url-preview.js @@ -1,46 +1,46 @@ (function($) { - $(document).ready(function() { + $(document).ready(function() { - /** - * Signup change value - */ - $('.login').on('keyup', '#field-site_url', function(event) { + /** + * Signup change value + */ + $('.login').on('keyup', '#field-site_url', function(event) { - event.preventDefault(); + event.preventDefault(); - const $selector = $(this); + const $selector = $(this); - const $target = $('#wu-your-site'); + const $target = $('#wu-your-site'); - $target.text($selector.val()); + $target.text($selector.val()); - }); // end on.keyUp; + }); // end on.keyUp; - $('.login').on('keyup', '#field-site_url', function(event) { + $('.login').on('keyup', '#field-site_url', function(event) { - event.preventDefault(); + event.preventDefault(); - const $selector = $(this); + const $selector = $(this); - const $target = $('#wu-your-site'); + const $target = $('#wu-your-site'); - $target.text($selector.val()); + $target.text($selector.val()); - }); // end on.keyUp; + }); // end on.keyUp; - $('.login').on('change', '#domain_option', function(event) { + $('.login').on('change', '#domain_option', function(event) { - event.preventDefault(); + event.preventDefault(); - const $selector = $(this); + const $selector = $(this); - const $target = $('#wu-site-domain'); + const $target = $('#wu-site-domain'); - $target.text($selector.val()); + $target.text($selector.val()); - }); // end on.keyUp; + }); // end on.keyUp; - }); + }); }(jQuery)); diff --git a/assets/js/view-logs.js b/assets/js/view-logs.js index aca795d5f..04ef57590 100644 --- a/assets/js/view-logs.js +++ b/assets/js/view-logs.js @@ -1,111 +1,111 @@ /* global ajaxurl, wu_block_ui, ClipboardJS, wu_log_payload, wu_view_logs, Vue, wu_ajax_error */ (function($) { - $(document).ready(function() { + $(document).ready(function() { - wu_log_payload = new Vue({ - el: '#wu_payload', - data() { + wu_log_payload = new Vue({ + el: '#wu_payload', + data() { - return { - payload: '', - log: $('select[name=log_file]').val(), - loading: true, - }; + return { + payload: '', + log: $('select[name=log_file]').val(), + loading: true, + }; - }, - watch: { - log() { + }, + watch: { + log() { - this.get_log_payload(); + this.get_log_payload(); - }, - }, - methods: { - get_log_payload() { + }, + }, + methods: { + get_log_payload() { - const block = wu_block_ui('#wu_payload_content'); + const block = wu_block_ui('#wu_payload_content'); - const app = this; + const app = this; - app.loading = true; + app.loading = true; - $.ajax({ - method: 'post', - // eslint-disable-next-line no-undef - url: ajaxurl, - data: { - action: 'wu_handle_view_logs', - file: app.log, - }, - success(response) { + $.ajax({ + method: 'post', + // eslint-disable-next-line no-undef + url: ajaxurl, + data: { + action: 'wu_handle_view_logs', + file: app.log, + }, + success(response) { - app.payload = response.data.contents; + app.payload = response.data.contents; - app.loading = false; + app.loading = false; - block.unblock(); + block.unblock(); - try { + try { - history.pushState({}, null, '?' + 'page=wp-ultimo-view-logs&log_file=' + app.log); + history.pushState({}, null, '?' + 'page=wp-ultimo-view-logs&log_file=' + app.log); - } catch (err) { + } catch (err) { - // eslint-disable-next-line no-console - console.warn('Browser does not support pushState.', err); + // eslint-disable-next-line no-console + console.warn('Browser does not support pushState.', err); - } // end try; + } // end try; - }, - error(jqXHR) { + }, + error(jqXHR) { - app.loading = false; + app.loading = false; - block.unblock(); + block.unblock(); - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, + }, - }); + }); - }, + }, - }, - mounted() { + }, + mounted() { - this.get_log_payload(); + this.get_log_payload(); - }, + }, - }); + }); - $(document).on('change', 'select[name=log_file]', function() { + $(document).on('change', 'select[name=log_file]', function() { - wu_log_payload.log = $('select[name=log_file]').val(); + wu_log_payload.log = $('select[name=log_file]').val(); - }); + }); - // eslint-disable-next-line no-unused-vars - const clipboard = new ClipboardJS('.btn-clipboard'); + // eslint-disable-next-line no-unused-vars + const clipboard = new ClipboardJS('.btn-clipboard'); - clipboard.on('success', function(e) { + clipboard.on('success', function(e) { - const target = $(e.trigger); + const target = $(e.trigger); - const default_text = target.text(); + const default_text = target.text(); - target.attr('disabled', 'disabled').text(wu_view_logs.i18n.copied); + target.attr('disabled', 'disabled').text(wu_view_logs.i18n.copied); - setTimeout(function() { + setTimeout(function() { - target.text(default_text).removeAttr('disabled'); + target.text(default_text).removeAttr('disabled'); - }, 3000); + }, 3000); - }); + }); - }); + }); }(jQuery)); diff --git a/assets/js/visits-counter.js b/assets/js/visits-counter.js index 738a0ac6a..71c552e15 100644 --- a/assets/js/visits-counter.js +++ b/assets/js/visits-counter.js @@ -1,47 +1,47 @@ (() => { -"use strict"; -const CreateCookie = (name, value, days) => { - let expires; - if (days) { - const date = /* @__PURE__ */ new Date(); - date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3); - expires = "; expires=" + date.toUTCString(); - } else { - expires = ""; - } - document.cookie = name + "=" + value + expires + "; path=/"; -}; -const ReadCookie = (name) => { - const nameEQ = name + "="; - const ca = document.cookie.split(";"); - for (let i = 0; i < ca.length; i++) { - let c = ca[i]; - while (c.charAt(0) === " ") { - c = c.substring(1, c.length); - } - if (c.indexOf(nameEQ) === 0) { - return c.substring(nameEQ.length, c.length); - } - } - return null; -}; -const countVisit = () => { - const counted = ReadCookie("WUVISIT"); - if (counted === "1") { - return; - } - const countVisit2 = async () => { - const url = new URL(wu_visits_counter.ajaxurl); - url.searchParams.set("action", "wu_count_visits"); - url.searchParams.set("code", wu_visits_counter.code); - await fetch(url); - CreateCookie("WUVISIT", "1", 1); - }; - document.addEventListener("DOMContentLoaded", () => { - setTimeout(function() { - countVisit2(); - }, 1e4); - }); -}; -countVisit(); + "use strict"; + const CreateCookie = (name, value, days) => { + let expires; + if (days) { + const date = /* @__PURE__ */ new Date(); + date.setTime(date.getTime() + days * 24 * 60 * 60 * 1e3); + expires = "; expires=" + date.toUTCString(); + } else { + expires = ""; + } + document.cookie = name + "=" + value + expires + "; path=/"; + }; + const ReadCookie = (name) => { + const nameEQ = name + "="; + const ca = document.cookie.split(";"); + for (let i = 0; i < ca.length; i++) { + let c = ca[ i ]; + while (c.charAt(0) === " ") { + c = c.substring(1, c.length); + } + if (c.indexOf(nameEQ) === 0) { + return c.substring(nameEQ.length, c.length); + } + } + return null; + }; + const countVisit = () => { + const counted = ReadCookie("WUVISIT"); + if (counted === "1") { + return; + } + const countVisit2 = async () => { + const url = new URL(wu_visits_counter.ajaxurl); + url.searchParams.set("action", "wu_count_visits"); + url.searchParams.set("code", wu_visits_counter.code); + await fetch(url); + CreateCookie("WUVISIT", "1", 1); + }; + document.addEventListener("DOMContentLoaded", () => { + setTimeout(function() { + countVisit2(); + }, 1e4); + }); + }; + countVisit(); })() \ No newline at end of file diff --git a/assets/js/vue-apps.js b/assets/js/vue-apps.js index b4087013e..a26b55d99 100644 --- a/assets/js/vue-apps.js +++ b/assets/js/vue-apps.js @@ -1,239 +1,239 @@ (() => { -"use strict"; -const { Vue: Vue$1, defineComponent } = window.wu_vue || {}; -const hooks = wp.hooks || {}; -const loadApp = (element, app_id, callback = null) => { - if (window["wu_" + app_id]) { - const exclusion_list = [ - "add_checkout_form_field" - ]; - if (!exclusion_list.includes(app_id)) { - return; - } - } - window["wu_" + app_id] = new Vue$1(defineComponent({ - name: typeof app_id === "string" ? app_id : "", - el: element, - directives: { - init: { - bind(el, binding, vnode) { - vnode.context[binding.arg] = binding.value; - } - }, - initempty: { - bind(el, binding, vnode) { - if (vnode.context[binding.arg] === "") { - vnode.context[binding.arg] = binding.value; - } - } - } - }, - data() { - let prefix = wu_settings.currency_symbol; - let suffix = ""; - if (wu_settings.currency_position === "%v%s") { - prefix = ""; - suffix = wu_settings.currency_symbol; - } else if (wu_settings.currency_position === "%s %v") { - prefix = wu_settings.currency_symbol + " "; - } else if (wu_settings.currency_position === "%v %s") { - prefix = ""; - suffix = " " + wu_settings.currency_symbol; - } - const settings = { - money_settings: { - prefix, - suffix, - decimal: wu_settings.decimal_separator, - thousands: wu_settings.thousand_separator, - precision: parseInt(wu_settings.precision, 10), - masked: false - } - }; - return Object.assign({}, JSON.parse(element.dataset.state || "{}"), settings); - }, - computed: { - hooks: () => hooks, - console: () => console, - window: () => window, - shortcode() { - if (typeof this.id === "undefined" || typeof this.attributes === "undefined") { - return ""; - } - const shortcodeValues = this.id + " " + Object.entries(this.attributes).map(([key, value]) => { - if (value === this.defaults[key] || typeof value === "object") { - return ""; - } - if (this.attributes[key + "_shortcode_requires"]) { - const hide = Object.entries(this.attributes[key + "_shortcode_requires"]).some(([k, v]) => { - return this.attributes[k] !== v; - }); - if (hide) { - return ""; - } - } - return key + '="' + (typeof value === "string" ? value.trim() : value) + '"'; - }).filter((value) => value).join(" "); - return "[" + shortcodeValues.trim() + "]"; - } - }, - mounted() { - wu_on_load(); - hooks.doAction("wu_" + app_id + "_mounted", this.$data); - const cb = element.dataset.onLoad; - if (typeof window[cb] === "function") { - window[cb](); - } - if (callback) { - callback(); - } - this.$nextTick(function() { - window.wu_initialize_code_editors(); - window.wubox.refresh(); - }); - }, - updated() { - if (!this._priorState) { - this._priorState = this.$options.data(); - } - const self = this; - const changedProp = Object.keys(this._data).find((key) => JSON.stringify(this._data[key]) !== JSON.stringify(self._priorState[key])); - this._priorState = { ...this._data }; - this.$nextTick(function() { - hooks.doAction("wu_" + app_id + "_changed", changedProp, self.$data); - window.wu_initialize_code_editors(); - window.wubox.refresh(); - }); - }, - methods: { - send(scope, function_name, value, cb) { - if (scope === "window") { - return window[function_name](value, cb); - } - return window[scope][function_name](value, cb); - }, - get_value(variable_name) { - return window[variable_name]; - }, - set_value(key, value) { - this[key] = value; - }, - get_state_value(value, default_value) { - return typeof this[value] === "undefined" ? default_value : this[value]; - }, - duplicate_and_clean($event, query) { - var _a; - const elements = document.querySelectorAll(query); - const target = elements.item(elements.length - 1); - const clone = target.cloneNode(true); - clone.id = clone.id + "_copy"; - const textAreas = clone.querySelectorAll("input, textarea"); - textAreas.forEach((el) => el.value = ""); - (_a = target.parentNode) == null ? void 0 : _a.insertBefore(clone, target.nextSibling); - }, - wu_format_money(value) { - return wu_format_money(value); - }, - require(data, value) { - if (Object.prototype.toString.call(this[data]) === "[object Array]") { - return this[data].indexOf(value) > -1; - } - if (Object.prototype.toString.call(value) === "[object Array]") { - return value.indexOf(this[data]) > -1; - } - return this[data] == value; - }, - open($event) { - $event.preventDefault(); - this.edit = true; - } - } - })); - window["wu_" + app_id].$watch("section", function(new_value) { - try { - const url = new URL(window.location.href); - url.searchParams.set(app_id, new_value); - history.pushState({}, "", url); - } catch (err) { - console.warn("Browser does not support pushState.", err); - } - }); -}; -const { Vue } = window.wu_vue || {}; -const loadApps = () => { - const appsElements = document.querySelectorAll("[data-wu-app]"); - appsElements.forEach((element) => { - if (!Vue) { - return; - } - const appId = element.dataset["wuApp"]; - if (appId) { - loadApp(element, appId); - } - }); -}; -document.addEventListener("DOMContentLoaded", () => { - Vue.component("colorPicker", { - props: ["value"], - template: '', - mounted() { - const vm = this; - jQuery(this.$el).val(this.value).wpColorPicker({ - width: 200, - defaultColor: this.value, - change(event, ui) { - vm.$emit("input", ui.color.toString()); - } - }); - }, - watch: { - value(value) { - jQuery(this.$el).wpColorPicker("color", value); - } - }, - destroyed() { - jQuery(this.$el).off().wpColorPicker("destroy"); - } - }); - Vue.component("wpEditor", { - props: ["value", "id", "name"], - template: '', - mounted() { - if (typeof wp.editor === "undefined") { - return; - } - const that = this; - wp.editor.remove(this.id); - wp.editor.initialize(this.id, { - tinymce: { - setup(editor) { - editor.on("init", function() { - wubox.refresh(); - }); - editor.on("keyup", () => { - if (editor.isDirty()) { - that.$emit("input", editor.getContent()); - } - }); - } - } - }); - }, - destroyed() { - if (typeof wp.editor === "undefined") { - return; - } - wp.editor.remove(this.id); - } - }); - document.body.addEventListener("wubox:unload", function() { - const modal = document.getElementById("WUB_window"); - const app = modal.querySelector("ul[data-wu-app]"); - const app_name = "wu_" + app.dataset["wuApp"]; - delete window[app_name]; - delete window[app_name + "_errors"]; - }); - document.body.addEventListener("wubox:load", loadApps); - loadApps(); -}); + "use strict"; + const { Vue: Vue$1, defineComponent } = window.wu_vue || {}; + const hooks = wp.hooks || {}; + const loadApp = (element, app_id, callback = null) => { + if (window[ "wu_" + app_id ]) { + const exclusion_list = [ + "add_checkout_form_field" + ]; + if (! exclusion_list.includes(app_id)) { + return; + } + } + window[ "wu_" + app_id ] = new Vue$1(defineComponent({ + name: typeof app_id === "string" ? app_id : "", + el: element, + directives: { + init: { + bind(el, binding, vnode) { + vnode.context[ binding.arg ] = binding.value; + } + }, + initempty: { + bind(el, binding, vnode) { + if (vnode.context[ binding.arg ] === "") { + vnode.context[ binding.arg ] = binding.value; + } + } + } + }, + data() { + let prefix = wu_settings.currency_symbol; + let suffix = ""; + if (wu_settings.currency_position === "%v%s") { + prefix = ""; + suffix = wu_settings.currency_symbol; + } else if (wu_settings.currency_position === "%s %v") { + prefix = wu_settings.currency_symbol + " "; + } else if (wu_settings.currency_position === "%v %s") { + prefix = ""; + suffix = " " + wu_settings.currency_symbol; + } + const settings = { + money_settings: { + prefix, + suffix, + decimal: wu_settings.decimal_separator, + thousands: wu_settings.thousand_separator, + precision: parseInt(wu_settings.precision, 10), + masked: false + } + }; + return Object.assign({}, JSON.parse(element.dataset.state || "{}"), settings); + }, + computed: { + hooks: () => hooks, + console: () => console, + window: () => window, + shortcode() { + if (typeof this.id === "undefined" || typeof this.attributes === "undefined") { + return ""; + } + const shortcodeValues = this.id + " " + Object.entries(this.attributes).map(([ key, value ]) => { + if (value === this.defaults[ key ] || typeof value === "object") { + return ""; + } + if (this.attributes[ key + "_shortcode_requires" ]) { + const hide = Object.entries(this.attributes[ key + "_shortcode_requires" ]).some(([ k, v ]) => { + return this.attributes[ k ] !== v; + }); + if (hide) { + return ""; + } + } + return key + '="' + (typeof value === "string" ? value.trim() : value) + '"'; + }).filter((value) => value).join(" "); + return "[" + shortcodeValues.trim() + "]"; + } + }, + mounted() { + wu_on_load(); + hooks.doAction("wu_" + app_id + "_mounted", this.$data); + const cb = element.dataset.onLoad; + if (typeof window[ cb ] === "function") { + window[ cb ](); + } + if (callback) { + callback(); + } + this.$nextTick(function() { + window.wu_initialize_code_editors(); + window.wubox.refresh(); + }); + }, + updated() { + if (! this._priorState) { + this._priorState = this.$options.data(); + } + const self = this; + const changedProp = Object.keys(this._data).find((key) => JSON.stringify(this._data[ key ]) !== JSON.stringify(self._priorState[ key ])); + this._priorState = { ...this._data }; + this.$nextTick(function() { + hooks.doAction("wu_" + app_id + "_changed", changedProp, self.$data); + window.wu_initialize_code_editors(); + window.wubox.refresh(); + }); + }, + methods: { + send(scope, function_name, value, cb) { + if (scope === "window") { + return window[ function_name ](value, cb); + } + return window[ scope ][ function_name ](value, cb); + }, + get_value(variable_name) { + return window[ variable_name ]; + }, + set_value(key, value) { + this[ key ] = value; + }, + get_state_value(value, default_value) { + return typeof this[ value ] === "undefined" ? default_value : this[ value ]; + }, + duplicate_and_clean($event, query) { + let _a; + const elements = document.querySelectorAll(query); + const target = elements.item(elements.length - 1); + const clone = target.cloneNode(true); + clone.id = clone.id + "_copy"; + const textAreas = clone.querySelectorAll("input, textarea"); + textAreas.forEach((el) => el.value = ""); + (_a = target.parentNode) == null ? void 0 : _a.insertBefore(clone, target.nextSibling); + }, + wu_format_money(value) { + return wu_format_money(value); + }, + require(data, value) { + if (Object.prototype.toString.call(this[ data ]) === "[object Array]") { + return this[ data ].indexOf(value) > -1; + } + if (Object.prototype.toString.call(value) === "[object Array]") { + return value.indexOf(this[ data ]) > -1; + } + return this[ data ] == value; + }, + open($event) { + $event.preventDefault(); + this.edit = true; + } + } + })); + window[ "wu_" + app_id ].$watch("section", function(new_value) { + try { + const url = new URL(window.location.href); + url.searchParams.set(app_id, new_value); + history.pushState({}, "", url); + } catch (err) { + console.warn("Browser does not support pushState.", err); + } + }); + }; + const { Vue } = window.wu_vue || {}; + const loadApps = () => { + const appsElements = document.querySelectorAll("[data-wu-app]"); + appsElements.forEach((element) => { + if (! Vue) { + return; + } + const appId = element.dataset.wuApp; + if (appId) { + loadApp(element, appId); + } + }); + }; + document.addEventListener("DOMContentLoaded", () => { + Vue.component("colorPicker", { + props: [ "value" ], + template: '', + mounted() { + const vm = this; + jQuery(this.$el).val(this.value).wpColorPicker({ + width: 200, + defaultColor: this.value, + change(event, ui) { + vm.$emit("input", ui.color.toString()); + } + }); + }, + watch: { + value(value) { + jQuery(this.$el).wpColorPicker("color", value); + } + }, + destroyed() { + jQuery(this.$el).off().wpColorPicker("destroy"); + } + }); + Vue.component("wpEditor", { + props: [ "value", "id", "name" ], + template: '', + mounted() { + if (typeof wp.editor === "undefined") { + return; + } + const that = this; + wp.editor.remove(this.id); + wp.editor.initialize(this.id, { + tinymce: { + setup(editor) { + editor.on("init", function() { + wubox.refresh(); + }); + editor.on("keyup", () => { + if (editor.isDirty()) { + that.$emit("input", editor.getContent()); + } + }); + } + } + }); + }, + destroyed() { + if (typeof wp.editor === "undefined") { + return; + } + wp.editor.remove(this.id); + } + }); + document.body.addEventListener("wubox:unload", function() { + const modal = document.getElementById("WUB_window"); + const app = modal.querySelector("ul[data-wu-app]"); + const app_name = "wu_" + app.dataset.wuApp; + delete window[ app_name ]; + delete window[ app_name + "_errors" ]; + }); + document.body.addEventListener("wubox:load", loadApps); + loadApps(); + }); })() \ No newline at end of file diff --git a/assets/js/webhook-page.js b/assets/js/webhook-page.js index 9acd3edec..ebeeff329 100644 --- a/assets/js/webhook-page.js +++ b/assets/js/webhook-page.js @@ -47,42 +47,42 @@ webhook_url, webhook_event, }, - success(data) { + success(data) { - if (data.response) { + if (data.response) { - $('[data-loading="wu_action_button_loading_' + data.id + '"]').addClass('hidden'); + $('[data-loading="wu_action_button_loading_' + data.id + '"]').addClass('hidden'); - Swal.fire({ - title: 'Test Response', - icon: 'success', - // eslint-disable-next-line max-len - html: '

' + JSON.stringify(data.response, null, 2) + '
', - showCloseButton: true, - showCancelButton: false, - }); + Swal.fire({ + title: 'Test Response', + icon: 'success', + // eslint-disable-next-line max-len + html: '
' + JSON.stringify(data.response, null, 2) + '
', + showCloseButton: true, + showCancelButton: false, + }); - } else { + } else { - $('[data-loading="wu_action_button_loading_' + data.id + '"]').addClass('hidden'); + $('[data-loading="wu_action_button_loading_' + data.id + '"]').addClass('hidden'); - Swal.fire({ - title: wu_webhook_page.i18n.error_title, - icon: 'error', - html: wu_webhook_page.i18n.error_message, - showCloseButton: true, - showCancelButton: false, - }); + Swal.fire({ + title: wu_webhook_page.i18n.error_title, + icon: 'error', + html: wu_webhook_page.i18n.error_message, + showCloseButton: true, + showCancelButton: false, + }); - } // end if; + } // end if; - }, - error(jqXHR) { + }, + error(jqXHR) { - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, - }); + }, + }); }); @@ -123,22 +123,22 @@ action: 'wu_get_event_payload_preview', event: app.event, }, - success(response) { + success(response) { - app.payload = response.data ?? {}; + app.payload = response.data ?? {}; - app.loading = false; + app.loading = false; - }, - error(jqXHR) { + }, + error(jqXHR) { - app.loading = false; + app.loading = false; - wu_ajax_error(jqXHR); + wu_ajax_error(jqXHR); - }, + }, - }); + }); }, diff --git a/assets/js/wu-password-reset.js b/assets/js/wu-password-reset.js index 80838bfff..1bc07540e 100644 --- a/assets/js/wu-password-reset.js +++ b/assets/js/wu-password-reset.js @@ -5,23 +5,24 @@ * Uses the shared WU_PasswordStrength utility to check password strength * and enforces minimum strength requirements. * + * @param $ * @since 2.3.0 */ (function($) { 'use strict'; - var passwordStrength; + let passwordStrength; /** * Initialize the password strength meter. */ $(document).ready(function() { - var $pass1 = $('#field-pass1'); - var $pass2 = $('#field-pass2'); - var $submit = $('#wp-submit'); - var $form = $pass1.closest('form'); + const $pass1 = $('#field-pass1'); + const $pass2 = $('#field-pass2'); + const $submit = $('#wp-submit'); + const $form = $pass1.closest('form'); - if (!$pass1.length || typeof WU_PasswordStrength === 'undefined') { + if (! $pass1.length || typeof WU_PasswordStrength === 'undefined') { return; } @@ -35,7 +36,7 @@ // Prevent form submission if password is too weak $form.on('submit', function(e) { - if (!passwordStrength.isValid()) { + if (! passwordStrength.isValid()) { e.preventDefault(); return false; } diff --git a/assets/js/wu-password-toggle.js b/assets/js/wu-password-toggle.js index b8b2ae94d..ab2b70991 100644 --- a/assets/js/wu-password-toggle.js +++ b/assets/js/wu-password-toggle.js @@ -11,7 +11,7 @@ (function() { 'use strict'; - var __ = wp.i18n.__; + const __ = wp.i18n.__; /** * Toggle password visibility. @@ -19,19 +19,19 @@ * @param {Event} event Click event. */ function togglePassword(event) { - var toggle = event.target.closest('.wu-pwd-toggle'); + const toggle = event.target.closest('.wu-pwd-toggle'); - if (!toggle) { + if (! toggle) { return; } event.preventDefault(); - var status = toggle.getAttribute('data-toggle'); - var input = toggle.parentElement.querySelector('input[type="password"], input[type="text"]'); - var icon = toggle.querySelector('.dashicons'); + const status = toggle.getAttribute('data-toggle'); + const input = toggle.parentElement.querySelector('input[type="password"], input[type="text"]'); + const icon = toggle.querySelector('.dashicons'); - if (!input || !icon) { + if (! input || ! icon) { return; } @@ -54,4 +54,4 @@ // Use event delegation to handle dynamically added elements (Vue, etc.) document.addEventListener('click', togglePassword); -})(); +}()); diff --git a/assets/js/wubox.js b/assets/js/wubox.js index 9ec3da219..7fec218a6 100644 --- a/assets/js/wubox.js +++ b/assets/js/wubox.js @@ -1,126 +1,133 @@ (() => { -"use strict"; -const createImageBox = (boxWindow, loaded, url, caption, imageGroup) => { - let prevCaption = "", prevURL = "", prevHTML = "", nextCaption = "", nextURL = "", nextHTML = "", imageCount = "", foundURL = false; - if (imageGroup) { - const tempArray = document.querySelectorAll(`a[rel="${imageGroup}"]`); - for (let index = 0; index < tempArray.length && nextHTML === ""; index++) { - if (tempArray[index].href !== url) { - if (foundURL) { - nextCaption = tempArray[index].title; - nextURL = tempArray[index].href; - nextHTML = "  
" + wuboxL10n.next + ""; - } else { - prevCaption = tempArray[index].title; - prevURL = tempArray[index].href; - prevHTML = "  " + wuboxL10n.prev + ""; - } - } else { - foundURL = true; - imageCount = wuboxL10n.image + " " + (index + 1) + " " + wuboxL10n.of + " " + tempArray.length; - } - } - } - const imgPreloader = new Image(); - imgPreloader.onload = () => { - var _a, _b, _c, _d; - imgPreloader.onload = null; - const pagesize = getPageSize(); - const x = pagesize.width - 150; - const y = pagesize.height - 150; - let imageWidth = imgPreloader.width; - let imageHeight = imgPreloader.height; - if (imageWidth > x) { - imageHeight = imageHeight * (x / imageWidth); - imageWidth = x; - if (imageHeight > y) { - imageWidth = imageWidth * (y / imageHeight); - imageHeight = y; - } - } else if (imageHeight > y) { - imageWidth = imageWidth * (y / imageHeight); - imageHeight = y; - if (imageWidth > x) { - imageHeight = imageHeight * (x / imageWidth); - imageWidth = x; - } - } - setBoxPosition(boxWindow, imageWidth, imageHeight); - boxWindow.insertAdjacentHTML("beforeend", ` + "use strict"; + const createImageBox = (boxWindow, loaded, url, caption, imageGroup) => { + let prevCaption = "", + prevURL = "", + prevHTML = "", + nextCaption = "", + nextURL = "", + nextHTML = "", + imageCount = "", + foundURL = false; + if (imageGroup) { + const tempArray = document.querySelectorAll(`a[rel="${ imageGroup }"]`); + for (let index = 0; index < tempArray.length && nextHTML === ""; index++) { + if (tempArray[ index ].href !== url) { + if (foundURL) { + nextCaption = tempArray[ index ].title; + nextURL = tempArray[ index ].href; + nextHTML = "  " + wuboxL10n.next + ""; + } else { + prevCaption = tempArray[ index ].title; + prevURL = tempArray[ index ].href; + prevHTML = "  " + wuboxL10n.prev + ""; + } + } else { + foundURL = true; + imageCount = wuboxL10n.image + " " + (index + 1) + " " + wuboxL10n.of + " " + tempArray.length; + } + } + } + const imgPreloader = new Image(); + imgPreloader.onload = () => { + let _a, _b, _c, _d; + imgPreloader.onload = null; + const pagesize = getPageSize(); + const x = pagesize.width - 150; + const y = pagesize.height - 150; + let imageWidth = imgPreloader.width; + let imageHeight = imgPreloader.height; + if (imageWidth > x) { + imageHeight = imageHeight * (x / imageWidth); + imageWidth = x; + if (imageHeight > y) { + imageWidth = imageWidth * (y / imageHeight); + imageHeight = y; + } + } else if (imageHeight > y) { + imageWidth = imageWidth * (y / imageHeight); + imageHeight = y; + if (imageWidth > x) { + imageHeight = imageHeight * (x / imageWidth); + imageWidth = x; + } + } + setBoxPosition(boxWindow, imageWidth, imageHeight); + boxWindow.insertAdjacentHTML("beforeend", ` - ${wuboxL10n.close} - ${caption} + ${ wuboxL10n.close } + ${ caption }
- ${caption} + ${ caption }
- ${imageCount + prevHTML + nextHTML} + ${ imageCount + prevHTML + nextHTML }
`); - (_a = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _a.addEventListener("click", removeBox); - const goPrev = () => { - boxWindow.innerHTML = ""; - unloadKeydownEvent(); - showBox(prevCaption, prevURL, imageGroup); - }; - const goNext = () => { - boxWindow.innerHTML = ""; - unloadKeydownEvent(); - showBox(nextCaption, nextURL, imageGroup); - }; - (_b = document.getElementById("WUB_prev")) == null ? void 0 : _b.addEventListener("click", goPrev); - (_c = document.getElementById("WUB_next")) == null ? void 0 : _c.addEventListener("click", goNext); - const keydownEvent = (e) => { - if (e.key === "Escape") { - removeBox(); - } else if (e.key === "ArrowRight" && nextHTML) { - goNext(); - } else if (e.key === "ArrowLeft" && prevHTML) { - goPrev(); - } - }; - const unloadKeydownEvent = () => { - window.removeEventListener("keydown", keydownEvent); - document.body.removeEventListener("wubox:unload", unloadKeydownEvent); - }; - window.addEventListener("keydown", keydownEvent); - document.body.addEventListener("wubox:unload", unloadKeydownEvent); - (_d = document.getElementById("WUB_ImageOff")) == null ? void 0 : _d.addEventListener("click", removeBox); - loaded(); - }; - imgPreloader.src = url; -}; -const createIframeBox = (boxWindow, boxOverlay, loaded, url, caption, params) => { - var _a, _b, _c; - const urlNoQuery = url.split("WUB_"); - (_a = document.getElementById("WUB_load")) == null ? void 0 : _a.remove(); - if (params.modal) { - boxOverlay.removeEventListener("click", removeBox); - boxWindow.insertAdjacentHTML("beforeend", ` + (_a = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _a.addEventListener("click", removeBox); + const goPrev = () => { + boxWindow.innerHTML = ""; + unloadKeydownEvent(); + showBox(prevCaption, prevURL, imageGroup); + }; + const goNext = () => { + boxWindow.innerHTML = ""; + unloadKeydownEvent(); + showBox(nextCaption, nextURL, imageGroup); + }; + (_b = document.getElementById("WUB_prev")) == null ? void 0 : _b.addEventListener("click", goPrev); + (_c = document.getElementById("WUB_next")) == null ? void 0 : _c.addEventListener("click", goNext); + const keydownEvent = (e) => { + if (e.key === "Escape") { + removeBox(); + } else if (e.key === "ArrowRight" && nextHTML) { + goNext(); + } else if (e.key === "ArrowLeft" && prevHTML) { + goPrev(); + } + }; + const unloadKeydownEvent = () => { + window.removeEventListener("keydown", keydownEvent); + document.body.removeEventListener("wubox:unload", unloadKeydownEvent); + }; + window.addEventListener("keydown", keydownEvent); + document.body.addEventListener("wubox:unload", unloadKeydownEvent); + (_d = document.getElementById("WUB_ImageOff")) == null ? void 0 : _d.addEventListener("click", removeBox); + loaded(); + }; + imgPreloader.src = url; + }; + const createIframeBox = (boxWindow, boxOverlay, loaded, url, caption, params) => { + let _a, _b, _c; + const urlNoQuery = url.split("WUB_"); + (_a = document.getElementById("WUB_load")) == null ? void 0 : _a.remove(); + if (params.modal) { + boxOverlay.removeEventListener("click", removeBox); + boxWindow.insertAdjacentHTML("beforeend", ` `); - (_b = document.getElementById("WUB_iframeContent")) == null ? void 0 : _b.addEventListener("load", showBoxIframe); - } else { - boxWindow.insertAdjacentHTML("beforeend", ` + (_b = document.getElementById("WUB_iframeContent")) == null ? void 0 : _b.addEventListener("load", showBoxIframe); + } else { + boxWindow.insertAdjacentHTML("beforeend", `
-
${caption}
+
${ caption }
@@ -129,375 +136,379 @@ const createIframeBox = (boxWindow, boxOverlay, loaded, url, caption, params) => frameborder='0' hspace='0' allowtransparency='true' - src='${urlNoQuery[0]}' - name='WUB_iframeContent${Math.round(Math.random() * 1e3)}' - style='width:${params.width + 29}px; height:${params.height + 17}px;' + src='${ urlNoQuery[ 0 ] }' + name='WUB_iframeContent${ Math.round(Math.random() * 1e3) }' + style='width:${ params.width + 29 }px; height:${ params.height + 17 }px;' > - ${wuboxL10n.noiframes} + ${ wuboxL10n.noiframes } `); - (_c = document.getElementById("WUB_iframeContent")) == null ? void 0 : _c.addEventListener("load", showBoxIframe); - } - setBoxPosition(boxWindow, params.width, params.height); - loaded(); -}; -const baseAjaxElement = (boxWindow, boxOverlay, caption, params) => { - if (boxWindow.style.visibility !== "visible") { - if (params.modal) { - boxOverlay.removeEventListener("click", removeBox); - boxWindow.insertAdjacentHTML("beforeend", `
`); - } else { - boxWindow.insertAdjacentHTML("beforeend", ` + (_c = document.getElementById("WUB_iframeContent")) == null ? void 0 : _c.addEventListener("load", showBoxIframe); + } + setBoxPosition(boxWindow, params.width, params.height); + loaded(); + }; + const baseAjaxElement = (boxWindow, boxOverlay, caption, params) => { + if (boxWindow.style.visibility !== "visible") { + if (params.modal) { + boxOverlay.removeEventListener("click", removeBox); + boxWindow.insertAdjacentHTML("beforeend", `
`); + } else { + boxWindow.insertAdjacentHTML("beforeend", `
-
${caption}
+
${ caption }
-
`); - } - } else { - const ajaxContent = document.getElementById("WUB_ajaxContent"); - ajaxContent.style.width = params.width + "px"; - ajaxContent.style.height = params.height + "px"; - ajaxContent.scrollTop = 0; - ajaxContent.innerHTML = caption; - } - return document.getElementById("WUB_ajaxContent"); -}; -const createAjaxBox = (boxWindow, boxOverlay, loaded, url, caption, params) => { - const ajaxContent = baseAjaxElement(boxWindow, boxOverlay, caption, params); - const load_url = url + (url.includes("?") ? "&" : "?") + "random=" + (/* @__PURE__ */ new Date()).getTime(); - fetch(load_url, { - headers: { - "X-Requested-With": "XMLHttpRequest" - } - }).then((response) => response.text()).then((html) => { - ajaxContent.innerHTML = html; - setBoxPosition(boxWindow, params.width, params.height); - loaded(); - }); -}; -const createInlineBox = (boxWindow, boxOverlay, loaded, caption, params) => { - const ajaxContent = baseAjaxElement(boxWindow, boxOverlay, caption, params); - const element = document.getElementById(params.inlineId); - ajaxContent.insertAdjacentElement("beforeend", element == null ? void 0 : element.children[0]); - const unloadAction = () => { - element == null ? void 0 : element.insertAdjacentElement("afterbegin", ajaxContent.children[0]); - document.body.removeEventListener("wubox:unload", unloadAction); - }; - document.body.addEventListener("wubox:unload", unloadAction); - setBoxPosition(boxWindow, params.width, params.height); - loaded(); -}; -const showFormErrors = (form, errors) => { - const formId = form.getAttribute("id"); - const errorApp = window["wu_" + formId + "_errors"]; - if (errorApp) { - errorApp.errors = errors; - } - const formAppEl = document.querySelector('[data-wu-app="' + formId + '_errors"]'); - if (formAppEl) { - formAppEl.setAttribute("tabindex", "-1"); - formAppEl.focus(); - } -}; -const formSubmit = (form) => async (event) => { - event.preventDefault(); - const textArea = form.querySelector("textarea[data-editor]"); - const textAreaInput = textArea ? form.querySelector('input[name="' + textArea.id + '"]') : null; - if (textArea && textAreaInput) { - textAreaInput.value = textArea.value; - } - const blocked_form = wu_block_ui(form); - if (window["wu_" + form.getAttribute("id") + "_errors"]) { - window["wu_" + form.getAttribute("id") + "_errors"].errors = []; - } - const submitButton = event.submitter.value; - const formData = new FormData(form); - formData.append("submit", submitButton); - let response; - try { - const fetchResponse = await fetch(form.getAttribute("action"), { - method: "POST", - body: formData, - headers: { - "X-Requested-With": "XMLHttpRequest" - } - }); - const txt = await fetchResponse.text(); - if (!fetchResponse.ok) { - throw new Error(fetchResponse.status + " " + fetchResponse.statusText); - } - response = txt ? JSON.parse(txt) : null; - } catch (error) { - blocked_form.unblock(); - const message = (typeof wuboxL10n !== "undefined" && wuboxL10n.server_error) ? wuboxL10n.server_error : "An unexpected error occurred. Please try again or contact support if the problem persists."; - showFormErrors(form, [{ code: "server-error", message }]); - return; - } - if (response === null || response.data === null) { - blocked_form.unblock(); - removeBox(); - return; - } - if (!response.success) { - blocked_form.unblock(); - showFormErrors(form, response.data); - } - if (typeof response.data.tables === "object") { - blocked_form.unblock(); - removeBox(); - Object.keys(response.data.tables).forEach((key) => { - window[key].update(); - }); - } - if (typeof response.data.download_url === "string") { - blocked_form.unblock(); - removeBox(); - // Trigger the ZIP download without navigating away from the current page. - const a = document.createElement("a"); - a.href = response.data.download_url; - a.setAttribute("download", ""); - document.body.appendChild(a); - a.click(); - document.body.removeChild(a); - } - if (typeof response.data.redirect_url === "string") { - window.location.href = response.data.redirect_url; - } - if (typeof response.data.send === "object") { - window[response.data.send.scope][response.data.send.function_name](response.data.send.data, removeBox); - } -}; -function getPageSize() { - const de = document.documentElement; - const width = window.innerWidth || self.innerWidth || de && de.clientWidth || document.body.clientWidth; - const height = window.innerHeight || self.innerHeight || de && de.clientHeight || document.body.clientHeight; - return { width, height }; -} -function setBoxPosition(boxWindow, width, height) { - boxWindow.style.marginLeft = "-" + width / 2 + "px"; - boxWindow.style.marginTop = "-" + height / 2 + "px"; -} -function fadeOutEffect(element, duration, callback) { - const startOpacity = parseFloat(getComputedStyle(element).opacity); - let startTime = null; - function step(timestamp) { - if (!startTime) - startTime = timestamp; - const progress = timestamp - startTime; - const opacity = Math.max(startOpacity - progress / duration, 0); - element.style.opacity = opacity.toString(); - if (progress < duration) { - requestAnimationFrame(step); - } else { - element.style.display = "none"; - if (callback) - callback(); - } - } - requestAnimationFrame(step); -} -function showBoxIframe() { - var _a; - (_a = document.getElementById("WUB_load")) == null ? void 0 : _a.remove(); - const boxWindow = document.getElementById("WUB_window"); - boxWindow.style.visibility = "visible"; - document.body.dispatchEvent(new Event("wubox:iframe:loaded")); -} -function showBox(caption, url, imageGroup) { - var _a; - const boxOverlay = document.getElementById("WUB_overlay") || document.createElement("div"); - boxOverlay.id = "WUB_overlay"; - const boxWindow = document.getElementById("WUB_window") || document.createElement("div"); - boxWindow.id = "WUB_window"; - document.body.insertAdjacentElement("beforeend", boxOverlay); - document.body.insertAdjacentElement("beforeend", boxWindow); - boxOverlay.addEventListener("click", removeBox); - document.body.classList.add("modal-open"); - const loader = document.createElement("div"); - loader.id = "WUB_load"; - loader.style.display = "block"; - const loaded = () => { - boxWindow.style.visibility = "visible"; - document.body.dispatchEvent(new Event("wubox:load")); - loader.remove(); - refreshBox(); - }; - document.body.insertAdjacentElement("beforeend", loader); - const baseURL = url.split("?")[0]; - const urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; - const isImage = !!baseURL.toLowerCase().match(urlString); - if (isImage) { - createImageBox(boxWindow, loaded, url, caption, imageGroup); - } else { - const queryString = url.replace(/^[^\?]+\??/, ""); - const searchParams = new URLSearchParams(queryString); - const params = { - width: parseInt(searchParams.get("width") || "") || 630, - height: parseInt(searchParams.get("height") || "") || 440, - modal: !!searchParams.get("modal") || false, - inlineId: searchParams.get("inlineId") || "" - }; - if (url.includes("WUB_iframe")) { - createIframeBox(boxWindow, boxOverlay, loaded, url, caption, params); - } else if (url.includes("WUB_inline")) { - createInlineBox(boxWindow, boxOverlay, loaded, caption, params); - } else { - createAjaxBox(boxWindow, boxOverlay, loaded, url, caption, params); - } - (_a = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _a.addEventListener("click", removeBox); - } - const closeBoxWindowButton = document.getElementById("WUB_closeWindowButton"); - const closeIcon = closeBoxWindowButton == null ? void 0 : closeBoxWindowButton.querySelector(".wutb-close-icon"); - if (closeIcon && !!(closeIcon.offsetWidth || closeIcon.offsetHeight || closeIcon.getClientRects().length)) { - closeBoxWindowButton.focus(); - } -} -function initForm(form) { - form.addEventListener("submit", formSubmit(form)); -} -const setBodyListeners = (domChunk) => { - document.body.addEventListener("wubox:iframe:loaded", () => { - var _a; - (_a = document.getElementById("WUB_window")) == null ? void 0 : _a.classList.remove("wubox-loading"); - }); - document.body.addEventListener("wubox:load", () => { - const form = document.querySelector("#WUB_ajaxContent .wu_form"); - if (!form) { - return; - } - initForm(form); - wu_initialize_editors(); - }); -}; -const onClickEvent = (event) => { - event.preventDefault(); - const target = event.currentTarget; - const caption = target.title || target.name || "", url = target.href || target.alt, imageGroup = target.rel || false; - showBox(caption, url, imageGroup); - target.blur(); -}; -const initBox = (domChunk, addGlobalListeners = false, addMutationObserver = false) => { - document.querySelectorAll(domChunk).forEach((el) => { - el.removeEventListener("click", onClickEvent); - el.addEventListener("click", onClickEvent); - }); - if (addGlobalListeners) { - setBodyListeners(); - } - if (addMutationObserver) { - const observerOptions = { - childList: true, - subtree: true - }; - const observer = new MutationObserver(() => { - initBox(domChunk, false, false); - }); - observer.observe(document.body, observerOptions); - } -}; -const removeBox = () => { - var _a, _b, _c; - (_a = document.getElementById("WUB_ImageOff")) == null ? void 0 : _a.removeEventListener("click", removeBox); - (_b = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _b.removeEventListener("click", removeBox); - document.body.classList.remove("modal-open"); - (_c = document.getElementById("WUB_load")) == null ? void 0 : _c.remove(); - fadeOutEffect(document.getElementById("WUB_window"), 200); - fadeOutEffect(document.getElementById("WUB_overlay"), 150, () => { - document.body.dispatchEvent(new Event("wubox:unload")); - document.querySelectorAll("#WUB_window, #WUB_overlay, #WUB_HideSelect").forEach((el) => el.remove()); - document.body.dispatchEvent(new Event("wubox:removed")); - }); -}; -const refreshBox = () => { - const form = document.querySelector("#WUB_ajaxContent .wu_form"); - if (!form) { - return; - } - wu_initialize_editors(); - const content = document.getElementById("WUB_ajaxContent"); - const boxWindow = document.getElementById("WUB_window"); - content.style.height = "100vh"; - const max_height = window.innerHeight - 120; - const height = form.offsetHeight >= max_height ? max_height : form.offsetHeight + 1; - boxWindow.style.transition = "margin 200ms"; - content.style.height = height + "px"; - boxWindow.style.marginTop = "-" + height / 2 + "px"; -}; -const setBoxWidth = (width) => { - const content = document.getElementById("WUB_ajaxContent"); - const boxWindow = document.getElementById("WUB_window"); - if (!content) { - return; - } - content.style.transition = "width 150ms"; - boxWindow.style.transition = "margin 150ms"; - content.style.width = width + "px"; - boxWindow.style.marginLeft = "-" + width / 2 + "px"; - boxWindow.style.width = width + "px"; - setTimeout(() => { - refreshBox(); - }, 150); -}; -window.wubox = { - /** - * Initializes the box. - * - * @param domChunk The DOM chunk to be used as the box content. - * @param addGlobalListeners Whether or not to add global listeners. - */ - init: initBox, - /** - * Progarmmatically shows the box. - * - * @param caption The title of the box. - * @param url The URL to be loaded in the box. - * @param imageGroup The image group to be used in the box. - */ - show: showBox, - /** - * Removes the current opened box. - * - */ - remove: removeBox, - /** - * Refreshes the current opened box. - */ - refresh: refreshBox, - /** - * set the box width. - * @param width - */ - width: setBoxWidth -}; -window.addEventListener("DOMContentLoaded", () => { - window.wubox.init(".wubox", true, true); +
`); + } + } else { + const ajaxContent = document.getElementById("WUB_ajaxContent"); + ajaxContent.style.width = params.width + "px"; + ajaxContent.style.height = params.height + "px"; + ajaxContent.scrollTop = 0; + ajaxContent.innerHTML = caption; + } + return document.getElementById("WUB_ajaxContent"); + }; + const createAjaxBox = (boxWindow, boxOverlay, loaded, url, caption, params) => { + const ajaxContent = baseAjaxElement(boxWindow, boxOverlay, caption, params); + const load_url = url + (url.includes("?") ? "&" : "?") + "random=" + (/* @__PURE__ */ new Date()).getTime(); + fetch(load_url, { + headers: { + "X-Requested-With": "XMLHttpRequest" + } + }).then((response) => response.text()).then((html) => { + ajaxContent.innerHTML = html; + setBoxPosition(boxWindow, params.width, params.height); + loaded(); + }); + }; + const createInlineBox = (boxWindow, boxOverlay, loaded, caption, params) => { + const ajaxContent = baseAjaxElement(boxWindow, boxOverlay, caption, params); + const element = document.getElementById(params.inlineId); + ajaxContent.insertAdjacentElement("beforeend", element == null ? void 0 : element.children[ 0 ]); + const unloadAction = () => { + element == null ? void 0 : element.insertAdjacentElement("afterbegin", ajaxContent.children[ 0 ]); + document.body.removeEventListener("wubox:unload", unloadAction); + }; + document.body.addEventListener("wubox:unload", unloadAction); + setBoxPosition(boxWindow, params.width, params.height); + loaded(); + }; + const showFormErrors = (form, errors) => { + const formId = form.getAttribute("id"); + const errorApp = window[ "wu_" + formId + "_errors" ]; + if (errorApp) { + errorApp.errors = errors; + } + const formAppEl = document.querySelector('[data-wu-app="' + formId + '_errors"]'); + if (formAppEl) { + formAppEl.setAttribute("tabindex", "-1"); + formAppEl.focus(); + } + }; + const formSubmit = (form) => async (event) => { + event.preventDefault(); + const textArea = form.querySelector("textarea[data-editor]"); + const textAreaInput = textArea ? form.querySelector('input[name="' + textArea.id + '"]') : null; + if (textArea && textAreaInput) { + textAreaInput.value = textArea.value; + } + const blocked_form = wu_block_ui(form); + if (window[ "wu_" + form.getAttribute("id") + "_errors" ]) { + window[ "wu_" + form.getAttribute("id") + "_errors" ].errors = []; + } + const submitButton = event.submitter.value; + const formData = new FormData(form); + formData.append("submit", submitButton); + let response; + try { + const fetchResponse = await fetch(form.getAttribute("action"), { + method: "POST", + body: formData, + headers: { + "X-Requested-With": "XMLHttpRequest" + } + }); + const txt = await fetchResponse.text(); + if (! fetchResponse.ok) { + throw new Error(fetchResponse.status + " " + fetchResponse.statusText); + } + response = txt ? JSON.parse(txt) : null; + } catch (error) { + blocked_form.unblock(); + const message = (typeof wuboxL10n !== "undefined" && wuboxL10n.server_error) ? wuboxL10n.server_error : "An unexpected error occurred. Please try again or contact support if the problem persists."; + showFormErrors(form, [ { code: "server-error", message } ]); + return; + } + if (response === null || response.data === null) { + blocked_form.unblock(); + removeBox(); + return; + } + if (! response.success) { + blocked_form.unblock(); + showFormErrors(form, response.data); + } + if (typeof response.data.tables === "object") { + blocked_form.unblock(); + removeBox(); + Object.keys(response.data.tables).forEach((key) => { + window[ key ].update(); + }); + } + if (typeof response.data.download_url === "string") { + blocked_form.unblock(); + removeBox(); + // Trigger the ZIP download without navigating away from the current page. + const a = document.createElement("a"); + a.href = response.data.download_url; + a.setAttribute("download", ""); + document.body.appendChild(a); + a.click(); + document.body.removeChild(a); + } + if (typeof response.data.redirect_url === "string") { + window.location.href = response.data.redirect_url; + } + if (typeof response.data.send === "object") { + window[ response.data.send.scope ][ response.data.send.function_name ](response.data.send.data, removeBox); + } + }; + function getPageSize() { + const de = document.documentElement; + const width = window.innerWidth || self.innerWidth || de && de.clientWidth || document.body.clientWidth; + const height = window.innerHeight || self.innerHeight || de && de.clientHeight || document.body.clientHeight; + return { width, height }; + } + function setBoxPosition(boxWindow, width, height) { + boxWindow.style.marginLeft = "-" + width / 2 + "px"; + boxWindow.style.marginTop = "-" + height / 2 + "px"; + } + function fadeOutEffect(element, duration, callback) { + const startOpacity = parseFloat(getComputedStyle(element).opacity); + let startTime = null; + function step(timestamp) { + if (! startTime) { + startTime = timestamp; + } + const progress = timestamp - startTime; + const opacity = Math.max(startOpacity - progress / duration, 0); + element.style.opacity = opacity.toString(); + if (progress < duration) { + requestAnimationFrame(step); + } else { + element.style.display = "none"; + if (callback) { + callback(); + } + } + } + requestAnimationFrame(step); + } + function showBoxIframe() { + let _a; + (_a = document.getElementById("WUB_load")) == null ? void 0 : _a.remove(); + const boxWindow = document.getElementById("WUB_window"); + boxWindow.style.visibility = "visible"; + document.body.dispatchEvent(new Event("wubox:iframe:loaded")); + } + function showBox(caption, url, imageGroup) { + let _a; + const boxOverlay = document.getElementById("WUB_overlay") || document.createElement("div"); + boxOverlay.id = "WUB_overlay"; + const boxWindow = document.getElementById("WUB_window") || document.createElement("div"); + boxWindow.id = "WUB_window"; + document.body.insertAdjacentElement("beforeend", boxOverlay); + document.body.insertAdjacentElement("beforeend", boxWindow); + boxOverlay.addEventListener("click", removeBox); + document.body.classList.add("modal-open"); + const loader = document.createElement("div"); + loader.id = "WUB_load"; + loader.style.display = "block"; + const loaded = () => { + boxWindow.style.visibility = "visible"; + document.body.dispatchEvent(new Event("wubox:load")); + loader.remove(); + refreshBox(); + }; + document.body.insertAdjacentElement("beforeend", loader); + const baseURL = url.split("?")[ 0 ]; + const urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/; + const isImage = !! baseURL.toLowerCase().match(urlString); + if (isImage) { + createImageBox(boxWindow, loaded, url, caption, imageGroup); + } else { + const queryString = url.replace(/^[^\?]+\??/, ""); + const searchParams = new URLSearchParams(queryString); + const params = { + width: parseInt(searchParams.get("width") || "") || 630, + height: parseInt(searchParams.get("height") || "") || 440, + modal: !! searchParams.get("modal") || false, + inlineId: searchParams.get("inlineId") || "" + }; + if (url.includes("WUB_iframe")) { + createIframeBox(boxWindow, boxOverlay, loaded, url, caption, params); + } else if (url.includes("WUB_inline")) { + createInlineBox(boxWindow, boxOverlay, loaded, caption, params); + } else { + createAjaxBox(boxWindow, boxOverlay, loaded, url, caption, params); + } + (_a = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _a.addEventListener("click", removeBox); + } + const closeBoxWindowButton = document.getElementById("WUB_closeWindowButton"); + const closeIcon = closeBoxWindowButton == null ? void 0 : closeBoxWindowButton.querySelector(".wutb-close-icon"); + if (closeIcon && !! (closeIcon.offsetWidth || closeIcon.offsetHeight || closeIcon.getClientRects().length)) { + closeBoxWindowButton.focus(); + } + } + function initForm(form) { + form.addEventListener("submit", formSubmit(form)); + } + const setBodyListeners = (domChunk) => { + document.body.addEventListener("wubox:iframe:loaded", () => { + let _a; + (_a = document.getElementById("WUB_window")) == null ? void 0 : _a.classList.remove("wubox-loading"); + }); + document.body.addEventListener("wubox:load", () => { + const form = document.querySelector("#WUB_ajaxContent .wu_form"); + if (! form) { + return; + } + initForm(form); + wu_initialize_editors(); + }); + }; + const onClickEvent = (event) => { + event.preventDefault(); + const target = event.currentTarget; + const caption = target.title || target.name || "", + url = target.href || target.alt, + imageGroup = target.rel || false; + showBox(caption, url, imageGroup); + target.blur(); + }; + const initBox = (domChunk, addGlobalListeners = false, addMutationObserver = false) => { + document.querySelectorAll(domChunk).forEach((el) => { + el.removeEventListener("click", onClickEvent); + el.addEventListener("click", onClickEvent); + }); + if (addGlobalListeners) { + setBodyListeners(); + } + if (addMutationObserver) { + const observerOptions = { + childList: true, + subtree: true + }; + const observer = new MutationObserver(() => { + initBox(domChunk, false, false); + }); + observer.observe(document.body, observerOptions); + } + }; + const removeBox = () => { + let _a, _b, _c; + (_a = document.getElementById("WUB_ImageOff")) == null ? void 0 : _a.removeEventListener("click", removeBox); + (_b = document.getElementById("WUB_closeWindowButton")) == null ? void 0 : _b.removeEventListener("click", removeBox); + document.body.classList.remove("modal-open"); + (_c = document.getElementById("WUB_load")) == null ? void 0 : _c.remove(); + fadeOutEffect(document.getElementById("WUB_window"), 200); + fadeOutEffect(document.getElementById("WUB_overlay"), 150, () => { + document.body.dispatchEvent(new Event("wubox:unload")); + document.querySelectorAll("#WUB_window, #WUB_overlay, #WUB_HideSelect").forEach((el) => el.remove()); + document.body.dispatchEvent(new Event("wubox:removed")); + }); + }; + const refreshBox = () => { + const form = document.querySelector("#WUB_ajaxContent .wu_form"); + if (! form) { + return; + } + wu_initialize_editors(); + const content = document.getElementById("WUB_ajaxContent"); + const boxWindow = document.getElementById("WUB_window"); + content.style.height = "100vh"; + const max_height = window.innerHeight - 120; + const height = form.offsetHeight >= max_height ? max_height : form.offsetHeight + 1; + boxWindow.style.transition = "margin 200ms"; + content.style.height = height + "px"; + boxWindow.style.marginTop = "-" + height / 2 + "px"; + }; + const setBoxWidth = (width) => { + const content = document.getElementById("WUB_ajaxContent"); + const boxWindow = document.getElementById("WUB_window"); + if (! content) { + return; + } + content.style.transition = "width 150ms"; + boxWindow.style.transition = "margin 150ms"; + content.style.width = width + "px"; + boxWindow.style.marginLeft = "-" + width / 2 + "px"; + boxWindow.style.width = width + "px"; + setTimeout(() => { + refreshBox(); + }, 150); + }; + window.wubox = { + /** + * Initializes the box. + * + * @param domChunk The DOM chunk to be used as the box content. + * @param addGlobalListeners Whether or not to add global listeners. + */ + init: initBox, + /** + * Progarmmatically shows the box. + * + * @param caption The title of the box. + * @param url The URL to be loaded in the box. + * @param imageGroup The image group to be used in the box. + */ + show: showBox, + /** + * Removes the current opened box. + * + */ + remove: removeBox, + /** + * Refreshes the current opened box. + */ + refresh: refreshBox, + /** + * set the box width. + * @param width + */ + width: setBoxWidth + }; + window.addEventListener("DOMContentLoaded", () => { + window.wubox.init(".wubox", true, true); - // Mark wubox as ready and process any queued early clicks - window.__wuboxReady = true; + // Mark wubox as ready and process any queued early clicks + window.__wuboxReady = true; - // Remove the early click listener - no longer needed - if (window.__wuboxEarlyClickHandler) { - document.removeEventListener('click', window.__wuboxEarlyClickHandler, true); - delete window.__wuboxEarlyClickHandler; - } + // Remove the early click listener - no longer needed + if (window.__wuboxEarlyClickHandler) { + document.removeEventListener('click', window.__wuboxEarlyClickHandler, true); + delete window.__wuboxEarlyClickHandler; + } - if (window.__wuboxEarlyClicks && window.__wuboxEarlyClicks.length > 0) { - // Remove duplicates - only keep unique elements - const uniqueClicks = [...new Set(window.__wuboxEarlyClicks)]; + if (window.__wuboxEarlyClicks && window.__wuboxEarlyClicks.length > 0) { + // Remove duplicates - only keep unique elements + const uniqueClicks = [ ...new Set(window.__wuboxEarlyClicks) ]; - uniqueClicks.forEach((target) => { - const caption = target.title || target.name || ''; - const url = target.href || target.alt; - const imageGroup = target.rel || false; + uniqueClicks.forEach((target) => { + const caption = target.title || target.name || ''; + const url = target.href || target.alt; + const imageGroup = target.rel || false; target.style.cursor = ''; - window.wubox.show(caption, url, imageGroup); - }); - window.__wuboxEarlyClicks = []; - } -}); + window.wubox.show(caption, url, imageGroup); + }); + window.__wuboxEarlyClicks = []; + } + }); })() diff --git a/inc/checkout/class-checkout.php b/inc/checkout/class-checkout.php index f6eb470ee..8da7ea566 100644 --- a/inc/checkout/class-checkout.php +++ b/inc/checkout/class-checkout.php @@ -2084,6 +2084,7 @@ public function get_checkout_variables() { 'forgot_password' => __('Forgot password?', 'ultimate-multisite'), 'cancel' => __('Cancel', 'ultimate-multisite'), 'email_exists' => __('A customer with the same email address or username already exists.', 'ultimate-multisite'), + 'provisioning_site' => __('Provisioning your site — this can take up to 60 seconds.', 'ultimate-multisite'), // Client-side validation messages (%s = field label, %d = numeric limit). /* translators: %s: field label */ 'field_required' => __('%s is required.', 'ultimate-multisite'), diff --git a/package-lock.json b/package-lock.json index 26472ff3e..6a8eed141 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "ultimate-multisite", - "version": "2.4.13-beta.1", + "version": "2.12.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "ultimate-multisite", - "version": "2.4.13-beta.1", + "version": "2.12.0", "dependencies": { "apexcharts": "^5.2.0", "shepherd.js": "^14.5.0"