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