883a63f5dc930f17e791721856822fe22bee340d
[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 slice = Array.prototype.slice;
12
13 /* Object constructors */
14
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 * @class mw.Map
19 *
20 * @constructor
21 * @param {boolean} global Whether to store the values in the global window
22 * object or a exclusively in the object property 'values'.
23 */
24 function Map( global ) {
25 this.values = global === true ? window : {};
26 return this;
27 }
28
29 Map.prototype = {
30 /**
31 * Get the value of one or multiple a keys.
32 *
33 * If called with no arguments, all values will be returned.
34 *
35 * @param {string|Array} selection String key or array of keys to get values for.
36 * @param {Mixed} [fallback] Value to use in case key(s) do not exist.
37 * @return mixed If selection was a string returns the value or null,
38 * If selection was an array, returns an object of key/values (value is null if not found),
39 * If selection was not passed or invalid, will return the 'values' object member (be careful as
40 * objects are always passed by reference in JavaScript!).
41 * @return {string|Object|null} Values as a string or object, null if invalid/inexistant.
42 */
43 get: function ( selection, fallback ) {
44 var results, i;
45 // If we only do this in the `return` block, it'll fail for the
46 // call to get() from the mutli-selection block.
47 fallback = arguments.length > 1 ? fallback : null;
48
49 if ( $.isArray( selection ) ) {
50 selection = slice.call( selection );
51 results = {};
52 for ( i = 0; i < selection.length; i++ ) {
53 results[selection[i]] = this.get( selection[i], fallback );
54 }
55 return results;
56 }
57
58 if ( typeof selection === 'string' ) {
59 if ( !hasOwn.call( this.values, selection ) ) {
60 return fallback;
61 }
62 return this.values[selection];
63 }
64
65 if ( selection === undefined ) {
66 return this.values;
67 }
68
69 // invalid selection key
70 return null;
71 },
72
73 /**
74 * Sets one or multiple key/value pairs.
75 *
76 * @param {string|Object} selection String key to set value for, or object mapping keys to values.
77 * @param {Mixed} [value] Value to set (optional, only in use when key is a string)
78 * @return {Boolean} This returns true on success, false on failure.
79 */
80 set: function ( selection, value ) {
81 var s;
82
83 if ( $.isPlainObject( selection ) ) {
84 for ( s in selection ) {
85 this.values[s] = selection[s];
86 }
87 return true;
88 }
89 if ( typeof selection === 'string' && arguments.length > 1 ) {
90 this.values[selection] = value;
91 return true;
92 }
93 return false;
94 },
95
96 /**
97 * Checks if one or multiple keys exist.
98 *
99 * @param {Mixed} selection String key or array of keys to check
100 * @return {boolean} Existence of key(s)
101 */
102 exists: function ( selection ) {
103 var s;
104
105 if ( $.isArray( selection ) ) {
106 for ( s = 0; s < selection.length; s++ ) {
107 if ( typeof selection[s] !== 'string' || !hasOwn.call( this.values, selection[s] ) ) {
108 return false;
109 }
110 }
111 return true;
112 }
113 return typeof selection === 'string' && hasOwn.call( this.values, selection );
114 }
115 };
116
117 /**
118 * Object constructor for messages,
119 * similar to the Message class in MediaWiki PHP.
120 * @class mw.Message
121 *
122 * @constructor
123 * @param {mw.Map} map Message storage
124 * @param {string} key
125 * @param {Array} [parameters]
126 */
127 function Message( map, key, parameters ) {
128 this.format = 'text';
129 this.map = map;
130 this.key = key;
131 this.parameters = parameters === undefined ? [] : slice.call( parameters );
132 return this;
133 }
134
135 Message.prototype = {
136 /**
137 * Simple message parser, does $N replacement and nothing else.
138 *
139 * This may be overridden to provide a more complex message parser.
140 *
141 * The primary override is in mediawiki.jqueryMsg.
142 *
143 * This function will not be called for nonexistent messages.
144 */
145 parser: function () {
146 var parameters = this.parameters;
147 return this.map.get( this.key ).replace( /\$(\d+)/g, function ( str, match ) {
148 var index = parseInt( match, 10 ) - 1;
149 return parameters[index] !== undefined ? parameters[index] : '$' + match;
150 } );
151 },
152
153 /**
154 * Appends (does not replace) parameters for replacement to the .parameters property.
155 *
156 * @param {Array} parameters
157 * @chainable
158 */
159 params: function ( parameters ) {
160 var i;
161 for ( i = 0; i < parameters.length; i += 1 ) {
162 this.parameters.push( parameters[i] );
163 }
164 return this;
165 },
166
167 /**
168 * Converts message object to it's string form based on the state of format.
169 *
170 * @return {string} Message as a string in the current form or `<key>` if key does not exist.
171 */
172 toString: function () {
173 var text;
174
175 if ( !this.exists() ) {
176 // Use <key> as text if key does not exist
177 if ( this.format === 'escaped' || this.format === 'parse' ) {
178 // format 'escaped' and 'parse' need to have the brackets and key html escaped
179 return mw.html.escape( '<' + this.key + '>' );
180 }
181 return '<' + this.key + '>';
182 }
183
184 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
185 text = this.parser();
186 }
187
188 if ( this.format === 'escaped' ) {
189 text = this.parser();
190 text = mw.html.escape( text );
191 }
192
193 return text;
194 },
195
196 /**
197 * Changes format to 'parse' and converts message to string
198 *
199 * If jqueryMsg is loaded, this parses the message text from wikitext
200 * (where supported) to HTML
201 *
202 * Otherwise, it is equivalent to plain.
203 *
204 * @return {string} String form of parsed message
205 */
206 parse: function () {
207 this.format = 'parse';
208 return this.toString();
209 },
210
211 /**
212 * Changes format to 'plain' and converts message to string
213 *
214 * This substitutes parameters, but otherwise does not change the
215 * message text.
216 *
217 * @return {string} String form of plain message
218 */
219 plain: function () {
220 this.format = 'plain';
221 return this.toString();
222 },
223
224 /**
225 * Changes format to 'text' and converts message to string
226 *
227 * If jqueryMsg is loaded, {{-transformation is done where supported
228 * (such as {{plural:}}, {{gender:}}, {{int:}}).
229 *
230 * Otherwise, it is equivalent to plain.
231 */
232 text: function () {
233 this.format = 'text';
234 return this.toString();
235 },
236
237 /**
238 * Changes the format to 'escaped' and converts message to string
239 *
240 * This is equivalent to using the 'text' format (see text method), then
241 * HTML-escaping the output.
242 *
243 * @return {string} String form of html escaped message
244 */
245 escaped: function () {
246 this.format = 'escaped';
247 return this.toString();
248 },
249
250 /**
251 * Checks if message exists
252 *
253 * @see mw.Map#exists
254 * @return {boolean}
255 */
256 exists: function () {
257 return this.map.exists( this.key );
258 }
259 };
260
261 /**
262 * Base library for MediaWiki.
263 *
264 * @class mw
265 * @alternateClassName mediaWiki
266 * @singleton
267 */
268 return {
269 /* Public Members */
270
271 /**
272 * Dummy placeholder for {@link mw.log}
273 * @method
274 */
275 log: ( function () {
276 var log = function () {};
277 log.warn = function () {};
278 log.deprecate = function ( obj, key, val ) {
279 obj[key] = val;
280 };
281 return log;
282 }() ),
283
284 // Make the Map constructor publicly available.
285 Map: Map,
286
287 // Make the Message constructor publicly available.
288 Message: Message,
289
290 /**
291 * List of configuration values
292 *
293 * Dummy placeholder. Initiated in startUp module as a new instance of mw.Map().
294 * If `$wgLegacyJavaScriptGlobals` is true, this Map will have its values
295 * in the global window object.
296 * @property
297 */
298 config: null,
299
300 /**
301 * Empty object that plugins can be installed in.
302 * @property
303 */
304 libs: {},
305
306 /**
307 * Access container for deprecated functionality that can be moved from
308 * from their legacy location and attached to this object (e.g. a global
309 * function that is deprecated and as stop-gap can be exposed through here).
310 *
311 * This was reserved for future use but never ended up being used.
312 *
313 * @deprecated since 1.22: Let deprecated identifiers keep their original name
314 * and use mw.log#deprecate to create an access container for tracking.
315 * @property
316 */
317 legacy: {},
318
319 /**
320 * Localization system
321 * @property {mw.Map}
322 */
323 messages: new Map(),
324
325 /* Public Methods */
326
327 /**
328 * Gets a message object, similar to wfMessage().
329 *
330 * @param {string} key Key of message to get
331 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
332 * @return {mw.Message}
333 */
334 message: function ( key ) {
335 // Variadic arguments
336 var parameters = slice.call( arguments, 1 );
337 return new Message( mw.messages, key, parameters );
338 },
339
340 /**
341 * Gets a message string, similar to wfMessage()
342 *
343 * @see mw.Message#toString
344 * @param {string} key Key of message to get
345 * @param {Mixed...} parameters Parameters for the $N replacements in messages.
346 * @return {string}
347 */
348 msg: function ( /* key, parameters... */ ) {
349 return mw.message.apply( mw.message, arguments ).toString();
350 },
351
352 /**
353 * Client-side module loader which integrates with the MediaWiki ResourceLoader
354 * @class mw.loader
355 * @singleton
356 */
357 loader: ( function () {
358
359 /* Private Members */
360
361 /**
362 * Mapping of registered modules
363 *
364 * The jquery module is pre-registered, because it must have already
365 * been provided for this object to have been built, and in debug mode
366 * jquery would have been provided through a unique loader request,
367 * making it impossible to hold back registration of jquery until after
368 * mediawiki.
369 *
370 * For exact details on support for script, style and messages, look at
371 * mw.loader.implement.
372 *
373 * Format:
374 * {
375 * 'moduleName': {
376 * 'version': ############## (unix timestamp),
377 * 'dependencies': ['required.foo', 'bar.also', ...], (or) function () {}
378 * 'group': 'somegroup', (or) null,
379 * 'source': 'local', 'someforeignwiki', (or) null
380 * 'state': 'registered', 'loaded', 'loading', 'ready', 'error' or 'missing'
381 * 'script': ...,
382 * 'style': ...,
383 * 'messages': { 'key': 'value' },
384 * }
385 * }
386 *
387 * @property
388 * @private
389 */
390 var registry = {},
391 //
392 // Mapping of sources, keyed by source-id, values are objects.
393 // Format:
394 // {
395 // 'sourceId': {
396 // 'loadScript': 'http://foo.bar/w/load.php'
397 // }
398 // }
399 //
400 sources = {},
401 // List of modules which will be loaded as when ready
402 batch = [],
403 // List of modules to be loaded
404 queue = [],
405 // List of callback functions waiting for modules to be ready to be called
406 jobs = [],
407 // Selector cache for the marker element. Use getMarker() to get/use the marker!
408 $marker = null,
409 // Buffer for addEmbeddedCSS.
410 cssBuffer = '',
411 // Callbacks for addEmbeddedCSS.
412 cssCallbacks = $.Callbacks();
413
414 /* Private methods */
415
416 function getMarker() {
417 // Cached ?
418 if ( $marker ) {
419 return $marker;
420 }
421
422 $marker = $( 'meta[name="ResourceLoaderDynamicStyles"]' );
423 if ( $marker.length ) {
424 return $marker;
425 }
426 mw.log( 'getMarker> No <meta name="ResourceLoaderDynamicStyles"> found, inserting dynamically.' );
427 $marker = $( '<meta>' ).attr( 'name', 'ResourceLoaderDynamicStyles' ).appendTo( 'head' );
428
429 return $marker;
430 }
431
432 /**
433 * Create a new style tag and add it to the DOM.
434 *
435 * @private
436 * @param {string} text CSS text
437 * @param {HTMLElement|jQuery} [nextnode=document.head] The element where the style tag should be
438 * inserted before. Otherwise it will be appended to `<head>`.
439 * @return {HTMLElement} Reference to the created `<style>` element.
440 */
441 function newStyleTag( text, nextnode ) {
442 var s = document.createElement( 'style' );
443 // Insert into document before setting cssText (bug 33305)
444 if ( nextnode ) {
445 // Must be inserted with native insertBefore, not $.fn.before.
446 // When using jQuery to insert it, like $nextnode.before( s ),
447 // then IE6 will throw "Access is denied" when trying to append
448 // to .cssText later. Some kind of weird security measure.
449 // http://stackoverflow.com/q/12586482/319266
450 // Works: jsfiddle.net/zJzMy/1
451 // Fails: jsfiddle.net/uJTQz
452 // Works again: http://jsfiddle.net/Azr4w/ (diff: the next 3 lines)
453 if ( nextnode.jquery ) {
454 nextnode = nextnode.get( 0 );
455 }
456 nextnode.parentNode.insertBefore( s, nextnode );
457 } else {
458 document.getElementsByTagName( 'head' )[0].appendChild( s );
459 }
460 if ( s.styleSheet ) {
461 // IE
462 s.styleSheet.cssText = text;
463 } else {
464 // Other browsers.
465 // (Safari sometimes borks on non-string values,
466 // play safe by casting to a string, just in case.)
467 s.appendChild( document.createTextNode( String( text ) ) );
468 }
469 return s;
470 }
471
472 /**
473 * Checks whether it is safe to add this css to a stylesheet.
474 *
475 * @private
476 * @param {string} cssText
477 * @return {boolean} False if a new one must be created.
478 */
479 function canExpandStylesheetWith( cssText ) {
480 // Makes sure that cssText containing `@import`
481 // rules will end up in a new stylesheet (as those only work when
482 // placed at the start of a stylesheet; bug 35562).
483 return cssText.indexOf( '@import' ) === -1;
484 }
485
486 /**
487 * Add a bit of CSS text to the current browser page.
488 *
489 * The CSS will be appended to an existing ResourceLoader-created `<style>` tag
490 * or create a new one based on whether the given `cssText` is safe for extension.
491 *
492 * @param {string} [cssText=cssBuffer] If called without cssText,
493 * the internal buffer will be inserted instead.
494 * @param {Function} [callback]
495 */
496 function addEmbeddedCSS( cssText, callback ) {
497 var $style, styleEl;
498
499 if ( callback ) {
500 cssCallbacks.add( callback );
501 }
502
503 // Yield once before inserting the <style> tag. There are likely
504 // more calls coming up which we can combine this way.
505 // Appending a stylesheet and waiting for the browser to repaint
506 // is fairly expensive, this reduces it (bug 45810)
507 if ( cssText ) {
508 // Be careful not to extend the buffer with css that needs a new stylesheet
509 if ( !cssBuffer || canExpandStylesheetWith( cssText ) ) {
510 // Linebreak for somewhat distinguishable sections
511 // (the rl-cachekey comment separating each)
512 cssBuffer += '\n' + cssText;
513 // TODO: Use requestAnimationFrame in the future which will
514 // perform even better by not injecting styles while the browser
515 // is paiting.
516 setTimeout( function () {
517 // Can't pass addEmbeddedCSS to setTimeout directly because Firefox
518 // (below version 13) has the non-standard behaviour of passing a
519 // numerical "lateness" value as first argument to this callback
520 // http://benalman.com/news/2009/07/the-mysterious-firefox-settime/
521 addEmbeddedCSS();
522 } );
523 return;
524 }
525
526 // This is a delayed call and we got a buffer still
527 } else if ( cssBuffer ) {
528 cssText = cssBuffer;
529 cssBuffer = '';
530 } else {
531 // This is a delayed call, but buffer is already cleared by
532 // another delayed call.
533 return;
534 }
535
536 // By default, always create a new <style>. Appending text
537 // to a <style> tag means the contents have to be re-parsed (bug 45810).
538 // Except, of course, in IE below 9, in there we default to
539 // re-using and appending to a <style> tag due to the
540 // IE stylesheet limit (bug 31676).
541 if ( 'documentMode' in document && document.documentMode <= 9 ) {
542
543 $style = getMarker().prev();
544 // Verify that the the element before Marker actually is a
545 // <style> tag and one that came from ResourceLoader
546 // (not some other style tag or even a `<meta>` or `<script>`).
547 if ( $style.data( 'ResourceLoaderDynamicStyleTag' ) === true ) {
548 // There's already a dynamic <style> tag present and
549 // canExpandStylesheetWith() gave a green light to append more to it.
550 styleEl = $style.get( 0 );
551 if ( styleEl.styleSheet ) {
552 try {
553 styleEl.styleSheet.cssText += cssText; // IE
554 } catch ( e ) {
555 log( 'addEmbeddedCSS fail\ne.message: ' + e.message, e );
556 }
557 } else {
558 styleEl.appendChild( document.createTextNode( String( cssText ) ) );
559 }
560 cssCallbacks.fire().empty();
561 return;
562 }
563 }
564
565 $( newStyleTag( cssText, getMarker() ) ).data( 'ResourceLoaderDynamicStyleTag', true );
566
567 cssCallbacks.fire().empty();
568 }
569
570 /**
571 * Generates an ISO8601 "basic" string from a UNIX timestamp
572 * @private
573 */
574 function formatVersionNumber( timestamp ) {
575 var d = new Date();
576 function pad( a, b, c ) {
577 return [a < 10 ? '0' + a : a, b < 10 ? '0' + b : b, c < 10 ? '0' + c : c].join( '' );
578 }
579 d.setTime( timestamp * 1000 );
580 return [
581 pad( d.getUTCFullYear(), d.getUTCMonth() + 1, d.getUTCDate() ), 'T',
582 pad( d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds() ), 'Z'
583 ].join( '' );
584 }
585
586 /**
587 * Resolves dependencies and detects circular references.
588 *
589 * @private
590 * @param {string} module Name of the top-level module whose dependencies shall be
591 * resolved and sorted.
592 * @param {Array} resolved Returns a topological sort of the given module and its
593 * dependencies, such that later modules depend on earlier modules. The array
594 * contains the module names. If the array contains already some module names,
595 * this function appends its result to the pre-existing array.
596 * @param {Object} [unresolved] Hash used to track the current dependency
597 * chain; used to report loops in the dependency graph.
598 * @throws {Error} If any unregistered module or a dependency loop is encountered
599 */
600 function sortDependencies( module, resolved, unresolved ) {
601 var n, deps, len;
602
603 if ( registry[module] === undefined ) {
604 throw new Error( 'Unknown dependency: ' + module );
605 }
606 // Resolves dynamic loader function and replaces it with its own results
607 if ( $.isFunction( registry[module].dependencies ) ) {
608 registry[module].dependencies = registry[module].dependencies();
609 // Ensures the module's dependencies are always in an array
610 if ( typeof registry[module].dependencies !== 'object' ) {
611 registry[module].dependencies = [registry[module].dependencies];
612 }
613 }
614 if ( $.inArray( module, resolved ) !== -1 ) {
615 // Module already resolved; nothing to do.
616 return;
617 }
618 // unresolved is optional, supply it if not passed in
619 if ( !unresolved ) {
620 unresolved = {};
621 }
622 // Tracks down dependencies
623 deps = registry[module].dependencies;
624 len = deps.length;
625 for ( n = 0; n < len; n += 1 ) {
626 if ( $.inArray( deps[n], resolved ) === -1 ) {
627 if ( unresolved[deps[n]] ) {
628 throw new Error(
629 'Circular reference detected: ' + module +
630 ' -> ' + deps[n]
631 );
632 }
633
634 // Add to unresolved
635 unresolved[module] = true;
636 sortDependencies( deps[n], resolved, unresolved );
637 delete unresolved[module];
638 }
639 }
640 resolved[resolved.length] = module;
641 }
642
643 /**
644 * Gets a list of module names that a module depends on in their proper dependency
645 * order.
646 *
647 * @private
648 * @param {string} module Module name or array of string module names
649 * @return {Array} list of dependencies, including 'module'.
650 * @throws {Error} If circular reference is detected
651 */
652 function resolve( module ) {
653 var m, resolved;
654
655 // Allow calling with an array of module names
656 if ( $.isArray( module ) ) {
657 resolved = [];
658 for ( m = 0; m < module.length; m += 1 ) {
659 sortDependencies( module[m], resolved );
660 }
661 return resolved;
662 }
663
664 if ( typeof module === 'string' ) {
665 resolved = [];
666 sortDependencies( module, resolved );
667 return resolved;
668 }
669
670 throw new Error( 'Invalid module argument: ' + module );
671 }
672
673 /**
674 * Narrows a list of module names down to those matching a specific
675 * state (see comment on top of this scope for a list of valid states).
676 * One can also filter for 'unregistered', which will return the
677 * modules names that don't have a registry entry.
678 *
679 * @private
680 * @param {string|string[]} states Module states to filter by
681 * @param {Array} [modules] List of module names to filter (optional, by default the entire
682 * registry is used)
683 * @return {Array} List of filtered module names
684 */
685 function filter( states, modules ) {
686 var list, module, s, m;
687
688 // Allow states to be given as a string
689 if ( typeof states === 'string' ) {
690 states = [states];
691 }
692 // If called without a list of modules, build and use a list of all modules
693 list = [];
694 if ( modules === undefined ) {
695 modules = [];
696 for ( module in registry ) {
697 modules[modules.length] = module;
698 }
699 }
700 // Build a list of modules which are in one of the specified states
701 for ( s = 0; s < states.length; s += 1 ) {
702 for ( m = 0; m < modules.length; m += 1 ) {
703 if ( registry[modules[m]] === undefined ) {
704 // Module does not exist
705 if ( states[s] === 'unregistered' ) {
706 // OK, undefined
707 list[list.length] = modules[m];
708 }
709 } else {
710 // Module exists, check state
711 if ( registry[modules[m]].state === states[s] ) {
712 // OK, correct state
713 list[list.length] = modules[m];
714 }
715 }
716 }
717 }
718 return list;
719 }
720
721 /**
722 * Determine whether all dependencies are in state 'ready', which means we may
723 * execute the module or job now.
724 *
725 * @private
726 * @param {Array} dependencies Dependencies (module names) to be checked.
727 * @return {boolean} True if all dependencies are in state 'ready', false otherwise
728 */
729 function allReady( dependencies ) {
730 return filter( 'ready', dependencies ).length === dependencies.length;
731 }
732
733 /**
734 * Log a message to window.console, if possible. Useful to force logging of some
735 * errors that are otherwise hard to detect (I.e., this logs also in production mode).
736 * Gets console references in each invocation, so that delayed debugging tools work
737 * fine. No need for optimization here, which would only result in losing logs.
738 *
739 * @private
740 * @param {string} msg text for the log entry.
741 * @param {Error} [e]
742 */
743 function log( msg, e ) {
744 var console = window.console;
745 if ( console && console.log ) {
746 console.log( msg );
747 // If we have an exception object, log it through .error() to trigger
748 // proper stacktraces in browsers that support it. There are no (known)
749 // browsers that don't support .error(), that do support .log() and
750 // have useful exception handling through .log().
751 if ( e && console.error ) {
752 console.error( e );
753 }
754 }
755 }
756
757 /**
758 * A module has entered state 'ready', 'error', or 'missing'. Automatically update pending jobs
759 * and modules that depend upon this module. if the given module failed, propagate the 'error'
760 * state up the dependency tree; otherwise, execute all jobs/modules that now have all their
761 * dependencies satisfied. On jobs depending on a failed module, run the error callback, if any.
762 *
763 * @private
764 * @param {string} module Name of module that entered one of the states 'ready', 'error', or 'missing'.
765 */
766 function handlePending( module ) {
767 var j, job, hasErrors, m, stateChange;
768
769 // Modules.
770 if ( $.inArray( registry[module].state, ['error', 'missing'] ) !== -1 ) {
771 // If the current module failed, mark all dependent modules also as failed.
772 // Iterate until steady-state to propagate the error state upwards in the
773 // dependency tree.
774 do {
775 stateChange = false;
776 for ( m in registry ) {
777 if ( $.inArray( registry[m].state, ['error', 'missing'] ) === -1 ) {
778 if ( filter( ['error', 'missing'], registry[m].dependencies ).length > 0 ) {
779 registry[m].state = 'error';
780 stateChange = true;
781 }
782 }
783 }
784 } while ( stateChange );
785 }
786
787 // Execute all jobs whose dependencies are either all satisfied or contain at least one failed module.
788 for ( j = 0; j < jobs.length; j += 1 ) {
789 hasErrors = filter( ['error', 'missing'], jobs[j].dependencies ).length > 0;
790 if ( hasErrors || allReady( jobs[j].dependencies ) ) {
791 // All dependencies satisfied, or some have errors
792 job = jobs[j];
793 jobs.splice( j, 1 );
794 j -= 1;
795 try {
796 if ( hasErrors ) {
797 throw new Error( 'Module ' + module + ' failed.');
798 } else {
799 if ( $.isFunction( job.ready ) ) {
800 job.ready();
801 }
802 }
803 } catch ( e ) {
804 if ( $.isFunction( job.error ) ) {
805 try {
806 job.error( e, [module] );
807 } catch ( ex ) {
808 // A user-defined operation raised an exception. Swallow to protect
809 // our state machine!
810 log( 'Exception thrown by job.error()', ex );
811 }
812 }
813 }
814 }
815 }
816
817 if ( registry[module].state === 'ready' ) {
818 // The current module became 'ready'. Recursively execute all dependent modules that are loaded
819 // and now have all dependencies satisfied.
820 for ( m in registry ) {
821 if ( registry[m].state === 'loaded' && allReady( registry[m].dependencies ) ) {
822 execute( m );
823 }
824 }
825 }
826 }
827
828 /**
829 * Adds a script tag to the DOM, either using document.write or low-level DOM manipulation,
830 * depending on whether document-ready has occurred yet and whether we are in async mode.
831 *
832 * @private
833 * @param {string} src URL to script, will be used as the src attribute in the script tag
834 * @param {Function} [callback] Callback which will be run when the script is done
835 */
836 function addScript( src, callback, async ) {
837 /*jshint evil:true */
838 var script, head, done;
839
840 // Using isReady directly instead of storing it locally from
841 // a $.fn.ready callback (bug 31895).
842 if ( $.isReady || async ) {
843 // Can't use jQuery.getScript because that only uses <script> for cross-domain,
844 // it uses XHR and eval for same-domain scripts, which we don't want because it
845 // messes up line numbers.
846 // The below is based on jQuery ([jquery@1.8.2]/src/ajax/script.js)
847
848 // IE-safe way of getting the <head>. document.head isn't supported
849 // in old IE, and doesn't work when in the <head>.
850 done = false;
851 head = document.getElementsByTagName( 'head' )[0] || document.body;
852
853 script = document.createElement( 'script' );
854 script.async = true;
855 script.src = src;
856 if ( $.isFunction( callback ) ) {
857 script.onload = script.onreadystatechange = function () {
858 if (
859 !done
860 && (
861 !script.readyState
862 || /loaded|complete/.test( script.readyState )
863 )
864 ) {
865 done = true;
866
867 // Handle memory leak in IE
868 script.onload = script.onreadystatechange = null;
869
870 // Detach the element from the document
871 if ( script.parentNode ) {
872 script.parentNode.removeChild( script );
873 }
874
875 // Dereference the element from javascript
876 script = undefined;
877
878 callback();
879 }
880 };
881 }
882
883 if ( window.opera ) {
884 // Appending to the <head> blocks rendering completely in Opera,
885 // so append to the <body> after document ready. This means the
886 // scripts only start loading after the document has been rendered,
887 // but so be it. Opera users don't deserve faster web pages if their
888 // browser makes it impossible.
889 $( function () {
890 document.body.appendChild( script );
891 } );
892 } else {
893 head.appendChild( script );
894 }
895 } else {
896 document.write( mw.html.element( 'script', { 'src': src }, '' ) );
897 if ( $.isFunction( callback ) ) {
898 // Document.write is synchronous, so this is called when it's done
899 // FIXME: that's a lie. doc.write isn't actually synchronous
900 callback();
901 }
902 }
903 }
904
905 /**
906 * Executes a loaded module, making it ready to use
907 *
908 * @private
909 * @param {string} module Module name to execute
910 */
911 function execute( module ) {
912 var key, value, media, i, urls, cssHandle, checkCssHandles,
913 cssHandlesRegistered = false;
914
915 if ( registry[module] === undefined ) {
916 throw new Error( 'Module has not been registered yet: ' + module );
917 } else if ( registry[module].state === 'registered' ) {
918 throw new Error( 'Module has not been requested from the server yet: ' + module );
919 } else if ( registry[module].state === 'loading' ) {
920 throw new Error( 'Module has not completed loading yet: ' + module );
921 } else if ( registry[module].state === 'ready' ) {
922 throw new Error( 'Module has already been executed: ' + module );
923 }
924
925 /**
926 * Define loop-function here for efficiency
927 * and to avoid re-using badly scoped variables.
928 * @ignore
929 */
930 function addLink( media, url ) {
931 var el = document.createElement( 'link' );
932 getMarker().before( el ); // IE: Insert in dom before setting href
933 el.rel = 'stylesheet';
934 if ( media && media !== 'all' ) {
935 el.media = media;
936 }
937 el.href = url;
938 }
939
940 function runScript() {
941 var script, markModuleReady, nestedAddScript;
942 try {
943 script = registry[module].script;
944 markModuleReady = function () {
945 registry[module].state = 'ready';
946 handlePending( module );
947 };
948 nestedAddScript = function ( arr, callback, async, i ) {
949 // Recursively call addScript() in its own callback
950 // for each element of arr.
951 if ( i >= arr.length ) {
952 // We're at the end of the array
953 callback();
954 return;
955 }
956
957 addScript( arr[i], function () {
958 nestedAddScript( arr, callback, async, i + 1 );
959 }, async );
960 };
961
962 if ( $.isArray( script ) ) {
963 nestedAddScript( script, markModuleReady, registry[module].async, 0 );
964 } else if ( $.isFunction( script ) ) {
965 registry[module].state = 'ready';
966 script( $ );
967 handlePending( module );
968 }
969 } catch ( e ) {
970 // This needs to NOT use mw.log because these errors are common in production mode
971 // and not in debug mode, such as when a symbol that should be global isn't exported
972 log( 'Exception thrown by ' + module + ': ' + e.message, e );
973 registry[module].state = 'error';
974 handlePending( module );
975 }
976 }
977
978 // This used to be inside runScript, but since that is now fired asychronously
979 // (after CSS is loaded) we need to set it here right away. It is crucial that
980 // when execute() is called this is set synchronously, otherwise modules will get
981 // executed multiple times as the registry will state that it isn't loading yet.
982 registry[module].state = 'loading';
983
984 // Add localizations to message system
985 if ( $.isPlainObject( registry[module].messages ) ) {
986 mw.messages.set( registry[module].messages );
987 }
988
989 // Make sure we don't run the scripts until all (potentially asynchronous)
990 // stylesheet insertions have completed.
991 ( function () {
992 var pending = 0;
993 checkCssHandles = function () {
994 // cssHandlesRegistered ensures we don't take off too soon, e.g. when
995 // one of the cssHandles is fired while we're still creating more handles.
996 if ( cssHandlesRegistered && pending === 0 && runScript ) {
997 runScript();
998 runScript = undefined; // Revoke
999 }
1000 };
1001 cssHandle = function () {
1002 var check = checkCssHandles;
1003 pending++;
1004 return function () {
1005 if (check) {
1006 pending--;
1007 check();
1008 check = undefined; // Revoke
1009 }
1010 };
1011 };
1012 }() );
1013
1014 // Process styles (see also mw.loader.implement)
1015 // * back-compat: { <media>: css }
1016 // * back-compat: { <media>: [url, ..] }
1017 // * { "css": [css, ..] }
1018 // * { "url": { <media>: [url, ..] } }
1019 if ( $.isPlainObject( registry[module].style ) ) {
1020 for ( key in registry[module].style ) {
1021 value = registry[module].style[key];
1022 media = undefined;
1023
1024 if ( key !== 'url' && key !== 'css' ) {
1025 // Backwards compatibility, key is a media-type
1026 if ( typeof value === 'string' ) {
1027 // back-compat: { <media>: css }
1028 // Ignore 'media' because it isn't supported (nor was it used).
1029 // Strings are pre-wrapped in "@media". The media-type was just ""
1030 // (because it had to be set to something).
1031 // This is one of the reasons why this format is no longer used.
1032 addEmbeddedCSS( value, cssHandle() );
1033 } else {
1034 // back-compat: { <media>: [url, ..] }
1035 media = key;
1036 key = 'bc-url';
1037 }
1038 }
1039
1040 // Array of css strings in key 'css',
1041 // or back-compat array of urls from media-type
1042 if ( $.isArray( value ) ) {
1043 for ( i = 0; i < value.length; i += 1 ) {
1044 if ( key === 'bc-url' ) {
1045 // back-compat: { <media>: [url, ..] }
1046 addLink( media, value[i] );
1047 } else if ( key === 'css' ) {
1048 // { "css": [css, ..] }
1049 addEmbeddedCSS( value[i], cssHandle() );
1050 }
1051 }
1052 // Not an array, but a regular object
1053 // Array of urls inside media-type key
1054 } else if ( typeof value === 'object' ) {
1055 // { "url": { <media>: [url, ..] } }
1056 for ( media in value ) {
1057 urls = value[media];
1058 for ( i = 0; i < urls.length; i += 1 ) {
1059 addLink( media, urls[i] );
1060 }
1061 }
1062 }
1063 }
1064 }
1065
1066 // Kick off.
1067 cssHandlesRegistered = true;
1068 checkCssHandles();
1069 }
1070
1071 /**
1072 * Adds a dependencies to the queue with optional callbacks to be run
1073 * when the dependencies are ready or fail
1074 *
1075 * @private
1076 * @param {string|string[]} dependencies Module name or array of string module names
1077 * @param {Function} [ready] Callback to execute when all dependencies are ready
1078 * @param {Function} [error] Callback to execute when any dependency fails
1079 * @param {boolean} [async] If true, load modules asynchronously even if
1080 * document ready has not yet occurred.
1081 */
1082 function request( dependencies, ready, error, async ) {
1083 var n;
1084
1085 // Allow calling by single module name
1086 if ( typeof dependencies === 'string' ) {
1087 dependencies = [dependencies];
1088 }
1089
1090 // Add ready and error callbacks if they were given
1091 if ( ready !== undefined || error !== undefined ) {
1092 jobs[jobs.length] = {
1093 'dependencies': filter(
1094 ['registered', 'loading', 'loaded'],
1095 dependencies
1096 ),
1097 'ready': ready,
1098 'error': error
1099 };
1100 }
1101
1102 // Queue up any dependencies that are registered
1103 dependencies = filter( ['registered'], dependencies );
1104 for ( n = 0; n < dependencies.length; n += 1 ) {
1105 if ( $.inArray( dependencies[n], queue ) === -1 ) {
1106 queue[queue.length] = dependencies[n];
1107 if ( async ) {
1108 // Mark this module as async in the registry
1109 registry[dependencies[n]].async = true;
1110 }
1111 }
1112 }
1113
1114 // Work the queue
1115 mw.loader.work();
1116 }
1117
1118 function sortQuery(o) {
1119 var sorted = {}, key, a = [];
1120 for ( key in o ) {
1121 if ( hasOwn.call( o, key ) ) {
1122 a.push( key );
1123 }
1124 }
1125 a.sort();
1126 for ( key = 0; key < a.length; key += 1 ) {
1127 sorted[a[key]] = o[a[key]];
1128 }
1129 return sorted;
1130 }
1131
1132 /**
1133 * Converts a module map of the form { foo: [ 'bar', 'baz' ], bar: [ 'baz, 'quux' ] }
1134 * to a query string of the form foo.bar,baz|bar.baz,quux
1135 * @private
1136 */
1137 function buildModulesString( moduleMap ) {
1138 var arr = [], p, prefix;
1139 for ( prefix in moduleMap ) {
1140 p = prefix === '' ? '' : prefix + '.';
1141 arr.push( p + moduleMap[prefix].join( ',' ) );
1142 }
1143 return arr.join( '|' );
1144 }
1145
1146 /**
1147 * Asynchronously append a script tag to the end of the body
1148 * that invokes load.php
1149 * @private
1150 * @param {Object} moduleMap Module map, see #buildModulesString
1151 * @param {Object} currReqBase Object with other parameters (other than 'modules') to use in the request
1152 * @param {string} sourceLoadScript URL of load.php
1153 * @param {boolean} async If true, use an asynchrounous request even if document ready has not yet occurred
1154 */
1155 function doRequest( moduleMap, currReqBase, sourceLoadScript, async ) {
1156 var request = $.extend(
1157 { modules: buildModulesString( moduleMap ) },
1158 currReqBase
1159 );
1160 request = sortQuery( request );
1161 // Asynchronously append a script tag to the end of the body
1162 // Append &* to avoid triggering the IE6 extension check
1163 addScript( sourceLoadScript + '?' + $.param( request ) + '&*', null, async );
1164 }
1165
1166 /* Public Methods */
1167 return {
1168 /**
1169 * @inheritdoc #newStyleTag
1170 * @method
1171 */
1172 addStyleTag: newStyleTag,
1173
1174 /**
1175 * Batch-request queued dependencies from the server.
1176 */
1177 work: function () {
1178 var reqBase, splits, maxQueryLength, q, b, bSource, bGroup, bSourceGroup,
1179 source, group, g, i, modules, maxVersion, sourceLoadScript,
1180 currReqBase, currReqBaseLength, moduleMap, l,
1181 lastDotIndex, prefix, suffix, bytesAdded, async;
1182
1183 // Build a list of request parameters common to all requests.
1184 reqBase = {
1185 skin: mw.config.get( 'skin' ),
1186 lang: mw.config.get( 'wgUserLanguage' ),
1187 debug: mw.config.get( 'debug' )
1188 };
1189 // Split module batch by source and by group.
1190 splits = {};
1191 maxQueryLength = mw.config.get( 'wgResourceLoaderMaxQueryLength', -1 );
1192
1193 // Appends a list of modules from the queue to the batch
1194 for ( q = 0; q < queue.length; q += 1 ) {
1195 // Only request modules which are registered
1196 if ( registry[queue[q]] !== undefined && registry[queue[q]].state === 'registered' ) {
1197 // Prevent duplicate entries
1198 if ( $.inArray( queue[q], batch ) === -1 ) {
1199 batch[batch.length] = queue[q];
1200 // Mark registered modules as loading
1201 registry[queue[q]].state = 'loading';
1202 }
1203 }
1204 }
1205 // Early exit if there's nothing to load...
1206 if ( !batch.length ) {
1207 return;
1208 }
1209
1210 // The queue has been processed into the batch, clear up the queue.
1211 queue = [];
1212
1213 // Always order modules alphabetically to help reduce cache
1214 // misses for otherwise identical content.
1215 batch.sort();
1216
1217 // Split batch by source and by group.
1218 for ( b = 0; b < batch.length; b += 1 ) {
1219 bSource = registry[batch[b]].source;
1220 bGroup = registry[batch[b]].group;
1221 if ( splits[bSource] === undefined ) {
1222 splits[bSource] = {};
1223 }
1224 if ( splits[bSource][bGroup] === undefined ) {
1225 splits[bSource][bGroup] = [];
1226 }
1227 bSourceGroup = splits[bSource][bGroup];
1228 bSourceGroup[bSourceGroup.length] = batch[b];
1229 }
1230
1231 // Clear the batch - this MUST happen before we append any
1232 // script elements to the body or it's possible that a script
1233 // will be locally cached, instantly load, and work the batch
1234 // again, all before we've cleared it causing each request to
1235 // include modules which are already loaded.
1236 batch = [];
1237
1238 for ( source in splits ) {
1239
1240 sourceLoadScript = sources[source].loadScript;
1241
1242 for ( group in splits[source] ) {
1243
1244 // Cache access to currently selected list of
1245 // modules for this group from this source.
1246 modules = splits[source][group];
1247
1248 // Calculate the highest timestamp
1249 maxVersion = 0;
1250 for ( g = 0; g < modules.length; g += 1 ) {
1251 if ( registry[modules[g]].version > maxVersion ) {
1252 maxVersion = registry[modules[g]].version;
1253 }
1254 }
1255
1256 currReqBase = $.extend( { version: formatVersionNumber( maxVersion ) }, reqBase );
1257 // For user modules append a user name to the request.
1258 if ( group === 'user' && mw.config.get( 'wgUserName' ) !== null ) {
1259 currReqBase.user = mw.config.get( 'wgUserName' );
1260 }
1261 currReqBaseLength = $.param( currReqBase ).length;
1262 async = true;
1263 // We may need to split up the request to honor the query string length limit,
1264 // so build it piece by piece.
1265 l = currReqBaseLength + 9; // '&modules='.length == 9
1266
1267 moduleMap = {}; // { prefix: [ suffixes ] }
1268
1269 for ( i = 0; i < modules.length; i += 1 ) {
1270 // Determine how many bytes this module would add to the query string
1271 lastDotIndex = modules[i].lastIndexOf( '.' );
1272 // Note that these substr() calls work even if lastDotIndex == -1
1273 prefix = modules[i].substr( 0, lastDotIndex );
1274 suffix = modules[i].substr( lastDotIndex + 1 );
1275 bytesAdded = moduleMap[prefix] !== undefined
1276 ? suffix.length + 3 // '%2C'.length == 3
1277 : modules[i].length + 3; // '%7C'.length == 3
1278
1279 // If the request would become too long, create a new one,
1280 // but don't create empty requests
1281 if ( maxQueryLength > 0 && !$.isEmptyObject( moduleMap ) && l + bytesAdded > maxQueryLength ) {
1282 // This request would become too long, create a new one
1283 // and fire off the old one
1284 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1285 moduleMap = {};
1286 async = true;
1287 l = currReqBaseLength + 9;
1288 }
1289 if ( moduleMap[prefix] === undefined ) {
1290 moduleMap[prefix] = [];
1291 }
1292 moduleMap[prefix].push( suffix );
1293 if ( !registry[modules[i]].async ) {
1294 // If this module is blocking, make the entire request blocking
1295 // This is slightly suboptimal, but in practice mixing of blocking
1296 // and async modules will only occur in debug mode.
1297 async = false;
1298 }
1299 l += bytesAdded;
1300 }
1301 // If there's anything left in moduleMap, request that too
1302 if ( !$.isEmptyObject( moduleMap ) ) {
1303 doRequest( moduleMap, currReqBase, sourceLoadScript, async );
1304 }
1305 }
1306 }
1307 },
1308
1309 /**
1310 * Register a source.
1311 *
1312 * @param {string} id Short lowercase a-Z string representing a source, only used internally.
1313 * @param {Object} props Object containing only the loadScript property which is a url to
1314 * the load.php location of the source.
1315 * @return {boolean}
1316 */
1317 addSource: function ( id, props ) {
1318 var source;
1319 // Allow multiple additions
1320 if ( typeof id === 'object' ) {
1321 for ( source in id ) {
1322 mw.loader.addSource( source, id[source] );
1323 }
1324 return true;
1325 }
1326
1327 if ( sources[id] !== undefined ) {
1328 throw new Error( 'source already registered: ' + id );
1329 }
1330
1331 sources[id] = props;
1332
1333 return true;
1334 },
1335
1336 /**
1337 * Register a module, letting the system know about it and its
1338 * properties. Startup modules contain calls to this function.
1339 *
1340 * @param {string} module Module name
1341 * @param {number} version Module version number as a timestamp (falls backs to 0)
1342 * @param {string|Array|Function} dependencies One string or array of strings of module
1343 * names on which this module depends, or a function that returns that array.
1344 * @param {string} [group=null] Group which the module is in
1345 * @param {string} [source='local'] Name of the source
1346 */
1347 register: function ( module, version, dependencies, group, source ) {
1348 var m;
1349 // Allow multiple registration
1350 if ( typeof module === 'object' ) {
1351 for ( m = 0; m < module.length; m += 1 ) {
1352 // module is an array of module names
1353 if ( typeof module[m] === 'string' ) {
1354 mw.loader.register( module[m] );
1355 // module is an array of arrays
1356 } else if ( typeof module[m] === 'object' ) {
1357 mw.loader.register.apply( mw.loader, module[m] );
1358 }
1359 }
1360 return;
1361 }
1362 // Validate input
1363 if ( typeof module !== 'string' ) {
1364 throw new Error( 'module must be a string, not a ' + typeof module );
1365 }
1366 if ( registry[module] !== undefined ) {
1367 throw new Error( 'module already registered: ' + module );
1368 }
1369 // List the module as registered
1370 registry[module] = {
1371 version: version !== undefined ? parseInt( version, 10 ) : 0,
1372 dependencies: [],
1373 group: typeof group === 'string' ? group : null,
1374 source: typeof source === 'string' ? source: 'local',
1375 state: 'registered'
1376 };
1377 if ( typeof dependencies === 'string' ) {
1378 // Allow dependencies to be given as a single module name
1379 registry[module].dependencies = [ dependencies ];
1380 } else if ( typeof dependencies === 'object' || $.isFunction( dependencies ) ) {
1381 // Allow dependencies to be given as an array of module names
1382 // or a function which returns an array
1383 registry[module].dependencies = dependencies;
1384 }
1385 },
1386
1387 /**
1388 * Implement a module given the components that make up the module.
1389 *
1390 * When #load or #using requests one or more modules, the server
1391 * response contain calls to this function.
1392 *
1393 * All arguments are required.
1394 *
1395 * @param {string} module Name of module
1396 * @param {Function|Array} script Function with module code or Array of URLs to
1397 * be used as the src attribute of a new `<script>` tag.
1398 * @param {Object} style Should follow one of the following patterns:
1399 * { "css": [css, ..] }
1400 * { "url": { <media>: [url, ..] } }
1401 * And for backwards compatibility (needs to be supported forever due to caching):
1402 * { <media>: css }
1403 * { <media>: [url, ..] }
1404 *
1405 * The reason css strings are not concatenated anymore is bug 31676. We now check
1406 * whether it's safe to extend the stylesheet (see #canExpandStylesheetWith).
1407 *
1408 * @param {Object} msgs List of key/value pairs to be added to {@link mw#messages}.
1409 */
1410 implement: function ( module, script, style, msgs ) {
1411 // Validate input
1412 if ( typeof module !== 'string' ) {
1413 throw new Error( 'module must be a string, not a ' + typeof module );
1414 }
1415 if ( !$.isFunction( script ) && !$.isArray( script ) ) {
1416 throw new Error( 'script must be a function or an array, not a ' + typeof script );
1417 }
1418 if ( !$.isPlainObject( style ) ) {
1419 throw new Error( 'style must be an object, not a ' + typeof style );
1420 }
1421 if ( !$.isPlainObject( msgs ) ) {
1422 throw new Error( 'msgs must be an object, not a ' + typeof msgs );
1423 }
1424 // Automatically register module
1425 if ( registry[module] === undefined ) {
1426 mw.loader.register( module );
1427 }
1428 // Check for duplicate implementation
1429 if ( registry[module] !== undefined && registry[module].script !== undefined ) {
1430 throw new Error( 'module already implemented: ' + module );
1431 }
1432 // Attach components
1433 registry[module].script = script;
1434 registry[module].style = style;
1435 registry[module].messages = msgs;
1436 // The module may already have been marked as erroneous
1437 if ( $.inArray( registry[module].state, ['error', 'missing'] ) === -1 ) {
1438 registry[module].state = 'loaded';
1439 if ( allReady( registry[module].dependencies ) ) {
1440 execute( module );
1441 }
1442 }
1443 },
1444
1445 /**
1446 * Execute a function as soon as one or more required modules are ready.
1447 *
1448 * @param {string|Array} dependencies Module name or array of modules names the callback
1449 * dependends on to be ready before executing
1450 * @param {Function} [ready] callback to execute when all dependencies are ready
1451 * @param {Function} [error] callback to execute when if dependencies have a errors
1452 */
1453 using: function ( dependencies, ready, error ) {
1454 var tod = typeof dependencies;
1455 // Validate input
1456 if ( tod !== 'object' && tod !== 'string' ) {
1457 throw new Error( 'dependencies must be a string or an array, not a ' + tod );
1458 }
1459 // Allow calling with a single dependency as a string
1460 if ( tod === 'string' ) {
1461 dependencies = [ dependencies ];
1462 }
1463 // Resolve entire dependency map
1464 dependencies = resolve( dependencies );
1465 if ( allReady( dependencies ) ) {
1466 // Run ready immediately
1467 if ( $.isFunction( ready ) ) {
1468 ready();
1469 }
1470 } else if ( filter( ['error', 'missing'], dependencies ).length ) {
1471 // Execute error immediately if any dependencies have errors
1472 if ( $.isFunction( error ) ) {
1473 error( new Error( 'one or more dependencies have state "error" or "missing"' ),
1474 dependencies );
1475 }
1476 } else {
1477 // Not all dependencies are ready: queue up a request
1478 request( dependencies, ready, error );
1479 }
1480 },
1481
1482 /**
1483 * Load an external script or one or more modules.
1484 *
1485 * @param {string|Array} modules Either the name of a module, array of modules,
1486 * or a URL of an external script or style
1487 * @param {string} [type='text/javascript'] mime-type to use if calling with a URL of an
1488 * external script or style; acceptable values are "text/css" and
1489 * "text/javascript"; if no type is provided, text/javascript is assumed.
1490 * @param {boolean} [async] If true, load modules asynchronously
1491 * even if document ready has not yet occurred. If false, block before
1492 * document ready and load async after. If not set, true will be
1493 * assumed if loading a URL, and false will be assumed otherwise.
1494 */
1495 load: function ( modules, type, async ) {
1496 var filtered, m, module, l;
1497
1498 // Validate input
1499 if ( typeof modules !== 'object' && typeof modules !== 'string' ) {
1500 throw new Error( 'modules must be a string or an array, not a ' + typeof modules );
1501 }
1502 // Allow calling with an external url or single dependency as a string
1503 if ( typeof modules === 'string' ) {
1504 // Support adding arbitrary external scripts
1505 if ( /^(https?:)?\/\//.test( modules ) ) {
1506 if ( async === undefined ) {
1507 // Assume async for bug 34542
1508 async = true;
1509 }
1510 if ( type === 'text/css' ) {
1511 // IE7-8 throws security warnings when inserting a <link> tag
1512 // with a protocol-relative URL set though attributes (instead of
1513 // properties) - when on HTTPS. See also bug #.
1514 l = document.createElement( 'link' );
1515 l.rel = 'stylesheet';
1516 l.href = modules;
1517 $( 'head' ).append( l );
1518 return;
1519 }
1520 if ( type === 'text/javascript' || type === undefined ) {
1521 addScript( modules, null, async );
1522 return;
1523 }
1524 // Unknown type
1525 throw new Error( 'invalid type for external url, must be text/css or text/javascript. not ' + type );
1526 }
1527 // Called with single module
1528 modules = [ modules ];
1529 }
1530
1531 // Filter out undefined modules, otherwise resolve() will throw
1532 // an exception for trying to load an undefined module.
1533 // Undefined modules are acceptable here in load(), because load() takes
1534 // an array of unrelated modules, whereas the modules passed to
1535 // using() are related and must all be loaded.
1536 for ( filtered = [], m = 0; m < modules.length; m += 1 ) {
1537 module = registry[modules[m]];
1538 if ( module !== undefined ) {
1539 if ( $.inArray( module.state, ['error', 'missing'] ) === -1 ) {
1540 filtered[filtered.length] = modules[m];
1541 }
1542 }
1543 }
1544
1545 if ( filtered.length === 0 ) {
1546 return;
1547 }
1548 // Resolve entire dependency map
1549 filtered = resolve( filtered );
1550 // If all modules are ready, nothing to be done
1551 if ( allReady( filtered ) ) {
1552 return;
1553 }
1554 // If any modules have errors: also quit.
1555 if ( filter( ['error', 'missing'], filtered ).length ) {
1556 return;
1557 }
1558 // Since some modules are not yet ready, queue up a request.
1559 request( filtered, undefined, undefined, async );
1560 },
1561
1562 /**
1563 * Change the state of one or more modules.
1564 *
1565 * @param {string|Object} module module name or object of module name/state pairs
1566 * @param {string} state state name
1567 */
1568 state: function ( module, state ) {
1569 var m;
1570
1571 if ( typeof module === 'object' ) {
1572 for ( m in module ) {
1573 mw.loader.state( m, module[m] );
1574 }
1575 return;
1576 }
1577 if ( registry[module] === undefined ) {
1578 mw.loader.register( module );
1579 }
1580 if ( $.inArray( state, ['ready', 'error', 'missing'] ) !== -1
1581 && registry[module].state !== state ) {
1582 // Make sure pending modules depending on this one get executed if their
1583 // dependencies are now fulfilled!
1584 registry[module].state = state;
1585 handlePending( module );
1586 } else {
1587 registry[module].state = state;
1588 }
1589 },
1590
1591 /**
1592 * Get the version of a module.
1593 *
1594 * @param {string} module Name of module to get version for
1595 */
1596 getVersion: function ( module ) {
1597 if ( registry[module] !== undefined && registry[module].version !== undefined ) {
1598 return formatVersionNumber( registry[module].version );
1599 }
1600 return null;
1601 },
1602
1603 /**
1604 * @inheritdoc #getVersion
1605 * @deprecated since 1.18 use #getVersion instead
1606 */
1607 version: function () {
1608 return mw.loader.getVersion.apply( mw.loader, arguments );
1609 },
1610
1611 /**
1612 * Get the state of a module.
1613 *
1614 * @param {string} module name of module to get state for
1615 */
1616 getState: function ( module ) {
1617 if ( registry[module] !== undefined && registry[module].state !== undefined ) {
1618 return registry[module].state;
1619 }
1620 return null;
1621 },
1622
1623 /**
1624 * Get names of all registered modules.
1625 *
1626 * @return {Array}
1627 */
1628 getModuleNames: function () {
1629 return $.map( registry, function ( i, key ) {
1630 return key;
1631 } );
1632 },
1633
1634 /**
1635 * Load the `mediawiki.user` module.
1636 *
1637 * For backwards-compatibility with cached pages from before 2013 where:
1638 *
1639 * - the `mediawiki.user` module didn't exist yet
1640 * - `mw.user` was still part of mediawiki.js
1641 * - `mw.loader.go` still existed and called after `mw.loader.load()`
1642 */
1643 go: function () {
1644 mw.loader.load( 'mediawiki.user' );
1645 }
1646 };
1647 }() ),
1648
1649 /**
1650 * HTML construction helper functions
1651 * @class mw.html
1652 * @singleton
1653 */
1654 html: ( function () {
1655 function escapeCallback( s ) {
1656 switch ( s ) {
1657 case '\'':
1658 return '&#039;';
1659 case '"':
1660 return '&quot;';
1661 case '<':
1662 return '&lt;';
1663 case '>':
1664 return '&gt;';
1665 case '&':
1666 return '&amp;';
1667 }
1668 }
1669
1670 return {
1671 /**
1672 * Escape a string for HTML. Converts special characters to HTML entities.
1673 * @param {string} s The string to escape
1674 */
1675 escape: function ( s ) {
1676 return s.replace( /['"<>&]/g, escapeCallback );
1677 },
1678
1679 /**
1680 * Wrapper object for raw HTML passed to mw.html.element().
1681 * @class mw.html.Raw
1682 */
1683 Raw: function ( value ) {
1684 this.value = value;
1685 },
1686
1687 /**
1688 * Wrapper object for CDATA element contents passed to mw.html.element()
1689 * @class mw.html.Cdata
1690 */
1691 Cdata: function ( value ) {
1692 this.value = value;
1693 },
1694
1695 /**
1696 * Create an HTML element string, with safe escaping.
1697 *
1698 * @param {string} name The tag name.
1699 * @param {Object} attrs An object with members mapping element names to values
1700 * @param {Mixed} contents The contents of the element. May be either:
1701 * - string: The string is escaped.
1702 * - null or undefined: The short closing form is used, e.g. <br/>.
1703 * - this.Raw: The value attribute is included without escaping.
1704 * - this.Cdata: The value attribute is included, and an exception is
1705 * thrown if it contains an illegal ETAGO delimiter.
1706 * See http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.3.2
1707 *
1708 * Example:
1709 * var h = mw.html;
1710 * return h.element( 'div', {},
1711 * new h.Raw( h.element( 'img', {src: '<'} ) ) );
1712 * Returns <div><img src="&lt;"/></div>
1713 */
1714 element: function ( name, attrs, contents ) {
1715 var v, attrName, s = '<' + name;
1716
1717 for ( attrName in attrs ) {
1718 v = attrs[attrName];
1719 // Convert name=true, to name=name
1720 if ( v === true ) {
1721 v = attrName;
1722 // Skip name=false
1723 } else if ( v === false ) {
1724 continue;
1725 }
1726 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
1727 }
1728 if ( contents === undefined || contents === null ) {
1729 // Self close tag
1730 s += '/>';
1731 return s;
1732 }
1733 // Regular open tag
1734 s += '>';
1735 switch ( typeof contents ) {
1736 case 'string':
1737 // Escaped
1738 s += this.escape( contents );
1739 break;
1740 case 'number':
1741 case 'boolean':
1742 // Convert to string
1743 s += String( contents );
1744 break;
1745 default:
1746 if ( contents instanceof this.Raw ) {
1747 // Raw HTML inclusion
1748 s += contents.value;
1749 } else if ( contents instanceof this.Cdata ) {
1750 // CDATA
1751 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
1752 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
1753 }
1754 s += contents.value;
1755 } else {
1756 throw new Error( 'mw.html.element: Invalid type of contents' );
1757 }
1758 }
1759 s += '</' + name + '>';
1760 return s;
1761 }
1762 };
1763 }() ),
1764
1765 // Skeleton user object. mediawiki.user.js extends this
1766 user: {
1767 options: new Map(),
1768 tokens: new Map()
1769 },
1770
1771 /**
1772 * Registry and firing of events.
1773 *
1774 * MediaWiki has various interface components that are extended, enhanced
1775 * or manipulated in some other way by extensions, gadgets and even
1776 * in core itself.
1777 *
1778 * This framework helps streamlining the timing of when these other
1779 * code paths fire their plugins (instead of using document-ready,
1780 * which can and should be limited to firing only once).
1781 *
1782 * Features like navigating to other wiki pages, previewing an edit
1783 * and editing itself – without a refresh – can then retrigger these
1784 * hooks accordingly to ensure everything still works as expected.
1785 *
1786 * Example usage:
1787 *
1788 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
1789 * mw.hook( 'wikipage.content' ).fire( $content );
1790 *
1791 * Handlers can be added and fired for arbitrary event names at any time. The same
1792 * event can be fired multiple times. The last run of an event is memorized
1793 * (similar to `$(document).ready` and `$.Deferred().done`).
1794 * This means if an event is fired, and a handler added afterwards, the added
1795 * function will be fired right away with the last given event data.
1796 *
1797 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
1798 * Thus allowing flexible use and optimal maintainability and authority control.
1799 * You can pass around the `add` and/or `fire` method to another piece of code
1800 * without it having to know the event name (or `mw.hook` for that matter).
1801 *
1802 * var h = mw.hook( 'bar.ready' );
1803 * new mw.Foo( .. ).fetch( { callback: h.fire } );
1804 *
1805 * @class mw.hook
1806 */
1807 hook: ( function () {
1808 var lists = {};
1809
1810 /**
1811 * Create an instance of mw.hook.
1812 *
1813 * @method hook
1814 * @member mw
1815 * @param {string} name Name of hook.
1816 * @return {mw.hook}
1817 */
1818 return function ( name ) {
1819 var list = lists[name] || ( lists[name] = $.Callbacks( 'memory' ) );
1820
1821 return {
1822 /**
1823 * Register a hook handler
1824 * @param {Function...} handler Function to bind.
1825 * @chainable
1826 */
1827 add: list.add,
1828
1829 /**
1830 * Unregister a hook handler
1831 * @param {Function...} handler Function to unbind.
1832 * @chainable
1833 */
1834 remove: list.remove,
1835
1836 /**
1837 * Run a hook.
1838 * @param {Mixed...} data
1839 * @chainable
1840 */
1841 fire: function () {
1842 return list.fireWith( null, slice.call( arguments ) );
1843 }
1844 };
1845 };
1846 }() )
1847 };
1848
1849 }( jQuery ) );
1850
1851 // Alias $j to jQuery for backwards compatibility
1852 window.$j = jQuery;
1853
1854 // Attach to window and globally alias
1855 window.mw = window.mediaWiki = mw;
1856
1857 // Auto-register from pre-loaded startup scripts
1858 if ( jQuery.isFunction( window.startUp ) ) {
1859 window.startUp();
1860 window.startUp = undefined;
1861 }