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