1 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
2 // 2007, Petr Baudis <pasky@suse.cz>
3 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
6 * @fileOverview Generic JavaScript code (helper functions)
7 * @license GPLv2 or later
11 /* ............................................................ */
12 /* unquoting/unescaping filenames */
17 var escCodeRe
= /\\([^0-7]|[0-7]{1,3})/g;
18 var octEscRe
= /^[0-7]{1,3}$/;
19 var maybeQuotedRe
= /^\"(.*)\"$/;
23 * unquote maybe C-quoted filename (as used by git, i.e. it is
24 * in double quotes '"' if there is any escape character used)
25 * e.g. 'aa' -> 'aa', '"a\ta"' -> 'a a'
27 * @param {String} str: git-quoted string
28 * @returns {String} Unquoted and unescaped string
30 * @globals escCodeRe, octEscRe, maybeQuotedRe
32 function unquote(str
) {
35 // character escape codes, aka escape sequences (from C)
36 // replacements are to some extent JavaScript specific
37 t: "\t", // tab (HT, TAB)
38 n: "\n", // newline (NL)
39 r: "\r", // return (CR)
40 f: "\f", // form feed (FF)
41 b: "\b", // backspace (BS)
42 a: "\x07", // alarm (bell) (BEL)
43 e: "\x1B", // escape (ESC)
44 v: "\v" // vertical tab (VT)
47 if (seq
.search(octEscRe
) !== -1) {
48 // octal char sequence
49 return String
.fromCharCode(parseInt(seq
, 8));
50 } else if (seq
in es
) {
51 // C escape sequence, aka character escape code
54 // quoted ordinary character
58 var match
= str
.match(maybeQuotedRe
);
61 // perhaps str = eval('"'+str+'"'); would be enough?
62 str
= str
.replace(escCodeRe
,
63 function (substr
, p1
, offset
, s
) { return unq(p1
); });
68 /* end of common-lib.js */
69 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
70 // 2007, Petr Baudis <pasky@suse.cz>
71 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
74 * @fileOverview Detect if JavaScript is enabled, and pass it to server-side
75 * @license GPLv2 or later
79 /* ============================================================ */
80 /* Manipulating links */
83 * used to check if link has 'js' query parameter already (at end),
84 * and other reasons to not add 'js=1' param at the end of link
87 var jsExceptionsRe
= /[;?]js=[01](#.*)?$/;
90 * Add '?js=1' or ';js=1' to the end of every link in the document
91 * that doesn't have 'js' query parameter set already.
93 * Links with 'js=1' lead to JavaScript version of given action, if it
94 * exists (currently there is only 'blame_incremental' for 'blame')
96 * To be used as `window.onload` handler
98 * @globals jsExceptionsRe
100 function fixLinks() {
101 var allLinks
= document
.getElementsByTagName("a") || document
.links
;
102 for (var i
= 0, len
= allLinks
.length
; i
< len
; i
++) {
103 var link
= allLinks
[i
];
104 if (!jsExceptionsRe
.test(link
)) {
105 link
.href
= link
.href
.replace(/(#|$)/,
106 (link
.href
.indexOf('?') === -1 ? '?' : ';') + 'js=1$1');
111 /* end of javascript-detection.js */
112 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
113 // 2007, Petr Baudis <pasky@suse.cz>
114 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
117 * @fileOverview JavaScript side of Ajax-y 'blame_incremental' view in gitweb
118 * @license GPLv2 or later
121 /* ============================================================ */
123 * This code uses DOM methods instead of (nonstandard) innerHTML
126 * innerHTML is non-standard IE extension, though supported by most
127 * browsers; however Firefox up to version 1.5 didn't implement it in
128 * a strict mode (application/xml+xhtml mimetype).
130 * Also my simple benchmarks show that using elem.firstChild.data =
131 * 'content' is slightly faster than elem.innerHTML = 'content'. It
132 * is however more fragile (text element fragment must exists), and
133 * less feature-rich (we cannot add HTML).
135 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
136 * equivalent using DOM 2 Core is usually shown in comments.
140 /* ............................................................ */
141 /* utility/helper functions (and variables) */
143 var projectUrl
; // partial query + separator ('?' or ';')
145 // 'commits' is an associative map. It maps SHA1s to Commit objects.
149 * constructor for Commit objects, used in 'blame'
150 * @class Represents a blamed commit
151 * @param {String} sha1: SHA-1 identifier of a commit
153 function Commit(sha1
) {
154 if (this instanceof Commit
) {
156 this.nprevious
= 0; /* number of 'previous', effective parents */
158 return new Commit(sha1
);
162 /* ............................................................ */
163 /* progress info, timing, error reporting */
166 var totalLines
= '???';
167 var div_progress_bar
;
168 var div_progress_info
;
171 * Detects how many lines does a blamed file have,
172 * This information is used in progress info
174 * @returns {Number|String} Number of lines in file, or string '...'
176 function countLines() {
178 document
.getElementById('blame_table') ||
179 document
.getElementsByTagName('table')[0];
182 return table
.getElementsByTagName('tr').length
- 1; // for header
189 * update progress info and length (width) of progress bar
191 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
193 function updateProgressInfo() {
194 if (!div_progress_info
) {
195 div_progress_info
= document
.getElementById('progress_info');
197 if (!div_progress_bar
) {
198 div_progress_bar
= document
.getElementById('progress_bar');
200 if (!div_progress_info
&& !div_progress_bar
) {
204 var percentage
= Math
.floor(100.0*blamedLines
/totalLines
);
206 if (div_progress_info
) {
207 div_progress_info
.firstChild
.data
= blamedLines
+ ' / ' + totalLines
+
208 ' (' + (''+percentage
).padStart(3, '\u00A0') + '%)';
211 if (div_progress_bar
) {
212 //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
213 div_progress_bar
.style
.width
= percentage
+ '%';
218 var t_interval_server
= '';
219 var cmds_server
= '';
223 * write how much it took to generate data, and to run script
225 * @globals t0, t_interval_server, cmds_server
227 function writeTimeInterval() {
228 var info_time
= document
.getElementById('generating_time');
229 if (!info_time
|| !t_interval_server
) {
233 info_time
.firstChild
.data
+= ' + (' +
234 t_interval_server
+ ' sec server blame_data / ' +
235 (t1
.getTime() - t0
.getTime())/1000 + ' sec client JavaScript)';
237 var info_cmds
= document
.getElementById('generating_cmd');
238 if (!info_time
|| !cmds_server
) {
241 info_cmds
.firstChild
.data
+= ' + ' + cmds_server
;
245 * show an error message alert to user within page (in progress info area)
246 * @param {String} str: plain text error message (no HTML)
248 * @globals div_progress_info
250 function errorInfo(str
) {
251 if (!div_progress_info
) {
252 div_progress_info
= document
.getElementById('progress_info');
254 if (div_progress_info
) {
255 div_progress_info
.className
= 'error';
256 div_progress_info
.firstChild
.data
= str
;
260 /* ............................................................ */
261 /* coloring rows during blame_data (git blame --incremental) run */
264 * used to extract N from 'colorN', where N is a number,
267 var colorRe
= /\bcolor([0-9]*)\b/;
270 * return N if <tr class="colorN">, otherwise return null
271 * (some browsers require CSS class names to begin with letter)
273 * @param {HTMLElement} tr: table row element to check
274 * @param {String} tr.className: 'class' attribute of tr element
275 * @returns {Number|null} N if tr.className == 'colorN', otherwise null
279 function getColorNo(tr
) {
283 var className
= tr
.className
;
285 var match
= colorRe
.exec(className
);
287 return parseInt(match
[1], 10);
293 var colorsFreq
= [0, 0, 0];
295 * return one of given possible colors (currently least used one)
296 * example: chooseColorNoFrom(2, 3) returns 2 or 3
298 * @param {Number[]} arguments: one or more numbers
299 * assumes that 1 <= arguments[i] <= colorsFreq.length
300 * @returns {Number} Least used color number from arguments
301 * @globals colorsFreq
303 function chooseColorNoFrom() {
304 // choose the color which is least used
305 var colorNo
= arguments
[0];
306 for (var i
= 1; i
< arguments
.length
; i
++) {
307 if (colorsFreq
[arguments
[i
]-1] < colorsFreq
[colorNo
-1]) {
308 colorNo
= arguments
[i
];
311 colorsFreq
[colorNo
-1]++;
316 * given two neighbor <tr> elements, find color which would be different
317 * from color of both of neighbors; used to 3-color blame table
319 * @param {HTMLElement} tr_prev
320 * @param {HTMLElement} tr_next
321 * @returns {Number} color number N such that
322 * colorN != tr_prev.className && colorN != tr_next.className
324 function findColorNo(tr_prev
, tr_next
) {
325 var color_prev
= getColorNo(tr_prev
);
326 var color_next
= getColorNo(tr_next
);
329 // neither of neighbors has color set
330 // THEN we can use any of 3 possible colors
331 if (!color_prev
&& !color_next
) {
332 return chooseColorNoFrom(1,2,3);
335 // either both neighbors have the same color,
336 // or only one of neighbors have color set
337 // THEN we can use any color except given
339 if (color_prev
=== color_next
) {
340 color
= color_prev
; // = color_next;
341 } else if (!color_prev
) {
343 } else if (!color_next
) {
347 return chooseColorNoFrom((color
% 3) + 1, ((color
+1) % 3) + 1);
350 // neighbors have different colors
351 // THEN there is only one color left
352 return (3 - ((color_prev
+ color_next
) % 3));
355 /* ............................................................ */
356 /* coloring rows like 'blame' after 'blame_data' finishes */
359 * returns true if given row element (tr) is first in commit group
360 * to be used only after 'blame_data' finishes (after processing)
362 * @param {HTMLElement} tr: table row
363 * @returns {Boolean} true if TR is first in commit group
365 function isStartOfGroup(tr
) {
366 return tr
.firstChild
.className
=== 'sha1';
370 * change colors to use zebra coloring (2 colors) instead of 3 colors
371 * concatenate neighbor commit groups belonging to the same commit
375 function fixColorsAndGroups() {
376 var colorClasses
= ['light', 'dark'];
381 document
.getElementById('blame_table') ||
382 document
.getElementsByTagName('table')[0];
384 while ((tr
= document
.getElementById('l'+linenum
))) {
385 // index origin is 0, which is table header; start from 1
386 //while ((tr = table.rows[linenum])) { // <- it is slower
387 if (isStartOfGroup(tr
, linenum
, document
)) {
389 prev_group
.firstChild
.firstChild
.href
===
390 tr
.firstChild
.firstChild
.href
) {
391 // we have to concatenate groups
392 var prev_rows
= prev_group
.firstChild
.rowSpan
|| 1;
393 var curr_rows
= tr
.firstChild
.rowSpan
|| 1;
394 prev_group
.firstChild
.rowSpan
= prev_rows
+ curr_rows
;
395 //tr.removeChild(tr.firstChild);
396 tr
.deleteCell(0); // DOM2 HTML way
398 colorClass
= (colorClass
+ 1) % 2;
402 var tr_class
= tr
.className
;
403 tr
.className
= tr_class
.replace(colorRe
, colorClasses
[colorClass
]);
409 /* ============================================================ */
410 /* main part: parsing response */
413 * Function called for each blame entry, as soon as it finishes.
414 * It updates page via DOM manipulation, adding sha1 info, etc.
416 * @param {Commit} commit: blamed commit
417 * @param {Object} group: object representing group of lines,
418 * which blame the same commit (blame entry)
420 * @globals blamedLines
422 function handleLine(commit
, group
) {
424 This is the structure of the HTML fragment we are working
427 <tr id="l123" class="">
428 <td class="sha1" title=""><a href=""> </a></td>
429 <td class="linenr"><a class="linenr" href="">123</a></td>
430 <td class="pre"># times (my ext3 doesn't).</td>
434 var resline
= group
.resline
;
436 // format date and time string only once per commit
438 /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
439 commit
.info
= commit
.author
+ ', ' +
440 formatDateISOLocal(commit
.authorTime
, commit
.authorTimezone
);
443 // color depends on group of lines, not only on blamed commit
444 var colorNo
= findColorNo(
445 document
.getElementById('l'+(resline
-1)),
446 document
.getElementById('l'+(resline
+group
.numlines
))
449 // loop over lines in commit group
450 for (var i
= 0; i
< group
.numlines
; i
++, resline
++) {
451 var tr
= document
.getElementById('l'+resline
);
456 <tr id="l123" class="">
457 <td class="sha1" title=""><a href=""> </a></td>
458 <td class="linenr"><a class="linenr" href="">123</a></td>
459 <td class="pre"># times (my ext3 doesn't).</td>
462 var td_sha1
= tr
.firstChild
;
463 var a_sha1
= td_sha1
.firstChild
;
464 var a_linenr
= td_sha1
.nextSibling
.firstChild
;
466 /* <tr id="l123" class=""> */
468 if (colorNo
!== null) {
469 tr_class
= 'color'+colorNo
;
471 if (commit
.boundary
) {
472 tr_class
+= ' boundary';
474 if (commit
.nprevious
=== 0) {
475 tr_class
+= ' no-previous';
476 } else if (commit
.nprevious
> 1) {
477 tr_class
+= ' multiple-previous';
479 tr
.className
= tr_class
;
481 /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
483 td_sha1
.title
= commit
.info
;
484 td_sha1
.rowSpan
= group
.numlines
;
486 a_sha1
.href
= projectUrl
+ 'a=commit;h=' + commit
.sha1
;
487 if (a_sha1
.firstChild
) {
488 a_sha1
.firstChild
.data
= commit
.sha1
.substr(0, 8);
491 document
.createTextNode(commit
.sha1
.substr(0, 8)));
493 if (group
.numlines
>= 2) {
494 var fragment
= document
.createDocumentFragment();
495 var br
= document
.createElement("br");
496 var match
= commit
.author
.match(/\b([A-Z])\B/g);
498 var text
= document
.createTextNode(
502 var elem
= fragment
|| td_sha1
;
503 elem
.appendChild(br
);
504 elem
.appendChild(text
);
506 td_sha1
.appendChild(fragment
);
511 //tr.removeChild(td_sha1); // DOM2 Core way
512 tr
.deleteCell(0); // DOM2 HTML way
515 /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
517 ('previous' in commit
? commit
.previous : commit
.sha1
);
518 var linenr_filename
=
519 ('file_parent' in commit
? commit
.file_parent : commit
.filename
);
520 a_linenr
.href
= projectUrl
+ 'a=blame_incremental' +
521 ';hb=' + linenr_commit
+
522 ';f=' + encodeURIComponent(linenr_filename
) +
523 '#l' + (group
.srcline
+ i
);
527 //updateProgressInfo();
531 // ----------------------------------------------------------------------
536 var sha1Re
= /^([0-9a
-f
]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
537 var infoRe
= /^([a
-z
-]+) ?(.*)/;
538 var endRe
= /^END
?([^ ]*) ?(.*)/;
541 var curCommit
= new Commit();
545 * Parse output from 'git blame --incremental [...]', received via
546 * XMLHttpRequest from server (blamedataUrl), and call handleLine
547 * (which updates page) as soon as blame entry is completed.
549 * @param {String[]} lines: new complete lines from blamedata server
551 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
552 * @globals sha1Re, infoRe, endRe
554 function processBlameLines(lines
) {
557 for (var i
= 0, len
= lines
.length
; i
< len
; i
++) {
559 if ((match
= sha1Re
.exec(lines
[i
]))) {
561 var srcline
= parseInt(match
[2], 10);
562 var resline
= parseInt(match
[3], 10);
563 var numlines
= parseInt(match
[4], 10);
565 var c
= commits
[sha1
];
567 c
= new Commit(sha1
);
572 curGroup
.srcline
= srcline
;
573 curGroup
.resline
= resline
;
574 curGroup
.numlines
= numlines
;
576 } else if ((match
= infoRe
.exec(lines
[i
]))) {
581 curCommit
.filename
= unquote(data
);
582 // 'filename' information terminates the entry
583 handleLine(curCommit
, curGroup
);
584 updateProgressInfo();
587 curCommit
.author
= data
;
590 curCommit
.authorTime
= parseInt(data
, 10);
593 curCommit
.authorTimezone
= data
;
596 curCommit
.nprevious
++;
597 // store only first 'previous' header
598 if (!('previous' in curCommit
)) {
599 var parts
= data
.split(' ', 2);
600 curCommit
.previous
= parts
[0];
601 curCommit
.file_parent
= unquote(parts
[1]);
605 curCommit
.boundary
= true;
609 } else if ((match
= endRe
.exec(lines
[i
]))) {
610 t_interval_server
= match
[1];
611 cmds_server
= match
[2];
613 } else if (lines
[i
] !== '') {
622 * Process new data and return pointer to end of processed part
624 * @param {String} unprocessed: new data (from nextReadPos)
625 * @param {Number} nextReadPos: end of last processed data
626 * @return {Number} end of processed data (new value for nextReadPos)
628 function processData(unprocessed
, nextReadPos
) {
629 var lastLineEnd
= unprocessed
.lastIndexOf('\n');
630 if (lastLineEnd
!== -1) {
631 var lines
= unprocessed
.substring(0, lastLineEnd
).split('\n');
632 nextReadPos
+= lastLineEnd
+ 1 /* 1 == '\n'.length */;
634 processBlameLines(lines
);
641 * Handle XMLHttpRequest errors
643 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
644 * @param {Number} [xhr.pollTimer] ID of the timeout to clear
648 function handleError(xhr
) {
649 errorInfo('Server error: ' +
650 xhr
.status
+ ' - ' + (xhr
.statusText
|| 'Error contacting server'));
652 if (typeof xhr
.pollTimer
=== "number") {
653 clearTimeout(xhr
.pollTimer
);
654 delete xhr
.pollTimer
;
656 commits
= {}; // free memory
660 * Called after XMLHttpRequest finishes (loads)
662 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
663 * @param {Number} [xhr.pollTimer] ID of the timeout to clear
667 function responseLoaded(xhr
) {
668 if (typeof xhr
.pollTimer
=== "number") {
669 clearTimeout(xhr
.pollTimer
);
670 delete xhr
.pollTimer
;
673 fixColorsAndGroups();
675 commits
= {}; // free memory
679 * handler for XMLHttpRequest onreadystatechange event
682 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
683 * @param {Number} xhr.prevDataLength: previous value of xhr.responseText.length
684 * @param {Number} xhr.nextReadPos: start of unread part of xhr.responseText
685 * @param {Number} [xhr.pollTimer] ID of the timeout (to reset or cancel)
686 * @param {Boolean} fromTimer: if handler was called from timer
688 function handleResponse(xhr
, fromTimer
) {
693 * Value Constant (W3C) Description
694 * -------------------------------------------------------------------
695 * 0 UNSENT open() has not been called yet.
696 * 1 OPENED send() has not been called yet.
697 * 2 HEADERS_RECEIVED send() has been called, and headers
698 * and status are available.
699 * 3 LOADING Downloading; responseText holds partial data.
700 * 4 DONE The operation is complete.
703 if (xhr
.readyState
!== 4 && xhr
.readyState
!== 3) {
707 // the server returned error
708 // try ... catch block is to work around bug in IE8
710 if (xhr
.readyState
=== 3 && xhr
.status
!== 200) {
716 if (xhr
.readyState
=== 4 && xhr
.status
!== 200) {
721 // In konqueror xhr.responseText is sometimes null here...
722 if (xhr
.responseText
=== null) {
727 // extract new whole (complete) lines, and process them
728 if (xhr
.prevDataLength
!== xhr
.responseText
.length
) {
729 xhr
.prevDataLength
= xhr
.responseText
.length
;
730 var unprocessed
= xhr
.responseText
.substring(xhr
.nextReadPos
);
731 xhr
.nextReadPos
= processData(unprocessed
, xhr
.nextReadPos
);
734 // did we finish work?
735 if (xhr
.readyState
=== 4) {
740 // if we get from timer, we have to restart it
741 // otherwise onreadystatechange gives us partial response, timer not needed
743 setTimeout(function () {
744 handleResponse(xhr
, true);
747 } else if (typeof xhr
.pollTimer
=== "number") {
748 clearTimeout(xhr
.pollTimer
);
749 delete xhr
.pollTimer
;
753 // ============================================================
754 // ------------------------------------------------------------
757 * Incrementally update line data in blame_incremental view in gitweb.
759 * @param {String} blamedataUrl: URL to server script generating blame data.
760 * @param {String} bUrl: partial URL to project, used to generate links.
762 * Called from 'blame_incremental' view after loading table with
763 * file contents, a base for blame view.
765 * @globals t0, projectUrl, div_progress_bar, totalLines
767 function startBlame(blamedataUrl
, bUrl
) {
769 var xhr
= new XMLHttpRequest();
771 errorInfo('ERROR: XMLHttpRequest not supported');
776 projectUrl
= bUrl
+ (bUrl
.indexOf('?') === -1 ? '?' : ';');
777 if ((div_progress_bar
= document
.getElementById('progress_bar'))) {
778 //div_progress_bar.setAttribute('style', 'width: 100%;');
779 div_progress_bar
.style
.cssText
= 'width: 100%;';
781 totalLines
= countLines();
782 updateProgressInfo();
784 /* add extra properties to xhr object to help processing response */
785 xhr
.prevDataLength
= -1; // used to detect if we have new data
786 xhr
.nextReadPos
= 0; // where unread part of response starts
788 xhr
.onreadystatechange = function () {
789 handleResponse(xhr
, false);
792 xhr
.open('GET', blamedataUrl
);
793 xhr
.setRequestHeader('Accept', 'text/plain');
796 // not all browsers call onreadystatechange event on each server flush
797 // poll response using timer every second to handle this issue
798 xhr
.pollTimer
= setTimeout(function () {
799 handleResponse(xhr
, true);
803 /* end of blame_incremental.js */