1 window.wp = window.wp || {};
3 (function( exports, $ ){
4 var api = {}, ctor, inherits,
5 slice = Array.prototype.slice;
7 // Shared empty constructor function to aid in prototype-chain creation.
11 * Helper function to correctly set up the prototype chain, for subclasses.
12 * Similar to `goog.inherits`, but uses a hash of prototype properties and
13 * class properties to be extended.
15 * @param object parent Parent class constructor to inherit from.
16 * @param object protoProps Properties to apply to the prototype for use as class instance properties.
17 * @param object staticProps Properties to apply directly to the class constructor.
18 * @return child The subclassed constructor.
20 inherits = function( parent, protoProps, staticProps ) {
23 // The constructor function for the new subclass is either defined by you
24 // (the "constructor" property in your `extend` definition), or defaulted
25 // by us to simply call `super()`.
26 if ( protoProps && protoProps.hasOwnProperty( 'constructor' ) ) {
27 child = protoProps.constructor;
30 // Storing the result `super()` before returning the value
31 // prevents a bug in Opera where, if the constructor returns
32 // a function, Opera will reject the return value in favor of
33 // the original object. This causes all sorts of trouble.
34 var result = parent.apply( this, arguments );
39 // Inherit class (static) properties from parent.
40 $.extend( child, parent );
42 // Set the prototype chain to inherit from `parent`, without calling
43 // `parent`'s constructor function.
44 ctor.prototype = parent.prototype;
45 child.prototype = new ctor();
47 // Add prototype properties (instance properties) to the subclass,
50 $.extend( child.prototype, protoProps );
52 // Add static properties to the constructor function, if supplied.
54 $.extend( child, staticProps );
56 // Correctly set child's `prototype.constructor`.
57 child.prototype.constructor = child;
59 // Set a convenience property in case the parent's prototype is needed later.
60 child.__super__ = parent.prototype;
66 * Base class for object inheritance.
68 api.Class = function( applicator, argsArray, options ) {
69 var magic, args = arguments;
71 if ( applicator && argsArray && api.Class.applicator === applicator ) {
73 $.extend( this, options || {} );
79 * If the class has a method called "instance",
80 * the return value from the class' constructor will be a function that
81 * calls the "instance" method.
83 * It is also an object that has properties and methods inside it.
85 if ( this.instance ) {
87 return magic.instance.apply( magic, arguments );
90 $.extend( magic, this );
93 magic.initialize.apply( magic, args );
98 * Creates a subclass of the class.
100 * @param object protoProps Properties to apply to the prototype.
101 * @param object staticProps Properties to apply directly to the class.
102 * @return child The subclass.
104 api.Class.extend = function( protoProps, classProps ) {
105 var child = inherits( this, protoProps, classProps );
106 child.extend = this.extend;
110 api.Class.applicator = {};
113 * Initialize a class instance.
115 * Override this function in a subclass as needed.
117 api.Class.prototype.initialize = function() {};
120 * Checks whether a given instance extended a constructor.
122 * The magic surrounding the instance parameter causes the instanceof
123 * keyword to return inaccurate results; it defaults to the function's
124 * prototype instead of the constructor chain. Hence this function.
126 api.Class.prototype.extended = function( constructor ) {
129 while ( typeof proto.constructor !== 'undefined' ) {
130 if ( proto.constructor === constructor )
132 if ( typeof proto.constructor.__super__ === 'undefined' )
134 proto = proto.constructor.__super__;
140 * An events manager object, offering the ability to bind to and trigger events.
145 trigger: function( id ) {
146 if ( this.topics && this.topics[ id ] )
147 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
151 bind: function( id ) {
152 this.topics = this.topics || {};
153 this.topics[ id ] = this.topics[ id ] || $.Callbacks();
154 this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
158 unbind: function( id ) {
159 if ( this.topics && this.topics[ id ] )
160 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
166 * Observable values that support two-way binding.
170 api.Value = api.Class.extend({
172 * @param {mixed} initial The initial value.
173 * @param {object} options
175 initialize: function( initial, options ) {
176 this._value = initial; // @todo: potentially change this to a this.set() call.
177 this.callbacks = $.Callbacks();
180 $.extend( this, options || {} );
182 this.set = $.proxy( this.set, this );
186 * Magic. Returns a function that will become the instance.
187 * Set to null to prevent the instance from extending a function.
189 instance: function() {
190 return arguments.length ? this.set.apply( this, arguments ) : this.get();
203 * Set the value and trigger all bound callbacks.
205 * @param {object} to New value.
207 set: function( to ) {
208 var from = this._value;
210 to = this._setter.apply( this, arguments );
211 to = this.validate( to );
213 // Bail if the sanitized value is null or unchanged.
214 if ( null === to || _.isEqual( from, to ) ) {
221 this.callbacks.fireWith( this, [ to, from ] );
226 _setter: function( to ) {
230 setter: function( callback ) {
231 var from = this.get();
232 this._setter = callback;
233 // Temporarily clear value so setter can decide if it's valid.
239 resetSetter: function() {
240 this._setter = this.constructor.prototype._setter;
241 this.set( this.get() );
245 validate: function( value ) {
250 * Bind a function to be invoked whenever the value changes.
252 * @param {...Function} A function, or multiple functions, to add to the callback stack.
255 this.callbacks.add.apply( this.callbacks, arguments );
260 * Unbind a previously bound function.
262 * @param {...Function} A function, or multiple functions, to remove from the callback stack.
265 this.callbacks.remove.apply( this.callbacks, arguments );
269 link: function() { // values*
271 $.each( arguments, function() {
277 unlink: function() { // values*
279 $.each( arguments, function() {
285 sync: function() { // values*
287 $.each( arguments, function() {
294 unsync: function() { // values*
296 $.each( arguments, function() {
305 * A collection of observable values.
308 * @augments wp.customize.Class
309 * @mixes wp.customize.Events
311 api.Values = api.Class.extend({
314 * The default constructor for items of the collection.
318 defaultConstructor: api.Value,
320 initialize: function( options ) {
321 $.extend( this, options || {} );
324 this._deferreds = {};
328 * Get the instance of an item from the collection if only ID is specified.
330 * If more than one argument is supplied, all are expected to be IDs and
331 * the last to be a function callback that will be invoked when the requested
332 * items are available.
334 * @see {api.Values.when}
336 * @param {string} id ID of the item.
337 * @param {...} Zero or more IDs of items to wait for and a callback
338 * function to invoke when they're available. Optional.
339 * @return {mixed} The item instance if only one ID was supplied.
340 * A Deferred Promise object if a callback function is supplied.
342 instance: function( id ) {
343 if ( arguments.length === 1 )
344 return this.value( id );
346 return this.when.apply( this, arguments );
350 * Get the instance of an item.
352 * @param {string} id The ID of the item.
353 * @return {[type]} [description]
355 value: function( id ) {
356 return this._value[ id ];
360 * Whether the collection has an item with the given ID.
362 * @param {string} id The ID of the item to look for.
365 has: function( id ) {
366 return typeof this._value[ id ] !== 'undefined';
370 * Add an item to the collection.
372 * @param {string} id The ID of the item.
373 * @param {mixed} value The item instance.
374 * @return {mixed} The new item's instance.
376 add: function( id, value ) {
377 if ( this.has( id ) )
378 return this.value( id );
380 this._value[ id ] = value;
383 // Propagate a 'change' event on an item up to the collection.
384 if ( value.extended( api.Value ) )
385 value.bind( this._change );
387 this.trigger( 'add', value );
389 // If a deferred object exists for this item,
391 if ( this._deferreds[ id ] )
392 this._deferreds[ id ].resolve();
394 return this._value[ id ];
398 * Create a new item of the collection using the collection's default constructor
399 * and store it in the collection.
401 * @param {string} id The ID of the item.
402 * @param {mixed} value Any extra arguments are passed into the item's initialize method.
403 * @return {mixed} The new item's instance.
405 create: function( id ) {
406 return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
410 * Iterate over all items in the collection invoking the provided callback.
412 * @param {Function} callback Function to invoke.
413 * @param {object} context Object context to invoke the function with. Optional.
415 each: function( callback, context ) {
416 context = typeof context === 'undefined' ? this : context;
418 $.each( this._value, function( key, obj ) {
419 callback.call( context, obj, key );
424 * Remove an item from the collection.
426 * @param {string} id The ID of the item to remove.
428 remove: function( id ) {
431 if ( this.has( id ) ) {
432 value = this.value( id );
433 this.trigger( 'remove', value );
434 if ( value.extended( api.Value ) )
435 value.unbind( this._change );
439 delete this._value[ id ];
440 delete this._deferreds[ id ];
444 * Runs a callback once all requested values exist.
446 * when( ids*, [callback] );
449 * when( id1, id2, id3, function( value1, value2, value3 ) {} );
451 * @returns $.Deferred.promise();
455 ids = slice.call( arguments ),
458 // If the last argument is a callback, bind it to .done()
459 if ( $.isFunction( ids[ ids.length - 1 ] ) )
460 dfd.done( ids.pop() );
463 * Create a stack of deferred objects for each item that is not
464 * yet available, and invoke the supplied callback when they are.
466 $.when.apply( $, $.map( ids, function( id ) {
467 if ( self.has( id ) )
471 * The requested item is not available yet, create a deferred
472 * object to resolve when it becomes available.
474 return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
475 })).done( function() {
476 var values = $.map( ids, function( id ) {
480 // If a value is missing, we've used at least one expired deferred.
481 // Call Values.when again to generate a new deferred.
482 if ( values.length !== ids.length ) {
483 // ids.push( callback );
484 self.when.apply( self, ids ).done( function() {
485 dfd.resolveWith( self, values );
490 dfd.resolveWith( self, values );
493 return dfd.promise();
497 * A helper function to propagate a 'change' event from an item
498 * to the collection itself.
500 _change: function() {
501 this.parent.trigger( 'change', this );
505 // Create a global events bus on the Customizer.
506 $.extend( api.Values.prototype, api.Events );
510 * Cast a string to a jQuery collection if it isn't already.
512 * @param {string|jQuery collection} element
514 api.ensure = function( element ) {
515 return typeof element == 'string' ? $( element ) : element;
519 * An observable value that syncs with an element.
521 * Handles inputs, selects, and textareas by default.
524 * @augments wp.customize.Value
525 * @augments wp.customize.Class
527 api.Element = api.Value.extend({
528 initialize: function( element, options ) {
530 synchronizer = api.Element.synchronizer.html,
531 type, update, refresh;
533 this.element = api.ensure( element );
536 if ( this.element.is('input, select, textarea') ) {
537 this.events += 'change';
538 synchronizer = api.Element.synchronizer.val;
540 if ( this.element.is('input') ) {
541 type = this.element.prop('type');
542 if ( api.Element.synchronizer[ type ] ) {
543 synchronizer = api.Element.synchronizer[ type ];
545 if ( 'text' === type || 'password' === type ) {
546 this.events += ' keyup';
547 } else if ( 'range' === type ) {
548 this.events += ' input propertychange';
550 } else if ( this.element.is('textarea') ) {
551 this.events += ' keyup';
555 api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
556 this._value = this.get();
558 update = this.update;
559 refresh = this.refresh;
561 this.update = function( to ) {
562 if ( to !== refresh.call( self ) )
563 update.apply( this, arguments );
565 this.refresh = function() {
566 self.set( refresh.call( self ) );
569 this.bind( this.update );
570 this.element.bind( this.events, this.refresh );
573 find: function( selector ) {
574 return $( selector, this.element );
577 refresh: function() {},
579 update: function() {}
582 api.Element.synchronizer = {};
584 $.each( [ 'html', 'val' ], function( index, method ) {
585 api.Element.synchronizer[ method ] = {
586 update: function( to ) {
587 this.element[ method ]( to );
589 refresh: function() {
590 return this.element[ method ]();
595 api.Element.synchronizer.checkbox = {
596 update: function( to ) {
597 this.element.prop( 'checked', to );
599 refresh: function() {
600 return this.element.prop( 'checked' );
604 api.Element.synchronizer.radio = {
605 update: function( to ) {
606 this.element.filter( function() {
607 return this.value === to;
608 }).prop( 'checked', true );
610 refresh: function() {
611 return this.element.filter( ':checked' ).val();
615 $.support.postMessage = !! window.postMessage;
618 * A communicator for sending data from one window to another over postMessage.
621 * @augments wp.customize.Class
622 * @mixes wp.customize.Events
624 api.Messenger = api.Class.extend({
626 * Create a new Value.
628 * @param {string} key Unique identifier.
629 * @param {mixed} initial Initial value.
630 * @param {mixed} options Options hash. Optional.
631 * @return {Value} Class instance of the Value.
633 add: function( key, initial, options ) {
634 return this[ key ] = new api.Value( initial, options );
638 * Initialize Messenger.
640 * @param {object} params Parameters to configure the messenger.
641 * {string} .url The URL to communicate with.
642 * {window} .targetWindow The window instance to communicate with. Default window.parent.
643 * {string} .channel If provided, will send the channel with each message and only accept messages a matching channel.
644 * @param {object} options Extend any instance parameter or method with this object.
646 initialize: function( params, options ) {
647 // Target the parent frame by default, but only if a parent frame exists.
648 var defaultTarget = window.parent == window ? null : window.parent;
650 $.extend( this, options || {} );
652 this.add( 'channel', params.channel );
653 this.add( 'url', params.url || '' );
654 this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
655 return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
658 // first add with no value
659 this.add( 'targetWindow', null );
660 // This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
661 this.targetWindow.set = function( to ) {
662 var from = this._value;
664 to = this._setter.apply( this, arguments );
665 to = this.validate( to );
667 if ( null === to || from === to ) {
674 this.callbacks.fireWith( this, [ to, from ] );
679 this.targetWindow( params.targetWindow || defaultTarget );
682 // Since we want jQuery to treat the receive function as unique
683 // to this instance, we give the function a new guid.
685 // This will prevent every Messenger's receive function from being
686 // unbound when calling $.off( 'message', this.receive );
687 this.receive = $.proxy( this.receive, this );
688 this.receive.guid = $.guid++;
690 $( window ).on( 'message', this.receive );
693 destroy: function() {
694 $( window ).off( 'message', this.receive );
698 * Receive data from the other window.
700 * @param {jQuery.Event} event Event with embedded data.
702 receive: function( event ) {
705 event = event.originalEvent;
707 if ( ! this.targetWindow || ! this.targetWindow() ) {
711 // Check to make sure the origin is valid.
712 if ( this.origin() && event.origin !== this.origin() )
715 // Ensure we have a string that's JSON.parse-able
716 if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
720 message = JSON.parse( event.data );
722 // Check required message properties.
723 if ( ! message || ! message.id || typeof message.data === 'undefined' )
726 // Check if channel names match.
727 if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
730 this.trigger( message.id, message.data );
734 * Send data to the other window.
736 * @param {string} id The event name.
737 * @param {object} data Data.
739 send: function( id, data ) {
742 data = typeof data === 'undefined' ? null : data;
744 if ( ! this.url() || ! this.targetWindow() )
747 message = { id: id, data: data };
748 if ( this.channel() )
749 message.channel = this.channel();
751 this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
755 // Add the Events mixin to api.Messenger.
756 $.extend( api.Messenger.prototype, api.Events );
762 * @augments wp.customize.Class
765 * @param {string} code The error code.
766 * @param {object} params Params.
767 * @param {string} params.message The error message.
768 * @param {string} [params.type=error] The notification type.
769 * @param {*} [params.data] Any additional data.
771 api.Notification = api.Class.extend({
772 initialize: function( code, params ) {
774 this.message = params.message;
775 this.type = params.type || 'error';
776 this.data = params.data || null;
780 // The main API object is also a collection of all customizer settings.
781 api = $.extend( new api.Values(), api );
784 * Get all customize settings.
788 api.get = function() {
791 this.each( function( obj, key ) {
792 result[ key ] = obj.get();
798 // Expose the API publicly on window.wp.customize
799 exports.customize = api;