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