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