2 * Implements mediaWiki.util library
7 // Local cache and alias
8 var hideMessageTimeout
,
9 messageBoxEvents
= false,
14 * (don't call before document ready)
17 var profile
, $tocTitle
, $tocToggleLink
, hideTocCookie
;
19 /* Set up $.messageBox */
25 /* Set tooltipAccessKeyPrefix */
26 profile
= $.client
.profile();
28 // Opera on any platform
29 if ( profile
.name
=== 'opera' ) {
30 util
.tooltipAccessKeyPrefix
= 'shift-esc-';
32 // Chrome on any platform
33 } else if ( profile
.name
=== 'chrome' ) {
35 util
.tooltipAccessKeyPrefix
= (
36 profile
.platform
=== 'mac'
39 : profile
.platform
=== 'win'
41 // (both alt- and alt-shift work, but alt-f triggers Chrome wrench menu
42 // which alt-shift-f does not)
44 // Chrome on other (Ubuntu?)
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-';
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-';
66 // Firefox 2.x and later
67 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
68 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
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
82 /* Legacy fallbacks for setting the content */
83 // Vector, Monobook, Chick, etc... based skins
89 // Standard, CologneBlue
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
98 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
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
105 for ( var i
= 0, l
= selectors
.length
; i
< l
; i
++ ) {
106 $content
= $( selectors
[i
] ).first();
107 if ( $content
.length
) {
112 // Make sure we don't unset util.$content if it was preset and we don't find anything
113 return util
.$content
;
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
) {
126 util
.toggleToc( $(this) );
130 .wrap( '<span class="toctoggle"></span>' )
132 .prepend( ' [' )
136 if ( hideTocCookie
=== '1' ) {
137 util
.toggleToc( $tocToggleLink
);
145 * Encode the string like PHP's rawurlencode
147 * @param str string String to be encoded
149 rawurlencode: function ( 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
' );
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
161 * @param str string String to be encoded
163 wikiUrlencode: function ( str ) {
164 return util.rawurlencode( str )
165 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
169 * Get the link to a page name (relative to wgServer)
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.
174 wikiGetlink: function ( str ) {
175 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
176 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
180 * Get address to a script in the wiki root.
181 * For index.php use mw.config.get( 'wgScript
' )
184 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
185 * @return string Address to script (eg. '/w
/api
.php
' )
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
' );
194 return mw.config.get( 'wgScriptPath
' ) + '/' + str +
195 mw.config.get( 'wgScriptExtension
' );
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).
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;
213 * @param text string CSS to be appended
214 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
216 addCSS: function ( text ) {
217 var s = mw.loader.addStyleTag( text );
222 * Hide/show the table of contents element
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
.
230 toggleToc: function ( $toggleLink
, callback
) {
231 var $tocList
= $( '#toc ul:first' );
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, {
246 $tocList
.slideUp( 'fast', callback
);
247 $toggleLink
.text( mw
.msg( 'showtoc' ) );
248 $( '#toc' ).addClass( 'tochidden' );
249 $.cookie( 'mw_hidetoc', '1', {
261 * Grab the URL parameter value for the given parameter.
262 * Returns null if not found.
264 * @param param string The parameter name.
265 * @param url string URL to search through (optional)
266 * @return mixed Parameter value or null.
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
) + '=([^&#]*)' ),
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' ) );
283 * Access key prefix. Will be re-defined based on browser/operating system
284 * detection in mw.util.init().
286 tooltipAccessKeyPrefix
: 'alt-',
290 * Regex to match accesskey tooltips.
292 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
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.
300 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
301 * of elements to update.
303 updateTooltipAccessKeys: function ( $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
);
313 $nodes
.attr( 'title', function ( i
, val
) {
314 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
315 return val
.replace( util
.tooltipAccessKeyRegexp
,
316 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
324 * A jQuery object that refers to the content area element
325 * Populated by init().
330 * Add a link to a portlet menu on the page, such as:
332 * p-cactions (Content actions), p-personal (Personal tools),
333 * p-navigation (Navigation), p-tb (Toolbox)
335 * The first three paramters are required, the others are optional and
336 * may be null. Though providing an id and tooltip is recommended.
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.
343 * @example mw.util.addPortletLink(
344 * 'p-tb', 'http://mediawiki.org/',
345 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
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
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.
364 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
365 var $item
, $link
, $portlet
, $ul
;
367 // Check if there's atleast 3 arguments to prevent a TypeError
368 if ( arguments
.length
< 3 ) {
371 // Setup the anchor tag
372 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
374 $link
.attr( 'title', tooltip
);
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' ) ) {
382 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
385 $( '#searchform' ).before( $link
).before( ' | ' );
387 default: // Skins like chick, modern, monobook, myskin, simple, vector...
389 // Select the specified portlet
390 $portlet
= $( '#' + portlet
);
391 if ( $portlet
.length
=== 0 ) {
394 // Select the first (most likely only) unordered list inside the portlet
395 $ul
= $portlet
.find( 'ul' ).eq( 0 );
397 // If it didn't have an unordered list yet, create it
398 if ( $ul
.length
=== 0 ) {
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
);
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
);
412 if ( $ul
.length
=== 0 ) {
416 // Unhide portlet if it was hidden before
417 $portlet
.removeClass( 'emptyPortlet' );
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();
424 $item
= $link
.wrap( '<li></li>' ).parent();
427 // Implement the properties passed to the function
429 $item
.attr( 'id', id
);
432 $link
.attr( 'accesskey', accesskey
);
433 tooltip
+= ' [' + accesskey
+ ']';
434 $link
.attr( 'title', tooltip
);
436 if ( accesskey
&& tooltip
) {
437 util
.updateTooltipAccessKeys( $link
);
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
);
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
);
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)
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
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.
471 jsMessage: function ( message
, className
) {
472 var $messageDiv
= $( '#mw-js-message' );
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
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
);
491 if ( !messageBoxEvents
) {
492 messageBoxEvents
= true;
495 'mouseenter': stopHideMessageTimeout
,
496 'mouseleave': startHideMessageTimeout
,
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
507 $messageDiv
.prop( 'className', 'mw-js-message-' + className
);
510 if ( typeof message
=== 'object' ) {
512 $messageDiv
.append( message
);
514 $messageDiv
.html( message
);
517 $messageDiv
.slideDown();
518 startHideMessageTimeout();
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.
528 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
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.
534 validateEmail: function ( mailtxt
) {
535 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
537 if ( mailtxt
=== '' ) {
542 * HTML5 defines a string as valid e-mail address if it matches
544 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
546 * - atext : defined in RFC 5322 section 3.2.3
547 * - ldh-str : defined in RFC 1034 section 3.5
549 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
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.
566 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
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>
577 rfc1034_ldh_str
= "a-z0-9\\-";
579 HTML5_email_regexp
= new RegExp(
583 // User part which is liberal :p
584 '[' + rfc5322_atext
+ '\\.]+'
590 '[' + rfc1034_ldh_str
+ ']+'
592 // Optional second part and following are separated by a dot
593 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
597 // RegExp is case insensitive
600 return (null !== mailtxt
.match( HTML5_email_regexp
) );
604 * Note: borrows from IP::isIPv4
606 * @param address string
607 * @param allowBlock boolean
610 isIPv4Address: function ( address
, allowBlock
) {
611 if ( typeof address
!== 'string' ) {
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
;
619 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
623 * Note: borrows from IP::isIPv6
625 * @param address string
626 * @param allowBlock boolean
629 isIPv6Address: function ( address
, allowBlock
) {
630 if ( typeof address
!== 'string' ) {
634 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
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}' +
644 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
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}';
651 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
652 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
656 // Message auto-hide helpers
657 function hideMessage() {
658 $( '#mw-js-message' ).fadeOut( 'slow' );
660 function stopHideMessageTimeout() {
661 clearTimeout( hideMessageTimeout
);
663 function startHideMessageTimeout() {
664 clearTimeout( hideMessageTimeout
);
665 hideMessageTimeout
= setTimeout( hideMessage
, 5000 );
670 }( mediaWiki
, jQuery
) );