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 +509 -343 3.3.1 → 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,14 +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');
74 169 $('#enable_webp_conversion').prop("checked", false);
75 170 $('#smush-information-modal .smush-information').text(resp.error_message);
76 - update_view_modal_message($('#smush-information-modal'))
171 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
77 172 } else {
78 173 $('#wpo_reset_webp_serving_method_done').show().delay(3000).fadeOut();
79 174 }
80 175 });
@@ -80,13 +175,21 @@
80 175 });
81 176 });
82 177
83 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 + /**
84 185 * Checks if smush is active and loads images if yes - image tabs change.
85 186 */
86 187 $('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab').on('click', function() {
188 + if (uncompressed_images_already_loaded) return;
189 +
87 190 if ($(this).is('#wp-optimize-nav-tab-wpo_images-smush')) {
88 - get_info_from_smush_manager();
191 + get_info_from_smush_manager(false);
89 192 }
90 193 });
91 194
92 195 /**
@@ -92,11 +195,13 @@
92 195 /**
93 196 * Checks if smush is active and loads images if yes - main menu change.
94 197 */
95 198 $('#wp-optimize-wrap').on('page-change', function(e, params) {
199 + if (uncompressed_images_already_loaded) return;
200 +
96 201 if ('wpo_images' == params.page) {
97 202 if ($('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab-active').is('#wp-optimize-nav-tab-wpo_images-smush')) {
98 - get_info_from_smush_manager();
203 + get_info_from_smush_manager(false);
99 204 }
100 205 }
101 206 });
102 207
@@ -154,28 +259,21 @@
154 259 */
155 260 smush_selected_images_btn.off().on('click', function() {
156 261
157 262 if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
158 - $('#smush-information-modal .smush-information').text(wposmush.please_select_images)
159 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
263 + block_ui(wposmush.please_select_images);
160 264 return;
161 265 }
162 266
163 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
164 - update_view_modal_message($('#smush-information-modal'));
267 + block_ui(wposmush.server_check);
165 268
166 - data = { 'server': $("input[name='compression_server']:checked").val() };
269 + data = { 'server': $("input[name='compression_server']:checked").val(), skip_notice: true };
167 270 smush_manager_send_command('check_server_status', data, function(resp) {
168 271 if (resp.online) {
169 272 bulk_smush_selected_images();
170 273 } else {
171 - if (resp.error) {
172 - error_message = resp.error + '<br>' + wposmush.server_error
173 - $('#smush-information-modal .smush-information').html(error_message);
174 - } else {
175 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
176 - }
177 - 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);
178 276 }
179 277 });
180 278 });
181 279
@@ -182,13 +280,8 @@
182 280 /**
183 281 * Mark as compressed
184 282 */
185 283 smush_mark_as_compressed_btn.off().on('click', function() {
186 - if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
187 - $('#smush-information-modal .smush-information').text(wposmush.please_select_compressed_images)
188 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
189 - return;
190 - }
191 284
192 285 var selected_images = [],
193 286 image;
194 287
@@ -199,15 +292,15 @@
199 292 };
200 293 selected_images.push(image);
201 294 });
202 295
203 - update_view_modal_message(wposmush.please_updating_images_info);
296 + block_ui(wposmush.please_updating_images_info);
204 297
205 298 smush_manager_send_command('mark_as_compressed', {selected_images: selected_images}, function(response) {
206 299 $('#smush-information-modal .smush-information').text(response.summary);
207 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
300 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
208 301 // refresh images list.
209 - get_info_from_smush_manager();
302 + get_info_from_smush_manager(false);
210 303 });
211 304 });
212 305
213 306 /**
@@ -217,10 +310,9 @@
217 310 if (!confirm(wposmush.mark_all_images_uncompressed)) return;
218 311
219 312 var restore_backup = confirm(wposmush.restore_images_from_backup);
220 313
221 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
222 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
314 + block_ui(wposmush.please_wait);
223 315
224 316 smush_mark_all_as_uncompressed = true;
225 317 run_mark_all_as_uncompressed(restore_backup);
226 318 });
@@ -230,10 +322,9 @@
230 322 */
231 323 restore_all_compressed_images_btn.on('click', function() {
232 324 if (!confirm(wposmush.restore_all_compressed_images)) return;
233 325
234 - update_view_modal_message($('#smush-information-modal-cancel-btn'));
235 - $('#smush-information-modal-cancel-btn .smush-information').text(wposmush.please_wait);
326 + block_ui(wposmush.please_wait);
236 327
237 328 smush_mark_all_as_uncompressed = true;
238 329 run_mark_all_as_uncompressed(true, true);
239 330 });
@@ -250,17 +341,22 @@
250 341 /**
251 342 * Send command for mark all compressed images as uncompressed.
252 343 *
253 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
254 346 */
255 347 function run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta) {
256 348 if (!smush_mark_all_as_uncompressed) return;
257 349
350 + restore_backup = restore_backup ? 1 : 0;
351 + delete_only_backups_meta = delete_only_backups_meta ? 1 : 0;
352 +
258 353 var info = $('#smush-information-modal-cancel-btn .smush-information');
259 354 smush_manager_send_command('mark_all_as_uncompressed',
260 355 {
261 - restore_backup: restore_backup ? 1 : 0,
262 - 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
263 359 },
264 360 function(resp) {
265 361 // if cancel button pressed then exit
266 362 if (!smush_mark_all_as_uncompressed) return;
@@ -266,10 +362,9 @@
266 362 if (!smush_mark_all_as_uncompressed) return;
267 363
268 364 // if we get an error then show it
269 365 if (resp.hasOwnProperty('error')) {
270 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
271 - $('#smush-information-modal .smush-information').text(resp.error);
366 + block_ui(resp.error);
272 367 get_info_from_smush_manager();
273 368 return;
274 369 }
275 370
@@ -274,14 +369,14 @@
274 369 }
275 370
276 371 // if completed then refresh uncompressed images list and show final message.
277 372 if (resp.completed) {
278 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
373 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
279 374 $('#smush-information-modal .smush-information').text(resp.message);
280 375 get_info_from_smush_manager();
281 376 } else {
282 377 info.text(resp.message);
283 - run_mark_all_as_uncompressed(restore_backup);
378 + run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta);
284 379 }
285 380 }
286 381 );
287 382 }
@@ -289,9 +384,10 @@
289 384 /**
290 385 * Refresh image list
291 386 */
292 387 smush_images_refresh_btn.off().on('click', function() {
293 - 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);
294 390 });
295 391
296 392 /**
297 393 * Bind select all / select none controls
@@ -353,15 +449,8 @@
353 449 });
354 450 });
355 451
356 452 /**
357 - * Saves options
358 - */
359 - smush_images_save_options_btn.off().on('click', function(e) {
360 - save_options();
361 - });
362 -
363 - /**
364 453 * Binds clear stats button
365 454 */
366 455 smush_images_stats_clear_btn.off().on('click', function(e) {
367 456 $('#wpo_smush_images_clear_stats_spinner').show().delay(3000).fadeOut();
@@ -372,44 +461,17 @@
372 461 });
373 462 });
374 463
375 464 /**
376 - * Binds pending tasks button
377 - */
378 - smush_images_pending_tasks_btn.off().on('click', function(e) {
379 - $('#smush-information-modal .smush-information').text(wposmush.server_check);
380 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
381 - data = { 'server': $("input[name='compression_server']:checked").val() };
382 - smush_manager_send_command('check_server_status', data, function(resp) {
383 - if (resp.online) {
384 - update_view_bulk_smush_start();
385 - smush_manager_send_command('process_pending_images', {}, function(resp) {
386 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
387 - });
388 - } else {
389 - if (resp.error) {
390 - error_message = resp.error + '<br>' + wposmush.server_error
391 - $('#smush-information-modal .smush-information').html(error_message);
392 - } else {
393 - $('#smush-information-modal .smush-information').text(wposmush.server_error);
394 - }
395 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
396 - }
397 - });
398 -
399 - });
400 -
401 -
402 - /**
403 465 * Binds smush cancel button
404 466 */
405 467 $('body').on('click', '#wpo_smush_images_pending_tasks_cancel_button', function(e) {
406 468
407 - if (wpoptimize.cancel === pending_tasks_cancel_btn.val()) {
408 - pending_tasks_cancel_btn.val(wpoptimize.cancelling);
469 + if (wposmush.cancel === pending_tasks_cancel_btn.val()) {
470 + pending_tasks_cancel_btn.val(wposmush.cancelling);
409 471 pending_tasks_cancel_btn.prop('disabled', true);
410 472 }
411 - smush_manager_send_command('clear_pending_images', {}, function(resp) {
473 + smush_manager_send_command('clear_pending_images', { restore_images: smush_image_list }, function(resp) {
412 474 $.unblockUI();
413 475 if (resp.status) {
414 476 get_info_from_smush_manager();
415 477 reset_view_bulk_smush();
@@ -415,14 +477,53 @@
415 477 reset_view_bulk_smush();
416 478 } else {
417 479 console.log('Cancelling pending images apparently failed.', resp);
418 480 }
419 - pending_tasks_cancel_btn.val(wpoptimize.cancel);
481 + pending_tasks_cancel_btn.val(wposmush.cancel);
420 482 pending_tasks_cancel_btn.prop('disabled', false);
421 483 });
422 484 });
423 485
424 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 + /**
425 526 * Single image compression
426 527 */
427 528 $('body').on('click', '.wpo_smush_single_image .button', function() {
428 529
@@ -447,20 +548,15 @@
447 548 'preserve_exif': $('#smush_exif_' + image.attachment_id).is(":checked")
448 549 }
449 550
450 551 data = { 'server': $("input[name='compression_server_" + $(this).attr('id').substring(15) + "']:checked").val() };
451 - update_view_modal_message(wposmush.server_check);
552 + block_ui(wposmush.server_check);
452 553 smush_manager_send_command('check_server_status', data, function(resp) {
453 554 if (resp.online) {
454 555 smush_selected_image(image, smush_options);
455 556 } else {
456 - if (resp.error) {
457 - error_message = resp.error + '<br>' + wposmush.server_error
458 -
459 - update_view_modal_message(error_message, $.unblockUI);
460 - } else {
461 - update_view_modal_message(wposmush.server_error, $.unblockUI);
462 - }
557 + error_message = resp.error ? resp.error + '<br>' + wposmush.server_error : wposmush.server_error;
558 + block_ui(error_message);
463 559 }
464 560 });
465 561 });
466 562
@@ -466,13 +562,15 @@
466 562
467 563 /**
468 564 * Single image restore
469 565 */
470 - $('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) {
471 567 var clicked_image = $(this);
472 568 blog_id = clicked_image.data('blog');
473 569 image_id = clicked_image.data('id');
474 570
571 + e.preventDefault();
572 +
475 573 if (!image_id || !blog_id) return;
476 574 restore_selected_image(blog_id, image_id);
477 575 });
478 576
@@ -478,58 +576,76 @@
478 576
479 577 /**
480 578 * Mark as compressed
481 579 */
482 - $('body').on('click', '.wpo_smush_mark_single_image .button', function() {
483 - var image = {
484 - 'attachment_id':$(this).data('id'),
485 - 'blog_id': $(this).data('blog')
486 - },
487 - 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 + });
488 583
489 - update_view_modal_message(wposmush.please_updating_images_info);
490 -
491 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ]}, function(response) {
492 - $('#smush-information-modal .smush-information').text(response.summary);
493 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
494 -
495 - if (response.status) {
496 - $('.wpo_smush_single_image', wrapper).hide();
497 - $('.wpo-toggle-advanced-options', wrapper).removeClass('opened');
498 - $('.wpo_smush_mark_single_image', wrapper).hide();
499 - $('.wpo_smush_unmark_single_image', wrapper).show();
500 - $('.wpo_restore_single_image', wrapper).show();
501 - $('#smush_info', wrapper).text(response.info);
502 - }
503 - });
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);
504 589 });
505 590
506 591 /**
507 - * 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
508 597 */
509 - $('body').on('click', '.wpo_smush_unmark_single_image .button', function() {
510 - var image = {
511 - 'attachment_id':$(this).data('id'),
512 - '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
513 604 },
514 - wrapper = $(this).closest('#smush-metabox-inside-wrapper');
605 + wrapper = target.closest('#smush-metabox-inside-wrapper')
606 + data = {selected_images: [ image ]};
515 607
516 - 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) {
517 617
518 - smush_manager_send_command('mark_as_compressed', {selected_images: [ image ], unmark: true}, function(response) {
519 618 $('#smush-information-modal .smush-information').text(response.summary);
520 - update_view_modal_message($('#smush-information-modal'), $.unblockUI);
521 619
620 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
621 +
522 622 if (response.status) {
523 - $('.wpo_smush_single_image', wrapper).show();
524 - $('.wpo_smush_mark_single_image', wrapper).show();
525 - $('.wpo_smush_unmark_single_image', wrapper).hide();
526 - $('.wpo_restore_single_image', wrapper).hide();
527 - $('#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 + }
528 643 }
529 644 });
530 - });
645 + }
531 646
647 +
532 648 $('body').on('click', '#wpo_smush_details .wpo-collapsible', toggle_smush_details);
533 649 $('body').on('click', '.column-wpo_smush .wpo-collapsible', toggle_smush_details);
534 650
535 651 function toggle_smush_details() {
@@ -542,14 +658,29 @@
542 658 }
543 659
544 660 $('body').on('click', '#smush-log-modal .close, #smush-information-modal .information-modal-close', function() {
545 661 $.unblockUI();
662 + if (smush_from_media_library) {
663 + reset_bulk_actions_dropdown();
664 + }
546 665 });
547 666
548 667 $('body').on('click', '.wpo_smush_stats_cta_btn, .wpo_smush_get_logs, #smush-complete-summary .close', function() {
549 668 $.unblockUI();
550 - get_info_from_smush_manager();
551 - 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 + }
552 683 });
553 684
554 685 $('body').on('click', '.wpo-toggle-advanced-options', function(e) {
555 686 e.preventDefault();
@@ -579,21 +710,21 @@
579 710 $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut();
580 711 $('#enable_webp_conversion').prop("disabled", true);
581 712
582 713 var smush_options = get_smush_options();
714 + // Skip default notice and use popup to show error messages
715 + smush_options.skip_notice = true;
583 716
584 717 smush_manager_send_command('update_webp_options', smush_options, function(resp) {
585 718 $('#wpo_smush_images_save_options_spinner').hide();
586 719 if (resp.hasOwnProperty('saved') && resp.saved) {
587 720 $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
588 - smush_images_save_options_btn.hide();
589 721 } else {
590 722 $('#enable_webp_conversion').prop("checked", false);
591 - smush_images_save_options_btn.show();
592 723 if ('update_failed_no_working_webp_converter' === resp.error_code) {
593 724 var html_msg = '<p>'
594 725 + wposmush.webp_conversion_tool_error
595 - + ' <a href="https://getwpo.com/faqs/#How-can-I-get-WebP-conversion-tools-to-work-" target="_blank">'
726 + + ' <a href="https://teamupdraft.com/documentation/wp-optimize/topics/image-compression/troubleshooting/the-webp-conversion-tool-is-not-working/" target="_blank">'
596 727 + wposmush.webp_conversion_tool_how_to
597 728 + '</a></p>';
598 729 $('#smush-information-modal .smush-information').html(html_msg);
599 730 } else {
@@ -598,34 +729,30 @@
598 729 $('#smush-information-modal .smush-information').html(html_msg);
599 730 } else {
600 731 $('#smush-information-modal .smush-information').text(resp.error_message);
601 732 }
602 - update_view_modal_message($('#smush-information-modal'));
733 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
603 734 }
604 735 $('#enable_webp_conversion').prop("disabled", false);
605 736 });
606 737 });
607 738
608 - convert_to_webp_btn.on('click', function(e){
739 + $('body').on('click', '.wpo_smush.column-wpo_smush .convert-to-webp', function(e){
609 740 e.preventDefault();
610 741 var $link = $(this);
611 742 data = {
612 - 'attachment_id': $(this).data('attachment-id')
743 + 'attachment_id': $(this).data('attachment-id'),
744 + skip_notice: true
613 745 };
614 - update_view_modal_message(wposmush.converting_to_webp);
746 + block_ui(wposmush.converting_to_webp, {}, 0, true);
615 747 smush_manager_send_command('convert_to_webp_format', data, function(response) {
616 - if (response.error) {
617 - update_view_modal_message(response.error, $.unblockUI);
618 - setTimeout(function() {
619 - $.unblockUI();
620 - }, 2000);
621 - } else {
622 - update_view_modal_message(response.success, $.unblockUI);
623 - setTimeout(function() {
624 - $.unblockUI();
625 - }, 2000);
748 + if (response.success) {
749 + block_ui(response.success, {}, 2000);
626 750 $link.next().remove();
751 + if ($link.prev().is('.wpo-action-separator')) $link.prev().remove();
627 752 $link.remove();
753 + } else {
754 + block_ui(response.error || response.error_message || wposmush.server_error , {}, 2000);
628 755 }
629 756 });
630 757 });
631 758
@@ -641,18 +768,25 @@
641 768 var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
642 769 var data = { 'use_cache': use_cache };
643 770
644 771 smush_images_optimization_message.html('...');
645 - smush_images_pending_tasks_container.hide();
646 772
647 773 disable_image_optimization_controls(true);
648 774
649 - smush_manager_send_command('get_ui_update', data, function(resp) {
650 - handle_response_from_smush_manager(resp, update_view_show_uncompressed_images);
651 - update_view_available_options();
652 - disable_image_optimization_controls(false);
653 - update_smush_action_buttons_state();
654 - });
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;
655 789 }
656 790
657 791
658 792 /**
@@ -682,9 +816,14 @@
682 816 }
683 817 }
684 818
685 819 update_view_bulk_smush_start();
686 - 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 + }));
687 826 }
688 827
689 828 /**
690 829 * Save options in the DB
@@ -702,12 +841,10 @@
702 841 smush_manager_send_command('update_smush_options', smush_options, function(resp) {
703 842 $('#wpo_smush_images_save_options_spinner').hide();
704 843 if (resp.hasOwnProperty('saved') && resp.saved) {
705 844 $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut();
706 - smush_images_save_options_btn.hide();
707 845 } else {
708 846 $('#wpo_smush_images_save_options_fail').show().delay(3000).fadeOut();
709 - smush_images_save_options_btn.show();
710 847 }
711 848 });
712 849 }
713 850
@@ -733,17 +870,26 @@
733 870 *
734 871 * @return void
735 872 */
736 873 function trigger_events(time_elapsed) {
737 -
738 874 if (0 == time_elapsed % 3) {
739 - update_smush_stats();
875 + update_smush_stats(time_elapsed);
740 876 }
741 877
742 878 if (0 == time_elapsed % 60) {
743 - smush_manager_send_command('process_pending_images', {}, function(resp) {
744 - handle_response_from_smush_manager(resp, update_view_bulk_smush_progress);
745 - });
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 + }));
746 892 }
747 893 }
748 894
749 895 /**
@@ -748,30 +894,41 @@
748 894
749 895 /**
750 896 * Updates the UI with stats
751 897 *
752 - * @param {Boolean} use_cache Use the request cache
898 + * @param {Int} time_elapsed Elapsed time since process start
753 899 *
754 900 * @return void
755 901 */
756 - function update_smush_stats(use_cache) {
757 -
758 - var use_cache = (typeof use_cache === 'undefined') ? true : use_cache;
759 -
902 + function update_smush_stats(time_elapsed) {
760 903 data = {
761 904 update_ui: true,
762 905 use_cache: false
763 906 }
764 907
765 - smush_manager_send_command('get_ui_update', data, function(resp) {
766 - 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 + }
767 918 });
919 +
920 + if (null !== agent) {
921 + last_ui_update_agent_uid = agent;
922 +
923 + heartbeat_agents.push(agent);
924 + }
768 925 }
769 926
770 927 /**
771 928 * Update images optimization tab view with data returned from images optimization.
772 929 *
773 - * @param {Object} data - meta data returned from task manager
930 + * @param {Object} data - metadata returned from task manager
774 931 *
775 932 * @return void
776 933 */
777 934 function update_view_show_uncompressed_images(data) {
@@ -786,12 +943,8 @@
786 943 if (0 == unsmushed_images.length && 0 == pending_tasks) {
787 944 smush_images_grid.text(wposmush.all_images_compressed).wrapInner("<div class='wpo-fieldgroup'> </div>");
788 945 }
789 946
790 - if (0 != pending_tasks) {
791 - smush_images_pending_tasks_container.show().find('.red').text(data.pending);
792 - }
793 -
794 947 if (1 === data.is_multisite) {
795 948 blog_id = uncompressed_images_sites_select.find(":selected").val();
796 949 add_unsmushed_images_to_grid(blog_id, data);
797 950 } else {
@@ -833,22 +986,45 @@
833 986 * @return void
834 987 */
835 988 function update_view_bulk_smush_start() {
836 989 if (smush_timer_locked) return;
837 - update_view_modal_message($('#wpo_smush_images_information_container'));
838 990
839 - service = $('.compression_server input[type="radio"]:checked + label small').text();
840 - $('#wpo_smush_images_information_server').html(service);
991 + block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
841 992
842 - // 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() {
843 1007 $('#smush_stats_pending_images').html("...");
844 1008 $('#smush_stats_completed_images').html("...");
845 1009 $('#smush_stats_bytes_saved').html("...");
846 1010 $('#smush_stats_percent_saved').html("...");
847 1011 $('#smush_stats_timer').html("...");
1012 + }
848 1013
849 - smush_timer_handle = window.setInterval(smush_timer, 1000);
850 - 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();
851 1027 }
852 1028
853 1029 /**
854 1030 * Updates the view with progress related stats
@@ -867,9 +1043,11 @@
867 1043
868 1044 // Show summary and close the modal
869 1045 if (true == resp.smush_complete) {
870 1046 // Force a delay here to avoid stale data
871 - 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);
872 1050 }
873 1051 }
874 1052
875 1053 /**
@@ -876,26 +1054,45 @@
876 1054 * Updates the view when bulk smush completes
877 1055 *
878 1056 * @return void
879 1057 */
880 - function update_view_bulk_smush_complete() {
1058 + function update_view_bulk_smush_complete(callback) {
881 1059
882 1060 data = {
883 1061 update_ui: true,
884 1062 use_cache: false,
885 1063 image_list: smush_image_list
886 - }
1064 + };
887 1065
888 - 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) {
889 1076
890 - summary = resp.session_stats;
1077 + summary = resp.session_stats;
1078 + // Prevent pops with undefined headers
1079 + if (!resp.session_stats) {
1080 + return;
1081 + }
891 1082
892 - if (0 != resp.completed_task_count) {
893 - 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 + }
894 1092 }
895 -
896 - show_smush_summary(summary);
897 - });
1093 + }));
1094 + })(callback);
898 1095 }
899 1096
900 1097 /**
901 1098 * Displays a modal with compression data
@@ -909,10 +1106,12 @@
909 1106 if (smush_completed) return;
910 1107
911 1108 $('#summary-message').html(summary);
912 1109 reset_view_bulk_smush();
913 - update_view_modal_message($('#smush-complete-summary'));
1110 + block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-complete-summary')}));
914 1111 smush_completed = true;
1112 +
1113 + heartbeat.cancel_agents(heartbeat_agents);
915 1114 }
916 1115
917 1116 /**
918 1117 * Updates the view when bulk smush completes
@@ -924,9 +1123,12 @@
924 1123 smush_total_seconds = 0;
925 1124 smush_timer_locked = false;
926 1125 smush_completed = false;
927 1126 smush_image_list = [];
928 - window.clearInterval(smush_timer_handle);
1127 +
1128 + heartbeat.cancel_agents(heartbeat_agents);
1129 + clearInterval(smush_timer_handle);
1130 +
929 1131 disable_image_optimization_controls(false);
930 1132 }
931 1133
932 1134 /**
@@ -988,11 +1190,9 @@
988 1190 $.each([
989 1191 smush_selected_images_btn,
990 1192 smush_images_select_all_btn,
991 1193 smush_images_select_none_btn,
992 - smush_images_save_options_btn,
993 1194 smush_images_refresh_btn,
994 - smush_images_pending_tasks_btn,
995 1195 smush_mark_as_compressed_btn,
996 1196 ], function(i, el) {
997 1197 el.prop('disabled', disable);
998 1198 });
@@ -1020,12 +1220,13 @@
1020 1220 if (0 == selected_image.length) return;
1021 1221
1022 1222 data = {
1023 1223 selected_image: selected_image,
1024 - smush_options: smush_options
1224 + smush_options: smush_options,
1225 + skip_notice: true
1025 1226 }
1026 1227
1027 - update_view_modal_message(wposmush.compress_single_image_dialog);
1228 + block_ui(wposmush.compress_single_image_dialog, {}, false, true);
1028 1229 smush_manager_send_command('compress_single_image', data, function(resp) {
1029 1230 handle_response_from_smush_manager(resp, update_view_single_image_complete);
1030 1231 });
1031 1232 }
@@ -1032,23 +1233,37 @@
1032 1233
1033 1234 /**
1034 1235 * Get selected image and make an ajax request to compress it.
1035 1236 *
1036 - * @param {Number} blog_id - The blog id
1037 - * @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)
1038 1240 *
1039 1241 * @return void
1040 1242 */
1041 - function restore_selected_image(blog_id, selected_image) {
1243 + function restore_selected_image(blog_id, selected_image, done_callback) {
1042 1244
1043 1245 // if no selected images then exit.
1044 1246 if (0 == selected_image.length) return;
1045 1247
1046 - update_view_modal_message(wposmush.please_wait, $.unblockUI);
1047 - var data = { 'blog_id': blog_id, 'selected_image': selected_image };
1048 - smush_manager_send_command('restore_single_image', data, function(resp) {
1049 - handle_response_from_smush_manager(resp, update_view_single_image_complete);
1050 - });
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 + }]);
1051 1266 }
1052 1267
1053 1268 /**
1054 1269 * Updates the view once a single image is compressed or restored.
@@ -1060,9 +1275,9 @@
1060 1275 function update_view_single_image_complete(resp) {
1061 1276
1062 1277 if (resp.hasOwnProperty('success') && resp.success) {
1063 1278 $(".smush-information").text(resp.summary);
1064 - update_view_modal_message($("#smush-information-modal"), $.unblockUI);
1279 + block_ui('', $.extend(block_ui_custom_options, {message: $("#smush-information-modal")}));
1065 1280
1066 1281 $('.wpo-toggle-advanced-options.wpo_smush_single_image').removeClass('opened');
1067 1282
1068 1283 update_view_singe_image_compress(resp.operation, resp.summary, resp.restore_possible, resp);
@@ -1075,8 +1290,12 @@
1075 1290
1076 1291 if (!smush_affected_images.hasOwnProperty(blog_id)) smush_affected_images[blog_id] = {};
1077 1292 if (!smush_affected_images[blog_id].hasOwnProperty(image_id)) smush_affected_images[blog_id][image_id] = {};
1078 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 +
1079 1298 if ('compress' == resp.operation) {
1080 1299 smush_affected_images[blog_id][image_id] = {
1081 1300 operation: resp.operation,
1082 1301 summary: resp.summary,
@@ -1082,19 +1301,34 @@
1082 1301 summary: resp.summary,
1083 1302 restore_possible: resp.restore_possible
1084 1303 }
1085 1304 } else {
1305 + if (image_id) {
1306 + reset_bulk_actions_dropdown();
1307 + }
1086 1308 smush_affected_images[blog_id][image_id] = {
1087 1309 operation: resp.operation
1088 1310 }
1089 1311 }
1090 1312 } else {
1091 - $(".smush-information").text(resp.error_message);
1092 - 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);
1093 1316 }
1094 1317 }
1095 1318
1096 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 + /**
1097 1331 * Update metabox view depending on a command response.
1098 1332 *
1099 1333 * @param {string} operation
1100 1334 * @param {string} summary
@@ -1103,8 +1337,10 @@
1103 1337 */
1104 1338 function update_view_singe_image_compress(operation, summary, restore_possible, smush_image_data) {
1105 1339 var wrapper = $("#smush_info").closest('#smush-metabox-inside-wrapper');
1106 1340
1341 + if (0 === wrapper.length) return;
1342 +
1107 1343 if ('compress' == operation) {
1108 1344 $(".wpo_smush_single_image").hide();
1109 1345 $(".wpo_restore_single_image").show();
1110 1346
@@ -1151,30 +1387,8 @@
1151 1387 }
1152 1388 });
1153 1389
1154 1390 /**
1155 - * Display a modal message
1156 - *
1157 - * @param {string} message The message or element to display
1158 - * @param {Function} callback Called when the overlay is clicked
1159 - *
1160 - * @return void
1161 - */
1162 - function update_view_modal_message(message, callback) {
1163 -
1164 - $.blockUI({
1165 - message: message,
1166 - onOverlayClick: callback,
1167 - baseZ: 160001,
1168 - css: {
1169 - width: '400px',
1170 - padding: '20px',
1171 - cursor: 'pointer'
1172 - }
1173 - });
1174 - }
1175 -
1176 - /**
1177 1391 * Check returned response from the smush manager and call update view callback.
1178 1392 *
1179 1393 * @param {Object} resp - response from smush manager.
1180 1394 * @param {Function} update_view_callback - callback function to update view.
@@ -1188,8 +1402,41 @@
1188 1402 alert(wposmush.error_unexpected_response);
1189 1403 console.log(resp);
1190 1404 }
1191 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 + }
1192 1439
1193 1440 /**
1194 1441 * Send an action to the task manager via admin-ajax.php.
1195 1442 *
@@ -1196,60 +1443,53 @@
1196 1443 * @param {string} action The action to send
1197 1444 * @param {[type]} data Data to send
1198 1445 * @param {Function} callback Will be called with the results
1199 1446 * @param {boolean} json_parse JSON parse the results
1447 + * @param {boolean} wait Wait for the response
1200 1448 *
1201 1449 * @return {JSON}
1202 1450 */
1203 - function smush_manager_send_command(action, data, callback, json_parse) {
1451 + function smush_manager_send_command(action, data, callback, json_parse, wait) {
1204 1452
1205 1453 json_parse = ('undefined' === typeof json_parse) ? true : json_parse;
1206 - data = $.isEmptyObject(data) ? {'use_cache' : false} : data;
1454 + var _wait = ('undefined' === typeof wait) ? false : wait;
1207 1455
1208 - var ajax_data = {
1209 - action: 'updraft_smush_ajax',
1210 - subaction: action,
1211 - nonce: wposmush.smush_ajax_nonce,
1212 - data: data
1213 - };
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);
1214 1459
1215 - var ajax_opts = {
1216 - type: 'POST',
1217 - url: ajaxurl,
1218 - data: ajax_data,
1219 - success: function(response) {
1460 + data = is_data_empty ? {'use_cache' : false} : data;
1461 + if (data_has_only_skip_notice) data.use_cache = false;
1220 1462
1221 - if (json_parse) {
1222 - try {
1223 - var resp = wpo_parse_json(response);
1224 - } catch (e) {
1225 - console.log("smush_manager_send_command JSON parse error");
1226 - console.log(e);
1227 - console.log(response);
1228 - 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);
1229 1483 }
1230 - if ('undefined' !== typeof callback) callback(resp);
1231 - } else {
1232 - if ('undefined' !== typeof callback) callback(response);
1233 1484 }
1234 - },
1235 - error: function(response, status, error_code) {
1236 - console.log("smush_manager_send_command AJAX parse error: "+status+" ("+error_code+")");
1237 - if ('undefined' !== typeof callback) {
1238 - callback(response);
1239 - } else {
1240 - console.log(response);
1241 - alert(wposmush.error_unexpected_response);
1242 - }
1243 - },
1244 - dataType: 'text'
1485 + }));
1486 + })(callback, this.keep, this.unique);
1487 + };
1245 1488
1246 - }
1489 + // Attach heartbeat API events
1490 + heartbeat.setup();
1247 1491
1248 - $.ajax(ajax_opts);
1249 -
1250 - };
1251 -
1252 1492 // Gather smush options
1253 1493 var get_smush_options = function() {
1254 1494 var image_quality = '';
1255 1495 if ($('#enable_custom_compression').is(":checked")) {
@@ -1275,78 +1515,4 @@
1275 1515 }
1276 1516 wp_optimize.smush_settings = get_smush_options;
1277 1517 } // END WP_Optimize_Smush
1278 1518
1279 -/**
1280 - * Parse JSON string, including automatically detecting unwanted extra input and skipping it
1281 - *
1282 - * @param {string|object} json_mix_str - JSON string which need to parse and convert to object
1283 - *
1284 - * @throws SyntaxError|String (including passing on what JSON.parse may throw) if a parsing error occurs.
1285 - *
1286 - * @return mixed parsed JSON object. Will only return if parsing is successful (otherwise, will throw)
1287 - */
1288 -function wpo_parse_json(json_mix_str) {
1289 - // When using wp_send_json to return the value, the format is already parsed.
1290 - if ('object' === typeof json_mix_str) return json_mix_str;
1291 -
1292 - // Just try it - i.e. the 'default' case where things work (which can include extra whitespace/line-feeds, and simple strings, etc.).
1293 - try {
1294 - var result = JSON.parse(json_mix_str);
1295 - return result;
1296 - } catch (e) {
1297 - console.log("WPO: Exception when trying to parse JSON (1) - will attempt to fix/re-parse");
1298 - console.log(json_mix_str);
1299 - }
1300 -
1301 - var json_start_pos = json_mix_str.indexOf('{');
1302 - var json_last_pos = json_mix_str.lastIndexOf('}');
1303 -
1304 - // Case where some php notice may be added after or before json string
1305 - if (json_start_pos > -1 && json_last_pos > -1) {
1306 - var json_str = json_mix_str.slice(json_start_pos, json_last_pos + 1);
1307 - try {
1308 - var parsed = JSON.parse(json_str);
1309 - return parsed;
1310 - } catch (e) {
1311 - console.log("WPO: Exception when trying to parse JSON (2) - will attempt to fix/re-parse based upon bracket counting");
1312 -
1313 - var cursor = json_start_pos;
1314 - var open_count = 0;
1315 - var last_character = '';
1316 - var inside_string = false;
1317 -
1318 - // 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.
1319 - while ((open_count > 0 || cursor == json_start_pos) && cursor <= json_last_pos) {
1320 -
1321 - var current_character = json_mix_str.charAt(cursor);
1322 -
1323 - if (!inside_string && '{' == current_character) {
1324 - open_count++;
1325 - } else if (!inside_string && '}' == current_character) {
1326 - open_count--;
1327 - } else if ('"' == current_character && '\\' != last_character) {
1328 - inside_string = inside_string ? false : true;
1329 - }
1330 -
1331 - last_character = current_character;
1332 - cursor++;
1333 - }
1334 -
1335 - console.log("Started at cursor="+json_start_pos+", ended at cursor="+cursor+" with result following:");
1336 - console.log(json_mix_str.substring(json_start_pos, cursor));
1337 -
1338 - try {
1339 - var parsed = JSON.parse(json_mix_str.substring(json_start_pos, cursor));
1340 - // console.log('WPO: JSON re-parse successful');
1341 - return parsed;
1342 - } catch (e) {
1343 - // Throw it again, so that our function works just like JSON.parse() in its behaviour.
1344 - throw e;
1345 - }
1346 -
1347 - }
1348 - }
1349 -
1350 - throw "WPO: could not parse the JSON";
1351 -
1352 -}