1 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
2 // 2007, Petr Baudis <pasky@suse.cz>
3 // 2008-2009, Jakub Narebski <jnareb@gmail.com>
6 * @fileOverview JavaScript code for gitweb (git web interface).
7 * @license GPLv2 or later
11 * This code uses DOM methods instead of (nonstandard) innerHTML
14 * innerHTML is non-standard IE extension, though supported by most
15 * browsers; however Firefox up to version 1.5 didn't implement it in
16 * a strict mode (application/xml+xhtml mimetype).
18 * Also my simple benchmarks show that using elem.firstChild.data =
19 * 'content' is slightly faster than elem.innerHTML = 'content'. It
20 * is however more fragile (text element fragment must exists), and
21 * less feature-rich (we cannot add HTML).
23 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
24 * equivalent using DOM 2 Core is usually shown in comments.
28 /* ============================================================ */
29 /* generic utility functions */
33 * pad number N with nonbreakable spaces on the left, to WIDTH characters
34 * example: padLeftStr(12, 3, ' ') == ' 12'
35 * (' ' is nonbreakable space)
37 * @param {Number|String} input: number to pad
38 * @param {Number} width: visible width of output
39 * @param {String} str: string to prefix to string, e.g. ' '
40 * @returns {String} INPUT prefixed with (WIDTH - INPUT.length) x STR
42 function padLeftStr(input, width, str) {
45 width -= input.toString().length;
50 return prefix + input;
54 * Pad INPUT on the left to SIZE width, using given padding character CH,
55 * for example padLeft('a', 3, '_') is '__a'.
57 * @param {String} input: input value converted to string.
58 * @param {Number} width: desired length of output.
59 * @param {String} ch: single character to prefix to string.
61 * @returns {String} Modified string, at least SIZE length.
63 function padLeft(input, width, ch) {
65 while (s.length < width) {
72 * Create XMLHttpRequest object in cross-browser way
73 * @returns XMLHttpRequest object, or null
75 function createRequestObject() {
77 return new XMLHttpRequest();
80 return window.createRequest();
83 return new ActiveXObject("Msxml2.XMLHTTP");
86 return new ActiveXObject("Microsoft.XMLHTTP");
92 /* ============================================================ */
93 /* utility/helper functions (and variables) */
95 var xhr; // XMLHttpRequest object
96 var projectUrl; // partial query + separator ('?' or ';')
98 // 'commits' is an associative map. It maps SHA1s to Commit objects.
102 * constructor for Commit objects, used in 'blame'
103 * @class Represents a blamed commit
104 * @param {String} sha1: SHA-1 identifier of a commit
106 function Commit(sha1) {
107 if (this instanceof Commit) {
109 this.nprevious = 0; /* number of 'previous', effective parents */
111 return new Commit(sha1);
115 /* ............................................................ */
116 /* progress info, timing, error reporting */
119 var totalLines = '???';
120 var div_progress_bar;
121 var div_progress_info;
124 * Detects how many lines does a blamed file have,
125 * This information is used in progress info
127 * @returns {Number|String} Number of lines in file, or string '...'
129 function countLines() {
131 document.getElementById('blame_table') ||
132 document.getElementsByTagName('table')[0];
135 return table.getElementsByTagName('tr').length - 1; // for header
142 * update progress info and length (width) of progress bar
144 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
146 function updateProgressInfo() {
147 if (!div_progress_info) {
148 div_progress_info = document.getElementById('progress_info');
150 if (!div_progress_bar) {
151 div_progress_bar = document.getElementById('progress_bar');
153 if (!div_progress_info && !div_progress_bar) {
157 var percentage = Math.floor(100.0*blamedLines/totalLines);
159 if (div_progress_info) {
160 div_progress_info.firstChild.data = blamedLines + ' / ' + totalLines +
161 ' (' + padLeftStr(percentage, 3, ' ') + '%)';
164 if (div_progress_bar) {
165 //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
166 div_progress_bar.style.width = percentage + '%';
171 var t_interval_server = '';
172 var cmds_server = '';
176 * write how much it took to generate data, and to run script
178 * @globals t0, t_interval_server, cmds_server
180 function writeTimeInterval() {
181 var info_time = document.getElementById('generating_time');
182 if (!info_time || !t_interval_server) {
186 info_time.firstChild.data += ' + (' +
187 t_interval_server + ' sec server blame_data / ' +
188 (t1.getTime() - t0.getTime())/1000 + ' sec client JavaScript)';
190 var info_cmds = document.getElementById('generating_cmd');
191 if (!info_time || !cmds_server) {
194 info_cmds.firstChild.data += ' + ' + cmds_server;
198 * show an error message alert to user within page (in prohress info area)
199 * @param {String} str: plain text error message (no HTML)
201 * @globals div_progress_info
203 function errorInfo(str) {
204 if (!div_progress_info) {
205 div_progress_info = document.getElementById('progress_info');
207 if (div_progress_info) {
208 div_progress_info.className = 'error';
209 div_progress_info.firstChild.data = str;
213 /* ............................................................ */
214 /* coloring rows during blame_data (git blame --incremental) run */
217 * used to extract N from 'colorN', where N is a number,
220 var colorRe = /\bcolor([0-9]*)\b/;
223 * return N if <tr class="colorN">, otherwise return null
224 * (some browsers require CSS class names to begin with letter)
226 * @param {HTMLElement} tr: table row element to check
227 * @param {String} tr.className: 'class' attribute of tr element
228 * @returns {Number|null} N if tr.className == 'colorN', otherwise null
232 function getColorNo(tr) {
236 var className = tr.className;
238 var match = colorRe.exec(className);
240 return parseInt(match[1], 10);
246 var colorsFreq = [0, 0, 0];
248 * return one of given possible colors (curently least used one)
249 * example: chooseColorNoFrom(2, 3) returns 2 or 3
251 * @param {Number[]} arguments: one or more numbers
252 * assumes that 1 <= arguments[i] <= colorsFreq.length
253 * @returns {Number} Least used color number from arguments
254 * @globals colorsFreq
256 function chooseColorNoFrom() {
257 // choose the color which is least used
258 var colorNo = arguments[0];
259 for (var i = 1; i < arguments.length; i++) {
260 if (colorsFreq[arguments[i]-1] < colorsFreq[colorNo-1]) {
261 colorNo = arguments[i];
264 colorsFreq[colorNo-1]++;
269 * given two neigbour <tr> elements, find color which would be different
270 * from color of both of neighbours; used to 3-color blame table
272 * @param {HTMLElement} tr_prev
273 * @param {HTMLElement} tr_next
274 * @returns {Number} color number N such that
275 * colorN != tr_prev.className && colorN != tr_next.className
277 function findColorNo(tr_prev, tr_next) {
278 var color_prev = getColorNo(tr_prev);
279 var color_next = getColorNo(tr_next);
282 // neither of neighbours has color set
283 // THEN we can use any of 3 possible colors
284 if (!color_prev && !color_next) {
285 return chooseColorNoFrom(1,2,3);
288 // either both neighbours have the same color,
289 // or only one of neighbours have color set
290 // THEN we can use any color except given
292 if (color_prev === color_next) {
293 color = color_prev; // = color_next;
294 } else if (!color_prev) {
296 } else if (!color_next) {
300 return chooseColorNoFrom((color % 3) + 1, ((color+1) % 3) + 1);
303 // neighbours have different colors
304 // THEN there is only one color left
305 return (3 - ((color_prev + color_next) % 3));
308 /* ............................................................ */
309 /* coloring rows like 'blame' after 'blame_data' finishes */
312 * returns true if given row element (tr) is first in commit group
313 * to be used only after 'blame_data' finishes (after processing)
315 * @param {HTMLElement} tr: table row
316 * @returns {Boolean} true if TR is first in commit group
318 function isStartOfGroup(tr) {
319 return tr.firstChild.className === 'sha1';
323 * change colors to use zebra coloring (2 colors) instead of 3 colors
324 * concatenate neighbour commit groups belonging to the same commit
328 function fixColorsAndGroups() {
329 var colorClasses = ['light', 'dark'];
334 document.getElementById('blame_table') ||
335 document.getElementsByTagName('table')[0];
337 while ((tr = document.getElementById('l'+linenum))) {
338 // index origin is 0, which is table header; start from 1
339 //while ((tr = table.rows[linenum])) { // <- it is slower
340 if (isStartOfGroup(tr, linenum, document)) {
342 prev_group.firstChild.firstChild.href ===
343 tr.firstChild.firstChild.href) {
344 // we have to concatenate groups
345 var prev_rows = prev_group.firstChild.rowSpan || 1;
346 var curr_rows = tr.firstChild.rowSpan || 1;
347 prev_group.firstChild.rowSpan = prev_rows + curr_rows;
348 //tr.removeChild(tr.firstChild);
349 tr.deleteCell(0); // DOM2 HTML way
351 colorClass = (colorClass + 1) % 2;
355 var tr_class = tr.className;
356 tr.className = tr_class.replace(colorRe, colorClasses[colorClass]);
361 /* ............................................................ */
365 * used to extract hours and minutes from timezone info, e.g '-0900'
368 var tzRe = /^([+-][0-9][0-9])([0-9][0-9])$/;
371 * return date in local time formatted in iso-8601 like format
372 * 'yyyy-mm-dd HH:MM:SS +/-ZZZZ' e.g. '2005-08-07 21:49:46 +0200'
374 * @param {Number} epoch: seconds since '00:00:00 1970-01-01 UTC'
375 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
376 * @returns {String} date in local time in iso-8601 like format
380 function formatDateISOLocal(epoch, timezoneInfo) {
381 var match = tzRe.exec(timezoneInfo);
382 // date corrected by timezone
383 var localDate = new Date(1000 * (epoch +
384 (parseInt(match[1],10)*3600 + parseInt(match[2],10)*60)));
385 var localDateStr = // e.g. '2005-08-07'
386 localDate.getUTCFullYear() + '-' +
387 padLeft(localDate.getUTCMonth()+1, 2, '0') + '-' +
388 padLeft(localDate.getUTCDate(), 2, '0');
389 var localTimeStr = // e.g. '21:49:46'
390 padLeft(localDate.getUTCHours(), 2, '0') + ':' +
391 padLeft(localDate.getUTCMinutes(), 2, '0') + ':' +
392 padLeft(localDate.getUTCSeconds(), 2, '0');
394 return localDateStr + ' ' + localTimeStr + ' ' + timezoneInfo;
397 /* ............................................................ */
398 /* unquoting/unescaping filenames */
403 var escCodeRe = /\\([^0-7]|[0-7]{1,3})/g;
404 var octEscRe = /^[0-7]{1,3}$/;
405 var maybeQuotedRe = /^\"(.*)\"$/;
409 * unquote maybe git-quoted filename
410 * e.g. 'aa' -> 'aa', '"a\ta"' -> 'a a'
412 * @param {String} str: git-quoted string
413 * @returns {String} Unquoted and unescaped string
415 * @globals escCodeRe, octEscRe, maybeQuotedRe
417 function unquote(str) {
420 // character escape codes, aka escape sequences (from C)
421 // replacements are to some extent JavaScript specific
422 t: "\t", // tab (HT, TAB)
423 n: "\n", // newline (NL)
424 r: "\r", // return (CR)
425 f: "\f", // form feed (FF)
426 b: "\b", // backspace (BS)
427 a: "\x07", // alarm (bell) (BEL)
428 e: "\x1B", // escape (ESC)
429 v: "\v" // vertical tab (VT)
432 if (seq.search(octEscRe) !== -1) {
433 // octal char sequence
434 return String.fromCharCode(parseInt(seq, 8));
435 } else if (seq in es) {
436 // C escape sequence, aka character escape code
439 // quoted ordinary character
443 var match = str.match(maybeQuotedRe);
446 // perhaps str = eval('"'+str+'"'); would be enough?
447 str = str.replace(escCodeRe,
448 function (substr, p1, offset, s) { return unq(p1); });
453 /* ============================================================ */
454 /* main part: parsing response */
457 * Function called for each blame entry, as soon as it finishes.
458 * It updates page via DOM manipulation, adding sha1 info, etc.
460 * @param {Commit} commit: blamed commit
461 * @param {Object} group: object representing group of lines,
462 * which blame the same commit (blame entry)
464 * @globals blamedLines
466 function handleLine(commit, group) {
468 This is the structure of the HTML fragment we are working
471 <tr id="l123" class="">
472 <td class="sha1" title=""><a href=""> </a></td>
473 <td class="linenr"><a class="linenr" href="">123</a></td>
474 <td class="pre"># times (my ext3 doesn't).</td>
478 var resline = group.resline;
480 // format date and time string only once per commit
482 /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
483 commit.info = commit.author + ', ' +
484 formatDateISOLocal(commit.authorTime, commit.authorTimezone);
487 // color depends on group of lines, not only on blamed commit
488 var colorNo = findColorNo(
489 document.getElementById('l'+(resline-1)),
490 document.getElementById('l'+(resline+group.numlines))
493 // loop over lines in commit group
494 for (var i = 0; i < group.numlines; i++, resline++) {
495 var tr = document.getElementById('l'+resline);
500 <tr id="l123" class="">
501 <td class="sha1" title=""><a href=""> </a></td>
502 <td class="linenr"><a class="linenr" href="">123</a></td>
503 <td class="pre"># times (my ext3 doesn't).</td>
506 var td_sha1 = tr.firstChild;
507 var a_sha1 = td_sha1.firstChild;
508 var a_linenr = td_sha1.nextSibling.firstChild;
510 /* <tr id="l123" class=""> */
512 if (colorNo !== null) {
513 tr_class = 'color'+colorNo;
515 if (commit.boundary) {
516 tr_class += ' boundary';
518 if (commit.nprevious === 0) {
519 tr_class += ' no-previous';
520 } else if (commit.nprevious > 1) {
521 tr_class += ' multiple-previous';
523 tr.className = tr_class;
525 /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
527 td_sha1.title = commit.info;
528 td_sha1.rowSpan = group.numlines;
530 a_sha1.href = projectUrl + 'a=commit;h=' + commit.sha1;
531 a_sha1.firstChild.data = commit.sha1.substr(0, 8);
532 if (group.numlines >= 2) {
533 var fragment = document.createDocumentFragment();
534 var br = document.createElement("br");
535 var text = document.createTextNode(
536 commit.author.match(/\b([A-Z])\B/g).join(''));
538 var elem = fragment || td_sha1;
539 elem.appendChild(br);
540 elem.appendChild(text);
542 td_sha1.appendChild(fragment);
547 //tr.removeChild(td_sha1); // DOM2 Core way
548 tr.deleteCell(0); // DOM2 HTML way
551 /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
553 ('previous' in commit ? commit.previous : commit.sha1);
554 var linenr_filename =
555 ('file_parent' in commit ? commit.file_parent : commit.filename);
556 a_linenr.href = projectUrl + 'a=blame_incremental' +
557 ';hb=' + linenr_commit +
558 ';f=' + encodeURIComponent(linenr_filename) +
559 '#l' + (group.srcline + i);
563 //updateProgressInfo();
567 // ----------------------------------------------------------------------
569 var inProgress = false; // are we processing response
574 var sha1Re = /^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
575 var infoRe = /^([a-z-]+) ?(.*)/;
576 var endRe = /^END ?([^ ]*) ?(.*)/;
579 var curCommit = new Commit();
582 var pollTimer = null;
585 * Parse output from 'git blame --incremental [...]', received via
586 * XMLHttpRequest from server (blamedataUrl), and call handleLine
587 * (which updates page) as soon as blame entry is completed.
589 * @param {String[]} lines: new complete lines from blamedata server
591 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
592 * @globals sha1Re, infoRe, endRe
594 function processBlameLines(lines) {
597 for (var i = 0, len = lines.length; i < len; i++) {
599 if ((match = sha1Re.exec(lines[i]))) {
601 var srcline = parseInt(match[2], 10);
602 var resline = parseInt(match[3], 10);
603 var numlines = parseInt(match[4], 10);
605 var c = commits[sha1];
607 c = new Commit(sha1);
612 curGroup.srcline = srcline;
613 curGroup.resline = resline;
614 curGroup.numlines = numlines;
616 } else if ((match = infoRe.exec(lines[i]))) {
621 curCommit.filename = unquote(data);
622 // 'filename' information terminates the entry
623 handleLine(curCommit, curGroup);
624 updateProgressInfo();
627 curCommit.author = data;
630 curCommit.authorTime = parseInt(data, 10);
633 curCommit.authorTimezone = data;
636 curCommit.nprevious++;
637 // store only first 'previous' header
638 if (!'previous' in curCommit) {
639 var parts = data.split(' ', 2);
640 curCommit.previous = parts[0];
641 curCommit.file_parent = unquote(parts[1]);
645 curCommit.boundary = true;
649 } else if ((match = endRe.exec(lines[i]))) {
650 t_interval_server = match[1];
651 cmds_server = match[2];
653 } else if (lines[i] !== '') {
662 * Process new data and return pointer to end of processed part
664 * @param {String} unprocessed: new data (from nextReadPos)
665 * @param {Number} nextReadPos: end of last processed data
666 * @return {Number} end of processed data (new value for nextReadPos)
668 function processData(unprocessed, nextReadPos) {
669 var lastLineEnd = unprocessed.lastIndexOf('\n');
670 if (lastLineEnd !== -1) {
671 var lines = unprocessed.substring(0, lastLineEnd).split('\n');
672 nextReadPos += lastLineEnd + 1 /* 1 == '\n'.length */;
674 processBlameLines(lines);
681 * Handle XMLHttpRequest errors
683 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
685 * @globals pollTimer, commits, inProgress
687 function handleError(xhr) {
688 errorInfo('Server error: ' +
689 xhr.status + ' - ' + (xhr.statusText || 'Error contacting server'));
691 clearInterval(pollTimer);
692 commits = {}; // free memory
698 * Called after XMLHttpRequest finishes (loads)
700 * @param {XMLHttpRequest} xhr: XMLHttpRequest object (unused)
702 * @globals pollTimer, commits, inProgress
704 function responseLoaded(xhr) {
705 clearInterval(pollTimer);
707 fixColorsAndGroups();
709 commits = {}; // free memory
715 * handler for XMLHttpRequest onreadystatechange event
718 * @globals xhr, inProgress
720 function handleResponse() {
725 * Value Constant (W3C) Description
726 * -------------------------------------------------------------------
727 * 0 UNSENT open() has not been called yet.
728 * 1 OPENED send() has not been called yet.
729 * 2 HEADERS_RECEIVED send() has been called, and headers
730 * and status are available.
731 * 3 LOADING Downloading; responseText holds partial data.
732 * 4 DONE The operation is complete.
735 if (xhr.readyState !== 4 && xhr.readyState !== 3) {
739 // the server returned error
740 if (xhr.readyState === 3 && xhr.status !== 200) {
743 if (xhr.readyState === 4 && xhr.status !== 200) {
748 // In konqueror xhr.responseText is sometimes null here...
749 if (xhr.responseText === null) {
753 // in case we were called before finished processing
760 // extract new whole (complete) lines, and process them
761 while (xhr.prevDataLength !== xhr.responseText.length) {
762 if (xhr.readyState === 4 &&
763 xhr.prevDataLength === xhr.responseText.length) {
767 xhr.prevDataLength = xhr.responseText.length;
768 var unprocessed = xhr.responseText.substring(xhr.nextReadPos);
769 xhr.nextReadPos = processData(unprocessed, xhr.nextReadPos);
772 // did we finish work?
773 if (xhr.readyState === 4 &&
774 xhr.prevDataLength === xhr.responseText.length) {
781 // ============================================================
782 // ------------------------------------------------------------
785 * Incrementally update line data in blame_incremental view in gitweb.
787 * @param {String} blamedataUrl: URL to server script generating blame data.
788 * @param {String} bUrl: partial URL to project, used to generate links.
790 * Called from 'blame_incremental' view after loading table with
791 * file contents, a base for blame view.
793 * @globals xhr, t0, projectUrl, div_progress_bar, totalLines, pollTimer
795 function startBlame(blamedataUrl, bUrl) {
797 xhr = createRequestObject();
799 errorInfo('ERROR: XMLHttpRequest not supported');
804 projectUrl = bUrl + (bUrl.indexOf('?') === -1 ? '?' : ';');
805 if ((div_progress_bar = document.getElementById('progress_bar'))) {
806 //div_progress_bar.setAttribute('style', 'width: 100%;');
807 div_progress_bar.style.cssText = 'width: 100%;';
809 totalLines = countLines();
810 updateProgressInfo();
812 /* add extra properties to xhr object to help processing response */
813 xhr.prevDataLength = -1; // used to detect if we have new data
814 xhr.nextReadPos = 0; // where unread part of response starts
816 xhr.onreadystatechange = handleResponse;
817 //xhr.onreadystatechange = function () { handleResponse(xhr); };
819 xhr.open('GET', blamedataUrl);
820 xhr.setRequestHeader('Accept', 'text/plain');
823 // not all browsers call onreadystatechange event on each server flush
824 // poll response using timer every second to handle this issue
825 pollTimer = setInterval(xhr.onreadystatechange, 1000);