first commit

This commit is contained in:
fuzi_fauzia committed 2024-07-31 13:12:38 +07:00
commit b4e8cbe182
10213 files changed
+3125839

No files matched your search

@@ -0,0 +1,158 @@
/*global jQuery, Backbone, _, woocommerce_admin_api_keys, wcSetClipboard, wcClearClipboard */
(function( $ ) {
var APIView = Backbone.View.extend({
/**
* Element
*
* @param {Object} '#key-fields'
*/
el: $( '#key-fields' ),
/**
* Events
*
* @type {Object}
*/
events: {
'click input#update_api_key': 'saveKey'
},
/**
* Initialize actions
*/
initialize: function(){
_.bindAll( this, 'saveKey' );
},
/**
* Init jQuery.BlockUI
*/
block: function() {
$( this.el ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
/**
* Remove jQuery.BlockUI
*/
unblock: function() {
$( this.el ).unblock();
},
/**
* Init TipTip
*/
initTipTip: function( css_class ) {
$( document.body )
.on( 'click', css_class, function( evt ) {
evt.preventDefault();
if ( ! document.queryCommandSupported( 'copy' ) ) {
$( css_class ).parent().find( 'input' ).trigger( 'focus' ).trigger( 'select' );
$( '#copy-error' ).text( woocommerce_admin_api_keys.clipboard_failed );
} else {
$( '#copy-error' ).text( '' );
wcClearClipboard();
wcSetClipboard( $( this ).prev( 'input' ).val().trim(), $( css_class ) );
}
} )
.on( 'aftercopy', css_class, function() {
$( '#copy-error' ).text( '' );
$( css_class ).tipTip( {
'attribute': 'data-tip',
'activation': 'focus',
'fadeIn': 50,
'fadeOut': 50,
'delay': 0
} ).trigger( 'focus' );
} )
.on( 'aftercopyerror', css_class, function() {
$( css_class ).parent().find( 'input' ).trigger( 'focus' ).trigger( 'select' );
$( '#copy-error' ).text( woocommerce_admin_api_keys.clipboard_failed );
} );
},
/**
* Create qrcode
*
* @param {string} consumer_key
* @param {string} consumer_secret
*/
createQRCode: function( consumer_key, consumer_secret ) {
$( '#keys-qrcode' ).qrcode({
text: consumer_key + '|' + consumer_secret,
width: 120,
height: 120
});
},
/**
* Save API Key using ajax
*
* @param {Object} e
*/
saveKey: function( e ) {
e.preventDefault();
var self = this;
self.block();
Backbone.ajax({
method: 'POST',
dataType: 'json',
url: woocommerce_admin_api_keys.ajax_url,
data: {
action: 'woocommerce_update_api_key',
security: woocommerce_admin_api_keys.update_api_nonce,
key_id: $( '#key_id', self.el ).val(),
description: $( '#key_description', self.el ).val(),
user: $( '#key_user', self.el ).val(),
permissions: $( '#key_permissions', self.el ).val()
},
success: function( response ) {
$( '.wc-api-message', self.el ).remove();
if ( response.success ) {
var data = response.data;
$( 'h2, h3', self.el ).first().append( '<div class="wc-api-message updated"><p>' + data.message + '</p></div>' );
if ( 0 < data.consumer_key.length && 0 < data.consumer_secret.length ) {
$( '#api-keys-options', self.el ).remove();
$( 'p.submit', self.el ).empty().append( data.revoke_url );
var template = wp.template( 'api-keys-template' );
$( 'p.submit', self.el ).before( template({
consumer_key: data.consumer_key,
consumer_secret: data.consumer_secret
}) );
self.createQRCode( data.consumer_key, data.consumer_secret );
self.initTipTip( '.copy-key' );
self.initTipTip( '.copy-secret' );
} else {
$( '#key_description', self.el ).val( data.description );
$( '#key_user', self.el ).val( data.user_id );
$( '#key_permissions', self.el ).val( data.permissions );
}
} else {
$( 'h2, h3', self.el )
.first()
.append( '<div class="wc-api-message error"><p>' + response.data.message + '</p></div>' );
}
self.unblock();
}
});
}
});
new APIView();
})( jQuery );
@@ -0,0 +1 @@
!function(e){new(Backbone.View.extend({el:e("#key-fields"),events:{"click input#update_api_key":"saveKey"},initialize:function(){_.bindAll(this,"saveKey")},block:function(){e(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){e(this.el).unblock()},initTipTip:function(i){e(document.body).on("click",i,function(t){t.preventDefault(),document.queryCommandSupported("copy")?(e("#copy-error").text(""),wcClearClipboard(),wcSetClipboard(e(this).prev("input").val().trim(),e(i))):(e(i).parent().find("input").trigger("focus").trigger("select"),e("#copy-error").text(woocommerce_admin_api_keys.clipboard_failed))}).on("aftercopy",i,function(){e("#copy-error").text(""),e(i).tipTip({attribute:"data-tip",activation:"focus",fadeIn:50,fadeOut:50,delay:0}).trigger("focus")}).on("aftercopyerror",i,function(){e(i).parent().find("input").trigger("focus").trigger("select"),e("#copy-error").text(woocommerce_admin_api_keys.clipboard_failed)})},createQRCode:function(i,t){e("#keys-qrcode").qrcode({text:i+"|"+t,width:120,height:120})},saveKey:function(i){i.preventDefault();var t=this;t.block(),Backbone.ajax({method:"POST",dataType:"json",url:woocommerce_admin_api_keys.ajax_url,data:{action:"woocommerce_update_api_key",security:woocommerce_admin_api_keys.update_api_nonce,key_id:e("#key_id",t.el).val(),description:e("#key_description",t.el).val(),user:e("#key_user",t.el).val(),permissions:e("#key_permissions",t.el).val()},success:function(i){if(e(".wc-api-message",t.el).remove(),i.success){var o=i.data;if(e("h2, h3",t.el).first().append('<div class="wc-api-message updated"><p>'+o.message+"</p></div>"),0<o.consumer_key.length&&0<o.consumer_secret.length){e("#api-keys-options",t.el).remove(),e("p.submit",t.el).empty().append(o.revoke_url);var r=wp.template("api-keys-template");e("p.submit",t.el).before(r({consumer_key:o.consumer_key,consumer_secret:o.consumer_secret})),t.createQRCode(o.consumer_key,o.consumer_secret),t.initTipTip(".copy-key"),t.initTipTip(".copy-secret")}else e("#key_description",t.el).val(o.description),e("#key_user",t.el).val(o.user_id),e("#key_permissions",t.el).val(o.permissions)}else e("h2, h3",t.el).first().append('<div class="wc-api-message error"><p>'+i.data.message+"</p></div>");t.unblock()}})}}))}(jQuery);
@@ -0,0 +1,170 @@
/*global jQuery, Backbone, _ */
( function( $, Backbone, _ ) {
'use strict';
/**
* WooCommerce Backbone Modal plugin
*
* @param {object} options
*/
$.fn.WCBackboneModal = function( options ) {
return this.each( function() {
( new $.WCBackboneModal( $( this ), options ) );
});
};
/**
* Initialize the Backbone Modal
*
* @param {object} element [description]
* @param {object} options [description]
*/
$.WCBackboneModal = function( element, options ) {
// Set settings
var settings = $.extend( {}, $.WCBackboneModal.defaultOptions, options );
if ( settings.template ) {
new $.WCBackboneModal.View({
target: settings.template,
string: settings.variable
});
}
};
/**
* Set default options
*
* @type {object}
*/
$.WCBackboneModal.defaultOptions = {
template: '',
variable: {}
};
/**
* Create the Backbone Modal
*
* @return {null}
*/
$.WCBackboneModal.View = Backbone.View.extend({
tagName: 'div',
id: 'wc-backbone-modal-dialog',
_target: undefined,
_string: undefined,
events: {
'click .modal-close': 'closeButton',
'click #btn-ok' : 'addButton',
'click #btn-back' : 'backButton',
'click #btn-next' : 'nextButton',
'touchstart #btn-ok': 'addButton',
'keydown' : 'keyboardActions',
'input' : 'handleInputValidation'
},
resizeContent: function() {
var $content = $( '.wc-backbone-modal-content' ).find( 'article' );
var max_h = $( window ).height() * 0.75;
$content.css({
'max-height': max_h + 'px'
});
},
initialize: function( data ) {
var view = this;
this._target = data.target;
this._string = data.string;
_.bindAll( this, 'render' );
this.render();
$( window ).on( 'resize', function() {
view.resizeContent();
});
},
render: function() {
var template = wp.template( this._target );
this.$el.append(
template( this._string )
);
$( document.body ).css({
'overflow': 'hidden'
}).append( this.$el );
this.resizeContent();
this.$( '.wc-backbone-modal-content' ).attr( 'tabindex' , '0' ).trigger( 'focus' );
$( document.body ).trigger( 'init_tooltips' );
$( document.body ).trigger( 'wc_backbone_modal_loaded', this._target );
},
closeButton: function( e, addButtonCalled ) {
e.preventDefault();
$( document.body ).trigger( 'wc_backbone_modal_before_remove', [ this._target, this.getFormData(), !!addButtonCalled ] );
this.undelegateEvents();
$( document ).off( 'focusin' );
$( document.body ).css({
'overflow': 'auto'
});
this.remove();
$( document.body ).trigger( 'wc_backbone_modal_removed', this._target );
},
addButton: function( e ) {
$( document.body ).trigger( 'wc_backbone_modal_response', [ this._target, this.getFormData() ] );
this.closeButton( e, true );
},
backButton: function( e ) {
$( document.body ).trigger( 'wc_backbone_modal_back_response', [ this._target, this.getFormData() ] );
this.closeButton( e, false );
},
nextButton: function( e ) {
var context = this;
function closeModal() {
context.closeButton( e );
}
$( document.body ).trigger( 'wc_backbone_modal_next_response', [ this._target, this.getFormData(), closeModal ] );
},
getFormData: function( updating = true ) {
var data = {};
if ( updating ) {
$( document.body ).trigger( 'wc_backbone_modal_before_update', this._target );
}
$.each( $( 'form', this.$el ).serializeArray(), function( index, item ) {
if ( item.name.indexOf( '[]' ) !== -1 ) {
item.name = item.name.replace( '[]', '' );
data[ item.name ] = $.makeArray( data[ item.name ] );
data[ item.name ].push( item.value );
} else {
data[ item.name ] = item.value;
}
});
return data;
},
handleInputValidation: function() {
$( document.body ).trigger( 'wc_backbone_modal_validation', [ this._target, this.getFormData( false ) ] );
},
keyboardActions: function( e ) {
var button = e.keyCode || e.which;
// Enter key
if (
13 === button &&
! ( e.target.tagName && ( e.target.tagName.toLowerCase() === 'input' || e.target.tagName.toLowerCase() === 'textarea' ) )
) {
if ( $( '#btn-ok' ).length ) {
this.addButton( e );
} else if ( $( '#btn-next' ).length ) {
this.nextButton( e );
}
}
// ESC key
if ( 27 === button ) {
this.closeButton( e );
}
}
});
}( jQuery, Backbone, _ ));
@@ -0,0 +1 @@
!function(t,e,n){"use strict";t.fn.WCBackboneModal=function(e){return this.each(function(){new t.WCBackboneModal(t(this),e)})},t.WCBackboneModal=function(e,n){var o=t.extend({},t.WCBackboneModal.defaultOptions,n);o.template&&new t.WCBackboneModal.View({target:o.template,string:o.variable})},t.WCBackboneModal.defaultOptions={template:"",variable:{}},t.WCBackboneModal.View=e.View.extend({tagName:"div",id:"wc-backbone-modal-dialog",_target:undefined,_string:undefined,events:{"click .modal-close":"closeButton","click #btn-ok":"addButton","click #btn-back":"backButton","click #btn-next":"nextButton","touchstart #btn-ok":"addButton",keydown:"keyboardActions",input:"handleInputValidation"},resizeContent:function(){var e=t(".wc-backbone-modal-content").find("article"),n=.75*t(window).height();e.css({"max-height":n+"px"})},initialize:function(e){var o=this;this._target=e.target,this._string=e.string,n.bindAll(this,"render"),this.render(),t(window).on("resize",function(){o.resizeContent()})},render:function(){var e=wp.template(this._target);this.$el.append(e(this._string)),t(document.body).css({overflow:"hidden"}).append(this.$el),this.resizeContent(),this.$(".wc-backbone-modal-content").attr("tabindex","0").trigger("focus"),t(document.body).trigger("init_tooltips"),t(document.body).trigger("wc_backbone_modal_loaded",this._target)},closeButton:function(e,n){e.preventDefault(),t(document.body).trigger("wc_backbone_modal_before_remove",[this._target,this.getFormData(),!!n]),this.undelegateEvents(),t(document).off("focusin"),t(document.body).css({overflow:"auto"}),this.remove(),t(document.body).trigger("wc_backbone_modal_removed",this._target)},addButton:function(e){t(document.body).trigger("wc_backbone_modal_response",[this._target,this.getFormData()]),this.closeButton(e,!0)},backButton:function(e){t(document.body).trigger("wc_backbone_modal_back_response",[this._target,this.getFormData()]),this.closeButton(e,!1)},nextButton:function(e){var n=this;t(document.body).trigger("wc_backbone_modal_next_response",[this._target,this.getFormData(),function(){n.closeButton(e)}])},getFormData:function(e=!0){var n={};return e&&t(document.body).trigger("wc_backbone_modal_before_update",this._target),t.each(t("form",this.$el).serializeArray(),function(e,o){-1!==o.name.indexOf("[]")?(o.name=o.name.replace("[]",""),n[o.name]=t.makeArray(n[o.name]),n[o.name].push(o.value)):n[o.name]=o.value}),n},handleInputValidation:function(){t(document.body).trigger("wc_backbone_modal_validation",[this._target,this.getFormData(!1)])},keyboardActions:function(e){var n=e.keyCode||e.which;13!==n||e.target.tagName&&("input"===e.target.tagName.toLowerCase()||"textarea"===e.target.tagName.toLowerCase())||(t("#btn-ok").length?this.addButton(e):t("#btn-next").length&&this.nextButton(e)),27===n&&this.closeButton(e)}})}(jQuery,Backbone,_);
@@ -0,0 +1,450 @@
/* global marketplace_suggestions, ajaxurl, Cookies */
( function( $, marketplace_suggestions, ajaxurl ) {
$( function() {
if ( 'undefined' === typeof marketplace_suggestions ) {
return;
}
// Stand-in wcTracks.recordEvent in case tracks is not available (for any reason).
window.wcTracks = window.wcTracks || {};
window.wcTracks.recordEvent = window.wcTracks.recordEvent || function() { };
// Tracks events sent in this file:
// - marketplace_suggestion_displayed
// - marketplace_suggestion_clicked
// - marketplace_suggestion_dismissed
// All are prefixed by {WC_Tracks::PREFIX}.
// All have one property for `suggestionSlug`, to identify the specific suggestion message.
// Dismiss the specified suggestion from the UI, and save the dismissal in settings.
function dismissSuggestion( context, product, promoted, url, suggestionSlug ) {
// hide the suggestion in the UI
var selector = '[data-suggestion-slug=' + suggestionSlug + ']';
$( selector ).fadeOut( function() {
$( this ).remove();
tidyProductEditMetabox();
} );
// save dismissal in user settings
jQuery.post(
ajaxurl,
{
'action': 'woocommerce_add_dismissed_marketplace_suggestion',
'_wpnonce': marketplace_suggestions.dismiss_suggestion_nonce,
'slug': suggestionSlug
}
);
// if this is a high-use area, delay new suggestion that area for a short while
var highUseSuggestionContexts = [ 'products-list-inline' ];
if ( _.contains( highUseSuggestionContexts, context ) ) {
// snooze suggestions in that area for 2 days
var contextSnoozeCookie = 'woocommerce_snooze_suggestions__' + context;
Cookies.set( contextSnoozeCookie, 'true', { expires: 2 } );
// keep track of how often this area gets dismissed in a cookie
var contextDismissalCountCookie = 'woocommerce_dismissed_suggestions__' + context;
var previousDismissalsInThisContext = parseInt( Cookies.get( contextDismissalCountCookie ), 10 ) || 0;
Cookies.set( contextDismissalCountCookie, previousDismissalsInThisContext + 1, { expires: 31 } );
}
window.wcTracks.recordEvent( 'marketplace_suggestion_dismissed', {
suggestion_slug: suggestionSlug,
context: context,
product: product || '',
promoted: promoted || '',
target: url || ''
} );
}
// Render DOM element for suggestion dismiss button.
function renderDismissButton( context, product, promoted, url, suggestionSlug ) {
var dismissButton = document.createElement( 'a' );
dismissButton.classList.add( 'suggestion-dismiss' );
dismissButton.setAttribute( 'title', marketplace_suggestions.i18n_marketplace_suggestions_dismiss_tooltip );
dismissButton.setAttribute( 'href', '#' );
dismissButton.onclick = function( event ) {
event.preventDefault();
dismissSuggestion( context, product, promoted, url, suggestionSlug );
};
return dismissButton;
}
function addURLParameters( context, url ) {
var urlParams = marketplace_suggestions.in_app_purchase_params;
urlParams.utm_source = 'unknown';
urlParams.utm_campaign = 'marketplacesuggestions';
urlParams.utm_medium = 'product';
var sourceContextMap = {
'productstable': [
'products-list-inline'
],
'productsempty': [
'products-list-empty-header',
'products-list-empty-footer',
'products-list-empty-body'
],
'ordersempty': [
'orders-list-empty-header',
'orders-list-empty-footer',
'orders-list-empty-body'
],
'editproduct': [
'product-edit-meta-tab-header',
'product-edit-meta-tab-footer',
'product-edit-meta-tab-body'
]
};
var utmSource = _.findKey( sourceContextMap, function( sourceInfo ) {
return _.contains( sourceInfo, context );
} );
if ( utmSource ) {
urlParams.utm_source = utmSource;
}
return url + '?' + jQuery.param( urlParams );
}
// Render DOM element for suggestion linkout, optionally with button style.
function renderLinkout( context, product, promoted, slug, url, text, isButton ) {
var linkoutButton = document.createElement( 'a' );
var utmUrl = addURLParameters( context, url );
linkoutButton.setAttribute( 'href', utmUrl );
// By default, CTA links should open in same tab (and feel integrated with Woo).
// Exception: when editing products, use new tab. User may have product edits
// that need to be saved.
var newTabContexts = [
'product-edit-meta-tab-header',
'product-edit-meta-tab-footer',
'product-edit-meta-tab-body',
'products-list-empty-footer'
];
if ( _.includes( newTabContexts, context ) ) {
linkoutButton.setAttribute( 'target', 'blank' );
}
linkoutButton.textContent = text;
linkoutButton.onclick = function() {
window.wcTracks.recordEvent( 'marketplace_suggestion_clicked', {
suggestion_slug: slug,
context: context,
product: product || '',
promoted: promoted || '',
target: url || ''
} );
};
if ( isButton ) {
linkoutButton.classList.add( 'button' );
} else {
linkoutButton.classList.add( 'linkout' );
var linkoutIcon = document.createElement( 'span' );
linkoutIcon.classList.add( 'dashicons', 'dashicons-external' );
linkoutButton.appendChild( linkoutIcon );
}
return linkoutButton;
}
// Render DOM element for suggestion icon image.
function renderSuggestionIcon( iconUrl ) {
if ( ! iconUrl ) {
return null;
}
var image = document.createElement( 'img' );
image.src = iconUrl;
image.classList.add( 'marketplace-suggestion-icon' );
return image;
}
// Render DOM elements for suggestion content.
function renderSuggestionContent( slug, title, copy ) {
var container = document.createElement( 'div' );
container.classList.add( 'marketplace-suggestion-container-content' );
if ( title ) {
var titleHeading = document.createElement( 'h4' );
titleHeading.textContent = title;
container.appendChild( titleHeading );
}
if ( copy ) {
var body = document.createElement( 'p' );
body.textContent = copy;
container.appendChild( body );
}
// Conditionally add in a Manage suggestions link to product edit
// metabox footer (based on suggestion slug).
var slugsWithManage = [
'product-edit-empty-footer-browse-all',
'product-edit-meta-tab-footer-browse-all'
];
if ( -1 !== slugsWithManage.indexOf( slug ) ) {
container.classList.add( 'has-manage-link' );
var manageSuggestionsLink = document.createElement( 'a' );
manageSuggestionsLink.classList.add( 'marketplace-suggestion-manage-link', 'linkout' );
manageSuggestionsLink.setAttribute(
'href',
marketplace_suggestions.manage_suggestions_url
);
manageSuggestionsLink.textContent = marketplace_suggestions.i18n_marketplace_suggestions_manage_suggestions;
container.appendChild( manageSuggestionsLink );
}
return container;
}
// Render DOM elements for suggestion call-to-action – button or link with dismiss 'x'.
function renderSuggestionCTA( context, product, promoted, slug, url, linkText, linkIsButton, allowDismiss ) {
var container = document.createElement( 'div' );
if ( ! linkText ) {
linkText = marketplace_suggestions.i18n_marketplace_suggestions_default_cta;
}
container.classList.add( 'marketplace-suggestion-container-cta' );
if ( url && linkText ) {
var linkoutElement = renderLinkout( context, product, promoted, slug, url, linkText, linkIsButton );
container.appendChild( linkoutElement );
}
if ( allowDismiss ) {
container.appendChild( renderDismissButton( context, product, promoted, url, slug ) );
}
return container;
}
// Render a "list item" style suggestion.
// These are used in onboarding style contexts, e.g. products list empty state.
function renderListItem( context, product, promoted, slug, iconUrl, title, copy, url, linkText, linkIsButton, allowDismiss ) {
var container = document.createElement( 'div' );
container.classList.add( 'marketplace-suggestion-container' );
container.dataset.suggestionSlug = slug;
var icon = renderSuggestionIcon( iconUrl );
if ( icon ) {
container.appendChild( icon );
}
container.appendChild(
renderSuggestionContent( slug, title, copy )
);
container.appendChild(
renderSuggestionCTA( context, product, promoted, slug, url, linkText, linkIsButton, allowDismiss )
);
return container;
}
// Filter suggestion data to remove less-relevant suggestions.
function getRelevantPromotions( marketplaceSuggestionsApiData, displayContext ) {
// select based on display context
var promos = _.filter( marketplaceSuggestionsApiData, function( promo ) {
if ( _.isArray( promo.context ) ) {
return _.contains( promo.context, displayContext );
}
return ( displayContext === promo.context );
} );
// hide promos the user has dismissed
promos = _.filter( promos, function( promo ) {
return ! _.contains( marketplace_suggestions.dismissed_suggestions, promo.slug );
} );
// hide promos for things the user already has installed
promos = _.filter( promos, function( promo ) {
return ! _.contains( marketplace_suggestions.active_plugins, promo.product );
} );
// hide promos that are not applicable based on user's installed extensions
promos = _.filter( promos, function( promo ) {
if ( ! promo['show-if-active'] ) {
// this promotion is relevant to all
return true;
}
// if the user has any of the prerequisites, show the promo
return ( _.intersection( marketplace_suggestions.active_plugins, promo['show-if-active'] ).length > 0 );
} );
return promos;
}
// Show and hide page elements dependent on suggestion state.
function hidePageElementsForSuggestionState( usedSuggestionsContexts ) {
var showingEmptyStateSuggestions = _.intersection(
usedSuggestionsContexts,
[ 'products-list-empty-body', 'orders-list-empty-body' ]
).length > 0;
// Streamline onboarding UI if we're in 'empty state' welcome mode.
if ( showingEmptyStateSuggestions ) {
$( '#screen-meta-links' ).hide();
$( '#wpfooter' ).hide();
}
// Hide the header & footer, they don't make sense without specific promotion content
if ( ! showingEmptyStateSuggestions ) {
$( '.marketplace-suggestions-container[data-marketplace-suggestions-context="products-list-empty-header"]' ).hide();
$( '.marketplace-suggestions-container[data-marketplace-suggestions-context="products-list-empty-footer"]' ).hide();
$( '.marketplace-suggestions-container[data-marketplace-suggestions-context="orders-list-empty-header"]' ).hide();
$( '.marketplace-suggestions-container[data-marketplace-suggestions-context="orders-list-empty-footer"]' ).hide();
}
}
// Streamline the product edit suggestions tab dependent on what's visible.
function tidyProductEditMetabox() {
var productMetaboxSuggestions = $(
'.marketplace-suggestions-container[data-marketplace-suggestions-context="product-edit-meta-tab-body"]'
).children();
if ( 0 >= productMetaboxSuggestions.length ) {
var metaboxSuggestionsUISelector =
'.marketplace-suggestions-container[data-marketplace-suggestions-context="product-edit-meta-tab-body"]';
metaboxSuggestionsUISelector +=
', .marketplace-suggestions-container[data-marketplace-suggestions-context="product-edit-meta-tab-header"]';
metaboxSuggestionsUISelector +=
', .marketplace-suggestions-container[data-marketplace-suggestions-context="product-edit-meta-tab-footer"]';
$( metaboxSuggestionsUISelector ).fadeOut( {
complete: function() {
$( '.marketplace-suggestions-metabox-nosuggestions-placeholder' ).fadeIn();
}
} );
}
}
function addManageSuggestionsTracksHandler() {
$( 'a.marketplace-suggestion-manage-link' ).on( 'click', function() {
window.wcTracks.recordEvent( 'marketplace_suggestions_manage_clicked' );
} );
}
function isContextHiddenOnPageLoad( context ) {
// Some suggestions are not visible on page load;
// e.g. the user reveals them by selecting a tab.
var revealableSuggestionsContexts = [
'product-edit-meta-tab-header',
'product-edit-meta-tab-body',
'product-edit-meta-tab-footer'
];
return _.includes( revealableSuggestionsContexts, context );
}
// track the current product data tab to avoid over-tracking suggestions
var currentTab = false;
// Render suggestion data in appropriate places in UI.
function displaySuggestions( marketplaceSuggestionsApiData ) {
var usedSuggestionsContexts = [];
// iterate over all suggestions containers, rendering promos
$( '.marketplace-suggestions-container' ).each( function() {
// determine the context / placement we're populating
var context = this.dataset.marketplaceSuggestionsContext;
// find promotions that target this context
var promos = getRelevantPromotions( marketplaceSuggestionsApiData, context );
// shuffle/randomly select five suggestions to display
var suggestionsToDisplay = _.sample( promos, 5 );
// render the promo content
for ( var i in suggestionsToDisplay ) {
var linkText = suggestionsToDisplay[ i ]['link-text'];
var linkoutIsButton = true;
if ( suggestionsToDisplay[ i ]['link-text'] ) {
linkText = suggestionsToDisplay[ i ]['link-text'];
linkoutIsButton = false;
}
// dismiss is allowed by default
var allowDismiss = true;
if ( suggestionsToDisplay[ i ]['allow-dismiss'] === false ) {
allowDismiss = false;
}
var content = renderListItem(
context,
suggestionsToDisplay[ i ].product,
suggestionsToDisplay[ i ].promoted,
suggestionsToDisplay[ i ].slug,
suggestionsToDisplay[ i ].icon,
suggestionsToDisplay[ i ].title,
suggestionsToDisplay[ i ].copy,
suggestionsToDisplay[ i ].url,
linkText,
linkoutIsButton,
allowDismiss
);
$( this ).append( content );
$( this ).addClass( 'showing-suggestion' );
usedSuggestionsContexts.push( context );
if ( ! isContextHiddenOnPageLoad( context ) ) {
// Fire 'displayed' tracks events for immediately visible suggestions.
window.wcTracks.recordEvent( 'marketplace_suggestion_displayed', {
suggestion_slug: suggestionsToDisplay[ i ].slug,
context: context,
product: suggestionsToDisplay[ i ].product || '',
promoted: suggestionsToDisplay[ i ].promoted || '',
target: suggestionsToDisplay[ i ].url || ''
} );
}
}
// Track when suggestions are displayed (and not already visible).
$( 'ul.product_data_tabs li.marketplace-suggestions_options a' ).on( 'click', function( e ) {
e.preventDefault();
if ( '#marketplace_suggestions' === currentTab ) {
return;
}
if ( ! isContextHiddenOnPageLoad( context ) ) {
// We've already fired 'displayed' event above.
return;
}
for ( var i in suggestionsToDisplay ) {
window.wcTracks.recordEvent( 'marketplace_suggestion_displayed', {
suggestion_slug: suggestionsToDisplay[ i ].slug,
context: context,
product: suggestionsToDisplay[ i ].product || '',
promoted: suggestionsToDisplay[ i ].promoted || '',
target: suggestionsToDisplay[ i ].url || ''
} );
}
} );
} );
hidePageElementsForSuggestionState( usedSuggestionsContexts );
tidyProductEditMetabox();
}
if ( marketplace_suggestions.suggestions_data ) {
displaySuggestions( marketplace_suggestions.suggestions_data );
// track the current product data tab to avoid over-reporting suggestion views
$( 'ul.product_data_tabs' ).on( 'click', 'li a', function( e ) {
e.preventDefault();
currentTab = $( this ).attr( 'href' );
} );
}
addManageSuggestionsTracksHandler();
});
})( jQuery, marketplace_suggestions, ajaxurl );
@@ -0,0 +1 @@
!function(t,e,s){t(function(){if(void 0!==e){window.wcTracks=window.wcTracks||{},window.wcTracks.recordEvent=window.wcTracks.recordEvent||function(){};var a,n,o=!1;e.suggestions_data&&(a=e.suggestions_data,n=[],t(".marketplace-suggestions-container").each(function(){var s=this.dataset.marketplaceSuggestionsContext,i=function(t,s){var a=_.filter(t,function(t){return _.isArray(t.context)?_.contains(t.context,s):s===t.context});return a=_.filter(a,function(t){return!_.contains(e.dismissed_suggestions,t.slug)}),a=_.filter(a,function(t){return!_.contains(e.active_plugins,t.product)}),a=_.filter(a,function(t){return!t["show-if-active"]||_.intersection(e.active_plugins,t["show-if-active"]).length>0})}(a,s),r=_.sample(i,5);for(var d in r){var l=r[d]["link-text"],p=!0;r[d]["link-text"]&&(l=r[d]["link-text"],p=!1);var g=!0;!1===r[d]["allow-dismiss"]&&(g=!1);var m=c(s,r[d].product,r[d].promoted,r[d].slug,r[d].icon,r[d].title,r[d].copy,r[d].url,l,p,g);t(this).append(m),t(this).addClass("showing-suggestion"),n.push(s),u(s)||window.wcTracks.recordEvent("marketplace_suggestion_displayed",{suggestion_slug:r[d].slug,context:s,product:r[d].product||"",promoted:r[d].promoted||"",target:r[d].url||""})}t("ul.product_data_tabs li.marketplace-suggestions_options a").on("click",function(t){if(t.preventDefault(),"#marketplace_suggestions"!==o&&u(s))for(var e in r)window.wcTracks.recordEvent("marketplace_suggestion_displayed",{suggestion_slug:r[e].slug,context:s,product:r[e].product||"",promoted:r[e].promoted||"",target:r[e].url||""})})}),function(e){var s=_.intersection(e,["products-list-empty-body","orders-list-empty-body"]).length>0;s&&(t("#screen-meta-links").hide(),t("#wpfooter").hide()),s||(t('.marketplace-suggestions-container[data-marketplace-suggestions-context="products-list-empty-header"]').hide(),t('.marketplace-suggestions-container[data-marketplace-suggestions-context="products-list-empty-footer"]').hide(),t('.marketplace-suggestions-container[data-marketplace-suggestions-context="orders-list-empty-header"]').hide(),t('.marketplace-suggestions-container[data-marketplace-suggestions-context="orders-list-empty-footer"]').hide())}(n),d(),t("ul.product_data_tabs").on("click","li a",function(e){e.preventDefault(),o=t(this).attr("href")})),t("a.marketplace-suggestion-manage-link").on("click",function(){window.wcTracks.recordEvent("marketplace_suggestions_manage_clicked")})}function i(a,n,o,i,r){var c=document.createElement("a");return c.classList.add("suggestion-dismiss"),c.setAttribute("title",e.i18n_marketplace_suggestions_dismiss_tooltip),c.setAttribute("href","#"),c.onclick=function(c){c.preventDefault(),function(a,n,o,i,r){if(t("[data-suggestion-slug="+r+"]").fadeOut(function(){t(this).remove(),d()}),jQuery.post(s,{action:"woocommerce_add_dismissed_marketplace_suggestion",_wpnonce:e.dismiss_suggestion_nonce,slug:r}),_.contains(["products-list-inline"],a)){var c="woocommerce_snooze_suggestions__"+a;Cookies.set(c,"true",{expires:2});var u="woocommerce_dismissed_suggestions__"+a,l=parseInt(Cookies.get(u),10)||0;Cookies.set(u,l+1,{expires:31})}window.wcTracks.recordEvent("marketplace_suggestion_dismissed",{suggestion_slug:r,context:a,product:n||"",promoted:o||"",target:i||""})}(a,n,o,i,r)},c}function r(t,s,a,n,o,i,r){var c=document.createElement("a"),d=function(t,s){var a=e.in_app_purchase_params;a.utm_source="unknown",a.utm_campaign="marketplacesuggestions",a.utm_medium="product";var n=_.findKey({productstable:["products-list-inline"],productsempty:["products-list-empty-header","products-list-empty-footer","products-list-empty-body"],ordersempty:["orders-list-empty-header","orders-list-empty-footer","orders-list-empty-body"],editproduct:["product-edit-meta-tab-header","product-edit-meta-tab-footer","product-edit-meta-tab-body"]},function(e){return _.contains(e,t)});return n&&(a.utm_source=n),s+"?"+jQuery.param(a)}(t,o);c.setAttribute("href",d);if(_.includes(["product-edit-meta-tab-header","product-edit-meta-tab-footer","product-edit-meta-tab-body","products-list-empty-footer"],t)&&c.setAttribute("target","blank"),c.textContent=i,c.onclick=function(){window.wcTracks.recordEvent("marketplace_suggestion_clicked",{suggestion_slug:n,context:t,product:s||"",promoted:a||"",target:o||""})},r)c.classList.add("button");else{c.classList.add("linkout");var u=document.createElement("span");u.classList.add("dashicons","dashicons-external"),c.appendChild(u)}return c}function c(t,s,a,n,o,c,d,u,l,p,g){var m=document.createElement("div");m.classList.add("marketplace-suggestion-container"),m.dataset.suggestionSlug=n;var _=function(t){if(!t)return null;var e=document.createElement("img");return e.src=t,e.classList.add("marketplace-suggestion-icon"),e}(o);return _&&m.appendChild(_),m.appendChild(function(t,s,a){var n=document.createElement("div");if(n.classList.add("marketplace-suggestion-container-content"),s){var o=document.createElement("h4");o.textContent=s,n.appendChild(o)}if(a){var i=document.createElement("p");i.textContent=a,n.appendCLine truncated
@@ -0,0 +1,70 @@
/* global woocommerce_admin_meta_boxes_coupon */
jQuery(function( $ ) {
/**
* Coupon actions
*/
var wc_meta_boxes_coupon_actions = {
/**
* Initialize variations actions
*/
init: function() {
$( 'select#discount_type' )
.on( 'change', this.type_options )
.trigger( 'change' );
this.insert_generate_coupon_code_button();
$( '.button.generate-coupon-code' ).on( 'click', this.generate_coupon_code );
},
/**
* Show/hide fields by coupon type options
*/
type_options: function() {
// Get value
var select_val = $( this ).val();
if ( 'percent' === select_val ) {
$( '#coupon_amount' ).removeClass( 'wc_input_price' ).addClass( 'wc_input_decimal' );
} else {
$( '#coupon_amount' ).removeClass( 'wc_input_decimal' ).addClass( 'wc_input_price' );
}
if ( select_val !== 'fixed_cart' ) {
$( '.limit_usage_to_x_items_field' ).show();
} else {
$( '.limit_usage_to_x_items_field' ).hide();
}
},
/**
* Insert generate coupon code buttom HTML.
*/
insert_generate_coupon_code_button: function() {
$( '.post-type-shop_coupon' ).find( '#title' ).after(
'<a href="#" class="button generate-coupon-code">' + woocommerce_admin_meta_boxes_coupon.generate_button_text + '</a>'
);
},
/**
* Generate a random coupon code
*/
generate_coupon_code: function( e ) {
e.preventDefault();
var $coupon_code_field = $( '#title' ),
$coupon_code_label = $( '#title-prompt-text' ),
$result = '';
for ( var i = 0; i < woocommerce_admin_meta_boxes_coupon.char_length; i++ ) {
$result += woocommerce_admin_meta_boxes_coupon.characters.charAt(
Math.floor( Math.random() * woocommerce_admin_meta_boxes_coupon.characters.length )
);
}
$result = woocommerce_admin_meta_boxes_coupon.prefix + $result + woocommerce_admin_meta_boxes_coupon.suffix;
$coupon_code_field.trigger( 'focus' ).val( $result );
$coupon_code_label.addClass( 'screen-reader-text' );
}
};
wc_meta_boxes_coupon_actions.init();
});
@@ -0,0 +1 @@
jQuery(function(e){({init:function(){e("select#discount_type").on("change",this.type_options).trigger("change"),this.insert_generate_coupon_code_button(),e(".button.generate-coupon-code").on("click",this.generate_coupon_code)},type_options:function(){var o=e(this).val();"percent"===o?e("#coupon_amount").removeClass("wc_input_price").addClass("wc_input_decimal"):e("#coupon_amount").removeClass("wc_input_decimal").addClass("wc_input_price"),"fixed_cart"!==o?e(".limit_usage_to_x_items_field").show():e(".limit_usage_to_x_items_field").hide()},insert_generate_coupon_code_button:function(){e(".post-type-shop_coupon").find("#title").after('<a href="#" class="button generate-coupon-code">'+woocommerce_admin_meta_boxes_coupon.generate_button_text+"</a>")},generate_coupon_code:function(o){o.preventDefault();for(var t=e("#title"),n=e("#title-prompt-text"),_="",c=0;c<woocommerce_admin_meta_boxes_coupon.char_length;c++)_+=woocommerce_admin_meta_boxes_coupon.characters.charAt(Math.floor(Math.random()*woocommerce_admin_meta_boxes_coupon.characters.length));_=woocommerce_admin_meta_boxes_coupon.prefix+_+woocommerce_admin_meta_boxes_coupon.suffix,t.trigger("focus").val(_),n.addClass("screen-reader-text")}}).init()});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
jQuery(function(e){window.wcTracks=window.wcTracks||{},window.wcTracks.recordEvent=window.wcTracks.recordEvent||function(){};var o={states:null,init:function(){"undefined"!=typeof woocommerce_admin_meta_boxes_order&&"undefined"!=typeof woocommerce_admin_meta_boxes_order.countries&&(this.states=JSON.parse(woocommerce_admin_meta_boxes_order.countries.replace(/&quot;/g,'"'))),e(".js_field-country").selectWoo().on("change",this.change_country),e(".js_field-country").trigger("change",[!0]),e(document.body).on("change","select.js_field-state",this.change_state),e("#woocommerce-order-actions input, #woocommerce-order-actions a").on("click",function(){window.onbeforeunload=""}),e("a.edit_address").on("click",this.edit_address),e("a.billing-same-as-shipping").on("click",this.copy_billing_to_shipping),e("a.load_customer_billing").on("click",this.load_billing),e("a.load_customer_shipping").on("click",this.load_shipping),e("#customer_user").on("change",this.change_customer_user)},change_country:function(t,r){if(void 0===r&&(r=!1),null!==o.states){var a,i=e(this),n=i.val(),d=i.parents("div.edit_address").find(":input.js_field-state"),c=d.parent(),_=d.val(),m=d.attr("name"),s=d.attr("id"),l=i.data("woocommerce.stickState-"+n)?i.data("woocommerce.stickState-"+n):_,u=d.attr("placeholder");if(r&&i.data("woocommerce.stickState-"+n,l),c.show().find(".select2-container").remove(),e.isEmptyObject(o.states[n]))a=e('<input type="text" />').prop("id",s).prop("name",m).prop("placeholder",u).addClass("js_field-state").val(_),d.replaceWith(a);else{var p=o.states[n],w=e('<option value=""></option>').text(woocommerce_admin_meta_boxes_order.i18n_select_state_text);a=e("<select></select>").prop("id",s).prop("name",m).prop("placeholder",u).addClass("js_field-state select short").append(w),e.each(p,function(o){var t=e("<option></option>").prop("value",o).text(p[o]);o===_&&t.prop("selected"),a.append(t)}),a.val(l),d.replaceWith(a),a.show().selectWoo().hide().trigger("change")}e(document.body).trigger("contry-change.woocommerce",[n,e(this).closest("div")]),e(document.body).trigger("country-change.woocommerce",[n,e(this).closest("div")])}},change_state:function(){var o=e(this),t=o.val(),r=o.parents("div.edit_address").find(":input.js_field-country"),a=r.val();r.data("woocommerce.stickState-"+a,t)},init_tiptip:function(){e("#tiptip_holder").removeAttr("style"),e("#tiptip_arrow").removeAttr("style"),e(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200,keepAlive:!0})},edit_address:function(o){o.preventDefault();var t=e(this),r=t.closest(".order_data_column"),a=r.find("div.edit_address"),i=r.find("div.address"),n=a.find(".js_field-country"),d=a.find(".js_field-state"),c=Boolean(a.find('input[name^="_billing_"]').length);i.hide(),t.parent().find("a").toggle(),n.val()||(n.val(woocommerce_admin_meta_boxes_order.default_country).trigger("change"),d.val(woocommerce_admin_meta_boxes_order.default_state).trigger("change")),a.show();var _=c?"order_edit_billing_address_click":"order_edit_shipping_address_click";window.wcTracks.recordEvent(_,{order_id:woocommerce_admin_meta_boxes.post_id,status:e("#order_status").val()})},change_customer_user:function(){e("#_billing_country").val()||(e("a.edit_address").trigger("click"),o.load_billing(!0),o.load_shipping(!0))},load_billing:function(o){if(!0===o||window.confirm(woocommerce_admin_meta_boxes.load_billing)){var t=e("#customer_user").val();if(!t)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var r={user_id:t,action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};e(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),e.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:r,type:"POST",success:function(o){o&&o.billing&&e.each(o.billing,function(o,t){e(":input#_billing_"+o).val(t).trigger("change")}),e("div.edit_address").unblock()}})}return!1},load_shipping:function(o){if(!0===o||window.confirm(woocommerce_admin_meta_boxes.load_shipping)){var t=e("#customer_user").val();if(!t)return window.alert(woocommerce_admin_meta_boxes.no_customer_selected),!1;var r={user_id:t,action:"woocommerce_get_customer_details",security:woocommerce_admin_meta_boxes.get_customer_details_nonce};e(this).closest("div.edit_address").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),e.ajax({url:woocommerce_admin_meta_boxes.ajax_url,data:r,type:"POST",success:function(o){o&&o.billing&&e.each(o.shipping,function(o,t){e(":input#_shipping_"+o).val(t).trigger("change")}),e("div.edit_address").unblock()}})}return!1},copy_billing_to_shipping:function(){return window.confirm(woocommerce_admin_meta_boxes.copy_billing)&&e('.order_data_column :input[name^="_billing_"]').each(function(){var o=e(this).attr("name");o=o.replace("_billing_","_shipping_"),e(":input#"+o).val(e(this).val()).trigger("change")}),!1}},t={init:function(){this.stupidtable.init(),e("#woocommerce-order-items").on("click","buttoLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
jQuery(function(a){"use strict";var e={init:function(){a("#variable_product_options").on("change","input.variable_is_downloadable",this.variable_is_downloadable).on("change","input.variable_is_virtual",this.variable_is_virtual).on("change","input.variable_manage_stock",this.variable_manage_stock).on("click","button.notice-dismiss",this.notice_dismiss).on("click","h3 .sort",this.set_menu_order).on("click","button.add_price_for_variations",this.open_modal_to_set_variations_price).on("reload",this.reload).on("click","button.create-variations",this.create_variations),a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock").trigger("change"),a("#woocommerce-product-data").on("woocommerce_variations_loaded",this.variations_loaded),a(document.body).on("keyup",".wc_input_variations_price",this.maybe_enable_button_to_add_price_to_variations)},create_variations:function(e){if(a(this).hasClass("disabled"))e.preventDefault();else{var i=a(".woocommerce_variation_new_attribute_data");a("#variable_product_options").block({message:null,overlayCSS:{background:"#fff",opacity:.6}});var o=i.find("input, select, textarea"),t={post_id:woocommerce_admin_meta_boxes.post_id,product_type:a("#product-type").val(),data:o.serialize(),action:"woocommerce_add_attributes_and_variations",security:woocommerce_admin_meta_boxes.add_attributes_and_variations};a.post(woocommerce_admin_meta_boxes.ajax_url,t,function(e){if(e.error)window.alert(e.error),a("#variable_product_options").unblock();else if(e){var i=window.location.toString();i=i.replace("post-new.php?","post.php?post="+woocommerce_admin_meta_boxes.post_id+"&action=edit&"),a.get(i,function(e){a("#variable_product_options").unblock(),a("#variable_product_options_inner").replaceWith(a(e).find("#variable_product_options_inner")),a("#variable_product_options").trigger("reload"),a("#product_attributes > .product_attributes").replaceWith(a(e).find("#product_attributes > .product_attributes"))})}})}},reload:function(){o.load_variations(1).then(o.show_hide_variation_empty_state),t.set_paginav(0)},variable_is_downloadable:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").hide(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".show_if_variation_downloadable").show()},variable_is_virtual:function(){a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").show(),a(this).is(":checked")&&a(this).closest(".woocommerce_variation").find(".hide_if_variation_virtual").hide()},maybe_enable_button_to_add_price_to_variations:function(){var e=parseInt(a(".wc_input_variations_price").val(),10);isNaN(e)?a(".add_variations_price_button").prop("disabled",!0):a(".add_variations_price_button").prop("disabled",!1)},variable_manage_stock:function(){a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").hide(),a(this).closest(".woocommerce_variation").find(".variable_stock_status").show(),a(this).is(":checked")&&(a(this).closest(".woocommerce_variation").find(".show_if_variation_manage_stock").show(),a(this).closest(".woocommerce_variation").find(".variable_stock_status").hide()),a("input#_manage_stock:checked").length&&a(this).closest(".woocommerce_variation").find(".variable_stock_status").hide()},notice_dismiss:function(){a(this).closest("div.notice").remove()},variations_loaded:function(i,o){o=o||!1;var t=a("#woocommerce-product-data");o||(a("input.variable_is_downloadable, input.variable_is_virtual, input.variable_manage_stock",t).trigger("change"),a(".woocommerce_variation",t).each(function(e,i){var o=a(i),t=a(".sale_price_dates_from",o).val(),n=a(".sale_price_dates_to",o).val();""===t&&""===n||a("a.sale_schedule",o).trigger("click")}),a(".woocommerce_variations .variation-needs-update",t).removeClass("variation-needs-update"),a("button.cancel-variation-changes, button.save-variation-changes",t).attr("disabled","disabled")),a("#tiptip_holder").removeAttr("style"),a("#tiptip_arrow").removeAttr("style"),a(".woocommerce_variations .tips, .woocommerce_variations .help_tip, .woocommerce_variations .woocommerce-help-tip, .toolbar-variations-defaults .woocommerce-help-tip",t).tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200}),a(".sale_price_dates_fields",t).find("input").datepicker({defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0,onSelect:function(){var e=a(this).is(".sale_price_dates_from")?"minDate":"maxDate",i=a(this).closest(".sale_price_dates_fields").find("input"),o=a(this).datepicker("getDate");i.not(this).datepicker("option",e,o),a(this).trigger("change")}}),a(".woocommerce_variations",t).sortable({items:".woocommerce_variation",cursor:"move",axis:"y",handle:".sort",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,stop:function(){e.variation_row_indexes()}}),a(document.body).trigger("wc-enhanced-select-init")},set_variations_price:function(){var e=a(".wc_input_variations_price").val(),i=a("select#product-tLine truncated
File diff suppressed because it is too large. Load diff
@@ -0,0 +1 @@
jQuery(function(t){let e=!1;function o(e){var o=t("select#product-type").val(),a=t("input#_virtual:checked").length,i=t("input#_downloadable:checked").length,r=".hide_if_downloadable, .hide_if_virtual",c=".show_if_downloadable, .show_if_virtual";t.each(woocommerce_admin_meta_boxes.product_types,function(t,e){r=r+", .hide_if_"+e,c=c+", .show_if_"+e}),t(r,e).show(),t(c,e).hide(),i&&t(".show_if_downloadable",e).show(),a&&t(".show_if_virtual",e).show(),t(".show_if_"+o,e).show(),i&&t(".hide_if_downloadable",e).hide(),a&&t(".hide_if_virtual",e).hide(),t(".hide_if_"+o,e).hide()}function a(){o(),t("input#_manage_stock").trigger("change"),t(".woocommerce_options_panel").each(function(){var e=t(this).children(".options_group");if(0!==e.length&&e.filter(function(){return"none"===t(this).css("display")}).length===e.length){var o=t(this).prop("id");t(".product_data_tabs").find('li a[href="#'+o+'"]').parent().hide()}})}function i(e){var o=t(e).next().is(".hasDatepicker")?"minDate":"maxDate",a="minDate"===o?t(e).next():t(e).prev(),i=t(e).datepicker("getDate");t(a).datepicker("option",o,i),t(e).trigger("change")}t(window).on("beforeunload",function(){e=!0}),t(function(){t('[id$="-all"] > ul.categorychecklist').each(function(){var e=t(this),o=e.find(":checked").first();if(o.length){var a=e.find("input").position().top,i=o.position().top;e.closest(".tabs-panel").scrollTop(i-a+5)}})}),t("#upsell_product_data").on("keypress",function(t){if(13===t.keyCode)return!1}),t("body").hasClass("wc-wp-version-gte-55")?t(".type_box").appendTo("#woocommerce-product-data .hndle"):t(".type_box").appendTo("#woocommerce-product-data .hndle span"),t(function(){var e=t("#woocommerce-product-data");e.find(".hndle").off("click.postboxes"),e.on("click",".hndle",function(o){t(o.target).filter("input, option, label, select").length||(e.hasClass("closed")?e.removeClass("closed"):e.addClass("closed"))})}),t("#catalog-visibility").find(".edit-catalog-visibility").on("click",function(){return t("#catalog-visibility-select").is(":hidden")&&(t("#catalog-visibility-select").slideDown("fast"),t(this).hide()),!1}),t("#catalog-visibility").find(".save-post-visibility").on("click",function(){t("#catalog-visibility-select").slideUp("fast"),t("#catalog-visibility").find(".edit-catalog-visibility").show();var e=t("input[name=_visibility]:checked").attr("data-label");return t("input[name=_featured]").is(":checked")&&(e=e+", "+woocommerce_admin_meta_boxes.featured_label,t("input[name=_featured]").attr("checked","checked")),t("#catalog-visibility-display").text(e),!1}),t("#catalog-visibility").find(".cancel-post-visibility").on("click",function(){t("#catalog-visibility-select").slideUp("fast"),t("#catalog-visibility").find(".edit-catalog-visibility").show();var e=t("#current_visibility").val(),o=t("#current_featured").val();t("input[name=_visibility]").prop("checked",!1),t("input[name=_visibility][value="+e+"]").attr("checked","checked");var a=t("input[name=_visibility]:checked").attr("data-label");return"yes"===o?(a=a+", "+woocommerce_admin_meta_boxes.featured_label,t("input[name=_featured]").attr("checked","checked")):t("input[name=_featured]").prop("checked",!1),t("#catalog-visibility-display").text(a),!1}),t("select#product-type").on("change",function(){var e,o=t(this).val();"variable"===o?(t("input#_manage_stock").trigger("change"),t("input#_downloadable").prop("checked",!1),t("input#_virtual").prop("checked",!1)):"grouped"===o?(t("input#_downloadable").prop("checked",!1),t("input#_virtual").prop("checked",!1)):"external"===o&&(t("input#_downloadable").prop("checked",!1),t("input#_virtual").prop("checked",!1)),a(),e=function(t){switch(t){case"simple":return woocommerce_admin_meta_boxes.i18n_product_simple_tip;case"grouped":return woocommerce_admin_meta_boxes.i18n_product_grouped_tip;case"external":return woocommerce_admin_meta_boxes.i18n_product_external_tip;case"variable":return woocommerce_admin_meta_boxes.i18n_product_variable_tip;default:return woocommerce_admin_meta_boxes.i18n_product_other_tip}}(o),t("#tiptip_holder").removeAttr("style"),t("#tiptip_arrow").removeAttr("style"),t(".woocommerce-product-type-tip").attr("tabindex","0").attr("aria-label",t("<div />").html(e).text()).tipTip({attribute:"data-tip",content:e,fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}),t("ul.wc-tabs li:visible").eq(0).find("a").trigger("click"),t(document.body).trigger("woocommerce-product-type-change",o,t(this))}).trigger("change"),t("input#_downloadable").on("change",function(){a()}),t("input#_virtual").on("change",function(){a(),t(this).is(":checked")&&t(".shipping_options.shipping_tab").hasClass("active")&&t(".general_options.general_tab > a").trigger("click")}),t(".sale_price_dates_fields").each(function(){var e=t(this),o=!1,a=e.closest("div, table");e.find("input").each(function(){""!==t(this).val()&&(o=!0)}),o?(a.find(".sale_schedule").hide(),a.find(".sale_price_dates_fields").show()):(a.find(".sale_schedule").show(),a.find(".sale_price_dates_fields").hide())}),t("#woocommeLine truncated
@@ -0,0 +1,195 @@
jQuery( function ( $ ) {
/**
* Function to check if the attribute and variation fields are empty.
*/
jQuery.is_attribute_or_variation_empty = function (
attributes_and_variations_data
) {
var has_empty_fields = false;
attributes_and_variations_data.each( function () {
var $this = $( this );
// Check if the field is checkbox or a search field.
if (
$this.hasClass( 'checkbox' ) ||
$this.filter( '[class*=search__field]' ).length
) {
return;
}
var is_empty = $this.is( 'select' )
? $this.find( ':selected' ).length === 0
: ! $this.val();
if ( is_empty ) {
has_empty_fields = true;
}
} );
return has_empty_fields;
};
/**
* Function to maybe disable the save button.
*/
jQuery.maybe_disable_save_button = function () {
var $tab;
var $save_button;
if (
$( '.woocommerce_variation_new_attribute_data' ).is( ':visible' )
) {
$tab = $( '.woocommerce_variation_new_attribute_data' );
$save_button = $( 'button.create-variations' );
} else {
var $tab = $( '.product_attributes' );
var $save_button = $( 'button.save_attributes' );
}
var attributes_and_variations_data = $tab.find(
'input, select, textarea'
);
if (
jQuery.is_attribute_or_variation_empty(
attributes_and_variations_data
)
) {
if ( ! $save_button.hasClass( 'disabled' ) ) {
$save_button.addClass( 'disabled' );
$save_button.attr( 'aria-disabled', true );
}
} else {
$save_button.removeClass( 'disabled' );
$save_button.removeAttr( 'aria-disabled' );
}
};
// Run tipTip
function runTipTip() {
// Remove any lingering tooltips
$( '#tiptip_holder' ).removeAttr( 'style' );
$( '#tiptip_arrow' ).removeAttr( 'style' );
$( '.tips' ).tipTip( {
attribute: 'data-tip',
fadeIn: 50,
fadeOut: 50,
delay: 200,
keepAlive: true,
} );
}
runTipTip();
$( '.save_attributes' ).tipTip( {
content: function () {
return $( '.save_attributes' ).hasClass( 'disabled' )
? woocommerce_admin_meta_boxes.i18n_save_attribute_variation_tip
: '';
},
fadeIn: 50,
fadeOut: 50,
delay: 200,
keepAlive: true,
} );
$( '.create-variations' ).tipTip( {
content: function () {
return $( '.create-variations' ).hasClass( 'disabled' )
? woocommerce_admin_meta_boxes.i18n_save_attribute_variation_tip
: '';
},
fadeIn: 50,
fadeOut: 50,
delay: 200,
keepAlive: true,
} );
$( '.wc-metaboxes-wrapper' ).on( 'click', '.wc-metabox > h3', function () {
var metabox = $( this ).parent( '.wc-metabox' );
if ( metabox.hasClass( 'closed' ) ) {
metabox.removeClass( 'closed' );
} else {
metabox.addClass( 'closed' );
}
if ( metabox.hasClass( 'open' ) ) {
metabox.removeClass( 'open' );
} else {
metabox.addClass( 'open' );
}
} );
// Tabbed Panels
$( document.body )
.on( 'wc-init-tabbed-panels', function () {
$( 'ul.wc-tabs' ).show();
$( 'ul.wc-tabs a' ).on( 'click', function ( e ) {
e.preventDefault();
var panel_wrap = $( this ).closest( 'div.panel-wrap' );
$( 'ul.wc-tabs li', panel_wrap ).removeClass( 'active' );
$( this ).parent().addClass( 'active' );
$( 'div.panel', panel_wrap ).hide();
$( $( this ).attr( 'href' ) ).show( 0, function () {
$( this ).trigger( 'woocommerce_tab_shown' );
} );
} );
$( 'div.panel-wrap' ).each( function () {
$( this )
.find( 'ul.wc-tabs li' )
.eq( 0 )
.find( 'a' )
.trigger( 'click' );
} );
} )
.trigger( 'wc-init-tabbed-panels' );
// Date Picker
$( document.body )
.on( 'wc-init-datepickers', function () {
$( '.date-picker-field, .date-picker' ).datepicker( {
dateFormat: 'yy-mm-dd',
numberOfMonths: 1,
showButtonPanel: true,
} );
} )
.trigger( 'wc-init-datepickers' );
// Meta-Boxes - Open/close
$( '.wc-metaboxes-wrapper' )
.on( 'click', '.wc-metabox h3', function ( event ) {
// If the user clicks on some form input inside the h3, like a select list (for variations), the box should not be toggled
if ( $( event.target ).filter( ':input, option, .sort' ).length ) {
return;
}
$( this ).next( '.wc-metabox-content' ).stop().slideToggle();
} )
.on( 'click', '.expand_all', function () {
$( this )
.closest( '.wc-metaboxes-wrapper' )
.find( '.wc-metabox > .wc-metabox-content' )
.show();
return false;
} )
.on( 'click', '.close_all', function () {
$( this )
.closest( '.wc-metaboxes-wrapper' )
.find( '.wc-metabox > .wc-metabox-content' )
.hide();
return false;
} );
$( '.wc-metabox.closed' ).each( function () {
$( this ).find( '.wc-metabox-content' ).hide();
} );
$( '#product_attributes' ).on(
'change',
'select.attribute_values',
jQuery.maybe_disable_save_button
);
$( '#product_attributes, #variable_product_options' ).on(
'keyup',
'input, textarea',
jQuery.maybe_disable_save_button
);
// Maybe disable save buttons when editing products.
jQuery.maybe_disable_save_button();
} );
@@ -0,0 +1 @@
jQuery(function(e){jQuery.is_attribute_or_variation_empty=function(t){var a=!1;return t.each(function(){var t=e(this);t.hasClass("checkbox")||t.filter("[class*=search__field]").length||(t.is("select")?0===t.find(":selected").length:!t.val())&&(a=!0)}),a},jQuery.maybe_disable_save_button=function(){if(e(".woocommerce_variation_new_attribute_data").is(":visible"))t=e(".woocommerce_variation_new_attribute_data"),a=e("button.create-variations");else var t=e(".product_attributes"),a=e("button.save_attributes");var i=t.find("input, select, textarea");jQuery.is_attribute_or_variation_empty(i)?a.hasClass("disabled")||(a.addClass("disabled"),a.attr("aria-disabled",!0)):(a.removeClass("disabled"),a.removeAttr("aria-disabled"))},e("#tiptip_holder").removeAttr("style"),e("#tiptip_arrow").removeAttr("style"),e(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}),e(".save_attributes").tipTip({content:function(){return e(".save_attributes").hasClass("disabled")?woocommerce_admin_meta_boxes.i18n_save_attribute_variation_tip:""},fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}),e(".create-variations").tipTip({content:function(){return e(".create-variations").hasClass("disabled")?woocommerce_admin_meta_boxes.i18n_save_attribute_variation_tip:""},fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}),e(".wc-metaboxes-wrapper").on("click",".wc-metabox > h3",function(){var t=e(this).parent(".wc-metabox");t.hasClass("closed")?t.removeClass("closed"):t.addClass("closed"),t.hasClass("open")?t.removeClass("open"):t.addClass("open")}),e(document.body).on("wc-init-tabbed-panels",function(){e("ul.wc-tabs").show(),e("ul.wc-tabs a").on("click",function(t){t.preventDefault();var a=e(this).closest("div.panel-wrap");e("ul.wc-tabs li",a).removeClass("active"),e(this).parent().addClass("active"),e("div.panel",a).hide(),e(e(this).attr("href")).show(0,function(){e(this).trigger("woocommerce_tab_shown")})}),e("div.panel-wrap").each(function(){e(this).find("ul.wc-tabs li").eq(0).find("a").trigger("click")})}).trigger("wc-init-tabbed-panels"),e(document.body).on("wc-init-datepickers",function(){e(".date-picker-field, .date-picker").datepicker({dateFormat:"yy-mm-dd",numberOfMonths:1,showButtonPanel:!0})}).trigger("wc-init-datepickers"),e(".wc-metaboxes-wrapper").on("click",".wc-metabox h3",function(t){e(t.target).filter(":input, option, .sort").length||e(this).next(".wc-metabox-content").stop().slideToggle()}).on("click",".expand_all",function(){return e(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").show(),!1}).on("click",".close_all",function(){return e(this).closest(".wc-metaboxes-wrapper").find(".wc-metabox > .wc-metabox-content").hide(),!1}),e(".wc-metabox.closed").each(function(){e(this).find(".wc-metabox-content").hide()}),e("#product_attributes").on("change","select.attribute_values",jQuery.maybe_disable_save_button),e("#product_attributes, #variable_product_options").on("keyup","input, textarea",jQuery.maybe_disable_save_button),jQuery.maybe_disable_save_button()});
@@ -0,0 +1,90 @@
/*global woocommerce_network_orders */
(function( $, _, undefined ) {
if ( 'undefined' === typeof woocommerce_network_orders ) {
return;
}
var orders = [],
promises = [], // Track completion (pass or fail) of ajax requests.
deferred = [], // Tracks the ajax deferreds.
$tbody = $( document.getElementById( 'network-orders-tbody' ) ),
template = _.template( $( document.getElementById( 'network-orders-row-template') ).text() ),
$loadingIndicator = $( document.getElementById( 'woocommerce-network-order-table-loading' ) ),
$orderTable = $( document.getElementById( 'woocommerce-network-order-table' ) ),
$noneFound = $( document.getElementById( 'woocommerce-network-orders-no-orders' ) );
// No sites, so bail.
if ( ! woocommerce_network_orders.sites.length ) {
$loadingIndicator.removeClass( 'is-active' );
$orderTable.removeClass( 'is-active' );
$noneFound.addClass( 'is-active' );
return;
}
$.each( woocommerce_network_orders.sites, function( index, value ) {
promises[ index ] = $.Deferred();
deferred.push( $.ajax( {
url : woocommerce_network_orders.order_endpoint,
data: {
_wpnonce: woocommerce_network_orders.nonce,
network_orders: true,
blog_id: value
},
type: 'GET'
} ).success(function( response ) {
var orderindex;
for ( orderindex in response ) {
orders.push( response[ orderindex ] );
}
promises[ index ].resolve();
}).fail(function (){
promises[ index ].resolve();
}) );
} );
if ( promises.length > 0 ) {
$.when.apply( $, promises ).done( function() {
var orderindex,
currentOrder;
// Sort orders, newest first
orders.sort(function( a, b ) {
var adate, bdate;
adate = Date.parse( a.date_created_gmt );
bdate = Date.parse( b.date_created_gmt );
if ( adate === bdate ) {
return 0;
}
if ( adate < bdate ) {
return 1;
} else {
return -1;
}
});
if ( orders.length > 0 ) {
for ( orderindex in orders ) {
currentOrder = orders[ orderindex ];
$tbody.append( template( currentOrder ) );
}
$noneFound.removeClass( 'is-active' );
$loadingIndicator.removeClass( 'is-active' );
$orderTable.addClass( 'is-active' );
} else {
$noneFound.addClass( 'is-active' );
$loadingIndicator.removeClass( 'is-active' );
$orderTable.removeClass( 'is-active' );
}
} );
}
})( jQuery, _ );
@@ -0,0 +1 @@
!function(e,o,r){if("undefined"!=typeof woocommerce_network_orders){var t=[],n=[],s=[],a=e(document.getElementById("network-orders-tbody")),d=o.template(e(document.getElementById("network-orders-row-template")).text()),c=e(document.getElementById("woocommerce-network-order-table-loading")),i=e(document.getElementById("woocommerce-network-order-table")),m=e(document.getElementById("woocommerce-network-orders-no-orders"));if(!woocommerce_network_orders.sites.length)return c.removeClass("is-active"),i.removeClass("is-active"),void m.addClass("is-active");e.each(woocommerce_network_orders.sites,function(o,r){n[o]=e.Deferred(),s.push(e.ajax({url:woocommerce_network_orders.order_endpoint,data:{_wpnonce:woocommerce_network_orders.nonce,network_orders:!0,blog_id:r},type:"GET"}).success(function(e){var r;for(r in e)t.push(e[r]);n[o].resolve()}).fail(function(){n[o].resolve()}))}),n.length>0&&e.when.apply(e,n).done(function(){var e,o;if(t.sort(function(e,o){var r,t;return(r=Date.parse(e.date_created_gmt))===(t=Date.parse(o.date_created_gmt))?0:r<t?1:-1}),t.length>0){for(e in t)o=t[e],a.append(d(o));m.removeClass("is-active"),c.removeClass("is-active"),i.addClass("is-active")}else m.addClass("is-active"),c.removeClass("is-active"),i.removeClass("is-active")})}}(jQuery,_);
@@ -0,0 +1,35 @@
/*global woocommerce_admin_meta_boxes, wcTracks */
jQuery( document ).ready( ( $ ) => {
'use strict';
// Stand-in wcTracks.recordEvent in case Tracks is not available (for any reason).
window.wcTracks = window.wcTracks || {};
window.wcTracks.recordEvent = window.wcTracks.recordEvent || ( () => {} );
// Handle the "Details" container toggle.
$( '.woocommerce-order-attribution-details-toggle' )
.on( 'click', ( e ) => {
const $this = $( e.target ).closest( '.woocommerce-order-attribution-details-toggle');
const $container = $this.closest( '.order-attribution-metabox' )
.find( '.woocommerce-order-attribution-details-container' );
let toggle = '';
e.preventDefault();
$container.fadeToggle( 250 );
$this.find( '.toggle-text' ).toggle();
if ( $container.hasClass( 'closed' ) ) {
$this.attr( 'aria-expanded', 'true' );
toggle = 'opened';
} else {
$this.attr( 'aria-expanded', 'false' );
toggle = 'closed';
}
$container.toggleClass( 'closed' );
window.wcTracks.recordEvent( 'order_attribution_details_toggle', {
order_id: window.woocommerce_admin_meta_boxes.order_id,
details: toggle
} );
} );
} );
@@ -0,0 +1 @@
jQuery(document).ready(e=>{"use strict";window.wcTracks=window.wcTracks||{},window.wcTracks.recordEvent=window.wcTracks.recordEvent||(()=>{}),e(".woocommerce-order-attribution-details-toggle").on("click",o=>{const t=e(o.target).closest(".woocommerce-order-attribution-details-toggle"),r=t.closest(".order-attribution-metabox").find(".woocommerce-order-attribution-details-container");let d="";o.preventDefault(),r.fadeToggle(250),t.find(".toggle-text").toggle(),r.hasClass("closed")?(t.attr("aria-expanded","true"),d="opened"):(t.attr("aria-expanded","false"),d="closed"),r.toggleClass("closed"),window.wcTracks.recordEvent("order_attribution_details_toggle",{order_id:window.woocommerce_admin_meta_boxes.order_id,details:d})})});
@@ -0,0 +1,15 @@
/* global woocommerce_admin_product_editor */
jQuery( function ( $ ) {
$( function () {
var editorWrapper = $( '#postdivrich' );
if ( editorWrapper.length ) {
editorWrapper.addClass( 'postbox woocommerce-product-description' );
editorWrapper.prepend(
'<h2 class="postbox-header"><label>' +
woocommerce_admin_product_editor.i18n_description +
'</label></h2>'
);
}
} );
} );
@@ -0,0 +1 @@
jQuery(function(o){o(function(){var e=o("#postdivrich");e.length&&(e.addClass("postbox woocommerce-product-description"),e.prepend('<h2 class="postbox-header"><label>'+woocommerce_admin_product_editor.i18n_description+"</label></h2>"))})});
@@ -0,0 +1,80 @@
/*global ajaxurl */
/**
* Based on Simple Page Ordering by 10up (https://wordpress.org/plugins/simple-page-ordering/)
*
* Modified - products have no children (non hierarchical)
*/
jQuery( function( $ ) {
$( 'table.widefat tbody th, table.widefat tbody td' ).css( 'cursor', 'move' );
$( 'table.widefat tbody' ).sortable({
items: 'tr:not(.inline-edit-row)',
cursor: 'move',
axis: 'y',
containment: 'table.widefat',
scrollSensitivity: 40,
helper: function( event, ui ) {
ui.each( function() {
$( this ).width( $( this ).width() );
});
return ui;
},
start: function( event, ui ) {
ui.item.css( 'background-color', '#ffffff' );
ui.item.children( 'td, th' ).css( 'border-bottom-width', '0' );
ui.item.css( 'outline', '1px solid #dfdfdf' );
},
stop: function( event, ui ) {
ui.item.removeAttr( 'style' );
ui.item.children( 'td,th' ).css( 'border-bottom-width', '1px' );
},
update: function( event, ui ) {
$( 'table.widefat tbody th, table.widefat tbody td' ).css( 'cursor', 'default' );
$( 'table.widefat tbody' ).sortable( 'disable' );
var postid = ui.item.find( '.check-column input' ).val();
var prevpostid = ui.item.prev().find( '.check-column input' ).val();
var nextpostid = ui.item.next().find( '.check-column input' ).val();
// Show Spinner
ui.item
.find( '.check-column input' )
.hide()
.after( '<img alt="processing" src="images/wpspin_light.gif" class="waiting" style="margin-left: 6px;" />' );
// Go do the sorting stuff via ajax
$.post(
ajaxurl,
{ action: 'woocommerce_product_ordering', id: postid, previd: prevpostid, nextid: nextpostid },
function( response ) {
$.each( response, function( key, value ) {
$( '#inline_' + key + ' .menu_order' ).html( value );
});
ui.item.find( '.check-column input' ).show().siblings( 'img' ).remove();
$( 'table.widefat tbody th, table.widefat tbody td' ).css( 'cursor', 'move' );
$( 'table.widefat tbody' ).sortable( 'enable' );
}
);
// fix cell colors
$( 'table.widefat tbody tr' ).each( function() {
var i = $( 'table.widefat tbody tr' ).index( this );
if ( i%2 === 0 ) {
$( this ).addClass( 'alternate' );
} else {
$( this ).removeClass( 'alternate' );
}
});
},
sort: function (e, ui) {
ui.placeholder.find( 'td' ).each( function( key, value ) {
if ( ui.helper.find( 'td' ).eq( key ).is( ':visible' ) ) {
$( this ).show();
} else {
$( this ).hide();
}
});
}
});
});
@@ -0,0 +1 @@
jQuery(function(t){t("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),t("table.widefat tbody").sortable({items:"tr:not(.inline-edit-row)",cursor:"move",axis:"y",containment:"table.widefat",scrollSensitivity:40,helper:function(e,i){return i.each(function(){t(this).width(t(this).width())}),i},start:function(t,e){e.item.css("background-color","#ffffff"),e.item.children("td, th").css("border-bottom-width","0"),e.item.css("outline","1px solid #dfdfdf")},stop:function(t,e){e.item.removeAttr("style"),e.item.children("td,th").css("border-bottom-width","1px")},update:function(e,i){t("table.widefat tbody th, table.widefat tbody td").css("cursor","default"),t("table.widefat tbody").sortable("disable");var o=i.item.find(".check-column input").val(),n=i.item.prev().find(".check-column input").val(),d=i.item.next().find(".check-column input").val();i.item.find(".check-column input").hide().after('<img alt="processing" src="images/wpspin_light.gif" class="waiting" style="margin-left: 6px;" />'),t.post(ajaxurl,{action:"woocommerce_product_ordering",id:o,previd:n,nextid:d},function(e){t.each(e,function(e,i){t("#inline_"+e+" .menu_order").html(i)}),i.item.find(".check-column input").show().siblings("img").remove(),t("table.widefat tbody th, table.widefat tbody td").css("cursor","move"),t("table.widefat tbody").sortable("enable")}),t("table.widefat tbody tr").each(function(){t("table.widefat tbody tr").index(this)%2==0?t(this).addClass("alternate"):t(this).removeClass("alternate")})},sort:function(e,i){i.placeholder.find("td").each(function(e,o){i.helper.find("td").eq(e).is(":visible")?t(this).show():t(this).hide()})}})});
@@ -0,0 +1,167 @@
/*global inlineEditPost, woocommerce_admin, woocommerce_quick_edit */
jQuery(
function( $ ) {
$( '#the-list' ).on(
'click',
'.editinline',
function() {
inlineEditPost.revert();
var post_id = $( this ).closest( 'tr' ).attr( 'id' );
post_id = post_id.replace( 'post-', '' );
var $wc_inline_data = $( '#woocommerce_inline_' + post_id );
var sku = $wc_inline_data.find( '.sku' ).text(),
regular_price = $wc_inline_data.find( '.regular_price' ).text(),
sale_price = $wc_inline_data.find( '.sale_price ' ).text(),
weight = $wc_inline_data.find( '.weight' ).text(),
length = $wc_inline_data.find( '.length' ).text(),
width = $wc_inline_data.find( '.width' ).text(),
height = $wc_inline_data.find( '.height' ).text(),
shipping_class = $wc_inline_data.find( '.shipping_class' ).text(),
visibility = $wc_inline_data.find( '.visibility' ).text(),
stock_status = $wc_inline_data.find( '.stock_status' ).text(),
stock = $wc_inline_data.find( '.stock' ).text(),
featured = $wc_inline_data.find( '.featured' ).text(),
manage_stock = $wc_inline_data.find( '.manage_stock' ).text(),
menu_order = $wc_inline_data.find( '.menu_order' ).text(),
tax_status = $wc_inline_data.find( '.tax_status' ).text(),
tax_class = $wc_inline_data.find( '.tax_class' ).text(),
backorders = $wc_inline_data.find( '.backorders' ).text(),
product_type = $wc_inline_data.find( '.product_type' ).text();
var formatted_regular_price = regular_price.replace( '.', woocommerce_admin.mon_decimal_point ),
formatted_sale_price = sale_price.replace( '.', woocommerce_admin.mon_decimal_point );
$( 'input[name="_sku"]', '.inline-edit-row' ).val( sku );
$( 'input[name="_regular_price"]', '.inline-edit-row' ).val( formatted_regular_price );
$( 'input[name="_sale_price"]', '.inline-edit-row' ).val( formatted_sale_price );
$( 'input[name="_weight"]', '.inline-edit-row' ).val( weight );
$( 'input[name="_length"]', '.inline-edit-row' ).val( length );
$( 'input[name="_width"]', '.inline-edit-row' ).val( width );
$( 'input[name="_height"]', '.inline-edit-row' ).val( height );
$( 'select[name="_shipping_class"] option:selected', '.inline-edit-row' ).attr( 'selected', false ).trigger( 'change' );
$( 'select[name="_shipping_class"] option[value="' + shipping_class + '"]' ).attr( 'selected', 'selected' )
.trigger( 'change' );
$( 'input[name="_stock"]', '.inline-edit-row' ).val( stock );
$( 'input[name="menu_order"]', '.inline-edit-row' ).val( menu_order );
$(
'select[name="_tax_status"] option, ' +
'select[name="_tax_class"] option, ' +
'select[name="_visibility"] option, ' +
'select[name="_stock_status"] option, ' +
'select[name="_backorders"] option'
).prop( 'selected', false ).removeAttr( 'selected' );
var is_variable_product = 'variable' === product_type;
$( 'select[name="_stock_status"] ~ .wc-quick-edit-warning', '.inline-edit-row' ).toggle( is_variable_product );
$( 'select[name="_stock_status"] option[value="' + (is_variable_product ? '' : stock_status) + '"]', '.inline-edit-row' )
.attr( 'selected', 'selected' );
$( 'select[name="_tax_status"] option[value="' + tax_status + '"]', '.inline-edit-row' ).attr( 'selected', 'selected' );
$( 'select[name="_tax_class"] option[value="' + tax_class + '"]', '.inline-edit-row' ).attr( 'selected', 'selected' );
$( 'select[name="_visibility"] option[value="' + visibility + '"]', '.inline-edit-row' ).attr( 'selected', 'selected' );
$( 'select[name="_backorders"] option[value="' + backorders + '"]', '.inline-edit-row' ).attr( 'selected', 'selected' );
if ( 'yes' === featured ) {
$( 'input[name="_featured"]', '.inline-edit-row' ).prop( 'checked', true );
} else {
$( 'input[name="_featured"]', '.inline-edit-row' ).prop( 'checked', false );
}
// Conditional display.
var product_is_virtual = $wc_inline_data.find( '.product_is_virtual' ).text();
var product_supports_stock_status = 'external' !== product_type;
var product_supports_stock_fields = 'external' !== product_type && 'grouped' !== product_type;
$( '.stock_fields, .manage_stock_field, .stock_status_field, .backorder_field' ).show();
if ( product_supports_stock_fields ) {
if ( 'yes' === manage_stock ) {
$( '.stock_qty_field, .backorder_field', '.inline-edit-row' ).show().removeAttr( 'style' );
$( '.stock_status_field' ).hide();
$( '.manage_stock_field input' ).prop( 'checked', true );
} else {
$( '.stock_qty_field, .backorder_field', '.inline-edit-row' ).hide();
$( '.stock_status_field' ).show().removeAttr( 'style' );
$( '.manage_stock_field input' ).prop( 'checked', false );
}
} else if ( product_supports_stock_status ) {
$( '.stock_fields, .manage_stock_field, .backorder_field' ).hide();
} else {
$( '.stock_fields, .manage_stock_field, .stock_status_field, .backorder_field' ).hide();
}
if ( 'simple' === product_type || 'external' === product_type ) {
$( '.price_fields', '.inline-edit-row' ).show().removeAttr( 'style' );
} else {
$( '.price_fields', '.inline-edit-row' ).hide();
}
if ( 'yes' === product_is_virtual ) {
$( '.dimension_fields', '.inline-edit-row' ).hide();
} else {
$( '.dimension_fields', '.inline-edit-row' ).show().removeAttr( 'style' );
}
// Rename core strings.
$( 'input[name="comment_status"]' ).parent().find( '.checkbox-title' ).text( woocommerce_quick_edit.strings.allow_reviews );
}
);
$( '#the-list' ).on(
'change',
'.inline-edit-row input[name="_manage_stock"]',
function() {
if ( $( this ).is( ':checked' ) ) {
$( '.stock_qty_field, .backorder_field', '.inline-edit-row' ).show().removeAttr( 'style' );
$( '.stock_status_field' ).hide();
} else {
$( '.stock_qty_field, .backorder_field', '.inline-edit-row' ).hide();
$( '.stock_status_field' ).show().removeAttr( 'style' );
}
}
);
$( '#wpbody' ).on(
'click',
'#doaction, #doaction2',
function() {
$( 'input.text', '.inline-edit-row' ).val( '' );
$( '#woocommerce-fields' ).find( 'select' ).prop( 'selectedIndex', 0 );
$( '#woocommerce-fields-bulk' ).find( '.inline-edit-group .change-input' ).hide();
}
);
$( '#wpbody' ).on(
'change',
'#woocommerce-fields-bulk .inline-edit-group .change_to',
function() {
if ( 0 < $( this ).val() ) {
$( this ).closest( 'div' ).find( '.change-input' ).show();
} else {
$( this ).closest( 'div' ).find( '.change-input' ).hide();
}
}
);
$( '#wpbody' ).on(
'click',
'.trash-product',
function() {
return window.confirm( woocommerce_admin.i18n_delete_product_notice );
}
);
}
);
@@ -0,0 +1 @@
jQuery(function(e){e("#the-list").on("click",".editinline",function(){inlineEditPost.revert();var t=e(this).closest("tr").attr("id");t=t.replace("post-","");var i=e("#woocommerce_inline_"+t),n=i.find(".sku").text(),o=i.find(".regular_price").text(),d=i.find(".sale_price ").text(),s=i.find(".weight").text(),l=i.find(".length").text(),c=i.find(".width").text(),a=i.find(".height").text(),r=i.find(".shipping_class").text(),_=i.find(".visibility").text(),p=i.find(".stock_status").text(),m=i.find(".stock").text(),u=i.find(".featured").text(),f=i.find(".manage_stock").text(),w=i.find(".menu_order").text(),h=i.find(".tax_status").text(),k=i.find(".tax_class").text(),g=i.find(".backorders").text(),v=i.find(".product_type").text(),x=o.replace(".",woocommerce_admin.mon_decimal_point),y=d.replace(".",woocommerce_admin.mon_decimal_point);e('input[name="_sku"]',".inline-edit-row").val(n),e('input[name="_regular_price"]',".inline-edit-row").val(x),e('input[name="_sale_price"]',".inline-edit-row").val(y),e('input[name="_weight"]',".inline-edit-row").val(s),e('input[name="_length"]',".inline-edit-row").val(l),e('input[name="_width"]',".inline-edit-row").val(c),e('input[name="_height"]',".inline-edit-row").val(a),e('select[name="_shipping_class"] option:selected',".inline-edit-row").attr("selected",!1).trigger("change"),e('select[name="_shipping_class"] option[value="'+r+'"]').attr("selected","selected").trigger("change"),e('input[name="_stock"]',".inline-edit-row").val(m),e('input[name="menu_order"]',".inline-edit-row").val(w),e('select[name="_tax_status"] option, select[name="_tax_class"] option, select[name="_visibility"] option, select[name="_stock_status"] option, select[name="_backorders"] option').prop("selected",!1).removeAttr("selected");var b="variable"===v;e('select[name="_stock_status"] ~ .wc-quick-edit-warning',".inline-edit-row").toggle(b),e('select[name="_stock_status"] option[value="'+(b?"":p)+'"]',".inline-edit-row").attr("selected","selected"),e('select[name="_tax_status"] option[value="'+h+'"]',".inline-edit-row").attr("selected","selected"),e('select[name="_tax_class"] option[value="'+k+'"]',".inline-edit-row").attr("selected","selected"),e('select[name="_visibility"] option[value="'+_+'"]',".inline-edit-row").attr("selected","selected"),e('select[name="_backorders"] option[value="'+g+'"]',".inline-edit-row").attr("selected","selected"),"yes"===u?e('input[name="_featured"]',".inline-edit-row").prop("checked",!0):e('input[name="_featured"]',".inline-edit-row").prop("checked",!1);var A=i.find(".product_is_virtual").text(),q="external"!==v,j="external"!==v&&"grouped"!==v;e(".stock_fields, .manage_stock_field, .stock_status_field, .backorder_field").show(),j?"yes"===f?(e(".stock_qty_field, .backorder_field",".inline-edit-row").show().removeAttr("style"),e(".stock_status_field").hide(),e(".manage_stock_field input").prop("checked",!0)):(e(".stock_qty_field, .backorder_field",".inline-edit-row").hide(),e(".stock_status_field").show().removeAttr("style"),e(".manage_stock_field input").prop("checked",!1)):q?e(".stock_fields, .manage_stock_field, .backorder_field").hide():e(".stock_fields, .manage_stock_field, .stock_status_field, .backorder_field").hide(),"simple"===v||"external"===v?e(".price_fields",".inline-edit-row").show().removeAttr("style"):e(".price_fields",".inline-edit-row").hide(),"yes"===A?e(".dimension_fields",".inline-edit-row").hide():e(".dimension_fields",".inline-edit-row").show().removeAttr("style"),e('input[name="comment_status"]').parent().find(".checkbox-title").text(woocommerce_quick_edit.strings.allow_reviews)}),e("#the-list").on("change",'.inline-edit-row input[name="_manage_stock"]',function(){e(this).is(":checked")?(e(".stock_qty_field, .backorder_field",".inline-edit-row").show().removeAttr("style"),e(".stock_status_field").hide()):(e(".stock_qty_field, .backorder_field",".inline-edit-row").hide(),e(".stock_status_field").show().removeAttr("style"))}),e("#wpbody").on("click","#doaction, #doaction2",function(){e("input.text",".inline-edit-row").val(""),e("#woocommerce-fields").find("select").prop("selectedIndex",0),e("#woocommerce-fields-bulk").find(".inline-edit-group .change-input").hide()}),e("#wpbody").on("change","#woocommerce-fields-bulk .inline-edit-group .change_to",function(){0<e(this).val()?e(this).closest("div").find(".change-input").show():e(this).closest("div").find(".change-input").hide()}),e("#wpbody").on("click",".trash-product",function(){return window.confirm(woocommerce_admin.i18n_delete_product_notice)})});
@@ -0,0 +1,257 @@
jQuery(function( $ ) {
function showTooltip( x, y, contents ) {
$( '<div class="chart-tooltip">' + contents + '</div>' ).css( {
top: y - 16,
left: x + 20
}).appendTo( 'body' ).fadeIn( 200 );
}
var prev_data_index = null;
var prev_series_index = null;
$( '.chart-placeholder' ).on( 'plothover', function ( event, pos, item ) {
if ( item ) {
if ( prev_data_index !== item.dataIndex || prev_series_index !== item.seriesIndex ) {
prev_data_index = item.dataIndex;
prev_series_index = item.seriesIndex;
$( '.chart-tooltip' ).remove();
if ( item.series.points.show || item.series.enable_tooltip ) {
var y = item.series.data[item.dataIndex][1],
tooltip_content = '';
if ( item.series.prepend_label ) {
tooltip_content = tooltip_content + item.series.label + ': ';
}
if ( item.series.prepend_tooltip ) {
tooltip_content = tooltip_content + item.series.prepend_tooltip;
}
tooltip_content = tooltip_content + y;
if ( item.series.append_tooltip ) {
tooltip_content = tooltip_content + item.series.append_tooltip;
}
if ( item.series.pie.show ) {
showTooltip( pos.pageX, pos.pageY, tooltip_content );
} else {
showTooltip( item.pageX, item.pageY, tooltip_content );
}
}
}
} else {
$( '.chart-tooltip' ).remove();
prev_data_index = null;
}
});
$( '.wc_sparkline.bars' ).each( function() {
var chart_data = $( this ).data( 'sparkline' );
var options = {
grid: {
show: false
}
};
// main series
var series = [{
data: chart_data,
color: $( this ).data( 'color' ),
bars: {
fillColor: $( this ).data( 'color' ),
fill: true,
show: true,
lineWidth: 1,
barWidth: $( this ).data( 'barwidth' ),
align: 'center'
},
shadowSize: 0
}];
// draw the sparkline
$.plot( $( this ), series, options );
});
$( '.wc_sparkline.lines' ).each( function() {
var chart_data = $( this ).data( 'sparkline' );
var options = {
grid: {
show: false
}
};
// main series
var series = [{
data: chart_data,
color: $( this ).data( 'color' ),
lines: {
fill: false,
show: true,
lineWidth: 1,
align: 'center'
},
shadowSize: 0
}];
// draw the sparkline
$.plot( $( this ), series, options );
});
var dates = $( '.range_datepicker' ).datepicker({
changeMonth: true,
changeYear: true,
defaultDate: '',
dateFormat: 'yy-mm-dd',
numberOfMonths: 1,
minDate: '-20Y',
maxDate: '+1D',
showButtonPanel: true,
showOn: 'focus',
buttonImageOnly: true,
onSelect: function() {
var option = $( this ).is( '.from' ) ? 'minDate' : 'maxDate',
date = $( this ).datepicker( 'getDate' );
dates.not( this ).datepicker( 'option', option, date );
}
});
var a = document.createElement( 'a' );
if ( typeof a.download === 'undefined' ) {
$( '.export_csv' ).hide();
}
// Export
$( '.export_csv' ).on( 'click', function() {
var exclude_series = $( this ).data( 'exclude_series' ) || '';
exclude_series = exclude_series.toString();
exclude_series = exclude_series.split( ',' );
var xaxes_label = $( this ).data( 'xaxes' );
var groupby = $( this ) .data( 'groupby' );
var index_type = $( this ).data( 'index_type' );
var export_format = $( this ).data( 'export' );
var csv_data = '';
var s, series_data, d;
if ( 'table' === export_format ) {
$( this ).offsetParent().find( 'thead tr,tbody tr' ).each( function() {
$( this ).find( 'th, td' ).each( function() {
var value = $( this ).text();
value = value.replace( '[?]', '' ).replace( '#', '' );
csv_data += '"' + value + '"' + ',';
});
csv_data = csv_data.substring( 0, csv_data.length - 1 );
csv_data += '\n';
});
$( this ).offsetParent().find( 'tfoot tr' ).each( function() {
$( this ).find( 'th, td' ).each( function() {
var value = $( this ).text();
value = value.replace( '[?]', '' ).replace( '#', '' );
csv_data += '"' + value + '"' + ',';
if ( $( this ).attr( 'colspan' ) > 0 ) {
for ( i = 1; i < $(this).attr('colspan'); i++ ) {
csv_data += '"",';
}
}
});
csv_data = csv_data.substring( 0, csv_data.length - 1 );
csv_data += '\n';
});
} else {
if ( ! window.main_chart ) {
return false;
}
var the_series = window.main_chart.getData();
var series = [];
csv_data += '"' + xaxes_label + '",';
$.each( the_series, function( index, value ) {
if ( ! exclude_series || $.inArray( index.toString(), exclude_series ) === -1 ) {
series.push( value );
}
});
// CSV Headers
for ( s = 0; s < series.length; ++s ) {
csv_data += '"' + series[s].label + '",';
}
csv_data = csv_data.substring( 0, csv_data.length - 1 );
csv_data += '\n';
// Get x axis values
var xaxis = {};
for ( s = 0; s < series.length; ++s ) {
series_data = series[s].data;
for ( d = 0; d < series_data.length; ++d ) {
xaxis[series_data[d][0]] = [];
// Zero values to start
for ( var i = 0; i < series.length; ++i ) {
xaxis[series_data[d][0]].push(0);
}
}
}
// Add chart data
for ( s = 0; s < series.length; ++s ) {
series_data = series[s].data;
for ( d = 0; d < series_data.length; ++d ) {
xaxis[series_data[d][0]][s] = series_data[d][1];
}
}
// Loop data and output to csv string
$.each( xaxis, function( index, value ) {
var date = new Date( parseInt( index, 10 ) );
if ( 'none' === index_type ) {
csv_data += '"' + index + '",';
} else {
if ( groupby === 'day' ) {
csv_data += '"' +
date.getUTCFullYear() +
'-' +
parseInt( date.getUTCMonth() + 1, 10 ) +
'-' +
date.getUTCDate() +
'",';
} else {
csv_data += '"' + date.getUTCFullYear() + '-' + parseInt( date.getUTCMonth() + 1, 10 ) + '",';
}
}
for ( var d = 0; d < value.length; ++d ) {
var val = value[d];
if ( Math.round( val ) !== val ) {
val = parseFloat( val );
val = val.toFixed( 2 );
}
csv_data += '"' + val + '",';
}
csv_data = csv_data.substring( 0, csv_data.length - 1 );
csv_data += '\n';
} );
}
csv_data = 'data:text/csv;charset=utf-8,\uFEFF' + encodeURIComponent( csv_data );
// Set data as href and return
$( this ).attr( 'href', csv_data );
return true;
});
});
@@ -0,0 +1 @@
jQuery(function(t){function e(e,a,n){t('<div class="chart-tooltip">'+n+"</div>").css({top:a-16,left:e+20}).appendTo("body").fadeIn(200)}var a=null,n=null;t(".chart-placeholder").on("plothover",function(i,r,o){if(o){if((a!==o.dataIndex||n!==o.seriesIndex)&&(a=o.dataIndex,n=o.seriesIndex,t(".chart-tooltip").remove(),o.series.points.show||o.series.enable_tooltip)){var s=o.series.data[o.dataIndex][1],l="";o.series.prepend_label&&(l=l+o.series.label+": "),o.series.prepend_tooltip&&(l+=o.series.prepend_tooltip),l+=s,o.series.append_tooltip&&(l+=o.series.append_tooltip),o.series.pie.show?e(r.pageX,r.pageY,l):e(o.pageX,o.pageY,l)}}else t(".chart-tooltip").remove(),a=null}),t(".wc_sparkline.bars").each(function(){var e=[{data:t(this).data("sparkline"),color:t(this).data("color"),bars:{fillColor:t(this).data("color"),fill:!0,show:!0,lineWidth:1,barWidth:t(this).data("barwidth"),align:"center"},shadowSize:0}];t.plot(t(this),e,{grid:{show:!1}})}),t(".wc_sparkline.lines").each(function(){var e=[{data:t(this).data("sparkline"),color:t(this).data("color"),lines:{fill:!1,show:!0,lineWidth:1,align:"center"},shadowSize:0}];t.plot(t(this),e,{grid:{show:!1}})});var i=t(".range_datepicker").datepicker({changeMonth:!0,changeYear:!0,defaultDate:"",dateFormat:"yy-mm-dd",numberOfMonths:1,minDate:"-20Y",maxDate:"+1D",showButtonPanel:!0,showOn:"focus",buttonImageOnly:!0,onSelect:function(){var e=t(this).is(".from")?"minDate":"maxDate",a=t(this).datepicker("getDate");i.not(this).datepicker("option",e,a)}});"undefined"==typeof document.createElement("a").download&&t(".export_csv").hide(),t(".export_csv").on("click",function(){var e=t(this).data("exclude_series")||"";e=(e=e.toString()).split(",");var a,n,i,r=t(this).data("xaxes"),o=t(this).data("groupby"),s=t(this).data("index_type"),l="";if("table"===t(this).data("export"))t(this).offsetParent().find("thead tr,tbody tr").each(function(){t(this).find("th, td").each(function(){var e=t(this).text();e=e.replace("[?]","").replace("#",""),l+='"'+e+'",'}),l=l.substring(0,l.length-1),l+="\n"}),t(this).offsetParent().find("tfoot tr").each(function(){t(this).find("th, td").each(function(){var e=t(this).text();if(e=e.replace("[?]","").replace("#",""),l+='"'+e+'",',t(this).attr("colspan")>0)for(p=1;p<t(this).attr("colspan");p++)l+='"",'}),l=l.substring(0,l.length-1),l+="\n"});else{if(!window.main_chart)return!1;var h=window.main_chart.getData(),d=[];for(l+='"'+r+'",',t.each(h,function(a,n){e&&-1!==t.inArray(a.toString(),e)||d.push(n)}),a=0;a<d.length;++a)l+='"'+d[a].label+'",';l=l.substring(0,l.length-1),l+="\n";var c={};for(a=0;a<d.length;++a)for(n=d[a].data,i=0;i<n.length;++i){c[n[i][0]]=[];for(var p=0;p<d.length;++p)c[n[i][0]].push(0)}for(a=0;a<d.length;++a)for(n=d[a].data,i=0;i<n.length;++i)c[n[i][0]][a]=n[i][1];t.each(c,function(t,e){var a=new Date(parseInt(t,10));l+="none"===s?'"'+t+'",':"day"===o?'"'+a.getUTCFullYear()+"-"+parseInt(a.getUTCMonth()+1,10)+"-"+a.getUTCDate()+'",':'"'+a.getUTCFullYear()+"-"+parseInt(a.getUTCMonth()+1,10)+'",';for(var n=0;n<e.length;++n){var i=e[n];Math.round(i)!==i&&(i=(i=parseFloat(i)).toFixed(2)),l+='"'+i+'",'}l=l.substring(0,l.length-1),l+="\n"})}return l="data:text/csv;charset=utf-8,\ufeff"+encodeURIComponent(l),t(this).attr("href",l),!0})});
@@ -0,0 +1,387 @@
/* global htmlSettingsTaxLocalizeScript, ajaxurl */
/**
* Used by woocommerce/includes/admin/settings/views/html-settings-tax.php
*/
( function( $, data, wp, ajaxurl ) {
$( function() {
if ( ! String.prototype.trim ) {
String.prototype.trim = function () {
return this.replace( /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '' );
};
}
var rowTemplate = wp.template( 'wc-tax-table-row' ),
rowTemplateEmpty = wp.template( 'wc-tax-table-row-empty' ),
paginationTemplate = wp.template( 'wc-tax-table-pagination' ),
$table = $( '.wc_tax_rates' ),
$tbody = $( '#rates' ),
$save_button = $( ':input[name="save"]' ),
$pagination = $( '#rates-pagination, #rates-bottom-pagination' ),
$search_field = $( '#rates-search .wc-tax-rates-search-field' ),
$submit = $( '.woocommerce-save-button[type=submit]' ),
WCTaxTableModelConstructor = Backbone.Model.extend({
changes: {},
setRateAttribute: function( rateID, attribute, value ) {
var rates = _.indexBy( this.get( 'rates' ), 'tax_rate_id' ),
changes = {};
if ( rates[ rateID ][ attribute ] !== value ) {
changes[ rateID ] = {};
changes[ rateID ][ attribute ] = value;
rates[ rateID ][ attribute ] = value;
}
this.logChanges( changes );
},
logChanges: function( changedRows ) {
var changes = this.changes || {};
_.each( changedRows, function( row, id ) {
changes[ id ] = _.extend( changes[ id ] || {
tax_rate_id : id
}, row );
} );
this.changes = changes;
this.trigger( 'change:rates' );
},
getFilteredRates: function() {
var rates = this.get( 'rates' ),
search = $search_field.val().toLowerCase();
if ( search.length ) {
rates = _.filter( rates, function( rate ) {
var search_text = _.toArray( rate ).join( ' ' ).toLowerCase();
return ( -1 !== search_text.indexOf( search ) );
} );
}
rates = _.sortBy( rates, function( rate ) {
return parseInt( rate.tax_rate_order, 10 );
} );
return rates;
},
block: function() {
$( '.wc_tax_rates' ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
if ( ! $submit.attr( 'disabled' ) ) {
$submit.addClass( 'is-busy' );
}
},
unblock: function() {
$( '.wc_tax_rates' ).unblock();
$submit.removeClass( 'is-busy' );
},
save: function() {
var self = this;
self.block();
Backbone.ajax({
method: 'POST',
dataType: 'json',
url: ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_tax_rates_save_changes',
data: {
current_class: data.current_class,
wc_tax_nonce: data.wc_tax_nonce,
changes: self.changes
},
success: function( response, textStatus ) {
if ( 'success' === textStatus && response.success ) {
WCTaxTableModelInstance.set( 'rates', response.data.rates );
WCTaxTableModelInstance.trigger( 'change:rates' );
WCTaxTableModelInstance.changes = {};
WCTaxTableModelInstance.trigger( 'saved:rates' );
// Reload view.
WCTaxTableInstance.render();
}
self.unblock();
}
});
}
} ),
WCTaxTableViewConstructor = Backbone.View.extend({
rowTemplate: rowTemplate,
per_page: data.limit,
page: data.page,
initialize: function() {
var qty_pages = Math.ceil( _.toArray( this.model.get( 'rates' ) ).length / this.per_page );
this.qty_pages = 0 === qty_pages ? 1 : qty_pages;
this.page = this.sanitizePage( data.page );
this.listenTo( this.model, 'change:rates', this.setUnloadConfirmation );
this.listenTo( this.model, 'saved:rates', this.clearUnloadConfirmation );
$tbody.on( 'change autocompletechange', ':input', { view: this }, this.updateModelOnChange );
$search_field.on( 'keyup search', { view: this }, this.onSearchField );
$pagination.on( 'click', 'a', { view: this }, this.onPageChange );
$pagination.on( 'change', 'input', { view: this }, this.onPageChange );
$( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation );
$submit.on( 'click', { view: this }, this.onSubmit );
$save_button.prop( 'disabled', true );
// Can bind these directly to the buttons, as they won't get overwritten.
$table.find( '.insert' ).on( 'click', { view: this }, this.onAddNewRow );
$table.find( '.remove_tax_rates' ).on( 'click', { view: this }, this.onDeleteRow );
$table.find( '.export' ).on( 'click', { view: this }, this.onExport );
},
render: function() {
var rates = this.model.getFilteredRates(),
qty_rates = _.size( rates ),
qty_pages = Math.ceil( qty_rates / this.per_page ),
first_index = 0 === qty_rates ? 0 : this.per_page * ( this.page - 1 ),
last_index = this.per_page * this.page,
paged_rates = _.toArray( rates ).slice( first_index, last_index ),
view = this;
// Blank out the contents.
this.$el.empty();
if ( paged_rates.length ) {
// Populate $tbody with the current page of results.
$.each( paged_rates, function( id, rowData ) {
view.$el.append( view.rowTemplate( rowData ) );
} );
} else {
view.$el.append( rowTemplateEmpty() );
}
// Initialize autocomplete for countries.
this.$el.find( 'td.country input' ).autocomplete({
source: data.countries,
minLength: 2
});
// Initialize autocomplete for states.
this.$el.find( 'td.state input' ).autocomplete({
source: data.states,
minLength: 3
});
// Postcode and city don't have `name` values by default.
// They're only created if the contents changes, to save on database queries (I think)
this.$el.find( 'td.postcode input, td.city input' ).on( 'change', function() {
$( this ).attr( 'name', $( this ).data( 'name' ) );
});
if ( qty_pages > 1 ) {
// We've now displayed our initial page, time to render the pagination box.
$pagination.html( paginationTemplate( {
qty_rates: qty_rates,
current_page: this.page,
qty_pages: qty_pages
} ) );
} else {
$pagination.empty();
view.page = 1;
}
},
updateUrl: function() {
if ( ! window.history.replaceState ) {
return;
}
var url = data.base_url,
search = $search_field.val();
if ( 1 < this.page ) {
url += '&p=' + encodeURIComponent( this.page );
}
if ( search.length ) {
url += '&s=' + encodeURIComponent( search );
}
window.history.replaceState( {}, '', url );
},
onSubmit: function( event ) {
event.data.view.model.save();
event.preventDefault();
},
onAddNewRow: function( event ) {
var view = event.data.view,
model = view.model,
rates = _.indexBy( model.get( 'rates' ), 'tax_rate_id' ),
changes = {},
size = _.size( rates ),
newRow = _.extend( {}, data.default_rate, {
tax_rate_id: 'new-' + size + '-' + Date.now(),
newRow: true
} ),
$current, current_id, current_order, rates_to_reorder, reordered_rates;
$current = $tbody.children( '.current' );
if ( $current.length ) {
current_id = $current.last().data( 'id' );
current_order = parseInt( rates[ current_id ].tax_rate_order, 10 );
newRow.tax_rate_order = 1 + current_order;
rates_to_reorder = _.filter( rates, function( rate ) {
if ( parseInt( rate.tax_rate_order, 10 ) > current_order ) {
return true;
}
return false;
} );
reordered_rates = _.map( rates_to_reorder, function( rate ) {
rate.tax_rate_order++;
changes[ rate.tax_rate_id ] = _.extend(
changes[ rate.tax_rate_id ] || {}, { tax_rate_order : rate.tax_rate_order }
);
return rate;
} );
} else {
newRow.tax_rate_order = 1 + _.max(
_.pluck( rates, 'tax_rate_order' ),
function ( val ) {
// Cast them all to integers, because strings compare funky. Sighhh.
return parseInt( val, 10 );
}
);
// Move the last page
view.page = view.qty_pages;
}
rates[ newRow.tax_rate_id ] = newRow;
changes[ newRow.tax_rate_id ] = newRow;
model.set( 'rates', rates );
model.logChanges( changes );
view.render();
},
onDeleteRow: function( event ) {
var view = event.data.view,
model = view.model,
rates = _.indexBy( model.get( 'rates' ), 'tax_rate_id' ),
changes = {},
$current, current_id;
event.preventDefault();
if ( $current = $tbody.children( '.current' ) ) {
$current.each(function(){
current_id = $( this ).data('id');
delete rates[ current_id ];
changes[ current_id ] = _.extend( changes[ current_id ] || {}, { deleted : 'deleted' } );
});
model.set( 'rates', rates );
model.logChanges( changes );
view.render();
} else {
window.alert( data.strings.no_rows_selected );
}
},
onSearchField: function( event ){
event.data.view.updateUrl();
event.data.view.render();
},
onPageChange: function( event ) {
var $target = $( event.currentTarget );
event.preventDefault();
event.data.view.page = $target.data( 'goto' ) ? $target.data( 'goto' ) : $target.val();
event.data.view.render();
event.data.view.updateUrl();
},
onExport: function( event ) {
var csv_data = 'data:application/csv;charset=utf-8,' + data.strings.csv_data_cols.join(',') + '\n';
$.each( event.data.view.model.getFilteredRates(), function( id, rowData ) {
var row = '';
row += rowData.tax_rate_country + ',';
row += rowData.tax_rate_state + ',';
row += ( rowData.postcode ? rowData.postcode.join( '; ' ) : '' ) + ',';
row += ( rowData.city ? rowData.city.join( '; ' ) : '' ) + ',';
row += rowData.tax_rate + ',';
row += rowData.tax_rate_name + ',';
row += rowData.tax_rate_priority + ',';
row += rowData.tax_rate_compound + ',';
row += rowData.tax_rate_shipping + ',';
row += data.current_class;
csv_data += row + '\n';
});
$( this ).attr( 'href', encodeURI( csv_data ) );
return true;
},
setUnloadConfirmation: function() {
this.needsUnloadConfirm = true;
$save_button.prop( 'disabled', false );
},
clearUnloadConfirmation: function() {
this.needsUnloadConfirm = false;
$save_button.prop( 'disabled', true );
},
unloadConfirmation: function( event ) {
if ( event.data.view.needsUnloadConfirm ) {
event.returnValue = data.strings.unload_confirmation_msg;
window.event.returnValue = data.strings.unload_confirmation_msg;
return data.strings.unload_confirmation_msg;
}
},
updateModelOnChange: function( event ) {
var model = event.data.view.model,
$target = $( event.target ),
id = $target.closest( 'tr' ).data( 'id' ),
attribute = $target.data( 'attribute' ),
val = $target.val();
if ( 'city' === attribute || 'postcode' === attribute ) {
val = val.split( ';' );
val = $.map( val, function( thing ) {
return thing.trim();
});
}
if ( 'tax_rate_compound' === attribute || 'tax_rate_shipping' === attribute ) {
if ( $target.is( ':checked' ) ) {
val = 1;
} else {
val = 0;
}
}
model.setRateAttribute( id, attribute, val );
},
sanitizePage: function( page_num ) {
page_num = parseInt( page_num, 10 );
if ( page_num < 1 ) {
page_num = 1;
} else if ( page_num > this.qty_pages ) {
page_num = this.qty_pages;
}
return page_num;
}
} ),
WCTaxTableModelInstance = new WCTaxTableModelConstructor({
rates: data.rates
} ),
WCTaxTableInstance = new WCTaxTableViewConstructor({
model: WCTaxTableModelInstance,
el: '#rates'
} );
WCTaxTableInstance.render();
});
})( jQuery, htmlSettingsTaxLocalizeScript, wp, ajaxurl );
@@ -0,0 +1 @@
!function(t,e,a,n){t(function(){String.prototype.trim||(String.prototype.trim=function(){return this.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"")});var i=a.template("wc-tax-table-row"),r=a.template("wc-tax-table-row-empty"),o=a.template("wc-tax-table-pagination"),s=t(".wc_tax_rates"),c=t("#rates"),d=t(':input[name="save"]'),l=t("#rates-pagination, #rates-bottom-pagination"),u=t("#rates-search .wc-tax-rates-search-field"),h=t(".woocommerce-save-button[type=submit]"),p=Backbone.Model.extend({changes:{},setRateAttribute:function(t,e,a){var n=_.indexBy(this.get("rates"),"tax_rate_id"),i={};n[t][e]!==a&&(i[t]={},i[t][e]=a,n[t][e]=a),this.logChanges(i)},logChanges:function(t){var e=this.changes||{};_.each(t,function(t,a){e[a]=_.extend(e[a]||{tax_rate_id:a},t)}),this.changes=e,this.trigger("change:rates")},getFilteredRates:function(){var t=this.get("rates"),e=u.val().toLowerCase();return e.length&&(t=_.filter(t,function(t){return-1!==_.toArray(t).join(" ").toLowerCase().indexOf(e)})),t=_.sortBy(t,function(t){return parseInt(t.tax_rate_order,10)})},block:function(){t(".wc_tax_rates").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),h.attr("disabled")||h.addClass("is-busy")},unblock:function(){t(".wc_tax_rates").unblock(),h.removeClass("is-busy")},save:function(){var t=this;t.block(),Backbone.ajax({method:"POST",dataType:"json",url:n+(n.indexOf("?")>0?"&":"?")+"action=woocommerce_tax_rates_save_changes",data:{current_class:e.current_class,wc_tax_nonce:e.wc_tax_nonce,changes:t.changes},success:function(e,a){"success"===a&&e.success&&(f.set("rates",e.data.rates),f.trigger("change:rates"),f.changes={},f.trigger("saved:rates"),m.render()),t.unblock()}})}}),g=Backbone.View.extend({rowTemplate:i,per_page:e.limit,page:e.page,initialize:function(){var a=Math.ceil(_.toArray(this.model.get("rates")).length/this.per_page);this.qty_pages=0===a?1:a,this.page=this.sanitizePage(e.page),this.listenTo(this.model,"change:rates",this.setUnloadConfirmation),this.listenTo(this.model,"saved:rates",this.clearUnloadConfirmation),c.on("change autocompletechange",":input",{view:this},this.updateModelOnChange),u.on("keyup search",{view:this},this.onSearchField),l.on("click","a",{view:this},this.onPageChange),l.on("change","input",{view:this},this.onPageChange),t(window).on("beforeunload",{view:this},this.unloadConfirmation),h.on("click",{view:this},this.onSubmit),d.prop("disabled",!0),s.find(".insert").on("click",{view:this},this.onAddNewRow),s.find(".remove_tax_rates").on("click",{view:this},this.onDeleteRow),s.find(".export").on("click",{view:this},this.onExport)},render:function(){var a=this.model.getFilteredRates(),n=_.size(a),i=Math.ceil(n/this.per_page),s=0===n?0:this.per_page*(this.page-1),c=this.per_page*this.page,d=_.toArray(a).slice(s,c),u=this;this.$el.empty(),d.length?t.each(d,function(t,e){u.$el.append(u.rowTemplate(e))}):u.$el.append(r()),this.$el.find("td.country input").autocomplete({source:e.countries,minLength:2}),this.$el.find("td.state input").autocomplete({source:e.states,minLength:3}),this.$el.find("td.postcode input, td.city input").on("change",function(){t(this).attr("name",t(this).data("name"))}),i>1?l.html(o({qty_rates:n,current_page:this.page,qty_pages:i})):(l.empty(),u.page=1)},updateUrl:function(){if(window.history.replaceState){var t=e.base_url,a=u.val();1<this.page&&(t+="&p="+encodeURIComponent(this.page)),a.length&&(t+="&s="+encodeURIComponent(a)),window.history.replaceState({},"",t)}},onSubmit:function(t){t.data.view.model.save(),t.preventDefault()},onAddNewRow:function(t){var a,n,i,r,o=t.data.view,s=o.model,d=_.indexBy(s.get("rates"),"tax_rate_id"),l={},u=_.size(d),h=_.extend({},e.default_rate,{tax_rate_id:"new-"+u+"-"+Date.now(),newRow:!0});(a=c.children(".current")).length?(n=a.last().data("id"),i=parseInt(d[n].tax_rate_order,10),h.tax_rate_order=1+i,r=_.filter(d,function(t){return parseInt(t.tax_rate_order,10)>i}),_.map(r,function(t){return t.tax_rate_order++,l[t.tax_rate_id]=_.extend(l[t.tax_rate_id]||{},{tax_rate_order:t.tax_rate_order}),t})):(h.tax_rate_order=1+_.max(_.pluck(d,"tax_rate_order"),function(t){return parseInt(t,10)}),o.page=o.qty_pages),d[h.tax_rate_id]=h,l[h.tax_rate_id]=h,s.set("rates",d),s.logChanges(l),o.render()},onDeleteRow:function(a){var n,i,r=a.data.view,o=r.model,s=_.indexBy(o.get("rates"),"tax_rate_id"),d={};a.preventDefault(),(n=c.children(".current"))?(n.each(function(){i=t(this).data("id"),delete s[i],d[i]=_.extend(d[i]||{},{deleted:"deleted"})}),o.set("rates",s),o.logChanges(d),r.render()):window.alert(e.strings.no_rows_selected)},onSearchField:function(t){t.data.view.updateUrl(),t.data.view.render()},onPageChange:function(e){var a=t(e.currentTarget);e.preventDefault(),e.data.view.page=a.data("goto")?a.data("goto"):a.val(),e.data.view.render(),e.data.view.updateUrl()},onExport:function(a){var n="data:application/csv;charset=utf-8,"+e.strings.csv_data_cols.join(",")+"\n";return t.each(a.data.view.model.getFilteredRates(),function(t,a){var i="";i+=a.tax_rateLine truncated
@@ -0,0 +1,300 @@
/* global woocommerce_settings_params, wp */
( function ( $, params, wp ) {
$( function () {
// Sell Countries
$( 'select#woocommerce_allowed_countries' )
.on( 'change', function () {
if ( 'specific' === $( this ).val() ) {
$( this ).closest( 'tr' ).next( 'tr' ).hide();
$( this ).closest( 'tr' ).next().next( 'tr' ).show();
} else if ( 'all_except' === $( this ).val() ) {
$( this ).closest( 'tr' ).next( 'tr' ).show();
$( this ).closest( 'tr' ).next().next( 'tr' ).hide();
} else {
$( this ).closest( 'tr' ).next( 'tr' ).hide();
$( this ).closest( 'tr' ).next().next( 'tr' ).hide();
}
} )
.trigger( 'change' );
// Ship Countries
$( 'select#woocommerce_ship_to_countries' )
.on( 'change', function () {
if ( 'specific' === $( this ).val() ) {
$( this ).closest( 'tr' ).next( 'tr' ).show();
} else {
$( this ).closest( 'tr' ).next( 'tr' ).hide();
}
} )
.trigger( 'change' );
// Stock management
$( 'input#woocommerce_manage_stock' )
.on( 'change', function () {
if ( $( this ).is( ':checked' ) ) {
$( this )
.closest( 'tbody' )
.find( '.manage_stock_field' )
.closest( 'tr' )
.show();
} else {
$( this )
.closest( 'tbody' )
.find( '.manage_stock_field' )
.closest( 'tr' )
.hide();
}
} )
.trigger( 'change' );
// Color picker
$( '.colorpick' )
.iris( {
change: function ( event, ui ) {
$( this )
.parent()
.find( '.colorpickpreview' )
.css( { backgroundColor: ui.color.toString() } );
},
hide: true,
border: true,
} )
.on( 'click focus', function ( event ) {
event.stopPropagation();
$( '.iris-picker' ).hide();
$( this ).closest( 'td' ).find( '.iris-picker' ).show();
$( this ).data( 'originalValue', $( this ).val() );
} )
.on( 'change', function () {
if ( $( this ).is( '.iris-error' ) ) {
var original_value = $( this ).data( 'originalValue' );
if (
original_value.match(
/^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/
)
) {
$( this )
.val( $( this ).data( 'originalValue' ) )
.trigger( 'change' );
} else {
$( this ).val( '' ).trigger( 'change' );
}
}
} );
$( 'body' ).on( 'click', function () {
$( '.iris-picker' ).hide();
} );
// Edit prompt
$( function () {
var changed = false;
let $check_column = $( '.wp-list-table .check-column' );
$( 'input, textarea, select, checkbox' ).on( 'change', function (
event
) {
// Toggling WP List Table checkboxes should not trigger navigation warnings.
if (
$check_column.length &&
$check_column.has( event.target )
) {
return;
}
if ( ! changed ) {
window.onbeforeunload = function () {
return params.i18n_nav_warning;
};
changed = true;
}
} );
$( '.submit :input, input#search-submit' ).on(
'click',
function () {
window.onbeforeunload = '';
}
);
} );
// Sorting
$( 'table.wc_gateways tbody, table.wc_shipping tbody' ).sortable( {
items: 'tr',
cursor: 'move',
axis: 'y',
handle: 'td.sort',
scrollSensitivity: 40,
helper: function ( event, ui ) {
ui.children().each( function () {
$( this ).width( $( this ).width() );
} );
ui.css( 'left', '0' );
return ui;
},
start: function ( event, ui ) {
ui.item.css( 'background-color', '#f6f6f6' );
},
stop: function ( event, ui ) {
ui.item.removeAttr( 'style' );
ui.item.trigger( 'updateMoveButtons' );
},
} );
// Select all/none
$( '.woocommerce' ).on( 'click', '.select_all', function () {
$( this )
.closest( 'td' )
.find( 'select option' )
.prop( 'selected', true );
$( this ).closest( 'td' ).find( 'select' ).trigger( 'change' );
return false;
} );
$( '.woocommerce' ).on( 'click', '.select_none', function () {
$( this )
.closest( 'td' )
.find( 'select option' )
.prop( 'selected', false );
$( this ).closest( 'td' ).find( 'select' ).trigger( 'change' );
return false;
} );
// Re-order buttons.
$( '.wc-item-reorder-nav' )
.find( '.wc-move-up, .wc-move-down' )
.on( 'click', function () {
var moveBtn = $( this ),
$row = moveBtn.closest( 'tr' );
moveBtn.trigger( 'focus' );
var isMoveUp = moveBtn.is( '.wc-move-up' ),
isMoveDown = moveBtn.is( '.wc-move-down' );
if ( isMoveUp ) {
var $previewRow = $row.prev( 'tr' );
if ( $previewRow && $previewRow.length ) {
$previewRow.before( $row );
wp.a11y.speak( params.i18n_moved_up );
}
} else if ( isMoveDown ) {
var $nextRow = $row.next( 'tr' );
if ( $nextRow && $nextRow.length ) {
$nextRow.after( $row );
wp.a11y.speak( params.i18n_moved_down );
}
}
moveBtn.trigger( 'focus' ); // Re-focus after the container was moved.
moveBtn.closest( 'table' ).trigger( 'updateMoveButtons' );
} );
$( '.wc-item-reorder-nav' )
.closest( 'table' )
.on( 'updateMoveButtons', function () {
var table = $( this ),
lastRow = $( this ).find( 'tbody tr:last' ),
firstRow = $( this ).find( 'tbody tr:first' );
table
.find( '.wc-item-reorder-nav .wc-move-disabled' )
.removeClass( 'wc-move-disabled' )
.attr( { tabindex: '0', 'aria-hidden': 'false' } );
firstRow
.find( '.wc-item-reorder-nav .wc-move-up' )
.addClass( 'wc-move-disabled' )
.attr( { tabindex: '-1', 'aria-hidden': 'true' } );
lastRow
.find( '.wc-item-reorder-nav .wc-move-down' )
.addClass( 'wc-move-disabled' )
.attr( { tabindex: '-1', 'aria-hidden': 'true' } );
} );
$( '.wc-item-reorder-nav' )
.closest( 'table' )
.trigger( 'updateMoveButtons' );
$( '.submit button' ).on( 'click', function () {
if (
$( 'select#woocommerce_allowed_countries' ).val() ===
'specific' &&
! $( '[name="woocommerce_specific_allowed_countries[]"]' ).val()
) {
if (
window.confirm(
woocommerce_settings_params.i18n_no_specific_countries_selected
)
) {
return true;
}
return false;
}
} );
$( '#settings-other-payment-methods' ).on( 'click', function ( e ) {
if (
typeof window.wcTracks.recordEvent === 'undefined' &&
typeof window.wc.tracks.recordEvent === 'undefined'
) {
return;
}
var recordEvent =
window.wc.tracks.recordEvent || window.wcTracks.recordEvent;
var payment_methods = $.map(
$(
'td.wc_payment_gateways_wrapper tbody tr[data-gateway_id] '
),
function ( tr ) {
return $( tr ).attr( 'data-gateway_id' );
}
);
recordEvent( 'settings_payments_recommendations_other_options', {
available_payment_methods: payment_methods,
} );
} );
$( '.woocommerce-save-button.components-button' ).on( 'click', function ( e ) {
if ( ! $( this ).attr( 'disabled' ) ) {
$( this ).addClass( 'is-busy' );
}
} );
/**
* Support conditionally displaying a settings field description when another element
* is set to a specific value.
*
* This logic is subject to change, and is not intended for use by other plugins.
* Note that we can't avoid jQuery here, because of our current dependence on Select2
* for various controls.
*/
document.querySelectorAll( 'body.woocommerce_page_wc-settings #mainform .conditional.description' ).forEach( description => {
const $underObservation = $( description.dataset.dependsOn );
const showIfEquals = description.dataset.showIfEquals;
if ( undefined === showIfEquals || $underObservation.length === 0 ) {
return;
}
/**
* Set visibility of the description element according to whether its value
* matches that of showIfEquals.
*/
const changeAgent = () => {
description.style.visibility = $underObservation.val() === showIfEquals ? 'visible' : 'hidden';
};
// Monitor future changes, and take action based on the current state.
$underObservation.on( 'change', changeAgent );
changeAgent();
} );
} );
} )( jQuery, woocommerce_settings_params, wp );
@@ -0,0 +1 @@
!function(t,e,i){t(function(){t("select#woocommerce_allowed_countries").on("change",function(){"specific"===t(this).val()?(t(this).closest("tr").next("tr").hide(),t(this).closest("tr").next().next("tr").show()):"all_except"===t(this).val()?(t(this).closest("tr").next("tr").show(),t(this).closest("tr").next().next("tr").hide()):(t(this).closest("tr").next("tr").hide(),t(this).closest("tr").next().next("tr").hide())}).trigger("change"),t("select#woocommerce_ship_to_countries").on("change",function(){"specific"===t(this).val()?t(this).closest("tr").next("tr").show():t(this).closest("tr").next("tr").hide()}).trigger("change"),t("input#woocommerce_manage_stock").on("change",function(){t(this).is(":checked")?t(this).closest("tbody").find(".manage_stock_field").closest("tr").show():t(this).closest("tbody").find(".manage_stock_field").closest("tr").hide()}).trigger("change"),t(".colorpick").iris({change:function(e,i){t(this).parent().find(".colorpickpreview").css({backgroundColor:i.color.toString()})},hide:!0,border:!0}).on("click focus",function(e){e.stopPropagation(),t(".iris-picker").hide(),t(this).closest("td").find(".iris-picker").show(),t(this).data("originalValue",t(this).val())}).on("change",function(){t(this).is(".iris-error")&&(t(this).data("originalValue").match(/^\#([a-fA-F0-9]{6}|[a-fA-F0-9]{3})$/)?t(this).val(t(this).data("originalValue")).trigger("change"):t(this).val("").trigger("change"))}),t("body").on("click",function(){t(".iris-picker").hide()}),t(function(){var i=!1;let o=t(".wp-list-table .check-column");t("input, textarea, select, checkbox").on("change",function(t){o.length&&o.has(t.target)||i||(window.onbeforeunload=function(){return e.i18n_nav_warning},i=!0)}),t(".submit :input, input#search-submit").on("click",function(){window.onbeforeunload=""})}),t("table.wc_gateways tbody, table.wc_shipping tbody").sortable({items:"tr",cursor:"move",axis:"y",handle:"td.sort",scrollSensitivity:40,helper:function(e,i){return i.children().each(function(){t(this).width(t(this).width())}),i.css("left","0"),i},start:function(t,e){e.item.css("background-color","#f6f6f6")},stop:function(t,e){e.item.removeAttr("style"),e.item.trigger("updateMoveButtons")}}),t(".woocommerce").on("click",".select_all",function(){return t(this).closest("td").find("select option").prop("selected",!0),t(this).closest("td").find("select").trigger("change"),!1}),t(".woocommerce").on("click",".select_none",function(){return t(this).closest("td").find("select option").prop("selected",!1),t(this).closest("td").find("select").trigger("change"),!1}),t(".wc-item-reorder-nav").find(".wc-move-up, .wc-move-down").on("click",function(){var o=t(this),n=o.closest("tr");o.trigger("focus");var s=o.is(".wc-move-up"),c=o.is(".wc-move-down");if(s){var r=n.prev("tr");r&&r.length&&(r.before(n),i.a11y.speak(e.i18n_moved_up))}else if(c){var a=n.next("tr");a&&a.length&&(a.after(n),i.a11y.speak(e.i18n_moved_down))}o.trigger("focus"),o.closest("table").trigger("updateMoveButtons")}),t(".wc-item-reorder-nav").closest("table").on("updateMoveButtons",function(){var e=t(this),i=t(this).find("tbody tr:last"),o=t(this).find("tbody tr:first");e.find(".wc-item-reorder-nav .wc-move-disabled").removeClass("wc-move-disabled").attr({tabindex:"0","aria-hidden":"false"}),o.find(".wc-item-reorder-nav .wc-move-up").addClass("wc-move-disabled").attr({tabindex:"-1","aria-hidden":"true"}),i.find(".wc-item-reorder-nav .wc-move-down").addClass("wc-move-disabled").attr({tabindex:"-1","aria-hidden":"true"})}),t(".wc-item-reorder-nav").closest("table").trigger("updateMoveButtons"),t(".submit button").on("click",function(){if("specific"===t("select#woocommerce_allowed_countries").val()&&!t('[name="woocommerce_specific_allowed_countries[]"]').val())return!!window.confirm(woocommerce_settings_params.i18n_no_specific_countries_selected)}),t("#settings-other-payment-methods").on("click",function(e){"undefined"==typeof window.wcTracks.recordEvent&&"undefined"==typeof window.wc.tracks.recordEvent||(window.wc.tracks.recordEvent||window.wcTracks.recordEvent)("settings_payments_recommendations_other_options",{available_payment_methods:t.map(t("td.wc_payment_gateways_wrapper tbody tr[data-gateway_id] "),function(e){return t(e).attr("data-gateway_id")})})}),t(".woocommerce-save-button.components-button").on("click",function(e){t(this).attr("disabled")||t(this).addClass("is-busy")}),document.querySelectorAll("body.woocommerce_page_wc-settings #mainform .conditional.description").forEach(e=>{const i=t(e.dataset.dependsOn),o=e.dataset.showIfEquals;if(undefined===o||0===i.length)return;const n=()=>{e.style.visibility=i.val()===o?"visible":"hidden"};i.on("change",n),n()})})}(jQuery,woocommerce_settings_params,wp);
@@ -0,0 +1,185 @@
/* global jQuery, woocommerce_admin_system_status, wcSetClipboard, wcClearClipboard */
jQuery( function ( $ ) {
/**
* Users country and state fields
*/
var wcSystemStatus = {
init: function () {
$( document.body )
.on(
'click',
'a.help_tip, a.woocommerce-help-tip, woocommerce-product-type-tip',
this.preventTipTipClick
)
.on( 'click', 'a.debug-report', this.generateReport )
.on( 'click', '#copy-for-support', this.copyReport )
.on( 'click', '#copy-for-github', this.copyGithubReport )
.on( 'aftercopy', '#copy-for-support, #copy-for-github', this.copySuccess )
.on( 'aftercopyfailure', '#copy-for-support, #copy-for-github', this.copyFail )
.on( 'click', '#download-for-support', this.downloadReport );
},
/**
* Prevent anchor behavior when click on TipTip.
*
* @return {Bool}
*/
preventTipTipClick: function() {
return false;
},
/**
* Generate system status report.
*
* @return {Bool}
*/
generateReport: function() {
var report = '';
$( '.wc_status_table thead, .wc_status_table tbody' ).each( function() {
if ( $( this ).is( 'thead' ) ) {
var label = $( this ).find( 'th:eq(0)' ).data( 'exportLabel' ) || $( this ).text();
report = report + '\n### ' + label.trim() + ' ###\n\n';
} else {
$( 'tr', $( this ) ).each( function() {
var label = $( this ).find( 'td:eq(0)' ).data( 'exportLabel' ) || $( this ).find( 'td:eq(0)' ).text();
var the_name = label.trim().replace( /(<([^>]+)>)/ig, '' ); // Remove HTML.
// Find value
var $value_html = $( this ).find( 'td:eq(2)' ).clone();
$value_html.find( '.private' ).remove();
$value_html.find( '.dashicons-yes' ).replaceWith( '&#10004;' );
$value_html.find( '.dashicons-no-alt, .dashicons-warning' ).replaceWith( '&#10060;' );
// Format value
var the_value = $value_html.text().trim();
var value_array = the_value.split( ', ' );
if ( value_array.length > 1 ) {
// If value have a list of plugins ','.
// Split to add new line.
var temp_line ='';
$.each( value_array, function( key, line ) {
temp_line = temp_line + line + '\n';
});
the_value = temp_line;
}
report = report + '' + the_name + ': ' + the_value + '\n';
});
}
});
try {
$( '#debug-report' ).slideDown();
$( '#debug-report' ).find( 'textarea' ).val( '`' + report + '`' ).trigger( 'focus' ).trigger( 'select' );
$( this ).fadeOut();
return false;
} catch ( e ) {
/* jshint devel: true */
console.log( e );
}
return false;
},
/**
* Copy for report.
*
* @param {Object} evt Copy event.
*/
copyReport: function( evt ) {
wcClearClipboard();
wcSetClipboard( $( '#debug-report' ).find( 'textarea' ).val(), $( this ) );
evt.preventDefault();
},
/**
* Apply redactions
*/
applyRedactions( report ) {
var redactions = [
{
regex: /(WordPress address \(URL\):)[^\n]*/,
replacement: "$1 [Redacted]"
},
{
regex: /(Site address \(URL\):)[^\n]*/,
replacement: "$1 [Redacted]"
},
{
regex: /(### Database ###\n)([\s\S]*?)(\n### Post Type Counts ###)/,
replacement: "$1\n[REDACTED]\n$3"
}
];
redactions.forEach( function( redaction ) {
report = report.replace( redaction.regex, redaction.replacement );
});
return report;
},
/**
* Copy for GitHub report.
*
* @param {Object} event Copy event.
*/
copyGithubReport: function( event ) {
wcClearClipboard();
var reportValue = $( '#debug-report' ).find( 'textarea' ).val();
var redactedReport = wcSystemStatus.applyRedactions( reportValue );
var reportForGithub = '<details><summary>System Status Report</summary>\n\n``' + redactedReport + '``\n</details>';
wcSetClipboard( reportForGithub, $( this ) );
event.preventDefault();
},
/**
* Display a "Copied!" tip when success copying
*/
copySuccess: function( event ) {
$( event.target ).tipTip({
'attribute': 'data-tip',
'activation': 'focus',
'fadeIn': 50,
'fadeOut': 50,
'delay': 0
}).trigger( 'focus' );
},
/**
* Displays the copy error message when failure copying.
*/
copyFail: function() {
$( '.copy-error' ).removeClass( 'hidden' );
$( '#debug-report' ).find( 'textarea' ).trigger( 'focus' ).trigger( 'select' );
},
downloadReport: function() {
var ssr_text = new Blob( [ $( '#debug-report' ).find( 'textarea' ).val() ], { type: 'text/plain' } );
var domain = window.location.hostname;
var datetime = new Date().toISOString().slice( 0, 19 ).replace( /:/g, '-' );
var a = document.createElement( 'a' );
a.download = 'SystemStatusReport_' + domain + '_' + datetime + '.txt';
a.href = window.URL.createObjectURL( ssr_text );
a.textContent = 'Download ready';
a.style='display:none';
a.click();
a.remove();
}
};
wcSystemStatus.init();
$( '.wc_status_table' ).on( 'click', '.run-tool .button', function( evt ) {
evt.stopImmediatePropagation();
return window.confirm( woocommerce_admin_system_status.run_tool_confirmation );
});
$( '#log-viewer-select' ).on( 'click', 'h2 a.page-title-action', function( evt ) {
evt.stopImmediatePropagation();
return window.confirm( woocommerce_admin_system_status.delete_log_confirmation );
});
});
@@ -0,0 +1 @@
jQuery(function(t){var e={init:function(){t(document.body).on("click","a.help_tip, a.woocommerce-help-tip, woocommerce-product-type-tip",this.preventTipTipClick).on("click","a.debug-report",this.generateReport).on("click","#copy-for-support",this.copyReport).on("click","#copy-for-github",this.copyGithubReport).on("aftercopy","#copy-for-support, #copy-for-github",this.copySuccess).on("aftercopyfailure","#copy-for-support, #copy-for-github",this.copyFail).on("click","#download-for-support",this.downloadReport)},preventTipTipClick:function(){return!1},generateReport:function(){var e="";t(".wc_status_table thead, .wc_status_table tbody").each(function(){if(t(this).is("thead")){var o=t(this).find("th:eq(0)").data("exportLabel")||t(this).text();e=e+"\n### "+o.trim()+" ###\n\n"}else t("tr",t(this)).each(function(){var o=(t(this).find("td:eq(0)").data("exportLabel")||t(this).find("td:eq(0)").text()).trim().replace(/(<([^>]+)>)/gi,""),r=t(this).find("td:eq(2)").clone();r.find(".private").remove(),r.find(".dashicons-yes").replaceWith("&#10004;"),r.find(".dashicons-no-alt, .dashicons-warning").replaceWith("&#10060;");var i=r.text().trim(),n=i.split(", ");if(n.length>1){var a="";t.each(n,function(t,e){a=a+e+"\n"}),i=a}e=e+""+o+": "+i+"\n"})});try{return t("#debug-report").slideDown(),t("#debug-report").find("textarea").val("`"+e+"`").trigger("focus").trigger("select"),t(this).fadeOut(),!1}catch(o){console.log(o)}return!1},copyReport:function(e){wcClearClipboard(),wcSetClipboard(t("#debug-report").find("textarea").val(),t(this)),e.preventDefault()},applyRedactions:t=>([{regex:/(WordPress address \(URL\):)[^\n]*/,replacement:"$1 [Redacted]"},{regex:/(Site address \(URL\):)[^\n]*/,replacement:"$1 [Redacted]"},{regex:/(### Database ###\n)([\s\S]*?)(\n### Post Type Counts ###)/,replacement:"$1\n[REDACTED]\n$3"}].forEach(function(e){t=t.replace(e.regex,e.replacement)}),t),copyGithubReport:function(o){wcClearClipboard();var r=t("#debug-report").find("textarea").val(),i=e.applyRedactions(r);wcSetClipboard("<details><summary>System Status Report</summary>\n\n``"+i+"``\n</details>",t(this)),o.preventDefault()},copySuccess:function(e){t(e.target).tipTip({attribute:"data-tip",activation:"focus",fadeIn:50,fadeOut:50,delay:0}).trigger("focus")},copyFail:function(){t(".copy-error").removeClass("hidden"),t("#debug-report").find("textarea").trigger("focus").trigger("select")},downloadReport:function(){var e=new Blob([t("#debug-report").find("textarea").val()],{type:"text/plain"}),o=window.location.hostname,r=(new Date).toISOString().slice(0,19).replace(/:/g,"-"),i=document.createElement("a");i.download="SystemStatusReport_"+o+"_"+r+".txt",i.href=window.URL.createObjectURL(e),i.textContent="Download ready",i.style="display:none",i.click(),i.remove()}};e.init(),t(".wc_status_table").on("click",".run-tool .button",function(t){return t.stopImmediatePropagation(),window.confirm(woocommerce_admin_system_status.run_tool_confirmation)}),t("#log-viewer-select").on("click","h2 a.page-title-action",function(t){return t.stopImmediatePropagation(),window.confirm(woocommerce_admin_system_status.delete_log_confirmation)})});
@@ -0,0 +1,148 @@
/*global ajaxurl, woocommerce_term_ordering_params */
/* Modifided script from the simple-page-ordering plugin */
jQuery( function( $ ) {
var table_selector = 'table.wp-list-table',
item_selector = 'tbody tr:not(.inline-edit-row)',
term_id_selector = '.column-handle input[name="term_id"]',
column_handle = '<td class="column-handle"></td>';
if ( 0 === $( table_selector ).find( '.column-handle' ).length ) {
$( table_selector ).find( 'tr:not(.inline-edit-row)' ).append( column_handle );
term_id_selector = '.check-column input';
}
// Stand-in wcTracks.recordEvent in case tracks is not available (for any reason).
window.wcTracks = window.wcTracks || {};
window.wcTracks.recordEvent = window.wcTracks.recordEvent || function() { };
$( table_selector ).find( '.column-handle' ).show();
$.wc_add_missing_sort_handles = function() {
var all_table_rows = $( table_selector ).find('tbody > tr');
var rows_with_handle = $( table_selector ).find('tbody > tr > td.column-handle').parent();
if ( all_table_rows.length !== rows_with_handle.length ) {
all_table_rows.each(function(index, elem){
if ( ! rows_with_handle.is( elem ) ) {
$( elem ).append( column_handle );
}
});
}
$( table_selector ).find( '.column-handle' ).show();
};
$( document ).ajaxComplete( function( event, request, options ) {
if (
request &&
4 === request.readyState &&
200 === request.status &&
options.data &&
( 0 <= options.data.indexOf( '_inline_edit' ) || 0 <= options.data.indexOf( 'add-tag' ) )
) {
$.wc_add_missing_sort_handles();
$( document.body ).trigger( 'init_tooltips' );
}
} );
$( table_selector ).sortable({
items: item_selector,
cursor: 'move',
handle: '.column-handle',
axis: 'y',
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
placeholder: 'product-cat-placeholder',
scrollSensitivity: 40,
start: function( event, ui ) {
if ( ! ui.item.hasClass( 'alternate' ) ) {
ui.item.css( 'background-color', '#ffffff' );
}
ui.item.children( 'td, th' ).css( 'border-bottom-width', '0' );
ui.item.css( 'outline', '1px solid #aaa' );
},
stop: function( event, ui ) {
ui.item.removeAttr( 'style' );
ui.item.children( 'td, th' ).css( 'border-bottom-width', '1px' );
},
update: function( event, ui ) {
var termid = ui.item.find( term_id_selector ).val(); // this post id
var termparent = ui.item.find( '.parent' ).html(); // post parent
var prevtermid = ui.item.prev().find( term_id_selector ).val();
var nexttermid = ui.item.next().find( term_id_selector ).val();
// Can only sort in same tree
var prevtermparent, nexttermparent;
if ( prevtermid !== undefined ) {
prevtermparent = ui.item.prev().find( '.parent' ).html();
if ( prevtermparent !== termparent) {
prevtermid = undefined;
}
}
if ( nexttermid !== undefined ) {
nexttermparent = ui.item.next().find( '.parent' ).html();
if ( nexttermparent !== termparent) {
nexttermid = undefined;
}
}
// If previous and next not at same tree level, or next not at same tree level and
// the previous is the parent of the next, or just moved item beneath its own children.
if (
( prevtermid === undefined && nexttermid === undefined ) ||
( nexttermid === undefined && nexttermparent === prevtermid ) ||
( nexttermid !== undefined && prevtermparent === termid )
) {
$( table_selector ).sortable( 'cancel' );
return;
}
window.wcTracks.recordEvent( 'product_attributes_ordering_term', {
is_category:
woocommerce_term_ordering_params.taxonomy === 'product_cat'
? 'yes'
: 'no',
} );
// Show Spinner
ui.item.find( '.check-column input' ).hide();
ui.item
.find( '.check-column' )
.append( '<img alt="processing" src="images/wpspin_light.gif" class="waiting" style="margin-left: 6px;" />' );
// Go do the sorting stuff via ajax.
$.post(
ajaxurl,
{
action: 'woocommerce_term_ordering',
id: termid,
nextid: nexttermid,
thetaxonomy: woocommerce_term_ordering_params.taxonomy
},
function(response) {
if ( response === 'children' ) {
window.location.reload();
} else {
ui.item.find( '.check-column input' ).show();
ui.item.find( '.check-column' ).find( 'img' ).remove();
}
}
);
// Fix cell colors
$( 'table.widefat tbody tr' ).each( function() {
var i = jQuery( 'table.widefat tbody tr' ).index( this );
if ( i%2 === 0 ) {
jQuery( this ).addClass( 'alternate' );
} else {
jQuery( this ).removeClass( 'alternate' );
}
});
}
});
});
@@ -0,0 +1 @@
jQuery(function(e){var t="table.wp-list-table",n='.column-handle input[name="term_id"]';0===e(t).find(".column-handle").length&&(e(t).find("tr:not(.inline-edit-row)").append('<td class="column-handle"></td>'),n=".check-column input"),window.wcTracks=window.wcTracks||{},window.wcTracks.recordEvent=window.wcTracks.recordEvent||function(){},e(t).find(".column-handle").show(),e.wc_add_missing_sort_handles=function(){var n=e(t).find("tbody > tr"),i=e(t).find("tbody > tr > td.column-handle").parent();n.length!==i.length&&n.each(function(t,n){i.is(n)||e(n).append('<td class="column-handle"></td>')}),e(t).find(".column-handle").show()},e(document).ajaxComplete(function(t,n,i){n&&4===n.readyState&&200===n.status&&i.data&&(0<=i.data.indexOf("_inline_edit")||0<=i.data.indexOf("add-tag"))&&(e.wc_add_missing_sort_handles(),e(document.body).trigger("init_tooltips"))}),e(t).sortable({items:"tbody tr:not(.inline-edit-row)",cursor:"move",handle:".column-handle",axis:"y",forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"product-cat-placeholder",scrollSensitivity:40,start:function(e,t){t.item.hasClass("alternate")||t.item.css("background-color","#ffffff"),t.item.children("td, th").css("border-bottom-width","0"),t.item.css("outline","1px solid #aaa")},stop:function(e,t){t.item.removeAttr("style"),t.item.children("td, th").css("border-bottom-width","1px")},update:function(i,d){var o,a,r=d.item.find(n).val(),c=d.item.find(".parent").html(),l=d.item.prev().find(n).val(),s=d.item.next().find(n).val();l!==undefined&&(o=d.item.prev().find(".parent").html())!==c&&(l=undefined),s!==undefined&&(a=d.item.next().find(".parent").html())!==c&&(s=undefined),l===undefined&&s===undefined||s===undefined&&a===l||s!==undefined&&o===r?e(t).sortable("cancel"):(window.wcTracks.recordEvent("product_attributes_ordering_term",{is_category:"product_cat"===woocommerce_term_ordering_params.taxonomy?"yes":"no"}),d.item.find(".check-column input").hide(),d.item.find(".check-column").append('<img alt="processing" src="images/wpspin_light.gif" class="waiting" style="margin-left: 6px;" />'),e.post(ajaxurl,{action:"woocommerce_term_ordering",id:r,nextid:s,thetaxonomy:woocommerce_term_ordering_params.taxonomy},function(e){"children"===e?window.location.reload():(d.item.find(".check-column input").show(),d.item.find(".check-column").find("img").remove())}),e("table.widefat tbody tr").each(function(){jQuery("table.widefat tbody tr").index(this)%2==0?jQuery(this).addClass("alternate"):jQuery(this).removeClass("alternate")}))}})});
@@ -0,0 +1,120 @@
/*global wc_users_params */
jQuery( function ( $ ) {
/**
* Users country and state fields
*/
var wc_users_fields = {
states: null,
init: function() {
if ( typeof wc_users_params.countries !== 'undefined' ) {
/* State/Country select boxes */
this.states = JSON.parse( wc_users_params.countries.replace( /&quot;/g, '"' ) );
}
$( '.js_field-country' ).selectWoo().on( 'change', this.change_country );
$( '.js_field-country' ).trigger( 'change', [ true ] );
$( document.body ).on( 'change', 'select.js_field-state', this.change_state );
$( document.body ).on( 'click', 'button.js_copy-billing', this.copy_billing );
},
change_country: function( e, stickValue ) {
// Check for stickValue before using it
if ( typeof stickValue === 'undefined' ) {
stickValue = false;
}
// Prevent if we don't have the metabox data
if ( wc_users_fields.states === null ) {
return;
}
var $this = $( this ),
country = $this.val(),
$state = $this.parents( '.form-table' ).find( ':input.js_field-state' ),
$parent = $state.parent(),
input_name = $state.attr( 'name' ),
input_id = $state.attr( 'id' ),
stickstatefield = 'woocommerce.stickState-' + country,
value = $this.data( stickstatefield ) ? $this.data( stickstatefield ) : $state.val(),
placeholder = $state.attr( 'placeholder' ),
$newstate;
if ( stickValue ){
$this.data( 'woocommerce.stickState-' + country, value );
}
// Remove the previous DOM element
$parent.show().find( '.select2-container' ).remove();
if ( ! $.isEmptyObject( wc_users_fields.states[ country ] ) ) {
var state = wc_users_fields.states[ country ],
$defaultOption = $( '<option value=""></option>' )
.text( wc_users_fields.i18n_select_state_text );
$newstate = $( '<select style="width: 25em;"></select>' )
.prop( 'id', input_id )
.prop( 'name', input_name )
.prop( 'placeholder', placeholder )
.addClass( 'js_field-state' )
.append( $defaultOption );
$.each( state, function( index ) {
var $option = $( '<option></option>' )
.prop( 'value', index )
.text( state[ index ] );
$newstate.append( $option );
} );
$newstate.val( value );
$state.replaceWith( $newstate );
$newstate.show().selectWoo().hide().trigger( 'change' );
} else {
$newstate = $( '<input type="text" />' )
.prop( 'id', input_id )
.prop( 'name', input_name )
.prop( 'placeholder', placeholder )
.addClass( 'js_field-state regular-text' )
.val( value );
$state.replaceWith( $newstate );
}
// This event has a typo - deprecated in 2.5.0
$( document.body ).trigger( 'contry-change.woocommerce', [country, $( this ).closest( 'div' )] );
$( document.body ).trigger( 'country-change.woocommerce', [country, $( this ).closest( 'div' )] );
},
change_state: function() {
// Here we will find if state value on a select has changed and stick it to the country data
var $this = $( this ),
state = $this.val(),
$country = $this.parents( '.form-table' ).find( ':input.js_field-country' ),
country = $country.val();
$country.data( 'woocommerce.stickState-' + country, state );
},
copy_billing: function( event ) {
event.preventDefault();
$( '#fieldset-billing' ).find( 'input, select' ).each( function( i, el ) {
// The address keys match up, except for the prefix
var shipName = el.name.replace( /^billing_/, 'shipping_' );
// Swap prefix, then check if there are any elements
var shipEl = $( '[name="' + shipName + '"]' );
// No corresponding shipping field, skip this item
if ( ! shipEl.length ) {
return;
}
// Found a matching shipping element, update the value
shipEl.val( el.value ).trigger( 'change' );
} );
}
};
wc_users_fields.init();
});
@@ -0,0 +1 @@
jQuery(function(e){var t={states:null,init:function(){"undefined"!=typeof wc_users_params.countries&&(this.states=JSON.parse(wc_users_params.countries.replace(/&quot;/g,'"'))),e(".js_field-country").selectWoo().on("change",this.change_country),e(".js_field-country").trigger("change",[!0]),e(document.body).on("change","select.js_field-state",this.change_state),e(document.body).on("click","button.js_copy-billing",this.copy_billing)},change_country:function(a,n){if(void 0===n&&(n=!1),null!==t.states){var o,i=e(this),c=i.val(),s=i.parents(".form-table").find(":input.js_field-state"),r=s.parent(),l=s.attr("name"),p=s.attr("id"),d="woocommerce.stickState-"+c,u=i.data(d)?i.data(d):s.val(),h=s.attr("placeholder");if(n&&i.data("woocommerce.stickState-"+c,u),r.show().find(".select2-container").remove(),e.isEmptyObject(t.states[c]))o=e('<input type="text" />').prop("id",p).prop("name",l).prop("placeholder",h).addClass("js_field-state regular-text").val(u),s.replaceWith(o);else{var g=t.states[c],f=e('<option value=""></option>').text(t.i18n_select_state_text);o=e('<select style="width: 25em;"></select>').prop("id",p).prop("name",l).prop("placeholder",h).addClass("js_field-state").append(f),e.each(g,function(t){var a=e("<option></option>").prop("value",t).text(g[t]);o.append(a)}),o.val(u),s.replaceWith(o),o.show().selectWoo().hide().trigger("change")}e(document.body).trigger("contry-change.woocommerce",[c,e(this).closest("div")]),e(document.body).trigger("country-change.woocommerce",[c,e(this).closest("div")])}},change_state:function(){var t=e(this),a=t.val(),n=t.parents(".form-table").find(":input.js_field-country"),o=n.val();n.data("woocommerce.stickState-"+o,a)},copy_billing:function(t){t.preventDefault(),e("#fieldset-billing").find("input, select").each(function(t,a){var n=a.name.replace(/^billing_/,"shipping_"),o=e('[name="'+n+'"]');o.length&&o.val(a.value).trigger("change")})}};t.init()});
@@ -0,0 +1,38 @@
/* exported wcSetClipboard, wcClearClipboard */
/**
* Simple text copy functions using native browser clipboard capabilities.
* @since 3.2.0
*/
/**
* Set the user's clipboard contents.
*
* @param string data: Text to copy to clipboard.
* @param object $el: jQuery element to trigger copy events on. (Default: document)
*/
function wcSetClipboard( data, $el ) {
if ( 'undefined' === typeof $el ) {
$el = jQuery( document );
}
var $temp_input = jQuery( '<textarea style="opacity:0">' );
jQuery( 'body' ).append( $temp_input );
$temp_input.val( data ).trigger( 'select' );
$el.trigger( 'beforecopy' );
try {
document.execCommand( 'copy' );
$el.trigger( 'aftercopy' );
} catch ( err ) {
$el.trigger( 'aftercopyfailure' );
}
$temp_input.remove();
}
/**
* Clear the user's clipboard.
*/
function wcClearClipboard() {
wcSetClipboard( '' );
}
@@ -0,0 +1 @@
function wcSetClipboard(e,r){void 0===r&&(r=jQuery(document));var t=jQuery('<textarea style="opacity:0">');jQuery("body").append(t),t.val(e).trigger("select"),r.trigger("beforecopy");try{document.execCommand("copy"),r.trigger("aftercopy")}catch(o){r.trigger("aftercopyfailure")}t.remove()}function wcClearClipboard(){wcSetClipboard("")}
@@ -0,0 +1,416 @@
/*global wc_enhanced_select_params */
jQuery( function( $ ) {
function getEnhancedSelectFormatString() {
return {
'language': {
errorLoading: function() {
// Workaround for https://github.com/select2/select2/issues/4355 instead of i18n_ajax_error.
return wc_enhanced_select_params.i18n_searching;
},
inputTooLong: function( args ) {
var overChars = args.input.length - args.maximum;
if ( 1 === overChars ) {
return wc_enhanced_select_params.i18n_input_too_long_1;
}
return wc_enhanced_select_params.i18n_input_too_long_n.replace( '%qty%', overChars );
},
inputTooShort: function( args ) {
var remainingChars = args.minimum - args.input.length;
if ( 1 === remainingChars ) {
return wc_enhanced_select_params.i18n_input_too_short_1;
}
return wc_enhanced_select_params.i18n_input_too_short_n.replace( '%qty%', remainingChars );
},
loadingMore: function() {
return wc_enhanced_select_params.i18n_load_more;
},
maximumSelected: function( args ) {
if ( args.maximum === 1 ) {
return wc_enhanced_select_params.i18n_selection_too_long_1;
}
return wc_enhanced_select_params.i18n_selection_too_long_n.replace( '%qty%', args.maximum );
},
noResults: function() {
return wc_enhanced_select_params.i18n_no_matches;
},
searching: function() {
return wc_enhanced_select_params.i18n_searching;
}
}
};
}
try {
$( document.body )
.on( 'wc-enhanced-select-init', function() {
// Regular select boxes
$( ':input.wc-enhanced-select, :input.chosen_select' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = $.extend({
minimumResultsForSearch: 10,
allowClear: $( this ).data( 'allow_clear' ) ? true : false,
placeholder: $( this ).data( 'placeholder' )
}, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
$( ':input.wc-enhanced-select-nostd, :input.chosen_select_nostd' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = $.extend({
minimumResultsForSearch: 10,
allowClear: true,
placeholder: $( this ).data( 'placeholder' )
}, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
function display_result( self, select2_args ) {
select2_args = $.extend( select2_args, getEnhancedSelectFormatString() );
$( self ).selectWoo( select2_args ).addClass( 'enhanced' );
if ( $( self ).data( 'sortable' ) ) {
var $select = $(self);
var $list = $( self ).next( '.select2-container' ).find( 'ul.select2-selection__rendered' );
$list.sortable({
placeholder : 'ui-state-highlight select2-selection__choice',
forcePlaceholderSize: true,
items : 'li:not(.select2-search__field)',
tolerance : 'pointer',
stop: function() {
$( $list.find( '.select2-selection__choice' ).get().reverse() ).each( function() {
var id = $( this ).data( 'data' ).id;
var option = $select.find( 'option[value="' + id + '"]' )[0];
$select.prepend( option );
} );
}
});
// Keep multiselects ordered alphabetically if they are not sortable.
} else if ( $( self ).prop( 'multiple' ) ) {
$( self ).on( 'change', function(){
var $children = $( self ).children();
$children.sort(function(a, b){
var atext = a.text.toLowerCase();
var btext = b.text.toLowerCase();
if ( atext > btext ) {
return 1;
}
if ( atext < btext ) {
return -1;
}
return 0;
});
$( self ).html( $children );
});
}
}
// Ajax product search box
$( ':input.wc-product-search' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = {
allowClear: $( this ).data( 'allow_clear' ) ? true : false,
placeholder: $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3',
escapeMarkup: function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 250,
data: function( params ) {
return {
term : params.term,
action : $( this ).data( 'action' ) || 'woocommerce_json_search_products_and_variations',
security : wc_enhanced_select_params.search_products_nonce,
exclude : $( this ).data( 'exclude' ),
exclude_type : $( this ).data( 'exclude_type' ),
include : $( this ).data( 'include' ),
limit : $( this ).data( 'limit' ),
display_stock: $( this ).data( 'display_stock' )
};
},
processResults: function( data ) {
var terms = [];
if ( data ) {
$.each( data, function( id, text ) {
terms.push( { id: id, text: text } );
});
}
return {
results: terms
};
},
cache: true
}
};
display_result( this, select2_args );
});
// Ajax Page Search.
$( ':input.wc-page-search' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = {
allowClear: $( this ).data( 'allow_clear' ) ? true : false,
placeholder: $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3',
escapeMarkup: function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 250,
data: function( params ) {
return {
term : params.term,
action : $( this ).data( 'action' ) || 'woocommerce_json_search_pages',
security : wc_enhanced_select_params.search_pages_nonce,
exclude : $( this ).data( 'exclude' ),
post_status : $( this ).data( 'post_status' ),
limit : $( this ).data( 'limit' ),
};
},
processResults: function( data ) {
var terms = [];
if ( data ) {
$.each( data, function( id, text ) {
terms.push( { id: id, text: text } );
} );
}
return {
results: terms
};
},
cache: true
}
};
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
// Ajax customer search boxes
$( ':input.wc-customer-search' ).filter( ':not(.enhanced)' ).each( function() {
var select2_args = {
allowClear: $( this ).data( 'allow_clear' ) ? true : false,
placeholder: $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '1',
escapeMarkup: function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 1000,
data: function( params ) {
return {
term: params.term,
action: 'woocommerce_json_search_customers',
security: wc_enhanced_select_params.search_customers_nonce,
exclude: $( this ).data( 'exclude' )
};
},
processResults: function( data ) {
var terms = [];
if ( data ) {
$.each( data, function( id, text ) {
terms.push({
id: id,
text: text
});
});
}
return {
results: terms
};
},
cache: true
}
};
select2_args = $.extend( select2_args, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
if ( $( this ).data( 'sortable' ) ) {
var $select = $(this);
var $list = $( this ).next( '.select2-container' ).find( 'ul.select2-selection__rendered' );
$list.sortable({
placeholder : 'ui-state-highlight select2-selection__choice',
forcePlaceholderSize: true,
items : 'li:not(.select2-search__field)',
tolerance : 'pointer',
stop: function() {
$( $list.find( '.select2-selection__choice' ).get().reverse() ).each( function() {
var id = $( this ).data( 'data' ).id;
var option = $select.find( 'option[value="' + id + '"]' )[0];
$select.prepend( option );
} );
}
});
}
});
// Ajax category search boxes
$( ':input.wc-category-search' ).filter( ':not(.enhanced)' ).each( function() {
var return_format = $( this ).data( 'return_id' ) ? 'id' : 'slug';
var select2_args = $.extend( {
allowClear : $( this ).data( 'allow_clear' ) ? true : false,
placeholder : $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) ? $( this ).data( 'minimum_input_length' ) : '3',
escapeMarkup : function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 250,
data: function( params ) {
return {
term: params.term,
action: 'woocommerce_json_search_categories',
security: wc_enhanced_select_params.search_categories_nonce
};
},
processResults: function( data ) {
var terms = [];
if ( data ) {
$.each( data, function( id, term ) {
terms.push({
id: 'id' === return_format ? term.term_id : term.slug,
text: term.formatted_name
});
});
}
return {
results: terms
};
},
cache: true
}
}, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
// Ajax category search boxes
$( ':input.wc-taxonomy-term-search' ).filter( ':not(.enhanced)' ).each( function() {
var return_format = $( this ).data( 'return_id' ) ? 'id' : 'slug';
var select2_args = $.extend( {
allowClear : $( this ).data( 'allow_clear' ) ? true : false,
placeholder : $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) !== null && $( this ).data( 'minimum_input_length' ) !== undefined ? $( this ).data( 'minimum_input_length' ) : '3',
escapeMarkup : function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 250,
data: function( params ) {
return {
taxonomy: $( this ).data( 'taxonomy' ),
limit: $( this ).data( 'limit' ),
orderby: $( this ).data( 'orderby'),
term: params.term,
action: 'woocommerce_json_search_taxonomy_terms',
security: wc_enhanced_select_params.search_taxonomy_terms_nonce
};
},
processResults: function( data ) {
var terms = [];
if ( data ) {
$.each( data, function( id, term ) {
terms.push({
id: 'id' === return_format ? term.term_id : term.slug,
text: term.name
});
});
}
return {
results: terms
};
},
cache: true
}
}, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
$( ':input.wc-attribute-search' ).filter( ':not(.enhanced)' ).each( function() {
var select2Element = this;
var select2_args = $.extend( {
allowClear : $( this ).data( 'allow_clear' ) ? true : false,
placeholder : $( this ).data( 'placeholder' ),
minimumInputLength: $( this ).data( 'minimum_input_length' ) !== null && $( this ).data( 'minimum_input_length' ) !== undefined ? $( this ).data( 'minimum_input_length' ) : '3',
escapeMarkup : function( m ) {
return m;
},
ajax: {
url: wc_enhanced_select_params.ajax_url,
dataType: 'json',
delay: 250,
data: function( params ) {
return {
term: params.term,
action: 'woocommerce_json_search_product_attributes',
security: wc_enhanced_select_params.search_product_attributes_nonce
};
},
processResults: function( data ) {
var disabledItems = $( select2Element ).data('disabled-items') || [];
var terms = [];
if ( data ) {
$.each( data, function( id, term ) {
terms.push({
id: term.slug,
text: term.name,
disabled: disabledItems.includes( term.slug )
});
});
}
return {
results: terms
};
},
cache: true
}
}, getEnhancedSelectFormatString() );
$( this ).selectWoo( select2_args ).addClass( 'enhanced' );
});
})
// WooCommerce Backbone Modal
.on( 'wc_backbone_modal_before_remove', function() {
$( '.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search' ).filter( '.select2-hidden-accessible' )
.selectWoo( 'close' );
})
.trigger( 'wc-enhanced-select-init' );
$( 'html' ).on( 'click', function( event ) {
if ( this === event.target ) {
$( '.wc-enhanced-select, :input.wc-product-search, :input.wc-customer-search' ).filter( '.select2-hidden-accessible' )
.selectWoo( 'close' );
}
} );
} catch( err ) {
// If select2 failed (conflict?) log the error but don't stop other scripts breaking.
window.console.log( err );
}
});
@@ -0,0 +1 @@
jQuery(function(e){function t(){return{language:{errorLoading:function(){return wc_enhanced_select_params.i18n_searching},inputTooLong:function(e){var t=e.input.length-e.maximum;return 1===t?wc_enhanced_select_params.i18n_input_too_long_1:wc_enhanced_select_params.i18n_input_too_long_n.replace("%qty%",t)},inputTooShort:function(e){var t=e.minimum-e.input.length;return 1===t?wc_enhanced_select_params.i18n_input_too_short_1:wc_enhanced_select_params.i18n_input_too_short_n.replace("%qty%",t)},loadingMore:function(){return wc_enhanced_select_params.i18n_load_more},maximumSelected:function(e){return 1===e.maximum?wc_enhanced_select_params.i18n_selection_too_long_1:wc_enhanced_select_params.i18n_selection_too_long_n.replace("%qty%",e.maximum)},noResults:function(){return wc_enhanced_select_params.i18n_no_matches},searching:function(){return wc_enhanced_select_params.i18n_searching}}}}try{e(document.body).on("wc-enhanced-select-init",function(){e(":input.wc-enhanced-select, :input.chosen_select").filter(":not(.enhanced)").each(function(){var a=e.extend({minimumResultsForSearch:10,allowClear:!!e(this).data("allow_clear"),placeholder:e(this).data("placeholder")},t());e(this).selectWoo(a).addClass("enhanced")}),e(":input.wc-enhanced-select-nostd, :input.chosen_select_nostd").filter(":not(.enhanced)").each(function(){var a=e.extend({minimumResultsForSearch:10,allowClear:!0,placeholder:e(this).data("placeholder")},t());e(this).selectWoo(a).addClass("enhanced")}),e(":input.wc-product-search").filter(":not(.enhanced)").each(function(){!function(a,n){if(n=e.extend(n,t()),e(a).selectWoo(n).addClass("enhanced"),e(a).data("sortable")){var c=e(a),i=e(a).next(".select2-container").find("ul.select2-selection__rendered");i.sortable({placeholder:"ui-state-highlight select2-selection__choice",forcePlaceholderSize:!0,items:"li:not(.select2-search__field)",tolerance:"pointer",stop:function(){e(i.find(".select2-selection__choice").get().reverse()).each(function(){var t=e(this).data("data").id,a=c.find('option[value="'+t+'"]')[0];c.prepend(a)})}})}else e(a).prop("multiple")&&e(a).on("change",function(){var t=e(a).children();t.sort(function(e,t){var a=e.text.toLowerCase(),n=t.text.toLowerCase();return a>n?1:a<n?-1:0}),e(a).html(t)})}(this,{allowClear:!!e(this).data("allow_clear"),placeholder:e(this).data("placeholder"),minimumInputLength:e(this).data("minimum_input_length")?e(this).data("minimum_input_length"):"3",escapeMarkup:function(e){return e},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",delay:250,data:function(t){return{term:t.term,action:e(this).data("action")||"woocommerce_json_search_products_and_variations",security:wc_enhanced_select_params.search_products_nonce,exclude:e(this).data("exclude"),exclude_type:e(this).data("exclude_type"),include:e(this).data("include"),limit:e(this).data("limit"),display_stock:e(this).data("display_stock")}},processResults:function(t){var a=[];return t&&e.each(t,function(e,t){a.push({id:e,text:t})}),{results:a}},cache:!0}})}),e(":input.wc-page-search").filter(":not(.enhanced)").each(function(){var t={allowClear:!!e(this).data("allow_clear"),placeholder:e(this).data("placeholder"),minimumInputLength:e(this).data("minimum_input_length")?e(this).data("minimum_input_length"):"3",escapeMarkup:function(e){return e},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",delay:250,data:function(t){return{term:t.term,action:e(this).data("action")||"woocommerce_json_search_pages",security:wc_enhanced_select_params.search_pages_nonce,exclude:e(this).data("exclude"),post_status:e(this).data("post_status"),limit:e(this).data("limit")}},processResults:function(t){var a=[];return t&&e.each(t,function(e,t){a.push({id:e,text:t})}),{results:a}},cache:!0}};e(this).selectWoo(t).addClass("enhanced")}),e(":input.wc-customer-search").filter(":not(.enhanced)").each(function(){var a={allowClear:!!e(this).data("allow_clear"),placeholder:e(this).data("placeholder"),minimumInputLength:e(this).data("minimum_input_length")?e(this).data("minimum_input_length"):"1",escapeMarkup:function(e){return e},ajax:{url:wc_enhanced_select_params.ajax_url,dataType:"json",delay:1e3,data:function(t){return{term:t.term,action:"woocommerce_json_search_customers",security:wc_enhanced_select_params.search_customers_nonce,exclude:e(this).data("exclude")}},processResults:function(t){var a=[];return t&&e.each(t,function(e,t){a.push({id:e,text:t})}),{results:a}},cache:!0}};if(a=e.extend(a,t()),e(this).selectWoo(a).addClass("enhanced"),e(this).data("sortable")){var n=e(this),c=e(this).next(".select2-container").find("ul.select2-selection__rendered");c.sortable({placeholder:"ui-state-highlight select2-selection__choice",forcePlaceholderSize:!0,items:"li:not(.select2-search__field)",tolerance:"pointer",stop:function(){e(c.find(".select2-selection__choice").get().reverse()).each(function(){var t=e(this).data("data").id,a=n.find('option[value="'+t+'"]')[0];n.prepend(a)})}})}}),e(":input.wc-category-search").filter(":not(.enhancedLine truncated
@@ -0,0 +1,92 @@
/* global wc_orders_params */
jQuery( function( $ ) {
if ( typeof wc_orders_params === 'undefined' ) {
return false;
}
/**
* WCOrdersTable class.
*/
var WCOrdersTable = function() {
$( document )
.on(
'click',
'.post-type-shop_order .wp-list-table tbody td, .woocommerce_page_wc-orders .wp-list-table.orders tbody td',
this.onRowClick
)
.on( 'click', '.order-preview:not(.disabled)', this.onPreview );
};
/**
* Click a row.
*/
WCOrdersTable.prototype.onRowClick = function( e ) {
if ( $( e.target ).filter( 'a, a *, .no-link, .no-link *, button, button *' ).length ) {
return true;
}
if ( window.getSelection && window.getSelection().toString().length ) {
return true;
}
var $row = $( this ).closest( 'tr' ),
href = $row.find( 'a.order-view' ).attr( 'href' );
if ( href && href.length ) {
e.preventDefault();
if ( e.metaKey || e.ctrlKey ) {
window.open( href, '_blank' );
} else {
window.location = href;
}
}
};
/**
* Preview an order.
*/
WCOrdersTable.prototype.onPreview = function() {
var $previewButton = $( this ),
$order_id = $previewButton.data( 'orderId' );
if ( $previewButton.data( 'order-data' ) ) {
$( this ).WCBackboneModal({
template: 'wc-modal-view-order',
variable : $previewButton.data( 'orderData' )
});
} else {
$previewButton.addClass( 'disabled' );
$.ajax({
url: wc_orders_params.ajax_url,
data: {
order_id: $order_id,
action : 'woocommerce_get_order_details',
security: wc_orders_params.preview_nonce
},
type: 'GET',
success: function( response ) {
$( '.order-preview' ).removeClass( 'disabled' );
if ( response.success ) {
$previewButton.data( 'orderData', response.data );
$( this ).WCBackboneModal({
template: 'wc-modal-view-order',
variable : response.data
});
}
}
});
}
return false;
};
/**
* Init WCOrdersTable.
*/
new WCOrdersTable();
} );
@@ -0,0 +1 @@
jQuery(function(e){if("undefined"==typeof wc_orders_params)return!1;var t=function(){e(document).on("click",".post-type-shop_order .wp-list-table tbody td, .woocommerce_page_wc-orders .wp-list-table.orders tbody td",this.onRowClick).on("click",".order-preview:not(.disabled)",this.onPreview)};t.prototype.onRowClick=function(t){if(e(t.target).filter("a, a *, .no-link, .no-link *, button, button *").length)return!0;if(window.getSelection&&window.getSelection().toString().length)return!0;var r=e(this).closest("tr").find("a.order-view").attr("href");r&&r.length&&(t.preventDefault(),t.metaKey||t.ctrlKey?window.open(r,"_blank"):window.location=r)},t.prototype.onPreview=function(){var t=e(this),r=t.data("orderId");return t.data("order-data")?e(this).WCBackboneModal({template:"wc-modal-view-order",variable:t.data("orderData")}):(t.addClass("disabled"),e.ajax({url:wc_orders_params.ajax_url,data:{order_id:r,action:"woocommerce_get_order_details",security:wc_orders_params.preview_nonce},type:"GET",success:function(r){e(".order-preview").removeClass("disabled"),r.success&&(t.data("orderData",r.data),e(this).WCBackboneModal({template:"wc-modal-view-order",variable:r.data}))}})),!1},new t});
@@ -0,0 +1,112 @@
/*global ajaxurl, wc_product_export_params */
;(function ( $, window ) {
/**
* productExportForm handles the export process.
*/
var productExportForm = function( $form ) {
this.$form = $form;
this.xhr = false;
// Initial state.
this.$form.find('.woocommerce-exporter-progress').val( 0 );
// Methods.
this.processStep = this.processStep.bind( this );
// Events.
$form.on( 'submit', { productExportForm: this }, this.onSubmit );
$form.find( '.woocommerce-exporter-types' ).on( 'change', { productExportForm: this }, this.exportTypeFields );
};
/**
* Handle export form submission.
*/
productExportForm.prototype.onSubmit = function( event ) {
event.preventDefault();
var currentDate = new Date(),
day = currentDate.getDate(),
month = currentDate.getMonth() + 1,
year = currentDate.getFullYear(),
timestamp = currentDate.getTime(),
filename = 'wc-product-export-' + day + '-' + month + '-' + year + '-' + timestamp + '.csv';
event.data.productExportForm.$form.addClass( 'woocommerce-exporter__exporting' );
event.data.productExportForm.$form.find('.woocommerce-exporter-progress').val( 0 );
event.data.productExportForm.$form.find('.woocommerce-exporter-button').prop( 'disabled', true );
event.data.productExportForm.processStep( 1, $( this ).serialize(), '', filename );
};
/**
* Process the current export step.
*/
productExportForm.prototype.processStep = function( step, data, columns, filename ) {
var $this = this,
selected_columns = $( '.woocommerce-exporter-columns' ).val(),
export_meta = $( '#woocommerce-exporter-meta:checked' ).length ? 1: 0,
export_types = $( '.woocommerce-exporter-types' ).val(),
export_category = $( '.woocommerce-exporter-category' ).val();
$.ajax( {
type: 'POST',
url: ajaxurl,
data: {
form : data,
action : 'woocommerce_do_ajax_product_export',
step : step,
columns : columns,
selected_columns : selected_columns,
export_meta : export_meta,
export_types : export_types,
export_category : export_category,
filename : filename,
security : wc_product_export_params.export_nonce
},
dataType: 'json',
success: function( response ) {
if ( response.success ) {
if ( 'done' === response.data.step ) {
$this.$form.find('.woocommerce-exporter-progress').val( response.data.percentage );
window.location = response.data.url;
setTimeout( function() {
$this.$form.removeClass( 'woocommerce-exporter__exporting' );
$this.$form.find('.woocommerce-exporter-button').prop( 'disabled', false );
}, 2000 );
} else {
$this.$form.find('.woocommerce-exporter-progress').val( response.data.percentage );
$this.processStep( parseInt( response.data.step, 10 ), data, response.data.columns, filename );
}
}
}
} ).fail( function( response ) {
window.console.log( response );
} );
};
/**
* Handle fields per export type.
*/
productExportForm.prototype.exportTypeFields = function() {
var exportCategory = $( '.woocommerce-exporter-category' );
if ( -1 !== $.inArray( 'variation', $( this ).val() ) ) {
exportCategory.closest( 'tr' ).hide();
exportCategory.val( '' ).trigger( 'change' ); // Reset WooSelect selected value.
} else {
exportCategory.closest( 'tr' ).show();
}
};
/**
* Function to call productExportForm on jquery selector.
*/
$.fn.wc_product_export_form = function() {
new productExportForm( this );
return this;
};
$( '.woocommerce-exporter' ).wc_product_export_form();
})( jQuery, window );
@@ -0,0 +1 @@
!function(o,e){var r=function(o){this.$form=o,this.xhr=!1,this.$form.find(".woocommerce-exporter-progress").val(0),this.processStep=this.processStep.bind(this),o.on("submit",{productExportForm:this},this.onSubmit),o.find(".woocommerce-exporter-types").on("change",{productExportForm:this},this.exportTypeFields)};r.prototype.onSubmit=function(e){e.preventDefault();var r=new Date,t="wc-product-export-"+r.getDate()+"-"+(r.getMonth()+1)+"-"+r.getFullYear()+"-"+r.getTime()+".csv";e.data.productExportForm.$form.addClass("woocommerce-exporter__exporting"),e.data.productExportForm.$form.find(".woocommerce-exporter-progress").val(0),e.data.productExportForm.$form.find(".woocommerce-exporter-button").prop("disabled",!0),e.data.productExportForm.processStep(1,o(this).serialize(),"",t)},r.prototype.processStep=function(r,t,c,p){var a=this,s=o(".woocommerce-exporter-columns").val(),m=o("#woocommerce-exporter-meta:checked").length?1:0,n=o(".woocommerce-exporter-types").val(),i=o(".woocommerce-exporter-category").val();o.ajax({type:"POST",url:ajaxurl,data:{form:t,action:"woocommerce_do_ajax_product_export",step:r,columns:c,selected_columns:s,export_meta:m,export_types:n,export_category:i,filename:p,security:wc_product_export_params.export_nonce},dataType:"json",success:function(o){o.success&&("done"===o.data.step?(a.$form.find(".woocommerce-exporter-progress").val(o.data.percentage),e.location=o.data.url,setTimeout(function(){a.$form.removeClass("woocommerce-exporter__exporting"),a.$form.find(".woocommerce-exporter-button").prop("disabled",!1)},2e3)):(a.$form.find(".woocommerce-exporter-progress").val(o.data.percentage),a.processStep(parseInt(o.data.step,10),t,o.data.columns,p)))}}).fail(function(o){e.console.log(o)})},r.prototype.exportTypeFields=function(){var e=o(".woocommerce-exporter-category");-1!==o.inArray("variation",o(this).val())?(e.closest("tr").hide(),e.val("").trigger("change")):e.closest("tr").show()},o.fn.wc_product_export_form=function(){return new r(this),this},o(".woocommerce-exporter").wc_product_export_form()}(jQuery,window);
@@ -0,0 +1,99 @@
/*global ajaxurl, wc_product_import_params */
;(function ( $, window ) {
/**
* productImportForm handles the import process.
*/
var productImportForm = function( $form ) {
this.$form = $form;
this.xhr = false;
this.mapping = wc_product_import_params.mapping;
this.position = 0;
this.file = wc_product_import_params.file;
this.update_existing = wc_product_import_params.update_existing;
this.delimiter = wc_product_import_params.delimiter;
this.security = wc_product_import_params.import_nonce;
this.character_encoding = wc_product_import_params.character_encoding;
// Number of import successes/failures.
this.imported = 0;
this.imported_variations = 0;
this.failed = 0;
this.updated = 0;
this.skipped = 0;
// Initial state.
this.$form.find('.woocommerce-importer-progress').val( 0 );
this.run_import = this.run_import.bind( this );
// Start importing.
this.run_import();
};
/**
* Run the import in batches until finished.
*/
productImportForm.prototype.run_import = function() {
var $this = this;
$.ajax( {
type: 'POST',
url: ajaxurl,
data: {
action : 'woocommerce_do_ajax_product_import',
position : $this.position,
mapping : $this.mapping,
file : $this.file,
update_existing : $this.update_existing,
delimiter : $this.delimiter,
security : $this.security,
character_encoding: $this.character_encoding
},
dataType: 'json',
success: function( response ) {
if ( response.success ) {
$this.position = response.data.position;
$this.imported += response.data.imported;
$this.imported_variations += response.data.imported_variations;
$this.failed += response.data.failed;
$this.updated += response.data.updated;
$this.skipped += response.data.skipped;
$this.$form.find('.woocommerce-importer-progress').val( response.data.percentage );
if ( 'done' === response.data.position ) {
var file_name = wc_product_import_params.file.split( '/' ).pop();
window.location = response.data.url +
'&products-imported=' +
parseInt( $this.imported, 10 ) +
'&products-imported-variations=' +
parseInt( $this.imported_variations, 10 ) +
'&products-failed=' +
parseInt( $this.failed, 10 ) +
'&products-updated=' +
parseInt( $this.updated, 10 ) +
'&products-skipped=' +
parseInt( $this.skipped, 10 ) +
'&file-name=' +
file_name;
} else {
$this.run_import();
}
}
}
} ).fail( function( response ) {
window.console.log( response );
} );
};
/**
* Function to call productImportForm on jQuery selector.
*/
$.fn.wc_product_importer = function() {
new productImportForm( this );
return this;
};
$( '.woocommerce-importer' ).wc_product_importer();
})( jQuery, window );
@@ -0,0 +1 @@
!function(i,t){var r=function(i){this.$form=i,this.xhr=!1,this.mapping=wc_product_import_params.mapping,this.position=0,this.file=wc_product_import_params.file,this.update_existing=wc_product_import_params.update_existing,this.delimiter=wc_product_import_params.delimiter,this.security=wc_product_import_params.import_nonce,this.character_encoding=wc_product_import_params.character_encoding,this.imported=0,this.imported_variations=0,this.failed=0,this.updated=0,this.skipped=0,this.$form.find(".woocommerce-importer-progress").val(0),this.run_import=this.run_import.bind(this),this.run_import()};r.prototype.run_import=function(){var r=this;i.ajax({type:"POST",url:ajaxurl,data:{action:"woocommerce_do_ajax_product_import",position:r.position,mapping:r.mapping,file:r.file,update_existing:r.update_existing,delimiter:r.delimiter,security:r.security,character_encoding:r.character_encoding},dataType:"json",success:function(i){if(i.success)if(r.position=i.data.position,r.imported+=i.data.imported,r.imported_variations+=i.data.imported_variations,r.failed+=i.data.failed,r.updated+=i.data.updated,r.skipped+=i.data.skipped,r.$form.find(".woocommerce-importer-progress").val(i.data.percentage),"done"===i.data.position){var o=wc_product_import_params.file.split("/").pop();t.location=i.data.url+"&products-imported="+parseInt(r.imported,10)+"&products-imported-variations="+parseInt(r.imported_variations,10)+"&products-failed="+parseInt(r.failed,10)+"&products-updated="+parseInt(r.updated,10)+"&products-skipped="+parseInt(r.skipped,10)+"&file-name="+o}else r.run_import()}}).fail(function(i){t.console.log(i)})},i.fn.wc_product_importer=function(){return new r(this),this},i(".woocommerce-importer").wc_product_importer()}(jQuery,window);
@@ -0,0 +1,322 @@
/*global wc_setup_params */
/*global wc_setup_currencies */
/*global wc_base_state */
/* @deprecated 4.6.0 */
jQuery( function( $ ) {
function blockWizardUI() {
$('.wc-setup-content').block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
}
$( '.button-next' ).on( 'click', function() {
var form = $( this ).parents( 'form' ).get( 0 );
if ( ( 'function' !== typeof form.checkValidity ) || form.checkValidity() ) {
blockWizardUI();
}
return true;
} );
$( 'form.address-step' ).on( 'submit', function( e ) {
var form = $( this );
if ( ( 'function' !== typeof form.checkValidity ) || form.checkValidity() ) {
blockWizardUI();
}
e.preventDefault();
$('.wc-setup-content').unblock();
$( this ).WCBackboneModal( {
template: 'wc-modal-tracking-setup'
} );
$( document.body ).on( 'wc_backbone_modal_response', function() {
form.off( 'submit' ).trigger( 'submit' );
} );
$( '#wc_tracker_checkbox_dialog' ).on( 'change', function( e ) {
var eventTarget = $( e.target );
$( '#wc_tracker_checkbox' ).prop( 'checked', eventTarget.prop( 'checked' ) );
} );
$( '#wc_tracker_submit' ).on( 'click', function () {
form.off( 'submit' ).trigger( 'submit' );
} );
return true;
} );
$( '#store_country' ).on( 'change', function() {
// Prevent if we don't have the metabox data
if ( wc_setup_params.states === null ){
return;
}
var $this = $( this ),
country = $this.val(),
$state_select = $( '#store_state' );
if ( ! $.isEmptyObject( wc_setup_params.states[ country ] ) ) {
var states = wc_setup_params.states[ country ];
$state_select.empty();
$.each( states, function( index ) {
$state_select.append( $( '<option value="' + index + '">' + states[ index ] + '</option>' ) );
} );
$( '.store-state-container' ).show();
$state_select.selectWoo().val( wc_base_state ).trigger( 'change' ).prop( 'required', true );
} else {
$( '.store-state-container' ).hide();
$state_select.empty().val( '' ).trigger( 'change' ).prop( 'required', false );
}
$( '#currency_code' ).val( wc_setup_currencies[ country ] ).trigger( 'change' );
} );
/* Setup postcode field and validations */
$( '#store_country' ).on( 'change', function() {
if ( ! wc_setup_params.postcodes ) {
return;
}
var $this = $( this ),
country = $this.val(),
$store_postcode_input = $( '#store_postcode' ),
country_postcode_obj = wc_setup_params.postcodes[ country ];
// Default to required, if its unknown whether postcode is required or not.
if ( $.isEmptyObject( country_postcode_obj ) || country_postcode_obj.required ) {
$store_postcode_input.attr( 'required', 'true' );
} else {
$store_postcode_input.prop( 'required', false );
}
} );
$( '#store_country' ).trigger( 'change' );
$( '.wc-wizard-services' ).on( 'change', '.wc-wizard-service-enable input', function() {
if ( $( this ).is( ':checked' ) ) {
$( this ).closest( '.wc-wizard-service-toggle' ).removeClass( 'disabled' );
$( this ).closest( '.wc-wizard-service-item' ).addClass( 'checked' );
$( this ).closest( '.wc-wizard-service-item' )
.find( '.wc-wizard-service-settings' ).removeClass( 'hide' );
} else {
$( this ).closest( '.wc-wizard-service-toggle' ).addClass( 'disabled' );
$( this ).closest( '.wc-wizard-service-item' ).removeClass( 'checked' );
$( this ).closest( '.wc-wizard-service-item' )
.find( '.wc-wizard-service-settings' ).addClass( 'hide' );
}
} );
$( '.wc-wizard-services' ).on( 'keyup', function( e ) {
var code = e.keyCode || e.which,
$focused = $( document.activeElement );
if ( $focused.is( '.wc-wizard-service-toggle, .wc-wizard-service-enable' ) && ( 13 === code || 32 === code ) ) {
$focused.find( ':input' ).trigger( 'click' );
}
} );
$( '.wc-wizard-services' ).on( 'click', '.wc-wizard-service-enable', function( e ) {
var eventTarget = $( e.target );
if ( eventTarget.is( 'input' ) ) {
e.stopPropagation();
return;
}
var $checkbox = $( this ).find( 'input[type="checkbox"]' );
$checkbox.prop( 'checked', ! $checkbox.prop( 'checked' ) ).trigger( 'change' );
} );
$( '.wc-wizard-services-list-toggle' ).on( 'click', function() {
var listToggle = $( this ).closest( '.wc-wizard-services-list-toggle' );
if ( listToggle.hasClass( 'closed' ) ) {
listToggle.removeClass( 'closed' );
} else {
listToggle.addClass( 'closed' );
}
$( this ).closest( '.wc-wizard-services' ).find( '.wc-wizard-service-item' )
.slideToggle()
.css( 'display', 'flex' );
} );
$( '.wc-wizard-services' ).on( 'change', '.wc-wizard-shipping-method-select .method', function( e ) {
var zone = $( this ).closest( '.wc-wizard-service-description' );
var selectedMethod = e.target.value;
var description = zone.find( '.shipping-method-descriptions' );
description.find( '.shipping-method-description' ).addClass( 'hide' );
description.find( '.' + selectedMethod ).removeClass( 'hide' );
var $checkbox = zone.parent().find( 'input[type="checkbox"]' );
var settings = zone.find( '.shipping-method-settings' );
settings
.find( '.shipping-method-setting' )
.addClass( 'hide' )
.find( '.shipping-method-required-field' )
.prop( 'required', false );
settings
.find( '.' + selectedMethod )
.removeClass( 'hide' )
.find( '.shipping-method-required-field' )
.prop( 'required', $checkbox.prop( 'checked' ) );
} ).find( '.wc-wizard-shipping-method-select .method' ).trigger( 'change' );
$( '.wc-wizard-services' ).on( 'change', '.wc-wizard-shipping-method-enable', function() {
var checked = $( this ).is( ':checked' );
var selectedMethod = $( this )
.closest( '.wc-wizard-service-item' )
.find( '.wc-wizard-shipping-method-select .method' )
.val();
$( this )
.closest( '.wc-wizard-service-item' )
.find( '.' + selectedMethod )
.find( '.shipping-method-required-field' )
.prop( 'required', checked );
} );
function submitActivateForm() {
$( 'form.activate-jetpack' ).trigger( 'submit' );
}
function waitForJetpackInstall() {
wp.ajax.post( 'setup_wizard_check_jetpack' )
.then( function( result ) {
// If we receive success, or an unexpected result
// let the form submit.
if (
! result ||
! result.is_active ||
'yes' === result.is_active
) {
return submitActivateForm();
}
// Wait until checking the status again
setTimeout( waitForJetpackInstall, 3000 );
} )
.fail( function() {
// Submit the form as normal if the request fails
submitActivateForm();
} );
}
// Wait for a pending Jetpack install to finish before triggering a "save"
// on the activate step, which launches the Jetpack connection flow.
$( '.activate-jetpack' ).on( 'click', '.button-primary', function( e ) {
blockWizardUI();
if ( 'no' === wc_setup_params.pending_jetpack_install ) {
return true;
}
e.preventDefault();
waitForJetpackInstall();
} );
$( '.activate-new-onboarding' ).on( 'click', '.button-primary', function() {
// Show pending spinner while activate happens.
blockWizardUI();
} );
$( '.wc-wizard-services' ).on( 'change', 'input#stripe_create_account, input#ppec_paypal_reroute_requests', function() {
if ( $( this ).is( ':checked' ) ) {
$( this ).closest( '.wc-wizard-service-settings' )
.find( 'input.payment-email-input' )
.attr( 'type', 'email' )
.prop( 'disabled', false )
.prop( 'required', true );
} else {
$( this ).closest( '.wc-wizard-service-settings' )
.find( 'input.payment-email-input' )
.attr( 'type', null )
.prop( 'disabled', true )
.prop( 'required', false );
}
} ).find( 'input#stripe_create_account, input#ppec_paypal_reroute_requests' ).trigger( 'change' );
function addPlugins( bySlug, $el, hover ) {
var plugins = $el.data( 'plugins' );
for ( var i in Array.isArray( plugins ) ? plugins : [] ) {
var slug = plugins[ i ].slug;
bySlug[ slug ] = bySlug[ slug ] ||
$( '<span class="plugin-install-info-list-item">' )
.append( '<a href="https://wordpress.org/plugins/' + slug + '/" target="_blank">' + plugins[ i ].name + '</a>' );
bySlug[ slug ].find( 'a' )
.on( 'mouseenter mouseleave', ( function( $hover, event ) {
$hover.toggleClass( 'plugin-install-source', 'mouseenter' === event.type );
} ).bind( null, hover ? $el.closest( hover ) : $el ) );
}
}
function updatePluginInfo() {
var pluginLinkBySlug = {};
var extraPlugins = [];
$( '.wc-wizard-service-enable input:checked' ).each( function() {
addPlugins( pluginLinkBySlug, $( this ), '.wc-wizard-service-item' );
var $container = $( this ).closest( '.wc-wizard-service-item' );
$container.find( 'input.payment-checkbox-input:checked' ).each( function() {
extraPlugins.push( $( this ).attr( 'id' ) );
addPlugins( pluginLinkBySlug, $( this ), '.wc-wizard-service-settings' );
} );
$container.find( '.wc-wizard-shipping-method-select .method' ).each( function() {
var $this = $( this );
if ( 'live_rates' === $this.val() ) {
addPlugins( pluginLinkBySlug, $this, '.wc-wizard-service-item' );
}
} );
} );
$( '.recommended-item input:checked' ).each( function() {
addPlugins( pluginLinkBySlug, $( this ), '.recommended-item' );
} );
var $list = $( 'span.plugin-install-info-list' ).empty();
for ( var slug in pluginLinkBySlug ) {
$list.append( pluginLinkBySlug[ slug ] );
}
if (
extraPlugins &&
wc_setup_params.current_step &&
wc_setup_params.i18n.extra_plugins[ wc_setup_params.current_step ] &&
wc_setup_params.i18n.extra_plugins[ wc_setup_params.current_step ][ extraPlugins.join( ',' ) ]
) {
$list.append(
wc_setup_params.i18n.extra_plugins[ wc_setup_params.current_step ][ extraPlugins.join( ',' ) ]
);
}
$( 'span.plugin-install-info' ).toggle( $list.children().length > 0 );
}
updatePluginInfo();
$( '.wc-setup-content' ).on( 'change', '[data-plugins]', updatePluginInfo );
$( document.body ).on( 'init_tooltips', function() {
$( '.help_tip' ).tipTip( {
'attribute': 'data-tip',
'fadeIn': 50,
'fadeOut': 50,
'delay': 200,
'defaultPosition': 'top'
} );
} ).trigger( 'init_tooltips' );
} );
@@ -0,0 +1 @@
jQuery(function(e){function i(){e(".wc-setup-content").block({message:null,overlayCSS:{background:"#fff",opacity:.6}})}function t(){e("form.activate-jetpack").trigger("submit")}function s(){wp.ajax.post("setup_wizard_check_jetpack").then(function(e){if(!e||!e.is_active||"yes"===e.is_active)return t();setTimeout(s,3e3)}).fail(function(){t()})}function c(i,t,s){var c=t.data("plugins");for(var r in Array.isArray(c)?c:[]){var n=c[r].slug;i[n]=i[n]||e('<span class="plugin-install-info-list-item">').append('<a href="https://wordpress.org/plugins/'+n+'/" target="_blank">'+c[r].name+"</a>"),i[n].find("a").on("mouseenter mouseleave",function(e,i){e.toggleClass("plugin-install-source","mouseenter"===i.type)}.bind(null,s?t.closest(s):t))}}function r(){var i={},t=[];e(".wc-wizard-service-enable input:checked").each(function(){c(i,e(this),".wc-wizard-service-item");var s=e(this).closest(".wc-wizard-service-item");s.find("input.payment-checkbox-input:checked").each(function(){t.push(e(this).attr("id")),c(i,e(this),".wc-wizard-service-settings")}),s.find(".wc-wizard-shipping-method-select .method").each(function(){var t=e(this);"live_rates"===t.val()&&c(i,t,".wc-wizard-service-item")})}),e(".recommended-item input:checked").each(function(){c(i,e(this),".recommended-item")});var s=e("span.plugin-install-info-list").empty();for(var r in i)s.append(i[r]);t&&wc_setup_params.current_step&&wc_setup_params.i18n.extra_plugins[wc_setup_params.current_step]&&wc_setup_params.i18n.extra_plugins[wc_setup_params.current_step][t.join(",")]&&s.append(wc_setup_params.i18n.extra_plugins[wc_setup_params.current_step][t.join(",")]),e("span.plugin-install-info").toggle(s.children().length>0)}e(".button-next").on("click",function(){var t=e(this).parents("form").get(0);return("function"!=typeof t.checkValidity||t.checkValidity())&&i(),!0}),e("form.address-step").on("submit",function(t){var s=e(this);return("function"!=typeof s.checkValidity||s.checkValidity())&&i(),t.preventDefault(),e(".wc-setup-content").unblock(),e(this).WCBackboneModal({template:"wc-modal-tracking-setup"}),e(document.body).on("wc_backbone_modal_response",function(){s.off("submit").trigger("submit")}),e("#wc_tracker_checkbox_dialog").on("change",function(i){var t=e(i.target);e("#wc_tracker_checkbox").prop("checked",t.prop("checked"))}),e("#wc_tracker_submit").on("click",function(){s.off("submit").trigger("submit")}),!0}),e("#store_country").on("change",function(){if(null!==wc_setup_params.states){var i=e(this).val(),t=e("#store_state");if(e.isEmptyObject(wc_setup_params.states[i]))e(".store-state-container").hide(),t.empty().val("").trigger("change").prop("required",!1);else{var s=wc_setup_params.states[i];t.empty(),e.each(s,function(i){t.append(e('<option value="'+i+'">'+s[i]+"</option>"))}),e(".store-state-container").show(),t.selectWoo().val(wc_base_state).trigger("change").prop("required",!0)}e("#currency_code").val(wc_setup_currencies[i]).trigger("change")}}),e("#store_country").on("change",function(){if(wc_setup_params.postcodes){var i=e(this).val(),t=e("#store_postcode"),s=wc_setup_params.postcodes[i];e.isEmptyObject(s)||s.required?t.attr("required","true"):t.prop("required",!1)}}),e("#store_country").trigger("change"),e(".wc-wizard-services").on("change",".wc-wizard-service-enable input",function(){e(this).is(":checked")?(e(this).closest(".wc-wizard-service-toggle").removeClass("disabled"),e(this).closest(".wc-wizard-service-item").addClass("checked"),e(this).closest(".wc-wizard-service-item").find(".wc-wizard-service-settings").removeClass("hide")):(e(this).closest(".wc-wizard-service-toggle").addClass("disabled"),e(this).closest(".wc-wizard-service-item").removeClass("checked"),e(this).closest(".wc-wizard-service-item").find(".wc-wizard-service-settings").addClass("hide"))}),e(".wc-wizard-services").on("keyup",function(i){var t=i.keyCode||i.which,s=e(document.activeElement);!s.is(".wc-wizard-service-toggle, .wc-wizard-service-enable")||13!==t&&32!==t||s.find(":input").trigger("click")}),e(".wc-wizard-services").on("click",".wc-wizard-service-enable",function(i){if(e(i.target).is("input"))i.stopPropagation();else{var t=e(this).find('input[type="checkbox"]');t.prop("checked",!t.prop("checked")).trigger("change")}}),e(".wc-wizard-services-list-toggle").on("click",function(){var i=e(this).closest(".wc-wizard-services-list-toggle");i.hasClass("closed")?i.removeClass("closed"):i.addClass("closed"),e(this).closest(".wc-wizard-services").find(".wc-wizard-service-item").slideToggle().css("display","flex")}),e(".wc-wizard-services").on("change",".wc-wizard-shipping-method-select .method",function(i){var t=e(this).closest(".wc-wizard-service-description"),s=i.target.value,c=t.find(".shipping-method-descriptions");c.find(".shipping-method-description").addClass("hide"),c.find("."+s).removeClass("hide");var r=t.parent().find('input[type="checkbox"]'),n=t.find(".shipping-method-settings");n.find(".shipping-method-setting").addClass("hide").find(".shipping-method-required-field"Line truncated
@@ -0,0 +1,211 @@
/* global shippingClassesLocalizeScript, ajaxurl */
( function( $, data, wp, ajaxurl ) {
$( function() {
var $tbody = $( '.wc-shipping-class-rows' ),
$save_button = $( '.wc-shipping-class-save' ),
$row_template = wp.template( 'wc-shipping-class-row' ),
$blank_template = wp.template( 'wc-shipping-class-row-blank' ),
// Backbone model
ShippingClass = Backbone.Model.extend({
save: function( changes ) {
$.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_classes_save_changes', {
wc_shipping_classes_nonce : data.wc_shipping_classes_nonce,
changes,
}, this.onSaveResponse, 'json' );
},
onSaveResponse: function( response, textStatus ) {
if ( 'success' === textStatus ) {
if ( response.success ) {
shippingClass.set( 'classes', response.data.shipping_classes );
shippingClass.trigger( 'saved:classes' );
} else if ( response.data ) {
window.alert( response.data );
} else {
window.alert( data.strings.save_failed );
}
}
shippingClassView.unblock();
}
} ),
// Backbone view
ShippingClassView = Backbone.View.extend({
rowTemplate: $row_template,
initialize: function() {
this.listenTo( this.model, 'saved:classes', this.render );
$( document.body ).on( 'click', '.wc-shipping-class-add-new', { view: this }, this.configureNewShippingClass );
$( document.body ).on( 'wc_backbone_modal_response', { view: this }, this.onConfigureShippingClassSubmitted );
$( document.body ).on( 'wc_backbone_modal_loaded', { view: this }, this.onLoadBackboneModal );
$( document.body ).on( 'wc_backbone_modal_validation', this.validateFormArguments );
},
block: function() {
$( this.el ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
unblock: function() {
$( this.el ).unblock();
},
render: function() {
var classes = _.indexBy( this.model.get( 'classes' ), 'term_id' ),
view = this;
this.$el.empty();
this.unblock();
if ( _.size( classes ) ) {
// Sort classes
classes = _.sortBy( classes, function( shipping_class ) {
return shipping_class.name;
} );
// Populate $tbody with the current classes
$.each( classes, function( id, rowData ) {
view.renderRow( rowData );
} );
} else {
view.$el.append( $blank_template );
}
},
renderRow: function( rowData ) {
var view = this;
view.$el.append( view.rowTemplate( rowData ) );
view.initRow( rowData );
},
initRow: function( rowData ) {
var view = this;
var $tr = view.$el.find( 'tr[data-id="' + rowData.term_id + '"]');
// Support select boxes
$tr.find( 'select' ).each( function() {
var attribute = $( this ).data( 'attribute' );
$( this ).find( 'option[value="' + rowData[ attribute ] + '"]' ).prop( 'selected', true );
} );
// Make the rows function
$tr.find( '.view' ).show();
$tr.find( '.edit' ).hide();
$tr.find( '.wc-shipping-class-edit' ).on( 'click', { view: this }, this.onEditRow );
$tr.find( '.wc-shipping-class-delete' ).on( 'click', { view: this }, this.onDeleteRow );
},
configureNewShippingClass: function( event ) {
event.preventDefault();
const term_id = 'new-1-' + Date.now();
$( this ).WCBackboneModal({
template : 'wc-shipping-class-configure',
variable : {
term_id,
action: 'create',
},
data : {
term_id,
action: 'create',
}
});
},
onConfigureShippingClassSubmitted: function( event, target, posted_data ) {
if ( target === 'wc-shipping-class-configure' ) {
const view = event.data.view;
const model = view.model;
const isNewRow = posted_data.term_id.includes( 'new-1-' );
const rowData = {
...posted_data,
};
if ( isNewRow ) {
rowData.newRow = true;
}
view.block();
model.save( {
[ posted_data.term_id ]: rowData
} );
}
},
validateFormArguments: function( element, target, data ) {
const requiredFields = [ 'name', 'description' ];
const formIsComplete = Object.keys( data ).every( key => {
if ( ! requiredFields.includes( key ) ) {
return true;
}
if ( Array.isArray( data[ key ] ) ) {
return data[ key ].length && !!data[ key ][ 0 ];
}
return !!data[ key ];
} );
const createButton = document.getElementById( 'btn-ok' );
createButton.disabled = ! formIsComplete;
createButton.classList.toggle( 'disabled', ! formIsComplete );
},
onEditRow: function( event ) {
const term_id = $( this ).closest('tr').data('id');
const model = event.data.view.model;
const classes = _.indexBy( model.get( 'classes' ), 'term_id' );
const rowData = classes[ term_id ];
event.preventDefault();
$( this ).WCBackboneModal({
template : 'wc-shipping-class-configure',
variable : {
action: 'edit',
...rowData
},
data : {
action: 'edit',
...rowData
}
});
},
onLoadBackboneModal: function( event, target ) {
if ( 'wc-shipping-class-configure' === target ) {
const modalContent = $('.wc-backbone-modal-content');
const term_id = modalContent.data('id');
const model = event.data.view.model;
const classes = _.indexBy( model.get( 'classes' ), 'term_id' );
const rowData = classes[ term_id ];
if ( rowData ) {
// Support select boxes
$('.wc-backbone-modal-content').find( 'select' ).each( function() {
var attribute = $( this ).data( 'attribute' );
$( this ).find( 'option[value="' + rowData[ attribute ] + '"]' ).prop( 'selected', true );
} );
}
}
},
onDeleteRow: function( event ) {
var view = event.data.view,
model = view.model,
term_id = $( this ).closest('tr').data('id');
event.preventDefault();
view.block();
model.save( {
[ term_id ]: {
term_id,
deleted: 'deleted',
}
} );
},
} ),
shippingClass = new ShippingClass({
classes: data.classes
} ),
shippingClassView = new ShippingClassView({
model: shippingClass,
el: $tbody
} );
shippingClassView.render();
});
})( jQuery, shippingClassesLocalizeScript, wp, ajaxurl );
@@ -0,0 +1 @@
!function(e,i,n,t){e(function(){var s=e(".wc-shipping-class-rows"),a=(e(".wc-shipping-class-save"),n.template("wc-shipping-class-row")),o=n.template("wc-shipping-class-row-blank"),c=Backbone.Model.extend({save:function(n){e.post(t+(t.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_classes_save_changes",{wc_shipping_classes_nonce:i.wc_shipping_classes_nonce,changes:n},this.onSaveResponse,"json")},onSaveResponse:function(e,n){"success"===n&&(e.success?(l.set("classes",e.data.shipping_classes),l.trigger("saved:classes")):e.data?window.alert(e.data):window.alert(i.strings.save_failed)),r.unblock()}}),d=Backbone.View.extend({rowTemplate:a,initialize:function(){this.listenTo(this.model,"saved:classes",this.render),e(document.body).on("click",".wc-shipping-class-add-new",{view:this},this.configureNewShippingClass),e(document.body).on("wc_backbone_modal_response",{view:this},this.onConfigureShippingClassSubmitted),e(document.body).on("wc_backbone_modal_loaded",{view:this},this.onLoadBackboneModal),e(document.body).on("wc_backbone_modal_validation",this.validateFormArguments)},block:function(){e(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){e(this.el).unblock()},render:function(){var i=_.indexBy(this.model.get("classes"),"term_id"),n=this;this.$el.empty(),this.unblock(),_.size(i)?(i=_.sortBy(i,function(e){return e.name}),e.each(i,function(e,i){n.renderRow(i)})):n.$el.append(o)},renderRow:function(e){this.$el.append(this.rowTemplate(e)),this.initRow(e)},initRow:function(i){var n=this.$el.find('tr[data-id="'+i.term_id+'"]');n.find("select").each(function(){var n=e(this).data("attribute");e(this).find('option[value="'+i[n]+'"]').prop("selected",!0)}),n.find(".view").show(),n.find(".edit").hide(),n.find(".wc-shipping-class-edit").on("click",{view:this},this.onEditRow),n.find(".wc-shipping-class-delete").on("click",{view:this},this.onDeleteRow)},configureNewShippingClass:function(i){i.preventDefault();const n="new-1-"+Date.now();e(this).WCBackboneModal({template:"wc-shipping-class-configure",variable:{term_id:n,action:"create"},data:{term_id:n,action:"create"}})},onConfigureShippingClassSubmitted:function(e,i,n){if("wc-shipping-class-configure"===i){const i=e.data.view,t=i.model,s=n.term_id.includes("new-1-"),a={...n};s&&(a.newRow=!0),i.block(),t.save({[n.term_id]:a})}},validateFormArguments:function(e,i,n){const t=["name","description"],s=Object.keys(n).every(e=>!t.includes(e)||(Array.isArray(n[e])?n[e].length&&!!n[e][0]:!!n[e])),a=document.getElementById("btn-ok");a.disabled=!s,a.classList.toggle("disabled",!s)},onEditRow:function(i){const n=e(this).closest("tr").data("id"),t=i.data.view.model,s=_.indexBy(t.get("classes"),"term_id")[n];i.preventDefault(),e(this).WCBackboneModal({template:"wc-shipping-class-configure",variable:{action:"edit",...s},data:{action:"edit",...s}})},onLoadBackboneModal:function(i,n){if("wc-shipping-class-configure"===n){const n=e(".wc-backbone-modal-content").data("id"),t=i.data.view.model,s=_.indexBy(t.get("classes"),"term_id")[n];s&&e(".wc-backbone-modal-content").find("select").each(function(){var i=e(this).data("attribute");e(this).find('option[value="'+s[i]+'"]').prop("selected",!0)})}},onDeleteRow:function(i){var n=i.data.view,t=n.model,s=e(this).closest("tr").data("id");i.preventDefault(),n.block(),t.save({[s]:{term_id:s,deleted:"deleted"}})}}),l=new c({classes:i.classes}),r=new d({model:l,el:s});r.render()})}(jQuery,shippingClassesLocalizeScript,wp,ajaxurl);
@@ -0,0 +1,743 @@
/* global shippingZoneMethodsLocalizeScript, ajaxurl */
( function( $, data, wp, ajaxurl ) {
$( function() {
var $table = $( '.wc-shipping-zone-methods' ),
$tbody = $( '.wc-shipping-zone-method-rows' ),
$save_button = $( '.wc-shipping-zone-method-save' ),
$row_template = wp.template( 'wc-shipping-zone-method-row' ),
$blank_template = wp.template( 'wc-shipping-zone-method-row-blank' ),
// Backbone model
ShippingMethod = Backbone.Model.extend({
changes: {},
logChanges: function( changedRows ) {
var changes = this.changes || {};
_.each( changedRows.methods, function( row, id ) {
changes.methods = changes.methods || { methods : {} };
changes.methods[ id ] = _.extend( changes.methods[ id ] || { instance_id : id }, row );
} );
if ( typeof changedRows.zone_name !== 'undefined' ) {
changes.zone_name = changedRows.zone_name;
}
if ( typeof changedRows.zone_locations !== 'undefined' ) {
changes.zone_locations = changedRows.zone_locations;
}
if ( typeof changedRows.zone_postcodes !== 'undefined' ) {
changes.zone_postcodes = changedRows.zone_postcodes;
}
this.changes = changes;
this.trigger( 'change:methods' );
},
save: function() {
// Special handling for an empty 'zone_locations' array, which jQuery filters out during $.post().
var changes = _.clone( this.changes );
if ( _.has( changes, 'zone_locations' ) && _.isEmpty( changes.zone_locations ) ) {
changes.zone_locations = [''];
}
$.post(
ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_methods_save_changes',
{
wc_shipping_zones_nonce : data.wc_shipping_zones_nonce,
changes : changes,
zone_id : data.zone_id
},
this.onSaveResponse,
'json'
);
},
onSaveResponse: function( response, textStatus ) {
if ( 'success' === textStatus ) {
if ( response.success ) {
if ( response.data.zone_id !== data.zone_id ) {
data.zone_id = response.data.zone_id;
if ( window.history.pushState ) {
window.history.pushState(
{},
'',
'admin.php?page=wc-settings&tab=shipping&zone_id=' + response.data.zone_id
);
}
}
shippingMethod.set( 'methods', response.data.methods );
shippingMethod.trigger( 'change:methods' );
shippingMethod.changes = {};
shippingMethod.trigger( 'saved:methods' );
// Overrides the onbeforeunload callback added by settings.js.
window.onbeforeunload = null;
} else {
window.alert( data.strings.save_failed );
}
}
}
} ),
// Backbone view
ShippingMethodView = Backbone.View.extend({
rowTemplate: $row_template,
initialize: function() {
this.listenTo( this.model, 'change:methods', this.setUnloadConfirmation );
this.listenTo( this.model, 'saved:methods', this.clearUnloadConfirmation );
this.listenTo( this.model, 'saved:methods', this.render );
this.listenTo( this.model, 'rerender', this.render );
$tbody.on( 'change', { view: this }, this.updateModelOnChange );
$tbody.on( 'sortupdate', { view: this }, this.updateModelOnSort );
$( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation );
$save_button.on( 'click', { view: this }, this.onSubmit );
$( document.body ).on(
'input change',
'#zone_name, #zone_locations, #zone_postcodes',
{ view: this },
this.onUpdateZone
);
$( document.body ).on( 'click', '.wc-shipping-zone-method-settings', { view: this }, this.onConfigureShippingMethod );
$( document.body ).on( 'click', '.wc-shipping-zone-add-method', { view: this }, this.onAddShippingMethod );
$( document.body ).on( 'wc_backbone_modal_response', this.onConfigureShippingMethodSubmitted );
$( document.body ).on( 'wc_region_picker_update', this.onUpdateZoneRegionPicker );
$( document.body ).on( 'wc_backbone_modal_next_response', this.onAddShippingMethodSubmitted );
$( document.body ).on( 'wc_backbone_modal_before_remove', this.onCloseConfigureShippingMethod );
$( document.body ).on( 'wc_backbone_modal_back_response', this.onConfigureShippingMethodBack );
$( document.body ).on( 'change', '.wc-shipping-zone-method-selector select', this.onChangeShippingMethodSelector );
$( document.body ).on( 'click', '.wc-shipping-zone-postcodes-toggle', this.onTogglePostcodes );
$( document.body ).on( 'wc_backbone_modal_validation', { view: this }, this.validateFormArguments );
$( document.body ).on( 'wc_backbone_modal_loaded', { view: this }, this.onModalLoaded );
},
onUpdateZoneRegionPicker: function( event ) {
var value = event.detail,
attribute = 'zone_locations',
changes = {};
changes[ attribute ] = value;
shippingMethodView.model.set( attribute, value );
shippingMethodView.model.logChanges( changes );
},
onUpdateZone: function( event ) {
var view = event.data.view,
model = view.model,
value = $( this ).val(),
$target = $( event.target ),
attribute = $target.data( 'attribute' ),
changes = {};
event.preventDefault();
changes[ attribute ] = value;
model.set( attribute, value );
model.logChanges( changes );
view.render();
},
block: function() {
$( this.el ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
unblock: function() {
$( this.el ).unblock();
},
render: function() {
var methods = _.indexBy( this.model.get( 'methods' ), 'instance_id' ),
zone_name = this.model.get( 'zone_name' ),
view = this;
// Set name.
$('.wc-shipping-zone-name').text( zone_name ? zone_name : data.strings.default_zone_name );
// Blank out the contents.
this.$el.empty();
this.unblock();
if ( _.size( methods ) ) {
// Sort methods
methods = _.sortBy( methods, function( method ) {
return parseInt( method.method_order, 10 );
} );
// Populate $tbody with the current methods
$.each( methods, function( id, rowData ) {
if ( 'yes' === rowData.enabled ) {
rowData.enabled_icon = '<span class="woocommerce-input-toggle woocommerce-input-toggle--enabled">' +
data.strings.yes +
'</span>';
} else {
rowData.enabled_icon = '<span class="woocommerce-input-toggle woocommerce-input-toggle--disabled">' +
data.strings.no +
'</span>';
}
view.$el.append( view.rowTemplate( rowData ) );
var $tr = view.$el.find( 'tr[data-id="' + rowData.instance_id + '"]');
if ( ! rowData.has_settings ) {
$tr
.find( '.wc-shipping-zone-method-title > a' )
.replaceWith('<span>' + $tr.find( '.wc-shipping-zone-method-title > a' ).text() + '</span>' );
var $del = $tr.find( '.wc-shipping-zone-method-delete' );
$tr.find( '.wc-shipping-zone-method-title .row-actions' ).empty().html($del);
}
} );
// Make the rows function
this.$el.find( '.wc-shipping-zone-method-delete' ).on( 'click', { view: this }, this.onDeleteRow );
this.$el.find( '.wc-shipping-zone-method-enabled a').on( 'click', { view: this }, this.onToggleEnabled );
} else {
view.$el.append( $blank_template );
}
this.initTooltips();
},
initTooltips: function() {
$( '#tiptip_holder' ).removeAttr( 'style' );
$( '#tiptip_arrow' ).removeAttr( 'style' );
$( '.tips' ).tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 50 });
},
onSubmit: function( event ) {
$save_button.addClass( 'is-busy' );
event.data.view.block();
event.data.view.model.save();
event.preventDefault();
},
onDeleteRow: function( event ) {
var view = event.data.view,
model = view.model,
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
changes = {},
instance_id = $( this ).closest( 'tr' ).data( 'id' );
event.preventDefault();
if ( window.confirm( data.strings.delete_shipping_method_confirmation ) ) {
shippingMethodView.block();
// Add method to zone via ajax call
$.post( {
url: ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?') + 'action=woocommerce_shipping_zone_remove_method',
data: {
wc_shipping_zones_nonce: data.wc_shipping_zones_nonce,
instance_id: instance_id,
zone_id: data.zone_id,
},
success: function( { data } ) {
delete methods[instance_id];
changes.methods = changes.methods || data.methods;
model.set('methods', methods);
model.logChanges( changes );
view.clearUnloadConfirmation();
view.render();
shippingMethodView.unblock();
},
error: function( jqXHR, textStatus, errorThrown ) {
window.alert( data.strings.remove_method_failed );
shippingMethodView.unblock();
},
dataType: 'json'
});
}
},
onToggleEnabled: function( event ) {
var view = event.data.view,
$target = $( event.target ),
model = view.model,
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
instance_id = $target.closest( 'tr' ).data( 'id' ),
enabled = $target.closest( 'tr' ).data( 'enabled' ) === 'yes' ? 'no' : 'yes',
changes = {};
event.preventDefault();
methods[ instance_id ].enabled = enabled;
changes.methods = changes.methods || { methods : {} };
changes.methods[ instance_id ] = _.extend( changes.methods[ instance_id ] || {}, { enabled : enabled } );
model.set( 'methods', methods );
model.logChanges( changes );
view.render();
},
setUnloadConfirmation: function() {
this.needsUnloadConfirm = true;
$save_button.prop( 'disabled', false );
$save_button.removeClass( 'is-busy' );
},
clearUnloadConfirmation: function() {
this.needsUnloadConfirm = false;
$save_button.attr( 'disabled', 'disabled' );
},
unloadConfirmation: function( event ) {
if ( event.data.view.needsUnloadConfirm ) {
event.returnValue = data.strings.unload_confirmation_msg;
window.event.returnValue = data.strings.unload_confirmation_msg;
return data.strings.unload_confirmation_msg;
}
},
updateModelOnChange: function( event ) {
var model = event.data.view.model,
$target = $( event.target ),
instance_id = $target.closest( 'tr' ).data( 'id' ),
attribute = $target.data( 'attribute' ),
value = $target.val(),
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
changes = {};
if ( methods[ instance_id ][ attribute ] !== value ) {
changes.methods[ instance_id ] = {};
changes.methods[ instance_id ][ attribute ] = value;
methods[ instance_id ][ attribute ] = value;
}
model.logChanges( changes );
},
updateModelOnSort: function( event ) {
var view = event.data.view,
model = view.model,
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
changes = {};
_.each( methods, function( method ) {
var old_position = parseInt( method.method_order, 10 );
var new_position = parseInt( $table.find( 'tr[data-id="' + method.instance_id + '"]').index() + 1, 10 );
if ( old_position !== new_position ) {
methods[ method.instance_id ].method_order = new_position;
changes.methods = changes.methods || { methods : {} };
changes.methods[ method.instance_id ] = _.extend(
changes.methods[ method.instance_id ] || {}, { method_order : new_position }
);
}
} );
if ( _.size( changes ) ) {
model.logChanges( changes );
}
},
onConfigureShippingMethod: function( event ) {
var instance_id = $( this ).closest( 'tr' ).data( 'id' ),
model = event.data.view.model,
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
method = methods[ instance_id ];
// Only load modal if supported.
if ( ! method.settings_html ) {
return true;
}
event.preventDefault();
method.settings_html = shippingMethodView.reformatSettingsHTML( method.settings_html );
$( this ).WCBackboneModal({
template : 'wc-modal-shipping-method-settings',
variable : {
instance_id : instance_id,
method : method,
status : 'existing'
},
data : {
instance_id : instance_id,
method : method,
status : 'existing'
}
});
shippingMethodView.highlightOnFocus( '.wc-shipping-modal-price' );
$( document.body ).trigger( 'init_tooltips' );
},
onConfigureShippingMethodSubmitted: function( event, target, posted_data ) {
if ( 'wc-modal-shipping-method-settings' === target ) {
shippingMethodView.block();
// Save method settings via ajax call
$.post(
ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_methods_save_settings',
{
wc_shipping_zones_nonce : data.wc_shipping_zones_nonce,
instance_id : posted_data.instance_id,
data : posted_data
},
function( response, textStatus ) {
if ( 'success' === textStatus && response.success ) {
$( 'table.wc-shipping-zone-methods' ).parent().find( '#woocommerce_errors' ).remove();
// If there were errors, prepend the form.
if ( response.data.errors.length > 0 ) {
shippingMethodView.showErrors( response.data.errors );
}
// Method was saved. Re-render.
if ( _.size( shippingMethodView.model.changes ) ) {
shippingMethodView.model.save();
} else {
shippingMethodView.model.onSaveResponse( response, textStatus );
}
} else {
window.alert( data.strings.save_failed );
shippingMethodView.unblock();
}
},
'json'
);
}
},
onConfigureShippingMethodBack: function( event, target ) {
if ( 'wc-modal-shipping-method-settings' === target ) {
shippingMethodView.onAddShippingMethod( event );
}
},
showErrors: function( errors ) {
var error_html = '<div id="woocommerce_errors" class="error notice is-dismissible">';
$( errors ).each( function( index, value ) {
error_html = error_html + '<p>' + value + '</p>';
} );
error_html = error_html + '</div>';
$( 'table.wc-shipping-zone-methods' ).before( error_html );
},
highlightOnFocus: function( query ) {
const inputs = $( query );
inputs.focus( function() {
$( this ).select();
} );
},
onAddShippingMethod: function( event ) {
event.preventDefault();
$( this ).WCBackboneModal({
template : 'wc-modal-add-shipping-method',
variable : {
zone_id : data.zone_id
}
});
$( '.wc-shipping-zone-method-selector select' ).trigger( 'change' );
$('.wc-shipping-zone-method-input input').change( function() {
const selected = $('.wc-shipping-zone-method-input input:checked');
const id = selected.attr( 'id' );
const description = $( `#${ id }-description` );
const descriptions = $( '.wc-shipping-zone-method-input-help-text' );
descriptions.css( 'display', 'none' );
description.css( 'display', 'block' );
});
},
/**
* The settings HTML is controlled and built by the settings api, so in order to refactor the
* markup, it needs to be manipulated here.
*/
reformatSettingsHTML: function( html ) {
const formattingFunctions = [
this.replaceHTMLTables,
this.moveAdvancedCostsHelpTip,
this.moveHTMLHelpTips,
this.addCurrencySymbol
];
return formattingFunctions.reduce( ( formattedHTML, fn ) => {
return fn( formattedHTML );
}, html );
},
moveAdvancedCostsHelpTip: function( html ) {
const htmlContent = $( html );
const advancedCostsHelpTip = htmlContent.find( '#wc-shipping-advanced-costs-help-text' );
advancedCostsHelpTip.addClass( 'wc-shipping-zone-method-fields-help-text' );
const input = htmlContent.find( '#woocommerce_flat_rate_cost' );
const fieldset = input.closest( 'fieldset' );
advancedCostsHelpTip.appendTo( fieldset );
return htmlContent.prop( 'outerHTML' );
},
addCurrencySymbol: function( html ) {
if ( ! window.wc.ShippingCurrencyContext || ! window.wc.ShippingCurrencyNumberFormat ) {
return html;
}
const htmlContent = $( html );
const priceInputs = htmlContent.find( '.wc-shipping-modal-price' );
const config = window.wc.ShippingCurrencyContext.getCurrencyConfig();
const { symbol, symbolPosition } = config;
priceInputs.addClass( `wc-shipping-currency-size-${ symbol.length }` );
priceInputs.addClass( `wc-shipping-currency-position-${ symbolPosition }` );
priceInputs.before(
`<div class="wc-shipping-zone-method-currency wc-shipping-currency-position-${ symbolPosition }">${ symbol }</div>`
);
priceInputs.each( ( i ) => {
const priceInput = $( priceInputs[ i ] );
const value = priceInput.attr( 'value' );
const formattedValue = window.wc.ShippingCurrencyNumberFormat( config, value );
priceInput.attr( 'value', formattedValue );
} );
return htmlContent.prop( 'outerHTML' );
},
moveHTMLHelpTips: function( html ) {
// These help tips aren't moved.
const helpTipsToRetain = [
'woocommerce_flat_rate_cost',
'woocommerce_flat_rate_no_class_cost',
'woocommerce_flat_rate_class_cost_'
];
const htmlContent = $( html );
const labels = htmlContent.find( 'label' );
labels.each( ( i ) => {
const label = $( labels[ i ] );
const helpTip = label.find( '.woocommerce-help-tip' );
if ( helpTip.length === 0 ) {
return;
}
const id = label.attr( 'for' );
if ( helpTipsToRetain.some( ( tip ) => id.includes( tip ) ) ) {
const helpTip = htmlContent.find( `label[for=${ id }] span.woocommerce-help-tip` );
helpTip.addClass( 'wc-shipping-visible-help-text' );
return;
}
// woocommerce_free_shipping_ignore_discounts gets a helpTip appended to its label.
// Otherwise, add the text as the last element in the fieldset.
if ( id === 'woocommerce_free_shipping_ignore_discounts' ) {
const input = htmlContent.find( `#${ id }` );
const fieldset = input.closest( 'fieldset' );
const inputLabel = fieldset.find( 'label' );
inputLabel.append( helpTip );
} else {
const text = helpTip.data( 'tip' );
const input = htmlContent.find( `#${ id }` );
const fieldset = input.closest( 'fieldset' );
if ( fieldset.length && fieldset.find( '.wc-shipping-zone-method-fields-help-text' ).length === 0 ) {
fieldset.append( `<div class="wc-shipping-zone-method-fields-help-text">${ text }</div>` );
}
}
// Coupon discounts doesn't get a title on Free Shipping.
if ( label.text().trim() === 'Coupons discounts' ) {
label.text( '' );
}
} );
return htmlContent.prop( 'outerHTML' );
},
replaceHTMLTables: function ( html ) {
// Wrap the html content in a div
const htmlContent = $( '<div>' + html + '</div>' );
// `<table class="form-table" />` elements added by the Settings API need to be removed.
// Modern browsers won't interpret other table elements like `td` not in a `table`, so
// Removing the `table` is sufficient.
const innerTables = htmlContent.find( 'table.form-table' );
innerTables.each( ( i ) => {
const table = $( innerTables[ i ] );
const div = $( '<div class="wc-shipping-zone-method-fields" />' );
div.html( table.html() );
table.replaceWith( div );
} );
return htmlContent.prop('outerHTML');
},
onAddShippingMethodSubmitted: function( event, target, posted_data, closeModal ) {
if ( 'wc-modal-add-shipping-method' === target ) {
shippingMethodView.block();
$('#btn-next').addClass( 'is-busy' );
// Add method to zone via ajax call
$.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zone_add_method', {
wc_shipping_zones_nonce : data.wc_shipping_zones_nonce,
method_id : posted_data.add_method_id,
zone_id : data.zone_id
}, function( response, textStatus ) {
if ( 'success' === textStatus && response.success ) {
if ( response.data.zone_id !== data.zone_id ) {
data.zone_id = response.data.zone_id;
if ( window.history.pushState ) {
window.history.pushState(
{},
'',
'admin.php?page=wc-settings&tab=shipping&zone_id=' + response.data.zone_id
);
}
}
// Avoid triggering a rerender here because we don't want to show the method
// in the table in case merchant doesn't finish flow.
shippingMethodView.model.set( 'methods', response.data.methods );
// Close original modal
closeModal();
}
var instance_id = response.data.instance_id,
method = response.data.methods[ instance_id ];
shippingMethodView.unblock();
if ( method.settings_html ) {
method.settings_html = shippingMethodView.reformatSettingsHTML( method.settings_html );
// Pop up next modal
$( this ).WCBackboneModal({
template : 'wc-modal-shipping-method-settings',
variable : {
instance_id : instance_id,
method : method,
status : 'new'
},
data : {
instance_id : instance_id,
method : method,
status : 'new'
}
});
shippingMethodView.highlightOnFocus( '.wc-shipping-modal-price' );
} else {
shippingMethodView.model.trigger( 'change:methods' );
shippingMethodView.model.trigger( 'saved:methods' );
}
$( document.body ).trigger( 'init_tooltips' );
}, 'json' );
}
},
// Free Shipping has hidden field elements depending on data values.
possiblyHideFreeShippingRequirements: function( data ) {
if ( Object.keys( data ).includes( 'woocommerce_free_shipping_requires' ) ) {
const shouldHideRequirements = data.woocommerce_free_shipping_requires === null ||
data.woocommerce_free_shipping_requires === '' ||
data.woocommerce_free_shipping_requires === 'coupon';
const select = $( '#woocommerce_free_shipping_requires' );
const fieldset = select.closest( 'fieldset' );
const allOtherLabelElementsAfter = fieldset.nextAll( 'label' );
const allOtherFieldsetElementsAfter = fieldset.nextAll( 'fieldset' );
allOtherLabelElementsAfter.each( ( i ) => {
$( allOtherLabelElementsAfter[ i ] ).css( 'display', shouldHideRequirements ? 'none' : 'block' );
} );
allOtherFieldsetElementsAfter.each( ( i ) => {
$( allOtherFieldsetElementsAfter[ i ] ).css( 'display', shouldHideRequirements ? 'none' : 'block' );
} );
}
},
onModalLoaded: function( event, target ) {
if ( target === 'wc-modal-shipping-method-settings' ) {
const select = $( '#woocommerce_free_shipping_requires' );
if ( select.length > 0 ) {
event.data.view.possiblyHideFreeShippingRequirements( { woocommerce_free_shipping_requires: select.val() } );
}
event.data.view.possiblyAddShippingClassLink( event );
}
},
possiblyAddShippingClassLink: function( event ) {
const article = $( 'article.wc-modal-shipping-method-settings' );
const shippingClassesCount = article.data( 'shipping-classes-count' );
const status = article.data( 'status' );
const instance_id = article.data( 'id' );
const model = event.data.view.model;
const methods = _.indexBy( model.get( 'methods' ), 'instance_id' );
const method = methods[ instance_id ];
if ( method.id === 'flat_rate' && shippingClassesCount === 0 ) {
const link = article.find( '.wc-shipping-method-add-class-costs' );
link.css( 'display', 'block' );
}
},
validateFormArguments: function( event, target, data ) {
if ( target === 'wc-modal-add-shipping-method' ) {
if ( data.add_method_id ) {
const nextButton = document.getElementById( 'btn-next' );
nextButton.disabled = false;
nextButton.classList.remove( 'disabled' );
}
} else if ( target === 'wc-modal-shipping-method-settings' ) {
event.data.view.possiblyHideFreeShippingRequirements( data );
}
},
onCloseConfigureShippingMethod: function( event, target, post_data, addButtonCalled ) {
if ( target === 'wc-modal-shipping-method-settings' ) {
var btnData = $( '#btn-ok' ).data();
if ( ! addButtonCalled && btnData && btnData.status === 'new' ) {
shippingMethodView.block();
var view = shippingMethodView,
model = view.model,
methods = _.indexBy( model.get( 'methods' ), 'instance_id' ),
changes = {},
instance_id = post_data.instance_id;
// Remove method to zone via ajax call
$.post( {
url: ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?') + 'action=woocommerce_shipping_zone_remove_method',
data: {
wc_shipping_zones_nonce: data.wc_shipping_zones_nonce,
instance_id: instance_id,
zone_id: data.zone_id,
},
success: function( { data } ) {
delete methods[instance_id];
changes.methods = changes.methods || data.methods;
model.set('methods', methods);
model.logChanges( changes );
view.clearUnloadConfirmation();
view.render();
shippingMethodView.unblock();
},
error: function( jqXHR, textStatus, errorThrown ) {
window.alert( data.strings.remove_method_failed );
shippingMethodView.unblock();
},
dataType: 'json'
});
}
}
},
onChangeShippingMethodSelector: function() {
var description = $( this ).find( 'option:selected' ).data( 'description' );
$( this ).parent().find( '.wc-shipping-zone-method-description' ).remove();
$( this ).after( '<div class="wc-shipping-zone-method-description">' + description + '</div>' );
},
onTogglePostcodes: function( event ) {
event.preventDefault();
var $tr = $( this ).closest( 'tr');
$tr.find( '.wc-shipping-zone-postcodes' ).show();
$tr.find( '.wc-shipping-zone-postcodes-toggle' ).hide();
}
} ),
shippingMethod = new ShippingMethod({
methods: data.methods,
zone_name: data.zone_name
} ),
shippingMethodView = new ShippingMethodView({
model: shippingMethod,
el: $tbody
} );
shippingMethodView.render();
$tbody.sortable({
items: 'tr',
cursor: 'move',
axis: 'y',
handle: 'td.wc-shipping-zone-method-sort',
scrollSensitivity: 40
});
});
})( jQuery, shippingZoneMethodsLocalizeScript, wp, ajaxurl );
@@ -0,0 +1 @@
!function(e,n,o,t){e(function(){var i=e(".wc-shipping-zone-methods"),s=e(".wc-shipping-zone-method-rows"),d=e(".wc-shipping-zone-method-save"),a=o.template("wc-shipping-zone-method-row"),c=o.template("wc-shipping-zone-method-row-blank"),h=Backbone.Model.extend({changes:{},logChanges:function(e){var n=this.changes||{};_.each(e.methods,function(e,o){n.methods=n.methods||{methods:{}},n.methods[o]=_.extend(n.methods[o]||{instance_id:o},e)}),"undefined"!=typeof e.zone_name&&(n.zone_name=e.zone_name),"undefined"!=typeof e.zone_locations&&(n.zone_locations=e.zone_locations),"undefined"!=typeof e.zone_postcodes&&(n.zone_postcodes=e.zone_postcodes),this.changes=n,this.trigger("change:methods")},save:function(){var o=_.clone(this.changes);_.has(o,"zone_locations")&&_.isEmpty(o.zone_locations)&&(o.zone_locations=[""]),e.post(t+(t.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zone_methods_save_changes",{wc_shipping_zones_nonce:n.wc_shipping_zones_nonce,changes:o,zone_id:n.zone_id},this.onSaveResponse,"json")},onSaveResponse:function(e,o){"success"===o&&(e.success?(e.data.zone_id!==n.zone_id&&(n.zone_id=e.data.zone_id,window.history.pushState&&window.history.pushState({},"","admin.php?page=wc-settings&tab=shipping&zone_id="+e.data.zone_id)),r.set("methods",e.data.methods),r.trigger("change:methods"),r.changes={},r.trigger("saved:methods"),window.onbeforeunload=null):window.alert(n.strings.save_failed))}}),p=Backbone.View.extend({rowTemplate:a,initialize:function(){this.listenTo(this.model,"change:methods",this.setUnloadConfirmation),this.listenTo(this.model,"saved:methods",this.clearUnloadConfirmation),this.listenTo(this.model,"saved:methods",this.render),this.listenTo(this.model,"rerender",this.render),s.on("change",{view:this},this.updateModelOnChange),s.on("sortupdate",{view:this},this.updateModelOnSort),e(window).on("beforeunload",{view:this},this.unloadConfirmation),d.on("click",{view:this},this.onSubmit),e(document.body).on("input change","#zone_name, #zone_locations, #zone_postcodes",{view:this},this.onUpdateZone),e(document.body).on("click",".wc-shipping-zone-method-settings",{view:this},this.onConfigureShippingMethod),e(document.body).on("click",".wc-shipping-zone-add-method",{view:this},this.onAddShippingMethod),e(document.body).on("wc_backbone_modal_response",this.onConfigureShippingMethodSubmitted),e(document.body).on("wc_region_picker_update",this.onUpdateZoneRegionPicker),e(document.body).on("wc_backbone_modal_next_response",this.onAddShippingMethodSubmitted),e(document.body).on("wc_backbone_modal_before_remove",this.onCloseConfigureShippingMethod),e(document.body).on("wc_backbone_modal_back_response",this.onConfigureShippingMethodBack),e(document.body).on("change",".wc-shipping-zone-method-selector select",this.onChangeShippingMethodSelector),e(document.body).on("click",".wc-shipping-zone-postcodes-toggle",this.onTogglePostcodes),e(document.body).on("wc_backbone_modal_validation",{view:this},this.validateFormArguments),e(document.body).on("wc_backbone_modal_loaded",{view:this},this.onModalLoaded)},onUpdateZoneRegionPicker:function(e){var n=e.detail,o={};o.zone_locations=n,l.model.set("zone_locations",n),l.model.logChanges(o)},onUpdateZone:function(n){var o=n.data.view,t=o.model,i=e(this).val(),s=e(n.target).data("attribute"),d={};n.preventDefault(),d[s]=i,t.set(s,i),t.logChanges(d),o.render()},block:function(){e(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){e(this.el).unblock()},render:function(){var o=_.indexBy(this.model.get("methods"),"instance_id"),t=this.model.get("zone_name"),i=this;e(".wc-shipping-zone-name").text(t||n.strings.default_zone_name),this.$el.empty(),this.unblock(),_.size(o)?(o=_.sortBy(o,function(e){return parseInt(e.method_order,10)}),e.each(o,function(e,o){"yes"===o.enabled?o.enabled_icon='<span class="woocommerce-input-toggle woocommerce-input-toggle--enabled">'+n.strings.yes+"</span>":o.enabled_icon='<span class="woocommerce-input-toggle woocommerce-input-toggle--disabled">'+n.strings.no+"</span>",i.$el.append(i.rowTemplate(o));var t=i.$el.find('tr[data-id="'+o.instance_id+'"]');if(!o.has_settings){t.find(".wc-shipping-zone-method-title > a").replaceWith("<span>"+t.find(".wc-shipping-zone-method-title > a").text()+"</span>");var s=t.find(".wc-shipping-zone-method-delete");t.find(".wc-shipping-zone-method-title .row-actions").empty().html(s)}}),this.$el.find(".wc-shipping-zone-method-delete").on("click",{view:this},this.onDeleteRow),this.$el.find(".wc-shipping-zone-method-enabled a").on("click",{view:this},this.onToggleEnabled)):i.$el.append(c),this.initTooltips()},initTooltips:function(){e("#tiptip_holder").removeAttr("style"),e("#tiptip_arrow").removeAttr("style"),e(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:50})},onSubmit:function(e){d.addClass("is-busy"),e.data.view.block(),e.data.view.model.save(),e.preventDefault()},onDeleteRow:function(o){var i=o.data.view,s=i.model,d=_.indexBy(s.get("methods"),"instLine truncated
@@ -0,0 +1,278 @@
/* global shippingZonesLocalizeScript, ajaxurl */
( function( $, data, wp, ajaxurl ) {
$( function() {
var $table = $( '.wc-shipping-zones' ),
$tbody = $( '.wc-shipping-zone-rows' ),
$save_button = $( '.wc-shipping-zone-save' ),
$row_template = wp.template( 'wc-shipping-zone-row' ),
$blank_template = wp.template( 'wc-shipping-zone-row-blank' ),
// Backbone model
ShippingZone = Backbone.Model.extend({
changes: {},
logChanges: function( changedRows ) {
var changes = this.changes || {};
_.each( changedRows, function( row, id ) {
changes[ id ] = _.extend( changes[ id ] || { zone_id : id }, row );
} );
this.changes = changes;
this.trigger( 'change:zones' );
},
discardChanges: function( id ) {
var changes = this.changes || {},
set_position = null,
zones = _.indexBy( this.get( 'zones' ), 'zone_id' );
// Find current set position if it has moved since last save
if ( changes[ id ] && changes[ id ].zone_order !== undefined ) {
set_position = changes[ id ].zone_order;
}
// Delete all changes
delete changes[ id ];
// If the position was set, and this zone does exist in DB, set the position again so the changes are not lost.
if ( set_position !== null && zones[ id ] && zones[ id ].zone_order !== set_position ) {
changes[ id ] = _.extend( changes[ id ] || {}, { zone_id : id, zone_order : set_position } );
}
this.changes = changes;
// No changes? Disable save button.
if ( 0 === _.size( this.changes ) ) {
shippingZoneView.clearUnloadConfirmation();
}
},
save: function() {
if ( _.size( this.changes ) ) {
$.post( ajaxurl + ( ajaxurl.indexOf( '?' ) > 0 ? '&' : '?' ) + 'action=woocommerce_shipping_zones_save_changes', {
wc_shipping_zones_nonce : data.wc_shipping_zones_nonce,
changes : this.changes
}, this.onSaveResponse, 'json' );
} else {
shippingZone.trigger( 'saved:zones' );
}
},
onSaveResponse: function( response, textStatus ) {
if ( 'success' === textStatus ) {
if ( response.success ) {
shippingZone.set( 'zones', response.data.zones );
shippingZone.trigger( 'change:zones' );
shippingZone.changes = {};
shippingZone.trigger( 'saved:zones' );
} else {
window.alert( data.strings.save_failed );
}
}
}
} ),
// Backbone view
ShippingZoneView = Backbone.View.extend({
rowTemplate: $row_template,
initialize: function() {
this.listenTo( this.model, 'change:zones', this.setUnloadConfirmation );
this.listenTo( this.model, 'saved:zones', this.clearUnloadConfirmation );
this.listenTo( this.model, 'saved:zones', this.render );
$tbody.on( 'change', { view: this }, this.updateModelOnChange );
$tbody.on( 'sortupdate', { view: this }, this.updateModelOnSort );
$( window ).on( 'beforeunload', { view: this }, this.unloadConfirmation );
$( document.body ).on( 'click', '.wc-shipping-zone-add', { view: this }, this.onAddNewRow );
},
onAddNewRow: function() {
var $link = $( this );
window.location.href = $link.attr( 'href' );
},
block: function() {
$( this.el ).block({
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6
}
});
},
unblock: function() {
$( this.el ).unblock();
},
render: function() {
var zones = _.indexBy( this.model.get( 'zones' ), 'zone_id' ),
view = this;
view.$el.empty();
view.unblock();
if ( _.size( zones ) ) {
// Sort zones
zones = _( zones )
.chain()
.sortBy( function ( zone ) { return parseInt( zone.zone_id, 10 ); } )
.sortBy( function ( zone ) { return parseInt( zone.zone_order, 10 ); } )
.value();
// Populate $tbody with the current zones
$.each( zones, function( id, rowData ) {
view.renderRow( rowData );
} );
} else {
view.$el.append( $blank_template );
}
view.initRows();
},
renderRow: function( rowData ) {
var view = this;
view.$el.append( view.rowTemplate( rowData ) );
view.initRow( rowData );
},
initRow: function( rowData ) {
var view = this;
var $tr = view.$el.find( 'tr[data-id="' + rowData.zone_id + '"]');
// List shipping methods
view.renderShippingMethods( rowData.zone_id, rowData.shipping_methods );
$tr.find( '.wc-shipping-zone-delete' ).on( 'click', { view: this }, this.onDeleteRow );
},
initRows: function() {
const isEven = 0 !== ( $( 'tbody.wc-shipping-zone-rows tr' ).length % 2 );
const tfoot = $( 'tfoot.wc-shipping-zone-rows-tfoot' );
// Stripe
if ( isEven ) {
tfoot.find( 'tr' ).addClass( 'even' );
} else {
tfoot.find( 'tr' ).removeClass( 'even' );
}
// Tooltips
$( '#tiptip_holder' ).removeAttr( 'style' );
$( '#tiptip_arrow' ).removeAttr( 'style' );
$( '.tips' ).tipTip({ 'attribute': 'data-tip', 'fadeIn': 50, 'fadeOut': 50, 'delay': 50 });
},
renderShippingMethods: function( zone_id, shipping_methods ) {
var $tr = $( '.wc-shipping-zones tr[data-id="' + zone_id + '"]');
var $method_list = $tr.find('.wc-shipping-zone-methods ul');
$method_list.find( '.wc-shipping-zone-method' ).remove();
if ( _.size( shipping_methods ) ) {
shipping_methods = _.sortBy( shipping_methods, function( method ) {
return parseInt( method.method_order, 10 );
} );
_.each( shipping_methods, function( shipping_method ) {
var class_name = 'method_disabled';
if ( 'yes' === shipping_method.enabled ) {
class_name = 'method_enabled';
}
$method_list.append(
'<li class="wc-shipping-zone-method ' + class_name + '">' + shipping_method.title + '</li>'
);
} );
} else {
$method_list.append( '<li class="wc-shipping-zone-method">' + data.strings.no_shipping_methods_offered + '</li>' );
}
},
onDeleteRow: function( event ) {
var view = event.data.view,
model = view.model,
zones = _.indexBy( model.get( 'zones' ), 'zone_id' ),
changes = {},
row = $( this ).closest('tr'),
zone_id = row.data('id');
event.preventDefault();
if ( window.confirm( data.strings.delete_confirmation_msg ) ) {
if ( zones[ zone_id ] ) {
delete zones[ zone_id ];
changes[ zone_id ] = _.extend( changes[ zone_id ] || {}, { deleted : 'deleted' } );
model.set( 'zones', zones );
model.logChanges( changes );
event.data.view.block();
event.data.view.model.save();
}
}
},
setUnloadConfirmation: function() {
this.needsUnloadConfirm = true;
$save_button.prop( 'disabled', false );
},
clearUnloadConfirmation: function() {
this.needsUnloadConfirm = false;
$save_button.prop( 'disabled', true );
},
unloadConfirmation: function( event ) {
if ( event.data.view.needsUnloadConfirm ) {
event.returnValue = data.strings.unload_confirmation_msg;
window.event.returnValue = data.strings.unload_confirmation_msg;
return data.strings.unload_confirmation_msg;
}
},
updateModelOnChange: function( event ) {
var model = event.data.view.model,
$target = $( event.target ),
zone_id = $target.closest( 'tr' ).data( 'id' ),
attribute = $target.data( 'attribute' ),
value = $target.val(),
zones = _.indexBy( model.get( 'zones' ), 'zone_id' ),
changes = {};
if ( ! zones[ zone_id ] || zones[ zone_id ][ attribute ] !== value ) {
changes[ zone_id ] = {};
changes[ zone_id ][ attribute ] = value;
}
model.logChanges( changes );
},
updateModelOnSort: function( event ) {
var view = event.data.view,
model = view.model,
zones = _.indexBy( model.get( 'zones' ), 'zone_id' ),
rows = $( 'tbody.wc-shipping-zone-rows tr' ),
changes = {};
// Update sorted row position
_.each( rows, function( row ) {
var zone_id = $( row ).data( 'id' ),
old_position = null,
new_position = parseInt( $( row ).index(), 10 );
if ( zones[ zone_id ] ) {
old_position = parseInt( zones[ zone_id ].zone_order, 10 );
}
if ( old_position !== new_position ) {
changes[ zone_id ] = _.extend( changes[ zone_id ] || {}, { zone_order : new_position } );
}
} );
if ( _.size( changes ) ) {
model.logChanges( changes );
event.data.view.block();
event.data.view.model.save();
}
}
} ),
shippingZone = new ShippingZone({
zones: data.zones
} ),
shippingZoneView = new ShippingZoneView({
model: shippingZone,
el: $tbody
} );
shippingZoneView.render();
$tbody.sortable({
items: 'tr',
cursor: 'move',
axis: 'y',
handle: 'td.wc-shipping-zone-sort',
scrollSensitivity: 40
});
});
})( jQuery, shippingZonesLocalizeScript, wp, ajaxurl );
@@ -0,0 +1 @@
!function(e,n,i,o){e(function(){e(".wc-shipping-zones");var t=e(".wc-shipping-zone-rows"),s=e(".wc-shipping-zone-save"),a=i.template("wc-shipping-zone-row"),d=i.template("wc-shipping-zone-row-blank"),r=Backbone.Model.extend({changes:{},logChanges:function(e){var n=this.changes||{};_.each(e,function(e,i){n[i]=_.extend(n[i]||{zone_id:i},e)}),this.changes=n,this.trigger("change:zones")},discardChanges:function(e){var n=this.changes||{},i=null,o=_.indexBy(this.get("zones"),"zone_id");n[e]&&n[e].zone_order!==undefined&&(i=n[e].zone_order),delete n[e],null!==i&&o[e]&&o[e].zone_order!==i&&(n[e]=_.extend(n[e]||{},{zone_id:e,zone_order:i})),this.changes=n,0===_.size(this.changes)&&h.clearUnloadConfirmation()},save:function(){_.size(this.changes)?e.post(o+(o.indexOf("?")>0?"&":"?")+"action=woocommerce_shipping_zones_save_changes",{wc_shipping_zones_nonce:n.wc_shipping_zones_nonce,changes:this.changes},this.onSaveResponse,"json"):c.trigger("saved:zones")},onSaveResponse:function(e,i){"success"===i&&(e.success?(c.set("zones",e.data.zones),c.trigger("change:zones"),c.changes={},c.trigger("saved:zones")):window.alert(n.strings.save_failed))}}),l=Backbone.View.extend({rowTemplate:a,initialize:function(){this.listenTo(this.model,"change:zones",this.setUnloadConfirmation),this.listenTo(this.model,"saved:zones",this.clearUnloadConfirmation),this.listenTo(this.model,"saved:zones",this.render),t.on("change",{view:this},this.updateModelOnChange),t.on("sortupdate",{view:this},this.updateModelOnSort),e(window).on("beforeunload",{view:this},this.unloadConfirmation),e(document.body).on("click",".wc-shipping-zone-add",{view:this},this.onAddNewRow)},onAddNewRow:function(){var n=e(this);window.location.href=n.attr("href")},block:function(){e(this.el).block({message:null,overlayCSS:{background:"#fff",opacity:.6}})},unblock:function(){e(this.el).unblock()},render:function(){var n=_.indexBy(this.model.get("zones"),"zone_id"),i=this;i.$el.empty(),i.unblock(),_.size(n)?(n=_(n).chain().sortBy(function(e){return parseInt(e.zone_id,10)}).sortBy(function(e){return parseInt(e.zone_order,10)}).value(),e.each(n,function(e,n){i.renderRow(n)})):i.$el.append(d),i.initRows()},renderRow:function(e){this.$el.append(this.rowTemplate(e)),this.initRow(e)},initRow:function(e){var n=this.$el.find('tr[data-id="'+e.zone_id+'"]');this.renderShippingMethods(e.zone_id,e.shipping_methods),n.find(".wc-shipping-zone-delete").on("click",{view:this},this.onDeleteRow)},initRows:function(){const n=0!=e("tbody.wc-shipping-zone-rows tr").length%2,i=e("tfoot.wc-shipping-zone-rows-tfoot");n?i.find("tr").addClass("even"):i.find("tr").removeClass("even"),e("#tiptip_holder").removeAttr("style"),e("#tiptip_arrow").removeAttr("style"),e(".tips").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:50})},renderShippingMethods:function(i,o){var t=e('.wc-shipping-zones tr[data-id="'+i+'"]').find(".wc-shipping-zone-methods ul");t.find(".wc-shipping-zone-method").remove(),_.size(o)?(o=_.sortBy(o,function(e){return parseInt(e.method_order,10)}),_.each(o,function(e){var n="method_disabled";"yes"===e.enabled&&(n="method_enabled"),t.append('<li class="wc-shipping-zone-method '+n+'">'+e.title+"</li>")})):t.append('<li class="wc-shipping-zone-method">'+n.strings.no_shipping_methods_offered+"</li>")},onDeleteRow:function(i){var o=i.data.view.model,t=_.indexBy(o.get("zones"),"zone_id"),s={},a=e(this).closest("tr").data("id");i.preventDefault(),window.confirm(n.strings.delete_confirmation_msg)&&t[a]&&(delete t[a],s[a]=_.extend(s[a]||{},{deleted:"deleted"}),o.set("zones",t),o.logChanges(s),i.data.view.block(),i.data.view.model.save())},setUnloadConfirmation:function(){this.needsUnloadConfirm=!0,s.prop("disabled",!1)},clearUnloadConfirmation:function(){this.needsUnloadConfirm=!1,s.prop("disabled",!0)},unloadConfirmation:function(e){if(e.data.view.needsUnloadConfirm)return e.returnValue=n.strings.unload_confirmation_msg,window.event.returnValue=n.strings.unload_confirmation_msg,n.strings.unload_confirmation_msg},updateModelOnChange:function(n){var i=n.data.view.model,o=e(n.target),t=o.closest("tr").data("id"),s=o.data("attribute"),a=o.val(),d=_.indexBy(i.get("zones"),"zone_id"),r={};d[t]&&d[t][s]===a||(r[t]={},r[t][s]=a),i.logChanges(r)},updateModelOnSort:function(n){var i=n.data.view.model,o=_.indexBy(i.get("zones"),"zone_id"),t=e("tbody.wc-shipping-zone-rows tr"),s={};_.each(t,function(n){var i=e(n).data("id"),t=null,a=parseInt(e(n).index(),10);o[i]&&(t=parseInt(o[i].zone_order,10)),t!==a&&(s[i]=_.extend(s[i]||{},{zone_order:a}))}),_.size(s)&&(i.logChanges(s),n.data.view.block(),n.data.view.model.save())}}),c=new r({zones:n.zones}),h=new l({model:c,el:t});h.render(),t.sortable({items:"tr",cursor:"move",axis:"y",handle:"td.wc-shipping-zone-sort",scrollSensitivity:40})})}(jQuery,shippingZonesLocalizeScript,wp,ajaxurl);
@@ -0,0 +1,36 @@
/*global jQuery */
(function( $ ) {
$( function() {
window.wcTracks.recordEvent( 'wcadmin_status_widget_view' );
});
var recordEvent = function( link ) {
window.wcTracks.recordEvent( 'status_widget_click', {
link: link
} );
};
$( '.sales-this-month a' ).on( 'click', function() {
recordEvent( 'net-sales' );
});
$( '.best-seller-this-month a' ).on( 'click', function() {
recordEvent( 'best-seller-this-month' );
});
$( '.processing-orders a' ).on( 'click', function() {
recordEvent( 'orders-processing' );
});
$( '.on-hold-orders a' ).on( 'click', function() {
recordEvent( 'orders-on-hold' );
});
$( '.low-in-stock a' ).on( 'click', function() {
recordEvent( 'low-stock' );
});
$( '.out-of-stock a' ).on( 'click', function() {
recordEvent( 'out-of-stock' );
});
})( jQuery );
@@ -0,0 +1 @@
!function(o){o(function(){window.wcTracks.recordEvent("wcadmin_status_widget_view")});var n=function(o){window.wcTracks.recordEvent("status_widget_click",{link:o})};o(".sales-this-month a").on("click",function(){n("net-sales")}),o(".best-seller-this-month a").on("click",function(){n("best-seller-this-month")}),o(".processing-orders a").on("click",function(){n("orders-processing")}),o(".on-hold-orders a").on("click",function(){n("orders-on-hold")}),o(".low-in-stock a").on("click",function(){n("low-stock")}),o(".out-of-stock a").on("click",function(){n("out-of-stock")})}(jQuery);
@@ -0,0 +1,760 @@
/* global woocommerce_admin */
( function ( $, woocommerce_admin ) {
$( function () {
if ( 'undefined' === typeof woocommerce_admin ) {
return;
}
// Add buttons to product screen.
var $product_screen = $( '.edit-php.post-type-product' ),
$title_action = $product_screen.find( '.page-title-action:first' ),
$blankslate = $product_screen.find( '.woocommerce-BlankState' );
if ( 0 === $blankslate.length ) {
if ( woocommerce_admin.urls.add_product ) {
$title_action
.first()
.attr( 'href', woocommerce_admin.urls.add_product );
}
if ( woocommerce_admin.urls.export_products ) {
$title_action.after(
'<a href="' +
woocommerce_admin.urls.export_products +
'" class="page-title-action">' +
woocommerce_admin.strings.export_products +
'</a>'
);
}
if ( woocommerce_admin.urls.import_products ) {
$title_action.after(
'<a href="' +
woocommerce_admin.urls.import_products +
'" class="page-title-action">' +
woocommerce_admin.strings.import_products +
'</a>'
);
}
} else {
$title_action.hide();
}
// Progress indicators when showing steps.
$( '.woocommerce-progress-form-wrapper .button-next' ).on(
'click',
function () {
$( '.wc-progress-form-content' ).block( {
message: null,
overlayCSS: {
background: '#fff',
opacity: 0.6,
},
} );
return true;
}
);
// Field validation error tips
$( document.body )
.on( 'wc_add_error_tip', function ( e, element, error_type ) {
var offset = element.position();
if ( element.parent().find( '.wc_error_tip' ).length === 0 ) {
element.after(
'<div class="wc_error_tip ' +
error_type +
'">' +
woocommerce_admin[ error_type ] +
'</div>'
);
element
.parent()
.find( '.wc_error_tip' )
.css(
'left',
offset.left +
element.width() -
element.width() / 2 -
$( '.wc_error_tip' ).width() / 2
)
.css( 'top', offset.top + element.height() )
.fadeIn( '100' );
}
} )
.on( 'wc_remove_error_tip', function ( e, element, error_type ) {
element
.parent()
.find( '.wc_error_tip.' + error_type )
.fadeOut( '100', function () {
$( this ).remove();
} );
} )
.on( 'click', function () {
$( '.wc_error_tip' ).fadeOut( '100', function () {
$( this ).remove();
} );
} )
.on(
'blur',
'.wc_input_decimal[type=text], .wc_input_price[type=text], .wc_input_country_iso[type=text]',
function () {
$( '.wc_error_tip' ).fadeOut( '100', function () {
$( this ).remove();
} );
}
)
.on(
'change',
'.wc_input_price[type=text], .wc_input_decimal[type=text], .wc-order-totals #refund_amount[type=text], ' +
'.wc_input_variations_price[type=text]',
function () {
var regex,
decimalRegex,
decimailPoint = woocommerce_admin.decimal_point;
if (
$( this ).is( '.wc_input_price' ) ||
$( this ).is( '.wc_input_variations_price' ) ||
$( this ).is( '#refund_amount' )
) {
decimailPoint = woocommerce_admin.mon_decimal_point;
}
regex = new RegExp(
'[^-0-9%\\' + decimailPoint + ']+',
'gi'
);
decimalRegex = new RegExp(
'\\' + decimailPoint + '+',
'gi'
);
var value = $( this ).val();
var newvalue = value
.replace( regex, '' )
.replace( decimalRegex, decimailPoint );
if ( value !== newvalue ) {
$( this ).val( newvalue );
}
}
)
.on(
'keyup',
// eslint-disable-next-line max-len
'.wc_input_price[type=text], .wc_input_decimal[type=text], .wc_input_country_iso[type=text], .wc-order-totals #refund_amount[type=text], .wc_input_variations_price[type=text]',
function () {
var regex, error, decimalRegex;
var checkDecimalNumbers = false;
if (
$( this ).is( '.wc_input_price' ) ||
$( this ).is( '.wc_input_variations_price' ) ||
$( this ).is( '#refund_amount' )
) {
checkDecimalNumbers = true;
regex = new RegExp(
'[^-0-9%\\' +
woocommerce_admin.mon_decimal_point +
']+',
'gi'
);
decimalRegex = new RegExp(
'[^\\' + woocommerce_admin.mon_decimal_point + ']',
'gi'
);
error = 'i18n_mon_decimal_error';
} else if ( $( this ).is( '.wc_input_country_iso' ) ) {
regex = new RegExp( '([^A-Z])+|(.){3,}', 'im' );
error = 'i18n_country_iso_error';
} else {
checkDecimalNumbers = true;
regex = new RegExp(
'[^-0-9%\\' +
woocommerce_admin.decimal_point +
']+',
'gi'
);
decimalRegex = new RegExp(
'[^\\' + woocommerce_admin.decimal_point + ']',
'gi'
);
error = 'i18n_decimal_error';
}
var value = $( this ).val();
var newvalue = value.replace( regex, '' );
// Check if newvalue have more than one decimal point.
if (
checkDecimalNumbers &&
1 < newvalue.replace( decimalRegex, '' ).length
) {
newvalue = newvalue.replace( decimalRegex, '' );
}
if ( value !== newvalue ) {
$( document.body ).triggerHandler( 'wc_add_error_tip', [
$( this ),
error,
] );
} else {
$(
document.body
).triggerHandler( 'wc_remove_error_tip', [
$( this ),
error,
] );
}
}
)
.on(
'change',
'#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]',
function () {
var sale_price_field = $( this ),
regular_price_field;
if (
sale_price_field
.attr( 'name' )
.indexOf( 'variable' ) !== -1
) {
regular_price_field = sale_price_field
.parents( '.variable_pricing' )
.find(
'.wc_input_price[name^=variable_regular_price]'
);
} else {
regular_price_field = $( '#_regular_price' );
}
var sale_price = parseFloat(
window.accounting.unformat(
sale_price_field.val(),
woocommerce_admin.mon_decimal_point
)
);
var regular_price = parseFloat(
window.accounting.unformat(
regular_price_field.val(),
woocommerce_admin.mon_decimal_point
)
);
if ( sale_price >= regular_price ) {
$( this ).val( '' );
}
}
)
.on(
'keyup',
'#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]',
function () {
var sale_price_field = $( this ),
regular_price_field;
if (
sale_price_field
.attr( 'name' )
.indexOf( 'variable' ) !== -1
) {
regular_price_field = sale_price_field
.parents( '.variable_pricing' )
.find(
'.wc_input_price[name^=variable_regular_price]'
);
} else {
regular_price_field = $( '#_regular_price' );
}
var sale_price = parseFloat(
window.accounting.unformat(
sale_price_field.val(),
woocommerce_admin.mon_decimal_point
)
);
var regular_price = parseFloat(
window.accounting.unformat(
regular_price_field.val(),
woocommerce_admin.mon_decimal_point
)
);
if ( sale_price >= regular_price ) {
$( document.body ).triggerHandler( 'wc_add_error_tip', [
$( this ),
'i18n_sale_less_than_regular_error',
] );
} else {
$(
document.body
).triggerHandler( 'wc_remove_error_tip', [
$( this ),
'i18n_sale_less_than_regular_error',
] );
}
}
)
.on( 'init_tooltips', function () {
$( '.tips, .help_tip, .woocommerce-help-tip' ).tipTip( {
attribute: 'data-tip',
fadeIn: 50,
fadeOut: 50,
delay: 200,
keepAlive: true,
} );
$( '.column-wc_actions .wc-action-button' ).tipTip( {
fadeIn: 50,
fadeOut: 50,
delay: 200,
} );
// Add tiptip to parent element for widefat tables
$( '.parent-tips' ).each( function () {
$( this )
.closest( 'a, th' )
.attr( 'data-tip', $( this ).data( 'tip' ) )
.tipTip( {
attribute: 'data-tip',
fadeIn: 50,
fadeOut: 50,
delay: 200,
keepAlive: true,
} )
.css( 'cursor', 'help' );
} );
} )
.on( 'click', '.wc-confirm-delete', function ( event ) {
if (
! window.confirm( woocommerce_admin.i18n_confirm_delete )
) {
event.stopPropagation();
}
} );
// Tooltips
$( document.body ).trigger( 'init_tooltips' );
// wc_input_table tables
$( '.wc_input_table.sortable tbody' ).sortable( {
items: 'tr',
cursor: 'move',
axis: 'y',
scrollSensitivity: 40,
forcePlaceholderSize: true,
helper: 'clone',
opacity: 0.65,
placeholder: 'wc-metabox-sortable-placeholder',
start: function ( event, ui ) {
ui.item.css( 'background-color', '#f6f6f6' );
},
stop: function ( event, ui ) {
ui.item.removeAttr( 'style' );
},
} );
// Focus on inputs within the table if clicked instead of trying to sort.
$( '.wc_input_table.sortable tbody input' ).on( 'click', function () {
$( this ).trigger( 'focus' );
} );
$( '.wc_input_table .remove_rows' ).on( 'click', function () {
var $tbody = $( this ).closest( '.wc_input_table' ).find( 'tbody' );
if ( $tbody.find( 'tr.current' ).length > 0 ) {
var $current = $tbody.find( 'tr.current' );
$current.each( function () {
$( this ).remove();
} );
}
return false;
} );
var controlled = false;
var shifted = false;
var hasFocus = false;
$( document.body ).on( 'keyup keydown', function ( e ) {
shifted = e.shiftKey;
controlled = e.ctrlKey || e.metaKey;
} );
$( '.wc_input_table' )
.on( 'focus click', 'input', function ( e ) {
var $this_table = $( this ).closest( 'table, tbody' );
var $this_row = $( this ).closest( 'tr' );
if (
( e.type === 'focus' && hasFocus !== $this_row.index() ) ||
( e.type === 'click' && $( this ).is( ':focus' ) )
) {
hasFocus = $this_row.index();
if ( ! shifted && ! controlled ) {
$( 'tr', $this_table )
.removeClass( 'current' )
.removeClass( 'last_selected' );
$this_row
.addClass( 'current' )
.addClass( 'last_selected' );
} else if ( shifted ) {
$( 'tr', $this_table ).removeClass( 'current' );
$this_row
.addClass( 'selected_now' )
.addClass( 'current' );
if ( $( 'tr.last_selected', $this_table ).length > 0 ) {
if (
$this_row.index() >
$( 'tr.last_selected', $this_table ).index()
) {
$( 'tr', $this_table )
.slice(
$(
'tr.last_selected',
$this_table
).index(),
$this_row.index()
)
.addClass( 'current' );
} else {
$( 'tr', $this_table )
.slice(
$this_row.index(),
$(
'tr.last_selected',
$this_table
).index() + 1
)
.addClass( 'current' );
}
}
$( 'tr', $this_table ).removeClass( 'last_selected' );
$this_row.addClass( 'last_selected' );
} else {
$( 'tr', $this_table ).removeClass( 'last_selected' );
if (
controlled &&
$( this ).closest( 'tr' ).is( '.current' )
) {
$this_row.removeClass( 'current' );
} else {
$this_row
.addClass( 'current' )
.addClass( 'last_selected' );
}
}
$( 'tr', $this_table ).removeClass( 'selected_now' );
}
} )
.on( 'blur', 'input', function () {
hasFocus = false;
} );
// Additional cost and Attribute term tables
$(
'.woocommerce_page_wc-settings .shippingrows tbody tr:even, table.attributes-table tbody tr:nth-child(odd)'
).addClass( 'alternate' );
// Show order items on orders page
$( document.body ).on( 'click', '.show_order_items', function () {
$( this ).closest( 'td' ).find( 'table' ).toggle();
return false;
} );
// Select availability
$( 'select.availability' )
.on( 'change', function () {
if ( $( this ).val() === 'all' ) {
$( this ).closest( 'tr' ).next( 'tr' ).hide();
} else {
$( this ).closest( 'tr' ).next( 'tr' ).show();
}
} )
.trigger( 'change' );
// Hidden options
$( '.hide_options_if_checked' ).each( function () {
$( this )
.find( 'input:eq(0)' )
.on( 'change', function () {
if ( $( this ).is( ':checked' ) ) {
$( this )
.closest( 'fieldset, tr' )
.nextUntil(
'.hide_options_if_checked, .show_options_if_checked',
'.hidden_option'
)
.hide();
} else {
$( this )
.closest( 'fieldset, tr' )
.nextUntil(
'.hide_options_if_checked, .show_options_if_checked',
'.hidden_option'
)
.show();
}
} )
.trigger( 'change' );
} );
$( '.show_options_if_checked' ).each( function () {
$( this )
.find( 'input:eq(0)' )
.on( 'change', function () {
if ( $( this ).is( ':checked' ) ) {
$( this )
.closest( 'fieldset, tr' )
.nextUntil(
'.hide_options_if_checked, .show_options_if_checked',
'.hidden_option'
)
.show();
} else {
$( this )
.closest( 'fieldset, tr' )
.nextUntil(
'.hide_options_if_checked, .show_options_if_checked',
'.hidden_option'
)
.hide();
}
} )
.trigger( 'change' );
} );
// Reviews.
$( 'input#woocommerce_enable_reviews' )
.on( 'change', function () {
if ( $( this ).is( ':checked' ) ) {
$( '#woocommerce_enable_review_rating' )
.closest( 'tr' )
.show();
} else {
$( '#woocommerce_enable_review_rating' )
.closest( 'tr' )
.hide();
}
} )
.trigger( 'change' );
// Attribute term table
$( 'table.attributes-table tbody tr:nth-child(odd)' ).addClass(
'alternate'
);
// Toggle gateway on/off.
$( '.wc_gateways' ).on(
'click',
'.wc-payment-gateway-method-toggle-enabled',
function () {
var $link = $( this ),
$row = $link.closest( 'tr' ),
$toggle = $link.find( '.woocommerce-input-toggle' );
var data = {
action: 'woocommerce_toggle_gateway_enabled',
security: woocommerce_admin.nonces.gateway_toggle,
gateway_id: $row.data( 'gateway_id' ),
};
$toggle.addClass( 'woocommerce-input-toggle--loading' );
$.ajax( {
url: woocommerce_admin.ajax_url,
data: data,
dataType: 'json',
type: 'POST',
success: function ( response ) {
if ( true === response.data ) {
$toggle.removeClass(
'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
);
$toggle.addClass(
'woocommerce-input-toggle--enabled'
);
$toggle.removeClass(
'woocommerce-input-toggle--loading'
);
} else if ( false === response.data ) {
$toggle.removeClass(
'woocommerce-input-toggle--enabled, woocommerce-input-toggle--disabled'
);
$toggle.addClass(
'woocommerce-input-toggle--disabled'
);
$toggle.removeClass(
'woocommerce-input-toggle--loading'
);
} else if ( 'needs_setup' === response.data ) {
window.location.href = $link.attr( 'href' );
}
},
} );
return false;
}
);
$( '#wpbody' ).on( 'click', '#doaction, #doaction2', function () {
var action = $( this ).is( '#doaction' )
? $( '#bulk-action-selector-top' ).val()
: $( '#bulk-action-selector-bottom' ).val();
if ( 'remove_personal_data' === action ) {
return window.confirm(
woocommerce_admin.i18n_remove_personal_data_notice
);
}
} );
var marketplaceSectionDropdown = $(
'#marketplace-current-section-dropdown'
);
var marketplaceSectionName = $( '#marketplace-current-section-name' );
var marketplaceMenuIsOpen = false;
// Add event listener to toggle Marketplace menu on touch devices
if ( marketplaceSectionDropdown.length ) {
if ( isTouchDevice() ) {
marketplaceSectionName.on( 'click', function () {
marketplaceMenuIsOpen = ! marketplaceMenuIsOpen;
if ( marketplaceMenuIsOpen ) {
marketplaceSectionDropdown.addClass( 'is-open' );
$( document ).on( 'click', maybeToggleMarketplaceMenu );
} else {
marketplaceSectionDropdown.removeClass( 'is-open' );
$( document ).off(
'click',
maybeToggleMarketplaceMenu
);
}
} );
} else {
document.body.classList.add( 'no-touch' );
}
}
// Close menu if the user clicks outside it
function maybeToggleMarketplaceMenu( e ) {
if (
! marketplaceSectionDropdown.is( e.target ) &&
marketplaceSectionDropdown.has( e.target ).length === 0
) {
marketplaceSectionDropdown.removeClass( 'is-open' );
marketplaceMenuIsOpen = false;
$( document ).off( 'click', maybeToggleMarketplaceMenu );
}
}
function isTouchDevice() {
return (
'ontouchstart' in window ||
navigator.maxTouchPoints > 0 ||
navigator.msMaxTouchPoints > 0
);
}
} );
$( function() {
/**
* Handles heartbeat integration of order locking when HPOS is enabled.
*/
var wc_order_lock = {
init: function() {
// Order screen.
this.$lock_dialog = $( '.woocommerce_page_wc-orders #post-lock-dialog.order-lock-dialog' );
if ( 0 !== this.$lock_dialog.length && 'undefined' !== typeof woocommerce_admin_meta_boxes ) {
// We do not want WP's lock to interfere.
$( document ).off( 'heartbeat-send.refresh-lock' );
$( document ).off( 'heartbeat-tick.refresh-lock' );
$( document ).on( 'heartbeat-send', this.refresh_order_lock );
$( document ).on( 'heartbeat-tick', this.check_order_lock );
}
// Orders list table.
this.$list_table = $( '.woocommerce_page_wc-orders table.wc-orders-list-table' );
if ( 0 !== this.$list_table.length ) {
$( document ).on( 'heartbeat-send', this.send_orders_in_list );
$( document ).on( 'heartbeat-tick', this.check_orders_in_list );
}
},
refresh_order_lock: function( e, data ) {
delete data['wp-refresh-post-lock'];
data['wc-refresh-order-lock'] = woocommerce_admin_meta_boxes.post_id;
},
check_order_lock: function( e, data ) {
var lock_data = data['wc-refresh-order-lock'];
if ( ! lock_data || ! lock_data.error ) {
// No lock request in heartbeat or lock refreshed ok.
return;
}
if ( wc_order_lock.$lock_dialog.is( ':visible' ) ) {
return;
}
if ( lock_data.error.user_avatar_src ) {
wc_order_lock.$lock_dialog.find( '.post-locked-avatar' ).empty().append(
$(
'<img />',
{
'class': 'avatar avatar-64 photo',
width: 64,
height: 64,
alt: '',
src: lock_data.error.user_avatar_src,
srcset: lock_data.error.user_avatar_src_2x ? lock_data.error.user_avatar_src_2x + ' 2x' : undefined
}
)
);
}
wc_order_lock.$lock_dialog.find( '.currently-editing' ).text( lock_data.error.message );
wc_order_lock.$lock_dialog.show();
wc_order_lock.$lock_dialog.find( '.wp-tab-first' ).trigger( 'focus' );
},
send_orders_in_list: function( e, data ) {
data['wc-check-locked-orders'] = wc_order_lock.$list_table.find( 'tr input[name="id[]"]' ).map(
function() { return this.value; }
).get();
},
check_orders_in_list: function( e, data ) {
var locked_orders = data['wc-check-locked-orders'] || {};
wc_order_lock.$list_table.find( 'tr' ).each( function( i, tr ) {
var $tr = $( tr );
var order_id = $tr.find( 'input[name="id[]"]' ).val();
if ( locked_orders[ order_id ] ) {
if ( ! $tr.hasClass( 'wp-locked' ) ) {
$tr.find( '.check-column checkbox' ).prop( 'checked', false );
$tr.addClass( 'wp-locked' );
}
} else {
$tr.removeClass( 'wp-locked' ).find( '.locked-info span' ).empty();
}
} );
}
};
wc_order_lock.init();
} );
} )( jQuery, woocommerce_admin );
@@ -0,0 +1 @@
!function(e,t){e(function(){if(void 0!==t){var o=e(".edit-php.post-type-product"),i=o.find(".page-title-action:first");0===o.find(".woocommerce-BlankState").length?(t.urls.add_product&&i.first().attr("href",t.urls.add_product),t.urls.export_products&&i.after('<a href="'+t.urls.export_products+'" class="page-title-action">'+t.strings.export_products+"</a>"),t.urls.import_products&&i.after('<a href="'+t.urls.import_products+'" class="page-title-action">'+t.strings.import_products+"</a>")):i.hide(),e(".woocommerce-progress-form-wrapper .button-next").on("click",function(){return e(".wc-progress-form-content").block({message:null,overlayCSS:{background:"#fff",opacity:.6}}),!0}),e(document.body).on("wc_add_error_tip",function(o,i,r){var n=i.position();0===i.parent().find(".wc_error_tip").length&&(i.after('<div class="wc_error_tip '+r+'">'+t[r]+"</div>"),i.parent().find(".wc_error_tip").css("left",n.left+i.width()-i.width()/2-e(".wc_error_tip").width()/2).css("top",n.top+i.height()).fadeIn("100"))}).on("wc_remove_error_tip",function(t,o,i){o.parent().find(".wc_error_tip."+i).fadeOut("100",function(){e(this).remove()})}).on("click",function(){e(".wc_error_tip").fadeOut("100",function(){e(this).remove()})}).on("blur",".wc_input_decimal[type=text], .wc_input_price[type=text], .wc_input_country_iso[type=text]",function(){e(".wc_error_tip").fadeOut("100",function(){e(this).remove()})}).on("change",".wc_input_price[type=text], .wc_input_decimal[type=text], .wc-order-totals #refund_amount[type=text], .wc_input_variations_price[type=text]",function(){var o,i,r=t.decimal_point;(e(this).is(".wc_input_price")||e(this).is(".wc_input_variations_price")||e(this).is("#refund_amount"))&&(r=t.mon_decimal_point),o=new RegExp("[^-0-9%\\"+r+"]+","gi"),i=new RegExp("\\"+r+"+","gi");var n=e(this).val(),c=n.replace(o,"").replace(i,r);n!==c&&e(this).val(c)}).on("keyup",".wc_input_price[type=text], .wc_input_decimal[type=text], .wc_input_country_iso[type=text], .wc-order-totals #refund_amount[type=text], .wc_input_variations_price[type=text]",function(){var o,i,r,n=!1;e(this).is(".wc_input_price")||e(this).is(".wc_input_variations_price")||e(this).is("#refund_amount")?(n=!0,o=new RegExp("[^-0-9%\\"+t.mon_decimal_point+"]+","gi"),r=new RegExp("[^\\"+t.mon_decimal_point+"]","gi"),i="i18n_mon_decimal_error"):e(this).is(".wc_input_country_iso")?(o=new RegExp("([^A-Z])+|(.){3,}","im"),i="i18n_country_iso_error"):(n=!0,o=new RegExp("[^-0-9%\\"+t.decimal_point+"]+","gi"),r=new RegExp("[^\\"+t.decimal_point+"]","gi"),i="i18n_decimal_error");var c=e(this).val(),a=c.replace(o,"");n&&1<a.replace(r,"").length&&(a=a.replace(r,"")),c!==a?e(document.body).triggerHandler("wc_add_error_tip",[e(this),i]):e(document.body).triggerHandler("wc_remove_error_tip",[e(this),i])}).on("change","#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]",function(){var o,i=e(this);o=-1!==i.attr("name").indexOf("variable")?i.parents(".variable_pricing").find(".wc_input_price[name^=variable_regular_price]"):e("#_regular_price"),parseFloat(window.accounting.unformat(i.val(),t.mon_decimal_point))>=parseFloat(window.accounting.unformat(o.val(),t.mon_decimal_point))&&e(this).val("")}).on("keyup","#_sale_price.wc_input_price[type=text], .wc_input_price[name^=variable_sale_price]",function(){var o,i=e(this);o=-1!==i.attr("name").indexOf("variable")?i.parents(".variable_pricing").find(".wc_input_price[name^=variable_regular_price]"):e("#_regular_price"),parseFloat(window.accounting.unformat(i.val(),t.mon_decimal_point))>=parseFloat(window.accounting.unformat(o.val(),t.mon_decimal_point))?e(document.body).triggerHandler("wc_add_error_tip",[e(this),"i18n_sale_less_than_regular_error"]):e(document.body).triggerHandler("wc_remove_error_tip",[e(this),"i18n_sale_less_than_regular_error"])}).on("init_tooltips",function(){e(".tips, .help_tip, .woocommerce-help-tip").tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}),e(".column-wc_actions .wc-action-button").tipTip({fadeIn:50,fadeOut:50,delay:200}),e(".parent-tips").each(function(){e(this).closest("a, th").attr("data-tip",e(this).data("tip")).tipTip({attribute:"data-tip",fadeIn:50,fadeOut:50,delay:200,keepAlive:!0}).css("cursor","help")})}).on("click",".wc-confirm-delete",function(e){window.confirm(t.i18n_confirm_delete)||e.stopPropagation()}),e(document.body).trigger("init_tooltips"),e(".wc_input_table.sortable tbody").sortable({items:"tr",cursor:"move",axis:"y",scrollSensitivity:40,forcePlaceholderSize:!0,helper:"clone",opacity:.65,placeholder:"wc-metabox-sortable-placeholder",start:function(e,t){t.item.css("background-color","#f6f6f6")},stop:function(e,t){t.item.removeAttr("style")}}),e(".wc_input_table.sortable tbody input").on("click",function(){e(this).trigger("focus")}),e(".wc_input_table .remove_rows").on("click",function(){var t=e(this).closest(".wc_input_table").find("tbody");t.find("tr.current").length>0&&t.find("tr.current").each(function(){e(this).remove()});return!1});varLine truncated