Merge "(bug 37158) display personal menu on top of page tabs on Vector"
[lhc/web/wiklou.git] / skins / common / wikibits.js
1 /**
2 * MediaWiki legacy wikibits
3 */
4 ( function ( mw ) {
5
6 window.clientPC = navigator.userAgent.toLowerCase(); // Get client info
7 window.is_gecko = /gecko/.test( clientPC ) &&
8 !/khtml|spoofer|netscape\/7\.0/.test(clientPC);
9
10 window.is_safari = window.is_safari_win = window.webkit_version =
11 window.is_chrome = window.is_chrome_mac = false;
12 window.webkit_match = clientPC.match(/applewebkit\/(\d+)/);
13 if (webkit_match) {
14 window.is_safari = clientPC.indexOf('applewebkit') != -1 &&
15 clientPC.indexOf('spoofer') == -1;
16 window.is_safari_win = is_safari && clientPC.indexOf('windows') != -1;
17 window.webkit_version = parseInt(webkit_match[1]);
18 // Tests for chrome here, to avoid breaking old scripts safari left alone
19 // This is here for accesskeys
20 window.is_chrome = clientPC.indexOf('chrome') !== -1 &&
21 clientPC.indexOf('spoofer') === -1;
22 window.is_chrome_mac = is_chrome && clientPC.indexOf('mac') !== -1
23 }
24
25 // For accesskeys; note that FF3+ is included here!
26 window.is_ff2 = /firefox\/[2-9]|minefield\/3/.test( clientPC );
27 window.ff2_bugs = /firefox\/2/.test( clientPC );
28 // These aren't used here, but some custom scripts rely on them
29 window.is_ff2_win = is_ff2 && clientPC.indexOf('windows') != -1;
30 window.is_ff2_x11 = is_ff2 && clientPC.indexOf('x11') != -1;
31
32 window.is_opera = window.is_opera_preseven = window.is_opera_95 =
33 window.opera6_bugs = window.opera7_bugs = window.opera95_bugs = false;
34 if (clientPC.indexOf('opera') != -1) {
35 window.is_opera = true;
36 window.is_opera_preseven = window.opera && !document.childNodes;
37 window.is_opera_seven = window.opera && document.childNodes;
38 window.is_opera_95 = /opera\/(9\.[5-9]|[1-9][0-9])/.test( clientPC );
39 window.opera6_bugs = is_opera_preseven;
40 window.opera7_bugs = is_opera_seven && !is_opera_95;
41 window.opera95_bugs = /opera\/(9\.5)/.test( clientPC );
42 }
43 // As recommended by <http://msdn.microsoft.com/en-us/library/ms537509.aspx>,
44 // avoiding false positives from moronic extensions that append to the IE UA
45 // string (bug 23171)
46 window.ie6_bugs = false;
47 if ( /msie ([0-9]{1,}[\.0-9]{0,})/.exec( clientPC ) != null
48 && parseFloat( RegExp.$1 ) <= 6.0 ) {
49 ie6_bugs = true;
50 }
51
52 // add any onload functions in this hook (please don't hard-code any events in the xhtml source)
53 window.doneOnloadHook = undefined;
54
55 if (!window.onloadFuncts) {
56 window.onloadFuncts = [];
57 }
58
59 window.addOnloadHook = function( hookFunct ) {
60 // Allows add-on scripts to add onload functions
61 if( !doneOnloadHook ) {
62 onloadFuncts[onloadFuncts.length] = hookFunct;
63 } else {
64 hookFunct(); // bug in MSIE script loading
65 }
66 };
67
68 window.importScript = function( page ) {
69 var uri = mw.config.get( 'wgScript' ) + '?title=' +
70 mw.util.wikiUrlencode( page ) +
71 '&action=raw&ctype=text/javascript';
72 return importScriptURI( uri );
73 };
74
75 window.loadedScripts = {}; // included-scripts tracker
76 window.importScriptURI = function( url ) {
77 if ( loadedScripts[url] ) {
78 return null;
79 }
80 loadedScripts[url] = true;
81 var s = document.createElement( 'script' );
82 s.setAttribute( 'src', url );
83 s.setAttribute( 'type', 'text/javascript' );
84 document.getElementsByTagName('head')[0].appendChild( s );
85 return s;
86 };
87
88 window.importStylesheet = function( page ) {
89 return importStylesheetURI( mw.config.get( 'wgScript' ) + '?action=raw&ctype=text/css&title=' + mw.util.wikiUrlencode( page ) );
90 };
91
92 window.importStylesheetURI = function( url, media ) {
93 var l = document.createElement( 'link' );
94 l.rel = 'stylesheet';
95 l.href = url;
96 if ( media ) {
97 l.media = media;
98 }
99 document.getElementsByTagName('head')[0].appendChild( l );
100 return l;
101 };
102
103 window.appendCSS = function( text ) {
104 var s = document.createElement( 'style' );
105 s.type = 'text/css';
106 s.rel = 'stylesheet';
107 if ( s.styleSheet ) {
108 s.styleSheet.cssText = text; // IE
109 } else {
110 s.appendChild( document.createTextNode( text + '' ) ); // Safari sometimes borks on null
111 }
112 document.getElementsByTagName('head')[0].appendChild( s );
113 return s;
114 };
115
116 // Special stylesheet links for Monobook only (see bug 14717)
117 var skinpath = mw.config.get( 'stylepath' ) + '/' + mw.config.get( 'skin' );
118 if ( mw.config.get( 'skin' ) === 'monobook' ) {
119 if ( opera6_bugs ) {
120 importStylesheetURI( skinpath + '/Opera6Fixes.css' );
121 } else if ( opera7_bugs ) {
122 importStylesheetURI( skinpath + '/Opera7Fixes.css' );
123 } else if ( opera95_bugs ) {
124 importStylesheetURI( skinpath + '/Opera9Fixes.css' );
125 } else if ( ff2_bugs ) {
126 importStylesheetURI( skinpath + '/FF2Fixes.css' );
127 }
128 }
129
130 if ( mw.config.get( 'wgBreakFrames' ) ) {
131 // Un-trap us from framesets
132 if ( window.top != window ) {
133 window.top.location = window.location;
134 }
135 }
136
137 window.changeText = function( el, newText ) {
138 // Safari work around
139 if ( el.innerText ) {
140 el.innerText = newText;
141 } else if ( el.firstChild && el.firstChild.nodeValue ) {
142 el.firstChild.nodeValue = newText;
143 }
144 };
145
146 window.killEvt = function( evt ) {
147 evt = evt || window.event || window.Event; // W3C, IE, Netscape
148 if ( typeof ( evt.preventDefault ) != 'undefined' ) {
149 evt.preventDefault(); // Don't follow the link
150 evt.stopPropagation();
151 } else {
152 evt.cancelBubble = true; // IE
153 }
154 return false; // Don't follow the link (IE)
155 };
156
157 window.mwEditButtons = [];
158 window.mwCustomEditButtons = []; // eg to add in MediaWiki:Common.js
159
160 window.escapeQuotes = function( text ) {
161 var re = new RegExp( "'", "g" );
162 text = text.replace( re, "\\'" );
163 re = new RegExp( "\\n", "g" );
164 text = text.replace( re, "\\n" );
165 return escapeQuotesHTML( text );
166 };
167
168 window.escapeQuotesHTML = function( text ) {
169 var re = new RegExp( '&', "g" );
170 text = text.replace( re, "&amp;" );
171 re = new RegExp( '"', "g" );
172 text = text.replace( re, "&quot;" );
173 re = new RegExp( '<', "g" );
174 text = text.replace( re, "&lt;" );
175 re = new RegExp( '>', "g" );
176 text = text.replace( re, "&gt;" );
177 return text;
178 };
179
180 /**
181 * Set the accesskey prefix based on browser detection.
182 */
183 window.tooltipAccessKeyPrefix = 'alt-';
184 if ( is_opera ) {
185 tooltipAccessKeyPrefix = 'shift-esc-';
186 } else if ( is_chrome ) {
187 tooltipAccessKeyPrefix = is_chrome_mac ? 'ctrl-option-' : 'alt-';
188 } else if ( !is_safari_win && is_safari && webkit_version > 526 ) {
189 tooltipAccessKeyPrefix = 'ctrl-alt-';
190 } else if ( !is_safari_win && ( is_safari
191 || clientPC.indexOf('mac') != -1
192 || clientPC.indexOf('konqueror') != -1 ) ) {
193 tooltipAccessKeyPrefix = 'ctrl-';
194 } else if ( is_ff2 ) {
195 tooltipAccessKeyPrefix = 'alt-shift-';
196 }
197 window.tooltipAccessKeyRegexp = /\[(ctrl-)?(alt-)?(shift-)?(esc-)?(.)\]$/;
198
199 /**
200 * Add the appropriate prefix to the accesskey shown in the tooltip.
201 * If the nodeList parameter is given, only those nodes are updated;
202 * otherwise, all the nodes that will probably have accesskeys by
203 * default are updated.
204 *
205 * @param nodeList Array list of elements to update
206 */
207 window.updateTooltipAccessKeys = function( nodeList ) {
208 if ( !nodeList ) {
209 // Rather than scan all links on the whole page, we can just scan these
210 // containers which contain the relevant links. This is really just an
211 // optimization technique.
212 var linkContainers = [
213 'column-one', // Monobook and Modern
214 'mw-head', 'mw-panel', 'p-logo' // Vector
215 ];
216 for ( var i in linkContainers ) {
217 var linkContainer = document.getElementById( linkContainers[i] );
218 if ( linkContainer ) {
219 updateTooltipAccessKeys( linkContainer.getElementsByTagName( 'a' ) );
220 }
221 }
222 // these are rare enough that no such optimization is needed
223 updateTooltipAccessKeys( document.getElementsByTagName( 'input' ) );
224 updateTooltipAccessKeys( document.getElementsByTagName( 'label' ) );
225 return;
226 }
227
228 for ( var i = 0; i < nodeList.length; i++ ) {
229 var element = nodeList[i];
230 var tip = element.getAttribute( 'title' );
231 if ( tip && tooltipAccessKeyRegexp.exec( tip ) ) {
232 tip = tip.replace(tooltipAccessKeyRegexp,
233 '[' + tooltipAccessKeyPrefix + "$5]");
234 element.setAttribute( 'title', tip );
235 }
236 }
237 };
238
239 /**
240 * Add a link to one of the portlet menus on the page, including:
241 *
242 * p-cactions: Content actions (shown as tabs above the main content in Monobook)
243 * p-personal: Personal tools (shown at the top right of the page in Monobook)
244 * p-navigation: Navigation
245 * p-tb: Toolbox
246 *
247 * This function exists for the convenience of custom JS authors. All
248 * but the first three parameters are optional, though providing at
249 * least an id and a tooltip is recommended.
250 *
251 * By default the new link will be added to the end of the list. To
252 * add the link before a given existing item, pass the DOM node of
253 * that item (easily obtained with document.getElementById()) as the
254 * nextnode parameter; to add the link _after_ an existing item, pass
255 * the node's nextSibling instead.
256 *
257 * @param portlet String id of the target portlet ("p-cactions", "p-personal", "p-navigation" or "p-tb")
258 * @param href String link URL
259 * @param text String link text (will be automatically lowercased by CSS for p-cactions in Monobook)
260 * @param id String id of the new item, should be unique and preferably have the appropriate prefix ("ca-", "pt-", "n-" or "t-")
261 * @param tooltip String text to show when hovering over the link, without accesskey suffix
262 * @param accesskey String accesskey to activate this link (one character, try to avoid conflicts)
263 * @param nextnode Node the DOM node before which the new item should be added, should be another item in the same list
264 *
265 * @return Node -- the DOM node of the new item (an LI element) or null
266 */
267 window.addPortletLink = function( portlet, href, text, id, tooltip, accesskey, nextnode ) {
268 var root = document.getElementById( portlet );
269 if ( !root ) {
270 return null;
271 }
272 var uls = root.getElementsByTagName( 'ul' );
273 var node;
274 if ( uls.length > 0 ) {
275 node = uls[0];
276 } else {
277 node = document.createElement( 'ul' );
278 var lastElementChild = null;
279 for ( var i = 0; i < root.childNodes.length; ++i ) { /* get root.lastElementChild */
280 if ( root.childNodes[i].nodeType == 1 ) {
281 lastElementChild = root.childNodes[i];
282 }
283 }
284 if ( lastElementChild && lastElementChild.nodeName.match( /div/i ) ) {
285 /* Insert into the menu divs */
286 lastElementChild.appendChild( node );
287 } else {
288 root.appendChild( node );
289 }
290 }
291 if ( !node ) {
292 return null;
293 }
294
295 // unhide portlet if it was hidden before
296 root.className = root.className.replace( /(^| )emptyPortlet( |$)/, "$2" );
297
298 var link = document.createElement( 'a' );
299 link.appendChild( document.createTextNode( text ) );
300 link.href = href;
301
302 // Wrap in a span - make it work with vector tabs and has no effect on any other portlets
303 var span = document.createElement( 'span' );
304 span.appendChild( link );
305
306 var item = document.createElement( 'li' );
307 item.appendChild( span );
308 if ( id ) {
309 item.id = id;
310 }
311
312 if ( accesskey ) {
313 link.setAttribute( 'accesskey', accesskey );
314 tooltip += ' [' + accesskey + ']';
315 }
316 if ( tooltip ) {
317 link.setAttribute( 'title', tooltip );
318 }
319 if ( accesskey && tooltip ) {
320 updateTooltipAccessKeys( [link] );
321 }
322
323 if ( nextnode && nextnode.parentNode == node ) {
324 node.insertBefore( item, nextnode );
325 } else {
326 node.appendChild( item ); // IE compatibility (?)
327 }
328
329 return item;
330 };
331
332 window.getInnerText = function( el ) {
333 if ( typeof el == 'string' ) {
334 return el;
335 }
336 if ( typeof el == 'undefined' ) {
337 return el;
338 }
339 // Custom sort value through 'data-sort-value' attribute
340 // (no need to prepend hidden text to change sort value)
341 if ( el.nodeType && el.getAttribute( 'data-sort-value' ) !== null ) {
342 // Make sure it's a valid DOM element (.nodeType) and that the attribute is set (!null)
343 return el.getAttribute( 'data-sort-value' );
344 }
345 if ( el.textContent ) {
346 return el.textContent; // not needed but it is faster
347 }
348 if ( el.innerText ) {
349 return el.innerText; // IE doesn't have textContent
350 }
351 var str = '';
352
353 var cs = el.childNodes;
354 var l = cs.length;
355 for ( var i = 0; i < l; i++ ) {
356 switch ( cs[i].nodeType ) {
357 case 1: // ELEMENT_NODE
358 str += getInnerText( cs[i] );
359 break;
360 case 3: // TEXT_NODE
361 str += cs[i].nodeValue;
362 break;
363 }
364 }
365 return str;
366 };
367
368 window.checkboxes = undefined;
369 window.lastCheckbox = undefined;
370
371 window.setupCheckboxShiftClick = function() {
372 checkboxes = [];
373 lastCheckbox = null;
374 var inputs = document.getElementsByTagName( 'input' );
375 addCheckboxClickHandlers( inputs );
376 };
377
378 window.addCheckboxClickHandlers = function( inputs, start ) {
379 if ( !start ) {
380 start = 0;
381 }
382
383 var finish = start + 250;
384 if ( finish > inputs.length ) {
385 finish = inputs.length;
386 }
387
388 for ( var i = start; i < finish; i++ ) {
389 var cb = inputs[i];
390 if ( !cb.type || cb.type.toLowerCase() != 'checkbox' || ( ' ' + cb.className + ' ' ).indexOf( ' noshiftselect ' ) != -1 ) {
391 continue;
392 }
393 var end = checkboxes.length;
394 checkboxes[end] = cb;
395 cb.index = end;
396 addClickHandler( cb, checkboxClickHandler );
397 }
398
399 if ( finish < inputs.length ) {
400 setTimeout( function() {
401 addCheckboxClickHandlers( inputs, finish );
402 }, 200 );
403 }
404 };
405
406 window.checkboxClickHandler = function( e ) {
407 if ( typeof e == 'undefined' ) {
408 e = window.event;
409 }
410 if ( !e.shiftKey || lastCheckbox === null ) {
411 lastCheckbox = this.index;
412 return true;
413 }
414 var endState = this.checked;
415 var start, finish;
416 if ( this.index < lastCheckbox ) {
417 start = this.index + 1;
418 finish = lastCheckbox;
419 } else {
420 start = lastCheckbox;
421 finish = this.index - 1;
422 }
423 for ( var i = start; i <= finish; ++i ) {
424 checkboxes[i].checked = endState;
425 if( i > start && typeof checkboxes[i].onchange == 'function' ) {
426 checkboxes[i].onchange(); // fire triggers
427 }
428 }
429 lastCheckbox = this.index;
430 return true;
431 };
432
433
434 /*
435 Written by Jonathan Snook, http://www.snook.ca/jonathan
436 Add-ons by Robert Nyman, http://www.robertnyman.com
437 Author says "The credit comment is all it takes, no license. Go crazy with it!:-)"
438 From http://www.robertnyman.com/2005/11/07/the-ultimate-getelementsbyclassname/
439 */
440 window.getElementsByClassName = function( oElm, strTagName, oClassNames ) {
441 var arrReturnElements = [];
442 if ( typeof( oElm.getElementsByClassName ) == 'function' ) {
443 /* Use a native implementation where possible FF3, Saf3.2, Opera 9.5 */
444 var arrNativeReturn = oElm.getElementsByClassName( oClassNames );
445 if ( strTagName == '*' ) {
446 return arrNativeReturn;
447 }
448 for ( var h = 0; h < arrNativeReturn.length; h++ ) {
449 if( arrNativeReturn[h].tagName.toLowerCase() == strTagName.toLowerCase() ) {
450 arrReturnElements[arrReturnElements.length] = arrNativeReturn[h];
451 }
452 }
453 return arrReturnElements;
454 }
455 var arrElements = ( strTagName == '*' && oElm.all ) ? oElm.all : oElm.getElementsByTagName( strTagName );
456 var arrRegExpClassNames = [];
457 if( typeof oClassNames == 'object' ) {
458 for( var i = 0; i < oClassNames.length; i++ ) {
459 arrRegExpClassNames[arrRegExpClassNames.length] =
460 new RegExp("(^|\\s)" + oClassNames[i].replace(/\-/g, "\\-") + "(\\s|$)");
461 }
462 } else {
463 arrRegExpClassNames[arrRegExpClassNames.length] =
464 new RegExp("(^|\\s)" + oClassNames.replace(/\-/g, "\\-") + "(\\s|$)");
465 }
466 var oElement;
467 var bMatchesAll;
468 for( var j = 0; j < arrElements.length; j++ ) {
469 oElement = arrElements[j];
470 bMatchesAll = true;
471 for( var k = 0; k < arrRegExpClassNames.length; k++ ) {
472 if( !arrRegExpClassNames[k].test( oElement.className ) ) {
473 bMatchesAll = false;
474 break;
475 }
476 }
477 if( bMatchesAll ) {
478 arrReturnElements[arrReturnElements.length] = oElement;
479 }
480 }
481 return ( arrReturnElements );
482 };
483
484 window.redirectToFragment = function( fragment ) {
485 var match = navigator.userAgent.match(/AppleWebKit\/(\d+)/);
486 if ( match ) {
487 var webKitVersion = parseInt( match[1] );
488 if ( webKitVersion < 420 ) {
489 // Released Safari w/ WebKit 418.9.1 messes up horribly
490 // Nightlies of 420+ are ok
491 return;
492 }
493 }
494 if ( window.location.hash == '' ) {
495 window.location.hash = fragment;
496
497 // Mozilla needs to wait until after load, otherwise the window doesn't
498 // scroll. See <https://bugzilla.mozilla.org/show_bug.cgi?id=516293>.
499 // There's no obvious way to detect this programmatically, so we use
500 // version-testing. If Firefox fixes the bug, they'll jump twice, but
501 // better twice than not at all, so make the fix hit future versions as
502 // well.
503 if ( is_gecko ) {
504 addOnloadHook(function() {
505 if ( window.location.hash == fragment ) {
506 window.location.hash = fragment;
507 }
508 });
509 }
510 }
511 };
512
513 /**
514 * Add a cute little box at the top of the screen to inform the user of
515 * something, replacing any preexisting message.
516 *
517 * @deprecated since 1.17 Use the 'mediawiki.notify' module instead.
518 * @param {String|HTMLElement} message To be put inside the message box.
519 */
520 window.jsMsg = function () {
521 return mw.util.jsMessage.apply( mw.util, arguments );
522 };
523
524 /**
525 * Inject a cute little progress spinner after the specified element
526 *
527 * @param element Element to inject after
528 * @param id Identifier string (for use with removeSpinner(), below)
529 */
530 window.injectSpinner = function( element, id ) {
531 var spinner = document.createElement( 'img' );
532 spinner.id = 'mw-spinner-' + id;
533 spinner.src = mw.config.get( 'stylepath' ) + '/common/images/spinner.gif';
534 spinner.alt = spinner.title = '...';
535 if( element.nextSibling ) {
536 element.parentNode.insertBefore( spinner, element.nextSibling );
537 } else {
538 element.parentNode.appendChild( spinner );
539 }
540 };
541
542 /**
543 * Remove a progress spinner added with injectSpinner()
544 *
545 * @param id Identifier string
546 */
547 window.removeSpinner = function( id ) {
548 var spinner = document.getElementById( 'mw-spinner-' + id );
549 if( spinner ) {
550 spinner.parentNode.removeChild( spinner );
551 }
552 };
553
554 window.runOnloadHook = function() {
555 // don't run anything below this for non-dom browsers
556 if ( doneOnloadHook || !( document.getElementById && document.getElementsByTagName ) ) {
557 return;
558 }
559
560 // set this before running any hooks, since any errors below
561 // might cause the function to terminate prematurely
562 doneOnloadHook = true;
563
564 // Run any added-on functions
565 for ( var i = 0; i < onloadFuncts.length; i++ ) {
566 onloadFuncts[i]();
567 }
568 };
569
570 /**
571 * Add an event handler to an element
572 *
573 * @param element Element to add handler to
574 * @param attach String Event to attach to
575 * @param handler callable Event handler callback
576 */
577 window.addHandler = function( element, attach, handler ) {
578 if( element.addEventListener ) {
579 element.addEventListener( attach, handler, false );
580 } else if( element.attachEvent ) {
581 element.attachEvent( 'on' + attach, handler );
582 }
583 };
584
585 window.hookEvent = function( hookName, hookFunct ) {
586 addHandler( window, hookName, hookFunct );
587 };
588
589 /**
590 * Add a click event handler to an element
591 *
592 * @param element Element to add handler to
593 * @param handler callable Event handler callback
594 */
595 window.addClickHandler = function( element, handler ) {
596 addHandler( element, 'click', handler );
597 };
598
599 /**
600 * Removes an event handler from an element
601 *
602 * @param element Element to remove handler from
603 * @param remove String Event to remove
604 * @param handler callable Event handler callback to remove
605 */
606 window.removeHandler = function( element, remove, handler ) {
607 if( window.removeEventListener ) {
608 element.removeEventListener( remove, handler, false );
609 } else if( window.detachEvent ) {
610 element.detachEvent( 'on' + remove, handler );
611 }
612 };
613 // note: all skins should call runOnloadHook() at the end of html output,
614 // so the below should be redundant. It's there just in case.
615 hookEvent( 'load', runOnloadHook );
616
617 if ( ie6_bugs ) {
618 importScriptURI( mw.config.get( 'stylepath' ) + '/common/IEFixes.js' );
619 }
620
621 }( mediaWiki ) );