Support message parameters in JavaScript messages with uselang=qqx
[lhc/web/wiklou.git] / resources / src / mediawiki.base / mediawiki.base.js
1 /*!
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
6 *
7 * In short:
8 *
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.
12 *
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.
16 */
17 ( function () {
18 'use strict';
19
20 var slice = Array.prototype.slice,
21 mwLoaderTrack = mw.track,
22 trackCallbacks = $.Callbacks( 'memory' ),
23 trackHandlers = [],
24 queue;
25
26 /**
27 * Object constructor for messages.
28 *
29 * Similar to the Message class in MediaWiki PHP.
30 *
31 * Format defaults to 'text'.
32 *
33 * @example
34 *
35 * var obj, str;
36 * mw.messages.set( {
37 * 'hello': 'Hello world',
38 * 'hello-user': 'Hello, $1!',
39 * 'welcome-user': 'Welcome back to $2, $1! Last visit by $1: $3'
40 * } );
41 *
42 * obj = new mw.Message( mw.messages, 'hello' );
43 * mw.log( obj.text() );
44 * // Hello world
45 *
46 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John Doe' ] );
47 * mw.log( obj.text() );
48 * // Hello, John Doe!
49 *
50 * obj = new mw.Message( mw.messages, 'welcome-user', [ 'John Doe', 'Wikipedia', '2 hours ago' ] );
51 * mw.log( obj.text() );
52 * // Welcome back to Wikipedia, John Doe! Last visit by John Doe: 2 hours ago
53 *
54 * // Using mw.message shortcut
55 * obj = mw.message( 'hello-user', 'John Doe' );
56 * mw.log( obj.text() );
57 * // Hello, John Doe!
58 *
59 * // Using mw.msg shortcut
60 * str = mw.msg( 'hello-user', 'John Doe' );
61 * mw.log( str );
62 * // Hello, John Doe!
63 *
64 * // Different formats
65 * obj = new mw.Message( mw.messages, 'hello-user', [ 'John "Wiki" <3 Doe' ] );
66 *
67 * obj.format = 'text';
68 * str = obj.toString();
69 * // Same as:
70 * str = obj.text();
71 *
72 * mw.log( str );
73 * // Hello, John "Wiki" <3 Doe!
74 *
75 * mw.log( obj.escaped() );
76 * // Hello, John &quot;Wiki&quot; &lt;3 Doe!
77 *
78 * @class mw.Message
79 *
80 * @constructor
81 * @param {mw.Map} map Message store
82 * @param {string} key
83 * @param {Array} [parameters]
84 */
85 function Message( map, key, parameters ) {
86 this.format = 'text';
87 this.map = map;
88 this.key = key;
89 this.parameters = parameters === undefined ? [] : slice.call( parameters );
90 return this;
91 }
92
93 Message.prototype = {
94 /**
95 * Get parsed contents of the message.
96 *
97 * The default parser does simple $N replacements and nothing else.
98 * This may be overridden to provide a more complex message parser.
99 * The primary override is in the mediawiki.jqueryMsg module.
100 *
101 * This function will not be called for nonexistent messages.
102 *
103 * @return {string} Parsed message
104 */
105 parser: function () {
106 var text;
107 if ( mw.config.get( 'wgUserLanguage' ) === 'qqx' ) {
108 text = '(' + this.key + '$*)';
109 } else {
110 text = this.map.get( this.key );
111 }
112 return mw.format.apply( null, [ text ].concat( this.parameters ) );
113 },
114
115 /**
116 * Add (does not replace) parameters for `$N` placeholder values.
117 *
118 * @param {Array} parameters
119 * @return {mw.Message}
120 * @chainable
121 */
122 params: function ( parameters ) {
123 var i;
124 for ( i = 0; i < parameters.length; i++ ) {
125 this.parameters.push( parameters[ i ] );
126 }
127 return this;
128 },
129
130 /**
131 * Convert message object to its string form based on current format.
132 *
133 * @return {string} Message as a string in the current form, or `<key>` if key
134 * does not exist.
135 */
136 toString: function () {
137 var text;
138
139 if ( !this.exists() ) {
140 // Use ⧼key⧽ as text if key does not exist
141 // Err on the side of safety, ensure that the output
142 // is always html safe in the event the message key is
143 // missing, since in that case its highly likely the
144 // message key is user-controlled.
145 // '⧼' is used instead of '<' to side-step any
146 // double-escaping issues.
147 // (Keep synchronised with Message::toString() in PHP.)
148 return '⧼' + mw.html.escape( this.key ) + '⧽';
149 }
150
151 if ( this.format === 'plain' || this.format === 'text' || this.format === 'parse' ) {
152 text = this.parser();
153 }
154
155 if ( this.format === 'escaped' ) {
156 text = this.parser();
157 text = mw.html.escape( text );
158 }
159
160 return text;
161 },
162
163 /**
164 * Change format to 'parse' and convert message to string
165 *
166 * If jqueryMsg is loaded, this parses the message text from wikitext
167 * (where supported) to HTML
168 *
169 * Otherwise, it is equivalent to plain.
170 *
171 * @return {string} String form of parsed message
172 */
173 parse: function () {
174 this.format = 'parse';
175 return this.toString();
176 },
177
178 /**
179 * Change format to 'plain' and convert message to string
180 *
181 * This substitutes parameters, but otherwise does not change the
182 * message text.
183 *
184 * @return {string} String form of plain message
185 */
186 plain: function () {
187 this.format = 'plain';
188 return this.toString();
189 },
190
191 /**
192 * Change format to 'text' and convert message to string
193 *
194 * If jqueryMsg is loaded, {{-transformation is done where supported
195 * (such as {{plural:}}, {{gender:}}, {{int:}}).
196 *
197 * Otherwise, it is equivalent to plain
198 *
199 * @return {string} String form of text message
200 */
201 text: function () {
202 this.format = 'text';
203 return this.toString();
204 },
205
206 /**
207 * Change the format to 'escaped' and convert message to string
208 *
209 * This is equivalent to using the 'text' format (see #text), then
210 * HTML-escaping the output.
211 *
212 * @return {string} String form of html escaped message
213 */
214 escaped: function () {
215 this.format = 'escaped';
216 return this.toString();
217 },
218
219 /**
220 * Check if a message exists
221 *
222 * @see mw.Map#exists
223 * @return {boolean}
224 */
225 exists: function () {
226 if ( mw.config.get( 'wgUserLanguage' ) === 'qqx' ) {
227 return true;
228 }
229 return this.map.exists( this.key );
230 }
231 };
232
233 /**
234 * @class mw
235 * @singleton
236 */
237
238 /**
239 * @inheritdoc mw.inspect#runReports
240 * @method
241 */
242 mw.inspect = function () {
243 var args = arguments;
244 // Lazy-load
245 mw.loader.using( 'mediawiki.inspect', function () {
246 mw.inspect.runReports.apply( mw.inspect, args );
247 } );
248 };
249
250 /**
251 * Replace $* with a list of parameters for &uselang=qqx.
252 *
253 * @since 1.33
254 * @param {string} formatString Format string
255 * @param {Array} parameters Values for $N replacements
256 * @return {string} Transformed format string
257 */
258 mw.transformFormatForQqx = function ( formatString, parameters ) {
259 var parametersString;
260 if ( formatString.indexOf( '$*' ) !== -1 ) {
261 parametersString = '';
262 if ( parameters.length ) {
263 parametersString = ': ' + parameters.map( function ( _, i ) {
264 return '$' + ( i + 1 );
265 } ).join( ', ' );
266 }
267 return formatString.replace( '$*', parametersString );
268 }
269 return formatString;
270 };
271
272 /**
273 * Format a string. Replace $1, $2 ... $N with positional arguments.
274 *
275 * Used by Message#parser().
276 *
277 * @since 1.25
278 * @param {string} formatString Format string
279 * @param {...Mixed} parameters Values for $N replacements
280 * @return {string} Formatted string
281 */
282 mw.format = function ( formatString ) {
283 var parameters = slice.call( arguments, 1 );
284 formatString = mw.transformFormatForQqx( formatString, parameters );
285 return formatString.replace( /\$(\d+)/g, function ( str, match ) {
286 var index = parseInt( match, 10 ) - 1;
287 return parameters[ index ] !== undefined ? parameters[ index ] : '$' + match;
288 } );
289 };
290
291 // Expose Message constructor
292 mw.Message = Message;
293
294 /**
295 * Get a message object.
296 *
297 * Shortcut for `new mw.Message( mw.messages, key, parameters )`.
298 *
299 * @see mw.Message
300 * @param {string} key Key of message to get
301 * @param {...Mixed} parameters Values for $N replacements
302 * @return {mw.Message}
303 */
304 mw.message = function ( key ) {
305 var parameters = slice.call( arguments, 1 );
306 return new Message( mw.messages, key, parameters );
307 };
308
309 /**
310 * Get a message string using the (default) 'text' format.
311 *
312 * Shortcut for `mw.message( key, parameters... ).text()`.
313 *
314 * @see mw.Message
315 * @param {string} key Key of message to get
316 * @param {...Mixed} parameters Values for $N replacements
317 * @return {string}
318 */
319 mw.msg = function () {
320 return mw.message.apply( mw.message, arguments ).toString();
321 };
322
323 /**
324 * Track an analytic event.
325 *
326 * This method provides a generic means for MediaWiki JavaScript code to capture state
327 * information for analysis. Each logged event specifies a string topic name that describes
328 * the kind of event that it is. Topic names consist of dot-separated path components,
329 * arranged from most general to most specific. Each path component should have a clear and
330 * well-defined purpose.
331 *
332 * Data handlers are registered via `mw.trackSubscribe`, and receive the full set of
333 * events that match their subcription, including those that fired before the handler was
334 * bound.
335 *
336 * @param {string} topic Topic name
337 * @param {Object} [data] Data describing the event, encoded as an object
338 */
339 mw.track = function ( topic, data ) {
340 mwLoaderTrack( topic, data );
341 trackCallbacks.fire( mw.trackQueue );
342 };
343
344 /**
345 * Register a handler for subset of analytic events, specified by topic.
346 *
347 * Handlers will be called once for each tracked event, including any events that fired before the
348 * handler was registered; 'this' is set to a plain object with a 'timeStamp' property indicating
349 * the exact time at which the event fired, a string 'topic' property naming the event, and a
350 * 'data' property which is an object of event-specific data. The event topic and event data are
351 * also passed to the callback as the first and second arguments, respectively.
352 *
353 * @param {string} topic Handle events whose name starts with this string prefix
354 * @param {Function} callback Handler to call for each matching tracked event
355 * @param {string} callback.topic
356 * @param {Object} [callback.data]
357 */
358 mw.trackSubscribe = function ( topic, callback ) {
359 var seen = 0;
360 function handler( trackQueue ) {
361 var event;
362 for ( ; seen < trackQueue.length; seen++ ) {
363 event = trackQueue[ seen ];
364 if ( event.topic.indexOf( topic ) === 0 ) {
365 callback.call( event, event.topic, event.data );
366 }
367 }
368 }
369
370 trackHandlers.push( [ handler, callback ] );
371
372 trackCallbacks.add( handler );
373 };
374
375 /**
376 * Stop handling events for a particular handler
377 *
378 * @param {Function} callback
379 */
380 mw.trackUnsubscribe = function ( callback ) {
381 trackHandlers = trackHandlers.filter( function ( fns ) {
382 if ( fns[ 1 ] === callback ) {
383 trackCallbacks.remove( fns[ 0 ] );
384 // Ensure the tuple is removed to avoid holding on to closures
385 return false;
386 }
387 return true;
388 } );
389 };
390
391 // Fire events from before track() triggered fire()
392 trackCallbacks.fire( mw.trackQueue );
393
394 /**
395 * Registry and firing of events.
396 *
397 * MediaWiki has various interface components that are extended, enhanced
398 * or manipulated in some other way by extensions, gadgets and even
399 * in core itself.
400 *
401 * This framework helps streamlining the timing of when these other
402 * code paths fire their plugins (instead of using document-ready,
403 * which can and should be limited to firing only once).
404 *
405 * Features like navigating to other wiki pages, previewing an edit
406 * and editing itself – without a refresh – can then retrigger these
407 * hooks accordingly to ensure everything still works as expected.
408 *
409 * Example usage:
410 *
411 * mw.hook( 'wikipage.content' ).add( fn ).remove( fn );
412 * mw.hook( 'wikipage.content' ).fire( $content );
413 *
414 * Handlers can be added and fired for arbitrary event names at any time. The same
415 * event can be fired multiple times. The last run of an event is memorized
416 * (similar to `$(document).ready` and `$.Deferred().done`).
417 * This means if an event is fired, and a handler added afterwards, the added
418 * function will be fired right away with the last given event data.
419 *
420 * Like Deferreds and Promises, the mw.hook object is both detachable and chainable.
421 * Thus allowing flexible use and optimal maintainability and authority control.
422 * You can pass around the `add` and/or `fire` method to another piece of code
423 * without it having to know the event name (or `mw.hook` for that matter).
424 *
425 * var h = mw.hook( 'bar.ready' );
426 * new mw.Foo( .. ).fetch( { callback: h.fire } );
427 *
428 * Note: Events are documented with an underscore instead of a dot in the event
429 * name due to jsduck not supporting dots in that position.
430 *
431 * @class mw.hook
432 */
433 mw.hook = ( function () {
434 var lists = Object.create( null );
435
436 /**
437 * Create an instance of mw.hook.
438 *
439 * @method hook
440 * @member mw
441 * @param {string} name Name of hook.
442 * @return {mw.hook}
443 */
444 return function ( name ) {
445 var list = lists[ name ] || ( lists[ name ] = $.Callbacks( 'memory' ) );
446
447 return {
448 /**
449 * Register a hook handler
450 *
451 * @param {...Function} handler Function to bind.
452 * @chainable
453 */
454 add: list.add,
455
456 /**
457 * Unregister a hook handler
458 *
459 * @param {...Function} handler Function to unbind.
460 * @chainable
461 */
462 remove: list.remove,
463
464 /**
465 * Run a hook.
466 *
467 * @param {...Mixed} data
468 * @return {mw.hook}
469 * @chainable
470 */
471 fire: function () {
472 return list.fireWith.call( this, null, slice.call( arguments ) );
473 }
474 };
475 };
476 }() );
477
478 /**
479 * HTML construction helper functions
480 *
481 * @example
482 *
483 * var Html, output;
484 *
485 * Html = mw.html;
486 * output = Html.element( 'div', {}, new Html.Raw(
487 * Html.element( 'img', { src: '<' } )
488 * ) );
489 * mw.log( output ); // <div><img src="&lt;"/></div>
490 *
491 * @class mw.html
492 * @singleton
493 */
494 mw.html = ( function () {
495 function escapeCallback( s ) {
496 switch ( s ) {
497 case '\'':
498 return '&#039;';
499 case '"':
500 return '&quot;';
501 case '<':
502 return '&lt;';
503 case '>':
504 return '&gt;';
505 case '&':
506 return '&amp;';
507 }
508 }
509
510 return {
511 /**
512 * Escape a string for HTML.
513 *
514 * Converts special characters to HTML entities.
515 *
516 * mw.html.escape( '< > \' & "' );
517 * // Returns &lt; &gt; &#039; &amp; &quot;
518 *
519 * @param {string} s The string to escape
520 * @return {string} HTML
521 */
522 escape: function ( s ) {
523 return s.replace( /['"<>&]/g, escapeCallback );
524 },
525
526 /**
527 * Create an HTML element string, with safe escaping.
528 *
529 * @param {string} name The tag name.
530 * @param {Object} [attrs] An object with members mapping element names to values
531 * @param {string|mw.html.Raw|mw.html.Cdata|null} [contents=null] The contents of the element.
532 *
533 * - string: Text to be escaped.
534 * - null: The element is treated as void with short closing form, e.g. `<br/>`.
535 * - this.Raw: The raw value is directly included.
536 * - this.Cdata: The raw value is directly included. An exception is
537 * thrown if it contains any illegal ETAGO delimiter.
538 * See <https://www.w3.org/TR/html401/appendix/notes.html#h-B.3.2>.
539 * @return {string} HTML
540 */
541 element: function ( name, attrs, contents ) {
542 var v, attrName, s = '<' + name;
543
544 if ( attrs ) {
545 for ( attrName in attrs ) {
546 v = attrs[ attrName ];
547 // Convert name=true, to name=name
548 if ( v === true ) {
549 v = attrName;
550 // Skip name=false
551 } else if ( v === false ) {
552 continue;
553 }
554 s += ' ' + attrName + '="' + this.escape( String( v ) ) + '"';
555 }
556 }
557 if ( contents === undefined || contents === null ) {
558 // Self close tag
559 s += '/>';
560 return s;
561 }
562 // Regular open tag
563 s += '>';
564 switch ( typeof contents ) {
565 case 'string':
566 // Escaped
567 s += this.escape( contents );
568 break;
569 case 'number':
570 case 'boolean':
571 // Convert to string
572 s += String( contents );
573 break;
574 default:
575 if ( contents instanceof this.Raw ) {
576 // Raw HTML inclusion
577 s += contents.value;
578 } else if ( contents instanceof this.Cdata ) {
579 // CDATA
580 if ( /<\/[a-zA-z]/.test( contents.value ) ) {
581 throw new Error( 'Illegal end tag found in CDATA' );
582 }
583 s += contents.value;
584 } else {
585 throw new Error( 'Invalid type of contents' );
586 }
587 }
588 s += '</' + name + '>';
589 return s;
590 },
591
592 /**
593 * Wrapper object for raw HTML passed to mw.html.element().
594 *
595 * @class mw.html.Raw
596 * @constructor
597 * @param {string} value
598 */
599 Raw: function ( value ) {
600 this.value = value;
601 },
602
603 /**
604 * Wrapper object for CDATA element contents passed to mw.html.element()
605 *
606 * @class mw.html.Cdata
607 * @constructor
608 * @param {string} value
609 */
610 Cdata: function ( value ) {
611 this.value = value;
612 }
613 };
614 }() );
615
616 /**
617 * Execute a function as soon as one or more required modules are ready.
618 *
619 * Example of inline dependency on OOjs:
620 *
621 * mw.loader.using( 'oojs', function () {
622 * OO.compare( [ 1 ], [ 1 ] );
623 * } );
624 *
625 * Example of inline dependency obtained via `require()`:
626 *
627 * mw.loader.using( [ 'mediawiki.util' ], function ( require ) {
628 * var util = require( 'mediawiki.util' );
629 * } );
630 *
631 * Since MediaWiki 1.23 this also returns a promise.
632 *
633 * Since MediaWiki 1.28 the promise is resolved with a `require` function.
634 *
635 * @member mw.loader
636 * @param {string|Array} dependencies Module name or array of modules names the
637 * callback depends on to be ready before executing
638 * @param {Function} [ready] Callback to execute when all dependencies are ready
639 * @param {Function} [error] Callback to execute if one or more dependencies failed
640 * @return {jQuery.Promise} With a `require` function
641 */
642 mw.loader.using = function ( dependencies, ready, error ) {
643 var deferred = $.Deferred();
644
645 // Allow calling with a single dependency as a string
646 if ( typeof dependencies === 'string' ) {
647 dependencies = [ dependencies ];
648 }
649
650 if ( ready ) {
651 deferred.done( ready );
652 }
653 if ( error ) {
654 deferred.fail( error );
655 }
656
657 try {
658 // Resolve entire dependency map
659 dependencies = mw.loader.resolve( dependencies );
660 } catch ( e ) {
661 return deferred.reject( e ).promise();
662 }
663
664 mw.loader.enqueue( dependencies, function () {
665 deferred.resolve( mw.loader.require );
666 }, deferred.reject );
667
668 return deferred.promise();
669 };
670
671 // Alias $j to jQuery for backwards compatibility
672 // @deprecated since 1.23 Use $ or jQuery instead
673 mw.log.deprecate( window, '$j', $, 'Use $ or jQuery instead.' );
674
675 // Process callbacks for Grade A that require modules.
676 queue = window.RLQ;
677 // Replace temporary RLQ implementation from startup.js with the
678 // final implementation that also processes callbacks that can
679 // require modules. It must also support late arrivals of
680 // plain callbacks. (T208093)
681 window.RLQ = {
682 push: function ( entry ) {
683 if ( typeof entry === 'function' ) {
684 entry();
685 } else {
686 mw.loader.using( entry[ 0 ], entry[ 1 ] );
687 }
688 }
689 };
690 while ( queue[ 0 ] ) {
691 window.RLQ.push( queue.shift() );
692 }
693 }() );