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 file_diffs = $('.FileDiff');
402 file_diffs.each(function() {
403 convertFileDiff(difftype, this);
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();
746 function isDiffSideBySide(file_diff) {
747 return diffState(file_diff) == 'sidebyside';
750 function diffState(file_diff) {
751 var diff_state = $(file_diff).attr('data-diffstate');
752 return diff_state || 'unified';
755 function unifyLine(line, from, to, contents, classNames, attributes, id) {
756 var new_line = unifiedLine(from, to, contents, false, classNames, attributes);
757 var old_line = $(line);
758 if (!old_line.hasClass('LineContainer'))
759 old_line = old_line.parents('.LineContainer');
761 var comments = commentsToTransferFor($(document.getElementById(id)));
762 old_line.after(comments);
763 old_line.replaceWith(new_line);
766 function updateDiffLinkVisibility(file_diff) {
767 if (diffState(file_diff) == 'unified') {
768 $('.side-by-side-link', file_diff).show();
769 $('.unify-link', file_diff).hide();
771 $('.side-by-side-link', file_diff).hide();
772 $('.unify-link', file_diff).show();
776 function convertFileDiff(diff_type, file_diff) {
777 if (diffState(file_diff) == diff_type)
780 $(file_diff).attr('data-diffstate', diff_type);
781 updateDiffLinkVisibility(file_diff);
783 $('.Line', file_diff).each(function() {
784 convertLine(diff_type, this);
787 $('.ExpansionLine', file_diff).each(function() {
788 convertExpansionLine(diff_type, this);
792 function convertLine(diff_type, line) {
793 var convert_function = diff_type == 'sidebyside' ? sideBySideifyLine : unifyLine;
794 var from = fromLineNumber(line);
795 var to = toLineNumber(line);
796 var contents = $('.text', line);
797 var classNames = classNamesForMovingLine(line);
798 var attributes = attributesForMovingLine(line);
800 convert_function(line, from, to, contents, classNames, attributes, id)
803 function classNamesForMovingLine(line) {
804 var classParts = line.className.split(' ');
805 var classBuffer = [];
806 for (var i = 0; i < classParts.length; i++) {
807 var part = classParts[i];
808 if (part != 'LineContainer' && part != 'Line')
809 classBuffer.push(part);
811 return classBuffer.join(' ');
814 function attributesForMovingLine(line) {
815 var attributesBuffer = ['id=' + line.id];
816 // Make sure to keep all data- attributes.
817 $(line.attributes).each(function() {
818 if (this.name.indexOf('data-') == 0)
819 attributesBuffer.push(this.name + '=' + this.value);
821 return attributesBuffer.join(' ');
824 // FIXME: Put removed lines to the left of their corresponding added lines.
825 function sideBySideifyLine(line, from, to, contents, classNames, attributes, id) {
828 var from_attributes = '';
829 var to_attributes = '';
830 var from_contents = contents;
831 var to_contents = contents;
833 if (from && !to) { // This is a remove line.
834 from_class = classNames;
835 from_attributes = attributes;
837 } else if (to && !from) { // This is an add line.
838 to_class = classNames;
839 to_attributes = attributes;
843 var container_class = 'LineContainer';
844 var container_attributes = '';
845 if (!to_attributes && !from_attributes) {
846 container_attributes = attributes;
847 container_class += ' Line ' + classNames;
850 var new_line = $('<div ' + container_attributes + ' class="' + container_class + '"></div>');
851 new_line.append(lineSide('from', from_contents, false, from, from_attributes, from_class));
852 new_line.append(lineSide('to', to_contents, false, to, to_attributes, to_class));
854 $(line).replaceWith(new_line);
856 var line = $(document.getElementById(id));
857 line.after(commentsToTransferFor(line));
860 function convertExpansionLine(diff_type, line) {
861 var convert_function = diff_type == 'sidebyside' ? sideBySideExpansionLine : unifiedExpansionLine;
862 var contents = textContentsFor(line);
863 var line_number = fromLineNumber(line);
864 var new_line = convert_function(line_number, contents);
865 $(line).replaceWith(new_line);
868 function commentsToTransferFor(line) {
869 var fragment = document.createDocumentFragment();
871 previousCommentsFor(line).each(function() {
872 fragment.appendChild(this);
875 var active_comments = activeCommentFor(line);
876 var num_active_comments = active_comments.size();
877 if (num_active_comments > 0) {
878 if (num_active_comments > 1)
879 console.log('ERROR: There is more than one active comment for ' + line.attr('id') + '.');
881 var parent = active_comments[0].parentNode;
882 var frozenComment = parent.nextSibling;
883 fragment.appendChild(parent);
884 fragment.appendChild(frozenComment);
890 function discardComment() {
891 var line_id = $(this).parentsUntil('.comment').parent().find('textarea').attr('data-comment-for');
892 var line = $('#' + line_id)
893 findCommentBlockFor(line).slideUp('fast', function() {
895 line.removeAttr('data-has-comment');
896 trimCommentContextToBefore(line);
900 function unfreezeComment() {
901 $(this).prev().show();
905 $('.side-by-side-link').live('click', handleSideBySideLinkClick);
906 $('.unify-link').live('click', handleUnifyLinkClick);
907 $('.ExpandLink').live('click', handleExpandLinkClick);
908 $('.comment .discard').live('click', discardComment);
909 $('.frozenComment').live('click', unfreezeComment);
911 $('.comment .ok').live('click', function() {
912 var comment_textarea = $(this).parentsUntil('.comment').parent().find('textarea');
913 if (comment_textarea.val().trim() == '') {
914 discardComment.call(this);
917 var line_id = comment_textarea.attr('data-comment-for');
918 var line = $('#' + line_id)
919 findCommentBlockFor(line).hide().after($('<div class="frozenComment"></div>').text(comment_textarea.val()));
922 function focusOn(comment) {
923 $('.focused').removeClass('focused');
924 if (comment.length == 0)
926 $(document).scrollTop(comment.addClass('focused').position().top - window.innerHeight/2);
929 function focusNextComment() {
930 var comments = $('.previousComment');
931 if (comments.length == 0)
933 var index = comments.index($('.focused'));
934 // Notice that -1 gets mapped to 0.
935 focusOn($(comments.get(index + 1)));
938 function focusPreviousComment() {
939 var comments = $('.previousComment');
940 if (comments.length == 0)
942 var index = comments.index($('.focused'));
944 index = comments.length;
949 focusOn($(comments.get(index - 1)));
952 var kCharCodeForN = 'n'.charCodeAt(0);
953 var kCharCodeForP = 'p'.charCodeAt(0);
955 $('body').live('keypress', function() {
956 // FIXME: There's got to be a better way to avoid seeing these keypress
958 if (event.target.nodeName == 'TEXTAREA')
960 if (event.charCode == kCharCodeForN)
962 else if (event.charCode == kCharCodeForP)
963 focusPreviousComment();
966 function contextLinesFor(line_id) {
967 return $('div[data-comment-base-line~="' + line_id + '"]');
970 function numberFrom(line_id) {
971 return Number(line_id.replace('line', ''));
974 function trimCommentContextToBefore(line) {
975 var base_line_id = line.attr('data-comment-base-line');
976 var line_to_trim_to = numberFrom(line.attr('id'));
977 contextLinesFor(base_line_id).each(function() {
978 var id = $(this).attr('id');
979 if (numberFrom(id) > line_to_trim_to)
982 removeDataCommentBaseLine(this, base_line_id);
983 if (!$(this).attr('data-comment-base-line'))
984 $(this).removeClass('commentContext');
988 var in_drag_select = false;
990 function stopDragSelect() {
991 $('.selected').removeClass('selected');
992 in_drag_select = false;
995 function lineOffsetFrom(line, offset) {
996 var file_diff = line.parents('.FileDiff');
997 var all_lines = $('.Line', file_diff);
998 var index = all_lines.index(line);
999 return $(all_lines[index + offset]);
1002 function previousLineFor(line) {
1003 return lineOffsetFrom(line, -1);
1006 function nextLineFor(line) {
1007 return lineOffsetFrom(line, 1);
1010 $('.lineNumber').live('click', function() {
1011 var line = $(this).parent();
1012 if (line.hasClass('commentContext'))
1013 trimCommentContextToBefore(previousLineFor(line));
1014 }).live('mousedown', function() {
1015 in_drag_select = true;
1016 $(lineFromLineDescendant(this)).addClass('selected');
1017 event.preventDefault();
1020 $('.LineContainer').live('mouseenter', function() {
1021 if (!in_drag_select)
1024 var line = lineFromLineContainer(this);
1025 line.addClass('selected');
1026 }).live('mouseup', function() {
1027 if (!in_drag_select)
1029 var selected = $('.selected');
1030 var should_add_comment = !nextLineFor(selected.last()).hasClass('commentContext');
1031 selected.addClass('commentContext');
1034 if (should_add_comment) {
1035 var last = lineFromLineDescendant(selected.last()[0]);
1036 addCommentFor($(last));
1039 id = nextLineFor(selected.last())[0].getAttribute('data-comment-base-line');
1042 selected.each(function() {
1043 addDataCommentBaseLine(this, id);
1047 function addDataCommentBaseLine(line, id) {
1048 var val = $(line).attr('data-comment-base-line');
1050 var parts = val ? val.split(' ') : [];
1051 for (var i = 0; i < parts.length; i++) {
1057 $(line).attr('data-comment-base-line', parts.join(' '));
1060 function removeDataCommentBaseLine(line, id) {
1061 var val = $(line).attr('data-comment-base-line');
1065 var parts = val.split(' ');
1067 for (var i = 0; i < parts.length; i++) {
1069 newVal.push(parts[i]);
1072 $(line).attr('data-comment-base-line', newVal.join(' '));
1075 function lineFromLineDescendant(descendant) {
1076 while (descendant && !$(descendant).hasClass('Line')) {
1077 descendant = descendant.parentNode;
1082 function lineFromLineContainer(lineContainer) {
1083 var line = $(lineContainer);
1084 if (!line.hasClass('Line'))
1085 line = $('.Line', line);
1089 $('.DiffSection').live('mouseleave', stopDragSelect).live('mouseup', stopDragSelect);
1091 function contextSnippetFor(line, indent) {
1093 contextLinesFor(line.attr('id')).each(function() {
1095 if ($(this).hasClass('add'))
1097 else if ($(this).hasClass('remove'))
1099 snippets.push(indent + action + textContentsFor(this));
1101 return snippets.join('\n');
1104 function fileNameFor(line) {
1105 return line.parentsUntil('.FileDiff').parent().find('h1').text();
1108 function indentFor(depth) {
1109 return (new Array(depth + 1)).join('>') + ' ';
1112 function snippetFor(line, indent) {
1113 var file_name = fileNameFor(line);
1114 var line_number = line.hasClass('remove') ? '-' + fromLineNumber(line[0]) : toLineNumber(line[0]);
1115 return indent + file_name + ':' + line_number + '\n' + contextSnippetFor(line, indent);
1118 function quotePreviousComments(comments) {
1119 var quoted_comments = [];
1120 var depth = comments.size();
1121 comments.each(function() {
1122 var indent = indentFor(depth--);
1123 var text = $(this).children('.content').text();
1124 quoted_comments.push(indent + '\n' + indent + text.split('\n').join('\n' + indent));
1126 return quoted_comments.join('\n');
1129 $('#comment_form .winter').live('click', function() {
1130 $('#comment_form').addClass('inactive');
1133 function fillInReviewForm() {
1134 var comments_in_context = []
1135 forEachLine(function(line) {
1136 if (line.attr('data-has-comment') != 'true')
1138 var comment = findCommentBlockFor(line).children('textarea').val().trim();
1141 var previous_comments = previousCommentsFor(line);
1142 var snippet = snippetFor(line, indentFor(previous_comments.size() + 1));
1143 var quoted_comments = quotePreviousComments(previous_comments);
1144 var comment_with_context = [];
1145 comment_with_context.push(snippet);
1146 if (quoted_comments != '')
1147 comment_with_context.push(quoted_comments);
1148 comment_with_context.push('\n' + comment);
1149 comments_in_context.push(comment_with_context.join('\n'));
1151 var comment = $('.overallComments textarea').val().trim();
1154 comment += comments_in_context.join('\n\n');
1155 if (comments_in_context.length > 0)
1156 comment = 'View in context: ' + window.location + '\n\n' + comment;
1157 var review_form = $('#reviewform').contents();
1158 review_form.find('#comment').val(comment);
1159 review_form.find('#flags select').each(function() {
1160 var control = findControlForFlag(this);
1161 if (!control.size())
1163 $(this).attr('selectedIndex', control.attr('selectedIndex'));
1167 $('#preview_comments').live('click', function() {
1169 $('#comment_form').removeClass('inactive');
1172 $('#post_comments').live('click', function() {
1174 $('#reviewform').contents().find('form').submit();