mw.hook: Implement callback framework
[lhc/web/wiklou.git] / resources / mediawiki / mediawiki.util.js
1 ( function ( mw, $ ) {
2 'use strict';
3
4 /**
5 * Utility library
6 * @class mw.util
7 * @singleton
8 */
9 var util = {
10
11 /**
12 * Initialisation
13 * (don't call before document ready)
14 */
15 init: function () {
16 var profile, $tocTitle, $tocToggleLink, hideTocCookie;
17
18 /* Set tooltipAccessKeyPrefix */
19 profile = $.client.profile();
20
21 // Opera on any platform
22 if ( profile.name === 'opera' ) {
23 util.tooltipAccessKeyPrefix = 'shift-esc-';
24
25 // Chrome on any platform
26 } else if ( profile.name === 'chrome' ) {
27
28 util.tooltipAccessKeyPrefix = (
29 profile.platform === 'mac'
30 // Chrome on Mac
31 ? 'ctrl-option-'
32 // Chrome on Windows or Linux
33 // (both alt- and alt-shift work, but alt with E, D, F etc does not
34 // work since they are browser shortcuts)
35 : 'alt-shift-'
36 );
37
38 // Non-Windows Safari with webkit_version > 526
39 } else if ( profile.platform !== 'win'
40 && profile.name === 'safari'
41 && profile.layoutVersion > 526 ) {
42 util.tooltipAccessKeyPrefix = 'ctrl-alt-';
43 // Firefox 14+ on Mac
44 } else if ( profile.platform === 'mac'
45 && profile.name === 'firefox'
46 && profile.versionNumber >= 14 ) {
47 util.tooltipAccessKeyPrefix = 'ctrl-option-';
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-';
55
56 // Firefox 2.x and later
57 } else if ( profile.name === 'firefox' && profile.versionBase > '1' ) {
58 util.tooltipAccessKeyPrefix = 'alt-shift-';
59 }
60
61 /* Fill $content var */
62 util.$content = ( function () {
63 var i, l, $content, selectors;
64 selectors = [
65 // The preferred standard for setting $content (class="mw-body")
66 // You may also use (class="mw-body mw-body-primary") if you use
67 // mw-body in multiple locations.
68 // Or class="mw-body-primary" if you want $content to be deeper
69 // in the dom than mw-body
70 '.mw-body-primary',
71 '.mw-body',
72
73 /* Legacy fallbacks for setting the content */
74 // Vector, Monobook, Chick, etc... based skins
75 '#bodyContent',
76
77 // Modern based skins
78 '#mw_contentholder',
79
80 // Standard, CologneBlue
81 '#article',
82
83 // #content is present on almost all if not all skins. Most skins (the above cases)
84 // have #content too, but as an outer wrapper instead of the article text container.
85 // The skins that don't have an outer wrapper do have #content for everything
86 // so it's a good fallback
87 '#content',
88
89 // If nothing better is found fall back to our bodytext div that is guaranteed to be here
90 '#mw-content-text',
91
92 // Should never happen... well, it could if someone is not finished writing a skin and has
93 // not inserted bodytext yet. But in any case <body> should always exist
94 'body'
95 ];
96 for ( i = 0, l = selectors.length; i < l; i++ ) {
97 $content = $( selectors[i] ).first();
98 if ( $content.length ) {
99 return $content;
100 }
101 }
102
103 // Make sure we don't unset util.$content if it was preset and we don't find anything
104 return util.$content;
105 } )();
106
107 mw.hook( 'wikipage.content' ).fire( util.$content );
108
109 // Table of contents toggle
110 $tocTitle = $( '#toctitle' );
111 $tocToggleLink = $( '#togglelink' );
112 // Only add it if there is a TOC and there is no toggle added already
113 if ( $( '#toc' ).length && $tocTitle.length && !$tocToggleLink.length ) {
114 hideTocCookie = $.cookie( 'mw_hidetoc' );
115 $tocToggleLink = $( '<a href="#" class="internal" id="togglelink"></a>' )
116 .text( mw.msg( 'hidetoc' ) )
117 .click( function ( e ) {
118 e.preventDefault();
119 util.toggleToc( $(this) );
120 } );
121 $tocTitle.append(
122 $tocToggleLink
123 .wrap( '<span class="toctoggle"></span>' )
124 .parent()
125 .prepend( '&nbsp;[' )
126 .append( ']&nbsp;' )
127 );
128
129 if ( hideTocCookie === '1' ) {
130 util.toggleToc( $tocToggleLink );
131 }
132 }
133 },
134
135 /* Main body */
136
137 /**
138 * Encode the string like PHP's rawurlencode
139 *
140 * @param {string} str String to be encoded.
141 */
142 rawurlencode: function ( str ) {
143 str = String( str );
144 return encodeURIComponent( str )
145 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
146 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
147 },
148
149 /**
150 * Encode page titles for use in a URL
151 * We want / and : to be included as literal characters in our title URLs
152 * as they otherwise fatally break the title
153 *
154 * @param {string} str String to be encoded.
155 */
156 wikiUrlencode: function ( str ) {
157 return util.rawurlencode( str )
158 .replace( /%20/g, '_' ).replace( /%3A/g, ':' ).replace( /%2F/g, '/' );
159 },
160
161 /**
162 * Get the link to a page name (relative to `wgServer`),
163 *
164 * @param {string} str Page name to get the link for.
165 * @return {string} Location for a page with name of `str` or boolean false on error.
166 */
167 wikiGetlink: function ( str ) {
168 return mw.config.get( 'wgArticlePath' ).replace( '$1',
169 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) ) );
170 },
171
172 /**
173 * Get address to a script in the wiki root.
174 * For index.php use `mw.config.get( 'wgScript' )`.
175 *
176 * @since 1.18
177 * @param str string Name of script (eg. 'api'), defaults to 'index'
178 * @return string Address to script (eg. '/w/api.php' )
179 */
180 wikiScript: function ( str ) {
181 str = str || 'index';
182 if ( str === 'index' ) {
183 return mw.config.get( 'wgScript' );
184 } else if ( str === 'load' ) {
185 return mw.config.get( 'wgLoadScript' );
186 } else {
187 return mw.config.get( 'wgScriptPath' ) + '/' + str +
188 mw.config.get( 'wgScriptExtension' );
189 }
190 },
191
192 /**
193 * Append a new style block to the head and return the CSSStyleSheet object.
194 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
195 * This function returns the styleSheet object for convience (due to cross-browsers
196 * difference as to where it is located).
197 *
198 * var sheet = mw.util.addCSS('.foobar { display: none; }');
199 * $(foo).click(function () {
200 * // Toggle the sheet on and off
201 * sheet.disabled = !sheet.disabled;
202 * });
203 *
204 * @param {string} text CSS to be appended
205 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
206 */
207 addCSS: function ( text ) {
208 var s = mw.loader.addStyleTag( text );
209 return s.sheet || s;
210 },
211
212 /**
213 * Hide/show the table of contents element
214 *
215 * @param {jQuery} $toggleLink A jQuery object of the toggle link.
216 * @param {Function} [callback] Function to be called after the toggle is
217 * completed (including the animation).
218 * @return {Mixed} Boolean visibility of the toc (true if it's visible)
219 * or Null if there was no table of contents.
220 */
221 toggleToc: function ( $toggleLink, callback ) {
222 var $tocList = $( '#toc ul:first' );
223
224 // This function shouldn't be called if there's no TOC,
225 // but just in case...
226 if ( $tocList.length ) {
227 if ( $tocList.is( ':hidden' ) ) {
228 $tocList.slideDown( 'fast', callback );
229 $toggleLink.text( mw.msg( 'hidetoc' ) );
230 $( '#toc' ).removeClass( 'tochidden' );
231 $.cookie( 'mw_hidetoc', null, {
232 expires: 30,
233 path: '/'
234 } );
235 return true;
236 } else {
237 $tocList.slideUp( 'fast', callback );
238 $toggleLink.text( mw.msg( 'showtoc' ) );
239 $( '#toc' ).addClass( 'tochidden' );
240 $.cookie( 'mw_hidetoc', '1', {
241 expires: 30,
242 path: '/'
243 } );
244 return false;
245 }
246 } else {
247 return null;
248 }
249 },
250
251 /**
252 * Grab the URL parameter value for the given parameter.
253 * Returns null if not found.
254 *
255 * @param {string} param The parameter name.
256 * @param {string} [url] URL to search through.
257 * @return {Mixed} Parameter value or null.
258 */
259 getParamValue: function ( param, url ) {
260 if ( url === undefined ) {
261 url = document.location.href;
262 }
263 // Get last match, stop at hash
264 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
265 m = re.exec( url );
266 if ( m ) {
267 // Beware that decodeURIComponent is not required to understand '+'
268 // by spec, as encodeURIComponent does not produce it.
269 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
270 }
271 return null;
272 },
273
274 /**
275 * @property {string}
276 * Access key prefix. Will be re-defined based on browser/operating system
277 * detection in mw.util#init.
278 */
279 tooltipAccessKeyPrefix: 'alt-',
280
281 /**
282 * @property {RegExp}
283 * Regex to match accesskey tooltips.
284 *
285 * Should match:
286 *
287 * - "ctrl-option-"
288 * - "alt-shift-"
289 * - "ctrl-alt-"
290 * - "ctrl-"
291 *
292 * The accesskey is matched in group $6.
293 */
294 tooltipAccessKeyRegexp: /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/,
295
296 /**
297 * Add the appropriate prefix to the accesskey shown in the tooltip.
298 * If the nodeList parameter is given, only those nodes are updated;
299 * otherwise, all the nodes that will probably have accesskeys by
300 * default are updated.
301 *
302 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
303 */
304 updateTooltipAccessKeys: function ( $nodes ) {
305 if ( !$nodes ) {
306 // Rather than going into a loop of all anchor tags, limit to few elements that
307 // contain the relevant anchor tags.
308 // Input and label are rare enough that no such optimization is needed
309 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label' );
310 } else if ( !( $nodes instanceof $ ) ) {
311 $nodes = $( $nodes );
312 }
313
314 $nodes.attr( 'title', function ( i, val ) {
315 if ( val && util.tooltipAccessKeyRegexp.test( val ) ) {
316 return val.replace( util.tooltipAccessKeyRegexp,
317 '[' + util.tooltipAccessKeyPrefix + '$6]' );
318 }
319 return val;
320 } );
321 },
322
323 /*
324 * @property {jQuery}
325 * A jQuery object that refers to the content area element.
326 * Populated by #init.
327 */
328 $content: null,
329
330 /**
331 * Add a link to a portlet menu on the page, such as:
332 *
333 * p-cactions (Content actions), p-personal (Personal tools),
334 * p-navigation (Navigation), p-tb (Toolbox)
335 *
336 * The first three paramters are required, the others are optional and
337 * may be null. Though providing an id and tooltip is recommended.
338 *
339 * By default the new link will be added to the end of the list. To
340 * add the link before a given existing item, pass the DOM node
341 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
342 * (e.g. `'#foobar'`) for that item.
343 *
344 * mw.util.addPortletLink(
345 * 'p-tb', 'http://mediawiki.org/',
346 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
347 * );
348 *
349 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
350 * @param {string} href Link URL
351 * @param {string} text Link text
352 * @param {string} [id] ID of the new item, should be unique and preferably have
353 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
354 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
355 * @param {string} [accesskey] Access key to activate this link (one character, try
356 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
357 * see if 'x' is already used.
358 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
359 * the new item should be added before, should be another item in the same
360 * list, it will be ignored otherwise
361 *
362 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
363 * depending on the skin) or null if no element was added to the document.
364 */
365 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
366 var $item, $link, $portlet, $ul;
367
368 // Check if there's atleast 3 arguments to prevent a TypeError
369 if ( arguments.length < 3 ) {
370 return null;
371 }
372 // Setup the anchor tag
373 $link = $( '<a>' ).attr( 'href', href ).text( text );
374 if ( tooltip ) {
375 $link.attr( 'title', tooltip );
376 }
377
378 // Select the specified portlet
379 $portlet = $( '#' + portlet );
380 if ( $portlet.length === 0 ) {
381 return null;
382 }
383 // Select the first (most likely only) unordered list inside the portlet
384 $ul = $portlet.find( 'ul' ).eq( 0 );
385
386 // If it didn't have an unordered list yet, create it
387 if ( $ul.length === 0 ) {
388
389 $ul = $( '<ul>' );
390
391 // If there's no <div> inside, append it to the portlet directly
392 if ( $portlet.find( 'div:first' ).length === 0 ) {
393 $portlet.append( $ul );
394 } else {
395 // otherwise if there's a div (such as div.body or div.pBody)
396 // append the <ul> to last (most likely only) div
397 $portlet.find( 'div' ).eq( -1 ).append( $ul );
398 }
399 }
400 // Just in case..
401 if ( $ul.length === 0 ) {
402 return null;
403 }
404
405 // Unhide portlet if it was hidden before
406 $portlet.removeClass( 'emptyPortlet' );
407
408 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
409 // and back up the selector to the list item
410 if ( $portlet.hasClass( 'vectorTabs' ) ) {
411 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
412 } else {
413 $item = $link.wrap( '<li></li>' ).parent();
414 }
415
416 // Implement the properties passed to the function
417 if ( id ) {
418 $item.attr( 'id', id );
419 }
420
421 if ( tooltip ) {
422 // Trim any existing accesskey hint and the trailing space
423 tooltip = $.trim( tooltip.replace( util.tooltipAccessKeyRegexp, '' ) );
424 if ( accesskey ) {
425 tooltip += ' [' + accesskey + ']';
426 }
427 $link.attr( 'title', tooltip );
428 if ( accesskey ) {
429 util.updateTooltipAccessKeys( $link );
430 }
431 }
432
433 if ( accesskey ) {
434 $link.attr( 'accesskey', accesskey );
435 }
436
437 // Where to put our node ?
438 // - nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
439 if ( nextnode && nextnode.parentNode === $ul[0] ) {
440 $( nextnode ).before( $item );
441
442 // - nextnode is a CSS selector for jQuery
443 } else if ( typeof nextnode === 'string' && $ul.find( nextnode ).length !== 0 ) {
444 $ul.find( nextnode ).eq( 0 ).before( $item );
445
446 // If the jQuery selector isn't found within the <ul>,
447 // or if nextnode was invalid or not passed at all,
448 // then just append it at the end of the <ul> (this is the default behavior)
449 } else {
450 $ul.append( $item );
451 }
452
453 return $item[0];
454 },
455
456 /**
457 * Add a little box at the top of the screen to inform the user of
458 * something, replacing any previous message.
459 * Calling with no arguments, with an empty string or null will hide the message
460 *
461 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
462 * to allow CSS/JS to hide different boxes. null = no class used.
463 * @deprecated Use mw#notify
464 */
465 jsMessage: function ( message ) {
466 if ( !arguments.length || message === '' || message === null ) {
467 return true;
468 }
469 if ( typeof message !== 'object' ) {
470 message = $.parseHTML( message );
471 }
472 mw.notify( message, { autoHide: true, tag: 'legacy' } );
473 return true;
474 },
475
476 /**
477 * Validate a string as representing a valid e-mail address
478 * according to HTML5 specification. Please note the specification
479 * does not validate a domain with one character.
480 *
481 * FIXME: should be moved to or replaced by a validation module.
482 *
483 * @param {string} mailtxt E-mail address to be validated.
484 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
485 * as determined by validation.
486 */
487 validateEmail: function ( mailtxt ) {
488 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
489
490 if ( mailtxt === '' ) {
491 return null;
492 }
493
494 // HTML5 defines a string as valid e-mail address if it matches
495 // the ABNF:
496 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
497 // With:
498 // - atext : defined in RFC 5322 section 3.2.3
499 // - ldh-str : defined in RFC 1034 section 3.5
500 //
501 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
502 // First, define the RFC 5322 'atext' which is pretty easy:
503 // atext = ALPHA / DIGIT / ; Printable US-ASCII
504 // "!" / "#" / ; characters not including
505 // "$" / "%" / ; specials. Used for atoms.
506 // "&" / "'" /
507 // "*" / "+" /
508 // "-" / "/" /
509 // "=" / "?" /
510 // "^" / "_" /
511 // "`" / "{" /
512 // "|" / "}" /
513 // "~"
514 rfc5322Atext = '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 rfc1034LdhStr = 'a-z0-9\\-';
524
525 html5EmailRegexp = new RegExp(
526 // start of string
527 '^'
528 +
529 // User part which is liberal :p
530 '[' + rfc5322Atext + '\\.]+'
531 +
532 // 'at'
533 '@'
534 +
535 // Domain first part
536 '[' + rfc1034LdhStr + ']+'
537 +
538 // Optional second part and following are separated by a dot
539 '(?:\\.[' + rfc1034LdhStr + ']+)*'
540 +
541 // End of string
542 '$',
543 // RegExp is case insensitive
544 'i'
545 );
546 return (null !== mailtxt.match( html5EmailRegexp ) );
547 },
548
549 /**
550 * Note: borrows from IP::isIPv4
551 *
552 * @param {string} address
553 * @param {boolean} allowBlock
554 * @return {boolean}
555 */
556 isIPv4Address: function ( address, allowBlock ) {
557 if ( typeof address !== 'string' ) {
558 return false;
559 }
560
561 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
562 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
563 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
564
565 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
566 },
567
568 /**
569 * Note: borrows from IP::isIPv6
570 *
571 * @param {string} address
572 * @param {boolean} allowBlock
573 * @return {boolean}
574 */
575 isIPv6Address: function ( address, allowBlock ) {
576 if ( typeof address !== 'string' ) {
577 return false;
578 }
579
580 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
581 RE_IPV6_ADD =
582 '(?:' + // starts with "::" (including "::")
583 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
584 '|' + // ends with "::" (except "::")
585 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
586 '|' + // contains no "::"
587 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
588 ')';
589
590 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
591 return true;
592 }
593
594 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
595 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
596
597 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
598 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
599 }
600 };
601
602 mw.util = util;
603
604 }( mediaWiki, jQuery ) );