mediawiki.util: Detect Iceweasel for accesskeys
[lhc/web/wiklou.git] / resources / 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 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
17
18 /* Set tooltipAccessKeyPrefix */
19 profile = $.client.profile();
20
21 // Opera on any platform
22 if ( profile.name === 'opera' ) {
23 util.tooltipAccessKeyPrefix = 'shift-esc-';
24
25 // Chrome on any platform
26 } else if ( profile.name === 'chrome' ) {
27
28 util.tooltipAccessKeyPrefix = (
29 profile.platform === 'mac'
30 // Chrome on Mac
31 ? 'ctrl-option-'
32 // Chrome on Windows or Linux
33 // (both alt- and alt-shift work, but alt with E, D, F etc does not
34 // work since they are browser shortcuts)
35 : 'alt-shift-'
36 );
37
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile.platform !== 'win'
40 && profile.name === 'safari'
41 && profile.layoutVersion > 526 ) {
42 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
43 // Firefox 14+ on Mac
44 } else if ( profile.platform === 'mac'
45 && profile.name === 'firefox'
46 && profile.versionNumber >= 14 ) {
47 util.tooltipAccessKeyPrefix = 'ctrl-option-';
48 // Safari/Konqueror on any platform, or any browser on Mac
49 // (but not Safari on Windows)
50 } else if ( !( profile.platform === 'win' && profile.name === 'safari' )
51 && ( profile.name === 'safari'
52 || profile.platform === 'mac'
53 || profile.name === 'konqueror' ) ) {
54 util.tooltipAccessKeyPrefix = 'ctrl-';
55
56 // Firefox/Iceweasel 2.x and later
57 } else if ( ( profile.name === 'firefox' || profile.name === 'iceweasel' )
58 && profile.versionBase > '1' ) {
59 util.tooltipAccessKeyPrefix = 'alt-shift-';
60 }
61
62 /* Fill $content var */
63 util.$content = ( function () {
64 var i, l, $content, selectors;
65 selectors = [
66 // The preferred standard for setting $content (class="mw-body")
67 // You may also use (class="mw-body mw-body-primary") if you use
68 // mw-body in multiple locations.
69 // Or class="mw-body-primary" if you want $content to be deeper
70 // in the dom than mw-body
71 '.mw-body-primary',
72 '.mw-body',
73
74 /* Legacy fallbacks for setting the content */
75 // Vector, Monobook, Chick, etc... based skins
76 '#bodyContent',
77
78 // Modern based skins
79 '#mw_contentholder',
80
81 // Standard, CologneBlue
82 '#article',
83
84 // #content is present on almost all if not all skins. Most skins (the above cases)
85 // have #content too, but as an outer wrapper instead of the article text container.
86 // The skins that don't have an outer wrapper do have #content for everything
87 // so it's a good fallback
88 '#content',
89
90 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
91 '#mw-content-text',
92
93 // Should never happen... well, it could if someone is not finished writing a skin and has
94 // not inserted bodytext yet. But in any case <body> should always exist
95 'body'
96 ];
97 for ( i = 0, l = selectors.length; i < l; i++ ) {
98 $content = $( selectors[i] ).first();
99 if ( $content.length ) {
100 return $content;
101 }
102 }
103
104 // Make sure we don't unset util.$content if it was preset and we don't find anything
105 return util.$content;
106 } )();
107
108 // Table of contents toggle
109 $tocTitle = $( '#toctitle' );
110 $tocToggleLink = $( '#togglelink' );
111 // Only add it if there is a TOC and there is no toggle added already
112 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
113 hideTocCookie = $.cookie( 'mw_hidetoc' );
114 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
115 .text( mw.msg( 'hidetoc' ) )
116 .click( function ( e ) {
117 e.preventDefault();
118 util.toggleToc( $(this) );
119 } );
120 $tocTitle.append(
121 $tocToggleLink
122 .wrap( '<span class="toctoggle"></span>' )
123 .parent()
124 .prepend( '&nbsp;[' )
125 .append( ']&nbsp;' )
126 );
127
128 if ( hideTocCookie === '1' ) {
129 util.toggleToc( $tocToggleLink );
130 }
131 }
132 },
133
134 /* Main body */
135
136 /**
137 * Encode the string like PHP's rawurlencode
138 *
139 * @param {string} str String to be encoded.
140 */
141 rawurlencode: function ( str ) {
142 str = String( str );
143 return encodeURIComponent( str )
144 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
145 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
146 },
147
148 /**
149 * Encode page titles for use in a URL
150 * We want / and : to be included as literal characters in our title URLs
151 * as they otherwise fatally break the title
152 *
153 * @param {string} str String to be encoded.
154 */
155 wikiUrlencode: function ( str ) {
156 return util.rawurlencode( str )
157 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
158 },
159
160 /**
161 * Get the link to a page name (relative to `wgServer`),
162 *
163 * @param {string} str Page name to get the link for.
164 * @return {string} Location for a page with name of `str` or boolean false on error.
165 */
166 wikiGetlink: function ( str ) {
167 return mw.config.get( 'wgArticlePath' ).replace( '$1',
168 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
169 },
170
171 /**
172 * Get address to a script in the wiki root.
173 * For index.php use `mw.config.get( 'wgScript' )`.
174 *
175 * @since 1.18
176 * @param str string Name of script (eg. 'api'), defaults to 'index'
177 * @return string Address to script (eg. '/w/api.php' )
178 */
179 wikiScript: function ( str ) {
180 str = str || 'index';
181 if ( str === 'index' ) {
182 return mw.config.get( 'wgScript' );
183 } else if ( str === 'load' ) {
184 return mw.config.get( 'wgLoadScript' );
185 } else {
186 return mw.config.get( 'wgScriptPath' ) + '/' + str +
187 mw.config.get( 'wgScriptExtension' );
188 }
189 },
190
191 /**
192 * Append a new style block to the head and return the CSSStyleSheet object.
193 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
194 * This function returns the styleSheet object for convience (due to cross-browsers
195 * difference as to where it is located).
196 *
197 * var sheet = mw.util.addCSS('.foobar { display: none; }');
198 * $(foo).click(function () {
199 * // Toggle the sheet on and off
200 * sheet.disabled = !sheet.disabled;
201 * });
202 *
203 * @param {string} text CSS to be appended
204 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
205 */
206 addCSS: function ( text ) {
207 var s = mw.loader.addStyleTag( text );
208 return s.sheet || s;
209 },
210
211 /**
212 * Hide/show the table of contents element
213 *
214 * @param {jQuery} $toggleLink A jQuery object of the toggle link.
215 * @param {Function} [callback] Function to be called after the toggle is
216 * completed (including the animation).
217 * @return {Mixed} Boolean visibility of the toc (true if it's visible)
218 * or Null if there was no table of contents.
219 */
220 toggleToc: function ( $toggleLink, callback ) {
221 var $tocList = $( '#toc ul:first' );
222
223 // This function shouldn't be called if there's no TOC,
224 // but just in case...
225 if ( $tocList.length ) {
226 if ( $tocList.is( ':hidden' ) ) {
227 $tocList.slideDown( 'fast', callback );
228 $toggleLink.text( mw.msg( 'hidetoc' ) );
229 $( '#toc' ).removeClass( 'tochidden' );
230 $.cookie( 'mw_hidetoc', null, {
231 expires: 30,
232 path: '/'
233 } );
234 return true;
235 } else {
236 $tocList.slideUp( 'fast', callback );
237 $toggleLink.text( mw.msg( 'showtoc' ) );
238 $( '#toc' ).addClass( 'tochidden' );
239 $.cookie( 'mw_hidetoc', '1', {
240 expires: 30,
241 path: '/'
242 } );
243 return false;
244 }
245 } else {
246 return null;
247 }
248 },
249
250 /**
251 * Grab the URL parameter value for the given parameter.
252 * Returns null if not found.
253 *
254 * @param {string} param The parameter name.
255 * @param {string} [url=document.location.href] URL to search through, defaulting to the current document's URL.
256 * @return {Mixed} Parameter value or null.
257 */
258 getParamValue: function ( param, url ) {
259 if ( url === undefined ) {
260 url = document.location.href;
261 }
262 // Get last match, stop at hash
263 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
264 m = re.exec( url );
265 if ( m ) {
266 // Beware that decodeURIComponent is not required to understand '+'
267 // by spec, as encodeURIComponent does not produce it.
268 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
269 }
270 return null;
271 },
272
273 /**
274 * @property {string}
275 * Access key prefix. Will be re-defined based on browser/operating system
276 * detection in mw.util#init.
277 */
278 tooltipAccessKeyPrefix: 'alt-',
279
280 /**
281 * @property {RegExp}
282 * Regex to match accesskey tooltips.
283 *
284 * Should match:
285 *
286 * - "ctrl-option-"
287 * - "alt-shift-"
288 * - "ctrl-alt-"
289 * - "ctrl-"
290 *
291 * The accesskey is matched in group $6.
292 */
293 tooltipAccessKeyRegexp: /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
294
295 /**
296 * Add the appropriate prefix to the accesskey shown in the tooltip.
297 * If the nodeList parameter is given, only those nodes are updated;
298 * otherwise, all the nodes that will probably have accesskeys by
299 * default are updated.
300 *
301 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes 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.test( val ) ) {
315 return val.replace( util.tooltipAccessKeyRegexp,
316 '[' + util.tooltipAccessKeyPrefix + '$6]' );
317 }
318 return val;
319 } );
320 },
321
322 /*
323 * @property {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 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
341 * (e.g. `'#foobar'`) for that item.
342 *
343 * 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 {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
349 * @param {string} href Link URL
350 * @param {string} text Link text
351 * @param {string} [id] ID of the new item, should be unique and preferably have
352 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
353 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
354 * @param {string} [accesskey] 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 {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
358 * the new item should be added before, should be another item in the same
359 * list, it will be ignored otherwise
360 *
361 * @return {HTMLElement|null} The added element (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 // Select the specified portlet
378 $portlet = $( '#' + portlet );
379 if ( $portlet.length === 0 ) {
380 return null;
381 }
382 // Select the first (most likely only) unordered list inside the portlet
383 $ul = $portlet.find( 'ul' ).eq( 0 );
384
385 // If it didn't have an unordered list yet, create it
386 if ( $ul.length === 0 ) {
387
388 $ul = $( '<ul>' );
389
390 // If there's no <div> inside, append it to the portlet directly
391 if ( $portlet.find( 'div:first' ).length === 0 ) {
392 $portlet.append( $ul );
393 } else {
394 // otherwise if there's a div (such as div.body or div.pBody)
395 // append the <ul> to last (most likely only) div
396 $portlet.find( 'div' ).eq( -1 ).append( $ul );
397 }
398 }
399 // Just in case..
400 if ( $ul.length === 0 ) {
401 return null;
402 }
403
404 // Unhide portlet if it was hidden before
405 $portlet.removeClass( 'emptyPortlet' );
406
407 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
408 // and back up the selector to the list item
409 if ( $portlet.hasClass( 'vectorTabs' ) ) {
410 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
411 } else {
412 $item = $link.wrap( '<li></li>' ).parent();
413 }
414
415 // Implement the properties passed to the function
416 if ( id ) {
417 $item.attr( 'id', id );
418 }
419
420 if ( tooltip ) {
421 // Trim any existing accesskey hint and the trailing space
422 tooltip = $.trim( tooltip.replace( util.tooltipAccessKeyRegexp, '' ) );
423 if ( accesskey ) {
424 tooltip += ' [' + accesskey + ']';
425 }
426 $link.attr( 'title', tooltip );
427 if ( accesskey ) {
428 util.updateTooltipAccessKeys( $link );
429 }
430 }
431
432 if ( accesskey ) {
433 $link.attr( 'accesskey', accesskey );
434 }
435
436 if ( nextnode ) {
437 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
438 // nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
439 // or nextnode is a CSS selector for jQuery
440 nextnode = $ul.find( nextnode );
441 } else if ( !nextnode.jquery || nextnode[0].parentNode !== $ul[0] ) {
442 // Fallback
443 $ul.append( $item );
444 return $item[0];
445 }
446 if ( nextnode.length === 1 ) {
447 // nextnode is a jQuery object that represents exactly one element
448 nextnode.before( $item );
449 return $item[0];
450 }
451 }
452
453 // Fallback (this is the default behavior)
454 $ul.append( $item );
455 return $item[0];
456
457 },
458
459 /**
460 * Add a little box at the top of the screen to inform the user of
461 * something, replacing any previous message.
462 * Calling with no arguments, with an empty string or null will hide the message
463 *
464 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
465 * to allow CSS/JS to hide different boxes. null = no class used.
466 * @deprecated since 1.20 Use mw#notify
467 */
468 jsMessage: function ( message ) {
469 if ( !arguments.length || message === '' || message === null ) {
470 return true;
471 }
472 if ( typeof message !== 'object' ) {
473 message = $.parseHTML( message );
474 }
475 mw.notify( message, { autoHide: true, tag: 'legacy' } );
476 return true;
477 },
478
479 /**
480 * Validate a string as representing a valid e-mail address
481 * according to HTML5 specification. Please note the specification
482 * does not validate a domain with one character.
483 *
484 * FIXME: should be moved to or replaced by a validation module.
485 *
486 * @param {string} mailtxt E-mail address to be validated.
487 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
488 * as determined by validation.
489 */
490 validateEmail: function ( mailtxt ) {
491 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
492
493 if ( mailtxt === '' ) {
494 return null;
495 }
496
497 // HTML5 defines a string as valid e-mail address if it matches
498 // the ABNF:
499 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
500 // With:
501 // - atext : defined in RFC 5322 section 3.2.3
502 // - ldh-str : defined in RFC 1034 section 3.5
503 //
504 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
505 // First, define the RFC 5322 'atext' which is pretty easy:
506 // atext = ALPHA / DIGIT / ; Printable US-ASCII
507 // "!" / "#" / ; characters not including
508 // "$" / "%" / ; specials. Used for atoms.
509 // "&" / "'" /
510 // "*" / "+" /
511 // "-" / "/" /
512 // "=" / "?" /
513 // "^" / "_" /
514 // "`" / "{" /
515 // "|" / "}" /
516 // "~"
517 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
518
519 // Next define the RFC 1034 'ldh-str'
520 // <domain> ::= <subdomain> | " "
521 // <subdomain> ::= <label> | <subdomain> "." <label>
522 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
523 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
524 // <let-dig-hyp> ::= <let-dig> | "-"
525 // <let-dig> ::= <letter> | <digit>
526 rfc1034LdhStr = 'a-z0-9\\-';
527
528 html5EmailRegexp = new RegExp(
529 // start of string
530 '^'
531 +
532 // User part which is liberal :p
533 '[' + rfc5322Atext + '\\.]+'
534 +
535 // 'at'
536 '@'
537 +
538 // Domain first part
539 '[' + rfc1034LdhStr + ']+'
540 +
541 // Optional second part and following are separated by a dot
542 '(?:\\.[' + rfc1034LdhStr + ']+)*'
543 +
544 // End of string
545 '$',
546 // RegExp is case insensitive
547 'i'
548 );
549 return (null !== mailtxt.match( html5EmailRegexp ) );
550 },
551
552 /**
553 * Note: borrows from IP::isIPv4
554 *
555 * @param {string} address
556 * @param {boolean} allowBlock
557 * @return {boolean}
558 */
559 isIPv4Address: function ( address, allowBlock ) {
560 if ( typeof address !== 'string' ) {
561 return false;
562 }
563
564 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
565 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
566 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
567
568 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
569 },
570
571 /**
572 * Note: borrows from IP::isIPv6
573 *
574 * @param {string} address
575 * @param {boolean} allowBlock
576 * @return {boolean}
577 */
578 isIPv6Address: function ( address, allowBlock ) {
579 if ( typeof address !== 'string' ) {
580 return false;
581 }
582
583 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
584 RE_IPV6_ADD =
585 '(?:' + // starts with "::" (including "::")
586 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
587 '|' + // ends with "::" (except "::")
588 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
589 '|' + // contains no "::"
590 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
591 ')';
592
593 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
594 return true;
595 }
596
597 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
598 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
599
600 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
601 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
602 }
603 };
604
605 mw.util = util;
606
607 }( mediaWiki, jQuery ) );