]> Lady’s Gitweb - Git/blob - static/gitweb.js
Initial commit
[Git] / static / gitweb.js
1 /*
2 SPDX-FileCopyrightText: 2007 Fredrik Kuivinen <frekui@gmail.com>
3 SPDX-FileCopyrightText: 2007 Petr Baudis <pasky@suse.cz>
4 SPDX-FileCopyrightText: 2008-2011 Jakub Narebski <jnareb@gmail.com>
5 SPDX-FileCopyrightText: 2011 John 'Warthog9' Hawley <warthog9@eaglescrag.net>
6 SPDX-License-Identifier: GPL-2.0-or-later
7 */
8
9 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
10 // 2007, Petr Baudis <pasky@suse.cz>
11 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
12
13 /**
14 * @fileOverview Generic JavaScript code (helper functions)
15 * @license GPLv2 or later
16 */
17
18
19 /* ============================================================ */
20 /* ............................................................ */
21 /* Padding */
22
23 /**
24 * pad INPUT on the left with STR that is assumed to have visible
25 * width of single character (for example nonbreakable spaces),
26 * to WIDTH characters
27 *
28 * example: padLeftStr(12, 3, '\u00A0') == '\u00A012'
29 * ('\u00A0' is nonbreakable space)
30 *
31 * @param {Number|String} input: number to pad
32 * @param {Number} width: visible width of output
33 * @param {String} str: string to prefix to string, defaults to '\u00A0'
34 * @returns {String} INPUT prefixed with STR x (WIDTH - INPUT.length)
35 */
36 function padLeftStr(input, width, str) {
37 var prefix = '';
38 if (typeof str === 'undefined') {
39 ch = '\u00A0'; // using '&nbsp;' doesn't work in all browsers
40 }
41
42 width -= input.toString().length;
43 while (width > 0) {
44 prefix += str;
45 width--;
46 }
47 return prefix + input;
48 }
49
50 /**
51 * Pad INPUT on the left to WIDTH, using given padding character CH,
52 * for example padLeft('a', 3, '_') is '__a'
53 * padLeft(4, 2) is '04' (same as padLeft(4, 2, '0'))
54 *
55 * @param {String} input: input value converted to string.
56 * @param {Number} width: desired length of output.
57 * @param {String} ch: single character to prefix to string, defaults to '0'.
58 *
59 * @returns {String} Modified string, at least SIZE length.
60 */
61 function padLeft(input, width, ch) {
62 var s = input + "";
63 if (typeof ch === 'undefined') {
64 ch = '0';
65 }
66
67 while (s.length < width) {
68 s = ch + s;
69 }
70 return s;
71 }
72
73
74 /* ............................................................ */
75 /* Handling browser incompatibilities */
76
77 /**
78 * Create XMLHttpRequest object in cross-browser way
79 * @returns XMLHttpRequest object, or null
80 */
81 function createRequestObject() {
82 try {
83 return new XMLHttpRequest();
84 } catch (e) {}
85 try {
86 return window.createRequest();
87 } catch (e) {}
88 try {
89 return new ActiveXObject("Msxml2.XMLHTTP");
90 } catch (e) {}
91 try {
92 return new ActiveXObject("Microsoft.XMLHTTP");
93 } catch (e) {}
94
95 return null;
96 }
97
98
99 /**
100 * Insert rule giving specified STYLE to given SELECTOR at the end of
101 * first CSS stylesheet.
102 *
103 * @param {String} selector: CSS selector, e.g. '.class'
104 * @param {String} style: rule contents, e.g. 'background-color: red;'
105 */
106 function addCssRule(selector, style) {
107 var stylesheet = document.styleSheets[0];
108
109 var theRules = [];
110 if (stylesheet.cssRules) { // W3C way
111 theRules = stylesheet.cssRules;
112 } else if (stylesheet.rules) { // IE way
113 theRules = stylesheet.rules;
114 }
115
116 if (stylesheet.insertRule) { // W3C way
117 stylesheet.insertRule(selector + ' { ' + style + ' }', theRules.length);
118 } else if (stylesheet.addRule) { // IE way
119 stylesheet.addRule(selector, style);
120 }
121 }
122
123
124 /* ............................................................ */
125 /* Support for legacy browsers */
126
127 /**
128 * Provides getElementsByClassName method, if there is no native
129 * implementation of this method.
130 *
131 * NOTE that there are limits and differences compared to native
132 * getElementsByClassName as defined by e.g.:
133 * https://developer.mozilla.org/en/DOM/document.getElementsByClassName
134 * http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-getelementsbyclassname
135 * http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-getelementsbyclassname
136 *
137 * Namely, this implementation supports only single class name as
138 * argument and not set of space-separated tokens representing classes,
139 * it returns Array of nodes rather than live NodeList, and has
140 * additional optional argument where you can limit search to given tags
141 * (via getElementsByTagName).
142 *
143 * Based on
144 * http://code.google.com/p/getelementsbyclassname/
145 * http://www.dustindiaz.com/getelementsbyclass/
146 * http://stackoverflow.com/questions/1818865/do-we-have-getelementsbyclassname-in-javascript
147 *
148 * See also http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
149 *
150 * @param {String} class: name of _single_ class to find
151 * @param {String} [taghint] limit search to given tags
152 * @returns {Node[]} array of matching elements
153 */
154 if (!('getElementsByClassName' in document)) {
155 document.getElementsByClassName = function (classname, taghint) {
156 taghint = taghint || "*";
157 var elements = (taghint === "*" && document.all) ?
158 document.all :
159 document.getElementsByTagName(taghint);
160 var pattern = new RegExp("(^|\\s)" + classname + "(\\s|$)");
161 var matches= [];
162 for (var i = 0, j = 0, n = elements.length; i < n; i++) {
163 var el= elements[i];
164 if (el.className && pattern.test(el.className)) {
165 // matches.push(el);
166 matches[j] = el;
167 j++;
168 }
169 }
170 return matches;
171 };
172 } // end if
173
174
175 /* ............................................................ */
176 /* unquoting/unescaping filenames */
177
178 /**#@+
179 * @constant
180 */
181 var escCodeRe = /\\([^0-7]|[0-7]{1,3})/g;
182 var octEscRe = /^[0-7]{1,3}$/;
183 var maybeQuotedRe = /^\"(.*)\"$/;
184 /**#@-*/
185
186 /**
187 * unquote maybe C-quoted filename (as used by git, i.e. it is
188 * in double quotes '"' if there is any escape character used)
189 * e.g. 'aa' -> 'aa', '"a\ta"' -> 'a a'
190 *
191 * @param {String} str: git-quoted string
192 * @returns {String} Unquoted and unescaped string
193 *
194 * @globals escCodeRe, octEscRe, maybeQuotedRe
195 */
196 function unquote(str) {
197 function unq(seq) {
198 var es = {
199 // character escape codes, aka escape sequences (from C)
200 // replacements are to some extent JavaScript specific
201 t: "\t", // tab (HT, TAB)
202 n: "\n", // newline (NL)
203 r: "\r", // return (CR)
204 f: "\f", // form feed (FF)
205 b: "\b", // backspace (BS)
206 a: "\x07", // alarm (bell) (BEL)
207 e: "\x1B", // escape (ESC)
208 v: "\v" // vertical tab (VT)
209 };
210
211 if (seq.search(octEscRe) !== -1) {
212 // octal char sequence
213 return String.fromCharCode(parseInt(seq, 8));
214 } else if (seq in es) {
215 // C escape sequence, aka character escape code
216 return es[seq];
217 }
218 // quoted ordinary character
219 return seq;
220 }
221
222 var match = str.match(maybeQuotedRe);
223 if (match) {
224 str = match[1];
225 // perhaps str = eval('"'+str+'"'); would be enough?
226 str = str.replace(escCodeRe,
227 function (substr, p1, offset, s) { return unq(p1); });
228 }
229 return str;
230 }
231
232 /* end of common-lib.js */
233 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
234 // 2007, Petr Baudis <pasky@suse.cz>
235 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
236
237 /**
238 * @fileOverview Datetime manipulation: parsing and formatting
239 * @license GPLv2 or later
240 */
241
242
243 /* ............................................................ */
244 /* parsing and retrieving datetime related information */
245
246 /**
247 * used to extract hours and minutes from timezone info, e.g '-0900'
248 * @constant
249 */
250 var tzRe = /^([+\-])([0-9][0-9])([0-9][0-9])$/;
251
252 /**
253 * convert numeric timezone +/-ZZZZ to offset from UTC in seconds
254 *
255 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
256 * @returns {Number} offset from UTC in seconds for timezone
257 *
258 * @globals tzRe
259 */
260 function timezoneOffset(timezoneInfo) {
261 var match = tzRe.exec(timezoneInfo);
262 var tz_sign = (match[1] === '-' ? -1 : +1);
263 var tz_hour = parseInt(match[2],10);
264 var tz_min = parseInt(match[3],10);
265
266 return tz_sign*(((tz_hour*60) + tz_min)*60);
267 }
268
269 /**
270 * return local (browser) timezone as offset from UTC in seconds
271 *
272 * @returns {Number} offset from UTC in seconds for local timezone
273 */
274 function localTimezoneOffset() {
275 // getTimezoneOffset returns the time-zone offset from UTC,
276 // in _minutes_, for the current locale
277 return ((new Date()).getTimezoneOffset() * -60);
278 }
279
280 /**
281 * return local (browser) timezone as numeric timezone '(+|-)HHMM'
282 *
283 * @returns {String} locat timezone as -/+ZZZZ
284 */
285 function localTimezoneInfo() {
286 var tzOffsetMinutes = (new Date()).getTimezoneOffset() * -1;
287
288 return formatTimezoneInfo(0, tzOffsetMinutes);
289 }
290
291
292 /**
293 * Parse RFC-2822 date into a Unix timestamp (into epoch)
294 *
295 * @param {String} date: date in RFC-2822 format, e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'
296 * @returns {Number} epoch i.e. seconds since '00:00:00 1970-01-01 UTC'
297 */
298 function parseRFC2822Date(date) {
299 // Date.parse accepts the IETF standard (RFC 1123 Section 5.2.14 and elsewhere)
300 // date syntax, which is defined in RFC 2822 (obsoletes RFC 822)
301 // and returns number of _milli_seconds since January 1, 1970, 00:00:00 UTC
302 return Date.parse(date) / 1000;
303 }
304
305
306 /* ............................................................ */
307 /* formatting date */
308
309 /**
310 * format timezone offset as numerical timezone '(+|-)HHMM' or '(+|-)HH:MM'
311 *
312 * @param {Number} hours: offset in hours, e.g. 2 for '+0200'
313 * @param {Number} [minutes] offset in minutes, e.g. 30 for '-4030';
314 * it is split into hours if not 0 <= minutes < 60,
315 * for example 1200 would give '+0100';
316 * defaults to 0
317 * @param {String} [sep] separator between hours and minutes part,
318 * default is '', might be ':' for W3CDTF (rfc-3339)
319 * @returns {String} timezone in '(+|-)HHMM' or '(+|-)HH:MM' format
320 */
321 function formatTimezoneInfo(hours, minutes, sep) {
322 minutes = minutes || 0; // to be able to use formatTimezoneInfo(hh)
323 sep = sep || ''; // default format is +/-ZZZZ
324
325 if (minutes < 0 || minutes > 59) {
326 hours = minutes > 0 ? Math.floor(minutes / 60) : Math.ceil(minutes / 60);
327 minutes = Math.abs(minutes - 60*hours); // sign of minutes is sign of hours
328 // NOTE: this works correctly because there is no UTC-00:30 timezone
329 }
330
331 var tzSign = hours >= 0 ? '+' : '-';
332 if (hours < 0) {
333 hours = -hours; // sign is stored in tzSign
334 }
335
336 return tzSign + padLeft(hours, 2, '0') + sep + padLeft(minutes, 2, '0');
337 }
338
339 /**
340 * translate 'utc' and 'local' to numerical timezone
341 * @param {String} timezoneInfo: might be 'utc' or 'local' (browser)
342 */
343 function normalizeTimezoneInfo(timezoneInfo) {
344 switch (timezoneInfo) {
345 case 'utc':
346 return '+0000';
347 case 'local': // 'local' is browser timezone
348 return localTimezoneInfo();
349 }
350 return timezoneInfo;
351 }
352
353
354 /**
355 * return date in local time formatted in iso-8601 like format
356 * 'yyyy-mm-dd HH:MM:SS +/-ZZZZ' e.g. '2005-08-07 21:49:46 +0200'
357 *
358 * @param {Number} epoch: seconds since '00:00:00 1970-01-01 UTC'
359 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
360 * @returns {String} date in local time in iso-8601 like format
361 */
362 function formatDateISOLocal(epoch, timezoneInfo) {
363 // date corrected by timezone
364 var localDate = new Date(1000 * (epoch +
365 timezoneOffset(timezoneInfo)));
366 var localDateStr = // e.g. '2005-08-07'
367 localDate.getUTCFullYear() + '-' +
368 padLeft(localDate.getUTCMonth()+1, 2, '0') + '-' +
369 padLeft(localDate.getUTCDate(), 2, '0');
370 var localTimeStr = // e.g. '21:49:46'
371 padLeft(localDate.getUTCHours(), 2, '0') + ':' +
372 padLeft(localDate.getUTCMinutes(), 2, '0') + ':' +
373 padLeft(localDate.getUTCSeconds(), 2, '0');
374
375 return localDateStr + ' ' + localTimeStr + ' ' + timezoneInfo;
376 }
377
378 /**
379 * return date in local time formatted in rfc-2822 format
380 * e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'
381 *
382 * @param {Number} epoch: seconds since '00:00:00 1970-01-01 UTC'
383 * @param {String} timezoneInfo: numeric timezone '(+|-)HHMM'
384 * @param {Boolean} [padDay] e.g. 'Sun, 07 Aug' if true, 'Sun, 7 Aug' otherwise
385 * @returns {String} date in local time in rfc-2822 format
386 */
387 function formatDateRFC2882(epoch, timezoneInfo, padDay) {
388 // A short textual representation of a month, three letters
389 var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
390 // A textual representation of a day, three letters
391 var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"];
392 // date corrected by timezone
393 var localDate = new Date(1000 * (epoch +
394 timezoneOffset(timezoneInfo)));
395 var localDateStr = // e.g. 'Sun, 7 Aug 2005' or 'Sun, 07 Aug 2005'
396 days[localDate.getUTCDay()] + ', ' +
397 (padDay ? padLeft(localDate.getUTCDate(),2,'0') : localDate.getUTCDate()) + ' ' +
398 months[localDate.getUTCMonth()] + ' ' +
399 localDate.getUTCFullYear();
400 var localTimeStr = // e.g. '21:49:46'
401 padLeft(localDate.getUTCHours(), 2, '0') + ':' +
402 padLeft(localDate.getUTCMinutes(), 2, '0') + ':' +
403 padLeft(localDate.getUTCSeconds(), 2, '0');
404
405 return localDateStr + ' ' + localTimeStr + ' ' + timezoneInfo;
406 }
407
408 /* end of datetime.js */
409 /**
410 * @fileOverview Accessing cookies from JavaScript
411 * @license GPLv2 or later
412 */
413
414 /*
415 * Based on subsection "Cookies in JavaScript" of "Professional
416 * JavaScript for Web Developers" by Nicholas C. Zakas and cookie
417 * plugin from jQuery (dual licensed under the MIT and GPL licenses)
418 */
419
420
421 /**
422 * Create a cookie with the given name and value,
423 * and other optional parameters.
424 *
425 * @example
426 * setCookie('foo', 'bar'); // will be deleted when browser exits
427 * setCookie('foo', 'bar', { expires: new Date(Date.parse('Jan 1, 2012')) });
428 * setCookie('foo', 'bar', { expires: 7 }); // 7 days = 1 week
429 * setCookie('foo', 'bar', { expires: 14, path: '/' });
430 *
431 * @param {String} sName: Unique name of a cookie (letters, numbers, underscores).
432 * @param {String} sValue: The string value stored in a cookie.
433 * @param {Object} [options] An object literal containing key/value pairs
434 * to provide optional cookie attributes.
435 * @param {String|Number|Date} [options.expires] Either literal string to be used as cookie expires,
436 * or an integer specifying the expiration date from now on in days,
437 * or a Date object to be used as cookie expiration date.
438 * If a negative value is specified or a date in the past),
439 * the cookie will be deleted.
440 * If set to null or omitted, the cookie will be a session cookie
441 * and will not be retained when the browser exits.
442 * @param {String} [options.path] Restrict access of a cookie to particular directory
443 * (default: path of page that created the cookie).
444 * @param {String} [options.domain] Override what web sites are allowed to access cookie
445 * (default: domain of page that created the cookie).
446 * @param {Boolean} [options.secure] If true, the secure attribute of the cookie will be set
447 * and the cookie would be accessible only from secure sites
448 * (cookie transmission will require secure protocol like HTTPS).
449 */
450 function setCookie(sName, sValue, options) {
451 options = options || {};
452 if (sValue === null) {
453 sValue = '';
454 option.expires = 'delete';
455 }
456
457 var sCookie = sName + '=' + encodeURIComponent(sValue);
458
459 if (options.expires) {
460 var oExpires = options.expires, sDate;
461 if (oExpires === 'delete') {
462 sDate = 'Thu, 01 Jan 1970 00:00:00 GMT';
463 } else if (typeof oExpires === 'string') {
464 sDate = oExpires;
465 } else {
466 var oDate;
467 if (typeof oExpires === 'number') {
468 oDate = new Date();
469 oDate.setTime(oDate.getTime() + (oExpires * 24 * 60 * 60 * 1000)); // days to ms
470 } else {
471 oDate = oExpires;
472 }
473 sDate = oDate.toGMTString();
474 }
475 sCookie += '; expires=' + sDate;
476 }
477
478 if (options.path) {
479 sCookie += '; path=' + (options.path);
480 }
481 if (options.domain) {
482 sCookie += '; domain=' + (options.domain);
483 }
484 if (options.secure) {
485 sCookie += '; secure';
486 }
487 document.cookie = sCookie;
488 }
489
490 /**
491 * Get the value of a cookie with the given name.
492 *
493 * @param {String} sName: Unique name of a cookie (letters, numbers, underscores)
494 * @returns {String|null} The string value stored in a cookie
495 */
496 function getCookie(sName) {
497 var sRE = '(?:; )?' + sName + '=([^;]*);?';
498 var oRE = new RegExp(sRE);
499 if (oRE.test(document.cookie)) {
500 return decodeURIComponent(RegExp['$1']);
501 } else {
502 return null;
503 }
504 }
505
506 /**
507 * Delete cookie with given name
508 *
509 * @param {String} sName: Unique name of a cookie (letters, numbers, underscores)
510 * @param {Object} [options] An object literal containing key/value pairs
511 * to provide optional cookie attributes.
512 * @param {String} [options.path] Must be the same as when setting a cookie
513 * @param {String} [options.domain] Must be the same as when setting a cookie
514 */
515 function deleteCookie(sName, options) {
516 options = options || {};
517 options.expires = 'delete';
518
519 setCookie(sName, '', options);
520 }
521
522 /* end of cookies.js */
523 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
524 // 2007, Petr Baudis <pasky@suse.cz>
525 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
526
527 /**
528 * @fileOverview Detect if JavaScript is enabled, and pass it to server-side
529 * @license GPLv2 or later
530 */
531
532
533 /* ============================================================ */
534 /* Manipulating links */
535
536 /**
537 * used to check if link has 'js' query parameter already (at end),
538 * and other reasons to not add 'js=1' param at the end of link
539 * @constant
540 */
541 var jsExceptionsRe = /[;?]js=[01](#.*)?$/;
542
543 /**
544 * Add '?js=1' or ';js=1' to the end of every link in the document
545 * that doesn't have 'js' query parameter set already.
546 *
547 * Links with 'js=1' lead to JavaScript version of given action, if it
548 * exists (currently there is only 'blame_incremental' for 'blame')
549 *
550 * To be used as `window.onload` handler
551 *
552 * @globals jsExceptionsRe
553 */
554 function fixLinks() {
555 var allLinks = document.getElementsByTagName("a") || document.links;
556 for (var i = 0, len = allLinks.length; i < len; i++) {
557 var link = allLinks[i];
558 if (!jsExceptionsRe.test(link)) {
559 link.href = link.href.replace(/(#|$)/,
560 (link.href.indexOf('?') === -1 ? '?' : ';') + 'js=1$1');
561 }
562 }
563 }
564
565 /* end of javascript-detection.js */
566 // Copyright (C) 2011, John 'Warthog9' Hawley <warthog9@eaglescrag.net>
567 // 2011, Jakub Narebski <jnareb@gmail.com>
568
569 /**
570 * @fileOverview Manipulate dates in gitweb output, adjusting timezone
571 * @license GPLv2 or later
572 */
573
574 /**
575 * Get common timezone, add UI for changing timezones, and adjust
576 * dates to use requested common timezone.
577 *
578 * This function is called during onload event (added to window.onload).
579 *
580 * @param {String} tzDefault: default timezone, if there is no cookie
581 * @param {Object} tzCookieInfo: object literal with info about cookie to store timezone
582 * @param {String} tzCookieInfo.name: name of cookie to store timezone
583 * @param {String} tzClassName: denotes elements with date to be adjusted
584 */
585 function onloadTZSetup(tzDefault, tzCookieInfo, tzClassName) {
586 var tzCookieTZ = getCookie(tzCookieInfo.name, tzCookieInfo);
587 var tz = tzDefault;
588
589 if (tzCookieTZ) {
590 // set timezone to value saved in a cookie
591 tz = tzCookieTZ;
592 // refresh cookie, so its expiration counts from last use of gitweb
593 setCookie(tzCookieInfo.name, tzCookieTZ, tzCookieInfo);
594 }
595
596 // add UI for changing timezone
597 addChangeTZ(tz, tzCookieInfo, tzClassName);
598
599 // server-side of gitweb produces datetime in UTC,
600 // so if tz is 'utc' there is no need for changes
601 var nochange = tz === 'utc';
602
603 // adjust dates to use specified common timezone
604 fixDatetimeTZ(tz, tzClassName, nochange);
605 }
606
607
608 /* ...................................................................... */
609 /* Changing dates to use requested timezone */
610
611 /**
612 * Replace RFC-2822 dates contained in SPAN elements with tzClassName
613 * CSS class with equivalent dates in given timezone.
614 *
615 * @param {String} tz: numeric timezone in '(-|+)HHMM' format, or 'utc', or 'local'
616 * @param {String} tzClassName: specifies elements to be changed
617 * @param {Boolean} nochange: markup for timezone change, but don't change it
618 */
619 function fixDatetimeTZ(tz, tzClassName, nochange) {
620 // sanity check, method should be ensured by common-lib.js
621 if (!document.getElementsByClassName) {
622 return;
623 }
624
625 // translate to timezone in '(-|+)HHMM' format
626 tz = normalizeTimezoneInfo(tz);
627
628 // NOTE: result of getElementsByClassName should probably be cached
629 var classesFound = document.getElementsByClassName(tzClassName, "span");
630 for (var i = 0, len = classesFound.length; i < len; i++) {
631 var curElement = classesFound[i];
632
633 curElement.title = 'Click to change timezone';
634 if (!nochange) {
635 // we use *.firstChild.data (W3C DOM) instead of *.innerHTML
636 // as the latter doesn't always work everywhere in every browser
637 var epoch = parseRFC2822Date(curElement.firstChild.data);
638 var adjusted = formatDateRFC2882(epoch, tz);
639
640 curElement.firstChild.data = adjusted;
641 }
642 }
643 }
644
645
646 /* ...................................................................... */
647 /* Adding triggers, generating timezone menu, displaying and hiding */
648
649 /**
650 * Adds triggers for UI to change common timezone used for dates in
651 * gitweb output: it marks up and/or creates item to click to invoke
652 * timezone change UI, creates timezone UI fragment to be attached,
653 * and installs appropriate onclick trigger (via event delegation).
654 *
655 * @param {String} tzSelected: pre-selected timezone,
656 * 'utc' or 'local' or '(-|+)HHMM'
657 * @param {Object} tzCookieInfo: object literal with info about cookie to store timezone
658 * @param {String} tzClassName: specifies elements to install trigger
659 */
660 function addChangeTZ(tzSelected, tzCookieInfo, tzClassName) {
661 // make link to timezone UI discoverable
662 addCssRule('.'+tzClassName + ':hover',
663 'text-decoration: underline; cursor: help;');
664
665 // create form for selecting timezone (to be saved in a cookie)
666 var tzSelectFragment = document.createDocumentFragment();
667 tzSelectFragment = createChangeTZForm(tzSelectFragment,
668 tzSelected, tzCookieInfo, tzClassName);
669
670 // event delegation handler for timezone selection UI (clicking on entry)
671 // see http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/
672 // assumes that there is no existing document.onclick handler
673 document.onclick = function onclickHandler(event) {
674 //IE doesn't pass in the event object
675 event = event || window.event;
676
677 //IE uses srcElement as the target
678 var target = event.target || event.srcElement;
679
680 switch (target.className) {
681 case tzClassName:
682 // don't display timezone menu if it is already displayed
683 if (tzSelectFragment.childNodes.length > 0) {
684 displayChangeTZForm(target, tzSelectFragment);
685 }
686 break;
687 } // end switch
688 };
689 }
690
691 /**
692 * Create DocumentFragment with UI for changing common timezone in
693 * which dates are shown in.
694 *
695 * @param {DocumentFragment} documentFragment: where attach UI
696 * @param {String} tzSelected: default (pre-selected) timezone
697 * @param {Object} tzCookieInfo: object literal with info about cookie to store timezone
698 * @returns {DocumentFragment}
699 */
700 function createChangeTZForm(documentFragment, tzSelected, tzCookieInfo, tzClassName) {
701 var div = document.createElement("div");
702 div.className = 'popup';
703
704 /* '<div class="close-button" title="(click on this box to close)">X</div>' */
705 var closeButton = document.createElement('div');
706 closeButton.className = 'close-button';
707 closeButton.title = '(click on this box to close)';
708 closeButton.appendChild(document.createTextNode('X'));
709 closeButton.onclick = closeTZFormHandler(documentFragment, tzClassName);
710 div.appendChild(closeButton);
711
712 /* 'Select timezone: <br clear="all">' */
713 div.appendChild(document.createTextNode('Select timezone: '));
714 var br = document.createElement('br');
715 br.clear = 'all';
716 div.appendChild(br);
717
718 /* '<select name="tzoffset">
719 * ...
720 * <option value="-0700">UTC-07:00</option>
721 * <option value="-0600">UTC-06:00</option>
722 * ...
723 * </select>' */
724 var select = document.createElement("select");
725 select.name = "tzoffset";
726 //select.style.clear = 'all';
727 select.appendChild(generateTZOptions(tzSelected));
728 select.onchange = selectTZHandler(documentFragment, tzCookieInfo, tzClassName);
729 div.appendChild(select);
730
731 documentFragment.appendChild(div);
732
733 return documentFragment;
734 }
735
736
737 /**
738 * Hide (remove from DOM) timezone change UI, ensuring that it is not
739 * garbage collected and that it can be re-enabled later.
740 *
741 * @param {DocumentFragment} documentFragment: contains detached UI
742 * @param {HTMLSelectElement} target: select element inside of UI
743 * @param {String} tzClassName: specifies element where UI was installed
744 * @returns {DocumentFragment} documentFragment
745 */
746 function removeChangeTZForm(documentFragment, target, tzClassName) {
747 // find containing element, where we appended timezone selection UI
748 // `target' is somewhere inside timezone menu
749 var container = target.parentNode, popup = target;
750 while (container &&
751 container.className !== tzClassName) {
752 popup = container;
753 container = container.parentNode;
754 }
755 // safety check if we found correct container,
756 // and if it isn't deleted already
757 if (!container || !popup ||
758 container.className !== tzClassName ||
759 popup.className !== 'popup') {
760 return documentFragment;
761 }
762
763 // timezone selection UI was appended as last child
764 // see also displayChangeTZForm function
765 var removed = popup.parentNode.removeChild(popup);
766 if (documentFragment.firstChild !== removed) { // the only child
767 // re-append it so it would be available for next time
768 documentFragment.appendChild(removed);
769 }
770 // all of inline style was added by this script
771 // it is not really needed to remove it, but it is a good practice
772 container.removeAttribute('style');
773
774 return documentFragment;
775 }
776
777
778 /**
779 * Display UI for changing common timezone for dates in gitweb output.
780 * To be used from 'onclick' event handler.
781 *
782 * @param {HTMLElement} target: where to install/display UI
783 * @param {DocumentFragment} tzSelectFragment: timezone selection UI
784 */
785 function displayChangeTZForm(target, tzSelectFragment) {
786 // for absolute positioning to be related to target element
787 target.style.position = 'relative';
788 target.style.display = 'inline-block';
789
790 // show/display UI for changing timezone
791 target.appendChild(tzSelectFragment);
792 }
793
794
795 /* ...................................................................... */
796 /* List of timezones for timezone selection menu */
797
798 /**
799 * Generate list of timezones for creating timezone select UI
800 *
801 * @returns {Object[]} list of e.g. { value: '+0100', descr: 'GMT+01:00' }
802 */
803 function generateTZList() {
804 var timezones = [
805 { value: "utc", descr: "UTC/GMT"},
806 { value: "local", descr: "Local (per browser)"}
807 ];
808
809 // generate all full hour timezones (no fractional timezones)
810 for (var x = -12, idx = timezones.length; x <= +14; x++, idx++) {
811 var hours = (x >= 0 ? '+' : '-') + padLeft(x >=0 ? x : -x, 2);
812 timezones[idx] = { value: hours + '00', descr: 'UTC' + hours + ':00'};
813 if (x === 0) {
814 timezones[idx].descr = 'UTC\u00B100:00'; // 'UTC&plusmn;00:00'
815 }
816 }
817
818 return timezones;
819 }
820
821 /**
822 * Generate <options> elements for timezone select UI
823 *
824 * @param {String} tzSelected: default timezone
825 * @returns {DocumentFragment} list of options elements to appendChild
826 */
827 function generateTZOptions(tzSelected) {
828 var elems = document.createDocumentFragment();
829 var timezones = generateTZList();
830
831 for (var i = 0, len = timezones.length; i < len; i++) {
832 var tzone = timezones[i];
833 var option = document.createElement("option");
834 if (tzone.value === tzSelected) {
835 option.defaultSelected = true;
836 }
837 option.value = tzone.value;
838 option.appendChild(document.createTextNode(tzone.descr));
839
840 elems.appendChild(option);
841 }
842
843 return elems;
844 }
845
846
847 /* ...................................................................... */
848 /* Event handlers and/or their generators */
849
850 /**
851 * Create event handler that select timezone and closes timezone select UI.
852 * To be used as $('select[name="tzselect"]').onchange handler.
853 *
854 * @param {DocumentFragment} tzSelectFragment: timezone selection UI
855 * @param {Object} tzCookieInfo: object literal with info about cookie to store timezone
856 * @param {String} tzCookieInfo.name: name of cookie to save result of selection
857 * @param {String} tzClassName: specifies element where UI was installed
858 * @returns {Function} event handler
859 */
860 function selectTZHandler(tzSelectFragment, tzCookieInfo, tzClassName) {
861 //return function selectTZ(event) {
862 return function (event) {
863 event = event || window.event;
864 var target = event.target || event.srcElement;
865
866 var selected = target.options.item(target.selectedIndex);
867 removeChangeTZForm(tzSelectFragment, target, tzClassName);
868
869 if (selected) {
870 selected.defaultSelected = true;
871 setCookie(tzCookieInfo.name, selected.value, tzCookieInfo);
872 fixDatetimeTZ(selected.value, tzClassName);
873 }
874 };
875 }
876
877 /**
878 * Create event handler that closes timezone select UI.
879 * To be used e.g. as $('.closebutton').onclick handler.
880 *
881 * @param {DocumentFragment} tzSelectFragment: timezone selection UI
882 * @param {String} tzClassName: specifies element where UI was installed
883 * @returns {Function} event handler
884 */
885 function closeTZFormHandler(tzSelectFragment, tzClassName) {
886 //return function closeTZForm(event) {
887 return function (event) {
888 event = event || window.event;
889 var target = event.target || event.srcElement;
890
891 removeChangeTZForm(tzSelectFragment, target, tzClassName);
892 };
893 }
894
895 /* end of adjust-timezone.js */
896 // Copyright (C) 2007, Fredrik Kuivinen <frekui@gmail.com>
897 // 2007, Petr Baudis <pasky@suse.cz>
898 // 2008-2011, Jakub Narebski <jnareb@gmail.com>
899
900 /**
901 * @fileOverview JavaScript side of Ajax-y 'blame_incremental' view in gitweb
902 * @license GPLv2 or later
903 */
904
905 /* ============================================================ */
906 /*
907 * This code uses DOM methods instead of (nonstandard) innerHTML
908 * to modify page.
909 *
910 * innerHTML is non-standard IE extension, though supported by most
911 * browsers; however Firefox up to version 1.5 didn't implement it in
912 * a strict mode (application/xml+xhtml mimetype).
913 *
914 * Also my simple benchmarks show that using elem.firstChild.data =
915 * 'content' is slightly faster than elem.innerHTML = 'content'. It
916 * is however more fragile (text element fragment must exists), and
917 * less feature-rich (we cannot add HTML).
918 *
919 * Note that DOM 2 HTML is preferred over generic DOM 2 Core; the
920 * equivalent using DOM 2 Core is usually shown in comments.
921 */
922
923
924 /* ............................................................ */
925 /* utility/helper functions (and variables) */
926
927 var projectUrl; // partial query + separator ('?' or ';')
928
929 // 'commits' is an associative map. It maps SHA1s to Commit objects.
930 var commits = {};
931
932 /**
933 * constructor for Commit objects, used in 'blame'
934 * @class Represents a blamed commit
935 * @param {String} sha1: SHA-1 identifier of a commit
936 */
937 function Commit(sha1) {
938 if (this instanceof Commit) {
939 this.sha1 = sha1;
940 this.nprevious = 0; /* number of 'previous', effective parents */
941 } else {
942 return new Commit(sha1);
943 }
944 }
945
946 /* ............................................................ */
947 /* progress info, timing, error reporting */
948
949 var blamedLines = 0;
950 var totalLines = '???';
951 var div_progress_bar;
952 var div_progress_info;
953
954 /**
955 * Detects how many lines does a blamed file have,
956 * This information is used in progress info
957 *
958 * @returns {Number|String} Number of lines in file, or string '...'
959 */
960 function countLines() {
961 var table =
962 document.getElementById('blame_table') ||
963 document.getElementsByTagName('table')[0];
964
965 if (table) {
966 return table.getElementsByTagName('tr').length - 1; // for header
967 } else {
968 return '...';
969 }
970 }
971
972 /**
973 * update progress info and length (width) of progress bar
974 *
975 * @globals div_progress_info, div_progress_bar, blamedLines, totalLines
976 */
977 function updateProgressInfo() {
978 if (!div_progress_info) {
979 div_progress_info = document.getElementById('progress_info');
980 }
981 if (!div_progress_bar) {
982 div_progress_bar = document.getElementById('progress_bar');
983 }
984 if (!div_progress_info && !div_progress_bar) {
985 return;
986 }
987
988 var percentage = Math.floor(100.0*blamedLines/totalLines);
989
990 if (div_progress_info) {
991 div_progress_info.firstChild.data = blamedLines + ' / ' + totalLines +
992 ' (' + padLeftStr(percentage, 3, '\u00A0') + '%)';
993 }
994
995 if (div_progress_bar) {
996 //div_progress_bar.setAttribute('style', 'width: '+percentage+'%;');
997 div_progress_bar.style.width = percentage + '%';
998 }
999 }
1000
1001
1002 var t_interval_server = '';
1003 var cmds_server = '';
1004 var t0 = new Date();
1005
1006 /**
1007 * write how much it took to generate data, and to run script
1008 *
1009 * @globals t0, t_interval_server, cmds_server
1010 */
1011 function writeTimeInterval() {
1012 var info_time = document.getElementById('generating_time');
1013 if (!info_time || !t_interval_server) {
1014 return;
1015 }
1016 var t1 = new Date();
1017 info_time.firstChild.data += ' + (' +
1018 t_interval_server + ' sec server blame_data / ' +
1019 (t1.getTime() - t0.getTime())/1000 + ' sec client JavaScript)';
1020
1021 var info_cmds = document.getElementById('generating_cmd');
1022 if (!info_time || !cmds_server) {
1023 return;
1024 }
1025 info_cmds.firstChild.data += ' + ' + cmds_server;
1026 }
1027
1028 /**
1029 * show an error message alert to user within page (in progress info area)
1030 * @param {String} str: plain text error message (no HTML)
1031 *
1032 * @globals div_progress_info
1033 */
1034 function errorInfo(str) {
1035 if (!div_progress_info) {
1036 div_progress_info = document.getElementById('progress_info');
1037 }
1038 if (div_progress_info) {
1039 div_progress_info.className = 'error';
1040 div_progress_info.firstChild.data = str;
1041 }
1042 }
1043
1044 /* ............................................................ */
1045 /* coloring rows during blame_data (git blame --incremental) run */
1046
1047 /**
1048 * used to extract N from 'colorN', where N is a number,
1049 * @constant
1050 */
1051 var colorRe = /\bcolor([0-9]*)\b/;
1052
1053 /**
1054 * return N if <tr class="colorN">, otherwise return null
1055 * (some browsers require CSS class names to begin with letter)
1056 *
1057 * @param {HTMLElement} tr: table row element to check
1058 * @param {String} tr.className: 'class' attribute of tr element
1059 * @returns {Number|null} N if tr.className == 'colorN', otherwise null
1060 *
1061 * @globals colorRe
1062 */
1063 function getColorNo(tr) {
1064 if (!tr) {
1065 return null;
1066 }
1067 var className = tr.className;
1068 if (className) {
1069 var match = colorRe.exec(className);
1070 if (match) {
1071 return parseInt(match[1], 10);
1072 }
1073 }
1074 return null;
1075 }
1076
1077 var colorsFreq = [0, 0, 0];
1078 /**
1079 * return one of given possible colors (currently least used one)
1080 * example: chooseColorNoFrom(2, 3) returns 2 or 3
1081 *
1082 * @param {Number[]} arguments: one or more numbers
1083 * assumes that 1 <= arguments[i] <= colorsFreq.length
1084 * @returns {Number} Least used color number from arguments
1085 * @globals colorsFreq
1086 */
1087 function chooseColorNoFrom() {
1088 // choose the color which is least used
1089 var colorNo = arguments[0];
1090 for (var i = 1; i < arguments.length; i++) {
1091 if (colorsFreq[arguments[i]-1] < colorsFreq[colorNo-1]) {
1092 colorNo = arguments[i];
1093 }
1094 }
1095 colorsFreq[colorNo-1]++;
1096 return colorNo;
1097 }
1098
1099 /**
1100 * given two neighbor <tr> elements, find color which would be different
1101 * from color of both of neighbors; used to 3-color blame table
1102 *
1103 * @param {HTMLElement} tr_prev
1104 * @param {HTMLElement} tr_next
1105 * @returns {Number} color number N such that
1106 * colorN != tr_prev.className && colorN != tr_next.className
1107 */
1108 function findColorNo(tr_prev, tr_next) {
1109 var color_prev = getColorNo(tr_prev);
1110 var color_next = getColorNo(tr_next);
1111
1112
1113 // neither of neighbors has color set
1114 // THEN we can use any of 3 possible colors
1115 if (!color_prev && !color_next) {
1116 return chooseColorNoFrom(1,2,3);
1117 }
1118
1119 // either both neighbors have the same color,
1120 // or only one of neighbors have color set
1121 // THEN we can use any color except given
1122 var color;
1123 if (color_prev === color_next) {
1124 color = color_prev; // = color_next;
1125 } else if (!color_prev) {
1126 color = color_next;
1127 } else if (!color_next) {
1128 color = color_prev;
1129 }
1130 if (color) {
1131 return chooseColorNoFrom((color % 3) + 1, ((color+1) % 3) + 1);
1132 }
1133
1134 // neighbors have different colors
1135 // THEN there is only one color left
1136 return (3 - ((color_prev + color_next) % 3));
1137 }
1138
1139 /* ............................................................ */
1140 /* coloring rows like 'blame' after 'blame_data' finishes */
1141
1142 /**
1143 * returns true if given row element (tr) is first in commit group
1144 * to be used only after 'blame_data' finishes (after processing)
1145 *
1146 * @param {HTMLElement} tr: table row
1147 * @returns {Boolean} true if TR is first in commit group
1148 */
1149 function isStartOfGroup(tr) {
1150 return tr.firstChild.className === 'sha1';
1151 }
1152
1153 /**
1154 * change colors to use zebra coloring (2 colors) instead of 3 colors
1155 * concatenate neighbor commit groups belonging to the same commit
1156 *
1157 * @globals colorRe
1158 */
1159 function fixColorsAndGroups() {
1160 var colorClasses = ['light', 'dark'];
1161 var linenum = 1;
1162 var tr, prev_group;
1163 var colorClass = 0;
1164 var table =
1165 document.getElementById('blame_table') ||
1166 document.getElementsByTagName('table')[0];
1167
1168 while ((tr = document.getElementById('l'+linenum))) {
1169 // index origin is 0, which is table header; start from 1
1170 //while ((tr = table.rows[linenum])) { // <- it is slower
1171 if (isStartOfGroup(tr, linenum, document)) {
1172 if (prev_group &&
1173 prev_group.firstChild.firstChild.href ===
1174 tr.firstChild.firstChild.href) {
1175 // we have to concatenate groups
1176 var prev_rows = prev_group.firstChild.rowSpan || 1;
1177 var curr_rows = tr.firstChild.rowSpan || 1;
1178 prev_group.firstChild.rowSpan = prev_rows + curr_rows;
1179 //tr.removeChild(tr.firstChild);
1180 tr.deleteCell(0); // DOM2 HTML way
1181 } else {
1182 colorClass = (colorClass + 1) % 2;
1183 prev_group = tr;
1184 }
1185 }
1186 var tr_class = tr.className;
1187 tr.className = tr_class.replace(colorRe, colorClasses[colorClass]);
1188 linenum++;
1189 }
1190 }
1191
1192
1193 /* ============================================================ */
1194 /* main part: parsing response */
1195
1196 /**
1197 * Function called for each blame entry, as soon as it finishes.
1198 * It updates page via DOM manipulation, adding sha1 info, etc.
1199 *
1200 * @param {Commit} commit: blamed commit
1201 * @param {Object} group: object representing group of lines,
1202 * which blame the same commit (blame entry)
1203 *
1204 * @globals blamedLines
1205 */
1206 function handleLine(commit, group) {
1207 /*
1208 This is the structure of the HTML fragment we are working
1209 with:
1210
1211 <tr id="l123" class="">
1212 <td class="sha1" title=""><a href=""> </a></td>
1213 <td class="linenr"><a class="linenr" href="">123</a></td>
1214 <td class="pre"># times (my ext3 doesn&#39;t).</td>
1215 </tr>
1216 */
1217
1218 var resline = group.resline;
1219
1220 // format date and time string only once per commit
1221 if (!commit.info) {
1222 /* e.g. 'Kay Sievers, 2005-08-07 21:49:46 +0200' */
1223 commit.info = commit.author + ', ' +
1224 formatDateISOLocal(commit.authorTime, commit.authorTimezone);
1225 }
1226
1227 // color depends on group of lines, not only on blamed commit
1228 var colorNo = findColorNo(
1229 document.getElementById('l'+(resline-1)),
1230 document.getElementById('l'+(resline+group.numlines))
1231 );
1232
1233 // loop over lines in commit group
1234 for (var i = 0; i < group.numlines; i++, resline++) {
1235 var tr = document.getElementById('l'+resline);
1236 if (!tr) {
1237 break;
1238 }
1239 /*
1240 <tr id="l123" class="">
1241 <td class="sha1" title=""><a href=""> </a></td>
1242 <td class="linenr"><a class="linenr" href="">123</a></td>
1243 <td class="pre"># times (my ext3 doesn&#39;t).</td>
1244 </tr>
1245 */
1246 var td_sha1 = tr.firstChild;
1247 var a_sha1 = td_sha1.firstChild;
1248 var a_linenr = td_sha1.nextSibling.firstChild;
1249
1250 /* <tr id="l123" class=""> */
1251 var tr_class = '';
1252 if (colorNo !== null) {
1253 tr_class = 'color'+colorNo;
1254 }
1255 if (commit.boundary) {
1256 tr_class += ' boundary';
1257 }
1258 if (commit.nprevious === 0) {
1259 tr_class += ' no-previous';
1260 } else if (commit.nprevious > 1) {
1261 tr_class += ' multiple-previous';
1262 }
1263 tr.className = tr_class;
1264
1265 /* <td class="sha1" title="?" rowspan="?"><a href="?">?</a></td> */
1266 if (i === 0) {
1267 td_sha1.title = commit.info;
1268 td_sha1.rowSpan = group.numlines;
1269
1270 a_sha1.href = projectUrl + 'a=commit;h=' + commit.sha1;
1271 if (a_sha1.firstChild) {
1272 a_sha1.firstChild.data = commit.sha1.substr(0, 8);
1273 } else {
1274 a_sha1.appendChild(
1275 document.createTextNode(commit.sha1.substr(0, 8)));
1276 }
1277 if (group.numlines >= 2) {
1278 var fragment = document.createDocumentFragment();
1279 var br = document.createElement("br");
1280 var match = commit.author.match(/\b([A-Z])\B/g);
1281 if (match) {
1282 var text = document.createTextNode(
1283 match.join(''));
1284 }
1285 if (br && text) {
1286 var elem = fragment || td_sha1;
1287 elem.appendChild(br);
1288 elem.appendChild(text);
1289 if (fragment) {
1290 td_sha1.appendChild(fragment);
1291 }
1292 }
1293 }
1294 } else {
1295 //tr.removeChild(td_sha1); // DOM2 Core way
1296 tr.deleteCell(0); // DOM2 HTML way
1297 }
1298
1299 /* <td class="linenr"><a class="linenr" href="?">123</a></td> */
1300 var linenr_commit =
1301 ('previous' in commit ? commit.previous : commit.sha1);
1302 var linenr_filename =
1303 ('file_parent' in commit ? commit.file_parent : commit.filename);
1304 a_linenr.href = projectUrl + 'a=blame_incremental' +
1305 ';hb=' + linenr_commit +
1306 ';f=' + encodeURIComponent(linenr_filename) +
1307 '#l' + (group.srcline + i);
1308
1309 blamedLines++;
1310
1311 //updateProgressInfo();
1312 }
1313 }
1314
1315 // ----------------------------------------------------------------------
1316
1317 /**#@+
1318 * @constant
1319 */
1320 var sha1Re = /^([0-9a-f]{40}) ([0-9]+) ([0-9]+) ([0-9]+)/;
1321 var infoRe = /^([a-z-]+) ?(.*)/;
1322 var endRe = /^END ?([^ ]*) ?(.*)/;
1323 /**@-*/
1324
1325 var curCommit = new Commit();
1326 var curGroup = {};
1327
1328 /**
1329 * Parse output from 'git blame --incremental [...]', received via
1330 * XMLHttpRequest from server (blamedataUrl), and call handleLine
1331 * (which updates page) as soon as blame entry is completed.
1332 *
1333 * @param {String[]} lines: new complete lines from blamedata server
1334 *
1335 * @globals commits, curCommit, curGroup, t_interval_server, cmds_server
1336 * @globals sha1Re, infoRe, endRe
1337 */
1338 function processBlameLines(lines) {
1339 var match;
1340
1341 for (var i = 0, len = lines.length; i < len; i++) {
1342
1343 if ((match = sha1Re.exec(lines[i]))) {
1344 var sha1 = match[1];
1345 var srcline = parseInt(match[2], 10);
1346 var resline = parseInt(match[3], 10);
1347 var numlines = parseInt(match[4], 10);
1348
1349 var c = commits[sha1];
1350 if (!c) {
1351 c = new Commit(sha1);
1352 commits[sha1] = c;
1353 }
1354 curCommit = c;
1355
1356 curGroup.srcline = srcline;
1357 curGroup.resline = resline;
1358 curGroup.numlines = numlines;
1359
1360 } else if ((match = infoRe.exec(lines[i]))) {
1361 var info = match[1];
1362 var data = match[2];
1363 switch (info) {
1364 case 'filename':
1365 curCommit.filename = unquote(data);
1366 // 'filename' information terminates the entry
1367 handleLine(curCommit, curGroup);
1368 updateProgressInfo();
1369 break;
1370 case 'author':
1371 curCommit.author = data;
1372 break;
1373 case 'author-time':
1374 curCommit.authorTime = parseInt(data, 10);
1375 break;
1376 case 'author-tz':
1377 curCommit.authorTimezone = data;
1378 break;
1379 case 'previous':
1380 curCommit.nprevious++;
1381 // store only first 'previous' header
1382 if (!('previous' in curCommit)) {
1383 var parts = data.split(' ', 2);
1384 curCommit.previous = parts[0];
1385 curCommit.file_parent = unquote(parts[1]);
1386 }
1387 break;
1388 case 'boundary':
1389 curCommit.boundary = true;
1390 break;
1391 } // end switch
1392
1393 } else if ((match = endRe.exec(lines[i]))) {
1394 t_interval_server = match[1];
1395 cmds_server = match[2];
1396
1397 } else if (lines[i] !== '') {
1398 // malformed line
1399
1400 } // end if (match)
1401
1402 } // end for (lines)
1403 }
1404
1405 /**
1406 * Process new data and return pointer to end of processed part
1407 *
1408 * @param {String} unprocessed: new data (from nextReadPos)
1409 * @param {Number} nextReadPos: end of last processed data
1410 * @return {Number} end of processed data (new value for nextReadPos)
1411 */
1412 function processData(unprocessed, nextReadPos) {
1413 var lastLineEnd = unprocessed.lastIndexOf('\n');
1414 if (lastLineEnd !== -1) {
1415 var lines = unprocessed.substring(0, lastLineEnd).split('\n');
1416 nextReadPos += lastLineEnd + 1 /* 1 == '\n'.length */;
1417
1418 processBlameLines(lines);
1419 } // end if
1420
1421 return nextReadPos;
1422 }
1423
1424 /**
1425 * Handle XMLHttpRequest errors
1426 *
1427 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
1428 * @param {Number} [xhr.pollTimer] ID of the timeout to clear
1429 *
1430 * @globals commits
1431 */
1432 function handleError(xhr) {
1433 errorInfo('Server error: ' +
1434 xhr.status + ' - ' + (xhr.statusText || 'Error contacting server'));
1435
1436 if (typeof xhr.pollTimer === "number") {
1437 clearTimeout(xhr.pollTimer);
1438 delete xhr.pollTimer;
1439 }
1440 commits = {}; // free memory
1441 }
1442
1443 /**
1444 * Called after XMLHttpRequest finishes (loads)
1445 *
1446 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
1447 * @param {Number} [xhr.pollTimer] ID of the timeout to clear
1448 *
1449 * @globals commits
1450 */
1451 function responseLoaded(xhr) {
1452 if (typeof xhr.pollTimer === "number") {
1453 clearTimeout(xhr.pollTimer);
1454 delete xhr.pollTimer;
1455 }
1456
1457 fixColorsAndGroups();
1458 writeTimeInterval();
1459 commits = {}; // free memory
1460 }
1461
1462 /**
1463 * handler for XMLHttpRequest onreadystatechange event
1464 * @see startBlame
1465 *
1466 * @param {XMLHttpRequest} xhr: XMLHttpRequest object
1467 * @param {Number} xhr.prevDataLength: previous value of xhr.responseText.length
1468 * @param {Number} xhr.nextReadPos: start of unread part of xhr.responseText
1469 * @param {Number} [xhr.pollTimer] ID of the timeout (to reset or cancel)
1470 * @param {Boolean} fromTimer: if handler was called from timer
1471 */
1472 function handleResponse(xhr, fromTimer) {
1473
1474 /*
1475 * xhr.readyState
1476 *
1477 * Value Constant (W3C) Description
1478 * -------------------------------------------------------------------
1479 * 0 UNSENT open() has not been called yet.
1480 * 1 OPENED send() has not been called yet.
1481 * 2 HEADERS_RECEIVED send() has been called, and headers
1482 * and status are available.
1483 * 3 LOADING Downloading; responseText holds partial data.
1484 * 4 DONE The operation is complete.
1485 */
1486
1487 if (xhr.readyState !== 4 && xhr.readyState !== 3) {
1488 return;
1489 }
1490
1491 // the server returned error
1492 // try ... catch block is to work around bug in IE8
1493 try {
1494 if (xhr.readyState === 3 && xhr.status !== 200) {
1495 return;
1496 }
1497 } catch (e) {
1498 return;
1499 }
1500 if (xhr.readyState === 4 && xhr.status !== 200) {
1501 handleError(xhr);
1502 return;
1503 }
1504
1505 // In konqueror xhr.responseText is sometimes null here...
1506 if (xhr.responseText === null) {
1507 return;
1508 }
1509
1510
1511 // extract new whole (complete) lines, and process them
1512 if (xhr.prevDataLength !== xhr.responseText.length) {
1513 xhr.prevDataLength = xhr.responseText.length;
1514 var unprocessed = xhr.responseText.substring(xhr.nextReadPos);
1515 xhr.nextReadPos = processData(unprocessed, xhr.nextReadPos);
1516 }
1517
1518 // did we finish work?
1519 if (xhr.readyState === 4) {
1520 responseLoaded(xhr);
1521 return;
1522 }
1523
1524 // if we get from timer, we have to restart it
1525 // otherwise onreadystatechange gives us partial response, timer not needed
1526 if (fromTimer) {
1527 setTimeout(function () {
1528 handleResponse(xhr, true);
1529 }, 1000);
1530
1531 } else if (typeof xhr.pollTimer === "number") {
1532 clearTimeout(xhr.pollTimer);
1533 delete xhr.pollTimer;
1534 }
1535 }
1536
1537 // ============================================================
1538 // ------------------------------------------------------------
1539
1540 /**
1541 * Incrementally update line data in blame_incremental view in gitweb.
1542 *
1543 * @param {String} blamedataUrl: URL to server script generating blame data.
1544 * @param {String} bUrl: partial URL to project, used to generate links.
1545 *
1546 * Called from 'blame_incremental' view after loading table with
1547 * file contents, a base for blame view.
1548 *
1549 * @globals t0, projectUrl, div_progress_bar, totalLines
1550 */
1551 function startBlame(blamedataUrl, bUrl) {
1552
1553 var xhr = createRequestObject();
1554 if (!xhr) {
1555 errorInfo('ERROR: XMLHttpRequest not supported');
1556 return;
1557 }
1558
1559 t0 = new Date();
1560 projectUrl = bUrl + (bUrl.indexOf('?') === -1 ? '?' : ';');
1561 if ((div_progress_bar = document.getElementById('progress_bar'))) {
1562 //div_progress_bar.setAttribute('style', 'width: 100%;');
1563 div_progress_bar.style.cssText = 'width: 100%;';
1564 }
1565 totalLines = countLines();
1566 updateProgressInfo();
1567
1568 /* add extra properties to xhr object to help processing response */
1569 xhr.prevDataLength = -1; // used to detect if we have new data
1570 xhr.nextReadPos = 0; // where unread part of response starts
1571
1572 xhr.onreadystatechange = function () {
1573 handleResponse(xhr, false);
1574 };
1575
1576 xhr.open('GET', blamedataUrl);
1577 xhr.setRequestHeader('Accept', 'text/plain');
1578 xhr.send(null);
1579
1580 // not all browsers call onreadystatechange event on each server flush
1581 // poll response using timer every second to handle this issue
1582 xhr.pollTimer = setTimeout(function () {
1583 handleResponse(xhr, true);
1584 }, 1000);
1585 }
1586
1587 /* end of blame_incremental.js */
This page took 0.557734 seconds and 5 git commands to generate.