2 * OOjs v2.1.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-05-30T22:56:52Z
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.' );
688 * @param {OO.EventEmitter} ee
689 * @param {Function|string} method Function or method name
690 * @param {Object} binding
692 function addBinding( ee, event, binding ) {
694 // Auto-initialize bindings list
695 if ( hasOwn.call( ee.bindings, event ) ) {
696 bindings = ee.bindings[ event ];
698 bindings = ee.bindings[ event ] = [];
701 bindings.push( binding );
707 * Add a listener to events of a specific event.
709 * The listener can be a function or the string name of a method; if the latter, then the
710 * name lookup happens at the time the listener is called.
712 * @param {string} event Type of event to listen to
713 * @param {Function|string} method Function or method name to call when event occurs
714 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
715 * @param {Object} [context=null] Context object for function or method call
716 * @throws {Error} Listener argument is not a function or a valid method name
719 oo.EventEmitter.prototype.on = function ( event, method, args, context ) {
720 validateMethod( method, context );
722 // Ensure consistent object shape (optimisation)
723 addBinding( this, event, {
726 context: ( arguments.length < 4 ) ? null : context,
733 * Add a one-time listener to a specific event.
735 * @param {string} event Type of event to listen to
736 * @param {Function} listener Listener to call when event occurs
739 oo.EventEmitter.prototype.once = function ( event, listener ) {
740 validateMethod( listener );
742 // Ensure consistent object shape (optimisation)
743 addBinding( this, event, {
753 * Remove a specific listener from a specific event.
755 * @param {string} event Type of event to remove listener from
756 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
757 * to "on". Omit to remove all listeners.
758 * @param {Object} [context=null] Context object function or method call
760 * @throws {Error} Listener argument is not a function or a valid method name
762 oo.EventEmitter.prototype.off = function ( event, method, context ) {
765 if ( arguments.length === 1 ) {
766 // Remove all bindings for event
767 delete this.bindings[ event ];
771 validateMethod( method, context );
773 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) {
774 // No matching bindings
778 // Default to null context
779 if ( arguments.length < 3 ) {
783 // Remove matching handlers
784 bindings = this.bindings[ event ];
787 if ( bindings[ i ].method === method && bindings[ i ].context === context ) {
788 bindings.splice( i, 1 );
792 // Cleanup if now empty
793 if ( bindings.length === 0 ) {
794 delete this.bindings[ event ];
802 * @param {string} event Type of event
803 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
804 * @return {boolean} Whether the event was handled by at least one listener
806 oo.EventEmitter.prototype.emit = function ( event ) {
808 i, len, binding, bindings, method;
810 if ( hasOwn.call( this.bindings, event ) ) {
811 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
812 bindings = this.bindings[ event ].slice();
813 for ( i = 1, len = arguments.length; i < len; i++ ) {
814 args.push( arguments[ i ] );
816 for ( i = 0, len = bindings.length; i < len; i++ ) {
817 binding = bindings[ i ];
818 if ( typeof binding.method === 'string' ) {
819 // Lookup method by name (late binding)
820 method = binding.context[ binding.method ];
822 method = binding.method;
824 if ( binding.once ) {
825 // Must unbind before calling method to avoid
826 // any nested triggers.
827 this.off( event, method );
831 binding.args ? binding.args.concat( args ) : args
840 * Connect event handlers to an object.
842 * @param {Object} context Object to call methods on when events occur
843 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
844 * event bindings keyed by event name containing either method names, functions or arrays containing
845 * method name or function followed by a list of arguments to be passed to callback before emitted
849 oo.EventEmitter.prototype.connect = function ( context, methods ) {
850 var method, args, event;
852 for ( event in methods ) {
853 method = methods[ event ];
854 // Allow providing additional args
855 if ( Array.isArray( method ) ) {
856 args = method.slice( 1 );
857 method = method[ 0 ];
862 this.on( event, method, args, context );
868 * Disconnect event handlers from an object.
870 * @param {Object} context Object to disconnect methods from
871 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
872 * event bindings keyed by event name. Values can be either method names, functions or arrays
873 * containing a method name.
874 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
875 * parameters as well, but only the method name is used to find bindings. Tt is discouraged to
876 * have multiple bindings for the same event to the same listener, but if used (and only the
877 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
878 * will disconnect other variations as well.
881 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
882 var i, event, method, bindings;
885 // Remove specific connections to the context
886 for ( event in methods ) {
887 method = methods[ event ];
888 if ( Array.isArray( method ) ) {
889 method = method[ 0 ];
891 this.off( event, method, context );
894 // Remove all connections to the context
895 for ( event in this.bindings ) {
896 bindings = this.bindings[ event ];
899 // bindings[i] may have been removed by the previous step's
900 // this.off so check it still exists
901 if ( bindings[ i ] && bindings[ i ].context === context ) {
902 this.off( event, bindings[ i ].method, context );
916 * Contain and manage a list of OO.EventEmitter items.
918 * Aggregates and manages their events collectively.
920 * This mixin must be used in a class that also mixes in OO.EventEmitter.
923 * @class OO.EmitterList
926 oo.EmitterList = function OoEmitterList() {
928 this.aggregateItemEvents = {};
934 * Item has been added
937 * @param {OO.EventEmitter} item Added item
938 * @param {number} index Index items were added at
942 * Item has been moved to a new index
945 * @param {OO.EventEmitter} item Moved item
946 * @param {number} index Index item was moved to
947 * @param {number} oldIndex The original index the item was in
951 * Item has been removed
954 * @param {OO.EventEmitter} item Removed item
955 * @param {number} index Index the item was removed from
959 * @event clear The list has been cleared of items
965 * Normalize requested index to fit into the bounds of the given array.
969 * @param {Array} arr Given array
970 * @param {number|undefined} index Requested index
971 * @return {number} Normalized index
973 function normalizeArrayIndex( arr, index ) {
974 return ( index === undefined || index < 0 || index >= arr.length ) ?
982 * @return {OO.EventEmitter[]} Items in the list
984 oo.EmitterList.prototype.getItems = function () {
985 return this.items.slice( 0 );
989 * Get the index of a specific item.
991 * @param {OO.EventEmitter} item Requested item
992 * @return {number} Index of the item
994 oo.EmitterList.prototype.getItemIndex = function ( item ) {
995 return this.items.indexOf( item );
999 * Get number of items.
1001 * @return {number} Number of items in the list
1003 oo.EmitterList.prototype.getItemCount = function () {
1004 return this.items.length;
1008 * Check if a list contains no items.
1010 * @return {boolean} Group is empty
1012 oo.EmitterList.prototype.isEmpty = function () {
1013 return !this.items.length;
1017 * Aggregate the events emitted by the group.
1019 * When events are aggregated, the group will listen to all contained items for the event,
1020 * and then emit the event under a new name. The new event will contain an additional leading
1021 * parameter containing the item that emitted the original event. Other arguments emitted from
1022 * the original event are passed through.
1024 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
1025 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
1026 * A `null` value will remove aggregated events.
1028 * @throws {Error} If aggregation already exists
1030 oo.EmitterList.prototype.aggregate = function ( events ) {
1031 var i, item, add, remove, itemEvent, groupEvent;
1033 for ( itemEvent in events ) {
1034 groupEvent = events[ itemEvent ];
1036 // Remove existing aggregated event
1037 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
1038 // Don't allow duplicate aggregations
1040 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
1042 // Remove event aggregation from existing items
1043 for ( i = 0; i < this.items.length; i++ ) {
1044 item = this.items[ i ];
1045 if ( item.connect && item.disconnect ) {
1047 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
1048 item.disconnect( this, remove );
1051 // Prevent future items from aggregating event
1052 delete this.aggregateItemEvents[ itemEvent ];
1055 // Add new aggregate event
1057 // Make future items aggregate event
1058 this.aggregateItemEvents[ itemEvent ] = groupEvent;
1059 // Add event aggregation to existing items
1060 for ( i = 0; i < this.items.length; i++ ) {
1061 item = this.items[ i ];
1062 if ( item.connect && item.disconnect ) {
1064 add[ itemEvent ] = [ 'emit', groupEvent, item ];
1065 item.connect( this, add );
1073 * Add items to the list.
1075 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1076 * an array of items to add
1077 * @param {number} [index] Index to add items at. If no index is
1078 * given, or if the index that is given is invalid, the item
1079 * will be added at the end of the list.
1084 oo.EmitterList.prototype.addItems = function ( items, index ) {
1087 if ( !Array.isArray( items ) ) {
1091 if ( items.length === 0 ) {
1095 index = normalizeArrayIndex( this.items, index );
1096 for ( i = 0; i < items.length; i++ ) {
1097 oldIndex = this.items.indexOf( items[ i ] );
1098 if ( oldIndex !== -1 ) {
1099 // Move item to new index
1100 index = this.moveItem( items[ i ], index );
1101 this.emit( 'move', items[ i ], index, oldIndex );
1103 // insert item at index
1104 index = this.insertItem( items[ i ], index );
1105 this.emit( 'add', items[ i ], index );
1114 * Move an item from its current position to a new index.
1116 * The item is expected to exist in the list. If it doesn't,
1117 * the method will throw an exception.
1120 * @param {OO.EventEmitter} item Items to add
1121 * @param {number} newIndex Index to move the item to
1122 * @return {number} The index the item was moved to
1123 * @throws {Error} If item is not in the list
1125 oo.EmitterList.prototype.moveItem = function ( item, newIndex ) {
1126 var existingIndex = this.items.indexOf( item );
1128 if ( existingIndex === -1 ) {
1129 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1132 newIndex = normalizeArrayIndex( this.items, newIndex );
1134 // Remove the item from the current index
1135 this.items.splice( existingIndex, 1 );
1137 // If necessary, adjust new index after removal
1138 if ( existingIndex < newIndex ) {
1142 // Move the item to the new index
1143 this.items.splice( newIndex, 0, item );
1149 * Utility method to insert an item into the list, and
1150 * connect it to aggregate events.
1152 * Don't call this directly unless you know what you're doing.
1153 * Use #addItems instead.
1155 * This method can be extended in child classes to produce
1156 * different behavior when an item is inserted. For example,
1157 * inserted items may also be attached to the DOM or may
1158 * interact with some other nodes in certain ways. Extending
1159 * this method is allowed, but if overriden, the aggregation
1160 * of events must be preserved, or behavior of emitted events
1163 * If you are extending this method, please make sure the
1164 * parent method is called.
1167 * @param {OO.EventEmitter} item Items to add
1168 * @param {number} index Index to add items at
1169 * @return {number} The index the item was added at
1171 oo.EmitterList.prototype.insertItem = function ( item, index ) {
1174 // Add the item to event aggregation
1175 if ( item.connect && item.disconnect ) {
1177 for ( event in this.aggregateItemEvents ) {
1178 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
1180 item.connect( this, events );
1183 index = normalizeArrayIndex( this.items, index );
1185 // Insert into items array
1186 this.items.splice( index, 0, item );
1193 * @param {OO.EventEmitter[]} items Items to remove
1197 oo.EmitterList.prototype.removeItems = function ( items ) {
1200 if ( !Array.isArray( items ) ) {
1204 if ( items.length === 0 ) {
1208 // Remove specific items
1209 for ( i = 0; i < items.length; i++ ) {
1211 index = this.items.indexOf( item );
1212 if ( index !== -1 ) {
1213 if ( item.connect && item.disconnect ) {
1214 // Disconnect all listeners from the item
1215 item.disconnect( this );
1217 this.items.splice( index, 1 );
1218 this.emit( 'remove', item, index );
1231 oo.EmitterList.prototype.clearItems = function () {
1233 cleared = this.items.splice( 0, this.items.length );
1235 // Disconnect all items
1236 for ( i = 0; i < cleared.length; i++ ) {
1237 item = cleared[ i ];
1238 if ( item.connect && item.disconnect ) {
1239 item.disconnect( this );
1243 this.emit( 'clear' );
1251 * Manage a sorted list of OO.EmitterList objects.
1253 * The sort order is based on a callback that compares two items. The return value of
1254 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1255 * if a is equal to b. The callback should only return zero if the two objects are
1258 * When an item changes in a way that could affect their sorting behavior, it must
1259 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1261 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1264 * @class OO.SortedEmitterList
1265 * @mixins OO.EmitterList
1267 * @param {Function} sortingCallback Callback that compares two items.
1269 oo.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) {
1270 // Mixin constructors
1271 oo.EmitterList.call( this );
1273 this.sortingCallback = sortingCallback;
1275 // Listen to sortChange event and make sure
1276 // we re-sort the changed item when that happens
1278 sortChange: 'itemSortChange'
1281 this.connect( this, {
1282 itemSortChange: 'onItemSortChange'
1286 oo.mixinClass( oo.SortedEmitterList, oo.EmitterList );
1291 * An item has changed properties that affect its sort positioning
1295 * @event itemSortChange
1301 * Handle a case where an item changed a property that relates
1302 * to its sorted order
1304 * @param {OO.EventEmitter} item Item in the list
1306 oo.SortedEmitterList.prototype.onItemSortChange = function ( item ) {
1308 this.removeItems( item );
1309 // Re-add the item so it is in the correct place
1310 this.addItems( item );
1314 * Change the sorting callback for this sorted list.
1316 * The callback receives two items. The return value of callback(a, b) must be less than zero
1317 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1319 * @param {Function} sortingCallback Sorting callback
1321 oo.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) {
1322 var items = this.getItems();
1324 this.sortingCallback = sortingCallback;
1328 // Re-add the items in the new order
1329 this.addItems( items );
1333 * Add items to the sorted list.
1336 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1337 * an array of items to add
1339 oo.SortedEmitterList.prototype.addItems = function ( items ) {
1340 var index, i, insertionIndex;
1342 if ( !Array.isArray( items ) ) {
1346 if ( items.length === 0 ) {
1350 for ( i = 0; i < items.length; i++ ) {
1351 // Find insertion index
1352 insertionIndex = this.findInsertionIndex( items[ i ] );
1354 // Check if the item exists using the sorting callback
1355 // and remove it first if it exists
1357 // First make sure the insertion index is not at the end
1358 // of the list (which means it does not point to any actual
1360 insertionIndex <= this.items.length &&
1361 // Make sure there actually is an item in this index
1362 this.items[ insertionIndex ] &&
1363 // The callback returns 0 if the items are equal
1364 this.sortingCallback( this.items[ insertionIndex ], items[ i ] ) === 0
1366 // Remove the existing item
1367 this.removeItems( this.items[ insertionIndex ] );
1370 // Insert item at the insertion index
1371 index = this.insertItem( items[ i ], insertionIndex );
1372 this.emit( 'add', items[ i ], index );
1379 * Find the index a given item should be inserted at. If the item is already
1380 * in the list, this will return the index where the item currently is.
1382 * @param {OO.EventEmitter} item Items to insert
1383 * @return {number} The index the item should be inserted at
1385 oo.SortedEmitterList.prototype.findInsertionIndex = function ( item ) {
1388 return oo.binarySearch(
1390 // Fake a this.sortingCallback.bind( null, item ) call here
1391 // otherwise this doesn't pass tests in phantomJS
1392 function ( otherItem ) {
1393 return list.sortingCallback( item, otherItem );
1403 * @class OO.Registry
1404 * @mixins OO.EventEmitter
1408 oo.Registry = function OoRegistry() {
1409 // Mixin constructors
1410 oo.EventEmitter.call( this );
1418 oo.mixinClass( oo.Registry, oo.EventEmitter );
1424 * @param {string} name
1425 * @param {Mixed} data
1430 * @param {string} name
1431 * @param {Mixed} data Data removed from registry
1437 * Associate one or more symbolic names with some data.
1439 * Any existing entry with the same name will be overridden.
1441 * @param {string|string[]} name Symbolic name or list of symbolic names
1442 * @param {Mixed} data Data to associate with symbolic name
1444 * @throws {Error} Name argument must be a string or array
1446 oo.Registry.prototype.register = function ( name, data ) {
1448 if ( typeof name === 'string' ) {
1449 this.registry[ name ] = data;
1450 this.emit( 'register', name, data );
1451 } else if ( Array.isArray( name ) ) {
1452 for ( i = 0, len = name.length; i < len; i++ ) {
1453 this.register( name[ i ], data );
1456 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1461 * Remove one or more symbolic names from the registry
1463 * @param {string|string[]} name Symbolic name or list of symbolic names
1465 * @throws {Error} Name argument must be a string or array
1467 oo.Registry.prototype.unregister = function ( name ) {
1469 if ( typeof name === 'string' ) {
1470 data = this.lookup( name );
1471 if ( data !== undefined ) {
1472 delete this.registry[ name ];
1473 this.emit( 'unregister', name, data );
1475 } else if ( Array.isArray( name ) ) {
1476 for ( i = 0, len = name.length; i < len; i++ ) {
1477 this.unregister( name[ i ] );
1480 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1485 * Get data for a given symbolic name.
1487 * @param {string} name Symbolic name
1488 * @return {Mixed|undefined} Data associated with symbolic name
1490 oo.Registry.prototype.lookup = function ( name ) {
1491 if ( hasOwn.call( this.registry, name ) ) {
1492 return this.registry[ name ];
1498 * @extends OO.Registry
1502 oo.Factory = function OoFactory() {
1503 // Parent constructor
1504 oo.Factory.super.call( this );
1509 oo.inheritClass( oo.Factory, oo.Registry );
1514 * Register a constructor with the factory.
1516 * Classes must have a static `name` property to be registered.
1518 * function MyClass() {};
1519 * OO.initClass( MyClass );
1520 * // Adds a static property to the class defining a symbolic name
1521 * MyClass.static.name = 'mine';
1522 * // Registers class with factory, available via symbolic name 'mine'
1523 * factory.register( MyClass );
1525 * @param {Function} constructor Constructor to use when creating object
1526 * @throws {Error} Name must be a string and must not be empty
1527 * @throws {Error} Constructor must be a function
1529 oo.Factory.prototype.register = function ( constructor ) {
1532 if ( typeof constructor !== 'function' ) {
1533 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1535 name = constructor.static && constructor.static.name;
1536 if ( typeof name !== 'string' || name === '' ) {
1537 throw new Error( 'Name must be a string and must not be empty' );
1541 oo.Factory.super.prototype.register.call( this, name, constructor );
1545 * Unregister a constructor from the factory.
1547 * @param {Function} constructor Constructor to unregister
1548 * @throws {Error} Name must be a string and must not be empty
1549 * @throws {Error} Constructor must be a function
1551 oo.Factory.prototype.unregister = function ( constructor ) {
1554 if ( typeof constructor !== 'function' ) {
1555 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1557 name = constructor.static && constructor.static.name;
1558 if ( typeof name !== 'string' || name === '' ) {
1559 throw new Error( 'Name must be a string and must not be empty' );
1563 oo.Factory.super.prototype.unregister.call( this, name );
1567 * Create an object based on a name.
1569 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1570 * constructor directly, so leaving one out will pass an undefined to the constructor.
1572 * @param {string} name Object name
1573 * @param {...Mixed} [args] Arguments to pass to the constructor
1574 * @return {Object} The new object
1575 * @throws {Error} Unknown object name
1577 oo.Factory.prototype.create = function ( name ) {
1580 constructor = this.lookup( name );
1582 if ( !constructor ) {
1583 throw new Error( 'No class registered by that name: ' + name );
1586 // Convert arguments to array and shift the first argument (name) off
1587 for ( i = 1; i < arguments.length; i++ ) {
1588 args.push( arguments[ i ] );
1591 // We can't use the "new" operator with .apply directly because apply needs a
1592 // context. So instead just do what "new" does: create an object that inherits from
1593 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1594 // then invoke the constructor with the object as context, and return it (ignoring
1595 // the constructor's return value).
1596 obj = Object.create( constructor.prototype );
1597 constructor.apply( obj, args );
1601 /* eslint-env node */
1603 /* istanbul ignore next */
1604 if ( typeof module !== 'undefined' && module.exports ) {
1605 module.exports = oo;