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
1156 lines (962 loc) · 35.4 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
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* global jQuery, wp, JSON, _customizeSnapshotsSettings */
/* eslint no-magic-numbers: [ "error", { "ignore": [0,1,-1] } ], consistent-this: [ "error", "snapshot" ] */
(function( api, $ ) {
'use strict';
var escKeyCode = 27;
api.Snapshots = api.Class.extend( {
data: {
action: '',
uuid: '',
editLink: '',
title: '',
publishDate: '',
postStatus: '',
currentUserCanPublish: true,
initialServerDate: '',
initialServerTimestamp: 0,
initialClientTimestamp: 0,
i18n: {},
dirty: false
},
uuidParam: 'customize_changeset_uuid',
initialize: function initialize( snapshotsConfig ) {
var snapshot = this;
snapshot.schedule = {};
if ( _.isObject( snapshotsConfig ) ) {
_.extend( snapshot.data, snapshotsConfig );
}
// Set the initial client timestamp.
snapshot.data.initialClientTimestamp = snapshot.dateValueOf();
api.bind( 'ready', function() {
api.state.create( 'snapshot-exists', false );
api.state.create( 'snapshot-saved', true );
api.state.create( 'snapshot-submitted', true );
snapshot.data.uuid = snapshot.data.uuid || api.settings.changeset.uuid;
snapshot.data.title = snapshot.data.title || snapshot.data.uuid;
snapshot.editBoxAutoSaveTriggered = false;
if ( api.state.has( 'changesetStatus' ) && api.state( 'changesetStatus' ).get() ) {
api.state( 'snapshot-exists' ).set( true );
}
snapshot.editControlSettings = new api.Values();
snapshot.editControlSettings.create( 'title', snapshot.data.title );
snapshot.editControlSettings.create( 'date', snapshot.data.publishDate );
api.bind( 'change', function() {
api.state( 'snapshot-submitted' ).set( false );
} );
snapshot.frontendPreviewUrl = new api.Value( api.previewer.previewUrl.get() );
snapshot.frontendPreviewUrl.link( api.previewer.previewUrl );
snapshot.addButtons();
snapshot.editSnapshotUI();
snapshot.prefilterAjax();
api.trigger( 'snapshots-ready', snapshot );
} );
api.bind( 'save', function( request ) {
request.fail( function( response ) {
var id = '#snapshot-dialog-error',
snapshotDialogPublishError = wp.template( 'snapshot-dialog-error' );
if ( response.responseText ) {
// Insert the dialog error template.
if ( 0 === $( id ).length ) {
$( 'body' ).append( snapshotDialogPublishError( {
title: snapshot.data.i18n.publish,
message: api.state( 'snapshot-exists' ).get() ? snapshot.data.i18n.permsMsg.update : snapshot.data.i18n.permsMsg.save
} ) );
}
snapshot.spinner.removeClass( 'is-active' );
$( id ).dialog( {
autoOpen: true,
modal: true
} );
}
} );
return request;
} );
},
/**
* Get state query vars.
*
* @return {{}} Query vars for scroll, device, url, and autofocus.
*/
getStateQueryVars: function() {
var queryVars = {
'autofocus[control]': null,
'autofocus[section]': null,
'autofocus[panel]': null
};
queryVars.scroll = parseInt( api.previewer.scroll, 10 ) || 0;
queryVars.device = api.previewedDevice.get();
queryVars.url = api.previewer.previewUrl.get();
_.find( [ 'control', 'section', 'panel' ], function( constructType ) {
var found = false;
api[ constructType ].each( function( construct ) { // @todo Core needs to support more Backbone methods on wp.customize.Values().
if ( ! found && construct.expanded && construct.expanded.get() ) {
queryVars[ 'autofocus[' + constructType + ']' ] = construct.id;
found = true;
}
} );
return found;
} );
return queryVars;
},
/**
* Update snapshot.
*
* @param {string} status post status.
* @returns {jQuery.promise} Request or promise.
*/
updateSnapshot: function updateSnapshot( status ) {
var snapshot = this, inputDate,
deferred = new $.Deferred(),
request,
requestData = {
status: status
};
if ( snapshot.statusButton && snapshot.statusButton.needConfirm ) {
snapshot.statusButton.disbleButton.set( false );
snapshot.statusButton.updateButtonText( 'confirm-text' );
snapshot.statusButton.needConfirm = false;
return deferred.promise();
}
if ( snapshot.snapshotTitle && snapshot.snapshotTitle.val() && 'publish' !== status ) {
requestData.title = snapshot.editControlSettings( 'title' ).get();
}
if ( ! _.isEmpty( snapshot.editContainer ) && snapshot.isFutureDate() && 'publish' !== status ) {
inputDate = snapshot.getDateFromInputs();
requestData.date = snapshot.formatDate( inputDate );
}
if ( 'future' === status ) {
if ( requestData.date ) {
request = snapshot.sendUpdateSnapshotRequest( requestData );
}
} else {
request = snapshot.sendUpdateSnapshotRequest( requestData );
}
return request ? request : deferred.promise();
},
/**
* Make the AJAX request to update/save a snapshot.
*
* @param {object} options Options.
* @param {string} options.status The post status for the snapshot.
* @return {object} request.
*/
sendUpdateSnapshotRequest: function sendUpdateSnapshotRequest( options ) {
var snapshot = this,
request, data, isPublishStatus;
data = _.extend(
{
status: 'draft'
},
options
);
api.state( 'snapshot-saved' ).set( false );
snapshot.statusButton.disable( true );
snapshot.spinner.addClass( 'is-active' );
request = api.previewer.save( data );
isPublishStatus = 'publish' === data.status;
request.always( function( response ) {
snapshot.spinner.removeClass( 'is-active' );
if ( response.edit_link ) {
snapshot.data.editLink = response.edit_link;
}
if ( response.publish_date ) {
snapshot.data.publishDate = response.publish_date;
}
if ( response.title ) {
snapshot.data.title = response.title;
}
snapshot.data.dirty = false;
} );
request.done( function( response ) {
var url = api.previewer.previewUrl(),
customizeUrl = window.location.href,
savedDelay = 400;
/***
* Delay because api.Posts.updateSettingsQuietly updates the settings after save, which triggers
* api change causing the publish button to get enabled again.
*/
_.delay( function() {
api.state( 'snapshot-saved' ).set( true );
if ( 'pending' === data.status ) {
api.state( 'snapshot-submitted' ).set( true );
}
}, savedDelay );
api.state( 'snapshot-exists' ).set( true );
snapshot.statusButton.disableSelect.set( isPublishStatus );
snapshot.statusButton.disbleButton.set( true );
snapshot.snapshotExpandButton.toggle( ! isPublishStatus );
snapshot.previewLink.toggle( ! isPublishStatus );
snapshot.statusButton.updateButtonText( 'alt-text' );
// 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( 'snapshot-dialog-error' ),
messages = snapshot.data.i18n.errorMsg,
invalidityCount = 0,
dialogElement;
snapshot.statusButton.disableSelect.set( false );
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.
$( id ).dialog( {
autoOpen: true,
modal: true
} );
} );
return request;
},
/**
* Create the snapshot buttons.
*
* @return {void}
*/
addButtons: function addButtons() {
var snapshot = this, setPreviewLinkHref;
snapshot.spinner = $( '#customize-header-actions' ).find( '.spinner' );
snapshot.publishButton = $( '#save' );
snapshot.publishButton.addClass( 'hidden' );
snapshot.statusButton = snapshot.addStatusButton();
snapshot.statusButton.disbleButton.set( true );
if ( api.state( 'changesetStatus' ).get() ) {
if ( 'auto-draft' === api.state( 'changesetStatus' ).get() ) {
snapshot.statusButton.disable( false );
} else {
snapshot.statusButton.updateButtonText( 'alt-text' );
}
} else {
snapshot.statusButton.disable( true );
}
// 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.statusButton.container.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.statusButton.container.after( snapshot.snapshotExpandButton );
if ( ! snapshot.data.editLink ) {
snapshot.snapshotExpandButton.hide();
snapshot.previewLink.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 );
snapshot.previewLink.toggle( exist );
} );
api.bind( 'change', function() {
if ( api.state( 'snapshot-saved' ).get() ) {
snapshot.statusButton.disable( false );
if ( snapshot.statusButton.button.data( 'confirm-text' ) !== snapshot.statusButton.buttonText.get() ) {
snapshot.statusButton.updateButtonText( 'button-text' );
}
if ( snapshot.submitButton ) {
snapshot.submitButton.prop( 'disabled', false );
}
if ( snapshot.saveButton ) {
snapshot.saveButton.prop( 'disabled', false );
}
api.state( 'snapshot-saved' ).set( false );
}
} );
if ( ! snapshot.data.currentUserCanPublish ) {
snapshot.addSubmitButton();
snapshot.addSaveButton();
}
},
/**
* Adds Submit Button when user does not have 'customize_publish' permission.
*
* @return {void}
*/
addSubmitButton: function() {
var snapshot = this, disableSubmitButton;
disableSubmitButton = 'pending' === snapshot.data.postStatus || ! api.state( 'snapshot-exists' ).get();
if ( snapshot.statusButton ) {
snapshot.statusButton.container.hide();
} else {
snapshot.publishButton.hide();
}
snapshot.submitButton = $( $.trim( wp.template( 'snapshot-submit' )( {
buttonText: snapshot.data.i18n.submit
} ) ) );
snapshot.submitButton.prop( 'disabled', disableSubmitButton );
snapshot.submitButton.insertBefore( snapshot.publishButton );
api.state( 'snapshot-submitted' ).bind( function( submitted ) {
snapshot.submitButton.prop( 'disabled', submitted );
} );
snapshot.submitButton.on( 'click', function( event ) {
event.preventDefault();
snapshot.submitButton.prop( 'disabled', true );
if ( snapshot.saveButton ) {
snapshot.saveButton.prop( 'disabled', true );
}
snapshot.updateSnapshot( 'pending' ).fail( function() {
snapshot.submitButton.prop( 'disabled', false );
} );
} );
snapshot.editControlSettings.bind( 'change', function() {
if ( api.state( 'snapshot-saved' ).get() ) {
snapshot.submitButton.prop( 'disabled', false );
}
} );
},
/**
* Adds Save Button when user does not have 'customize_publish' permission.
*
* @return {void}
*/
addSaveButton: function() {
var snapshot = this, disableSaveButton, isSaved;
isSaved = _.contains( [ 'future', 'pending', 'draft' ], api.state( 'changesetStatus' ).get() );
disableSaveButton = isSaved || ! api.state( 'snapshot-exists' ).get();
snapshot.saveButton = $( $.trim( wp.template( 'snapshot-save' )( {
buttonText: isSaved ? snapshot.data.i18n.updateButton : snapshot.data.i18n.saveButton
} ) ) );
snapshot.saveButton.prop( 'disabled', disableSaveButton );
snapshot.saveButton.insertBefore( snapshot.publishButton );
api.state( 'snapshot-submitted' ).bind( function( submitted ) {
if ( submitted ) {
snapshot.saveButton.prop( 'disabled', true );
}
} );
snapshot.saveButton.on( 'click', function( event ) {
event.preventDefault();
snapshot.saveButton.prop( 'disabled', true );
snapshot.submitButton.prop( 'disabled', true );
snapshot.updateSnapshot( 'draft' ).done( function() {
snapshot.saveButton.prop( 'disabled', true );
snapshot.submitButton.prop( 'disabled', false );
snapshot.saveButton.text( snapshot.data.i18n.updateButton );
} ).fail( function() {
snapshot.saveButton.prop( 'disabled', false );
snapshot.submitButton.prop( 'disabled', false );
} );
} );
snapshot.editControlSettings.bind( 'change', function() {
if ( api.state( 'snapshot-saved' ).get() ) {
snapshot.saveButton.prop( 'disabled', false );
}
} );
},
/**
* Renders snapshot schedule and handles it's events.
*
* @returns {void}
*/
editSnapshotUI: function editSnapshotUI() {
var snapshot = this, sliceBegin = 0,
sliceEnd = -2, updateUI, toggleDateNotification;
snapshot.snapshotEditContainerDisplayed = new api.Value( false );
updateUI = function() {
snapshot.populateSetting();
};
// Inject the UI.
if ( _.isEmpty( snapshot.editContainer ) ) {
if ( '0000-00-00 00:00:00' === snapshot.data.publishDate ) {
snapshot.data.publishDate = snapshot.getCurrentTime();
}
// Normalize date with secs set as zeros removed.
snapshot.data.publishDate = snapshot.data.publishDate.slice( sliceBegin, sliceEnd ) + '00';
// Extend the snapshots data object and add the parsed datetime strings.
snapshot.data = _.extend( snapshot.data, snapshot.parseDateTime( snapshot.data.publishDate ) );
// Add the template to the DOM.
snapshot.editContainer = $( $.trim( wp.template( 'snapshot-edit-container' )( snapshot.data ) ) );
snapshot.editContainer.hide().appendTo( $( '#customize-header-actions' ) );
snapshot.dateNotification = snapshot.editContainer.find( '.snapshot-future-date-notification' );
snapshot.countdown = snapshot.editContainer.find( '.snapshot-scheduled-countdown' );
snapshot.dateControl = snapshot.editContainer.find( '.snapshot-control-date' );
if ( snapshot.data.currentUserCanPublish ) {
// Store the date inputs.
snapshot.schedule.inputs = snapshot.editContainer.find( '.date-input' );
snapshot.schedule.inputs.on( 'input', updateUI );
snapshot.schedule.inputs.on( 'blur', function() {
snapshot.populateInputs();
updateUI();
} );
snapshot.updateCountdown();
snapshot.editContainer.find( '.reset-time a' ).on( 'click', function( event ) {
event.preventDefault();
snapshot.updateSnapshotEditControls();
} );
}
if ( snapshot.statusButton && 'future' !== snapshot.statusButton.value.get() ) {
snapshot.countdown.hide();
}
snapshot.snapshotTitle = snapshot.editContainer.find( '#snapshot-title' );
snapshot.snapshotTitle.on( 'input', updateUI );
}
toggleDateNotification = function() {
if ( ! _.isEmpty( snapshot.dateNotification ) ) {
snapshot.dateNotification.toggle( ! snapshot.isFutureDate() );
}
};
// Set up toggling of the schedule container.
snapshot.snapshotEditContainerDisplayed.bind( function( isDisplayed ) {
if ( snapshot.statusButton ) {
snapshot.dateControl.toggle( 'future' === snapshot.statusButton.value.get() );
}
if ( isDisplayed ) {
snapshot.editContainer.stop().slideDown( 'fast' ).attr( 'aria-expanded', 'true' );
snapshot.snapshotExpandButton.attr( 'aria-pressed', 'true' );
snapshot.snapshotExpandButton.prop( 'title', snapshot.data.i18n.collapseSnapshotScheduling );
toggleDateNotification();
} else {
snapshot.editContainer.stop().slideUp( 'fast' ).attr( 'aria-expanded', 'false' );
snapshot.snapshotExpandButton.attr( 'aria-pressed', 'false' );
snapshot.snapshotExpandButton.prop( 'title', snapshot.data.i18n.expandSnapshotScheduling );
}
} );
snapshot.editControlSettings( 'date' ).bind( function() {
toggleDateNotification();
} );
// Toggle schedule container when clicking the button.
snapshot.snapshotExpandButton.on( 'click', function() {
snapshot.snapshotEditContainerDisplayed.set( ! snapshot.snapshotEditContainerDisplayed.get() );
} );
// Collapse the schedule container when Esc is pressed while the button is focused.
snapshot.snapshotExpandButton.on( 'keydown', function( event ) {
if ( escKeyCode === event.which && snapshot.snapshotEditContainerDisplayed.get() ) {
event.stopPropagation();
event.preventDefault();
snapshot.snapshotEditContainerDisplayed.set( false );
}
} );
// Collapse the schedule container when Esc is pressed inside of the schedule container.
snapshot.editContainer.on( 'keydown', function( event ) {
if ( escKeyCode === event.which && snapshot.snapshotEditContainerDisplayed.get() ) {
event.stopPropagation();
event.preventDefault();
snapshot.snapshotEditContainerDisplayed.set( false );
snapshot.snapshotExpandButton.focus();
}
} );
// Collapse the schedule container interacting outside the schedule container.
$( 'body' ).on( 'mousedown', function( event ) {
var isDisplayed = snapshot.snapshotEditContainerDisplayed.get(),
isTargetEditContainer = snapshot.editContainer.is( event.target ) || 0 !== snapshot.editContainer.has( event.target ).length,
isTargetExpandButton = snapshot.snapshotExpandButton.is( event.target );
if ( isDisplayed && ! isTargetEditContainer && ! isTargetExpandButton ) {
snapshot.snapshotEditContainerDisplayed.set( false );
}
} );
snapshot.snapshotEditContainerDisplayed.set( false );
api.state( 'snapshot-saved' ).bind( function( saved ) {
if ( saved && ! snapshot.dirtyEditControlValues ) {
snapshot.updateSnapshotEditControls();
}
} );
api.bind( 'change', function() {
snapshot.data.dirty = true;
snapshot.editContainer.find( 'a.snapshot-edit-link' ).hide();
} );
api.state( 'snapshot-exists' ).bind( function( exists ) {
if ( exists && ! _.isEmpty( snapshot.editContainer ) ) {
snapshot.updateSnapshotEditControls();
} else {
snapshot.snapshotEditContainerDisplayed.set( false );
}
} );
if ( snapshot.statusButton ) {
snapshot.updateSnapshotEditControls();
}
snapshot.autoSaveEditBox();
},
/**
* Auto save the edit box values.
*
* @return {void}
*/
autoSaveEditBox: function() {
var snapshot = this, update,
delay = 2000, status, isValidChangesetStatus, isFutureDateAndStatus;
snapshot.updatePending = false;
snapshot.dirtyEditControlValues = false;
update = _.debounce( function() {
status = snapshot.statusButton.value.get();
isFutureDateAndStatus = 'future' === status && ! snapshot.isFutureDate();
if ( 'publish' === status || isFutureDateAndStatus ) {
snapshot.updatePending = false;
return;
}
snapshot.updatePending = true;
snapshot.editBoxAutoSaveTriggered = true;
snapshot.dirtyEditControlValues = false;
snapshot.updateSnapshot( status ).done( function() {
snapshot.updatePending = snapshot.dirtyEditControlValues;
if ( ! snapshot.updatePending ) {
snapshot.updateSnapshotEditControls();
} else if ( snapshot.dirtyEditControlValues ) {
update();
}
snapshot.dirtyEditControlValues = false;
} ).fail( function() {
snapshot.updatePending = false;
snapshot.dirtyEditControlValues = true;
} );
}, delay );
snapshot.editControlSettings( 'title' ).bind( function() {
snapshot.dirtyEditControlValues = true;
if ( ! snapshot.updatePending ) {
update();
}
} );
snapshot.editControlSettings( 'date' ).bind( function() {
if ( snapshot.isFutureDate() ) {
snapshot.dirtyEditControlValues = true;
if ( ! snapshot.updatePending ) {
update();
}
}
} );
$( window ).on( 'beforeunload.customize-confirm', function() {
if ( snapshot.updatePending || snapshot.dirtyEditControlValues ) {
return snapshot.data.i18n.aysMsg;
}
return undefined;
} );
isValidChangesetStatus = function() {
return _.contains( [ 'future', 'pending', 'draft' ], api.state( 'changesetStatus' ).get() );
};
// @todo Show loader and disable button while auto saving.
api.bind( 'changeset-save', function() {
if ( isValidChangesetStatus() ) {
snapshot.extendPreviewerQuery();
}
} );
api.bind( 'changeset-saved', function() {
if ( 'auto-draft' !== api.state( 'changesetStatus' ).get() ) {
api.state( 'saved' ).set( true ); // Suppress the AYS dialog.
}
});
},
/**
* Get the preview URL with the snapshot UUID attached.
*
* @returns {string} URL.
*/
getSnapshotFrontendPreviewUrl: function getSnapshotFrontendPreviewUrl() {
var snapshot = this, a = document.createElement( 'a' );
a.href = snapshot.frontendPreviewUrl.get();
if ( a.search ) {
a.search += '&';
}
a.search += snapshot.uuidParam + '=' + snapshot.data.uuid;
return a.href;
},
/**
* Updates snapshot schedule with `snapshot.data`.
*
* @return {void}
*/
updateSnapshotEditControls: function updateSnapshotEditControls() {
var snapshot = this,
parsed,
status,
sliceBegin = 0,
sliceEnd = -2;
if ( _.isEmpty( snapshot.editContainer ) ) {
return;
}
status = api.state( 'changesetStatus' ).get();
if ( snapshot.data.currentUserCanPublish ) {
if ( '0000-00-00 00:00:00' === snapshot.data.publishDate || ! status || 'auto-draft' === status ) {
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();
},
/**
* Update the scheduled countdown text.
*
* Hides countdown if post_status is not already future.
* Toggles the countdown if there is no remaining time.
*
* @returns {boolean} True if date inputs are valid.
*/
updateCountdown: function updateCountdown() {
var snapshot = this,
countdownTemplate = wp.template( 'snapshot-scheduled-countdown' ),
dateTimeFromInput = snapshot.getDateFromInputs(),
millisecondsDivider = 1000,
remainingTime;
if ( ! dateTimeFromInput ) {
return false;
}
remainingTime = dateTimeFromInput.valueOf();
remainingTime -= snapshot.dateValueOf( snapshot.getCurrentTime() );
remainingTime = Math.ceil( remainingTime / millisecondsDivider );
if ( 0 < remainingTime ) {
snapshot.countdown.text( countdownTemplate( {
remainingTime: remainingTime
} ) );
snapshot.countdown.show();
} else {
snapshot.countdown.hide();
}
return true;
},
/**
* Get date from inputs.
*
* @returns {Date|null} Date created from inputs or null if invalid date.
*/
getDateFromInputs: function getDateFromInputs() {
var snapshot = this,
template = snapshot.editContainer,
monthOffset = 1,
date;
date = new Date(
parseInt( template.find( '[data-date-input="year"]' ).val(), 10 ),
parseInt( template.find( '[data-date-input="month"]' ).val(), 10 ) - monthOffset,
parseInt( template.find( '[data-date-input="day"]' ).val(), 10 ),
parseInt( template.find( '[data-date-input="hour"]' ).val(), 10 ),
parseInt( template.find( '[data-date-input="minute"]' ).val(), 10 )
);
if ( isNaN( date.valueOf() ) ) {
return null;
}
date.setSeconds( 0 );
return date;
},
/**
* Parse datetime string.
*
* @param {string} datetime Date/Time string.
* @returns {object|null} Returns object containing date components or null if parse error.
*/
parseDateTime: function parseDateTime( datetime ) {
var matches = datetime.match( /^(\d\d\d\d)-(\d\d)-(\d\d) (\d\d):(\d\d):(\d\d)$/ );
if ( ! matches ) {
return null;
}
matches.shift();
return {
year: matches.shift(),
month: matches.shift(),
day: matches.shift(),
hour: matches.shift(),
minute: matches.shift(),
second: matches.shift()
};
},
/**
* Format a Date Object. Returns 'Y-m-d H:i:s' format.
*
* @props http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript#comment33639551_10073699
*
* @param {Date} date A Date object.
* @returns {string} A formatted date String.
*/
formatDate: function formatDate( date ) {
var formattedDate,
yearLength = 4,
nonYearLength = 2,
monthOffset = 1;
formattedDate = ( '0000' + date.getFullYear() ).substr( -yearLength, yearLength );
formattedDate += '-' + ( '00' + ( date.getMonth() + monthOffset ) ).substr( -nonYearLength, nonYearLength );
formattedDate += '-' + ( '00' + date.getDate() ).substr( -nonYearLength, nonYearLength );
formattedDate += ' ' + ( '00' + date.getHours() ).substr( -nonYearLength, nonYearLength );
formattedDate += ':' + ( '00' + date.getMinutes() ).substr( -nonYearLength, nonYearLength );
formattedDate += ':' + ( '00' + date.getSeconds() ).substr( -nonYearLength, nonYearLength );
return formattedDate;
},
/**
* Populate inputs from the setting value, if none of them are currently focused.
*
* @returns {boolean} Whether the inputs were populated.
*/
populateInputs: function populateInputs() {
var snapshot = this, parsed;
if ( snapshot.schedule.inputs.is( ':focus' ) || '0000-00-00 00:00:00' === snapshot.data.publishDate ) {
return false;
}
parsed = snapshot.parseDateTime( snapshot.data.publishDate );
if ( ! parsed ) {
return false;
}
snapshot.schedule.inputs.each( function() {
var input = $( this ),
fieldName = input.data( 'date-input' );
if ( ! $( this ).is( 'select' ) && '' === $( this ).val() ) {
$( this ).val( parsed[fieldName] );
}
} );
return true;
},
/**
* Populate setting value from the inputs.
*
* @returns {void}
*/
populateSetting: function populateSetting() {
var snapshot = this,
date = snapshot.getDateFromInputs(),
scheduled;
snapshot.editControlSettings( 'title' ).set( snapshot.snapshotTitle.val() );
if ( ! date || ! snapshot.data.currentUserCanPublish ) {
return;
}
date.setSeconds( 0 );
scheduled = snapshot.formatDate( date ) !== snapshot.data.publishDate;
snapshot.editControlSettings( 'date' ).set( snapshot.formatDate( date ) );
if ( 'future' === snapshot.statusButton.value.get() ) {
snapshot.updateCountdown();
}
snapshot.editContainer.find( '.reset-time' ).toggle( scheduled );
},
/**
* Check if the schedule date is in the future.
*
* @returns {boolean} True if future date.
*/
isFutureDate: function isFutureDate() {
var snapshot = this,
date = snapshot.getDateFromInputs(),
millisecondsDivider = 1000,
remainingTime;
if ( ! date ) {
return false;
}
remainingTime = snapshot.dateValueOf( date );
remainingTime -= snapshot.dateValueOf( snapshot.getCurrentTime() );
remainingTime = Math.ceil( remainingTime / millisecondsDivider );
return 0 < remainingTime;
},
/**
* Get current date/time in the site's timezone.
*
* Same functionality as the `current_time( 'mysql', false )` function in PHP.
*
* @returns {string} Current datetime string.
*/
getCurrentTime: function getCurrentTime() {
var snapshot = this,
currentDate = new Date( snapshot.data.initialServerDate ),
currentTimestamp = snapshot.dateValueOf(),
timestampDifferential;
timestampDifferential = currentTimestamp - snapshot.data.initialClientTimestamp;
timestampDifferential += snapshot.data.initialClientTimestamp - snapshot.data.initialServerTimestamp;
currentDate.setTime( currentDate.getTime() + timestampDifferential );
return snapshot.formatDate( currentDate );
},
/**
* Get the primitive value of a Date object.
*
* @param {string|Date} dateString The post status for the snapshot.
* @returns {object|string} The primitive value or date object.
*/
dateValueOf: function dateValueOf( dateString ) {
var date;
if ( 'string' === typeof dateString ) {
date = new Date( dateString );
} else if ( dateString instanceof Date ) {
date = dateString;
} else {
date = new Date();
}
return date.valueOf();
},
/**
* Amend the preview query so we can update the snapshot during `changeset_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() );