71daa00e6bcdf6eab0e483720e05d82f8023b00c
2 * JavaScript backwards-compatibility and support
5 // Implementation of string trimming functionality introduced natively in JavaScript 1.8.1
6 if ( typeof String
.prototype.trim
=== 'undefined' ) {
7 // Add removing trailing and leading whitespace functionality cross-browser
8 // See also: http://blog.stevenlevithan.com/archives/faster-trim-javascript
9 String
.prototype.trim = function() {
10 return this.replace( /^\s+|\s+$/g, '' );
13 if ( typeof String
.prototype.trimLeft
=== 'undefined' ) {
14 String
.prototype.trimLeft = function() {
15 return this.replace( /^\s\s*/, "" );
18 if ( typeof String
.prototype.trimRight
=== 'undefined' ) {
19 String
.prototype.trimRight = function() {
20 return this.replace(/\s\s*$/, "");
25 * Prototype enhancements
28 // Capitalize the first character of the given string
29 if ( typeof String
.prototype.ucFirst
=== 'undefined' ) {
30 String
.prototype.ucFirst = function() {
31 return this.substr(0, 1).toUpperCase() + this.substr(1, this.length
);
35 // Escape all RegExp special characters such that the result can be safely used
36 // in a RegExp as a literal.
37 if ( typeof String
.prototype.escapeRE
=== 'undefined' ) {
38 String
.prototype.escapeRE = function() {
39 return this.replace (/([\\{}()|.?*+^$\[\]])/g, "\\$1");
44 * Core MediaWiki JavaScript Library
48 window
.mediaWiki
= new ( function( $ ) {
52 // This will not change until we are 100% ready to turn off legacy globals
53 var LEGACY_GLOBALS
= true;
57 // List of messages that have been requested to be loaded
58 var messageQueue
= {};
63 * An object which allows single and multiple get/set/exists functionality on a list of key / value pairs.
65 * @param {boolean} global Whether to get/set/exists values on the window object or a private object
67 function Map( global
) {
68 this.values
= ( global
=== true ) ? window
: {};
72 * Gets the value of a key, or a list of key/value pairs for an array of keys.
74 * If called with no arguments, all values will be returned.
76 * @param {mixed} selection Key or array of keys to get values for
77 * @param {mixed} fallback Value to use in case key(s) do not exist (optional)
79 Map
.prototype.get = function( selection
, fallback
) {
80 if ( typeof selection
=== 'object' ) {
81 selection
= $.makeArray( selection
);
83 for ( var i
= 0; i
< selection
.length
; i
++ ) {
84 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
87 } else if ( typeof selection
=== 'string' ) {
88 if ( typeof this.values
[selection
] === 'undefined' ) {
89 if ( typeof fallback
!== 'undefined' ) {
94 return this.values
[selection
];
100 * Sets one or multiple key/value pairs.
102 * @param {mixed} selection Key or object of key/value pairs to set
103 * @param {mixed} value Value to set (optional, only in use when key is a string)
105 Map
.prototype.set = function( selection
, value
) {
106 if ( typeof selection
=== 'object' ) {
107 for ( var s
in selection
) {
108 this.values
[s
] = selection
[s
];
110 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
111 this.values
[selection
] = value
;
116 * Checks if one or multiple keys exist.
118 * @param {mixed} key Key or array of keys to check
119 * @return {boolean} Existence of key(s)
121 Map
.prototype.exists = function( selection
) {
122 if ( typeof keys
=== 'object' ) {
123 for ( var s
= 0; s
< selection
.length
; s
++ ) {
124 if ( !( selection
[s
] in this.values
) ) {
130 return selection
in this.values
;
135 * Message object, similar to Message in PHP
137 function Message( map
, key
, parameters
) {
138 this.format
= 'parse';
141 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
145 * Appends parameters for replacement
147 * @param {mixed} args First in a list of variadic arguments to append as message parameters
149 Message
.prototype.params = function( parameters
) {
150 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
151 this.parameters
[this.parameters
.length
] = parameters
[i
];
157 * Converts message object to it's string form based on the state of format
159 * @return {string} String form of message
161 Message
.prototype.toString = function() {
162 if ( !this.map
.exists( this.key
) ) {
163 // Return <key> if key does not exist
164 return '<' + this.key
+ '>';
166 var text
= this.map
.get( this.key
);
167 var parameters
= this.parameters
;
168 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
169 var index
= parseInt( match
, 10 ) - 1;
170 return index
in parameters
? parameters
[index
] : '$' + match
;
172 /* This should be fixed up when we have a parser
173 if ( this.format === 'parse' && 'language' in mediaWiki ) {
174 text = mediaWiki.language.parse( text );
181 * Changes format to parse and converts message to string
183 * @return {string} String form of parsed message
185 Message
.prototype.parse = function() {
186 this.format
= 'parse';
187 return this.toString();
191 * Changes format to plain and converts message to string
193 * @return {string} String form of plain message
195 Message
.prototype.plain = function() {
196 this.format
= 'plain';
197 return this.toString();
201 * Checks if message exists
203 * @return {string} String form of parsed message
205 Message
.prototype.exists = function() {
206 return this.map
.exists( this.key
);
213 this.options
= new Map();
219 * Dummy function which in debug mode can be replaced with a function that does something clever
221 this.log = function() { };
224 * List of configuration values
226 * In legacy mode the values this object wraps will be in the global space
228 this.config
= new Map( LEGACY_GLOBALS
);
231 * Information about the current user
233 this.user
= new User();
236 * Localization system
238 this.messages
= new Map();
243 * Gets a message object, similar to wfMessage()
245 * @param {string} key Key of message to get
246 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
249 this.message = function( key
, parameters
) {
250 // Support variadic arguments
251 if ( typeof parameters
!== 'undefined' ) {
252 parameters
= $.makeArray( arguments
);
257 return new Message( mediaWiki
.messages
, key
, parameters
);
261 * Gets a message string, similar to wfMsg()
263 * @param {string} key Key of message to get
264 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
267 this.msg = function( key
, parameters
) {
268 return mediaWiki
.message
.apply( mediaWiki
.message
, arguments
).toString();
272 * Client-side module loader which integrates with the MediaWiki ResourceLoader
274 this.loader
= new ( function() {
276 /* Private Members */
279 * Mapping of registered modules
281 * The jquery module is pre-registered, because it must have already been provided for this object to have
282 * been built, and in debug mode jquery would have been provided through a unique loader request, making it
283 * impossible to hold back registration of jquery until after mediawiki.
288 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
289 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
290 * 'script': function() {},
291 * 'style': 'css code string',
292 * 'messages': { 'key': 'value' },
293 * 'version': ############## (unix timestamp)
298 // List of modules which will be loaded as when ready
300 // List of modules to be loaded
302 // List of callback functions waiting for modules to be ready to be called
304 // Flag indicating that requests should be suspended
305 var suspended
= true;
306 // Flag inidicating that document ready has occured
309 /* Private Methods */
311 function compare( a
, b
) {
312 if ( a
.length
!= b
.length
) {
315 for ( var i
= 0; i
< b
.length
; i
++ ) {
316 if ( $.isArray( a
[i
] ) ) {
317 if ( !compare( a
[i
], b
[i
] ) ) {
321 if ( a
[i
] !== b
[i
] ) {
329 * Generates an ISO8601 "basic" string from a UNIX timestamp
331 function formatVersionNumber( timestamp
) {
332 function pad( a
, b
, c
) {
333 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
336 d
.setTime( timestamp
* 1000 );
338 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
339 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
344 * Recursively resolves dependencies and detects circular references
346 function recurse( module
, resolved
, unresolved
) {
347 if ( typeof registry
[module
] === 'undefined' ) {
348 throw new Error( 'Unknown dependency: ' + module
);
350 // Resolves dynamic loader function and replaces it with it's own results
351 if ( typeof registry
[module
].dependencies
=== 'function' ) {
352 registry
[module
].dependencies
= registry
[module
].dependencies();
353 // Ensures the module's dependencies are always in an array
354 if ( typeof registry
[module
].dependencies
!== 'object' ) {
355 registry
[module
].dependencies
= [registry
[module
].dependencies
];
358 // Tracks down dependencies
359 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
360 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
361 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
363 'Circular reference detected: ' + module
+ ' -> ' + registry
[module
].dependencies
[n
]
366 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
369 resolved
[resolved
.length
] = module
;
370 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
374 * Gets a list of modules names that a module dependencies in their proper dependency order
376 * @param mixed string module name or array of string module names
377 * @return list of dependencies
378 * @throws Error if circular reference is detected
380 function resolve( module
, resolved
, unresolved
) {
381 // Allow calling with an array of module names
382 if ( typeof module
=== 'object' ) {
384 for ( var m
= 0; m
< module
.length
; m
++ ) {
385 var dependencies
= resolve( module
[m
] );
386 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
387 modules
[modules
.length
] = dependencies
[n
];
391 } else if ( typeof module
=== 'string' ) {
392 // Undefined modules have no dependencies
393 if ( !( module
in registry
) ) {
397 recurse( module
, resolved
, [] );
400 throw new Error( 'Invalid module argument: ' + module
);
404 * Narrows a list of module names down to those matching a specific state. Possible states are 'undefined',
405 * 'registered', 'loading', 'loaded', or 'ready'
407 * @param mixed string or array of strings of module states to filter by
408 * @param array list of module names to filter (optional, all modules will be used by default)
409 * @return array list of filtered module names
411 function filter( states
, modules
) {
412 // Allow states to be given as a string
413 if ( typeof states
=== 'string' ) {
416 // If called without a list of modules, build and use a list of all modules
418 if ( typeof modules
=== 'undefined' ) {
420 for ( module
in registry
) {
421 modules
[modules
.length
] = module
;
424 // Build a list of modules which are in one of the specified states
425 for ( var s
= 0; s
< states
.length
; s
++ ) {
426 for ( var m
= 0; m
< modules
.length
; m
++ ) {
428 ( states
[s
] == 'undefined' && typeof registry
[modules
[m
]] === 'undefined' ) ||
429 ( typeof registry
[modules
[m
]] === 'object' && registry
[modules
[m
]].state
=== states
[s
] )
431 list
[list
.length
] = modules
[m
];
439 * Executes a loaded module, making it ready to use
441 * @param string module name to execute
443 function execute( module
) {
444 if ( typeof registry
[module
] === 'undefined' ) {
445 throw new Error( 'Module has not been registered yet: ' + module
);
446 } else if ( registry
[module
].state
=== 'registered' ) {
447 throw new Error( 'Module has not been requested from the server yet: ' + module
);
448 } else if ( registry
[module
].state
=== 'loading' ) {
449 throw new Error( 'Module has not completed loading yet: ' + module
);
450 } else if ( registry
[module
].state
=== 'ready' ) {
451 throw new Error( 'Module has already been loaded: ' + module
);
453 // Add style sheet to document
454 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
455 $( 'head' ).append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
456 } else if ( typeof registry
[module
].style
=== 'object' && !( registry
[module
].style
instanceof Array
) ) {
457 for ( var media
in registry
[module
].style
) {
459 '<style type="text/css" media="' + media
+ '">' + registry
[module
].style
[media
] + '</style>'
463 // Add localizations to message system
464 if ( typeof registry
[module
].messages
=== 'object' ) {
465 mediaWiki
.messages
.set( registry
[module
].messages
);
469 registry
[module
].script();
470 registry
[module
].state
= 'ready';
471 // Run jobs who's dependencies have just been met
472 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
473 if ( compare( filter( 'ready', jobs
[j
].dependencies
), jobs
[j
].dependencies
) ) {
474 if ( typeof jobs
[j
].ready
=== 'function' ) {
481 // Execute modules who's dependencies have just been met
482 for ( r
in registry
) {
483 if ( registry
[r
].state
== 'loaded' ) {
484 if ( compare( filter( ['ready'], registry
[r
].dependencies
), registry
[r
].dependencies
) ) {
490 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
492 registry
[module
].state
= 'error';
493 // Run error callbacks of jobs affected by this condition
494 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
495 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
496 if ( typeof jobs
[j
].error
=== 'function' ) {
507 * Adds a dependencies to the queue with optional callbacks to be run when the dependencies are ready or fail
509 * @param mixed string moulde name or array of string module names
510 * @param function ready callback to execute when all dependencies are ready
511 * @param function error callback to execute when any dependency fails
513 function request( dependencies
, ready
, error
) {
514 // Allow calling by single module name
515 if ( typeof dependencies
=== 'string' ) {
516 dependencies
= [dependencies
];
517 if ( dependencies
[0] in registry
) {
518 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
519 dependencies
[dependencies
.length
] = registry
[dependencies
[0]].dependencies
[n
];
523 // Add ready and error callbacks if they were given
524 if ( arguments
.length
> 1 ) {
525 jobs
[jobs
.length
] = {
526 'dependencies': filter( ['undefined', 'registered', 'loading', 'loaded'], dependencies
),
531 // Queue up any dependencies that are undefined or registered
532 dependencies
= filter( ['undefined', 'registered'], dependencies
);
533 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
534 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
535 queue
[queue
.length
] = dependencies
[n
];
539 mediaWiki
.loader
.work();
542 function sortQuery(o
) {
543 var sorted
= {}, key
, a
= [];
545 if ( o
.hasOwnProperty( key
) ) {
550 for ( key
= 0; key
< a
.length
; key
++ ) {
551 sorted
[a
[key
]] = o
[a
[key
]];
559 * Requests dependencies from server, loading and executing when things when ready.
561 this.work = function() {
562 // Appends a list of modules to the batch
563 for ( var q
= 0; q
< queue
.length
; q
++ ) {
564 // Only request modules which are undefined or registered
565 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
566 // Prevent duplicate entries
567 if ( $.inArray( queue
[q
], batch
) === -1 ) {
568 batch
[batch
.length
] = queue
[q
];
569 // Mark registered modules as loading
570 if ( queue
[q
] in registry
) {
571 registry
[queue
[q
]].state
= 'loading';
576 // Clean up the queue
578 // After document ready, handle the batch
579 if ( !suspended
&& batch
.length
) {
580 // Always order modules alphabetically to help reduce cache misses for otherwise identical content
582 // Build a list of request parameters
584 'skin': mediaWiki
.config
.get( 'skin' ),
585 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
586 'debug': mediaWiki
.config
.get( 'debug' )
588 // Extend request parameters with a list of modules in the batch
592 for ( var b
= 0; b
< batch
.length
; b
++ ) {
593 var group
= registry
[batch
[b
]].group
;
594 if ( !( group
in groups
) ) {
597 groups
[group
][groups
[group
].length
] = batch
[b
];
599 for ( var group
in groups
) {
600 // Calculate the highest timestamp
602 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
603 if ( registry
[groups
[group
][g
]].version
> version
) {
604 version
= registry
[groups
[group
][g
]].version
;
607 requests
[requests
.length
] = $.extend(
608 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
611 // Clear the batch - this MUST happen before we append the script element to the body or it's
612 // possible that the script will be locally cached, instantly load, and work the batch again,
613 // all before we've cleared it causing each request to include modules which are already loaded
615 // Asynchronously append a script tag to the end of the body
618 for ( var r
= 0; r
< requests
.length
; r
++ ) {
619 requests
[r
] = sortQuery( requests
[r
] );
620 // Build out the HTML
621 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
622 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
626 // Load asynchronously after doumument ready
628 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
630 document
.write( request() );
636 * Registers a module, letting the system know about it and it's dependencies. loader.js files contain calls
639 this.register = function( module
, version
, dependencies
, group
) {
640 // Allow multiple registration
641 if ( typeof module
=== 'object' ) {
642 for ( var m
= 0; m
< module
.length
; m
++ ) {
643 if ( typeof module
[m
] === 'string' ) {
644 mediaWiki
.loader
.register( module
[m
] );
645 } else if ( typeof module
[m
] === 'object' ) {
646 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
652 if ( typeof module
!== 'string' ) {
653 throw new Error( 'module must be a string, not a ' + typeof module
);
655 if ( typeof registry
[module
] !== 'undefined' ) {
656 throw new Error( 'module already implemeneted: ' + module
);
658 // List the module as registered
660 'state': 'registered',
661 'group': typeof group
=== 'string' ? group
: null,
663 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
665 if ( typeof dependencies
=== 'string' ) {
666 // Allow dependencies to be given as a single module name
667 registry
[module
].dependencies
= [dependencies
];
668 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
669 // Allow dependencies to be given as an array of module names or a function which returns an array
670 registry
[module
].dependencies
= dependencies
;
675 * Implements a module, giving the system a course of action to take upon loading. Results of a request for
676 * one or more modules contain calls to this function.
678 this.implement = function( module
, script
, style
, localization
) {
679 // Automaically register module
680 if ( typeof registry
[module
] === 'undefined' ) {
681 mediaWiki
.loader
.register( module
);
684 if ( typeof script
!== 'function' ) {
685 throw new Error( 'script must be a function, not a ' + typeof script
);
687 if ( typeof style
!== 'undefined' && typeof style
!== 'string' && typeof style
!== 'object' ) {
688 throw new Error( 'style must be a string or object, not a ' + typeof style
);
690 if ( typeof localization
!== 'undefined' && typeof localization
!== 'object' ) {
691 throw new Error( 'localization must be an object, not a ' + typeof localization
);
693 if ( typeof registry
[module
] !== 'undefined' && typeof registry
[module
].script
!== 'undefined' ) {
694 throw new Error( 'module already implemeneted: ' + module
);
696 // Mark module as loaded
697 registry
[module
].state
= 'loaded';
699 registry
[module
].script
= script
;
700 if ( typeof style
=== 'string' || typeof style
=== 'object' && !( style
instanceof Array
) ) {
701 registry
[module
].style
= style
;
703 if ( typeof localization
=== 'object' ) {
704 registry
[module
].messages
= localization
;
706 // Execute or queue callback
707 if ( compare( filter( ['ready'], registry
[module
].dependencies
), registry
[module
].dependencies
) ) {
715 * Executes a function as soon as one or more required modules are ready
717 * @param mixed string or array of strings of modules names the callback dependencies to be ready before
719 * @param function callback to execute when all dependencies are ready (optional)
720 * @param function callback to execute when if dependencies have a errors (optional)
722 this.using = function( dependencies
, ready
, error
) {
724 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
725 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
727 // Allow calling with a single dependency as a string
728 if ( typeof dependencies
=== 'string' ) {
729 dependencies
= [dependencies
];
731 // Resolve entire dependency map
732 dependencies
= resolve( dependencies
);
733 // If all dependencies are met, execute ready immediately
734 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
735 if ( typeof ready
=== 'function' ) {
739 // If any dependencies have errors execute error immediately
740 else if ( filter( ['error'], dependencies
).length
) {
741 if ( typeof error
=== 'function' ) {
745 // Since some dependencies are not yet ready, queue up a request
747 request( dependencies
, ready
, error
);
752 * Loads an external script or one or more modules for future use
754 * @param {mixed} modules either the name of a module, array of modules, or a URL of an external script or style
755 * @param {string} type mime-type to use if calling with a URL of an external script or style; acceptable values
756 * are "text/css" and "text/javascript"; if no type is provided, text/javascript is assumed
758 this.load = function( modules
, type
) {
760 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
761 throw new Error( 'dependencies must be a string or an array, not a ' + typeof dependencies
)
763 // Allow calling with an external script or single dependency as a string
764 if ( typeof modules
=== 'string' ) {
765 // Support adding arbitrary external scripts
766 if ( modules
.substr( 0, 7 ) == 'http://' || modules
.substr( 0, 8 ) == 'https://' ) {
767 if ( type
=== 'text/css' ) {
768 $( 'head' ).append( $( '<link rel="stylesheet" type="text/css" />' ).attr( 'href', modules
) );
770 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
771 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
773 $( 'body' ).append( script
);
775 document
.write( script
);
782 // Called with single module
785 // Resolve entire dependency map
786 modules
= resolve( modules
);
787 // If all modules are ready, nothing dependency be done
788 if ( compare( filter( ['ready'], modules
), modules
) ) {
791 // If any modules have errors return false
792 else if ( filter( ['error'], modules
).length
) {
795 // Since some modules are not yet ready, queue up a request
803 * Flushes the request queue and begin executing load requests on demand
805 this.go = function() {
807 mediaWiki
.loader
.work();
811 * Changes the state of a module
813 * @param mixed module string module name or object of module name/state pairs
814 * @param string state string state name
816 this.state = function( module
, state
) {
817 if ( typeof module
=== 'object' ) {
818 for ( var m
in module
) {
819 mediaWiki
.loader
.state( m
, module
[m
] );
823 if ( !( module
in registry
) ) {
824 mediaWiki
.loader
.register( module
);
826 registry
[module
].state
= state
;
830 * Gets the version of a module
832 * @param string module name of module to get version for
834 this.version = function( module
) {
835 if ( module
in registry
&& 'version' in registry
[module
] ) {
836 return formatVersionNumber( registry
[module
].version
);
841 /* Cache document ready status */
843 $(document
).ready( function() { ready
= true; } );
846 /* Extension points */
852 /* Auto-register from pre-loaded startup scripts */
854 if ( typeof startUp
=== 'function' ) {
859 // Alias $j to jQuery for backwards compatibility
861 window
.mw
= mediaWiki
;