1 // Copyright (C) 2010 Adam Barth. All rights reserved.
3 // Redistribution and use in source and binary forms, with or without
4 // modification, are permitted provided that the following conditions are met:
6 // 1. Redistributions of source code must retain the above copyright notice,
7 // this list of conditions and the following disclaimer.
9 // 2. Redistributions in binary form must reproduce the above copyright notice,
10 // this list of conditions and the following disclaimer in the documentation
11 // and/or other materials provided with the distribution.
13 // THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS "AS IS" AND ANY
14 // EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
15 // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 // DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS BE LIABLE FOR
17 // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
18 // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
20 // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
21 // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
22 // OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
27 * Create a new function with some of its arguements
29 * Taken from goog.partial in the Closure library.
30 * @param {Function} fn A function to partially apply.
31 * @param {...*} var_args Additional arguments that are partially
33 * @return {!Function} A partially-applied form of the function.
35 function partial(fn, var_args) {
36 var args = Array.prototype.slice.call(arguments, 1);
38 // Prepend the bound arguments to the current arguments.
39 var newArgs = Array.prototype.slice.call(arguments);
40 newArgs.unshift.apply(newArgs, args);
41 return fn.apply(this, newArgs);
45 function determineAttachmentID() {
47 return /id=(\d+)/.exec(window.location.search)[1]
53 // Attempt to activate only in the "Review Patch" context.
54 if (window.top != window)
56 if (!window.location.search.match(/action=review/))
58 var attachment_id = determineAttachmentID();
64 var original_file_contents = {};
65 var patched_file_contents = {};
66 var WEBKIT_BASE_DIR = "http://svn.webkit.org/repository/webkit/trunk/";
67 var SIDE_BY_SIDE_DIFFS_KEY = 'sidebysidediffs';
69 function idForLine(number) {
70 return 'line' + number;
73 function nextLineID() {
74 return idForLine(next_line_id++);
77 function forEachLine(callback) {
78 for (var i = 0; i < next_line_id; ++i) {
79 callback($('#' + idForLine(i)));
84 this.id = nextLineID();
87 function containerify() {
88 $(this).addClass('LineContainer');
92 $(this).hover(function() {
93 $(this).addClass('hot');
96 $(this).removeClass('hot');
100 function diffSectionFrom(line) {
101 return line.parents('.FileDiff');
104 function activeCommentFor(line) {
105 // Scope to the diffSection as a performance improvement.
106 return $('textarea[data-comment-for~="' + line[0].id + '"]', diffSectionFrom(line));
109 function previousCommentsFor(line) {
110 // Scope to the diffSection as a performance improvement.
111 return $('div[data-comment-for~="' + line[0].id + '"].previousComment', diffSectionFrom(line));
114 function findCommentPositionFor(line) {
115 var previous_comments = previousCommentsFor(line);
116 var num_previous_comments = previous_comments.size();
117 if (num_previous_comments)
118 return $(previous_comments[num_previous_comments - 1])
122 function findCommentBlockFor(line) {
123 var comment_block = findCommentPositionFor(line).next();
124 if (!comment_block.hasClass('comment'))
126 return comment_block;
129 function insertCommentFor(line, block) {
130 findCommentPositionFor(line).after(block);
133 function addCommentFor(line) {
134 if (line.attr('data-has-comment')) {
135 // FIXME: This query is overly complex because we place comment blocks
136 // after Lines. Instead, comment blocks should be children of Lines.
137 findCommentPositionFor(line).next().next().filter('.frozenComment').each(unfreezeComment);
140 line.attr('data-has-comment', 'true');
141 line.addClass('commentContext');
143 var comment_block = $('<div class="comment"><textarea data-comment-for="' + line.attr('id') + '"></textarea><div class="actions"><button class="ok">OK</button><button class="discard">Discard</button></div></div>');
144 insertCommentFor(line, comment_block);
145 comment_block.hide().slideDown('fast', function() {
146 $(this).children('textarea').focus();
150 function addCommentField() {
151 var id = $(this).attr('data-comment-for');
154 addCommentFor($('#' + id));
157 function addPreviousComment(line, author, comment_text) {
158 var line_id = line.attr('id');
159 var comment_block = $('<div data-comment-for="' + line_id + '" class="previousComment"></div>');
160 var author_block = $('<div class="author"></div>').text(author + ':');
161 var text_block = $('<div class="content"></div>').text(comment_text);
162 comment_block.append(author_block).append(text_block).each(hoverify).click(addCommentField);
163 addDataCommentBaseLine(line, line_id);
164 insertCommentFor(line, comment_block);
167 function displayPreviousComments(comments) {
168 for (var i = 0; i < comments.length; ++i) {
169 var author = comments[i].author;
170 var file_name = comments[i].file_name;
171 var line_number = comments[i].line_number;
172 var comment_text = comments[i].comment_text;
174 var file = files[file_name];
176 var query = '.Line .to';
177 if (line_number[0] == '-') {
178 // The line_number represent a removal. We need to adjust the query to
179 // look at the "from" lines.
180 query = '.Line .from';
181 // Trim off the '-' control character.
182 line_number = line_number.substr(1);
185 $(file).find(query).each(function() {
186 if ($(this).text() != line_number)
188 var line = $(this).parent();
189 addPreviousComment(line, author, comment_text);
192 if (comments.length == 0)
194 descriptor = comments.length + ' comment';
195 if (comments.length > 1)
197 $('#message .commentStatus').text('This patch has ' + descriptor + '. Scroll through them with the "n" and "p" keys.');
200 function scanForComments(author, text) {
202 var lines = text.split('\n');
203 for (var i = 0; i < lines.length; ++i) {
204 var parts = lines[i].match(/^([> ]+)([^:]+):(-?\d+)$/);
207 var quote_markers = parts[1];
208 var file_name = parts[2];
209 // FIXME: Store multiple lines for multiline comments and correctly import them here.
210 var line_number = parts[3];
211 if (!file_name in files)
213 while (i < lines.length && lines[i].length > 0 && lines[i][0] == '>')
215 var comment_lines = [];
216 while (i < lines.length && (lines[i].length == 0 || lines[i][0] != '>')) {
217 comment_lines.push(lines[i]);
220 --i; // Decrement i because the for loop will increment it again in a second.
221 var comment_text = comment_lines.join('\n').trim();
224 'file_name': file_name,
225 'line_number': line_number,
226 'comment_text': comment_text
232 function isReviewFlag(select) {
233 return $(select).attr('title') == 'Request for patch review.';
236 function isCommitQueueFlag(select) {
237 return $(select).attr('title').match(/commit-queue/);
240 function findControlForFlag(select) {
241 if (isReviewFlag(select))
242 return $('#toolbar .review select');
243 else if (isCommitQueueFlag(select))
244 return $('#toolbar .commitQueue select');
248 function addFlagsForAttachment(details) {
249 var flag_control = "<select><option></option><option>?</option><option>+</option><option>-</option></select>";
250 $('#flagContainer').append(
251 $('<span class="review"> r: ' + flag_control + '</span>')).append(
252 $('<span class="commitQueue"> cq: ' + flag_control + '</span>'));
254 details.find('#flags select').each(function() {
255 var requestee = $(this).parent().siblings('td:first-child').text().trim();
256 if (requestee.length) {
257 // Remove trailing ':'.
258 requestee = requestee.substr(0, requestee.length - 1);
259 requestee = ' (' + requestee + ')';
261 var control = findControlForFlag(this)
262 control.attr('selectedIndex', $(this).attr('selectedIndex'));
263 control.parent().prepend(requestee);
267 window.addEventListener('message', function(e) {
268 if (e.origin != 'https://webkit-commit-queue.appspot.com')
272 $('.statusBubble')[0].style.height = e.data.height;
273 $('.statusBubble')[0].style.width = e.data.width;
277 function handleStatusBubbleLoad(e) {
278 e.target.contentWindow.postMessage('containerMetrics', 'https://webkit-commit-queue.appspot.com');
281 function fetchHistory() {
282 $.get('attachment.cgi?id=' + attachment_id + '&action=edit', function(data) {
283 var bug_id = /Attachment \d+ Details for Bug (\d+)/.exec(data)[1];
284 $.get('show_bug.cgi?id=' + bug_id, function(data) {
286 $(data).find('.bz_comment').each(function() {
287 var author = $(this).find('.email').text();
288 var text = $(this).find('.bz_comment_text').text();
289 var comment_marker = '(From update of attachment ' + attachment_id + ' .details.)';
290 if (text.match(comment_marker))
291 $.merge(comments, scanForComments(author, text));
293 displayPreviousComments(comments);
296 var details = $(data);
297 addFlagsForAttachment(details);
299 var statusBubble = document.createElement('iframe');
300 statusBubble.className = 'statusBubble';
301 statusBubble.src = 'https://webkit-commit-queue.appspot.com/status-bubble/' + attachment_id;
302 statusBubble.scrolling = 'no';
303 // Can't append the HTML because we need to set the onload handler before appending the iframe to the DOM.
304 statusBubble.onload = handleStatusBubbleLoad;
305 $('#statusBubbleContainer').append(statusBubble);
307 $('#toolbar .bugLink').html('<a href="/show_bug.cgi?id=' + bug_id + '" target="_blank">Bug ' + bug_id + '</a>');
311 function crawlDiff() {
312 $('.Line').each(idify).each(hoverify).each(containerify);
313 $('.FileDiff').each(function() {
314 var file_name = $(this).children('h1').text();
315 files[file_name] = this;
316 addExpandLinks(file_name);
317 $('h1', this).before('<div class="FileDiffLinkContainer">' + diffLinksHtml() + '</div>');
318 updateDiffLinkVisibility(this);
322 function addExpandLinks(file_name) {
323 if (file_name.indexOf('ChangeLog') != -1)
326 var file_diff = files[file_name];
328 // Don't show the links to expand upwards/downwards if the patch starts/ends without context
329 // lines, i.e. starts/ends with add/remove lines.
330 var first_line = file_diff.querySelector('.LineContainer');
332 // If there is no element with a "Line" class, then this is an image diff.
336 $('.context', file_diff).detach();
338 var expand_bar_index = 0;
339 if (!$(first_line).hasClass('add') && !$(first_line).hasClass('remove'))
340 $('h1', file_diff).after(expandBarHtml(file_name, BELOW))
342 $('br').replaceWith(expandBarHtml(file_name));
344 var last_line = file_diff.querySelector('.LineContainer:last-of-type');
345 // Some patches for new files somehow end up with an empty context line at the end
346 // with a from line number of 0. Don't show expand links in that case either.
347 if (!$(last_line).hasClass('add') && !$(last_line).hasClass('remove') && fromLineNumber(last_line) != 0)
348 $(file_diff).append(expandBarHtml(file_name, ABOVE));
351 function expandBarHtml(file_name, opt_direction) {
352 var html = '<div class="ExpandBar">' +
353 '<pre class="ExpandArea Expand' + ABOVE + '"></pre>' +
354 '<div class="ExpandLinkContainer LinkContainer"><span class="ExpandText">expand: </span>';
356 // FIXME: If there are <100 line to expand, don't show the expand-100 link.
357 // If there are <20 lines to expand, don't show the expand-20 link.
358 if (!opt_direction || opt_direction == ABOVE) {
359 html += expandLinkHtml(ABOVE, 100) +
360 expandLinkHtml(ABOVE, 20);
363 html += expandLinkHtml(ALL);
365 if (!opt_direction || opt_direction == BELOW) {
366 html += expandLinkHtml(BELOW, 20) +
367 expandLinkHtml(BELOW, 100);
370 html += '</div><pre class="ExpandArea Expand' + BELOW + '"></pre></div>';
374 function expandLinkHtml(direction, amount) {
375 return "<a class='ExpandLink' href='javascript:' data-direction='" + direction + "' data-amount='" + amount + "'>" +
376 (amount ? amount + " " : "") + direction + "</a>";
379 function handleExpandLinkClick() {
380 var expand_bar = $(this).parents('.ExpandBar');
381 var file_name = expand_bar.parents('.FileDiff').children('h1')[0].textContent;
382 var expand_function = partial(expand, expand_bar[0], file_name, this.getAttribute('data-direction'), Number(this.getAttribute('data-amount')));
383 if (file_name in original_file_contents)
386 getWebKitSourceFile(file_name, expand_function, expand_bar);
389 function handleSideBySideLinkClick() {
390 convertDiff('sidebyside', this);
393 function handleUnifyLinkClick() {
394 convertDiff('unified', this);
397 function convertDiff(difftype, convert_link) {
398 var file_diffs = $(convert_link).parents('.FileDiff');
399 if (!file_diffs.size()) {
400 localStorage.setItem('code-review-diffstate', difftype);
401 file_diffs = $('.FileDiff');
404 convertAllFileDiffs(difftype, file_diffs);
407 function getWebKitSourceFile(file_name, onLoad, expand_bar) {
408 function handleLoad(contents) {
409 original_file_contents[file_name] = contents.split('\n');
410 patched_file_contents[file_name] = applyDiff(original_file_contents[file_name], file_name);
415 url: WEBKIT_BASE_DIR + file_name,
416 context: document.body,
417 complete: function(xhr, data) {
419 handleLoadError(expand_bar);
421 handleLoad(xhr.responseText);
426 function replaceExpandLinkContainers(expand_bar, text) {
427 $('.ExpandLinkContainer', $(expand_bar).parents('.FileDiff')).replaceWith('<span class="ExpandText">' + text + '</span>');
430 function handleLoadError(expand_bar) {
431 // FIXME: In this case, try fetching the source file at the revision the patch was created at,
432 // in case the file has bee deleted.
433 // Might need to modify webkit-patch to include that data in the diff.
434 replaceExpandLinkContainers(expand_bar, "Can't expand. Is this a new or deleted file?");
441 function expand(expand_bar, file_name, direction, amount) {
442 if (file_name in original_file_contents && !patched_file_contents[file_name]) {
443 // FIXME: In this case, try fetching the source file at the revision the patch was created at.
444 // Might need to modify webkit-patch to include that data in the diff.
445 replaceExpandLinkContainers(expand_bar, "Can't expand. Unable to apply patch to tip of tree.");
449 var above_expansion = expand_bar.querySelector('.Expand' + ABOVE)
450 var below_expansion = expand_bar.querySelector('.Expand' + BELOW)
452 var above_last_line = above_expansion.querySelector('.ExpansionLine:last-of-type');
453 if (!above_last_line) {
454 var diff_section = expand_bar.previousElementSibling;
455 above_last_line = diff_section.querySelector('.LineContainer:last-of-type');
458 var above_last_line_num, above_last_from_line_num;
459 if (above_last_line) {
460 above_last_line_num = toLineNumber(above_last_line);
461 above_last_from_line_num = fromLineNumber(above_last_line);
463 above_last_from_line_num = above_last_line_num = 0;
465 var below_first_line = below_expansion.querySelector('.ExpansionLine');
466 if (!below_first_line) {
467 var diff_section = expand_bar.nextElementSibling;
469 below_first_line = diff_section.querySelector('.LineContainer');
472 var below_first_line_num, below_first_from_line_num;
473 if (below_first_line) {
474 below_first_line_num = toLineNumber(below_first_line) - 1;
475 below_first_from_line_num = fromLineNumber(below_first_line) - 1;
477 below_first_from_line_num = below_first_line_num = patched_file_contents[file_name].length - 1;
479 var start_line_num, start_from_line_num;
482 if (direction == ABOVE) {
483 start_from_line_num = above_last_from_line_num;
484 start_line_num = above_last_line_num;
485 end_line_num = Math.min(start_line_num + amount, below_first_line_num);
486 } else if (direction == BELOW) {
487 end_line_num = below_first_line_num;
488 start_line_num = Math.max(end_line_num - amount, above_last_line_num)
489 start_from_line_num = Math.max(below_first_from_line_num - amount, above_last_from_line_num)
490 } else { // direction == ALL
491 start_line_num = above_last_line_num;
492 start_from_line_num = above_last_from_line_num;
493 end_line_num = below_first_line_num;
497 // Filling in all the remaining lines. Overwrite the expand links.
498 if (start_line_num == above_last_line_num && end_line_num == below_first_line_num) {
499 expansion_area = expand_bar.querySelector('.ExpandLinkContainer');
500 expansion_area.innerHTML = '';
502 expansion_area = direction == ABOVE ? above_expansion : below_expansion;
505 insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num);
508 function unifiedLine(from, to, contents, is_expansion_line, opt_className, opt_attributes) {
509 var className = is_expansion_line ? 'ExpansionLine' : 'LineContainer Line';
511 className += ' ' + opt_className;
513 var lineNumberClassName = is_expansion_line ? 'expansionLineNumber' : 'lineNumber';
515 var line = $('<div class="' + className + '" ' + (opt_attributes || '') + '>' +
516 '<span class="from ' + lineNumberClassName + '">' + (from || ' ') +
517 '</span><span class="to ' + lineNumberClassName + '">' + (to || ' ') +
518 '</span> <span class="text"></span>' +
521 $('.text', line).replaceWith(contents);
525 function unifiedExpansionLine(line_number, contents) {
526 return unifiedLine(line_number, line_number, contents, true);
529 function sideBySideExpansionLine(line_number, contents) {
530 var line = $('<div class="ExpansionLine"></div>');
531 line.append(lineSide('from', contents, true, line_number));
532 line.append(lineSide('to', contents, true, line_number));
536 function lineSide(side, contents, is_expansion_line, opt_line_number, opt_attributes, opt_class) {
538 if (opt_attributes || opt_class) {
539 class_name = 'class="';
541 class_name += is_expansion_line ? 'ExpansionLine' : 'Line';
542 class_name += ' ' + (opt_class || '') + '"';
545 var attributes = opt_attributes || '';
547 var line_side = $('<div class="LineSide">' +
548 '<div ' + attributes + ' ' + class_name + '>' +
549 '<span class="' + side + ' ' + (is_expansion_line ? 'expansionLineNumber' : 'lineNumber') + '">' +
550 (opt_line_number || ' ') +
552 '<span class="text"></span>' +
556 $('.text', line_side).replaceWith(contents);
560 function insertLines(file_name, expansion_area, direction, start_line_num, end_line_num, start_from_line_num) {
561 var fragment = document.createDocumentFragment();
562 var is_side_by_side = isDiffSideBySide(files[file_name]);
564 for (var i = 0; i < end_line_num - start_line_num; i++) {
565 // FIXME: from line numbers are wrong
566 var line_number = start_from_line_num + i + 1;
567 var contents = patched_file_contents[file_name][start_line_num + i];
568 var line = is_side_by_side ? sideBySideExpansionLine(line_number, contents) : unifiedExpansionLine(line_number, contents);
569 fragment.appendChild(line[0]);
572 if (direction == BELOW)
573 expansion_area.insertBefore(fragment, expansion_area.firstChild);
575 expansion_area.appendChild(fragment);
578 function hunkStartingLine(patched_file, context, prev_line, hunk_num) {
580 var current_line = -1;
581 var last_context_line = context[context.length - 1];
582 if (patched_file[prev_line] == last_context_line)
583 current_line = prev_line + 1;
585 for (var i = prev_line - PATCH_FUZZ; i < prev_line + PATCH_FUZZ; i++) {
586 if (patched_file[i] == last_context_line)
587 current_line = i + 1;
590 if (current_line == -1) {
591 console.log('Hunk #' + hunk_num + ' FAILED.');
596 // For paranoia sake, confirm the rest of the context matches;
597 for (var i = 0; i < context.length - 1; i++) {
598 if (patched_file[current_line - context.length + i] != context[i]) {
599 console.log('Hunk #' + hunk_num + ' FAILED. Did not match preceding context.');
607 function fromLineNumber(line) {
608 var node = line.querySelector('.from');
609 return node ? Number(node.textContent) : 0;
612 function toLineNumber(line) {
613 var node = line.querySelector('.to');
614 return node ? Number(node.textContent) : 0;
617 function textContentsFor(line) {
618 // Just get the first match since a side-by-side diff has two lines with text inside them for
619 // unmodified lines in the diff.
620 return $('.text', line).first().text();
623 function lineNumberForFirstNonContextLine(patched_file, line, prev_line, context, hunk_num) {
624 if (context.length) {
625 var prev_line_num = fromLineNumber(prev_line) - 1;
626 return hunkStartingLine(patched_file, context, prev_line_num, hunk_num);
629 if (toLineNumber(line) == 1 || fromLineNumber(line) == 1)
632 console.log('Failed to apply patch. Adds or removes lines before any context lines.');
636 function applyDiff(original_file, file_name) {
637 var diff_sections = files[file_name].getElementsByClassName('DiffSection');
638 var patched_file = original_file.concat([]);
640 // Apply diffs in reverse order to avoid needing to keep track of changing line numbers.
641 for (var i = diff_sections.length - 1; i >= 0; i--) {
642 var section = diff_sections[i];
643 var lines = section.getElementsByClassName('Line');
644 var current_line = -1;
646 var hunk_num = i + 1;
648 for (var j = 0, lines_len = lines.length; j < lines_len; j++) {
650 var line_contents = textContentsFor(line);
651 if ($(line).hasClass('add')) {
652 if (current_line == -1) {
653 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
654 if (current_line == -1)
658 patched_file.splice(current_line, 0, line_contents);
660 } else if ($(line).hasClass('remove')) {
661 if (current_line == -1) {
662 current_line = lineNumberForFirstNonContextLine(patched_file, line, lines[j-1], context, hunk_num);
663 if (current_line == -1)
667 if (patched_file[current_line] != line_contents) {
668 console.log('Hunk #' + hunk_num + ' FAILED.');
672 patched_file.splice(current_line, 1);
673 } else if (current_line == -1) {
674 context.push(line_contents);
675 } else if (line_contents != patched_file[current_line]) {
676 console.log('Hunk #' + hunk_num + ' FAILED. Context at end did not match');
687 function openOverallComments(e) {
688 $('.overallComments textarea').addClass('open');
689 $('#statusBubbleContainer').addClass('wrap');
692 function onBodyResize() {
693 updateToolbarAnchorState();
696 function updateToolbarAnchorState() {
697 var has_scrollbar = window.innerWidth > document.documentElement.offsetWidth;
698 $('#toolbar').toggleClass('anchored', has_scrollbar);
701 function diffLinksHtml(opt_containerClassName) {
702 var containerClassName = opt_containerClassName || '';
703 return '<div class="DiffLinks ' + containerClassName + '">' +
704 '<a href="javascript:" class="unify-link">unified</a>' +
705 '<a href="javascript:" class="side-by-side-link">side-by-side</a>' +
709 $(document).ready(function() {
712 $(document.body).prepend('<div id="message">' +
713 '<div class="help">Select line numbers to add a comment.' +
714 diffLinksHtml('LinkContainer') +
716 '<div class="commentStatus"></div>' +
718 $(document.body).append('<div id="toolbar">' +
719 '<div class="overallComments">' +
720 '<textarea placeholder="Overall comments"></textarea>' +
723 '<span id="statusBubbleContainer"></span>' +
724 '<span class="actions">' +
725 '<span class="links"><span class="bugLink"></span></span>' +
726 '<span id="flagContainer"></span>' +
727 '<button id="preview_comments">Preview</button>' +
728 '<button id="post_comments">Publish</button> ' +
733 $('.overallComments textarea').bind('click', openOverallComments);
735 $(document.body).prepend('<div id="comment_form" class="inactive"><div class="winter"></div><div class="lightbox"><iframe id="reviewform" src="attachment.cgi?id=' + attachment_id + '&action=reviewform"></iframe></div></div>');
737 // Create a dummy iframe and monitor resizes in it's contentWindow to detect when the top document's body changes size.
738 // FIXME: Should we setTimeout throttle these?
739 var resize_iframe = $('<iframe class="pseudo_resize_event_iframe"></iframe>');
740 $(document.body).append(resize_iframe);
741 $(resize_iframe[0].contentWindow).bind('resize', onBodyResize);
743 updateToolbarAnchorState();
747 function loadDiffState() {
748 var diffstate = localStorage.getItem('code-review-diffstate');
749 if (diffstate != 'sidebyside' && diffstate != 'unified')
752 convertAllFileDiffs(diffstate, $('.FileDiff'));
755 function isDiffSideBySide(file_diff) {
756 return diffState(file_diff) == 'sidebyside';
759 function diffState(file_diff) {
760 var diff_state = $(file_diff).attr('data-diffstate');
761 return diff_state || 'unified';
764 function unifyLine(line, from, to, contents, classNames, attributes, id) {
765 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
766 var old_line = $(line);
767 if (!old_line.hasClass('LineContainer'))
768 old_line = old_line.parents('.LineContainer');
770 var comments = commentsToTransferFor($(document.getElementById(id)));
771 old_line.after(comments);
772 old_line.replaceWith(new_line);
775 function updateDiffLinkVisibility(file_diff) {
776 if (diffState(file_diff) == 'unified') {
777 $('.side-by-side-link', file_diff).show();
778 $('.unify-link', file_diff).hide();
780 $('.side-by-side-link', file_diff).hide();
781 $('.unify-link', file_diff).show();
785 function convertAllFileDiffs(diff_type, file_diffs) {
786 file_diffs.each(function() {
787 convertFileDiff(diff_type, this);
791 function convertFileDiff(diff_type, file_diff) {
792 if (diffState(file_diff) == diff_type)
795 $(file_diff).attr('data-diffstate', diff_type);
796 updateDiffLinkVisibility(file_diff);
798 $('.Line', file_diff).each(function() {
799 convertLine(diff_type, this);
802 $('.ExpansionLine', file_diff).each(function() {
803 convertExpansionLine(diff_type, this);
807 function convertLine(diff_type, line) {
808 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
809 var from = fromLineNumber(line);
810 var to = toLineNumber(line);
811 var contents = $('.text', line);
812 var classNames = classNamesForMovingLine(line);
813 var attributes = attributesForMovingLine(line);
815 convert_function(line, from, to, contents, classNames, attributes, id)
818 function classNamesForMovingLine(line) {
819 var classParts = line.className.split(' ');
820 var classBuffer = [];
821 for (var i = 0; i < classParts.length; i++) {
822 var part = classParts[i];
823 if (part != 'LineContainer' && part != 'Line')
824 classBuffer.push(part);
826 return classBuffer.join(' ');
829 function attributesForMovingLine(line) {
830 var attributesBuffer = ['id=' + line.id];
831 // Make sure to keep all data- attributes.
832 $(line.attributes).each(function() {
833 if (this.name.indexOf('data-') == 0)
834 attributesBuffer.push(this.name + '=' + this.value);
836 return attributesBuffer.join(' ');
839 // FIXME: Put removed lines to the left of their corresponding added lines.
840 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
843 var from_attributes = '';
844 var to_attributes = '';
845 var from_contents = contents;
846 var to_contents = contents;
848 if (from && !to) { // This is a remove line.
849 from_class = classNames;
850 from_attributes = attributes;
852 } else if (to && !from) { // This is an add line.
853 to_class = classNames;
854 to_attributes = attributes;
858 var container_class = 'LineContainer';
859 var container_attributes = '';
860 if (!to_attributes && !from_attributes) {
861 container_attributes = attributes;
862 container_class += ' Line ' + classNames;
865 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
866 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
867 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
869 $(line).replaceWith(new_line);
871 var line = $(document.getElementById(id));
872 line.after(commentsToTransferFor(line));
875 function convertExpansionLine(diff_type, line) {
876 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
877 var contents = textContentsFor(line);
878 var line_number = fromLineNumber(line);
879 var new_line = convert_function(line_number, contents);
880 $(line).replaceWith(new_line);
883 function commentsToTransferFor(line) {
884 var fragment = document.createDocumentFragment();
886 previousCommentsFor(line).each(function() {
887 fragment.appendChild(this);
890 var active_comments = activeCommentFor(line);
891 var num_active_comments = active_comments.size();
892 if (num_active_comments > 0) {
893 if (num_active_comments > 1)
894 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
896 var parent = active_comments[0].parentNode;
897 var frozenComment = parent.nextSibling;
898 fragment.appendChild(parent);
899 fragment.appendChild(frozenComment);
905 function discardComment() {
906 var line_id = $(this).parentsUntil('.comment').parent().find('textarea').attr('data-comment-for');
907 var line = $('#' + line_id)
908 findCommentBlockFor(line).slideUp('fast', function() {
910 line.removeAttr('data-has-comment');
911 trimCommentContextToBefore(line);
915 function unfreezeComment() {
916 $(this).prev().show();
920 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
921 $('.unify-link').live('click', handleUnifyLinkClick);
922 $('.ExpandLink').live('click', handleExpandLinkClick);
923 $('.comment .discard').live('click', discardComment);
924 $('.frozenComment').live('click', unfreezeComment);
926 $('.comment .ok').live('click', function() {
927 var comment_textarea = $(this).parentsUntil('.comment').parent().find('textarea');
928 if (comment_textarea.val().trim() == '') {
929 discardComment.call(this);
932 var line_id = comment_textarea.attr('data-comment-for');
933 var line = $('#' + line_id)
934 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
937 function focusOn(comment) {
938 $('.focused').removeClass('focused');
939 if (comment.length == 0)
941 $(document).scrollTop(comment.addClass('focused').position().top - window.innerHeight/2);
944 function focusNextComment() {
945 var comments = $('.previousComment');
946 if (comments.length == 0)
948 var index = comments.index($('.focused'));
949 // Notice that -1 gets mapped to 0.
950 focusOn($(comments.get(index + 1)));
953 function focusPreviousComment() {
954 var comments = $('.previousComment');
955 if (comments.length == 0)
957 var index = comments.index($('.focused'));
959 index = comments.length;
964 focusOn($(comments.get(index - 1)));
967 var kCharCodeForN = 'n'.charCodeAt(0);
968 var kCharCodeForP = 'p'.charCodeAt(0);
970 $('body').live('keypress', function() {
971 // FIXME: There's got to be a better way to avoid seeing these keypress
973 if (event.target.nodeName == 'TEXTAREA')
975 if (event.charCode == kCharCodeForN)
977 else if (event.charCode == kCharCodeForP)
978 focusPreviousComment();
981 function contextLinesFor(line_id) {
982 return $('div[data-comment-base-line~="' + line_id + '"]');
985 function numberFrom(line_id) {
986 return Number(line_id.replace('line', ''));
989 function trimCommentContextToBefore(line) {
990 var base_line_id = line.attr('data-comment-base-line');
991 var line_to_trim_to = numberFrom(line.attr('id'));
992 contextLinesFor(base_line_id).each(function() {
993 var id = $(this).attr('id');
994 if (numberFrom(id) > line_to_trim_to)
997 removeDataCommentBaseLine(this, base_line_id);
998 if (!$(this).attr('data-comment-base-line'))
999 $(this).removeClass('commentContext');
1003 var in_drag_select = false;
1005 function stopDragSelect() {
1006 $('.selected').removeClass('selected');
1007 in_drag_select = false;
1010 function lineOffsetFrom(line, offset) {
1011 var file_diff = line.parents('.FileDiff');
1012 var all_lines = $('.Line', file_diff);
1013 var index = all_lines.index(line);
1014 return $(all_lines[index + offset]);
1017 function previousLineFor(line) {
1018 return lineOffsetFrom(line, -1);
1021 function nextLineFor(line) {
1022 return lineOffsetFrom(line, 1);
1025 $('.lineNumber').live('click', function() {
1026 var line = $(this).parent();
1027 if (line.hasClass('commentContext'))
1028 trimCommentContextToBefore(previousLineFor(line));
1029 }).live('mousedown', function() {
1030 in_drag_select = true;
1031 $(lineFromLineDescendant(this)).addClass('selected');
1032 event.preventDefault();
1035 $('.LineContainer').live('mouseenter', function() {
1036 if (!in_drag_select)
1039 var line = lineFromLineContainer(this);
1040 line.addClass('selected');
1041 }).live('mouseup', function() {
1042 if (!in_drag_select)
1044 var selected = $('.selected');
1045 var should_add_comment = !nextLineFor(selected.last()).hasClass('commentContext');
1046 selected.addClass('commentContext');
1049 if (should_add_comment) {
1050 var last = lineFromLineDescendant(selected.last()[0]);
1051 addCommentFor($(last));
1054 id = nextLineFor(selected.last())[0].getAttribute('data-comment-base-line');
1057 selected.each(function() {
1058 addDataCommentBaseLine(this, id);
1062 function addDataCommentBaseLine(line, id) {
1063 var val = $(line).attr('data-comment-base-line');
1065 var parts = val ? val.split(' ') : [];
1066 for (var i = 0; i < parts.length; i++) {
1072 $(line).attr('data-comment-base-line', parts.join(' '));
1075 function removeDataCommentBaseLine(line, id) {
1076 var val = $(line).attr('data-comment-base-line');
1080 var parts = val.split(' ');
1082 for (var i = 0; i < parts.length; i++) {
1084 newVal.push(parts[i]);
1087 $(line).attr('data-comment-base-line', newVal.join(' '));
1090 function lineFromLineDescendant(descendant) {
1091 while (descendant && !$(descendant).hasClass('Line')) {
1092 descendant = descendant.parentNode;
1097 function lineFromLineContainer(lineContainer) {
1098 var line = $(lineContainer);
1099 if (!line.hasClass('Line'))
1100 line = $('.Line', line);
1104 $('.DiffSection').live('mouseleave', stopDragSelect).live('mouseup', stopDragSelect);
1106 function contextSnippetFor(line, indent) {
1108 contextLinesFor(line.attr('id')).each(function() {
1110 if ($(this).hasClass('add'))
1112 else if ($(this).hasClass('remove'))
1114 snippets.push(indent + action + textContentsFor(this));
1116 return snippets.join('\n');
1119 function fileNameFor(line) {
1120 return line.parentsUntil('.FileDiff').parent().find('h1').text();
1123 function indentFor(depth) {
1124 return (new Array(depth + 1)).join('>') + ' ';
1127 function snippetFor(line, indent) {
1128 var file_name = fileNameFor(line);
1129 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1130 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1133 function quotePreviousComments(comments) {
1134 var quoted_comments = [];
1135 var depth = comments.size();
1136 comments.each(function() {
1137 var indent = indentFor(depth--);
1138 var text = $(this).children('.content').text();
1139 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1141 return quoted_comments.join('\n');
1144 $('#comment_form .winter').live('click', function() {
1145 $('#comment_form').addClass('inactive');
1148 function fillInReviewForm() {
1149 var comments_in_context = []
1150 forEachLine(function(line) {
1151 if (line.attr('data-has-comment') != 'true')
1153 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1156 var previous_comments = previousCommentsFor(line);
1157 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1158 var quoted_comments = quotePreviousComments(previous_comments);
1159 var comment_with_context = [];
1160 comment_with_context.push(snippet);
1161 if (quoted_comments != '')
1162 comment_with_context.push(quoted_comments);
1163 comment_with_context.push('\n' + comment);
1164 comments_in_context.push(comment_with_context.join('\n'));
1166 var comment = $('.overallComments textarea').val().trim();
1169 comment += comments_in_context.join('\n\n');
1170 if (comments_in_context.length > 0)
1171 comment = 'View in context: ' + window.location + '\n\n' + comment;
1172 var review_form = $('#reviewform').contents();
1173 review_form.find('#comment').val(comment);
1174 review_form.find('#flags select').each(function() {
1175 var control = findControlForFlag(this);
1176 if (!control.size())
1178 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1182 $('#preview_comments').live('click', function() {
1184 $('#comment_form').removeClass('inactive');
1187 $('#post_comments').live('click', function() {
1189 $('#reviewform').contents().find('form').submit();