How to use wp method in storybook-root

Best JavaScript code snippet using storybook-root

wp-smushit-admin.js

Source:wp-smushit-admin.js Github

copy

Full Screen

1/**2 * Processes bulk smushing3 *4 * @author Umesh Kumar <umeshsingla05@gmail.com>5 *6 */7/**@todo: Use Element tag for all the class selectors **/8var WP_Smush = WP_Smush || {};9/**10 * Show/hide the progress bar for Smushing/Restore/SuperSmush11 *12 * @param cur_ele13 * @param txt Message to be displayed14 * @param state show/hide15 */16var progress_bar = function (cur_ele, txt, state) {17 //Update Progress bar text and show it18 var progress_button = cur_ele.parents().eq(1).find('.wp-smush-progress');19 if ('show' == state) {20 progress_button.find('span').html(txt);21 progress_button.removeClass('hidden');22 } else {23 progress_button.find('span').html(wp_smush_msgs.all_done);24 progress_button.hide();25 }26};27var dash_offset = function (percent) {28 //Get the dasharray value29 var dasharray = jQuery('.wp-smush-svg-circle-progress').attr('stroke-dasharray');30 return dasharray - ( dasharray * percent );31}32var update_dashoffset = function (stats) {33 var total = stats.total;34 if (total > 0) {35 var dashoffset = dash_offset(stats.smushed / total);36 var circle_progress = jQuery('.wp-smush-svg-circle-progress');37 if (typeof dashoffset != 'undefined' && circle_progress.length) {38 circle_progress.css({'stroke-dashoffset': dashoffset});39 }40 }41};42var membership_validity = function (data) {43 var member_validity_notice = jQuery('#wp-smush-invalid-member');44 //Check for Membership warning45 if ('undefined' != typeof ( data.show_warning ) && member_validity_notice.length > 0) {46 if (data.show_warning) {47 member_validity_notice.show();48 } else {49 member_validity_notice.hide();50 }51 }52};53/**54 * Resize Background width55 */56var resize_width = function () {57 var width = jQuery('.wp-smush-pro-for-free').width();58 if ('undefined' != typeof ( width ) && 500 < width) {59 jQuery('.wpmud .wp-smush-pro-adv').css({'background-size': '500px'});60 } else {61 jQuery('.wpmud .wp-smush-pro-adv').css({'background-size': '90%'});62 }63};64var remove_element = function (el, timeout) {65 if (typeof timeout == 'undefined') {66 timeout = 100;67 }68 el.fadeTo(timeout, 0, function () {69 el.slideUp(timeout, function () {70 el.remove();71 });72 });73};74jQuery(function ($) {75 var smushAddParams = function (url, data) {76 if (!$.isEmptyObject(data)) {77 url += ( url.indexOf('?') >= 0 ? '&' : '?' ) + $.param(data);78 }79 return url;80 };81 // url for smushing82 WP_Smush.errors = [];83 WP_Smush.timeout = wp_smushit_data.timeout;84 /**85 * Checks for the specified param in URL86 * @param arg87 * @returns {*}88 */89 WP_Smush.geturlparam = function (arg) {90 var $sPageURL = window.location.search.substring(1);91 var $sURLVariables = $sPageURL.split('&');92 for (var i = 0; i < $sURLVariables.length; i++) {93 var $sParameterName = $sURLVariables[i].split('=');94 if ($sParameterName[0] == arg) {95 return $sParameterName[1];96 }97 }98 };99 WP_Smush.Smush = function ($button, bulk, smush_type) {100 var self = this;101 var skip_resmush = $button.data('smush');102 //If smush attribute is not defined, Need not skip resmush ids103 skip_resmush = ( ( typeof skip_resmush == typeof undefined ) || skip_resmush == false ) ? false : true;104 this.init = function () {105 this.$button = $($button[0]);106 this.is_bulk = typeof bulk ? bulk : false;107 this.url = ajaxurl;108 this.$log = $(".smush-final-log");109 this.deferred = jQuery.Deferred();110 this.deferred.errors = [];111 //If button has resmush class, and we do have ids that needs to resmushed, put them in the list112 this.ids = wp_smushit_data.resmush.length > 0 && !skip_resmush ? ( wp_smushit_data.unsmushed.length > 0 ? wp_smushit_data.resmush.concat(wp_smushit_data.unsmushed) : wp_smushit_data.resmush ) : wp_smushit_data.unsmushed;113 this.is_bulk_resmush = wp_smushit_data.resmush.length > 0 && !skip_resmush ? true : false;114 this.$status = this.$button.parent().find('.smush-status');115 //Added for NextGen support116 this.smush_type = typeof smush_type ? smush_type : false;117 this.single_ajax_suffix = this.smush_type ? 'smush_manual_nextgen' : 'wp_smushit_manual';118 this.bulk_ajax_suffix = this.smush_type ? 'wp_smushit_nextgen_bulk' : 'wp_smushit_bulk';119 this.url = this.is_bulk ? smushAddParams(this.url, {action: this.bulk_ajax_suffix}) : smushAddParams(this.url, {action: this.single_ajax_suffix});120 };121 /** Send Ajax request for smushing the image **/122 WP_Smush.ajax = function (is_bulk_resmush, $id, $send_url, $getnxt, nonce) {123 "use strict";124 var param = {125 is_bulk_resmush: is_bulk_resmush,126 attachment_id: $id,127 get_next: $getnxt,128 _nonce: nonce129 };130 param = jQuery.param(param);131 return $.ajax({132 type: "GET",133 data: param,134 url: $send_url,135 timeout: WP_Smush.timeout,136 dataType: 'json'137 });138 };139 //Show loader in button for single and bulk smush140 this.start = function () {141 this.$button.attr('disabled', 'disabled');142 this.$button.addClass('wp-smush-started');143 this.bulk_start();144 this.single_start();145 };146 this.bulk_start = function () {147 if (!this.is_bulk) return;148 //Hide the Bulk Div149 $('.wp-smush-bulk-wrapper').hide();150 //Show the Progress Bar151 $('.bulk-smush-wrapper .wp-smush-bulk-progress-bar-wrapper').show();152 //Remove any Global Notices if there153 $('.wp-smush-notice.wp-smush-resmush-message').remove();154 };155 this.single_start = function () {156 if (this.is_bulk) return;157 this.show_loader();158 this.$status.removeClass("error");159 };160 this.enable_button = function () {161 this.$button.prop("disabled", false);162 //For Bulk process, Enable other buttons163 $('button.wp-smush-all').removeAttr('disabled');164 $('button.wp-smush-scan').removeAttr('disabled');165 };166 this.show_loader = function () {167 progress_bar(this.$button, wp_smush_msgs.smushing, 'show');168 };169 this.hide_loader = function () {170 progress_bar(this.$button, wp_smush_msgs.smushing, 'hide');171 };172 this.single_done = function () {173 if (this.is_bulk) return;174 this.hide_loader();175 this.request.done(function (response) {176 if (typeof response.data != 'undefined') {177 //Append the smush stats or error178 self.$status.html(response.data);179 //Check whether to show membership validity notice or not180 membership_validity(response.data);181 if (response.success && response.data !== "Not processed") {182 self.$status.removeClass('hidden');183 self.$button.parent().removeClass('unsmushed').addClass('smushed');184 self.$button.remove();185 } else {186 self.$status.addClass("error");187 self.$status.html(response.data.error_msg);188 self.$status.show();189 }190 if (response.data.status) {191 self.$status.html(response.data.status);192 }193 //Check if stats div exists194 var parent = self.$status.parent();195 var stats_div = parent.find('.smush-stats-wrapper');196 if ('undefined' != stats_div && stats_div.length) {197 stats_div.replaceWith(response.data.stats);198 } else {199 parent.append(response.data.stats);200 }201 }202 self.enable_button();203 }).error(function (response) {204 self.$status.html(response.data);205 self.$status.addClass("error");206 self.enable_button();207 });208 };209 /** After the Bulk Smushing has been Finished **/210 this.bulk_done = function () {211 if (!this.is_bulk) return;212 //Enable the button213 this.enable_button();214 //Show Notice215 if (self.ids.length == 0) {216 $('.bulk-smush-wrapper .wp-smush-all-done').show();217 $('.wp-smush-bulk-wrapper').hide();218 } else {219 if ($('.bulk-smush-wrapper .wp-smush-resmush-notice').length > 0) {220 $('.bulk-smush-wrapper .wp-smush-resmush-notice').show();221 } else {222 $('.bulk-smush-wrapper .wp-smush-remaining').show();223 }224 $('.wp-smush-bulk-wrapper').show();225 }226 //Hide the Progress Bar227 $('.wp-smush-bulk-progress-bar-wrapper').hide();228 //Enable Resmush and scan button229 $('.wp-resmush.wp-smush-action, .wp-smush-scan').removeAttr('disabled');230 };231 this.is_resolved = function () {232 "use strict";233 return this.deferred.state() === "resolved";234 };235 this.free_exceeded = function () {236 //Hide the Progress bar and show the Bulk smush wrapper237 $('.wp-smush-bulk-progress-bar-wrapper').hide();238 if (self.ids.length > 0) {239 //Show Bulk wrapper240 $('.wp-smush-bulk-wrapper ').show();241 } else {242 $('.wp-smush-notice.wp-smush-all-done').show();243 }244 };245 this.update_remaining_count = function () {246 if (this.is_bulk_resmush) {247 //ReSmush Notice248 if ($('.wp-smush-resmush-notice .wp-smush-remaining-count').length && 'undefined' != typeof self.ids) {249 $('.wp-smush-resmush-notice .wp-smush-remaining-count').html(self.ids.length);250 }251 } else {252 //Smush Notice253 if ($('.bulk-smush-wrapper .wp-smush-remaining-count').length && 'undefined' != typeof self.ids) {254 $('.bulk-smush-wrapper .wp-smush-remaining-count').html(self.ids.length);255 }256 }257 }258 this.update_progress = function (_res) {259 //If not bulk260 if (!this.is_bulk_resmush && !this.is_bulk) {261 return;262 }263 var progress = '';264 if (!this.is_bulk_resmush) {265 if (_res && ( 'undefined' == typeof _res.data || 'undefined' == typeof _res.data.stats )) {266 return;267 }268 //handle progress for normal bulk smush269 progress = ( _res.data.stats.smushed / _res.data.stats.total ) * 100;270 } else {271 //If the Request was successful, Update the progress bar272 if (_res.success) {273 //Handle progress for Super smush progress bar274 if (wp_smushit_data.resmush.length > 0) {275 //Update the Count276 $('.wp-smush-images-remaining').html(wp_smushit_data.resmush.length);277 } else if (wp_smushit_data.resmush.length == 0 && this.ids.length == 0) {278 //If all images are resmushed, show the All Smushed message279 //Show All Smushed280 $('.bulk-resmush-wrapper .wp-smush-all-done').removeClass('hidden');281 //Hide Everything else282 $('.wp-smush-resmush-wrap, .wp-smush-bulk-progress-bar-wrapper').hide();283 }284 }285 //handle progress for normal bulk smush286 //Set Progress Bar width287 if ('undefined' !== typeof self.ids && 'undefined' !== typeof wp_smushit_data.count_total && wp_smushit_data.count_total > 0) {288 progress = ( ( wp_smushit_data.count_total - self.ids.length ) / wp_smushit_data.count_total ) * 100;289 }290 }291 //Show Bulk Wrapper and Smush Notice292 if (self.ids.length == 0) {293 //Hide the bulk wrapper294 $('.wp-smush-bulk-wrapper').hide();295 //Show All done notice296 $('.wp-smush-notice.wp-smush-all-done').show();297 }298 //Update remaining count299 self.update_remaining_count();300 //if we have received the progress data, update the stats else skip301 if ('undefined' != typeof _res.data.stats) {302 // increase the progress bar303 this._update_progress(_res.data.stats.smushed, progress);304 }305 // Update stats and counts.306 update_stats(_res);307 };308 this._update_progress = function (count, width) {309 "use strict";310 if (!this.is_bulk && !this.is_bulk_resmush) {311 return;312 }313 //Update the Progress Bar Width314 // get the progress bar315 var $progress_bar = jQuery('.bulk-smush-wrapper .wp-smush-progress-inner');316 if ($progress_bar.length < 1) {317 return;318 }319 // increase progress320 $progress_bar.css('width', width + '%');321 };322 //Whether to send the ajax requests further or not323 this.continue = function () {324 var continue_smush = self.$button.attr('continue_smush');325 if (typeof continue_smush == typeof undefined) {326 continue_smush = true;327 }328 if ('false' == continue_smush || !continue_smush) {329 continue_smush = false;330 }331 return continue_smush && this.ids.length > 0 && this.is_bulk;332 };333 this.increment_errors = function (id) {334 WP_Smush.errors.push(id);335 };336 //Send ajax request for smushing single and bulk, call update_progress on ajax response337 this.call_ajax = function () {338 var nonce_value = '';339 this.current_id = this.is_bulk ? this.ids.shift() : this.$button.data("id"); //remove from array while processing so we can continue where left off340 //Remove the id from respective variable as well341 this.update_smush_ids(this.current_id);342 var nonce_field = this.$button.parent().find('#_wp_smush_nonce');343 if (nonce_field) {344 nonce_value = nonce_field.val();345 }346 this.request = WP_Smush.ajax(this.is_bulk_resmush, this.current_id, this.url, 0, nonce_value)347 .error(function () {348 self.increment_errors(self.current_id);349 }).done(function (res) {350 //Increase the error count if any351 if (typeof res.success === "undefined" || ( typeof res.success !== "undefined" && res.success === false && res.data.error !== 'bulk_request_image_limit_exceeded' )) {352 self.increment_errors(self.current_id);353 }354 //If no response or success is false, do not process further355 if (typeof res == 'undefined' || !res || !res.success) {356 if ('undefined' !== typeof res && 'undefined' !== typeof res.data && typeof res.data.error_msg !== 'undefined') {357 //Print the error on screen358 self.$log.append(res.data.error_msg);359 self.$log.removeClass('hidden');360 }361 }362 //Check whether to show the warning notice or not363 membership_validity(res.data);364 if (typeof res.data !== "undefined" && res.data.error == 'bulk_request_image_limit_exceeded' && !self.is_resolved()) {365 //Add a data attribute to the smush button, to stop sending ajax366 self.$button.attr('continue_smush', false);367 self.free_exceeded();368 //Reinsert the current id369 wp_smushit_data.unsmushed.push(self.current_id);370 //Update the remaining count to length of remaining ids + 1 (Current id)371 self.update_remaining_count();372 } else {373 if (self.is_bulk && res.success) {374 self.update_progress(res);375 }376 }377 self.single_done();378 }).complete(function () {379 if (!self.continue() || !self.is_bulk) {380 //Calls deferred.done()381 self.deferred.resolve();382 } else {383 self.call_ajax();384 }385 });386 self.deferred.errors = WP_Smush.errors;387 return self.deferred;388 };389 this.init(arguments);390 //Send ajax request for single and bulk smushing391 this.run = function () {392 // if we have a definite number of ids393 if (this.is_bulk && this.ids.length > 0) {394 this.call_ajax();395 }396 if (!this.is_bulk)397 this.call_ajax();398 };399 //Show bulk smush errors, and disable bulk smush button on completion400 this.bind_deferred_events = function () {401 this.deferred.done(function () {402 self.$button.removeAttr('continue_smush');403 if (WP_Smush.errors.length) {404 var error_message = '<div class="wp-smush-ajax-error">' + wp_smush_msgs.error_in_bulk.replace("{{errors}}", WP_Smush.errors.length) + '</div>';405 //Remove any existing notice406 $('.wp-smush-ajax-error').remove();407 self.$log.prepend(error_message);408 }409 self.bulk_done();410 //Re enable the buttons411 $('.wp-smush-button:not(.wp-smush-finished), .wp-smush-scan').removeAttr('disabled');412 });413 };414 /** Handles the Cancel button Click415 *416 * Update the UI, and enables the bulk smush button417 *418 **/419 this.cancel_ajax = function () {420 $('.wp-smush-cancel-bulk').on('click', function () {421 //Add a data attribute to the smush button, to stop sending ajax422 self.$button.attr('continue_smush', false);423 self.request.abort();424 self.enable_button();425 self.$button.removeClass('wp-smush-started');426 $('.wp-smush-bulk-wrapper').show();427 //Hide the Progress Bar428 $('.wp-smush-bulk-progress-bar-wrapper').hide();429 });430 };431 /**432 * Remove the current id from unsmushed/resmush variable433 * @param current_id434 */435 this.update_smush_ids = function (current_id) {436 if ('undefined' !== typeof wp_smushit_data.unsmushed && wp_smushit_data.unsmushed.length > 0) {437 var u_index = wp_smushit_data.unsmushed.indexOf(current_id);438 if (u_index > -1) {439 wp_smushit_data.unsmushed.splice(u_index, 1);440 }441 }442 //remove from the resmush list443 if ('undefined' !== typeof wp_smushit_data.resmush && wp_smushit_data.resmush.length > 0) {444 var index = wp_smushit_data.resmush.indexOf(current_id);445 if (index > -1) {446 wp_smushit_data.resmush.splice(index, 1);447 }448 }449 }450 this.start();451 this.run();452 this.bind_deferred_events();453 //Handle Cancel Ajax454 this.cancel_ajax();455 return this.deferred;456 };457 /**458 * Handle the Bulk Smush/ Bulk Resmush button click459 */460 $('body').on('click', 'button.wp-smush-all', function (e) {461 // prevent the default action462 e.preventDefault();463 $('.wp-smush-notice.wp-smush-settings-updated').remove();464 //Disable Resmush and scan button465 $('.wp-resmush.wp-smush-action, .wp-smush-scan, .wp-smush-button').attr('disabled', 'disabled');466 //Check for ids, if there is none (Unsmushed or lossless), don't call smush function467 if (typeof wp_smushit_data == 'undefined' ||468 ( wp_smushit_data.unsmushed.length == 0 && wp_smushit_data.resmush.length == 0 )469 ) {470 return false;471 }472 $(".wp-smush-remaining").hide();473 new WP_Smush.Smush($(this), true);474 });475 /** Disable the action links **/476 var disable_links = function (c_element) {477 var parent = c_element.parent();478 //reduce parent opacity479 parent.css({'opacity': '0.5'});480 //Disable Links481 parent.find('a').attr('disabled', 'disabled');482 };483 /** Enable the Action Links **/484 var enable_links = function (c_element) {485 var parent = c_element.parent();486 //reduce parent opacity487 parent.css({'opacity': '1'});488 //Disable Links489 parent.find('a').removeAttr('disabled');490 };491 /**492 * Restore image request with a specified action for Media Library / NextGen Gallery493 * @param e494 * @param current_button495 * @param smush_action496 * @returns {boolean}497 */498 var process_smush_action = function (e, current_button, smush_action, action) {499 //If disabled500 if ('disabled' == current_button.attr('disabled')) {501 return false;502 }503 e.preventDefault();504 //Remove Error505 $('.wp-smush-error').remove();506 //Hide stats507 $('.smush-stats-wrapper').hide();508 //Get the image ID and nonce509 var params = {510 action: smush_action,511 attachment_id: current_button.data('id'),512 _nonce: current_button.data('nonce')513 };514 //Reduce the opacity of stats and disable the click515 disable_links(current_button);516 progress_bar(current_button, wp_smush_msgs[action], 'show');517 //Restore the image518 $.post(ajaxurl, params, function (r) {519 progress_bar(current_button, wp_smush_msgs[action], 'hide');520 //reset all functionality521 enable_links(current_button);522 if (r.success && 'undefined' != typeof( r.data.button )) {523 //Show the smush button, and remove stats and restore option524 current_button.parents().eq(1).html(r.data.button);525 } else {526 if (r.data.message) {527 //show error528 current_button.parent().append(r.data.message);529 }530 }531 })532 };533 /**534 * Validates the Resize Width and Height against the Largest Thumbnail Width and Height535 *536 * @param wrapper_div jQuery object for the whole setting row wrapper div537 * @param width_only Whether to validate only width538 * @param height_only Validate only Height539 * @returns {boolean} All Good or not540 *541 */542 var validate_resize_settings = function (wrapper_div, width_only, height_only) {543 var resize_checkbox = wrapper_div.find('#wp-smush-resize');544 if (!height_only) {545 var width_input = wrapper_div.find('#wp-smush-resize_width');546 var width_error_note = wrapper_div.find('.wp-smush-size-info.wp-smush-update-width');547 }548 if (!width_only) {549 var height_input = wrapper_div.find('#wp-smush-resize_height');550 var height_error_note = wrapper_div.find('.wp-smush-size-info.wp-smush-update-height');551 }552 var width_error = false;553 var height_error = false554 //If resize settings is not enabled, return true555 if (!resize_checkbox.is(':checked')) {556 return true;557 }558 //Check if we have localised width and height559 if ('undefined' == typeof (wp_smushit_data.resize_sizes) || 'undefined' == typeof (wp_smushit_data.resize_sizes.width)) {560 //Rely on server validation561 return true;562 }563 //Check for width564 if (!height_only && 'undefined' != typeof width_input && parseInt(wp_smushit_data.resize_sizes.width) > parseInt(width_input.val())) {565 width_input.addClass('error');566 width_error_note.show('slow');567 width_error = true;568 } else {569 //Remove error class570 width_input.removeClass('error');571 width_error_note.hide();572 if (height_input.hasClass('error')) {573 height_error_note.show('slow');574 }575 }576 //Check for height577 if (!width_only && 'undefined' != typeof height_input && parseInt(wp_smushit_data.resize_sizes.height) > parseInt(height_input.val())) {578 height_input.addClass('error');579 //If we are not showing the width error already580 if (!width_error) {581 height_error_note.show('slow');582 }583 height_error = true;584 } else {585 //Remove error class586 height_input.removeClass('error');587 height_error_note.hide();588 if (width_input.hasClass('error')) {589 width_error_note.show('slow');590 }591 }592 if (width_error || height_error) {593 return false;594 }595 return true;596 };597 //Stackoverflow: http://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript598 var precise_round = function (num, decimals) {599 var sign = num >= 0 ? 1 : -1;600 return (Math.round((num * Math.pow(10, decimals)) + (sign * 0.001)) / Math.pow(10, decimals));601 };602 /**603 * Update the progress bar width if we have images that needs to be resmushed604 * @param unsmushed_count605 * @returns {boolean}606 */607 var update_progress_bar_resmush = function (unsmushed_count) {608 if ('undefined' == typeof unsmushed_count) {609 return false;610 }611 var smushed_count = wp_smushit_data.count_total - unsmushed_count;612 //Update the Progress Bar Width613 // get the progress bar614 var $progress_bar = jQuery('.bulk-smush-wrapper .wp-smush-progress-inner');615 if ($progress_bar.length < 1) {616 return;617 }618 var width = ( smushed_count / wp_smushit_data.count_total ) * 100;619 // increase progress620 $progress_bar.css('width', width + '%');621 };622 var run_re_check = function (button, process_settings) {623 var spinner = button.parent().find('.spinner');624 //Check if type is set in data attributes625 var scan_type = button.data('type');626 scan_type = 'undefined' == typeof scan_type ? 'media' : scan_type;627 //Show spinner628 spinner.addClass('is-active');629 //Remove the Skip resmush attribute from button630 $('button.wp-smush-all').removeAttr('data-smush');631 //remove notices632 var el = $('.wp-smush-notice.wp-smush-resmush-message, .wp-smush-notice.wp-smush-settings-updated');633 el.slideUp(100, function () {634 el.remove();635 });636 //Disable Bulk smush button and itself637 button.attr('disabled', 'disabled');638 $('.wp-smush-button').attr('disabled', 'disabled');639 //Hide Settings changed Notice640 $('.wp-smush-settings-changed').hide();641 //Show Loading Animation642 jQuery('.bulk-resmush-wrapper .wp-smush-progress-bar-wrap').removeClass('hidden');643 //Ajax Params644 var params = {645 action: 'scan_for_resmush',646 type: scan_type,647 get_ui: true,648 process_settings: process_settings,649 wp_smush_options_nonce: jQuery('#wp_smush_options_nonce').val()650 };651 //Send ajax request and get ids if any652 $.get(ajaxurl, params, function (r) {653 //Check if we have the ids, initialize the local variable654 if ('undefined' != typeof r.data) {655 //Update Resmush id list656 if ('undefined' != typeof r.data.resmush_ids) {657 wp_smushit_data.resmush = r.data.resmush_ids;658 //Get the Smushed image count659 var smushed_count = wp_smushit_data.count_smushed - r.data.resmush_ids.length;660 var smush_percent = ( smushed_count / wp_smushit_data.count_total ) * 100;661 smush_percent = precise_round( smush_percent, 1 );662 //Update it in stats bar663 $('.wp-smush-images-percent').html(smush_percent);664 //Hide the Existing wrapper665 var notices = $('.bulk-smush-wrapper .wp-smush-notice');666 if (notices.length > 0) {667 notices.hide();668 }669 //remove existing Re-Smush notices670 $('.wp-smush-resmush-notice').remove();671 //Show Bulk wrapper672 $('.wp-smush-bulk-wrapper').show();673 if ('undefined' !== typeof r.data.count) {674 //Update progress bar675 update_progress_bar_resmush(r.data.count);676 }677 }678 //If content is received, Prepend it679 if ('undefined' != typeof r.data.content) {680 $('.bulk-smush-wrapper .box-container').prepend(r.data.content);681 }682 //If we have any notice to show683 if ('undefined' != typeof r.data.notice) {684 $('.wp-smush-page-header').after(r.data.notice);685 }686 //Hide errors687 $('.smush-final-log').hide();688 //Hide Super Smush notice if it's enabled in media settings689 if ('undefined' != typeof r.data.super_smush && r.data.super_smush) {690 var enable_lossy = jQuery('.wp-smush-enable-lossy');691 if (enable_lossy.length > 0) {692 enable_lossy.remove();693 }694 if ('undefined' !== r.data.super_smush_stats) {695 $('.super-smush-attachments .wp-smush-stats').html(r.data.super_smush_stats);696 }697 }698 }699 }).always(function () {700 //Hide the progress bar701 jQuery('.bulk-smush-wrapper .wp-smush-bulk-progress-bar-wrapper').hide();702 //Enable the Bulk Smush Button and itself703 button.removeAttr('disabled');704 //Hide Spinner705 spinner.removeClass('is-active');706 $('.wp-smush-button').removeAttr('disabled');707 //If wp-smush-re-check-message is there, remove it708 if ($('.wp-smush-re-check-message').length) {709 remove_element($('.wp-smush-re-check-message'));710 }711 });712 }713 /**714 * Get directory list using Ajax715 *716 * @param param717 * @returns {string}718 *719 */720 var getDirectoryList = function (param) {721 param.action = 'smush_get_directory_list';722 param.list_nonce = jQuery('input[name="list_nonce"]').val();723 var res = '';724 $.ajax({725 type: "GET",726 url: ajaxurl,727 data: param,728 success: function (response) {729 res = response;730 },731 async: false732 });733 return res;734 }735 /**736 * Hide the popup and reset the opacity for the button737 *738 */739 var close_dialog = function () {740 //Hide the dialog741 $('.wp-smush-list-dialog').hide();742 $('.wp-smush-select-dir, button.wp-smush-browse, button.wp-smush-resume').removeAttr('disabled');743 //Remove the spinner744 $('div.dir-smush-button-wrap span.spinner').removeClass('is-active');745 //Reset the opacity for content and scan button746 $('.wp-smush-select-dir, .wp-smush-list-dialog .box .content').css({'opacity': '1'});747 $('.wp-smush-select-button-wrap .spinner').removeClass('is-active');748 }749 /**750 * Initialize accordion751 *752 */753 var set_accordion = function () {754 //Accordion On WP Smush All Page755 var acc = document.getElementsByClassName("wp-smush-li-path");756 var i;757 for (i = 0; i < acc.length; i++) {758 acc[i].onclick = function () {759 var parent = $(this).parent();760 if (parent.hasClass('active')) {761 parent.removeClass('active');762 parent.find('.wp-smush-image-list-inner').removeClass("show");763 } else {764 parent.addClass("active");765 $('.wp-smush-image-ul.active .wp-smush-image-list-inner').addClass("show");766 }767 }768 }769 }770 /**771 * Appends the waiting message to child elements for a directory772 * @param ele773 */774 var update_dir_ele_status = function (ele) {775 //Get the parent element776 var parent = ele.parents('li.wp-smush-image-ul');777 //Spinner778 var spinner = $('div.wp-smush-scan-result span.spinner:first').clone();779 if (!parent.length) {780 return;781 }782 //Check if the selected element is under expandable li783 parent.removeClass('partial complete').addClass('active in-progress');784 //Append a spinner, if parent doesn't have it785 if (!parent.find('span.wp-smush-li-path span.spinner').length) {786 parent.find('span.wp-smush-li-path').prepend(spinner.clone());787 }788 var list = parent.find('.wp-smush-image-list-inner');789 list.addClass('show');790 //Check if first image, Add a loader against directory path791 var progress_wrap = parent.find('div.wp-smush-dir-progress-wrap');792 var waiting_message = $('content').find('span.waiting-message').clone();793 if (ele.is(':first-child')) {794 progress_wrap.css({'display': 'inline-block'});795 parent.find('a.wp-smush-exclude-dir').remove();796 }797 var child = parent.find('ul.wp-smush-image-list-inner li');798 //Mark all the images inside a directory path, as waiting. Copy and append a single span from the page799 var unsmushed = child.filter(":not('.optimised')");800 if (unsmushed.length > 0) {801 //Append a waiting message802 unsmushed.append(waiting_message);803 unsmushed.find(waiting_message).show();804 }805 }806 /**807 * Check if all the elements in the directory are smushed or not808 *809 * @param parent directory selector810 *811 * @returns {boolean}812 *813 */814 var is_last_element = function(parent) {815 var elements = parent.find('li.wp-smush-image-ele:not(.optimised,.error)');816 if( elements.length <= 0 ) {817 return true;818 }819 return false;820 };821 /**822 * Update directory optimisation progress if the element has a parent823 *824 * @param ele825 *826 */827 var update_dir_progress = function (ele) {828 //Get the parent element829 var parent = ele.parents('li.wp-smush-image-ul');830 if (!parent.length) {831 return;832 }833 var child = parent.find('ul.wp-smush-image-list-inner li');834 //Check if first image, Add a loader against directory path835 var progress_wrap = parent.find('div.wp-smush-dir-progress-wrap');836 //Update the percentage, Check the total number of images inside dir, smushed images count837 var total = child.length;838 var smushed = child.filter('.optimised').length;839 var smush_progress = progress_wrap.find('.wp-smush-dir-progress');840 if (smushed > 0 && total > 0) {841 var percent = ( smushed / total ) * 100;842 percent = precise_round(percent, 1);843 progress_wrap.find('.smush-percent').html(percent + '%');844 smush_progress.css({'width': percent + '%'});845 }846 //Add the class in-progress, to show the respective icon for parent847 if (0 != $('input[name="wp-smush-continue-ajax"]').val() && !parent.hasClass('in-progress') && smushed != total) {848 parent.addClass('in-progress').removeClass('partial');849 //Append a spinner850 var spinner = $('div.wp-smush-scan-result span.spinner:first').clone();851 if (spinner) {852 parent.find('span.wp-smush-li-path').prepend(spinner);853 }854 }855 var parent_class = '';856 //Check if last image, and if all the images are not smushed under the specified directory path, add a generic warning message857 if (is_last_element(parent)) {858 if (smushed < total) {859 var unsmushed = total - smushed;860 var message = '<div class="wp-smush-dir-notice"><i class="dev-icon wdv-icon wdv-icon-fw wdv-icon-exclamation-sign"></i>' + unsmushed + ' ' + ( 1 == unsmushed ? wp_smush_msgs.unfinished_smush_single : wp_smush_msgs.unfinished_smush ) + '</div>';861 //If the notice is already displayed, remove it862 var notice = parent.find('div.wp-smush-dir-notice');863 if( notice.length ) {864 notice.remove();865 }866 //Append message to 2nd parent i.e li867 parent.find('ul.wp-smush-image-list-inner').after(message);868 //Check If all the images are smushed, remove the class in-progress and add the class complete, else add class partial869 parent_class = 'partial';870 //Remove the Spinner871 parent.find('span.wp-smush-li-path span.spinner').remove();872 } else {873 parent_class = 'complete';874 smush_progress.removeClass('partial').addClass('complete');875 }876 //Remove Spinner877 parent.find('span.wp-smush-li-path span.spinner').remove();878 //Remove In progress class for the element and add partial/complete class879 parent.removeClass('in-progress active').addClass(parent_class);880 //Remove active class from parent881 parent.removeClass('active').find('.wp-smush-image-list-inner').removeClass("show");882 }883 }884 /**885 * Add choose directory button at the top886 *887 */888 var add_dir_browser_button = function () {889 //Get the content div length, if less than 1500, Skip890 if( $('div.wp-smush-scan-result div.content').height() < 1500 || $('div.dir-smush-button-wrap.top').length >= 1 ) {891 return;892 }893 var choose_button = $('div.dir-smush-button-wrap').clone();894 choose_button.addClass('top');895 $('div.wp-smush-scan-result div.content').prepend(choose_button);896 };897 var add_smush_button = function() {898 //Get the content div length, if less than 1500, Skip899 if( $('div.wp-smush-scan-result div.content').height() < 1500 || $('div.wp-smush-all-button-wrap.top').length >= 1 ) {900 return;901 }902 var smush_button = $('div.wp-smush-all-button-wrap.bottom').clone();903 smush_button.addClass('top').removeClass('bottom');904 $('div.wp-smush-scan-result div.content').prepend(smush_button);905 };906 /**907 * Add smush notice after directory smushing is finished908 *909 * @param notice_type910 * all_done - If all the images were smushed else warning911 * smush_limit - If Free users exceeded limit912 *913 */914 var add_smush_dir_notice = function ( notice_type ) {915 //Get the content div length, if less than 1500, Skip916 if( $('div.wp-smush-scan-result div.content').height() < 1500 || $('div.wp-smush-scan-result div.wp-smush-notice.top').length >= 1 ) {917 return;918 }919 var notice = '';920 //Clone and append the notice921 if( 'all_done' == notice_type ) {922 notice = $('div.wp-smush-notice.wp-smush-dir-all-done').clone();923 }else if( 'smush_limit' == notice_type ){924 notice = $('div.wp-smush-notice.wp-smush-dir-limit').clone();925 }else{926 notice = $('div.wp-smush-notice.wp-smush-dir-remaining').clone();927 }928 //Add class top929 notice.addClass('top');930 //Append the notice931 $('div.wp-smush-scan-result div.dir-smush-button-wrap').after( notice );932 };933 var update_smush_progress = function() {934 var in_progress_path = $('ul.wp-smush-image-list li.in-progress');935 in_progress_path.removeClass('in-progress active');936 if( in_progress_path.length > 0 ) {937 in_progress_path.each( function( index, ele ) {938 if ($(ele).hasClass('wp-smush-image-ul')) {939 //Remove Spinner940 $(ele).find('span.spinner').remove();941 //Check if images are pending942 var in_progress_ele = $(ele).find('li.wp-smush-image-ele');943 //If there are elements944 if (in_progress_ele.length > 0) {945 var optimised = in_progress_ele.filter('.optimised').length;946 var error = in_progress_ele.filter('.error').length;947 //if all the elements are optimised948 if (optimised == in_progress_ele.length) {949 $( ele ).addClass('complete');950 } else if (0 < optimised || 0 < error) {951 //If there are images that needs to be smushed, add the class partial952 $( ele ).addClass('partial');953 }954 }955 }else{956 //Remove spinner for the element957 $(ele).find('span.spinner').remove();958 }959 });960 }961 };962 /**963 * Update all stats sections based on the response.964 *965 * @param _res Ajax response data.966 */967 var update_stats = function (_res) {968 // If we have received the stats data, procced.969 if ('undefined' != typeof _res.data.stats) {970 var stats = _res.data.stats;971 // Update Progress on Circle.972 update_dashoffset(_res.data.stats);973 // Update main stats.974 $('.wp-smush-savings .wp-smush-stats-percent').html(stats.percent);975 $('.wp-smush-savings .wp-smush-stats-human').html(stats.human);976 var smush_percent = ( stats.smushed / stats.total ) * 100;977 smush_percent = precise_round( smush_percent, 1 );978 $('span.wp-smush-images-percent').html(smush_percent);979 $('.wp-smush-total-optimised').html(stats.total_images);980 if ($('.super-smush-attachments .smushed-count').length && 'undefined' != typeof stats.super_smushed) {981 $('.super-smush-attachments .smushed-count').html(stats.super_smushed);982 }983 var smush_conversion_savings = $('.smush-conversion-savings');984 //Update Conversion Savings985 if (smush_conversion_savings.length > 0 && 'undefined' != typeof ( stats.conversion_savings ) && stats.conversion_savings != '') {986 var conversion_savings = smush_conversion_savings.find('.wp-smush-stats');987 if (conversion_savings.length > 0) {988 conversion_savings.html(stats.conversion_savings);989 }990 }991 var smush_resize_savings = $('.smush-resize-savings');992 //Update Resize Savings993 if (smush_resize_savings.length > 0 && 'undefined' != typeof ( stats.resize_savings ) && stats.resize_savings != '') {994 // Get the resize savings in number.995 var savings_value = parseInt(stats.resize_savings);996 var resize_savings = smush_resize_savings.find('.wp-smush-stats');997 // Replace only if value is grater than 0.998 if (savings_value > 0 && resize_savings.length > 0) {999 resize_savings.html(stats.resize_savings);1000 }1001 }1002 // Updating pro savings stats.1003 if ('undefined' != typeof (stats.pro_savings)) {1004 // Make pro savings div visible if hidden.1005 $('#smush-avg-pro-savings').show();1006 // Pro stats section.1007 var smush_pro_savings = $('.smush-avg-pro-savings');1008 if (smush_pro_savings.length > 0) {1009 var pro_savings_percent = smush_pro_savings.find('.wp-smush-stats-percent');1010 var pro_savings_bytes = smush_pro_savings.find('.wp-smush-stats-human');1011 if (pro_savings_percent.length > 0 && 'undefined' != typeof (stats.pro_savings.percent) && stats.pro_savings.percent != '') {1012 pro_savings_percent.html(_res.data.stats.pro_savings.percent);1013 }1014 if (pro_savings_bytes.length > 0 && 'undefined' != typeof (stats.pro_savings.savings) && stats.pro_savings.savings != '') {1015 pro_savings_bytes.html(stats.pro_savings.savings);1016 }1017 }1018 }1019 }1020 }1021 /**1022 * Update the progress and show notice when smush completes1023 */1024 var directory_smush_finished = function( notice_type ) {1025 //If there are no images left1026 $('div.wp-smush-all-button-wrap span.spinner').remove();1027 $('button.wp-smush-pause').hide().attr('disabled', 'disabled');1028 //Hide Bulk Smush button if smush was stopped for error or finished1029 if ('' == notice_type) {1030 $('button.wp-smush-start').parent().hide();1031 } else {1032 $('button.wp-smush-start').show().removeAttr('disabled');1033 }1034 //Enable Choose directory button1035 $('button.wp-smush-browse').show().removeAttr('disabled', 'disabled');1036 //Clone Choose Directory Button and add at the top1037 add_dir_browser_button();1038 //Clone and add Smush button1039 add_smush_button();1040 if( '' == notice_type ) {1041 //Get the Total and Optimised image count1042 var image_ele = $('li.wp-smush-image-ele')1043 var total = image_ele.length;1044 var remaning = image_ele.filter(':not(.optimised)').length;1045 var smushed = total - remaning;1046 if (remaning > 0) {1047 //Append the count1048 $('span.wp-smush-dir-remaining').html(remaning);1049 $('span.wp-smush-dir-total').html(total);1050 $('span.wp-smush-dir-smushed').html(smushed);1051 //Show remaining image notice1052 $('.wp-smush-notice.wp-smush-dir-remaining').show();1053 //Show notice on top if required1054 add_smush_dir_notice();1055 } else {1056 // Hide images list.1057 $('ul.wp-smush-image-list').hide();1058 $('div.dir-smush-button-wrap.top').hide();1059 //Show All done notice1060 $('.wp-smush-notice.wp-smush-dir-all-done').show();1061 //Show notice on top if required1062 add_smush_dir_notice('all_done');1063 }1064 }else{1065 //Show Bulk Limit Notice1066 $('.wp-smush-notice.wp-smush-dir-limit').show();1067 //Show notice on top if required1068 add_smush_dir_notice('smush_limit');1069 }1070 //Update Directory progress and remove any loaders still in there1071 update_smush_progress();1072 }1073 /**1074 * Start Optimising all the images listed in last directory scan1075 *1076 */1077 var smush_all = function () {1078 var spinner = $('div.smush-page-wrap span.spinner:first').clone();1079 spinner.addClass('is-active');1080 var unprocessed_child = jQuery('ul.wp-smush-image-list li.wp-smush-image-ele:not(".optimised, .processed")');1081 //Update the Optimising status for the image1082 var first_child = unprocessed_child.first();1083 var parent = first_child.parents('li.wp-smush-image-ul');1084 //Check if the selected element is under expandable li1085 if (parent.length == 1) {1086 parent.addClass('active in-progress').removeClass('partial');1087 parent.find('.wp-smush-image-list-inner').addClass('show');1088 if (!parent.find('span.wp-smush-li-path span.spinner').length) {1089 parent.find('span.wp-smush-li-path').prepend(spinner.clone());1090 }1091 }1092 //Append and show spinner1093 first_child.addClass('in-progress processed');1094 if (!first_child.find('spam.spinner').length) {1095 first_child.prepend(spinner.clone());1096 }1097 //If all the elements are optimised, No need to send ajax request1098 if( first_child.length == 0 ) {1099 directory_smush_finished('');1100 return;1101 }1102 /** Ajax Request to optimise directory images */1103 var param = {1104 action: 'optimise',1105 image_id: first_child.attr('id'),1106 get_stats: unprocessed_child.length > 1 ? 0: 1,1107 nonce: $('#wp-smush-all').val()1108 };1109 //Send Ajax request1110 $.get(ajaxurl, param, function (res) {1111 //Check, if limit is exceeded for free version1112 if (typeof res.data !== "undefined" && res.data.error == 'dir_smush_limit_exceeded') {1113 //Show error, Bulk Smush limit exceeded1114 directory_smush_finished( 'wp-smush-dir-limit' );1115 return;1116 }1117 //append stats, remove loader, add loader to next image, loop1118 var data = 'undefined' != typeof ( res.data ) ? res.data : '';1119 //If image element is there1120 if ('undefined' != typeof(data.image)) {1121 //Mark Optimised1122 var ele = jQuery(document.getElementById(data.image.id));1123 //Remove the spinner1124 ele.find('span.spinner').remove();1125 ele.removeClass('in-progress');1126 if (res.success) {1127 ele.addClass('optimised');1128 //Show the Optimisation status1129 ele.find('span.wp-smush-image-ele-status').show();1130 //Update Directory progress1131 update_dir_progress(ele);1132 // Update dir savings stats.1133 if ('undefined' != typeof (res.data.total.percent) && 'undefined' != typeof (res.data.total.human) && 'undefined' != typeof (res.data.total.bytes)) {1134 // Directory stats section.1135 var smush_dir_savings = $('.smush-dir-savings');1136 if (smush_dir_savings.length > 0 && res.data.total.bytes > 0) {1137 // Make separator visible if hidden.1138 smush_dir_savings.find('.wp-smush-stats-sep').show();1139 var dir_savings_percent = smush_dir_savings.find('.wp-smush-stats-percent');1140 var dir_savings_human = smush_dir_savings.find('.wp-smush-stats-human');1141 if (dir_savings_percent.length > 0) {1142 dir_savings_percent.html(res.data.total.percent + '%');1143 }1144 if (dir_savings_human.length > 0) {1145 dir_savings_human.html(res.data.total.human);1146 }1147 }1148 }1149 } else {1150 //If there was an error optimising the image1151 ele.addClass('error');1152 //Update Directory progress1153 update_dir_progress(ele);1154 }1155 // Update stats.1156 update_stats(res);1157 }1158 //If user haven't paused the Smushing1159 if ( 1 == $('input[name="wp-smush-continue-ajax"]').val() ) {1160 //Loop1161 smush_all(false);1162 } else {1163 //Reset the Ajax flag1164 $('input.wp-smush-continue-ajax').val(1);1165 }1166 });1167 }1168 //Scroll the element to top of the page1169 var goToByScroll = function (selector) {1170 // Scroll1171 $('html,body').animate({1172 scrollTop: selector.offset().top1173 },1174 'slow');1175 };1176 var disable_buttons = function (self) {1177 self.attr('disabled', 'disabled');1178 $('.wp-smush-browse').attr('disabled', 'disabled');1179 };1180 var update_cummulative_stats = function (stats) {1181 //Update Directory Smush Stats1182 if ('undefined' != typeof ( stats.dir_smush )) {1183 var stats_human = $('div.smush-dir-savings span.wp-smush-stats span.wp-smush-stats-human');1184 var stats_percent = $('div.smush-dir-savings span.wp-smush-stats span.wp-smush-stats-percent');1185 // Do not replace if 0 savings.1186 if (stats.dir_smush.bytes > 0) {1187 // Show size and percentage separator.1188 $('div.smush-dir-savings span.wp-smush-stats span.wp-smush-stats-sep').show();1189 //Update Savings in bytes1190 if (stats_human.length > 0) {1191 stats_human.html(stats.dir_smush.human);1192 } else {1193 var span = '<span class="wp-smush-stats-human">' + stats.dir_smush.bytes + '</span>';1194 }1195 //Update Optimisation percentage1196 if (stats_percent.length > 0) {1197 stats_percent.html(stats.dir_smush.percent + '%');1198 } else {1199 var span = '<span class="wp-smush-stats-percent">' + stats.dir_smush.percent + '%' + '</span>';1200 }1201 }1202 }1203 //Update Combined stats1204 if ('undefined' != typeof ( stats.combined_stats ) && stats.combined_stats.length > 0) {1205 var c_stats = stats.combined_stats;1206 var smush_percent = ( c_stats.smushed / c_stats.total_count ) * 100;1207 smush_percent = precise_round( smush_percent, 1 );1208 //Update Circle Progress1209 if (c_stats.dash_offset) {1210 $('circle.wp-smush-svg-circle-progress').css({'stroke-dashoffset': c_stats.dash_offset});1211 }1212 //Smushed Percent1213 if (smush_percent) {1214 $('div.wp-smush-count-total span.wp-smush-images-percent').html(smush_percent);1215 }1216 //Update Total Attachment Count1217 if (c_stats.total_count) {1218 $('div.wp-smush-count-total div.wp-smush-smush-stats-wrapper span:last-child').html(c_stats.total_count);1219 }1220 //Update Savings and Percent1221 if (c_stats.savings) {1222 $('div.wp-smush-savings span.wp-smush-stats-human').html(c_stats.savings);1223 }1224 if (c_stats.percent) {1225 $('div.wp-smush-savings span.wp-smush-stats-percent').html(c_stats.percent);1226 }1227 }1228 };1229 /**1230 * Handle the Smush Stats link click1231 */1232 $('body').on('click', 'a.smush-stats-details', function (e) {1233 //If disabled1234 if ('disabled' == $(this).attr('disabled')) {1235 return false;1236 }1237 // prevent the default action1238 e.preventDefault();1239 //Replace the `+` with a `-`1240 var slide_symbol = $(this).find('.stats-toggle');1241 $(this).parents().eq(1).find('.smush-stats-wrapper').slideToggle();1242 slide_symbol.text(slide_symbol.text() == '+' ? '-' : '+');1243 });1244 /** Handle smush button click **/1245 $('body').on('click', '.wp-smush-send:not(.wp-smush-resmush)', function (e) {1246 // prevent the default action1247 e.preventDefault();1248 new WP_Smush.Smush($(this), false);1249 });1250 /** Handle NextGen Gallery smush button click **/1251 $('body').on('click', '.wp-smush-nextgen-send', function (e) {1252 // prevent the default action1253 e.preventDefault();1254 new WP_Smush.Smush($(this), false, 'nextgen');1255 });1256 /** Handle NextGen Gallery Bulk smush button click **/1257 $('body').on('click', '.wp-smush-nextgen-bulk', function (e) {1258 // prevent the default action1259 e.preventDefault();1260 //Check for ids, if there is none (Unsmushed or lossless), don't call smush function1261 if (typeof wp_smushit_data == 'undefined' ||1262 ( wp_smushit_data.unsmushed.length == 0 && wp_smushit_data.resmush.length == 0 )1263 ) {1264 return false;1265 }1266 jQuery('.wp-smush-button, .wp-smush-scan').attr('disabled', 'disabled');1267 $(".wp-smush-notice.wp-smush-remaining").hide();1268 new WP_Smush.Smush($(this), true, 'nextgen');1269 });1270 /** Restore: Media Library **/1271 $('body').on('click', '.wp-smush-action.wp-smush-restore', function (e) {1272 var current_button = $(this);1273 var smush_action = 'smush_restore_image';1274 process_smush_action(e, current_button, smush_action, 'restore');1275 });1276 /** Resmush: Media Library **/1277 $('body').on('click', '.wp-smush-action.wp-smush-resmush', function (e) {1278 var current_button = $(this);1279 var smush_action = 'smush_resmush_image';1280 process_smush_action(e, current_button, smush_action, 'smushing');1281 });1282 /** Restore: NextGen Gallery **/1283 $('body').on('click', '.wp-smush-action.wp-smush-nextgen-restore', function (e) {1284 var current_button = $(this);1285 var smush_action = 'smush_restore_nextgen_image';1286 process_smush_action(e, current_button, smush_action, 'restore');1287 });1288 /** Resmush: NextGen Gallery **/1289 $('body').on('click', '.wp-smush-action.wp-smush-nextgen-resmush', function (e) {1290 var current_button = $(this);1291 var smush_action = 'smush_resmush_nextgen_image';1292 process_smush_action(e, current_button, smush_action, 'smushing');1293 });1294 //Scan For resmushing images1295 $('body').on('click', '.wp-smush-scan', function (e) {1296 e.preventDefault();1297 //Run the Re-check1298 run_re_check($(this), false);1299 });1300 //Dismiss Welcome notice1301 $('#wp-smush-welcome-box .smush-dismiss-welcome').on('click', function (e) {1302 e.preventDefault();1303 var $el = $(this).parents().eq(1);1304 remove_element($el);1305 //Send a ajax request to save the dismissed notice option1306 var param = {1307 action: 'dismiss_welcome_notice'1308 };1309 $.post(ajaxurl, param);1310 });1311 //Remove Notice1312 $('body').on('click', '.wp-smush-notice .dev-icon-cross', function (e) {1313 e.preventDefault();1314 var $el = $(this).parent();1315 remove_element($el);1316 });1317 //On Click Update Settings. Check for change in settings1318 $('input#wp-smush-save-settings').on('click', function (e) {1319 e.preventDefault();1320 var setting_type = '';1321 var setting_input = $('input[name="setting-type"]');1322 //Check if setting type is set in the form1323 if (setting_input.length > 0) {1324 setting_type = setting_input.val();1325 }1326 //Show the spinner1327 var self = $(this);1328 self.parent().find('span.spinner').addClass('is-active');1329 //Save settings if in network admin1330 if ('' != setting_type && 'network' == setting_type) {1331 //Ajax param1332 var param = {1333 action: 'save_settings',1334 nonce: $('#wp_smush_options_nonce').val()1335 };1336 param = jQuery.param(param) + '&' + jQuery('form#wp-smush-settings-form').serialize();1337 //Send ajax, Update Settings, And Check For resmush1338 jQuery.post(ajaxurl, param).done(function () {1339 jQuery('form#wp-smush-settings-form').submit();1340 return true;1341 });1342 } else {1343 //Check for all the settings, and scan for resmush1344 var wrapper_div = self.parents().eq(1);1345 //Get all the main settings1346 var keep_exif = document.getElementById("wp-smush-keep_exif");1347 var super_smush = document.getElementById("wp-smush-lossy");1348 var smush_original = document.getElementById("wp-smush-original");1349 var resize_images = document.getElementById("wp-smush-resize");1350 var smush_pngjpg = document.getElementById("wp-smush-png_to_jpg");1351 var update_button_txt = true;1352 $('.wp-smush-hex-notice').hide();1353 //If Preserve Exif is Checked, and all other settings are off, just save the settings1354 if (keep_exif.checked && !super_smush.checked && !smush_original.checked && !resize_images.checked && !smush_pngjpg.checked) {1355 update_button_txt = false;1356 }1357 //Update text1358 self.attr('disabled', 'disabled').addClass('button-grey');1359 if (update_button_txt) {1360 self.val(wp_smush_msgs.checking)1361 }1362 //Check if type is set in data attributes1363 var scan_type = self.data('type');1364 scan_type = 'undefined' == typeof scan_type ? 'media' : scan_type;1365 //Ajax param1366 var param = {1367 action: 'scan_for_resmush',1368 wp_smush_options_nonce: jQuery('#wp_smush_options_nonce').val(),1369 scan_type: scan_type1370 };1371 param = jQuery.param(param) + '&' + jQuery('form#wp-smush-settings-form').serialize();1372 //Send ajax, Update Settings, And Check For resmush1373 jQuery.post(ajaxurl, param).done(function () {1374 jQuery('form#wp-smush-settings-form').submit();1375 return true;1376 });1377 }1378 });1379 //On Resmush click1380 $('body').on('click', '.wp-smush-skip-resmush', function (e) {1381 e.preventDefault();1382 var self = jQuery(this);1383 var container = self.parents().eq(1);1384 //Remove Parent div1385 var $el = self.parent();1386 remove_element($el);1387 //Remove Settings Notice1388 $('.wp-smush-notice.wp-smush-settings-updated').remove();1389 //Set button attribute to skip re-smush ids1390 container.find('.wp-smush-all').attr('data-smush', 'skip_resmush');1391 //Update Stats1392 if (wp_smushit_data.count_smushed == wp_smushit_data.count_total) {1393 //Show all done notice1394 $('.wp-smush-notice.wp-smush-all-done').show();1395 //Hide Smush button1396 $('.wp-smush-bulk-wrapper ').hide()1397 }1398 //Remove Re-Smush Notice1399 $('.wp-smush-resmush-notice').remove();1400 var type = $('.wp-smush-scan').data('type');1401 type = 'undefined' == typeof type ? 'media' : type;1402 var smushed_count = 'undefined' != typeof wp_smushit_data.count_smushed ? wp_smushit_data.count_smushed : 01403 var smush_percent = ( smushed_count / wp_smushit_data.count_total ) * 100;1404 smush_percent = precise_round( smush_percent, 1 );1405 $('.wp-smush-images-percent').html(smush_percent);1406 //Update the Progress Bar Width1407 // get the progress bar1408 var $progress_bar = jQuery('.bulk-smush-wrapper .wp-smush-progress-inner');1409 if ($progress_bar.length < 1) {1410 return;1411 }1412 // increase progress1413 $progress_bar.css('width', smush_percent + '%');1414 //Show the default bulk smush notice1415 $('.wp-smush-bulk-wrapper .wp-smush-notice').show();1416 var params = {1417 action: 'delete_resmush_list',1418 type: type1419 }1420 //Delete resmush list1421 $.post(ajaxurl, params);1422 });1423 //Enable Super Smush1424 $('.wp-smush-lossy-enable').on('click', function (e) {1425 e.preventDefault();1426 //Enable Super Smush1427 $('#wp-smush-lossy').prop('checked', true);1428 //Induce Setting button save click1429 $('#wp-smush-save-settings').click();1430 });1431 //Enable Resize1432 $('.wp-smush-resize-enable').on('click', function (e) {1433 e.preventDefault();1434 //Enable Super Smush1435 $('#wp-smush-resize').prop('checked', true);1436 //Induce Setting button save click1437 $('#wp-smush-save-settings').click();1438 });1439 //Trigger Bulk1440 $('body').on('click', '.wp-smush-trigger-bulk', function (e) {1441 e.preventDefault();1442 //Induce Setting button save click1443 $('button.wp-smush-all').click();1444 });1445 //Allow the checkboxes to be Keyboard Accessible1446 $('.wp-smush-setting-row .toggle-checkbox').focus(function () {1447 //If Space is pressed1448 $(this).keypress(function (e) {1449 if (e.keyCode == 32) {1450 e.preventDefault();1451 $(this).find('.toggle-checkbox').click();1452 }1453 });1454 });1455 //Re-Validate Resize Width And Height1456 $('.wp-smush-resize-input').blur(function () {1457 var self = $(this);1458 var wrapper_div = self.parents().eq(2);1459 //Initiate the check1460 validate_resize_settings(wrapper_div, false, false); // run the validation1461 });1462 //Handle Resize Checkbox toggle, to show/hide width, height settings1463 $('#wp-smush-resize').click(function () {1464 var self = $(this);1465 var settings_wrap = $('.wp-smush-resize-settings-wrap');1466 if (self.is(':checked')) {1467 settings_wrap.show();1468 } else {1469 settings_wrap.hide();1470 }1471 });1472 //Handle PNG to JPG Checkbox toggle, to show/hide Transparent image conversion settings1473 $('#wp-smush-png_to_jpg').click(function () {1474 var self = $(this);1475 var settings_wrap = $('.wp-smush-png_to_jpg-wrap');1476 if (self.is(':checked')) {1477 settings_wrap.show();1478 } else {1479 settings_wrap.hide();1480 }1481 });1482 //Handle, Change event in Enable Networkwide settings1483 $('#wp-smush-networkwide').on('click', function (e) {1484 if ($(this).is(':checked')) {1485 $('.network-settings-wrapper').show();1486 } else {1487 $('.network-settings-wrapper').hide();1488 }1489 });1490 //Handle Twitter Share1491 $('#wp-smush-twitter-share').on('click', function (e) {1492 e.preventDefault();1493 var width = 550,1494 height = 420,1495 left = ($(window).width() - width) / 2,1496 top = ($(window).height() - height) / 2,1497 url = this.href,1498 opts = 'status=1' +1499 ',width=' + width +1500 ',height=' + height +1501 ',top=' + top +1502 ',left=' + left;1503 window.open(url, 'twitter', opts);1504 return false;1505 });1506 //Handle Facebook Share1507 $('#wp-smush-facebook-share').on('click', function (e) {1508 e.preventDefault();1509 var width = 550,1510 height = 420,1511 left = ($(window).width() - width) / 2,1512 top = ($(window).height() - height) / 2,1513 url = this.href,1514 opts = 'status=1' +1515 ',width=' + width +1516 ',height=' + height +1517 ',top=' + top +1518 ',left=' + left;1519 window.open(url, 'facebook', opts);1520 return false;1521 });1522 //Adjust background image size if required1523 if ($('.wp-smush-pro-for-free').length) {1524 //On Page load1525 resize_width();1526 //Adjust background image1527 $(window).resize(function () {1528 resize_width();1529 });1530 }1531 //Handle Re-check button functionality1532 $("#wp-smush-revalidate-member").on('click', function (e) {1533 e.preventDefault();1534 //Ajax Params1535 var params = {1536 action: 'smush_show_warning',1537 };1538 var link = $(this);1539 var parent = link.parents().eq(1);1540 parent.addClass('loading-notice');1541 $.get(ajaxurl, params, function (r) {1542 //remove the warning1543 parent.removeClass('loading-notice').addClass("loaded-notice");1544 if (0 == r) {1545 parent.attr('data-message', wp_smush_msgs.membership_valid);1546 remove_element(parent, 1000);1547 } else {1548 parent.attr('data-message', wp_smush_msgs.membership_invalid);1549 setTimeout(function remove_loader() {1550 parent.removeClass('loaded-notice');1551 }, 1000)1552 }1553 });1554 });1555 //Initiate Re-check if the variable is set1556 if ('undefined' != typeof (wp_smush_run_re_check) && 1 == wp_smush_run_re_check && $('.wp-smush-scan').length > 0) {1557 //Run the Re-check1558 run_re_check($('.wp-smush-scan'), false);1559 }1560 //WP Smush all : Scan Images1561 $('div.row').on('click', 'button.wp-smush-browse', function (e) {1562 e.preventDefault();1563 //Hide all the notices1564 $('div.wp-smush-scan-result div.wp-smush-notice').hide();1565 //If disabled, do not process1566 if ($(this).attr('disabled')) {1567 return;1568 } else {1569 //Disable Buttons1570 $(this).attr('disabled', 'disabled');1571 $('button.wp-smush-resume').attr('disabled', 'disabled');1572 $('div.dir-smush-button-wrap span.spinner').addClass('is-active');1573 }1574 //Remove Notice1575 $('div.wp-smush-info').remove();1576 //Shows the directories available1577 $('.wp-smush-list-dialog').show();1578 //Display the loader1579 $('button.dir-smush-button-wrap span.spinner').addClass('is-active');1580 $(".wp-smush-list-dialog .content").fileTree({1581 script: getDirectoryList,1582 //folderEvent: 'dblclick',1583 multiFolder: false1584 //onlyFolders: true1585 });1586 });1587 //WP Smush all: Close button functionality1588 $('.wp-smush-list-dialog').on('click', '.close', function (e) {1589 e.preventDefault();1590 close_dialog();1591 });1592 //Image Directories: On Select button click1593 $('.wp-smush-select-dir').on('click', function (e) {1594 e.preventDefault();1595 //If disabled, do not process1596 if ($(this).attr('disabled')) {1597 return;1598 }1599 var button = $(this);1600 button.css({'opacity': '0.5'});1601 $('div.wp-smush-list-dialog div.box div.content').css({'opacity': '0.8'});1602 $('div.wp-smush-list-dialog div.box div.content a').unbind('click');1603 //Remove resume button1604 $('button.wp-smush-resume').remove();1605 //Disable Button1606 button.attr('disabled', 'disabled');1607 //Display the spinner1608 button.parent().find('.spinner').addClass('is-active');1609 //Get the Selected directory path1610 var path = $('.jqueryFileTree .selected a').attr('rel');1611 path = 'undefined' == typeof (path) ? '' : path;1612 //Absolute path1613 var abs_path = $('input[name="wp-smush-base-path"]').val();1614 //Fill in the input field1615 $('.wp-smush-dir-path').val(abs_path + path);1616 //Send a ajax request to get a list of all the image files1617 var param = {1618 action: 'image_list',1619 smush_path: $('.wp-smush-dir-path').val(),1620 image_list_nonce: $('input[name="image_list_nonce"]').val()1621 };1622 //Get the List of images1623 $.get(ajaxurl, param, function (res) {1624 if( !res.success && 'undefined' !== typeof ( res.data.message ) ) {1625 $('div.wp-smush-scan-result div.content').html(res.data.message );1626 }else {1627 $('div.wp-smush-scan-result div.content').html(res.data );1628 wp_smush_dir_image_ids = res.data.ids;1629 }1630 set_accordion();1631 close_dialog();1632 //Show Scan result1633 $('.wp-smush-scan-result').removeClass('hidden');1634 }).done(function (res) {1635 //If there was no image list, return1636 if( !res.success ) {1637 //Hide the smush button1638 $('div.wp-smush-all-button-wrap.bottom').hide();1639 return;1640 }1641 //Show the smush button1642 $('div.wp-smush-all-button-wrap.bottom').show();1643 //Remove disabled attribute for the button1644 $('button.wp-smush-start').removeAttr('disabled');1645 //Append a Directory browser button at the top1646 add_dir_browser_button();1647 //Clone and add Smush button1648 add_smush_button();1649 });1650 });1651 /**1652 * Handle the Smush Now button click1653 */1654 $('div.wp-smush-scan-result').on('click', 'button.wp-smush-start', function (e) {1655 e.preventDefault();1656 //Check if we have images to be optimised1657 if (!$('.wp-smush-image-list li').length) {1658 return;1659 }1660 //Disable this button1661 var button = $('.wp-smush-start');1662 var parent = button.parent();1663 //Hide all the notices1664 $('div.wp-smush-scan-result div.wp-smush-notice').hide();1665 //Set the button status to 0, to cancel next ajax request1666 $('input[name="wp-smush-continue-ajax"]').val(1);1667 //Hide Directory browser button1668 $('button.wp-smush-browse').hide();1669 //Hide Exclude directory button link1670 $('a.wp-smush-exclude-dir').hide();1671 /** All the Styling changes **/1672 button.attr('disabled', 'disabled');1673 parent.find('span.spinner').addClass('is-active');1674 parent.find('button.wp-smush-pause').show().removeClass('disabled').removeAttr('disabled');1675 //Disable Select Directory button1676 $('button.wp-smush-browse').attr('disabled', 'disabled');1677 //Initialize the optimisation1678 smush_all(true);1679 });1680 //Handle the Pause button click1681 $('div.wp-smush-scan-result').on('click', 'button.wp-smush-pause', function (e) {1682 e.preventDefault();1683 var pause_button = $('button.wp-smush-pause');1684 //Return if the link is disabled1685 if (pause_button.hasClass('disabled')) {1686 return false;1687 }1688 //Set the button status to 0, to cancel next ajax request1689 $('input[name="wp-smush-continue-ajax"]').val(0);1690 //Enable the smush button, disable Pause button1691 pause_button.attr('disabled', 'disabled');1692 //Enable the smush button, hide the spinner1693 $('button.wp-smush-start, button.wp-smush-browse').show().removeAttr('disabled');1694 $('div.wp-smush-all-button-wrap span.spinner').removeClass('is-active');1695 //Show directory exclude option1696 $('a.wp-smush-exclude-dir').show();1697 //Remove the loaders1698 update_smush_progress();1699 });1700 //Exclude Directory from list - Handle Click1701 $('div.wp-smush-scan-result').on('click', 'a.wp-smush-exclude-dir', function (e) {1702 e.preventDefault();1703 var self = $(this);1704 var parent = self.parent();1705 //Hide the link1706 self.hide();1707 //Append the loader1708 parent.find('span.wp-smush-li-path').after($('div.wp-smush-scan-result span.spinner:first').clone());1709 //Store the spinner in a element1710 var loader = parent.find('span.spinner:first');1711 loader.removeClass('is-active');1712 var path = self.data('path');1713 var param = {1714 action: 'smush_exclude_path',1715 path: path,1716 nonce: $('input[name="exclude-path-nonce"]').val()1717 };1718 //Send Ajax request to remove image for the given path from db1719 $.post(ajaxurl, param, function (res) {1720 loader.remove();1721 //Remove the whole li element on success1722 if (res.success) {1723 //Check if immediate sibling is ul, add a hr tag to it1724 if (parent.is("li.wp-smush-image-ul:first")) {1725 //Add a hr tag for the next element1726 parent.siblings('li.wp-smush-image-ul:first').prepend('<hr />');1727 }1728 parent.remove();1729 }1730 });1731 });1732 //Handle Click for Resume Last scan button1733 $('button.wp-smush-resume').on('click', function () {1734 var self = $(this);1735 //Disable buttons1736 disable_buttons(self);1737 //Show Spinner1738 $('div.dir-smush-button-wrap span.spinner').addClass('is-active');1739 var params = {1740 action: 'resume_scan',1741 };1742 //Send Ajax request to load a list of images1743 $.get(ajaxurl, params, function (r) {1744 //Hide the buttons1745 $('button.wp-smush-resume').remove();1746 //Remove the loader for choose directory button1747 $('div.dir-smush-button-wrap span.spinner').remove();1748 // Allow to select a new directory1749 $('button.wp-smush-browse').removeAttr('disabled');1750 //Append the results1751 if (!r.success) {1752 //Append the error message before the buttons1753 $('div.wp-smush-dir-desc').after(r.data.message);1754 } else {1755 //Append the image markup after the buttons1756 $('div.wp-smush-scan-result div.content').html(r.data);1757 $('div.wp-smush-scan-result').removeClass('hidden');1758 set_accordion();1759 }1760 }).done(function () {1761 //Add Choose dir browser button1762 add_dir_browser_button();1763 //Clone and add Smush button1764 add_smush_button();1765 });1766 });1767 if ($('div.smush-dir-savings').length > 0) {1768 //Update Directory Smush, as soon as the page loads1769 var stats_param = {1770 action: 'get_dir_smush_stats'1771 }1772 $.get(ajaxurl, stats_param, function (r) {1773 //Hide the spinner1774 $('div.smush-dir-savings span.spinner').hide();1775 //If there are no errors, and we have a message to display1776 if (!r.success && 'undefined' != typeof ( r.data.message )) {1777 $('div.wp-smush-scan-result div.content').prepend(r.data.message);1778 return;1779 }1780 //If there is no value in r1781 if ('undefined' == typeof ( r.data) || 'undefined' == typeof ( r.data.dir_smush )) {1782 //Append the text1783 $('div.smush-dir-savings span.wp-smush-stats').append(wp_smush_msgs.ajax_error);1784 $('div.smush-dir-savings span.wp-smush-stats span').hide();1785 return;1786 } else {1787 //Update the stats1788 update_cummulative_stats(r.data);1789 }1790 });1791 }1792 //Close Directory smush modal, if pressed esc1793 $(document).keyup(function (e) {1794 if (e.keyCode === 27) {1795 var modal = $('div.dev-overlay.wp-smush-list-dialog');1796 //If the Directory dialog is not visible1797 if (!modal.is(':visible')) {1798 return;1799 }1800 modal.find('div.close').click();1801 }1802 });1803});1804(function ($) {1805 var Smush = function (element, options) {1806 var elem = $(element);1807 var defaults = {1808 isSingle: false,1809 ajaxurl: '',1810 msgs: {},1811 msgClass: 'wp-smush-msg',1812 ids: []1813 };1814 };1815 $.fn.wpsmush = function (options) {1816 return this.each(function () {1817 var element = $(this);1818 // Return early if this element already has a plugin instance1819 if (element.data('wpsmush'))1820 return;1821 // pass options to plugin constructor and create a new instance1822 var wpsmush = new Smush(this, options);1823 // Store plugin object in this element's data1824 element.data('wpsmush', wpsmush);1825 });1826 };...

Full Screen

Full Screen

updates.js

Source:updates.js Github

copy

Full Screen

1/* global tb_remove, JSON */2window.wp = window.wp || {};3(function( $, wp ) {4 'use strict';5 wp.envato = {};6 /**7 * User nonce for ajax calls.8 *9 * @since 1.0.010 *11 * @var string12 */13 wp.envato.ajaxNonce = window._wpUpdatesSettings.ajax_nonce;14 /**15 * Localized strings.16 *17 * @since 1.0.018 *19 * @var object20 */21 wp.envato.l10n = window._wpUpdatesSettings.l10n;22 /**23 * Whether filesystem credentials need to be requested from the user.24 *25 * @since 1.0.026 *27 * @var bool28 */29 wp.envato.shouldRequestFilesystemCredentials = null;30 /**31 * Filesystem credentials to be packaged along with the request.32 *33 * @since 1.0.034 *35 * @var object36 */37 wp.envato.filesystemCredentials = {38 ftp: {39 host: null,40 username: null,41 password: null,42 connectionType: null43 },44 ssh: {45 publicKey: null,46 privateKey: null47 }48 };49 /**50 * Flag if we're waiting for an update to complete.51 *52 * @since 1.0.053 *54 * @var bool55 */56 wp.envato.updateLock = false;57 /**58 * * Flag if we've done an update successfully.59 *60 * @since 1.0.061 *62 * @var bool63 */64 wp.envato.updateDoneSuccessfully = false;65 /**66 * If the user tries to update a plugin while an update is67 * already happening, it can be placed in this queue to perform later.68 *69 * @since 1.0.070 *71 * @var array72 */73 wp.envato.updateQueue = [];74 /**75 * Store a jQuery reference to return focus to when exiting the request credentials modal.76 *77 * @since 1.0.078 *79 * @var jQuery object80 */81 wp.envato.$elToReturnFocusToFromCredentialsModal = null;82 /**83 * Decrement update counts throughout the various menus.84 *85 * @since 3.9.086 *87 * @param {string} upgradeType88 */89 wp.envato.decrementCount = function( upgradeType ) {90 var count,91 pluginCount,92 $adminBarUpdateCount = $( '#wp-admin-bar-updates .ab-label' ),93 $dashboardNavMenuUpdateCount = $( 'a[href="update-core.php"] .update-plugins' ),94 $pluginsMenuItem = $( '#menu-plugins' );95 count = $adminBarUpdateCount.text();96 count = parseInt( count, 10 ) - 1;97 if ( count < 0 || isNaN( count ) ) {98 return;99 }100 $( '#wp-admin-bar-updates .ab-item' ).removeAttr( 'title' );101 $adminBarUpdateCount.text( count );102 $dashboardNavMenuUpdateCount.each( function( index, elem ) {103 elem.className = elem.className.replace( /count-\d+/, 'count-' + count );104 } );105 $dashboardNavMenuUpdateCount.removeAttr( 'title' );106 $dashboardNavMenuUpdateCount.find( '.update-count' ).text( count );107 if ( 'plugin' === upgradeType ) {108 pluginCount = $pluginsMenuItem.find( '.plugin-count' ).eq( 0 ).text();109 pluginCount = parseInt( pluginCount, 10 ) - 1;110 if ( pluginCount < 0 || isNaN( pluginCount ) ) {111 return;112 }113 $pluginsMenuItem.find( '.plugin-count' ).text( pluginCount );114 $pluginsMenuItem.find( '.update-plugins' ).each( function( index, elem ) {115 elem.className = elem.className.replace( /count-\d+/, 'count-' + pluginCount );116 } );117 if ( pluginCount > 0 ) {118 $( '.subsubsub .upgrade .count' ).text( '(' + pluginCount + ')' );119 } else {120 $( '.subsubsub .upgrade' ).remove();121 }122 }123 };124 /**125 * Send an Ajax request to the server to update a plugin.126 *127 * @since 1.0.0128 *129 * @param {string} plugin130 * @param {string} slug131 */132 wp.envato.updatePlugin = function( plugin, slug ) {133 var data,134 $message = $( '.envato-card-' + slug ).find( '.update-now' ),135 name = $message.data( 'name' );136 $message.attr( 'aria-label', wp.envato.l10n.updatingLabel.replace( '%s', name ) );137 $message.addClass( 'updating-message' );138 if ( $message.html() !== wp.envato.l10n.updating ) {139 $message.data( 'originaltext', $message.html() );140 }141 $message.text( wp.envato.l10n.updating );142 wp.a11y.speak( wp.envato.l10n.updatingMsg );143 if ( wp.envato.updateLock ) {144 wp.envato.updateQueue.push( {145 type: 'update-plugin',146 data: {147 plugin: plugin,148 slug: slug149 }150 } );151 return;152 }153 wp.envato.updateLock = true;154 data = {155 _ajax_nonce: wp.envato.ajaxNonce,156 plugin: plugin,157 slug: slug,158 username: wp.envato.filesystemCredentials.ftp.username,159 password: wp.envato.filesystemCredentials.ftp.password,160 hostname: wp.envato.filesystemCredentials.ftp.hostname,161 connection_type: wp.envato.filesystemCredentials.ftp.connectionType,162 public_key: wp.envato.filesystemCredentials.ssh.publicKey,163 private_key: wp.envato.filesystemCredentials.ssh.privateKey164 };165 wp.ajax.post( 'update-plugin', data )166 .done( wp.envato.updateSuccess )167 .fail( wp.envato.updateError );168 };169 /**170 * Send an Ajax request to the server to update a theme.171 *172 * @since 1.0.0173 *174 * @param {string} plugin175 * @param {string} slug176 */177 wp.envato.updateTheme = function( slug ) {178 var data,179 $message = $( '.envato-card-' + slug ).find( '.update-now' ),180 name = $message.data( 'name' );181 $message.attr( 'aria-label', wp.envato.l10n.updatingLabel.replace( '%s', name ) );182 $message.addClass( 'updating-message' );183 if ( $message.html() !== wp.envato.l10n.updating ) {184 $message.data( 'originaltext', $message.html() );185 }186 $message.text( wp.envato.l10n.updating );187 wp.a11y.speak( wp.envato.l10n.updatingMsg );188 if ( wp.envato.updateLock ) {189 wp.envato.updateQueue.push( {190 type: 'upgrade-theme',191 data: {192 theme: slug193 }194 } );195 return;196 }197 wp.envato.updateLock = true;198 data = {199 _ajax_nonce: wp.envato.ajaxNonce,200 theme: slug,201 username: wp.envato.filesystemCredentials.ftp.username,202 password: wp.envato.filesystemCredentials.ftp.password,203 hostname: wp.envato.filesystemCredentials.ftp.hostname,204 connection_type: wp.envato.filesystemCredentials.ftp.connectionType,205 public_key: wp.envato.filesystemCredentials.ssh.publicKey,206 private_key: wp.envato.filesystemCredentials.ssh.privateKey207 };208 wp.ajax.post( 'upgrade-theme', data )209 .done( wp.envato.updateSuccess )210 .fail( wp.envato.updateError );211 };212 /**213 * On a successful plugin update, update the UI with the result.214 *215 * @since 1.0.0216 *217 * @param {object} response218 */219 wp.envato.updateSuccess = function( response ) {220 var $card, $updateColumn, $updateMessage, $updateVersion, name, version, versionText;221 $card = $( '.envato-card-' + response.slug );222 $updateColumn = $card.find( '.column-update' );223 $updateMessage = $card.find( '.update-now' );224 $updateVersion = $card.find( '.version' );225 name = $updateMessage.data( 'name' );226 version = $updateMessage.data( 'version' );227 versionText = $updateVersion.attr( 'aria-label' ).replace( '%s', version );228 $updateMessage.addClass( 'disabled' );229 $updateMessage.attr( 'aria-label', wp.envato.l10n.updatedLabel.replace( '%s', name ) );230 $updateVersion.text( versionText );231 $updateMessage.removeClass( 'updating-message' ).addClass( 'updated-message' );232 $updateMessage.text( wp.envato.l10n.updated );233 wp.a11y.speak( wp.envato.l10n.updatedMsg );234 $updateColumn.addClass( 'update-complete' ).delay( 1000 ).fadeOut();235 wp.envato.decrementCount( 'plugin' );236 wp.envato.updateDoneSuccessfully = true;237 /*238 * The lock can be released since the update was successful,239 * and any other updates can commence.240 */241 wp.envato.updateLock = false;242 $( document ).trigger( 'envato-update-success', response );243 wp.envato.queueChecker();244 };245 /**246 * On a plugin update error, update the UI appropriately.247 *248 * @since 1.0.0249 *250 * @param {object} response251 */252 wp.envato.updateError = function( response ) {253 var $message, name;254 wp.envato.updateDoneSuccessfully = false;255 if ( response.errorCode && 'unable_to_connect_to_filesystem' === response.errorCode && wp.envato.shouldRequestFilesystemCredentials ) {256 wp.envato.credentialError( response, 'update-plugin' );257 return;258 }259 $message = $( '.envato-card-' + response.slug ).find( '.update-now' );260 name = $message.data( 'name' );261 $message.attr( 'aria-label', wp.envato.l10n.updateFailedLabel.replace( '%s', name ) );262 $message.removeClass( 'updating-message' );263 $message.html( wp.envato.l10n.updateFailed.replace( '%s', response.error ) );264 wp.a11y.speak( wp.envato.l10n.updateFailed );265 /*266 * The lock can be released since this failure was267 * after the credentials form.268 */269 wp.envato.updateLock = false;270 $( document ).trigger( 'envato-update-error', response );271 wp.envato.queueChecker();272 };273 /**274 * Show an error message in the request for credentials form.275 *276 * @param {string} message277 * @since 1.0.0278 */279 wp.envato.showErrorInCredentialsForm = function( message ) {280 var $modal = $( '.notification-dialog' );281 // Remove any existing error.282 $modal.find( '.error' ).remove();283 $modal.find( 'h3' ).after( '<div class="error">' + message + '</div>' );284 };285 /**286 * Events that need to happen when there is a credential error287 *288 * @since 1.0.0289 */290 wp.envato.credentialError = function( response, type ) {291 wp.envato.updateQueue.push( {292 'type': type,293 'data': {294 // Not cool that we're depending on response for this data.295 // This would feel more whole in a view all tied together.296 plugin: response.plugin,297 slug: response.slug298 }299 } );300 wp.envato.showErrorInCredentialsForm( response.error );301 wp.envato.requestFilesystemCredentials();302 };303 /**304 * If an update job has been placed in the queue, queueChecker pulls it out and runs it.305 *306 * @since 1.0.0307 */308 wp.envato.queueChecker = function() {309 var job;310 if ( wp.envato.updateLock || wp.envato.updateQueue.length <= 0 ) {311 return;312 }313 job = wp.envato.updateQueue.shift();314 wp.envato.updatePlugin( job.data.plugin, job.data.slug );315 };316 /**317 * Request the users filesystem credentials if we don't have them already.318 *319 * @since 1.0.0320 */321 wp.envato.requestFilesystemCredentials = function( event ) {322 if ( false === wp.envato.updateDoneSuccessfully ) {323 wp.envato.$elToReturnFocusToFromCredentialsModal = $( event.target );324 wp.envato.updateLock = true;325 wp.envato.requestForCredentialsModalOpen();326 }327 };328 /**329 * Keydown handler for the request for credentials modal.330 *331 * Close the modal when the escape key is pressed.332 * Constrain keyboard navigation to inside the modal.333 *334 * @since 1.0.0335 */336 wp.envato.keydown = function( event ) {337 if ( 27 === event.keyCode ) {338 wp.envato.requestForCredentialsModalCancel();339 } else if ( 9 === event.keyCode ) {340 // #upgrade button must always be the last focusable element in the dialog.341 if ( 'upgrade' === event.target.id && ! event.shiftKey ) {342 $( '#hostname' ).focus();343 event.preventDefault();344 } else if ( 'hostname' === event.target.id && event.shiftKey ) {345 $( '#upgrade' ).focus();346 event.preventDefault();347 }348 }349 };350 /**351 * Open the request for credentials modal.352 *353 * @since 1.0.0354 */355 wp.envato.requestForCredentialsModalOpen = function() {356 var $modal = $( '#request-filesystem-credentials-dialog' );357 $( 'body' ).addClass( 'modal-open' );358 $modal.show();359 $modal.find( 'input:enabled:first' ).focus();360 $modal.keydown( wp.envato.keydown );361 };362 /**363 * Close the request for credentials modal.364 *365 * @since 1.0.0366 */367 wp.envato.requestForCredentialsModalClose = function() {368 $( '#request-filesystem-credentials-dialog' ).hide();369 $( 'body' ).removeClass( 'modal-open' );370 wp.envato.$elToReturnFocusToFromCredentialsModal.focus();371 };372 /**373 * The steps that need to happen when the modal is canceled out374 *375 * @since 1.0.0376 */377 wp.envato.requestForCredentialsModalCancel = function() {378 var slug, $message;379 // No updateLock and no updateQueue means we already have cleared things up380 if ( false === wp.envato.updateLock && 0 === wp.envato.updateQueue.length ) {381 return;382 }383 slug = wp.envato.updateQueue[0].data.slug,384 // Remove the lock, and clear the queue385 wp.envato.updateLock = false;386 wp.envato.updateQueue = [];387 wp.envato.requestForCredentialsModalClose();388 $message = $( '.envato-card-' + slug ).find( '.update-now' );389 $message.removeClass( 'updating-message' );390 $message.html( $message.data( 'originaltext' ) );391 wp.a11y.speak( wp.envato.l10n.updateCancel );392 };393 /**394 * Potentially add an AYS to a user attempting to leave the page395 *396 * If an update is on-going and a user attempts to leave the page,397 * open an "Are you sure?" alert.398 *399 * @since 1.0.0400 */401 wp.envato.beforeunload = function() {402 if ( wp.envato.updateLock ) {403 return wp.envato.l10n.beforeunload;404 }405 };406 $( document ).ready( function() {407 /*408 * Check whether a user needs to submit filesystem credentials based on whether409 * the form was output on the page server-side.410 *411 * @see {wp_print_request_filesystem_credentials_modal() in PHP}412 */413 wp.envato.shouldRequestFilesystemCredentials = ( $( '#request-filesystem-credentials-dialog' ).length <= 0 ) ? false : true;414 // File system credentials form submit noop-er / handler.415 $( '#request-filesystem-credentials-dialog form' ).on( 'submit', function() {416 // Persist the credentials input by the user for the duration of the page load.417 wp.envato.filesystemCredentials.ftp.hostname = $( '#hostname' ).val();418 wp.envato.filesystemCredentials.ftp.username = $( '#username' ).val();419 wp.envato.filesystemCredentials.ftp.password = $( '#password' ).val();420 wp.envato.filesystemCredentials.ftp.connectionType = $( 'input[name="connection_type"]:checked' ).val();421 wp.envato.filesystemCredentials.ssh.publicKey = $( '#public_key' ).val();422 wp.envato.filesystemCredentials.ssh.privateKey = $( '#private_key' ).val();423 wp.envato.requestForCredentialsModalClose();424 // Unlock and invoke the queue.425 wp.envato.updateLock = false;426 wp.envato.queueChecker();427 return false;428 });429 // Close the request credentials modal when430 $( '#request-filesystem-credentials-dialog [data-js-action="close"], .notification-dialog-background' ).on( 'click', function() {431 wp.envato.requestForCredentialsModalCancel();432 });433 // Hide SSH fields when not selected434 $( '#request-filesystem-credentials-dialog input[name="connection_type"]' ).on( 'change', function() {435 $( this ).parents( 'form' ).find( '#private_key, #public_key' ).parents( 'label' ).toggle( ( 'ssh' === $( this ).val() ) );436 }).change();437 // Click handler for plugin updates.438 $( '.envato-card.plugin' ).on( 'click', '.update-now', function( e ) {439 var $button = $( e.target );440 e.preventDefault();441 if ( wp.envato.shouldRequestFilesystemCredentials && ! wp.envato.updateLock ) {442 wp.envato.requestFilesystemCredentials( e );443 }444 wp.envato.updatePlugin( $button.data( 'plugin' ), $button.data( 'slug' ) );445 } );446 // Click handler for theme updates.447 $( '.envato-card.theme' ).on( 'click', '.update-now', function( e ) {448 var $button = $( e.target );449 e.preventDefault();450 if ( wp.envato.shouldRequestFilesystemCredentials && ! wp.envato.updateLock ) {451 wp.envato.requestFilesystemCredentials( e );452 }453 wp.envato.updateTheme( $button.data( 'slug' ) );454 } );455 // @todo456 $( '#plugin_update_from_iframe' ).on( 'click', function( e ) {457 var target, data;458 target = window.parent === window ? null : window.parent,459 $.support.postMessage = !! window.postMessage;460 if ( false === $.support.postMessage || null === target || window.parent.location.pathname.indexOf( 'update-core.php' ) !== -1 ) {461 return;462 }463 e.preventDefault();464 data = {465 'action': 'updatePlugin',466 'slug': $( this ).data( 'slug' )467 };468 target.postMessage( JSON.stringify( data ), window.location.origin );469 });470 } );471 $( window ).on( 'message', function( e ) {472 var event = e.originalEvent,473 message,474 loc = document.location,475 expectedOrigin = loc.protocol + '//' + loc.hostname;476 if ( event.origin !== expectedOrigin ) {477 return;478 }479 message = $.parseJSON( event.data );480 if ( 'undefined' === typeof message.action ) {481 return;482 }483 switch ( message.action ){484 case 'decrementUpdateCount' :485 wp.envato.decrementCount( message.upgradeType );486 break;487 case 'updatePlugin' :488 tb_remove();489 $( '.envato-card-' + message.slug ).find( 'h4 a' ).focus();490 $( '.envato-card-' + message.slug ).find( '[data-slug="' + message.slug + '"]' ).trigger( 'click' );491 break;492 }493 } );494 $( window ).on( 'beforeunload', wp.envato.beforeunload );...

Full Screen

Full Screen

custommenu.js

Source:custommenu.js Github

copy

Full Screen

1function wpShowMenuPopup(objMenu, event, popupId)2{3 if (typeof wpCustommenuTimerHide[popupId] != 'undefined') clearTimeout(wpCustommenuTimerHide[popupId]);4 objMenu = $(objMenu.id); var popup = $(popupId); if (!popup) return;5 if (!!wpActiveMenu) {6 wpHideMenuPopup(objMenu, event, wpActiveMenu.popupId, wpActiveMenu.menuId);7 }8 wpActiveMenu = {menuId: objMenu.id, popupId: popupId};9 if (!objMenu.hasClassName('active')) {10 wpCustommenuTimerShow[popupId] = setTimeout(function() {11 objMenu.addClassName('active');12 var popupWidth = CUSTOMMENU_POPUP_WIDTH;13 if (!popupWidth) popupWidth = popup.getWidth();14 var pos = wpPopupPos(objMenu, popupWidth);15 popup.style.top = pos.top + 'px';16 popup.style.left = pos.left + 'px';17 wpSetPopupZIndex(popup);18 if (CUSTOMMENU_POPUP_WIDTH)19 popup.style.width = CUSTOMMENU_POPUP_WIDTH + 'px';20 // --- Static Block width ---21 var block2 = $(popupId).select('div.block2');22 if (typeof block2[0] != 'undefined') {23 var wStart = block2[0].id.indexOf('_w');24 if (wStart > -1) {25 var w = block2[0].id.substr(wStart+2);26 } else {27 var w = 0;28 $(popupId).select('div.block1 div.column').each(function(item) {29 w += $(item).getWidth();30 });31 }32 if (w) block2[0].style.width = w + 'px';33 }34 // --- change href ---35 var wpMenuAnchor = $(objMenu.select('a')[0]);36 wpChangeTopMenuHref(wpMenuAnchor);37 // --- show popup ---38 popup.style.display = 'block';39 //jQuery('#' + popupId).stop(true, true).fadeIn();40 }, CUSTOMMENU_POPUP_DELAY_BEFORE_DISPLAYING);41 }42}43function wpHideMenuPopup(element, event, popupId, menuId)44{45 if (typeof wpCustommenuTimerShow[popupId] != 'undefined') clearTimeout(wpCustommenuTimerShow[popupId]);46 var element = $(element); var objMenu = $(menuId) ;var popup = $(popupId); if (!popup) return;47 var wpCurrentMouseTarget = getCurrentMouseTarget(event);48 if (!!wpCurrentMouseTarget) {49 if (!wpIsChildOf(element, wpCurrentMouseTarget) && element != wpCurrentMouseTarget) {50 if (!wpIsChildOf(popup, wpCurrentMouseTarget) && popup != wpCurrentMouseTarget) {51 if (objMenu.hasClassName('active')) {52 wpCustommenuTimerHide[popupId] = setTimeout(function() {53 objMenu.removeClassName('active');54 // --- change href ---55 var wpMenuAnchor = $(objMenu.select('a')[0]);56 wpChangeTopMenuHref(wpMenuAnchor);57 // --- hide popup ---58 popup.style.display = 'none';59 //jQuery('#' + popupId).stop(true, true).fadeOut();60 }, CUSTOMMENU_POPUP_DELAY_BEFORE_HIDING);61 }62 }63 }64 }65}66function wpPopupOver(element, event, popupId, menuId)67{68 if (typeof wpCustommenuTimerHide[popupId] != 'undefined') clearTimeout(wpCustommenuTimerHide[popupId]);69}70function wpPopupPos(objMenu, w)71{72 var pos = objMenu.cumulativeOffset();73 var wraper = $('custommenu');74 var posWraper = wraper.cumulativeOffset();75 var xTop = pos.top - posWraper.top76 if (CUSTOMMENU_POPUP_TOP_OFFSET) {77 xTop += CUSTOMMENU_POPUP_TOP_OFFSET;78 } else {79 xTop += objMenu.getHeight();80 }81 var res = {'top': xTop};82 if (CUSTOMMENU_RTL_MODE) {83 var xLeft = pos.left - posWraper.left - w + objMenu.getWidth();84 if (xLeft < 0) xLeft = 0;85 res.left = xLeft;86 } else {87 var wWraper = wraper.getWidth();88 var xLeft = pos.left - posWraper.left;89 if ((xLeft + w) > wWraper) xLeft = wWraper - w;90 if (xLeft < 0) xLeft = 0;91 res.left = xLeft;92 }93 return res;94}95function wpChangeTopMenuHref(wpMenuAnchor)96{97 var wpValue = wpMenuAnchor.href;98 wpMenuAnchor.href = wpMenuAnchor.rel;99 wpMenuAnchor.rel = wpValue;100}101function wpIsChildOf(parent, child)102{103 if (child != null) {104 while (child.parentNode) {105 if ((child = child.parentNode) == parent) {106 return true;107 }108 }109 }110 return false;111}112function wpSetPopupZIndex(popup)113{114 $$('.wp-custom-menu-popup').each(function(item){115 item.style.zIndex = '9999';116 });117 popup.style.zIndex = '10000';118}119function getCurrentMouseTarget(xEvent)120{121 var wpCurrentMouseTarget = null;122 if (xEvent.toElement) {123 wpCurrentMouseTarget = xEvent.toElement;124 } else if (xEvent.relatedTarget) {125 wpCurrentMouseTarget = xEvent.relatedTarget;126 }127 return wpCurrentMouseTarget;128}129/*130Event.observe(document, 'click', function (event) {131 if (!!wpActiveMenu) {132 var element = event.element();133 if (!!element) {134 var menuObj = $(wpActiveMenu.menuId);135 var popupObj = $(wpActiveMenu.popupId);136 if (!wpIsChildOf(menuObj, element) && menuObj != element) {137 if (!wpIsChildOf(popupObj, element) && popupObj != element) {138 wpHideMenuPopup(element, event, wpActiveMenu.popupId, wpActiveMenu.menuId);139 wpActiveMenu = null;140 }141 }142 }143 }144});...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { wp } = require('@cypress/webpack-preprocessor');2const webpackOptions = require('../webpack.config');3module.exports = (on, config) => {4 const options = {5 watchOptions: {},6 };7 on('file:preprocessor', wp(options));8};9const path = require('path');10const { merge } = require('webpack-merge');11const common = require('../webpack.common.js');12module.exports = merge(common, {13 resolve: {14 alias: {15 '@': path.resolve(__dirname, 'src'),16 },17 },18 devServer: {19 },20 module: {21 {22 loaders: [require.resolve('@storybook/source-loader')],23 },24 },25});26const HtmlWebpackPlugin = require('html-webpack-plugin');27const path = require('path');28const { CleanWebpackPlugin } = require('clean-webpack-plugin');29module.exports = {30 entry: {31 },32 new CleanWebpackPlugin({33 }),34 new HtmlWebpackPlugin({35 }),36 output: {37 path: path.resolve(__dirname, 'dist'),38 },39 module: {40 {41 test: /\.(js|jsx)$/,42 },43 {44 },45 },46 resolve: {47 },48};49{50 "scripts": {51 },52 "devDependencies": {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from 'storybook-root/.storybook/manager';2import { action } from '@storybook/addon-actions';3storiesOf('Button', module)4 .add('with text', () => ({5 components: { Button },6 methods: { action: action('clicked') },7 }))8 .add('with some emoji', () => ({9 components: { Button },10 methods: { action: action('clicked') },11 }));12import { configure } from '@storybook/vue';13import { setOptions } from '@storybook/addon-options';14setOptions({15});16function loadStories() {17 require('./stories');18}19configure(loadStories, module);20{21 "scripts": {22 },23 "dependencies": {24 },25 "devDependencies": {26 }27}28{29 {30 "targets": {31 }32 }33}34const path = require('path');35module.exports = {36 resolve: {

Full Screen

Using AI Code Generation

copy

Full Screen

1import { storiesOf } from 'storybook-root';2storiesOf('Button', module)3 .add('with text', () => {4 return {5 };6 });7import { configure } from '@storybook/angular';8import { setAddon } from '@storybook/angular';9import { withKnobs } from '@storybook/addon-knobs/angular';10import { withNotes } from '@storybook/addon-notes';11import { withA11y } from '@storybook/addon-a11y';12setAddon({13});14configure(require.context('../src', true, /\.stories\.ts$/), module);15const path = require('path');16module.exports = async ({ config }) => {17 config.module.rules.push({18 loader: require.resolve('awesome-typescript-loader'),19 options: {20 configFileName: path.resolve(__dirname, '../tsconfig.json'),21 },22 });23 config.resolve.extensions.push('.ts', '.js');24 return config;25};26{27 "compilerOptions": {28 },29}30{31 "compilerOptions": {32 }33}34{35 "scripts": {

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run storybook-root automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful