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( ']', '' ).replace( '[', '-' );
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 // Support the .dropdown class to open/close complex elements
99 this.container.on( 'click', '.dropdown', function( event ) {
100 event.preventDefault();
101 control.container.toggleClass('open');
104 this.setting.bind( update );
105 update( this.setting() );
109 api.ColorControl = api.Control.extend({
112 rhex, spot, input, text, update;
114 rhex = /^#([A-Fa-f0-9]{3}){0,2}$/;
115 spot = this.container.find('.dropdown-content');
116 input = new api.Element( this.container.find('.color-picker-hex') );
117 update = function( color ) {
118 spot.css( 'background', color );
119 control.farbtastic.setColor( color );
122 this.farbtastic = $.farbtastic( this.container.find('.farbtastic-placeholder'), control.setting.set );
124 // Only pass through values that are valid hexes/empty.
125 input.sync( this.setting ).validate = function( to ) {
126 return rhex.test( to ) ? to : null;
129 this.setting.bind( update );
130 update( this.setting() );
136 api.UploadControl = api.Control.extend({
140 this.params.removed = this.params.removed || '';
142 this.success = $.proxy( this.success, this );
144 this.uploader = $.extend({
145 container: this.container,
146 browser: this.container.find('.upload'),
147 dropzone: this.container.find('.upload-dropzone'),
148 success: this.success
149 }, this.uploader || {} );
151 if ( this.uploader.supported ) {
152 if ( control.params.context )
153 control.uploader.param( 'post_data[context]', this.params.context );
155 control.uploader.param( 'post_data[theme]', api.settings.theme.stylesheet );
158 this.uploader = new wp.Uploader( this.uploader );
160 this.remover = this.container.find('.remove');
161 this.remover.click( function( event ) {
162 control.setting.set( control.params.removed );
163 event.preventDefault();
166 this.removerVisibility = $.proxy( this.removerVisibility, this );
167 this.setting.bind( this.removerVisibility );
168 this.removerVisibility( this.setting.get() );
170 success: function( attachment ) {
171 this.setting.set( attachment.url );
173 removerVisibility: function( to ) {
174 this.remover.toggle( to != this.params.removed );
178 api.ImageControl = api.UploadControl.extend({
184 init: function( up ) {
185 var fallback, button;
187 if ( this.supports.dragdrop )
190 // Maintain references while wrapping the fallback button.
191 fallback = control.container.find( '.upload-fallback' );
192 button = fallback.children().detach();
194 this.browser.detach().empty().append( button );
195 fallback.append( this.browser ).show();
199 api.UploadControl.prototype.ready.call( this );
201 this.thumbnail = this.container.find('.preview-thumbnail img');
202 this.thumbnailSrc = $.proxy( this.thumbnailSrc, this );
203 this.setting.bind( this.thumbnailSrc );
205 this.library = this.container.find('.library');
207 // Generate tab objects
209 panels = this.library.find('.library-content');
211 this.library.children('ul').children('li').each( function() {
213 id = link.data('customizeTab'),
214 panel = panels.filter('[data-customize-tab="' + id + '"]');
216 control.tabs[ id ] = {
217 both: link.add( panel ),
223 // Bind tab switch events
224 this.library.children('ul').on( 'click', 'li', function( event ) {
225 var id = $(this).data('customizeTab'),
226 tab = control.tabs[ id ];
228 event.preventDefault();
230 if ( tab.link.hasClass('library-selected') )
233 control.selected.both.removeClass('library-selected');
234 control.selected = tab;
235 control.selected.both.addClass('library-selected');
238 // Bind events to switch image urls.
239 this.library.on( 'click', 'a', function( event ) {
240 var value = $(this).data('customizeImageValue');
243 control.setting.set( value );
244 event.preventDefault();
248 if ( this.tabs.uploaded ) {
249 this.tabs.uploaded.target = this.library.find('.uploaded-target');
250 if ( ! this.tabs.uploaded.panel.find('.thumbnail').length )
251 this.tabs.uploaded.both.addClass('hidden');
255 panels.each( function() {
256 var tab = control.tabs[ $(this).data('customizeTab') ];
258 // Select the first visible tab.
259 if ( ! tab.link.hasClass('hidden') ) {
260 control.selected = tab;
261 tab.both.addClass('library-selected');
268 success: function( attachment ) {
269 api.UploadControl.prototype.success.call( this, attachment );
271 // Add the uploaded image to the uploaded tab.
272 if ( this.tabs.uploaded && this.tabs.uploaded.target.length ) {
273 this.tabs.uploaded.both.removeClass('hidden');
275 attachment.element = $( '<a href="#" class="thumbnail"></a>' )
276 .data( 'customizeImageValue', attachment.url )
277 .append( '<img src="' + attachment.url+ '" />' )
278 .appendTo( this.tabs.uploaded.target );
281 thumbnailSrc: function( to ) {
282 if ( /^(https?:)?\/\//.test( to ) )
283 this.thumbnail.prop( 'src', to ).show();
285 this.thumbnail.hide();
289 // Change objects contained within the main customize object to Settings.
290 api.defaultConstructor = api.Setting;
292 // Create the collection of Control objects.
293 api.control = new api.Values({ defaultConstructor: api.Control });
295 api.PreviewFrame = api.Messenger.extend({
298 initialize: function( params, options ) {
299 var deferred = $.Deferred(),
302 // This is the promise object.
303 deferred.promise( this );
305 this.container = params.container;
306 this.signature = params.signature;
308 $.extend( params, { channel: api.PreviewFrame.uuid() });
310 api.Messenger.prototype.initialize.call( this, params, options );
312 this.add( 'previewUrl', params.previewUrl );
314 this.query = $.extend( params.query || {}, { customize_messenger_channel: this.channel() });
316 this.run( deferred );
319 run: function( deferred ) {
325 this.unbind( 'ready', this._ready );
327 this._ready = function() {
331 deferred.resolveWith( self );
334 this.bind( 'ready', this._ready );
336 this.request = $.ajax( this.previewUrl(), {
340 withCredentials: true
344 this.request.fail( function() {
345 deferred.rejectWith( self, [ 'request failure' ] );
348 this.request.done( function( response ) {
349 var location = self.request.getResponseHeader('Location'),
350 signature = self.signature,
353 // Check if the location response header differs from the current URL.
354 // If so, the request was redirected; try loading the requested page.
355 if ( location && location != self.previewUrl() ) {
356 deferred.rejectWith( self, [ 'redirect', location ] );
360 // Check if the user is not logged in.
361 if ( '0' === response ) {
362 self.login( deferred );
366 // Check for cheaters.
367 if ( '-1' === response ) {
368 deferred.rejectWith( self, [ 'cheatin' ] );
372 // Check for a signature in the request.
373 index = response.lastIndexOf( signature );
374 if ( -1 === index || index < response.lastIndexOf('</html>') ) {
375 deferred.rejectWith( self, [ 'unsigned' ] );
379 // Strip the signature from the request.
380 response = response.slice( 0, index ) + response.slice( index + signature.length );
382 // Create the iframe and inject the html content.
383 self.iframe = $('<iframe />').appendTo( self.container );
385 // Bind load event after the iframe has been added to the page;
386 // otherwise it will fire when injected into the DOM.
387 self.iframe.one( 'load', function() {
391 deferred.resolveWith( self );
393 setTimeout( function() {
394 deferred.rejectWith( self, [ 'ready timeout' ] );
395 }, self.sensitivity );
399 self.targetWindow( self.iframe[0].contentWindow );
401 self.targetWindow().document.open();
402 self.targetWindow().document.write( response );
403 self.targetWindow().document.close();
407 login: function( deferred ) {
411 reject = function() {
412 deferred.rejectWith( self, [ 'logged out' ] );
415 if ( this.triedLogin )
418 // Check if we have an admin cookie.
419 $.get( api.settings.url.ajax, {
421 }).fail( reject ).done( function( response ) {
424 if ( '1' !== response )
427 iframe = $('<iframe src="' + self.previewUrl() + '" />').hide();
428 iframe.appendTo( self.container );
429 iframe.load( function() {
430 self.triedLogin = true;
433 self.run( deferred );
438 destroy: function() {
439 api.Messenger.prototype.destroy.call( this );
440 this.request.abort();
443 this.iframe.remove();
447 delete this.targetWindow;
453 api.PreviewFrame.uuid = function() {
454 return 'preview-' + uuid++;
458 api.Previewer = api.Messenger.extend({
463 * - container - a selector or jQuery element
464 * - previewUrl - the URL of preview frame
466 initialize: function( params, options ) {
471 $.extend( this, options || {} );
474 * Wrap this.refresh to prevent it from hammering the servers:
476 * If refresh is called once and no other refresh requests are
477 * loading, trigger the request immediately.
479 * If refresh is called while another refresh request is loading,
480 * debounce the refresh requests:
481 * 1. Stop the loading request (as it is instantly outdated).
482 * 2. Trigger the new request once refresh hasn't been called for
483 * self.refreshBuffer milliseconds.
485 this.refresh = (function( self ) {
486 var refresh = self.refresh,
487 callback = function() {
489 refresh.call( self );
494 if ( typeof timeout !== 'number' ) {
495 if ( self.loading ) {
502 clearTimeout( timeout );
503 timeout = setTimeout( callback, self.refreshBuffer );
507 this.container = api.ensure( params.container );
508 this.allowedUrls = params.allowedUrls;
509 this.signature = params.signature;
511 params.url = window.location.href;
513 api.Messenger.prototype.initialize.call( this, params );
515 this.add( 'scheme', this.origin() ).link( this.origin ).setter( function( to ) {
516 var match = to.match( rscheme );
517 return match ? match[0] : '';
520 // Limit the URL to internal, front-end links.
522 // If the frontend and the admin are served from the same domain, load the
523 // preview over ssl if the customizer is being loaded over ssl. This avoids
524 // insecure content warnings. This is not attempted if the admin and frontend
525 // are on different domains to avoid the case where the frontend doesn't have
528 this.add( 'previewUrl', params.previewUrl ).setter( function( to ) {
531 // Check for URLs that include "/wp-admin/" or end in "/wp-admin".
532 // Strip hashes and query strings before testing.
533 if ( /\/wp-admin(\/|$)/.test( to.replace(/[#?].*$/, '') ) )
536 // Attempt to match the URL to the control frame's scheme
537 // and check if it's allowed. If not, try the original URL.
538 $.each([ to.replace( rscheme, self.scheme() ), to ], function( i, url ) {
539 $.each( self.allowedUrls, function( i, allowed ) {
540 if ( 0 === url.indexOf( allowed ) ) {
549 // If we found a matching result, return it. If not, bail.
550 return result ? result : null;
553 // Refresh the preview when the URL is changed (but not yet).
554 this.previewUrl.bind( this.refresh );
557 this.bind( 'scroll', function( distance ) {
558 this.scroll = distance;
561 // Update the URL when the iframe sends a URL message.
562 this.bind( 'url', this.previewUrl );
565 query: function() {},
568 if ( this.loading ) {
569 this.loading.destroy();
574 refresh: function() {
579 this.loading = new api.PreviewFrame({
581 previewUrl: this.previewUrl(),
582 query: this.query() || {},
583 container: this.container,
584 signature: this.signature
587 this.loading.done( function() {
588 // 'this' is the loading frame
589 this.bind( 'synced', function() {
591 self.preview.destroy();
595 self.targetWindow( this.targetWindow() );
596 self.channel( this.channel() );
598 self.send( 'active' );
607 this.loading.fail( function( reason, location ) {
608 if ( 'redirect' === reason && location )
609 self.previewUrl( location );
611 if ( 'logged out' === reason ) {
612 if ( self.preview ) {
613 self.preview.destroy();
617 self.login().done( self.refresh );
620 if ( 'cheatin' === reason )
626 var previewer = this,
627 deferred, messenger, iframe;
632 deferred = $.Deferred();
633 this._login = deferred.promise();
635 messenger = new api.Messenger({
637 url: api.settings.url.login
640 iframe = $('<iframe src="' + api.settings.url.login + '" />').appendTo( this.container );
642 messenger.targetWindow( iframe[0].contentWindow );
644 messenger.bind( 'login', function() {
647 delete previewer._login;
654 cheatin: function() {
655 $( document.body ).empty().addClass('cheatin').append( '<p>' + api.l10n.cheatin + '</p>' );
659 /* =====================================================================
661 * ===================================================================== */
663 api.controlConstructor = {
664 color: api.ColorControl,
665 upload: api.UploadControl,
666 image: api.ImageControl
670 api.settings = window._wpCustomizeSettings;
671 api.l10n = window._wpCustomizeControlsL10n;
673 // Check if we can run the customizer.
674 if ( ! api.settings )
677 // Redirect to the fallback preview if any incompatibilities are found.
678 if ( ! $.support.postMessage || ( ! $.support.cors && api.settings.isCrossDomain ) )
679 return window.location = api.settings.url.fallback;
681 var body = $( document.body ),
682 overlay = body.children('.wp-full-overlay'),
683 query, previewer, parent;
685 // Prevent the form from saving when enter is pressed.
686 $('#customize-controls').on( 'keydown', function( e ) {
687 if ( $( e.target ).is('textarea') )
690 if ( 13 === e.which ) // Enter
694 // Initialize Previewer
695 previewer = new api.Previewer({
696 container: '#customize-preview',
697 form: '#customize-controls',
698 previewUrl: api.settings.url.preview,
699 allowedUrls: api.settings.url.allowed,
700 signature: 'WP_CUSTOMIZER_SIGNATURE'
703 nonce: api.settings.nonce,
708 theme: api.settings.theme.stylesheet,
709 customized: JSON.stringify( api.get() ),
710 nonce: this.nonce.preview
716 query = $.extend( this.query(), {
717 action: 'customize_save',
718 nonce: this.nonce.save
720 request = $.post( api.settings.url.ajax, query );
722 api.trigger( 'save', request );
724 body.addClass('saving');
726 request.always( function() {
727 body.removeClass('saving');
730 request.done( function( response ) {
731 // Check if the user is logged out.
732 if ( '0' === response ) {
733 self.preview.iframe.hide();
734 self.login().done( function() {
736 self.preview.iframe.show();
741 // Check for cheaters.
742 if ( '-1' === response ) {
747 api.trigger( 'saved' );
752 // Refresh the nonces if the preview sends updated nonces over.
753 previewer.bind( 'nonce', function( nonce ) {
754 $.extend( this.nonce, nonce );
757 $.each( api.settings.settings, function( id, data ) {
758 api.create( id, id, data.value, {
759 transport: data.transport,
764 $.each( api.settings.controls, function( id, data ) {
765 var constructor = api.controlConstructor[ data.type ] || api.Control,
768 control = api.control.add( id, new constructor( id, {
774 // Check if preview url is valid and load the preview frame.
775 if ( previewer.previewUrl() )
778 previewer.previewUrl( api.settings.url.home );
780 // Save and activated states
782 var state = new api.Values(),
783 saved = state.create('saved'),
784 activated = state.create('activated');
786 state.bind( 'change', function() {
787 var save = $('#save'),
790 if ( ! activated() ) {
791 save.val( api.l10n.activate ).prop( 'disabled', false );
792 back.text( api.l10n.cancel );
794 } else if ( saved() ) {
795 save.val( api.l10n.saved ).prop( 'disabled', true );
796 back.text( api.l10n.close );
799 save.val( api.l10n.save ).prop( 'disabled', false );
800 back.text( api.l10n.cancel );
804 // Set default states.
806 activated( api.settings.theme.active );
808 api.bind( 'change', function() {
809 state('saved').set( false );
812 api.bind( 'saved', function() {
813 state('saved').set( true );
814 state('activated').set( true );
817 activated.bind( function( to ) {
819 api.trigger( 'activated' );
822 // Expose states to the API.
826 // Temporary accordion code.
827 $('.customize-section-title').click( function( event ) {
828 var clicked = $( this ).parents( '.customize-section' );
830 if ( clicked.hasClass('cannot-expand') )
833 $( '.customize-section' ).not( clicked ).removeClass( 'open' );
834 clicked.toggleClass( 'open' );
835 event.preventDefault();
839 $('#save').click( function( event ) {
841 event.preventDefault();
844 $('.collapse-sidebar').click( function( event ) {
845 overlay.toggleClass( 'collapsed' ).toggleClass( 'expanded' );
846 event.preventDefault();
849 // Create a potential postMessage connection with the parent frame.
850 parent = new api.Messenger({
851 url: api.settings.url.parent,
855 // If we receive a 'back' event, we're inside an iframe.
856 // Send any clicks to the 'Return' link to the parent page.
857 parent.bind( 'back', function() {
858 $('.back').on( 'click.back', function( event ) {
859 event.preventDefault();
860 parent.send( 'close' );
864 // Pass events through to the parent.
865 api.bind( 'saved', function() {
866 parent.send( 'saved' );
869 // When activated, let the loader handle redirecting the page.
870 // If no loader exists, redirect the page ourselves (if a url exists).
871 api.bind( 'activated', function() {
872 if ( parent.targetWindow() )
873 parent.send( 'activated', api.settings.url.activated );
874 else if ( api.settings.url.activated )
875 window.location = api.settings.url.activated;
878 // Initialize the connection with the parent frame.
879 parent.send( 'ready' );
881 // Control visibility for default controls
883 'background_image': {
884 controls: [ 'background_repeat', 'background_position_x', 'background_attachment' ],
885 callback: function( to ) { return !! to }
888 controls: [ 'page_on_front', 'page_for_posts' ],
889 callback: function( to ) { return 'page' === to }
891 'header_textcolor': {
892 controls: [ 'header_textcolor' ],
893 callback: function( to ) { return 'blank' !== to }
895 }, function( settingId, o ) {
896 api( settingId, function( setting ) {
897 $.each( o.controls, function( i, controlId ) {
898 api.control( controlId, function( control ) {
899 var visibility = function( to ) {
900 control.container.toggle( o.callback( to ) );
903 visibility( setting.get() );
904 setting.bind( visibility );
910 // Juggle the two controls that use header_textcolor
911 api.control( 'display_header_text', function( control ) {
914 control.elements[0].unsync( api( 'header_textcolor' ) );
916 control.element = new api.Element( control.container.find('input') );
917 control.element.set( 'blank' !== control.setting() );
919 control.element.bind( function( to ) {
921 last = api( 'header_textcolor' ).get();
923 control.setting.set( to ? last : 'blank' );
926 control.setting.bind( function( to ) {
927 control.element.set( 'blank' !== to );
931 // Handle header image data
932 api.control( 'header_image', function( control ) {
933 control.setting.bind( function( to ) {
934 if ( to === control.params.removed )
935 control.settings.data.set( false );
938 control.library.on( 'click', 'a', function( event ) {
939 control.settings.data.set( $(this).data('customizeHeaderImageData') );
942 control.uploader.success = function( attachment ) {
945 api.ImageControl.prototype.success.call( control, attachment );
948 attachment_id: attachment.id,
950 thumbnail_url: attachment.url,
951 height: attachment.meta.height,
952 width: attachment.meta.width
955 attachment.element.data( 'customizeHeaderImageData', data );
956 control.settings.data.set( data );
960 api.trigger( 'ready' );