mediawiki.util: Insert node before updating tooltip for accesskey
[lhc/web/wiklou.git] / resources / src / 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 util.$content = ( function () {
17 var i, l, $node, selectors;
18
19 selectors = [
20 // The preferred standard is class "mw-body".
21 // You may also use class "mw-body mw-body-primary" if you use
22 // mw-body in multiple locations. Or class "mw-body-primary" if
23 // you use mw-body deeper in the DOM.
24 '.mw-body-primary',
25 '.mw-body',
26
27 // If the skin has no such class, fall back to the parser output
28 '#mw-content-text',
29
30 // Should never happen... well, it could if someone is not finished writing a
31 // skin and has not yet inserted bodytext yet.
32 'body'
33 ];
34
35 for ( i = 0, l = selectors.length; i < l; i++ ) {
36 $node = $( selectors[i] );
37 if ( $node.length ) {
38 return $node.first();
39 }
40 }
41
42 // Preserve existing customized value in case it was preset
43 return util.$content;
44 }() );
45 },
46
47 /* Main body */
48
49 /**
50 * Encode the string like PHP's rawurlencode
51 *
52 * @param {string} str String to be encoded.
53 */
54 rawurlencode: function ( str ) {
55 str = String( str );
56 return encodeURIComponent( str )
57 .replace( /!/g, '%21' ).replace( /'/g, '%27' ).replace( /\(/g, '%28' )
58 .replace( /\)/g, '%29' ).replace( /\*/g, '%2A' ).replace( /~/g, '%7E' );
59 },
60
61 /**
62 * Encode page titles for use in a URL
63 *
64 * We want / and : to be included as literal characters in our title URLs
65 * as they otherwise fatally break the title.
66 *
67 * The others are decoded because we can, it's prettier and matches behaviour
68 * of `wfUrlencode` in PHP.
69 *
70 * @param {string} str String to be encoded.
71 */
72 wikiUrlencode: function ( str ) {
73 return util.rawurlencode( str )
74 .replace( /%20/g, '_' )
75 // wfUrlencode replacements
76 .replace( /%3B/g, ';' )
77 .replace( /%40/g, '@' )
78 .replace( /%24/g, '$' )
79 .replace( /%21/g, '!' )
80 .replace( /%2A/g, '*' )
81 .replace( /%28/g, '(' )
82 .replace( /%29/g, ')' )
83 .replace( /%2C/g, ',' )
84 .replace( /%2F/g, '/' )
85 .replace( /%3A/g, ':' );
86 },
87
88 /**
89 * Get the link to a page name (relative to `wgServer`),
90 *
91 * @param {string} str Page name
92 * @param {Object} [params] A mapping of query parameter names to values,
93 * e.g. `{ action: 'edit' }`
94 * @return {string} Url of the page with name of `str`
95 */
96 getUrl: function ( str, params ) {
97 var url = mw.config.get( 'wgArticlePath' ).replace(
98 '$1',
99 util.wikiUrlencode( typeof str === 'string' ? str : mw.config.get( 'wgPageName' ) )
100 );
101
102 if ( params && !$.isEmptyObject( params ) ) {
103 url += ( url.indexOf( '?' ) !== -1 ? '&' : '?' ) + $.param( params );
104 }
105
106 return url;
107 },
108
109 /**
110 * Get address to a script in the wiki root.
111 * For index.php use `mw.config.get( 'wgScript' )`.
112 *
113 * @since 1.18
114 * @param str string Name of script (eg. 'api'), defaults to 'index'
115 * @return string Address to script (eg. '/w/api.php' )
116 */
117 wikiScript: function ( str ) {
118 str = str || 'index';
119 if ( str === 'index' ) {
120 return mw.config.get( 'wgScript' );
121 } else if ( str === 'load' ) {
122 return mw.config.get( 'wgLoadScript' );
123 } else {
124 return mw.config.get( 'wgScriptPath' ) + '/' + str +
125 mw.config.get( 'wgScriptExtension' );
126 }
127 },
128
129 /**
130 * Append a new style block to the head and return the CSSStyleSheet object.
131 * Use .ownerNode to access the `<style>` element, or use mw.loader#addStyleTag.
132 * This function returns the styleSheet object for convience (due to cross-browsers
133 * difference as to where it is located).
134 *
135 * var sheet = mw.util.addCSS( '.foobar { display: none; }' );
136 * $( foo ).click( function () {
137 * // Toggle the sheet on and off
138 * sheet.disabled = !sheet.disabled;
139 * } );
140 *
141 * @param {string} text CSS to be appended
142 * @return {CSSStyleSheet} Use .ownerNode to get to the `<style>` element.
143 */
144 addCSS: function ( text ) {
145 var s = mw.loader.addStyleTag( text );
146 return s.sheet || s.styleSheet || s;
147 },
148
149 /**
150 * Grab the URL parameter value for the given parameter.
151 * Returns null if not found.
152 *
153 * @param {string} param The parameter name.
154 * @param {string} [url=document.location.href] URL to search through, defaulting to the current document's URL.
155 * @return {Mixed} Parameter value or null.
156 */
157 getParamValue: function ( param, url ) {
158 if ( url === undefined ) {
159 url = document.location.href;
160 }
161 // Get last match, stop at hash
162 var re = new RegExp( '^[^#]*[&?]' + $.escapeRE( param ) + '=([^&#]*)' ),
163 m = re.exec( url );
164 if ( m ) {
165 // Beware that decodeURIComponent is not required to understand '+'
166 // by spec, as encodeURIComponent does not produce it.
167 return decodeURIComponent( m[1].replace( /\+/g, '%20' ) );
168 }
169 return null;
170 },
171
172 /**
173 * The content wrapper of the skin (e.g. `.mw-body`).
174 *
175 * Populated on document ready by #init. To use this property,
176 * wait for `$.ready` and be sure to have a module depedendency on
177 * `mediawiki.util` and `mediawiki.page.startup` which will ensure
178 * your document ready handler fires after #init.
179 *
180 * Because of the lazy-initialised nature of this property,
181 * you're discouraged from using it.
182 *
183 * If you need just the wikipage content (not any of the
184 * extra elements output by the skin), use `$( '#mw-content-text' )`
185 * instead. Or listen to mw.hook#wikipage_content which will
186 * allow your code to re-run when the page changes (e.g. live preview
187 * or re-render after ajax save).
188 *
189 * @property {jQuery}
190 */
191 $content: null,
192
193 /**
194 * Add a link to a portlet menu on the page, such as:
195 *
196 * p-cactions (Content actions), p-personal (Personal tools),
197 * p-navigation (Navigation), p-tb (Toolbox)
198 *
199 * The first three paramters are required, the others are optional and
200 * may be null. Though providing an id and tooltip is recommended.
201 *
202 * By default the new link will be added to the end of the list. To
203 * add the link before a given existing item, pass the DOM node
204 * (e.g. `document.getElementById( 'foobar' )`) or a jQuery-selector
205 * (e.g. `'#foobar'`) for that item.
206 *
207 * mw.util.addPortletLink(
208 * 'p-tb', 'http://mediawiki.org/',
209 * 'MediaWiki.org', 't-mworg', 'Go to MediaWiki.org ', 'm', '#t-print'
210 * );
211 *
212 * @param {string} portlet ID of the target portlet ( 'p-cactions' or 'p-personal' etc.)
213 * @param {string} href Link URL
214 * @param {string} text Link text
215 * @param {string} [id] ID of the new item, should be unique and preferably have
216 * the appropriate prefix ( 'ca-', 'pt-', 'n-' or 't-' )
217 * @param {string} [tooltip] Text to show when hovering over the link, without accesskey suffix
218 * @param {string} [accesskey] Access key to activate this link (one character, try
219 * to avoid conflicts. Use `$( '[accesskey=x]' ).get()` in the console to
220 * see if 'x' is already used.
221 * @param {HTMLElement|jQuery|string} [nextnode] Element or jQuery-selector string to the item that
222 * the new item should be added before, should be another item in the same
223 * list, it will be ignored otherwise
224 *
225 * @return {HTMLElement|null} The added element (a ListItem or Anchor element,
226 * depending on the skin) or null if no element was added to the document.
227 */
228 addPortletLink: function ( portlet, href, text, id, tooltip, accesskey, nextnode ) {
229 var $item, $link, $portlet, $ul;
230
231 // Check if there's atleast 3 arguments to prevent a TypeError
232 if ( arguments.length < 3 ) {
233 return null;
234 }
235 // Setup the anchor tag
236 $link = $( '<a>' ).attr( 'href', href ).text( text );
237 if ( tooltip ) {
238 $link.attr( 'title', tooltip );
239 }
240
241 // Select the specified portlet
242 $portlet = $( '#' + portlet );
243 if ( $portlet.length === 0 ) {
244 return null;
245 }
246 // Select the first (most likely only) unordered list inside the portlet
247 $ul = $portlet.find( 'ul' ).eq( 0 );
248
249 // If it didn't have an unordered list yet, create it
250 if ( $ul.length === 0 ) {
251
252 $ul = $( '<ul>' );
253
254 // If there's no <div> inside, append it to the portlet directly
255 if ( $portlet.find( 'div:first' ).length === 0 ) {
256 $portlet.append( $ul );
257 } else {
258 // otherwise if there's a div (such as div.body or div.pBody)
259 // append the <ul> to last (most likely only) div
260 $portlet.find( 'div' ).eq( -1 ).append( $ul );
261 }
262 }
263 // Just in case..
264 if ( $ul.length === 0 ) {
265 return null;
266 }
267
268 // Unhide portlet if it was hidden before
269 $portlet.removeClass( 'emptyPortlet' );
270
271 // Wrap the anchor tag in a list item (and a span if $portlet is a Vector tab)
272 // and back up the selector to the list item
273 if ( $portlet.hasClass( 'vectorTabs' ) ) {
274 $item = $link.wrap( '<li><span></span></li>' ).parent().parent();
275 } else {
276 $item = $link.wrap( '<li></li>' ).parent();
277 }
278
279 // Implement the properties passed to the function
280 if ( id ) {
281 $item.attr( 'id', id );
282 }
283
284 if ( accesskey ) {
285 $link.attr( 'accesskey', accesskey );
286 }
287
288 if ( tooltip ) {
289 $link.attr( 'title', tooltip );
290 }
291
292 if ( nextnode ) {
293 // Case: nextnode is a DOM element (was the only option before MW 1.17, in wikibits.js)
294 // Case: nextnode is a CSS selector for jQuery
295 if ( nextnode.nodeType || typeof nextnode === 'string' ) {
296 nextnode = $ul.find( nextnode );
297 } else if ( !nextnode.jquery ) {
298 // Error: Invalid nextnode
299 nextnode = undefined;
300 }
301 if ( nextnode && ( nextnode.length !== 1 || nextnode[0].parentNode !== $ul[0] ) ) {
302 // Error: nextnode must resolve to a single node
303 // Error: nextnode must have the associated <ul> as its parent
304 nextnode = undefined;
305 }
306 }
307
308 // Case: nextnode is a jQuery-wrapped DOM element
309 if ( nextnode ) {
310 nextnode.before( $item );
311 } else {
312 // Fallback (this is the default behavior)
313 $ul.append( $item );
314 }
315
316 // Update tooltip for the access key after inserting into DOM
317 // to get a localized access key label (bug 67946).
318 $link.updateTooltipAccessKeys();
319
320 return $item[0];
321 },
322
323 /**
324 * Validate a string as representing a valid e-mail address
325 * according to HTML5 specification. Please note the specification
326 * does not validate a domain with one character.
327 *
328 * FIXME: should be moved to or replaced by a validation module.
329 *
330 * @param {string} mailtxt E-mail address to be validated.
331 * @return {boolean|null} Null if `mailtxt` was an empty string, otherwise true/false
332 * as determined by validation.
333 */
334 validateEmail: function ( mailtxt ) {
335 var rfc5322Atext, rfc1034LdhStr, html5EmailRegexp;
336
337 if ( mailtxt === '' ) {
338 return null;
339 }
340
341 // HTML5 defines a string as valid e-mail address if it matches
342 // the ABNF:
343 // 1 * ( atext / "." ) "@" ldh-str 1*( "." ldh-str )
344 // With:
345 // - atext : defined in RFC 5322 section 3.2.3
346 // - ldh-str : defined in RFC 1034 section 3.5
347 //
348 // (see STD 68 / RFC 5234 http://tools.ietf.org/html/std68)
349 // First, define the RFC 5322 'atext' which is pretty easy:
350 // atext = ALPHA / DIGIT / ; Printable US-ASCII
351 // "!" / "#" / ; characters not including
352 // "$" / "%" / ; specials. Used for atoms.
353 // "&" / "'" /
354 // "*" / "+" /
355 // "-" / "/" /
356 // "=" / "?" /
357 // "^" / "_" /
358 // "`" / "{" /
359 // "|" / "}" /
360 // "~"
361 rfc5322Atext = 'a-z0-9!#$%&\'*+\\-/=?^_`{|}~';
362
363 // Next define the RFC 1034 'ldh-str'
364 // <domain> ::= <subdomain> | " "
365 // <subdomain> ::= <label> | <subdomain> "." <label>
366 // <label> ::= <letter> [ [ <ldh-str> ] <let-dig> ]
367 // <ldh-str> ::= <let-dig-hyp> | <let-dig-hyp> <ldh-str>
368 // <let-dig-hyp> ::= <let-dig> | "-"
369 // <let-dig> ::= <letter> | <digit>
370 rfc1034LdhStr = 'a-z0-9\\-';
371
372 html5EmailRegexp = new RegExp(
373 // start of string
374 '^'
375 +
376 // User part which is liberal :p
377 '[' + rfc5322Atext + '\\.]+'
378 +
379 // 'at'
380 '@'
381 +
382 // Domain first part
383 '[' + rfc1034LdhStr + ']+'
384 +
385 // Optional second part and following are separated by a dot
386 '(?:\\.[' + rfc1034LdhStr + ']+)*'
387 +
388 // End of string
389 '$',
390 // RegExp is case insensitive
391 'i'
392 );
393 return ( mailtxt.match( html5EmailRegexp ) !== null );
394 },
395
396 /**
397 * Note: borrows from IP::isIPv4
398 *
399 * @param {string} address
400 * @param {boolean} allowBlock
401 * @return {boolean}
402 */
403 isIPv4Address: function ( address, allowBlock ) {
404 if ( typeof address !== 'string' ) {
405 return false;
406 }
407
408 var block = allowBlock ? '(?:\\/(?:3[0-2]|[12]?\\d))?' : '',
409 RE_IP_BYTE = '(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|0?[0-9]?[0-9])',
410 RE_IP_ADD = '(?:' + RE_IP_BYTE + '\\.){3}' + RE_IP_BYTE;
411
412 return address.search( new RegExp( '^' + RE_IP_ADD + block + '$' ) ) !== -1;
413 },
414
415 /**
416 * Note: borrows from IP::isIPv6
417 *
418 * @param {string} address
419 * @param {boolean} allowBlock
420 * @return {boolean}
421 */
422 isIPv6Address: function ( address, allowBlock ) {
423 if ( typeof address !== 'string' ) {
424 return false;
425 }
426
427 var block = allowBlock ? '(?:\\/(?:12[0-8]|1[01][0-9]|[1-9]?\\d))?' : '',
428 RE_IPV6_ADD =
429 '(?:' + // starts with "::" (including "::")
430 ':(?::|(?::' + '[0-9A-Fa-f]{1,4}' + '){1,7})' +
431 '|' + // ends with "::" (except "::")
432 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){0,6}::' +
433 '|' + // contains no "::"
434 '[0-9A-Fa-f]{1,4}' + '(?::' + '[0-9A-Fa-f]{1,4}' + '){7}' +
435 ')';
436
437 if ( address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1 ) {
438 return true;
439 }
440
441 RE_IPV6_ADD = // contains one "::" in the middle (single '::' check below)
442 '[0-9A-Fa-f]{1,4}' + '(?:::?' + '[0-9A-Fa-f]{1,4}' + '){1,6}';
443
444 return address.search( new RegExp( '^' + RE_IPV6_ADD + block + '$' ) ) !== -1
445 && address.search( /::/ ) !== -1 && address.search( /::.*::/ ) === -1;
446 }
447 };
448
449 /**
450 * @method wikiGetlink
451 * @inheritdoc #getUrl
452 * @deprecated since 1.23 Use #getUrl instead.
453 */
454 mw.log.deprecate( util, 'wikiGetlink', util.getUrl, 'Use mw.util.getUrl instead.' );
455
456 /**
457 * Access key prefix. Might be wrong for browsers implementing the accessKeyLabel property.
458 * @property {string} tooltipAccessKeyPrefix
459 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
460 */
461 mw.log.deprecate( util, 'tooltipAccessKeyPrefix', $.fn.updateTooltipAccessKeys.getAccessKeyPrefix(), 'Use jquery.accessKeyLabel instead.' );
462
463 /**
464 * Regex to match accesskey tooltips.
465 *
466 * Should match:
467 *
468 * - "[ctrl-option-x]"
469 * - "[alt-shift-x]"
470 * - "[ctrl-alt-x]"
471 * - "[ctrl-x]"
472 *
473 * The accesskey is matched in group $6.
474 *
475 * Will probably not work for browsers implementing the accessKeyLabel property.
476 *
477 * @property {RegExp} tooltipAccessKeyRegexp
478 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
479 */
480 mw.log.deprecate( util, 'tooltipAccessKeyRegexp', /\[(ctrl-)?(option-)?(alt-)?(shift-)?(esc-)?(.)\]$/, 'Use jquery.accessKeyLabel instead.' );
481
482 /**
483 * Add the appropriate prefix to the accesskey shown in the tooltip.
484 *
485 * If the `$nodes` parameter is given, only those nodes are updated;
486 * otherwise, depending on browser support, we update either all elements
487 * with accesskeys on the page or a bunch of elements which are likely to
488 * have them on core skins.
489 *
490 * @method updateTooltipAccessKeys
491 * @param {Array|jQuery} [$nodes] A jQuery object, or array of nodes to update.
492 * @deprecated since 1.24 Use the module jquery.accessKeyLabel instead.
493 */
494 mw.log.deprecate( util, 'updateTooltipAccessKeys', function ( $nodes ) {
495 if ( !$nodes ) {
496 if ( document.querySelectorAll ) {
497 // If we're running on a browser where we can do this efficiently,
498 // just find all elements that have accesskeys. We can't use jQuery's
499 // polyfill for the selector since looping over all elements on page
500 // load might be too slow.
501 $nodes = $( document.querySelectorAll( '[accesskey]' ) );
502 } else {
503 // Otherwise go through some elements likely to have accesskeys rather
504 // than looping over all of them. Unfortunately this will not fully
505 // work for custom skins with different HTML structures. Input, label
506 // and button should be rare enough that no optimizations are needed.
507 $nodes = $( '#column-one a, #mw-head a, #mw-panel a, #p-logo a, input, label, button' );
508 }
509 } else if ( !( $nodes instanceof $ ) ) {
510 $nodes = $( $nodes );
511 }
512
513 $nodes.updateTooltipAccessKeys();
514 }, 'Use jquery.accessKeyLabel instead.' );
515
516 /**
517 * Add a little box at the top of the screen to inform the user of
518 * something, replacing any previous message.
519 * Calling with no arguments, with an empty string or null will hide the message
520 *
521 * @method jsMessage
522 * @deprecated since 1.20 Use mw#notify
523 * @param {Mixed} message The DOM-element, jQuery object or HTML-string to be put inside the message box.
524 * to allow CSS/JS to hide different boxes. null = no class used.
525 */
526 mw.log.deprecate( util, 'jsMessage', function ( message ) {
527 if ( !arguments.length || message === '' || message === null ) {
528 return true;
529 }
530 if ( typeof message !== 'object' ) {
531 message = $.parseHTML( message );
532 }
533 mw.notify( message, { autoHide: true, tag: 'legacy' } );
534 return true;
535 }, 'Use mw.notify instead.' );
536
537 mw.util = util;
538
539 }( mediaWiki, jQuery ) );