resources: Upgrade OOjs from v2.2.2 to v3.0.0
[lhc/web/wiklou.git] / resources / lib / oojs / oojs.jquery.js
1 /*!
2 * OOjs v3.0.0 optimised for jQuery
3 * https://www.mediawiki.org/wiki/OOjs
4 *
5 * Copyright 2011-2019 OOjs Team and other contributors.
6 * Released under the MIT license
7 * https://oojs.mit-license.org
8 *
9 * Date: 2019-08-28T15:41:06Z
10 */
11 ( function ( global ) {
12
13 'use strict';
14
15 /* exported slice, toString */
16 /**
17 * Namespace for all classes, static methods and static properties.
18 * @namespace OO
19 */
20 var
21 OO = {},
22 // Optimisation: Local reference to methods from a global prototype
23 hasOwn = OO.hasOwnProperty,
24 slice = Array.prototype.slice,
25 toString = OO.toString;
26
27 /* Class Methods */
28
29 /**
30 * Utility to initialize a class for OO inheritance.
31 *
32 * Currently this just initializes an empty static object.
33 *
34 * @memberOf OO
35 * @method initClass
36 * @param {Function} fn
37 */
38 OO.initClass = function ( fn ) {
39 fn.static = fn.static || {};
40 };
41
42 /**
43 * Inherit from prototype to another using Object#create.
44 *
45 * Beware: This redefines the prototype, call before setting your prototypes.
46 *
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).
53 *
54 * function Thing() {}
55 * Thing.prototype.exists = function () {};
56 *
57 * function Person() {
58 * Person.super.apply( this, arguments );
59 * }
60 * OO.inheritClass( Person, Thing );
61 * Person.static.defaultEyeCount = 2;
62 * Person.prototype.walk = function () {};
63 *
64 * function Jumper() {
65 * Jumper.super.apply( this, arguments );
66 * }
67 * OO.inheritClass( Jumper, Person );
68 * Jumper.prototype.jump = function () {};
69 *
70 * Jumper.static.defaultEyeCount === 2;
71 * var x = new Jumper();
72 * x.jump();
73 * x.walk();
74 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
75 *
76 * @memberOf OO
77 * @method inheritClass
78 * @param {Function} targetFn
79 * @param {Function} originFn
80 * @throws {Error} If target already inherits from origin
81 */
82 OO.inheritClass = function ( targetFn, originFn ) {
83 var targetConstructor;
84
85 if ( !originFn ) {
86 throw new Error( 'inheritClass: Origin is not a function (actually ' + originFn + ')' );
87 }
88 if ( targetFn.prototype instanceof originFn ) {
89 throw new Error( 'inheritClass: Target already inherits from origin' );
90 }
91
92 targetConstructor = targetFn.prototype.constructor;
93
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;
97
98 targetFn.prototype = Object.create( originFn.prototype, {
99 // Restore constructor property of targetFn
100 constructor: {
101 value: targetConstructor,
102 enumerable: false,
103 writable: true,
104 configurable: true
105 }
106 } );
107
108 // Extend static properties - always initialize both sides
109 OO.initClass( originFn );
110 targetFn.static = Object.create( originFn.static );
111 };
112
113 /**
114 * Copy over *own* prototype properties of a mixin.
115 *
116 * The 'constructor' (whether implicit or explicit) is not copied over.
117 *
118 * This does not create inheritance to the origin. If you need inheritance,
119 * use OO.inheritClass instead.
120 *
121 * Beware: This can redefine a prototype property, call before setting your prototypes.
122 *
123 * Beware: Don't call before OO.inheritClass.
124 *
125 * function Foo() {}
126 * function Context() {}
127 *
128 * // Avoid repeating this code
129 * function ContextLazyLoad() {}
130 * ContextLazyLoad.prototype.getContext = function () {
131 * if ( !this.context ) {
132 * this.context = new Context();
133 * }
134 * return this.context;
135 * };
136 *
137 * function FooBar() {}
138 * OO.inheritClass( FooBar, Foo );
139 * OO.mixinClass( FooBar, ContextLazyLoad );
140 *
141 * @memberOf OO
142 * @method mixinClass
143 * @param {Function} targetFn
144 * @param {Function} originFn
145 */
146 OO.mixinClass = function ( targetFn, originFn ) {
147 var key;
148
149 if ( !originFn ) {
150 throw new Error( 'mixinClass: Origin is not a function (actually ' + originFn + ')' );
151 }
152
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 ];
157 }
158 }
159
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 ];
166 }
167 }
168 } else {
169 OO.initClass( originFn );
170 }
171 };
172
173 /**
174 * Test whether one class is a subclass of another, without instantiating it.
175 *
176 * Every class is considered a subclass of Object and of itself.
177 *
178 * @memberOf OO
179 * @method isSubClass
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)
183 */
184 OO.isSubclass = function ( testFn, baseFn ) {
185 return testFn === baseFn || testFn.prototype instanceof baseFn;
186 };
187
188 /* Object Methods */
189
190 /**
191 * Get a deeply nested property of an object using variadic arguments, protecting against
192 * undefined property errors.
193 *
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
197 * that case.
198 *
199 * @memberOf OO
200 * @method getProp
201 * @param {Object} obj
202 * @param {...any} [keys]
203 * @return {Object|undefined} obj[arguments[1]][arguments[2]].... or undefined
204 */
205 OO.getProp = function ( obj ) {
206 var i,
207 retval = 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
211 return undefined;
212 }
213 retval = retval[ arguments[ i ] ];
214 }
215 return retval;
216 };
217
218 /**
219 * Set a deeply nested property of an object using variadic arguments, protecting against
220 * undefined property errors.
221 *
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.
227 *
228 * @memberOf OO
229 * @method setProp
230 * @param {Object} obj
231 * @param {...any} [keys]
232 * @param {any} [value]
233 */
234 OO.setProp = function ( obj ) {
235 var i,
236 prop = obj;
237 if ( Object( obj ) !== obj || arguments.length < 2 ) {
238 return;
239 }
240 for ( i = 1; i < arguments.length - 2; i++ ) {
241 if ( prop[ arguments[ i ] ] === undefined ) {
242 prop[ arguments[ i ] ] = {};
243 }
244 if ( Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ] ) {
245 return;
246 }
247 prop = prop[ arguments[ i ] ];
248 }
249 prop[ arguments[ arguments.length - 2 ] ] = arguments[ arguments.length - 1 ];
250 };
251
252 /**
253 * Delete a deeply nested property of an object using variadic arguments, protecting against
254 * undefined property errors, and deleting resulting empty objects.
255 *
256 * @memberOf OO
257 * @method deleteProp
258 * @param {Object} obj
259 * @param {...any} [keys]
260 */
261 OO.deleteProp = function ( obj ) {
262 var i,
263 prop = obj,
264 props = [ prop ];
265 if ( Object( obj ) !== obj || arguments.length < 2 ) {
266 return;
267 }
268 for ( i = 1; i < arguments.length - 1; i++ ) {
269 if (
270 prop[ arguments[ i ] ] === undefined ||
271 Object( prop[ arguments[ i ] ] ) !== prop[ arguments[ i ] ]
272 ) {
273 return;
274 }
275 prop = prop[ arguments[ i ] ];
276 props.push( prop );
277 }
278 delete prop[ arguments[ i ] ];
279 // Walk back through props removing any plain empty objects
280 while (
281 props.length > 1 &&
282 ( prop = props.pop() ) &&
283 OO.isPlainObject( prop ) && !Object.keys( prop ).length
284 ) {
285 delete props[ props.length - 1 ][ arguments[ props.length ] ];
286 }
287 };
288
289 /**
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.
293 *
294 * This makes a shallow non-recursive copy of own properties.
295 * To create a recursive copy of plain objects, use #copy.
296 *
297 * var foo = new Person( mom, dad );
298 * foo.setAge( 21 );
299 * var foo2 = OO.cloneObject( foo );
300 * foo.setAge( 22 );
301 *
302 * // Then
303 * foo2 !== foo; // true
304 * foo2 instanceof Person; // true
305 * foo2.getAge(); // 21
306 * foo.getAge(); // 22
307 *
308 * @memberOf OO
309 * @method cloneObject
310 * @param {Object} origin
311 * @return {Object} Clone of origin
312 */
313 OO.cloneObject = function ( origin ) {
314 var key, r;
315
316 r = Object.create( origin.constructor.prototype );
317
318 for ( key in origin ) {
319 if ( hasOwn.call( origin, key ) ) {
320 r[ key ] = origin[ key ];
321 }
322 }
323
324 return r;
325 };
326
327 /**
328 * Get an array of all property values in an object.
329 *
330 * @memberOf OO
331 * @method getObjectValues
332 * @param {Object} obj Object to get values from
333 * @return {Array} List of object values
334 */
335 OO.getObjectValues = function ( obj ) {
336 var key, values;
337
338 if ( obj !== Object( obj ) ) {
339 throw new TypeError( 'Called on non-object' );
340 }
341
342 values = [];
343 for ( key in obj ) {
344 if ( hasOwn.call( obj, key ) ) {
345 values[ values.length ] = obj[ key ];
346 }
347 }
348
349 return values;
350 };
351
352 /**
353 * Use binary search to locate an element in a sorted array.
354 *
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.
358 *
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 )`.
362 *
363 * @memberOf OO
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
369 */
370 OO.binarySearch = function ( arr, searchFunc, forInsertion ) {
371 var mid, cmpResult,
372 left = 0,
373 right = arr.length;
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 ) {
380 right = mid;
381 } else if ( cmpResult > 0 ) {
382 left = mid + 1;
383 } else {
384 return mid;
385 }
386 }
387 return forInsertion ? right : null;
388 };
389
390 /**
391 * Recursively compare properties between two objects.
392 *
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.
396 *
397 * If either a or b is null or undefined it will be treated as an empty object.
398 *
399 * @memberOf OO
400 * @method compare
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
406 */
407 OO.compare = function ( a, b, asymmetrical ) {
408 var aValue, bValue, aType, bType, k;
409
410 if ( a === b ) {
411 return true;
412 }
413
414 a = a || {};
415 b = b || {};
416
417 if ( typeof a.nodeType === 'number' && typeof a.isEqualNode === 'function' ) {
418 return a.isEqualNode( b );
419 }
420
421 for ( k in a ) {
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.
425 continue;
426 }
427
428 aValue = a[ k ];
429 bValue = b[ k ];
430 aType = typeof aValue;
431 bType = typeof bValue;
432 if ( aType !== bType ||
433 (
434 ( aType === 'string' || aType === 'number' || aType === 'boolean' ) &&
435 aValue !== bValue
436 ) ||
437 ( aValue === Object( aValue ) && !OO.compare( aValue, bValue, true ) ) ) {
438 return false;
439 }
440 }
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 );
443 };
444
445 /**
446 * Create a plain deep copy of any kind of object.
447 *
448 * Copies are deep, and will either be an object or an array depending on `source`.
449 *
450 * @memberOf OO
451 * @method copy
452 * @param {Object} source Object to copy
453 * @param {Function} [leafCallback] Applied to leaf values after they are cloned but before they are
454 * added to the clone
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
459 */
460 OO.copy = function ( source, leafCallback, nodeCallback ) {
461 var key, destination;
462
463 if ( nodeCallback ) {
464 // Extensibility: check before attempting to clone source.
465 destination = nodeCallback( source );
466 if ( destination !== undefined ) {
467 return destination;
468 }
469 }
470
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' ) {
478 // DOM Node
479 return leafCallback ?
480 leafCallback( source.cloneNode( true ) ) :
481 source.cloneNode( true );
482 } else if ( OO.isPlainObject( source ) ) {
483 // Plain objects (fall through)
484 destination = {};
485 } else {
486 // Non-plain objects (incl. functions) and primitive values
487 return leafCallback ? leafCallback( source ) : source;
488 }
489
490 // source is an array or a plain object
491 for ( key in source ) {
492 destination[ key ] = OO.copy( source[ key ], leafCallback, nodeCallback );
493 }
494
495 // This is an internal node, so we don't apply the leafCallback.
496 return destination;
497 };
498
499 /**
500 * Generate a hash of an object based on its name and data.
501 *
502 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
503 *
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.
507 *
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.
511 *
512 * @memberOf OO
513 * @method getHash
514 * @param {Object} val Object to generate hash for
515 * @return {string} Hash of object
516 */
517 OO.getHash = function ( val ) {
518 return JSON.stringify( val, OO.getHash.keySortReplacer );
519 };
520
521 /**
522 * Sort objects by key (helper function for OO.getHash).
523 *
524 * This is a callback passed into JSON.stringify.
525 *
526 * @memberOf OO
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
531 */
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();
537 }
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).
541 normalized = {};
542 keys = Object.keys( val ).sort();
543 i = 0;
544 len = keys.length;
545 for ( ; i < len; i += 1 ) {
546 normalized[ keys[ i ] ] = val[ keys[ i ] ];
547 }
548 return normalized;
549 } else {
550 // Primitive values and arrays get stable hashes
551 // by default. Lets those be stringified as-is.
552 return val;
553 }
554 };
555
556 /**
557 * Get the unique values of an array, removing duplicates.
558 *
559 * @memberOf OO
560 * @method unique
561 * @param {Array} arr Array
562 * @return {Array} Unique values in array
563 */
564 OO.unique = function ( arr ) {
565 return arr.reduce( function ( result, current ) {
566 if ( result.indexOf( current ) === -1 ) {
567 result.push( current );
568 }
569 return result;
570 }, [] );
571 };
572
573 /**
574 * Compute the union (duplicate-free merge) of a set of arrays.
575 *
576 * Arrays values must be convertable to object keys (strings).
577 *
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.
580 *
581 * @memberOf OO
582 * @method simpleArrayUnion
583 * @param {...Array} arrays Arrays to union
584 * @return {Array} Union of the arrays
585 */
586 OO.simpleArrayUnion = function () {
587 var i, ilen, arr, j, jlen,
588 obj = {},
589 result = [];
590
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 ] );
597 }
598 }
599 }
600
601 return result;
602 };
603
604 /**
605 * Combine arrays (intersection or difference).
606 *
607 * An intersection checks the item exists in 'b' while difference checks it doesn't.
608 *
609 * Arrays values must be convertable to object keys (strings).
610 *
611 * By building an object (with the values for keys) of 'b' we can
612 * compute the result faster.
613 *
614 * @private
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
619 */
620 function simpleArrayCombine( a, b, includeB ) {
621 var i, ilen, isInB,
622 bObj = {},
623 result = [];
624
625 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
626 bObj[ b[ i ] ] = true;
627 }
628
629 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
630 isInB = !!bObj[ a[ i ] ];
631 if ( isInB === includeB ) {
632 result.push( a[ i ] );
633 }
634 }
635
636 return result;
637 }
638
639 /**
640 * Compute the intersection of two arrays (items in both arrays).
641 *
642 * Arrays values must be convertable to object keys (strings).
643 *
644 * @memberOf OO
645 * @method simpleArrayIntersection
646 * @param {Array} a First array
647 * @param {Array} b Second array
648 * @return {Array} Intersection of arrays
649 */
650 OO.simpleArrayIntersection = function ( a, b ) {
651 return simpleArrayCombine( a, b, true );
652 };
653
654 /**
655 * Compute the difference of two arrays (items in 'a' but not 'b').
656 *
657 * Arrays values must be convertable to object keys (strings).
658 *
659 * @memberOf OO
660 * @method simpleArrayDifference
661 * @param {Array} a First array
662 * @param {Array} b Second array
663 * @return {Array} Intersection of arrays
664 */
665 OO.simpleArrayDifference = function ( a, b ) {
666 return simpleArrayCombine( a, b, false );
667 };
668
669 OO.isPlainObject = $.isPlainObject;
670
671 /* global hasOwn, slice */
672
673 ( function () {
674
675 /**
676 * @class
677 */
678 OO.EventEmitter = function OoEventEmitter() {
679 // Properties
680
681 /**
682 * Storage of bound event handlers by event name.
683 *
684 * @private
685 * @property {Object} bindings
686 */
687 this.bindings = {};
688 };
689
690 OO.initClass( OO.EventEmitter );
691
692 /* Private helper functions */
693
694 /**
695 * Validate a function or method call in a context
696 *
697 * For a method name, check that it names a function in the context object
698 *
699 * @private
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
705 */
706 function validateMethod( method, context ) {
707 // Validate method and context
708 if ( typeof method === 'string' ) {
709 // Validate method
710 if ( context === undefined || context === null ) {
711 throw new Error( 'Method name "' + method + '" has no context.' );
712 }
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' );
717 }
718 } else if ( typeof method !== 'function' ) {
719 throw new Error( 'Invalid callback. Function or method name expected.' );
720 }
721 }
722
723 /**
724 * @private
725 * @param {OO.EventEmitter} eventEmitter Event emitter
726 * @param {string} event Event name
727 * @param {Object} binding
728 */
729 function addBinding( eventEmitter, event, binding ) {
730 var bindings;
731 // Auto-initialize bindings list
732 if ( hasOwn.call( eventEmitter.bindings, event ) ) {
733 bindings = eventEmitter.bindings[ event ];
734 } else {
735 bindings = eventEmitter.bindings[ event ] = [];
736 }
737 // Add binding
738 bindings.push( binding );
739 }
740
741 /* Methods */
742
743 /**
744 * Add a listener to events of a specific event.
745 *
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.
748 *
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
755 */
756 OO.EventEmitter.prototype.on = function ( event, method, args, context ) {
757 validateMethod( method, context );
758
759 // Ensure consistent object shape (optimisation)
760 addBinding( this, event, {
761 method: method,
762 args: args,
763 context: ( arguments.length < 4 ) ? null : context,
764 once: false
765 } );
766 return this;
767 };
768
769 /**
770 * Add a one-time listener to a specific event.
771 *
772 * @param {string} event Type of event to listen to
773 * @param {Function} listener Listener to call when event occurs
774 * @return {OO.EventEmitter}
775 */
776 OO.EventEmitter.prototype.once = function ( event, listener ) {
777 validateMethod( listener );
778
779 // Ensure consistent object shape (optimisation)
780 addBinding( this, event, {
781 method: listener,
782 args: undefined,
783 context: null,
784 once: true
785 } );
786 return this;
787 };
788
789 /**
790 * Remove a specific listener from a specific event.
791 *
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
798 */
799 OO.EventEmitter.prototype.off = function ( event, method, context ) {
800 var i, bindings;
801
802 if ( arguments.length === 1 ) {
803 // Remove all bindings for event
804 delete this.bindings[ event ];
805 return this;
806 }
807
808 validateMethod( method, context );
809
810 if ( !hasOwn.call( this.bindings, event ) || !this.bindings[ event ].length ) {
811 // No matching bindings
812 return this;
813 }
814
815 // Default to null context
816 if ( arguments.length < 3 ) {
817 context = null;
818 }
819
820 // Remove matching handlers
821 bindings = this.bindings[ event ];
822 i = bindings.length;
823 while ( i-- ) {
824 if ( bindings[ i ].method === method && bindings[ i ].context === context ) {
825 bindings.splice( i, 1 );
826 }
827 }
828
829 // Cleanup if now empty
830 if ( bindings.length === 0 ) {
831 delete this.bindings[ event ];
832 }
833 return this;
834 };
835
836 /**
837 * Emit an event.
838 *
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.
843 *
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.
847 *
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
852 */
853 OO.EventEmitter.prototype.emit = function ( event ) {
854 var bindings, args, i, binding, method;
855
856 if ( !hasOwn.call( this.bindings, event ) ) {
857 return false;
858 }
859
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 ];
869 } else {
870 method = binding.method;
871 }
872 if ( binding.once ) {
873 // Unbind before calling, to avoid any nested triggers.
874 this.off( event, method );
875 }
876 try {
877 method.apply(
878 binding.context,
879 binding.args ? binding.args.concat( args ) : args
880 );
881 } catch ( e ) {
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 ) {
886 throw error;
887 } ).bind( null, e ) );
888 }
889
890 }
891 return true;
892 };
893
894 /**
895 * Emit an event, propagating the first exception some listener throws
896 *
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.
902 *
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.
906 *
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
911 */
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;
917
918 if ( !hasOwn.call( this.bindings, event ) ) {
919 return false;
920 }
921
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 ];
931 } else {
932 method = binding.method;
933 }
934 if ( binding.once ) {
935 // Unbind before calling, to avoid any nested triggers.
936 this.off( event, method );
937 }
938 try {
939 method.apply(
940 binding.context,
941 binding.args ? binding.args.concat( args ) : args
942 );
943 } catch ( e ) {
944 if ( firstError === undefined ) {
945 firstError = e;
946 } else {
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 ) {
951 throw error;
952 } ).bind( null, e ) );
953 }
954 }
955
956 }
957 if ( firstError !== undefined ) {
958 throw firstError;
959 }
960 return true;
961 };
962
963 /**
964 * Connect event handlers to an object.
965 *
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}
972 */
973 OO.EventEmitter.prototype.connect = function ( context, methods ) {
974 var method, args, event;
975
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 ];
982 } else {
983 args = [];
984 }
985 // Add binding
986 this.on( event, method, args, context );
987 }
988 return this;
989 };
990
991 /**
992 * Disconnect event handlers from an object.
993 *
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}
1004 */
1005 OO.EventEmitter.prototype.disconnect = function ( context, methods ) {
1006 var i, event, method, bindings;
1007
1008 if ( methods ) {
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 ];
1014 }
1015 this.off( event, method, context );
1016 }
1017 } else {
1018 // Remove all connections to the context
1019 for ( event in this.bindings ) {
1020 bindings = this.bindings[ event ];
1021 i = bindings.length;
1022 while ( i-- ) {
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 );
1027 }
1028 }
1029 }
1030 }
1031
1032 return this;
1033 };
1034
1035 }() );
1036
1037 ( function () {
1038
1039 /**
1040 * Contain and manage a list of @{link OO.EventEmitter} items.
1041 *
1042 * Aggregates and manages their events collectively.
1043 *
1044 * This mixin must be used in a class that also mixes in @{link OO.EventEmitter}.
1045 *
1046 * @abstract
1047 * @class
1048 */
1049 OO.EmitterList = function OoEmitterList() {
1050 this.items = [];
1051 this.aggregateItemEvents = {};
1052 };
1053
1054 /* Events */
1055
1056 /**
1057 * Item has been added.
1058 *
1059 * @event OO.EmitterList#add
1060 * @param {OO.EventEmitter} item Added item
1061 * @param {number} index Index items were added at
1062 */
1063
1064 /**
1065 * Item has been moved to a new index.
1066 *
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
1071 */
1072
1073 /**
1074 * Item has been removed.
1075 *
1076 * @event OO.EmitterList#remove
1077 * @param {OO.EventEmitter} item Removed item
1078 * @param {number} index Index the item was removed from
1079 */
1080
1081 /**
1082 * The list has been cleared of items.
1083 *
1084 * @event OO.EmitterList#clear
1085 */
1086
1087 /* Methods */
1088
1089 /**
1090 * Normalize requested index to fit into the bounds of the given array.
1091 *
1092 * @private
1093 * @static
1094 * @param {Array} arr Given array
1095 * @param {number|undefined} index Requested index
1096 * @return {number} Normalized index
1097 */
1098 function normalizeArrayIndex( arr, index ) {
1099 return ( index === undefined || index < 0 || index >= arr.length ) ?
1100 arr.length :
1101 index;
1102 }
1103
1104 /**
1105 * Get all items.
1106 *
1107 * @return {OO.EventEmitter[]} Items in the list
1108 */
1109 OO.EmitterList.prototype.getItems = function () {
1110 return this.items.slice( 0 );
1111 };
1112
1113 /**
1114 * Get the index of a specific item.
1115 *
1116 * @param {OO.EventEmitter} item Requested item
1117 * @return {number} Index of the item
1118 */
1119 OO.EmitterList.prototype.getItemIndex = function ( item ) {
1120 return this.items.indexOf( item );
1121 };
1122
1123 /**
1124 * Get number of items.
1125 *
1126 * @return {number} Number of items in the list
1127 */
1128 OO.EmitterList.prototype.getItemCount = function () {
1129 return this.items.length;
1130 };
1131
1132 /**
1133 * Check if a list contains no items.
1134 *
1135 * @return {boolean} Group is empty
1136 */
1137 OO.EmitterList.prototype.isEmpty = function () {
1138 return !this.items.length;
1139 };
1140
1141 /**
1142 * Aggregate the events emitted by the group.
1143 *
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.
1148 *
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
1153 */
1154 OO.EmitterList.prototype.aggregate = function ( events ) {
1155 var i, item, add, remove, itemEvent, groupEvent;
1156
1157 for ( itemEvent in events ) {
1158 groupEvent = events[ itemEvent ];
1159
1160 // Remove existing aggregated event
1161 if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) {
1162 // Don't allow duplicate aggregations
1163 if ( groupEvent ) {
1164 throw new Error( 'Duplicate item event aggregation for ' + itemEvent );
1165 }
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 ) {
1170 remove = {};
1171 remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ];
1172 item.disconnect( this, remove );
1173 }
1174 }
1175 // Prevent future items from aggregating event
1176 delete this.aggregateItemEvents[ itemEvent ];
1177 }
1178
1179 // Add new aggregate event
1180 if ( groupEvent ) {
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 ) {
1187 add = {};
1188 add[ itemEvent ] = [ 'emit', groupEvent, item ];
1189 item.connect( this, add );
1190 }
1191 }
1192 }
1193 }
1194 };
1195
1196 /**
1197 * Add items to the list.
1198 *
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
1207 */
1208 OO.EmitterList.prototype.addItems = function ( items, index ) {
1209 var i, oldIndex;
1210
1211 if ( !Array.isArray( items ) ) {
1212 items = [ items ];
1213 }
1214
1215 if ( items.length === 0 ) {
1216 return this;
1217 }
1218
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 );
1226 } else {
1227 // insert item at index
1228 index = this.insertItem( items[ i ], index );
1229 this.emit( 'add', items[ i ], index );
1230 }
1231 index++;
1232 }
1233
1234 return this;
1235 };
1236
1237 /**
1238 * Move an item from its current position to a new index.
1239 *
1240 * The item is expected to exist in the list. If it doesn't,
1241 * the method will throw an exception.
1242 *
1243 * @private
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
1248 */
1249 OO.EmitterList.prototype.moveItem = function ( item, newIndex ) {
1250 var existingIndex = this.items.indexOf( item );
1251
1252 if ( existingIndex === -1 ) {
1253 throw new Error( 'Item cannot be moved, because it is not in the list.' );
1254 }
1255
1256 newIndex = normalizeArrayIndex( this.items, newIndex );
1257
1258 // Remove the item from the current index
1259 this.items.splice( existingIndex, 1 );
1260
1261 // If necessary, adjust new index after removal
1262 if ( existingIndex < newIndex ) {
1263 newIndex--;
1264 }
1265
1266 // Move the item to the new index
1267 this.items.splice( newIndex, 0, item );
1268
1269 return newIndex;
1270 };
1271
1272 /**
1273 * Utility method to insert an item into the list, and
1274 * connect it to aggregate events.
1275 *
1276 * Don't call this directly unless you know what you're doing.
1277 * Use #addItems instead.
1278 *
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
1285 * will be broken.
1286 *
1287 * If you are extending this method, please make sure the
1288 * parent method is called.
1289 *
1290 * @protected
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
1294 */
1295 OO.EmitterList.prototype.insertItem = function ( item, index ) {
1296 var events, event;
1297
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 );
1301 }
1302
1303 // Add the item to event aggregation
1304 if ( item.connect && item.disconnect ) {
1305 events = {};
1306 for ( event in this.aggregateItemEvents ) {
1307 events[ event ] = [ 'emit', this.aggregateItemEvents[ event ], item ];
1308 }
1309 item.connect( this, events );
1310 }
1311
1312 index = normalizeArrayIndex( this.items, index );
1313
1314 // Insert into items array
1315 this.items.splice( index, 0, item );
1316 return index;
1317 };
1318
1319 /**
1320 * Remove items.
1321 *
1322 * @param {OO.EventEmitter[]} items Items to remove
1323 * @return {OO.EmitterList}
1324 * @fires OO.EmitterList#remove
1325 */
1326 OO.EmitterList.prototype.removeItems = function ( items ) {
1327 var i, item, index;
1328
1329 if ( !Array.isArray( items ) ) {
1330 items = [ items ];
1331 }
1332
1333 if ( items.length === 0 ) {
1334 return this;
1335 }
1336
1337 // Remove specific items
1338 for ( i = 0; i < items.length; i++ ) {
1339 item = items[ 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 );
1345 }
1346 this.items.splice( index, 1 );
1347 this.emit( 'remove', item, index );
1348 }
1349 }
1350
1351 return this;
1352 };
1353
1354 /**
1355 * Clear all items.
1356 *
1357 * @return {OO.EmitterList}
1358 * @fires OO.EmitterList#clear
1359 */
1360 OO.EmitterList.prototype.clearItems = function () {
1361 var i, item,
1362 cleared = this.items.splice( 0, this.items.length );
1363
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 );
1369 }
1370 }
1371
1372 this.emit( 'clear' );
1373
1374 return this;
1375 };
1376
1377 }() );
1378
1379 /**
1380 * Manage a sorted list of OO.EmitterList objects.
1381 *
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
1385 * considered equal.
1386 *
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.
1390 *
1391 * This mixin must be used in a class that also mixes in {@link OO.EventEmitter}.
1392 *
1393 * @abstract
1394 * @class
1395 * @mixes OO.EmitterList
1396 * @param {Function} sortingCallback Callback that compares two items.
1397 */
1398 OO.SortedEmitterList = function OoSortedEmitterList( sortingCallback ) {
1399 // Mixin constructors
1400 OO.EmitterList.call( this );
1401
1402 this.sortingCallback = sortingCallback;
1403
1404 // Listen to sortChange event and make sure
1405 // we re-sort the changed item when that happens
1406 this.aggregate( {
1407 sortChange: 'itemSortChange'
1408 } );
1409
1410 this.connect( this, {
1411 itemSortChange: 'onItemSortChange'
1412 } );
1413 };
1414
1415 OO.mixinClass( OO.SortedEmitterList, OO.EmitterList );
1416
1417 /* Events */
1418
1419 /**
1420 * An item has changed properties that affect its sort positioning
1421 * inside the list.
1422 *
1423 * @ignore
1424 * @event OO.SortedEmitterList#itemSortChange
1425 */
1426
1427 /* Methods */
1428
1429 /**
1430 * Handle a case where an item changed a property that relates
1431 * to its sorted order.
1432 *
1433 * @param {OO.EventEmitter} item Item in the list
1434 */
1435 OO.SortedEmitterList.prototype.onItemSortChange = function ( item ) {
1436 // Remove the item
1437 this.removeItems( item );
1438 // Re-add the item so it is in the correct place
1439 this.addItems( item );
1440 };
1441
1442 /**
1443 * Change the sorting callback for this sorted list.
1444 *
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.
1447 *
1448 * @param {Function} sortingCallback Sorting callback
1449 */
1450 OO.SortedEmitterList.prototype.setSortingCallback = function ( sortingCallback ) {
1451 var items = this.getItems();
1452
1453 this.sortingCallback = sortingCallback;
1454
1455 // Empty the list
1456 this.clearItems();
1457 // Re-add the items in the new order
1458 this.addItems( items );
1459 };
1460
1461 /**
1462 * Add items to the sorted list.
1463 *
1464 * @param {OO.EventEmitter|OO.EventEmitter[]} items Item to add or
1465 * an array of items to add
1466 * @return {OO.SortedEmitterList}
1467 */
1468 OO.SortedEmitterList.prototype.addItems = function ( items ) {
1469 var index, i, insertionIndex;
1470
1471 if ( !Array.isArray( items ) ) {
1472 items = [ items ];
1473 }
1474
1475 if ( items.length === 0 ) {
1476 return this;
1477 }
1478
1479 for ( i = 0; i < items.length; i++ ) {
1480 // Find insertion index
1481 insertionIndex = this.findInsertionIndex( items[ i ] );
1482
1483 // Check if the item exists using the sorting callback
1484 // and remove it first if it exists
1485 if (
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
1488 // items)
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
1494 ) {
1495 // Remove the existing item
1496 this.removeItems( this.items[ insertionIndex ] );
1497 }
1498
1499 // Insert item at the insertion index
1500 index = this.insertItem( items[ i ], insertionIndex );
1501 this.emit( 'add', items[ i ], index );
1502 }
1503
1504 return this;
1505 };
1506
1507 /**
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.
1510 *
1511 * @param {OO.EventEmitter} item Items to insert
1512 * @return {number} The index the item should be inserted at
1513 */
1514 OO.SortedEmitterList.prototype.findInsertionIndex = function ( item ) {
1515 var list = this;
1516
1517 return OO.binarySearch(
1518 this.items,
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 );
1523 },
1524 true
1525 );
1526
1527 };
1528
1529 /* global hasOwn */
1530
1531 /**
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.
1535 *
1536 * See <https://www.mediawiki.org/wiki/OOjs/Registries_and_factories>.
1537 *
1538 * @class
1539 * @mixes OO.EventEmitter
1540 */
1541 OO.Registry = function OoRegistry() {
1542 // Mixin constructors
1543 OO.EventEmitter.call( this );
1544
1545 // Properties
1546 this.registry = {};
1547 };
1548
1549 /* Inheritance */
1550
1551 OO.mixinClass( OO.Registry, OO.EventEmitter );
1552
1553 /* Events */
1554
1555 /**
1556 * @event OO.Registry#register
1557 * @param {string} name
1558 * @param {any} data
1559 */
1560
1561 /**
1562 * @event OO.Registry#unregister
1563 * @param {string} name
1564 * @param {any} data Data removed from registry
1565 */
1566
1567 /* Methods */
1568
1569 /**
1570 * Associate one or more symbolic names with some data.
1571 *
1572 * Any existing entry with the same name will be overridden.
1573 *
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
1578 */
1579 OO.Registry.prototype.register = function ( name, data ) {
1580 var i, len;
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 );
1587 }
1588 } else {
1589 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1590 }
1591 };
1592
1593 /**
1594 * Remove one or more symbolic names from the registry.
1595 *
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
1599 */
1600 OO.Registry.prototype.unregister = function ( name ) {
1601 var i, len, data;
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 );
1607 }
1608 } else if ( Array.isArray( name ) ) {
1609 for ( i = 0, len = name.length; i < len; i++ ) {
1610 this.unregister( name[ i ] );
1611 }
1612 } else {
1613 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
1614 }
1615 };
1616
1617 /**
1618 * Get data for a given symbolic name.
1619 *
1620 * @param {string} name Symbolic name
1621 * @return {any|undefined} Data associated with symbolic name
1622 */
1623 OO.Registry.prototype.lookup = function ( name ) {
1624 if ( hasOwn.call( this.registry, name ) ) {
1625 return this.registry[ name ];
1626 }
1627 };
1628
1629 /**
1630 * @class
1631 * @extends OO.Registry
1632 */
1633 OO.Factory = function OoFactory() {
1634 // Parent constructor
1635 OO.Factory.super.call( this );
1636 };
1637
1638 /* Inheritance */
1639
1640 OO.inheritClass( OO.Factory, OO.Registry );
1641
1642 /* Methods */
1643
1644 /**
1645 * Register a constructor with the factory.
1646 *
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 );
1652 *
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
1658 */
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 );
1662 }
1663 if ( arguments.length <= 1 ) {
1664 name = constructor.static && constructor.static.name;
1665 }
1666 if ( typeof name !== 'string' || name === '' ) {
1667 throw new Error( 'name must be a non-empty string' );
1668 }
1669
1670 // Parent method
1671 OO.Factory.super.prototype.register.call( this, name, constructor );
1672 };
1673
1674 /**
1675 * Unregister a constructor from the factory.
1676 *
1677 * @param {string|Function} name Constructor function or symbolic name to unregister
1678 * @throws {Error} If a parameter is invalid
1679 */
1680 OO.Factory.prototype.unregister = function ( name ) {
1681 if ( typeof name === 'function' ) {
1682 name = name.static && name.static.name;
1683 }
1684 if ( typeof name !== 'string' || name === '' ) {
1685 throw new Error( 'name must be a non-empty string' );
1686 }
1687
1688 // Parent method
1689 OO.Factory.super.prototype.unregister.call( this, name );
1690 };
1691
1692 /**
1693 * Create an object based on a name.
1694 *
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.
1697 *
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
1702 */
1703 OO.Factory.prototype.create = function ( name ) {
1704 var obj, i,
1705 args = [],
1706 constructor = this.lookup( name );
1707
1708 if ( !constructor ) {
1709 throw new Error( 'No class registered by that name: ' + name );
1710 }
1711
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 ] );
1715 }
1716
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 );
1724 return obj;
1725 };
1726
1727 /* eslint-env node */
1728
1729 /* istanbul ignore next */
1730 if ( typeof module !== 'undefined' && module.exports ) {
1731 module.exports = OO;
1732 } else {
1733 global.OO = OO;
1734 }
1735
1736 }( this ) );