This repository has been archived by the owner on Dec 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 16
/
customize-snapshots.js
495 lines (418 loc) · 15.3 KB
/
customize-snapshots.js
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
/* global jQuery, wp, _customizeSnapshotsCompatSettings, JSON */
/* eslint consistent-this: ["error", "snapshot"], no-magic-numbers: [ "error", { "ignore": [0,1,2] } ] */
( function( api, $ ) {
'use strict';
api.SnapshotsCompat = api.Snapshots.extend( {
uuidParam: 'customize_snapshot_uuid',
initialize: function initialize( snapshotsConfig ) {
var snapshot = this;
if ( _.isObject( snapshotsConfig ) ) {
_.extend( snapshot.data, snapshotsConfig );
}
window._wpCustomizeControlsL10n.save = snapshot.data.i18n.publish;
window._wpCustomizeControlsL10n.saved = snapshot.data.i18n.published;
api.bind( 'ready', function() {
api.state.create( 'snapshot-exists', snapshot.data.snapshotExists );
snapshot.extendPreviewerQuery();
if ( api.state( 'snapshot-exists' ).get() ) {
api.state( 'saved' ).set( false );
snapshot.resetSavedStateQuietly();
}
} );
// Make sure that saved state is false so that Published button behaves as expected.
api.bind( 'save', function() {
api.state( 'saved' ).set( false );
} );
api.bind( 'change', function() {
api.state( 'snapshot-saved' ).set( false );
} );
api.bind( 'saved', function( response ) {
var url = window.location.href,
updatedUrl,
urlParts;
// Update the UUID.
if ( response.new_customize_snapshot_uuid ) {
snapshot.data.uuid = response.new_customize_snapshot_uuid;
snapshot.previewLink.attr( 'target', snapshot.data.uuid );
}
api.state( 'snapshot-exists' ).set( false );
// Replace the history state with an updated Customizer URL that does not include the Snapshot UUID.
urlParts = url.split( '?' );
if ( history.replaceState && urlParts[1] ) {
updatedUrl = urlParts[0] + '?' + _.filter( urlParts[1].split( '&' ), function( queryPair ) {
return ! /^(customize_snapshot_uuid)=/.test( queryPair );
} ).join( '&' );
updatedUrl = updatedUrl.replace( /\?$/, '' );
if ( updatedUrl !== url ) {
history.replaceState( {}, document.title, updatedUrl );
}
}
} );
api.Snapshots.prototype.initialize.call( snapshot, snapshotsConfig );
},
/**
* Update button text.
*
* @returns {void}
*/
updateButtonText: function updateButtonText() {
var snapshot = this, date = snapshot.getDateFromInputs();
if ( snapshot.isFutureDate() && date && snapshot.data.currentUserCanPublish ) {
snapshot.snapshotButton.text( snapshot.data.i18n.scheduleButton );
} else {
snapshot.snapshotButton.text( api.state( 'snapshot-exists' ).get() ? snapshot.data.i18n.updateButton : snapshot.data.i18n.saveButton );
}
},
/**
* Make the AJAX request to update/save a snapshot.
*
* @param {object} options Options.
* @param {string} options.status The post status for the snapshot.
* @return {void}
*/
sendUpdateSnapshotRequest: function sendUpdateSnapshotRequest( options ) {
var snapshot = this,
spinner = $( '#customize-header-actions' ).find( '.spinner' ),
request, data;
data = _.extend(
{
status: 'draft'
},
api.previewer.query(),
options,
{
nonce: api.settings.nonce.snapshot,
customize_snapshot_uuid: snapshot.data.uuid
}
);
request = wp.ajax.post( 'customize_update_snapshot', data );
spinner.addClass( 'is-active' );
request.always( function( response ) {
spinner.removeClass( 'is-active' );
if ( response.edit_link ) {
snapshot.data.editLink = response.edit_link;
}
if ( response.snapshot_publish_date ) {
snapshot.data.publishDate = response.snapshot_publish_date;
}
if ( response.title ) {
snapshot.data.title = response.title;
}
snapshot.updateSnapshotEditControls();
snapshot.data.dirty = false;
// @todo Remove privateness from _handleSettingValidities in Core.
if ( api._handleSettingValidities && response.setting_validities ) {
api._handleSettingValidities( {
settingValidities: response.setting_validities,
focusInvalidControl: true
} );
}
} );
request.done( function( response ) {
var url = api.previewer.previewUrl(),
regex = new RegExp( '([?&])customize_snapshot_uuid=.*?(&|$)', 'i' ),
notFound = -1,
separator = url.indexOf( '?' ) !== notFound ? '&' : '?',
customizeUrl = window.location.href,
customizeSeparator = customizeUrl.indexOf( '?' ) !== notFound ? '&' : '?';
if ( url.match( regex ) ) {
url = url.replace( regex, '$1customize_snapshot_uuid=' + encodeURIComponent( snapshot.data.uuid ) + '$2' );
} else {
url = url + separator + 'customize_snapshot_uuid=' + encodeURIComponent( snapshot.data.uuid );
}
// Change the save button text to update.
api.state( 'snapshot-exists' ).set( true );
// Replace the history state with an updated Customizer URL that includes the Snapshot UUID.
if ( history.replaceState && ! customizeUrl.match( regex ) ) {
customizeUrl += customizeSeparator + 'customize_snapshot_uuid=' + encodeURIComponent( snapshot.data.uuid );
history.replaceState( {}, document.title, customizeUrl );
}
api.state( 'snapshot-saved' ).set( true );
if ( 'pending' === data.status ) {
api.state( 'snapshot-submitted' ).set( true );
}
snapshot.resetSavedStateQuietly();
// Trigger an event for plugins to use.
api.trigger( 'customize-snapshots-update', {
previewUrl: url,
customizeUrl: customizeUrl,
uuid: snapshot.data.uuid,
response: response
} );
} );
request.fail( function( response ) {
var id = 'snapshot-dialog-error',
snapshotDialogShareError = wp.template( id ),
messages = snapshot.data.i18n.errorMsg,
invalidityCount = 0,
dialogElement;
if ( response.setting_validities ) {
invalidityCount = _.size( response.setting_validities, function( validity ) {
return true !== validity;
} );
}
/*
* Short-circuit if there are setting validation errors, since the error messages
* will be displayed with the controls themselves. Eventually, once we have
* a global notification area in the Customizer, we can eliminate this
* short-circuit and instead display the messages in there.
* See https://core.trac.wordpress.org/ticket/35210
*/
if ( invalidityCount > 0 ) {
return;
}
if ( response.errors ) {
messages += ' ' + _.pluck( response.errors, 'message' ).join( ' ' );
}
// Insert the snapshot dialog error template.
dialogElement = $( '#' + id );
if ( ! dialogElement.length ) {
dialogElement = $( snapshotDialogShareError( {
title: snapshot.data.i18n.errorTitle,
message: messages
} ) );
$( 'body' ).append( dialogElement );
}
// Open the dialog.
dialogElement.dialog( {
autoOpen: true,
modal: true
} );
} );
return request;
},
/**
* Amend the preview query so we can update the snapshot during `customize_save`.
*
* @return {void}
*/
extendPreviewerQuery: function extendPreviewerQuery() {
var snapshot = this, originalQuery = api.previewer.query;
api.previewer.query = function() {
var retval = originalQuery.apply( this, arguments );
retval.customizer_state_query_vars = JSON.stringify( snapshot.getStateQueryVars() );
if ( api.state( 'snapshot-exists' ).get() ) {
retval.customize_snapshot_uuid = snapshot.data.uuid;
if ( snapshot.snapshotTitle && snapshot.snapshotTitle.val() ) {
retval.title = snapshot.snapshotTitle.val();
}
}
return retval;
};
},
/**
* Create the snapshot buttons.
*
* @return {void}
*/
addButtons: function addButtons() {
var snapshot = this,
header = $( '#customize-header-actions' ),
templateData = {}, setPreviewLinkHref;
snapshot.publishButton = header.find( '#save' );
snapshot.spinner = header.find( '.spinner' );
snapshot.dirtyScheduleDate = new api.Value();
// Save/update button.
if ( api.state( 'snapshot-exists' ).get() ) {
if ( 'future' === snapshot.data.postStatus ) {
templateData.buttonText = snapshot.data.i18n.scheduleButton;
} else {
templateData.buttonText = snapshot.data.i18n.updateButton;
}
} else {
templateData.buttonText = snapshot.data.i18n.saveButton;
}
snapshot.snapshotButton = $( $.trim( wp.template( 'snapshot-save' )( templateData ) ) );
if ( ! snapshot.data.currentUserCanPublish ) {
snapshot.snapshotButton.attr( 'title', api.state( 'snapshot-exists' ).get() ? snapshot.data.i18n.permsMsg.update : snapshot.data.i18n.permsMsg.save );
}
snapshot.snapshotButton.prop( 'disabled', true );
snapshot.snapshotButton.on( 'click', function( event ) {
var status;
event.preventDefault();
status = snapshot.isFutureDate() ? 'future' : 'draft';
snapshot.snapshotButton.prop( 'disabled', true );
snapshot.updateSnapshot( status ).done( function() {
snapshot.snapshotButton.prop( 'disabled', true );
} ).fail( function() {
snapshot.snapshotButton.prop( 'disabled', false );
} );
} );
snapshot.snapshotButton.insertAfter( snapshot.publishButton );
// Preview link.
snapshot.previewLink = $( $.trim( wp.template( 'snapshot-preview-link' )() ) );
snapshot.previewLink.toggle( api.state( 'snapshot-saved' ).get() );
snapshot.previewLink.attr( 'target', snapshot.data.uuid );
setPreviewLinkHref = _.debounce( function() {
if ( api.state( 'snapshot-exists' ).get() ) {
snapshot.previewLink.attr( 'href', snapshot.getSnapshotFrontendPreviewUrl() );
} else {
snapshot.previewLink.attr( 'href', snapshot.frontendPreviewUrl.get() );
}
} );
snapshot.frontendPreviewUrl.bind( setPreviewLinkHref );
setPreviewLinkHref();
api.state.bind( 'change', setPreviewLinkHref );
api.bind( 'saved', setPreviewLinkHref );
snapshot.snapshotButton.after( snapshot.previewLink );
api.state( 'snapshot-saved' ).bind( function( saved ) {
snapshot.previewLink.toggle( saved );
} );
// Edit button.
snapshot.snapshotExpandButton = $( $.trim( wp.template( 'snapshot-expand-button' )( {} ) ) );
snapshot.snapshotExpandButton.insertAfter( snapshot.snapshotButton );
if ( ! snapshot.data.editLink ) {
snapshot.snapshotExpandButton.hide();
}
api.state( 'change', function() {
snapshot.snapshotExpandButton.toggle( api.state( 'snapshot-saved' ).get() && api.state( 'snapshot-exists' ).get() );
} );
api.state( 'snapshot-exists' ).bind( function( exist ) {
snapshot.snapshotExpandButton.toggle( exist );
} );
api.state( 'snapshot-saved' ).bind( function( saved ) {
snapshot.snapshotButton.prop( 'disabled', saved );
} );
api.state( 'saved' ).bind( function( saved ) {
if ( saved ) {
snapshot.snapshotButton.prop( 'disabled', true );
}
} );
api.bind( 'change', function() {
snapshot.snapshotButton.prop( 'disabled', false );
} );
api.state( 'snapshot-exists' ).bind( function( exists ) {
var buttonText, permsMsg;
if ( exists ) {
buttonText = snapshot.data.i18n.updateButton;
permsMsg = snapshot.data.i18n.permsMsg.update;
} else {
buttonText = snapshot.data.i18n.saveButton;
permsMsg = snapshot.data.i18n.permsMsg.save;
}
snapshot.snapshotButton.text( buttonText );
if ( ! snapshot.data.currentUserCanPublish ) {
snapshot.snapshotButton.attr( 'title', permsMsg );
}
} );
snapshot.editControlSettings.bind( 'change', function() {
snapshot.snapshotButton.prop( 'disabled', false );
snapshot.updateButtonText();
} );
snapshot.dirtyScheduleDate.bind( function( dirty ) {
var date;
if ( dirty ) {
date = snapshot.getDateFromInputs();
if ( ! date || ! snapshot.data.currentUserCanPublish ) {
return;
}
snapshot.snapshotButton.text( snapshot.data.i18n.scheduleButton );
} else {
snapshot.updateButtonText();
}
} );
// Submit for review button.
if ( ! snapshot.data.currentUserCanPublish ) {
snapshot.addSubmitButton();
}
header.addClass( 'button-added' );
},
/**
* Silently update the saved state to be true without triggering the
* changed event so that the AYS beforeunload dialog won't appear
* if no settings have been changed after saving a snapshot. Note
* that it would be better if jQuery's callbacks allowed them to
* disabled and then re-enabled later, for example:
* wp.customize.state.topics.change.disable();
* wp.customize.state( 'saved' ).set( true );
* wp.customize.state.topics.change.enable();
* But unfortunately there is no such enable method.
*
* @return {void}
*/
resetSavedStateQuietly: function resetSavedStateQuietly() {
api.state( 'saved' )._value = true;
},
/**
* Overrides the autoSaveEditBox method used in api.Snapshots
* because we do not auto save in < 4.7.
*
* @inheritdoc
*/
autoSaveEditBox: function autoSaveEditor() {
},
/**
* Renders snapshot schedule and handles it's events.
*
* @returns {void}
*/
editSnapshotUI: function editSnapshotUI() {
var snapshot = this;
api.Snapshots.prototype.editSnapshotUI.call( snapshot );
api.state( 'saved' ).bind( function( saved ) {
if ( saved && ! _.isEmpty( snapshot.editContainer ) ) {
snapshot.data.dirty = false;
snapshot.data.publishDate = snapshot.getCurrentTime();
snapshot.snapshotEditContainerDisplayed.set( false );
snapshot.updateSnapshotEditControls();
}
} );
},
/**
* Updates snapshot schedule with `snapshot.data`.
*
* @return {void}
*/
updateSnapshotEditControls: function updateSnapshotEditControls() {
var snapshot = this, parsed,
sliceBegin = 0,
sliceEnd = -2;
if ( _.isEmpty( snapshot.editContainer ) ) {
return;
}
if ( snapshot.data.currentUserCanPublish ) {
if ( '0000-00-00 00:00:00' === snapshot.data.publishDate ) {
snapshot.data.publishDate = snapshot.getCurrentTime();
}
// Normalize date with seconds removed.
snapshot.data.publishDate = snapshot.data.publishDate.slice( sliceBegin, sliceEnd ) + '00';
parsed = snapshot.parseDateTime( snapshot.data.publishDate );
// Update date controls.
snapshot.schedule.inputs.each( function() {
var input = $( this ),
fieldName = input.data( 'date-input' );
$( this ).val( parsed[fieldName] );
} );
}
snapshot.editContainer.find( 'a.snapshot-edit-link' )
.attr( 'href', snapshot.data.editLink )
.show();
if ( ! _.isEmpty( snapshot.data.title ) ) {
snapshot.snapshotTitle.val( snapshot.data.title );
}
snapshot.populateSetting();
},
/**
* Populate setting value from the inputs.
*
* @returns {void}
*/
populateSetting: function populateSetting() {
var snapshot = this,
date = snapshot.getDateFromInputs(),
scheduled, isDirtyDate;
snapshot.editControlSettings( 'title' ).set( snapshot.snapshotTitle.val() );
if ( ! date || ! snapshot.data.currentUserCanPublish ) {
return;
}
date.setSeconds( 0 );
scheduled = snapshot.formatDate( date ) !== snapshot.data.publishDate;
isDirtyDate = scheduled && snapshot.isFutureDate();
snapshot.dirtyScheduleDate.set( isDirtyDate );
snapshot.editControlSettings( 'date' ).set( snapshot.formatDate( date ) );
snapshot.updateCountdown();
snapshot.editContainer.find( '.reset-time' ).toggle( scheduled );
}
} );
api.snapshotsCompat = new api.SnapshotsCompat( _customizeSnapshotsCompatSettings );
} )( wp.customize, jQuery );