This commit is contained in:
2024-05-20 15:37:46 +03:00
commit 00b7dbd0b7
10404 changed files with 3285853 additions and 0 deletions

View File

@ -0,0 +1,20 @@
jQuery(function ($) {
'use strict';
/**
* Handle the Smush Stats link click
*/
$('body').on('click', 'a.smush-stats-details', function (e) {
//If disabled
if ($(this).prop('disabled')) {
return false;
}
// prevent the default action
e.preventDefault();
//Replace the `+` with a `-`
const slide_symbol = $(this).find('.stats-toggle');
$(this).parents().eq(1).find('.smush-stats-wrapper').slideToggle();
slide_symbol.text(slide_symbol.text() == '+' ? '-' : '+');
});
});

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,395 @@
/* global WP_Smush */
/**
* Bulk Smush Background Optimization.
*
* @since 3.12.0
*/
import Fetcher from '../utils/fetcher';
import MixPanel from "../mixpanel";
import SmushProgress from '../common/progressbar';
import {GlobalStats, UpsellManger} from "../common/globalStats";
(function () {
'use strict';
if (!window.wp_smush_msgs) {
return;
}
const $ = document.querySelector.bind(document);
const NO_FREE_LIMITED = 50;
/**
* Handle Background Process.
* @returns
*/
const BackgroundProcess = () => {
return {
handle(action) {
return Fetcher.background[action]();
},
initState() {
return Fetcher.background.initState();
},
}
}
/**
* Background Optimization.
*/
const BackgroundSmush = (() => {
const startBtn = window.wp_smushit_data && window.wp_smushit_data.bo_stats && $('.wp-smush-bo-start');
if (!startBtn) {
return;
}
const mixPanel = MixPanel.getInstance();
const BO = new BackgroundProcess();
const bulkWrapper = $('.bulk-smush-wrapper');
const reScanImagesButton = $('.wp-smush-scan');
let intervalHandle = 0;
let cancellationInProgress = false;
return {
hookStatusChecks() {
if (intervalHandle) {
// Already done
return;
}
let count = 0;
let statusSyncInProgress = false;
let statSyncInProgress = false;
intervalHandle = setInterval(() => {
if (statusSyncInProgress) {
return;
}
statusSyncInProgress = true;
count++;
const statusSynced = this.syncBackgroundStatus();
if (count % 3 === 0) {
// Do a full update every nth time
statusSynced.then(() => {
if (!statSyncInProgress) {
this.syncStats().then(() => {
statSyncInProgress = false;
});
statSyncInProgress = true;
}
});
}
statusSynced.finally(() => {
statusSyncInProgress = false;
});
}, 3 * 1000);
},
resetBOStatsOnStart() {
GlobalStats.setBoStats( {
is_cancelled: false,
is_completed: false,
processed_items: 0,
failed_items: 0,
} );
},
start() {
// Reset boStats.
this.resetBOStatsOnStart();
// Disable UI.
this.onStart();
// Start BO.
BO.handle('start').then((res) => {
if (res.success) {
// Update stats.
const updatedStats = this.updateStats(res.data, false);
// Show progress bar.
this.showProgressBar();
this.hookStatusChecks();
if ( updatedStats ) {
// Render stats.
GlobalStats.renderStats();
}
} else {
WP_Smush.helpers.showNotice( res, {
'showdismiss': true,
'autoclose' : false,
} );
this.cancelBulk();
}
});
},
/**
* Initial state when load the Bulk Smush page while BO is running.
*/
initState() {
if (!GlobalStats.getBoStats().in_processing) {
return;
}
// Disable UI.
this.onStart();
// Start BO.
BO.initState().then((res) => {
if (res.success) {
// Update stats.
this.updateStats(res.data, false);
// Show progress bar.
this.showProgressBar();
this.hookStatusChecks();
// Maybe update errors.
if ( res.data.errors && ! Object.keys( GlobalStats.getErrors() ).length ) {
GlobalStats.setErrors( res.data.errors );
}
// Render stats.
GlobalStats.renderStats();
} else {
WP_Smush.helpers.showNotice( res );
}
});
},
/**
* Cancel.
*/
cancel() {
cancellationInProgress = true;
this.setCancelButtonStateToStarted();
BO.handle('cancel').then((res) => {
if (res.success) {
this.cancelBulk();
} else {
WP_Smush.helpers.showNotice( res );
}
});
},
hideProgressBar() {
// Hide progress bar.
SmushProgress.close().update(0, GlobalStats.getBoStats().total_items);
},
showProgressBar() {
// Reset progress bar.
SmushProgress.update(GlobalStats.getBoStats().processed_items, GlobalStats.getBoStats().total_items);
// Show progress bar.
SmushProgress.show();
},
/**
* Update stats.
* @param {Object} newStats Included increment stats and new BO stats.
* @param updateGlobal
*/
updateStats(newStats, updateGlobal) {
// Make sure we have processed_stats/errors property (not added by default when start).
newStats.global_stats = newStats.global_stats || {};
newStats.errors = newStats.errors || {};
const {
global_stats,
errors,
...newBoStats
} = newStats;
if ( ! GlobalStats.isChangedStats( newBoStats ) ) {
return false;
}
// Update BO stats.
GlobalStats.setBoStats(newBoStats);
if (updateGlobal) {
// Update global stats.
GlobalStats.setGlobalStats(global_stats);
}
// Update Errors.
GlobalStats.setErrors( errors );
return true;
},
cancelBulk() {
// Sync Stats.
this.syncStats(() => {
if (100 === GlobalStats.getGlobalStats().percent_optimized) {
// If the last item was getting processed when the user cancelled then the process might have completed
GlobalStats.setBoStats( {
is_completed: true
} );
this.onCompletedBulk();
} else {
// Update status of boStats.
GlobalStats.setBoStats( {
is_cancelled: true
} );
// Reset and hide progress bar.
this.onFinish();
// Bulk is cancelled, show bulk desc.
SmushProgress.showBulkSmushDescription();
}
mixPanel.trackBulkSmushCancel();
cancellationInProgress = false;
});
},
showCompletedMessage() {
// Render completed message.
// Show completed message.
const processedWrapper = bulkWrapper.querySelector('.wp-smush-all-done');
if ( GlobalStats.getBoStats().failed_items ) {
let completeMessage = wp_smush_msgs.all_failed;
if ( ! this.isFailedAllItems() ) {
completeMessage = wp_smush_msgs.error_in_bulk.replace( '{{smushed}}', GlobalStats.getBoStats().total_items - GlobalStats.getBoStats().failed_items )
.replace('{{total}}', GlobalStats.getBoStats().total_items )
.replace('{{errors}}', GlobalStats.getBoStats().failed_items );
}
processedWrapper.querySelector('p').innerHTML = completeMessage;
processedWrapper.classList.remove('sui-notice-success', 'sui-notice-warning');
const noticeType = this.getNoticeType();
const noticeIcon = 'warning' === noticeType ? 'info' : 'check-tick';
const iconElement = processedWrapper.querySelector('.sui-notice-icon');
processedWrapper.classList.add( 'sui-notice-' + noticeType );
iconElement.classList.remove('sui-icon-check-tick', 'sui-icon-info');
iconElement.classList.add( 'sui-icon-' + noticeIcon );
} else {
processedWrapper.querySelector('p').innerHTML = wp_smush_msgs.all_smushed;
}
processedWrapper.classList.remove('sui-hidden');
},
isFailedAllItems() {
return GlobalStats.getBoStats().failed_items === GlobalStats.getBoStats().total_items;
},
getNoticeType() {
return this.isFailedAllItems() ? 'warning' : 'success';
},
onCompletedBulk() {
// Reset and hide progress bar.
this.onFinish();
// Bulk is completed, hide bulk desc.
SmushProgress.hideBulkSmushDescription();
// Show completed message.
this.showCompletedMessage();
// Reset the progress when we finish so the next smushing starts from zero.
SmushProgress.update(0, GlobalStats.getBoStats().total_items);
},
completeBulk() {
// Sync Stats.
this.syncStats(() => this.onCompletedBulk());
},
syncStats(onComplete = () => false) {
return BO.handle('getStats').then((res) => {
if ( res.success ) {
const responseErrors = res.data.errors || {};
this.updateStats( { global_stats: res.data, errors: responseErrors }, true );
GlobalStats.renderStats();
if ( res.data.content ) {
$('#wp-smush-bulk-content').innerHTML = res.data.content;
}
onComplete();
} else {
WP_Smush.helpers.showNotice( res );
}
}).catch( (error) => console.log('error', error));
},
syncBackgroundStatus() {
return BO.handle('getStatus').then((res) => {
if ((res.data || {}).in_process_notice) {
SmushProgress.setNotice( res.data.in_process_notice );
}
if (res.success) {
// Update stats.
if ( this.updateStats(res.data, false) ) {
// Update progress bar.
SmushProgress.update(GlobalStats.getBoStats().processed_items, GlobalStats.getBoStats().total_items);
if (! GlobalStats.getBoStats().is_cancelled && ! GlobalStats.getBoStats().is_completed) {
// Render stats.
GlobalStats.renderStats();
}
}
if (GlobalStats.getBoStats().is_cancelled && !cancellationInProgress) {
// Cancelled on server side
this.cancelBulk();
} else if (GlobalStats.getBoStats().is_completed) {
this.completeBulk();
}
} else {
WP_Smush.helpers.showNotice( res );
}
});
},
onStart() {
// Disable btn.
startBtn.setAttribute('disabled', '');
// Disable re-check images.
reScanImagesButton && reScanImagesButton.setAttribute('disabled', '');
$('.wp-smush-restore').setAttribute('disabled', '');
// Show upsell cdn.
UpsellManger.maybeShowCDNUpsellForPreSiteOnStart();
this.setCancelButtonStateToInitial();
},
onFinish() {
// Clear interval.
if (intervalHandle) {
clearInterval(intervalHandle);
intervalHandle = 0;
}
// Disable btn.
startBtn.removeAttribute('disabled');
// Reset and hide Progress Bar.
this.hideProgressBar();
// Disable re-check images.
reScanImagesButton && reScanImagesButton.removeAttribute('disabled', '');
$('.wp-smush-restore').removeAttribute('disabled', '');
// Show upsell cdn.
UpsellManger.maybeShowCDNUpsellForPreSiteOnCompleted();
},
init() {
if (!startBtn) {
return;
}
// Start BO.
startBtn.onclick = () => {
const requiredScanMedia = startBtn.classList.contains('wp-smush-scan-and-bulk-smush');
if ( requiredScanMedia ) {
return;
}
this.start();
}
// If BO is running, initial new state.
this.initState();
},
setCancelButtonStateToInitial() {
SmushProgress.setCancelButtonLabel( wp_smush_msgs.cancel );
SmushProgress.setOnCancelCallback( this.cancel.bind(this) );
},
setCancelButtonStateToStarted() {
SmushProgress.setCancelButtonLabel( wp_smush_msgs.cancelling );
SmushProgress.setOnCancelCallback( () => false );
},
}
})();
// Run.
BackgroundSmush && BackgroundSmush.init();
/**
* For globalStats, we will need to update it on reload and after re-checking images,
* and on finish the BO.
* 1. On finish, we handled via BackgroundSmush.syncStats -> BackgroundSmush.updateStats
* 2. On reload or after re-checking images, we need to update globalStats from global variable:
* window.wp_smushit_data
*/
// Update global stats after re-checking images.
document.addEventListener('wpSmushAfterRecheckImages', function(){
GlobalStats.updateGlobalStatsFromSmushScriptData();
});
document.addEventListener('backgroundBulkSmushOnScanCompleted', function(){
if ( ! BackgroundSmush ) {
return;
}
GlobalStats.setBoStats({
in_processing: true,
});
BackgroundSmush.initState();
});
})();

View File

@ -0,0 +1,276 @@
/* global WP_Smush */
/* global ajaxurl */
/* global _ */
import MixPanel from "../mixpanel";
/**
* Bulk restore JavaScript code.
*
* @since 3.2.2
*/
(function () {
'use strict';
/**
* Bulk restore modal.
*
* @since 3.2.2
*/
WP_Smush.restore = {
modal: document.getElementById('smush-restore-images-dialog'),
contentContainer: document.getElementById('smush-bulk-restore-content'),
settings: {
slide: 'start', // start, progress or finish.
success: 0,
errors: [],
},
items: [], // total items, 1 item = 1 step.
success: [], // successful items restored.
errors: [], // failed items.
currentStep: 0,
totalSteps: 0,
/**
* Init module.
*/
init() {
if (!this.modal) {
return;
}
this.settings = {
slide: 'start',
success: 0,
errors: [],
};
this.mixPanel = MixPanel.getInstance();
this.resetModalWidth();
this.renderTemplate();
// Show the modal.
window.SUI.openModal(
'smush-restore-images-dialog',
'wpbody-content',
undefined,
false
);
},
/**
* Update the template, register new listeners.
*/
renderTemplate() {
const template = WP_Smush.onboarding.template('smush-bulk-restore');
const content = template(this.settings);
if (content) {
this.contentContainer.innerHTML = content;
}
this.bindSubmit();
},
/**
* Reset modal width.
*
* @since 3.6.0
*/
resetModalWidth() {
this.modal.style.maxWidth = '460px';
this.modal.querySelector('.sui-box').style.maxWidth = '460px';
},
/**
* Catch "Finish setup wizard" button click.
*/
bindSubmit() {
const confirmButton = this.modal.querySelector(
'button[id="smush-bulk-restore-button"]'
);
const self = this;
if (confirmButton) {
confirmButton.addEventListener('click', function (e) {
e.preventDefault();
self.resetModalWidth();
self.settings = { slide: 'progress' };
self.errors = [];
self.renderTemplate();
self.initScan();
self.mixPanel.track('Bulk Restore Triggered');
});
}
},
/**
* Cancel the bulk restore.
*/
cancel() {
if (
'start' === this.settings.slide ||
'finish' === this.settings.slide
) {
// Hide the modal.
window.SUI.closeModal();
} else {
this.updateProgressBar(true);
window.location.reload();
}
},
/**
* Update progress bar during directory smush.
*
* @param {boolean} cancel Cancel status.
*/
updateProgressBar(cancel = false) {
let progress = 0;
if (0 < this.currentStep) {
progress = Math.min(
Math.round((this.currentStep * 100) / this.totalSteps),
99
);
}
if (progress > 100) {
progress = 100;
}
// Update progress bar
this.modal.querySelector('.sui-progress-text span').innerHTML =
progress + '%';
this.modal.querySelector('.sui-progress-bar span').style.width =
progress + '%';
const statusDiv = this.modal.querySelector(
'.sui-progress-state-text'
);
if (progress >= 90) {
statusDiv.innerHTML = 'Finalizing...';
} else if (cancel) {
statusDiv.innerHTML = 'Cancelling...';
} else {
statusDiv.innerHTML =
this.currentStep +
'/' +
this.totalSteps +
' ' +
'images restored';
}
},
/**
* First step in bulk restore - get the bulk attachment count.
*/
initScan() {
const self = this;
const _nonce = document.getElementById('_wpnonce');
const xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl + '?action=get_image_count', true);
xhr.setRequestHeader(
'Content-type',
'application/x-www-form-urlencoded'
);
xhr.onload = () => {
if (200 === xhr.status) {
const res = JSON.parse(xhr.response);
if ('undefined' !== typeof res.data.items) {
self.items = res.data.items;
self.totalSteps = res.data.items.length;
self.step();
}
} else {
window.console.log(
'Request failed. Returned status of ' + xhr.status
);
}
};
xhr.send('_ajax_nonce=' + _nonce.value);
},
/**
* Execute a scan step recursively
*/
step() {
const self = this;
const _nonce = document.getElementById('_wpnonce');
if (0 < this.items.length) {
const item = this.items.pop();
const xhr = new XMLHttpRequest();
xhr.open('POST', ajaxurl + '?action=restore_step', true);
xhr.setRequestHeader(
'Content-type',
'application/x-www-form-urlencoded'
);
xhr.onload = () => {
this.currentStep++;
if (200 === xhr.status) {
const res = JSON.parse(xhr.response);
const data = ((res || {}).data || {});
if (data.success) {
self.success.push(item);
} else {
self.errors.push({
id: item,
src: data.src || "Error",
thumb: data.thumb,
link: data.link,
});
}
}
self.updateProgressBar();
self.step();
};
xhr.send('item=' + item + '&_ajax_nonce=' + _nonce.value);
} else {
// Finish.
this.settings = {
slide: 'finish',
success: this.success.length,
errors: this.errors,
total: this.totalSteps,
};
self.renderTemplate();
if (0 < this.errors.length) {
this.modal.style.maxWidth = '660px';
this.modal.querySelector('.sui-box').style.maxWidth =
'660px';
}
}
},
};
/**
* Template function (underscores based).
*
* @type {Function}
*/
WP_Smush.restore.template = _.memoize((id) => {
let compiled;
const options = {
evaluate: /<#([\s\S]+?)#>/g,
interpolate: /{{{([\s\S]+?)}}}/g,
escape: /{{([^}]+?)}}(?!})/g,
variable: 'data',
};
return (data) => {
_.templateSettings = options;
compiled =
compiled || _.template(document.getElementById(id).innerHTML);
return compiled(data);
};
});
})();

View File

@ -0,0 +1,149 @@
/* global WP_Smush */
/* global ajaxurl */
/**
* Bulk Smush functionality.
*
* @since 2.9.0 Moved from admin.js
*/
import Smush from '../smush/smush';
import Fetcher from '../utils/fetcher';
import SmushProcess from '../common/progressbar';
( function( $ ) {
'use strict';
WP_Smush.bulk = {
init() {
this.onClickBulkSmushNow();
this.onClickIgnoreImage();
this.onClickIgnoreAllImages();
this.onScanCompleted();
},
onClickBulkSmushNow() {
/**
* Handle the Bulk Smush/Bulk re-Smush button click.
*/
$( '.wp-smush-all' ).on( 'click', function( e ) {
const bulkSmushButton = $(this);
if ( bulkSmushButton.hasClass('wp-smush-scan-and-bulk-smush') ) {
return;
}
e.preventDefault();
WP_Smush.bulk.ajaxBulkSmushStart( bulkSmushButton );
} );
},
ajaxBulkSmushStart( bulkSmushButton ) {
bulkSmushButton = bulkSmushButton || $( '#wp-smush-bulk-content .wp-smush-all' );
// Check for IDs, if there is none (unsmushed or lossless), don't call Smush function.
/** @param {Array} wp_smushit_data.unsmushed */
if (
'undefined' === typeof window.wp_smushit_data ||
( 0 === window.wp_smushit_data.unsmushed.length &&
0 === window.wp_smushit_data.resmush.length )
) {
return false;
}
// Disable re-Smush and scan button.
// TODO: refine what is disabled.
$(
'.wp-resmush.wp-smush-action, .wp-smush-scan, .wp-smush-all:not(.sui-progress-close), a.wp-smush-lossy-enable, button.wp-smush-resize-enable, button#save-settings-button'
).prop( 'disabled', true );
if ( bulkSmushButton.hasClass('wp-smush-resume-bulk-smush') && this.bulkSmush ) {
this.resumeBulkSmush();
return;
}
this.bulkSmush = new Smush( bulkSmushButton, true );
SmushProcess.setOnCancelCallback( () => {
this.bulkSmush.cancelAjax()
}).update( 0, this.bulkSmush.ids.length ).show();
// Show upsell cdn.
this.maybeShowCDNUpsellForPreSiteOnStart();
// Run bulk Smush.
this.bulkSmush.run();
},
resumeBulkSmush() {
SmushProcess.disableExceedLimitMode();
SmushProcess.hideBulkSmushDescription();
this.bulkSmush.onStart();
this.bulkSmush.callAjax();
},
onClickIgnoreImage() {
/**
* Ignore file from bulk Smush.
*
* @since 2.9.0
*/
$( 'body' ).on( 'click', '.smush-ignore-image', function( e ) {
e.preventDefault();
const self = $( this );
self.prop( 'disabled', true );
self.attr( 'data-tooltip' );
self.removeClass( 'sui-tooltip' );
$.post( ajaxurl, {
action: 'ignore_bulk_image',
id: self.attr( 'data-id' ),
_ajax_nonce: wp_smush_msgs.nonce,
} ).done( ( response ) => {
if ( self.is( 'a' ) && response.success && 'undefined' !== typeof response.data.html ) {
if( self.closest('.smush-status-links') ) {
self.closest('.smush-status-links').parent().html( response.data.html );
} else if (e.target.closest( '.smush-bulk-error-row' ) ){
self.addClass('disabled');
e.target.closest( '.smush-bulk-error-row' ).style.opacity = 0.5;
}
}
} );
} );
},
onClickIgnoreAllImages() {
/**
* Ignore file from bulk Smush.
*
* @since 3.12.0
*/
const ignoreAll = document.querySelector('.wp_smush_ignore_all_failed_items');
if ( ignoreAll ) {
ignoreAll.onclick = (e) => {
e.preventDefault();
e.target.setAttribute('disabled','');
e.target.style.cursor = 'progress';
const type = e.target.dataset.type || null;
e.target.classList.remove('sui-tooltip');
Fetcher.smush.ignoreAll(type).then((res) => {
if ( res.success ) {
window.location.reload();
} else {
e.target.style.cursor = 'pointer';
e.target.removeAttribute('disabled');
WP_Smush.helpers.showNotice( res );
}
});
}
}
},
onScanCompleted() {
document.addEventListener('ajaxBulkSmushOnScanCompleted', (e) => {
this.ajaxBulkSmushStart();
});
},
maybeShowCDNUpsellForPreSiteOnStart: () => {
// Show upsell cdn.
const upsell_cdn = document.querySelector('.wp-smush-upsell-cdn');
if ( upsell_cdn ) {
upsell_cdn.classList.remove('sui-hidden');
}
}
};
WP_Smush.bulk.init();
} )( jQuery );

View File

@ -0,0 +1,279 @@
/* global WP_Smush */
/* global ajaxurl */
/**
* Directory Smush module JavaScript code.
*
* @since 2.8.1 Separated from admin.js into dedicated file.
*/
import { createTree } from 'jquery.fancytree';
import Scanner from '../smush/directory-scanner';
( function( $ ) {
'use strict';
WP_Smush.directory = {
selected: [],
tree: [],
wp_smush_msgs: [],
triggered: false,
init() {
const self = this,
progressDialog = $( '#wp-smush-progress-dialog' );
let totalSteps = 0,
currentScanStep = 0;
// Make sure directory smush vars are set.
if ( typeof window.wp_smushit_data.dir_smush !== 'undefined' ) {
totalSteps = window.wp_smushit_data.dir_smush.totalSteps;
currentScanStep =
window.wp_smushit_data.dir_smush.currentScanStep;
}
// Init image scanner.
this.scanner = new Scanner( totalSteps, currentScanStep );
/**
* Smush translation strings.
*
* @param {Array} wp_smush_msgs
*/
this.wp_smush_msgs = window.wp_smush_msgs || {};
/**
* Open the "Select Smush directory" modal.
*/
$( 'button.wp-smush-browse, a#smush-directory-open-modal' ).on(
'click',
function( e ) {
e.preventDefault();
if ( $( e.currentTarget ).hasClass( 'wp-smush-browse' ) ) {
// Hide all the notices.
$( 'div.wp-smush-scan-result div.wp-smush-notice' ).hide();
// Remove notice.
$( 'div.wp-smush-info' ).remove();
}
window.SUI.openModal(
'wp-smush-list-dialog',
e.currentTarget,
$(
'#wp-smush-list-dialog .sui-box-header [data-modal-close]'
)[0],
true
);
//Display File tree for Directory Smush
self.initFileTree();
}
);
/**
* Smush images: Smush in Choose Directory modal clicked
*/
$( '#wp-smush-select-dir' ).on( 'click', function( e ) {
e.preventDefault();
$( 'div.wp-smush-list-dialog div.sui-box-body' ).css( {
opacity: '0.8',
} );
$( 'div.wp-smush-list-dialog div.sui-box-body a' ).off(
'click'
);
const button = $( this );
// Display the spinner.
button.addClass('sui-button-onload');
const selectedFolders = self.tree.getSelectedNodes();
const paths = [];
selectedFolders.forEach( function( folder ) {
paths.push( folder.key );
} );
// Send a ajax request to get a list of all the image files
const param = {
action: 'image_list',
smush_path: paths,
image_list_nonce: $(
'input[name="image_list_nonce"]'
).val(),
};
$.post( ajaxurl, param, function( response ) {
if ( response.success ) {
// Close the modal.
window.SUI.closeModal();
self.scanner = new Scanner( response.data, 0 );
self.showProgressDialog( response.data );
self.scanner.scan();
} else {
// Remove the spinner.
button.removeClass('sui-button-onload');
window.SUI.openNotice(
'wp-smush-ajax-notice',
response.data.message,
{ type: 'warning' }
);
}
} );
} );
/**
* Cancel scan.
*/
progressDialog.on(
'click',
'#cancel-directory-smush, #dialog-close-div, .wp-smush-cancel-dir',
function( e ) {
e.preventDefault();
// Display the spinner
$( '.wp-smush-cancel-dir' ).addClass( 'sui-button-onload' );
self.scanner
.cancel()
.done(
() =>
( window.location.href =
self.wp_smush_msgs.directory_url )
);
}
);
/**
* Continue scan.
*/
progressDialog.on(
'click',
'.sui-icon-play, .wp-smush-resume-scan',
function( e ) {
e.preventDefault();
self.scanner.resume();
}
);
/**
* Check to see if we should open the directory module.
* Used to redirect from dashboard page.
*
* @since 3.8.6
*/
const queryString = window.location.search;
const urlParams = new URLSearchParams( queryString );
if ( urlParams.has( 'start' ) && ! this.triggered ) {
this.triggered = true;
$( 'button.wp-smush-browse' ).trigger( 'click' );
}
},
/**
* Init fileTree.
*/
initFileTree() {
const self = this,
smushButton = $( 'button#wp-smush-select-dir' ),
ajaxSettings = {
type: 'GET',
url: ajaxurl,
data: {
action: 'smush_get_directory_list',
list_nonce: $( 'input[name="list_nonce"]' ).val(),
},
cache: false,
};
// Object already defined.
if ( Object.entries( self.tree ).length > 0 ) {
return;
}
self.tree = createTree( '.wp-smush-list-dialog .content', {
autoCollapse: true, // Automatically collapse all siblings, when a node is expanded
clickFolderMode: 3, // 1:activate, 2:expand, 3:activate and expand, 4:activate (dblclick expands)
checkbox: true, // Show checkboxes
debugLevel: 0, // 0:quiet, 1:errors, 2:warnings, 3:infos, 4:debug
selectMode: 3, // 1:single, 2:multi, 3:multi-hier
tabindex: '0', // Whole tree behaves as one single control
keyboard: true, // Support keyboard navigation
quicksearch: true, // Navigate to next node by typing the first letters
source: ajaxSettings,
lazyLoad: ( event, data ) => {
data.result = new Promise( function( resolve, reject ) {
ajaxSettings.data.dir = data.node.key;
$.ajax( ajaxSettings )
.done( ( response ) => resolve( response ) )
.fail( reject );
} );
},
loadChildren: ( event, data ) =>
data.node.fixSelection3AfterClick(), // Apply parent's state to new child nodes:
select: () =>
smushButton.prop(
'disabled',
! +self.tree.getSelectedNodes().length
),
init: () => smushButton.prop( 'disabled', true ),
} );
},
/**
* Show progress dialog.
*
* @param {number} items Number of items in the scan.
*/
showProgressDialog( items ) {
// Update items status and show the progress dialog..
$( '.wp-smush-progress-dialog .sui-progress-state-text' ).html(
'0/' + items + ' ' + self.wp_smush_msgs.progress_smushed
);
window.SUI.openModal(
'wp-smush-progress-dialog',
'dialog-close-div',
undefined,
false
);
},
/**
* Update progress bar during directory smush.
*
* @param {number} progress Current progress in percent.
* @param {boolean} cancel Cancel status.
*/
updateProgressBar( progress, cancel = false ) {
if ( progress > 100 ) {
progress = 100;
}
// Update progress bar
$( '.sui-progress-block .sui-progress-text span' ).text(
progress + '%'
);
$( '.sui-progress-block .sui-progress-bar span' ).width(
progress + '%'
);
if ( progress >= 90 ) {
$( '.sui-progress-state .sui-progress-state-text' ).text(
'Finalizing...'
);
}
if ( cancel ) {
$( '.sui-progress-state .sui-progress-state-text' ).text(
'Cancelling...'
);
}
},
};
WP_Smush.directory.init();
}( jQuery ) );

View File

@ -0,0 +1,298 @@
/* global WP_Smush */
/* global ajaxurl */
/* global wp_smush_msgs */
/**
* Helpers functions.
*
* @since 2.9.0 Moved from admin.js
*/
( function() {
'use strict';
WP_Smush.helpers = {
init: () => {},
cacheUpsellErrorCodes: [],
/**
* Convert bytes to human-readable form.
*
* @param {number} a Bytes
* @param {number} b Number of digits
* @return {*} Formatted Bytes
*/
formatBytes: ( a, b ) => {
const thresh = 1024,
units = [ 'KB', 'MB', 'GB', 'TB', 'PB' ];
if ( Math.abs( a ) < thresh ) {
return a + ' B';
}
let u = -1;
do {
a /= thresh;
++u;
} while ( Math.abs( a ) >= thresh && u < units.length - 1 );
return a.toFixed( b ) + ' ' + units[ u ];
},
/**
* Get size from a string.
*
* @param {string} formattedSize Formatter string
* @return {*} Formatted Bytes
*/
getSizeFromString: ( formattedSize ) => {
return formattedSize.replace( /[a-zA-Z]/g, '' ).trim();
},
/**
* Get type from formatted string.
*
* @param {string} formattedSize Formatted string
* @return {*} Formatted Bytes
*/
getFormatFromString: ( formattedSize ) => {
return formattedSize.replace( /[0-9.]/g, '' ).trim();
},
/**
* Stackoverflow: http://stackoverflow.com/questions/1726630/formatting-a-number-with-exactly-two-decimals-in-javascript
*
* @param {number} num
* @param {number} decimals
* @return {number} Number
*/
precise_round: ( num, decimals ) => {
const sign = num >= 0 ? 1 : -1;
// Keep the percentage below 100.
num = num > 100 ? 100 : num;
return (
Math.round( num * Math.pow( 10, decimals ) + sign * 0.001 ) /
Math.pow( 10, decimals )
);
},
/**
* Displays a floating error message using the #wp-smush-ajax-notice container.
*
* @since 3.8.0
*
* @param {string} message
*/
showErrorNotice: ( message ) => {
if ( 'undefined' === typeof message ) {
return;
}
const noticeMessage = `<p>${ message }</p>`,
noticeOptions = {
type: 'error',
icon: 'info',
};
SUI.openNotice( 'wp-smush-ajax-notice', noticeMessage, noticeOptions );
const loadingButton = document.querySelector( '.sui-button-onload' );
if ( loadingButton ) {
loadingButton.classList.remove( 'sui-button-onload' );
}
},
/**
* Reset settings.
*
* @since 3.2.0
*/
resetSettings: () => {
const _nonce = document.getElementById( 'wp_smush_reset' );
const xhr = new XMLHttpRequest();
xhr.open( 'POST', ajaxurl + '?action=reset_settings', true );
xhr.setRequestHeader(
'Content-type',
'application/x-www-form-urlencoded'
);
xhr.onload = () => {
if ( 200 === xhr.status ) {
const res = JSON.parse( xhr.response );
if ( 'undefined' !== typeof res.success && res.success ) {
window.location.href = wp_smush_msgs.smush_url;
}
} else {
window.console.log(
'Request failed. Returned status of ' + xhr.status
);
}
};
xhr.send( '_ajax_nonce=' + _nonce.value );
},
/**
* Prepare error row. Will only allow to hide errors for WP media attachments (not nextgen).
*
* @since 1.9.0
* @since 3.12.0 Moved from Smush.
*
* @param {string} errorMsg Error message.
* @param {string} fileName File name.
* @param {string} thumbnail Thumbnail for image (if available).
* @param {number} id Image ID.
* @param {string} type Smush type: media or netxgen.
* @param {string} errorCode Error code.
*
* @return {string} Row with error.
*/
prepareBulkSmushErrorRow: (errorMsg, fileName, thumbnail, id, type, errorCode) => {
const thumbDiv =
thumbnail && 'undefined' !== typeof thumbnail ?
`<img class="attachment-thumbnail" src="${thumbnail}" />` :
'<i class="sui-icon-photo-picture" aria-hidden="true"></i>';
const editLink = window.wp_smush_msgs.edit_link.replace('{{id}}', id);
fileName =
'undefined' === fileName || 'undefined' === typeof fileName ?
'undefined' :
fileName;
let tableDiv =
`<div class="smush-bulk-error-row" data-error-code="${errorCode}">
<div class="smush-bulk-image-data">
<div class="smush-bulk-image-title">
${ thumbDiv }
<span class="smush-image-name">
<a href="${editLink}">${fileName}</a>
</span>
</div>
<div class="smush-image-error">
${errorMsg}
</div>
</div>`;
if ('media' === type) {
tableDiv +=
`<div class="smush-bulk-image-actions">
<a href="javascript:void(0)" class="sui-tooltip sui-tooltip-constrained sui-tooltip-left smush-ignore-image" data-tooltip="${window.wp_smush_msgs.error_ignore}" data-id="${id}">
${window.wp_smush_msgs.btn_ignore}
</a>
<a class="smush-link-detail" href="${editLink}">
${window.wp_smush_msgs.view_detail}
</a>
</div>`;
}
tableDiv += '</div>';
tableDiv += WP_Smush.helpers.upsellWithError( errorCode );
return tableDiv;
},
cacheUpsellErrorCode( errorCode ) {
this.cacheUpsellErrorCodes.push( errorCode );
},
/**
* Get upsell base on error code.
* @param {string} errorCode Error code.
* @returns {string}
*/
upsellWithError(errorCode) {
if (
!errorCode
|| !window.wp_smush_msgs['error_' + errorCode]
|| this.isUpsellRendered( errorCode )
) {
return '';
}
this.cacheRenderedUpsell( errorCode );
return '<div class="smush-bulk-error-row smush-error-upsell">' +
'<div class="smush-bulk-image-title">' +
'<span class="smush-image-error">' +
window.wp_smush_msgs['error_' + errorCode] +
'</span>' +
'</div></div>';
},
// Do not use arrow function to use `this`.
isUpsellRendered( errorCode ) {
return this.cacheUpsellErrorCodes.includes( errorCode );
},
// Do not use arrow function to use `this`.
cacheRenderedUpsell( errorCode ) {
this.cacheUpsellErrorCodes.push( errorCode );
},
/**
* Get error message from Ajax response or Error.
* @param {Object} resp
*/
getErrorMessage: ( resp ) => {
return resp.message || resp.data && resp.data.message ||
resp.responseJSON && resp.responseJSON.data && resp.responseJSON.data.message ||
window.wp_smush_msgs.generic_ajax_error ||
resp.status && 'Request failed. Returned status of ' + resp.status
},
/**
* Displays a floating message from response,
* using the #wp-smush-ajax-notice container.
*
* @param {Object|string} notice
* @param {Object} noticeOptions
*/
showNotice: function( notice, noticeOptions ) {
let message;
if ( 'object' === typeof notice ) {
message = this.getErrorMessage( notice );
} else {
message = notice;
}
if ( ! message ) {
return;
}
noticeOptions = noticeOptions || {};
noticeOptions = Object.assign({
showdismiss: false,
autoclose: true,
},noticeOptions);
noticeOptions = {
type: noticeOptions.type || 'error',
icon: noticeOptions.icon || ( 'success' === noticeOptions.type ? 'check-tick' : 'info' ),
dismiss: {
show: noticeOptions.showdismiss,
label: window.wp_smush_msgs.noticeDismiss,
tooltip: window.wp_smush_msgs.noticeDismissTooltip,
},
autoclose: {
show: noticeOptions.autoclose
}
};
const noticeMessage = `<p>${ message }</p>`;
SUI.openNotice( 'wp-smush-ajax-notice', noticeMessage, noticeOptions );
return Promise.resolve( '#wp-smush-ajax-notice' );
},
closeNotice() {
window.SUI.closeNotice( 'wp-smush-ajax-notice' );
},
renderActivationCDNNotice: function( noticeMessage ) {
const animatedNotice = document.getElementById('wp-smush-animated-upsell-notice');
if ( animatedNotice ) {
return;
}
const upsellHtml = `<div class="sui-notice sui-notice-info sui-margin-top" id="wp-smush-animated-upsell-notice">
<div class="sui-notice-content">
<div class="sui-notice-message">
<i class="sui-notice-icon sui-icon-info" aria-hidden="true"></i>
<p>${noticeMessage}</p>
</div>
</div>
</div>`;
document.querySelector( '#smush-box-bulk .wp-smush-bulk-wrapper' ).outerHTML += upsellHtml;
}
};
WP_Smush.helpers.init();
}() );

View File

@ -0,0 +1,385 @@
/* global WP_Smush */
/**
* Scan Media Library.
*
*/
import SmushProgress from '../common/progressbar';
import MediaLibraryScanner from '../common/media-library-scanner';
import { GlobalStats } from '../common/globalStats';
( function() {
'use strict';
if ( ! window.wp_smush_msgs ) {
return;
}
const $ = document.querySelector.bind( document );
const existScanProgressBar = $( '.wp-smush-scan-progress-bar-wrapper' );
if ( ! existScanProgressBar ) {
return;
}
const recheckImagesBtn = $( '.wp-smush-scan' );
if ( ! recheckImagesBtn ) {
return;
}
const bulkSmushButton = $( '.wp-smush-bo-start' ) || $( '.wp-smush-bulk-wrapper .wp-smush-all' );
const { __ } = wp.i18n;
class MediaLibraryScannerOnBulkSmush extends MediaLibraryScanner {
constructor() {
super();
this.runBulkSmushOnComplete = false;
this.restoreButton = $( '.wp-smush-restore' );
this.autoBulkSmushNotification = $( '.wp-smush-auto-bulk-smush-notification' );
}
startScanThenBulkSmushOnComplete() {
this.runBulkSmushOnComplete = true;
return this.startScan( true );
}
onStart() {
this.hideRecheckNotice();
this.disableRelatedButtons();
this.setRecheckImagesButtonOnLoad();
this.toggleBulkSmushBoxContent();
return this;
}
onStartFailure( response ) {
super.onStartFailure( response );
this.revertRelatedButtons();
}
onCloseProgressBar() {
this.maybeHideAutoBulkSmushNotification();
}
disableRelatedButtons() {
this.restoreButton.setAttribute( 'disabled', true );
if ( bulkSmushButton ) {
bulkSmushButton.setAttribute( 'disabled', true );
this.setInnerText( bulkSmushButton, __( 'Waiting for Re-check to finish', 'wp-smushit' ) );
}
}
revertRelatedButtons() {
if ( bulkSmushButton ) {
bulkSmushButton.removeAttribute( 'disabled' );
this.revertInnerText( bulkSmushButton );
}
this.restoreButton.removeAttribute( 'disabled' );
this.revertRecheckImagesButton();
return this;
}
setRecheckImagesButtonOnLoad() {
// recheckImagesBtn.classList.add( 'sui-button-onload' );
this.disableRecheckImagesButton();
this.setInnerText( recheckImagesBtn.querySelector( '.wp-smush-inner-text' ), __( 'Checking Images', 'wp-smushit' ) );
}
disableRecheckImagesButton() {
recheckImagesBtn.setAttribute( 'disabled', true );
}
revertRecheckImagesButton() {
// recheckImagesBtn.classList.remove( 'sui-button-onload' );
recheckImagesBtn.removeAttribute( 'disabled' );
this.revertInnerText( recheckImagesBtn.querySelector( '.wp-smush-inner-text' ) );
}
beforeUpdateStatus( stats ) {
this.runBulkSmushOnComplete = stats?.optimize_on_scan_completed;
this.maybeShowAutoBulkSmushNotification();
}
onDead( stats ) {
super.onDead( stats );
this.revertRelatedButtons();
this.setRequiredScanForBulkSmushButton();
}
onFinish( stats ) {
const globalStats = stats.global_stats;
super.onFinish( stats );
this.revertRelatedButtons();
this.toggleBulkSmushDescription( globalStats );
if ( globalStats.is_outdated ) {
this.setRequiredScanForBulkSmushButton();
} else {
this.removeScanEventFromBulkSmushButton();
}
this.revertRecheckWarning();
}
onCompleted( stats ) {
const requiredReloadPage = ! bulkSmushButton;
if ( requiredReloadPage ) {
window.location.reload();
return;
}
this.onFinish( stats );
const globalStats = stats.global_stats;
const allImagesSmushed = globalStats.remaining_count < 1;
if ( allImagesSmushed ) {
return;
}
if ( ! this.runBulkSmushOnComplete ) {
this.showRecheckNoticeSuccess();
return;
}
this.runBulkSmushOnComplete = false;
this.triggerBulkSmushEvent( stats );
}
showNotice( stats ) {
if ( ! stats.notice ) {
return;
}
let type = 'success';
if ( 'undefined' !== typeof stats.noticeType ) {
type = stats.noticeType;
}
window.SUI.openNotice(
'wp-smush-ajax-notice',
'<p>' + stats.notice + '</p>',
{ type, icon: 'check-tick' }
);
}
showRecheckNoticeSuccess() {
const recheckNotice = $( '.wp-smush-recheck-images-notice-box' );
if ( ! recheckNotice ) {
return;
}
this.showAnElement( recheckNotice );
this.hideAnElement( recheckNotice.querySelector( '.wp-smush-recheck-images-notice-warning' ) );
this.showAnElement( recheckNotice.querySelector( '.wp-smush-recheck-images-notice-success' ) );
}
showRecheckNoticeWarning() {
const recheckNotice = $( '.wp-smush-recheck-images-notice-box' );
if ( ! recheckNotice ) {
return;
}
this.showAnElement( recheckNotice );
this.hideAnElement( recheckNotice.querySelector( '.wp-smush-recheck-images-notice-success' ) );
this.showAnElement( recheckNotice.querySelector( '.wp-smush-recheck-images-notice-warning' ) );
}
hideRecheckNotice() {
this.hideAnElement( $( '.wp-smush-recheck-images-notice-box' ) );
}
showProgressErrorNoticeOnRecheckNotice() {
const recheckWarningElement = $( '.wp-smush-recheck-images-notice-box .wp-smush-recheck-images-notice-warning' );
if ( ! recheckWarningElement ) {
return;
}
recheckWarningElement.classList.add( 'sui-notice-error' );
recheckWarningElement.classList.remove( 'sui-notice-warning' );
this.setInnerText( recheckWarningElement.querySelector( 'span' ), this.getErrorProgressMessage() );
this.showRecheckNoticeWarning();
}
revertRecheckWarning() {
const recheckWarningElement = $( '.wp-smush-recheck-images-notice-box .wp-smush-recheck-images-notice-warning' );
if ( ! recheckWarningElement ) {
return;
}
recheckWarningElement.classList.add( 'sui-notice-warning' );
recheckWarningElement.classList.remove( 'sui-notice-error' );
this.revertInnerText( recheckWarningElement.querySelector( 'span' ) );
}
triggerBulkSmushEvent( stats ) {
this.disableRecheckImagesButton();
if ( stats.enabled_background_process ) {
this.triggerBackgroundBulkSmushEvent( stats.global_stats );
} else {
this.triggerAjaxBulkSmushEvent( stats.global_stats );
}
}
toggleBulkSmushDescription( globalStats ) {
if ( SmushProgress.isEmptyObject ) {
return;
}
if ( globalStats.remaining_count < 1 ) {
SmushProgress.hideBulkSmushDescription();
SmushProgress.showBulkSmushAllDone();
} else {
SmushProgress.showBulkSmushDescription();
SmushProgress.hideBulkSmushAllDone();
}
}
setRequiredScanForBulkSmushButton() {
bulkSmushButton && bulkSmushButton.classList.add( 'wp-smush-scan-and-bulk-smush' );
}
removeScanEventFromBulkSmushButton() {
bulkSmushButton && bulkSmushButton.classList.remove( 'wp-smush-scan-and-bulk-smush' );
}
triggerBackgroundBulkSmushEvent( globalStats ) {
document.dispatchEvent(
new CustomEvent( 'backgroundBulkSmushOnScanCompleted', {
detail: globalStats
} )
);
}
triggerAjaxBulkSmushEvent( globalStats ) {
document.dispatchEvent(
new CustomEvent( 'ajaxBulkSmushOnScanCompleted', {
detail: globalStats
} )
);
}
onCancelled( stats ) {
this.onFinish( stats );
this.runBulkSmushOnComplete = false;
this.setRequiredScanForBulkSmushButton();
}
maybeShowAutoBulkSmushNotification() {
if (
! this.runBulkSmushOnComplete
) {
return;
}
this.showAnElement( this.autoBulkSmushNotification );
}
maybeHideAutoBulkSmushNotification() {
if (
! this.runBulkSmushOnComplete
) {
return;
}
this.hideAnElement( this.autoBulkSmushNotification );
}
toggleBulkSmushBoxContent() {
GlobalStats.resetAndHideBulkErrors();
this.toggleBulkSmushDescription( GlobalStats.getGlobalStats() );
}
}
const mediaLibScanner = new MediaLibraryScannerOnBulkSmush();
/**
* Event Listeners.
*/
// Background Scan Media Library.
const registerScanMediaLibraryEvent = () => {
if ( ! recheckImagesBtn ) {
return;
}
const canScanInBackground = recheckImagesBtn.classList.contains( 'wp-smush-background-scan' );
if ( ! canScanInBackground ) {
return;
}
recheckImagesBtn.addEventListener( 'click', () => mediaLibScanner.startScan() );
//Check scan is running.
if ( window.wp_smushit_data.media_library_scan?.in_processing ) {
mediaLibScanner.onStart().showProgressBar().autoSyncStatus();
return;
}
if ( window.location.search.includes( 'smush-action=start-scan-media' ) ) {
recheckImagesBtn.click();
const removeScanActionFromURLAddress = () => {
const cleanedURL = window.location.href.replace( '&smush-action=start-scan-media', '' );
window.history.pushState( null, null, cleanedURL );
};
removeScanActionFromURLAddress();
}
};
registerScanMediaLibraryEvent();
/**
* Recheck Images Notice events.
*/
const registerEventsRelatedRecheckImagesNotice = () => {
const recheckImagesNotice = $( '.wp-smush-recheck-images-notice-box' );
if ( ! recheckImagesNotice || ! recheckImagesBtn ) {
return;
}
const triggerBackgroundScanImagesLink = recheckImagesNotice.querySelector( '.wp-smush-trigger-background-scan' );
if ( triggerBackgroundScanImagesLink ) {
triggerBackgroundScanImagesLink.onclick = ( e ) => {
e.preventDefault();
recheckImagesBtn.click();
};
if ( window.wp_smushit_data.media_library_scan?.is_dead ) {
mediaLibScanner.showProgressErrorNoticeOnRecheckNotice();
} else if( window.wp_smushit_data.is_outdated ) {
mediaLibScanner.showRecheckNoticeWarning();
}
}
const triggerBulkSmush = recheckImagesNotice.querySelector( '.wp-smush-trigger-bulk-smush' );
if ( triggerBulkSmush && bulkSmushButton ) {
triggerBulkSmush.onclick = ( e ) => {
e.preventDefault();
recheckImagesNotice.classList.add( 'sui-hidden' );
bulkSmushButton.click();
};
}
const dismissNotices = recheckImagesNotice.querySelectorAll( 'button.sui-button-icon' );
if ( dismissNotices ) {
dismissNotices.forEach( ( dismissNotice ) => {
dismissNotice.onclick = ( e ) => {
dismissNotice.closest( '.sui-recheck-images-notice' ).classList.add( 'sui-hidden' );
};
} );
}
document.addEventListener( 'onSavedSmushSettings', function( e ) {
if ( ! e?.detail?.is_outdated_stats ) {
return;
}
mediaLibScanner.setRequiredScanForBulkSmushButton();
recheckImagesNotice.classList.remove( 'sui-hidden' );
recheckImagesNotice.querySelector( '.wp-smush-recheck-images-notice-success' ).classList.add( 'sui-hidden' );
recheckImagesNotice.querySelector( '.wp-smush-recheck-images-notice-warning' ).classList.remove( 'sui-hidden' );
} );
};
registerEventsRelatedRecheckImagesNotice();
// Scan and Bulk Smush.
const registerScanAndBulkSmushEvent = () => {
if ( ! bulkSmushButton ) {
return;
}
const handleScanAndBulkSmush = ( e ) => {
const shouldRunScan = bulkSmushButton.classList.contains( 'wp-smush-scan-and-bulk-smush' );
if ( ! shouldRunScan ) {
return;
}
e.preventDefault();
mediaLibScanner.startScanThenBulkSmushOnComplete();
};
bulkSmushButton.addEventListener( 'click', handleScanAndBulkSmush );
};
registerScanAndBulkSmushEvent();
}() );

View File

@ -0,0 +1,63 @@
/* global WP_Smush */
/**
* Scan Media Library.
*
*/
import MediaLibraryScanner from '../common/media-library-scanner';
( function() {
'use strict';
if ( ! window.wp_smush_msgs ) {
return;
}
const $ = document.querySelector.bind( document );
const existScanProgressBar = $( '.wp-smush-scan-progress-bar-wrapper' );
if ( ! existScanProgressBar ) {
return;
}
const recheckImagesBtn = $( '.wp-smush-scan' );
if ( recheckImagesBtn ) {
return;
}
//Check scan is running.
const is_scan_running = window.wp_smushit_data.media_library_scan?.in_processing;
if ( ! is_scan_running ) {
return;
}
const { __ } = wp.i18n;
class mediaLibraryScannerOnDashboard extends MediaLibraryScanner {
constructor() {
super();
this.bulkSmushLink = $( '.wp-smush-bulk-smush-link' );
}
onShowProgressBar() {
this.disableBulkSmushLink();
}
onCloseProgressBar() {
this.revertBulkSmushLink();
}
disableBulkSmushLink() {
if ( ! this.bulkSmushLink ) {
return;
}
this.bulkSmushLink.setAttribute( 'disabled', true );
this.setInnerText( this.bulkSmushLink, __( 'Waiting for Re-check to finish', 'wp-smushit' ) );
}
revertBulkSmushLink() {
if ( ! this.bulkSmushLink ) {
return;
}
this.bulkSmushLink.removeAttribute( 'disabled' );
this.revertInnerText( this.bulkSmushLink );
}
}
( new mediaLibraryScannerOnDashboard() ).showProgressBar().autoSyncStatus();
}() );

View File

@ -0,0 +1,52 @@
import Smush from '../smush/smush';
import SmushProcess from '../common/progressbar';
(function($) {
$(function() {
/** Handle NextGen Gallery smush button click **/
$('body').on('click', '.wp-smush-nextgen-send', function (e) {
// prevent the default action
e.preventDefault();
new Smush($(this), false, 'nextgen');
});
/** Handle NextGen Gallery Bulk smush button click **/
$('body').on('click', '.wp-smush-nextgen-bulk', function (e) {
// prevent the default action
e.preventDefault();
// Remove existing Re-Smush notices.
// TODO: REMOVE re-smush-notice since no longer used.
$('.wp-smush-resmush-notice').remove();
//Check for ids, if there is none (Unsmushed or lossless), don't call smush function
if (
'undefined' === typeof wp_smushit_data ||
(wp_smushit_data.unsmushed.length === 0 &&
wp_smushit_data.resmush.length === 0)
) {
return false;
}
const bulkSmush = new Smush( $(this), true, 'nextgen' );
SmushProcess.setOnCancelCallback( () => {
bulkSmush.cancelAjax();
}).update( 0, bulkSmush.ids.length ).show();
jQuery('.wp-smush-all, .wp-smush-scan').prop('disabled', true);
$('.wp-smush-notice.wp-smush-remaining').hide();
// Run bulk Smush.
bulkSmush.run();
})
.on('click', '.wp-smush-trigger-nextgen-bulk', function(e){
e.preventDefault();
const bulkSmushButton = $('.wp-smush-nextgen-bulk');
if ( bulkSmushButton.length ) {
bulkSmushButton.trigger('click');
SUI.closeNotice( 'wp-smush-ajax-notice' );
}
});
});
}(window.jQuery));

View File

@ -0,0 +1,81 @@
/* global ajaxurl */
/* global wp_smush_msgs */
( function( $ ) {
'use strict';
const s3alert = $( '#wp-smush-s3support-alert' );
/**
* S3 support alert.
*
* @since 3.6.2 Moved from class-s3.php
*/
if ( s3alert.length ) {
const noticeOptions = {
type: 'warning',
icon: 'info',
dismiss: {
show: true,
label: wp_smush_msgs.noticeDismiss,
tooltip: wp_smush_msgs.noticeDismissTooltip,
},
};
window.SUI.openNotice(
'wp-smush-s3support-alert',
s3alert.data( 'message' ),
noticeOptions
);
}
// Dismiss S3 support alert.
s3alert.on( 'click', 'button', () => {
$.post( ajaxurl,
{
action: 'dismiss_s3support_alert',
_ajax_nonce: window.wp_smush_msgs.nonce,
}
);
} );
// Remove API message.
$( '#wp-smush-api-message button.sui-button-icon' ).on( 'click', function( e ) {
e.preventDefault();
const notice = $( '#wp-smush-api-message' );
notice.slideUp( 'slow', function() {
notice.remove();
} );
$.post( ajaxurl,
{
action: 'hide_api_message',
_ajax_nonce: window.wp_smush_msgs.nonce,
}
);
} );
// Hide the notice after a CTA button was clicked
function removeNotice( e ) {
const $notice = $( e.currentTarget ).closest( '.smush-notice' );
$notice.fadeTo( 100, 0, () =>
$notice.slideUp( 100, () => $notice.remove() )
);
}
// Only used for the Dashboard notification for now.
$( '.smush-notice .smush-notice-act' ).on( 'click', ( e ) => {
removeNotice( e );
} );
// Dismiss the update notice.
$( '.wp-smush-update-info' ).on( 'click', '.notice-dismiss', ( e ) => {
e.preventDefault();
removeNotice( e );
$.post( ajaxurl,
{
action: 'dismiss_update_info',
_ajax_nonce: window.wp_smush_msgs.nonce,
}
);
} );
}( jQuery ) );

View File

@ -0,0 +1,378 @@
/* global WP_Smush */
/* global ajaxurl */
/**
* Modals JavaScript code.
*/
( function() {
'use strict';
/**
* Onboarding modal.
*
* @since 3.1
*/
WP_Smush.onboarding = {
membership: 'free', // Assume free by default.
onboardingModal: document.getElementById( 'smush-onboarding-dialog' ),
first_slide: 'usage',
settings: {
first: true,
last: false,
slide: 'usage',
value: false,
},
selection: {
usage: false,
auto: true,
lossy: true,
strip_exif: true,
original: false,
lazy_load: true,
},
contentContainer: document.getElementById( 'smush-onboarding-content' ),
onboardingSlides: [
'usage',
'auto',
'lossy',
'strip_exif',
'original',
'lazy_load',
],
touchX: null,
touchY: null,
recheckImagesLink: '',
/**
* Init module.
*/
init() {
if ( ! this.onboardingModal ) {
return;
}
const dialog = document.getElementById( 'smush-onboarding' );
this.membership = dialog.dataset.type;
this.recheckImagesLink = dialog.dataset.ctaUrl;
if ( 'pro' !== this.membership ) {
this.onboardingSlides = [
'usage',
'auto',
'lossy',
'strip_exif',
'lazy_load',
];
}
if ( 'false' === dialog.dataset.tracking ) {
this.onboardingSlides.pop();
}
this.renderTemplate();
// Skip setup.
const skipButton = this.onboardingModal.querySelector(
'.smush-onboarding-skip-link'
);
if ( skipButton ) {
skipButton.addEventListener( 'click', this.skipSetup.bind( this ) );
}
// Show the modal.
window.SUI.openModal(
'smush-onboarding-dialog',
'wpcontent',
undefined,
false
);
},
/**
* Get swipe coordinates.
*
* @param {Object} e
*/
handleTouchStart( e ) {
const firstTouch = e.touches[ 0 ];
this.touchX = firstTouch.clientX;
this.touchY = firstTouch.clientY;
},
/**
* Process swipe left/right.
*
* @param {Object} e
*/
handleTouchMove( e ) {
if ( ! this.touchX || ! this.touchY ) {
return;
}
const xUp = e.touches[ 0 ].clientX,
yUp = e.touches[ 0 ].clientY,
xDiff = this.touchX - xUp,
yDiff = this.touchY - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {
if ( xDiff > 0 ) {
if ( false === WP_Smush.onboarding.settings.last ) {
WP_Smush.onboarding.next( null, 'next' );
}
} else if ( false === WP_Smush.onboarding.settings.first ) {
WP_Smush.onboarding.next( null, 'prev' );
}
}
this.touchX = null;
this.touchY = null;
},
/**
* Update the template, register new listeners.
*
* @param {string} directionClass Accepts: fadeInRight, fadeInLeft, none.
*/
renderTemplate( directionClass = 'none' ) {
// Grab the selected value.
const input = this.onboardingModal.querySelector(
'input[type="checkbox"]'
);
if ( input ) {
this.selection[ input.id ] = input.checked;
}
const template = WP_Smush.onboarding.template( 'smush-onboarding' );
const content = template( this.settings );
if ( content ) {
this.contentContainer.innerHTML = content;
if ( 'none' === directionClass ) {
this.contentContainer.classList.add( 'loaded' );
} else {
this.contentContainer.classList.remove( 'loaded' );
this.contentContainer.classList.add( directionClass );
setTimeout( () => {
this.contentContainer.classList.add( 'loaded' );
this.contentContainer.classList.remove(
directionClass
);
}, 600 );
}
}
this.onboardingModal.addEventListener(
'touchstart',
this.handleTouchStart,
false
);
this.onboardingModal.addEventListener(
'touchmove',
this.handleTouchMove,
false
);
this.bindSubmit();
},
/**
* Catch "Finish setup wizard" button click.
*/
bindSubmit() {
const submitButton = this.onboardingModal.querySelector(
'button[type="submit"]'
);
const self = this;
if ( submitButton ) {
submitButton.addEventListener( 'click', function( e ) {
e.preventDefault();
// Because we are not rendering the template, we need to update the last element value.
const input = self.onboardingModal.querySelector(
'input[type="checkbox"]'
);
if ( input ) {
self.selection[ input.id ] = input.checked;
}
const _nonce = document.getElementById(
'smush_quick_setup_nonce'
);
const xhr = new XMLHttpRequest();
xhr.open( 'POST', ajaxurl + '?action=smush_setup', true );
xhr.setRequestHeader(
'Content-type',
'application/x-www-form-urlencoded'
);
xhr.onload = () => {
if ( 200 === xhr.status ) {
self.onFinishingSetup();
} else {
window.console.log(
'Request failed. Returned status of ' +
xhr.status
);
}
};
xhr.send(
'smush_settings=' +
JSON.stringify( self.selection ) +
'&_ajax_nonce=' +
_nonce.value
);
} );
}
},
onFinishingSetup() {
this.onFinish();
this.startRecheckImages();
},
onFinish() {
window.SUI.closeModal();
},
startRecheckImages() {
if ( ! this.recheckImagesLink ) {
return;
}
window.location.href = this.recheckImagesLink;
},
/**
* Handle navigation.
*
* @param {Object} e
* @param {null|string} whereTo
*/
next( e, whereTo = null ) {
const index = this.onboardingSlides.indexOf( this.settings.slide );
let newIndex = 0;
if ( ! whereTo ) {
newIndex =
null !== e && e.classList.contains( 'next' )
? index + 1
: index - 1;
} else {
newIndex = 'next' === whereTo ? index + 1 : index - 1;
}
const directionClass =
null !== e && e.classList.contains( 'next' )
? 'fadeInRight'
: 'fadeInLeft';
this.settings = {
first: 0 === newIndex,
last: newIndex + 1 === this.onboardingSlides.length, // length !== index
slide: this.onboardingSlides[ newIndex ],
value: this.selection[ this.onboardingSlides[ newIndex ] ],
};
this.renderTemplate( directionClass );
},
/**
* Handle circle navigation.
*
* @param {string} target
*/
goTo( target ) {
const newIndex = this.onboardingSlides.indexOf( target );
this.settings = {
first: 0 === newIndex,
last: newIndex + 1 === this.onboardingSlides.length, // length !== index
slide: target,
value: this.selection[ target ],
};
this.renderTemplate();
},
/**
* Skip onboarding experience.
*/
skipSetup() {
const _nonce = document.getElementById( 'smush_quick_setup_nonce' );
const xhr = new XMLHttpRequest();
xhr.open(
'POST',
ajaxurl + '?action=skip_smush_setup&_ajax_nonce=' + _nonce.value
);
xhr.onload = () => {
if ( 200 === xhr.status ) {
this.onSkipSetup();
} else {
window.console.log(
'Request failed. Returned status of ' + xhr.status
);
}
};
xhr.send();
},
onSkipSetup() {
this.onFinish();
},
/**
* Hide new features modal.
* @since 3.7.0
* @since 3.12.2 Add a new parameter redirectUrl
*/
hideUpgradeModal: ( e, button ) => {
e.preventDefault();
button.classList.add( 'wp-smush-link-in-progress' );
const redirectUrl = button?.href;
const xhr = new XMLHttpRequest();
xhr.open( 'POST', ajaxurl + '?action=hide_new_features&_ajax_nonce=' + window.wp_smush_msgs.nonce );
xhr.onload = () => {
window.SUI.closeModal();
button.classList.remove( 'wp-smush-link-in-progress' );
if ( 200 === xhr.status ) {
if ( redirectUrl ) {
window.location.href = redirectUrl;
}
} else {
window.console.log(
'Request failed. Returned status of ' + xhr.status
);
}
};
xhr.send();
},
};
/**
* Template function (underscores based).
*
* @type {Function}
*/
WP_Smush.onboarding.template = _.memoize( ( id ) => {
let compiled;
const options = {
evaluate: /<#([\s\S]+?)#>/g,
interpolate: /{{{([\s\S]+?)}}}/g,
escape: /{{([^}]+?)}}(?!})/g,
variable: 'data',
};
return ( data ) => {
_.templateSettings = options;
compiled =
compiled ||
_.template( document.getElementById( id ).innerHTML );
data.first_slide = WP_Smush.onboarding.first_slide;
return compiled( data );
};
} );
window.addEventListener( 'load', () => WP_Smush.onboarding.init() );
}() );