3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2023 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
9 ( function ( global ) {
13 /* exported slice, toString */
15 * Namespace for all classes, static methods and static properties.
20 // eslint-disable-next-line no-redeclare
22 // Optimisation: Local reference to methods from a global prototype
23 hasOwn = OO.hasOwnProperty,
24 slice = Array.prototype.slice,
25 // eslint-disable-next-line no-redeclare
26 toString = OO.toString;
31 * Utility to initialize a class for OO inheritance.
33 * Currently this just initializes an empty static object.
37 * @param {Function} fn
39 OO.initClass = function ( fn ) {
40 fn.static = fn.static || {};
44 * Inherit from prototype to another using Object#create.
46 * Beware: This redefines the prototype, call before setting your prototypes.
48 * Beware: This redefines the prototype, can only be called once on a function.
49 * If called multiple times on the same function, the previous prototype is lost.
50 * This is how prototypal inheritance works, it can only be one straight chain
51 * (just like classical inheritance in PHP for example). If you need to work with
52 * multiple constructors consider storing an instance of the other constructor in a
53 * property instead, or perhaps use a mixin (see OO.mixinClass).
56 * Thing.prototype.exists = function () {};
59 * Person.super.apply( this, arguments );
61 * OO.inheritClass( Person, Thing );
62 * Person.static.defaultEyeCount = 2;
63 * Person.prototype.walk = function () {};
66 * Jumper.super.apply( this, arguments );
68 * OO.inheritClass( Jumper, Person );
69 * Jumper.prototype.jump = function () {};
71 * Jumper.static.defaultEyeCount === 2;
72 * var x = new Jumper();
75 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
78 * @method inheritClass
79 * @param {Function} targetFn
80 * @param {Function} originFn
81 * @throws {Error} If target already inherits from origin
83 OO.inheritClass = function ( targetFn, originFn ) {
85 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn + ')' );
87 if ( targetFn.prototype instanceof originFn ) {
88 throw new Error( 'inheritClass: Target already inherits from origin' );
91 var targetConstructor = targetFn.prototype.constructor;
93 // [DEPRECATED] Provide .parent as alias for code supporting older browsers which
94 // allows people to comply with their style guide.
95 targetFn.super = targetFn.parent = originFn;
97 targetFn.prototype = Object.create( originFn.prototype, {
98 // Restore constructor property of targetFn
100 value: targetConstructor,
107 // Extend static properties - always initialize both sides
108 OO.initClass( originFn );
109 targetFn.static = Object.create( originFn.static );
113 * Copy over *own* prototype properties of a mixin.
115 * The 'constructor' (whether implicit or explicit) is not copied over.
117 * This does not create inheritance to the origin. If you need inheritance,
118 * use OO.inheritClass instead.
120 * Beware: This can redefine a prototype property, call before setting your prototypes.
122 * Beware: Don't call before OO.inheritClass.
125 * function Context() {}
127 * // Avoid repeating this code
128 * function ContextLazyLoad() {}
129 * ContextLazyLoad.prototype.getContext = function () {
130 * if ( !this.context ) {
131 * this.context = new Context();
133 * return this.context;
136 * function FooBar() {}
137 * OO.inheritClass( FooBar, Foo );
138 * OO.mixinClass( FooBar, ContextLazyLoad );
142 * @param {Function} targetFn
143 * @param {Function} originFn
145 OO.mixinClass = function ( targetFn, originFn ) {
147 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn + ')' );
151 // Copy prototype properties
152 for ( key in originFn.prototype ) {
153 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
154 targetFn.prototype[ key ] = originFn.prototype[ key ];
158 // Copy static properties - always initialize both sides
159 OO.initClass( targetFn );
160 if ( originFn.static ) {
161 for ( key in originFn.static ) {
162 if ( hasOwn.call( originFn.static, key ) ) {
163 targetFn.static[ key ] = originFn.static[ key ];
167 OO.initClass( originFn );
172 * Test whether one class is a subclass of another, without instantiating it.
174 * Every class is considered a subclass of Object and of itself.
178 * @param {Function} testFn The class to be tested
179 * @param {Function} baseFn The base class
180 * @return {boolean} Whether testFn is a subclass of baseFn (or equal to it)
182 OO.isSubclass = function ( testFn, baseFn ) {
183 return testFn === baseFn || testFn.prototype instanceof baseFn;
189 * Get a deeply nested property of an object using variadic arguments, protecting against
190 * undefined property errors.
192 * `quux = OO.getProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `quux = obj.foo.bar.baz;`
193 * except that the former protects against JS errors if one of the intermediate properties
194 * is undefined. Instead of throwing an error, this function will return undefined in
199 * @param {Object} obj
200 * @param {...any} [keys]
201 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
203 OO.getProp = function ( obj ) {
205 for ( var i = 1; i < arguments.length; i++ ) {
206 if ( retval === undefined || retval === null ) {
207 // Trying to access a property of undefined or null causes an error
210 retval = retval[ arguments[ i ] ];
216 * Set a deeply nested property of an object using variadic arguments, protecting against
217 * undefined property errors.
219 * `OO.setProp( obj, 'foo', 'bar', 'baz' );` is equivalent to `obj.foo.bar = baz;` except that
220 * the former protects against JS errors if one of the intermediate properties is
221 * undefined. Instead of throwing an error, undefined intermediate properties will be
222 * initialized to an empty object. If an intermediate property is not an object, or if obj itself
223 * is not an object, this function will silently abort.
227 * @param {Object} obj
228 * @param {...any} [keys]
229 * @param {any} [value]
231 OO.setProp = function ( obj ) {
232 if ( Object( obj ) !== obj || arguments.length < 2 ) {
236 for ( var i = 1; i < arguments.length - 2; i++ ) {
237 if ( prop[ arguments[ i ] ] === undefined ) {
238 prop[ arguments[ i ] ] = {};
240 if ( Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) {
243 prop = prop[ arguments[ i ] ];
245 prop[ arguments[ arguments.length - 2 ] ] = arguments[ arguments.length - 1 ];
249 * Delete a deeply nested property of an object using variadic arguments, protecting against
250 * undefined property errors, and deleting resulting empty objects.
254 * @param {Object} obj
255 * @param {...any} [keys]
257 OO.deleteProp = function ( obj ) {
258 if ( Object( obj ) !== obj || arguments.length < 2 ) {
262 var props = [ prop ];
264 for ( ; i < arguments.length - 1; i++ ) {
266 prop[ arguments[ i ] ] === undefined ||
267 Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ]
271 prop = prop[ arguments[ i ] ];
274 delete prop[ arguments[ i ] ];
275 // Walk back through props removing any plain empty objects
278 ( prop = props.pop() ) &&
280 OO.isPlainObject( prop ) && !Object.keys( prop ).length
282 delete props[ props.length - 1 ][ arguments[ props.length ] ];
287 * Create a new object that is an instance of the same
288 * constructor as the input, inherits from the same object
289 * and contains the same own properties.
291 * This makes a shallow non-recursive copy of own properties.
292 * To create a recursive copy of plain objects, use #copy.
294 * var foo = new Person( mom, dad );
296 * var foo2 = OO.cloneObject( foo );
300 * foo2 !== foo; // true
301 * foo2 instanceof Person; // true
302 * foo2.getAge(); // 21
303 * foo.getAge(); // 22
306 * @method cloneObject
307 * @param {Object} origin
308 * @return {Object} Clone of origin
310 OO.cloneObject = function ( origin ) {
311 var r = Object.create( origin.constructor.prototype );
313 for ( var key in origin ) {
314 if ( hasOwn.call( origin, key ) ) {
315 r[ key ] = origin[ key ];
323 * Get an array of all property values in an object.
326 * @method getObjectValues
327 * @param {Object} obj Object to get values from
328 * @return {Array} List of object values
330 OO.getObjectValues = function ( obj ) {
331 if ( obj !== Object( obj ) ) {
332 throw new TypeError( 'Called on non-object' );
336 for ( var key in obj ) {
337 if ( hasOwn.call( obj, key ) ) {
338 values[ values.length ] = obj[ key ];
346 * Use binary search to locate an element in a sorted array.
348 * searchFunc is given an element from the array. `searchFunc(elem)` must return a number
349 * above 0 if the element we're searching for is to the right of (has a higher index than) elem,
350 * below 0 if it is to the left of elem, or zero if it's equal to elem.
352 * To search for a specific value with a comparator function (a `function cmp(a,b)` that returns
353 * above 0 if `a > b`, below 0 if `a < b`, and 0 if `a == b`), you can use
354 * `searchFunc = cmp.bind( null, value )`.
357 * @method binarySearch
358 * @param {Array} arr Array to search in
359 * @param {Function} searchFunc Search function
360 * @param {boolean} [forInsertion] If not found, return index where val could be inserted
361 * @return {number|null} Index where val was found, or null if not found
363 OO.binarySearch = function ( arr, searchFunc, forInsertion ) {
365 var right = arr.length;
366 while ( left < right ) {
367 // Equivalent to Math.floor( ( left + right ) / 2 ) but much faster
368 // eslint-disable-next-line no-bitwise
369 var mid = ( left + right ) >> 1;
370 var cmpResult = searchFunc( arr[ mid ] );
371 if ( cmpResult < 0 ) {
373 } else if ( cmpResult > 0 ) {
379 return forInsertion ? right : null;
383 * Recursively compare properties between two objects.
385 * A false result may be caused by property inequality or by properties in one object missing from
386 * the other. An asymmetrical test may also be performed, which checks only that properties in the
387 * first object are present in the second object, but not the inverse.
389 * If either a or b is null or undefined it will be treated as an empty object.
393 * @param {Object|undefined|null} a First object to compare
394 * @param {Object|undefined|null} b Second object to compare
395 * @param {boolean} [asymmetrical] Whether to check only that a's values are equal to b's
396 * (i.e. a is a subset of b)
397 * @return {boolean} If the objects contain the same values as each other
399 OO.compare = function ( a, b, asymmetrical ) {
407 if ( typeof a.nodeType === 'number' && typeof a.isEqualNode === 'function' ) {
408 return a.isEqualNode( b );
412 if ( !hasOwn.call( a, k ) || a[ k ] === undefined || a[ k ] === b[ k ] ) {
413 // Ignore undefined values, because there is no conceptual difference between
414 // a key that is absent and a key that is present but whose value is undefined.
420 var aType = typeof aValue;
421 var bType = typeof bValue;
422 if ( aType !== bType ||
424 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) &&
427 ( aValue === Object( aValue ) && !OO.compare( aValue, bValue, true ) ) ) {
431 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
432 return asymmetrical ? true : OO.compare( b, a, true );
436 * Create a plain deep copy of any kind of object.
438 * Copies are deep, and will either be an object or an array depending on `source`.
442 * @param {Object} source Object to copy
443 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are
445 * @param {Function} [nodeCallback] Applied to all values before they are cloned. If the
446 * nodeCallback returns a value other than undefined, the returned value is used instead of
447 * attempting to clone.
448 * @return {Object} Copy of source object
450 OO.copy = function ( source, leafCallback, nodeCallback ) {
453 if ( nodeCallback ) {
454 // Extensibility: check before attempting to clone source.
455 destination = nodeCallback( source );
456 if ( destination !== undefined ) {
461 if ( Array.isArray( source ) ) {
462 // Array (fall through)
463 destination = new Array( source.length );
464 } else if ( source && typeof source.clone === 'function' ) {
465 // Duck type object with custom clone method
466 return leafCallback ? leafCallback( source.clone() ) : source.clone();
467 } else if ( source && typeof source.cloneNode === 'function' ) {
469 return leafCallback ?
470 leafCallback( source.cloneNode( true ) ) :
471 source.cloneNode( true );
472 } else if ( OO.isPlainObject( source ) ) {
473 // Plain objects (fall through)
476 // Non-plain objects (incl. functions) and primitive values
477 return leafCallback ? leafCallback( source ) : source;
480 // source is an array or a plain object
481 for ( var key in source ) {
482 destination[ key ] = OO.copy( source[ key ], leafCallback, nodeCallback );
485 // This is an internal node, so we don't apply the leafCallback.
490 * Generate a hash of an object based on its name and data.
492 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
494 * To avoid two objects with the same values generating different hashes, we utilize the replacer
495 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
496 * not be the fastest way to do this; we should investigate this further.
498 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
499 * function, we call that function and use its return value rather than hashing the object
500 * ourselves. This allows classes to define custom hashing.
504 * @param {Object} val Object to generate hash for
505 * @return {string} Hash of object
507 OO.getHash = function ( val ) {
508 return JSON.stringify( val, OO.getHash.keySortReplacer );
512 * Sort objects by key (helper function for OO.getHash).
514 * This is a callback passed into JSON.stringify.
517 * @method getHash_keySortReplacer
518 * @param {string} key Property name of value being replaced
519 * @param {any} val Property value to replace
520 * @return {any} Replacement value
522 OO.getHash.keySortReplacer = function ( key, val ) {
523 if ( val && typeof val.getHashObject === 'function' ) {
524 // This object has its own custom hash function, use it
525 val = val.getHashObject();
527 if ( !Array.isArray( val ) && Object( val ) === val ) {
528 // Only normalize objects when the key-order is ambiguous
529 // (e.g. any object not an array).
532 var keys = Object.keys( val ).sort();
533 for ( var i = 0, len = keys.length; i < len; i++ ) {
534 normalized[ keys[ i ] ] = val[ keys[ i ] ];
538 // Primitive values and arrays get stable hashes
539 // by default. Lets those be stringified as-is.
545 * Get the unique values of an array, removing duplicates.
549 * @param {Array} arr Array
550 * @return {Array} Unique values in array
552 OO.unique = function ( arr ) {
553 return Array.from( new Set( arr ) );
557 * Compute the union (duplicate-free merge) of a set of arrays.
560 * @method simpleArrayUnion
561 * @param {Array} a First array
562 * @param {...Array} rest Arrays to union
563 * @return {Array} Union of the arrays
565 OO.simpleArrayUnion = function ( a, ...rest ) {
566 var set = new Set( a );
568 for ( var i = 0; i < rest.length; i++ ) {
570 for ( var j = 0; j < arr.length; j++ ) {
575 return Array.from( set );
579 * Combine arrays (intersection or difference).
581 * An intersection checks the item exists in 'b' while difference checks it doesn't.
584 * @param {Array} a First array
585 * @param {Array} b Second array
586 * @param {boolean} includeB Whether to items in 'b'
587 * @return {Array} Combination (intersection or difference) of arrays
589 function simpleArrayCombine( a, b, includeB ) {
590 var set = new Set( b );
593 for ( var j = 0; j < a.length; j++ ) {
594 var isInB = set.has( a[ j ] );
595 if ( isInB === includeB ) {
596 result.push( a[ j ] );
604 * Compute the intersection of two arrays (items in both arrays).
607 * @method simpleArrayIntersection
608 * @param {Array} a First array
609 * @param {Array} b Second array
610 * @return {Array} Intersection of arrays
612 OO.simpleArrayIntersection = function ( a, b ) {
613 return simpleArrayCombine( a, b, true );
617 * Compute the difference of two arrays (items in 'a' but not 'b').
620 * @method simpleArrayDifference
621 * @param {Array} a First array
622 * @param {Array} b Second array
623 * @return {Array} Intersection of arrays
625 OO.simpleArrayDifference = function ( a, b ) {
626 return simpleArrayCombine( a, b, false );
629 /* eslint-disable-next-line no-redeclare */
630 /* global hasOwn, toString */
633 * Assert whether a value is a plain object or not.
639 OO.isPlainObject = function ( obj ) {
640 // Optimise for common case where internal [[Class]] property is not "Object"
641 if ( !obj || toString.call( obj ) !== '[object Object]' ) {
645 var proto = Object.getPrototypeOf( obj );
647 // Objects without prototype (e.g., `Object.create( null )`) are considered plain
652 // The 'isPrototypeOf' method is set on Object.prototype.
653 return hasOwn.call( proto, 'isPrototypeOf' );
656 /* global hasOwn, slice */
663 OO.EventEmitter = function OoEventEmitter() {
667 * Storage of bound event handlers by event name.
670 * @property {Object} bindings
675 OO.initClass( OO.EventEmitter );
677 /* Private helper functions */
680 * Validate a function or method call in a context
682 * For a method name, check that it names a function in the context object
685 * @param {Function|string} method Function or method name
686 * @param {any} context The context of the call
687 * @throws {Error} A method name is given but there is no context
688 * @throws {Error} In the context object, no property exists with the given name
689 * @throws {Error} In the context object, the named property is not a function
691 function validateMethod( method, context ) {
692 // Validate method and context
693 if ( typeof method === 'string' ) {
695 if ( context === undefined || context === null ) {
696 throw new Error( 'Method name "' + method + '" has no context.' );
698 if ( typeof context[ method ] !== 'function' ) {
699 // Technically the property could be replaced by a function before
700 // call time. But this probably signals a typo.
701 throw new Error( 'Property "' + method + '" is not a function' );
703 } else if ( typeof method !== 'function' ) {
704 throw new Error( 'Invalid callback. Function or method name expected.' );
710 * @param {OO.EventEmitter} eventEmitter Event emitter
711 * @param {string} event Event name
712 * @param {Object} binding
714 function addBinding( eventEmitter, event, binding ) {
716 // Auto-initialize bindings list
717 if ( hasOwn.call( eventEmitter.bindings, event ) ) {
718 bindings = eventEmitter.bindings[ event ];
720 bindings = eventEmitter.bindings[ event ] = [];
723 bindings.push( binding );
729 * Add a listener to events of a specific event.
731 * The listener can be a function or the string name of a method; if the latter, then the
732 * name lookup happens at the time the listener is called.
734 * @param {string} event Type of event to listen to
735 * @param {Function|string} method Function or method name to call when event occurs
736 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
737 * @param {Object} [context=null] Context object for function or method call
738 * @return {OO.EventEmitter}
739 * @throws {Error} Listener argument is not a function or a valid method name
741 OO.EventEmitter.prototype.on = function ( event, method, args, context ) {
742 validateMethod( method, context );
744 // Ensure consistent object shape (optimisation)
745 addBinding( this, event, {
748 context: ( arguments.length < 4 ) ? null : context,
755 * Add a one-time listener to a specific event.
757 * @param {string} event Type of event to listen to
758 * @param {Function} listener Listener to call when event occurs
759 * @return {OO.EventEmitter}
761 OO.EventEmitter.prototype.once = function ( event, listener ) {
762 validateMethod( listener );
764 // Ensure consistent object shape (optimisation)
765 addBinding( this, event, {
775 * Remove a specific listener from a specific event.
777 * @param {string} event Type of event to remove listener from
778 * @param {Function|string} [method] Listener to remove. Must be in the same form as was passed
779 * to "on". Omit to remove all listeners.
780 * @param {Object} [context=null] Context object function or method call
781 * @return {OO.EventEmitter}
782 * @throws {Error} Listener argument is not a function or a valid method name
784 OO.EventEmitter.prototype.off = function ( event, method, context ) {
785 if ( arguments.length === 1 ) {
786 // Remove all bindings for event
787 delete this.bindings[ event ];
791 validateMethod( method, context );
793 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) {
794 // No matching bindings
798 // Default to null context
799 if ( arguments.length < 3 ) {
803 // Remove matching handlers
804 var bindings = this.bindings[ event ];
805 var i = bindings.length;
807 if ( bindings[ i ].method === method && bindings[ i ].context === context ) {
808 bindings.splice( i, 1 );
812 // Cleanup if now empty
813 if ( bindings.length === 0 ) {
814 delete this.bindings[ event ];
822 * All listeners for the event will be called synchronously, in an
823 * unspecified order. If any listeners throw an exception, this won't
824 * disrupt the calls to the remaining listeners; however, the exception
825 * won't be thrown until the next tick.
827 * Listeners should avoid mutating the emitting object, as this is
828 * something of an anti-pattern which can easily result in
829 * hard-to-understand code with hidden side-effects and dependencies.
831 * @param {string} event Type of event
832 * @param {...any} [args] Arguments passed to the event handler
833 * @return {boolean} Whether the event was handled by at least one listener
835 OO.EventEmitter.prototype.emit = function ( event ) {
836 if ( !hasOwn.call( this.bindings, event ) ) {
840 // Slicing ensures that we don't get tripped up by event
841 // handlers that add/remove bindings
842 var bindings = this.bindings[ event ].slice();
843 var args = slice.call( arguments, 1 );
844 for ( var i = 0; i < bindings.length; i++ ) {
845 var binding = bindings[ i ];
847 if ( typeof binding.method === 'string' ) {
848 // Lookup method by name (late binding)
849 method = binding.context[ binding.method ];
851 method = binding.method;
853 if ( binding.once ) {
854 // Unbind before calling, to avoid any nested triggers.
855 this.off( event, method );
860 binding.args ? binding.args.concat( args ) : args
863 // If one listener has an unhandled error, don't have it
864 // take down the emitter. But rethrow asynchronously so
865 // debuggers can break with a full async stack trace.
866 setTimeout( ( function ( error ) {
868 } ).bind( null, e ) );
876 * Emit an event, propagating the first exception some listener throws
878 * All listeners for the event will be called synchronously, in an
879 * unspecified order. If any listener throws an exception, this won't
880 * disrupt the calls to the remaining listeners. The first exception
881 * thrown will be propagated back to the caller; any others won't be
882 * thrown until the next tick.
884 * Listeners should avoid mutating the emitting object, as this is
885 * something of an anti-pattern which can easily result in
886 * hard-to-understand code with hidden side-effects and dependencies.
888 * @param {string} event Type of event
889 * @param {...any} [args] Arguments passed to the event handler
890 * @return {boolean} Whether the event was handled by at least one listener
892 OO.EventEmitter.prototype.emitThrow = function ( event ) {
893 // We tolerate code duplication with #emit, because the
894 // alternative is an extra level of indirection which will
895 // appear in very many stack traces.
896 if ( !hasOwn.call( this.bindings, event ) ) {
901 // Slicing ensures that we don't get tripped up by event
902 // handlers that add/remove bindings
903 var bindings = this.bindings[ event ].slice();
904 var args = slice.call( arguments, 1 );
905 for ( var i = 0; i < bindings.length; i++ ) {
906 var binding = bindings[ i ];
908 if ( typeof binding.method === 'string' ) {
909 // Lookup method by name (late binding)
910 method = binding.context[ binding.method ];
912 method = binding.method;
914 if ( binding.once ) {
915 // Unbind before calling, to avoid any nested triggers.
916 this.off( event, method );
921 binding.args ? binding.args.concat( args ) : args
924 if ( firstError === undefined ) {
927 // If one listener has an unhandled error, don't have it
928 // take down the emitter. But rethrow asynchronously so
929 // debuggers can break with a full async stack trace.
930 setTimeout( ( function ( error ) {
932 } ).bind( null, e ) );
937 if ( firstError !== undefined ) {
944 * Connect event handlers to an object.
946 * @param {Object} context Object to call methods on when events occur
947 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods
948 * List of event bindings keyed by event name containing either method names, functions or
949 * arrays containing method name or function followed by a list of arguments to be passed to
950 * callback before emitted arguments.
951 * @return {OO.EventEmitter}
953 OO.EventEmitter.prototype.connect = function ( context, methods ) {
954 for ( var event in methods ) {
955 var method = methods[ event ];
957 // Allow providing additional args
958 if ( Array.isArray( method ) ) {
959 args = method.slice( 1 );
960 method = method[ 0 ];
965 this.on( event, method, args, context );
971 * Disconnect event handlers from an object.
973 * @param {Object} context Object to disconnect methods from
974 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods]
975 * List of event bindings keyed by event name. Values can be either method names, functions or
976 * arrays containing a method name.
977 * NOTE: To allow matching call sites with connect(), array values are allowed to contain the
978 * parameters as well, but only the method name is used to find bindings. It is discouraged to
979 * have multiple bindings for the same event to the same listener, but if used (and only the
980 * parameters vary), disconnecting one variation of (event name, event listener, parameters)
981 * will disconnect other variations as well.
982 * @return {OO.EventEmitter}
984 OO.EventEmitter.prototype.disconnect = function ( context, methods ) {
987 // Remove specific connections to the context
988 for ( event in methods ) {
989 var method = methods[ event ];
990 if ( Array.isArray( method ) ) {
991 method = method[ 0 ];
993 this.off( event, method, context );
996 // Remove all connections to the context
997 for ( event in this.bindings ) {
998 var bindings = this.bindings[ event ];
999 var i = bindings.length;
1001 // bindings[i] may have been removed by the previous step's
1002 // this.off so check it still exists
1003 if ( bindings[ i ] && bindings[ i ].context === context ) {
1004 this.off( event, bindings[ i ].method, context );
1018 * Contain and manage a list of @{link OO.EventEmitter} items.
1020 * Aggregates and manages their events collectively.
1022 * This mixin must be used in a class that also mixes in @{link OO.EventEmitter}.
1027 OO.EmitterList = function OoEmitterList() {
1029 this.aggregateItemEvents = {};
1032 OO.initClass( OO.EmitterList );
1037 * Item has been added.
1039 * @event OO.EmitterList#add
1040 * @param {OO.EventEmitter} item Added item
1041 * @param {number} index Index items were added at
1045 * Item has been moved to a new index.
1047 * @event OO.EmitterList#move
1048 * @param {OO.EventEmitter} item Moved item
1049 * @param {number} index Index item was moved to
1050 * @param {number} oldIndex The original index the item was in
1054 * Item has been removed.
1056 * @event OO.EmitterList#remove
1057 * @param {OO.EventEmitter} item Removed item
1058 * @param {number} index Index the item was removed from
1062 * The list has been cleared of items.
1064 * @event OO.EmitterList#clear
1070 * Normalize requested index to fit into the bounds of the given array.
1074 * @param {Array} arr Given array
1075 * @param {number|undefined} index Requested index
1076 * @return {number} Normalized index
1078 function normalizeArrayIndex( arr, index ) {
1079 return ( index === undefined || index < 0 || index >= arr.length ) ?
1087 * @return {OO.EventEmitter[]} Items in the list
1089 OO.EmitterList.prototype.getItems = function () {
1090 return this.items.slice( 0 );
1094 * Get the index of a specific item.
1096 * @param {OO.EventEmitter} item Requested item
1097 * @return {number} Index of the item
1099 OO.EmitterList.prototype.getItemIndex = function ( item ) {
1100 return this.items.indexOf( item );
1104 * Get number of items.
1106 * @return {number} Number of items in the list
1108 OO.EmitterList.prototype.getItemCount = function () {
1109 return this.items.length;
1113 * Check if a list contains no items.
1115 * @return {boolean} Group is empty
1117 OO.EmitterList.prototype.isEmpty = function () {
1118 return !this.items.length;
1122 * Aggregate the events emitted by the group.
1124 * When events are aggregated, the group will listen to all contained items for the event,
1125 * and then emit the event under a new name. The new event will contain an additional leading
1126 * parameter containing the item that emitted the original event. Other arguments emitted from
1127 * the original event are passed through.
1129 * @param {Object.<string,string|null>} events An object keyed by the name of the event that
1130 * should be aggregated (e.g., ‘click’) and the value of the new name to use
1131 * (e.g., ‘groupClick’). A `null` value will remove aggregated events.
1132 * @throws {Error} If aggregation already exists
1134 OO.EmitterList.prototype.aggregate = function ( events ) {
1136 for ( var itemEvent in events ) {
1137 var groupEvent = events[ itemEvent ];
1139 // Remove existing aggregated event
1140 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
1141 // Don't allow duplicate aggregations
1143 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
1145 // Remove event aggregation from existing items
1146 for ( i = 0; i < this.items.length; i++ ) {
1147 item = this.items[ i ];
1148 if ( item.connect && item.disconnect ) {
1150 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
1151 item.disconnect( this, remove );
1154 // Prevent future items from aggregating event
1155 delete this.aggregateItemEvents[ itemEvent ];
1158 // Add new aggregate event
1160 // Make future items aggregate event
1161 this.aggregateItemEvents[ itemEvent ] = groupEvent;
1162 // Add event aggregation to existing items
1163 for ( i = 0; i < this.items.length; i++ ) {
1164 item = this.items[ i ];
1165 if ( item.connect && item.disconnect ) {
1167 add[ itemEvent ] = [ 'emit', groupEvent, item ];
1168 item.connect( this, add );
1176 * Add items to the list.
1178 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1179 * an array of items to add
1180 * @param {number} [index] Index to add items at. If no index is
1181 * given, or if the index that is given is invalid, the item
1182 * will be added at the end of the list.
1183 * @return {OO.EmitterList}
1184 * @fires OO.EmitterList#add
1185 * @fires OO.EmitterList#move
1187 OO.EmitterList.prototype.addItems = function ( items, index ) {
1188 if ( !Array.isArray( items ) ) {
1192 if ( items.length === 0 ) {
1196 index = normalizeArrayIndex( this.items, index );
1197 for ( var i = 0; i < items.length; i++ ) {
1198 var oldIndex = this.items.indexOf( items[ i ] );
1199 if ( oldIndex !== -1 ) {
1200 // Move item to new index
1201 index = this.moveItem( items[ i ], index );
1202 this.emit( 'move', items[ i ], index, oldIndex );
1204 // insert item at index
1205 index = this.insertItem( items[ i ], index );
1206 this.emit( 'add', items[ i ], index );
1215 * Move an item from its current position to a new index.
1217 * The item is expected to exist in the list. If it doesn't,
1218 * the method will throw an exception.
1221 * @param {OO.EventEmitter} item Items to add
1222 * @param {number} newIndex Index to move the item to
1223 * @return {number} The index the item was moved to
1224 * @throws {Error} If item is not in the list
1226 OO.EmitterList.prototype.moveItem = function ( item, newIndex ) {
1227 var existingIndex = this.items.indexOf( item );
1229 if ( existingIndex === -1 ) {
1230 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1233 newIndex = normalizeArrayIndex( this.items, newIndex );
1235 // Remove the item from the current index
1236 this.items.splice( existingIndex, 1 );
1238 // If necessary, adjust new index after removal
1239 if ( existingIndex < newIndex ) {
1243 // Move the item to the new index
1244 this.items.splice( newIndex, 0, item );
1250 * Utility method to insert an item into the list, and
1251 * connect it to aggregate events.
1253 * Don't call this directly unless you know what you're doing.
1254 * Use #addItems instead.
1256 * This method can be extended in child classes to produce
1257 * different behavior when an item is inserted. For example,
1258 * inserted items may also be attached to the DOM or may
1259 * interact with some other nodes in certain ways. Extending
1260 * this method is allowed, but if overridden, the aggregation
1261 * of events must be preserved, or behavior of emitted events
1264 * If you are extending this method, please make sure the
1265 * parent method is called.
1268 * @param {OO.EventEmitter|Object} item Item to add
1269 * @param {number} index Index to add items at
1270 * @return {number} The index the item was added at
1272 OO.EmitterList.prototype.insertItem = function ( item, index ) {
1273 // Throw an error if null or item is not an object.
1274 if ( item === null || typeof item !== 'object' ) {
1275 throw new Error( 'Expected object, but item is ' + typeof item );
1278 // Add the item to event aggregation
1279 if ( item.connect && item.disconnect ) {
1281 for ( var event in this.aggregateItemEvents ) {
1282 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
1284 item.connect( this, events );
1287 index = normalizeArrayIndex( this.items, index );
1289 // Insert into items array
1290 this.items.splice( index, 0, item );
1297 * @param {OO.EventEmitter|OO.EventEmitter[]} items Items to remove
1298 * @return {OO.EmitterList}
1299 * @fires OO.EmitterList#remove
1301 OO.EmitterList.prototype.removeItems = function ( items ) {
1302 if ( !Array.isArray( items ) ) {
1306 if ( items.length === 0 ) {
1310 // Remove specific items
1311 for ( var i = 0; i < items.length; i++ ) {
1312 var item = items[ i ];
1313 var index = this.items.indexOf( item );
1314 if ( index !== -1 ) {
1315 if ( item.connect && item.disconnect ) {
1316 // Disconnect all listeners from the item
1317 item.disconnect( this );
1319 this.items.splice( index, 1 );
1320 this.emit( 'remove', item, index );
1330 * @return {OO.EmitterList}
1331 * @fires OO.EmitterList#clear
1333 OO.EmitterList.prototype.clearItems = function () {
1334 var cleared = this.items.splice( 0, this.items.length );
1336 // Disconnect all items
1337 for ( var i = 0; i < cleared.length; i++ ) {
1338 var item = cleared[ i ];
1339 if ( item.connect && item.disconnect ) {
1340 item.disconnect( this );
1344 this.emit( 'clear' );
1352 * Manage a sorted list of OO.EmitterList objects.
1354 * The sort order is based on a callback that compares two items. The return value of
1355 * callback( a, b ) must be less than zero if a < b, greater than zero if a > b, and zero
1356 * if a is equal to b. The callback should only return zero if the two objects are
1359 * When an item changes in a way that could affect their sorting behavior, it must
1360 * emit the {@link OO.SortedEmitterList#event:itemSortChange itemSortChange} event.
1361 * This will cause it to be re-sorted automatically.
1363 * This mixin must be used in a class that also mixes in {@link OO.EventEmitter}.
1367 * @mixes OO.EmitterList
1368 * @param {Function} sortingCallback Callback that compares two items.
1370 OO.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) {
1371 // Mixin constructors
1372 OO.EmitterList.call( this );
1374 this.sortingCallback = sortingCallback;
1376 // Listen to sortChange event and make sure
1377 // we re-sort the changed item when that happens
1379 sortChange: 'itemSortChange'
1382 this.connect( this, {
1383 itemSortChange: 'onItemSortChange'
1387 OO.mixinClass( OO.SortedEmitterList, OO.EmitterList );
1392 * An item has changed properties that affect its sort positioning
1396 * @event OO.SortedEmitterList#itemSortChange
1402 * Handle a case where an item changed a property that relates
1403 * to its sorted order.
1405 * @param {OO.EventEmitter} item Item in the list
1407 OO.SortedEmitterList.prototype.onItemSortChange = function ( item ) {
1409 this.removeItems( item );
1410 // Re-add the item so it is in the correct place
1411 this.addItems( item );
1415 * Change the sorting callback for this sorted list.
1417 * The callback receives two items. The return value of callback(a, b) must be less than zero
1418 * if a < b, greater than zero if a > b, and zero if a is equal to b.
1420 * @param {Function} sortingCallback Sorting callback
1422 OO.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) {
1423 var items = this.getItems();
1425 this.sortingCallback = sortingCallback;
1429 // Re-add the items in the new order
1430 this.addItems( items );
1434 * Add items to the sorted list.
1436 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1437 * an array of items to add
1438 * @return {OO.SortedEmitterList}
1440 OO.SortedEmitterList.prototype.addItems = function ( items ) {
1441 if ( !Array.isArray( items ) ) {
1445 if ( items.length === 0 ) {
1449 for ( var i = 0; i < items.length; i++ ) {
1450 // Find insertion index
1451 var insertionIndex = this.findInsertionIndex( items[ i ] );
1453 // Check if the item exists using the sorting callback
1454 // and remove it first if it exists
1456 // First make sure the insertion index is not at the end
1457 // of the list (which means it does not point to any actual
1459 insertionIndex <= this.items.length &&
1460 // Make sure there actually is an item in this index
1461 this.items[ insertionIndex ] &&
1462 // The callback returns 0 if the items are equal
1463 this.sortingCallback( this.items[ insertionIndex ], items[ i ] ) === 0
1465 // Remove the existing item
1466 this.removeItems( this.items[ insertionIndex ] );
1469 // Insert item at the insertion index
1470 var index = this.insertItem( items[ i ], insertionIndex );
1471 this.emit( 'add', items[ i ], index );
1478 * Find the index a given item should be inserted at. If the item is already
1479 * in the list, this will return the index where the item currently is.
1481 * @param {OO.EventEmitter} item Items to insert
1482 * @return {number} The index the item should be inserted at
1484 OO.SortedEmitterList.prototype.findInsertionIndex = function ( item ) {
1487 return OO.binarySearch(
1489 // Fake a this.sortingCallback.bind( null, item ) call here
1490 // otherwise this doesn't pass tests in phantomJS
1491 function ( otherItem ) {
1492 return list.sortingCallback( item, otherItem );
1502 * A map interface for associating arbitrary data with a symbolic name. Used in
1503 * place of a plain object to provide additional {@link OO.Registry#register registration}
1504 * or {@link OO.Registry#lookup lookup} functionality.
1506 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1509 * @mixes OO.EventEmitter
1511 OO.Registry = function OoRegistry() {
1512 // Mixin constructors
1513 OO.EventEmitter.call( this );
1521 OO.mixinClass( OO.Registry, OO.EventEmitter );
1526 * @event OO.Registry#register
1527 * @param {string} name
1532 * @event OO.Registry#unregister
1533 * @param {string} name
1534 * @param {any} data Data removed from registry
1540 * Associate one or more symbolic names with some data.
1542 * Any existing entry with the same name will be overridden.
1544 * @param {string|string[]} name Symbolic name or list of symbolic names
1545 * @param {any} data Data to associate with symbolic name
1546 * @fires OO.Registry#register
1547 * @throws {Error} Name argument must be a string or array
1549 OO.Registry.prototype.register = function ( name, data ) {
1550 if ( typeof name === 'string' ) {
1551 this.registry[ name ] = data;
1552 this.emit( 'register', name, data );
1553 } else if ( Array.isArray( name ) ) {
1554 for ( var i = 0, len = name.length; i < len; i++ ) {
1555 this.register( name[ i ], data );
1558 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1563 * Remove one or more symbolic names from the registry.
1565 * @param {string|string[]} name Symbolic name or list of symbolic names
1566 * @fires OO.Registry#unregister
1567 * @throws {Error} Name argument must be a string or array
1569 OO.Registry.prototype.unregister = function ( name ) {
1570 if ( typeof name === 'string' ) {
1571 var data = this.lookup( name );
1572 if ( data !== undefined ) {
1573 delete this.registry[ name ];
1574 this.emit( 'unregister', name, data );
1576 } else if ( Array.isArray( name ) ) {
1577 for ( var i = 0, len = name.length; i < len; i++ ) {
1578 this.unregister( name[ i ] );
1581 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1586 * Get data for a given symbolic name.
1588 * @param {string} name Symbolic name
1589 * @return {any|undefined} Data associated with symbolic name
1591 OO.Registry.prototype.lookup = function ( name ) {
1592 if ( hasOwn.call( this.registry, name ) ) {
1593 return this.registry[ name ];
1599 * @extends OO.Registry
1601 OO.Factory = function OoFactory() {
1602 // Parent constructor
1603 OO.Factory.super.call( this );
1608 OO.inheritClass( OO.Factory, OO.Registry );
1613 * Register a class with the factory.
1615 * function MyClass() {};
1616 * OO.initClass( MyClass );
1617 * MyClass.key = 'hello';
1619 * // Register class with the factory
1620 * factory.register( MyClass );
1622 * // Instantiate a class based on its registered key (also known as a "symbolic name")
1623 * factory.create( 'hello' );
1625 * @param {Function} constructor Class to use when creating an object
1626 * @param {string} [key] The key for #create().
1627 * This parameter is usually omitted in favour of letting the class declare
1628 * its own key, through `MyClass.key`.
1629 * For backwards-compatiblity with OOjs 6.0 (2021) and older, it can also be declared
1630 * via `MyClass.static.name`.
1631 * @throws {Error} If a parameter is invalid
1633 OO.Factory.prototype.register = function ( constructor, key ) {
1634 if ( typeof constructor !== 'function' ) {
1635 throw new Error( 'constructor must be a function, got ' + typeof constructor );
1637 if ( arguments.length <= 1 ) {
1638 key = constructor.key || ( constructor.static && constructor.static.name );
1640 if ( typeof key !== 'string' || key === '' ) {
1641 throw new Error( 'key must be a non-empty string' );
1645 OO.Factory.super.prototype.register.call( this, key, constructor );
1649 * Unregister a class from the factory.
1651 * @param {string|Function} key Constructor function or key to unregister
1652 * @throws {Error} If a parameter is invalid
1654 OO.Factory.prototype.unregister = function ( key ) {
1655 if ( typeof key === 'function' ) {
1656 key = key.key || ( key.static && key.static.name );
1658 if ( typeof key !== 'string' || key === '' ) {
1659 throw new Error( 'key must be a non-empty string' );
1663 OO.Factory.super.prototype.unregister.call( this, key );
1667 * Create an object based on a key.
1669 * The key is used to look up the class to use, with any subsequent arguments passed to the
1670 * constructor function.
1672 * @param {string} key Class key
1673 * @param {...any} [args] Arguments to pass to the constructor
1674 * @return {Object} The new object
1675 * @throws {Error} Unknown key
1677 OO.Factory.prototype.create = function ( key, ...args ) {
1678 var constructor = this.lookup( key );
1679 if ( !constructor ) {
1680 throw new Error( 'No class registered by that key: ' + key );
1683 return new constructor( ...args );
1686 /* eslint-env node */
1688 /* istanbul ignore next */
1689 if ( typeof module !== 'undefined' && module.exports ) {
1690 module.exports = OO;