1 (function( exports, $ ){
2 var api = wp.customize;
6 * - previewer - The Previewer instance to sync with.
7 * - transport - The transport to use for previewing. Supports 'refresh' and 'postMessage'.
9 api.Setting = api.Value.extend({
10 initialize: function( id, value, options ) {
13 api.Value.prototype.initialize.call( this, value, options );
16 this.transport = this.transport || 'refresh';
18 this.bind( this.preview );
21 switch ( this.transport ) {
23 return this.previewer.refresh();
25 return this.previewer.send( 'setting', [ this.id, this() ] );
30 api.Control = api.Class.extend({
31 initialize: function( id, options ) {
33 nodes, radios, settings;
36 $.extend( this, options || {} );
39 this.selector = '#customize-control-' + id.replace( /\]/g, '' ).replace( /\[/g, '-' );
40 this.container = $( this.selector );
42 settings = $.map( this.params.settings, function( value ) {
46 api.apply( api, settings.concat( function() {
49 control.settings = {};
50 for ( key in control.params.settings ) {
51 control.settings[ key ] = api( control.params.settings[ key ] );
54 control.setting = control.settings['default'] || null;
58 control.elements = [];
60 nodes = this.container.find('[data-customize-setting-link]');
63 nodes.each( function() {
67 if ( node.is(':radio') ) {
68 name = node.prop('name');
72 radios[ name ] = true;
73 node = nodes.filter( '[name="' + name + '"]' );
76 api( node.data('customizeSettingLink'), function( setting ) {
77 var element = new api.Element( node );
78 control.elements.push( element );
79 element.sync( setting );
80 element.set( setting() );
87 dropdownInit: function() {
89 statuses = this.container.find('.dropdown-status'),
91 update = function( to ) {
92 if ( typeof to === 'string' && params.statuses && params.statuses[ to ] )
93 statuses.html( params.statuses[ to ] ).show();
98 var toggleFreeze = false;
100 // Support the .dropdown class to open/close complex elements
101 this.container.on( 'click keydown', '.dropdown', function( event ) {
102 if ( event.type === 'keydown' && 13 !== event.which ) // enter
105 event.preventDefault();
108 control.container.toggleClass('open');
110 if ( control.container.hasClass('open') )
111 control.container.parent().parent().find('li.library-selected').focus();
113 // Don't want to fire focus and click at same time
115 setTimeout(function () {
116 toggleFreeze = false;
120 this.setting.bind( update );
121 update( this.setting() );
125 api.ColorControl = api.Control.extend({
128 picker = this.container.find('.color-picker-hex');
130 picker.val( control.setting() ).wpColorPicker({
131 change: function( event, options ) {
132 control.setting.set( picker.wpColorPicker('color') );
135 control.setting.set( false );
141 api.UploadControl = api.Control.extend({
145 this.params.removed = this.params.removed || '';
147 this.success = $.proxy( this.success, this );
149 this.uploader = $.extend({
150 container: this.container,
151 browser: this.container.find('.upload'),
152 dropzone: this.container.find('.upload-dropzone'),
153 success: this.success,
156 }, this.uploader || {} );
158 if ( control.params.extensions ) {
159 control.uploader.plupload.filters = [{
160 title: api.l10n.allowedFiles,
161 extensions: control.params.extensions
165 if ( control.params.context )
166 control.uploader.params['post_data[context]'] = this.params.context;
168 if ( api.settings.theme.stylesheet )
169 control.uploader.params['post_data[theme]'] = api.settings.theme.stylesheet;
171 this.uploader = new wp.Uploader( this.uploader );
173 this.remover = this.container.find('.remove');
174 this.remover.on( 'click keydown', function( event ) {
175 if ( event.type === 'keydown' && 13 !== event.which ) // enter
178 control.setting.set( control.params.removed );
179 event.preventDefault();
182 this.removerVisibility = $.proxy( this.removerVisibility, this );
183 this.setting.bind( this.removerVisibility );
184 this.removerVisibility( this.setting.get() );
186 success: function( attachment ) {
187 this.setting.set( attachment.get('url') );
189 removerVisibility: function( to ) {
190 this.remover.toggle( to != this.params.removed );
194 api.ImageControl = api.UploadControl.extend({
200 init: function( up ) {
201 var fallback, button;
203 if ( this.supports.dragdrop )
206 // Maintain references while wrapping the fallback button.
207 fallback = control.container.find( '.upload-fallback' );
208 button = fallback.children().detach();
210 this.browser.detach().empty().append( button );
211 fallback.append( this.browser ).show();
215 api.UploadControl.prototype.ready.call( this );
217 this.thumbnail = this.container.find('.preview-thumbnail img');
218 this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
219 this.setting.bind( this.thumbnailSrc );
221 this.library = this.container.find('.library');
223 // Generate tab objects
225 panels = this.library.find('.library-content');
227 this.library.children('ul').children('li').each( function() {
229 id = link.data('customizeTab'),
230 panel = panels.filter('[data-customize-tab="' + id + '"]');
232 control.tabs[ id ] = {
233 both: link.add( panel ),
239 // Bind tab switch events
240 this.library.children('ul').on( 'click keydown', 'li', function( event ) {
241 if ( event.type === 'keydown' && 13 !== event.which ) // enter
244 var id = $(this).data('customizeTab'),
245 tab = control.tabs[ id ];
247 event.preventDefault();
249 if ( tab.link.hasClass('library-selected') )
252 control.selected.both.removeClass('library-selected');
253 control.selected = tab;
254 control.selected.both.addClass('library-selected');
257 // Bind events to switch image urls.
258 this.library.on( 'click keydown', 'a', function( event ) {
259 if ( event.type === 'keydown' && 13 !== event.which ) // enter
262 var value = $(this).data('customizeImageValue');
265 control.setting.set( value );
266 event.preventDefault();
270 if ( this.tabs.uploaded ) {
271 this.tabs.uploaded.target = this.library.find('.uploaded-target');
272 if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
273 this.tabs.uploaded.both.addClass('hidden');
277 panels.each( function() {
278 var tab = control.tabs[ $(this).data('customizeTab') ];
280 // Select the first visible tab.
281 if ( ! tab.link.hasClass('hidden') ) {
282 control.selected = tab;
283 tab.both.addClass('library-selected');
290 success: function( attachment ) {
291 api.UploadControl.prototype.success.call( this, attachment );
293 // Add the uploaded image to the uploaded tab.
294 if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
295 this.tabs.uploaded.both.removeClass('hidden');
297 // @todo: Do NOT store this on the attachment model. That is bad.
298 attachment.element = $( '<a href="#" class="thumbnail"></a>' )
299 .data( 'customizeImageValue', attachment.get('url') )
300 .append( '<img src="' + attachment.get('url')+ '" />' )
301 .appendTo( this.tabs.uploaded.target );
304 thumbnailSrc: function( to ) {
305 if ( /^(https?:)?\/\//.test( to ) )
306 this.thumbnail.prop( 'src', to ).show();
308 this.thumbnail.hide();
312 // Change objects contained within the main customize object to Settings.
313 api.defaultConstructor = api.Setting;
315 // Create the collection of Control objects.
316 api.control = new api.Values({ defaultConstructor: api.Control });
318 api.PreviewFrame = api.Messenger.extend({
321 initialize: function( params, options ) {
322 var deferred = $.Deferred(),
325 // This is the promise object.
326 deferred.promise( this );
328 this.container = params.container;
329 this.signature = params.signature;
331 $.extend( params, { channel: api.PreviewFrame.uuid() });
333 api.Messenger.prototype.initialize.call( this, params, options );
335 this.add( 'previewUrl', params.previewUrl );
337 this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
339 this.run( deferred );
342 run: function( deferred ) {
348 this.unbind( 'ready', this._ready );
350 this._ready = function() {
354 deferred.resolveWith( self );
357 this.bind( 'ready', this._ready );
359 this.request = $.ajax( this.previewUrl(), {
363 withCredentials: true
367 this.request.fail( function() {
368 deferred.rejectWith( self, [ 'request failure' ] );
371 this.request.done( function( response ) {
372 var location = self.request.getResponseHeader('Location'),
373 signature = self.signature,
376 // Check if the location response header differs from the current URL.
377 // If so, the request was redirected; try loading the requested page.
378 if ( location && location != self.previewUrl() ) {
379 deferred.rejectWith( self, [ 'redirect', location ] );
383 // Check if the user is not logged in.
384 if ( '0' === response ) {
385 self.login( deferred );
389 // Check for cheaters.
390 if ( '-1' === response ) {
391 deferred.rejectWith( self, [ 'cheatin' ] );
395 // Check for a signature in the request.
396 index = response.lastIndexOf( signature );
397 if ( -1 === index || index < response.lastIndexOf('</html>') ) {
398 deferred.rejectWith( self, [ 'unsigned' ] );
402 // Strip the signature from the request.
403 response = response.slice( 0, index ) + response.slice( index + signature.length );
405 // Create the iframe and inject the html content.
406 self.iframe = $('<iframe />').appendTo( self.container );
408 // Bind load event after the iframe has been added to the page;
409 // otherwise it will fire when injected into the DOM.
410 self.iframe.one( 'load', function() {
414 deferred.resolveWith( self );
416 setTimeout( function() {
417 deferred.rejectWith( self, [ 'ready timeout' ] );
418 }, self.sensitivity );
422 self.targetWindow( self.iframe[0].contentWindow );
424 self.targetWindow().document.open();
425 self.targetWindow().document.write( response );
426 self.targetWindow().document.close();
430 login: function( deferred ) {
434 reject = function() {
435 deferred.rejectWith( self, [ 'logged out' ] );
438 if ( this.triedLogin )
441 // Check if we have an admin cookie.
442 $.get( api.settings.url.ajax, {
444 }).fail( reject ).done( function( response ) {
447 if ( '1' !== response )
450 iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
451 iframe.appendTo( self.container );
452 iframe.load( function() {
453 self.triedLogin = true;
456 self.run( deferred );
461 destroy: function() {
462 api.Messenger.prototype.destroy.call( this );
463 this.request.abort();
466 this.iframe.remove();
470 delete this.targetWindow;
476 api.PreviewFrame.uuid = function() {
477 return 'preview-' + uuid++;
481 api.Previewer = api.Messenger.extend({
486 * - container - a selector or jQuery element
487 * - previewUrl - the URL of preview frame
489 initialize: function( params, options ) {
494 $.extend( this, options || {} );
497 * Wrap this.refresh to prevent it from hammering the servers:
499 * If refresh is called once and no other refresh requests are
500 * loading, trigger the request immediately.
502 * If refresh is called while another refresh request is loading,
503 * debounce the refresh requests:
504 * 1. Stop the loading request (as it is instantly outdated).
505 * 2. Trigger the new request once refresh hasn't been called for
506 * self.refreshBuffer milliseconds.
508 this.refresh = (function( self ) {
509 var refresh = self.refresh,
510 callback = function() {
512 refresh.call( self );
517 if ( typeof timeout !== 'number' ) {
518 if ( self.loading ) {
525 clearTimeout( timeout );
526 timeout = setTimeout( callback, self.refreshBuffer );
530 this.container = api.ensure( params.container );
531 this.allowedUrls = params.allowedUrls;
532 this.signature = params.signature;
534 params.url = window.location.href;
536 api.Messenger.prototype.initialize.call( this, params );
538 this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
539 var match = to.match( rscheme );
540 return match ? match[0] : '';
543 // Limit the URL to internal, front-end links.
545 // If the frontend and the admin are served from the same domain, load the
546 // preview over ssl if the customizer is being loaded over ssl. This avoids
547 // insecure content warnings. This is not attempted if the admin and frontend
548 // are on different domains to avoid the case where the frontend doesn't have
551 this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
554 // Check for URLs that include "/wp-admin/" or end in "/wp-admin".
555 // Strip hashes and query strings before testing.
556 if ( /\/wp-admin(\/|$)/.test( to.replace( /[#?].*$/, '' ) ) )
559 // Attempt to match the URL to the control frame's scheme
560 // and check if it's allowed. If not, try the original URL.
561 $.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
562 $.each( self.allowedUrls, function( i, allowed ) {
565 allowed = allowed.replace( /\/+$/, '' );
566 path = url.replace( allowed, '' );
568 if ( 0 === url.indexOf( allowed ) && /^([/#?]|$)/.test( path ) ) {
577 // If we found a matching result, return it. If not, bail.
578 return result ? result : null;
581 // Refresh the preview when the URL is changed (but not yet).
582 this.previewUrl.bind( this.refresh );
585 this.bind( 'scroll', function( distance ) {
586 this.scroll = distance;
589 // Update the URL when the iframe sends a URL message.
590 this.bind( 'url', this.previewUrl );
593 query: function() {},
596 if ( this.loading ) {
597 this.loading.destroy();
602 refresh: function() {
607 this.loading = new api.PreviewFrame({
609 previewUrl: this.previewUrl(),
610 query: this.query() || {},
611 container: this.container,
612 signature: this.signature
615 this.loading.done( function() {
616 // 'this' is the loading frame
617 this.bind( 'synced', function() {
619 self.preview.destroy();
623 self.targetWindow( this.targetWindow() );
624 self.channel( this.channel() );
626 self.send( 'active' );
635 this.loading.fail( function( reason, location ) {
636 if ( 'redirect' === reason && location )
637 self.previewUrl( location );
639 if ( 'logged out' === reason ) {
640 if ( self.preview ) {
641 self.preview.destroy();
645 self.login().done( self.refresh );
648 if ( 'cheatin' === reason )
654 var previewer = this,
655 deferred, messenger, iframe;
660 deferred = $.Deferred();
661 this._login = deferred.promise();
663 messenger = new api.Messenger({
665 url: api.settings.url.login
668 iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
670 messenger.targetWindow( iframe[0].contentWindow );
672 messenger.bind( 'login', function() {
675 delete previewer._login;
682 cheatin: function() {
683 $( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
687 /* =====================================================================
689 * ===================================================================== */
691 api.controlConstructor = {
692 color: api.ColorControl,
693 upload: api.UploadControl,
694 image: api.ImageControl
698 api.settings = window._wpCustomizeSettings;
699 api.l10n = window._wpCustomizeControlsL10n;
701 // Check if we can run the customizer.
702 if ( ! api.settings )
705 // Redirect to the fallback preview if any incompatibilities are found.
706 if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
707 return window.location = api.settings.url.fallback;
709 var body = $( document.body ),
710 overlay = body.children('.wp-full-overlay'),
711 query, previewer, parent;
713 // Prevent the form from saving when enter is pressed.
714 $('#customize-controls').on( 'keydown', function( e ) {
715 if ( $( e.target ).is('textarea') )
718 if ( 13 === e.which ) // Enter
722 // Initialize Previewer
723 previewer = new api.Previewer({
724 container: '#customize-preview',
725 form: '#customize-controls',
726 previewUrl: api.settings.url.preview,
727 allowedUrls: api.settings.url.allowed,
728 signature: 'WP_CUSTOMIZER_SIGNATURE'
731 nonce: api.settings.nonce,
736 theme: api.settings.theme.stylesheet,
737 customized: JSON.stringify( api.get() ),
738 nonce: this.nonce.preview
744 query = $.extend( this.query(), {
745 action: 'customize_save',
746 nonce: this.nonce.save
748 request = $.post( api.settings.url.ajax, query );
750 api.trigger( 'save', request );
752 body.addClass('saving');
754 request.always( function() {
755 body.removeClass('saving');
758 request.done( function( response ) {
759 // Check if the user is logged out.
760 if ( '0' === response ) {
761 self.preview.iframe.hide();
762 self.login().done( function() {
764 self.preview.iframe.show();
769 // Check for cheaters.
770 if ( '-1' === response ) {
775 api.trigger( 'saved' );
780 // Refresh the nonces if the preview sends updated nonces over.
781 previewer.bind( 'nonce', function( nonce ) {
782 $.extend( this.nonce, nonce );
785 $.each( api.settings.settings, function( id, data ) {
786 api.create( id, id, data.value, {
787 transport: data.transport,
792 $.each( api.settings.controls, function( id, data ) {
793 var constructor = api.controlConstructor[ data.type ] || api.Control,
796 control = api.control.add( id, new constructor( id, {
802 // Check if preview url is valid and load the preview frame.
803 if ( previewer.previewUrl() )
806 previewer.previewUrl( api.settings.url.home );
808 // Save and activated states
810 var state = new api.Values(),
811 saved = state.create('saved'),
812 activated = state.create('activated');
814 state.bind( 'change', function() {
815 var save = $('#save'),
818 if ( ! activated() ) {
819 save.val( api.l10n.activate ).prop( 'disabled', false );
820 back.text( api.l10n.cancel );
822 } else if ( saved() ) {
823 save.val( api.l10n.saved ).prop( 'disabled', true );
824 back.text( api.l10n.close );
827 save.val( api.l10n.save ).prop( 'disabled', false );
828 back.text( api.l10n.cancel );
832 // Set default states.
834 activated( api.settings.theme.active );
836 api.bind( 'change', function() {
837 state('saved').set( false );
840 api.bind( 'saved', function() {
841 state('saved').set( true );
842 state('activated').set( true );
845 activated.bind( function( to ) {
847 api.trigger( 'activated' );
850 // Expose states to the API.
855 $('#save').click( function( event ) {
857 event.preventDefault();
858 }).keydown( function( event ) {
859 if ( 9 === event.which ) // tab
861 if ( 13 === event.which ) // enter
863 event.preventDefault();
866 $('.back').keydown( function( event ) {
867 if ( 9 === event.which ) // tab
869 if ( 13 === event.which ) // enter
871 event.preventDefault();
874 $('.upload-dropzone a.upload').keydown( function( event ) {
875 if ( 13 === event.which ) // enter
879 $('.collapse-sidebar').on( 'click keydown', function( event ) {
880 if ( event.type === 'keydown' && 13 !== event.which ) // enter
883 overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
884 event.preventDefault();
887 // Create a potential postMessage connection with the parent frame.
888 parent = new api.Messenger({
889 url: api.settings.url.parent,
893 // If we receive a 'back' event, we're inside an iframe.
894 // Send any clicks to the 'Return' link to the parent page.
895 parent.bind( 'back', function() {
896 $('.back').on( 'click.back', function( event ) {
897 event.preventDefault();
898 parent.send( 'close' );
902 // Pass events through to the parent.
903 api.bind( 'saved', function() {
904 parent.send( 'saved' );
907 // When activated, let the loader handle redirecting the page.
908 // If no loader exists, redirect the page ourselves (if a url exists).
909 api.bind( 'activated', function() {
910 if ( parent.targetWindow() )
911 parent.send( 'activated', api.settings.url.activated );
912 else if ( api.settings.url.activated )
913 window.location = api.settings.url.activated;
916 // Initialize the connection with the parent frame.
917 parent.send( 'ready' );
919 // Control visibility for default controls
921 'background_image': {
922 controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
923 callback: function( to ) { return !! to }
926 controls: [ 'page_on_front', 'page_for_posts' ],
927 callback: function( to ) { return 'page' === to }
929 'header_textcolor': {
930 controls: [ 'header_textcolor' ],
931 callback: function( to ) { return 'blank' !== to }
933 }, function( settingId, o ) {
934 api( settingId, function( setting ) {
935 $.each( o.controls, function( i, controlId ) {
936 api.control( controlId, function( control ) {
937 var visibility = function( to ) {
938 control.container.toggle( o.callback( to ) );
941 visibility( setting.get() );
942 setting.bind( visibility );
948 // Juggle the two controls that use header_textcolor
949 api.control( 'display_header_text', function( control ) {
952 control.elements[0].unsync( api( 'header_textcolor' ) );
954 control.element = new api.Element( control.container.find('input') );
955 control.element.set( 'blank' !== control.setting() );
957 control.element.bind( function( to ) {
959 last = api( 'header_textcolor' ).get();
961 control.setting.set( to ? last : 'blank' );
964 control.setting.bind( function( to ) {
965 control.element.set( 'blank' !== to );
969 // Handle header image data
970 api.control( 'header_image', function( control ) {
971 control.setting.bind( function( to ) {
972 if ( to === control.params.removed )
973 control.settings.data.set( false );
976 control.library.on( 'click', 'a', function( event ) {
977 control.settings.data.set( $(this).data('customizeHeaderImageData') );
980 control.uploader.success = function( attachment ) {
983 api.ImageControl.prototype.success.call( control, attachment );
986 attachment_id: attachment.get('id'),
987 url: attachment.get('url'),
988 thumbnail_url: attachment.get('url'),
989 height: attachment.get('height'),
990 width: attachment.get('width')
993 attachment.element.data( 'customizeHeaderImageData', data );
994 control.settings.data.set( data );
998 api.trigger( 'ready' );
1000 // Make sure left column gets focus
1001 var topFocus = $('.back');
1003 setTimeout(function () {