[mw.loader] Refactor addInlineCSS's logic, fixing various bugs
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.js
1 /*
2 * Core MediaWiki JavaScript Library
3 */
4
5 var mw = ( function ( $, undefined ) {
6 "use strict";
7
8 /* Private Members */
9
10 var hasOwn = Object.prototype.hasOwnProperty;
11 /* Object constructors */
12
13 /**
14 * Map
15 *
16 * Creates an object that can be read from or written to from prototype functions
17 * that allow both single and multiple variables at once.
18 *
19 * @param global boolean Whether to store the values in the global window
20 * object or a exclusively in the object property 'values'.
21 * @return Map
22 */
23 function Map( global ) {
24 this.values = global === true ? window : {};
25 return this;
26 }
27
28 Map.prototype = {
29 /**
30 * Get the value of one or multiple a keys.
31 *
32 * If called with no arguments, all values will be returned.
33 *
34 * @param selection mixed String key or array of keys to get values for.
35 * @param fallback mixed Value to use in case key(s) do not exist (optional).
36 * @return mixed If selection was a string returns the value or null,
37 * If selection was an array, returns an object of key/values (value is null if not found),
38 * If selection was not passed or invalid, will return the 'values' object member (be careful as
39 * objects are always passed by reference in JavaScript!).
40 * @return Values as a string or object, null if invalid/inexistant.
41 */
42 get: function ( selection, fallback ) {
43 var results, i;
44
45 if ( $.isArray( selection ) ) {
46 selection = $.makeArray( selection );
47 results = {};
48 for ( i = 0; i < selection.length; i += 1 ) {
49 results[selection[i]] = this.get( selection[i], fallback );
50 }
51 return results;
52 } else if ( typeof selection === 'string' ) {
53 if ( this.values[selection] === undefined ) {
54 if ( fallback !== undefined ) {
55 return fallback;
56 }
57 return null;
58 }
59 return this.values[selection];
60 }
61 if ( selection === undefined ) {
62 return this.values;
63 } else {
64 return null; // invalid selection key
65 }
66 },
67
68 /**
69 * Sets one or multiple key/value pairs.
70 *
71 * @param selection {mixed} String key or array of keys to set values for.
72 * @param value {mixed} Value to set (optional, only in use when key is a string)
73 * @return {Boolean} This returns true on success, false on failure.
74 */
75 set: function ( selection, value ) {
76 var s;
77
78 if ( $.isPlainObject( selection ) ) {
79 for ( s in selection ) {
80 this.values[s] = selection[s];
81 }
82 return true;
83 } else if ( typeof selection === 'string' && value !== undefined ) {
84 this.values[selection] = value;
85 return true;
86 }
87 return false;
88 },
89
90 /**
91 * Checks if one or multiple keys exist.
92 *
93 * @param selection {mixed} String key or array of keys to check
94 * @return {Boolean} Existence of key(s)
95 */
96 exists: function ( selection ) {
97 var s;
98
99 if ( $.isArray( selection ) ) {
100 for ( s = 0; s < selection.length; s += 1 ) {
101 if ( this.values[selection[s]] === undefined ) {
102 return false;
103 }
104 }
105 return true;
106 } else {
107 return this.values[selection] !== undefined;
108 }
109 }
110 };
111
112 /**
113 * Message
114 *
115 * Object constructor for messages,
116 * similar to the Message class in MediaWiki PHP.
117 *
118 * @param map Map Instance of mw.Map
119 * @param key String
120 * @param parameters Array
121 * @return Message
122 */
123 function Message( map, key, parameters ) {
124 this.format = 'plain';
125 this.map = map;
126 this.key = key;
127 this.parameters = parameters === undefined ? [] : $.makeArray( parameters );
128 return this;
129 }
130
131 Message.prototype = {
132 /**
133 * Simple message parser, does $N replacement and nothing else.
134 * This may be overridden to provide a more complex message parser.
135 *
136 * This function will not be called for nonexistent messages.
137 */
138 parser: function() {
139 var parameters = this.parameters;
140 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
141 var index = parseInt( match, 10 ) - 1;
142 return parameters[index] !== undefined ? parameters[index] : '$' + match;
143 } );
144 },
145
146 /**
147 * Appends (does not replace) parameters for replacement to the .parameters property.
148 *
149 * @param parameters Array
150 * @return Message
151 */
152 params: function ( parameters ) {
153 var i;
154 for ( i = 0; i < parameters.length; i += 1 ) {
155 this.parameters.push( parameters[i] );
156 }
157 return this;
158 },
159
160 /**
161 * Converts message object to it's string form based on the state of format.
162 *
163 * @return string Message as a string in the current form or <key> if key does not exist.
164 */
165 toString: function() {
166 var text;
167
168 if ( !this.exists() ) {
169 // Use <key> as text if key does not exist
170 if ( this.format !== 'plain' ) {
171 // format 'escape' and 'parse' need to have the brackets and key html escaped
172 return mw.html.escape( '<' + this.key + '>' );
173 }
174 return '<' + this.key + '>';
175 }
176
177 if ( this.format === 'plain' ) {
178 // @todo FIXME: Although not applicable to core Message,
179 // Plugins like jQueryMsg should be able to distinguish
180 // between 'plain' (only variable replacement and plural/gender)
181 // and actually parsing wikitext to HTML.
182 text = this.parser();
183 }
184
185 if ( this.format === 'escaped' ) {
186 text = this.parser();
187 text = mw.html.escape( text );
188 }
189
190 if ( this.format === 'parse' ) {
191 text = this.parser();
192 }
193
194 return text;
195 },
196
197 /**
198 * Changes format to parse and converts message to string
199 *
200 * @return {string} String form of parsed message
201 */
202 parse: function() {
203 this.format = 'parse';
204 return this.toString();
205 },
206
207 /**
208 * Changes format to plain and converts message to string
209 *
210 * @return {string} String form of plain message
211 */
212 plain: function() {
213 this.format = 'plain';
214 return this.toString();
215 },
216
217 /**
218 * Changes the format to html escaped and converts message to string
219 *
220 * @return {string} String form of html escaped message
221 */
222 escaped: function() {
223 this.format = 'escaped';
224 return this.toString();
225 },
226
227 /**
228 * Checks if message exists
229 *
230 * @return {string} String form of parsed message
231 */
232 exists: function() {
233 return this.map.exists( this.key );
234 }
235 };
236
237 return {
238 /* Public Members */
239
240 /**
241 * Dummy function which in debug mode can be replaced with a function that
242 * emulates console.log in console-less environments.
243 */
244 log: function() { },
245
246 /**
247 * @var constructor Make the Map constructor publicly available.
248 */
249 Map: Map,
250
251 /**
252 * @var constructor Make the Message constructor publicly available.
253 */
254 Message: Message,
255
256 /**
257 * List of configuration values
258 *
259 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
260 * If $wgLegacyJavaScriptGlobals is true, this Map will have its values
261 * in the global window object.
262 */
263 config: null,
264
265 /**
266 * @var object
267 *
268 * Empty object that plugins can be installed in.
269 */
270 libs: {},
271
272 /* Extension points */
273
274 legacy: {},
275
276 /**
277 * Localization system
278 */
279 messages: new Map(),
280
281 /* Public Methods */
282
283 /**
284 * Gets a message object, similar to wfMessage()
285 *
286 * @param key string Key of message to get
287 * @param parameter_1 mixed First argument in a list of variadic arguments,
288 * each a parameter for $N replacement in messages.
289 * @return Message
290 */
291 message: function ( key, parameter_1 /* [, parameter_2] */ ) {
292 var parameters;
293 // Support variadic arguments
294 if ( parameter_1 !== undefined ) {
295 parameters = $.makeArray( arguments );
296 parameters.shift();
297 } else {
298 parameters = [];
299 }
300 return new Message( mw.messages, key, parameters );
301 },
302
303 /**
304 * Gets a message string, similar to wfMsg()
305 *
306 * @param key string Key of message to get
307 * @param parameters mixed First argument in a list of variadic arguments,
308 * each a parameter for $N replacement in messages.
309 * @return String.
310 */
311 msg: function ( key, parameters ) {
312 return mw.message.apply( mw.message, arguments ).toString();
313 },
314
315 /**
316 * Client-side module loader which integrates with the MediaWiki ResourceLoader
317 */
318 loader: ( function () {
319
320 /* Private Members */
321
322 /**
323 * Mapping of registered modules
324 *
325 * The jquery module is pre-registered, because it must have already
326 * been provided for this object to have been built, and in debug mode
327 * jquery would have been provided through a unique loader request,
328 * making it impossible to hold back registration of jquery until after
329 * mediawiki.
330 *
331 * For exact details on support for script, style and messages, look at
332 * mw.loader.implement.
333 *
334 * Format:
335 * {
336 * 'moduleName': {
337 * 'version': ############## (unix timestamp),
338 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function() {}
339 * 'group': 'somegroup', (or) null,
340 * 'source': 'local', 'someforeignwiki', (or) null
341 * 'state': 'registered', 'loading', 'loaded', 'ready', 'error' or 'missing'
342 * 'script': ...,
343 * 'style': ...,
344 * 'messages': { 'key': 'value' },
345 * }
346 * }
347 */
348 var registry = {},
349 /**
350 * Mapping of sources, keyed by source-id, values are objects.
351 * Format:
352 * {
353 * 'sourceId': {
354 * 'loadScript': 'http://foo.bar/w/load.php'
355 * }
356 * }
357 */
358 sources = {},
359 // List of modules which will be loaded as when ready
360 batch = [],
361 // List of modules to be loaded
362 queue = [],
363 // List of callback functions waiting for modules to be ready to be called
364 jobs = [],
365 // Flag indicating that document ready has occured
366 ready = false,
367 // Selector cache for the marker element. Use getMarker() to get/use the marker!
368 $marker = null;
369
370 /* Cache document ready status */
371
372 $(document).ready( function () {
373 ready = true;
374 } );
375
376 /* Private methods */
377
378 function getMarker() {
379 // Cached ?
380 if ( $marker ) {
381 return $marker;
382 } else {
383 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
384 if ( $marker.length ) {
385 return $marker;
386 }
387 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
388 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
389 return $marker;
390 }
391 }
392
393 /**
394 * Create a new style tag and add it to the DOM.
395 *
396 * @param text String: CSS text
397 * @param $nextnode mixed: [optional] An Element or jQuery object for an element where
398 * the style tag should be inserted before. Otherwise appended to the <head>.
399 * @return HTMLStyleElement
400 */
401 function addStyleTag( text, $nextnode ) {
402 var s = document.createElement( 'style' );
403 s.type = 'text/css';
404 s.rel = 'stylesheet';
405 // Insert into document before setting cssText (bug 33305)
406 if ( $nextnode ) {
407 // If a raw element, create a jQuery object, otherwise use directly
408 if ( $nextnode.nodeType ) {
409 $nextnode = $( $nextnode );
410 }
411 $nextnode.before( s );
412 } else {
413 document.getElementsByTagName('head')[0].appendChild( s );
414 }
415 if ( s.styleSheet ) {
416 s.styleSheet.cssText = text; // IE
417 } else {
418 // Safari sometimes borks on null
419 s.appendChild( document.createTextNode( String( text ) ) );
420 }
421 return s;
422 }
423
424 function addInlineCSS( css, media ) {
425 var $style, style, $newStyle;
426 $style = getMarker().prev();
427 if ( $style.is( 'style' ) && $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
428 // There's already a dynamic <style> tag present, append to it. This recycling of
429 // <style> tags is for bug 31676 (can't have more than 32 <style> tags in IE)
430 style = $style.get( 0 );
431 if ( style.styleSheet ) {
432 style.styleSheet.cssText += css; // IE
433 } else {
434 style.appendChild( document.createTextNode( String( css ) ) );
435 }
436 } else {
437 $newStyle = $( addStyleTag( css, getMarker() ) )
438 .attr( 'media', media )
439 .data( 'ResourceLoaderDynamicStyleTag', true );
440 }
441 }
442
443 function compare( a, b ) {
444 var i;
445 if ( a.length !== b.length ) {
446 return false;
447 }
448 for ( i = 0; i < b.length; i += 1 ) {
449 if ( $.isArray( a[i] ) ) {
450 if ( !compare( a[i], b[i] ) ) {
451 return false;
452 }
453 }
454 if ( a[i] !== b[i] ) {
455 return false;
456 }
457 }
458 return true;
459 }
460
461 /**
462 * Generates an ISO8601 "basic" string from a UNIX timestamp
463 */
464 function formatVersionNumber( timestamp ) {
465 var pad = function ( a, b, c ) {
466 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
467 },
468 d = new Date();
469 d.setTime( timestamp * 1000 );
470 return [
471 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
472 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
473 ].join( '' );
474 }
475
476 /**
477 * Recursively resolves dependencies and detects circular references
478 */
479 function recurse( module, resolved, unresolved ) {
480 var n, deps, len;
481
482 if ( registry[module] === undefined ) {
483 throw new Error( 'Unknown dependency: ' + module );
484 }
485 // Resolves dynamic loader function and replaces it with its own results
486 if ( $.isFunction( registry[module].dependencies ) ) {
487 registry[module].dependencies = registry[module].dependencies();
488 // Ensures the module's dependencies are always in an array
489 if ( typeof registry[module].dependencies !== 'object' ) {
490 registry[module].dependencies = [registry[module].dependencies];
491 }
492 }
493 // Tracks down dependencies
494 deps = registry[module].dependencies;
495 len = deps.length;
496 for ( n = 0; n < len; n += 1 ) {
497 if ( $.inArray( deps[n], resolved ) === -1 ) {
498 if ( $.inArray( deps[n], unresolved ) !== -1 ) {
499 throw new Error(
500 'Circular reference detected: ' + module +
501 ' -> ' + deps[n]
502 );
503 }
504
505 // Add to unresolved
506 unresolved[unresolved.length] = module;
507 recurse( deps[n], resolved, unresolved );
508 // module is at the end of unresolved
509 unresolved.pop();
510 }
511 }
512 resolved[resolved.length] = module;
513 }
514
515 /**
516 * Gets a list of module names that a module depends on in their proper dependency order
517 *
518 * @param module string module name or array of string module names
519 * @return list of dependencies, including 'module'.
520 * @throws Error if circular reference is detected
521 */
522 function resolve( module ) {
523 var modules, m, deps, n, resolved;
524
525 // Allow calling with an array of module names
526 if ( $.isArray( module ) ) {
527 modules = [];
528 for ( m = 0; m < module.length; m += 1 ) {
529 deps = resolve( module[m] );
530 for ( n = 0; n < deps.length; n += 1 ) {
531 modules[modules.length] = deps[n];
532 }
533 }
534 return modules;
535 } else if ( typeof module === 'string' ) {
536 resolved = [];
537 recurse( module, resolved, [] );
538 return resolved;
539 }
540 throw new Error( 'Invalid module argument: ' + module );
541 }
542
543 /**
544 * Narrows a list of module names down to those matching a specific
545 * state (see comment on top of this scope for a list of valid states).
546 * One can also filter for 'unregistered', which will return the
547 * modules names that don't have a registry entry.
548 *
549 * @param states string or array of strings of module states to filter by
550 * @param modules array list of module names to filter (optional, by default the entire
551 * registry is used)
552 * @return array list of filtered module names
553 */
554 function filter( states, modules ) {
555 var list, module, s, m;
556
557 // Allow states to be given as a string
558 if ( typeof states === 'string' ) {
559 states = [states];
560 }
561 // If called without a list of modules, build and use a list of all modules
562 list = [];
563 if ( modules === undefined ) {
564 modules = [];
565 for ( module in registry ) {
566 modules[modules.length] = module;
567 }
568 }
569 // Build a list of modules which are in one of the specified states
570 for ( s = 0; s < states.length; s += 1 ) {
571 for ( m = 0; m < modules.length; m += 1 ) {
572 if ( registry[modules[m]] === undefined ) {
573 // Module does not exist
574 if ( states[s] === 'unregistered' ) {
575 // OK, undefined
576 list[list.length] = modules[m];
577 }
578 } else {
579 // Module exists, check state
580 if ( registry[modules[m]].state === states[s] ) {
581 // OK, correct state
582 list[list.length] = modules[m];
583 }
584 }
585 }
586 }
587 return list;
588 }
589
590 /**
591 * Automatically executes jobs and modules which are pending with satistifed dependencies.
592 *
593 * This is used when dependencies are satisfied, such as when a module is executed.
594 */
595 function handlePending( module ) {
596 var j, r;
597
598 try {
599 // Run jobs whose dependencies have just been met
600 for ( j = 0; j < jobs.length; j += 1 ) {
601 if ( compare(
602 filter( 'ready', jobs[j].dependencies ),
603 jobs[j].dependencies ) )
604 {
605 if ( $.isFunction( jobs[j].ready ) ) {
606 jobs[j].ready();
607 }
608 jobs.splice( j, 1 );
609 j -= 1;
610 }
611 }
612 // Execute modules whose dependencies have just been met
613 for ( r in registry ) {
614 if ( registry[r].state === 'loaded' ) {
615 if ( compare(
616 filter( ['ready'], registry[r].dependencies ),
617 registry[r].dependencies ) )
618 {
619 execute( r );
620 }
621 }
622 }
623 } catch ( e ) {
624 // Run error callbacks of jobs affected by this condition
625 for ( j = 0; j < jobs.length; j += 1 ) {
626 if ( $.inArray( module, jobs[j].dependencies ) !== -1 ) {
627 if ( $.isFunction( jobs[j].error ) ) {
628 jobs[j].error( e, module );
629 }
630 jobs.splice( j, 1 );
631 j -= 1;
632 }
633 }
634 }
635 }
636
637 /**
638 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
639 * depending on whether document-ready has occured yet and whether we are in async mode.
640 *
641 * @param src String: URL to script, will be used as the src attribute in the script tag
642 * @param callback Function: Optional callback which will be run when the script is done
643 */
644 function addScript( src, callback, async ) {
645 var done = false, script, head;
646 if ( ready || async ) {
647 // jQuery's getScript method is NOT better than doing this the old-fashioned way
648 // because jQuery will eval the script's code, and errors will not have sane
649 // line numbers.
650 script = document.createElement( 'script' );
651 script.setAttribute( 'src', src );
652 script.setAttribute( 'type', 'text/javascript' );
653 if ( $.isFunction( callback ) ) {
654 // Attach handlers for all browsers (based on jQuery.ajax)
655 script.onload = script.onreadystatechange = function() {
656
657 if (
658 !done
659 && (
660 !script.readyState
661 || /loaded|complete/.test( script.readyState )
662 )
663 ) {
664
665 done = true;
666
667 callback();
668
669 // Handle memory leak in IE. This seems to fail in
670 // IE7 sometimes (Permission Denied error when
671 // accessing script.parentNode) so wrap it in
672 // a try catch.
673 try {
674 script.onload = script.onreadystatechange = null;
675 if ( script.parentNode ) {
676 script.parentNode.removeChild( script );
677 }
678
679 // Dereference the script
680 script = undefined;
681 } catch ( e ) { }
682 }
683 };
684 }
685
686 if ( window.opera ) {
687 // Appending to the <head> blocks rendering completely in Opera,
688 // so append to the <body> after document ready. This means the
689 // scripts only start loading after the document has been rendered,
690 // but so be it. Opera users don't deserve faster web pages if their
691 // browser makes it impossible
692 $( function() { document.body.appendChild( script ); } );
693 } else {
694 // IE-safe way of getting the <head> . document.documentElement.head doesn't
695 // work in scripts that run in the <head>
696 head = document.getElementsByTagName( 'head' )[0];
697 ( document.body || head ).appendChild( script );
698 }
699 } else {
700 document.write( mw.html.element(
701 'script', { 'type': 'text/javascript', 'src': src }, ''
702 ) );
703 if ( $.isFunction( callback ) ) {
704 // Document.write is synchronous, so this is called when it's done
705 // FIXME: that's a lie. doc.write isn't actually synchronous
706 callback();
707 }
708 }
709 }
710
711 /**
712 * Executes a loaded module, making it ready to use
713 *
714 * @param module string module name to execute
715 */
716 function execute( module, callback ) {
717 var style, media, i, script, markModuleReady, nestedAddScript;
718
719 if ( registry[module] === undefined ) {
720 throw new Error( 'Module has not been registered yet: ' + module );
721 } else if ( registry[module].state === 'registered' ) {
722 throw new Error( 'Module has not been requested from the server yet: ' + module );
723 } else if ( registry[module].state === 'loading' ) {
724 throw new Error( 'Module has not completed loading yet: ' + module );
725 } else if ( registry[module].state === 'ready' ) {
726 throw new Error( 'Module has already been loaded: ' + module );
727 }
728
729 // Add styles
730 if ( $.isPlainObject( registry[module].style ) ) {
731 for ( media in registry[module].style ) {
732 style = registry[module].style[media];
733 if ( $.isArray( style ) ) {
734 for ( i = 0; i < style.length; i += 1 ) {
735 getMarker().before( mw.html.element( 'link', {
736 'type': 'text/css',
737 'media': media,
738 'rel': 'stylesheet',
739 'href': style[i]
740 } ) );
741 }
742 } else if ( typeof style === 'string' ) {
743 addInlineCSS( style, media );
744 }
745 }
746 }
747 // Add localizations to message system
748 if ( $.isPlainObject( registry[module].messages ) ) {
749 mw.messages.set( registry[module].messages );
750 }
751 // Execute script
752 try {
753 script = registry[module].script;
754 markModuleReady = function() {
755 registry[module].state = 'ready';
756 handlePending( module );
757 if ( $.isFunction( callback ) ) {
758 callback();
759 }
760 };
761 nestedAddScript = function ( arr, callback, async, i ) {
762 // Recursively call addScript() in its own callback
763 // for each element of arr.
764 if ( i >= arr.length ) {
765 // We're at the end of the array
766 callback();
767 return;
768 }
769
770 addScript( arr[i], function() {
771 nestedAddScript( arr, callback, async, i + 1 );
772 }, async );
773 };
774
775 if ( $.isArray( script ) ) {
776 registry[module].state = 'loading';
777 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
778 } else if ( $.isFunction( script ) ) {
779 script();
780 markModuleReady();
781 }
782 } catch ( e ) {
783 // This needs to NOT use mw.log because these errors are common in production mode
784 // and not in debug mode, such as when a symbol that should be global isn't exported
785 if ( window.console && typeof window.console.log === 'function' ) {
786 console.log( 'mw.loader::execute> Exception thrown by ' + module + ': ' + e.message );
787 }
788 registry[module].state = 'error';
789 throw e;
790 }
791 }
792
793 /**
794 * Adds a dependencies to the queue with optional callbacks to be run
795 * when the dependencies are ready or fail
796 *
797 * @param dependencies string module name or array of string module names
798 * @param ready function callback to execute when all dependencies are ready
799 * @param error function callback to execute when any dependency fails
800 * @param async (optional) If true, load modules asynchronously even if
801 * document ready has not yet occurred
802 */
803 function request( dependencies, ready, error, async ) {
804 var regItemDeps, regItemDepLen, n;
805
806 // Allow calling by single module name
807 if ( typeof dependencies === 'string' ) {
808 dependencies = [dependencies];
809 if ( registry[dependencies[0]] !== undefined ) {
810 // Cache repetitively accessed deep level object member
811 regItemDeps = registry[dependencies[0]].dependencies;
812 // Cache to avoid looped access to length property
813 regItemDepLen = regItemDeps.length;
814 for ( n = 0; n < regItemDepLen; n += 1 ) {
815 dependencies[dependencies.length] = regItemDeps[n];
816 }
817 }
818 }
819 // Add ready and error callbacks if they were given
820 if ( arguments.length > 1 ) {
821 jobs[jobs.length] = {
822 'dependencies': filter(
823 ['registered', 'loading', 'loaded'],
824 dependencies
825 ),
826 'ready': ready,
827 'error': error
828 };
829 }
830 // Queue up any dependencies that are registered
831 dependencies = filter( ['registered'], dependencies );
832 for ( n = 0; n < dependencies.length; n += 1 ) {
833 if ( $.inArray( dependencies[n], queue ) === -1 ) {
834 queue[queue.length] = dependencies[n];
835 if ( async ) {
836 // Mark this module as async in the registry
837 registry[dependencies[n]].async = true;
838 }
839 }
840 }
841 // Work the queue
842 mw.loader.work();
843 }
844
845 function sortQuery(o) {
846 var sorted = {}, key, a = [];
847 for ( key in o ) {
848 if ( hasOwn.call( o, key ) ) {
849 a.push( key );
850 }
851 }
852 a.sort();
853 for ( key = 0; key < a.length; key += 1 ) {
854 sorted[a[key]] = o[a[key]];
855 }
856 return sorted;
857 }
858
859 /**
860 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
861 * to a query string of the form foo.bar,baz|bar.baz,quux
862 */
863 function buildModulesString( moduleMap ) {
864 var arr = [], p, prefix;
865 for ( prefix in moduleMap ) {
866 p = prefix === '' ? '' : prefix + '.';
867 arr.push( p + moduleMap[prefix].join( ',' ) );
868 }
869 return arr.join( '|' );
870 }
871
872 /**
873 * Asynchronously append a script tag to the end of the body
874 * that invokes load.php
875 * @param moduleMap {Object}: Module map, see buildModulesString()
876 * @param currReqBase {Object}: Object with other parameters (other than 'modules') to use in the request
877 * @param sourceLoadScript {String}: URL of load.php
878 * @param async {Boolean}: If true, use an asynchrounous request even if document ready has not yet occurred
879 */
880 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
881 var request = $.extend(
882 { 'modules': buildModulesString( moduleMap ) },
883 currReqBase
884 );
885 request = sortQuery( request );
886 // Asynchronously append a script tag to the end of the body
887 // Append &* to avoid triggering the IE6 extension check
888 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
889 }
890
891 /* Public Methods */
892 return {
893 addStyleTag: addStyleTag,
894
895 /**
896 * Requests dependencies from server, loading and executing when things when ready.
897 */
898 work: function () {
899 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
900 source, group, g, i, modules, maxVersion, sourceLoadScript,
901 currReqBase, currReqBaseLength, moduleMap, l,
902 lastDotIndex, prefix, suffix, bytesAdded, async;
903
904 // Build a list of request parameters common to all requests.
905 reqBase = {
906 skin: mw.config.get( 'skin' ),
907 lang: mw.config.get( 'wgUserLanguage' ),
908 debug: mw.config.get( 'debug' )
909 };
910 // Split module batch by source and by group.
911 splits = {};
912 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
913
914 // Appends a list of modules from the queue to the batch
915 for ( q = 0; q < queue.length; q += 1 ) {
916 // Only request modules which are registered
917 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
918 // Prevent duplicate entries
919 if ( $.inArray( queue[q], batch ) === -1 ) {
920 batch[batch.length] = queue[q];
921 // Mark registered modules as loading
922 registry[queue[q]].state = 'loading';
923 }
924 }
925 }
926 // Early exit if there's nothing to load...
927 if ( !batch.length ) {
928 return;
929 }
930
931 // The queue has been processed into the batch, clear up the queue.
932 queue = [];
933
934 // Always order modules alphabetically to help reduce cache
935 // misses for otherwise identical content.
936 batch.sort();
937
938 // Split batch by source and by group.
939 for ( b = 0; b < batch.length; b += 1 ) {
940 bSource = registry[batch[b]].source;
941 bGroup = registry[batch[b]].group;
942 if ( splits[bSource] === undefined ) {
943 splits[bSource] = {};
944 }
945 if ( splits[bSource][bGroup] === undefined ) {
946 splits[bSource][bGroup] = [];
947 }
948 bSourceGroup = splits[bSource][bGroup];
949 bSourceGroup[bSourceGroup.length] = batch[b];
950 }
951
952 // Clear the batch - this MUST happen before we append any
953 // script elements to the body or it's possible that a script
954 // will be locally cached, instantly load, and work the batch
955 // again, all before we've cleared it causing each request to
956 // include modules which are already loaded.
957 batch = [];
958
959 for ( source in splits ) {
960
961 sourceLoadScript = sources[source].loadScript;
962
963 for ( group in splits[source] ) {
964
965 // Cache access to currently selected list of
966 // modules for this group from this source.
967 modules = splits[source][group];
968
969 // Calculate the highest timestamp
970 maxVersion = 0;
971 for ( g = 0; g < modules.length; g += 1 ) {
972 if ( registry[modules[g]].version > maxVersion ) {
973 maxVersion = registry[modules[g]].version;
974 }
975 }
976
977 currReqBase = $.extend( { 'version': formatVersionNumber( maxVersion ) }, reqBase );
978 currReqBaseLength = $.param( currReqBase ).length;
979 async = true;
980 // We may need to split up the request to honor the query string length limit,
981 // so build it piece by piece.
982 l = currReqBaseLength + 9; // '&modules='.length == 9
983
984 moduleMap = {}; // { prefix: [ suffixes ] }
985
986 for ( i = 0; i < modules.length; i += 1 ) {
987 // Determine how many bytes this module would add to the query string
988 lastDotIndex = modules[i].lastIndexOf( '.' );
989 // Note that these substr() calls work even if lastDotIndex == -1
990 prefix = modules[i].substr( 0, lastDotIndex );
991 suffix = modules[i].substr( lastDotIndex + 1 );
992 bytesAdded = moduleMap[prefix] !== undefined
993 ? suffix.length + 3 // '%2C'.length == 3
994 : modules[i].length + 3; // '%7C'.length == 3
995
996 // If the request would become too long, create a new one,
997 // but don't create empty requests
998 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
999 // This request would become too long, create a new one
1000 // and fire off the old one
1001 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1002 moduleMap = {};
1003 async = true;
1004 l = currReqBaseLength + 9;
1005 }
1006 if ( moduleMap[prefix] === undefined ) {
1007 moduleMap[prefix] = [];
1008 }
1009 moduleMap[prefix].push( suffix );
1010 if ( !registry[modules[i]].async ) {
1011 // If this module is blocking, make the entire request blocking
1012 // This is slightly suboptimal, but in practice mixing of blocking
1013 // and async modules will only occur in debug mode.
1014 async = false;
1015 }
1016 l += bytesAdded;
1017 }
1018 // If there's anything left in moduleMap, request that too
1019 if ( !$.isEmptyObject( moduleMap ) ) {
1020 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1021 }
1022 }
1023 }
1024 },
1025
1026 /**
1027 * Register a source.
1028 *
1029 * @param id {String}: Short lowercase a-Z string representing a source, only used internally.
1030 * @param props {Object}: Object containing only the loadScript property which is a url to
1031 * the load.php location of the source.
1032 * @return {Boolean}
1033 */
1034 addSource: function ( id, props ) {
1035 var source;
1036 // Allow multiple additions
1037 if ( typeof id === 'object' ) {
1038 for ( source in id ) {
1039 mw.loader.addSource( source, id[source] );
1040 }
1041 return true;
1042 }
1043
1044 if ( sources[id] !== undefined ) {
1045 throw new Error( 'source already registered: ' + id );
1046 }
1047
1048 sources[id] = props;
1049
1050 return true;
1051 },
1052
1053 /**
1054 * Registers a module, letting the system know about it and its
1055 * properties. Startup modules contain calls to this function.
1056 *
1057 * @param module {String}: Module name
1058 * @param version {Number}: Module version number as a timestamp (falls backs to 0)
1059 * @param dependencies {String|Array|Function}: One string or array of strings of module
1060 * names on which this module depends, or a function that returns that array.
1061 * @param group {String}: Group which the module is in (optional, defaults to null)
1062 * @param source {String}: Name of the source. Defaults to local.
1063 */
1064 register: function ( module, version, dependencies, group, source ) {
1065 var m;
1066 // Allow multiple registration
1067 if ( typeof module === 'object' ) {
1068 for ( m = 0; m < module.length; m += 1 ) {
1069 // module is an array of module names
1070 if ( typeof module[m] === 'string' ) {
1071 mw.loader.register( module[m] );
1072 // module is an array of arrays
1073 } else if ( typeof module[m] === 'object' ) {
1074 mw.loader.register.apply( mw.loader, module[m] );
1075 }
1076 }
1077 return;
1078 }
1079 // Validate input
1080 if ( typeof module !== 'string' ) {
1081 throw new Error( 'module must be a string, not a ' + typeof module );
1082 }
1083 if ( registry[module] !== undefined ) {
1084 throw new Error( 'module already registered: ' + module );
1085 }
1086 // List the module as registered
1087 registry[module] = {
1088 'version': version !== undefined ? parseInt( version, 10 ) : 0,
1089 'dependencies': [],
1090 'group': typeof group === 'string' ? group : null,
1091 'source': typeof source === 'string' ? source: 'local',
1092 'state': 'registered'
1093 };
1094 if ( typeof dependencies === 'string' ) {
1095 // Allow dependencies to be given as a single module name
1096 registry[module].dependencies = [dependencies];
1097 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1098 // Allow dependencies to be given as an array of module names
1099 // or a function which returns an array
1100 registry[module].dependencies = dependencies;
1101 }
1102 },
1103
1104 /**
1105 * Implements a module, giving the system a course of action to take
1106 * upon loading. Results of a request for one or more modules contain
1107 * calls to this function.
1108 *
1109 * All arguments are required.
1110 *
1111 * @param module String: Name of module
1112 * @param script Mixed: Function of module code or String of URL to be used as the src
1113 * attribute when adding a script element to the body
1114 * @param style Object: Object of CSS strings keyed by media-type or Object of lists of URLs
1115 * keyed by media-type
1116 * @param msgs Object: List of key/value pairs to be passed through mw.messages.set
1117 */
1118 implement: function ( module, script, style, msgs ) {
1119 // Validate input
1120 if ( typeof module !== 'string' ) {
1121 throw new Error( 'module must be a string, not a ' + typeof module );
1122 }
1123 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1124 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1125 }
1126 if ( !$.isPlainObject( style ) ) {
1127 throw new Error( 'style must be an object, not a ' + typeof style );
1128 }
1129 if ( !$.isPlainObject( msgs ) ) {
1130 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1131 }
1132 // Automatically register module
1133 if ( registry[module] === undefined ) {
1134 mw.loader.register( module );
1135 }
1136 // Check for duplicate implementation
1137 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1138 throw new Error( 'module already implemented: ' + module );
1139 }
1140 // Mark module as loaded
1141 registry[module].state = 'loaded';
1142 // Attach components
1143 registry[module].script = script;
1144 registry[module].style = style;
1145 registry[module].messages = msgs;
1146 // Execute or queue callback
1147 if ( compare(
1148 filter( ['ready'], registry[module].dependencies ),
1149 registry[module].dependencies ) )
1150 {
1151 execute( module );
1152 }
1153 },
1154
1155 /**
1156 * Executes a function as soon as one or more required modules are ready
1157 *
1158 * @param dependencies {String|Array} Module name or array of modules names the callback
1159 * dependends on to be ready before executing
1160 * @param ready {Function} callback to execute when all dependencies are ready (optional)
1161 * @param error {Function} callback to execute when if dependencies have a errors (optional)
1162 */
1163 using: function ( dependencies, ready, error ) {
1164 var tod = typeof dependencies;
1165 // Validate input
1166 if ( tod !== 'object' && tod !== 'string' ) {
1167 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1168 }
1169 // Allow calling with a single dependency as a string
1170 if ( tod === 'string' ) {
1171 dependencies = [dependencies];
1172 }
1173 // Resolve entire dependency map
1174 dependencies = resolve( dependencies );
1175 // If all dependencies are met, execute ready immediately
1176 if ( compare( filter( ['ready'], dependencies ), dependencies ) ) {
1177 if ( $.isFunction( ready ) ) {
1178 ready();
1179 }
1180 }
1181 // If any dependencies have errors execute error immediately
1182 else if ( filter( ['error'], dependencies ).length ) {
1183 if ( $.isFunction( error ) ) {
1184 error( new Error( 'one or more dependencies have state "error"' ),
1185 dependencies );
1186 }
1187 }
1188 // Since some dependencies are not yet ready, queue up a request
1189 else {
1190 request( dependencies, ready, error );
1191 }
1192 },
1193
1194 /**
1195 * Loads an external script or one or more modules for future use
1196 *
1197 * @param modules {mixed} Either the name of a module, array of modules,
1198 * or a URL of an external script or style
1199 * @param type {String} mime-type to use if calling with a URL of an
1200 * external script or style; acceptable values are "text/css" and
1201 * "text/javascript"; if no type is provided, text/javascript is assumed.
1202 * @param async {Boolean} (optional) If true, load modules asynchronously
1203 * even if document ready has not yet occurred. If false (default),
1204 * block before document ready and load async after
1205 */
1206 load: function ( modules, type, async ) {
1207 var filtered, m;
1208
1209 // Validate input
1210 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1211 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1212 }
1213 // Allow calling with an external url or single dependency as a string
1214 if ( typeof modules === 'string' ) {
1215 // Support adding arbitrary external scripts
1216 if ( /^(https?:)?\/\//.test( modules ) ) {
1217 if ( type === 'text/css' ) {
1218 $( 'head' ).append( $( '<link>', {
1219 rel: 'stylesheet',
1220 type: 'text/css',
1221 href: modules
1222 } ) );
1223 return;
1224 } else if ( type === 'text/javascript' || type === undefined ) {
1225 addScript( modules, null, async );
1226 return;
1227 }
1228 // Unknown type
1229 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1230 }
1231 // Called with single module
1232 modules = [modules];
1233 }
1234
1235 // Filter out undefined modules, otherwise resolve() will throw
1236 // an exception for trying to load an undefined module.
1237 // Undefined modules are acceptable here in load(), because load() takes
1238 // an array of unrelated modules, whereas the modules passed to
1239 // using() are related and must all be loaded.
1240 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1241 if ( registry[modules[m]] !== undefined ) {
1242 filtered[filtered.length] = modules[m];
1243 }
1244 }
1245
1246 // Resolve entire dependency map
1247 filtered = resolve( filtered );
1248 // If all modules are ready, nothing dependency be done
1249 if ( compare( filter( ['ready'], filtered ), filtered ) ) {
1250 return;
1251 }
1252 // If any modules have errors
1253 else if ( filter( ['error'], filtered ).length ) {
1254 return;
1255 }
1256 // Since some modules are not yet ready, queue up a request
1257 else {
1258 request( filtered, null, null, async );
1259 return;
1260 }
1261 },
1262
1263 /**
1264 * Changes the state of a module
1265 *
1266 * @param module {String|Object} module name or object of module name/state pairs
1267 * @param state {String} state name
1268 */
1269 state: function ( module, state ) {
1270 var m;
1271 if ( typeof module === 'object' ) {
1272 for ( m in module ) {
1273 mw.loader.state( m, module[m] );
1274 }
1275 return;
1276 }
1277 if ( registry[module] === undefined ) {
1278 mw.loader.register( module );
1279 }
1280 registry[module].state = state;
1281 },
1282
1283 /**
1284 * Gets the version of a module
1285 *
1286 * @param module string name of module to get version for
1287 */
1288 getVersion: function ( module ) {
1289 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1290 return formatVersionNumber( registry[module].version );
1291 }
1292 return null;
1293 },
1294
1295 /**
1296 * @deprecated since 1.18 use mw.loader.getVersion() instead
1297 */
1298 version: function () {
1299 return mw.loader.getVersion.apply( mw.loader, arguments );
1300 },
1301
1302 /**
1303 * Gets the state of a module
1304 *
1305 * @param module string name of module to get state for
1306 */
1307 getState: function ( module ) {
1308 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1309 return registry[module].state;
1310 }
1311 return null;
1312 },
1313
1314 /**
1315 * Get names of all registered modules.
1316 *
1317 * @return {Array}
1318 */
1319 getModuleNames: function () {
1320 return $.map( registry, function ( i, key ) {
1321 return key;
1322 } );
1323 },
1324
1325 /**
1326 * For backwards-compatibility with Squid-cached pages. Loads mw.user
1327 */
1328 go: function () {
1329 mw.loader.load( 'mediawiki.user' );
1330 }
1331 };
1332 }() ),
1333
1334 /** HTML construction helper functions */
1335 html: ( function () {
1336 function escapeCallback( s ) {
1337 switch ( s ) {
1338 case "'":
1339 return '&#039;';
1340 case '"':
1341 return '&quot;';
1342 case '<':
1343 return '&lt;';
1344 case '>':
1345 return '&gt;';
1346 case '&':
1347 return '&amp;';
1348 }
1349 }
1350
1351 return {
1352 /**
1353 * Escape a string for HTML. Converts special characters to HTML entities.
1354 * @param s The string to escape
1355 */
1356 escape: function ( s ) {
1357 return s.replace( /['"<>&]/g, escapeCallback );
1358 },
1359
1360 /**
1361 * Wrapper object for raw HTML passed to mw.html.element().
1362 * @constructor
1363 */
1364 Raw: function ( value ) {
1365 this.value = value;
1366 },
1367
1368 /**
1369 * Wrapper object for CDATA element contents passed to mw.html.element()
1370 * @constructor
1371 */
1372 Cdata: function ( value ) {
1373 this.value = value;
1374 },
1375
1376 /**
1377 * Create an HTML element string, with safe escaping.
1378 *
1379 * @param name The tag name.
1380 * @param attrs An object with members mapping element names to values
1381 * @param contents The contents of the element. May be either:
1382 * - string: The string is escaped.
1383 * - null or undefined: The short closing form is used, e.g. <br/>.
1384 * - this.Raw: The value attribute is included without escaping.
1385 * - this.Cdata: The value attribute is included, and an exception is
1386 * thrown if it contains an illegal ETAGO delimiter.
1387 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1388 *
1389 * Example:
1390 * var h = mw.html;
1391 * return h.element( 'div', {},
1392 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1393 * Returns <div><img src="&lt;"/></div>
1394 */
1395 element: function ( name, attrs, contents ) {
1396 var v, attrName, s = '<' + name;
1397
1398 for ( attrName in attrs ) {
1399 v = attrs[attrName];
1400 // Convert name=true, to name=name
1401 if ( v === true ) {
1402 v = attrName;
1403 // Skip name=false
1404 } else if ( v === false ) {
1405 continue;
1406 }
1407 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1408 }
1409 if ( contents === undefined || contents === null ) {
1410 // Self close tag
1411 s += '/>';
1412 return s;
1413 }
1414 // Regular open tag
1415 s += '>';
1416 switch ( typeof contents ) {
1417 case 'string':
1418 // Escaped
1419 s += this.escape( contents );
1420 break;
1421 case 'number':
1422 case 'boolean':
1423 // Convert to string
1424 s += String( contents );
1425 break;
1426 default:
1427 if ( contents instanceof this.Raw ) {
1428 // Raw HTML inclusion
1429 s += contents.value;
1430 } else if ( contents instanceof this.Cdata ) {
1431 // CDATA
1432 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1433 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1434 }
1435 s += contents.value;
1436 } else {
1437 throw new Error( 'mw.html.element: Invalid type of contents' );
1438 }
1439 }
1440 s += '</' + name + '>';
1441 return s;
1442 }
1443 };
1444 }() ),
1445
1446 // Skeleton user object. mediawiki.user.js extends this
1447 user: {
1448 options: new Map(),
1449 tokens: new Map()
1450 }
1451 };
1452
1453 })( jQuery );
1454
1455 // Alias $j to jQuery for backwards compatibility
1456 window.$j = jQuery;
1457
1458 // Attach to window and globally alias
1459 window.mw = window.mediaWiki = mw;
1460
1461 // Auto-register from pre-loaded startup scripts
1462 if ( typeof startUp !== 'undefined' && jQuery.isFunction( startUp ) ) {
1463 startUp();
1464 startUp = undefined;
1465 }