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