background-process.js
15.5 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
/* 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();
});
})();