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