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 // Safari/Konqueror on any platform, or any browser on Mac
55 // (but not Safari on Windows)
56 } else if ( !( profile
.platform
=== 'win' && profile
.name
=== 'safari' )
57 && ( profile
.name
=== 'safari'
58 || profile
.platform
=== 'mac'
59 || profile
.name
=== 'konqueror' ) ) {
60 util
.tooltipAccessKeyPrefix
= 'ctrl-';
62 // Firefox 2.x and later
63 } else if ( profile
.name
=== 'firefox' && profile
.versionBase
> '1' ) {
64 util
.tooltipAccessKeyPrefix
= 'alt-shift-';
67 /* Fill $content var */
68 if ( $( '#bodyContent' ).length
) {
69 // Vector, Monobook, Chick etc.
70 util
.$content
= $( '#bodyContent' );
72 } else if ( $( '#mw_contentholder' ).length
) {
74 util
.$content
= $( '#mw_contentholder' );
76 } else if ( $( '#article' ).length
) {
77 // Standard, CologneBlue
78 util
.$content
= $( '#article' );
81 // #content is present on almost all if not all skins. Most skins (the above cases)
82 // have #content too, but as an outer wrapper instead of the article text container.
83 // The skins that don't have an outer wrapper do have #content for everything
84 // so it's a good fallback
85 util
.$content
= $( '#content' );
88 // Table of contents toggle
89 $tocTitle
= $( '#toctitle' );
90 $tocToggleLink
= $( '#togglelink' );
91 // Only add it if there is a TOC and there is no toggle added already
92 if ( $( '#toc' ).length
&& $tocTitle
.length
&& !$tocToggleLink
.length
) {
93 hideTocCookie
= $.cookie( 'mw_hidetoc' );
94 $tocToggleLink
= $( '<a href="#" class="internal" id="togglelink"></a>' )
95 .text( mw
.msg( 'hidetoc' ) )
96 .click( function ( e
) {
98 util
.toggleToc( $(this) );
102 .wrap( '<span class="toctoggle"></span>' )
104 .prepend( ' [' )
108 if ( hideTocCookie
=== '1' ) {
109 util
.toggleToc( $tocToggleLink
);
117 * Encode the string like PHP's rawurlencode
119 * @param str string String to be encoded
121 rawurlencode: function ( str
) {
123 return encodeURIComponent( str
)
124 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
125 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A
' ).replace( /~/g, '%7E
' );
129 * Encode page titles for use in a URL
130 * We want / and : to be included as literal characters in our title URLs
131 * as they otherwise fatally break the title
133 * @param str string String to be encoded
135 wikiUrlencode: function ( str ) {
136 return util.rawurlencode( str )
137 .replace( /%20/g, '_
' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
141 * Get the link to a page name (relative to wgServer)
143 * @param str String: Page name to get the link for.
144 * @return String: Location for a page with name of 'str
' or boolean false on error.
146 wikiGetlink: function ( str ) {
147 return mw.config.get( 'wgArticlePath
' ).replace( '$1',
148 util.wikiUrlencode( typeof str === 'string
' ? str : mw.config.get( 'wgPageName
' ) ) );
152 * Get address to a script in the wiki root.
153 * For index.php use mw.config.get( 'wgScript
' )
156 * @param str string Name of script (eg. 'api
'), defaults to 'index
'
157 * @return string Address to script (eg. '/w
/api
.php
' )
159 wikiScript: function ( str ) {
160 return mw.config.get( 'wgScriptPath
' ) + '/' + ( str || 'index
' ) +
161 mw.config.get( 'wgScriptExtension
' );
165 * Append a new style block to the head and return the CSSStyleSheet object.
166 * Use .ownerNode to access the <style> element, or use mw.loader.addStyleTag.
167 * This function returns the styleSheet object for convience (due to cross-browsers
168 * difference as to where it is located).
171 * var sheet = mw.util.addCSS('.foobar
{ display
: none
; }');
172 * $(foo).click(function () {
173 * // Toggle the sheet on and off
174 * sheet.disabled = !sheet.disabled;
178 * @param text string CSS to be appended
179 * @return CSSStyleSheet (use .ownerNode to get to the <style> element)
181 addCSS: function ( text ) {
182 var s = mw.loader.addStyleTag( text );
187 * Hide/show the table of contents element
189 * @param $toggleLink jQuery A jQuery object of the toggle link.
190 * @param callback function Function to be called after the toggle is
191 * completed (including the animation) (optional)
192 * @return mixed Boolean visibility of the toc (true if it's visible
)
193 * or Null
if there was no table
of contents
.
195 toggleToc: function ( $toggleLink
, callback
) {
196 var $tocList
= $( '#toc ul:first' );
198 // This function shouldn't be called if there's no TOC,
199 // but just in case...
200 if ( $tocList
.length
) {
201 if ( $tocList
.is( ':hidden' ) ) {
202 $tocList
.slideDown( 'fast', callback
);
203 $toggleLink
.text( mw
.msg( 'hidetoc' ) );
204 $( '#toc' ).removeClass( 'tochidden' );
205 $.cookie( 'mw_hidetoc', null, {
211 $tocList
.slideUp( 'fast', callback
);
212 $toggleLink
.text( mw
.msg( 'showtoc' ) );
213 $( '#toc' ).addClass( 'tochidden' );
214 $.cookie( 'mw_hidetoc', '1', {
226 * Grab the URL parameter value for the given parameter.
227 * Returns null if not found.
229 * @param param string The parameter name.
230 * @param url string URL to search through (optional)
231 * @return mixed Parameter value or null.
233 getParamValue: function ( param
, url
) {
234 url
= url
|| document
.location
.href
;
235 // Get last match, stop at hash
236 var re
= new RegExp( '^[^#]*[&?]' + $.escapeRE( param
) + '=([^&#]*)' ),
239 // Beware that decodeURIComponent is not required to understand '+'
240 // by spec, as encodeURIComponent does not produce it.
241 return decodeURIComponent( m
[1].replace( /\+/g, '%20' ) );
248 * Access key prefix. Will be re-defined based on browser/operating system
249 * detection in mw.util.init().
251 tooltipAccessKeyPrefix
: 'alt-',
255 * Regex to match accesskey tooltips.
257 tooltipAccessKeyRegexp
: /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
260 * Add the appropriate prefix to the accesskey shown in the tooltip.
261 * If the nodeList parameter is given, only those nodes are updated;
262 * otherwise, all the nodes that will probably have accesskeys by
263 * default are updated.
265 * @param $nodes {Array|jQuery} [optional] A jQuery object, or array
266 * of elements to update.
268 updateTooltipAccessKeys: function ( $nodes
) {
270 // Rather than going into a loop of all anchor tags, limit to few elements that
271 // contain the relevant anchor tags.
272 // Input and label are rare enough that no such optimization is needed
273 $nodes
= $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
274 } else if ( !( $nodes
instanceof $ ) ) {
275 $nodes
= $( $nodes
);
278 $nodes
.attr( 'title', function ( i
, val
) {
279 if ( val
&& util
.tooltipAccessKeyRegexp
.exec( val
) ) {
280 return val
.replace( util
.tooltipAccessKeyRegexp
,
281 '[' + util
.tooltipAccessKeyPrefix
+ '$5]' );
289 * A jQuery object that refers to the page-content element
290 * Populated by init().
295 * Add a link to a portlet menu on the page, such as:
297 * p-cactions (Content actions), p-personal (Personal tools),
298 * p-navigation (Navigation), p-tb (Toolbox)
300 * The first three paramters are required, the others are optional and
301 * may be null. Though providing an id and tooltip is recommended.
303 * By default the new link will be added to the end of the list. To
304 * add the link before a given existing item, pass the DOM node
305 * (document.getElementById( 'foobar' )) or the jQuery-selector
306 * ( '#foobar' ) of that item.
308 * @example mw.util.addPortletLink(
309 * 'p-tb', 'http://mediawiki.org/',
310 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
313 * @param portlet string ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
314 * @param href string Link URL
315 * @param text string Link text
316 * @param id string ID of the new item, should be unique and preferably have
317 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
318 * @param tooltip string Text to show when hovering over the link, without accesskey suffix
319 * @param accesskey string Access key to activate this link (one character, try
320 * to avoid conflicts. Use $( '[accesskey=x]' ).get() in the console to
321 * see if 'x' is already used.
322 * @param nextnode mixed DOM Node or jQuery-selector string of the item that the new
323 * item should be added before, should be another item in the same
324 * list, it will be ignored otherwise
326 * @return mixed The DOM Node of the added item (a ListItem or Anchor element,
327 * depending on the skin) or null if no element was added to the document.
329 addPortletLink: function ( portlet
, href
, text
, id
, tooltip
, accesskey
, nextnode
) {
330 var $item
, $link
, $portlet
, $ul
;
332 // Check if there's atleast 3 arguments to prevent a TypeError
333 if ( arguments
.length
< 3 ) {
336 // Setup the anchor tag
337 $link
= $( '<a>' ).attr( 'href', href
).text( text
);
339 $link
.attr( 'title', tooltip
);
342 // Some skins don't have any portlets
343 // just add it to the bottom of their 'sidebar' element as a fallback
344 switch ( mw
.config
.get( 'skin' ) ) {
347 $( '#quickbar' ).append( $link
.after( '<br/>' ) );
350 $( '#searchform' ).before( $link
).before( ' | ' );
352 default: // Skins like chick, modern, monobook, myskin, simple, vector...
354 // Select the specified portlet
355 $portlet
= $( '#' + portlet
);
356 if ( $portlet
.length
=== 0 ) {
359 // Select the first (most likely only) unordered list inside the portlet
360 $ul
= $portlet
.find( 'ul' ).eq( 0 );
362 // If it didn't have an unordered list yet, create it
363 if ( $ul
.length
=== 0 ) {
367 // If there's no <div> inside, append it to the portlet directly
368 if ( $portlet
.find( 'div:first' ).length
=== 0 ) {
369 $portlet
.append( $ul
);
371 // otherwise if there's a div (such as div.body or div.pBody)
372 // append the <ul> to last (most likely only) div
373 $portlet
.find( 'div' ).eq( -1 ).append( $ul
);
377 if ( $ul
.length
=== 0 ) {
381 // Unhide portlet if it was hidden before
382 $portlet
.removeClass( 'emptyPortlet' );
384 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
385 // and back up the selector to the list item
386 if ( $portlet
.hasClass( 'vectorTabs' ) ) {
387 $item
= $link
.wrap( '<li><span></span></li>' ).parent().parent();
389 $item
= $link
.wrap( '<li></li>' ).parent();
392 // Implement the properties passed to the function
394 $item
.attr( 'id', id
);
397 $link
.attr( 'accesskey', accesskey
);
398 tooltip
+= ' [' + accesskey
+ ']';
399 $link
.attr( 'title', tooltip
);
401 if ( accesskey
&& tooltip
) {
402 util
.updateTooltipAccessKeys( $link
);
405 // Where to put our node ?
406 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
407 if ( nextnode
&& nextnode
.parentNode
=== $ul
[0] ) {
408 $(nextnode
).before( $item
);
410 // - nextnode is a CSS selector for jQuery
411 } else if ( typeof nextnode
=== 'string' && $ul
.find( nextnode
).length
!== 0 ) {
412 $ul
.find( nextnode
).eq( 0 ).before( $item
);
414 // If the jQuery selector isn't found within the <ul>,
415 // or if nextnode was invalid or not passed at all,
416 // then just append it at the end of the <ul> (this is the default behaviour)
427 * Add a little box at the top of the screen to inform the user of
428 * something, replacing any previous message.
429 * Calling with no arguments, with an empty string or null will hide the message
431 * @param message {mixed} The DOM-element, jQuery object or HTML-string to be put inside the message box.
432 * @param className {String} Used in adding a class; should be different for each call
433 * to allow CSS/JS to hide different boxes. null = no class used.
434 * @return {Boolean} True on success, false on failure.
436 jsMessage: function ( message
, className
) {
437 var $messageDiv
= $( '#mw-js-message' );
439 if ( !arguments
.length
|| message
=== '' || message
=== null ) {
440 $messageDiv
.empty().hide();
441 stopHideMessageTimeout();
442 return true; // Emptying and hiding message is intended behaviour, return true
444 // We special-case skin structures provided by the software. Skins that
445 // choose to abandon or significantly modify our formatting can just define
446 // an mw-js-message div to start with.
447 if ( !$messageDiv
.length
) {
448 $messageDiv
= $( '<div id="mw-js-message"></div>' );
449 if ( util
.$content
.parent().length
) {
450 util
.$content
.parent().prepend( $messageDiv
);
456 if ( !messageBoxEvents
) {
457 messageBoxEvents
= true;
460 'mouseenter': stopHideMessageTimeout
,
461 'mouseleave': startHideMessageTimeout
,
464 .on( 'click', 'a', function ( e
) {
465 // Prevent links, even those that don't exist yet, from causing the
466 // message box to close when clicked
472 $messageDiv
.prop( 'className', 'mw-js-message-' + className
);
475 if ( typeof message
=== 'object' ) {
477 $messageDiv
.append( message
);
479 $messageDiv
.html( message
);
482 $messageDiv
.slideDown();
483 startHideMessageTimeout();
489 * Validate a string as representing a valid e-mail address
490 * according to HTML5 specification. Please note the specification
491 * does not validate a domain with one character.
493 * @todo FIXME: should be moved to or replaced by a JavaScript validation module.
495 * @param mailtxt string E-mail address to be validated.
496 * @return mixed Null if mailtxt was an empty string, otherwise true/false
497 * is determined by validation.
499 validateEmail: function ( mailtxt
) {
500 var rfc5322_atext
, rfc1034_ldh_str
, HTML5_email_regexp
;
502 if ( mailtxt
=== '' ) {
507 * HTML5 defines a string as valid e-mail address if it matches
509 * 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
511 * - atext : defined in RFC 5322 section 3.2.3
512 * - ldh-str : defined in RFC 1034 section 3.5
514 * (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68):
518 * First, define the RFC 5322 'atext' which is pretty easy:
519 * atext = ALPHA / DIGIT / ; Printable US-ASCII
520 "!" / "#" / ; characters not including
521 "$" / "%" / ; specials. Used for atoms.
531 rfc5322_atext
= "a-z0-9!#$%&'*+\\-/=?^_`{|}~";
534 * Next define the RFC 1034 'ldh-str'
535 * <domain> ::= <subdomain> | " "
536 * <subdomain> ::= <label> | <subdomain> "." <label>
537 * <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
538 * <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
539 * <let-dig-hyp> ::= <let-dig> | "-"
540 * <let-dig> ::= <letter> | <digit>
542 rfc1034_ldh_str
= "a-z0-9\\-";
544 HTML5_email_regexp
= new RegExp(
548 // User part which is liberal :p
549 '[' + rfc5322_atext
+ '\\.]+'
555 '[' + rfc1034_ldh_str
+ ']+'
557 // Optional second part and following are separated by a dot
558 '(?:\\.[' + rfc1034_ldh_str
+ ']+)*'
562 // RegExp is case insensitive
565 return (null !== mailtxt
.match( HTML5_email_regexp
) );
569 * Note: borrows from IP::isIPv4
571 * @param address string
572 * @param allowBlock boolean
575 isIPv4Address: function ( address
, allowBlock
) {
576 if ( typeof address
!== 'string' ) {
580 var block
= allowBlock
? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
581 RE_IP_BYTE
= '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
582 RE_IP_ADD
= '(?:' + RE_IP_BYTE
+ '\\.){3}' + RE_IP_BYTE
;
584 return address
.search( new RegExp( '^' + RE_IP_ADD
+ block
+ '$' ) ) !== -1;
588 * Note: borrows from IP::isIPv6
590 * @param address string
591 * @param allowBlock boolean
594 isIPv6Address: function ( address
, allowBlock
) {
595 if ( typeof address
!== 'string' ) {
599 var block
= allowBlock
? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
601 '(?:' + // starts with "::" (including "::")
602 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
603 '|' + // ends with "::" (except "::")
604 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
605 '|' + // contains no "::"
606 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
609 if ( address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1 ) {
613 RE_IPV6_ADD
= // contains one "::" in the middle (single '::' check below)
614 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
616 return address
.search( new RegExp( '^' + RE_IPV6_ADD
+ block
+ '$' ) ) !== -1
617 && address
.search( /::/ ) !== -1 && address
.search( /::.*::/ ) === -1;
621 // Message auto-hide helpers
622 function hideMessage() {
623 $( '#mw-js-message' ).fadeOut( 'slow' );
625 function stopHideMessageTimeout() {
626 clearTimeout( hideMessageTimeout
);
628 function startHideMessageTimeout() {
629 clearTimeout( hideMessageTimeout
);
630 hideMessageTimeout
= setTimeout( hideMessage
, 5000 );
635 }( mediaWiki
, jQuery
) );