background-process.js
23.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/* global WP_Smush */
/**
* Bulk Smush Background Optimization.
*
* @since 3.12.0
*/
import Fetcher from '../utils/fetcher';
import MixPanel from "../mixpanel";
(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;
}
// Cache initial stats.
let boStats = window.wp_smushit_data.bo_stats;
let globalStats = {
count_images: 0,
count_total: 0,
count_resize: 0,
count_skipped: 0,
count_smushed: 0,
savings_bytes: 0,
savings_resize: 0,
size_after: 0,
size_before: 0,
savings_percent: 0,
percent_grade: 'sui-grade-dismissed',
percent_metric: 0,
percent_optimized: 0,
remaining_count: 0,
};
const mixPanel = new MixPanel();
const BO = new BackgroundProcess();
const bulkWrapper = $('.bulk-smush-wrapper');
const bulkRunning = bulkWrapper.querySelector('#wp-smush-running-notice');
const progressBar = bulkWrapper.querySelector('.wp-smush-bulk-progress-bar-wrapper');
const imageScore = $( '#smush-image-score' );
const summarySmush = $('.sui-summary-smush');
const logBulk = $('.smush-final-log .smush-bulk-errors');
const btnCancel = $('.wp-smush-bo-cancel-bulk');
let intervalHandle = 0;
let allErrors = [];
let cancellationInProgress = false;
/**
* 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
*/
const updateGlobalStats = () => {
globalStats = Object.keys(globalStats).reduce(function (newStats, key) {
if (key in window.wp_smushit_data) {
if ( 'percent_grade' === key ) {
newStats[key] = window.wp_smushit_data[key];
} else {
newStats[key] = parseInt( window.wp_smushit_data[key] ) || 0;
}
}
return newStats;
}, {});
};
// Update global stats on reload.
updateGlobalStats();
// Update global stats after re-checking images.
document.addEventListener('wpSmushAfterRecheckImages', function(){
updateGlobalStats();
});
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() {
boStats = Object.assign( boStats, {
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.
this.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 (!boStats.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( allErrors ).length ) {
allErrors = Object.assign( {}, res.data.errors );
}
// Render stats.
this.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 );
}
});
},
/**
* Update progress bar.
* @param {number} processedItems
* @param {number} totalItems
*/
updateProgressBar(processedItems, totalItems) {
const width = Math.floor(processedItems / totalItems * 100) || 0;
// Progress bar label.
progressBar.querySelector('.wp-smush-images-percent').innerHTML = width + '%';
// Progress bar.
progressBar.querySelector('.wp-smush-progress-inner').style.width = width + '%';
// Update processed/total.
const processStateStats = progressBar.querySelector('.sui-progress-state-text');
processStateStats.firstElementChild.innerHTML = processedItems;
processStateStats.lastElementChild.innerHTML = totalItems;
},
hideProgressBar() {
// Hide progress bar.
progressBar.classList.add('sui-hidden');
// Reset progress bar.
this.updateProgressBar(0, boStats.total_items);
},
showProgressBar() {
// Reset progress bar.
this.updateProgressBar(boStats.processed_items, boStats.total_items);
// Show progress bar.
progressBar.classList.remove('sui-hidden');
bulkWrapper.querySelector('.wp-smush-bulk-wrapper').classList.add('sui-hidden');
},
/**
* 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 ( ! this.isChangedStats( newBoStats ) ) {
return false;
}
// Update BO stats.
boStats = Object.assign(boStats, newBoStats);
if (updateGlobal) {
// Update global stats.
globalStats = Object.assign(globalStats, global_stats);
}
// Update Errors.
allErrors = errors;
return true;
},
isChangedStats( newBoStats ) {
const primaryKeys = ['total_items', 'processed_items', 'failed_items', 'is_cancelled', 'is_completed'];
return primaryKeys.some( (key) => {
return newBoStats[key] !== boStats[key];
});
},
cancelBulk() {
// Sync Stats.
this.syncStats(() => {
if (100 === globalStats.percent_optimized) {
// If the last item was getting processed when the user cancelled then the process might have completed
boStats.is_completed = true;
this.onCompletedBulk();
} else {
// Update status of boStats.
boStats.is_cancelled = true;
// Reset and hide progress bar.
this.onFinish();
// Bulk is cancelled, show bulk desc.
bulkWrapper.querySelector('.wp-smush-bulk-wrapper').classList.remove('sui-hidden');
}
mixPanel.trackBulkSmushCancel();
cancellationInProgress = false;
});
},
showCompletedMessage() {
// Render completed message.
// Show completed message.
const processedWrapper = bulkWrapper.querySelector('.wp-smush-all-done');
if ( boStats.failed_items ) {
let completeMessage = wp_smush_msgs.all_failed;
if ( ! this.isFailedAllItems() ) {
completeMessage = wp_smush_msgs.error_in_bulk.replace( '{{smushed}}', boStats.total_items - boStats.failed_items )
.replace('{{total}}', boStats.total_items )
.replace('{{errors}}', boStats.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 boStats.failed_items === boStats.total_items;
},
getNoticeType() {
return this.isFailedAllItems() ? 'warning' : 'success';
},
onCompletedBulk() {
// Reset and hide progress bar.
this.onFinish();
// Bulk is completed, hide bulk desc.
bulkWrapper.querySelector('.wp-smush-bulk-wrapper').classList.add('sui-hidden');
// Show completed message.
this.showCompletedMessage();
this.trackBulkSmushCompleted();
// Reset the progress when we finish so the next smushing starts from zero.
this.updateProgressBar(0, boStats.total_items);
},
getFormattedSavingsBytes: function () {
return WP_Smush.helpers.formatBytes(globalStats.savings_bytes, 1);
},
trackBulkSmushCompleted() {
mixPanel.trackBulkSmushCompleted(
this.getFormattedSavingsBytes(),
globalStats.count_images,
globalStats.percent_optimized,
globalStats.savings_percent
);
},
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 );
this.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) {
const progressMessage = progressBar.querySelector('#wp-smush-running-notice .sui-notice-message p');
progressMessage.innerHTML = res.data.in_process_notice;
}
if (res.success) {
// Update stats.
if ( this.updateStats(res.data, false) ) {
// Update progress bar.
this.updateProgressBar(boStats.processed_items, boStats.total_items);
if (! boStats.is_cancelled && ! boStats.is_completed) {
// Render stats.
this.renderStats();
}
}
if (boStats.is_cancelled && !cancellationInProgress) {
// Cancelled on server side
this.cancelBulk();
} else if (boStats.is_completed) {
this.completeBulk();
}
} else {
WP_Smush.helpers.showNotice( res );
}
});
},
onStart() {
bulkRunning.classList.remove('sui-hidden');
// Disable btn.
startBtn.setAttribute('disabled', '');
// Disable re-check images.
$('.wp-smush-scan').setAttribute('disabled', '');
$('.wp-smush-restore').setAttribute('disabled', '');
// Show upsell cdn.
this.maybeShowCDNUpsellForPreSiteOnStart();
this.setCancelButtonStateToInitial();
},
onFinish() {
// Clear interval.
if (intervalHandle) {
clearInterval(intervalHandle);
intervalHandle = 0;
}
bulkRunning.classList.add('sui-hidden');
// Disable btn.
startBtn.removeAttribute('disabled');
// Reset and hide Progress Bar.
this.hideProgressBar();
// Disable re-check images.
$('.wp-smush-scan').removeAttribute('disabled');
$('.wp-smush-restore').removeAttribute('disabled', '');
// Show upsell cdn.
this.maybeShowCDNUpsellForPreSiteOnCompleted();
},
/**
* Circle progress bar.
*/
renderScoreProgress() {
imageScore.className = imageScore.className.replace( /(^|\s)sui-grade-\S+/g, '' );
imageScore.classList.add( globalStats.percent_grade );
imageScore.dataset.score = globalStats.percent_optimized;
imageScore.querySelector( '.sui-circle-score-label' ).innerHTML = globalStats.percent_optimized;
imageScore
.querySelector( 'circle:last-child' )
.setAttribute( 'style', '--metric-array:' + ( 2.63893782902 * globalStats.percent_metric ) + ' ' + ( 263.893782902 - globalStats.percent_metric ) );
},
/**
* Summary detail - center meta box.
*/
renderSummaryDetail() {
// Total Savings.
// Use decimal is 1 to the same on php.
const formattedSize = this.getFormattedSavingsBytes();
summarySmush.querySelector('.sui-summary-large.wp-smush-stats-human').innerHTML = Math.round( WP_Smush.helpers.getSizeFromString( formattedSize ) );
summarySmush.querySelector('.wp-smush-savings .wp-smush-stats-human').innerHTML = WP_Smush.helpers.getFormatFromString( formattedSize );
// Update the savings percent.
if (globalStats.size_before) {
summarySmush.querySelector('.wp-smush-savings .wp-smush-stats-percent').innerHTML = globalStats.savings_percent;
}
// To total smushed images files.
summarySmush.querySelector('.wp-smush-count-total .wp-smush-total-optimised').innerHTML = globalStats.count_images;
// Images Resized.
if ( globalStats.count_resize ) {
summarySmush.querySelector('.wp-smush-count-resize-total').classList.remove('sui-hidden');
summarySmush.querySelector('.wp-smush-count-resize-total .wp-smush-total-optimised').innerHTML = globalStats.count_resize;
}
// Image Resize Savings.
summarySmush.querySelector('.smush-resize-savings .wp-smush-stats').innerHTML = WP_Smush.helpers.formatBytes( globalStats.savings_resize, 1 );
},
renderBoxSummary() {
// Circle core progress.
this.renderScoreProgress();
// Summary detail.
this.renderSummaryDetail();
},
renderErrors() {
if ( ! Object.keys( allErrors ).length || ! boStats.is_completed ) {
return;
}
const errors = [];
const errorKeys = Object.keys( allErrors );
// Cache error code to avoid double upsell notice.
const cacheUpsellErrorCodes = {};
let showAnimatedUpsell = false;
errorKeys.map( ( image_id, index ) => {
let upsellErrorCode = allErrors[ image_id ].error_code;
if ( index < 5 && 'animated' === upsellErrorCode ) {
showAnimatedUpsell = true;
}
if ( ! ( upsellErrorCode in cacheUpsellErrorCodes ) ) {
cacheUpsellErrorCodes[ upsellErrorCode ] = upsellErrorCode;
} else {
upsellErrorCode = false;
}
errors.push( WP_Smush.helpers.prepareBulkSmushErrorRow(
allErrors[ image_id ].error_msg,
allErrors[ image_id ].file_link,
allErrors[ image_id ].thumbnail ? '<img class="attachment-thumbnail" src='+ allErrors[ image_id ].thumbnail +' />' : 'undefined',
image_id,
'media',
upsellErrorCode,
) );
}
);
logBulk.innerHTML = errors.join('');
logBulk.parentElement.classList.remove('sui-hidden');
logBulk.parentElement.style.display = null;
// Show view all.
if ( errorKeys.length > 1 ) {
$('.smush-bulk-errors-actions').classList.remove('sui-hidden');
}
// Show animated upsell CDN if user disabled CDN and found an animated error in first 5 errors.
if ( showAnimatedUpsell ) {
this.maybeShowCDNActivationNotice();
}
},
renderStats() {
// Render Smush box summary.
this.renderBoxSummary();
// Render Errors.
this.renderErrors();
},
init() {
if (!startBtn) {
return;
}
// Start BO.
startBtn.onclick = this.start.bind(this);
// If BO is running, initial new state.
this.initState();
this.setCancelButtonStateToInitial();
},
setCancelButtonStateToInitial() {
btnCancel.textContent = wp_smush_msgs.cancel;
btnCancel.onclick = this.cancel.bind(this);
},
setCancelButtonStateToStarted() {
btnCancel.textContent = wp_smush_msgs.cancelling;
btnCancel.onclick = () => false;
},
maybeShowCDNActivationNotice () {
if ( ! wp_smush_msgs.smush_cdn_activation_notice ) {
return;
}
WP_Smush.helpers.renderActivationCDNNotice( wp_smush_msgs.smush_cdn_activation_notice );
},
maybeShowCDNUpsellForPreSiteOnStart() {
const upsellCdn = document.querySelector('.wp-smush-upsell-cdn');
if ( upsellCdn ) {
upsellCdn.querySelector('p').innerHTML = wp_smush_msgs.processing_cdn_for_free;
upsellCdn.classList.remove('sui-hidden');
}
},
maybeShowCDNUpsellForPreSiteOnCompleted() {
const upsellCdn = document.querySelector('.wp-smush-upsell-cdn');
if ( upsellCdn ) {
upsellCdn.querySelector('p').innerHTML = wp_smush_msgs.processed_cdn_for_free;
upsellCdn.classList.remove('sui-hidden');
}
}
}
})();
// Run.
BackgroundSmush && BackgroundSmush.init();
})();