Merge "Accessor to get EditPage parent revision ID"
[lhc/web/wiklou.git] / resources / lib / oojs / oojs.jquery.js
1 /*!
2 * OOjs v1.1.10 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
4 *
5 * Copyright 2011-2015 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
8 *
9 * Date: 2015-11-11T16:49:11Z
10 */
11 ( function ( global ) {
12
13 'use strict';
14
15 /*exported toString */
16 var
17 /**
18 * Namespace for all classes, static methods and static properties.
19 * @class OO
20 * @singleton
21 */
22 oo = {},
23 // Optimisation: Local reference to Object.prototype.hasOwnProperty
24 hasOwn = oo.hasOwnProperty,
25 toString = oo.toString,
26 // Object.create() is impossible to fully polyfill, so don't require it
27 createObject = Object.create || ( function () {
28 // Reusable constructor function
29 function Empty() {}
30 return function ( prototype, properties ) {
31 var obj;
32 Empty.prototype = prototype;
33 obj = new Empty();
34 if ( properties && hasOwn.call( properties, 'constructor' ) ) {
35 obj.constructor = properties.constructor.value;
36 }
37 return obj;
38 };
39 } )();
40
41 /* Class Methods */
42
43 /**
44 * Utility to initialize a class for OO inheritance.
45 *
46 * Currently this just initializes an empty static object.
47 *
48 * @param {Function} fn
49 */
50 oo.initClass = function ( fn ) {
51 fn.static = fn.static || {};
52 };
53
54 /**
55 * Inherit from prototype to another using Object#create.
56 *
57 * Beware: This redefines the prototype, call before setting your prototypes.
58 *
59 * Beware: This redefines the prototype, can only be called once on a function.
60 * If called multiple times on the same function, the previous prototype is lost.
61 * This is how prototypal inheritance works, it can only be one straight chain
62 * (just like classical inheritance in PHP for example). If you need to work with
63 * multiple constructors consider storing an instance of the other constructor in a
64 * property instead, or perhaps use a mixin (see OO.mixinClass).
65 *
66 * function Thing() {}
67 * Thing.prototype.exists = function () {};
68 *
69 * function Person() {
70 * Person.super.apply( this, arguments );
71 * }
72 * OO.inheritClass( Person, Thing );
73 * Person.static.defaultEyeCount = 2;
74 * Person.prototype.walk = function () {};
75 *
76 * function Jumper() {
77 * Jumper.super.apply( this, arguments );
78 * }
79 * OO.inheritClass( Jumper, Person );
80 * Jumper.prototype.jump = function () {};
81 *
82 * Jumper.static.defaultEyeCount === 2;
83 * var x = new Jumper();
84 * x.jump();
85 * x.walk();
86 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
87 *
88 * @param {Function} targetFn
89 * @param {Function} originFn
90 * @throws {Error} If target already inherits from origin
91 */
92 oo.inheritClass = function ( targetFn, originFn ) {
93 var targetConstructor;
94
95 if ( targetFn.prototype instanceof originFn ) {
96 throw new Error( 'Target already inherits from origin' );
97 }
98
99 targetConstructor = targetFn.prototype.constructor;
100
101 // Using ['super'] instead of .super because 'super' is not supported
102 // by IE 8 and below (bug 63303).
103 // Provide .parent as alias for code supporting older browsers which
104 // allows people to comply with their style guide.
105 targetFn[ 'super' ] = targetFn.parent = originFn;
106
107 targetFn.prototype = createObject( originFn.prototype, {
108 // Restore constructor property of targetFn
109 constructor: {
110 value: targetConstructor,
111 enumerable: false,
112 writable: true,
113 configurable: true
114 }
115 } );
116
117 // Extend static properties - always initialize both sides
118 oo.initClass( originFn );
119 targetFn.static = createObject( originFn.static );
120 };
121
122 /**
123 * Copy over *own* prototype properties of a mixin.
124 *
125 * The 'constructor' (whether implicit or explicit) is not copied over.
126 *
127 * This does not create inheritance to the origin. If you need inheritance,
128 * use OO.inheritClass instead.
129 *
130 * Beware: This can redefine a prototype property, call before setting your prototypes.
131 *
132 * Beware: Don't call before OO.inheritClass.
133 *
134 * function Foo() {}
135 * function Context() {}
136 *
137 * // Avoid repeating this code
138 * function ContextLazyLoad() {}
139 * ContextLazyLoad.prototype.getContext = function () {
140 * if ( !this.context ) {
141 * this.context = new Context();
142 * }
143 * return this.context;
144 * };
145 *
146 * function FooBar() {}
147 * OO.inheritClass( FooBar, Foo );
148 * OO.mixinClass( FooBar, ContextLazyLoad );
149 *
150 * @param {Function} targetFn
151 * @param {Function} originFn
152 */
153 oo.mixinClass = function ( targetFn, originFn ) {
154 var key;
155
156 // Copy prototype properties
157 for ( key in originFn.prototype ) {
158 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
159 targetFn.prototype[ key ] = originFn.prototype[ key ];
160 }
161 }
162
163 // Copy static properties - always initialize both sides
164 oo.initClass( targetFn );
165 if ( originFn.static ) {
166 for ( key in originFn.static ) {
167 if ( hasOwn.call( originFn.static, key ) ) {
168 targetFn.static[ key ] = originFn.static[ key ];
169 }
170 }
171 } else {
172 oo.initClass( originFn );
173 }
174 };
175
176 /* Object Methods */
177
178 /**
179 * Get a deeply nested property of an object using variadic arguments, protecting against
180 * undefined property errors.
181 *
182 * `quux = oo.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
183 * except that the former protects against JS errors if one of the intermediate properties
184 * is undefined. Instead of throwing an error, this function will return undefined in
185 * that case.
186 *
187 * @param {Object} obj
188 * @param {...Mixed} [keys]
189 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
190 */
191 oo.getProp = function ( obj ) {
192 var i,
193 retval = obj;
194 for ( i = 1; i < arguments.length; i++ ) {
195 if ( retval === undefined || retval === null ) {
196 // Trying to access a property of undefined or null causes an error
197 return undefined;
198 }
199 retval = retval[ arguments[ i ] ];
200 }
201 return retval;
202 };
203
204 /**
205 * Set a deeply nested property of an object using variadic arguments, protecting against
206 * undefined property errors.
207 *
208 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
209 * the former protects against JS errors if one of the intermediate properties is
210 * undefined. Instead of throwing an error, undefined intermediate properties will be
211 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
212 * is not an object, this function will silently abort.
213 *
214 * @param {Object} obj
215 * @param {...Mixed} [keys]
216 * @param {Mixed} [value]
217 */
218 oo.setProp = function ( obj ) {
219 var i,
220 prop = obj;
221 if ( Object( obj ) !== obj ) {
222 return;
223 }
224 for ( i = 1; i < arguments.length - 2; i++ ) {
225 if ( prop[ arguments[ i ] ] === undefined ) {
226 prop[ arguments[ i ] ] = {};
227 }
228 if ( Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) {
229 return;
230 }
231 prop = prop[ arguments[ i ] ];
232 }
233 prop[ arguments[ arguments.length - 2 ] ] = arguments[ arguments.length - 1 ];
234 };
235
236 /**
237 * Create a new object that is an instance of the same
238 * constructor as the input, inherits from the same object
239 * and contains the same own properties.
240 *
241 * This makes a shallow non-recursive copy of own properties.
242 * To create a recursive copy of plain objects, use #copy.
243 *
244 * var foo = new Person( mom, dad );
245 * foo.setAge( 21 );
246 * var foo2 = OO.cloneObject( foo );
247 * foo.setAge( 22 );
248 *
249 * // Then
250 * foo2 !== foo; // true
251 * foo2 instanceof Person; // true
252 * foo2.getAge(); // 21
253 * foo.getAge(); // 22
254 *
255 * @param {Object} origin
256 * @return {Object} Clone of origin
257 */
258 oo.cloneObject = function ( origin ) {
259 var key, r;
260
261 r = createObject( origin.constructor.prototype );
262
263 for ( key in origin ) {
264 if ( hasOwn.call( origin, key ) ) {
265 r[ key ] = origin[ key ];
266 }
267 }
268
269 return r;
270 };
271
272 /**
273 * Get an array of all property values in an object.
274 *
275 * @param {Object} obj Object to get values from
276 * @return {Array} List of object values
277 */
278 oo.getObjectValues = function ( obj ) {
279 var key, values;
280
281 if ( obj !== Object( obj ) ) {
282 throw new TypeError( 'Called on non-object' );
283 }
284
285 values = [];
286 for ( key in obj ) {
287 if ( hasOwn.call( obj, key ) ) {
288 values[ values.length ] = obj[ key ];
289 }
290 }
291
292 return values;
293 };
294
295 /**
296 * Use binary search to locate an element in a sorted array.
297 *
298 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
299 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
300 * below 0 if it is to the left of elem, or zero if it's equal to elem.
301 *
302 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
303 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
304 * `searchFunc = cmp.bind( null, value )`.
305 *
306 * @param {Array} arr Array to search in
307 * @param {Function} searchFunc Search function
308 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
309 * @return {number|null} Index where val was found, or null if not found
310 */
311 oo.binarySearch = function ( arr, searchFunc, forInsertion ) {
312 var mid, cmpResult,
313 left = 0,
314 right = arr.length;
315 while ( left < right ) {
316 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
317 /*jshint bitwise:false */
318 mid = ( left + right ) >> 1;
319 cmpResult = searchFunc( arr[ mid ] );
320 if ( cmpResult < 0 ) {
321 right = mid;
322 } else if ( cmpResult > 0 ) {
323 left = mid + 1;
324 } else {
325 return mid;
326 }
327 }
328 return forInsertion ? right : null;
329 };
330
331 /**
332 * Recursively compare properties between two objects.
333 *
334 * A false result may be caused by property inequality or by properties in one object missing from
335 * the other. An asymmetrical test may also be performed, which checks only that properties in the
336 * first object are present in the second object, but not the inverse.
337 *
338 * If either a or b is null or undefined it will be treated as an empty object.
339 *
340 * @param {Object|undefined|null} a First object to compare
341 * @param {Object|undefined|null} b Second object to compare
342 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
343 * (i.e. a is a subset of b)
344 * @return {boolean} If the objects contain the same values as each other
345 */
346 oo.compare = function ( a, b, asymmetrical ) {
347 var aValue, bValue, aType, bType, k;
348
349 if ( a === b ) {
350 return true;
351 }
352
353 a = a || {};
354 b = b || {};
355
356 if ( typeof a.nodeType === 'number' && typeof a.isEqualNode === 'function' ) {
357 return a.isEqualNode( b );
358 }
359
360 for ( k in a ) {
361 if ( !hasOwn.call( a, k ) || a[ k ] === undefined || a[ k ] === b[ k ] ) {
362 // Support es3-shim: Without the hasOwn filter, comparing [] to {} will be false in ES3
363 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
364 // Also ignore undefined values, because there is no conceptual difference between
365 // a key that is absent and a key that is present but whose value is undefined.
366 continue;
367 }
368
369 aValue = a[ k ];
370 bValue = b[ k ];
371 aType = typeof aValue;
372 bType = typeof bValue;
373 if ( aType !== bType ||
374 (
375 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) &&
376 aValue !== bValue
377 ) ||
378 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, true ) ) ) {
379 return false;
380 }
381 }
382 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
383 return asymmetrical ? true : oo.compare( b, a, true );
384 };
385
386 /**
387 * Create a plain deep copy of any kind of object.
388 *
389 * Copies are deep, and will either be an object or an array depending on `source`.
390 *
391 * @param {Object} source Object to copy
392 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
393 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the nodeCallback returns a value other than undefined, the returned value is used instead of attempting to clone.
394 * @return {Object} Copy of source object
395 */
396 oo.copy = function ( source, leafCallback, nodeCallback ) {
397 var key, destination;
398
399 if ( nodeCallback ) {
400 // Extensibility: check before attempting to clone source.
401 destination = nodeCallback( source );
402 if ( destination !== undefined ) {
403 return destination;
404 }
405 }
406
407 if ( Array.isArray( source ) ) {
408 // Array (fall through)
409 destination = new Array( source.length );
410 } else if ( source && typeof source.clone === 'function' ) {
411 // Duck type object with custom clone method
412 return leafCallback ? leafCallback( source.clone() ) : source.clone();
413 } else if ( source && typeof source.cloneNode === 'function' ) {
414 // DOM Node
415 return leafCallback ?
416 leafCallback( source.cloneNode( true ) ) :
417 source.cloneNode( true );
418 } else if ( oo.isPlainObject( source ) ) {
419 // Plain objects (fall through)
420 destination = {};
421 } else {
422 // Non-plain objects (incl. functions) and primitive values
423 return leafCallback ? leafCallback( source ) : source;
424 }
425
426 // source is an array or a plain object
427 for ( key in source ) {
428 destination[ key ] = oo.copy( source[ key ], leafCallback, nodeCallback );
429 }
430
431 // This is an internal node, so we don't apply the leafCallback.
432 return destination;
433 };
434
435 /**
436 * Generate a hash of an object based on its name and data.
437 *
438 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
439 *
440 * To avoid two objects with the same values generating different hashes, we utilize the replacer
441 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
442 * not be the fastest way to do this; we should investigate this further.
443 *
444 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
445 * function, we call that function and use its return value rather than hashing the object
446 * ourselves. This allows classes to define custom hashing.
447 *
448 * @param {Object} val Object to generate hash for
449 * @return {string} Hash of object
450 */
451 oo.getHash = function ( val ) {
452 return JSON.stringify( val, oo.getHash.keySortReplacer );
453 };
454
455 /**
456 * Sort objects by key (helper function for OO.getHash).
457 *
458 * This is a callback passed into JSON.stringify.
459 *
460 * @method getHash_keySortReplacer
461 * @param {string} key Property name of value being replaced
462 * @param {Mixed} val Property value to replace
463 * @return {Mixed} Replacement value
464 */
465 oo.getHash.keySortReplacer = function ( key, val ) {
466 var normalized, keys, i, len;
467 if ( val && typeof val.getHashObject === 'function' ) {
468 // This object has its own custom hash function, use it
469 val = val.getHashObject();
470 }
471 if ( !Array.isArray( val ) && Object( val ) === val ) {
472 // Only normalize objects when the key-order is ambiguous
473 // (e.g. any object not an array).
474 normalized = {};
475 keys = Object.keys( val ).sort();
476 i = 0;
477 len = keys.length;
478 for ( ; i < len; i += 1 ) {
479 normalized[ keys[ i ] ] = val[ keys[ i ] ];
480 }
481 return normalized;
482
483 // Primitive values and arrays get stable hashes
484 // by default. Lets those be stringified as-is.
485 } else {
486 return val;
487 }
488 };
489
490 /**
491 * Get the unique values of an array, removing duplicates
492 *
493 * @param {Array} arr Array
494 * @return {Array} Unique values in array
495 */
496 oo.unique = function ( arr ) {
497 return arr.reduce( function ( result, current ) {
498 if ( result.indexOf( current ) === -1 ) {
499 result.push( current );
500 }
501 return result;
502 }, [] );
503 };
504
505 /**
506 * Compute the union (duplicate-free merge) of a set of arrays.
507 *
508 * Arrays values must be convertable to object keys (strings).
509 *
510 * By building an object (with the values for keys) in parallel with
511 * the array, a new item's existence in the union can be computed faster.
512 *
513 * @param {...Array} arrays Arrays to union
514 * @return {Array} Union of the arrays
515 */
516 oo.simpleArrayUnion = function () {
517 var i, ilen, arr, j, jlen,
518 obj = {},
519 result = [];
520
521 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
522 arr = arguments[ i ];
523 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
524 if ( !obj[ arr[ j ] ] ) {
525 obj[ arr[ j ] ] = true;
526 result.push( arr[ j ] );
527 }
528 }
529 }
530
531 return result;
532 };
533
534 /**
535 * Combine arrays (intersection or difference).
536 *
537 * An intersection checks the item exists in 'b' while difference checks it doesn't.
538 *
539 * Arrays values must be convertable to object keys (strings).
540 *
541 * By building an object (with the values for keys) of 'b' we can
542 * compute the result faster.
543 *
544 * @private
545 * @param {Array} a First array
546 * @param {Array} b Second array
547 * @param {boolean} includeB Whether to items in 'b'
548 * @return {Array} Combination (intersection or difference) of arrays
549 */
550 function simpleArrayCombine( a, b, includeB ) {
551 var i, ilen, isInB,
552 bObj = {},
553 result = [];
554
555 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
556 bObj[ b[ i ] ] = true;
557 }
558
559 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
560 isInB = !!bObj[ a[ i ] ];
561 if ( isInB === includeB ) {
562 result.push( a[ i ] );
563 }
564 }
565
566 return result;
567 }
568
569 /**
570 * Compute the intersection of two arrays (items in both arrays).
571 *
572 * Arrays values must be convertable to object keys (strings).
573 *
574 * @param {Array} a First array
575 * @param {Array} b Second array
576 * @return {Array} Intersection of arrays
577 */
578 oo.simpleArrayIntersection = function ( a, b ) {
579 return simpleArrayCombine( a, b, true );
580 };
581
582 /**
583 * Compute the difference of two arrays (items in 'a' but not 'b').
584 *
585 * Arrays values must be convertable to object keys (strings).
586 *
587 * @param {Array} a First array
588 * @param {Array} b Second array
589 * @return {Array} Intersection of arrays
590 */
591 oo.simpleArrayDifference = function ( a, b ) {
592 return simpleArrayCombine( a, b, false );
593 };
594
595 /*global $ */
596
597 oo.isPlainObject = $.isPlainObject;
598
599 /*global hasOwn */
600
601 ( function () {
602
603 /**
604 * @class OO.EventEmitter
605 *
606 * @constructor
607 */
608 oo.EventEmitter = function OoEventEmitter() {
609 // Properties
610
611 /**
612 * Storage of bound event handlers by event name.
613 *
614 * @property
615 */
616 this.bindings = {};
617 };
618
619 oo.initClass( oo.EventEmitter );
620
621 /* Private helper functions */
622
623 /**
624 * Validate a function or method call in a context
625 *
626 * For a method name, check that it names a function in the context object
627 *
628 * @private
629 * @param {Function|string} method Function or method name
630 * @param {Mixed} context The context of the call
631 * @throws {Error} A method name is given but there is no context
632 * @throws {Error} In the context object, no property exists with the given name
633 * @throws {Error} In the context object, the named property is not a function
634 */
635 function validateMethod( method, context ) {
636 // Validate method and context
637 if ( typeof method === 'string' ) {
638 // Validate method
639 if ( context === undefined || context === null ) {
640 throw new Error( 'Method name "' + method + '" has no context.' );
641 }
642 if ( typeof context[ method ] !== 'function' ) {
643 // Technically the property could be replaced by a function before
644 // call time. But this probably signals a typo.
645 throw new Error( 'Property "' + method + '" is not a function' );
646 }
647 } else if ( typeof method !== 'function' ) {
648 throw new Error( 'Invalid callback. Function or method name expected.' );
649 }
650 }
651
652 /* Methods */
653
654 /**
655 * Add a listener to events of a specific event.
656 *
657 * The listener can be a function or the string name of a method; if the latter, then the
658 * name lookup happens at the time the listener is called.
659 *
660 * @param {string} event Type of event to listen to
661 * @param {Function|string} method Function or method name to call when event occurs
662 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
663 * @param {Object} [context=null] Context object for function or method call
664 * @throws {Error} Listener argument is not a function or a valid method name
665 * @chainable
666 */
667 oo.EventEmitter.prototype.on = function ( event, method, args, context ) {
668 var bindings;
669
670 validateMethod( method, context );
671
672 if ( hasOwn.call( this.bindings, event ) ) {
673 bindings = this.bindings[ event ];
674 } else {
675 // Auto-initialize bindings list
676 bindings = this.bindings[ event ] = [];
677 }
678 // Add binding
679 bindings.push( {
680 method: method,
681 args: args,
682 context: ( arguments.length < 4 ) ? null : context
683 } );
684 return this;
685 };
686
687 /**
688 * Add a one-time listener to a specific event.
689 *
690 * @param {string} event Type of event to listen to
691 * @param {Function} listener Listener to call when event occurs
692 * @chainable
693 */
694 oo.EventEmitter.prototype.once = function ( event, listener ) {
695 var eventEmitter = this,
696 wrapper = function () {
697 eventEmitter.off( event, wrapper );
698 return listener.apply( this, arguments );
699 };
700 return this.on( event, wrapper );
701 };
702
703 /**
704 * Remove a specific listener from a specific event.
705 *
706 * @param {string} event Type of event to remove listener from
707 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
708 * to "on". Omit to remove all listeners.
709 * @param {Object} [context=null] Context object function or method call
710 * @chainable
711 * @throws {Error} Listener argument is not a function or a valid method name
712 */
713 oo.EventEmitter.prototype.off = function ( event, method, context ) {
714 var i, bindings;
715
716 if ( arguments.length === 1 ) {
717 // Remove all bindings for event
718 delete this.bindings[ event ];
719 return this;
720 }
721
722 validateMethod( method, context );
723
724 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) {
725 // No matching bindings
726 return this;
727 }
728
729 // Default to null context
730 if ( arguments.length < 3 ) {
731 context = null;
732 }
733
734 // Remove matching handlers
735 bindings = this.bindings[ event ];
736 i = bindings.length;
737 while ( i-- ) {
738 if ( bindings[ i ].method === method && bindings[ i ].context === context ) {
739 bindings.splice( i, 1 );
740 }
741 }
742
743 // Cleanup if now empty
744 if ( bindings.length === 0 ) {
745 delete this.bindings[ event ];
746 }
747 return this;
748 };
749
750 /**
751 * Emit an event.
752 *
753 * @param {string} event Type of event
754 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
755 * @return {boolean} Whether the event was handled by at least one listener
756 */
757 oo.EventEmitter.prototype.emit = function ( event ) {
758 var args = [],
759 i, len, binding, bindings, method;
760
761 if ( hasOwn.call( this.bindings, event ) ) {
762 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
763 bindings = this.bindings[ event ].slice();
764 for ( i = 1, len = arguments.length; i < len; i++ ) {
765 args.push( arguments[ i ] );
766 }
767 for ( i = 0, len = bindings.length; i < len; i++ ) {
768 binding = bindings[ i ];
769 if ( typeof binding.method === 'string' ) {
770 // Lookup method by name (late binding)
771 method = binding.context[ binding.method ];
772 } else {
773 method = binding.method;
774 }
775 method.apply(
776 binding.context,
777 binding.args ? binding.args.concat( args ) : args
778 );
779 }
780 return true;
781 }
782 return false;
783 };
784
785 /**
786 * Connect event handlers to an object.
787 *
788 * @param {Object} context Object to call methods on when events occur
789 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
790 * event bindings keyed by event name containing either method names, functions or arrays containing
791 * method name or function followed by a list of arguments to be passed to callback before emitted
792 * arguments
793 * @chainable
794 */
795 oo.EventEmitter.prototype.connect = function ( context, methods ) {
796 var method, args, event;
797
798 for ( event in methods ) {
799 method = methods[ event ];
800 // Allow providing additional args
801 if ( Array.isArray( method ) ) {
802 args = method.slice( 1 );
803 method = method[ 0 ];
804 } else {
805 args = [];
806 }
807 // Add binding
808 this.on( event, method, args, context );
809 }
810 return this;
811 };
812
813 /**
814 * Disconnect event handlers from an object.
815 *
816 * @param {Object} context Object to disconnect methods from
817 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
818 * event bindings keyed by event name. Values can be either method names or functions, but must be
819 * consistent with those used in the corresponding call to "connect".
820 * @chainable
821 */
822 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
823 var i, event, method, bindings;
824
825 if ( methods ) {
826 // Remove specific connections to the context
827 for ( event in methods ) {
828 method = methods[ event ];
829 if ( Array.isArray( method ) ) {
830 method = method[ 0 ];
831 }
832 this.off( event, method, context );
833 }
834 } else {
835 // Remove all connections to the context
836 for ( event in this.bindings ) {
837 bindings = this.bindings[ event ];
838 i = bindings.length;
839 while ( i-- ) {
840 // bindings[i] may have been removed by the previous step's
841 // this.off so check it still exists
842 if ( bindings[ i ] && bindings[ i ].context === context ) {
843 this.off( event, bindings[ i ].method, context );
844 }
845 }
846 }
847 }
848
849 return this;
850 };
851
852 }() );
853
854 ( function () {
855
856 /**
857 * Contain and manage a list of OO.EventEmitter items.
858 *
859 * Aggregates and manages their events collectively.
860 *
861 * This mixin must be used in a class that also mixes in OO.EventEmitter.
862 *
863 * @abstract
864 * @class OO.EmitterList
865 * @constructor
866 */
867 oo.EmitterList = function OoEmitterList() {
868 this.items = [];
869 this.aggregateItemEvents = {};
870 };
871
872 /* Events */
873
874 /**
875 * Item has been added
876 *
877 * @event add
878 * @param {OO.EventEmitter} item Added item
879 * @param {number} index Index items were added at
880 */
881
882 /**
883 * Item has been moved to a new index
884 *
885 * @event move
886 * @param {OO.EventEmitter} item Moved item
887 * @param {number} index Index item was moved to
888 * @param {number} oldIndex The original index the item was in
889 */
890
891 /**
892 * Item has been removed
893 *
894 * @event remove
895 * @param {OO.EventEmitter} item Removed item
896 * @param {number} index Index the item was removed from
897 */
898
899 /**
900 * @event clear The list has been cleared of items
901 */
902
903 /* Methods */
904
905 /**
906 * Normalize requested index to fit into the bounds of the given array.
907 *
908 * @private
909 * @static
910 * @param {Array} arr Given array
911 * @param {number|undefined} index Requested index
912 * @return {number} Normalized index
913 */
914 function normalizeArrayIndex( arr, index ) {
915 return ( index === undefined || index < 0 || index >= arr.length ) ?
916 arr.length :
917 index;
918 }
919
920 /**
921 * Get all items.
922 *
923 * @return {OO.EventEmitter[]} Items in the list
924 */
925 oo.EmitterList.prototype.getItems = function () {
926 return this.items.slice( 0 );
927 };
928
929 /**
930 * Get the index of a specific item.
931 *
932 * @param {OO.EventEmitter} item Requested item
933 * @return {number} Index of the item
934 */
935 oo.EmitterList.prototype.getItemIndex = function ( item ) {
936 return this.items.indexOf( item );
937 };
938
939 /**
940 * Get number of items.
941 *
942 * @return {number} Number of items in the list
943 */
944 oo.EmitterList.prototype.getItemCount = function () {
945 return this.items.length;
946 };
947
948 /**
949 * Check if a list contains no items.
950 *
951 * @return {boolean} Group is empty
952 */
953 oo.EmitterList.prototype.isEmpty = function () {
954 return !this.items.length;
955 };
956
957 /**
958 * Aggregate the events emitted by the group.
959 *
960 * When events are aggregated, the group will listen to all contained items for the event,
961 * and then emit the event under a new name. The new event will contain an additional leading
962 * parameter containing the item that emitted the original event. Other arguments emitted from
963 * the original event are passed through.
964 *
965 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
966 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
967 * A `null` value will remove aggregated events.
968
969 * @throws {Error} If aggregation already exists
970 */
971 oo.EmitterList.prototype.aggregate = function ( events ) {
972 var i, item, add, remove, itemEvent, groupEvent;
973
974 for ( itemEvent in events ) {
975 groupEvent = events[ itemEvent ];
976
977 // Remove existing aggregated event
978 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
979 // Don't allow duplicate aggregations
980 if ( groupEvent ) {
981 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
982 }
983 // Remove event aggregation from existing items
984 for ( i = 0; i < this.items.length; i++ ) {
985 item = this.items[ i ];
986 if ( item.connect && item.disconnect ) {
987 remove = {};
988 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
989 item.disconnect( this, remove );
990 }
991 }
992 // Prevent future items from aggregating event
993 delete this.aggregateItemEvents[ itemEvent ];
994 }
995
996 // Add new aggregate event
997 if ( groupEvent ) {
998 // Make future items aggregate event
999 this.aggregateItemEvents[ itemEvent ] = groupEvent;
1000 // Add event aggregation to existing items
1001 for ( i = 0; i < this.items.length; i++ ) {
1002 item = this.items[ i ];
1003 if ( item.connect && item.disconnect ) {
1004 add = {};
1005 add[ itemEvent ] = [ 'emit', groupEvent, item ];
1006 item.connect( this, add );
1007 }
1008 }
1009 }
1010 }
1011 };
1012
1013 /**
1014 * Add items to the list.
1015 *
1016 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1017 * an array of items to add
1018 * @param {number} [index] Index to add items at. If no index is
1019 * given, or if the index that is given is invalid, the item
1020 * will be added at the end of the list.
1021 * @chainable
1022 * @fires add
1023 * @fires move
1024 */
1025 oo.EmitterList.prototype.addItems = function ( items, index ) {
1026 var i, oldIndex;
1027
1028 if ( !Array.isArray( items ) ) {
1029 items = [ items ];
1030 }
1031
1032 if ( items.length === 0 ) {
1033 return this;
1034 }
1035
1036 index = normalizeArrayIndex( this.items, index );
1037 for ( i = 0; i < items.length; i++ ) {
1038 oldIndex = this.items.indexOf( items[ i ] );
1039 if ( oldIndex !== -1 ) {
1040 // Move item to new index
1041 index = this.moveItem( items[ i ], index );
1042 this.emit( 'move', items[ i ], index, oldIndex );
1043 } else {
1044 // insert item at index
1045 index = this.insertItem( items[ i ], index );
1046 this.emit( 'add', items[ i ], index );
1047 }
1048 index++;
1049 }
1050
1051 return this;
1052 };
1053
1054 /**
1055 * Move an item from its current position to a new index.
1056 *
1057 * The item is expected to exist in the list. If it doesn't,
1058 * the method will throw an exception.
1059 *
1060 * @private
1061 * @param {OO.EventEmitter} item Items to add
1062 * @param {number} newIndex Index to move the item to
1063 * @return {number} The index the item was moved to
1064 * @throws {Error} If item is not in the list
1065 */
1066 oo.EmitterList.prototype.moveItem = function ( item, newIndex ) {
1067 var existingIndex = this.items.indexOf( item );
1068
1069 if ( existingIndex === -1 ) {
1070 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1071 }
1072
1073 newIndex = normalizeArrayIndex( this.items, newIndex );
1074
1075 // Remove the item from the current index
1076 this.items.splice( existingIndex, 1 );
1077
1078 // Adjust new index after removal
1079 newIndex--;
1080
1081 // Move the item to the new index
1082 this.items.splice( newIndex, 0, item );
1083
1084 return newIndex;
1085 };
1086
1087 /**
1088 * Utility method to insert an item into the list, and
1089 * connect it to aggregate events.
1090 *
1091 * Don't call this directly unless you know what you're doing.
1092 * Use #addItems instead.
1093 *
1094 * @private
1095 * @param {OO.EventEmitter} item Items to add
1096 * @param {number} index Index to add items at
1097 * @return {number} The index the item was added at
1098 */
1099 oo.EmitterList.prototype.insertItem = function ( item, index ) {
1100 var events, event;
1101
1102 // Add the item to event aggregation
1103 if ( item.connect && item.disconnect ) {
1104 events = {};
1105 for ( event in this.aggregateItemEvents ) {
1106 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
1107 }
1108 item.connect( this, events );
1109 }
1110
1111 index = normalizeArrayIndex( this.items, index );
1112
1113 // Insert into items array
1114 this.items.splice( index, 0, item );
1115 return index;
1116 };
1117
1118 /**
1119 * Remove items.
1120 *
1121 * @param {OO.EventEmitter[]} items Items to remove
1122 * @chainable
1123 * @fires remove
1124 */
1125 oo.EmitterList.prototype.removeItems = function ( items ) {
1126 var i, item, index;
1127
1128 if ( !Array.isArray( items ) ) {
1129 items = [ items ];
1130 }
1131
1132 if ( items.length === 0 ) {
1133 return this;
1134 }
1135
1136 // Remove specific items
1137 for ( i = 0; i < items.length; i++ ) {
1138 item = items[ i ];
1139 index = this.items.indexOf( item );
1140 if ( index !== -1 ) {
1141 if ( item.connect && item.disconnect ) {
1142 // Disconnect all listeners from the item
1143 item.disconnect( this );
1144 }
1145 this.items.splice( index, 1 );
1146 this.emit( 'remove', item, index );
1147 }
1148 }
1149
1150 return this;
1151 };
1152
1153 /**
1154 * Clear all items
1155 *
1156 * @chainable
1157 * @fires clear
1158 */
1159 oo.EmitterList.prototype.clearItems = function () {
1160 var i, item,
1161 cleared = this.items.splice( 0, this.items.length );
1162
1163 // Disconnect all items
1164 for ( i = 0; i < cleared.length; i++ ) {
1165 item = cleared[ i ];
1166 if ( item.connect && item.disconnect ) {
1167 item.disconnect( this );
1168 }
1169 }
1170
1171 this.emit( 'clear' );
1172
1173 return this;
1174 };
1175
1176 }() );
1177
1178 /**
1179 * Manage a sorted list of OO.EmitterList objects.
1180 *
1181 * The sort order is based on a callback that compares two items. The return value of
1182 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1183 * if a is equal to b. The callback should only return zero if the two objects are
1184 * considered equal.
1185 *
1186 * When an item changes in a way that could affect their sorting behavior, it must
1187 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1188 *
1189 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1190 *
1191 * @abstract
1192 * @class OO.SortedEmitterList
1193 * @mixins OO.EmitterList
1194 * @constructor
1195 * @param {Function} sortingCallback Callback that compares two items.
1196 */
1197 oo.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) {
1198 // Mixin constructors
1199 oo.EmitterList.call( this );
1200
1201 this.sortingCallback = sortingCallback;
1202
1203 // Listen to sortChange event and make sure
1204 // we re-sort the changed item when that happens
1205 this.aggregate( {
1206 sortChange: 'itemSortChange'
1207 } );
1208
1209 this.connect( this, {
1210 itemSortChange: 'onItemSortChange'
1211 } );
1212 };
1213
1214 oo.mixinClass( oo.SortedEmitterList, oo.EmitterList );
1215
1216 /* Events */
1217
1218 /**
1219 * An item has changed properties that affect its sort positioning
1220 * inside the list.
1221 *
1222 * @private
1223 * @event itemSortChange
1224 */
1225
1226 /* Methods */
1227
1228 /**
1229 * Handle a case where an item changed a property that relates
1230 * to its sorted order
1231 *
1232 * @param {OO.EventEmitter} item Item in the list
1233 */
1234 oo.SortedEmitterList.prototype.onItemSortChange = function ( item ) {
1235 // Remove the item
1236 this.removeItems( item );
1237 // Re-add the item so it is in the correct place
1238 this.addItems( item );
1239 };
1240
1241 /**
1242 * Change the sorting callback for this sorted list.
1243 *
1244 * The callback receives two items. The return value of callback(a, b) must be less than zero
1245 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1246 *
1247 * @param {Function} sortingCallback Sorting callback
1248 */
1249 oo.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) {
1250 var items = this.getItems();
1251
1252 this.sortingCallback = sortingCallback;
1253
1254 // Empty the list
1255 this.clearItems();
1256 // Re-add the items in the new order
1257 this.addItems( items );
1258 };
1259
1260 /**
1261 * Add items to the sorted list.
1262 *
1263 * @chainable
1264 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1265 * an array of items to add
1266 */
1267 oo.SortedEmitterList.prototype.addItems = function ( items ) {
1268 var index, i, insertionIndex;
1269
1270 if ( !Array.isArray( items ) ) {
1271 items = [ items ];
1272 }
1273
1274 if ( items.length === 0 ) {
1275 return this;
1276 }
1277
1278 for ( i = 0; i < items.length; i++ ) {
1279 // Find insertion index
1280 insertionIndex = this.findInsertionIndex( items[ i ] );
1281
1282 // Check if the item exists using the sorting callback
1283 // and remove it first if it exists
1284 if (
1285 // First make sure the insertion index is not at the end
1286 // of the list (which means it does not point to any actual
1287 // items)
1288 insertionIndex <= this.items.length &&
1289 // Make sure there actually is an item in this index
1290 this.items[ insertionIndex ] &&
1291 // The callback returns 0 if the items are equal
1292 this.sortingCallback( this.items[ insertionIndex ], items[ i ] ) === 0
1293 ) {
1294 // Remove the existing item
1295 this.removeItems( this.items[ insertionIndex ] );
1296 }
1297
1298 // Insert item at the insertion index
1299 index = this.insertItem( items[ i ], insertionIndex );
1300 this.emit( 'add', items[ i ], insertionIndex );
1301 }
1302
1303 return this;
1304 };
1305
1306 /**
1307 * Find the index a given item should be inserted at. If the item is already
1308 * in the list, this will return the index where the item currently is.
1309 *
1310 * @param {OO.EventEmitter} item Items to insert
1311 * @return {number} The index the item should be inserted at
1312 */
1313 oo.SortedEmitterList.prototype.findInsertionIndex = function ( item ) {
1314 var list = this;
1315
1316 return oo.binarySearch(
1317 this.items,
1318 // Fake a this.sortingCallback.bind( null, item ) call here
1319 // otherwise this doesn't pass tests in phantomJS
1320 function ( otherItem ) {
1321 return list.sortingCallback( item, otherItem );
1322 },
1323 true
1324 );
1325
1326 };
1327
1328 /*global hasOwn */
1329
1330 /**
1331 * @class OO.Registry
1332 * @mixins OO.EventEmitter
1333 *
1334 * @constructor
1335 */
1336 oo.Registry = function OoRegistry() {
1337 // Mixin constructors
1338 oo.EventEmitter.call( this );
1339
1340 // Properties
1341 this.registry = {};
1342 };
1343
1344 /* Inheritance */
1345
1346 oo.mixinClass( oo.Registry, oo.EventEmitter );
1347
1348 /* Events */
1349
1350 /**
1351 * @event register
1352 * @param {string} name
1353 * @param {Mixed} data
1354 */
1355
1356 /**
1357 * @event unregister
1358 * @param {string} name
1359 * @param {Mixed} data Data removed from registry
1360 */
1361
1362 /* Methods */
1363
1364 /**
1365 * Associate one or more symbolic names with some data.
1366 *
1367 * Any existing entry with the same name will be overridden.
1368 *
1369 * @param {string|string[]} name Symbolic name or list of symbolic names
1370 * @param {Mixed} data Data to associate with symbolic name
1371 * @fires register
1372 * @throws {Error} Name argument must be a string or array
1373 */
1374 oo.Registry.prototype.register = function ( name, data ) {
1375 var i, len;
1376 if ( typeof name === 'string' ) {
1377 this.registry[ name ] = data;
1378 this.emit( 'register', name, data );
1379 } else if ( Array.isArray( name ) ) {
1380 for ( i = 0, len = name.length; i < len; i++ ) {
1381 this.register( name[ i ], data );
1382 }
1383 } else {
1384 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1385 }
1386 };
1387
1388 /**
1389 * Remove one or more symbolic names from the registry
1390 *
1391 * @param {string|string[]} name Symbolic name or list of symbolic names
1392 * @fires unregister
1393 * @throws {Error} Name argument must be a string or array
1394 */
1395 oo.Registry.prototype.unregister = function ( name ) {
1396 var i, len, data;
1397 if ( typeof name === 'string' ) {
1398 data = this.lookup( name );
1399 if ( data !== undefined ) {
1400 delete this.registry[ name ];
1401 this.emit( 'unregister', name, data );
1402 }
1403 } else if ( Array.isArray( name ) ) {
1404 for ( i = 0, len = name.length; i < len; i++ ) {
1405 this.unregister( name[ i ] );
1406 }
1407 } else {
1408 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1409 }
1410 };
1411
1412 /**
1413 * Get data for a given symbolic name.
1414 *
1415 * @param {string} name Symbolic name
1416 * @return {Mixed|undefined} Data associated with symbolic name
1417 */
1418 oo.Registry.prototype.lookup = function ( name ) {
1419 if ( hasOwn.call( this.registry, name ) ) {
1420 return this.registry[ name ];
1421 }
1422 };
1423
1424 /*global createObject */
1425
1426 /**
1427 * @class OO.Factory
1428 * @extends OO.Registry
1429 *
1430 * @constructor
1431 */
1432 oo.Factory = function OoFactory() {
1433 // Parent constructor
1434 oo.Factory.parent.call( this );
1435 };
1436
1437 /* Inheritance */
1438
1439 oo.inheritClass( oo.Factory, oo.Registry );
1440
1441 /* Methods */
1442
1443 /**
1444 * Register a constructor with the factory.
1445 *
1446 * Classes must have a static `name` property to be registered.
1447 *
1448 * function MyClass() {};
1449 * OO.initClass( MyClass );
1450 * // Adds a static property to the class defining a symbolic name
1451 * MyClass.static.name = 'mine';
1452 * // Registers class with factory, available via symbolic name 'mine'
1453 * factory.register( MyClass );
1454 *
1455 * @param {Function} constructor Constructor to use when creating object
1456 * @throws {Error} Name must be a string and must not be empty
1457 * @throws {Error} Constructor must be a function
1458 */
1459 oo.Factory.prototype.register = function ( constructor ) {
1460 var name;
1461
1462 if ( typeof constructor !== 'function' ) {
1463 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1464 }
1465 name = constructor.static && constructor.static.name;
1466 if ( typeof name !== 'string' || name === '' ) {
1467 throw new Error( 'Name must be a string and must not be empty' );
1468 }
1469
1470 // Parent method
1471 oo.Factory.parent.prototype.register.call( this, name, constructor );
1472 };
1473
1474 /**
1475 * Unregister a constructor from the factory.
1476 *
1477 * @param {Function} constructor Constructor to unregister
1478 * @throws {Error} Name must be a string and must not be empty
1479 * @throws {Error} Constructor must be a function
1480 */
1481 oo.Factory.prototype.unregister = function ( constructor ) {
1482 var name;
1483
1484 if ( typeof constructor !== 'function' ) {
1485 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1486 }
1487 name = constructor.static && constructor.static.name;
1488 if ( typeof name !== 'string' || name === '' ) {
1489 throw new Error( 'Name must be a string and must not be empty' );
1490 }
1491
1492 // Parent method
1493 oo.Factory.parent.prototype.unregister.call( this, name );
1494 };
1495
1496 /**
1497 * Create an object based on a name.
1498 *
1499 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1500 * constructor directly, so leaving one out will pass an undefined to the constructor.
1501 *
1502 * @param {string} name Object name
1503 * @param {...Mixed} [args] Arguments to pass to the constructor
1504 * @return {Object} The new object
1505 * @throws {Error} Unknown object name
1506 */
1507 oo.Factory.prototype.create = function ( name ) {
1508 var obj, i,
1509 args = [],
1510 constructor = this.lookup( name );
1511
1512 if ( !constructor ) {
1513 throw new Error( 'No class registered by that name: ' + name );
1514 }
1515
1516 // Convert arguments to array and shift the first argument (name) off
1517 for ( i = 1; i < arguments.length; i++ ) {
1518 args.push( arguments[ i ] );
1519 }
1520
1521 // We can't use the "new" operator with .apply directly because apply needs a
1522 // context. So instead just do what "new" does: create an object that inherits from
1523 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1524 // then invoke the constructor with the object as context, and return it (ignoring
1525 // the constructor's return value).
1526 obj = createObject( constructor.prototype );
1527 constructor.apply( obj, args );
1528 return obj;
1529 };
1530
1531 /*jshint node:true */
1532 if ( typeof module !== 'undefined' && module.exports ) {
1533 module.exports = oo;
1534 } else {
1535 global.OO = oo;
1536 }
1537
1538 }( this ) );