This repository has been archived by the owner on Dec 16, 2022. It is now read-only.
/
customize-posts.js
1152 lines (1024 loc) · 37.9 KB
/
customize-posts.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, _, _wpCustomizePostsExports, console */
/* eslint no-magic-numbers: [ "error", { "ignore": [0,1,2,3,4] } ] */
/* eslint-disable consistent-this */
(function( api, $ ) {
'use strict';
var component;
if ( ! api.Posts ) {
api.Posts = {};
}
component = api.Posts;
component.data = {
postTypes: {},
initialServerDate: '',
initialServerTimestamp: 0,
initialClientTimestamp: ( new Date() ).valueOf(),
l10n: {
sectionCustomizeActionTpl: '',
fieldTitleLabel: '',
fieldContentLabel: '',
fieldExcerptLabel: ''
},
postIdInput: null
};
component.fetchedPosts = {};
if ( 'undefined' !== typeof _wpCustomizePostsExports ) {
_.extend( component.data, _wpCustomizePostsExports );
}
api.panelConstructor.posts = component.PostsPanel;
api.sectionConstructor.post = component.PostSection;
api.controlConstructor.post_discussion_fields = api.controlConstructor.dynamic.extend({
initialize: function( id, args ) {
args.params.type = 'post_discussion_fields';
args.params.field_type = 'checkbox';
api.controlConstructor.dynamic.prototype.initialize.call( this, id, args );
}
});
/*
* Create initial post type-specific constructors for panel and sections.
* Note plugins can override the panel and section constructors by making customize-posts a script dependency.
*/
_.each( component.data.postTypes, function( postType ) {
var panelType, sectionType;
panelType = 'posts[' + postType.name + ']';
if ( ! api.panelConstructor[ panelType ] ) {
api.panelConstructor[ panelType ] = api.panelConstructor.posts.extend({
postType: postType
});
}
sectionType = 'post[' + postType.name + ']';
if ( ! api.sectionConstructor[ sectionType ] ) {
api.sectionConstructor[ sectionType ] = api.sectionConstructor.post.extend({
postType: postType
});
}
} );
/**
* Parse post/postmeta setting ID.
*
* @param {string} settingId Setting ID.
* @returns {object|null} Parsed setting or null if error.
*/
component.parseSettingId = function parseSettingId( settingId ) {
var parsed = {}, idParts;
idParts = settingId.replace( /]/g, '' ).split( '[' );
if ( 'post' !== idParts[0] && 'postmeta' !== idParts[0] ) {
return null;
}
parsed.settingType = idParts[0];
if ( 'post' === parsed.settingType && 3 !== idParts.length || 'postmeta' === parsed.settingType && 4 !== idParts.length ) {
return null;
}
parsed.postType = idParts[1];
if ( ! parsed.postType ) {
return null;
}
parsed.postId = parseInt( idParts[2], 10 );
if ( isNaN( parsed.postId ) || parsed.postId <= 0 ) {
return null;
}
if ( 'postmeta' === parsed.settingType ) {
parsed.metaKey = idParts[3];
if ( ! parsed.metaKey ) {
return null;
}
}
return parsed;
};
/**
* Get post URL.
*
* @param {object} params - Query vars.
* @param {number} params.post_id - Post ID.
* @param {string} [params.post_type] - Post type.
* @param {boolean} [params.preview] - Preview.
* @return {string} Preview URL.
*/
component.getPostUrl = function getPostUrl( params ) {
var queryVars, postId;
queryVars = _.clone( params );
postId = parseInt( queryVars.post_id, 10 );
if ( ! postId ) {
throw new Error( 'Missing post_id param.' );
}
delete queryVars.post_id;
if ( queryVars.post_type && 'page' === queryVars.post_type ) {
queryVars.page_id = postId;
} else {
queryVars.p = postId;
}
if ( 'post' === params.post_type || 'page' === params.post_type ) {
delete queryVars.post_type;
}
return api.settings.url.home + '?' + $.param( queryVars );
};
/**
* Get the post preview URL.
*
* @param {object} params - Parameters to configure the preview URL.
* @param {number} params.post_id - Post ID to preview.
* @param {string} [params.post_type] - Post type to preview.
* @return {string} Preview URL.
*/
component.getPreviewUrl = function getPreviewUrl( params ) {
return component.getPostUrl( _.extend( {}, params, { preview: true } ) );
};
/**
* Insert a new stubbed `auto-draft` post.
*
* @param {string} postType Post type to create.
* @return {jQuery.promise} Promise resolved with the added section.
*/
component.insertAutoDraftPost = function( postType ) {
var request, deferred = $.Deferred(), done;
request = wp.ajax.post( 'customize-posts-insert-auto-draft', {
'customize-posts-nonce': api.settings.nonce['customize-posts'],
'wp_customize': 'on',
'post_type': postType
} );
/**
* Done inserting auto-draft post.
*
* @param {object} data Data.
* @param {int} data.postId Post ID.
* @param {string} data.postSettingId Post setting ID.
* @param {object} data.settings Setting, mapping setting IDs to setting params for posts/postmeta.
* @returns {void}
*/
done = function doneInsertAutoDraftPost( data ) {
var section, availableItem, availableMenuItemsList, itemTemplate;
component.addPostSettings( data.settings );
if ( ! data.postSettingId || ! api.has( data.postSettingId ) ) {
deferred.reject( 'no_setting' );
return;
}
section = component.addPostSection( data.postSettingId );
if ( ! section ) {
deferred.reject( 'no_section' );
return;
}
// Add new page to dropdown-pages controls.
api.control.each( function( control ) {
var select;
if ( 'dropdown-pages' === control.params.type ) {
select = control.container.find( 'select[name^="_customize-dropdown-pages-"]' );
select.append( new Option( api.Posts.data.l10n.noTitle, data.postId ) );
}
} );
if ( api.section.has( 'static_front_page' ) ) {
api.section( 'static_front_page' ).activate();
}
// Add the new item to the list of available items.
availableItem = new api.Menus.AvailableItemModel( {
'id': 'post-' + data.postId, // Used for available menu item Backbone models.
'title': api.Posts.data.l10n.noTitle,
'type': 'post_type',
'type_label': api.Posts.data.postTypes[ postType ].labels.singular_name,
'object': postType,
'object_id': data.postId,
'url': api.Posts.getPostUrl( { post_id: data.postId, post_type: postType } )
} );
api.Menus.availableMenuItemsPanel.collection.add( availableItem );
availableMenuItemsList = $( '#available-menu-items-post_type-' + postType ).find( '.available-menu-items-list' );
itemTemplate = wp.template( 'available-menu-item' );
availableMenuItemsList.prepend( itemTemplate( availableItem.attributes ) );
deferred.resolve( {
postId: data.postId,
section: section,
setting: api( data.postSettingId )
} );
};
request.done( done );
request.fail( function( response ) {
var error = response || '';
if ( 'undefined' !== typeof response.message ) {
error = response.message;
}
console.error( error );
deferred.reject( error );
} );
return deferred.promise();
};
/**
* Handle receiving customized-posts messages from the preview.
*
* @param {object} data Data from preview.
* @param {boolean} data.isPartial Whether it is a full refresh or partial refresh.
* @param {Array} data.postIds Post IDs previewed.
* @return {void}
*/
component.receivePreviewData = function receivePreviewData( data ) {
var previewerQuery = component.previewedQuery.get();
if ( data.isPartial ) {
previewerQuery = _.clone( previewerQuery );
previewerQuery.postIds = previewerQuery.postIds.concat( data.postIds );
component.previewedQuery.set( previewerQuery );
} else {
component.previewedQuery.set( data );
}
component.ensurePosts( component.previewedQuery.get().postIds );
};
/**
* Gather posts data.
*
* @param {int[]} postIds Post IDs.
* @returns {{}} Mapping of post ID to relevant data about the post.
*/
component.gatherFetchedPostsData = function gatherFetchedPostsData( postIds ) {
var postsData = {};
_.each( postIds, function( postId ) {
var postType, postData, id, setting;
postType = component.fetchedPosts[ postId ];
if ( 'nav_menu_item' === postType ) {
id = 'nav_menu_item[' + String( postId ) + ']';
setting = api( id );
postData = {
postType: postType,
customizeId: id,
section: setting ? api.section( 'nav_menu[' + String( setting.get().nav_menu_term_id ) + ']' ) : null,
setting: setting
};
} else if ( postType ) {
id = 'post[' + postType + '][' + String( postId ) + ']';
postData = {
postType: postType,
customizeId: id,
section: api.section( id ),
setting: api( id )
};
} else {
postData = null;
}
postsData[ postId ] = postData;
} );
return postsData;
};
/**
* Fetch settings for posts and ensure sections are added for the given post IDs.
*
* @param {int[]} postIds Post IDs.
* @returns {jQuery.promise} Promise resolved with an object mapping ids to setting and section.
*/
component.ensurePosts = function ensurePosts( postIds ) {
var request, deferred = $.Deferred(), newPostIds;
newPostIds = _.filter( postIds, function( postId ) {
return ! component.fetchedPosts[ postId ];
} );
if ( 0 === newPostIds.length ) {
deferred.resolve( component.gatherFetchedPostsData( postIds ) );
return deferred;
}
request = wp.ajax.post( 'customize-posts-fetch-settings', {
'customize-posts-nonce': api.settings.nonce['customize-posts'],
'wp_customize': 'on',
'customized': api.previewer.query().customized,
'post_ids': newPostIds
} );
request.done( function( settings ) {
component.addPostSettings( settings );
_.each( settings, function( settingParams, settingId ) {
if ( 'post' === settingParams.type ) {
component.addPostSection( settingId );
}
} );
deferred.resolve( component.gatherFetchedPostsData( postIds ) );
} );
request.fail( function() {
deferred.reject();
} );
return deferred.promise();
};
/**
* Add post settings.
*
* @param {object} settings Mapping of setting IDs to setting params for posts and postmeta.
* @returns {int[]} Post IDs for added settings.
*/
component.addPostSettings = function addPostSettings( settings ) {
var postIds = [];
_.each( settings, function( settingArgs, id ) {
var setting, matches, parsedSettingId = component.parseSettingId( id ), SettingConstructor, settingParams;
if ( ! parsedSettingId ) {
// Special case: make sure the fetch of a nav menu item is recorded so that it is not re-fetched later.
matches = id.match( /^nav_menu_item\[(-?\d+)]$/ );
if ( matches ) {
component.fetchedPosts[ parseInt( matches[1], 10 ) ] = 'nav_menu_item';
}
return;
}
postIds.push( parsedSettingId.postId );
component.fetchedPosts[ parsedSettingId.postId ] = parsedSettingId.postType;
setting = api( id );
if ( ! setting ) {
if ( ! _.isUndefined( api.settingConstructor ) && api.settingConstructor[ settingArgs.type ] ) {
SettingConstructor = api.settingConstructor[ settingArgs.type ];
} else {
SettingConstructor = api.Setting;
}
settingParams = _.extend(
{},
settingArgs,
{
previewer: api.previewer,
dirty: false
}
);
delete settingParams.value;
setting = new SettingConstructor( id, settingArgs.value, settingParams );
api.add( id, setting );
// Mark as dirty and trigger change if setting is pre-dirty; see code in wp.customize.Value.prototype.set().
if ( settingArgs.dirty ) {
setting._dirty = true;
setting.callbacks.fireWith( setting, [ setting.get(), setting.get() ] );
}
/*
* Ensure that the setting gets created in the preview as well. When the post/postmeta settings
* are sent to the preview, this is the point at which the related selective refresh partials
* will also be created.
*/
api.previewer.send( 'customize-posts-setting', _.extend( { id: id }, settingArgs ) );
}
} );
return _.unique( postIds );
};
/**
* Add a section for a post.
*
* @param {string} settingId - Setting ID for post.
* @return {wp.customize.Section|null} Added (or existing) section, or null if not able to be added.
*/
component.addPostSection = function( settingId ) {
var section, parsedSettingId, sectionId, panelId, sectionType, Constructor, htmlParser, postTypeObj, customizeActionTpl;
parsedSettingId = component.parseSettingId( settingId );
if ( ! parsedSettingId || 'post' !== parsedSettingId.settingType ) {
throw new Error( 'Bad setting ID' );
}
postTypeObj = component.data.postTypes[ parsedSettingId.postType ];
if ( ! postTypeObj ) {
if ( 'undefined' !== typeof console && console.error ) {
console.error( 'Unrecognized post type: ' + parsedSettingId.postType );
}
return null;
}
if ( ! postTypeObj.show_in_customizer ) {
return null;
}
sectionType = 'post[' + parsedSettingId.postType + ']';
panelId = 'posts[' + parsedSettingId.postType + ']';
sectionId = 'post[' + parsedSettingId.postType + '][' + String( parsedSettingId.postId ) + ']';
if ( api.section.has( sectionId ) ) {
return api.section( sectionId );
}
Constructor = api.sectionConstructor[ sectionType ] || api.sectionConstructor.post;
customizeActionTpl = postTypeObj.labels.customize_action || component.data.l10n.sectionCustomizeActionTpl;
htmlParser = $( '<div>' ).html( customizeActionTpl.replace( '%s', api.panel( panelId ).params.title ) );
section = new Constructor( sectionId, {
params: {
id: sectionId,
panel: panelId,
post_type: parsedSettingId.postType,
post_id: parsedSettingId.postId,
active: true,
customizeAction: htmlParser.text()
}
});
api.section.add( sectionId, section );
return section;
};
/**
* Emulate sanitize_title_with_dashes().
*
* @todo This can be more verbose, supporting Unicode.
*
* @param {string} title Title
* @returns {string} slug
*/
component.sanitizeTitleWithDashes = function sanitizeTitleWithDashes( title ) {
var slug = $.trim( title ).toLowerCase();
slug = slug.replace( /[^a-z0-9\-_]+/g, '-' );
slug = slug.replace( /--+/g, '-' );
slug = slug.replace( /^-+|-+$/g, '' );
return slug;
};
/**
* Handle purging the trash after Customize `saved`.
*
* @returns {void}
*/
component.purgeTrash = function purgeTrash() {
api.section.each( function( section ) {
if ( section.extended( component.PostSection ) && 'trash' === api( section.id ).get().post_status ) {
section.active.set( false );
section.collapse();
_.each( section.controls(), function( control ) {
control.container.remove();
api.control.remove( control.id );
} );
api.section.remove( section.id );
section.container.remove();
if ( true === component.previewedQuery.get().isSingular ) {
api.previewer.previewUrl( api.settings.url.home );
}
// @todo Also remove all postmeta settings for this post?
api.remove( section.id );
delete component.fetchedPosts[ section.params.post_id ];
if ( 'page' === section.params.post_type ) {
section.removeFromDropdownPagesControls();
}
}
} );
};
/**
* Update settings quietly.
*
* Update all of the settings without causing the overall dirty state to change.
*
* This was originally part of the Customize Setting Validation plugin.
*
* @link https://github.com/xwp/wp-customize-setting-validation/blob/2e5ddc66a870ad7b1aee5f8e414bad4b78e120d2/js/customize-setting-validation.js#L186-L209
*
* @param {object} settingValues Setting IDs mapped to values.
* @return {void}
*/
component.updateSettingsQuietly = function updateSettingsQuietly( settingValues ) {
var wasSaved = api.state( 'saved' ).get();
_.each( settingValues, function( value, settingId ) {
var setting = api( settingId ), wasDirty;
if ( setting && ! _.isEqual( setting.get(), value ) ) {
wasDirty = setting._dirty;
setting.set( value );
setting._dirty = wasDirty;
}
} );
api.state( 'saved' ).set( wasSaved );
};
/**
* Format a Date Object. Returns 'Y-m-d H:i:s' format.
*
* @param {Date} date A Date object.
* @returns {string} A formatted date String.
*/
component.formatDate = function formatDate( date ) {
var formattedDate, yearLength = 4, nonYearLength = 2;
// Props: http://stackoverflow.com/questions/10073699/pad-a-number-with-leading-zeros-in-javascript#comment33639551_10073699
formattedDate = ( '0000' + date.getFullYear() ).substr( -yearLength, yearLength );
formattedDate += '-' + ( '00' + ( date.getMonth() + 1 ) ).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;
};
/**
* Get current date/time in the site's timezone, as does the current_time( 'mysql', false ) function in PHP.
*
* @returns {string} Current datetime string.
*/
component.getCurrentTime = function getCurrentTime() {
var currentDate, currentTimestamp, timestampDifferential;
currentTimestamp = ( new Date() ).valueOf();
currentDate = component.parsePostDate( component.data.initialServerDate );
timestampDifferential = currentTimestamp - component.data.initialClientTimestamp;
timestampDifferential += component.data.initialClientTimestamp - component.data.initialServerTimestamp;
currentDate.setTime( currentDate.getTime() + timestampDifferential );
return component.formatDate( currentDate );
};
/**
* Parse post date string in YYYY-MM-DD HH:MM:SS format (local timezone).
*
* @param {string} postDate Post date string.
* @returns {Date} Parsed date.
*/
component.parsePostDate = function parsePostDate( postDate ) {
var dateParts = _.map( postDate.split( /\D/ ), function( datePart ) {
return parseInt( datePart, 10 );
} );
return new Date( dateParts[0], dateParts[1] - 1, dateParts[2], dateParts[3], dateParts[4], dateParts[5] ); // eslint-disable-line no-magic-numbers
};
/**
* Focus on the control requested from the preview.
*
* If the control doesn't exist yet, try to determine the section it would
* be part of by parsing its ID, and then if that section exists, expand it.
* Once expanded, try finding the control again, since controls for post
* sections may get embedded only once section.contentsEmbedded is resolved.
*
* @param {string} controlId Control ID.
* @return {void}
*/
component.focusControl = function focusControl( controlId ) {
var control, section, postSectionId, matches, postId;
/**
* Attempt focus on the control.
*
* @returns {boolean} Whether the control exists.
*/
function tryFocus() {
control = api.control( controlId );
if ( control ) {
control.focus();
return true;
}
return false;
}
if ( tryFocus() ) {
return;
}
matches = controlId.match( /^post(?:meta)?\[(.+?)]\[(\d+)]/ );
if ( ! matches ) {
return;
}
postId = parseInt( matches[2], 10 );
postSectionId = 'post[' + matches[1] + '][' + String( postId ) + ']';
/**
* Expand and focus on control in section.
*
* @param {component.PostSection} postSection - Section.
* @returns {void}
*/
function sectionResolved( postSection ) {
postSection.expand();
postSection.contentsEmbedded.done( function() {
var ms = 500;
// @todo It is not clear why a delay is needed for focus to work. It could be due to focus failing during animation.
_.delay( tryFocus, ms );
} );
}
section = api.section( postSectionId );
if ( section ) {
sectionResolved( section );
} else {
api.Posts.ensurePosts( [ postId ] ).done( function( data ) {
sectionResolved( data[ postId ].section );
} );
}
};
/**
* Ensure that "edit" and "add" buttons to are added dropdown-pages controls.
*
* @returns {void}
*/
component.ensureButtonsOnDropdownPagesControls = function ensureButtonsOnDropdownPagesControls() {
api.control.each( component.addActionButtonsToDropdownPagesControl );
api.control.bind( 'add', component.addActionButtonsToDropdownPagesControl );
};
/**
* Add "edit" and "add" buttons to are added dropdown-pages controls.
*
* @param {wp.customize.Control} control Control.
* @returns {void}
*/
component.addActionButtonsToDropdownPagesControl = function addActionButtonsToDropdownPagesControl( control ) {
if ( 'dropdown-pages' !== control.params.type ) {
return;
}
control.deferred.embedded.done( function onceDropdownPagesControlEmbedded() {
var inputsTemplate, inputsContainer, select, editButton, createButton, onSelect;
inputsTemplate = wp.template( 'customize-posts-dropdown-pages-inputs' );
inputsContainer = $( inputsTemplate() );
select = control.container.find( 'select' );
select.after( inputsContainer );
inputsContainer.prepend( select );
editButton = inputsContainer.find( '.edit-page' );
createButton = inputsContainer.find( '.create-page' );
onSelect = function( pageId ) {
editButton.toggle( 0 !== parseInt( pageId, 10 ) );
};
onSelect( control.setting.get() );
control.setting.bind( onSelect );
editButton.on( 'click', function( e ) {
e.preventDefault();
component.startEditPostFlow( {
postId: parseInt( control.setting.get(), 10 ),
initiatingButton: $( this ),
originatingConstruct: control,
restorePreviousUrl: true,
returnToOriginatingConstruct: true
} );
} );
createButton.on( 'click', function( e ) {
e.preventDefault();
component.startCreatePostFlow( {
postType: 'page',
initiatingButton: $( this ),
originatingConstruct: control,
restorePreviousUrl: true,
returnToOriginatingConstruct: true,
breadcrumbReturnCallback: function( data ) {
if ( 'publish' === data.setting.get().post_status ) {
control.setting.set( data.postId );
}
}
} );
} );
} );
};
/**
* Handle creating a new page.
*
* @param {object} args Args.
* @param {String} args.postType - Post type.
* @param {jQuery} [args.initiatingButton] - Clicked button which will be disabled during the request, and re-focused if returnToOriginatingConstruct is true.
* @param {wp.customize.Control} [args.originatingConstruct] - Control containing button.
* @param {Boolean} [args.restorePreviousUrl] - Whether the URL prior to navigating to the created page should be returned to.
* @param {Boolean} [args.returnToOriginatingConstruct] - Whether the originating control should be returned to.
* @param {Function} [args.breadcrumbReturnCallback] - Function that is called when breadcrumbs are followed back. The post setting is passed as its argument.
* @returns {jQuery.promise} Promise from wp.customize.Posts.insertAutoDraftPost().
*/
component.startCreatePostFlow = function startCreatePostFlow( args ) {
var promise, options, postTypeObj, errorCode = 'create_post_failure';
options = _.extend(
{
postType: null,
initiatingButton: null,
originatingConstruct: null,
restorePreviousUrl: true,
returnToOriginatingConstruct: Boolean( args.originatingConstruct ),
breadcrumbReturnCallback: null
},
args
);
if ( ! options.postType ) {
throw new Error( 'Missing postType' );
}
if ( options.initiatingButton ) {
options.initiatingButton.prop( 'disabled', true );
}
postTypeObj = api.Posts.data.postTypes[ options.postType ];
promise = api.Posts.insertAutoDraftPost( options.postType );
if ( options.originatingConstruct && options.originatingConstruct.notifications ) {
options.originatingConstruct.notifications.remove( errorCode );
}
promise.done( function( data ) {
var section = data.section, returnPromise, postData, returnUrl = null, watchPreviewUrlChange;
section.focus();
// Navigate to the newly-created post.
if ( postTypeObj['public'] ) {
returnUrl = api.previewer.previewUrl.get();
api.previewer.previewUrl( api.Posts.getPreviewUrl( {
post_type: options.postType,
post_id: data.postId
} ) );
} else {
api.previewer.refresh();
}
// Set initial post data.
postData = {};
if ( postTypeObj.supports.title ) {
postData.post_title = api.Posts.data.l10n.noTitle;
}
data.setting.set( _.extend(
{},
data.setting.get(),
postData
) );
if ( ! options.returnToOriginatingConstruct || ! options.originatingConstruct ) {
component.focusFirstSectionControlOnceFocusable( section );
} else {
// Clear out the return URL if the preview URL was changed when editing the newly-created post.
if ( options.restorePreviousUrl ) {
watchPreviewUrlChange = function() {
returnUrl = null;
};
api.previewer.previewUrl.bind( watchPreviewUrlChange );
}
returnPromise = component.focusConstructWithBreadcrumb( section, options.originatingConstruct );
returnPromise.done( function() {
// @todo Promise?
if ( options.breadcrumbReturnCallback ) {
options.breadcrumbReturnCallback( data );
}
if ( options.initiatingButton ) {
options.initiatingButton.focus();
}
// Return to the previewed URL.
if ( returnUrl && options.restorePreviousUrl ) {
api.previewer.previewUrl.unbind( watchPreviewUrlChange );
api.previewer.previewUrl( returnUrl );
}
} );
}
} );
promise.fail( function() {
if ( options.originatingConstruct && options.originatingConstruct.notifications ) {
options.originatingConstruct.notifications.add( errorCode, new api.Notification( errorCode, {
message: api.Posts.data.l10n.createPostFailure
} ) );
}
} );
promise.always( function() {
if ( options.initiatingButton ) {
options.initiatingButton.prop( 'disabled', false );
}
} );
return promise;
};
/**
* Handle editing an existing page.
*
* @param {object} args Args.
* @param {Number} args.postId - Post type.
* @param {jQuery} [args.initiatingButton] - Clicked button which will be disabled during the request, and re-focused if returnToOriginatingConstruct is true.
* @param {wp.customize.Control} [args.originatingConstruct] - Control containing button.
* @param {Boolean} [args.restorePreviousUrl] - Whether the URL prior to navigating to the created page should be returned to.
* @param {Boolean} [args.returnToOriginatingConstruct] - Whether the originating control should be returned to.
* @param {Function} [args.breadcrumbReturnCallback] - Function that is called when breadcrumbs are followed back. The post setting is passed as its argument.
* @returns {jQuery.promise} Promise from wp.customize.Posts.ensurePosts().
*/
component.startEditPostFlow = function startEditPostFlow( args ) {
var options, promise, errorCode = 'edit_post_failure';
options = _.extend(
{
postId: null,
initiatingButton: null,
originatingConstruct: null,
restorePreviousUrl: true,
returnToOriginatingConstruct: Boolean( args.originatingConstruct ),
breadcrumbReturnCallback: null
},
args
);
if ( ! options.postId ) {
throw new Error( 'Missing postId' );
}
if ( options.initiatingButton ) {
options.initiatingButton.prop( 'disabled', true );
}
promise = api.Posts.ensurePosts( [ options.postId ] );
if ( options.originatingConstruct && options.originatingConstruct.notifications ) {
options.originatingConstruct.notifications.remove( errorCode );
}
promise.done( function( data ) {
var section, returnPromise, returnUrl = null, watchPreviewUrlChange;
section = data[ options.postId ].section;
section.focus();
if ( ! options.returnToOriginatingConstruct || ! options.originatingConstruct ) {
component.focusFirstSectionControlOnceFocusable( section );
} else {
// Navigate to the newly-created page.
returnUrl = api.previewer.previewUrl.get();
api.previewer.previewUrl( api.Posts.getPreviewUrl( {
post_type: data[ options.postId ].postType,
post_id: options.postId
} ) );
// Clear out the return URL if the preview URL was changed when editing the newly-created post.
if ( options.restorePreviousUrl ) {
watchPreviewUrlChange = function() {
returnUrl = null;
};
api.previewer.previewUrl.bind( watchPreviewUrlChange );
}
returnPromise = component.focusConstructWithBreadcrumb( section, options.originatingConstruct );
returnPromise.done( function() {
if ( options.breadcrumbReturnCallback ) {
options.breadcrumbReturnCallback( data[ options.postId ] );
}
if ( options.initiatingButton ) {
options.initiatingButton.focus();
}
// Return to the previewed URL.
if ( options.restorePreviousUrl && returnUrl ) {
api.previewer.previewUrl.unbind( watchPreviewUrlChange );
api.previewer.previewUrl( returnUrl );
}
} );
}
} );
promise.fail( function() {
if ( options.originatingConstruct && options.originatingConstruct.notifications ) {
options.originatingConstruct.notifications.add( errorCode, new api.Notification( errorCode, {
message: api.Posts.data.l10n.editPostFailure
} ) );
}
} );
promise.always( function() {
if ( options.initiatingButton ) {
options.initiatingButton.prop( 'disabled', false );
}
} );
return promise;
};
/**
* Focus (expand) one construct and then focus on another construct after the first is collapsed.
*
* This overrides the back button to serve the purpose of breadcrumb navigation.
* This is modified from WP Core.
*
* @link https://github.com/xwp/wordpress-develop/blob/e7bbb482d6069d9c2d0e33789c7d290ac231f056/src/wp-admin/js/customize-widgets.js#L2143-L2193
* @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} focusConstruct - The object to initially focus.
* @param {wp.customize.Section|wp.customize.Panel|wp.customize.Control} returnConstruct - The object to return focus.
* @returns {void}
*/
component.focusConstructWithBreadcrumb = function focusConstructWithBreadcrumb( focusConstruct, returnConstruct ) {
var deferred = $.Deferred(), onceCollapsed;
focusConstruct.focus( {
completeCallback: function() {
if ( focusConstruct.extended( api.Section ) ) {
/*
* Note the defer is because the controls get embedded
* once the section is expanded and also because it seems
* that focus fails when the input is not visible yet.
*/
_.defer( function() {
component.focusFirstSectionControlOnceFocusable( focusConstruct );
} );
}
}
} );
onceCollapsed = function( isExpanded ) {
if ( ! isExpanded ) {
focusConstruct.expanded.unbind( onceCollapsed );
returnConstruct.focus( {
completeCallback: function() {
deferred.resolve();
}
} );
}
};
focusConstruct.expanded.bind( onceCollapsed );
return deferred;
};
/**
* Perform a dance to focus on the first control in the section.
*
* There is a race condition where focusing on a control too
* early can result in the focus logic not being able to see
* any visible inputs to focus on.
*
* @param {wp.customize.Section} section Section.
* @returns {void}
*/
component.focusFirstSectionControlOnceFocusable = function focusFirstSectionControlOnceFocusable( section ) {
var firstControl = section.controls()[0], onChangeActive, delay;
if ( ! firstControl ) {
return;
}
onChangeActive = function _onChangeActive( isActive ) {
if ( isActive ) {
section.active.unbind( onChangeActive );
// @todo Determine why a delay is required.
delay = 100; // eslint-disable-line no-magic-numbers
_.delay( function focusControlAfterDelay() {
firstControl.focus( {
completeCallback: function() {
var input = firstControl.container.find( 'input:first' );
if ( input.val() === api.Posts.data.l10n.noTitle ) {
input.select();
} else {
input.focus();
}
}
} );
}, delay );
}
};
if ( section.active.get() ) {
onChangeActive( true );
} else {
section.active.bind( onChangeActive );
}
};
/**
* Prevent the page on front and the page for posts from being set to be the same.
*
* Note that when the static front page is set to a given page, this same page will
* be hidden from the page on front dropdown, and vice versa. In contrast, when
* a page is trashed it will be *disabled* in the dropdowns. So there are two states
* that effect whether or not an option should be selected. So it is taking advantage
* of the `disabled` and `hidden` to correspond to these two separate states so that
* they don't overwrite each other and accidentally allow an option to be selected.
*
* @see wp.customize.Posts.PostSection.syncPageData()