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