Fix up the preferred way to specify mw.util.$content
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.util.js
1 /**
2 * Implements mediaWiki.util library
3 */
4 ( function ( mw, $ ) {
5 'use strict';
6
7 // Local cache and alias
8 var hideMessageTimeout,
9 messageBoxEvents = false,
10 util = {
11
12 /**
13 * Initialisation
14 * (don't call before document ready)
15 */
16 init: function () {
17 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
18
19 /* Set up $.messageBox */
20 $.messageBoxNew( {
21 id: 'mw-js-message',
22 parent: '#content'
23 } );
24
25 /* Set tooltipAccessKeyPrefix */
26 profile = $.client.profile();
27
28 // Opera on any platform
29 if ( profile.name === 'opera' ) {
30 util.tooltipAccessKeyPrefix = 'shift-esc-';
31
32 // Chrome on any platform
33 } else if ( profile.name === 'chrome' ) {
34
35 util.tooltipAccessKeyPrefix = (
36 profile.platform === 'mac'
37 // Chrome on Mac
38 ? 'ctrl-option-'
39 : profile.platform === 'win'
40 // Chrome on Windows
41 // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
42 // which alt-shift-f does not)
43 ? 'alt-shift-'
44 // Chrome on other (Ubuntu?)
45 : 'alt-'
46 );
47
48 // Non-Windows Safari with webkit_version > 526
49 } else if ( profile.platform !== 'win'
50 && profile.name === 'safari'
51 && profile.layoutVersion > 526 ) {
52 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
53 // Firefox 14+ on Mac
54 } else if ( profile.platform === 'mac'
55 && profile.name === 'firefox'
56 && profile.versionNumber >= 14 ) {
57 util.tooltipAccessKeyPrefix = 'ctrl-option-';
58 // Safari/Konqueror on any platform, or any browser on Mac
59 // (but not Safari on Windows)
60 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
61 && ( profile.name === 'safari'
62 || profile.platform === 'mac'
63 || profile.name === 'konqueror' ) ) {
64 util.tooltipAccessKeyPrefix = 'ctrl-';
65
66 // Firefox 2.x and later
67 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
68 util.tooltipAccessKeyPrefix = 'alt-shift-';
69 }
70
71 /* Fill $content var */
72 util.$content = ( function () {
73 var $content, selectors = [
74 // The preferred standard for setting $content (class="mw-body")
75 // You may also use (class="mw-body mw-body-primary") if you use
76 // mw-body in multiple locations.
77 // Or class="mw-body-primary" if you want $content to be deeper
78 // in the dom than mw-body
79 '.mw-body-primary',
80 '.mw-body',
81
82 /* Legacy fallbacks for setting the content */
83 // Vector, Monobook, Chick, etc... based skins
84 '#bodyContent',
85
86 // Modern based skins
87 '#mw_contentholder',
88
89 // Standard, CologneBlue
90 '#article',
91
92 // #content is present on almost all if not all skins. Most skins (the above cases)
93 // have #content too, but as an outer wrapper instead of the article text container.
94 // The skins that don't have an outer wrapper do have #content for everything
95 // so it's a good fallback
96 '#content',
97
98 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
99 '#mw-content-text',
100
101 // Should never happen... well, it could if someone is not finished writing a skin and has
102 // not inserted bodytext yet. But in any case <body> should always exist
103 'body'
104 ];
105 for ( var i = 0, l = selectors.length; i < l; i++ ) {
106 $content = $( selectors[i] ).first();
107 if ( $content.length ) {
108 return $content;
109 }
110 }
111
112 // Make sure we don't unset util.$content if it was preset and we don't find anything
113 return util.$content;
114 } )();
115
116 // Table of contents toggle
117 $tocTitle = $( '#toctitle' );
118 $tocToggleLink = $( '#togglelink' );
119 // Only add it if there is a TOC and there is no toggle added already
120 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
121 hideTocCookie = $.cookie( 'mw_hidetoc' );
122 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
123 .text( mw.msg( 'hidetoc' ) )
124 .click( function ( e ) {
125 e.preventDefault();
126 util.toggleToc( $(this) );
127 } );
128 $tocTitle.append(
129 $tocToggleLink
130 .wrap( '<span class="toctoggle"></span>' )
131 .parent()
132 .prepend( '&nbsp;[' )
133 .append( ']&nbsp;' )
134 );
135
136 if ( hideTocCookie === '1' ) {
137 util.toggleToc( $tocToggleLink );
138 }
139 }
140 },
141
142 /* Main body */
143
144 /**
145 * Encode the string like PHP's rawurlencode
146 *
147 * @param str string String to be encoded
148 */
149 rawurlencode: function ( str ) {
150 str = String( str );
151 return encodeURIComponent( str )
152 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
153 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
154 },
155
156 /**
157 * Encode page titles for use in a URL
158 * We want / and : to be included as literal characters in our title URLs
159 * as they otherwise fatally break the title
160 *
161 * @param str string String to be encoded
162 */
163 wikiUrlencode: function ( str ) {
164 return util.rawurlencode( str )
165 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
166 },
167
168 /**
169 * Get the link to a page name (relative to wgServer)
170 *
171 * @param str String: Page name to get the link for.
172 * @return String: Location for a page with name of 'str' or boolean false on error.
173 */
174 wikiGetlink: function ( str ) {
175 return mw.config.get( 'wgArticlePath' ).replace( '$1',
176 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
177 },
178
179 /**
180 * Get address to a script in the wiki root.
181 * For index.php use mw.config.get( 'wgScript' )
182 *
183 * @since 1.18
184 * @param str string Name of script (eg. 'api'), defaults to 'index'
185 * @return string Address to script (eg. '/w/api.php' )
186 */
187 wikiScript: function ( str ) {
188 str = str || 'index';
189 if ( str === 'index' ) {
190 return mw.config.get( 'wgScript' );
191 } else if ( str === 'load' ) {
192 return mw.config.get( 'wgLoadScript' );
193 } else {
194 return mw.config.get( 'wgScriptPath' ) + '/' + str +
195 mw.config.get( 'wgScriptExtension' );
196 }
197 },
198
199 /**
200 * Append a new style block to the head and return the CSSStyleSheet object.
201 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
202 * This function returns the styleSheet object for convience (due to cross-browsers
203 * difference as to where it is located).
204 * @example
205 * <code>
206 * var sheet = mw.util.addCSS('.foobar { display: none; }');
207 * $(foo).click(function () {
208 * // Toggle the sheet on and off
209 * sheet.disabled = !sheet.disabled;
210 * });
211 * </code>
212 *
213 * @param text string CSS to be appended
214 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
215 */
216 addCSS: function ( text ) {
217 var s = mw.loader.addStyleTag( text );
218 return s.sheet || s;
219 },
220
221 /**
222 * Hide/show the table of contents element
223 *
224 * @param $toggleLink jQuery A jQuery object of the toggle link.
225 * @param callback function Function to be called after the toggle is
226 * completed (including the animation) (optional)
227 * @return mixed Boolean visibility of the toc (true if it's visible)
228 * or Null if there was no table of contents.
229 */
230 toggleToc: function ( $toggleLink, callback ) {
231 var $tocList = $( '#toc ul:first' );
232
233 // This function shouldn't be called if there's no TOC,
234 // but just in case...
235 if ( $tocList.length ) {
236 if ( $tocList.is( ':hidden' ) ) {
237 $tocList.slideDown( 'fast', callback );
238 $toggleLink.text( mw.msg( 'hidetoc' ) );
239 $( '#toc' ).removeClass( 'tochidden' );
240 $.cookie( 'mw_hidetoc', null, {
241 expires: 30,
242 path: '/'
243 } );
244 return true;
245 } else {
246 $tocList.slideUp( 'fast', callback );
247 $toggleLink.text( mw.msg( 'showtoc' ) );
248 $( '#toc' ).addClass( 'tochidden' );
249 $.cookie( 'mw_hidetoc', '1', {
250 expires: 30,
251 path: '/'
252 } );
253 return false;
254 }
255 } else {
256 return null;
257 }
258 },
259
260 /**
261 * Grab the URL parameter value for the given parameter.
262 * Returns null if not found.
263 *
264 * @param param string The parameter name.
265 * @param url string URL to search through (optional)
266 * @return mixed Parameter value or null.
267 */
268 getParamValue: function ( param, url ) {
269 url = url || document.location.href;
270 // Get last match, stop at hash
271 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
272 m = re.exec( url );
273 if ( m ) {
274 // Beware that decodeURIComponent is not required to understand '+'
275 // by spec, as encodeURIComponent does not produce it.
276 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
277 }
278 return null;
279 },
280
281 /**
282 * @var string
283 * Access key prefix. Will be re-defined based on browser/operating system
284 * detection in mw.util.init().
285 */
286 tooltipAccessKeyPrefix: 'alt-',
287
288 /**
289 * @var RegExp
290 * Regex to match accesskey tooltips.
291 */
292 tooltipAccessKeyRegexp: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
293
294 /**
295 * Add the appropriate prefix to the accesskey shown in the tooltip.
296 * If the nodeList parameter is given, only those nodes are updated;
297 * otherwise, all the nodes that will probably have accesskeys by
298 * default are updated.
299 *
300 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
301 * of elements to update.
302 */
303 updateTooltipAccessKeys: function ( $nodes ) {
304 if ( !$nodes ) {
305 // Rather than going into a loop of all anchor tags, limit to few elements that
306 // contain the relevant anchor tags.
307 // Input and label are rare enough that no such optimization is needed
308 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
309 } else if ( !( $nodes instanceof $ ) ) {
310 $nodes = $( $nodes );
311 }
312
313 $nodes.attr( 'title', function ( i, val ) {
314 if ( val && util.tooltipAccessKeyRegexp.exec( val ) ) {
315 return val.replace( util.tooltipAccessKeyRegexp,
316 '[' + util.tooltipAccessKeyPrefix + '$5]' );
317 }
318 return val;
319 } );
320 },
321
322 /*
323 * @var jQuery
324 * A jQuery object that refers to the content area element
325 * Populated by init().
326 */
327 $content: null,
328
329 /**
330 * Add a link to a portlet menu on the page, such as:
331 *
332 * p-cactions (Content actions), p-personal (Personal tools),
333 * p-navigation (Navigation), p-tb (Toolbox)
334 *
335 * The first three paramters are required, the others are optional and
336 * may be null. Though providing an id and tooltip is recommended.
337 *
338 * By default the new link will be added to the end of the list. To
339 * add the link before a given existing item, pass the DOM node
340 * (document.getElementById( 'foobar' )) or the jQuery-selector
341 * ( '#foobar' ) of that item.
342 *
343 * @example mw.util.addPortletLink(
344 * 'p-tb', 'http://mediawiki.org/',
345 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
346 * )
347 *
348 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
349 * @param href string Link URL
350 * @param text string Link text
351 * @param id string ID of the new item, should be unique and preferably have
352 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
353 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
354 * @param accesskey string Access key to activate this link (one character, try
355 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
356 * see if 'x' is already used.
357 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
358 * item should be added before, should be another item in the same
359 * list, it will be ignored otherwise
360 *
361 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
362 * depending on the skin) or null if no element was added to the document.
363 */
364 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
365 var $item, $link, $portlet, $ul;
366
367 // Check if there's atleast 3 arguments to prevent a TypeError
368 if ( arguments.length < 3 ) {
369 return null;
370 }
371 // Setup the anchor tag
372 $link = $( '<a>' ).attr( 'href', href ).text( text );
373 if ( tooltip ) {
374 $link.attr( 'title', tooltip );
375 }
376
377 // Some skins don't have any portlets
378 // just add it to the bottom of their 'sidebar' element as a fallback
379 switch ( mw.config.get( 'skin' ) ) {
380 case 'standard':
381 case 'cologneblue':
382 $( '#quickbar' ).append( $link.after( '<br/>' ) );
383 return $link[0];
384 case 'nostalgia':
385 $( '#searchform' ).before( $link ).before( ' &#124; ' );
386 return $link[0];
387 default: // Skins like chick, modern, monobook, myskin, simple, vector...
388
389 // Select the specified portlet
390 $portlet = $( '#' + portlet );
391 if ( $portlet.length === 0 ) {
392 return null;
393 }
394 // Select the first (most likely only) unordered list inside the portlet
395 $ul = $portlet.find( 'ul' ).eq( 0 );
396
397 // If it didn't have an unordered list yet, create it
398 if ( $ul.length === 0 ) {
399
400 $ul = $( '<ul>' );
401
402 // If there's no <div> inside, append it to the portlet directly
403 if ( $portlet.find( 'div:first' ).length === 0 ) {
404 $portlet.append( $ul );
405 } else {
406 // otherwise if there's a div (such as div.body or div.pBody)
407 // append the <ul> to last (most likely only) div
408 $portlet.find( 'div' ).eq( -1 ).append( $ul );
409 }
410 }
411 // Just in case..
412 if ( $ul.length === 0 ) {
413 return null;
414 }
415
416 // Unhide portlet if it was hidden before
417 $portlet.removeClass( 'emptyPortlet' );
418
419 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
420 // and back up the selector to the list item
421 if ( $portlet.hasClass( 'vectorTabs' ) ) {
422 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
423 } else {
424 $item = $link.wrap( '<li></li>' ).parent();
425 }
426
427 // Implement the properties passed to the function
428 if ( id ) {
429 $item.attr( 'id', id );
430 }
431 if ( accesskey ) {
432 $link.attr( 'accesskey', accesskey );
433 tooltip += ' [' + accesskey + ']';
434 $link.attr( 'title', tooltip );
435 }
436 if ( accesskey && tooltip ) {
437 util.updateTooltipAccessKeys( $link );
438 }
439
440 // Where to put our node ?
441 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
442 if ( nextnode && nextnode.parentNode === $ul[0] ) {
443 $(nextnode).before( $item );
444
445 // - nextnode is a CSS selector for jQuery
446 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
447 $ul.find( nextnode ).eq( 0 ).before( $item );
448
449 // If the jQuery selector isn't found within the <ul>,
450 // or if nextnode was invalid or not passed at all,
451 // then just append it at the end of the <ul> (this is the default behaviour)
452 } else {
453 $ul.append( $item );
454 }
455
456
457 return $item[0];
458 }
459 },
460
461 /**
462 * Add a little box at the top of the screen to inform the user of
463 * something, replacing any previous message.
464 * Calling with no arguments, with an empty string or null will hide the message
465 *
466 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
467 * @param className {String} Used in adding a class; should be different for each call
468 * to allow CSS/JS to hide different boxes. null = no class used.
469 * @return {Boolean} True on success, false on failure.
470 */
471 jsMessage: function ( message, className ) {
472 var $messageDiv = $( '#mw-js-message' );
473
474 if ( !arguments.length || message === '' || message === null ) {
475 $messageDiv.empty().hide();
476 stopHideMessageTimeout();
477 return true; // Emptying and hiding message is intended behaviour, return true
478 } else {
479 // We special-case skin structures provided by the software. Skins that
480 // choose to abandon or significantly modify our formatting can just define
481 // an mw-js-message div to start with.
482 if ( !$messageDiv.length ) {
483 $messageDiv = $( '<div id="mw-js-message"></div>' );
484 if ( util.$content.parent().length ) {
485 util.$content.parent().prepend( $messageDiv );
486 } else {
487 return false;
488 }
489 }
490
491 if ( !messageBoxEvents ) {
492 messageBoxEvents = true;
493 $messageDiv
494 .on( {
495 'mouseenter': stopHideMessageTimeout,
496 'mouseleave': startHideMessageTimeout,
497 'click': hideMessage
498 } )
499 .on( 'click', 'a', function ( e ) {
500 // Prevent links, even those that don't exist yet, from causing the
501 // message box to close when clicked
502 e.stopPropagation();
503 } );
504 }
505
506 if ( className ) {
507 $messageDiv.prop( 'className', 'mw-js-message-' + className );
508 }
509
510 if ( typeof message === 'object' ) {
511 $messageDiv.empty();
512 $messageDiv.append( message );
513 } else {
514 $messageDiv.html( message );
515 }
516
517 $messageDiv.slideDown();
518 startHideMessageTimeout();
519 return true;
520 }
521 },
522
523 /**
524 * Validate a string as representing a valid e-mail address
525 * according to HTML5 specification. Please note the specification
526 * does not validate a domain with one character.
527 *
528 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
529 *
530 * @param mailtxt string E-mail address to be validated.
531 * @return mixed Null if mailtxt was an empty string, otherwise true/false
532 * is determined by validation.
533 */
534 validateEmail: function ( mailtxt ) {
535 var rfc5322_atext, rfc1034_ldh_str, HTML5_email_regexp;
536
537 if ( mailtxt === '' ) {
538 return null;
539 }
540
541 /**
542 * HTML5 defines a string as valid e-mail address if it matches
543 * the ABNF:
544 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
545 * With:
546 * - atext : defined in RFC 5322 section 3.2.3
547 * - ldh-str : defined in RFC 1034 section 3.5
548 *
549 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
550 */
551
552 /**
553 * First, define the RFC 5322 'atext' which is pretty easy:
554 * atext = ALPHA / DIGIT / ; Printable US-ASCII
555 "!" / "#" / ; characters not including
556 "$" / "%" / ; specials. Used for atoms.
557 "&" / "'" /
558 "*" / "+" /
559 "-" / "/" /
560 "=" / "?" /
561 "^" / "_" /
562 "`" / "{" /
563 "|" / "}" /
564 "~"
565 */
566 rfc5322_atext = "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
567
568 /**
569 * Next define the RFC 1034 'ldh-str'
570 * <domain> ::= <subdomain> | " "
571 * <subdomain> ::= <label> | <subdomain> "." <label>
572 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
573 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
574 * <let-dig-hyp> ::= <let-dig> | "-"
575 * <let-dig> ::= <letter> | <digit>
576 */
577 rfc1034_ldh_str = "a-z0-9\\-";
578
579 HTML5_email_regexp = new RegExp(
580 // start of string
581 '^'
582 +
583 // User part which is liberal :p
584 '[' + rfc5322_atext + '\\.]+'
585 +
586 // 'at'
587 '@'
588 +
589 // Domain first part
590 '[' + rfc1034_ldh_str + ']+'
591 +
592 // Optional second part and following are separated by a dot
593 '(?:\\.[' + rfc1034_ldh_str + ']+)*'
594 +
595 // End of string
596 '$',
597 // RegExp is case insensitive
598 'i'
599 );
600 return (null !== mailtxt.match( HTML5_email_regexp ) );
601 },
602
603 /**
604 * Note: borrows from IP::isIPv4
605 *
606 * @param address string
607 * @param allowBlock boolean
608 * @return boolean
609 */
610 isIPv4Address: function ( address, allowBlock ) {
611 if ( typeof address !== 'string' ) {
612 return false;
613 }
614
615 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
616 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
617 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
618
619 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
620 },
621
622 /**
623 * Note: borrows from IP::isIPv6
624 *
625 * @param address string
626 * @param allowBlock boolean
627 * @return boolean
628 */
629 isIPv6Address: function ( address, allowBlock ) {
630 if ( typeof address !== 'string' ) {
631 return false;
632 }
633
634 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
635 RE_IPV6_ADD =
636 '(?:' + // starts with "::" (including "::")
637 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
638 '|' + // ends with "::" (except "::")
639 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
640 '|' + // contains no "::"
641 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
642 ')';
643
644 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
645 return true;
646 }
647
648 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
649 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
650
651 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
652 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
653 }
654 };
655
656 // Message auto-hide helpers
657 function hideMessage() {
658 $( '#mw-js-message' ).fadeOut( 'slow' );
659 }
660 function stopHideMessageTimeout() {
661 clearTimeout( hideMessageTimeout );
662 }
663 function startHideMessageTimeout() {
664 clearTimeout( hideMessageTimeout );
665 hideMessageTimeout = setTimeout( hideMessage, 5000 );
666 }
667
668 mw.util = util;
669
670 }( mediaWiki, jQuery ) );