5caafc3d4164432cf5cea6057d326e4b6e899c0e
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
64 * on a list of key / value pairs.
66 * @param {boolean} global Whether to get/set/exists values on the window
67 * object or a private object
69 function Map( global
) {
70 this.values
= ( global
=== true ) ? window
: {};
74 * Gets the value of a key, or a list of key/value pairs for an array of keys.
76 * If called with no arguments, all values will be returned.
78 * @param {mixed} selection Key or array of keys to get values for
79 * @param {mixed} fallback Value to use in case key(s) do not exist (optional)
81 Map
.prototype.get = function( selection
, fallback
) {
82 if ( typeof selection
=== 'object' ) {
83 selection
= $.makeArray( selection
);
85 for ( var i
= 0; i
< selection
.length
; i
++ ) {
86 results
[selection
[i
]] = this.get( selection
[i
], fallback
);
89 } else if ( typeof selection
=== 'string' ) {
90 if ( typeof this.values
[selection
] === 'undefined' ) {
91 if ( typeof fallback
!== 'undefined' ) {
96 return this.values
[selection
];
102 * Sets one or multiple key/value pairs.
104 * @param {mixed} selection Key or object of key/value pairs to set
105 * @param {mixed} value Value to set (optional, only in use when key is a string)
107 Map
.prototype.set = function( selection
, value
) {
108 if ( typeof selection
=== 'object' ) {
109 for ( var s
in selection
) {
110 this.values
[s
] = selection
[s
];
112 } else if ( typeof selection
=== 'string' && typeof value
!== 'undefined' ) {
113 this.values
[selection
] = value
;
118 * Checks if one or multiple keys exist.
120 * @param {mixed} key Key or array of keys to check
121 * @return {boolean} Existence of key(s)
123 Map
.prototype.exists = function( selection
) {
124 if ( typeof keys
=== 'object' ) {
125 for ( var s
= 0; s
< selection
.length
; s
++ ) {
126 if ( !( selection
[s
] in this.values
) ) {
132 return selection
in this.values
;
137 * Message object, similar to Message in PHP
139 function Message( map
, key
, parameters
) {
140 this.format
= 'parse';
143 this.parameters
= typeof parameters
=== 'undefined' ? [] : $.makeArray( parameters
);
147 * Appends parameters for replacement
149 * @param {mixed} args First in a list of variadic arguments to append as message parameters
151 Message
.prototype.params = function( parameters
) {
152 for ( var i
= 0; i
< parameters
.length
; i
++ ) {
153 this.parameters
[this.parameters
.length
] = parameters
[i
];
159 * Converts message object to it's string form based on the state of format
161 * @return {string} String form of message
163 Message
.prototype.toString = function() {
164 if ( !this.map
.exists( this.key
) ) {
165 // Return <key> if key does not exist
166 return '<' + this.key
+ '>';
168 var text
= this.map
.get( this.key
);
169 var parameters
= this.parameters
;
170 text
= text
.replace( /\$(\d+)/g, function( string
, match
) {
171 var index
= parseInt( match
, 10 ) - 1;
172 return index
in parameters
? parameters
[index
] : '$' + match
;
174 /* This should be fixed up when we have a parser
175 if ( this.format === 'parse' && 'language' in mediaWiki ) {
176 text = mediaWiki.language.parse( text );
183 * Changes format to parse and converts message to string
185 * @return {string} String form of parsed message
187 Message
.prototype.parse = function() {
188 this.format
= 'parse';
189 return this.toString();
193 * Changes format to plain and converts message to string
195 * @return {string} String form of plain message
197 Message
.prototype.plain = function() {
198 this.format
= 'plain';
199 return this.toString();
203 * Checks if message exists
205 * @return {string} String form of parsed message
207 Message
.prototype.exists = function() {
208 return this.map
.exists( this.key
);
215 this.options
= new Map();
221 * Dummy function which in debug mode can be replaced with a function that
222 * does something clever
224 this.log = function() { };
227 * List of configuration values
229 * In legacy mode the values this object wraps will be in the global space
231 this.config
= new Map( LEGACY_GLOBALS
);
234 * Information about the current user
236 this.user
= new User();
239 * Localization system
241 this.messages
= new Map();
246 * Gets a message object, similar to wfMessage()
248 * @param {string} key Key of message to get
249 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
252 this.message = function( key
, parameters
) {
253 // Support variadic arguments
254 if ( typeof parameters
!== 'undefined' ) {
255 parameters
= $.makeArray( arguments
);
260 return new Message( mediaWiki
.messages
, key
, parameters
);
264 * Gets a message string, similar to wfMsg()
266 * @param {string} key Key of message to get
267 * @param {mixed} params First argument in a list of variadic arguments, each a parameter for $
270 this.msg = function( key
, parameters
) {
271 return mediaWiki
.message
.apply( mediaWiki
.message
, arguments
).toString();
275 * Client-side module loader which integrates with the MediaWiki ResourceLoader
277 this.loader
= new ( function() {
279 /* Private Members */
282 * Mapping of registered modules
284 * The jquery module is pre-registered, because it must have already
285 * been provided for this object to have been built, and in debug mode
286 * jquery would have been provided through a unique loader request,
287 * making it impossible to hold back registration of jquery until after
293 * 'dependencies': ['required module', 'required module', ...], (or) function() {}
294 * 'state': 'registered', 'loading', 'loaded', 'ready', or 'error'
295 * 'script': function() {},
296 * 'style': 'css code string',
297 * 'messages': { 'key': 'value' },
298 * 'version': ############## (unix timestamp)
303 // List of modules which will be loaded as when ready
305 // List of modules to be loaded
307 // List of callback functions waiting for modules to be ready to be called
309 // Flag indicating that requests should be suspended
310 var suspended
= true;
311 // Flag inidicating that document ready has occured
314 /* Private Methods */
316 function compare( a
, b
) {
317 if ( a
.length
!= b
.length
) {
320 for ( var i
= 0; i
< b
.length
; i
++ ) {
321 if ( $.isArray( a
[i
] ) ) {
322 if ( !compare( a
[i
], b
[i
] ) ) {
326 if ( a
[i
] !== b
[i
] ) {
334 * Generates an ISO8601 "basic" string from a UNIX timestamp
336 function formatVersionNumber( timestamp
) {
337 function pad( a
, b
, c
) {
338 return [a
< 10 ? '0' + a
: a
, b
< 10 ? '0' + b
: b
, c
< 10 ? '0' + c
: c
].join( '' );
341 d
.setTime( timestamp
* 1000 );
343 pad( d
.getUTCFullYear(), d
.getUTCMonth() + 1, d
.getUTCDate() ), 'T',
344 pad( d
.getUTCHours(), d
.getUTCMinutes(), d
.getUTCSeconds() ), 'Z'
349 * Recursively resolves dependencies and detects circular references
351 function recurse( module
, resolved
, unresolved
) {
352 if ( typeof registry
[module
] === 'undefined' ) {
353 throw new Error( 'Unknown dependency: ' + module
);
355 // Resolves dynamic loader function and replaces it with its own results
356 if ( typeof registry
[module
].dependencies
=== 'function' ) {
357 registry
[module
].dependencies
= registry
[module
].dependencies();
358 // Ensures the module's dependencies are always in an array
359 if ( typeof registry
[module
].dependencies
!== 'object' ) {
360 registry
[module
].dependencies
= [registry
[module
].dependencies
];
363 // Tracks down dependencies
364 for ( var n
= 0; n
< registry
[module
].dependencies
.length
; n
++ ) {
365 if ( $.inArray( registry
[module
].dependencies
[n
], resolved
) === -1 ) {
366 if ( $.inArray( registry
[module
].dependencies
[n
], unresolved
) !== -1 ) {
368 'Circular reference detected: ' + module
+
369 ' -> ' + registry
[module
].dependencies
[n
]
372 recurse( registry
[module
].dependencies
[n
], resolved
, unresolved
);
375 resolved
[resolved
.length
] = module
;
376 unresolved
.splice( $.inArray( module
, unresolved
), 1 );
380 * Gets a list of module names that a module depends on in their proper dependency order
382 * @param mixed string module name or array of string module names
383 * @return list of dependencies
384 * @throws Error if circular reference is detected
386 function resolve( module
, resolved
, unresolved
) {
387 // Allow calling with an array of module names
388 if ( typeof module
=== 'object' ) {
390 for ( var m
= 0; m
< module
.length
; m
++ ) {
391 var dependencies
= resolve( module
[m
] );
392 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
393 modules
[modules
.length
] = dependencies
[n
];
397 } else if ( typeof module
=== 'string' ) {
398 // Undefined modules have no dependencies
399 if ( !( module
in registry
) ) {
403 recurse( module
, resolved
, [] );
406 throw new Error( 'Invalid module argument: ' + module
);
410 * Narrows a list of module names down to those matching a specific
411 * state. Possible states are 'undefined', 'registered', 'loading',
412 * 'loaded', or 'ready'
414 * @param mixed string or array of strings of module states to filter by
415 * @param array list of module names to filter (optional, all modules
416 * will be used by default)
417 * @return array list of filtered module names
419 function filter( states
, modules
) {
420 // Allow states to be given as a string
421 if ( typeof states
=== 'string' ) {
424 // If called without a list of modules, build and use a list of all modules
426 if ( typeof modules
=== 'undefined' ) {
428 for ( module
in registry
) {
429 modules
[modules
.length
] = module
;
432 // Build a list of modules which are in one of the specified states
433 for ( var s
= 0; s
< states
.length
; s
++ ) {
434 for ( var m
= 0; m
< modules
.length
; m
++ ) {
435 if ( typeof registry
[modules
[m
]] === 'undefined' ) {
436 // Module does not exist
437 if ( states
[s
] == 'undefined' ) {
439 list
[list
.length
] = modules
[m
];
442 // Module exists, check state
443 if ( registry
[modules
[m
]].state
=== states
[s
] ) {
445 list
[list
.length
] = modules
[m
];
453 this.filter_
= filter
;
456 * Executes a loaded module, making it ready to use
458 * @param string module name to execute
460 function execute( module
) {
461 if ( typeof registry
[module
] === 'undefined' ) {
462 throw new Error( 'Module has not been registered yet: ' + module
);
463 } else if ( registry
[module
].state
=== 'registered' ) {
464 throw new Error( 'Module has not been requested from the server yet: ' + module
);
465 } else if ( registry
[module
].state
=== 'loading' ) {
466 throw new Error( 'Module has not completed loading yet: ' + module
);
467 } else if ( registry
[module
].state
=== 'ready' ) {
468 throw new Error( 'Module has already been loaded: ' + module
);
470 // Add style sheet to document
471 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
473 .append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
474 } else if ( typeof registry
[module
].style
=== 'object'
475 && !( registry
[module
].style
instanceof Array
) )
477 for ( var media
in registry
[module
].style
) {
479 '<style type="text/css" media="' + media
+ '">' +
480 registry
[module
].style
[media
] +
485 // Add localizations to message system
486 if ( typeof registry
[module
].messages
=== 'object' ) {
487 mediaWiki
.messages
.set( registry
[module
].messages
);
491 registry
[module
].script();
492 registry
[module
].state
= 'ready';
493 // Run jobs who's dependencies have just been met
494 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
496 filter( 'ready', jobs
[j
].dependencies
),
497 jobs
[j
].dependencies
) )
499 if ( typeof jobs
[j
].ready
=== 'function' ) {
506 // Execute modules who's dependencies have just been met
507 for ( r
in registry
) {
508 if ( registry
[r
].state
== 'loaded' ) {
510 filter( ['ready'], registry
[r
].dependencies
),
511 registry
[r
].dependencies
) )
518 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
520 registry
[module
].state
= 'error';
521 // Run error callbacks of jobs affected by this condition
522 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
523 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
524 if ( typeof jobs
[j
].error
=== 'function' ) {
535 * Adds a dependencies to the queue with optional callbacks to be run
536 * when the dependencies are ready or fail
538 * @param mixed string moulde name or array of string module names
539 * @param function ready callback to execute when all dependencies are ready
540 * @param function error callback to execute when any dependency fails
542 function request( dependencies
, ready
, error
) {
543 // Allow calling by single module name
544 if ( typeof dependencies
=== 'string' ) {
545 dependencies
= [dependencies
];
546 if ( dependencies
[0] in registry
) {
547 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
548 dependencies
[dependencies
.length
] =
549 registry
[dependencies
[0]].dependencies
[n
];
553 // Add ready and error callbacks if they were given
554 if ( arguments
.length
> 1 ) {
555 jobs
[jobs
.length
] = {
556 'dependencies': filter(
557 ['undefined', 'registered', 'loading', 'loaded'],
563 // Queue up any dependencies that are undefined or registered
564 dependencies
= filter( ['undefined', 'registered'], dependencies
);
565 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
566 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
567 queue
[queue
.length
] = dependencies
[n
];
571 mediaWiki
.loader
.work();
574 function sortQuery(o
) {
575 var sorted
= {}, key
, a
= [];
577 if ( o
.hasOwnProperty( key
) ) {
582 for ( key
= 0; key
< a
.length
; key
++ ) {
583 sorted
[a
[key
]] = o
[a
[key
]];
591 * Requests dependencies from server, loading and executing when things when ready.
593 this.work = function() {
594 // Appends a list of modules to the batch
595 for ( var q
= 0; q
< queue
.length
; q
++ ) {
596 // Only request modules which are undefined or registered
597 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
598 // Prevent duplicate entries
599 if ( $.inArray( queue
[q
], batch
) === -1 ) {
600 batch
[batch
.length
] = queue
[q
];
601 // Mark registered modules as loading
602 if ( queue
[q
] in registry
) {
603 registry
[queue
[q
]].state
= 'loading';
608 // Clean up the queue
610 // After document ready, handle the batch
611 if ( !suspended
&& batch
.length
) {
612 // Always order modules alphabetically to help reduce cache
613 // misses for otherwise identical content
615 // Build a list of request parameters
617 'skin': mediaWiki
.config
.get( 'skin' ),
618 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
619 'debug': mediaWiki
.config
.get( 'debug' )
621 // Extend request parameters with a list of modules in the batch
625 for ( var b
= 0; b
< batch
.length
; b
++ ) {
626 var group
= registry
[batch
[b
]].group
;
627 if ( !( group
in groups
) ) {
630 groups
[group
][groups
[group
].length
] = batch
[b
];
632 for ( var group
in groups
) {
633 // Calculate the highest timestamp
635 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
636 if ( registry
[groups
[group
][g
]].version
> version
) {
637 version
= registry
[groups
[group
][g
]].version
;
640 requests
[requests
.length
] = $.extend(
641 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
644 // Clear the batch - this MUST happen before we append the
645 // script element to the body or it's possible that the script
646 // will be locally cached, instantly load, and work the batch
647 // again, all before we've cleared it causing each request to
648 // include modules which are already loaded
650 // Asynchronously append a script tag to the end of the body
653 for ( var r
= 0; r
< requests
.length
; r
++ ) {
654 requests
[r
] = sortQuery( requests
[r
] );
655 // Build out the HTML
656 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
657 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
661 // Load asynchronously after doumument ready
663 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
665 document
.write( request() );
671 * Registers a module, letting the system know about it and its
672 * dependencies. loader.js files contain calls to this function.
674 this.register = function( module
, version
, dependencies
, group
) {
675 // Allow multiple registration
676 if ( typeof module
=== 'object' ) {
677 for ( var m
= 0; m
< module
.length
; m
++ ) {
678 if ( typeof module
[m
] === 'string' ) {
679 mediaWiki
.loader
.register( module
[m
] );
680 } else if ( typeof module
[m
] === 'object' ) {
681 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
687 if ( typeof module
!== 'string' ) {
688 throw new Error( 'module must be a string, not a ' + typeof module
);
690 if ( typeof registry
[module
] !== 'undefined' ) {
691 throw new Error( 'module already implemeneted: ' + module
);
693 // List the module as registered
695 'state': 'registered',
696 'group': typeof group
=== 'string' ? group
: null,
698 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
700 if ( typeof dependencies
=== 'string' ) {
701 // Allow dependencies to be given as a single module name
702 registry
[module
].dependencies
= [dependencies
];
703 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
704 // Allow dependencies to be given as an array of module names
705 // or a function which returns an array
706 registry
[module
].dependencies
= dependencies
;
711 * Implements a module, giving the system a course of action to take
712 * upon loading. Results of a request for one or more modules contain
713 * calls to this function.
715 this.implement = function( module
, script
, style
, localization
) {
716 // Automaically register module
717 if ( typeof registry
[module
] === 'undefined' ) {
718 mediaWiki
.loader
.register( module
);
721 if ( typeof script
!== 'function' ) {
722 throw new Error( 'script must be a function, not a ' + typeof script
);
724 if ( typeof style
!== 'undefined'
725 && typeof style
!== 'string'
726 && typeof style
!== 'object' )
728 throw new Error( 'style must be a string or object, not a ' + typeof style
);
730 if ( typeof localization
!== 'undefined'
731 && typeof localization
!== 'object' )
733 throw new Error( 'localization must be an object, not a ' + typeof localization
);
735 if ( typeof registry
[module
] !== 'undefined'
736 && typeof registry
[module
].script
!== 'undefined' )
738 throw new Error( 'module already implemeneted: ' + module
);
740 // Mark module as loaded
741 registry
[module
].state
= 'loaded';
743 registry
[module
].script
= script
;
744 if ( typeof style
=== 'string'
745 || typeof style
=== 'object' && !( style
instanceof Array
) )
747 registry
[module
].style
= style
;
749 if ( typeof localization
=== 'object' ) {
750 registry
[module
].messages
= localization
;
752 // Execute or queue callback
754 filter( ['ready'], registry
[module
].dependencies
),
755 registry
[module
].dependencies
) )
764 * Executes a function as soon as one or more required modules are ready
766 * @param mixed string or array of strings of modules names the callback
767 * dependencies to be ready before
769 * @param function callback to execute when all dependencies are ready (optional)
770 * @param function callback to execute when if dependencies have a errors (optional)
772 this.using = function( dependencies
, ready
, error
) {
774 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
775 throw new Error( 'dependencies must be a string or an array, not a ' +
776 typeof dependencies
)
778 // Allow calling with a single dependency as a string
779 if ( typeof dependencies
=== 'string' ) {
780 dependencies
= [dependencies
];
782 // Resolve entire dependency map
783 dependencies
= resolve( dependencies
);
784 // If all dependencies are met, execute ready immediately
785 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
786 if ( typeof ready
=== 'function' ) {
790 // If any dependencies have errors execute error immediately
791 else if ( filter( ['error'], dependencies
).length
) {
792 if ( typeof error
=== 'function' ) {
796 // Since some dependencies are not yet ready, queue up a request
798 request( dependencies
, ready
, error
);
803 * Loads an external script or one or more modules for future use
805 * @param {mixed} modules either the name of a module, array of modules,
806 * or a URL of an external script or style
807 * @param {string} type mime-type to use if calling with a URL of an
808 * external script or style; acceptable values are "text/css" and
809 * "text/javascript"; if no type is provided, text/javascript is
812 this.load = function( modules
, type
) {
814 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
815 throw new Error( 'dependencies must be a string or an array, not a ' +
816 typeof dependencies
)
818 // Allow calling with an external script or single dependency as a string
819 if ( typeof modules
=== 'string' ) {
820 // Support adding arbitrary external scripts
821 if ( modules
.substr( 0, 7 ) == 'http://'
822 || modules
.substr( 0, 8 ) == 'https://' )
824 if ( type
=== 'text/css' ) {
826 .append( $( '<link rel="stylesheet" type="text/css" />' )
827 .attr( 'href', modules
) );
829 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
830 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
832 $( 'body' ).append( script
);
834 document
.write( script
);
841 // Called with single module
844 // Resolve entire dependency map
845 modules
= resolve( modules
);
846 // If all modules are ready, nothing dependency be done
847 if ( compare( filter( ['ready'], modules
), modules
) ) {
850 // If any modules have errors return false
851 else if ( filter( ['error'], modules
).length
) {
854 // Since some modules are not yet ready, queue up a request
862 * Flushes the request queue and begin executing load requests on demand
864 this.go = function() {
866 mediaWiki
.loader
.work();
870 * Changes the state of a module
872 * @param mixed module string module name or object of module name/state pairs
873 * @param string state string state name
875 this.state = function( module
, state
) {
876 if ( typeof module
=== 'object' ) {
877 for ( var m
in module
) {
878 mediaWiki
.loader
.state( m
, module
[m
] );
882 if ( !( module
in registry
) ) {
883 mediaWiki
.loader
.register( module
);
885 registry
[module
].state
= state
;
889 * Gets the version of a module
891 * @param string module name of module to get version for
893 this.version = function( module
) {
894 if ( module
in registry
&& 'version' in registry
[module
] ) {
895 return formatVersionNumber( registry
[module
].version
);
900 /* Cache document ready status */
902 $(document
).ready( function() { ready
= true; } );
905 /* Extension points */
911 /* Auto-register from pre-loaded startup scripts */
913 if ( typeof startUp
=== 'function' ) {
918 // Alias $j to jQuery for backwards compatibility
920 window
.mw
= mediaWiki
;