2 * OOjs v2.0.0 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2017 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
9 * Date: 2017-04-05T02:18:04Z
11 ( function ( global
) {
15 /* exported toString */
18 * Namespace for all classes, static methods and static properties.
23 // Optimisation: Local reference to Object.prototype.hasOwnProperty
24 hasOwn
= oo
.hasOwnProperty
,
25 toString
= oo
.toString
;
30 * Utility to initialize a class for OO inheritance.
32 * Currently this just initializes an empty static object.
34 * @param {Function} fn
36 oo
.initClass = function ( fn
) {
37 fn
.static = fn
.static || {};
41 * Inherit from prototype to another using Object#create.
43 * Beware: This redefines the prototype, call before setting your prototypes.
45 * Beware: This redefines the prototype, can only be called once on a function.
46 * If called multiple times on the same function, the previous prototype is lost.
47 * This is how prototypal inheritance works, it can only be one straight chain
48 * (just like classical inheritance in PHP for example). If you need to work with
49 * multiple constructors consider storing an instance of the other constructor in a
50 * property instead, or perhaps use a mixin (see OO.mixinClass).
53 * Thing.prototype.exists = function () {};
56 * Person.super.apply( this, arguments );
58 * OO.inheritClass( Person, Thing );
59 * Person.static.defaultEyeCount = 2;
60 * Person.prototype.walk = function () {};
63 * Jumper.super.apply( this, arguments );
65 * OO.inheritClass( Jumper, Person );
66 * Jumper.prototype.jump = function () {};
68 * Jumper.static.defaultEyeCount === 2;
69 * var x = new Jumper();
72 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
74 * @param {Function} targetFn
75 * @param {Function} originFn
76 * @throws {Error} If target already inherits from origin
78 oo
.inheritClass = function ( targetFn
, originFn
) {
79 var targetConstructor
;
82 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn
+ ')' );
84 if ( targetFn
.prototype instanceof originFn
) {
85 throw new Error( 'inheritClass: Target already inherits from origin' );
88 targetConstructor
= targetFn
.prototype.constructor;
90 // Using ['super'] instead of .super because 'super' is not supported
91 // by IE 8 and below (bug 63303).
92 // Provide .parent as alias for code supporting older browsers which
93 // allows people to comply with their style guide.
94 // eslint-disable-next-line dot-notation
95 targetFn
[ 'super' ] = targetFn
.parent
= originFn
;
97 targetFn
.prototype = Object
.create( originFn
.prototype, {
98 // Restore constructor property of targetFn
100 value
: targetConstructor
,
107 // Extend static properties - always initialize both sides
108 oo
.initClass( originFn
);
109 targetFn
.static = Object
.create( originFn
.static );
113 * Copy over *own* prototype properties of a mixin.
115 * The 'constructor' (whether implicit or explicit) is not copied over.
117 * This does not create inheritance to the origin. If you need inheritance,
118 * use OO.inheritClass instead.
120 * Beware: This can redefine a prototype property, call before setting your prototypes.
122 * Beware: Don't call before OO.inheritClass.
125 * function Context() {}
127 * // Avoid repeating this code
128 * function ContextLazyLoad() {}
129 * ContextLazyLoad.prototype.getContext = function () {
130 * if ( !this.context ) {
131 * this.context = new Context();
133 * return this.context;
136 * function FooBar() {}
137 * OO.inheritClass( FooBar, Foo );
138 * OO.mixinClass( FooBar, ContextLazyLoad );
140 * @param {Function} targetFn
141 * @param {Function} originFn
143 oo
.mixinClass = function ( targetFn
, originFn
) {
147 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn
+ ')' );
150 // Copy prototype properties
151 for ( key
in originFn
.prototype ) {
152 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
153 targetFn
.prototype[ key
] = originFn
.prototype[ key
];
157 // Copy static properties - always initialize both sides
158 oo
.initClass( targetFn
);
159 if ( originFn
.static ) {
160 for ( key
in originFn
.static ) {
161 if ( hasOwn
.call( originFn
.static, key
) ) {
162 targetFn
.static[ key
] = originFn
.static[ key
];
166 oo
.initClass( originFn
);
171 * Test whether one class is a subclass of another, without instantiating it.
173 * Every class is considered a subclass of Object and of itself.
175 * @param {Function} testFn The class to be tested
176 * @param {Function} baseFn The base class
177 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
179 oo
.isSubclass = function ( testFn
, baseFn
) {
180 return testFn
=== baseFn
|| testFn
.prototype instanceof baseFn
;
186 * Get a deeply nested property of an object using variadic arguments, protecting against
187 * undefined property errors.
189 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
190 * except that the former protects against JS errors if one of the intermediate properties
191 * is undefined. Instead of throwing an error, this function will return undefined in
194 * @param {Object} obj
195 * @param {...Mixed} [keys]
196 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
198 oo
.getProp = function ( obj
) {
201 for ( i
= 1; i
< arguments
.length
; i
++ ) {
202 if ( retval
=== undefined || retval
=== null ) {
203 // Trying to access a property of undefined or null causes an error
206 retval
= retval
[ arguments
[ i
] ];
212 * Set a deeply nested property of an object using variadic arguments, protecting against
213 * undefined property errors.
215 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
216 * the former protects against JS errors if one of the intermediate properties is
217 * undefined. Instead of throwing an error, undefined intermediate properties will be
218 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
219 * is not an object, this function will silently abort.
221 * @param {Object} obj
222 * @param {...Mixed} [keys]
223 * @param {Mixed} [value]
225 oo
.setProp = function ( obj
) {
228 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
231 for ( i
= 1; i
< arguments
.length
- 2; i
++ ) {
232 if ( prop
[ arguments
[ i
] ] === undefined ) {
233 prop
[ arguments
[ i
] ] = {};
235 if ( Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
238 prop
= prop
[ arguments
[ i
] ];
240 prop
[ arguments
[ arguments
.length
- 2 ] ] = arguments
[ arguments
.length
- 1 ];
244 * Delete a deeply nested property of an object using variadic arguments, protecting against
245 * undefined property errors, and deleting resulting empty objects.
247 * @param {Object} obj
248 * @param {...Mixed} [keys]
250 oo
.deleteProp = function ( obj
) {
254 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
257 for ( i
= 1; i
< arguments
.length
- 1; i
++ ) {
258 if ( prop
[ arguments
[ i
] ] === undefined || Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
261 prop
= prop
[ arguments
[ i
] ];
264 delete prop
[ arguments
[ i
] ];
265 // Walk back through props removing any plain empty objects
266 while ( ( prop
= props
.pop() ) && oo
.isPlainObject( prop
) && !Object
.keys( prop
).length
) {
267 delete props
[ props
.length
- 1 ][ arguments
[ props
.length
] ];
272 * Create a new object that is an instance of the same
273 * constructor as the input, inherits from the same object
274 * and contains the same own properties.
276 * This makes a shallow non-recursive copy of own properties.
277 * To create a recursive copy of plain objects, use #copy.
279 * var foo = new Person( mom, dad );
281 * var foo2 = OO.cloneObject( foo );
285 * foo2 !== foo; // true
286 * foo2 instanceof Person; // true
287 * foo2.getAge(); // 21
288 * foo.getAge(); // 22
290 * @param {Object} origin
291 * @return {Object} Clone of origin
293 oo
.cloneObject = function ( origin
) {
296 r
= Object
.create( origin
.constructor.prototype );
298 for ( key
in origin
) {
299 if ( hasOwn
.call( origin
, key
) ) {
300 r
[ key
] = origin
[ key
];
308 * Get an array of all property values in an object.
310 * @param {Object} obj Object to get values from
311 * @return {Array} List of object values
313 oo
.getObjectValues = function ( obj
) {
316 if ( obj
!== Object( obj
) ) {
317 throw new TypeError( 'Called on non-object' );
322 if ( hasOwn
.call( obj
, key
) ) {
323 values
[ values
.length
] = obj
[ key
];
331 * Use binary search to locate an element in a sorted array.
333 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
334 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
335 * below 0 if it is to the left of elem, or zero if it's equal to elem.
337 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
338 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
339 * `searchFunc = cmp.bind( null, value )`.
341 * @param {Array} arr Array to search in
342 * @param {Function} searchFunc Search function
343 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
344 * @return {number|null} Index where val was found, or null if not found
346 oo
.binarySearch = function ( arr
, searchFunc
, forInsertion
) {
350 while ( left
< right
) {
351 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
352 // eslint-disable-next-line no-bitwise
353 mid
= ( left
+ right
) >> 1;
354 cmpResult
= searchFunc( arr
[ mid
] );
355 if ( cmpResult
< 0 ) {
357 } else if ( cmpResult
> 0 ) {
363 return forInsertion
? right
: null;
367 * Recursively compare properties between two objects.
369 * A false result may be caused by property inequality or by properties in one object missing from
370 * the other. An asymmetrical test may also be performed, which checks only that properties in the
371 * first object are present in the second object, but not the inverse.
373 * If either a or b is null or undefined it will be treated as an empty object.
375 * @param {Object|undefined|null} a First object to compare
376 * @param {Object|undefined|null} b Second object to compare
377 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
378 * (i.e. a is a subset of b)
379 * @return {boolean} If the objects contain the same values as each other
381 oo
.compare = function ( a
, b
, asymmetrical
) {
382 var aValue
, bValue
, aType
, bType
, k
;
391 if ( typeof a
.nodeType
=== 'number' && typeof a
.isEqualNode
=== 'function' ) {
392 return a
.isEqualNode( b
);
396 if ( !hasOwn
.call( a
, k
) || a
[ k
] === undefined || a
[ k
] === b
[ k
] ) {
397 // Support es3-shim: Without the hasOwn filter, comparing [] to {} will be false in ES3
398 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
399 // Also ignore undefined values, because there is no conceptual difference between
400 // a key that is absent and a key that is present but whose value is undefined.
406 aType
= typeof aValue
;
407 bType
= typeof bValue
;
408 if ( aType
!== bType
||
410 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
413 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, true ) ) ) {
417 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
418 return asymmetrical
? true : oo
.compare( b
, a
, true );
422 * Create a plain deep copy of any kind of object.
424 * Copies are deep, and will either be an object or an array depending on `source`.
426 * @param {Object} source Object to copy
427 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
428 * @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.
429 * @return {Object} Copy of source object
431 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
432 var key
, destination
;
434 if ( nodeCallback
) {
435 // Extensibility: check before attempting to clone source.
436 destination
= nodeCallback( source
);
437 if ( destination
!== undefined ) {
442 if ( Array
.isArray( source
) ) {
443 // Array (fall through)
444 destination
= new Array( source
.length
);
445 } else if ( source
&& typeof source
.clone
=== 'function' ) {
446 // Duck type object with custom clone method
447 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
448 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
450 return leafCallback
?
451 leafCallback( source
.cloneNode( true ) ) :
452 source
.cloneNode( true );
453 } else if ( oo
.isPlainObject( source
) ) {
454 // Plain objects (fall through)
457 // Non-plain objects (incl. functions) and primitive values
458 return leafCallback
? leafCallback( source
) : source
;
461 // source is an array or a plain object
462 for ( key
in source
) {
463 destination
[ key
] = oo
.copy( source
[ key
], leafCallback
, nodeCallback
);
466 // This is an internal node, so we don't apply the leafCallback.
471 * Generate a hash of an object based on its name and data.
473 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
475 * To avoid two objects with the same values generating different hashes, we utilize the replacer
476 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
477 * not be the fastest way to do this; we should investigate this further.
479 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
480 * function, we call that function and use its return value rather than hashing the object
481 * ourselves. This allows classes to define custom hashing.
483 * @param {Object} val Object to generate hash for
484 * @return {string} Hash of object
486 oo
.getHash = function ( val
) {
487 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
491 * Sort objects by key (helper function for OO.getHash).
493 * This is a callback passed into JSON.stringify.
495 * @method getHash_keySortReplacer
496 * @param {string} key Property name of value being replaced
497 * @param {Mixed} val Property value to replace
498 * @return {Mixed} Replacement value
500 oo
.getHash
.keySortReplacer = function ( key
, val
) {
501 var normalized
, keys
, i
, len
;
502 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
503 // This object has its own custom hash function, use it
504 val
= val
.getHashObject();
506 if ( !Array
.isArray( val
) && Object( val
) === val
) {
507 // Only normalize objects when the key-order is ambiguous
508 // (e.g. any object not an array).
510 keys
= Object
.keys( val
).sort();
513 for ( ; i
< len
; i
+= 1 ) {
514 normalized
[ keys
[ i
] ] = val
[ keys
[ i
] ];
518 // Primitive values and arrays get stable hashes
519 // by default. Lets those be stringified as-is.
525 * Get the unique values of an array, removing duplicates
527 * @param {Array} arr Array
528 * @return {Array} Unique values in array
530 oo
.unique = function ( arr
) {
531 return arr
.reduce( function ( result
, current
) {
532 if ( result
.indexOf( current
) === -1 ) {
533 result
.push( current
);
540 * Compute the union (duplicate-free merge) of a set of arrays.
542 * Arrays values must be convertable to object keys (strings).
544 * By building an object (with the values for keys) in parallel with
545 * the array, a new item's existence in the union can be computed faster.
547 * @param {...Array} arrays Arrays to union
548 * @return {Array} Union of the arrays
550 oo
.simpleArrayUnion = function () {
551 var i
, ilen
, arr
, j
, jlen
,
555 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
556 arr
= arguments
[ i
];
557 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
558 if ( !obj
[ arr
[ j
] ] ) {
559 obj
[ arr
[ j
] ] = true;
560 result
.push( arr
[ j
] );
569 * Combine arrays (intersection or difference).
571 * An intersection checks the item exists in 'b' while difference checks it doesn't.
573 * Arrays values must be convertable to object keys (strings).
575 * By building an object (with the values for keys) of 'b' we can
576 * compute the result faster.
579 * @param {Array} a First array
580 * @param {Array} b Second array
581 * @param {boolean} includeB Whether to items in 'b'
582 * @return {Array} Combination (intersection or difference) of arrays
584 function simpleArrayCombine( a
, b
, includeB
) {
589 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
590 bObj
[ b
[ i
] ] = true;
593 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
594 isInB
= !!bObj
[ a
[ i
] ];
595 if ( isInB
=== includeB
) {
596 result
.push( a
[ i
] );
604 * Compute the intersection of two arrays (items in both arrays).
606 * Arrays values must be convertable to object keys (strings).
608 * @param {Array} a First array
609 * @param {Array} b Second array
610 * @return {Array} Intersection of arrays
612 oo
.simpleArrayIntersection = function ( a
, b
) {
613 return simpleArrayCombine( a
, b
, true );
617 * Compute the difference of two arrays (items in 'a' but not 'b').
619 * Arrays values must be convertable to object keys (strings).
621 * @param {Array} a First array
622 * @param {Array} b Second array
623 * @return {Array} Intersection of arrays
625 oo
.simpleArrayDifference = function ( a
, b
) {
626 return simpleArrayCombine( a
, b
, false );
631 oo
.isPlainObject
= $.isPlainObject
;
638 * @class OO.EventEmitter
642 oo
.EventEmitter
= function OoEventEmitter() {
646 * Storage of bound event handlers by event name.
653 oo
.initClass( oo
.EventEmitter
);
655 /* Private helper functions */
658 * Validate a function or method call in a context
660 * For a method name, check that it names a function in the context object
663 * @param {Function|string} method Function or method name
664 * @param {Mixed} context The context of the call
665 * @throws {Error} A method name is given but there is no context
666 * @throws {Error} In the context object, no property exists with the given name
667 * @throws {Error} In the context object, the named property is not a function
669 function validateMethod( method
, context
) {
670 // Validate method and context
671 if ( typeof method
=== 'string' ) {
673 if ( context
=== undefined || context
=== null ) {
674 throw new Error( 'Method name "' + method
+ '" has no context.' );
676 if ( typeof context
[ method
] !== 'function' ) {
677 // Technically the property could be replaced by a function before
678 // call time. But this probably signals a typo.
679 throw new Error( 'Property "' + method
+ '" is not a function' );
681 } else if ( typeof method
!== 'function' ) {
682 throw new Error( 'Invalid callback. Function or method name expected.' );
689 * Add a listener to events of a specific event.
691 * The listener can be a function or the string name of a method; if the latter, then the
692 * name lookup happens at the time the listener is called.
694 * @param {string} event Type of event to listen to
695 * @param {Function|string} method Function or method name to call when event occurs
696 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
697 * @param {Object} [context=null] Context object for function or method call
698 * @throws {Error} Listener argument is not a function or a valid method name
701 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
704 validateMethod( method
, context
);
706 if ( hasOwn
.call( this.bindings
, event
) ) {
707 bindings
= this.bindings
[ event
];
709 // Auto-initialize bindings list
710 bindings
= this.bindings
[ event
] = [];
716 context
: ( arguments
.length
< 4 ) ? null : context
722 * Add a one-time listener to a specific event.
724 * @param {string} event Type of event to listen to
725 * @param {Function} listener Listener to call when event occurs
728 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
729 var eventEmitter
= this,
730 wrapper = function () {
731 eventEmitter
.off( event
, wrapper
);
732 return listener
.apply( this, arguments
);
734 return this.on( event
, wrapper
);
738 * Remove a specific listener from a specific event.
740 * @param {string} event Type of event to remove listener from
741 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
742 * to "on". Omit to remove all listeners.
743 * @param {Object} [context=null] Context object function or method call
745 * @throws {Error} Listener argument is not a function or a valid method name
747 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
750 if ( arguments
.length
=== 1 ) {
751 // Remove all bindings for event
752 delete this.bindings
[ event
];
756 validateMethod( method
, context
);
758 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[ event
].length
) {
759 // No matching bindings
763 // Default to null context
764 if ( arguments
.length
< 3 ) {
768 // Remove matching handlers
769 bindings
= this.bindings
[ event
];
772 if ( bindings
[ i
].method
=== method
&& bindings
[ i
].context
=== context
) {
773 bindings
.splice( i
, 1 );
777 // Cleanup if now empty
778 if ( bindings
.length
=== 0 ) {
779 delete this.bindings
[ event
];
787 * @param {string} event Type of event
788 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
789 * @return {boolean} Whether the event was handled by at least one listener
791 oo
.EventEmitter
.prototype.emit = function ( event
) {
793 i
, len
, binding
, bindings
, method
;
795 if ( hasOwn
.call( this.bindings
, event
) ) {
796 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
797 bindings
= this.bindings
[ event
].slice();
798 for ( i
= 1, len
= arguments
.length
; i
< len
; i
++ ) {
799 args
.push( arguments
[ i
] );
801 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
802 binding
= bindings
[ i
];
803 if ( typeof binding
.method
=== 'string' ) {
804 // Lookup method by name (late binding)
805 method
= binding
.context
[ binding
.method
];
807 method
= binding
.method
;
811 binding
.args
? binding
.args
.concat( args
) : args
820 * Connect event handlers to an object.
822 * @param {Object} context Object to call methods on when events occur
823 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
824 * event bindings keyed by event name containing either method names, functions or arrays containing
825 * method name or function followed by a list of arguments to be passed to callback before emitted
829 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
830 var method
, args
, event
;
832 for ( event
in methods
) {
833 method
= methods
[ event
];
834 // Allow providing additional args
835 if ( Array
.isArray( method
) ) {
836 args
= method
.slice( 1 );
837 method
= method
[ 0 ];
842 this.on( event
, method
, args
, context
);
848 * Disconnect event handlers from an object.
850 * @param {Object} context Object to disconnect methods from
851 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
852 * event bindings keyed by event name. Values can be either method names or functions, but must be
853 * consistent with those used in the corresponding call to "connect".
856 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
857 var i
, event
, method
, bindings
;
860 // Remove specific connections to the context
861 for ( event
in methods
) {
862 method
= methods
[ event
];
863 if ( Array
.isArray( method
) ) {
864 method
= method
[ 0 ];
866 this.off( event
, method
, context
);
869 // Remove all connections to the context
870 for ( event
in this.bindings
) {
871 bindings
= this.bindings
[ event
];
874 // bindings[i] may have been removed by the previous step's
875 // this.off so check it still exists
876 if ( bindings
[ i
] && bindings
[ i
].context
=== context
) {
877 this.off( event
, bindings
[ i
].method
, context
);
891 * Contain and manage a list of OO.EventEmitter items.
893 * Aggregates and manages their events collectively.
895 * This mixin must be used in a class that also mixes in OO.EventEmitter.
898 * @class OO.EmitterList
901 oo
.EmitterList
= function OoEmitterList() {
903 this.aggregateItemEvents
= {};
909 * Item has been added
912 * @param {OO.EventEmitter} item Added item
913 * @param {number} index Index items were added at
917 * Item has been moved to a new index
920 * @param {OO.EventEmitter} item Moved item
921 * @param {number} index Index item was moved to
922 * @param {number} oldIndex The original index the item was in
926 * Item has been removed
929 * @param {OO.EventEmitter} item Removed item
930 * @param {number} index Index the item was removed from
934 * @event clear The list has been cleared of items
940 * Normalize requested index to fit into the bounds of the given array.
944 * @param {Array} arr Given array
945 * @param {number|undefined} index Requested index
946 * @return {number} Normalized index
948 function normalizeArrayIndex( arr
, index
) {
949 return ( index
=== undefined || index
< 0 || index
>= arr
.length
) ?
957 * @return {OO.EventEmitter[]} Items in the list
959 oo
.EmitterList
.prototype.getItems = function () {
960 return this.items
.slice( 0 );
964 * Get the index of a specific item.
966 * @param {OO.EventEmitter} item Requested item
967 * @return {number} Index of the item
969 oo
.EmitterList
.prototype.getItemIndex = function ( item
) {
970 return this.items
.indexOf( item
);
974 * Get number of items.
976 * @return {number} Number of items in the list
978 oo
.EmitterList
.prototype.getItemCount = function () {
979 return this.items
.length
;
983 * Check if a list contains no items.
985 * @return {boolean} Group is empty
987 oo
.EmitterList
.prototype.isEmpty = function () {
988 return !this.items
.length
;
992 * Aggregate the events emitted by the group.
994 * When events are aggregated, the group will listen to all contained items for the event,
995 * and then emit the event under a new name. The new event will contain an additional leading
996 * parameter containing the item that emitted the original event. Other arguments emitted from
997 * the original event are passed through.
999 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
1000 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
1001 * A `null` value will remove aggregated events.
1003 * @throws {Error} If aggregation already exists
1005 oo
.EmitterList
.prototype.aggregate = function ( events
) {
1006 var i
, item
, add
, remove
, itemEvent
, groupEvent
;
1008 for ( itemEvent
in events
) {
1009 groupEvent
= events
[ itemEvent
];
1011 // Remove existing aggregated event
1012 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
1013 // Don't allow duplicate aggregations
1015 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
1017 // Remove event aggregation from existing items
1018 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1019 item
= this.items
[ i
];
1020 if ( item
.connect
&& item
.disconnect
) {
1022 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
1023 item
.disconnect( this, remove
);
1026 // Prevent future items from aggregating event
1027 delete this.aggregateItemEvents
[ itemEvent
];
1030 // Add new aggregate event
1032 // Make future items aggregate event
1033 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
1034 // Add event aggregation to existing items
1035 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1036 item
= this.items
[ i
];
1037 if ( item
.connect
&& item
.disconnect
) {
1039 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
1040 item
.connect( this, add
);
1048 * Add items to the list.
1050 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1051 * an array of items to add
1052 * @param {number} [index] Index to add items at. If no index is
1053 * given, or if the index that is given is invalid, the item
1054 * will be added at the end of the list.
1059 oo
.EmitterList
.prototype.addItems = function ( items
, index
) {
1062 if ( !Array
.isArray( items
) ) {
1066 if ( items
.length
=== 0 ) {
1070 index
= normalizeArrayIndex( this.items
, index
);
1071 for ( i
= 0; i
< items
.length
; i
++ ) {
1072 oldIndex
= this.items
.indexOf( items
[ i
] );
1073 if ( oldIndex
!== -1 ) {
1074 // Move item to new index
1075 index
= this.moveItem( items
[ i
], index
);
1076 this.emit( 'move', items
[ i
], index
, oldIndex
);
1078 // insert item at index
1079 index
= this.insertItem( items
[ i
], index
);
1080 this.emit( 'add', items
[ i
], index
);
1089 * Move an item from its current position to a new index.
1091 * The item is expected to exist in the list. If it doesn't,
1092 * the method will throw an exception.
1095 * @param {OO.EventEmitter} item Items to add
1096 * @param {number} newIndex Index to move the item to
1097 * @return {number} The index the item was moved to
1098 * @throws {Error} If item is not in the list
1100 oo
.EmitterList
.prototype.moveItem = function ( item
, newIndex
) {
1101 var existingIndex
= this.items
.indexOf( item
);
1103 if ( existingIndex
=== -1 ) {
1104 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1107 newIndex
= normalizeArrayIndex( this.items
, newIndex
);
1109 // Remove the item from the current index
1110 this.items
.splice( existingIndex
, 1 );
1112 // Adjust new index after removal
1115 // Move the item to the new index
1116 this.items
.splice( newIndex
, 0, item
);
1122 * Utility method to insert an item into the list, and
1123 * connect it to aggregate events.
1125 * Don't call this directly unless you know what you're doing.
1126 * Use #addItems instead.
1128 * This method can be extended in child classes to produce
1129 * different behavior when an item is inserted. For example,
1130 * inserted items may also be attached to the DOM or may
1131 * interact with some other nodes in certain ways. Extending
1132 * this method is allowed, but if overriden, the aggregation
1133 * of events must be preserved, or behavior of emitted events
1136 * If you are extending this method, please make sure the
1137 * parent method is called.
1140 * @param {OO.EventEmitter} item Items to add
1141 * @param {number} index Index to add items at
1142 * @return {number} The index the item was added at
1144 oo
.EmitterList
.prototype.insertItem = function ( item
, index
) {
1147 // Add the item to event aggregation
1148 if ( item
.connect
&& item
.disconnect
) {
1150 for ( event
in this.aggregateItemEvents
) {
1151 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
1153 item
.connect( this, events
);
1156 index
= normalizeArrayIndex( this.items
, index
);
1158 // Insert into items array
1159 this.items
.splice( index
, 0, item
);
1166 * @param {OO.EventEmitter[]} items Items to remove
1170 oo
.EmitterList
.prototype.removeItems = function ( items
) {
1173 if ( !Array
.isArray( items
) ) {
1177 if ( items
.length
=== 0 ) {
1181 // Remove specific items
1182 for ( i
= 0; i
< items
.length
; i
++ ) {
1184 index
= this.items
.indexOf( item
);
1185 if ( index
!== -1 ) {
1186 if ( item
.connect
&& item
.disconnect
) {
1187 // Disconnect all listeners from the item
1188 item
.disconnect( this );
1190 this.items
.splice( index
, 1 );
1191 this.emit( 'remove', item
, index
);
1204 oo
.EmitterList
.prototype.clearItems = function () {
1206 cleared
= this.items
.splice( 0, this.items
.length
);
1208 // Disconnect all items
1209 for ( i
= 0; i
< cleared
.length
; i
++ ) {
1210 item
= cleared
[ i
];
1211 if ( item
.connect
&& item
.disconnect
) {
1212 item
.disconnect( this );
1216 this.emit( 'clear' );
1224 * Manage a sorted list of OO.EmitterList objects.
1226 * The sort order is based on a callback that compares two items. The return value of
1227 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1228 * if a is equal to b. The callback should only return zero if the two objects are
1231 * When an item changes in a way that could affect their sorting behavior, it must
1232 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1234 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1237 * @class OO.SortedEmitterList
1238 * @mixins OO.EmitterList
1240 * @param {Function} sortingCallback Callback that compares two items.
1242 oo
.SortedEmitterList
= function OoSortedEmitterList( sortingCallback
) {
1243 // Mixin constructors
1244 oo
.EmitterList
.call( this );
1246 this.sortingCallback
= sortingCallback
;
1248 // Listen to sortChange event and make sure
1249 // we re-sort the changed item when that happens
1251 sortChange
: 'itemSortChange'
1254 this.connect( this, {
1255 itemSortChange
: 'onItemSortChange'
1259 oo
.mixinClass( oo
.SortedEmitterList
, oo
.EmitterList
);
1264 * An item has changed properties that affect its sort positioning
1268 * @event itemSortChange
1274 * Handle a case where an item changed a property that relates
1275 * to its sorted order
1277 * @param {OO.EventEmitter} item Item in the list
1279 oo
.SortedEmitterList
.prototype.onItemSortChange = function ( item
) {
1281 this.removeItems( item
);
1282 // Re-add the item so it is in the correct place
1283 this.addItems( item
);
1287 * Change the sorting callback for this sorted list.
1289 * The callback receives two items. The return value of callback(a, b) must be less than zero
1290 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1292 * @param {Function} sortingCallback Sorting callback
1294 oo
.SortedEmitterList
.prototype.setSortingCallback = function ( sortingCallback
) {
1295 var items
= this.getItems();
1297 this.sortingCallback
= sortingCallback
;
1301 // Re-add the items in the new order
1302 this.addItems( items
);
1306 * Add items to the sorted list.
1309 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1310 * an array of items to add
1312 oo
.SortedEmitterList
.prototype.addItems = function ( items
) {
1313 var index
, i
, insertionIndex
;
1315 if ( !Array
.isArray( items
) ) {
1319 if ( items
.length
=== 0 ) {
1323 for ( i
= 0; i
< items
.length
; i
++ ) {
1324 // Find insertion index
1325 insertionIndex
= this.findInsertionIndex( items
[ i
] );
1327 // Check if the item exists using the sorting callback
1328 // and remove it first if it exists
1330 // First make sure the insertion index is not at the end
1331 // of the list (which means it does not point to any actual
1333 insertionIndex
<= this.items
.length
&&
1334 // Make sure there actually is an item in this index
1335 this.items
[ insertionIndex
] &&
1336 // The callback returns 0 if the items are equal
1337 this.sortingCallback( this.items
[ insertionIndex
], items
[ i
] ) === 0
1339 // Remove the existing item
1340 this.removeItems( this.items
[ insertionIndex
] );
1343 // Insert item at the insertion index
1344 index
= this.insertItem( items
[ i
], insertionIndex
);
1345 this.emit( 'add', items
[ i
], index
);
1352 * Find the index a given item should be inserted at. If the item is already
1353 * in the list, this will return the index where the item currently is.
1355 * @param {OO.EventEmitter} item Items to insert
1356 * @return {number} The index the item should be inserted at
1358 oo
.SortedEmitterList
.prototype.findInsertionIndex = function ( item
) {
1361 return oo
.binarySearch(
1363 // Fake a this.sortingCallback.bind( null, item ) call here
1364 // otherwise this doesn't pass tests in phantomJS
1365 function ( otherItem
) {
1366 return list
.sortingCallback( item
, otherItem
);
1376 * @class OO.Registry
1377 * @mixins OO.EventEmitter
1381 oo
.Registry
= function OoRegistry() {
1382 // Mixin constructors
1383 oo
.EventEmitter
.call( this );
1391 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
1397 * @param {string} name
1398 * @param {Mixed} data
1403 * @param {string} name
1404 * @param {Mixed} data Data removed from registry
1410 * Associate one or more symbolic names with some data.
1412 * Any existing entry with the same name will be overridden.
1414 * @param {string|string[]} name Symbolic name or list of symbolic names
1415 * @param {Mixed} data Data to associate with symbolic name
1417 * @throws {Error} Name argument must be a string or array
1419 oo
.Registry
.prototype.register = function ( name
, data
) {
1421 if ( typeof name
=== 'string' ) {
1422 this.registry
[ name
] = data
;
1423 this.emit( 'register', name
, data
);
1424 } else if ( Array
.isArray( name
) ) {
1425 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1426 this.register( name
[ i
], data
);
1429 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1434 * Remove one or more symbolic names from the registry
1436 * @param {string|string[]} name Symbolic name or list of symbolic names
1438 * @throws {Error} Name argument must be a string or array
1440 oo
.Registry
.prototype.unregister = function ( name
) {
1442 if ( typeof name
=== 'string' ) {
1443 data
= this.lookup( name
);
1444 if ( data
!== undefined ) {
1445 delete this.registry
[ name
];
1446 this.emit( 'unregister', name
, data
);
1448 } else if ( Array
.isArray( name
) ) {
1449 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1450 this.unregister( name
[ i
] );
1453 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1458 * Get data for a given symbolic name.
1460 * @param {string} name Symbolic name
1461 * @return {Mixed|undefined} Data associated with symbolic name
1463 oo
.Registry
.prototype.lookup = function ( name
) {
1464 if ( hasOwn
.call( this.registry
, name
) ) {
1465 return this.registry
[ name
];
1471 * @extends OO.Registry
1475 oo
.Factory
= function OoFactory() {
1476 // Parent constructor
1477 oo
.Factory
.super.call( this );
1482 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
1487 * Register a constructor with the factory.
1489 * Classes must have a static `name` property to be registered.
1491 * function MyClass() {};
1492 * OO.initClass( MyClass );
1493 * // Adds a static property to the class defining a symbolic name
1494 * MyClass.static.name = 'mine';
1495 * // Registers class with factory, available via symbolic name 'mine'
1496 * factory.register( MyClass );
1498 * @param {Function} constructor Constructor to use when creating object
1499 * @throws {Error} Name must be a string and must not be empty
1500 * @throws {Error} Constructor must be a function
1502 oo
.Factory
.prototype.register = function ( constructor ) {
1505 if ( typeof constructor !== 'function' ) {
1506 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1508 name
= constructor.static && constructor.static.name
;
1509 if ( typeof name
!== 'string' || name
=== '' ) {
1510 throw new Error( 'Name must be a string and must not be empty' );
1514 oo
.Factory
.super.prototype.register
.call( this, name
, constructor );
1518 * Unregister a constructor from the factory.
1520 * @param {Function} constructor Constructor to unregister
1521 * @throws {Error} Name must be a string and must not be empty
1522 * @throws {Error} Constructor must be a function
1524 oo
.Factory
.prototype.unregister = function ( constructor ) {
1527 if ( typeof constructor !== 'function' ) {
1528 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1530 name
= constructor.static && constructor.static.name
;
1531 if ( typeof name
!== 'string' || name
=== '' ) {
1532 throw new Error( 'Name must be a string and must not be empty' );
1536 oo
.Factory
.super.prototype.unregister
.call( this, name
);
1540 * Create an object based on a name.
1542 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1543 * constructor directly, so leaving one out will pass an undefined to the constructor.
1545 * @param {string} name Object name
1546 * @param {...Mixed} [args] Arguments to pass to the constructor
1547 * @return {Object} The new object
1548 * @throws {Error} Unknown object name
1550 oo
.Factory
.prototype.create = function ( name
) {
1553 constructor = this.lookup( name
);
1555 if ( !constructor ) {
1556 throw new Error( 'No class registered by that name: ' + name
);
1559 // Convert arguments to array and shift the first argument (name) off
1560 for ( i
= 1; i
< arguments
.length
; i
++ ) {
1561 args
.push( arguments
[ i
] );
1564 // We can't use the "new" operator with .apply directly because apply needs a
1565 // context. So instead just do what "new" does: create an object that inherits from
1566 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1567 // then invoke the constructor with the object as context, and return it (ignoring
1568 // the constructor's return value).
1569 obj
= Object
.create( constructor.prototype );
1570 constructor.apply( obj
, args
);
1574 /* eslint-env node */
1575 if ( typeof module
!== 'undefined' && module
.exports
) {
1576 module
.exports
= oo
;