PrefixSearch: Avoid notice when no subpage exists
[mediawiki.git] / resources / lib / oojs / oojs.js
blob8ccd50ab6f0b918dcc6d998e7f10042b52eb2a33
1 /*!
2 * OOjs v1.0.10
3 * https://www.mediawiki.org/wiki/OOjs
5 * Copyright 2011-2014 OOjs Team and other contributors.
6 * Released under the MIT license
7 * http://oojs.mit-license.org
9 * Date: Wed Jun 18 2014 20:03:40 GMT-0700 (PDT)
11 ( function ( global ) {
13 'use strict';
14 /*exported toString */
15 var
16 /**
17 * Namespace for all classes, static methods and static properties.
18 * @class OO
19 * @singleton
21 oo = {},
22 hasOwn = oo.hasOwnProperty,
23 toString = oo.toString;
25 /* Class Methods */
27 /**
28 * Utility to initialize a class for OO inheritance.
30 * Currently this just initializes an empty static object.
32 * @param {Function} fn
34 oo.initClass = function ( fn ) {
35 fn.static = fn.static || {};
38 /**
39 * Utility for common usage of Object#create for inheriting from one
40 * prototype to another.
42 * Beware: This redefines the prototype, call before setting your prototypes.
43 * Beware: This redefines the prototype, can only be called once on a function.
44 * If called multiple times on the same function, the previous prototype is lost.
45 * This is how prototypal inheritance works, it can only be one straight chain
46 * (just like classical inheritance in PHP for example). If you need to work with
47 * multiple constructors consider storing an instance of the other constructor in a
48 * property instead, or perhaps use a mixin (see OO.mixinClass).
50 * function Thing() {}
51 * Thing.prototype.exists = function () {};
53 * function Person() {
54 * Person.super.apply( this, arguments );
55 * }
56 * OO.inheritClass( Person, Thing );
57 * Person.static.defaultEyeCount = 2;
58 * Person.prototype.walk = function () {};
60 * function Jumper() {
61 * Jumper.super.apply( this, arguments );
62 * }
63 * OO.inheritClass( Jumper, Person );
64 * Jumper.prototype.jump = function () {};
66 * Jumper.static.defaultEyeCount === 2;
67 * var x = new Jumper();
68 * x.jump();
69 * x.walk();
70 * x instanceof Thing && x instanceof Person && x instanceof Jumper;
72 * @param {Function} targetFn
73 * @param {Function} originFn
74 * @throws {Error} If target already inherits from origin
76 oo.inheritClass = function ( targetFn, originFn ) {
77 if ( targetFn.prototype instanceof originFn ) {
78 throw new Error( 'Target already inherits from origin' );
81 var targetConstructor = targetFn.prototype.constructor;
83 // Using ['super'] instead of .super because 'super' is not supported
84 // by IE 8 and below (bug 63303).
85 // Provide .parent as alias for code supporting older browsers which
86 // allows people to comply with their style guide.
87 targetFn['super'] = targetFn.parent = originFn;
89 targetFn.prototype = Object.create( originFn.prototype, {
90 // Restore constructor property of targetFn
91 constructor: {
92 value: targetConstructor,
93 enumerable: false,
94 writable: true,
95 configurable: true
97 } );
99 // Extend static properties - always initialize both sides
100 oo.initClass( originFn );
101 targetFn.static = Object.create( originFn.static );
105 * Utility to copy over *own* prototype properties of a mixin.
106 * The 'constructor' (whether implicit or explicit) is not copied over.
108 * This does not create inheritance to the origin. If inheritance is needed
109 * use oo.inheritClass instead.
111 * Beware: This can redefine a prototype property, call before setting your prototypes.
112 * Beware: Don't call before oo.inheritClass.
114 * function Foo() {}
115 * function Context() {}
117 * // Avoid repeating this code
118 * function ContextLazyLoad() {}
119 * ContextLazyLoad.prototype.getContext = function () {
120 * if ( !this.context ) {
121 * this.context = new Context();
123 * return this.context;
124 * };
126 * function FooBar() {}
127 * OO.inheritClass( FooBar, Foo );
128 * OO.mixinClass( FooBar, ContextLazyLoad );
130 * @param {Function} targetFn
131 * @param {Function} originFn
133 oo.mixinClass = function ( targetFn, originFn ) {
134 var key;
136 // Copy prototype properties
137 for ( key in originFn.prototype ) {
138 if ( key !== 'constructor' && hasOwn.call( originFn.prototype, key ) ) {
139 targetFn.prototype[key] = originFn.prototype[key];
143 // Copy static properties - always initialize both sides
144 oo.initClass( targetFn );
145 if ( originFn.static ) {
146 for ( key in originFn.static ) {
147 if ( hasOwn.call( originFn.static, key ) ) {
148 targetFn.static[key] = originFn.static[key];
151 } else {
152 oo.initClass( originFn );
156 /* Object Methods */
159 * Create a new object that is an instance of the same
160 * constructor as the input, inherits from the same object
161 * and contains the same own properties.
163 * This makes a shallow non-recursive copy of own properties.
164 * To create a recursive copy of plain objects, use #copy.
166 * var foo = new Person( mom, dad );
167 * foo.setAge( 21 );
168 * var foo2 = OO.cloneObject( foo );
169 * foo.setAge( 22 );
171 * // Then
172 * foo2 !== foo; // true
173 * foo2 instanceof Person; // true
174 * foo2.getAge(); // 21
175 * foo.getAge(); // 22
177 * @param {Object} origin
178 * @return {Object} Clone of origin
180 oo.cloneObject = function ( origin ) {
181 var key, r;
183 r = Object.create( origin.constructor.prototype );
185 for ( key in origin ) {
186 if ( hasOwn.call( origin, key ) ) {
187 r[key] = origin[key];
191 return r;
195 * Get an array of all property values in an object.
197 * @param {Object} Object to get values from
198 * @return {Array} List of object values
200 oo.getObjectValues = function ( obj ) {
201 var key, values;
203 if ( obj !== Object( obj ) ) {
204 throw new TypeError( 'Called on non-object' );
207 values = [];
208 for ( key in obj ) {
209 if ( hasOwn.call( obj, key ) ) {
210 values[values.length] = obj[key];
214 return values;
218 * Recursively compares properties between two objects.
220 * A false result may be caused by property inequality or by properties in one object missing from
221 * the other. An asymmetrical test may also be performed, which checks only that properties in the
222 * first object are present in the second object, but not the inverse.
224 * @param {Object} a First object to compare
225 * @param {Object} b Second object to compare
226 * @param {boolean} [asymmetrical] Whether to check only that b contains values from a
227 * @return {boolean} If the objects contain the same values as each other
229 oo.compare = function ( a, b, asymmetrical ) {
230 var aValue, bValue, aType, bType, k;
232 if ( a === b ) {
233 return true;
236 for ( k in a ) {
237 if ( !hasOwn.call( a, k ) ) {
238 // Support es3-shim: Without this filter, comparing [] to {} will be false in ES3
239 // because the shimmed "forEach" is enumerable and shows up in Array but not Object.
240 continue;
243 aValue = a[k];
244 bValue = b[k];
245 aType = typeof aValue;
246 bType = typeof bValue;
247 if ( aType !== bType ||
248 ( ( aType === 'string' || aType === 'number' ) && aValue !== bValue ) ||
249 ( aValue === Object( aValue ) && !oo.compare( aValue, bValue, asymmetrical ) ) ) {
250 return false;
253 // If the check is not asymmetrical, recursing with the arguments swapped will verify our result
254 return asymmetrical ? true : oo.compare( b, a, true );
258 * Create a plain deep copy of any kind of object.
260 * Copies are deep, and will either be an object or an array depending on `source`.
262 * @param {Object} source Object to copy
263 * @param {Function} [callback] Applied to leaf values before they added to the clone
264 * @return {Object} Copy of source object
266 oo.copy = function ( source, callback ) {
267 var key, sourceValue, sourceType, destination;
269 if ( typeof source.clone === 'function' ) {
270 return source.clone();
273 destination = Array.isArray( source ) ? new Array( source.length ) : {};
275 for ( key in source ) {
276 sourceValue = source[key];
277 sourceType = typeof sourceValue;
278 if ( Array.isArray( sourceValue ) ) {
279 // Array
280 destination[key] = oo.copy( sourceValue, callback );
281 } else if ( sourceValue && typeof sourceValue.clone === 'function' ) {
282 // Duck type object with custom clone method
283 destination[key] = callback ?
284 callback( sourceValue.clone() ) : sourceValue.clone();
285 } else if ( sourceValue && typeof sourceValue.cloneNode === 'function' ) {
286 // DOM Node
287 destination[key] = callback ?
288 callback( sourceValue.cloneNode( true ) ) : sourceValue.cloneNode( true );
289 } else if ( oo.isPlainObject( sourceValue ) ) {
290 // Plain objects
291 destination[key] = oo.copy( sourceValue, callback );
292 } else {
293 // Non-plain objects (incl. functions) and primitive values
294 destination[key] = callback ? callback( sourceValue ) : sourceValue;
298 return destination;
302 * Generate a hash of an object based on its name and data.
304 * Performance optimization: <http://jsperf.com/ve-gethash-201208#/toJson_fnReplacerIfAoForElse>
306 * To avoid two objects with the same values generating different hashes, we utilize the replacer
307 * argument of JSON.stringify and sort the object by key as it's being serialized. This may or may
308 * not be the fastest way to do this; we should investigate this further.
310 * Objects and arrays are hashed recursively. When hashing an object that has a .getHash()
311 * function, we call that function and use its return value rather than hashing the object
312 * ourselves. This allows classes to define custom hashing.
314 * @param {Object} val Object to generate hash for
315 * @return {string} Hash of object
317 oo.getHash = function ( val ) {
318 return JSON.stringify( val, oo.getHash.keySortReplacer );
322 * Helper function for OO.getHash which sorts objects by key.
324 * This is a callback passed into JSON.stringify.
326 * @method getHash_keySortReplacer
327 * @param {string} key Property name of value being replaced
328 * @param {Mixed} val Property value to replace
329 * @return {Mixed} Replacement value
331 oo.getHash.keySortReplacer = function ( key, val ) {
332 var normalized, keys, i, len;
333 if ( val && typeof val.getHashObject === 'function' ) {
334 // This object has its own custom hash function, use it
335 val = val.getHashObject();
337 if ( !Array.isArray( val ) && Object( val ) === val ) {
338 // Only normalize objects when the key-order is ambiguous
339 // (e.g. any object not an array).
340 normalized = {};
341 keys = Object.keys( val ).sort();
342 i = 0;
343 len = keys.length;
344 for ( ; i < len; i += 1 ) {
345 normalized[keys[i]] = val[keys[i]];
347 return normalized;
349 // Primitive values and arrays get stable hashes
350 // by default. Lets those be stringified as-is.
351 } else {
352 return val;
357 * Compute the union (duplicate-free merge) of a set of arrays.
359 * Arrays values must be convertable to object keys (strings).
361 * By building an object (with the values for keys) in parallel with
362 * the array, a new item's existence in the union can be computed faster.
364 * @param {Array...} arrays Arrays to union
365 * @return {Array} Union of the arrays
367 oo.simpleArrayUnion = function () {
368 var i, ilen, arr, j, jlen,
369 obj = {},
370 result = [];
372 for ( i = 0, ilen = arguments.length; i < ilen; i++ ) {
373 arr = arguments[i];
374 for ( j = 0, jlen = arr.length; j < jlen; j++ ) {
375 if ( !obj[ arr[j] ] ) {
376 obj[ arr[j] ] = true;
377 result.push( arr[j] );
382 return result;
386 * Combine arrays (intersection or difference).
388 * An intersection checks the item exists in 'b' while difference checks it doesn't.
390 * Arrays values must be convertable to object keys (strings).
392 * By building an object (with the values for keys) of 'b' we can
393 * compute the result faster.
395 * @private
396 * @param {Array} a First array
397 * @param {Array} b Second array
398 * @param {boolean} includeB Whether to items in 'b'
399 * @return {Array} Combination (intersection or difference) of arrays
401 function simpleArrayCombine( a, b, includeB ) {
402 var i, ilen, isInB,
403 bObj = {},
404 result = [];
406 for ( i = 0, ilen = b.length; i < ilen; i++ ) {
407 bObj[ b[i] ] = true;
410 for ( i = 0, ilen = a.length; i < ilen; i++ ) {
411 isInB = !!bObj[ a[i] ];
412 if ( isInB === includeB ) {
413 result.push( a[i] );
417 return result;
421 * Compute the intersection of two arrays (items in both arrays).
423 * Arrays values must be convertable to object keys (strings).
425 * @param {Array} a First array
426 * @param {Array} b Second array
427 * @return {Array} Intersection of arrays
429 oo.simpleArrayIntersection = function ( a, b ) {
430 return simpleArrayCombine( a, b, true );
434 * Compute the difference of two arrays (items in 'a' but not 'b').
436 * Arrays values must be convertable to object keys (strings).
438 * @param {Array} a First array
439 * @param {Array} b Second array
440 * @return {Array} Intersection of arrays
442 oo.simpleArrayDifference = function ( a, b ) {
443 return simpleArrayCombine( a, b, false );
445 /*global hasOwn, toString */
448 * Assert whether a value is a plain object or not.
450 * @param {Mixed} obj
451 * @return {boolean}
453 oo.isPlainObject = function ( obj ) {
454 /*jshint eqnull:true, eqeqeq:false */
456 // Any object or value whose internal [[Class]] property is not "[object Object]"
457 // Support IE8: Explicitly filter out DOM nodes
458 // Support IE8: Explicitly filter out Window object (needs loose comparison)
459 if ( !obj || toString.call( obj ) !== '[object Object]' || obj.nodeType || ( obj != null && obj == obj.window ) ) {
460 return false;
463 // The try/catch suppresses exceptions thrown when attempting to access
464 // the "constructor" property of certain host objects suich as window.location
465 // in Firefox < 20 (https://bugzilla.mozilla.org/814622)
466 try {
467 if ( obj.constructor &&
468 !hasOwn.call( obj.constructor.prototype, 'isPrototypeOf' ) ) {
469 return false;
471 } catch ( e ) {
472 return false;
475 return true;
478 * @class OO.EventEmitter
480 * @constructor
482 oo.EventEmitter = function OoEventEmitter() {
483 // Properties
486 * Storage of bound event handlers by event name.
488 * @property
490 this.bindings = {};
493 /* Methods */
496 * Add a listener to events of a specific event.
498 * If the callback/context are already bound to the event, they will not be bound again.
500 * @param {string} event Type of event to listen to
501 * @param {Function} callback Function to call when event occurs
502 * @param {Array} [args] Arguments to pass to listener, will be prepended to emitted arguments
503 * @param {Object} [context=null] Object to use as context for callback function or call method on
504 * @throws {Error} Listener argument is not a function or method name
505 * @chainable
507 oo.EventEmitter.prototype.on = function ( event, callback, args, context ) {
508 var i, bindings, binding;
510 // Validate callback
511 if ( typeof callback !== 'function' ) {
512 throw new Error( 'Invalid callback. Function or method name expected.' );
514 // Fallback to null context
515 if ( arguments.length < 4 ) {
516 context = null;
518 if ( this.bindings.hasOwnProperty( event ) ) {
519 // Check for duplicate callback and context for this event
520 bindings = this.bindings[event];
521 i = bindings.length;
522 while ( i-- ) {
523 binding = bindings[i];
524 if ( bindings.callback === callback && bindings.context === context ) {
525 return this;
528 } else {
529 // Auto-initialize bindings list
530 bindings = this.bindings[event] = [];
532 // Add binding
533 bindings.push( {
534 callback: callback,
535 args: args,
536 context: context
537 } );
538 return this;
542 * Adds a one-time listener to a specific event.
544 * @param {string} event Type of event to listen to
545 * @param {Function} listener Listener to call when event occurs
546 * @chainable
548 oo.EventEmitter.prototype.once = function ( event, listener ) {
549 var eventEmitter = this,
550 listenerWrapper = function () {
551 eventEmitter.off( event, listenerWrapper );
552 listener.apply( eventEmitter, Array.prototype.slice.call( arguments, 0 ) );
554 return this.on( event, listenerWrapper );
558 * Remove a specific listener from a specific event.
560 * @param {string} event Type of event to remove listener from
561 * @param {Function} [callback] Listener to remove, omit to remove all
562 * @param {Object} [context=null] Object used context for callback function or method
563 * @chainable
564 * @throws {Error} Listener argument is not a function
566 oo.EventEmitter.prototype.off = function ( event, callback, context ) {
567 var i, bindings;
569 if ( arguments.length === 1 ) {
570 // Remove all bindings for event
571 if ( event in this.bindings ) {
572 delete this.bindings[event];
574 } else {
575 if ( typeof callback !== 'function' ) {
576 throw new Error( 'Invalid callback. Function expected.' );
578 if ( !( event in this.bindings ) || !this.bindings[event].length ) {
579 // No matching bindings
580 return this;
582 // Fallback to null context
583 if ( arguments.length < 3 ) {
584 context = null;
586 // Remove matching handlers
587 bindings = this.bindings[event];
588 i = bindings.length;
589 while ( i-- ) {
590 if ( bindings[i].callback === callback && bindings[i].context === context ) {
591 bindings.splice( i, 1 );
594 // Cleanup if now empty
595 if ( bindings.length === 0 ) {
596 delete this.bindings[event];
599 return this;
603 * Emit an event.
605 * TODO: Should this be chainable? What is the usefulness of the boolean
606 * return value here?
608 * @param {string} event Type of event
609 * @param {Mixed} args First in a list of variadic arguments passed to event handler (optional)
610 * @return {boolean} If event was handled by at least one listener
612 oo.EventEmitter.prototype.emit = function ( event ) {
613 var i, len, binding, bindings, args;
615 if ( event in this.bindings ) {
616 // Slicing ensures that we don't get tripped up by event handlers that add/remove bindings
617 bindings = this.bindings[event].slice();
618 args = Array.prototype.slice.call( arguments, 1 );
619 for ( i = 0, len = bindings.length; i < len; i++ ) {
620 binding = bindings[i];
621 binding.callback.apply(
622 binding.context,
623 binding.args ? binding.args.concat( args ) : args
626 return true;
628 return false;
632 * Connect event handlers to an object.
634 * @param {Object} context Object to call methods on when events occur
635 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} methods List of
636 * event bindings keyed by event name containing either method names, functions or arrays containing
637 * method name or function followed by a list of arguments to be passed to callback before emitted
638 * arguments
639 * @chainable
641 oo.EventEmitter.prototype.connect = function ( context, methods ) {
642 var method, callback, args, event;
644 for ( event in methods ) {
645 method = methods[event];
646 // Allow providing additional args
647 if ( Array.isArray( method ) ) {
648 args = method.slice( 1 );
649 method = method[0];
650 } else {
651 args = [];
653 // Allow callback to be a method name
654 if ( typeof method === 'string' ) {
655 // Validate method
656 if ( !context[method] || typeof context[method] !== 'function' ) {
657 throw new Error( 'Method not found: ' + method );
659 // Resolve to function
660 callback = context[method];
661 } else {
662 callback = method;
664 // Add binding
665 this.on.apply( this, [ event, callback, args, context ] );
667 return this;
671 * Disconnect event handlers from an object.
673 * @param {Object} context Object to disconnect methods from
674 * @param {Object.<string,string>|Object.<string,Function>|Object.<string,Array>} [methods] List of
675 * event bindings keyed by event name containing either method names or functions
676 * @chainable
678 oo.EventEmitter.prototype.disconnect = function ( context, methods ) {
679 var i, method, callback, event, bindings;
681 if ( methods ) {
682 // Remove specific connections to the context
683 for ( event in methods ) {
684 method = methods[event];
685 if ( typeof method === 'string' ) {
686 // Validate method
687 if ( !context[method] || typeof context[method] !== 'function' ) {
688 throw new Error( 'Method not found: ' + method );
690 // Resolve to function
691 callback = context[method];
692 } else {
693 callback = method;
695 this.off( event, callback, context );
697 } else {
698 // Remove all connections to the context
699 for ( event in this.bindings ) {
700 bindings = this.bindings[event];
701 i = bindings.length;
702 while ( i-- ) {
703 if ( bindings[i].context === context ) {
704 this.off( event, bindings[i].callback, context );
710 return this;
713 * @class OO.Registry
714 * @mixins OO.EventEmitter
716 * @constructor
718 oo.Registry = function OoRegistry() {
719 // Mixin constructors
720 oo.EventEmitter.call( this );
722 // Properties
723 this.registry = {};
726 /* Inheritance */
728 oo.mixinClass( oo.Registry, oo.EventEmitter );
730 /* Events */
733 * @event register
734 * @param {string} name
735 * @param {Mixed} data
738 /* Methods */
741 * Associate one or more symbolic names with some data.
743 * Only the base name will be registered, overriding any existing entry with the same base name.
745 * @param {string|string[]} name Symbolic name or list of symbolic names
746 * @param {Mixed} data Data to associate with symbolic name
747 * @fires register
748 * @throws {Error} Name argument must be a string or array
750 oo.Registry.prototype.register = function ( name, data ) {
751 var i, len;
752 if ( typeof name === 'string' ) {
753 this.registry[name] = data;
754 this.emit( 'register', name, data );
755 } else if ( Array.isArray( name ) ) {
756 for ( i = 0, len = name.length; i < len; i++ ) {
757 this.register( name[i], data );
759 } else {
760 throw new Error( 'Name must be a string or array, cannot be a ' + typeof name );
765 * Get data for a given symbolic name.
767 * Lookups are done using the base name.
769 * @param {string} name Symbolic name
770 * @return {Mixed|undefined} Data associated with symbolic name
772 oo.Registry.prototype.lookup = function ( name ) {
773 return this.registry[name];
776 * @class OO.Factory
777 * @extends OO.Registry
779 * @constructor
781 oo.Factory = function OoFactory() {
782 oo.Factory.parent.call( this );
784 // Properties
785 this.entries = [];
788 /* Inheritance */
790 oo.inheritClass( oo.Factory, oo.Registry );
792 /* Methods */
795 * Register a constructor with the factory.
797 * Classes must have a static `name` property to be registered.
799 * function MyClass() {};
800 * OO.initClass( MyClass );
801 * // Adds a static property to the class defining a symbolic name
802 * MyClass.static.name = 'mine';
803 * // Registers class with factory, available via symbolic name 'mine'
804 * factory.register( MyClass );
806 * @param {Function} constructor Constructor to use when creating object
807 * @throws {Error} Name must be a string and must not be empty
808 * @throws {Error} Constructor must be a function
810 oo.Factory.prototype.register = function ( constructor ) {
811 var name;
813 if ( typeof constructor !== 'function' ) {
814 throw new Error( 'constructor must be a function, cannot be a ' + typeof constructor );
816 name = constructor.static && constructor.static.name;
817 if ( typeof name !== 'string' || name === '' ) {
818 throw new Error( 'Name must be a string and must not be empty' );
820 this.entries.push( name );
822 oo.Factory.parent.prototype.register.call( this, name, constructor );
826 * Create an object based on a name.
828 * Name is used to look up the constructor to use, while all additional arguments are passed to the
829 * constructor directly, so leaving one out will pass an undefined to the constructor.
831 * @param {string} name Object name
832 * @param {Mixed...} [args] Arguments to pass to the constructor
833 * @return {Object} The new object
834 * @throws {Error} Unknown object name
836 oo.Factory.prototype.create = function ( name ) {
837 var args, obj, constructor;
839 if ( !this.registry.hasOwnProperty( name ) ) {
840 throw new Error( 'No class registered by that name: ' + name );
842 constructor = this.registry[name];
844 // Convert arguments to array and shift the first argument (name) off
845 args = Array.prototype.slice.call( arguments, 1 );
847 // We can't use the "new" operator with .apply directly because apply needs a
848 // context. So instead just do what "new" does: create an object that inherits from
849 // the constructor's prototype (which also makes it an "instanceof" the constructor),
850 // then invoke the constructor with the object as context, and return it (ignoring
851 // the constructor's return value).
852 obj = Object.create( constructor.prototype );
853 constructor.apply( obj, args );
854 return obj;
856 /*jshint node:true */
857 if ( typeof module !== 'undefined' && module.exports ) {
858 module.exports = oo;
859 } else {
860 global.OO = oo;
862 }( this ) );