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