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
];
454 * Executes a loaded module, making it ready to use
456 * @param string module name to execute
458 function execute( module
) {
459 if ( typeof registry
[module
] === 'undefined' ) {
460 throw new Error( 'Module has not been registered yet: ' + module
);
461 } else if ( registry
[module
].state
=== 'registered' ) {
462 throw new Error( 'Module has not been requested from the server yet: ' + module
);
463 } else if ( registry
[module
].state
=== 'loading' ) {
464 throw new Error( 'Module has not completed loading yet: ' + module
);
465 } else if ( registry
[module
].state
=== 'ready' ) {
466 throw new Error( 'Module has already been loaded: ' + module
);
468 // Add style sheet to document
469 if ( typeof registry
[module
].style
=== 'string' && registry
[module
].style
.length
) {
471 .append( '<style type="text/css">' + registry
[module
].style
+ '</style>' );
472 } else if ( typeof registry
[module
].style
=== 'object'
473 && !( registry
[module
].style
instanceof Array
) )
475 for ( var media
in registry
[module
].style
) {
477 '<style type="text/css" media="' + media
+ '">' +
478 registry
[module
].style
[media
] +
483 // Add localizations to message system
484 if ( typeof registry
[module
].messages
=== 'object' ) {
485 mediaWiki
.messages
.set( registry
[module
].messages
);
489 registry
[module
].script();
490 registry
[module
].state
= 'ready';
491 // Run jobs who's dependencies have just been met
492 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
494 filter( 'ready', jobs
[j
].dependencies
),
495 jobs
[j
].dependencies
) )
497 if ( typeof jobs
[j
].ready
=== 'function' ) {
504 // Execute modules who's dependencies have just been met
505 for ( r
in registry
) {
506 if ( registry
[r
].state
== 'loaded' ) {
508 filter( ['ready'], registry
[r
].dependencies
),
509 registry
[r
].dependencies
) )
516 mediaWiki
.log( 'Exception thrown by ' + module
+ ': ' + e
.message
);
518 registry
[module
].state
= 'error';
519 // Run error callbacks of jobs affected by this condition
520 for ( var j
= 0; j
< jobs
.length
; j
++ ) {
521 if ( $.inArray( module
, jobs
[j
].dependencies
) !== -1 ) {
522 if ( typeof jobs
[j
].error
=== 'function' ) {
533 * Adds a dependencies to the queue with optional callbacks to be run
534 * when the dependencies are ready or fail
536 * @param mixed string moulde name or array of string module names
537 * @param function ready callback to execute when all dependencies are ready
538 * @param function error callback to execute when any dependency fails
540 function request( dependencies
, ready
, error
) {
541 // Allow calling by single module name
542 if ( typeof dependencies
=== 'string' ) {
543 dependencies
= [dependencies
];
544 if ( dependencies
[0] in registry
) {
545 for ( var n
= 0; n
< registry
[dependencies
[0]].dependencies
.length
; n
++ ) {
546 dependencies
[dependencies
.length
] =
547 registry
[dependencies
[0]].dependencies
[n
];
551 // Add ready and error callbacks if they were given
552 if ( arguments
.length
> 1 ) {
553 jobs
[jobs
.length
] = {
554 'dependencies': filter(
555 ['undefined', 'registered', 'loading', 'loaded'],
561 // Queue up any dependencies that are undefined or registered
562 dependencies
= filter( ['undefined', 'registered'], dependencies
);
563 for ( var n
= 0; n
< dependencies
.length
; n
++ ) {
564 if ( $.inArray( dependencies
[n
], queue
) === -1 ) {
565 queue
[queue
.length
] = dependencies
[n
];
569 mediaWiki
.loader
.work();
572 function sortQuery(o
) {
573 var sorted
= {}, key
, a
= [];
575 if ( o
.hasOwnProperty( key
) ) {
580 for ( key
= 0; key
< a
.length
; key
++ ) {
581 sorted
[a
[key
]] = o
[a
[key
]];
589 * Requests dependencies from server, loading and executing when things when ready.
591 this.work = function() {
592 // Appends a list of modules to the batch
593 for ( var q
= 0; q
< queue
.length
; q
++ ) {
594 // Only request modules which are undefined or registered
595 if ( !( queue
[q
] in registry
) || registry
[queue
[q
]].state
== 'registered' ) {
596 // Prevent duplicate entries
597 if ( $.inArray( queue
[q
], batch
) === -1 ) {
598 batch
[batch
.length
] = queue
[q
];
599 // Mark registered modules as loading
600 if ( queue
[q
] in registry
) {
601 registry
[queue
[q
]].state
= 'loading';
606 // Clean up the queue
608 // After document ready, handle the batch
609 if ( !suspended
&& batch
.length
) {
610 // Always order modules alphabetically to help reduce cache
611 // misses for otherwise identical content
613 // Build a list of request parameters
615 'skin': mediaWiki
.config
.get( 'skin' ),
616 'lang': mediaWiki
.config
.get( 'wgUserLanguage' ),
617 'debug': mediaWiki
.config
.get( 'debug' )
619 // Extend request parameters with a list of modules in the batch
623 for ( var b
= 0; b
< batch
.length
; b
++ ) {
624 var group
= registry
[batch
[b
]].group
;
625 if ( !( group
in groups
) ) {
628 groups
[group
][groups
[group
].length
] = batch
[b
];
630 for ( var group
in groups
) {
631 // Calculate the highest timestamp
633 for ( var g
= 0; g
< groups
[group
].length
; g
++ ) {
634 if ( registry
[groups
[group
][g
]].version
> version
) {
635 version
= registry
[groups
[group
][g
]].version
;
638 requests
[requests
.length
] = $.extend(
639 { 'modules': groups
[group
].join( '|' ), 'version': formatVersionNumber( version
) }, base
642 // Clear the batch - this MUST happen before we append the
643 // script element to the body or it's possible that the script
644 // will be locally cached, instantly load, and work the batch
645 // again, all before we've cleared it causing each request to
646 // include modules which are already loaded
648 // Asynchronously append a script tag to the end of the body
651 for ( var r
= 0; r
< requests
.length
; r
++ ) {
652 requests
[r
] = sortQuery( requests
[r
] );
653 // Build out the HTML
654 var src
= mediaWiki
.config
.get( 'wgLoadScript' ) + '?' + $.param( requests
[r
] );
655 html
+= '<script type="text/javascript" src="' + src
+ '"></script>';
659 // Load asynchronously after doumument ready
661 setTimeout( function() { $( 'body' ).append( request() ); }, 0 )
663 document
.write( request() );
669 * Registers a module, letting the system know about it and its
670 * dependencies. loader.js files contain calls to this function.
672 this.register = function( module
, version
, dependencies
, group
) {
673 // Allow multiple registration
674 if ( typeof module
=== 'object' ) {
675 for ( var m
= 0; m
< module
.length
; m
++ ) {
676 if ( typeof module
[m
] === 'string' ) {
677 mediaWiki
.loader
.register( module
[m
] );
678 } else if ( typeof module
[m
] === 'object' ) {
679 mediaWiki
.loader
.register
.apply( mediaWiki
.loader
, module
[m
] );
685 if ( typeof module
!== 'string' ) {
686 throw new Error( 'module must be a string, not a ' + typeof module
);
688 if ( typeof registry
[module
] !== 'undefined' ) {
689 throw new Error( 'module already implemeneted: ' + module
);
691 // List the module as registered
693 'state': 'registered',
694 'group': typeof group
=== 'string' ? group
: null,
696 'version': typeof version
!== 'undefined' ? parseInt( version
) : 0
698 if ( typeof dependencies
=== 'string' ) {
699 // Allow dependencies to be given as a single module name
700 registry
[module
].dependencies
= [dependencies
];
701 } else if ( typeof dependencies
=== 'object' || typeof dependencies
=== 'function' ) {
702 // Allow dependencies to be given as an array of module names
703 // or a function which returns an array
704 registry
[module
].dependencies
= dependencies
;
709 * Implements a module, giving the system a course of action to take
710 * upon loading. Results of a request for one or more modules contain
711 * calls to this function.
713 this.implement = function( module
, script
, style
, localization
) {
714 // Automaically register module
715 if ( typeof registry
[module
] === 'undefined' ) {
716 mediaWiki
.loader
.register( module
);
719 if ( typeof script
!== 'function' ) {
720 throw new Error( 'script must be a function, not a ' + typeof script
);
722 if ( typeof style
!== 'undefined'
723 && typeof style
!== 'string'
724 && typeof style
!== 'object' )
726 throw new Error( 'style must be a string or object, not a ' + typeof style
);
728 if ( typeof localization
!== 'undefined'
729 && typeof localization
!== 'object' )
731 throw new Error( 'localization must be an object, not a ' + typeof localization
);
733 if ( typeof registry
[module
] !== 'undefined'
734 && typeof registry
[module
].script
!== 'undefined' )
736 throw new Error( 'module already implemeneted: ' + module
);
738 // Mark module as loaded
739 registry
[module
].state
= 'loaded';
741 registry
[module
].script
= script
;
742 if ( typeof style
=== 'string'
743 || typeof style
=== 'object' && !( style
instanceof Array
) )
745 registry
[module
].style
= style
;
747 if ( typeof localization
=== 'object' ) {
748 registry
[module
].messages
= localization
;
750 // Execute or queue callback
752 filter( ['ready'], registry
[module
].dependencies
),
753 registry
[module
].dependencies
) )
762 * Executes a function as soon as one or more required modules are ready
764 * @param mixed string or array of strings of modules names the callback
765 * dependencies to be ready before
767 * @param function callback to execute when all dependencies are ready (optional)
768 * @param function callback to execute when if dependencies have a errors (optional)
770 this.using = function( dependencies
, ready
, error
) {
772 if ( typeof dependencies
!== 'object' && typeof dependencies
!== 'string' ) {
773 throw new Error( 'dependencies must be a string or an array, not a ' +
774 typeof dependencies
)
776 // Allow calling with a single dependency as a string
777 if ( typeof dependencies
=== 'string' ) {
778 dependencies
= [dependencies
];
780 // Resolve entire dependency map
781 dependencies
= resolve( dependencies
);
782 // If all dependencies are met, execute ready immediately
783 if ( compare( filter( ['ready'], dependencies
), dependencies
) ) {
784 if ( typeof ready
=== 'function' ) {
788 // If any dependencies have errors execute error immediately
789 else if ( filter( ['error'], dependencies
).length
) {
790 if ( typeof error
=== 'function' ) {
794 // Since some dependencies are not yet ready, queue up a request
796 request( dependencies
, ready
, error
);
801 * Loads an external script or one or more modules for future use
803 * @param {mixed} modules either the name of a module, array of modules,
804 * or a URL of an external script or style
805 * @param {string} type mime-type to use if calling with a URL of an
806 * external script or style; acceptable values are "text/css" and
807 * "text/javascript"; if no type is provided, text/javascript is
810 this.load = function( modules
, type
) {
812 if ( typeof modules
!== 'object' && typeof modules
!== 'string' ) {
813 throw new Error( 'dependencies must be a string or an array, not a ' +
814 typeof dependencies
)
816 // Allow calling with an external script or single dependency as a string
817 if ( typeof modules
=== 'string' ) {
818 // Support adding arbitrary external scripts
819 if ( modules
.substr( 0, 7 ) == 'http://'
820 || modules
.substr( 0, 8 ) == 'https://' )
822 if ( type
=== 'text/css' ) {
824 .append( $( '<link rel="stylesheet" type="text/css" />' )
825 .attr( 'href', modules
) );
827 } else if ( type
=== 'text/javascript' || typeof type
=== 'undefined' ) {
828 var script
= '<script type="text/javascript" src="' + modules
+ '"></script>';
830 $( 'body' ).append( script
);
832 document
.write( script
);
839 // Called with single module
842 // Resolve entire dependency map
843 modules
= resolve( modules
);
844 // If all modules are ready, nothing dependency be done
845 if ( compare( filter( ['ready'], modules
), modules
) ) {
848 // If any modules have errors return false
849 else if ( filter( ['error'], modules
).length
) {
852 // Since some modules are not yet ready, queue up a request
860 * Flushes the request queue and begin executing load requests on demand
862 this.go = function() {
864 mediaWiki
.loader
.work();
868 * Changes the state of a module
870 * @param mixed module string module name or object of module name/state pairs
871 * @param string state string state name
873 this.state = function( module
, state
) {
874 if ( typeof module
=== 'object' ) {
875 for ( var m
in module
) {
876 mediaWiki
.loader
.state( m
, module
[m
] );
880 if ( !( module
in registry
) ) {
881 mediaWiki
.loader
.register( module
);
883 registry
[module
].state
= state
;
887 * Gets the version of a module
889 * @param string module name of module to get version for
891 this.version = function( module
) {
892 if ( module
in registry
&& 'version' in registry
[module
] ) {
893 return formatVersionNumber( registry
[module
].version
);
898 /* Cache document ready status */
900 $(document
).ready( function() { ready
= true; } );
903 /* Extension points */
909 /* Auto-register from pre-loaded startup scripts */
911 if ( typeof startUp
=== 'function' ) {
916 // Alias $j to jQuery for backwards compatibility
918 window
.mw
= mediaWiki
;