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