Merge "output: Narrow Title type hint to LinkTarget"
[lhc/web/wiklou.git] / resources / src / mediawiki.util / util.js
1 'use strict';
2
3 var util,
4 config = require( './config.json' );
5
6 require( './jquery.accessKeyLabel.js' );
7
8 /**
9 * Encode the string like PHP's rawurlencode
10 * @ignore
11 *
12 * @param {string} str String to be encoded.
13 * @return {string} Encoded string
14 */
15 function rawurlencode( str ) {
16 return encodeURIComponent( String( str ) )
17 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
18 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
19 }
20
21 /**
22 * Private helper function used by util.escapeId*()
23 * @ignore
24 *
25 * @param {string} str String to be encoded
26 * @param {string} mode Encoding mode, see documentation for $wgFragmentMode
27 * in DefaultSettings.php
28 * @return {string} Encoded string
29 */
30 function escapeIdInternal( str, mode ) {
31 str = String( str );
32
33 switch ( mode ) {
34 case 'html5':
35 return str.replace( / /g, '_' );
36 case 'legacy':
37 return rawurlencode( str.replace( / /g, '_' ) )
38 .replace( /%3A/g, ':' )
39 .replace( /%/g, '.' );
40 default:
41 throw new Error( 'Unrecognized ID escaping mode ' + mode );
42 }
43 }
44
45 /**
46 * Utility library
47 * @class mw.util
48 * @singleton
49 */
50 util = {
51
52 /**
53 * Encode the string like PHP's rawurlencode
54 *
55 * @param {string} str String to be encoded.
56 * @return {string} Encoded string
57 */
58 rawurlencode: rawurlencode,
59
60 /**
61 * Encode a string as CSS id, for use as HTML id attribute value.
62 *
63 * Analog to `Sanitizer::escapeIdForAttribute()` in PHP.
64 *
65 * @since 1.30
66 * @param {string} str String to encode
67 * @return {string} Encoded string
68 */
69 escapeIdForAttribute: function ( str ) {
70 return escapeIdInternal( str, config.FragmentMode[ 0 ] );
71 },
72
73 /**
74 * Encode a string as URL fragment, for use as HTML anchor link.
75 *
76 * Analog to `Sanitizer::escapeIdForLink()` in PHP.
77 *
78 * @since 1.30
79 * @param {string} str String to encode
80 * @return {string} Encoded string
81 */
82 escapeIdForLink: function ( str ) {
83 return escapeIdInternal( str, config.FragmentMode[ 0 ] );
84 },
85
86 /**
87 * Return a wrapper function that is debounced for the given duration.
88 *
89 * When it is first called, a timeout is scheduled. If before the timer
90 * is reached the wrapper is called again, it gets rescheduled for the
91 * same duration from now until it stops being called. The original function
92 * is called from the "tail" of such chain, with the last set of arguments.
93 *
94 * @since 1.34
95 * @param {number} delay Time in milliseconds
96 * @param {Function} callback
97 * @return {Function}
98 */
99 debounce: function ( delay, callback ) {
100 var timeout;
101 return function () {
102 clearTimeout( timeout );
103 timeout = setTimeout( Function.prototype.apply.bind( callback, this, arguments ), delay );
104 };
105 },
106
107 /**
108 * Encode page titles for use in a URL
109 *
110 * We want / and : to be included as literal characters in our title URLs
111 * as they otherwise fatally break the title.
112 *
113 * The others are decoded because we can, it's prettier and matches behaviour
114 * of `wfUrlencode` in PHP.
115 *
116 * @param {string} str String to be encoded.
117 * @return {string} Encoded string
118 */
119 wikiUrlencode: function ( str ) {
120 return util.rawurlencode( str )
121 .replace( /%20/g, '_' )
122 // wfUrlencode replacements
123 .replace( /%3B/g, ';' )
124 .replace( /%40/g, '@' )
125 .replace( /%24/g, '$' )
126 .replace( /%21/g, '!' )
127 .replace( /%2A/g, '*' )
128 .replace( /%28/g, '(' )
129 .replace( /%29/g, ')' )
130 .replace( /%2C/g, ',' )
131 .replace( /%2F/g, '/' )
132 .replace( /%7E/g, '~' )
133 .replace( /%3A/g, ':' );
134 },
135
136 /**
137 * Get the link to a page name (relative to `wgServer`),
138 *
139 * @param {string|null} [pageName=wgPageName] Page name
140 * @param {Object} [params] A mapping of query parameter names to values,
141 * e.g. `{ action: 'edit' }`
142 * @return {string} Url of the page with name of `pageName`
143 */
144 getUrl: function ( pageName, params ) {
145 var fragmentIdx, url, query, fragment,
146 title = typeof pageName === 'string' ? pageName : mw.config.get( 'wgPageName' );
147
148 // Find any fragment
149 fragmentIdx = title.indexOf( '#' );
150 if ( fragmentIdx !== -1 ) {
151 fragment = title.slice( fragmentIdx + 1 );
152 // Exclude the fragment from the page name
153 title = title.slice( 0, fragmentIdx );
154 }
155
156 // Produce query string
157 if ( params ) {
158 query = $.param( params );
159 }
160 if ( query ) {
161 url = title ?
162 util.wikiScript() + '?title=' + util.wikiUrlencode( title ) + '&' + query :
163 util.wikiScript() + '?' + query;
164 } else {
165 url = mw.config.get( 'wgArticlePath' )
166 .replace( '$1', util.wikiUrlencode( title ).replace( /\$/g, '$$$$' ) );
167 }
168
169 // Append the encoded fragment
170 if ( fragment && fragment.length ) {
171 url += '#' + util.escapeIdForLink( fragment );
172 }
173
174 return url;
175 },
176
177 /**
178 * Get URL to a MediaWiki entry point.
179 *
180 * @since 1.18
181 * @param {string} [str="index"] Name of MW entry point (e.g. 'index' or 'api')
182 * @return {string} URL to the script file (e.g. '/w/api.php' )
183 */
184 wikiScript: function ( str ) {
185 if ( !str || str === 'index' ) {
186 return mw.config.get( 'wgScript' );
187 } else if ( str === 'load' ) {
188 return config.LoadScript;
189 } else {
190 return mw.config.get( 'wgScriptPath' ) + '/' + str + '.php';
191 }
192 },
193
194 /**
195 * Append a new style block to the head and return the CSSStyleSheet object.
196 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
197 * This function returns the styleSheet object for convience (due to cross-browsers
198 * difference as to where it is located).
199 *
200 * var sheet = util.addCSS( '.foobar { display: none; }' );
201 * $( foo ).click( function () {
202 * // Toggle the sheet on and off
203 * sheet.disabled = !sheet.disabled;
204 * } );
205 *
206 * @param {string} text CSS to be appended
207 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
208 */
209 addCSS: function ( text ) {
210 var s = mw.loader.addStyleTag( text );
211 return s.sheet;
212 },
213
214 /**
215 * Grab the URL parameter value for the given parameter.
216 * Returns null if not found.
217 *
218 * @param {string} param The parameter name.
219 * @param {string} [url=location.href] URL to search through, defaulting to the current browsing location.
220 * @return {Mixed} Parameter value or null.
221 */
222 getParamValue: function ( param, url ) {
223 // Get last match, stop at hash
224 var re = new RegExp( '^[^#]*[&?]' + util.escapeRegExp( param ) + '=([^&#]*)' ),
225 m = re.exec( url !== undefined ? url : location.href );
226
227 if ( m ) {
228 // Beware that decodeURIComponent is not required to understand '+'
229 // by spec, as encodeURIComponent does not produce it.
230 return decodeURIComponent( m[ 1 ].replace( /\+/g, '%20' ) );
231 }
232 return null;
233 },
234
235 /**
236 * The content wrapper of the skin (e.g. `.mw-body`).
237 *
238 * Populated on document ready. To use this property,
239 * wait for `$.ready` and be sure to have a module dependency on
240 * `mediawiki.util` which will ensure
241 * your document ready handler fires after initialization.
242 *
243 * Because of the lazy-initialised nature of this property,
244 * you're discouraged from using it.
245 *
246 * If you need just the wikipage content (not any of the
247 * extra elements output by the skin), use `$( '#mw-content-text' )`
248 * instead. Or listen to mw.hook#wikipage_content which will
249 * allow your code to re-run when the page changes (e.g. live preview
250 * or re-render after ajax save).
251 *
252 * @property {jQuery}
253 */
254 $content: null,
255
256 /**
257 * Add a link to a portlet menu on the page, such as:
258 *
259 * p-cactions (Content actions), p-personal (Personal tools),
260 * p-navigation (Navigation), p-tb (Toolbox)
261 *
262 * The first three parameters are required, the others are optional and
263 * may be null. Though providing an id and tooltip is recommended.
264 *
265 * By default the new link will be added to the end of the list. To
266 * add the link before a given existing item, pass the DOM node
267 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
268 * (e.g. `'#foobar'`) for that item.
269 *
270 * util.addPortletLink(
271 * 'p-tb', 'https://www.mediawiki.org/',
272 * 'mediawiki.org', 't-mworg', 'Go to mediawiki.org', 'm', '#t-print'
273 * );
274 *
275 * var node = util.addPortletLink(
276 * 'p-tb',
277 * new mw.Title( 'Special:Example' ).getUrl(),
278 * 'Example'
279 * );
280 * $( node ).on( 'click', function ( e ) {
281 * console.log( 'Example' );
282 * e.preventDefault();
283 * } );
284 *
285 * @param {string} portletId ID of the target portlet (e.g. 'p-cactions' or 'p-personal')
286 * @param {string} href Link URL
287 * @param {string} text Link text
288 * @param {string} [id] ID of the list item, should be unique and preferably have
289 * the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
290 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
291 * @param {string} [accesskey] Access key to activate this link. One character only,
292 * avoid conflicts with other links. Use `$( '[accesskey=x]' )` in the console to
293 * see if 'x' is already used.
294 * @param {HTMLElement|jQuery|string} [nextnode] Element that the new item should be added before.
295 * Must be another item in the same list, it will be ignored otherwise.
296 * Can be specified as DOM reference, as jQuery object, or as CSS selector string.
297 * @return {HTMLElement|null} The added list item, or null if no element was added.
298 */
299 addPortletLink: function ( portletId, href, text, id, tooltip, accesskey, nextnode ) {
300 var item, link, $portlet, portlet, portletDiv, ul, next;
301
302 if ( !portletId ) {
303 // Avoid confusing id="undefined" lookup
304 return null;
305 }
306
307 portlet = document.getElementById( portletId );
308 if ( !portlet ) {
309 // Invalid portlet ID
310 return null;
311 }
312
313 // Setup the anchor tag and set any the properties
314 link = document.createElement( 'a' );
315 link.href = href;
316 link.textContent = text;
317 if ( tooltip ) {
318 link.title = tooltip;
319 }
320 if ( accesskey ) {
321 link.accessKey = accesskey;
322 }
323
324 // Unhide portlet if it was hidden before
325 $portlet = $( portlet );
326 $portlet.removeClass( 'emptyPortlet' );
327
328 // Setup the list item (and a span if $portlet is a Vector tab)
329 // eslint-disable-next-line no-jquery/no-class-state
330 if ( $portlet.hasClass( 'vectorTabs' ) ) {
331 item = $( '<li>' ).append( $( '<span>' ).append( link )[ 0 ] )[ 0 ];
332 } else {
333 item = $( '<li>' ).append( link )[ 0 ];
334 }
335 if ( id ) {
336 item.id = id;
337 }
338
339 // Select the first (most likely only) unordered list inside the portlet
340 ul = portlet.querySelector( 'ul' );
341 if ( !ul ) {
342 // If it didn't have an unordered list yet, create one
343 ul = document.createElement( 'ul' );
344 portletDiv = portlet.querySelector( 'div' );
345 if ( portletDiv ) {
346 // Support: Legacy skins have a div (such as div.body or div.pBody).
347 // Append the <ul> to that.
348 portletDiv.appendChild( ul );
349 } else {
350 // Append it to the portlet directly
351 portlet.appendChild( ul );
352 }
353 }
354
355 if ( nextnode && ( typeof nextnode === 'string' || nextnode.nodeType || nextnode.jquery ) ) {
356 nextnode = $( ul ).find( nextnode );
357 if ( nextnode.length === 1 && nextnode[ 0 ].parentNode === ul ) {
358 // Insertion point: Before nextnode
359 nextnode.before( item );
360 next = true;
361 }
362 // Else: Invalid nextnode value (no match, more than one match, or not a direct child)
363 // Else: Invalid nextnode type
364 }
365
366 if ( !next ) {
367 // Insertion point: End of list (default)
368 ul.appendChild( item );
369 }
370
371 // Update tooltip for the access key after inserting into DOM
372 // to get a localized access key label (T69946).
373 if ( accesskey ) {
374 $( link ).updateTooltipAccessKeys();
375 }
376
377 return item;
378 },
379
380 /**
381 * Validate a string as representing a valid e-mail address
382 * according to HTML5 specification. Please note the specification
383 * does not validate a domain with one character.
384 *
385 * FIXME: should be moved to or replaced by a validation module.
386 *
387 * @param {string} mailtxt E-mail address to be validated.
388 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
389 * as determined by validation.
390 */
391 validateEmail: function ( mailtxt ) {
392 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
393
394 if ( mailtxt === '' ) {
395 return null;
396 }
397
398 // HTML5 defines a string as valid e-mail address if it matches
399 // the ABNF:
400 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
401 // With:
402 // - atext : defined in RFC 5322 section 3.2.3
403 // - ldh-str : defined in RFC 1034 section 3.5
404 //
405 // (see STD 68 / RFC 5234 https://tools.ietf.org/html/std68)
406 // First, define the RFC 5322 'atext' which is pretty easy:
407 // atext = ALPHA / DIGIT / ; Printable US-ASCII
408 // "!" / "#" / ; characters not including
409 // "$" / "%" / ; specials. Used for atoms.
410 // "&" / "'" /
411 // "*" / "+" /
412 // "-" / "/" /
413 // "=" / "?" /
414 // "^" / "_" /
415 // "`" / "{" /
416 // "|" / "}" /
417 // "~"
418 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
419
420 // Next define the RFC 1034 'ldh-str'
421 // <domain> ::= <subdomain> | " "
422 // <subdomain> ::= <label> | <subdomain> "." <label>
423 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
424 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
425 // <let-dig-hyp> ::= <let-dig> | "-"
426 // <let-dig> ::= <letter> | <digit>
427 rfc1034LdhStr = 'a-z0-9\\-';
428
429 html5EmailRegexp = new RegExp(
430 // start of string
431 '^' +
432 // User part which is liberal :p
433 '[' + rfc5322Atext + '\\.]+' +
434 // 'at'
435 '@' +
436 // Domain first part
437 '[' + rfc1034LdhStr + ']+' +
438 // Optional second part and following are separated by a dot
439 '(?:\\.[' + rfc1034LdhStr + ']+)*' +
440 // End of string
441 '$',
442 // RegExp is case insensitive
443 'i'
444 );
445 return ( mailtxt.match( html5EmailRegexp ) !== null );
446 },
447
448 /**
449 * Note: borrows from IP::isIPv4
450 *
451 * @param {string} address
452 * @param {boolean} [allowBlock=false]
453 * @return {boolean}
454 */
455 isIPv4Address: function ( address, allowBlock ) {
456 var block,
457 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
458 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
459
460 if ( typeof address !== 'string' ) {
461 return false;
462 }
463
464 block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '';
465
466 return ( new RegExp( '^' + RE_IP_ADD + block + '$' ).test( address ) );
467 },
468
469 /**
470 * Note: borrows from IP::isIPv6
471 *
472 * @param {string} address
473 * @param {boolean} [allowBlock=false]
474 * @return {boolean}
475 */
476 isIPv6Address: function ( address, allowBlock ) {
477 var block, RE_IPV6_ADD;
478
479 if ( typeof address !== 'string' ) {
480 return false;
481 }
482
483 block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '';
484 RE_IPV6_ADD =
485 '(?:' + // starts with "::" (including "::")
486 ':(?::|(?::' +
487 '[0-9A-Fa-f]{1,4}' +
488 '){1,7})' +
489 '|' + // ends with "::" (except "::")
490 '[0-9A-Fa-f]{1,4}' +
491 '(?::' +
492 '[0-9A-Fa-f]{1,4}' +
493 '){0,6}::' +
494 '|' + // contains no "::"
495 '[0-9A-Fa-f]{1,4}' +
496 '(?::' +
497 '[0-9A-Fa-f]{1,4}' +
498 '){7}' +
499 ')';
500
501 if ( new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) ) {
502 return true;
503 }
504
505 // contains one "::" in the middle (single '::' check below)
506 RE_IPV6_ADD =
507 '[0-9A-Fa-f]{1,4}' +
508 '(?:::?' +
509 '[0-9A-Fa-f]{1,4}' +
510 '){1,6}';
511
512 return (
513 new RegExp( '^' + RE_IPV6_ADD + block + '$' ).test( address ) &&
514 /::/.test( address ) &&
515 !/::.*::/.test( address )
516 );
517 },
518
519 /**
520 * Check whether a string is an IP address
521 *
522 * @since 1.25
523 * @param {string} address String to check
524 * @param {boolean} [allowBlock=false] If a block of IPs should be allowed
525 * @return {boolean}
526 */
527 isIPAddress: function ( address, allowBlock ) {
528 return util.isIPv4Address( address, allowBlock ) ||
529 util.isIPv6Address( address, allowBlock );
530 },
531
532 /**
533 * Escape string for safe inclusion in regular expression
534 *
535 * The following characters are escaped:
536 *
537 * \ { } ( ) | . ? * + - ^ $ [ ]
538 *
539 * @since 1.26; moved to mw.util in 1.34
540 * @param {string} str String to escape
541 * @return {string} Escaped string
542 */
543 escapeRegExp: function ( str ) {
544 // eslint-disable-next-line no-useless-escape
545 return str.replace( /([\\{}()|.?*+\-^$\[\]])/g, '\\$1' );
546 }
547 };
548
549 // Backwards-compatible alias for mediawiki.RegExp module.
550 // @deprecated since 1.34
551 mw.RegExp = {};
552 mw.log.deprecate( mw.RegExp, 'escape', util.escapeRegExp, 'Use mw.util.escapeRegExp() instead.', 'mw.RegExp.escape' );
553
554 // Not allowed outside unit tests
555 if ( window.QUnit ) {
556 util.setOptionsForTest = function ( opts ) {
557 var oldConfig = config;
558 config = $.extend( {}, config, opts );
559 return oldConfig;
560 };
561 }
562
563 /**
564 * Initialisation of mw.util.$content
565 */
566 function init() {
567 util.$content = ( function () {
568 var i, l, $node, selectors;
569
570 selectors = [
571 // The preferred standard is class "mw-body".
572 // You may also use class "mw-body mw-body-primary" if you use
573 // mw-body in multiple locations. Or class "mw-body-primary" if
574 // you use mw-body deeper in the DOM.
575 '.mw-body-primary',
576 '.mw-body',
577
578 // If the skin has no such class, fall back to the parser output
579 '#mw-content-text'
580 ];
581
582 for ( i = 0, l = selectors.length; i < l; i++ ) {
583 $node = $( selectors[ i ] );
584 if ( $node.length ) {
585 return $node.first();
586 }
587 }
588
589 // Should never happen... well, it could if someone is not finished writing a
590 // skin and has not yet inserted bodytext yet.
591 return $( 'body' );
592 }() );
593 }
594
595 $( init );
596
597 mw.util = util;
598 module.exports = util;