]>
Lady’s Gitweb - Gitweb/blob - static/js/blame_incremental.js
e68ba72129125f867951585c7d3a072b30ea4eeef5ee9990da5da795517117d2
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 JavaScript side of Ajax-y 'blame_incremental' view in gitweb
7 * @license GPLv2 or later
12 * This code uses DOM methods instead of (nonstandard) innerHTML
15 * innerHTML is non-standard IE extension, though supported by most
16 * browsers; however Firefox up to version 1.5 didn't implement it in
17 * a strict mode (application/xml+xhtml mimetype).
19 * Also my simple benchmarks show that using elem.firstChild.data =
20 * 'content' is slightly faster than elem.innerHTML = 'content'. It
21 * is however more fragile (text element fragment must exists), and
22 * less feature-rich (we cannot add HTML).
24 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
25 * equivalent using DOM 2 Core is usually shown in comments.
29 /* ============================================================ */
30 /* utility/helper functions (and variables) */
32 var xhr
; // XMLHttpRequest object
33 var projectUrl
; // partial query + separator ('?' or ';')
35 // 'commits' is an associative map. It maps SHA1s to Commit objects.
39 * constructor for Commit objects, used in 'blame'
40 * @class Represents a blamed commit
41 * @param {String} sha1: SHA-1 identifier of a commit
43 function Commit(sha1
) {
44 if (this instanceof Commit
) {
46 this.nprevious
= 0; /* number of 'previous', effective parents */
48 return new Commit(sha1
);
52 /* ............................................................ */
53 /* progress info, timing, error reporting */
56 var totalLines
= '???';
58 var div_progress_info
;
61 * Detects how many lines does a blamed file have,
62 * This information is used in progress info
64 * @returns {Number|String} Number of lines in file, or string '...'
66 function countLines() {
68 document
.getElementById('blame_table') ||
69 document
.getElementsByTagName('table')[0];
72 return table
.getElementsByTagName('tr').length
- 1; // for header
79 * update progress info and length (width) of progress bar
81 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
83 function updateProgressInfo() {
84 if (!div_progress_info
) {
85 div_progress_info
= document
.getElementById('progress_info');
87 if (!div_progress_bar
) {
88 div_progress_bar
= document
.getElementById('progress_bar');
90 if (!div_progress_info
&& !div_progress_bar
) {
94 var percentage
= Math
.floor(100.0*blamedLines
/totalLines
);
96 if (div_progress_info
) {
97 div_progress_info
.firstChild
.data
= blamedLines
+ ' / ' + totalLines
+
98 ' (' + padLeftStr(percentage
, 3, '\u00A0') + '%)';
101 if (div_progress_bar
) {
102 //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
103 div_progress_bar
.style
.width
= percentage
+ '%';
108 var t_interval_server
= '';
109 var cmds_server
= '';
113 * write how much it took to generate data, and to run script
115 * @globals t0, t_interval_server, cmds_server
117 function writeTimeInterval() {
118 var info_time
= document
.getElementById('generating_time');
119 if (!info_time
|| !t_interval_server
) {
123 info_time
.firstChild
.data
+= ' + (' +
124 t_interval_server
+ ' sec server blame_data / ' +
125 (t1
.getTime() - t0
.getTime())/1000 + ' sec client JavaScript)';
127 var info_cmds
= document
.getElementById('generating_cmd');
128 if (!info_time
|| !cmds_server
) {
131 info_cmds
.firstChild
.data
+= ' + ' + cmds_server
;
135 * show an error message alert to user within page (in prohress info area)
136 * @param {String} str: plain text error message (no HTML)
138 * @globals div_progress_info
140 function errorInfo(str
) {
141 if (!div_progress_info
) {
142 div_progress_info
= document
.getElementById('progress_info');
144 if (div_progress_info
) {
145 div_progress_info
.className
= 'error';
146 div_progress_info
.firstChild
.data
= str
;
150 /* ............................................................ */
151 /* coloring rows during blame_data (git blame --incremental) run */
154 * used to extract N from 'colorN', where N is a number,
157 var colorRe
= /\bcolor([0-9]*)\b/;
160 * return N if <tr class="colorN">, otherwise return null
161 * (some browsers require CSS class names to begin with letter)
163 * @param {HTMLElement} tr: table row element to check
164 * @param {String} tr.className: 'class' attribute of tr element
165 * @returns {Number|null} N if tr.className == 'colorN', otherwise null
169 function getColorNo(tr
) {
173 var className
= tr
.className
;
175 var match
= colorRe
.exec(className
);
177 return parseInt(match
[1], 10);
183 var colorsFreq
= [0, 0, 0];
185 * return one of given possible colors (curently least used one)
186 * example: chooseColorNoFrom(2, 3) returns 2 or 3
188 * @param {Number[]} arguments: one or more numbers
189 * assumes that 1 <= arguments[i] <= colorsFreq.length
190 * @returns {Number} Least used color number from arguments
191 * @globals colorsFreq
193 function chooseColorNoFrom() {
194 // choose the color which is least used
195 var colorNo
= arguments
[0];
196 for (var i
= 1; i
< arguments
.length
; i
++) {
197 if (colorsFreq
[arguments
[i
]-1] < colorsFreq
[colorNo
-1]) {
198 colorNo
= arguments
[i
];
201 colorsFreq
[colorNo
-1]++;
206 * given two neigbour <tr> elements, find color which would be different
207 * from color of both of neighbours; used to 3-color blame table
209 * @param {HTMLElement} tr_prev
210 * @param {HTMLElement} tr_next
211 * @returns {Number} color number N such that
212 * colorN != tr_prev.className && colorN != tr_next.className
214 function findColorNo(tr_prev
, tr_next
) {
215 var color_prev
= getColorNo(tr_prev
);
216 var color_next
= getColorNo(tr_next
);
219 // neither of neighbours has color set
220 // THEN we can use any of 3 possible colors
221 if (!color_prev
&& !color_next
) {
222 return chooseColorNoFrom(1,2,3);
225 // either both neighbours have the same color,
226 // or only one of neighbours have color set
227 // THEN we can use any color except given
229 if (color_prev
=== color_next
) {
230 color
= color_prev
; // = color_next;
231 } else if (!color_prev
) {
233 } else if (!color_next
) {
237 return chooseColorNoFrom((color
% 3) + 1, ((color
+1) % 3) + 1);
240 // neighbours have different colors
241 // THEN there is only one color left
242 return (3 - ((color_prev
+ color_next
) % 3));
245 /* ............................................................ */
246 /* coloring rows like 'blame' after 'blame_data' finishes */
249 * returns true if given row element (tr) is first in commit group
250 * to be used only after 'blame_data' finishes (after processing)
252 * @param {HTMLElement} tr: table row
253 * @returns {Boolean} true if TR is first in commit group
255 function isStartOfGroup(tr
) {
256 return tr
.firstChild
.className
=== 'sha1';
260 * change colors to use zebra coloring (2 colors) instead of 3 colors
261 * concatenate neighbour commit groups belonging to the same commit
265 function fixColorsAndGroups() {
266 var colorClasses
= ['light', 'dark'];
271 document
.getElementById('blame_table') ||
272 document
.getElementsByTagName('table')[0];
274 while ((tr
= document
.getElementById('l'+linenum
))) {
275 // index origin is 0, which is table header; start from 1
276 //while ((tr = table.rows[linenum])) { // <- it is slower
277 if (isStartOfGroup(tr
, linenum
, document
)) {
279 prev_group
.firstChild
.firstChild
.href
===
280 tr
.firstChild
.firstChild
.href
) {
281 // we have to concatenate groups
282 var prev_rows
= prev_group
.firstChild
.rowSpan
|| 1;
283 var curr_rows
= tr
.firstChild
.rowSpan
|| 1;
284 prev_group
.firstChild
.rowSpan
= prev_rows
+ curr_rows
;
285 //tr.removeChild(tr.firstChild);
286 tr
.deleteCell(0); // DOM2 HTML way
288 colorClass
= (colorClass
+ 1) % 2;
292 var tr_class
= tr
.className
;
293 tr
.className
= tr_class
.replace(colorRe
, colorClasses
[colorClass
]);
299 /* ============================================================ */
300 /* main part: parsing response */
303 * Function called for each blame entry, as soon as it finishes.
304 * It updates page via DOM manipulation, adding sha1 info, etc.
306 * @param {Commit} commit: blamed commit
307 * @param {Object} group: object representing group of lines,
308 * which blame the same commit (blame entry)
310 * @globals blamedLines
312 function handleLine(commit
, group
) {
314 This is the structure of the HTML fragment we are working
317 <tr id="l123" class="">
318 <td class="sha1" title=""><a href=""> </a></td>
319 <td class="linenr"><a class="linenr" href="">123</a></td>
320 <td class="pre"># times (my ext3 doesn't).</td>
324 var resline
= group
.resline
;
326 // format date and time string only once per commit
328 /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
329 commit
.info
= commit
.author
+ ', ' +
330 formatDateISOLocal(commit
.authorTime
, commit
.authorTimezone
);
333 // color depends on group of lines, not only on blamed commit
334 var colorNo
= findColorNo(
335 document
.getElementById('l'+(resline
-1)),
336 document
.getElementById('l'+(resline
+group
.numlines
))
339 // loop over lines in commit group
340 for (var i
= 0; i
< group
.numlines
; i
++, resline
++) {
341 var tr
= document
.getElementById('l'+resline
);
346 <tr id="l123" class="">
347 <td class="sha1" title=""><a href=""> </a></td>
348 <td class="linenr"><a class="linenr" href="">123</a></td>
349 <td class="pre"># times (my ext3 doesn't).</td>
352 var td_sha1
= tr
.firstChild
;
353 var a_sha1
= td_sha1
.firstChild
;
354 var a_linenr
= td_sha1
.nextSibling
.firstChild
;
356 /* <tr id="l123" class=""> */
358 if (colorNo
!== null) {
359 tr_class
= 'color'+colorNo
;
361 if (commit
.boundary
) {
362 tr_class
+= ' boundary';
364 if (commit
.nprevious
=== 0) {
365 tr_class
+= ' no-previous';
366 } else if (commit
.nprevious
> 1) {
367 tr_class
+= ' multiple-previous';
369 tr
.className
= tr_class
;
371 /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
373 td_sha1
.title
= commit
.info
;
374 td_sha1
.rowSpan
= group
.numlines
;
376 a_sha1
.href
= projectUrl
+ 'a=commit;h=' + commit
.sha1
;
377 if (a_sha1
.firstChild
) {
378 a_sha1
.firstChild
.data
= commit
.sha1
.substr(0, 8);
381 document
.createTextNode(commit
.sha1
.substr(0, 8)));
383 if (group
.numlines
>= 2) {
384 var fragment
= document
.createDocumentFragment();
385 var br
= document
.createElement("br");
386 var match
= commit
.author
.match(/\b([A-Z])\B/g);
388 var text
= document
.createTextNode(
392 var elem
= fragment
|| td_sha1
;
393 elem
.appendChild(br
);
394 elem
.appendChild(text
);
396 td_sha1
.appendChild(fragment
);
401 //tr.removeChild(td_sha1); // DOM2 Core way
402 tr
.deleteCell(0); // DOM2 HTML way
405 /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
407 ('previous' in commit
? commit
.previous : commit
.sha1
);
408 var linenr_filename
=
409 ('file_parent' in commit
? commit
.file_parent : commit
.filename
);
410 a_linenr
.href
= projectUrl
+ 'a=blame_incremental' +
411 ';hb=' + linenr_commit
+
412 ';f=' + encodeURIComponent(linenr_filename
) +
413 '#l' + (group
.srcline
+ i
);
417 //updateProgressInfo();
421 // ----------------------------------------------------------------------
423 var inProgress
= false; // are we processing response
428 var sha1Re
= /^([0-9a
-f
]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
429 var infoRe
= /^([a
-z
-]+) ?(.*)/;
430 var endRe
= /^END
?([^ ]*) ?(.*)/;
433 var curCommit
= new Commit();
436 var pollTimer
= null;
439 * Parse output from 'git blame --incremental [...]', received via
440 * XMLHttpRequest from server (blamedataUrl), and call handleLine
441 * (which updates page) as soon as blame entry is completed.
443 * @param {String[]} lines: new complete lines from blamedata server
445 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
446 * @globals sha1Re, infoRe, endRe
448 function processBlameLines(lines
) {
451 for (var i
= 0, len
= lines
.length
; i
< len
; i
++) {
453 if ((match
= sha1Re
.exec(lines
[i
]))) {
455 var srcline
= parseInt(match
[2], 10);
456 var resline
= parseInt(match
[3], 10);
457 var numlines
= parseInt(match
[4], 10);
459 var c
= commits
[sha1
];
461 c
= new Commit(sha1
);
466 curGroup
.srcline
= srcline
;
467 curGroup
.resline
= resline
;
468 curGroup
.numlines
= numlines
;
470 } else if ((match
= infoRe
.exec(lines
[i
]))) {
475 curCommit
.filename
= unquote(data
);
476 // 'filename' information terminates the entry
477 handleLine(curCommit
, curGroup
);
478 updateProgressInfo();
481 curCommit
.author
= data
;
484 curCommit
.authorTime
= parseInt(data
, 10);
487 curCommit
.authorTimezone
= data
;
490 curCommit
.nprevious
++;
491 // store only first 'previous' header
492 if (!'previous' in curCommit
) {
493 var parts
= data
.split(' ', 2);
494 curCommit
.previous
= parts
[0];
495 curCommit
.file_parent
= unquote(parts
[1]);
499 curCommit
.boundary
= true;
503 } else if ((match
= endRe
.exec(lines
[i
]))) {
504 t_interval_server
= match
[1];
505 cmds_server
= match
[2];
507 } else if (lines
[i
] !== '') {
516 * Process new data and return pointer to end of processed part
518 * @param {String} unprocessed: new data (from nextReadPos)
519 * @param {Number} nextReadPos: end of last processed data
520 * @return {Number} end of processed data (new value for nextReadPos)
522 function processData(unprocessed
, nextReadPos
) {
523 var lastLineEnd
= unprocessed
.lastIndexOf('\n');
524 if (lastLineEnd
!== -1) {
525 var lines
= unprocessed
.substring(0, lastLineEnd
).split('\n');
526 nextReadPos
+= lastLineEnd
+ 1 /* 1 == '\n'.length */;
528 processBlameLines(lines
);
535 * Handle XMLHttpRequest errors
537 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
539 * @globals pollTimer, commits, inProgress
541 function handleError(xhr
) {
542 errorInfo('Server error: ' +
543 xhr
.status
+ ' - ' + (xhr
.statusText
|| 'Error contacting server'));
545 clearInterval(pollTimer
);
546 commits
= {}; // free memory
552 * Called after XMLHttpRequest finishes (loads)
554 * @param {XMLHttpRequest} xhr: XMLHttpRequest object (unused)
556 * @globals pollTimer, commits, inProgress
558 function responseLoaded(xhr
) {
559 clearInterval(pollTimer
);
561 fixColorsAndGroups();
563 commits
= {}; // free memory
569 * handler for XMLHttpRequest onreadystatechange event
572 * @globals xhr, inProgress
574 function handleResponse() {
579 * Value Constant (W3C) Description
580 * -------------------------------------------------------------------
581 * 0 UNSENT open() has not been called yet.
582 * 1 OPENED send() has not been called yet.
583 * 2 HEADERS_RECEIVED send() has been called, and headers
584 * and status are available.
585 * 3 LOADING Downloading; responseText holds partial data.
586 * 4 DONE The operation is complete.
589 if (xhr
.readyState
!== 4 && xhr
.readyState
!== 3) {
593 // the server returned error
594 // try ... catch block is to work around bug in IE8
596 if (xhr
.readyState
=== 3 && xhr
.status
!== 200) {
602 if (xhr
.readyState
=== 4 && xhr
.status
!== 200) {
607 // In konqueror xhr.responseText is sometimes null here...
608 if (xhr
.responseText
=== null) {
612 // in case we were called before finished processing
619 // extract new whole (complete) lines, and process them
620 while (xhr
.prevDataLength
!== xhr
.responseText
.length
) {
621 if (xhr
.readyState
=== 4 &&
622 xhr
.prevDataLength
=== xhr
.responseText
.length
) {
626 xhr
.prevDataLength
= xhr
.responseText
.length
;
627 var unprocessed
= xhr
.responseText
.substring(xhr
.nextReadPos
);
628 xhr
.nextReadPos
= processData(unprocessed
, xhr
.nextReadPos
);
631 // did we finish work?
632 if (xhr
.readyState
=== 4 &&
633 xhr
.prevDataLength
=== xhr
.responseText
.length
) {
640 // ============================================================
641 // ------------------------------------------------------------
644 * Incrementally update line data in blame_incremental view in gitweb.
646 * @param {String} blamedataUrl: URL to server script generating blame data.
647 * @param {String} bUrl: partial URL to project, used to generate links.
649 * Called from 'blame_incremental' view after loading table with
650 * file contents, a base for blame view.
652 * @globals xhr, t0, projectUrl, div_progress_bar, totalLines, pollTimer
654 function startBlame(blamedataUrl
, bUrl
) {
656 xhr
= createRequestObject();
658 errorInfo('ERROR: XMLHttpRequest not supported');
663 projectUrl
= bUrl
+ (bUrl
.indexOf('?') === -1 ? '?' : ';');
664 if ((div_progress_bar
= document
.getElementById('progress_bar'))) {
665 //div_progress_bar.setAttribute('style', 'width: 100%;');
666 div_progress_bar
.style
.cssText
= 'width: 100%;';
668 totalLines
= countLines();
669 updateProgressInfo();
671 /* add extra properties to xhr object to help processing response */
672 xhr
.prevDataLength
= -1; // used to detect if we have new data
673 xhr
.nextReadPos
= 0; // where unread part of response starts
675 xhr
.onreadystatechange
= handleResponse
;
676 //xhr.onreadystatechange = function () { handleResponse(xhr); };
678 xhr
.open('GET', blamedataUrl
);
679 xhr
.setRequestHeader('Accept', 'text/plain');
682 // not all browsers call onreadystatechange event on each server flush
683 // poll response using timer every second to handle this issue
684 pollTimer
= setInterval(xhr
.onreadystatechange
, 1000);
687 /* end of blame_incremental.js */
This page took 0.769467 seconds and 3 git commands to generate.