2 * OOjs v2.2.2 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2018 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
9 * Date: 2018-06-14T20:13:14Z
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 // [DEPRECATED] Provide .parent as alias for code supporting older browsers which
91 // allows people to comply with their style guide.
92 targetFn
.super = targetFn
.parent
= originFn
;
94 targetFn
.prototype = Object
.create( originFn
.prototype, {
95 // Restore constructor property of targetFn
97 value
: targetConstructor
,
104 // Extend static properties - always initialize both sides
105 oo
.initClass( originFn
);
106 targetFn
.static = Object
.create( originFn
.static );
110 * Copy over *own* prototype properties of a mixin.
112 * The 'constructor' (whether implicit or explicit) is not copied over.
114 * This does not create inheritance to the origin. If you need inheritance,
115 * use OO.inheritClass instead.
117 * Beware: This can redefine a prototype property, call before setting your prototypes.
119 * Beware: Don't call before OO.inheritClass.
122 * function Context() {}
124 * // Avoid repeating this code
125 * function ContextLazyLoad() {}
126 * ContextLazyLoad.prototype.getContext = function () {
127 * if ( !this.context ) {
128 * this.context = new Context();
130 * return this.context;
133 * function FooBar() {}
134 * OO.inheritClass( FooBar, Foo );
135 * OO.mixinClass( FooBar, ContextLazyLoad );
137 * @param {Function} targetFn
138 * @param {Function} originFn
140 oo
.mixinClass = function ( targetFn
, originFn
) {
144 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn
+ ')' );
147 // Copy prototype properties
148 for ( key
in originFn
.prototype ) {
149 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
150 targetFn
.prototype[ key
] = originFn
.prototype[ key
];
154 // Copy static properties - always initialize both sides
155 oo
.initClass( targetFn
);
156 if ( originFn
.static ) {
157 for ( key
in originFn
.static ) {
158 if ( hasOwn
.call( originFn
.static, key
) ) {
159 targetFn
.static[ key
] = originFn
.static[ key
];
163 oo
.initClass( originFn
);
168 * Test whether one class is a subclass of another, without instantiating it.
170 * Every class is considered a subclass of Object and of itself.
172 * @param {Function} testFn The class to be tested
173 * @param {Function} baseFn The base class
174 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
176 oo
.isSubclass = function ( testFn
, baseFn
) {
177 return testFn
=== baseFn
|| testFn
.prototype instanceof baseFn
;
183 * Get a deeply nested property of an object using variadic arguments, protecting against
184 * undefined property errors.
186 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
187 * except that the former protects against JS errors if one of the intermediate properties
188 * is undefined. Instead of throwing an error, this function will return undefined in
191 * @param {Object} obj
192 * @param {...Mixed} [keys]
193 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
195 oo
.getProp = function ( obj
) {
198 for ( i
= 1; i
< arguments
.length
; i
++ ) {
199 if ( retval
=== undefined || retval
=== null ) {
200 // Trying to access a property of undefined or null causes an error
203 retval
= retval
[ arguments
[ i
] ];
209 * Set a deeply nested property of an object using variadic arguments, protecting against
210 * undefined property errors.
212 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
213 * the former protects against JS errors if one of the intermediate properties is
214 * undefined. Instead of throwing an error, undefined intermediate properties will be
215 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
216 * is not an object, this function will silently abort.
218 * @param {Object} obj
219 * @param {...Mixed} [keys]
220 * @param {Mixed} [value]
222 oo
.setProp = function ( obj
) {
225 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
228 for ( i
= 1; i
< arguments
.length
- 2; i
++ ) {
229 if ( prop
[ arguments
[ i
] ] === undefined ) {
230 prop
[ arguments
[ i
] ] = {};
232 if ( Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
235 prop
= prop
[ arguments
[ i
] ];
237 prop
[ arguments
[ arguments
.length
- 2 ] ] = arguments
[ arguments
.length
- 1 ];
241 * Delete a deeply nested property of an object using variadic arguments, protecting against
242 * undefined property errors, and deleting resulting empty objects.
244 * @param {Object} obj
245 * @param {...Mixed} [keys]
247 oo
.deleteProp = function ( obj
) {
251 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
254 for ( i
= 1; i
< arguments
.length
- 1; i
++ ) {
255 if ( prop
[ arguments
[ i
] ] === undefined || Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
258 prop
= prop
[ arguments
[ i
] ];
261 delete prop
[ arguments
[ i
] ];
262 // Walk back through props removing any plain empty objects
263 while ( props
.length
> 1 && ( prop
= props
.pop() ) && oo
.isPlainObject( prop
) && !Object
.keys( prop
).length
) {
264 delete props
[ props
.length
- 1 ][ arguments
[ props
.length
] ];
269 * Create a new object that is an instance of the same
270 * constructor as the input, inherits from the same object
271 * and contains the same own properties.
273 * This makes a shallow non-recursive copy of own properties.
274 * To create a recursive copy of plain objects, use #copy.
276 * var foo = new Person( mom, dad );
278 * var foo2 = OO.cloneObject( foo );
282 * foo2 !== foo; // true
283 * foo2 instanceof Person; // true
284 * foo2.getAge(); // 21
285 * foo.getAge(); // 22
287 * @param {Object} origin
288 * @return {Object} Clone of origin
290 oo
.cloneObject = function ( origin
) {
293 r
= Object
.create( origin
.constructor.prototype );
295 for ( key
in origin
) {
296 if ( hasOwn
.call( origin
, key
) ) {
297 r
[ key
] = origin
[ key
];
305 * Get an array of all property values in an object.
307 * @param {Object} obj Object to get values from
308 * @return {Array} List of object values
310 oo
.getObjectValues = function ( obj
) {
313 if ( obj
!== Object( obj
) ) {
314 throw new TypeError( 'Called on non-object' );
319 if ( hasOwn
.call( obj
, key
) ) {
320 values
[ values
.length
] = obj
[ key
];
328 * Use binary search to locate an element in a sorted array.
330 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
331 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
332 * below 0 if it is to the left of elem, or zero if it's equal to elem.
334 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
335 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
336 * `searchFunc = cmp.bind( null, value )`.
338 * @param {Array} arr Array to search in
339 * @param {Function} searchFunc Search function
340 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
341 * @return {number|null} Index where val was found, or null if not found
343 oo
.binarySearch = function ( arr
, searchFunc
, forInsertion
) {
347 while ( left
< right
) {
348 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
349 // eslint-disable-next-line no-bitwise
350 mid
= ( left
+ right
) >> 1;
351 cmpResult
= searchFunc( arr
[ mid
] );
352 if ( cmpResult
< 0 ) {
354 } else if ( cmpResult
> 0 ) {
360 return forInsertion
? right
: null;
364 * Recursively compare properties between two objects.
366 * A false result may be caused by property inequality or by properties in one object missing from
367 * the other. An asymmetrical test may also be performed, which checks only that properties in the
368 * first object are present in the second object, but not the inverse.
370 * If either a or b is null or undefined it will be treated as an empty object.
372 * @param {Object|undefined|null} a First object to compare
373 * @param {Object|undefined|null} b Second object to compare
374 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
375 * (i.e. a is a subset of b)
376 * @return {boolean} If the objects contain the same values as each other
378 oo
.compare = function ( a
, b
, asymmetrical
) {
379 var aValue
, bValue
, aType
, bType
, k
;
388 if ( typeof a
.nodeType
=== 'number' && typeof a
.isEqualNode
=== 'function' ) {
389 return a
.isEqualNode( b
);
393 if ( !hasOwn
.call( a
, k
) || a
[ k
] === undefined || a
[ k
] === b
[ k
] ) {
394 // Ignore undefined values, because there is no conceptual difference between
395 // a key that is absent and a key that is present but whose value is undefined.
401 aType
= typeof aValue
;
402 bType
= typeof bValue
;
403 if ( aType
!== bType
||
405 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
408 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, true ) ) ) {
412 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
413 return asymmetrical
? true : oo
.compare( b
, a
, true );
417 * Create a plain deep copy of any kind of object.
419 * Copies are deep, and will either be an object or an array depending on `source`.
421 * @param {Object} source Object to copy
422 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
423 * @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.
424 * @return {Object} Copy of source object
426 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
427 var key
, destination
;
429 if ( nodeCallback
) {
430 // Extensibility: check before attempting to clone source.
431 destination
= nodeCallback( source
);
432 if ( destination
!== undefined ) {
437 if ( Array
.isArray( source
) ) {
438 // Array (fall through)
439 destination
= new Array( source
.length
);
440 } else if ( source
&& typeof source
.clone
=== 'function' ) {
441 // Duck type object with custom clone method
442 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
443 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
445 return leafCallback
?
446 leafCallback( source
.cloneNode( true ) ) :
447 source
.cloneNode( true );
448 } else if ( oo
.isPlainObject( source
) ) {
449 // Plain objects (fall through)
452 // Non-plain objects (incl. functions) and primitive values
453 return leafCallback
? leafCallback( source
) : source
;
456 // source is an array or a plain object
457 for ( key
in source
) {
458 destination
[ key
] = oo
.copy( source
[ key
], leafCallback
, nodeCallback
);
461 // This is an internal node, so we don't apply the leafCallback.
466 * Generate a hash of an object based on its name and data.
468 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
470 * To avoid two objects with the same values generating different hashes, we utilize the replacer
471 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
472 * not be the fastest way to do this; we should investigate this further.
474 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
475 * function, we call that function and use its return value rather than hashing the object
476 * ourselves. This allows classes to define custom hashing.
478 * @param {Object} val Object to generate hash for
479 * @return {string} Hash of object
481 oo
.getHash = function ( val
) {
482 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
486 * Sort objects by key (helper function for OO.getHash).
488 * This is a callback passed into JSON.stringify.
490 * @method getHash_keySortReplacer
491 * @param {string} key Property name of value being replaced
492 * @param {Mixed} val Property value to replace
493 * @return {Mixed} Replacement value
495 oo
.getHash
.keySortReplacer = function ( key
, val
) {
496 var normalized
, keys
, i
, len
;
497 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
498 // This object has its own custom hash function, use it
499 val
= val
.getHashObject();
501 if ( !Array
.isArray( val
) && Object( val
) === val
) {
502 // Only normalize objects when the key-order is ambiguous
503 // (e.g. any object not an array).
505 keys
= Object
.keys( val
).sort();
508 for ( ; i
< len
; i
+= 1 ) {
509 normalized
[ keys
[ i
] ] = val
[ keys
[ i
] ];
513 // Primitive values and arrays get stable hashes
514 // by default. Lets those be stringified as-is.
520 * Get the unique values of an array, removing duplicates
522 * @param {Array} arr Array
523 * @return {Array} Unique values in array
525 oo
.unique = function ( arr
) {
526 return arr
.reduce( function ( result
, current
) {
527 if ( result
.indexOf( current
) === -1 ) {
528 result
.push( current
);
535 * Compute the union (duplicate-free merge) of a set of arrays.
537 * Arrays values must be convertable to object keys (strings).
539 * By building an object (with the values for keys) in parallel with
540 * the array, a new item's existence in the union can be computed faster.
542 * @param {...Array} arrays Arrays to union
543 * @return {Array} Union of the arrays
545 oo
.simpleArrayUnion = function () {
546 var i
, ilen
, arr
, j
, jlen
,
550 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
551 arr
= arguments
[ i
];
552 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
553 if ( !obj
[ arr
[ j
] ] ) {
554 obj
[ arr
[ j
] ] = true;
555 result
.push( arr
[ j
] );
564 * Combine arrays (intersection or difference).
566 * An intersection checks the item exists in 'b' while difference checks it doesn't.
568 * Arrays values must be convertable to object keys (strings).
570 * By building an object (with the values for keys) of 'b' we can
571 * compute the result faster.
574 * @param {Array} a First array
575 * @param {Array} b Second array
576 * @param {boolean} includeB Whether to items in 'b'
577 * @return {Array} Combination (intersection or difference) of arrays
579 function simpleArrayCombine( a
, b
, includeB
) {
584 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
585 bObj
[ b
[ i
] ] = true;
588 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
589 isInB
= !!bObj
[ a
[ i
] ];
590 if ( isInB
=== includeB
) {
591 result
.push( a
[ i
] );
599 * Compute the intersection of two arrays (items in both arrays).
601 * Arrays values must be convertable to object keys (strings).
603 * @param {Array} a First array
604 * @param {Array} b Second array
605 * @return {Array} Intersection of arrays
607 oo
.simpleArrayIntersection = function ( a
, b
) {
608 return simpleArrayCombine( a
, b
, true );
612 * Compute the difference of two arrays (items in 'a' but not 'b').
614 * Arrays values must be convertable to object keys (strings).
616 * @param {Array} a First array
617 * @param {Array} b Second array
618 * @return {Array} Intersection of arrays
620 oo
.simpleArrayDifference = function ( a
, b
) {
621 return simpleArrayCombine( a
, b
, false );
626 oo
.isPlainObject
= $.isPlainObject
;
633 * @class OO.EventEmitter
637 oo
.EventEmitter
= function OoEventEmitter() {
641 * Storage of bound event handlers by event name.
648 oo
.initClass( oo
.EventEmitter
);
650 /* Private helper functions */
653 * Validate a function or method call in a context
655 * For a method name, check that it names a function in the context object
658 * @param {Function|string} method Function or method name
659 * @param {Mixed} context The context of the call
660 * @throws {Error} A method name is given but there is no context
661 * @throws {Error} In the context object, no property exists with the given name
662 * @throws {Error} In the context object, the named property is not a function
664 function validateMethod( method
, context
) {
665 // Validate method and context
666 if ( typeof method
=== 'string' ) {
668 if ( context
=== undefined || context
=== null ) {
669 throw new Error( 'Method name "' + method
+ '" has no context.' );
671 if ( typeof context
[ method
] !== 'function' ) {
672 // Technically the property could be replaced by a function before
673 // call time. But this probably signals a typo.
674 throw new Error( 'Property "' + method
+ '" is not a function' );
676 } else if ( typeof method
!== 'function' ) {
677 throw new Error( 'Invalid callback. Function or method name expected.' );
683 * @param {OO.EventEmitter} eventEmitter Event emitter
684 * @param {string} event Event name
685 * @param {Object} binding
687 function addBinding( eventEmitter
, event
, binding
) {
689 // Auto-initialize bindings list
690 if ( hasOwn
.call( eventEmitter
.bindings
, event
) ) {
691 bindings
= eventEmitter
.bindings
[ event
];
693 bindings
= eventEmitter
.bindings
[ event
] = [];
696 bindings
.push( binding
);
702 * Add a listener to events of a specific event.
704 * The listener can be a function or the string name of a method; if the latter, then the
705 * name lookup happens at the time the listener is called.
707 * @param {string} event Type of event to listen to
708 * @param {Function|string} method Function or method name to call when event occurs
709 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
710 * @param {Object} [context=null] Context object for function or method call
712 * @throws {Error} Listener argument is not a function or a valid method name
714 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
715 validateMethod( method
, context
);
717 // Ensure consistent object shape (optimisation)
718 addBinding( this, event
, {
721 context
: ( arguments
.length
< 4 ) ? null : context
,
728 * Add a one-time listener to a specific event.
730 * @param {string} event Type of event to listen to
731 * @param {Function} listener Listener to call when event occurs
734 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
735 validateMethod( listener
);
737 // Ensure consistent object shape (optimisation)
738 addBinding( this, event
, {
748 * Remove a specific listener from a specific event.
750 * @param {string} event Type of event to remove listener from
751 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
752 * to "on". Omit to remove all listeners.
753 * @param {Object} [context=null] Context object function or method call
755 * @throws {Error} Listener argument is not a function or a valid method name
757 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
760 if ( arguments
.length
=== 1 ) {
761 // Remove all bindings for event
762 delete this.bindings
[ event
];
766 validateMethod( method
, context
);
768 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[ event
].length
) {
769 // No matching bindings
773 // Default to null context
774 if ( arguments
.length
< 3 ) {
778 // Remove matching handlers
779 bindings
= this.bindings
[ event
];
782 if ( bindings
[ i
].method
=== method
&& bindings
[ i
].context
=== context
) {
783 bindings
.splice( i
, 1 );
787 // Cleanup if now empty
788 if ( bindings
.length
=== 0 ) {
789 delete this.bindings
[ event
];
797 * @param {string} event Type of event
798 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
799 * @return {boolean} Whether the event was handled by at least one listener
801 oo
.EventEmitter
.prototype.emit = function ( event
) {
803 i
, len
, binding
, bindings
, method
;
805 if ( hasOwn
.call( this.bindings
, event
) ) {
806 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
807 bindings
= this.bindings
[ event
].slice();
808 for ( i
= 1, len
= arguments
.length
; i
< len
; i
++ ) {
809 args
.push( arguments
[ i
] );
811 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
812 binding
= bindings
[ i
];
813 if ( typeof binding
.method
=== 'string' ) {
814 // Lookup method by name (late binding)
815 method
= binding
.context
[ binding
.method
];
817 method
= binding
.method
;
819 if ( binding
.once
) {
820 // Must unbind before calling method to avoid
821 // any nested triggers.
822 this.off( event
, method
);
826 binding
.args
? binding
.args
.concat( args
) : args
835 * Connect event handlers to an object.
837 * @param {Object} context Object to call methods on when events occur
838 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
839 * event bindings keyed by event name containing either method names, functions or arrays containing
840 * method name or function followed by a list of arguments to be passed to callback before emitted
844 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
845 var method
, args
, event
;
847 for ( event
in methods
) {
848 method
= methods
[ event
];
849 // Allow providing additional args
850 if ( Array
.isArray( method
) ) {
851 args
= method
.slice( 1 );
852 method
= method
[ 0 ];
857 this.on( event
, method
, args
, context
);
863 * Disconnect event handlers from an object.
865 * @param {Object} context Object to disconnect methods from
866 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
867 * event bindings keyed by event name. Values can be either method names, functions or arrays
868 * containing a method name.
869 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
870 * parameters as well, but only the method name is used to find bindings. Tt is discouraged to
871 * have multiple bindings for the same event to the same listener, but if used (and only the
872 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
873 * will disconnect other variations as well.
876 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
877 var i
, event
, method
, bindings
;
880 // Remove specific connections to the context
881 for ( event
in methods
) {
882 method
= methods
[ event
];
883 if ( Array
.isArray( method
) ) {
884 method
= method
[ 0 ];
886 this.off( event
, method
, context
);
889 // Remove all connections to the context
890 for ( event
in this.bindings
) {
891 bindings
= this.bindings
[ event
];
894 // bindings[i] may have been removed by the previous step's
895 // this.off so check it still exists
896 if ( bindings
[ i
] && bindings
[ i
].context
=== context
) {
897 this.off( event
, bindings
[ i
].method
, context
);
911 * Contain and manage a list of OO.EventEmitter items.
913 * Aggregates and manages their events collectively.
915 * This mixin must be used in a class that also mixes in OO.EventEmitter.
918 * @class OO.EmitterList
921 oo
.EmitterList
= function OoEmitterList() {
923 this.aggregateItemEvents
= {};
929 * Item has been added
932 * @param {OO.EventEmitter} item Added item
933 * @param {number} index Index items were added at
937 * Item has been moved to a new index
940 * @param {OO.EventEmitter} item Moved item
941 * @param {number} index Index item was moved to
942 * @param {number} oldIndex The original index the item was in
946 * Item has been removed
949 * @param {OO.EventEmitter} item Removed item
950 * @param {number} index Index the item was removed from
954 * @event clear The list has been cleared of items
960 * Normalize requested index to fit into the bounds of the given array.
964 * @param {Array} arr Given array
965 * @param {number|undefined} index Requested index
966 * @return {number} Normalized index
968 function normalizeArrayIndex( arr
, index
) {
969 return ( index
=== undefined || index
< 0 || index
>= arr
.length
) ?
977 * @return {OO.EventEmitter[]} Items in the list
979 oo
.EmitterList
.prototype.getItems = function () {
980 return this.items
.slice( 0 );
984 * Get the index of a specific item.
986 * @param {OO.EventEmitter} item Requested item
987 * @return {number} Index of the item
989 oo
.EmitterList
.prototype.getItemIndex = function ( item
) {
990 return this.items
.indexOf( item
);
994 * Get number of items.
996 * @return {number} Number of items in the list
998 oo
.EmitterList
.prototype.getItemCount = function () {
999 return this.items
.length
;
1003 * Check if a list contains no items.
1005 * @return {boolean} Group is empty
1007 oo
.EmitterList
.prototype.isEmpty = function () {
1008 return !this.items
.length
;
1012 * Aggregate the events emitted by the group.
1014 * When events are aggregated, the group will listen to all contained items for the event,
1015 * and then emit the event under a new name. The new event will contain an additional leading
1016 * parameter containing the item that emitted the original event. Other arguments emitted from
1017 * the original event are passed through.
1019 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
1020 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
1021 * A `null` value will remove aggregated events.
1023 * @throws {Error} If aggregation already exists
1025 oo
.EmitterList
.prototype.aggregate = function ( events
) {
1026 var i
, item
, add
, remove
, itemEvent
, groupEvent
;
1028 for ( itemEvent
in events
) {
1029 groupEvent
= events
[ itemEvent
];
1031 // Remove existing aggregated event
1032 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
1033 // Don't allow duplicate aggregations
1035 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
1037 // Remove event aggregation from existing items
1038 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1039 item
= this.items
[ i
];
1040 if ( item
.connect
&& item
.disconnect
) {
1042 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
1043 item
.disconnect( this, remove
);
1046 // Prevent future items from aggregating event
1047 delete this.aggregateItemEvents
[ itemEvent
];
1050 // Add new aggregate event
1052 // Make future items aggregate event
1053 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
1054 // Add event aggregation to existing items
1055 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1056 item
= this.items
[ i
];
1057 if ( item
.connect
&& item
.disconnect
) {
1059 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
1060 item
.connect( this, add
);
1068 * Add items to the list.
1070 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1071 * an array of items to add
1072 * @param {number} [index] Index to add items at. If no index is
1073 * given, or if the index that is given is invalid, the item
1074 * will be added at the end of the list.
1079 oo
.EmitterList
.prototype.addItems = function ( items
, index
) {
1082 if ( !Array
.isArray( items
) ) {
1086 if ( items
.length
=== 0 ) {
1090 index
= normalizeArrayIndex( this.items
, index
);
1091 for ( i
= 0; i
< items
.length
; i
++ ) {
1092 oldIndex
= this.items
.indexOf( items
[ i
] );
1093 if ( oldIndex
!== -1 ) {
1094 // Move item to new index
1095 index
= this.moveItem( items
[ i
], index
);
1096 this.emit( 'move', items
[ i
], index
, oldIndex
);
1098 // insert item at index
1099 index
= this.insertItem( items
[ i
], index
);
1100 this.emit( 'add', items
[ i
], index
);
1109 * Move an item from its current position to a new index.
1111 * The item is expected to exist in the list. If it doesn't,
1112 * the method will throw an exception.
1115 * @param {OO.EventEmitter} item Items to add
1116 * @param {number} newIndex Index to move the item to
1117 * @return {number} The index the item was moved to
1118 * @throws {Error} If item is not in the list
1120 oo
.EmitterList
.prototype.moveItem = function ( item
, newIndex
) {
1121 var existingIndex
= this.items
.indexOf( item
);
1123 if ( existingIndex
=== -1 ) {
1124 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1127 newIndex
= normalizeArrayIndex( this.items
, newIndex
);
1129 // Remove the item from the current index
1130 this.items
.splice( existingIndex
, 1 );
1132 // If necessary, adjust new index after removal
1133 if ( existingIndex
< newIndex
) {
1137 // Move the item to the new index
1138 this.items
.splice( newIndex
, 0, item
);
1144 * Utility method to insert an item into the list, and
1145 * connect it to aggregate events.
1147 * Don't call this directly unless you know what you're doing.
1148 * Use #addItems instead.
1150 * This method can be extended in child classes to produce
1151 * different behavior when an item is inserted. For example,
1152 * inserted items may also be attached to the DOM or may
1153 * interact with some other nodes in certain ways. Extending
1154 * this method is allowed, but if overriden, the aggregation
1155 * of events must be preserved, or behavior of emitted events
1158 * If you are extending this method, please make sure the
1159 * parent method is called.
1162 * @param {OO.EventEmitter} item Items to add
1163 * @param {number} index Index to add items at
1164 * @return {number} The index the item was added at
1166 oo
.EmitterList
.prototype.insertItem = function ( item
, index
) {
1169 // Add the item to event aggregation
1170 if ( item
.connect
&& item
.disconnect
) {
1172 for ( event
in this.aggregateItemEvents
) {
1173 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
1175 item
.connect( this, events
);
1178 index
= normalizeArrayIndex( this.items
, index
);
1180 // Insert into items array
1181 this.items
.splice( index
, 0, item
);
1188 * @param {OO.EventEmitter[]} items Items to remove
1192 oo
.EmitterList
.prototype.removeItems = function ( items
) {
1195 if ( !Array
.isArray( items
) ) {
1199 if ( items
.length
=== 0 ) {
1203 // Remove specific items
1204 for ( i
= 0; i
< items
.length
; i
++ ) {
1206 index
= this.items
.indexOf( item
);
1207 if ( index
!== -1 ) {
1208 if ( item
.connect
&& item
.disconnect
) {
1209 // Disconnect all listeners from the item
1210 item
.disconnect( this );
1212 this.items
.splice( index
, 1 );
1213 this.emit( 'remove', item
, index
);
1226 oo
.EmitterList
.prototype.clearItems = function () {
1228 cleared
= this.items
.splice( 0, this.items
.length
);
1230 // Disconnect all items
1231 for ( i
= 0; i
< cleared
.length
; i
++ ) {
1232 item
= cleared
[ i
];
1233 if ( item
.connect
&& item
.disconnect
) {
1234 item
.disconnect( this );
1238 this.emit( 'clear' );
1246 * Manage a sorted list of OO.EmitterList objects.
1248 * The sort order is based on a callback that compares two items. The return value of
1249 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1250 * if a is equal to b. The callback should only return zero if the two objects are
1253 * When an item changes in a way that could affect their sorting behavior, it must
1254 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1256 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1259 * @class OO.SortedEmitterList
1260 * @mixins OO.EmitterList
1262 * @param {Function} sortingCallback Callback that compares two items.
1264 oo
.SortedEmitterList
= function OoSortedEmitterList( sortingCallback
) {
1265 // Mixin constructors
1266 oo
.EmitterList
.call( this );
1268 this.sortingCallback
= sortingCallback
;
1270 // Listen to sortChange event and make sure
1271 // we re-sort the changed item when that happens
1273 sortChange
: 'itemSortChange'
1276 this.connect( this, {
1277 itemSortChange
: 'onItemSortChange'
1281 oo
.mixinClass( oo
.SortedEmitterList
, oo
.EmitterList
);
1286 * An item has changed properties that affect its sort positioning
1290 * @event itemSortChange
1296 * Handle a case where an item changed a property that relates
1297 * to its sorted order
1299 * @param {OO.EventEmitter} item Item in the list
1301 oo
.SortedEmitterList
.prototype.onItemSortChange = function ( item
) {
1303 this.removeItems( item
);
1304 // Re-add the item so it is in the correct place
1305 this.addItems( item
);
1309 * Change the sorting callback for this sorted list.
1311 * The callback receives two items. The return value of callback(a, b) must be less than zero
1312 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1314 * @param {Function} sortingCallback Sorting callback
1316 oo
.SortedEmitterList
.prototype.setSortingCallback = function ( sortingCallback
) {
1317 var items
= this.getItems();
1319 this.sortingCallback
= sortingCallback
;
1323 // Re-add the items in the new order
1324 this.addItems( items
);
1328 * Add items to the sorted list.
1330 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1331 * an array of items to add
1334 oo
.SortedEmitterList
.prototype.addItems = function ( items
) {
1335 var index
, i
, insertionIndex
;
1337 if ( !Array
.isArray( items
) ) {
1341 if ( items
.length
=== 0 ) {
1345 for ( i
= 0; i
< items
.length
; i
++ ) {
1346 // Find insertion index
1347 insertionIndex
= this.findInsertionIndex( items
[ i
] );
1349 // Check if the item exists using the sorting callback
1350 // and remove it first if it exists
1352 // First make sure the insertion index is not at the end
1353 // of the list (which means it does not point to any actual
1355 insertionIndex
<= this.items
.length
&&
1356 // Make sure there actually is an item in this index
1357 this.items
[ insertionIndex
] &&
1358 // The callback returns 0 if the items are equal
1359 this.sortingCallback( this.items
[ insertionIndex
], items
[ i
] ) === 0
1361 // Remove the existing item
1362 this.removeItems( this.items
[ insertionIndex
] );
1365 // Insert item at the insertion index
1366 index
= this.insertItem( items
[ i
], insertionIndex
);
1367 this.emit( 'add', items
[ i
], index
);
1374 * Find the index a given item should be inserted at. If the item is already
1375 * in the list, this will return the index where the item currently is.
1377 * @param {OO.EventEmitter} item Items to insert
1378 * @return {number} The index the item should be inserted at
1380 oo
.SortedEmitterList
.prototype.findInsertionIndex = function ( item
) {
1383 return oo
.binarySearch(
1385 // Fake a this.sortingCallback.bind( null, item ) call here
1386 // otherwise this doesn't pass tests in phantomJS
1387 function ( otherItem
) {
1388 return list
.sortingCallback( item
, otherItem
);
1398 * A map interface for associating arbitrary data with a symbolic name. Used in
1399 * place of a plain object to provide additional {@link #method-register registration}
1400 * or {@link #method-lookup lookup} functionality.
1402 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1404 * @class OO.Registry
1405 * @mixins OO.EventEmitter
1409 oo
.Registry
= function OoRegistry() {
1410 // Mixin constructors
1411 oo
.EventEmitter
.call( this );
1419 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
1425 * @param {string} name
1426 * @param {Mixed} data
1431 * @param {string} name
1432 * @param {Mixed} data Data removed from registry
1438 * Associate one or more symbolic names with some data.
1440 * Any existing entry with the same name will be overridden.
1442 * @param {string|string[]} name Symbolic name or list of symbolic names
1443 * @param {Mixed} data Data to associate with symbolic name
1445 * @throws {Error} Name argument must be a string or array
1447 oo
.Registry
.prototype.register = function ( name
, data
) {
1449 if ( typeof name
=== 'string' ) {
1450 this.registry
[ name
] = data
;
1451 this.emit( 'register', name
, data
);
1452 } else if ( Array
.isArray( name
) ) {
1453 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1454 this.register( name
[ i
], data
);
1457 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1462 * Remove one or more symbolic names from the registry
1464 * @param {string|string[]} name Symbolic name or list of symbolic names
1466 * @throws {Error} Name argument must be a string or array
1468 oo
.Registry
.prototype.unregister = function ( name
) {
1470 if ( typeof name
=== 'string' ) {
1471 data
= this.lookup( name
);
1472 if ( data
!== undefined ) {
1473 delete this.registry
[ name
];
1474 this.emit( 'unregister', name
, data
);
1476 } else if ( Array
.isArray( name
) ) {
1477 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1478 this.unregister( name
[ i
] );
1481 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1486 * Get data for a given symbolic name.
1488 * @param {string} name Symbolic name
1489 * @return {Mixed|undefined} Data associated with symbolic name
1491 oo
.Registry
.prototype.lookup = function ( name
) {
1492 if ( hasOwn
.call( this.registry
, name
) ) {
1493 return this.registry
[ name
];
1499 * @extends OO.Registry
1503 oo
.Factory
= function OoFactory() {
1504 // Parent constructor
1505 oo
.Factory
.super.call( this );
1510 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
1515 * Register a constructor with the factory.
1517 * Classes must have a static `name` property to be registered.
1519 * function MyClass() {};
1520 * OO.initClass( MyClass );
1521 * // Adds a static property to the class defining a symbolic name
1522 * MyClass.static.name = 'mine';
1523 * // Registers class with factory, available via symbolic name 'mine'
1524 * factory.register( MyClass );
1526 * @param {Function} constructor Constructor to use when creating object
1527 * @throws {Error} Name must be a string and must not be empty
1528 * @throws {Error} Constructor must be a function
1530 oo
.Factory
.prototype.register = function ( constructor ) {
1533 if ( typeof constructor !== 'function' ) {
1534 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1536 name
= constructor.static && constructor.static.name
;
1537 if ( typeof name
!== 'string' || name
=== '' ) {
1538 throw new Error( 'Name must be a string and must not be empty' );
1542 oo
.Factory
.super.prototype.register
.call( this, name
, constructor );
1546 * Unregister a constructor from the factory.
1548 * @param {Function} constructor Constructor to unregister
1549 * @throws {Error} Name must be a string and must not be empty
1550 * @throws {Error} Constructor must be a function
1552 oo
.Factory
.prototype.unregister = function ( constructor ) {
1555 if ( typeof constructor !== 'function' ) {
1556 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1558 name
= constructor.static && constructor.static.name
;
1559 if ( typeof name
!== 'string' || name
=== '' ) {
1560 throw new Error( 'Name must be a string and must not be empty' );
1564 oo
.Factory
.super.prototype.unregister
.call( this, name
);
1568 * Create an object based on a name.
1570 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1571 * constructor directly, so leaving one out will pass an undefined to the constructor.
1573 * @param {string} name Object name
1574 * @param {...Mixed} [args] Arguments to pass to the constructor
1575 * @return {Object} The new object
1576 * @throws {Error} Unknown object name
1578 oo
.Factory
.prototype.create = function ( name
) {
1581 constructor = this.lookup( name
);
1583 if ( !constructor ) {
1584 throw new Error( 'No class registered by that name: ' + name
);
1587 // Convert arguments to array and shift the first argument (name) off
1588 for ( i
= 1; i
< arguments
.length
; i
++ ) {
1589 args
.push( arguments
[ i
] );
1592 // We can't use the "new" operator with .apply directly because apply needs a
1593 // context. So instead just do what "new" does: create an object that inherits from
1594 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1595 // then invoke the constructor with the object as context, and return it (ignoring
1596 // the constructor's return value).
1597 obj
= Object
.create( constructor.prototype );
1598 constructor.apply( obj
, args
);
1602 /* eslint-env node */
1604 /* istanbul ignore next */
1605 if ( typeof module
!== 'undefined' && module
.exports
) {
1606 module
.exports
= oo
;