]> scripts.mit.edu Git - autoinstalls/wordpress.git/blob - wp-includes/js/customize-base.js
WordPress 4.2.1-scripts
[autoinstalls/wordpress.git] / wp-includes / js / customize-base.js
1 window.wp = window.wp || {};
2
3 (function( exports, $ ){
4         var api = {}, ctor, inherits,
5                 slice = Array.prototype.slice;
6
7         // Shared empty constructor function to aid in prototype-chain creation.
8         ctor = function() {};
9
10         /**
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.
14          *
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.
19          */
20         inherits = function( parent, protoProps, staticProps ) {
21                 var child;
22
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;
28                 } else {
29                         child = function() {
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 );
35                                 return result;
36                         };
37                 }
38
39                 // Inherit class (static) properties from parent.
40                 $.extend( child, parent );
41
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();
46
47                 // Add prototype properties (instance properties) to the subclass,
48                 // if supplied.
49                 if ( protoProps )
50                         $.extend( child.prototype, protoProps );
51
52                 // Add static properties to the constructor function, if supplied.
53                 if ( staticProps )
54                         $.extend( child, staticProps );
55
56                 // Correctly set child's `prototype.constructor`.
57                 child.prototype.constructor = child;
58
59                 // Set a convenience property in case the parent's prototype is needed later.
60                 child.__super__ = parent.prototype;
61
62                 return child;
63         };
64
65         /**
66          * Base class for object inheritance.
67          */
68         api.Class = function( applicator, argsArray, options ) {
69                 var magic, args = arguments;
70
71                 if ( applicator && argsArray && api.Class.applicator === applicator ) {
72                         args = argsArray;
73                         $.extend( this, options || {} );
74                 }
75
76                 magic = this;
77                 if ( this.instance ) {
78                         magic = function() {
79                                 return magic.instance.apply( magic, arguments );
80                         };
81
82                         $.extend( magic, this );
83                 }
84
85                 magic.initialize.apply( magic, args );
86                 return magic;
87         };
88
89         /**
90          * Creates a subclass of the class.
91          *
92          * @param  object protoProps  Properties to apply to the prototype.
93          * @param  object staticProps Properties to apply directly to the class.
94          * @return child              The subclass.
95          */
96         api.Class.extend = function( protoProps, classProps ) {
97                 var child = inherits( this, protoProps, classProps );
98                 child.extend = this.extend;
99                 return child;
100         };
101
102         api.Class.applicator = {};
103
104         api.Class.prototype.initialize = function() {};
105
106         /*
107          * Checks whether a given instance extended a constructor.
108          *
109          * The magic surrounding the instance parameter causes the instanceof
110          * keyword to return inaccurate results; it defaults to the function's
111          * prototype instead of the constructor chain. Hence this function.
112          */
113         api.Class.prototype.extended = function( constructor ) {
114                 var proto = this;
115
116                 while ( typeof proto.constructor !== 'undefined' ) {
117                         if ( proto.constructor === constructor )
118                                 return true;
119                         if ( typeof proto.constructor.__super__ === 'undefined' )
120                                 return false;
121                         proto = proto.constructor.__super__;
122                 }
123                 return false;
124         };
125
126         /**
127          * An events manager object, offering the ability to bind to and trigger events.
128          *
129          * Used as a mixin.
130          */
131         api.Events = {
132                 trigger: function( id ) {
133                         if ( this.topics && this.topics[ id ] )
134                                 this.topics[ id ].fireWith( this, slice.call( arguments, 1 ) );
135                         return this;
136                 },
137
138                 bind: function( id ) {
139                         this.topics = this.topics || {};
140                         this.topics[ id ] = this.topics[ id ] || $.Callbacks();
141                         this.topics[ id ].add.apply( this.topics[ id ], slice.call( arguments, 1 ) );
142                         return this;
143                 },
144
145                 unbind: function( id ) {
146                         if ( this.topics && this.topics[ id ] )
147                                 this.topics[ id ].remove.apply( this.topics[ id ], slice.call( arguments, 1 ) );
148                         return this;
149                 }
150         };
151
152         /**
153          * Observable values that support two-way binding.
154          *
155          * @constuctor
156          */
157         api.Value = api.Class.extend({
158                 initialize: function( initial, options ) {
159                         this._value = initial; // @todo: potentially change this to a this.set() call.
160                         this.callbacks = $.Callbacks();
161                         this._dirty = false;
162
163                         $.extend( this, options || {} );
164
165                         this.set = $.proxy( this.set, this );
166                 },
167
168                 /*
169                  * Magic. Returns a function that will become the instance.
170                  * Set to null to prevent the instance from extending a function.
171                  */
172                 instance: function() {
173                         return arguments.length ? this.set.apply( this, arguments ) : this.get();
174                 },
175
176                 get: function() {
177                         return this._value;
178                 },
179
180                 set: function( to ) {
181                         var from = this._value;
182
183                         to = this._setter.apply( this, arguments );
184                         to = this.validate( to );
185
186                         // Bail if the sanitized value is null or unchanged.
187                         if ( null === to || _.isEqual( from, to ) ) {
188                                 return this;
189                         }
190
191                         this._value = to;
192                         this._dirty = true;
193
194                         this.callbacks.fireWith( this, [ to, from ] );
195
196                         return this;
197                 },
198
199                 _setter: function( to ) {
200                         return to;
201                 },
202
203                 setter: function( callback ) {
204                         var from = this.get();
205                         this._setter = callback;
206                         // Temporarily clear value so setter can decide if it's valid.
207                         this._value = null;
208                         this.set( from );
209                         return this;
210                 },
211
212                 resetSetter: function() {
213                         this._setter = this.constructor.prototype._setter;
214                         this.set( this.get() );
215                         return this;
216                 },
217
218                 validate: function( value ) {
219                         return value;
220                 },
221
222                 bind: function() {
223                         this.callbacks.add.apply( this.callbacks, arguments );
224                         return this;
225                 },
226
227                 unbind: function() {
228                         this.callbacks.remove.apply( this.callbacks, arguments );
229                         return this;
230                 },
231
232                 link: function() { // values*
233                         var set = this.set;
234                         $.each( arguments, function() {
235                                 this.bind( set );
236                         });
237                         return this;
238                 },
239
240                 unlink: function() { // values*
241                         var set = this.set;
242                         $.each( arguments, function() {
243                                 this.unbind( set );
244                         });
245                         return this;
246                 },
247
248                 sync: function() { // values*
249                         var that = this;
250                         $.each( arguments, function() {
251                                 that.link( this );
252                                 this.link( that );
253                         });
254                         return this;
255                 },
256
257                 unsync: function() { // values*
258                         var that = this;
259                         $.each( arguments, function() {
260                                 that.unlink( this );
261                                 this.unlink( that );
262                         });
263                         return this;
264                 }
265         });
266
267         /**
268          * A collection of observable values.
269          *
270          * @constuctor
271          * @augments wp.customize.Class
272          * @mixes wp.customize.Events
273          */
274         api.Values = api.Class.extend({
275                 defaultConstructor: api.Value,
276
277                 initialize: function( options ) {
278                         $.extend( this, options || {} );
279
280                         this._value = {};
281                         this._deferreds = {};
282                 },
283
284                 instance: function( id ) {
285                         if ( arguments.length === 1 )
286                                 return this.value( id );
287
288                         return this.when.apply( this, arguments );
289                 },
290
291                 value: function( id ) {
292                         return this._value[ id ];
293                 },
294
295                 has: function( id ) {
296                         return typeof this._value[ id ] !== 'undefined';
297                 },
298
299                 add: function( id, value ) {
300                         if ( this.has( id ) )
301                                 return this.value( id );
302
303                         this._value[ id ] = value;
304                         value.parent = this;
305                         if ( value.extended( api.Value ) )
306                                 value.bind( this._change );
307
308                         this.trigger( 'add', value );
309
310                         if ( this._deferreds[ id ] )
311                                 this._deferreds[ id ].resolve();
312
313                         return this._value[ id ];
314                 },
315
316                 create: function( id ) {
317                         return this.add( id, new this.defaultConstructor( api.Class.applicator, slice.call( arguments, 1 ) ) );
318                 },
319
320                 each: function( callback, context ) {
321                         context = typeof context === 'undefined' ? this : context;
322
323                         $.each( this._value, function( key, obj ) {
324                                 callback.call( context, obj, key );
325                         });
326                 },
327
328                 remove: function( id ) {
329                         var value;
330
331                         if ( this.has( id ) ) {
332                                 value = this.value( id );
333                                 this.trigger( 'remove', value );
334                                 if ( value.extended( api.Value ) )
335                                         value.unbind( this._change );
336                                 delete value.parent;
337                         }
338
339                         delete this._value[ id ];
340                         delete this._deferreds[ id ];
341                 },
342
343                 /**
344                  * Runs a callback once all requested values exist.
345                  *
346                  * when( ids*, [callback] );
347                  *
348                  * For example:
349                  *     when( id1, id2, id3, function( value1, value2, value3 ) {} );
350                  *
351                  * @returns $.Deferred.promise();
352                  */
353                 when: function() {
354                         var self = this,
355                                 ids  = slice.call( arguments ),
356                                 dfd  = $.Deferred();
357
358                         // If the last argument is a callback, bind it to .done()
359                         if ( $.isFunction( ids[ ids.length - 1 ] ) )
360                                 dfd.done( ids.pop() );
361
362                         $.when.apply( $, $.map( ids, function( id ) {
363                                 if ( self.has( id ) )
364                                         return;
365
366                                 return self._deferreds[ id ] = self._deferreds[ id ] || $.Deferred();
367                         })).done( function() {
368                                 var values = $.map( ids, function( id ) {
369                                                 return self( id );
370                                         });
371
372                                 // If a value is missing, we've used at least one expired deferred.
373                                 // Call Values.when again to generate a new deferred.
374                                 if ( values.length !== ids.length ) {
375                                         // ids.push( callback );
376                                         self.when.apply( self, ids ).done( function() {
377                                                 dfd.resolveWith( self, values );
378                                         });
379                                         return;
380                                 }
381
382                                 dfd.resolveWith( self, values );
383                         });
384
385                         return dfd.promise();
386                 },
387
388                 _change: function() {
389                         this.parent.trigger( 'change', this );
390                 }
391         });
392
393         $.extend( api.Values.prototype, api.Events );
394
395
396         /**
397          * Cast a string to a jQuery collection if it isn't already.
398          *
399          * @param {string|jQuery collection} element
400          */
401         api.ensure = function( element ) {
402                 return typeof element == 'string' ? $( element ) : element;
403         };
404
405         /**
406          * An observable value that syncs with an element.
407          *
408          * Handles inputs, selects, and textareas by default.
409          *
410          * @constuctor
411          * @augments wp.customize.Value
412          * @augments wp.customize.Class
413          */
414         api.Element = api.Value.extend({
415                 initialize: function( element, options ) {
416                         var self = this,
417                                 synchronizer = api.Element.synchronizer.html,
418                                 type, update, refresh;
419
420                         this.element = api.ensure( element );
421                         this.events = '';
422
423                         if ( this.element.is('input, select, textarea') ) {
424                                 this.events += 'change';
425                                 synchronizer = api.Element.synchronizer.val;
426
427                                 if ( this.element.is('input') ) {
428                                         type = this.element.prop('type');
429                                         if ( api.Element.synchronizer[ type ] ) {
430                                                 synchronizer = api.Element.synchronizer[ type ];
431                                         }
432                                         if ( 'text' === type || 'password' === type ) {
433                                                 this.events += ' keyup';
434                                         } else if ( 'range' === type ) {
435                                                 this.events += ' input propertychange';
436                                         }
437                                 } else if ( this.element.is('textarea') ) {
438                                         this.events += ' keyup';
439                                 }
440                         }
441
442                         api.Value.prototype.initialize.call( this, null, $.extend( options || {}, synchronizer ) );
443                         this._value = this.get();
444
445                         update  = this.update;
446                         refresh = this.refresh;
447
448                         this.update = function( to ) {
449                                 if ( to !== refresh.call( self ) )
450                                         update.apply( this, arguments );
451                         };
452                         this.refresh = function() {
453                                 self.set( refresh.call( self ) );
454                         };
455
456                         this.bind( this.update );
457                         this.element.bind( this.events, this.refresh );
458                 },
459
460                 find: function( selector ) {
461                         return $( selector, this.element );
462                 },
463
464                 refresh: function() {},
465
466                 update: function() {}
467         });
468
469         api.Element.synchronizer = {};
470
471         $.each( [ 'html', 'val' ], function( index, method ) {
472                 api.Element.synchronizer[ method ] = {
473                         update: function( to ) {
474                                 this.element[ method ]( to );
475                         },
476                         refresh: function() {
477                                 return this.element[ method ]();
478                         }
479                 };
480         });
481
482         api.Element.synchronizer.checkbox = {
483                 update: function( to ) {
484                         this.element.prop( 'checked', to );
485                 },
486                 refresh: function() {
487                         return this.element.prop( 'checked' );
488                 }
489         };
490
491         api.Element.synchronizer.radio = {
492                 update: function( to ) {
493                         this.element.filter( function() {
494                                 return this.value === to;
495                         }).prop( 'checked', true );
496                 },
497                 refresh: function() {
498                         return this.element.filter( ':checked' ).val();
499                 }
500         };
501
502         $.support.postMessage = !! window.postMessage;
503
504         /**
505          * Messenger for postMessage.
506          *
507          * @constuctor
508          * @augments wp.customize.Class
509          * @mixes wp.customize.Events
510          */
511         api.Messenger = api.Class.extend({
512                 /**
513                  * Create a new Value.
514                  *
515                  * @param  {string} key     Unique identifier.
516                  * @param  {mixed}  initial Initial value.
517                  * @param  {mixed}  options Options hash. Optional.
518                  * @return {Value}          Class instance of the Value.
519                  */
520                 add: function( key, initial, options ) {
521                         return this[ key ] = new api.Value( initial, options );
522                 },
523
524                 /**
525                  * Initialize Messenger.
526                  *
527                  * @param  {object} params        Parameters to configure the messenger.
528                  *         {string} .url          The URL to communicate with.
529                  *         {window} .targetWindow The window instance to communicate with. Default window.parent.
530                  *         {string} .channel      If provided, will send the channel with each message and only accept messages a matching channel.
531                  * @param  {object} options       Extend any instance parameter or method with this object.
532                  */
533                 initialize: function( params, options ) {
534                         // Target the parent frame by default, but only if a parent frame exists.
535                         var defaultTarget = window.parent == window ? null : window.parent;
536
537                         $.extend( this, options || {} );
538
539                         this.add( 'channel', params.channel );
540                         this.add( 'url', params.url || '' );
541                         this.add( 'origin', this.url() ).link( this.url ).setter( function( to ) {
542                                 return to.replace( /([^:]+:\/\/[^\/]+).*/, '$1' );
543                         });
544
545                         // first add with no value
546                         this.add( 'targetWindow', null );
547                         // This avoids SecurityErrors when setting a window object in x-origin iframe'd scenarios.
548                         this.targetWindow.set = function( to ) {
549                                 var from = this._value;
550
551                                 to = this._setter.apply( this, arguments );
552                                 to = this.validate( to );
553
554                                 if ( null === to || from === to ) {
555                                         return this;
556                                 }
557
558                                 this._value = to;
559                                 this._dirty = true;
560
561                                 this.callbacks.fireWith( this, [ to, from ] );
562
563                                 return this;
564                         };
565                         // now set it
566                         this.targetWindow( params.targetWindow || defaultTarget );
567
568
569                         // Since we want jQuery to treat the receive function as unique
570                         // to this instance, we give the function a new guid.
571                         //
572                         // This will prevent every Messenger's receive function from being
573                         // unbound when calling $.off( 'message', this.receive );
574                         this.receive = $.proxy( this.receive, this );
575                         this.receive.guid = $.guid++;
576
577                         $( window ).on( 'message', this.receive );
578                 },
579
580                 destroy: function() {
581                         $( window ).off( 'message', this.receive );
582                 },
583
584                 receive: function( event ) {
585                         var message;
586
587                         event = event.originalEvent;
588
589                         if ( ! this.targetWindow() )
590                                 return;
591
592                         // Check to make sure the origin is valid.
593                         if ( this.origin() && event.origin !== this.origin() )
594                                 return;
595
596                         // Ensure we have a string that's JSON.parse-able
597                         if ( typeof event.data !== 'string' || event.data[0] !== '{' ) {
598                                 return;
599                         }
600
601                         message = JSON.parse( event.data );
602
603                         // Check required message properties.
604                         if ( ! message || ! message.id || typeof message.data === 'undefined' )
605                                 return;
606
607                         // Check if channel names match.
608                         if ( ( message.channel || this.channel() ) && this.channel() !== message.channel )
609                                 return;
610
611                         this.trigger( message.id, message.data );
612                 },
613
614                 send: function( id, data ) {
615                         var message;
616
617                         data = typeof data === 'undefined' ? null : data;
618
619                         if ( ! this.url() || ! this.targetWindow() )
620                                 return;
621
622                         message = { id: id, data: data };
623                         if ( this.channel() )
624                                 message.channel = this.channel();
625
626                         this.targetWindow().postMessage( JSON.stringify( message ), this.origin() );
627                 }
628         });
629
630         // Add the Events mixin to api.Messenger.
631         $.extend( api.Messenger.prototype, api.Events );
632
633         // Core customize object.
634         api = $.extend( new api.Values(), api );
635         api.get = function() {
636                 var result = {};
637
638                 this.each( function( obj, key ) {
639                         result[ key ] = obj.get();
640                 });
641
642                 return result;
643         };
644
645         // Expose the API publicly on window.wp.customize
646         exports.customize = api;
647 })( wp, jQuery );