jQuery(function($) {
WP_Optimize_Smush = WP_Optimize_Smush();
});
var WP_Optimize_Smush = function() {
var $ = jQuery;
var heartbeat = WP_Optimize_Heartbeat();
var heartbeat_agents = [];
var last_ui_update_agent_uid = null;
var block_ui = wp_optimize.block_ui;
/**
* Variables for smushing.
*/
var smush_images_grid = $('#wpo_smush_images_grid'),
smush_images_optimization_message = $('#smush_info_images'),
smush_images_refresh_btn = $('#wpo_smush_images_refresh'),
smush_images_select_all_btn = $('#wpo_smush_images_select_all'),
smush_images_select_none_btn = $('#wpo_smush_images_select_none'),
smush_images_stats_clear_btn = $('#wpo_smush_clear_stats_btn'),
smush_selected_images_btn = $('#wpo_smush_images_btn'),
smush_mark_as_compressed_btn = $('#wpo_smush_mark_as_compressed'),
convert_to_webp_btn = $('.wpo_smush.column-wpo_smush .convert-to-webp');
smush_mark_all_as_uncompressed_btn = $('#wpo_smush_mark_all_as_uncompressed_btn'),
restore_all_compressed_images_btn = $('#wpo_smush_restore_all_compressed_images_btn'),
smush_view_logs_btn = $('.wpo_smush_get_logs'),
smush_delete_backup_images_btn = $('#wpo_smush_delete_backup_btn'),
compression_server_select = $('.compression_server'),
reset_webp_serving_method_btn = $('#wpo_reset_webp_serving_method'),
smush_images_tab_loaded = false,
smush_service_features = [],
smush_total_seconds = 0,
smush_timer_locked = false,
smush_timer_handle = 0,
smush_image_list = [],
smush_completed = false,
smush_from_media_library = false,
smush_mark_all_as_uncompressed = false,
smush_affected_images = {},
pending_tasks_cancel_btn = $('#wpo_smush_images_pending_tasks_cancel_button'),
uncompressed_images_sites_select = $('#wpo_uncompressed_images_sites_select');
/**
* These options used for block UI with custom content.
*/
var block_ui_custom_options = {
baseZ: 160001,
css: {
top: '50%',
transform: 'translate(0, -50%)',
width: '400px',
padding: '20px',
cursor: 'pointer'
}
}
$('#doaction, #doaction2').on('click', function(e) {
e.stopImmediatePropagation();
var action = $(this).prev('select').val();
if ('wp_optimize_bulk_compression' !== action && 'wp_optimize_bulk_restore' !== action ) return;
var $selected_images = get_media_library_selected_images();
if (0 === $selected_images.length) return;
e.preventDefault();
if ('wp_optimize_bulk_compression' === action) bulk_compression($selected_images);
if ('wp_optimize_bulk_restore' === action) bulk_restore($selected_images);
});
/**
* Handles bulk compression action from media library
*
* @param {Object} $selected_images
*/
function bulk_compression($selected_images) {
block_ui(wposmush.server_check);
data = { 'server': wposmush.smush_settings.compression_server, skip_notice: true };
smush_manager_send_command('check_server_status', data, function(resp) {
if (resp.online) {
$selected_images.each(function(index, element) {
smush_image_list.push({
'attachment_id': parseInt(element.value),
'blog_id': wposmush.blog_id
});
});
data = {
optimization_id: 'smush',
selected_images: smush_image_list,
smush_options: {
'compression_server': wposmush.smush_settings.compression_server,
'image_quality': wposmush.smush_settings.image_quality,
'lossy_compression': wposmush.smush_settings.lossy_compression,
'back_up_original': wposmush.smush_settings.back_up_original,
'preserve_exif': wposmush.smush_settings.preserve_exif
}
}
smush_from_media_library = true;
smush_completed = false;
if (smush_timer_locked) return;
block_ui('', $.extend(block_ui_custom_options, {message: $('#wpo_smush_images_information_container')}), false, true);
$('#wpo_smush_images_information_server').html(wposmush.smush_settings.compression_server);
clear_smush_stats();
smush_timer_handle = window.setInterval(smush_timer, 1000);
smush_manager_send_command('process_bulk_smush', data);
} else {
error_message = resp.error ? resp.error + '
' + wposmush.server_error : wposmush.server_error;
block_ui(error_message);
}
});
}
/**
* Handles bulk restore action from media library
*
* @param {Object} $selected_images
*/
function bulk_restore($selected_images) {
smush_from_media_library = true;
var processed_elements = [];
var progress = function(element_id) {
return function(callback) {
processed_elements.push(element_id);
if (1 < processed_elements.length && processed_elements.length === $selected_images.length) {
callback(wposmush.images_restored_successfully);
} else {
callback();
}
}
}
$selected_images.each(function(index, element) {
restore_selected_image(wposmush.blog_id, parseInt(element.value), progress(parseInt(element.value)));
});
}
/**
* Handle Image Selection
*/
smush_images_grid.on('click', '.thumbnail', function (e) {
$(this).closest('input[type="checkbox"]').prop('checked', true);
});
/**
* Handle Shift Ctrl keys state.
*/
var ctrl_shift_on_image_held = false;
smush_images_grid.on('mousedown', '.thumbnail', function (e) {
ctrl_shift_on_image_held = e.shiftKey || e.ctrlKey;
});
smush_images_grid.on('mouseup', '.thumbnail', function (e) {
ctrl_shift_on_image_held = e.shiftKey || e.ctrlKey;
});
// Resets server rewrite capability
reset_webp_serving_method_btn.on('click', function(e) {
e.preventDefault();
smush_manager_send_command('reset_webp_serving_method', { skip_notice: true }, function(resp) {
if (!resp.success) {
$('#enable_webp_conversion').prop("checked", false);
$('#smush-information-modal .smush-information').text(resp.error_message);
block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true);
} else {
$('#wpo_reset_webp_serving_method_done').show().delay(3000).fadeOut();
}
});
});
/**
* Boolean flag to track whether uncompressed images have already been loaded,
* preventing multiple unnecessary loads
*/
var uncompressed_images_already_loaded = false;
/**
* Checks if smush is active and loads images if yes - image tabs change.
*/
$('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab').on('click', function() {
if (uncompressed_images_already_loaded) return;
if ($(this).is('#wp-optimize-nav-tab-wpo_images-smush')) {
get_info_from_smush_manager(false);
}
});
/**
* Checks if smush is active and loads images if yes - main menu change.
*/
$('#wp-optimize-wrap').on('page-change', function(e, params) {
if (uncompressed_images_already_loaded) return;
if ('wpo_images' == params.page) {
if ($('#wp-optimize-nav-tab-wrapper__wpo_images .nav-tab-active').is('#wp-optimize-nav-tab-wpo_images-smush')) {
get_info_from_smush_manager(false);
}
}
});
if ($('#smush-metabox').length > 0) {
update_view_available_options();
}
var lastclick = null;
smush_images_grid.on('click' , '.wpo_smush_image' , function(e) {
var grid_input = $('#wpo_smush_images_grid input[type="checkbox"]');
var input = $(this).find('.wpo_smush_image__input');
var input_val = (!(input.prop('checked')));
if (!lastclick) {
$(this).find('.wpo_smush_image__input').prop('checked',input_val);
lastclick = input;
}
if (true === ctrl_shift_on_image_held) {
var start = grid_input.index(input);
var end = grid_input.index(lastclick);
if (start === end) {
grid_input.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', input_val);
} else {
if (true === lastclick.prop('checked')) {
grid_input.slice(Math.min(start,end), Math.max(start,end)+ 1).prop('checked', input_val);
}
}
}
lastclick = input;
update_smush_action_buttons_state();
});
/**
* Disable smush actions buttons if no images selected.
*/
function update_smush_action_buttons_state() {
var state = (0 == $('input[type="checkbox"]:checked', smush_images_grid).length);
smush_selected_images_btn.prop('disabled', state);
smush_mark_as_compressed_btn.prop('disabled', state);
}
update_smush_action_buttons_state();
/**
* Handles change of smush service provider
*/
compression_server_select.on('change', function(e) {
update_view_available_options();
save_options();
});
/**
* Process bulk smush
*/
smush_selected_images_btn.off().on('click', function() {
if (0 == $('#wpo_smush_images_grid input[type="checkbox"]:checked').length) {
block_ui(wposmush.please_select_images);
return;
}
block_ui(wposmush.server_check);
data = { 'server': $("input[name='compression_server']:checked").val(), skip_notice: true };
smush_manager_send_command('check_server_status', data, function(resp) {
if (resp.online) {
bulk_smush_selected_images();
} else {
error_message = resp.error ? resp.error + '
' + wposmush.server_error : wposmush.server_error;
block_ui(error_message);
}
});
});
/**
* Mark as compressed
*/
smush_mark_as_compressed_btn.off().on('click', function() {
var selected_images = [],
image;
$('#wpo_smush_images_grid input:checked').each(function() {
image = {
'attachment_id':$(this).val(),
'blog_id': $(this).data('blog')
};
selected_images.push(image);
});
block_ui(wposmush.please_updating_images_info);
smush_manager_send_command('mark_as_compressed', {selected_images: selected_images}, function(response) {
$('#smush-information-modal .smush-information').text(response.summary);
block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
// refresh images list.
get_info_from_smush_manager(false);
});
});
/**
* Handle "Mark all images as uncompressed" click.
*/
smush_mark_all_as_uncompressed_btn.on('click', function() {
if (!confirm(wposmush.mark_all_images_uncompressed)) return;
var restore_backup = confirm(wposmush.restore_images_from_backup);
block_ui(wposmush.please_wait);
smush_mark_all_as_uncompressed = true;
run_mark_all_as_uncompressed(restore_backup);
});
/**
* Handle "Restore all compressed images" click.
*/
restore_all_compressed_images_btn.on('click', function() {
if (!confirm(wposmush.restore_all_compressed_images)) return;
block_ui(wposmush.please_wait);
smush_mark_all_as_uncompressed = true;
run_mark_all_as_uncompressed(true, true);
});
/**
* Handle "Cancel" button click for mark all images as uncompressed process
*/
$('#smush-information-modal-cancel-btn input[type="button"]').on('click', function() {
smush_mark_all_as_uncompressed = false;
get_info_from_smush_manager();
$.unblockUI();
});
/**
* Send command for mark all compressed images as uncompressed.
*
* @param {bool} restore_backup if set to true then images will restored from backup if possible.
* @param {bool} delete_only_backups_meta if set to true the only backup meta will be deleted
*/
function run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta) {
if (!smush_mark_all_as_uncompressed) return;
restore_backup = restore_backup ? 1 : 0;
delete_only_backups_meta = delete_only_backups_meta ? 1 : 0;
var info = $('#smush-information-modal-cancel-btn .smush-information');
smush_manager_send_command('mark_all_as_uncompressed',
{
restore_backup: restore_backup,
delete_only_backups_meta: delete_only_backups_meta,
skip_notice: true
},
function(resp) {
// if cancel button pressed then exit
if (!smush_mark_all_as_uncompressed) return;
// if we get an error then show it
if (resp.hasOwnProperty('error')) {
block_ui(resp.error);
get_info_from_smush_manager();
return;
}
// if completed then refresh uncompressed images list and show final message.
if (resp.completed) {
block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}));
$('#smush-information-modal .smush-information').text(resp.message);
get_info_from_smush_manager();
} else {
info.text(resp.message);
run_mark_all_as_uncompressed(restore_backup, delete_only_backups_meta);
}
}
);
}
/**
* Refresh image list
*/
smush_images_refresh_btn.off().on('click', function() {
// The refresh image list button should not fetch from cache but run the query
get_info_from_smush_manager(false);
});
/**
* Bind select all / select none controls
*/
smush_images_select_all_btn.off().on('click', function() {
$('#wpo_smush_images_grid input[type="checkbox"]').prop("checked", true);
lastclick = null;
update_smush_action_buttons_state();
});
/**
* Bind select all / select none controls
*/
smush_images_select_none_btn.off().on('click', function() {
$('#wpo_smush_images_grid input[type="checkbox"]').prop("checked", false);
lastclick = null;
update_smush_action_buttons_state();
});
/**
* Displays logs in a modal
*/
smush_view_logs_btn.off().on('click', function() {
$("#log-panel").text("Please wait, fetching logs.");
smush_manager_send_command('get_smush_logs', {}, function(resp) {
$.blockUI({
message: $("#smush-log-modal"),
onOverlayClick: $.unblockUI(),
css: {
width: '80%',
height: '80%',
top: '15%',
left: '15%'
}
});
$("#log-panel").html("
" + resp + ""); download_link = ajaxurl + "?action=updraft_smush_ajax&subaction=get_smush_logs&nonce=" + wposmush.smush_ajax_nonce; $("#smush-log-modal a").attr('href', download_link); }, false); }); /** * Handle delete all backup images button click. */ smush_delete_backup_images_btn.on('click', function() { if (!confirm(wposmush.delete_image_backup_confirm)) return; smush_delete_backup_images_btn.prop('disabled', true); var spinner = $('#wpo_smush_delete_backup_spinner'), done = $('#wpo_smush_delete_backup_done'); spinner.show(); smush_manager_send_command('clean_all_backup_images', {}, function() { spinner.hide(); smush_delete_backup_images_btn.prop('disabled', false); done.css('display', 'inline-block').delay(3000).fadeOut(); }); }); /** * Binds clear stats button */ smush_images_stats_clear_btn.off().on('click', function(e) { $('#wpo_smush_images_clear_stats_spinner').show().delay(3000).fadeOut(); smush_manager_send_command('clear_smush_stats', {}, function(resp) { $('#wpo_smush_images_clear_stats_spinner').hide(); $('#wpo_smush_images_clear_stats_done').show().delay(3000).fadeOut(); }); }); /** * Binds smush cancel button */ $('body').on('click', '#wpo_smush_images_pending_tasks_cancel_button', function(e) { if (wposmush.cancel === pending_tasks_cancel_btn.val()) { pending_tasks_cancel_btn.val(wposmush.cancelling); pending_tasks_cancel_btn.prop('disabled', true); } smush_manager_send_command('clear_pending_images', { restore_images: smush_image_list }, function(resp) { $.unblockUI(); if (resp.status) { get_info_from_smush_manager(); reset_view_bulk_smush(); } else { console.log('Cancelling pending images apparently failed.', resp); } pending_tasks_cancel_btn.val(wposmush.cancel); pending_tasks_cancel_btn.prop('disabled', false); }); }); /** * Handle the click on the 'Compress' button within the Media Library page and open a dialog for the image compression action. */ $('.column-wpo_smush').on('click', '.wpo-smush-compress-popup-btn', function(e) { var attachment_id = $(this).data('id'), blog_id = $(this).data('blog'); e.preventDefault(); smush_manager_send_command('get_smush_settings_form', { attachment_id: attachment_id, blog_id: blog_id }, function(resp) { if (resp.success) { var html = [ '
' + wposmush.webp_conversion_tool_error + ' ' + wposmush.webp_conversion_tool_how_to + '
'; $('#smush-information-modal .smush-information').html(html_msg); } else { $('#smush-information-modal .smush-information').text(resp.error_message); } block_ui('', $.extend(block_ui_custom_options, {message: $('#smush-information-modal')}), false, true); } $('#enable_webp_conversion').prop("disabled", false); }); }); convert_to_webp_btn.on('click', function(e){ e.preventDefault(); var $link = $(this); data = { 'attachment_id': $(this).data('attachment-id'), skip_notice: true }; block_ui(wposmush.converting_to_webp); smush_manager_send_command('convert_to_webp_format', data, function(response) { if (response.error) { block_ui(response.error, {}, 2000); } else { block_ui(response.success, {}, 2000); $link.next().remove(); $link.remove(); } }); }); /** * Load and show information about uncompressed images. * * @param {Boolean} use_cache Use the request cache * * @return void */ function get_info_from_smush_manager(use_cache) { var use_cache = (typeof use_cache === 'undefined') ? true : use_cache; var data = { 'use_cache': use_cache }; smush_images_optimization_message.html('...'); disable_image_optimization_controls(true); heartbeat_agents.push(heartbeat.add_agent({ _wait: false, _keep: false, command: 'updraft_smush_ajax', command_data: {data: data, subaction: 'get_ui_update'}, callback: function(resp) { handle_response_from_smush_manager(resp, update_view_show_uncompressed_images); update_view_available_options(); disable_image_optimization_controls(false); update_smush_action_buttons_state(); } })); uncompressed_images_already_loaded = true; } /** * Get selected images and make an ajax request to compress them. * * @return void */ function bulk_smush_selected_images() { $('#wpo_smush_images_grid input:checked').each(function() { image = { 'attachment_id':$(this).val(), 'blog_id': $(this).data('blog') }; smush_image_list.push(image); }); data = { optimization_id: 'smush', selected_images: smush_image_list, smush_options: { 'compression_server': $("input[name='compression_server']:checked").val(), 'image_quality': $('#image_quality').val(), 'lossy_compression': $('#smush-lossy-compression').is(":checked"), 'back_up_original': $('#smush-backup-original').is(":checked"), 'preserve_exif': $('#smush-preserve-exif').is(":checked") } } update_view_bulk_smush_start(); heartbeat_agents.push(heartbeat.add_agent({ _wait: false, _keep: false, command: 'updraft_smush_ajax', command_data: {data: data, subaction: 'process_bulk_smush'} })); } /** * Save options in the DB * * @return void */ function save_options() { // only save when changing the options on the wpo dashboard. if (!$('#wp-optimize-wrap').length) return; $('#wpo_smush_images_save_options_spinner').show().delay(3000).fadeOut(); var smush_options = get_smush_options(); smush_manager_send_command('update_smush_options', smush_options, function(resp) { $('#wpo_smush_images_save_options_spinner').hide(); if (resp.hasOwnProperty('saved') && resp.saved) { $('#wpo_smush_images_save_options_done').show().delay(3000).fadeOut(); } else { $('#wpo_smush_images_save_options_fail').show().delay(3000).fadeOut(); } }); } /** * A timer to run for the duration of the bulk smush operation. * * @return void */ function smush_timer() { smush_timer_locked = true; smush_total_seconds++; seconds = (smush_total_seconds % 60) + '' < 10 ? '0' + (smush_total_seconds % 60) : (smush_total_seconds % 60); minutes = parseInt(smush_total_seconds / 60) + '' < 10 ? '0' + parseInt(smush_total_seconds / 60) : parseInt(smush_total_seconds / 60); $('#smush_stats_timer').text(minutes + ":" + seconds); trigger_events(smush_total_seconds); } /** * A timer to run for the duration of the bulk smush operation. * * @param {Number} time_elapsed - time in seconds * * @return void */ function trigger_events(time_elapsed) { if (0 == time_elapsed % 3) { update_smush_stats(time_elapsed); } if (0 == time_elapsed % 60) { if (null != last_ui_update_agent_uid) { heartbeat.cancel_agent(last_ui_update_agent_uid); last_ui_update_agent_uid = null; } heartbeat_agents.push(heartbeat.add_agent({ _wait: false, command: 'updraft_smush_ajax', command_data: {data: {}, subaction: 'process_pending_images'}, callback: function(resp) { handle_response_from_smush_manager(resp, update_view_bulk_smush_progress); } })); } } /** * Updates the UI with stats * * @param {Int} time_elapsed Elapsed time since process start * * @return void */ function update_smush_stats(time_elapsed) { data = { update_ui: true, use_cache: false } var initial_requests = time_elapsed < 5; var agent = heartbeat.add_agent({ _wait: !initial_requests, _keep: false, command: 'updraft_smush_ajax', command_data: {data: data, subaction: 'get_ui_update'}, callback: function(resp) { handle_response_from_smush_manager(resp, update_view_bulk_smush_progress); } }); if (null !== agent) { last_ui_update_agent_uid = agent; heartbeat_agents.push(agent); } } /** * Update images optimization tab view with data returned from images optimization. * * @param {Object} data - meta data returned from task manager * * @return void */ function update_view_show_uncompressed_images(data) { smush_images_grid.html(''); if (!data || !data.hasOwnProperty('unsmushed_images')) return; var unsmushed_images = data.unsmushed_images, pending_tasks = data.pending_tasks, blog_id = 0; if (0 == unsmushed_images.length && 0 == pending_tasks) { smush_images_grid.text(wposmush.all_images_compressed).wrapInner("