2 * OOjs v2.2.0 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-04-03T19:45:13Z
11 ( function ( global
) {
17 * Namespace for all classes, static methods and static properties.
22 // Optimisation: Local reference to Object.prototype.hasOwnProperty
23 hasOwn
= oo
.hasOwnProperty
,
24 // Marking this as "exported" doesn't work when parserOptions.sourceType is module
25 // eslint-disable-next-line no-unused-vars
26 toString
= oo
.toString
;
31 * Utility to initialize a class for OO inheritance.
33 * Currently this just initializes an empty static object.
35 * @param {Function} fn
37 oo
.initClass = function ( fn
) {
38 fn
.static = fn
.static || {};
42 * Inherit from prototype to another using Object#create.
44 * Beware: This redefines the prototype, call before setting your prototypes.
46 * Beware: This redefines the prototype, can only be called once on a function.
47 * If called multiple times on the same function, the previous prototype is lost.
48 * This is how prototypal inheritance works, it can only be one straight chain
49 * (just like classical inheritance in PHP for example). If you need to work with
50 * multiple constructors consider storing an instance of the other constructor in a
51 * property instead, or perhaps use a mixin (see OO.mixinClass).
54 * Thing.prototype.exists = function () {};
57 * Person.super.apply( this, arguments );
59 * OO.inheritClass( Person, Thing );
60 * Person.static.defaultEyeCount = 2;
61 * Person.prototype.walk = function () {};
64 * Jumper.super.apply( this, arguments );
66 * OO.inheritClass( Jumper, Person );
67 * Jumper.prototype.jump = function () {};
69 * Jumper.static.defaultEyeCount === 2;
70 * var x = new Jumper();
73 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
75 * @param {Function} targetFn
76 * @param {Function} originFn
77 * @throws {Error} If target already inherits from origin
79 oo
.inheritClass = function ( targetFn
, originFn
) {
80 var targetConstructor
;
83 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn
+ ')' );
85 if ( targetFn
.prototype instanceof originFn
) {
86 throw new Error( 'inheritClass: Target already inherits from origin' );
89 targetConstructor
= targetFn
.prototype.constructor;
91 // [DEPRECATED] Provide .parent as alias for code supporting older browsers which
92 // allows people to comply with their style guide.
93 targetFn
.super = targetFn
.parent
= originFn
;
95 targetFn
.prototype = Object
.create( originFn
.prototype, {
96 // Restore constructor property of targetFn
98 value
: targetConstructor
,
105 // Extend static properties - always initialize both sides
106 oo
.initClass( originFn
);
107 targetFn
.static = Object
.create( originFn
.static );
111 * Copy over *own* prototype properties of a mixin.
113 * The 'constructor' (whether implicit or explicit) is not copied over.
115 * This does not create inheritance to the origin. If you need inheritance,
116 * use OO.inheritClass instead.
118 * Beware: This can redefine a prototype property, call before setting your prototypes.
120 * Beware: Don't call before OO.inheritClass.
123 * function Context() {}
125 * // Avoid repeating this code
126 * function ContextLazyLoad() {}
127 * ContextLazyLoad.prototype.getContext = function () {
128 * if ( !this.context ) {
129 * this.context = new Context();
131 * return this.context;
134 * function FooBar() {}
135 * OO.inheritClass( FooBar, Foo );
136 * OO.mixinClass( FooBar, ContextLazyLoad );
138 * @param {Function} targetFn
139 * @param {Function} originFn
141 oo
.mixinClass = function ( targetFn
, originFn
) {
145 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn
+ ')' );
148 // Copy prototype properties
149 for ( key
in originFn
.prototype ) {
150 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
151 targetFn
.prototype[ key
] = originFn
.prototype[ key
];
155 // Copy static properties - always initialize both sides
156 oo
.initClass( targetFn
);
157 if ( originFn
.static ) {
158 for ( key
in originFn
.static ) {
159 if ( hasOwn
.call( originFn
.static, key
) ) {
160 targetFn
.static[ key
] = originFn
.static[ key
];
164 oo
.initClass( originFn
);
169 * Test whether one class is a subclass of another, without instantiating it.
171 * Every class is considered a subclass of Object and of itself.
173 * @param {Function} testFn The class to be tested
174 * @param {Function} baseFn The base class
175 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
177 oo
.isSubclass = function ( testFn
, baseFn
) {
178 return testFn
=== baseFn
|| testFn
.prototype instanceof baseFn
;
184 * Get a deeply nested property of an object using variadic arguments, protecting against
185 * undefined property errors.
187 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
188 * except that the former protects against JS errors if one of the intermediate properties
189 * is undefined. Instead of throwing an error, this function will return undefined in
192 * @param {Object} obj
193 * @param {...Mixed} [keys]
194 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
196 oo
.getProp = function ( obj
) {
199 for ( i
= 1; i
< arguments
.length
; i
++ ) {
200 if ( retval
=== undefined || retval
=== null ) {
201 // Trying to access a property of undefined or null causes an error
204 retval
= retval
[ arguments
[ i
] ];
210 * Set a deeply nested property of an object using variadic arguments, protecting against
211 * undefined property errors.
213 * `oo.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
214 * the former protects against JS errors if one of the intermediate properties is
215 * undefined. Instead of throwing an error, undefined intermediate properties will be
216 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
217 * is not an object, this function will silently abort.
219 * @param {Object} obj
220 * @param {...Mixed} [keys]
221 * @param {Mixed} [value]
223 oo
.setProp = function ( obj
) {
226 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
229 for ( i
= 1; i
< arguments
.length
- 2; i
++ ) {
230 if ( prop
[ arguments
[ i
] ] === undefined ) {
231 prop
[ arguments
[ i
] ] = {};
233 if ( Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
236 prop
= prop
[ arguments
[ i
] ];
238 prop
[ arguments
[ arguments
.length
- 2 ] ] = arguments
[ arguments
.length
- 1 ];
242 * Delete a deeply nested property of an object using variadic arguments, protecting against
243 * undefined property errors, and deleting resulting empty objects.
245 * @param {Object} obj
246 * @param {...Mixed} [keys]
248 oo
.deleteProp = function ( obj
) {
252 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
255 for ( i
= 1; i
< arguments
.length
- 1; i
++ ) {
256 if ( prop
[ arguments
[ i
] ] === undefined || Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
259 prop
= prop
[ arguments
[ i
] ];
262 delete prop
[ arguments
[ i
] ];
263 // Walk back through props removing any plain empty objects
264 while ( props
.length
> 1 && ( prop
= props
.pop() ) && oo
.isPlainObject( prop
) && !Object
.keys( prop
).length
) {
265 delete props
[ props
.length
- 1 ][ arguments
[ props
.length
] ];
270 * Create a new object that is an instance of the same
271 * constructor as the input, inherits from the same object
272 * and contains the same own properties.
274 * This makes a shallow non-recursive copy of own properties.
275 * To create a recursive copy of plain objects, use #copy.
277 * var foo = new Person( mom, dad );
279 * var foo2 = OO.cloneObject( foo );
283 * foo2 !== foo; // true
284 * foo2 instanceof Person; // true
285 * foo2.getAge(); // 21
286 * foo.getAge(); // 22
288 * @param {Object} origin
289 * @return {Object} Clone of origin
291 oo
.cloneObject = function ( origin
) {
294 r
= Object
.create( origin
.constructor.prototype );
296 for ( key
in origin
) {
297 if ( hasOwn
.call( origin
, key
) ) {
298 r
[ key
] = origin
[ key
];
306 * Get an array of all property values in an object.
308 * @param {Object} obj Object to get values from
309 * @return {Array} List of object values
311 oo
.getObjectValues = function ( obj
) {
314 if ( obj
!== Object( obj
) ) {
315 throw new TypeError( 'Called on non-object' );
320 if ( hasOwn
.call( obj
, key
) ) {
321 values
[ values
.length
] = obj
[ key
];
329 * Use binary search to locate an element in a sorted array.
331 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
332 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
333 * below 0 if it is to the left of elem, or zero if it's equal to elem.
335 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
336 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
337 * `searchFunc = cmp.bind( null, value )`.
339 * @param {Array} arr Array to search in
340 * @param {Function} searchFunc Search function
341 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
342 * @return {number|null} Index where val was found, or null if not found
344 oo
.binarySearch = function ( arr
, searchFunc
, forInsertion
) {
348 while ( left
< right
) {
349 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
350 // eslint-disable-next-line no-bitwise
351 mid
= ( left
+ right
) >> 1;
352 cmpResult
= searchFunc( arr
[ mid
] );
353 if ( cmpResult
< 0 ) {
355 } else if ( cmpResult
> 0 ) {
361 return forInsertion
? right
: null;
365 * Recursively compare properties between two objects.
367 * A false result may be caused by property inequality or by properties in one object missing from
368 * the other. An asymmetrical test may also be performed, which checks only that properties in the
369 * first object are present in the second object, but not the inverse.
371 * If either a or b is null or undefined it will be treated as an empty object.
373 * @param {Object|undefined|null} a First object to compare
374 * @param {Object|undefined|null} b Second object to compare
375 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
376 * (i.e. a is a subset of b)
377 * @return {boolean} If the objects contain the same values as each other
379 oo
.compare = function ( a
, b
, asymmetrical
) {
380 var aValue
, bValue
, aType
, bType
, k
;
389 if ( typeof a
.nodeType
=== 'number' && typeof a
.isEqualNode
=== 'function' ) {
390 return a
.isEqualNode( b
);
394 if ( !hasOwn
.call( a
, k
) || a
[ k
] === undefined || a
[ k
] === b
[ k
] ) {
395 // Ignore undefined values, because there is no conceptual difference between
396 // a key that is absent and a key that is present but whose value is undefined.
402 aType
= typeof aValue
;
403 bType
= typeof bValue
;
404 if ( aType
!== bType
||
406 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
409 ( aValue
=== Object( aValue
) && !oo
.compare( aValue
, bValue
, true ) ) ) {
413 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
414 return asymmetrical
? true : oo
.compare( b
, a
, true );
418 * Create a plain deep copy of any kind of object.
420 * Copies are deep, and will either be an object or an array depending on `source`.
422 * @param {Object} source Object to copy
423 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are added to the clone
424 * @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.
425 * @return {Object} Copy of source object
427 oo
.copy = function ( source
, leafCallback
, nodeCallback
) {
428 var key
, destination
;
430 if ( nodeCallback
) {
431 // Extensibility: check before attempting to clone source.
432 destination
= nodeCallback( source
);
433 if ( destination
!== undefined ) {
438 if ( Array
.isArray( source
) ) {
439 // Array (fall through)
440 destination
= new Array( source
.length
);
441 } else if ( source
&& typeof source
.clone
=== 'function' ) {
442 // Duck type object with custom clone method
443 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
444 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
446 return leafCallback
?
447 leafCallback( source
.cloneNode( true ) ) :
448 source
.cloneNode( true );
449 } else if ( oo
.isPlainObject( source
) ) {
450 // Plain objects (fall through)
453 // Non-plain objects (incl. functions) and primitive values
454 return leafCallback
? leafCallback( source
) : source
;
457 // source is an array or a plain object
458 for ( key
in source
) {
459 destination
[ key
] = oo
.copy( source
[ key
], leafCallback
, nodeCallback
);
462 // This is an internal node, so we don't apply the leafCallback.
467 * Generate a hash of an object based on its name and data.
469 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
471 * To avoid two objects with the same values generating different hashes, we utilize the replacer
472 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
473 * not be the fastest way to do this; we should investigate this further.
475 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
476 * function, we call that function and use its return value rather than hashing the object
477 * ourselves. This allows classes to define custom hashing.
479 * @param {Object} val Object to generate hash for
480 * @return {string} Hash of object
482 oo
.getHash = function ( val
) {
483 return JSON
.stringify( val
, oo
.getHash
.keySortReplacer
);
487 * Sort objects by key (helper function for OO.getHash).
489 * This is a callback passed into JSON.stringify.
491 * @method getHash_keySortReplacer
492 * @param {string} key Property name of value being replaced
493 * @param {Mixed} val Property value to replace
494 * @return {Mixed} Replacement value
496 oo
.getHash
.keySortReplacer = function ( key
, val
) {
497 var normalized
, keys
, i
, len
;
498 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
499 // This object has its own custom hash function, use it
500 val
= val
.getHashObject();
502 if ( !Array
.isArray( val
) && Object( val
) === val
) {
503 // Only normalize objects when the key-order is ambiguous
504 // (e.g. any object not an array).
506 keys
= Object
.keys( val
).sort();
509 for ( ; i
< len
; i
+= 1 ) {
510 normalized
[ keys
[ i
] ] = val
[ keys
[ i
] ];
514 // Primitive values and arrays get stable hashes
515 // by default. Lets those be stringified as-is.
521 * Get the unique values of an array, removing duplicates
523 * @param {Array} arr Array
524 * @return {Array} Unique values in array
526 oo
.unique = function ( arr
) {
527 return arr
.reduce( function ( result
, current
) {
528 if ( result
.indexOf( current
) === -1 ) {
529 result
.push( current
);
536 * Compute the union (duplicate-free merge) of a set of arrays.
538 * Arrays values must be convertable to object keys (strings).
540 * By building an object (with the values for keys) in parallel with
541 * the array, a new item's existence in the union can be computed faster.
543 * @param {...Array} arrays Arrays to union
544 * @return {Array} Union of the arrays
546 oo
.simpleArrayUnion = function () {
547 var i
, ilen
, arr
, j
, jlen
,
551 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
552 arr
= arguments
[ i
];
553 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
554 if ( !obj
[ arr
[ j
] ] ) {
555 obj
[ arr
[ j
] ] = true;
556 result
.push( arr
[ j
] );
565 * Combine arrays (intersection or difference).
567 * An intersection checks the item exists in 'b' while difference checks it doesn't.
569 * Arrays values must be convertable to object keys (strings).
571 * By building an object (with the values for keys) of 'b' we can
572 * compute the result faster.
575 * @param {Array} a First array
576 * @param {Array} b Second array
577 * @param {boolean} includeB Whether to items in 'b'
578 * @return {Array} Combination (intersection or difference) of arrays
580 function simpleArrayCombine( a
, b
, includeB
) {
585 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
586 bObj
[ b
[ i
] ] = true;
589 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
590 isInB
= !!bObj
[ a
[ i
] ];
591 if ( isInB
=== includeB
) {
592 result
.push( a
[ i
] );
600 * Compute the intersection of two arrays (items in both arrays).
602 * Arrays values must be convertable to object keys (strings).
604 * @param {Array} a First array
605 * @param {Array} b Second array
606 * @return {Array} Intersection of arrays
608 oo
.simpleArrayIntersection = function ( a
, b
) {
609 return simpleArrayCombine( a
, b
, true );
613 * Compute the difference of two arrays (items in 'a' but not 'b').
615 * Arrays values must be convertable to object keys (strings).
617 * @param {Array} a First array
618 * @param {Array} b Second array
619 * @return {Array} Intersection of arrays
621 oo
.simpleArrayDifference = function ( a
, b
) {
622 return simpleArrayCombine( a
, b
, false );
627 oo
.isPlainObject
= $.isPlainObject
;
634 * @class OO.EventEmitter
638 oo
.EventEmitter
= function OoEventEmitter() {
642 * Storage of bound event handlers by event name.
649 oo
.initClass( oo
.EventEmitter
);
651 /* Private helper functions */
654 * Validate a function or method call in a context
656 * For a method name, check that it names a function in the context object
659 * @param {Function|string} method Function or method name
660 * @param {Mixed} context The context of the call
661 * @throws {Error} A method name is given but there is no context
662 * @throws {Error} In the context object, no property exists with the given name
663 * @throws {Error} In the context object, the named property is not a function
665 function validateMethod( method
, context
) {
666 // Validate method and context
667 if ( typeof method
=== 'string' ) {
669 if ( context
=== undefined || context
=== null ) {
670 throw new Error( 'Method name "' + method
+ '" has no context.' );
672 if ( typeof context
[ method
] !== 'function' ) {
673 // Technically the property could be replaced by a function before
674 // call time. But this probably signals a typo.
675 throw new Error( 'Property "' + method
+ '" is not a function' );
677 } else if ( typeof method
!== 'function' ) {
678 throw new Error( 'Invalid callback. Function or method name expected.' );
684 * @param {OO.EventEmitter} eventEmitter Event emitter
685 * @param {string} event Event name
686 * @param {Object} binding
688 function addBinding( eventEmitter
, event
, binding
) {
690 // Auto-initialize bindings list
691 if ( hasOwn
.call( eventEmitter
.bindings
, event
) ) {
692 bindings
= eventEmitter
.bindings
[ event
];
694 bindings
= eventEmitter
.bindings
[ event
] = [];
697 bindings
.push( binding
);
703 * Add a listener to events of a specific event.
705 * The listener can be a function or the string name of a method; if the latter, then the
706 * name lookup happens at the time the listener is called.
708 * @param {string} event Type of event to listen to
709 * @param {Function|string} method Function or method name to call when event occurs
710 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
711 * @param {Object} [context=null] Context object for function or method call
713 * @throws {Error} Listener argument is not a function or a valid method name
715 oo
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
716 validateMethod( method
, context
);
718 // Ensure consistent object shape (optimisation)
719 addBinding( this, event
, {
722 context
: ( arguments
.length
< 4 ) ? null : context
,
729 * Add a one-time listener to a specific event.
731 * @param {string} event Type of event to listen to
732 * @param {Function} listener Listener to call when event occurs
735 oo
.EventEmitter
.prototype.once = function ( event
, listener
) {
736 validateMethod( listener
);
738 // Ensure consistent object shape (optimisation)
739 addBinding( this, event
, {
749 * Remove a specific listener from a specific event.
751 * @param {string} event Type of event to remove listener from
752 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
753 * to "on". Omit to remove all listeners.
754 * @param {Object} [context=null] Context object function or method call
756 * @throws {Error} Listener argument is not a function or a valid method name
758 oo
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
761 if ( arguments
.length
=== 1 ) {
762 // Remove all bindings for event
763 delete this.bindings
[ event
];
767 validateMethod( method
, context
);
769 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[ event
].length
) {
770 // No matching bindings
774 // Default to null context
775 if ( arguments
.length
< 3 ) {
779 // Remove matching handlers
780 bindings
= this.bindings
[ event
];
783 if ( bindings
[ i
].method
=== method
&& bindings
[ i
].context
=== context
) {
784 bindings
.splice( i
, 1 );
788 // Cleanup if now empty
789 if ( bindings
.length
=== 0 ) {
790 delete this.bindings
[ event
];
798 * @param {string} event Type of event
799 * @param {...Mixed} args First in a list of variadic arguments passed to event handler (optional)
800 * @return {boolean} Whether the event was handled by at least one listener
802 oo
.EventEmitter
.prototype.emit = function ( event
) {
804 i
, len
, binding
, bindings
, method
;
806 if ( hasOwn
.call( this.bindings
, event
) ) {
807 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
808 bindings
= this.bindings
[ event
].slice();
809 for ( i
= 1, len
= arguments
.length
; i
< len
; i
++ ) {
810 args
.push( arguments
[ i
] );
812 for ( i
= 0, len
= bindings
.length
; i
< len
; i
++ ) {
813 binding
= bindings
[ i
];
814 if ( typeof binding
.method
=== 'string' ) {
815 // Lookup method by name (late binding)
816 method
= binding
.context
[ binding
.method
];
818 method
= binding
.method
;
820 if ( binding
.once
) {
821 // Must unbind before calling method to avoid
822 // any nested triggers.
823 this.off( event
, method
);
827 binding
.args
? binding
.args
.concat( args
) : args
836 * Connect event handlers to an object.
838 * @param {Object} context Object to call methods on when events occur
839 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
840 * event bindings keyed by event name containing either method names, functions or arrays containing
841 * method name or function followed by a list of arguments to be passed to callback before emitted
845 oo
.EventEmitter
.prototype.connect = function ( context
, methods
) {
846 var method
, args
, event
;
848 for ( event
in methods
) {
849 method
= methods
[ event
];
850 // Allow providing additional args
851 if ( Array
.isArray( method
) ) {
852 args
= method
.slice( 1 );
853 method
= method
[ 0 ];
858 this.on( event
, method
, args
, context
);
864 * Disconnect event handlers from an object.
866 * @param {Object} context Object to disconnect methods from
867 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
868 * event bindings keyed by event name. Values can be either method names, functions or arrays
869 * containing a method name.
870 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
871 * parameters as well, but only the method name is used to find bindings. Tt is discouraged to
872 * have multiple bindings for the same event to the same listener, but if used (and only the
873 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
874 * will disconnect other variations as well.
877 oo
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
878 var i
, event
, method
, bindings
;
881 // Remove specific connections to the context
882 for ( event
in methods
) {
883 method
= methods
[ event
];
884 if ( Array
.isArray( method
) ) {
885 method
= method
[ 0 ];
887 this.off( event
, method
, context
);
890 // Remove all connections to the context
891 for ( event
in this.bindings
) {
892 bindings
= this.bindings
[ event
];
895 // bindings[i] may have been removed by the previous step's
896 // this.off so check it still exists
897 if ( bindings
[ i
] && bindings
[ i
].context
=== context
) {
898 this.off( event
, bindings
[ i
].method
, context
);
912 * Contain and manage a list of OO.EventEmitter items.
914 * Aggregates and manages their events collectively.
916 * This mixin must be used in a class that also mixes in OO.EventEmitter.
919 * @class OO.EmitterList
922 oo
.EmitterList
= function OoEmitterList() {
924 this.aggregateItemEvents
= {};
930 * Item has been added
933 * @param {OO.EventEmitter} item Added item
934 * @param {number} index Index items were added at
938 * Item has been moved to a new index
941 * @param {OO.EventEmitter} item Moved item
942 * @param {number} index Index item was moved to
943 * @param {number} oldIndex The original index the item was in
947 * Item has been removed
950 * @param {OO.EventEmitter} item Removed item
951 * @param {number} index Index the item was removed from
955 * @event clear The list has been cleared of items
961 * Normalize requested index to fit into the bounds of the given array.
965 * @param {Array} arr Given array
966 * @param {number|undefined} index Requested index
967 * @return {number} Normalized index
969 function normalizeArrayIndex( arr
, index
) {
970 return ( index
=== undefined || index
< 0 || index
>= arr
.length
) ?
978 * @return {OO.EventEmitter[]} Items in the list
980 oo
.EmitterList
.prototype.getItems = function () {
981 return this.items
.slice( 0 );
985 * Get the index of a specific item.
987 * @param {OO.EventEmitter} item Requested item
988 * @return {number} Index of the item
990 oo
.EmitterList
.prototype.getItemIndex = function ( item
) {
991 return this.items
.indexOf( item
);
995 * Get number of items.
997 * @return {number} Number of items in the list
999 oo
.EmitterList
.prototype.getItemCount = function () {
1000 return this.items
.length
;
1004 * Check if a list contains no items.
1006 * @return {boolean} Group is empty
1008 oo
.EmitterList
.prototype.isEmpty = function () {
1009 return !this.items
.length
;
1013 * Aggregate the events emitted by the group.
1015 * When events are aggregated, the group will listen to all contained items for the event,
1016 * and then emit the event under a new name. The new event will contain an additional leading
1017 * parameter containing the item that emitted the original event. Other arguments emitted from
1018 * the original event are passed through.
1020 * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be
1021 * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’).
1022 * A `null` value will remove aggregated events.
1024 * @throws {Error} If aggregation already exists
1026 oo
.EmitterList
.prototype.aggregate = function ( events
) {
1027 var i
, item
, add
, remove
, itemEvent
, groupEvent
;
1029 for ( itemEvent
in events
) {
1030 groupEvent
= events
[ itemEvent
];
1032 // Remove existing aggregated event
1033 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
1034 // Don't allow duplicate aggregations
1036 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
1038 // Remove event aggregation from existing items
1039 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1040 item
= this.items
[ i
];
1041 if ( item
.connect
&& item
.disconnect
) {
1043 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
1044 item
.disconnect( this, remove
);
1047 // Prevent future items from aggregating event
1048 delete this.aggregateItemEvents
[ itemEvent
];
1051 // Add new aggregate event
1053 // Make future items aggregate event
1054 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
1055 // Add event aggregation to existing items
1056 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1057 item
= this.items
[ i
];
1058 if ( item
.connect
&& item
.disconnect
) {
1060 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
1061 item
.connect( this, add
);
1069 * Add items to the list.
1071 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1072 * an array of items to add
1073 * @param {number} [index] Index to add items at. If no index is
1074 * given, or if the index that is given is invalid, the item
1075 * will be added at the end of the list.
1080 oo
.EmitterList
.prototype.addItems = function ( items
, index
) {
1083 if ( !Array
.isArray( items
) ) {
1087 if ( items
.length
=== 0 ) {
1091 index
= normalizeArrayIndex( this.items
, index
);
1092 for ( i
= 0; i
< items
.length
; i
++ ) {
1093 oldIndex
= this.items
.indexOf( items
[ i
] );
1094 if ( oldIndex
!== -1 ) {
1095 // Move item to new index
1096 index
= this.moveItem( items
[ i
], index
);
1097 this.emit( 'move', items
[ i
], index
, oldIndex
);
1099 // insert item at index
1100 index
= this.insertItem( items
[ i
], index
);
1101 this.emit( 'add', items
[ i
], index
);
1110 * Move an item from its current position to a new index.
1112 * The item is expected to exist in the list. If it doesn't,
1113 * the method will throw an exception.
1116 * @param {OO.EventEmitter} item Items to add
1117 * @param {number} newIndex Index to move the item to
1118 * @return {number} The index the item was moved to
1119 * @throws {Error} If item is not in the list
1121 oo
.EmitterList
.prototype.moveItem = function ( item
, newIndex
) {
1122 var existingIndex
= this.items
.indexOf( item
);
1124 if ( existingIndex
=== -1 ) {
1125 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1128 newIndex
= normalizeArrayIndex( this.items
, newIndex
);
1130 // Remove the item from the current index
1131 this.items
.splice( existingIndex
, 1 );
1133 // If necessary, adjust new index after removal
1134 if ( existingIndex
< newIndex
) {
1138 // Move the item to the new index
1139 this.items
.splice( newIndex
, 0, item
);
1145 * Utility method to insert an item into the list, and
1146 * connect it to aggregate events.
1148 * Don't call this directly unless you know what you're doing.
1149 * Use #addItems instead.
1151 * This method can be extended in child classes to produce
1152 * different behavior when an item is inserted. For example,
1153 * inserted items may also be attached to the DOM or may
1154 * interact with some other nodes in certain ways. Extending
1155 * this method is allowed, but if overriden, the aggregation
1156 * of events must be preserved, or behavior of emitted events
1159 * If you are extending this method, please make sure the
1160 * parent method is called.
1163 * @param {OO.EventEmitter} item Items to add
1164 * @param {number} index Index to add items at
1165 * @return {number} The index the item was added at
1167 oo
.EmitterList
.prototype.insertItem = function ( item
, index
) {
1170 // Add the item to event aggregation
1171 if ( item
.connect
&& item
.disconnect
) {
1173 for ( event
in this.aggregateItemEvents
) {
1174 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
1176 item
.connect( this, events
);
1179 index
= normalizeArrayIndex( this.items
, index
);
1181 // Insert into items array
1182 this.items
.splice( index
, 0, item
);
1189 * @param {OO.EventEmitter[]} items Items to remove
1193 oo
.EmitterList
.prototype.removeItems = function ( items
) {
1196 if ( !Array
.isArray( items
) ) {
1200 if ( items
.length
=== 0 ) {
1204 // Remove specific items
1205 for ( i
= 0; i
< items
.length
; i
++ ) {
1207 index
= this.items
.indexOf( item
);
1208 if ( index
!== -1 ) {
1209 if ( item
.connect
&& item
.disconnect
) {
1210 // Disconnect all listeners from the item
1211 item
.disconnect( this );
1213 this.items
.splice( index
, 1 );
1214 this.emit( 'remove', item
, index
);
1227 oo
.EmitterList
.prototype.clearItems = function () {
1229 cleared
= this.items
.splice( 0, this.items
.length
);
1231 // Disconnect all items
1232 for ( i
= 0; i
< cleared
.length
; i
++ ) {
1233 item
= cleared
[ i
];
1234 if ( item
.connect
&& item
.disconnect
) {
1235 item
.disconnect( this );
1239 this.emit( 'clear' );
1247 * Manage a sorted list of OO.EmitterList objects.
1249 * The sort order is based on a callback that compares two items. The return value of
1250 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1251 * if a is equal to b. The callback should only return zero if the two objects are
1254 * When an item changes in a way that could affect their sorting behavior, it must
1255 * emit the itemSortChange event. This will cause it to be re-sorted automatically.
1257 * This mixin must be used in a class that also mixes in OO.EventEmitter.
1260 * @class OO.SortedEmitterList
1261 * @mixins OO.EmitterList
1263 * @param {Function} sortingCallback Callback that compares two items.
1265 oo
.SortedEmitterList
= function OoSortedEmitterList( sortingCallback
) {
1266 // Mixin constructors
1267 oo
.EmitterList
.call( this );
1269 this.sortingCallback
= sortingCallback
;
1271 // Listen to sortChange event and make sure
1272 // we re-sort the changed item when that happens
1274 sortChange
: 'itemSortChange'
1277 this.connect( this, {
1278 itemSortChange
: 'onItemSortChange'
1282 oo
.mixinClass( oo
.SortedEmitterList
, oo
.EmitterList
);
1287 * An item has changed properties that affect its sort positioning
1291 * @event itemSortChange
1297 * Handle a case where an item changed a property that relates
1298 * to its sorted order
1300 * @param {OO.EventEmitter} item Item in the list
1302 oo
.SortedEmitterList
.prototype.onItemSortChange = function ( item
) {
1304 this.removeItems( item
);
1305 // Re-add the item so it is in the correct place
1306 this.addItems( item
);
1310 * Change the sorting callback for this sorted list.
1312 * The callback receives two items. The return value of callback(a, b) must be less than zero
1313 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1315 * @param {Function} sortingCallback Sorting callback
1317 oo
.SortedEmitterList
.prototype.setSortingCallback = function ( sortingCallback
) {
1318 var items
= this.getItems();
1320 this.sortingCallback
= sortingCallback
;
1324 // Re-add the items in the new order
1325 this.addItems( items
);
1329 * Add items to the sorted list.
1331 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1332 * an array of items to add
1335 oo
.SortedEmitterList
.prototype.addItems = function ( items
) {
1336 var index
, i
, insertionIndex
;
1338 if ( !Array
.isArray( items
) ) {
1342 if ( items
.length
=== 0 ) {
1346 for ( i
= 0; i
< items
.length
; i
++ ) {
1347 // Find insertion index
1348 insertionIndex
= this.findInsertionIndex( items
[ i
] );
1350 // Check if the item exists using the sorting callback
1351 // and remove it first if it exists
1353 // First make sure the insertion index is not at the end
1354 // of the list (which means it does not point to any actual
1356 insertionIndex
<= this.items
.length
&&
1357 // Make sure there actually is an item in this index
1358 this.items
[ insertionIndex
] &&
1359 // The callback returns 0 if the items are equal
1360 this.sortingCallback( this.items
[ insertionIndex
], items
[ i
] ) === 0
1362 // Remove the existing item
1363 this.removeItems( this.items
[ insertionIndex
] );
1366 // Insert item at the insertion index
1367 index
= this.insertItem( items
[ i
], insertionIndex
);
1368 this.emit( 'add', items
[ i
], index
);
1375 * Find the index a given item should be inserted at. If the item is already
1376 * in the list, this will return the index where the item currently is.
1378 * @param {OO.EventEmitter} item Items to insert
1379 * @return {number} The index the item should be inserted at
1381 oo
.SortedEmitterList
.prototype.findInsertionIndex = function ( item
) {
1384 return oo
.binarySearch(
1386 // Fake a this.sortingCallback.bind( null, item ) call here
1387 // otherwise this doesn't pass tests in phantomJS
1388 function ( otherItem
) {
1389 return list
.sortingCallback( item
, otherItem
);
1399 * A map interface for associating arbitrary data with a symbolic name. Used in
1400 * place of a plain object to provide additional {@link #method-register registration}
1401 * or {@link #method-lookup lookup} functionality.
1403 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1405 * @class OO.Registry
1406 * @mixins OO.EventEmitter
1410 oo
.Registry
= function OoRegistry() {
1411 // Mixin constructors
1412 oo
.EventEmitter
.call( this );
1420 oo
.mixinClass( oo
.Registry
, oo
.EventEmitter
);
1426 * @param {string} name
1427 * @param {Mixed} data
1432 * @param {string} name
1433 * @param {Mixed} data Data removed from registry
1439 * Associate one or more symbolic names with some data.
1441 * Any existing entry with the same name will be overridden.
1443 * @param {string|string[]} name Symbolic name or list of symbolic names
1444 * @param {Mixed} data Data to associate with symbolic name
1446 * @throws {Error} Name argument must be a string or array
1448 oo
.Registry
.prototype.register = function ( name
, data
) {
1450 if ( typeof name
=== 'string' ) {
1451 this.registry
[ name
] = data
;
1452 this.emit( 'register', name
, data
);
1453 } else if ( Array
.isArray( name
) ) {
1454 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1455 this.register( name
[ i
], data
);
1458 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1463 * Remove one or more symbolic names from the registry
1465 * @param {string|string[]} name Symbolic name or list of symbolic names
1467 * @throws {Error} Name argument must be a string or array
1469 oo
.Registry
.prototype.unregister = function ( name
) {
1471 if ( typeof name
=== 'string' ) {
1472 data
= this.lookup( name
);
1473 if ( data
!== undefined ) {
1474 delete this.registry
[ name
];
1475 this.emit( 'unregister', name
, data
);
1477 } else if ( Array
.isArray( name
) ) {
1478 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1479 this.unregister( name
[ i
] );
1482 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1487 * Get data for a given symbolic name.
1489 * @param {string} name Symbolic name
1490 * @return {Mixed|undefined} Data associated with symbolic name
1492 oo
.Registry
.prototype.lookup = function ( name
) {
1493 if ( hasOwn
.call( this.registry
, name
) ) {
1494 return this.registry
[ name
];
1500 * @extends OO.Registry
1504 oo
.Factory
= function OoFactory() {
1505 // Parent constructor
1506 oo
.Factory
.super.call( this );
1511 oo
.inheritClass( oo
.Factory
, oo
.Registry
);
1516 * Register a constructor with the factory.
1518 * Classes must have a static `name` property to be registered.
1520 * function MyClass() {};
1521 * OO.initClass( MyClass );
1522 * // Adds a static property to the class defining a symbolic name
1523 * MyClass.static.name = 'mine';
1524 * // Registers class with factory, available via symbolic name 'mine'
1525 * factory.register( MyClass );
1527 * @param {Function} constructor Constructor to use when creating object
1528 * @throws {Error} Name must be a string and must not be empty
1529 * @throws {Error} Constructor must be a function
1531 oo
.Factory
.prototype.register = function ( constructor ) {
1534 if ( typeof constructor !== 'function' ) {
1535 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1537 name
= constructor.static && constructor.static.name
;
1538 if ( typeof name
!== 'string' || name
=== '' ) {
1539 throw new Error( 'Name must be a string and must not be empty' );
1543 oo
.Factory
.super.prototype.register
.call( this, name
, constructor );
1547 * Unregister a constructor from the factory.
1549 * @param {Function} constructor Constructor to unregister
1550 * @throws {Error} Name must be a string and must not be empty
1551 * @throws {Error} Constructor must be a function
1553 oo
.Factory
.prototype.unregister = function ( constructor ) {
1556 if ( typeof constructor !== 'function' ) {
1557 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
1559 name
= constructor.static && constructor.static.name
;
1560 if ( typeof name
!== 'string' || name
=== '' ) {
1561 throw new Error( 'Name must be a string and must not be empty' );
1565 oo
.Factory
.super.prototype.unregister
.call( this, name
);
1569 * Create an object based on a name.
1571 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1572 * constructor directly, so leaving one out will pass an undefined to the constructor.
1574 * @param {string} name Object name
1575 * @param {...Mixed} [args] Arguments to pass to the constructor
1576 * @return {Object} The new object
1577 * @throws {Error} Unknown object name
1579 oo
.Factory
.prototype.create = function ( name
) {
1582 constructor = this.lookup( name
);
1584 if ( !constructor ) {
1585 throw new Error( 'No class registered by that name: ' + name
);
1588 // Convert arguments to array and shift the first argument (name) off
1589 for ( i
= 1; i
< arguments
.length
; i
++ ) {
1590 args
.push( arguments
[ i
] );
1593 // We can't use the "new" operator with .apply directly because apply needs a
1594 // context. So instead just do what "new" does: create an object that inherits from
1595 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1596 // then invoke the constructor with the object as context, and return it (ignoring
1597 // the constructor's return value).
1598 obj
= Object
.create( constructor.prototype );
1599 constructor.apply( obj
, args
);
1603 /* eslint-env node */
1605 /* istanbul ignore next */
1606 if ( typeof module
!== 'undefined' && module
.exports
) {
1607 module
.exports
= oo
;