fixing a TypeError when the function would be called without any arguments
[mediawiki.git] / resources / mediawiki.util / mediawiki.util.js
blob15c1735f6765bbf4575af7a97256ff6e44e3bf24
1 /*
2  * Utilities
3  */
5 (function ($, mw) {
7         mediaWiki.util = {
9                 /* Initialisation */
10                 'initialised' : false,
11                 'init' : function () {
12                         if ( this.initialised === false ) {
13                                 this.initialised = true;
15                                 // Any initialisation after the DOM is ready
16                                 $(function () {
18                                         // Shortcut
19                                         var profile = $.client.profile();
21                                         // Set tooltipAccessKeyPrefix
23                                         // Opera on any platform
24                                         if ( profile.name == 'opera' ) {
25                                                 mw.util.tooltipAccessKeyPrefix = 'shift-esc-';
27                                         // Chrome on any platform
28                                         } else if ( profile.name == 'chrome' ) {
29                                                 // Chrome on Mac or Chrome on other platform ?
30                                                 mw.util.tooltipAccessKeyPrefix = ( profile.platform == 'mac' 
31                                                         ? 'ctrl-option-' : 'alt-' );
33                                         // Non-Windows Safari with webkit_version > 526
34                                         } else if ( profile.platform !== 'win' 
35                                                 && profile.name == 'safari' 
36                                                 && profile.layoutVersion > 526 ) 
37                                         {
38                                                 mw.util.tooltipAccessKeyPrefix = 'ctrl-alt-';
40                                         // Safari/Konqueror on any platform, or any browser on Mac 
41                                         // (but not Safari on Windows)
42                                         } else if ( !( profile.platform == 'win' && profile.name == 'safari' )
43                                                                         && ( profile.name == 'safari'
44                                                                           || profile.platform == 'mac'
45                                                                           || profile.name == 'konqueror' ) ) {
46                                                 mw.util.tooltipAccessKeyPrefix = 'ctrl-';
48                                         // Firefox 2.x
49                                         } else if ( profile.name == 'firefox' && profile.versionBase == '2' ) {
50                                                 mw.util.tooltipAccessKeyPrefix = 'alt-shift-';
51                                         }
53                                         // Enable CheckboxShiftClick
54                                         $('input[type=checkbox]:not(.noshiftselect)').checkboxShiftClick();
56                                         // Emulate placeholder if not supported by browser
57                                         if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
58                                                 $('input[placeholder]').placeholder();
59                                         }
61                                         // Fill $content var
62                                         if ( $('#bodyContent').length ) {
63                                                 mw.util.$content = $('#bodyContent');
64                                         } else if ( $('#article').length ) {
65                                                 mw.util.$content = $('#article');
66                                         } else {
67                                                 mw.util.$content = $('#content');
68                                         }
69                                 });
71                                 return true;
72                         }
73                         return false;
74                 },
76                 /* Main body */
78                 /**
79                  * Encode the string like PHP's rawurlencode
80                  *
81                  * @param str String to be encoded
82                  */
83                 'rawurlencode' : function( str ) {
84                         str = (str + '').toString();
85                         return encodeURIComponent( str )
86                                 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
87                                 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
88                 },
90                 /**
91                  * Encode page titles for use in a URL
92                  * We want / and : to be included as literal characters in our title URLs
93                  * as they otherwise fatally break the title
94                  *
95                  * @param str String to be encoded
96                  */
97                 'wikiUrlencode' : function( str ) {
98                         return this.rawurlencode( str )
99                                 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
100                 },
102                 /**
103                  * Append a new style block to the head
104                  *
105                  * @param text String CSS to be appended
106                  * @return the CSS stylesheet
107                  */
108                 'addCSS' : function( text ) {
109                         var s = document.createElement( 'style' );
110                         s.type = 'text/css';
111                         s.rel = 'stylesheet';
112                         if ( s.styleSheet ) {
113                                 s.styleSheet.cssText = text; // IE
114                         } else {
115                                 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
116                         }
117                         document.getElementsByTagName("head")[0].appendChild( s );
118                         return s.sheet || s;
119                 },
121                 /**
122                  * Get the full URL to a page name
123                  *
124                  * @param str Page name to link to
125                  */
126                 'wikiGetlink' : function( str ) {
127                         return wgServer + wgArticlePath.replace( '$1', this.wikiUrlencode( str ) );
128                 },
130                 /**
131                  * Check is a variable is empty. Supports strings, booleans, arrays and 
132                  * objects. The string "0" is considered empty. A string containing only 
133                  * whitespace (ie. " ") is considered not empty.
134                  *
135                  * @param v The variable to check for emptyness
136                  */
137                 'isEmpty' : function( v ) {
138                         var key;
139                         if ( v === "" || v === 0 || v === "0" || v === null 
140                                 || v === false || typeof v === 'undefined' ) 
141                         {
142                                 return true;
143                         }
144                         if ( v.length === 0 ) {
145                                 return true;
146                         }
147                         if ( typeof v === 'object' ) {
148                                 for ( key in v ) {
149                                         return false;
150                                 }
151                                 return true;
152                         }
153                         return false;
154                 },
157                 /**
158                  * Grab the URL parameter value for the given parameter.
159                  * Returns null if not found.
160                  *
161                  * @param param The parameter name
162                  * @param url URL to search through (optional)
163                  */
164                 'getParamValue' : function( param, url ) {
165                         url = url ? url : document.location.href;
166                         // Get last match, stop at hash
167                         var re = new RegExp( '[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ); 
168                         var m = re.exec( url );
169                         if ( m && m.length > 1 ) {
170                                 return decodeURIComponent( m[1] );
171                         }
172                         return null;
173                 },
175                 // Access key prefix.
176                 // Will be re-defined based on browser/operating system detection in 
177                 // mw.util.init().
178                 'tooltipAccessKeyPrefix' : 'alt-',
180                 // Regex to match accesskey tooltips
181                 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
183                 /**
184                  * Add the appropriate prefix to the accesskey shown in the tooltip.
185                  * If the nodeList parameter is given, only those nodes are updated;
186                  * otherwise, all the nodes that will probably have accesskeys by
187                  * default are updated.
188                  *
189                  * @param nodeList jQuery object, or array of elements
190                  */
191                 'updateTooltipAccessKeys' : function( nodeList ) {
192                         var $nodes;
193                         if ( nodeList instanceof jQuery ) {
194                                 $nodes = nodeList;
195                         } else if ( nodeList ) {
196                                 $nodes = $(nodeList);
197                         } else {
198                                 // Rather than scanning all links, just the elements that 
199                                 // contain the relevant links
200                                 this.updateTooltipAccessKeys( 
201                                         $('#column-one a, #mw-head a, #mw-panel a, #p-logo a') );
203                                 // these are rare enough that no such optimization is needed
204                                 this.updateTooltipAccessKeys( $('input') );
205                                 this.updateTooltipAccessKeys( $('label') );
206                                 return;
207                         }
209                         $nodes.each( function ( i ) {
210                                 var tip = $(this).attr( 'title' );
211                                 if ( !!tip && mw.util.tooltipAccessKeyRegexp.exec( tip ) ) {
212                                         tip = tip.replace( mw.util.tooltipAccessKeyRegexp, 
213                                                 '[' + mw.util.tooltipAccessKeyPrefix + "$5]" );
214                                         $(this).attr( 'title', tip );
215                                 }
216                         });
217                 },
219                 // jQuery object that refers to the page-content element
220                 // Populated by init()
221                 '$content' : null,
223                 /**
224                  * Add a link to a portlet menu on the page, such as:
225                  *
226                  * p-cactions (Content actions), p-personal (Personal tools), 
227                  * p-navigation (Navigation), p-tb (Toolbox)
228                  *
229                  * The first three paramters are required, others are optionals. Though
230                  * providing an id and tooltip is recommended.
231                  *
232                  * By default the new link will be added to the end of the list. To 
233                  * add the link before a given existing item, pass the DOM node 
234                  * (document.getElementById('foobar')) or the jQuery-selector 
235                  * ('#foobar') of that item.
236                  *
237                  * @example mw.util.addPortletLink(
238                  *     'p-tb', 'http://mediawiki.org/', 
239                  *     'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
240                  *   )
241                  *
242                  * @param portlet ID of the target portlet ('p-cactions' or 'p-personal' etc.)
243                  * @param href Link URL
244                  * @param text Link text (will be automatically converted to lower 
245                  *     case by CSS for p-cactions in Monobook)
246                  * @param id ID of the new item, should be unique and preferably have 
247                  *     the appropriate prefix ('ca-', 'pt-', 'n-' or 't-')
248                  * @param tooltip Text to show when hovering over the link, without accesskey suffix
249                  * @param accesskey Access key to activate this link (one character, try 
250                  *     to avoid conflicts. Use $('[accesskey=x').get() in the console to 
251                  *     see if 'x' is already used.
252                  * @param nextnode DOM node or jQuery-selector of the item that the new 
253                  *     item should be added before, should be another item in the same 
254                  *     list will be ignored if not the so
255                  *
256                  * @return The DOM node of the new item (a LI element, or A element for 
257                  *     older skins) or null.
258                  */
259                 'addPortletLink' : function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
261                         // Check if there's atleast 3 arguments to prevent a TypeError
262                         if ( arguments.length < 3 ) {
263                                 return null;
264                         }
265                         // Setup the anchor tag
266                         var $link = $('<a />').attr( 'href', href ).text( text );
268                         // Some skins don't have any portlets
269                         // just add it to the bottom of their 'sidebar' element as a fallback
270                         switch ( skin ) {
271                         case 'standard' :
272                         case 'cologneblue' :
273                                 $("#quickbar").append($link.after( '<br />' ));
274                                 return $link.get(0);
275                         case 'nostalgia' :
276                                 $("#searchform").before($link).before( ' &#124; ' );
277                                 return $link.get(0);
278                         default : // Skins like chick, modern, monobook, myskin, simple, vector...
280                                 // Select the specified portlet
281                                 var $portlet = $('#' + portlet);
282                                 if ( $portlet.length === 0 ) {
283                                         return null;
284                                 }
285                                 // Select the first (most likely only) unordered list inside the portlet
286                                 var $ul = $portlet.find( 'ul' ).eq( 0 );
288                                 // If it didn't have an unordered list yet, create it
289                                 if ($ul.length === 0) {
290                                         // If there's no <div> inside, append it to the portlet directly
291                                         if ($portlet.find( 'div' ).length === 0) {
292                                                 $portlet.append( '<ul/>' );
293                                         } else {
294                                                 // otherwise if there's a div (such as div.body or div.pBody) 
295                                                 // append the <ul> to last (most likely only) div
296                                                 $portlet.find( 'div' ).eq( -1 ).append( '<ul/>' );
297                                         }
298                                         // Select the created element
299                                         $ul = $portlet.find( 'ul' ).eq( 0 );
300                                 }
301                                 // Just in case..
302                                 if ( $ul.length === 0 ) {
303                                         return null;
304                                 }
306                                 // Unhide portlet if it was hidden before
307                                 $portlet.removeClass( 'emptyPortlet' );
309                                 // Wrap the anchor tag in a <span> and create a list item for it
310                                 // and back up the selector to the list item
311                                 var $item = $link.wrap( '<li><span /></li>' ).parent().parent();
313                                 // Implement the properties passed to the function
314                                 if ( id ) {
315                                         $item.attr( 'id', id );
316                                 }
317                                 if ( accesskey ) {
318                                         $link.attr( 'accesskey', accesskey );
319                                         tooltip += ' [' + accesskey + ']';
320                                 }
321                                 if ( tooltip ) {
322                                         $link.attr( 'title', tooltip );
323                                 }
324                                 if ( accesskey && tooltip ) {
325                                         this.updateTooltipAccessKeys( $link );
326                                 }
328                                 // Append using DOM-element passing
329                                 if ( nextnode && nextnode.parentNode == $ul.get( 0 ) ) {
330                                         $(nextnode).before( $item );
331                                 } else {
332                                         // If the jQuery selector isn't found within the <ul>, just 
333                                         // append it at the end
334                                         if ( $ul.find( nextnode ).length === 0 ) {
335                                                 $ul.append( $item );
336                                         } else {
337                                                 // Append using jQuery CSS selector
338                                                 $ul.find( nextnode ).eq( 0 ).before( $item );
339                                         }
340                                 }
342                                 return $item.get( 0 );
343                         }
344                 }
346         };
348         mediaWiki.util.init();
350 })(jQuery, mediaWiki);