PluginProbe
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance / 4.7.0
WP-Optimize – Cache, Compress images, Minify & Clean database to boost page speed & performance v4.7.0
4.7.0 4.6.1 4.6.0 4.5.5 4.5.4 4.5.3 4.5.2 3.2.20 3.2.21 3.2.22 3.2.3 3.2.5 3.2.6 3.2.7 3.2.9 3.3.0 3.3.1 3.3.2 3.4.0 3.4.1 3.4.2 3.5.0 3.6.0 3.7.0 3.7.1 All 111 releases
← All changes | js/wposmush.js +541 -339 3.3.0 → 4.7.0 View file →
@@ -5,17 +5,20 @@
5 5 var WP_Optimize_Smush = function() {
6 6
7 7 var $ = jQuery;
8 8
9 + var heartbeat = WP_Optimize_Heartbeat();
10 + var heartbeat_agents = [];
11 +
12 + var last_ui_update_agent_uid = null;
13 +
14 + var block_ui = wp_optimize.block_ui;
15 +
9 16 /**
10 17 * Variables for smushing.
11 18 */
12 - var smush_nav_tab = $('#wp-optimize-images-nav-tab-smush'),
13 - smush_images_grid = $('#wpo_smush_images_grid'),
19 + var smush_images_grid = $('#wpo_smush_images_grid'),
14 20 smush_images_optimization_message = $('#smush_info_images'),
15 - smush_images_pending_tasks_container = $('#wpo_smush_images_pending_tasks_container'),
16 - smush_images_pending_tasks_btn = $('#wpo_smush_images_pending_tasks_button'),
17 - smush_images_save_options_btn = $('.wpo-fieldgroup #wpo_smush_images_save_options_button'),
18 21 smush_images_refresh_btn = $('#wpo_smush_images_refresh'),
19 22 smush_images_select_all_btn = $('#wpo_smush_images_select_all'),
20 23 smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
21 24 smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
@@ -20,11 +23,8 @@
20 23 smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
21 24 smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
22 25 smush_selected_images_btn = $('#wpo_smush_images_btn'),
23 26 smush_mark_as_compressed_btn = $('#wpo_smush_mark_as_compressed'),
24 - smush_single_image_btn = $('.wpo_smush_single_image .button'),
25 - smush_single_restore_btn = $('.wpo_restore_single_image .button'),
26 - convert_to_webp_btn = $('.wpo_smush.column-wpo_smush .convert-to-webp');
27 27 smush_mark_all_as_uncompressed_btn = $('#wpo_smush_mark_all_as_uncompressed_btn'),
28 28 restore_all_compressed_images_btn = $('#wpo_smush_restore_all_compressed_images_btn'),
29 29 smush_view_logs_btn = $('.wpo_smush_get_logs'),
30 30 smush_delete_backup_images_btn = $('#wpo_smush_delete_backup_btn'),
@@ -36,8 +36,9 @@
36 36 smush_timer_locked = false,
37 37 smush_timer_handle = 0,
38 38 smush_image_list = [],
39 39 smush_completed = false,
40 + smush_from_media_library = false,
40 41 smush_mark_all_as_uncompressed = false,
41 42 smush_affected_images = {},
42 43 pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
43 44 uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
@@ -42,11 +43,106 @@
42 43 pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
43 44 uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
44 45
45 46 /**
47 + * These options used for block UI with custom content.
48 + */
49 + var block_ui_custom_options = {
50 + baseZ: 160001,
51 + css: {
52 + top: '50%',
53 + transform: 'translate(0, -50%)',
54 + width: '400px',
55 + padding: '20px',
56 + cursor: 'pointer'
57 + }
58 + }
59 +
60 + $('#doaction, #doaction2').on('click', function(e) {
61 + e.stopImmediatePropagation();
62 + var action = $(this).prev('select').val();
63 + if ('wp_optimize_bulk_compression' !== action && 'wp_optimize_bulk_restore' !== action ) return;
64 +
65 + var $selected_images = get_media_library_selected_images();
66 + if (0 === $selected_images.length) return;
67 + e.preventDefault();
68 + if ('wp_optimize_bulk_compression' === action) bulk_compression($selected_images);
69 + if ('wp_optimize_bulk_restore' === action) bulk_restore($selected_images);
70 + });
71 +
72 + /**
73 + * Handles bulk compression action from media library
74 + *
75 + * @param {Object} $selected_images
76 + */
77 + function bulk_compression($selected_images) {
78 + block_ui(wposmush.server_check);
79 +
80 + data = { 'server': wposmush.smush_settings.compression_server, skip_notice: true };
81 + smush_manager_send_command('check_server_status', data, function(resp) {
82 + if (resp.online) {
83 + $selected_images.each(function(index, element) {
84 + smush_image_list.push({
85 + 'attachment_id': parseInt(element.value),
86 + 'blog_id': wposmush.blog_id
87 + });
88 + });
89 +
90 + data = {
91 + optimization_id: 'smush',
92 + selected_images: smush_image_list,
93 + smush_options: {
94 + 'compression_server': wposmush.smush_settings.compression_server,
95 + 'image_quality': wposmush.smush_settings.image_quality,
96 + 'lossy_compression': wposmush.smush_settings.lossy_compression,
97 + 'back_up_original': wposmush.smush_settings.back_up_original,
98 + 'preserve_exif': wposmush.smush_settings.preserve_exif
99 + }
100 + }
101 + smush_from_media_library = true;
102 + smush_completed = false;
103 + if (smush_timer_locked) return;
104 + block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
105 + clear_smush_stats();
106 +
107 + smush_timer_handle = window.setInterval(smush_timer, 1000);
108 + smush_manager_send_command('process_bulk_smush', data);
109 + } else {
110 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
111 + block_ui(error_message);
112 + }
113 + });
114 + }
115 +
116 + /**
117 + * Handles bulk restore action from media library
118 + *
119 + * @param {Object} $selected_images
120 + */
121 + function bulk_restore($selected_images) {
122 + smush_from_media_library = true;
123 +
124 + var processed_elements = [];
125 + var progress = function(element_id) {
126 + return function(callback) {
127 + processed_elements.push(element_id);
128 +
129 + if (1 < processed_elements.length && processed_elements.length === $selected_images.length) {
130 + callback(wposmush.images_restored_successfully);
131 + } else {
132 + callback();
133 + }
134 + }
135 + }
136 +
137 + $selected_images.each(function(index, element) {
138 + restore_selected_image(wposmush.blog_id, parseInt(element.value), progress(parseInt(element.value)));
139 + });
140 + }
141 +
142 + /**
46 143 * Handle Image Selection
47 144 */
48 -
49 145 smush_images_grid.on('click', '.thumbnail', function (e) {
50 146 $(this).closest('input[type="checkbox"]').prop('checked', true);
51 147 });
52 148
@@ -67,11 +163,13 @@
67 163
68 164 // Resets server rewrite capability
69 165 reset_webp_serving_method_btn.on('click', function(e) {
70 166 e.preventDefault();
71 - smush_manager_send_command('reset_webp_serving_method', {}, function(resp) {
167 + smush_manager_send_command('reset_webp_serving_method', { skip_notice: true }, function(resp) {
72 168 if (!resp.success) {
73 - console.log('[Failed] WebP server capability detection');
169 + $('#enable_webp_conversion').prop("checked", false);
170 + $('#smush-information-modal .smush-information').text(resp.error_message);
171 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
74 172 } else {
75 173 $('#wpo_reset_webp_serving_method_done').show().delay(3000).fadeOut();
76 174 }
77 175 });
@@ -77,13 +175,21 @@
77 175 });
78 176 });
79 177
80 178 /**
179 + * Boolean flag to track whether uncompressed images have already been loaded,
180 + * preventing multiple unnecessary loads
181 + */
182 + var uncompressed_images_already_loaded = false;
183 +
184 + /**
81 185 * Checks if smush is active and loads images if yes - image tabs change.
82 186 */
83 187 $('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab').on('click', function() {
188 + if (uncompressed_images_already_loaded) return;
189 +
84 190 if ($(this).is('#wp-optimize-nav-tab-wpo_images-smush')) {
85 - get_info_from_smush_manager();
191 + get_info_from_smush_manager(false);
86 192 }
87 193 });
88 194
89 195 /**
@@ -89,11 +195,13 @@
89 195 /**
90 196 * Checks if smush is active and loads images if yes - main menu change.
91 197 */
92 198 $('#wp-optimize-wrap').on('page-change', function(e, params) {
199 + if (uncompressed_images_already_loaded) return;
200 +
93 201 if ('wpo_images' == params.page) {
94 202 if ($('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab-active').is('#wp-optimize-nav-tab-wpo_images-smush')) {
95 - get_info_from_smush_manager();
203 + get_info_from_smush_manager(false);
96 204 }
97 205 }
98 206 });
99 207
@@ -151,28 +259,21 @@
151 259 */
152 260 smush_selected_images_btn.off().on('click', function() {
153 261
154 262 if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
155 - $('#smush-information-modal .smush-information').text(wposmush.please_select_images)
156 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
263 + block_ui(wposmush.please_select_images);
157 264 return;
158 265 }
159 266
160 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
161 - update_view_modal_message($('#smush-information-modal'));
267 + block_ui(wposmush.server_check);
162 268
163 - data = { 'server': $("input[name='compression_server']:checked").val() };
269 + data = { 'server': $("input[name='compression_server']:checked").val(), skip_notice: true };
164 270 smush_manager_send_command('check_server_status', data, function(resp) {
165 271 if (resp.online) {
166 272 bulk_smush_selected_images();
167 273 } else {
168 - if (resp.error) {
169 - error_message = resp.error + '<br>' + wposmush.server_error
170 - $('#smush-information-modal .smush-information').html(error_message);
171 - } else {
172 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
173 - }
174 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
274 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
275 + block_ui(error_message);
175 276 }
176 277 });
177 278 });
178 279
@@ -179,13 +280,8 @@
179 280 /**
180 281 * Mark as compressed
181 282 */
182 283 smush_mark_as_compressed_btn.off().on('click', function() {
183 - if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
184 - $('#smush-information-modal .smush-information').text(wposmush.please_select_compressed_images)
185 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
186 - return;
187 - }
188 284
189 285 var selected_images = [],
190 286 image;
191 287
@@ -196,15 +292,15 @@
196 292 };
197 293 selected_images.push(image);
198 294 });
199 295
200 - update_view_modal_message(wposmush.please_updating_images_info);
296 + block_ui(wposmush.please_updating_images_info);
201 297
202 298 smush_manager_send_command('mark_as_compressed', {selected_images: selected_images}, function(response) {
203 299 $('#smush-information-modal .smush-information').text(response.summary);
204 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
300 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
205 301 // refresh images list.
206 - get_info_from_smush_manager();
302 + get_info_from_smush_manager(false);
207 303 });
208 304 });
209 305
210 306 /**
@@ -214,10 +310,9 @@
214 310 if (!confirm(wposmush.mark_all_images_uncompressed)) return;
215 311
216 312 var restore_backup = confirm(wposmush.restore_images_from_backup);
217 313
218 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
219 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
314 + block_ui(wposmush.please_wait);
220 315
221 316 smush_mark_all_as_uncompressed = true;
222 317 run_mark_all_as_uncompressed(restore_backup);
223 318 });
@@ -227,10 +322,9 @@
227 322 */
228 323 restore_all_compressed_images_btn.on('click', function() {
229 324 if (!confirm(wposmush.restore_all_compressed_images)) return;
230 325
231 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
232 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
326 + block_ui(wposmush.please_wait);
233 327
234 328 smush_mark_all_as_uncompressed = true;
235 329 run_mark_all_as_uncompressed(true, true);
236 330 });
@@ -247,17 +341,22 @@
247 341 /**
248 342 * Send command for mark all compressed images as uncompressed.
249 343 *
250 344 * @param {bool} restore_backup if set to true then images will restored from backup if possible.
345 + * @param {bool} delete_only_backups_meta if set to true the only backup meta will be deleted
251 346 */
252 347 function run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta) {
253 348 if (!smush_mark_all_as_uncompressed) return;
254 349
350 + restore_backup = restore_backup ? 1 : 0;
351 + delete_only_backups_meta = delete_only_backups_meta ? 1 : 0;
352 +
255 353 var info = $('#smush-information-modal-cancel-btn .smush-information');
256 354 smush_manager_send_command('mark_all_as_uncompressed',
257 355 {
258 - restore_backup: restore_backup ? 1 : 0,
259 - delete_only_backups_meta: delete_only_backups_meta ? 1 : 0
356 + restore_backup: restore_backup,
357 + delete_only_backups_meta: delete_only_backups_meta,
358 + skip_notice: true
260 359 },
261 360 function(resp) {
262 361 // if cancel button pressed then exit
263 362 if (!smush_mark_all_as_uncompressed) return;
@@ -263,10 +362,9 @@
263 362 if (!smush_mark_all_as_uncompressed) return;
264 363
265 364 // if we get an error then show it
266 365 if (resp.hasOwnProperty('error')) {
267 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
268 - $('#smush-information-modal .smush-information').text(resp.error);
366 + block_ui(resp.error);
269 367 get_info_from_smush_manager();
270 368 return;
271 369 }
272 370
@@ -271,14 +369,14 @@
271 369 }
272 370
273 371 // if completed then refresh uncompressed images list and show final message.
274 372 if (resp.completed) {
275 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
373 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
276 374 $('#smush-information-modal .smush-information').text(resp.message);
277 375 get_info_from_smush_manager();
278 376 } else {
279 377 info.text(resp.message);
280 - run_mark_all_as_uncompressed(restore_backup);
378 + run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta);
281 379 }
282 380 }
283 381 );
284 382 }
@@ -286,9 +384,10 @@
286 384 /**
287 385 * Refresh image list
288 386 */
289 387 smush_images_refresh_btn.off().on('click', function() {
290 - get_info_from_smush_manager();
388 + // The refresh image list button should not fetch from cache but run the query
389 + get_info_from_smush_manager(false);
291 390 });
292 391
293 392 /**
294 393 * Bind select all / select none controls
@@ -350,15 +449,8 @@
350 449 });
351 450 });
352 451
353 452 /**
354 - * Saves options
355 - */
356 - smush_images_save_options_btn.off().on('click', function(e) {
357 - save_options();
358 - });
359 -
360 - /**
361 453 * Binds clear stats button
362 454 */
363 455 smush_images_stats_clear_btn.off().on('click', function(e) {
364 456 $('#wpo_smush_images_clear_stats_spinner').show().delay(3000).fadeOut();
@@ -369,44 +461,17 @@
369 461 });
370 462 });
371 463
372 464 /**
373 - * Binds pending tasks button
374 - */
375 - smush_images_pending_tasks_btn.off().on('click', function(e) {
376 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
377 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
378 - data = { 'server': $("input[name='compression_server']:checked").val() };
379 - smush_manager_send_command('check_server_status', data, function(resp) {
380 - if (resp.online) {
381 - update_view_bulk_smush_start();
382 - smush_manager_send_command('process_pending_images', {}, function(resp) {
383 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
384 - });
385 - } else {
386 - if (resp.error) {
387 - error_message = resp.error + '<br>' + wposmush.server_error
388 - $('#smush-information-modal .smush-information').html(error_message);
389 - } else {
390 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
391 - }
392 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
393 - }
394 - });
395 -
396 - });
397 -
398 -
399 - /**
400 465 * Binds smush cancel button
401 466 */
402 467 $('body').on('click', '#wpo_smush_images_pending_tasks_cancel_button', function(e) {
403 468
404 - if (wpoptimize.cancel === pending_tasks_cancel_btn.val()) {
405 - pending_tasks_cancel_btn.val(wpoptimize.cancelling);
469 + if (wposmush.cancel === pending_tasks_cancel_btn.val()) {
470 + pending_tasks_cancel_btn.val(wposmush.cancelling);
406 471 pending_tasks_cancel_btn.prop('disabled', true);
407 472 }
408 - smush_manager_send_command('clear_pending_images', {}, function(resp) {
473 + smush_manager_send_command('clear_pending_images', { restore_images: smush_image_list }, function(resp) {
409 474 $.unblockUI();
410 475 if (resp.status) {
411 476 get_info_from_smush_manager();
412 477 reset_view_bulk_smush();
@@ -412,14 +477,53 @@
412 477 reset_view_bulk_smush();
413 478 } else {
414 479 console.log('Cancelling pending images apparently failed.', resp);
415 480 }
416 - pending_tasks_cancel_btn.val(wpoptimize.cancel);
481 + pending_tasks_cancel_btn.val(wposmush.cancel);
417 482 pending_tasks_cancel_btn.prop('disabled', false);
418 483 });
419 484 });
420 485
421 486 /**
487 + * Handle the click on the 'Compress' button within the Media Library page and open a dialog for the image compression action.
488 + */
489 + $('.column-wpo_smush').on('click', '.wpo-smush-compress-popup-btn', function(e) {
490 + var attachment_id = $(this).data('id'),
491 + blog_id = $(this).data('blog');
492 +
493 + e.preventDefault();
494 +
495 + smush_manager_send_command('get_smush_settings_form', {
496 + attachment_id: attachment_id,
497 + blog_id: blog_id
498 + }, function(resp) {
499 + if (resp.success) {
500 + var html = [
501 + '<div class="wpo-smush-compress-popup-content">',
502 + '<h3>',wposmush.compress_image,'</h3>',
503 + resp.html,
504 + '</div>',
505 + '<div class="wpo_smush_single_image action_button" style="display:inline-block;">',
506 + '<input type="button" data-blog="',blog_id,'" data-id="',attachment_id,'" id="smush_compress_',attachment_id,'" class="button-primary button" value="',wposmush.compress,'">',
507 + '</div>',
508 + '&nbsp;&nbsp;',
509 + '<a href="#" class="button wpo-smush-popup-cancel-btn">',wposmush.close,'</a>'
510 + ].join('');
511 + block_ui('', $.extend(block_ui_custom_options, {message: html}));
512 + }
513 + });
514 +
515 + });
516 +
517 + /**
518 + * Handle the 'Cancel' button in the dialog for the image compression action.
519 + */
520 + $('body').on('click', '.wpo-smush-popup-cancel-btn', function(e) {
521 + e.preventDefault();
522 + $.unblockUI();
523 + });
524 +
525 + /**
422 526 * Single image compression
423 527 */
424 528 $('body').on('click', '.wpo_smush_single_image .button', function() {
425 529
@@ -444,20 +548,15 @@
444 548 'preserve_exif': $('#smush_exif_' + image.attachment_id).is(":checked")
445 549 }
446 550
447 551 data = { 'server': $("input[name='compression_server_" + $(this).attr('id').substring(15) + "']:checked").val() };
448 - update_view_modal_message(wposmush.server_check);
552 + block_ui(wposmush.server_check);
449 553 smush_manager_send_command('check_server_status', data, function(resp) {
450 554 if (resp.online) {
451 555 smush_selected_image(image, smush_options);
452 556 } else {
453 - if (resp.error) {
454 - error_message = resp.error + '<br>' + wposmush.server_error
455 -
456 - update_view_modal_message(error_message, $.unblockUI);
457 - } else {
458 - update_view_modal_message(wposmush.server_error, $.unblockUI);
459 - }
557 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
558 + block_ui(error_message);
460 559 }
461 560 });
462 561 });
463 562
@@ -463,13 +562,15 @@
463 562
464 563 /**
465 564 * Single image restore
466 565 */
467 - $('body').on('click', '.wpo_restore_single_image .button', function() {
566 + $('body').on('click', '.wpo_restore_single_image .button, .wpo_restore_single_image a', function(e) {
468 567 var clicked_image = $(this);
469 568 blog_id = clicked_image.data('blog');
470 569 image_id = clicked_image.data('id');
471 570
571 + e.preventDefault();
572 +
472 573 if (!image_id || !blog_id) return;
473 574 restore_selected_image(blog_id, image_id);
474 575 });
475 576
@@ -475,58 +576,76 @@
475 576
476 577 /**
477 578 * Mark as compressed
478 579 */
479 - $('body').on('click', '.wpo_smush_mark_single_image .button', function() {
480 - var image = {
481 - 'attachment_id':$(this).data('id'),
482 - 'blog_id': $(this).data('blog')
483 - },
484 - wrapper = $(this).closest('#smush-metabox-inside-wrapper');
580 + $('body').on('click', '.wpo_smush_mark_single_image .button, .wpo_smush_mark_single_image a', function(e) {
581 + mark_unmark_as_compressed_handler($(this), e, true);
582 + });
485 583
486 - update_view_modal_message(wposmush.please_updating_images_info);
487 -
488 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ]}, function(response) {
489 - $('#smush-information-modal .smush-information').text(response.summary);
490 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
491 -
492 - if (response.status) {
493 - $('.wpo_smush_single_image', wrapper).hide();
494 - $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
495 - $('.wpo_smush_mark_single_image', wrapper).hide();
496 - $('.wpo_smush_unmark_single_image', wrapper).show();
497 - $('.wpo_restore_single_image', wrapper).show();
498 - $('#smush_info', wrapper).text(response.info);
499 - }
500 - });
584 + /**
585 + * Unmark as compressed
586 + */
587 + $('body').on('click', '.wpo_smush_unmark_single_image .button, .wpo_smush_unmark_single_image a', function(e) {
588 + mark_unmark_as_compressed_handler($(this), e, false);
501 589 });
502 590
503 591 /**
504 - * Unmark as uncompressed
592 + * Handler for Mark/Unmark as compressed event.
593 + *
594 + * @param {jQuery} target jQuery object for target element
595 + * @param {Event} e
596 + * @param {Boolean} mark True or false - mark / unmark
505 597 */
506 - $('body').on('click', '.wpo_smush_unmark_single_image .button', function() {
507 - var image = {
508 - 'attachment_id':$(this).data('id'),
509 - 'blog_id': $(this).data('blog')
598 + function mark_unmark_as_compressed_handler(target, e, mark) {
599 + var blog_id = target.data('blog'),
600 + attachment_id = target.data('id'),
601 + image = {
602 + 'attachment_id': attachment_id,
603 + 'blog_id': blog_id
510 604 },
511 - wrapper = $(this).closest('#smush-metabox-inside-wrapper');
605 + wrapper = target.closest('#smush-metabox-inside-wrapper')
606 + data = {selected_images: [ image ]};
512 607
513 - update_view_modal_message(wposmush.please_updating_images_info);
608 + if (mark === false) {
609 + data.unmark = true;
610 + }
611 +
612 + e.preventDefault();
613 +
614 + block_ui(wposmush.please_updating_images_info);
615 +
616 + smush_manager_send_command('mark_as_compressed', data, function(response) {
514 617
515 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ], unmark: true}, function(response) {
516 618 $('#smush-information-modal .smush-information').text(response.summary);
517 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
518 619
620 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
621 +
519 622 if (response.status) {
520 - $('.wpo_smush_single_image', wrapper).show();
521 - $('.wpo_smush_mark_single_image', wrapper).show();
522 - $('.wpo_smush_unmark_single_image', wrapper).hide();
523 - $('.wpo_restore_single_image', wrapper).hide();
524 - $('#smush_info', wrapper).text('');
623 + if (wrapper.length) {
624 + if (mark) {
625 + $('.wpo_smush_single_image', wrapper).hide();
626 + $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
627 + $('.wpo_smush_mark_single_image', wrapper).hide();
628 + $('.wpo_smush_unmark_single_image', wrapper).show();
629 + $('.wpo_restore_single_image', wrapper).show();
630 + $('#smush_info', wrapper).text(response.info);
631 + } else {
632 + $('.wpo_smush_single_image', wrapper).show();
633 + $('.wpo_smush_mark_single_image', wrapper).show();
634 + $('.wpo_smush_unmark_single_image', wrapper).hide();
635 + $('.wpo_restore_single_image', wrapper).hide();
636 + $('#smush_info', wrapper).text(response.info);
637 + }
638 + }
639 +
640 + if (response.hasOwnProperty('media_column_html')) {
641 + update_smush_information_media_library_column(blog_id, attachment_id, response.media_column_html);
642 + }
525 643 }
526 644 });
527 - });
645 + }
528 646
647 +
529 648 $('body').on('click', '#wpo_smush_details .wpo-collapsible', toggle_smush_details);
530 649 $('body').on('click', '.column-wpo_smush .wpo-collapsible', toggle_smush_details);
531 650
532 651 function toggle_smush_details() {
@@ -539,14 +658,29 @@
539 658 }
540 659
541 660 $('body').on('click', '#smush-log-modal .close, #smush-information-modal .information-modal-close', function() {
542 661 $.unblockUI();
662 + if (smush_from_media_library) {
663 + reset_bulk_actions_dropdown();
664 + }
543 665 });
544 666
545 667 $('body').on('click', '.wpo_smush_stats_cta_btn, .wpo_smush_get_logs, #smush-complete-summary .close', function() {
546 668 $.unblockUI();
547 - get_info_from_smush_manager();
548 - setTimeout(reset_view_bulk_smush, 500);
669 + if (smush_from_media_library) {
670 + var selected_images_list = get_media_library_selected_images_list();
671 + smush_manager_send_command('get_smush_details', {selected_images: selected_images_list}, function(response) {
672 + if (response.success) {
673 + window.clearInterval(smush_timer_handle);
674 + update_media_library_screen(response.smush_details);
675 + } else {
676 + console.log(response)
677 + }
678 + });
679 + } else {
680 + get_info_from_smush_manager();
681 + setTimeout(reset_view_bulk_smush, 500);
682 + }
549 683 });
550 684
551 685 $('body').on('click', '.wpo-toggle-advanced-options', function(e) {
552 686 e.preventDefault();
@@ -552,9 +686,9 @@
552 686 e.preventDefault();
553 687 $(this).toggleClass('opened');
554 688 });
555 689
556 - $('.wpo-fieldgroup .autosmush input, .wpo-fieldgroup .compression_level, .wpo-fieldgroup .image_options, #smush-show-metabox, #enable_webp_conversion').on('change', function(e) {
690 + $('.wpo-fieldgroup .autosmush input, .wpo-fieldgroup .compression_level, .wpo-fieldgroup .image_options, #smush-show-metabox').on('change', function(e) {
557 691 save_options();
558 692 });
559 693
560 694 $('body').on('change', '.smush-options.compression_level', function() {
@@ -568,28 +702,57 @@
568 702 $('body').on('change', '.smush-advanced input[type="radio"]', function() {
569 703 update_view_available_options();
570 704 });
571 705
572 - convert_to_webp_btn.on('click', function(e){
706 + $('#enable_webp_conversion').on('change', function(e) {
707 + // only save when changing the options on the wpo dashboard.
708 + if (!$('#wp-optimize-wrap').length) return;
709 +
710 + $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut();
711 + $('#enable_webp_conversion').prop("disabled", true);
712 +
713 + var smush_options = get_smush_options();
714 + // Skip default notice and use popup to show error messages
715 + smush_options.skip_notice = true;
716 +
717 + smush_manager_send_command('update_webp_options', smush_options, function(resp) {
718 + $('#wpo_smush_images_save_options_spinner').hide();
719 + if (resp.hasOwnProperty('saved') && resp.saved) {
720 + $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
721 + } else {
722 + $('#enable_webp_conversion').prop("checked", false);
723 + if ('update_failed_no_working_webp_converter' === resp.error_code) {
724 + var html_msg = '<p>'
725 + + wposmush.webp_conversion_tool_error
726 + + ' <a href="https://teamupdraft.com/documentation/wp-optimize/topics/image-compression/troubleshooting/the-webp-conversion-tool-is-not-working/" target="_blank">'
727 + + wposmush.webp_conversion_tool_how_to
728 + + '</a></p>';
729 + $('#smush-information-modal .smush-information').html(html_msg);
730 + } else {
731 + $('#smush-information-modal .smush-information').text(resp.error_message);
732 + }
733 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
734 + }
735 + $('#enable_webp_conversion').prop("disabled", false);
736 + });
737 + });
738 +
739 + $('body').on('click', '.wpo_smush.column-wpo_smush .convert-to-webp', function(e){
573 740 e.preventDefault();
574 741 var $link = $(this);
575 742 data = {
576 - 'attachment_id': $(this).data('attachment-id')
743 + 'attachment_id': $(this).data('attachment-id'),
744 + skip_notice: true
577 745 };
578 - update_view_modal_message(wposmush.converting_to_webp);
746 + block_ui(wposmush.converting_to_webp, {}, 0, true);
579 747 smush_manager_send_command('convert_to_webp_format', data, function(response) {
580 - if (response.error) {
581 - update_view_modal_message(response.error, $.unblockUI);
582 - setTimeout(function() {
583 - $.unblockUI();
584 - }, 2000);
585 - } else {
586 - update_view_modal_message(response.success, $.unblockUI);
587 - setTimeout(function() {
588 - $.unblockUI();
589 - }, 2000);
748 + if (response.success) {
749 + block_ui(response.success, {}, 2000);
590 750 $link.next().remove();
751 + if ($link.prev().is('.wpo-action-separator')) $link.prev().remove();
591 752 $link.remove();
753 + } else {
754 + block_ui(response.error || response.error_message || wposmush.server_error , {}, 2000);
592 755 }
593 756 });
594 757 });
595 758
@@ -605,18 +768,25 @@
605 768 var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
606 769 var data = { 'use_cache': use_cache };
607 770
608 771 smush_images_optimization_message.html('...');
609 - smush_images_pending_tasks_container.hide();
610 772
611 773 disable_image_optimization_controls(true);
612 774
613 - smush_manager_send_command('get_ui_update', data, function(resp) {
614 - handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
615 - update_view_available_options();
616 - disable_image_optimization_controls(false);
617 - update_smush_action_buttons_state();
618 - });
775 + heartbeat_agents.push(heartbeat.add_agent({
776 + _wait: false,
777 + _keep: false,
778 + command: 'updraft_smush_ajax',
779 + command_data: {data: data, subaction: 'get_ui_update'},
780 + callback: function(resp) {
781 + handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
782 + update_view_available_options();
783 + disable_image_optimization_controls(false);
784 + update_smush_action_buttons_state();
785 + }
786 + }));
787 +
788 + uncompressed_images_already_loaded = true;
619 789 }
620 790
621 791
622 792 /**
@@ -646,9 +816,14 @@
646 816 }
647 817 }
648 818
649 819 update_view_bulk_smush_start();
650 - smush_manager_send_command('process_bulk_smush', data);
820 + heartbeat_agents.push(heartbeat.add_agent({
821 + _wait: false,
822 + _keep: false,
823 + command: 'updraft_smush_ajax',
824 + command_data: {data: data, subaction: 'process_bulk_smush'}
825 + }));
651 826 }
652 827
653 828 /**
654 829 * Save options in the DB
@@ -666,12 +841,10 @@
666 841 smush_manager_send_command('update_smush_options', smush_options, function(resp) {
667 842 $('#wpo_smush_images_save_options_spinner').hide();
668 843 if (resp.hasOwnProperty('saved') && resp.saved) {
669 844 $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
670 - smush_images_save_options_btn.hide();
671 845 } else {
672 846 $('#wpo_smush_images_save_options_fail').show().delay(3000).fadeOut();
673 - smush_images_save_options_btn.show();
674 847 }
675 848 });
676 849 }
677 850
@@ -697,17 +870,26 @@
697 870 *
698 871 * @return void
699 872 */
700 873 function trigger_events(time_elapsed) {
701 -
702 874 if (0 == time_elapsed % 3) {
703 - update_smush_stats();
875 + update_smush_stats(time_elapsed);
704 876 }
705 877
706 878 if (0 == time_elapsed % 60) {
707 - smush_manager_send_command('process_pending_images', {}, function(resp) {
708 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
709 - });
879 + if (null != last_ui_update_agent_uid) {
880 + heartbeat.cancel_agent(last_ui_update_agent_uid);
881 + last_ui_update_agent_uid = null;
882 + }
883 +
884 + heartbeat_agents.push(heartbeat.add_agent({
885 + _wait: false,
886 + command: 'updraft_smush_ajax',
887 + command_data: {data: {}, subaction: 'process_pending_images'},
888 + callback: function(resp) {
889 + handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
890 + }
891 + }));
710 892 }
711 893 }
712 894
713 895 /**
@@ -712,30 +894,41 @@
712 894
713 895 /**
714 896 * Updates the UI with stats
715 897 *
716 - * @param {Boolean} use_cache Use the request cache
898 + * @param {Int} time_elapsed Elapsed time since process start
717 899 *
718 900 * @return void
719 901 */
720 - function update_smush_stats(use_cache) {
721 -
722 - var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
723 -
902 + function update_smush_stats(time_elapsed) {
724 903 data = {
725 904 update_ui: true,
726 905 use_cache: false
727 906 }
728 907
729 - smush_manager_send_command('get_ui_update', data, function(resp) {
730 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
908 + var initial_requests = time_elapsed < 5;
909 +
910 + var agent = heartbeat.add_agent({
911 + _wait: !initial_requests,
912 + _keep: false,
913 + command: 'updraft_smush_ajax',
914 + command_data: {data: data, subaction: 'get_ui_update'},
915 + callback: function(resp) {
916 + handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
917 + }
731 918 });
919 +
920 + if (null !== agent) {
921 + last_ui_update_agent_uid = agent;
922 +
923 + heartbeat_agents.push(agent);
924 + }
732 925 }
733 926
734 927 /**
735 928 * Update images optimization tab view with data returned from images optimization.
736 929 *
737 - * @param {Object} data - meta data returned from task manager
930 + * @param {Object} data - metadata returned from task manager
738 931 *
739 932 * @return void
740 933 */
741 934 function update_view_show_uncompressed_images(data) {
@@ -750,12 +943,8 @@
750 943 if (0 == unsmushed_images.length && 0 == pending_tasks) {
751 944 smush_images_grid.text(wposmush.all_images_compressed).wrapInner("<div class='wpo-fieldgroup'> </div>");
752 945 }
753 946
754 - if (0 != pending_tasks) {
755 - smush_images_pending_tasks_container.show().find('.red').text(data.pending);
756 - }
757 -
758 947 if (1 === data.is_multisite) {
759 948 blog_id = uncompressed_images_sites_select.find(":selected").val();
760 949 add_unsmushed_images_to_grid(blog_id, data);
761 950 } else {
@@ -797,22 +986,45 @@
797 986 * @return void
798 987 */
799 988 function update_view_bulk_smush_start() {
800 989 if (smush_timer_locked) return;
801 - update_view_modal_message($('#wpo_smush_images_information_container'));
802 990
803 - service = $('.compression_server input[type="radio"]:checked + label small').text();
804 - $('#wpo_smush_images_information_server').html(service);
991 + block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
805 992
806 - // Clear stats
993 + clear_smush_stats();
994 +
995 + smush_timer_handle = window.setInterval(smush_timer, 1000);
996 + disable_image_optimization_controls(true);
997 + }
998 +
999 + /**
1000 + * Clears the statistics for image smushing in popup.
1001 + *
1002 + * This function clears the statistics displayed on the popup for image smushing.
1003 + *
1004 + * @returns {void}
1005 + */
1006 + function clear_smush_stats() {
807 1007 $('#smush_stats_pending_images').html("...");
808 1008 $('#smush_stats_completed_images').html("...");
809 1009 $('#smush_stats_bytes_saved').html("...");
810 1010 $('#smush_stats_percent_saved').html("...");
811 1011 $('#smush_stats_timer').html("...");
1012 + }
812 1013
813 - smush_timer_handle = window.setInterval(smush_timer, 1000);
814 - disable_image_optimization_controls(true);
1014 + /**
1015 + * Updates the media library screen with the provided smush details.
1016 + *
1017 + * @param {Object} smush_details - The details of the smushed images
1018 + * @return {void}
1019 + */
1020 + function update_media_library_screen(smush_details) {
1021 + for (var image_id in smush_details) {
1022 + if(smush_details.hasOwnProperty(image_id)) {
1023 + $('#post-' + image_id + ' .column-wpo_smush').html(smush_details[image_id]);
1024 + }
1025 + }
1026 + reset_bulk_actions_dropdown();
815 1027 }
816 1028
817 1029 /**
818 1030 * Updates the view with progress related stats
@@ -831,9 +1043,11 @@
831 1043
832 1044 // Show summary and close the modal
833 1045 if (true == resp.smush_complete) {
834 1046 // Force a delay here to avoid stale data
835 - setTimeout(update_view_bulk_smush_complete, 1500);
1047 + setTimeout(function() {
1048 + update_view_bulk_smush_complete(function() { get_info_from_smush_manager(false); });
1049 + }, 1500);
836 1050 }
837 1051 }
838 1052
839 1053 /**
@@ -840,26 +1054,45 @@
840 1054 * Updates the view when bulk smush completes
841 1055 *
842 1056 * @return void
843 1057 */
844 - function update_view_bulk_smush_complete() {
1058 + function update_view_bulk_smush_complete(callback) {
845 1059
846 1060 data = {
847 1061 update_ui: true,
848 1062 use_cache: false,
849 1063 image_list: smush_image_list
850 - }
1064 + };
851 1065
852 - smush_manager_send_command('get_ui_update', data, function(resp) {
1066 + (function(single_callback) {
1067 + heartbeat_agents.push(heartbeat.add_agent({
1068 + // We have to use a non-unique agent in the complete action because the info update subactions
1069 + // have the same names, and the agent may not be added. This ensures that the "smush_complete" action will run.
1070 + _unique: false,
1071 + _wait: false,
1072 + _keep: false,
1073 + command: 'updraft_smush_ajax',
1074 + command_data: {data: data, subaction: 'get_ui_update'},
1075 + callback: function(resp) {
853 1076
854 - summary = resp.session_stats;
1077 + summary = resp.session_stats;
1078 + // Prevent pops with undefined headers
1079 + if (!resp.session_stats) {
1080 + return;
1081 + }
855 1082
856 - if (0 != resp.completed_task_count) {
857 - summary += '<hr>' + resp.summary;
1083 + if (0 != resp.completed_task_count) {
1084 + summary += '<hr>' + resp.summary;
1085 + }
1086 +
1087 + show_smush_summary(summary);
1088 +
1089 + if (single_callback instanceof Function) {
1090 + single_callback();
1091 + }
858 1092 }
859 -
860 - show_smush_summary(summary);
861 - });
1093 + }));
1094 + })(callback);
862 1095 }
863 1096
864 1097 /**
865 1098 * Displays a modal with compression data
@@ -873,10 +1106,12 @@
873 1106 if (smush_completed) return;
874 1107
875 1108 $('#summary-message').html(summary);
876 1109 reset_view_bulk_smush();
877 - update_view_modal_message($('#smush-complete-summary'));
1110 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-complete-summary')}));
878 1111 smush_completed = true;
1112 +
1113 + heartbeat.cancel_agents(heartbeat_agents);
879 1114 }
880 1115
881 1116 /**
882 1117 * Updates the view when bulk smush completes
@@ -888,9 +1123,12 @@
888 1123 smush_total_seconds = 0;
889 1124 smush_timer_locked = false;
890 1125 smush_completed = false;
891 1126 smush_image_list = [];
892 - window.clearInterval(smush_timer_handle);
1127 +
1128 + heartbeat.cancel_agents(heartbeat_agents);
1129 + clearInterval(smush_timer_handle);
1130 +
893 1131 disable_image_optimization_controls(false);
894 1132 }
895 1133
896 1134 /**
@@ -952,11 +1190,9 @@
952 1190 $.each([
953 1191 smush_selected_images_btn,
954 1192 smush_images_select_all_btn,
955 1193 smush_images_select_none_btn,
956 - smush_images_save_options_btn,
957 1194 smush_images_refresh_btn,
958 - smush_images_pending_tasks_btn,
959 1195 smush_mark_as_compressed_btn,
960 1196 ], function(i, el) {
961 1197 el.prop('disabled', disable);
962 1198 });
@@ -984,12 +1220,13 @@
984 1220 if (0 == selected_image.length) return;
985 1221
986 1222 data = {
987 1223 selected_image: selected_image,
988 - smush_options: smush_options
1224 + smush_options: smush_options,
1225 + skip_notice: true
989 1226 }
990 1227
991 - update_view_modal_message(wposmush.compress_single_image_dialog);
1228 + block_ui(wposmush.compress_single_image_dialog, {}, false, true);
992 1229 smush_manager_send_command('compress_single_image', data, function(resp) {
993 1230 handle_response_from_smush_manager(resp, update_view_single_image_complete);
994 1231 });
995 1232 }
@@ -996,23 +1233,37 @@
996 1233
997 1234 /**
998 1235 * Get selected image and make an ajax request to compress it.
999 1236 *
1000 - * @param {Number} blog_id - The blog id
1001 - * @param {Number} selected_image - The image id
1237 + * @param {Number} blog_id - The blog id
1238 + * @param {Number} selected_image - The image id
1239 + * @param {Function} done_callback - Optional. It will be called when the AJAX command is done, used for multiple calls that need a single `done` action (like bulk_restore)
1002 1240 *
1003 1241 * @return void
1004 1242 */
1005 - function restore_selected_image(blog_id, selected_image) {
1243 + function restore_selected_image(blog_id, selected_image, done_callback) {
1006 1244
1007 1245 // if no selected images then exit.
1008 1246 if (0 == selected_image.length) return;
1009 1247
1010 - update_view_modal_message(wposmush.please_wait, $.unblockUI);
1011 - var data = { 'blog_id': blog_id, 'selected_image': selected_image };
1012 - smush_manager_send_command('restore_single_image', data, function(resp) {
1013 - handle_response_from_smush_manager(resp, update_view_single_image_complete);
1014 - });
1248 + block_ui(wposmush.please_wait);
1249 + var data = { 'blog_id': blog_id, 'selected_image': selected_image, skip_notice: true };
1250 +
1251 + smush_manager_send_command.apply({unique: false}, ['restore_single_image', data, function(resp) {
1252 + var done = function(resp_summary_alt) {
1253 + if ('undefined' != typeof(resp_summary_alt)) {
1254 + resp.summary = resp_summary_alt;
1255 + }
1256 +
1257 + handle_response_from_smush_manager(resp, update_view_single_image_complete);
1258 + }
1259 +
1260 + if (done_callback instanceof Function) {
1261 + done_callback(done);
1262 + } else {
1263 + done();
1264 + }
1265 + }]);
1015 1266 }
1016 1267
1017 1268 /**
1018 1269 * Updates the view once a single image is compressed or restored.
@@ -1024,9 +1275,9 @@
1024 1275 function update_view_single_image_complete(resp) {
1025 1276
1026 1277 if (resp.hasOwnProperty('success') && resp.success) {
1027 1278 $(".smush-information").text(resp.summary);
1028 - update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1279 + block_ui('', $.extend(block_ui_custom_options, {message: $("#smush-information-modal")}));
1029 1280
1030 1281 $('.wpo-toggle-advanced-options.wpo_smush_single_image').removeClass('opened');
1031 1282
1032 1283 update_view_singe_image_compress(resp.operation, resp.summary, resp.restore_possible, resp);
@@ -1039,8 +1290,12 @@
1039 1290
1040 1291 if (!smush_affected_images.hasOwnProperty(blog_id)) smush_affected_images[blog_id] = {};
1041 1292 if (!smush_affected_images[blog_id].hasOwnProperty(image_id)) smush_affected_images[blog_id][image_id] = {};
1042 1293
1294 + if (resp.hasOwnProperty('media_column_html')) {
1295 + update_smush_information_media_library_column(blog_id, image_id, resp.media_column_html);
1296 + }
1297 +
1043 1298 if ('compress' == resp.operation) {
1044 1299 smush_affected_images[blog_id][image_id] = {
1045 1300 operation: resp.operation,
1046 1301 summary: resp.summary,
@@ -1046,19 +1301,34 @@
1046 1301 summary: resp.summary,
1047 1302 restore_possible: resp.restore_possible
1048 1303 }
1049 1304 } else {
1305 + if (image_id) {
1306 + reset_bulk_actions_dropdown();
1307 + }
1050 1308 smush_affected_images[blog_id][image_id] = {
1051 1309 operation: resp.operation
1052 1310 }
1053 1311 }
1054 1312 } else {
1055 - $(".smush-information").text(resp.error_message);
1056 - update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1313 + // Update the error message to be user-friendly
1314 + if (/exceeded_max_filesize/.test(resp.error_message)) resp.error_message = wposmush.exceeded_max_filesize
1315 + block_ui(resp.error_message, {}, 4000);
1057 1316 }
1058 1317 }
1059 1318
1060 1319 /**
1320 + * Update information for the WP-Optimize column in the Media Library.
1321 + *
1322 + * @param {number} blog_id
1323 + * @param {number} image_id
1324 + * @param {string} html
1325 + */
1326 + function update_smush_information_media_library_column(blog_id, image_id, html) {
1327 + $(['.wpo-smush-media-library-column[data-blog="',blog_id,'"][data-id="',image_id,'"]'].join('')).parent().html(html);
1328 + }
1329 +
1330 + /**
1061 1331 * Update metabox view depending on a command response.
1062 1332 *
1063 1333 * @param {string} operation
1064 1334 * @param {string} summary
@@ -1067,8 +1337,10 @@
1067 1337 */
1068 1338 function update_view_singe_image_compress(operation, summary, restore_possible, smush_image_data) {
1069 1339 var wrapper = $("#smush_info").closest('#smush-metabox-inside-wrapper');
1070 1340
1341 + if (0 === wrapper.length) return;
1342 +
1071 1343 if ('compress' == operation) {
1072 1344 $(".wpo_smush_single_image").hide();
1073 1345 $(".wpo_restore_single_image").show();
1074 1346
@@ -1115,30 +1387,8 @@
1115 1387 }
1116 1388 });
1117 1389
1118 1390 /**
1119 - * Display a modal message
1120 - *
1121 - * @param {string} message The message or element to display
1122 - * @param {Function} callback Called when the overlay is clicked
1123 - *
1124 - * @return void
1125 - */
1126 - function update_view_modal_message(message, callback) {
1127 -
1128 - $.blockUI({
1129 - message: message,
1130 - onOverlayClick: callback,
1131 - baseZ: 160001,
1132 - css: {
1133 - width: '400px',
1134 - padding: '20px',
1135 - cursor: 'pointer'
1136 - }
1137 - });
1138 - }
1139 -
1140 - /**
1141 1391 * Check returned response from the smush manager and call update view callback.
1142 1392 *
1143 1393 * @param {Object} resp - response from smush manager.
1144 1394 * @param {Function} update_view_callback - callback function to update view.
@@ -1152,8 +1402,41 @@
1152 1402 alert(wposmush.error_unexpected_response);
1153 1403 console.log(resp);
1154 1404 }
1155 1405 }
1406 +
1407 + /**
1408 + * Retrieves the selected images from the media library.
1409 + *
1410 + * @return {jQuery} - The selected images as a jQuery object.
1411 + */
1412 + function get_media_library_selected_images() {
1413 + return $('input[name="media[]"]:checked');
1414 + }
1415 +
1416 + /**
1417 + * Retrieves the list of selected images from the media library.
1418 + *
1419 + * @return {Array.<number>} The list of selected image IDs.
1420 + */
1421 + function get_media_library_selected_images_list() {
1422 + var selected_images_list = [];
1423 + var $selected_images = get_media_library_selected_images();
1424 + $selected_images.each(function(index, element) {
1425 + selected_images_list.push(parseInt(element.value));
1426 + });
1427 + return selected_images_list;
1428 + }
1429 +
1430 + /**
1431 + * Resets the bulk action dropdown by setting its value to "-1" and unchecking all the selected checkboxes.
1432 + *
1433 + * @returns {void}
1434 + */
1435 + function reset_bulk_actions_dropdown() {
1436 + $('#bulk-action-selector-top, #bulk-action-selector-bottom').val("-1");
1437 + $('input[name="media[]"]:checked, #cb-select-all-1, #cb-select-all-2').prop('checked', false);
1438 + }
1156 1439
1157 1440 /**
1158 1441 * Send an action to the task manager via admin-ajax.php.
1159 1442 *
@@ -1160,60 +1443,53 @@
1160 1443 * @param {string} action The action to send
1161 1444 * @param {[type]} data Data to send
1162 1445 * @param {Function} callback Will be called with the results
1163 1446 * @param {boolean} json_parse JSON parse the results
1447 + * @param {boolean} wait Wait for the response
1164 1448 *
1165 1449 * @return {JSON}
1166 1450 */
1167 - function smush_manager_send_command(action, data, callback, json_parse) {
1451 + function smush_manager_send_command(action, data, callback, json_parse, wait) {
1168 1452
1169 1453 json_parse = ('undefined' === typeof json_parse) ? true : json_parse;
1170 - data = $.isEmptyObject(data) ? {'use_cache' : false} : data;
1454 + var _wait = ('undefined' === typeof wait) ? false : wait;
1171 1455
1172 - var ajax_data = {
1173 - action: 'updraft_smush_ajax',
1174 - subaction: action,
1175 - nonce: wposmush.smush_ajax_nonce,
1176 - data: data
1177 - };
1456 + var skip_notice = data.hasOwnProperty('skip_notice');
1457 + var data_has_only_skip_notice = skip_notice && 1 === Object.keys(data).length;
1458 + var is_data_empty = $.isEmptyObject(data);
1178 1459
1179 - var ajax_opts = {
1180 - type: 'POST',
1181 - url: ajaxurl,
1182 - data: ajax_data,
1183 - success: function(response) {
1460 + data = is_data_empty ? {'use_cache' : false} : data;
1461 + if (data_has_only_skip_notice) data.use_cache = false;
1184 1462
1185 - if (json_parse) {
1186 - try {
1187 - var resp = wpo_parse_json(response);
1188 - } catch (e) {
1189 - console.log("smush_manager_send_command JSON parse error");
1190 - console.log(e);
1191 - console.log(response);
1192 - alert(wposmush.error_unexpected_response);
1463 + (function(single_callback, _keep, _unique) {
1464 + heartbeat_agents.push(heartbeat.add_agent({
1465 + _wait: _wait,
1466 + _keep: _keep,
1467 + _unique: _unique,
1468 + command: 'updraft_smush_ajax',
1469 + command_data: {data: data, subaction: action},
1470 + callback: function(response) {
1471 + if (json_parse) {
1472 + try {
1473 + var resp = wpo_parse_json(response);
1474 + } catch (e) {
1475 + console.log("smush_manager_send_command JSON parse error");
1476 + console.log(e);
1477 + console.log(response);
1478 + alert(wposmush.error_unexpected_response);
1479 + }
1480 + if ('undefined' !== typeof single_callback) single_callback(resp);
1481 + } else {
1482 + if ('undefined' !== typeof single_callback) single_callback(response);
1193 1483 }
1194 - if ('undefined' !== typeof callback) callback(resp);
1195 - } else {
1196 - if ('undefined' !== typeof callback) callback(response);
1197 1484 }
1198 - },
1199 - error: function(response, status, error_code) {
1200 - console.log("smush_manager_send_command AJAX parse error: "+status+" ("+error_code+")");
1201 - if ('undefined' !== typeof callback) {
1202 - callback(response);
1203 - } else {
1204 - console.log(response);
1205 - alert(wposmush.error_unexpected_response);
1206 - }
1207 - },
1208 - dataType: 'text'
1485 + }));
1486 + })(callback, this.keep, this.unique);
1487 + };
1209 1488
1210 - }
1489 + // Attach heartbeat API events
1490 + heartbeat.setup();
1211 1491
1212 - $.ajax(ajax_opts);
1213 -
1214 - };
1215 -
1216 1492 // Gather smush options
1217 1493 var get_smush_options = function() {
1218 1494 var image_quality = '';
1219 1495 if ($('#enable_custom_compression').is(":checked")) {
@@ -1239,78 +1515,4 @@
1239 1515 }
1240 1516 wp_optimize.smush_settings = get_smush_options;
1241 1517 } // END WP_Optimize_Smush
1242 1518
1243 -/**
1244 - * Parse JSON string, including automatically detecting unwanted extra input and skipping it
1245 - *
1246 - * @param {string|object} json_mix_str - JSON string which need to parse and convert to object
1247 - *
1248 - * @throws SyntaxError|String (including passing on what JSON.parse may throw) if a parsing error occurs.
1249 - *
1250 - * @return mixed parsed JSON object. Will only return if parsing is successful (otherwise, will throw)
1251 - */
1252 -function wpo_parse_json(json_mix_str) {
1253 - // When using wp_send_json to return the value, the format is already parsed.
1254 - if ('object' === typeof json_mix_str) return json_mix_str;
1255 -
1256 - // Just try it - i.e. the 'default' case where things work (which can include extra whitespace/line-feeds, and simple strings, etc.).
1257 - try {
1258 - var result = JSON.parse(json_mix_str);
1259 - return result;
1260 - } catch (e) {
1261 - console.log("WPO: Exception when trying to parse JSON (1) - will attempt to fix/re-parse");
1262 - console.log(json_mix_str);
1263 - }
1264 -
1265 - var json_start_pos = json_mix_str.indexOf('{');
1266 - var json_last_pos = json_mix_str.lastIndexOf('}');
1267 -
1268 - // Case where some php notice may be added after or before json string
1269 - if (json_start_pos > -1 && json_last_pos > -1) {
1270 - var json_str = json_mix_str.slice(json_start_pos, json_last_pos + 1);
1271 - try {
1272 - var parsed = JSON.parse(json_str);
1273 - return parsed;
1274 - } catch (e) {
1275 - console.log("WPO: Exception when trying to parse JSON (2) - will attempt to fix/re-parse based upon bracket counting");
1276 -
1277 - var cursor = json_start_pos;
1278 - var open_count = 0;
1279 - var last_character = '';
1280 - var inside_string = false;
1281 -
1282 - // Don't mistake this for a real JSON parser. Its aim is to improve the odds in real-world cases seen, not to arrive at universal perfection.
1283 - while ((open_count > 0 || cursor == json_start_pos) && cursor <= json_last_pos) {
1284 -
1285 - var current_character = json_mix_str.charAt(cursor);
1286 -
1287 - if (!inside_string && '{' == current_character) {
1288 - open_count++;
1289 - } else if (!inside_string && '}' == current_character) {
1290 - open_count--;
1291 - } else if ('"' == current_character && '\\' != last_character) {
1292 - inside_string = inside_string ? false : true;
1293 - }
1294 -
1295 - last_character = current_character;
1296 - cursor++;
1297 - }
1298 -
1299 - console.log("Started at cursor="+json_start_pos+", ended at cursor="+cursor+" with result following:");
1300 - console.log(json_mix_str.substring(json_start_pos, cursor));
1301 -
1302 - try {
1303 - var parsed = JSON.parse(json_mix_str.substring(json_start_pos, cursor));
1304 - // console.log('WPO: JSON re-parse successful');
1305 - return parsed;
1306 - } catch (e) {
1307 - // Throw it again, so that our function works just like JSON.parse() in its behaviour.
1308 - throw e;
1309 - }
1310 -
1311 - }
1312 - }
1313 -
1314 - throw "WPO: could not parse the JSON";
1315 -
1316 -}