2 * OOjs v3.0.0 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2019 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
9 * Date: 2019-08-28T15:41:06Z
11 ( function ( global
) {
15 /* exported slice, toString */
17 * Namespace for all classes, static methods and static properties.
22 // Optimisation: Local reference to methods from a global prototype
23 hasOwn
= OO
.hasOwnProperty
,
24 slice
= Array
.prototype.slice
,
25 toString
= OO
.toString
;
30 * Utility to initialize a class for OO inheritance.
32 * Currently this just initializes an empty static object.
36 * @param {Function} fn
38 OO
.initClass = function ( fn
) {
39 fn
.static = fn
.static || {};
43 * Inherit from prototype to another using Object#create.
45 * Beware: This redefines the prototype, call before setting your prototypes.
47 * Beware: This redefines the prototype, can only be called once on a function.
48 * If called multiple times on the same function, the previous prototype is lost.
49 * This is how prototypal inheritance works, it can only be one straight chain
50 * (just like classical inheritance in PHP for example). If you need to work with
51 * multiple constructors consider storing an instance of the other constructor in a
52 * property instead, or perhaps use a mixin (see OO.mixinClass).
55 * Thing.prototype.exists = function () {};
58 * Person.super.apply( this, arguments );
60 * OO.inheritClass( Person, Thing );
61 * Person.static.defaultEyeCount = 2;
62 * Person.prototype.walk = function () {};
65 * Jumper.super.apply( this, arguments );
67 * OO.inheritClass( Jumper, Person );
68 * Jumper.prototype.jump = function () {};
70 * Jumper.static.defaultEyeCount === 2;
71 * var x = new Jumper();
74 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
77 * @method inheritClass
78 * @param {Function} targetFn
79 * @param {Function} originFn
80 * @throws {Error} If target already inherits from origin
82 OO
.inheritClass = function ( targetFn
, originFn
) {
83 var targetConstructor
;
86 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn
+ ')' );
88 if ( targetFn
.prototype instanceof originFn
) {
89 throw new Error( 'inheritClass: Target already inherits from origin' );
92 targetConstructor
= targetFn
.prototype.constructor;
94 // [DEPRECATED] Provide .parent as alias for code supporting older browsers which
95 // allows people to comply with their style guide.
96 targetFn
.super = targetFn
.parent
= originFn
;
98 targetFn
.prototype = Object
.create( originFn
.prototype, {
99 // Restore constructor property of targetFn
101 value
: targetConstructor
,
108 // Extend static properties - always initialize both sides
109 OO
.initClass( originFn
);
110 targetFn
.static = Object
.create( originFn
.static );
114 * Copy over *own* prototype properties of a mixin.
116 * The 'constructor' (whether implicit or explicit) is not copied over.
118 * This does not create inheritance to the origin. If you need inheritance,
119 * use OO.inheritClass instead.
121 * Beware: This can redefine a prototype property, call before setting your prototypes.
123 * Beware: Don't call before OO.inheritClass.
126 * function Context() {}
128 * // Avoid repeating this code
129 * function ContextLazyLoad() {}
130 * ContextLazyLoad.prototype.getContext = function () {
131 * if ( !this.context ) {
132 * this.context = new Context();
134 * return this.context;
137 * function FooBar() {}
138 * OO.inheritClass( FooBar, Foo );
139 * OO.mixinClass( FooBar, ContextLazyLoad );
143 * @param {Function} targetFn
144 * @param {Function} originFn
146 OO
.mixinClass = function ( targetFn
, originFn
) {
150 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn
+ ')' );
153 // Copy prototype properties
154 for ( key
in originFn
.prototype ) {
155 if ( key
!== 'constructor' && hasOwn
.call( originFn
.prototype, key
) ) {
156 targetFn
.prototype[ key
] = originFn
.prototype[ key
];
160 // Copy static properties - always initialize both sides
161 OO
.initClass( targetFn
);
162 if ( originFn
.static ) {
163 for ( key
in originFn
.static ) {
164 if ( hasOwn
.call( originFn
.static, key
) ) {
165 targetFn
.static[ key
] = originFn
.static[ key
];
169 OO
.initClass( originFn
);
174 * Test whether one class is a subclass of another, without instantiating it.
176 * Every class is considered a subclass of Object and of itself.
180 * @param {Function} testFn The class to be tested
181 * @param {Function} baseFn The base class
182 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
184 OO
.isSubclass = function ( testFn
, baseFn
) {
185 return testFn
=== baseFn
|| testFn
.prototype instanceof baseFn
;
191 * Get a deeply nested property of an object using variadic arguments, protecting against
192 * undefined property errors.
194 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
195 * except that the former protects against JS errors if one of the intermediate properties
196 * is undefined. Instead of throwing an error, this function will return undefined in
201 * @param {Object} obj
202 * @param {...any} [keys]
203 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
205 OO
.getProp = function ( obj
) {
208 for ( i
= 1; i
< arguments
.length
; i
++ ) {
209 if ( retval
=== undefined || retval
=== null ) {
210 // Trying to access a property of undefined or null causes an error
213 retval
= retval
[ arguments
[ i
] ];
219 * Set a deeply nested property of an object using variadic arguments, protecting against
220 * undefined property errors.
222 * `OO.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
223 * the former protects against JS errors if one of the intermediate properties is
224 * undefined. Instead of throwing an error, undefined intermediate properties will be
225 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
226 * is not an object, this function will silently abort.
230 * @param {Object} obj
231 * @param {...any} [keys]
232 * @param {any} [value]
234 OO
.setProp = function ( obj
) {
237 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
240 for ( i
= 1; i
< arguments
.length
- 2; i
++ ) {
241 if ( prop
[ arguments
[ i
] ] === undefined ) {
242 prop
[ arguments
[ i
] ] = {};
244 if ( Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ] ) {
247 prop
= prop
[ arguments
[ i
] ];
249 prop
[ arguments
[ arguments
.length
- 2 ] ] = arguments
[ arguments
.length
- 1 ];
253 * Delete a deeply nested property of an object using variadic arguments, protecting against
254 * undefined property errors, and deleting resulting empty objects.
258 * @param {Object} obj
259 * @param {...any} [keys]
261 OO
.deleteProp = function ( obj
) {
265 if ( Object( obj
) !== obj
|| arguments
.length
< 2 ) {
268 for ( i
= 1; i
< arguments
.length
- 1; i
++ ) {
270 prop
[ arguments
[ i
] ] === undefined ||
271 Object( prop
[ arguments
[ i
] ] ) !== prop
[ arguments
[ i
] ]
275 prop
= prop
[ arguments
[ i
] ];
278 delete prop
[ arguments
[ i
] ];
279 // Walk back through props removing any plain empty objects
282 ( prop
= props
.pop() ) &&
283 OO
.isPlainObject( prop
) && !Object
.keys( prop
).length
285 delete props
[ props
.length
- 1 ][ arguments
[ props
.length
] ];
290 * Create a new object that is an instance of the same
291 * constructor as the input, inherits from the same object
292 * and contains the same own properties.
294 * This makes a shallow non-recursive copy of own properties.
295 * To create a recursive copy of plain objects, use #copy.
297 * var foo = new Person( mom, dad );
299 * var foo2 = OO.cloneObject( foo );
303 * foo2 !== foo; // true
304 * foo2 instanceof Person; // true
305 * foo2.getAge(); // 21
306 * foo.getAge(); // 22
309 * @method cloneObject
310 * @param {Object} origin
311 * @return {Object} Clone of origin
313 OO
.cloneObject = function ( origin
) {
316 r
= Object
.create( origin
.constructor.prototype );
318 for ( key
in origin
) {
319 if ( hasOwn
.call( origin
, key
) ) {
320 r
[ key
] = origin
[ key
];
328 * Get an array of all property values in an object.
331 * @method getObjectValues
332 * @param {Object} obj Object to get values from
333 * @return {Array} List of object values
335 OO
.getObjectValues = function ( obj
) {
338 if ( obj
!== Object( obj
) ) {
339 throw new TypeError( 'Called on non-object' );
344 if ( hasOwn
.call( obj
, key
) ) {
345 values
[ values
.length
] = obj
[ key
];
353 * Use binary search to locate an element in a sorted array.
355 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
356 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
357 * below 0 if it is to the left of elem, or zero if it's equal to elem.
359 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
360 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
361 * `searchFunc = cmp.bind( null, value )`.
364 * @method binarySearch
365 * @param {Array} arr Array to search in
366 * @param {Function} searchFunc Search function
367 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
368 * @return {number|null} Index where val was found, or null if not found
370 OO
.binarySearch = function ( arr
, searchFunc
, forInsertion
) {
374 while ( left
< right
) {
375 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
376 // eslint-disable-next-line no-bitwise
377 mid
= ( left
+ right
) >> 1;
378 cmpResult
= searchFunc( arr
[ mid
] );
379 if ( cmpResult
< 0 ) {
381 } else if ( cmpResult
> 0 ) {
387 return forInsertion
? right
: null;
391 * Recursively compare properties between two objects.
393 * A false result may be caused by property inequality or by properties in one object missing from
394 * the other. An asymmetrical test may also be performed, which checks only that properties in the
395 * first object are present in the second object, but not the inverse.
397 * If either a or b is null or undefined it will be treated as an empty object.
401 * @param {Object|undefined|null} a First object to compare
402 * @param {Object|undefined|null} b Second object to compare
403 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
404 * (i.e. a is a subset of b)
405 * @return {boolean} If the objects contain the same values as each other
407 OO
.compare = function ( a
, b
, asymmetrical
) {
408 var aValue
, bValue
, aType
, bType
, k
;
417 if ( typeof a
.nodeType
=== 'number' && typeof a
.isEqualNode
=== 'function' ) {
418 return a
.isEqualNode( b
);
422 if ( !hasOwn
.call( a
, k
) || a
[ k
] === undefined || a
[ k
] === b
[ k
] ) {
423 // Ignore undefined values, because there is no conceptual difference between
424 // a key that is absent and a key that is present but whose value is undefined.
430 aType
= typeof aValue
;
431 bType
= typeof bValue
;
432 if ( aType
!== bType
||
434 ( aType
=== 'string' || aType
=== 'number' || aType
=== 'boolean' ) &&
437 ( aValue
=== Object( aValue
) && !OO
.compare( aValue
, bValue
, true ) ) ) {
441 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
442 return asymmetrical
? true : OO
.compare( b
, a
, true );
446 * Create a plain deep copy of any kind of object.
448 * Copies are deep, and will either be an object or an array depending on `source`.
452 * @param {Object} source Object to copy
453 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are
455 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the
456 * nodeCallback returns a value other than undefined, the returned value is used instead of
457 * attempting to clone.
458 * @return {Object} Copy of source object
460 OO
.copy = function ( source
, leafCallback
, nodeCallback
) {
461 var key
, destination
;
463 if ( nodeCallback
) {
464 // Extensibility: check before attempting to clone source.
465 destination
= nodeCallback( source
);
466 if ( destination
!== undefined ) {
471 if ( Array
.isArray( source
) ) {
472 // Array (fall through)
473 destination
= new Array( source
.length
);
474 } else if ( source
&& typeof source
.clone
=== 'function' ) {
475 // Duck type object with custom clone method
476 return leafCallback
? leafCallback( source
.clone() ) : source
.clone();
477 } else if ( source
&& typeof source
.cloneNode
=== 'function' ) {
479 return leafCallback
?
480 leafCallback( source
.cloneNode( true ) ) :
481 source
.cloneNode( true );
482 } else if ( OO
.isPlainObject( source
) ) {
483 // Plain objects (fall through)
486 // Non-plain objects (incl. functions) and primitive values
487 return leafCallback
? leafCallback( source
) : source
;
490 // source is an array or a plain object
491 for ( key
in source
) {
492 destination
[ key
] = OO
.copy( source
[ key
], leafCallback
, nodeCallback
);
495 // This is an internal node, so we don't apply the leafCallback.
500 * Generate a hash of an object based on its name and data.
502 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
504 * To avoid two objects with the same values generating different hashes, we utilize the replacer
505 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
506 * not be the fastest way to do this; we should investigate this further.
508 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
509 * function, we call that function and use its return value rather than hashing the object
510 * ourselves. This allows classes to define custom hashing.
514 * @param {Object} val Object to generate hash for
515 * @return {string} Hash of object
517 OO
.getHash = function ( val
) {
518 return JSON
.stringify( val
, OO
.getHash
.keySortReplacer
);
522 * Sort objects by key (helper function for OO.getHash).
524 * This is a callback passed into JSON.stringify.
527 * @method getHash_keySortReplacer
528 * @param {string} key Property name of value being replaced
529 * @param {any} val Property value to replace
530 * @return {any} Replacement value
532 OO
.getHash
.keySortReplacer = function ( key
, val
) {
533 var normalized
, keys
, i
, len
;
534 if ( val
&& typeof val
.getHashObject
=== 'function' ) {
535 // This object has its own custom hash function, use it
536 val
= val
.getHashObject();
538 if ( !Array
.isArray( val
) && Object( val
) === val
) {
539 // Only normalize objects when the key-order is ambiguous
540 // (e.g. any object not an array).
542 keys
= Object
.keys( val
).sort();
545 for ( ; i
< len
; i
+= 1 ) {
546 normalized
[ keys
[ i
] ] = val
[ keys
[ i
] ];
550 // Primitive values and arrays get stable hashes
551 // by default. Lets those be stringified as-is.
557 * Get the unique values of an array, removing duplicates.
561 * @param {Array} arr Array
562 * @return {Array} Unique values in array
564 OO
.unique = function ( arr
) {
565 return arr
.reduce( function ( result
, current
) {
566 if ( result
.indexOf( current
) === -1 ) {
567 result
.push( current
);
574 * Compute the union (duplicate-free merge) of a set of arrays.
576 * Arrays values must be convertable to object keys (strings).
578 * By building an object (with the values for keys) in parallel with
579 * the array, a new item's existence in the union can be computed faster.
582 * @method simpleArrayUnion
583 * @param {...Array} arrays Arrays to union
584 * @return {Array} Union of the arrays
586 OO
.simpleArrayUnion = function () {
587 var i
, ilen
, arr
, j
, jlen
,
591 for ( i
= 0, ilen
= arguments
.length
; i
< ilen
; i
++ ) {
592 arr
= arguments
[ i
];
593 for ( j
= 0, jlen
= arr
.length
; j
< jlen
; j
++ ) {
594 if ( !obj
[ arr
[ j
] ] ) {
595 obj
[ arr
[ j
] ] = true;
596 result
.push( arr
[ j
] );
605 * Combine arrays (intersection or difference).
607 * An intersection checks the item exists in 'b' while difference checks it doesn't.
609 * Arrays values must be convertable to object keys (strings).
611 * By building an object (with the values for keys) of 'b' we can
612 * compute the result faster.
615 * @param {Array} a First array
616 * @param {Array} b Second array
617 * @param {boolean} includeB Whether to items in 'b'
618 * @return {Array} Combination (intersection or difference) of arrays
620 function simpleArrayCombine( a
, b
, includeB
) {
625 for ( i
= 0, ilen
= b
.length
; i
< ilen
; i
++ ) {
626 bObj
[ b
[ i
] ] = true;
629 for ( i
= 0, ilen
= a
.length
; i
< ilen
; i
++ ) {
630 isInB
= !!bObj
[ a
[ i
] ];
631 if ( isInB
=== includeB
) {
632 result
.push( a
[ i
] );
640 * Compute the intersection of two arrays (items in both arrays).
642 * Arrays values must be convertable to object keys (strings).
645 * @method simpleArrayIntersection
646 * @param {Array} a First array
647 * @param {Array} b Second array
648 * @return {Array} Intersection of arrays
650 OO
.simpleArrayIntersection = function ( a
, b
) {
651 return simpleArrayCombine( a
, b
, true );
655 * Compute the difference of two arrays (items in 'a' but not 'b').
657 * Arrays values must be convertable to object keys (strings).
660 * @method simpleArrayDifference
661 * @param {Array} a First array
662 * @param {Array} b Second array
663 * @return {Array} Intersection of arrays
665 OO
.simpleArrayDifference = function ( a
, b
) {
666 return simpleArrayCombine( a
, b
, false );
669 OO
.isPlainObject
= $.isPlainObject
;
671 /* global hasOwn, slice */
678 OO
.EventEmitter
= function OoEventEmitter() {
682 * Storage of bound event handlers by event name.
685 * @property {Object} bindings
690 OO
.initClass( OO
.EventEmitter
);
692 /* Private helper functions */
695 * Validate a function or method call in a context
697 * For a method name, check that it names a function in the context object
700 * @param {Function|string} method Function or method name
701 * @param {any} context The context of the call
702 * @throws {Error} A method name is given but there is no context
703 * @throws {Error} In the context object, no property exists with the given name
704 * @throws {Error} In the context object, the named property is not a function
706 function validateMethod( method
, context
) {
707 // Validate method and context
708 if ( typeof method
=== 'string' ) {
710 if ( context
=== undefined || context
=== null ) {
711 throw new Error( 'Method name "' + method
+ '" has no context.' );
713 if ( typeof context
[ method
] !== 'function' ) {
714 // Technically the property could be replaced by a function before
715 // call time. But this probably signals a typo.
716 throw new Error( 'Property "' + method
+ '" is not a function' );
718 } else if ( typeof method
!== 'function' ) {
719 throw new Error( 'Invalid callback. Function or method name expected.' );
725 * @param {OO.EventEmitter} eventEmitter Event emitter
726 * @param {string} event Event name
727 * @param {Object} binding
729 function addBinding( eventEmitter
, event
, binding
) {
731 // Auto-initialize bindings list
732 if ( hasOwn
.call( eventEmitter
.bindings
, event
) ) {
733 bindings
= eventEmitter
.bindings
[ event
];
735 bindings
= eventEmitter
.bindings
[ event
] = [];
738 bindings
.push( binding
);
744 * Add a listener to events of a specific event.
746 * The listener can be a function or the string name of a method; if the latter, then the
747 * name lookup happens at the time the listener is called.
749 * @param {string} event Type of event to listen to
750 * @param {Function|string} method Function or method name to call when event occurs
751 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
752 * @param {Object} [context=null] Context object for function or method call
753 * @return {OO.EventEmitter}
754 * @throws {Error} Listener argument is not a function or a valid method name
756 OO
.EventEmitter
.prototype.on = function ( event
, method
, args
, context
) {
757 validateMethod( method
, context
);
759 // Ensure consistent object shape (optimisation)
760 addBinding( this, event
, {
763 context
: ( arguments
.length
< 4 ) ? null : context
,
770 * Add a one-time listener to a specific event.
772 * @param {string} event Type of event to listen to
773 * @param {Function} listener Listener to call when event occurs
774 * @return {OO.EventEmitter}
776 OO
.EventEmitter
.prototype.once = function ( event
, listener
) {
777 validateMethod( listener
);
779 // Ensure consistent object shape (optimisation)
780 addBinding( this, event
, {
790 * Remove a specific listener from a specific event.
792 * @param {string} event Type of event to remove listener from
793 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
794 * to "on". Omit to remove all listeners.
795 * @param {Object} [context=null] Context object function or method call
796 * @return {OO.EventEmitter}
797 * @throws {Error} Listener argument is not a function or a valid method name
799 OO
.EventEmitter
.prototype.off = function ( event
, method
, context
) {
802 if ( arguments
.length
=== 1 ) {
803 // Remove all bindings for event
804 delete this.bindings
[ event
];
808 validateMethod( method
, context
);
810 if ( !hasOwn
.call( this.bindings
, event
) || !this.bindings
[ event
].length
) {
811 // No matching bindings
815 // Default to null context
816 if ( arguments
.length
< 3 ) {
820 // Remove matching handlers
821 bindings
= this.bindings
[ event
];
824 if ( bindings
[ i
].method
=== method
&& bindings
[ i
].context
=== context
) {
825 bindings
.splice( i
, 1 );
829 // Cleanup if now empty
830 if ( bindings
.length
=== 0 ) {
831 delete this.bindings
[ event
];
839 * All listeners for the event will be called synchronously, in an
840 * unspecified order. If any listeners throw an exception, this won't
841 * disrupt the calls to the remaining listeners; however, the exception
842 * won't be thrown until the next tick.
844 * Listeners should avoid mutating the emitting object, as this is
845 * something of an anti-pattern which can easily result in
846 * hard-to-understand code with hidden side-effects and dependencies.
848 * @param {string} event Type of event
849 * @param {...any} args First in a list of variadic arguments
850 * passed to event handler (optional)
851 * @return {boolean} Whether the event was handled by at least one listener
853 OO
.EventEmitter
.prototype.emit = function ( event
) {
854 var bindings
, args
, i
, binding
, method
;
856 if ( !hasOwn
.call( this.bindings
, event
) ) {
860 // Slicing ensures that we don't get tripped up by event
861 // handlers that add/remove bindings
862 bindings
= this.bindings
[ event
].slice();
863 args
= slice
.call( arguments
, 1 );
864 for ( i
= 0; i
< bindings
.length
; i
++ ) {
865 binding
= bindings
[ i
];
866 if ( typeof binding
.method
=== 'string' ) {
867 // Lookup method by name (late binding)
868 method
= binding
.context
[ binding
.method
];
870 method
= binding
.method
;
872 if ( binding
.once
) {
873 // Unbind before calling, to avoid any nested triggers.
874 this.off( event
, method
);
879 binding
.args
? binding
.args
.concat( args
) : args
882 // If one listener has an unhandled error, don't have it
883 // take down the emitter. But rethrow asynchronously so
884 // debuggers can break with a full async stack trace.
885 setTimeout( ( function ( error
) {
887 } ).bind( null, e
) );
895 * Emit an event, propagating the first exception some listener throws
897 * All listeners for the event will be called synchronously, in an
898 * unspecified order. If any listener throws an exception, this won't
899 * disrupt the calls to the remaining listeners. The first exception
900 * thrown will be propagated back to the caller; any others won't be
901 * thrown until the next tick.
903 * Listeners should avoid mutating the emitting object, as this is
904 * something of an anti-pattern which can easily result in
905 * hard-to-understand code with hidden side-effects and dependencies.
907 * @param {string} event Type of event
908 * @param {...any} args First in a list of variadic arguments
909 * passed to event handler (optional)
910 * @return {boolean} Whether the event was handled by at least one listener
912 OO
.EventEmitter
.prototype.emitThrow = function ( event
) {
913 // We tolerate code duplication with #emit, because the
914 // alternative is an extra level of indirection which will
915 // appear in very many stack traces.
916 var bindings
, args
, i
, binding
, method
, firstError
;
918 if ( !hasOwn
.call( this.bindings
, event
) ) {
922 // Slicing ensures that we don't get tripped up by event
923 // handlers that add/remove bindings
924 bindings
= this.bindings
[ event
].slice();
925 args
= slice
.call( arguments
, 1 );
926 for ( i
= 0; i
< bindings
.length
; i
++ ) {
927 binding
= bindings
[ i
];
928 if ( typeof binding
.method
=== 'string' ) {
929 // Lookup method by name (late binding)
930 method
= binding
.context
[ binding
.method
];
932 method
= binding
.method
;
934 if ( binding
.once
) {
935 // Unbind before calling, to avoid any nested triggers.
936 this.off( event
, method
);
941 binding
.args
? binding
.args
.concat( args
) : args
944 if ( firstError
=== undefined ) {
947 // If one listener has an unhandled error, don't have it
948 // take down the emitter. But rethrow asynchronously so
949 // debuggers can break with a full async stack trace.
950 setTimeout( ( function ( error
) {
952 } ).bind( null, e
) );
957 if ( firstError
!== undefined ) {
964 * Connect event handlers to an object.
966 * @param {Object} context Object to call methods on when events occur
967 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods
968 * List of event bindings keyed by event name containing either method names, functions or
969 * arrays containing method name or function followed by a list of arguments to be passed to
970 * callback before emitted arguments.
971 * @return {OO.EventEmitter}
973 OO
.EventEmitter
.prototype.connect = function ( context
, methods
) {
974 var method
, args
, event
;
976 for ( event
in methods
) {
977 method
= methods
[ event
];
978 // Allow providing additional args
979 if ( Array
.isArray( method
) ) {
980 args
= method
.slice( 1 );
981 method
= method
[ 0 ];
986 this.on( event
, method
, args
, context
);
992 * Disconnect event handlers from an object.
994 * @param {Object} context Object to disconnect methods from
995 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods]
996 * List of event bindings keyed by event name. Values can be either method names, functions or
997 * arrays containing a method name.
998 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
999 * parameters as well, but only the method name is used to find bindings. Tt is discouraged to
1000 * have multiple bindings for the same event to the same listener, but if used (and only the
1001 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
1002 * will disconnect other variations as well.
1003 * @return {OO.EventEmitter}
1005 OO
.EventEmitter
.prototype.disconnect = function ( context
, methods
) {
1006 var i
, event
, method
, bindings
;
1009 // Remove specific connections to the context
1010 for ( event
in methods
) {
1011 method
= methods
[ event
];
1012 if ( Array
.isArray( method
) ) {
1013 method
= method
[ 0 ];
1015 this.off( event
, method
, context
);
1018 // Remove all connections to the context
1019 for ( event
in this.bindings
) {
1020 bindings
= this.bindings
[ event
];
1021 i
= bindings
.length
;
1023 // bindings[i] may have been removed by the previous step's
1024 // this.off so check it still exists
1025 if ( bindings
[ i
] && bindings
[ i
].context
=== context
) {
1026 this.off( event
, bindings
[ i
].method
, context
);
1040 * Contain and manage a list of @{link OO.EventEmitter} items.
1042 * Aggregates and manages their events collectively.
1044 * This mixin must be used in a class that also mixes in @{link OO.EventEmitter}.
1049 OO
.EmitterList
= function OoEmitterList() {
1051 this.aggregateItemEvents
= {};
1057 * Item has been added.
1059 * @event OO.EmitterList#add
1060 * @param {OO.EventEmitter} item Added item
1061 * @param {number} index Index items were added at
1065 * Item has been moved to a new index.
1067 * @event OO.EmitterList#move
1068 * @param {OO.EventEmitter} item Moved item
1069 * @param {number} index Index item was moved to
1070 * @param {number} oldIndex The original index the item was in
1074 * Item has been removed.
1076 * @event OO.EmitterList#remove
1077 * @param {OO.EventEmitter} item Removed item
1078 * @param {number} index Index the item was removed from
1082 * The list has been cleared of items.
1084 * @event OO.EmitterList#clear
1090 * Normalize requested index to fit into the bounds of the given array.
1094 * @param {Array} arr Given array
1095 * @param {number|undefined} index Requested index
1096 * @return {number} Normalized index
1098 function normalizeArrayIndex( arr
, index
) {
1099 return ( index
=== undefined || index
< 0 || index
>= arr
.length
) ?
1107 * @return {OO.EventEmitter[]} Items in the list
1109 OO
.EmitterList
.prototype.getItems = function () {
1110 return this.items
.slice( 0 );
1114 * Get the index of a specific item.
1116 * @param {OO.EventEmitter} item Requested item
1117 * @return {number} Index of the item
1119 OO
.EmitterList
.prototype.getItemIndex = function ( item
) {
1120 return this.items
.indexOf( item
);
1124 * Get number of items.
1126 * @return {number} Number of items in the list
1128 OO
.EmitterList
.prototype.getItemCount = function () {
1129 return this.items
.length
;
1133 * Check if a list contains no items.
1135 * @return {boolean} Group is empty
1137 OO
.EmitterList
.prototype.isEmpty = function () {
1138 return !this.items
.length
;
1142 * Aggregate the events emitted by the group.
1144 * When events are aggregated, the group will listen to all contained items for the event,
1145 * and then emit the event under a new name. The new event will contain an additional leading
1146 * parameter containing the item that emitted the original event. Other arguments emitted from
1147 * the original event are passed through.
1149 * @param {Object.<string,string|null>} events An object keyed by the name of the event that
1150 * should be aggregated (e.g., ‘click’) and the value of the new name to use
1151 * (e.g., ‘groupClick’). A `null` value will remove aggregated events.
1152 * @throws {Error} If aggregation already exists
1154 OO
.EmitterList
.prototype.aggregate = function ( events
) {
1155 var i
, item
, add
, remove
, itemEvent
, groupEvent
;
1157 for ( itemEvent
in events
) {
1158 groupEvent
= events
[ itemEvent
];
1160 // Remove existing aggregated event
1161 if ( Object
.prototype.hasOwnProperty
.call( this.aggregateItemEvents
, itemEvent
) ) {
1162 // Don't allow duplicate aggregations
1164 throw new Error( 'Duplicate item event aggregation for ' + itemEvent
);
1166 // Remove event aggregation from existing items
1167 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1168 item
= this.items
[ i
];
1169 if ( item
.connect
&& item
.disconnect
) {
1171 remove
[ itemEvent
] = [ 'emit', this.aggregateItemEvents
[ itemEvent
], item
];
1172 item
.disconnect( this, remove
);
1175 // Prevent future items from aggregating event
1176 delete this.aggregateItemEvents
[ itemEvent
];
1179 // Add new aggregate event
1181 // Make future items aggregate event
1182 this.aggregateItemEvents
[ itemEvent
] = groupEvent
;
1183 // Add event aggregation to existing items
1184 for ( i
= 0; i
< this.items
.length
; i
++ ) {
1185 item
= this.items
[ i
];
1186 if ( item
.connect
&& item
.disconnect
) {
1188 add
[ itemEvent
] = [ 'emit', groupEvent
, item
];
1189 item
.connect( this, add
);
1197 * Add items to the list.
1199 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1200 * an array of items to add
1201 * @param {number} [index] Index to add items at. If no index is
1202 * given, or if the index that is given is invalid, the item
1203 * will be added at the end of the list.
1204 * @return {OO.EmitterList}
1205 * @fires OO.EmitterList#add
1206 * @fires OO.EmitterList#move
1208 OO
.EmitterList
.prototype.addItems = function ( items
, index
) {
1211 if ( !Array
.isArray( items
) ) {
1215 if ( items
.length
=== 0 ) {
1219 index
= normalizeArrayIndex( this.items
, index
);
1220 for ( i
= 0; i
< items
.length
; i
++ ) {
1221 oldIndex
= this.items
.indexOf( items
[ i
] );
1222 if ( oldIndex
!== -1 ) {
1223 // Move item to new index
1224 index
= this.moveItem( items
[ i
], index
);
1225 this.emit( 'move', items
[ i
], index
, oldIndex
);
1227 // insert item at index
1228 index
= this.insertItem( items
[ i
], index
);
1229 this.emit( 'add', items
[ i
], index
);
1238 * Move an item from its current position to a new index.
1240 * The item is expected to exist in the list. If it doesn't,
1241 * the method will throw an exception.
1244 * @param {OO.EventEmitter} item Items to add
1245 * @param {number} newIndex Index to move the item to
1246 * @return {number} The index the item was moved to
1247 * @throws {Error} If item is not in the list
1249 OO
.EmitterList
.prototype.moveItem = function ( item
, newIndex
) {
1250 var existingIndex
= this.items
.indexOf( item
);
1252 if ( existingIndex
=== -1 ) {
1253 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1256 newIndex
= normalizeArrayIndex( this.items
, newIndex
);
1258 // Remove the item from the current index
1259 this.items
.splice( existingIndex
, 1 );
1261 // If necessary, adjust new index after removal
1262 if ( existingIndex
< newIndex
) {
1266 // Move the item to the new index
1267 this.items
.splice( newIndex
, 0, item
);
1273 * Utility method to insert an item into the list, and
1274 * connect it to aggregate events.
1276 * Don't call this directly unless you know what you're doing.
1277 * Use #addItems instead.
1279 * This method can be extended in child classes to produce
1280 * different behavior when an item is inserted. For example,
1281 * inserted items may also be attached to the DOM or may
1282 * interact with some other nodes in certain ways. Extending
1283 * this method is allowed, but if overridden, the aggregation
1284 * of events must be preserved, or behavior of emitted events
1287 * If you are extending this method, please make sure the
1288 * parent method is called.
1291 * @param {OO.EventEmitter|Object} item Item to add
1292 * @param {number} index Index to add items at
1293 * @return {number} The index the item was added at
1295 OO
.EmitterList
.prototype.insertItem = function ( item
, index
) {
1298 // Throw an error if null or item is not an object.
1299 if ( item
=== null || typeof item
!== 'object' ) {
1300 throw new Error( 'Expected object, but item is ' + typeof item
);
1303 // Add the item to event aggregation
1304 if ( item
.connect
&& item
.disconnect
) {
1306 for ( event
in this.aggregateItemEvents
) {
1307 events
[ event
] = [ 'emit', this.aggregateItemEvents
[ event
], item
];
1309 item
.connect( this, events
);
1312 index
= normalizeArrayIndex( this.items
, index
);
1314 // Insert into items array
1315 this.items
.splice( index
, 0, item
);
1322 * @param {OO.EventEmitter[]} items Items to remove
1323 * @return {OO.EmitterList}
1324 * @fires OO.EmitterList#remove
1326 OO
.EmitterList
.prototype.removeItems = function ( items
) {
1329 if ( !Array
.isArray( items
) ) {
1333 if ( items
.length
=== 0 ) {
1337 // Remove specific items
1338 for ( i
= 0; i
< items
.length
; i
++ ) {
1340 index
= this.items
.indexOf( item
);
1341 if ( index
!== -1 ) {
1342 if ( item
.connect
&& item
.disconnect
) {
1343 // Disconnect all listeners from the item
1344 item
.disconnect( this );
1346 this.items
.splice( index
, 1 );
1347 this.emit( 'remove', item
, index
);
1357 * @return {OO.EmitterList}
1358 * @fires OO.EmitterList#clear
1360 OO
.EmitterList
.prototype.clearItems = function () {
1362 cleared
= this.items
.splice( 0, this.items
.length
);
1364 // Disconnect all items
1365 for ( i
= 0; i
< cleared
.length
; i
++ ) {
1366 item
= cleared
[ i
];
1367 if ( item
.connect
&& item
.disconnect
) {
1368 item
.disconnect( this );
1372 this.emit( 'clear' );
1380 * Manage a sorted list of OO.EmitterList objects.
1382 * The sort order is based on a callback that compares two items. The return value of
1383 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1384 * if a is equal to b. The callback should only return zero if the two objects are
1387 * When an item changes in a way that could affect their sorting behavior, it must
1388 * emit the {@link OO.SortedEmitterList#event:itemSortChange itemSortChange} event.
1389 * This will cause it to be re-sorted automatically.
1391 * This mixin must be used in a class that also mixes in {@link OO.EventEmitter}.
1395 * @mixes OO.EmitterList
1396 * @param {Function} sortingCallback Callback that compares two items.
1398 OO
.SortedEmitterList
= function OoSortedEmitterList( sortingCallback
) {
1399 // Mixin constructors
1400 OO
.EmitterList
.call( this );
1402 this.sortingCallback
= sortingCallback
;
1404 // Listen to sortChange event and make sure
1405 // we re-sort the changed item when that happens
1407 sortChange
: 'itemSortChange'
1410 this.connect( this, {
1411 itemSortChange
: 'onItemSortChange'
1415 OO
.mixinClass( OO
.SortedEmitterList
, OO
.EmitterList
);
1420 * An item has changed properties that affect its sort positioning
1424 * @event OO.SortedEmitterList#itemSortChange
1430 * Handle a case where an item changed a property that relates
1431 * to its sorted order.
1433 * @param {OO.EventEmitter} item Item in the list
1435 OO
.SortedEmitterList
.prototype.onItemSortChange = function ( item
) {
1437 this.removeItems( item
);
1438 // Re-add the item so it is in the correct place
1439 this.addItems( item
);
1443 * Change the sorting callback for this sorted list.
1445 * The callback receives two items. The return value of callback(a, b) must be less than zero
1446 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1448 * @param {Function} sortingCallback Sorting callback
1450 OO
.SortedEmitterList
.prototype.setSortingCallback = function ( sortingCallback
) {
1451 var items
= this.getItems();
1453 this.sortingCallback
= sortingCallback
;
1457 // Re-add the items in the new order
1458 this.addItems( items
);
1462 * Add items to the sorted list.
1464 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1465 * an array of items to add
1466 * @return {OO.SortedEmitterList}
1468 OO
.SortedEmitterList
.prototype.addItems = function ( items
) {
1469 var index
, i
, insertionIndex
;
1471 if ( !Array
.isArray( items
) ) {
1475 if ( items
.length
=== 0 ) {
1479 for ( i
= 0; i
< items
.length
; i
++ ) {
1480 // Find insertion index
1481 insertionIndex
= this.findInsertionIndex( items
[ i
] );
1483 // Check if the item exists using the sorting callback
1484 // and remove it first if it exists
1486 // First make sure the insertion index is not at the end
1487 // of the list (which means it does not point to any actual
1489 insertionIndex
<= this.items
.length
&&
1490 // Make sure there actually is an item in this index
1491 this.items
[ insertionIndex
] &&
1492 // The callback returns 0 if the items are equal
1493 this.sortingCallback( this.items
[ insertionIndex
], items
[ i
] ) === 0
1495 // Remove the existing item
1496 this.removeItems( this.items
[ insertionIndex
] );
1499 // Insert item at the insertion index
1500 index
= this.insertItem( items
[ i
], insertionIndex
);
1501 this.emit( 'add', items
[ i
], index
);
1508 * Find the index a given item should be inserted at. If the item is already
1509 * in the list, this will return the index where the item currently is.
1511 * @param {OO.EventEmitter} item Items to insert
1512 * @return {number} The index the item should be inserted at
1514 OO
.SortedEmitterList
.prototype.findInsertionIndex = function ( item
) {
1517 return OO
.binarySearch(
1519 // Fake a this.sortingCallback.bind( null, item ) call here
1520 // otherwise this doesn't pass tests in phantomJS
1521 function ( otherItem
) {
1522 return list
.sortingCallback( item
, otherItem
);
1532 * A map interface for associating arbitrary data with a symbolic name. Used in
1533 * place of a plain object to provide additional {@link OO.Registry#register registration}
1534 * or {@link OO.Registry#lookup lookup} functionality.
1536 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1539 * @mixes OO.EventEmitter
1541 OO
.Registry
= function OoRegistry() {
1542 // Mixin constructors
1543 OO
.EventEmitter
.call( this );
1551 OO
.mixinClass( OO
.Registry
, OO
.EventEmitter
);
1556 * @event OO.Registry#register
1557 * @param {string} name
1562 * @event OO.Registry#unregister
1563 * @param {string} name
1564 * @param {any} data Data removed from registry
1570 * Associate one or more symbolic names with some data.
1572 * Any existing entry with the same name will be overridden.
1574 * @param {string|string[]} name Symbolic name or list of symbolic names
1575 * @param {any} data Data to associate with symbolic name
1576 * @fires OO.Registry#register
1577 * @throws {Error} Name argument must be a string or array
1579 OO
.Registry
.prototype.register = function ( name
, data
) {
1581 if ( typeof name
=== 'string' ) {
1582 this.registry
[ name
] = data
;
1583 this.emit( 'register', name
, data
);
1584 } else if ( Array
.isArray( name
) ) {
1585 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1586 this.register( name
[ i
], data
);
1589 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1594 * Remove one or more symbolic names from the registry.
1596 * @param {string|string[]} name Symbolic name or list of symbolic names
1597 * @fires OO.Registry#unregister
1598 * @throws {Error} Name argument must be a string or array
1600 OO
.Registry
.prototype.unregister = function ( name
) {
1602 if ( typeof name
=== 'string' ) {
1603 data
= this.lookup( name
);
1604 if ( data
!== undefined ) {
1605 delete this.registry
[ name
];
1606 this.emit( 'unregister', name
, data
);
1608 } else if ( Array
.isArray( name
) ) {
1609 for ( i
= 0, len
= name
.length
; i
< len
; i
++ ) {
1610 this.unregister( name
[ i
] );
1613 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name
);
1618 * Get data for a given symbolic name.
1620 * @param {string} name Symbolic name
1621 * @return {any|undefined} Data associated with symbolic name
1623 OO
.Registry
.prototype.lookup = function ( name
) {
1624 if ( hasOwn
.call( this.registry
, name
) ) {
1625 return this.registry
[ name
];
1631 * @extends OO.Registry
1633 OO
.Factory
= function OoFactory() {
1634 // Parent constructor
1635 OO
.Factory
.super.call( this );
1640 OO
.inheritClass( OO
.Factory
, OO
.Registry
);
1645 * Register a constructor with the factory.
1647 * function MyClass() {};
1648 * OO.initClass( MyClass );
1649 * MyClass.static.name = 'hello';
1650 * // Register class with the factory, available via the symbolic name "hello"
1651 * factory.register( MyClass );
1653 * @param {Function} constructor Constructor to use when creating object
1654 * @param {string} [name] Symbolic name to use for #create().
1655 * This parameter may be omitted in favour of letting the constructor decide
1656 * its own name, through `constructor.static.name`.
1657 * @throws {Error} If a parameter is invalid
1659 OO
.Factory
.prototype.register = function ( constructor, name
) {
1660 if ( typeof constructor !== 'function' ) {
1661 throw new Error( 'constructor must be a function, got ' + typeof constructor );
1663 if ( arguments
.length
<= 1 ) {
1664 name
= constructor.static && constructor.static.name
;
1666 if ( typeof name
!== 'string' || name
=== '' ) {
1667 throw new Error( 'name must be a non-empty string' );
1671 OO
.Factory
.super.prototype.register
.call( this, name
, constructor );
1675 * Unregister a constructor from the factory.
1677 * @param {string|Function} name Constructor function or symbolic name to unregister
1678 * @throws {Error} If a parameter is invalid
1680 OO
.Factory
.prototype.unregister = function ( name
) {
1681 if ( typeof name
=== 'function' ) {
1682 name
= name
.static && name
.static.name
;
1684 if ( typeof name
!== 'string' || name
=== '' ) {
1685 throw new Error( 'name must be a non-empty string' );
1689 OO
.Factory
.super.prototype.unregister
.call( this, name
);
1693 * Create an object based on a name.
1695 * Name is used to look up the constructor to use, while all additional arguments are passed to the
1696 * constructor directly, so leaving one out will pass an undefined to the constructor.
1698 * @param {string} name Object name
1699 * @param {...any} [args] Arguments to pass to the constructor
1700 * @return {Object} The new object
1701 * @throws {Error} Unknown object name
1703 OO
.Factory
.prototype.create = function ( name
) {
1706 constructor = this.lookup( name
);
1708 if ( !constructor ) {
1709 throw new Error( 'No class registered by that name: ' + name
);
1712 // Convert arguments to array and shift the first argument (name) off
1713 for ( i
= 1; i
< arguments
.length
; i
++ ) {
1714 args
.push( arguments
[ i
] );
1717 // We can't use the "new" operator with .apply directly because apply needs a
1718 // context. So instead just do what "new" does: create an object that inherits from
1719 // the constructor's prototype (which also makes it an "instanceof" the constructor),
1720 // then invoke the constructor with the object as context, and return it (ignoring
1721 // the constructor's return value).
1722 obj
= Object
.create( constructor.prototype );
1723 constructor.apply( obj
, args
);
1727 /* eslint-env node */
1729 /* istanbul ignore next */
1730 if ( typeof module
!== 'undefined' && module
.exports
) {
1731 module
.exports
= OO
;