2 * This file is currently loaded as part of the 'mediawiki' module and therefore
3 * concatenated to mediawiki.js and executed at the same time. This file exists
4 * to help prepare for splitting up the 'mediawiki' module.
5 * This effort is tracked at https://phabricator.wikimedia.org/T192623
9 * - mediawiki.js will be reduced to the minimum needed to define mw.loader and
10 * mw.config, and then moved to its own private "mediawiki.loader" module that
11 * can be embedded within the StartupModule response.
13 * - mediawiki.base.js and other files in this directory will remain part of the
14 * "mediawiki" module, and will remain a default/implicit dependency for all
15 * regular modules, just like jquery and wikibits already are.
21 var slice
= Array
.prototype.slice
,
22 mwLoaderTrack
= mw
.track
,
23 trackCallbacks
= $.Callbacks( 'memory' ),
28 * Object constructor for messages.
30 * Similar to the Message class in MediaWiki PHP.
32 * Format defaults to 'text'.
38 * 'hello': 'Hello world',
39 * 'hello-user': 'Hello, $1!',
40 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
43 * obj = new mw.Message( mw.messages, 'hello' );
44 * mw.log( obj.text() );
47 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
48 * mw.log( obj.text() );
51 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
52 * mw.log( obj.text() );
53 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
55 * // Using mw.message shortcut
56 * obj = mw.message( 'hello-user', 'John Doe' );
57 * mw.log( obj.text() );
60 * // Using mw.msg shortcut
61 * str = mw.msg( 'hello-user', 'John Doe' );
65 * // Different formats
66 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
68 * obj.format = 'text';
69 * str = obj.toString();
74 * // Hello, John "Wiki" <3 Doe!
76 * mw.log( obj.escaped() );
77 * // Hello, John "Wiki" <3 Doe!
82 * @param {mw.Map} map Message store
84 * @param {Array} [parameters]
86 function Message( map
, key
, parameters
) {
90 this.parameters
= parameters
=== undefined ? [] : slice
.call( parameters
);
96 * Get parsed contents of the message.
98 * The default parser does simple $N replacements and nothing else.
99 * This may be overridden to provide a more complex message parser.
100 * The primary override is in the mediawiki.jqueryMsg module.
102 * This function will not be called for nonexistent messages.
104 * @return {string} Parsed message
106 parser: function () {
107 return mw
.format
.apply( null, [ this.map
.get( this.key
) ].concat( this.parameters
) );
111 * Add (does not replace) parameters for `$N` placeholder values.
113 * @param {Array} parameters
114 * @return {mw.Message}
117 params: function ( parameters
) {
119 for ( i
= 0; i
< parameters
.length
; i
++ ) {
120 this.parameters
.push( parameters
[ i
] );
126 * Convert message object to its string form based on current format.
128 * @return {string} Message as a string in the current form, or `<key>` if key
131 toString: function () {
134 if ( !this.exists() ) {
135 // Use ⧼key⧽ as text if key does not exist
136 // Err on the side of safety, ensure that the output
137 // is always html safe in the event the message key is
138 // missing, since in that case its highly likely the
139 // message key is user-controlled.
140 // '⧼' is used instead of '<' to side-step any
141 // double-escaping issues.
142 // (Keep synchronised with Message::toString() in PHP.)
143 return '⧼' + mw
.html
.escape( this.key
) + '⧽';
146 if ( this.format
=== 'plain' || this.format
=== 'text' || this.format
=== 'parse' ) {
147 text
= this.parser();
150 if ( this.format
=== 'escaped' ) {
151 text
= this.parser();
152 text
= mw
.html
.escape( text
);
159 * Change format to 'parse' and convert message to string
161 * If jqueryMsg is loaded, this parses the message text from wikitext
162 * (where supported) to HTML
164 * Otherwise, it is equivalent to plain.
166 * @return {string} String form of parsed message
169 this.format
= 'parse';
170 return this.toString();
174 * Change format to 'plain' and convert message to string
176 * This substitutes parameters, but otherwise does not change the
179 * @return {string} String form of plain message
182 this.format
= 'plain';
183 return this.toString();
187 * Change format to 'text' and convert message to string
189 * If jqueryMsg is loaded, {{-transformation is done where supported
190 * (such as {{plural:}}, {{gender:}}, {{int:}}).
192 * Otherwise, it is equivalent to plain
194 * @return {string} String form of text message
197 this.format
= 'text';
198 return this.toString();
202 * Change the format to 'escaped' and convert message to string
204 * This is equivalent to using the 'text' format (see #text), then
205 * HTML-escaping the output.
207 * @return {string} String form of html escaped message
209 escaped: function () {
210 this.format
= 'escaped';
211 return this.toString();
215 * Check if a message exists
220 exists: function () {
221 return this.map
.exists( this.key
);
231 * @inheritdoc mw.inspect#runReports
234 mw
.inspect = function () {
235 var args
= arguments
;
237 mw
.loader
.using( 'mediawiki.inspect', function () {
238 mw
.inspect
.runReports
.apply( mw
.inspect
, args
);
243 * Format a string. Replace $1, $2 ... $N with positional arguments.
245 * Used by Message#parser().
248 * @param {string} formatString Format string
249 * @param {...Mixed} parameters Values for $N replacements
250 * @return {string} Formatted string
252 mw
.format = function ( formatString
) {
253 var parameters
= slice
.call( arguments
, 1 );
254 return formatString
.replace( /\$(\d+)/g, function ( str
, match
) {
255 var index
= parseInt( match
, 10 ) - 1;
256 return parameters
[ index
] !== undefined ? parameters
[ index
] : '$' + match
;
260 // Expose Message constructor
261 mw
.Message
= Message
;
264 * Get a message object.
266 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
269 * @param {string} key Key of message to get
270 * @param {...Mixed} parameters Values for $N replacements
271 * @return {mw.Message}
273 mw
.message = function ( key
) {
274 var parameters
= slice
.call( arguments
, 1 );
275 return new Message( mw
.messages
, key
, parameters
);
279 * Get a message string using the (default) 'text' format.
281 * Shortcut for `mw.message( key, parameters... ).text()`.
284 * @param {string} key Key of message to get
285 * @param {...Mixed} parameters Values for $N replacements
288 mw
.msg = function () {
289 return mw
.message
.apply( mw
.message
, arguments
).toString();
293 * Track an analytic event.
295 * This method provides a generic means for MediaWiki JavaScript code to capture state
296 * information for analysis. Each logged event specifies a string topic name that describes
297 * the kind of event that it is. Topic names consist of dot-separated path components,
298 * arranged from most general to most specific. Each path component should have a clear and
299 * well-defined purpose.
301 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
302 * events that match their subcription, including those that fired before the handler was
305 * @param {string} topic Topic name
306 * @param {Object} [data] Data describing the event, encoded as an object
308 mw
.track = function ( topic
, data
) {
309 mwLoaderTrack( topic
, data
);
310 trackCallbacks
.fire( mw
.trackQueue
);
314 * Register a handler for subset of analytic events, specified by topic.
316 * Handlers will be called once for each tracked event, including any events that fired before the
317 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
318 * the exact time at which the event fired, a string 'topic' property naming the event, and a
319 * 'data' property which is an object of event-specific data. The event topic and event data are
320 * also passed to the callback as the first and second arguments, respectively.
322 * @param {string} topic Handle events whose name starts with this string prefix
323 * @param {Function} callback Handler to call for each matching tracked event
324 * @param {string} callback.topic
325 * @param {Object} [callback.data]
327 mw
.trackSubscribe = function ( topic
, callback
) {
329 function handler( trackQueue
) {
331 for ( ; seen
< trackQueue
.length
; seen
++ ) {
332 event
= trackQueue
[ seen
];
333 if ( event
.topic
.indexOf( topic
) === 0 ) {
334 callback
.call( event
, event
.topic
, event
.data
);
339 trackHandlers
.push( [ handler
, callback
] );
341 trackCallbacks
.add( handler
);
345 * Stop handling events for a particular handler
347 * @param {Function} callback
349 mw
.trackUnsubscribe = function ( callback
) {
350 trackHandlers
= trackHandlers
.filter( function ( fns
) {
351 if ( fns
[ 1 ] === callback
) {
352 trackCallbacks
.remove( fns
[ 0 ] );
353 // Ensure the tuple is removed to avoid holding on to closures
360 // Fire events from before track() triggred fire()
361 trackCallbacks
.fire( mw
.trackQueue
);
364 * Registry and firing of events.
366 * MediaWiki has various interface components that are extended, enhanced
367 * or manipulated in some other way by extensions, gadgets and even
370 * This framework helps streamlining the timing of when these other
371 * code paths fire their plugins (instead of using document-ready,
372 * which can and should be limited to firing only once).
374 * Features like navigating to other wiki pages, previewing an edit
375 * and editing itself – without a refresh – can then retrigger these
376 * hooks accordingly to ensure everything still works as expected.
380 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
381 * mw.hook( 'wikipage.content' ).fire( $content );
383 * Handlers can be added and fired for arbitrary event names at any time. The same
384 * event can be fired multiple times. The last run of an event is memorized
385 * (similar to `$(document).ready` and `$.Deferred().done`).
386 * This means if an event is fired, and a handler added afterwards, the added
387 * function will be fired right away with the last given event data.
389 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
390 * Thus allowing flexible use and optimal maintainability and authority control.
391 * You can pass around the `add` and/or `fire` method to another piece of code
392 * without it having to know the event name (or `mw.hook` for that matter).
394 * var h = mw.hook( 'bar.ready' );
395 * new mw.Foo( .. ).fetch( { callback: h.fire } );
397 * Note: Events are documented with an underscore instead of a dot in the event
398 * name due to jsduck not supporting dots in that position.
402 mw
.hook
= ( function () {
403 var lists
= Object
.create( null );
406 * Create an instance of mw.hook.
410 * @param {string} name Name of hook.
413 return function ( name
) {
414 var list
= lists
[ name
] || ( lists
[ name
] = $.Callbacks( 'memory' ) );
418 * Register a hook handler
420 * @param {...Function} handler Function to bind.
426 * Unregister a hook handler
428 * @param {...Function} handler Function to unbind.
436 * @param {...Mixed} data
441 return list
.fireWith
.call( this, null, slice
.call( arguments
) );
448 * HTML construction helper functions
455 * output = Html.element( 'div', {}, new Html.Raw(
456 * Html.element( 'img', { src: '<' } )
458 * mw.log( output ); // <div><img src="<"/></div>
463 mw
.html
= ( function () {
464 function escapeCallback( s
) {
481 * Escape a string for HTML.
483 * Converts special characters to HTML entities.
485 * mw.html.escape( '< > \' & "' );
486 * // Returns < > ' & "
488 * @param {string} s The string to escape
489 * @return {string} HTML
491 escape: function ( s
) {
492 return s
.replace( /['"<>&]/g, escapeCallback
);
496 * Create an HTML element string, with safe escaping.
498 * @param {string} name The tag name.
499 * @param {Object} [attrs] An object with members mapping element names to values
500 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
502 * - string: Text to be escaped.
503 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
504 * - this.Raw: The raw value is directly included.
505 * - this.Cdata: The raw value is directly included. An exception is
506 * thrown if it contains any illegal ETAGO delimiter.
507 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
508 * @return {string} HTML
510 element: function ( name
, attrs
, contents
) {
511 var v
, attrName
, s
= '<' + name
;
514 for ( attrName
in attrs
) {
515 v
= attrs
[ attrName
];
516 // Convert name=true, to name=name
520 } else if ( v
=== false ) {
523 s
+= ' ' + attrName
+ '="' + this.escape( String( v
) ) + '"';
526 if ( contents
=== undefined || contents
=== null ) {
533 switch ( typeof contents
) {
536 s
+= this.escape( contents
);
541 s
+= String( contents
);
544 if ( contents
instanceof this.Raw
) {
545 // Raw HTML inclusion
547 } else if ( contents
instanceof this.Cdata
) {
549 if ( /<\/[a-zA-z]/.test( contents
.value
) ) {
550 throw new Error( 'mw.html.element: Illegal end tag found in CDATA' );
554 throw new Error( 'mw.html.element: Invalid type of contents' );
557 s
+= '</' + name
+ '>';
562 * Wrapper object for raw HTML passed to mw.html.element().
566 * @param {string} value
568 Raw: function ( value
) {
573 * Wrapper object for CDATA element contents passed to mw.html.element()
575 * @class mw.html.Cdata
577 * @param {string} value
579 Cdata: function ( value
) {
586 * Execute a function as soon as one or more required modules are ready.
588 * Example of inline dependency on OOjs:
590 * mw.loader.using( 'oojs', function () {
591 * OO.compare( [ 1 ], [ 1 ] );
594 * Example of inline dependency obtained via `require()`:
596 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
597 * var util = require( 'mediawiki.util' );
600 * Since MediaWiki 1.23 this also returns a promise.
602 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
605 * @param {string|Array} dependencies Module name or array of modules names the
606 * callback depends on to be ready before executing
607 * @param {Function} [ready] Callback to execute when all dependencies are ready
608 * @param {Function} [error] Callback to execute if one or more dependencies failed
609 * @return {jQuery.Promise} With a `require` function
611 mw
.loader
.using = function ( dependencies
, ready
, error
) {
612 var deferred
= $.Deferred();
614 // Allow calling with a single dependency as a string
615 if ( typeof dependencies
=== 'string' ) {
616 dependencies
= [ dependencies
];
620 deferred
.done( ready
);
623 deferred
.fail( error
);
627 // Resolve entire dependency map
628 dependencies
= mw
.loader
.resolve( dependencies
);
630 return deferred
.reject( e
).promise();
633 mw
.loader
.enqueue( dependencies
, function () {
634 deferred
.resolve( mw
.loader
.require
);
635 }, deferred
.reject
);
637 return deferred
.promise();
640 // Alias $j to jQuery for backwards compatibility
641 // @deprecated since 1.23 Use $ or jQuery instead
642 mw
.log
.deprecate( window
, '$j', $, 'Use $ or jQuery instead.' );
644 // Process callbacks for Grade A that require modules.
645 // Plain ones were already processed by startup.js.
647 // Redefine publicly to capture any late arrivals
649 push: function ( entry
) {
650 mw
.loader
.using( entry
[ 0 ], entry
[ 1 ] );
653 while ( queue
[ 0 ] ) {
654 window
.RLQ
.push( queue
.shift() );