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