Follow-up r76987. Apparently this works better in Firefox 2.
[lhc/web/wiklou.git] / resources / mediawiki.util / mediawiki.util.js
1 /*
2 * Utilities
3 */
4
5 (function ($, mw) {
6
7 mediaWiki.util = {
8
9 /* Initialisation */
10 'initialised' : false,
11 'init' : function () {
12 if ( this.initialised === false ) {
13 this.initialised = true;
14
15 // Any initialisation after the DOM is ready
16 $(function () {
17
18 // Shortcut
19 var profile = $.client.profile();
20
21 // Set tooltipAccessKeyPrefix
22
23 // Opera on any platform
24 if ( profile.name == 'opera' ) {
25 mw.util.tooltipAccessKeyPrefix = 'shift-esc-';
26
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-' );
32
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-';
39
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-';
47
48 // Firefox 2.x
49 } else if ( profile.name == 'firefox' && profile.versionBase == '2' ) {
50 mw.util.tooltipAccessKeyPrefix = 'alt-shift-';
51 }
52
53 // Enable CheckboxShiftClick
54 $('input[type=checkbox]:not(.noshiftselect)').checkboxShiftClick();
55
56 // Emulate placeholder if not supported by browser
57 if ( !( 'placeholder' in document.createElement( 'input' ) ) ) {
58 $('input[placeholder]').placeholder();
59 }
60
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 });
70
71 return true;
72 }
73 return false;
74 },
75
76 /* Main body */
77
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 },
89
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 },
101
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 },
120
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 },
129
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 },
155
156
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 },
174
175 // Access key prefix.
176 // Will be re-defined based on browser/operating system detection in
177 // mw.util.init().
178 'tooltipAccessKeyPrefix' : 'alt-',
179
180 // Regex to match accesskey tooltips
181 'tooltipAccessKeyRegexp': /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
182
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') );
202
203 // these are rare enough that no such optimization is needed
204 this.updateTooltipAccessKeys( $('input') );
205 this.updateTooltipAccessKeys( $('label') );
206 return;
207 }
208
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 },
218
219 // jQuery object that refers to the page-content element
220 // Populated by init()
221 '$content' : null,
222
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 ) {
260
261 // Setup the anchor tag
262 var $link = $('<a />').attr( 'href', href ).text( text );
263
264 // Some skins don't have any portlets
265 // just add it to the bottom of their 'sidebar' element as a fallback
266 switch ( skin ) {
267 case 'standard' :
268 case 'cologneblue' :
269 $("#quickbar").append($link.after( '<br />' ));
270 return $link.get(0);
271 case 'nostalgia' :
272 $("#searchform").before($link).before( ' &#124; ' );
273 return $link.get(0);
274 default : // Skins like chick, modern, monobook, myskin, simple, vector...
275
276 // Select the specified portlet
277 var $portlet = $('#' + portlet);
278 if ( $portlet.length === 0 ) {
279 return null;
280 }
281 // Select the first (most likely only) unordered list inside the portlet
282 var $ul = $portlet.find( 'ul' ).eq( 0 );
283
284 // If it didn't have an unordered list yet, create it
285 if ($ul.length === 0) {
286 // If there's no <div> inside, append it to the portlet directly
287 if ($portlet.find( 'div' ).length === 0) {
288 $portlet.append( '<ul/>' );
289 } else {
290 // otherwise if there's a div (such as div.body or div.pBody)
291 // append the <ul> to last (most likely only) div
292 $portlet.find( 'div' ).eq( -1 ).append( '<ul/>' );
293 }
294 // Select the created element
295 $ul = $portlet.find( 'ul' ).eq( 0 );
296 }
297 // Just in case..
298 if ( $ul.length === 0 ) {
299 return null;
300 }
301
302 // Unhide portlet if it was hidden before
303 $portlet.removeClass( 'emptyPortlet' );
304
305 // Wrap the anchor tag in a <span> and create a list item for it
306 // and back up the selector to the list item
307 var $item = $link.wrap( '<li><span /></li>' ).parent().parent();
308
309 // Implement the properties passed to the function
310 if ( id ) {
311 $item.attr( 'id', id );
312 }
313 if ( accesskey ) {
314 $link.attr( 'accesskey', accesskey );
315 tooltip += ' [' + accesskey + ']';
316 }
317 if ( tooltip ) {
318 $link.attr( 'title', tooltip );
319 }
320 if ( accesskey && tooltip ) {
321 this.updateTooltipAccessKeys( $link );
322 }
323
324 // Append using DOM-element passing
325 if ( nextnode && nextnode.parentNode == $ul.get( 0 ) ) {
326 $(nextnode).before( $item );
327 } else {
328 // If the jQuery selector isn't found within the <ul>, just
329 // append it at the end
330 if ( $ul.find( nextnode ).length === 0 ) {
331 $ul.append( $item );
332 } else {
333 // Append using jQuery CSS selector
334 $ul.find( nextnode ).eq( 0 ).before( $item );
335 }
336 }
337
338 return $item.get( 0 );
339 }
340 }
341
342 };
343
344 mediaWiki.util.init();
345
346 })(jQuery, mediaWiki);