-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathview.js
663 lines (578 loc) · 17.3 KB
/
view.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
/******************************************************************************
* view.js *
* Copyright 2012 *
* For details about the copyright holders, see the COPYRIGHT file. *
* This software is freely distributed under the ISC License. *
* For details about the license, see the LICENSE file. *
******************************************************************************/
var CodeReview = (function( CodeReview ) {
var comments_div,
highlight_start = -1,
highlight_end = -1,
selection_start = -1,
selection_end = -1,
comment_ob = null,
comment_box_ob = null,
selection_ob = null,
num_lines = -1,
comments = {},
language_data = null,
codeArea = null,
diffArea = null,
mergeArea = null,
noSelect = false,
codeOptions = null,
diffOptions = null,
commentOptions = null,
commentAreas = [],
diffComputer = new diff_match_patch(),
appliedDiffs = [];
var codeId = null;
CodeReview.codeArea = undefined;
/******************************************************************************
* Utility Functions *
******************************************************************************/
function modulo(n,m) {
while(n < 0)
n += m;
return n%m;
}
function logError(text) {
console.log('ERROR: ' + text);
}
function reportError(text) {
logError(text);
$('#error').text(text).show();
}
function handleAjaxError(jqXHR, textStatus, errorThrown) {
reportError(errorThrown);
}
function include(filename) {
if(filename.indexOf('.js') != -1) {
$('<script>').attr('src',filename).appendTo($('head'));
} else if(filename.indexOf('.css') != -1) {
$('<link>')
.attr('rel','stylesheet')
.attr('href',filename)
.appendTo($('head'));
} else {
logError('failed to include file: '+filename);
}
}
function resolveRequirements(languages,language,requirements,req_list){
var lang = languages[language];
var requires = lang.requires;
if(requires){
for(var requirement in requires){
var name = requires[requirement];
if(!requirements[name]){
requirements[name] = true;
resolveRequirements(languages,name,requirements,req_list);
req_list.push(name);
}
}
}
}
// taken from
// http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
var expires = "";
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
document.cookie = name+"="+value+expires+"; path=/";
}
// taken from
// http://www.quirksmode.org/js/cookies.html
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0)
return c.substring(nameEQ.length,c.length);
}
return null;
}
/******************************************************************************
* Data retrieval *
******************************************************************************/
function getCode(id,success_fn,error_fn) {
$.ajax('/do/code',{
data: {id:id},
dataType: 'json',
error: error_fn,
success: success_fn
});
}
function getComments(id,success_fn,error_fn) {
$.ajax('/do/comments',{
data: {code_id:id},
dataType: 'json',
error: error_fn,
success: success_fn
});
}
function getLanguage(id,success_fn,error_fn) {
$.ajax('/do/language',{
data: {id:id},
dataType: 'json',
error: error_fn,
success: success_fn
});
}
function getLanguageData(success_fn,error_fn) {
$.ajax('languages.json',{
dataType: 'json',
error: error_fn,
success: success_fn
});
}
/******************************************************************************
* Highlighting *
******************************************************************************/
function handleSelection(){
if(!noSelect){
if(somethingSelected(codeArea)){
var lines = getSelectedLines(codeArea);
var top = getPositionOfLine(codeArea,lines.start);
$('#comment-new').css("top", top);
hideComments();
showCommentBox(lines.start+1,lines.end+1);
}else{
closeCommentBox();
}
}
}
function setSelection(event){
var startLine = event.data.startLine-1;
var endLine = event.data.endLine;
noSelect = true;
setSelectedLines(codeArea,startLine,endLine);
noSelect = false;
}
function clearCodeSelection(event){
clearSelection(codeArea);
}
/******************************************************************************
* Comment Input *
******************************************************************************/
function showCommentBox(start,end) {
selection_start = start;
selection_end = end;
$('input#line-start').val(start);
$('input#line-end').val(end);
$('#line-start-num').text(start);
$('#line-end-num').text(end);
setFirstLineNumber(diffArea,start);
var text = getTextOnLines(codeArea,start,end);
setText(diffArea,text);
$('#comment-new').slideDown();
}
function closeCommentBox() {
$('#comment-new').hide();
selection_start = -1;
selection_end = -1;
}
/******************************************************************************
* Comment Display *
******************************************************************************/
function writeComments(comments_ob) {
if((typeof comments_ob) === "string"){
comments_ob = jQuery.parseJSON(comments_ob);
}
buildCommentStructure(comments_ob);
}
function buildCommentStructure(comments_ob) {
var comments_list = comments_ob.comments;
for(var index in comments_list) {
var comment = comments_list[index];
var line_start = comment.line_start;
if(comments[line_start] === undefined)
comments[line_start] = [];
comments[line_start].push(comment);
}
for(var i in comments){
buildCommentSet(Number(i),comments[i]);
}
}
function buildCommentSet(lineNumber,commentSet) {
if(codeArea == null) {
logError('Tried to build comment set while codeArea null');
return;
}
commentAreas[lineNumber] = [];
var commentInfo = $("#comment-info");
var commentInfoBtn = $("<button class='commentButton'>");
commentInfoBtn.text(commentSet.length+" comments");
commentInfoBtn.css("position","absolute");
var top = getPositionOfLine(codeArea,lineNumber-1);
commentInfoBtn.css("top",top);
commentInfoBtn.click(lineNumber,showComments);
commentInfoBtn.attr("lineNumber",lineNumber-1);
commentInfo.append(commentInfoBtn);
var set = $("<div class='comment-set'>");
set.attr("lineNumber",lineNumber);
var rawDiffsList = {};
for(var i=0;i<commentSet.length;i++){
var comment = commentSet[i];
var commentDiv = $("<div class='comment-box'>");
commentDiv.mouseover({startLine:comment.line_start,
endLine:comment.line_end},setSelection);
commentDiv.mouseout(clearCodeSelection);
var title = $("<div class='comment-title'>");
title.text(comment.user);
var body = $("<div class='comment-body'>");
body.text(comment.text);
commentDiv.append(title);
commentDiv.append(body);
set.append(commentDiv);
if(comment.diffs){
var diffTextArea = $("<textarea class='comment-diffs'>");
var originalText = getTextOnLines(codeArea,
comment.line_start, comment.line_end);
var newText = comment.diffs.replace(/\r/gm,'');
if(originalText != newText){
var rawDiffs = computeDiffs(originalText,newText);
rawDiffs.range = getRangeOfLines(comment.line_start-1,
comment.line_end-1);
var diffs = computeDiffText(rawDiffs);
rawDiffsList[i]=rawDiffs;
commentDiv.append(diffTextArea);
diffTextArea.text(diffs);
var area = createArea(diffTextArea.get(0),commentOptions);
styleDiffArea(area,rawDiffs);
setFirstLineNumber(area,lineNumber);
commentAreas[lineNumber].push(area);
var useIt = $("<input type='checkbox'>");
useIt.attr("value",i);
useIt.click(function(){
var diffNum = $(this).attr("value");
if($(this).is(":checked")){
appliedDiffs.push(rawDiffsList[diffNum]);
}else{
appliedDiffs.splice(
appliedDiffs.indexOf(rawDiffsList[diffNum]),1);
}
})
commentDiv.append($("<label>Use this diff </label>"));
commentDiv.append(useIt);
}
}
}
$("#comment-view").append(set);
set.hide();
}
function showComments(event){
var lineNumber = event.data;
closeCommentBox();
hideComments();
discardMerge();
var top = getPositionOfLine(codeArea,lineNumber-1);
var set = $(".comment-set[lineNumber='"+lineNumber+"']");
set.css('top',$(event.target).css("top"));
set.slideDown(400,function(){
var areas = commentAreas[lineNumber];
for(var index in areas){
reRender(areas[index]);
}
});
}
function hideComments(){
$(".comment-set").hide();
}
/*********************
* TextArea Utilities *
*********************/
function createArea(area,options){
return CodeMirror.fromTextArea(area,options);
}
function getSelectedLines(area){
var result = {};
result.start = area.getCursor(true).line;
result.end = area.getCursor(false).line;
if(area.getCursor(false).ch==0){
result.end--;
}
return result;
}
function setSelectedLines(area,startLine,endLine){
area.setSelection({line:startLine,ch:0},{line:endLine,ch:0});
}
function clearSelection(area){
area.setSelection({line:0},{line:0});
}
function somethingSelected(area){
return area.somethingSelected();
}
function getPositionOfLine(area,line){
var pos = getPositionOfLineAbsolute(area,line);
var parent = $(area.getTextArea()).parent();
if(parent.position()){
pos-=parent.position().top;
}
return pos;
}
function getPositionOfLineAbsolute(area,line){
return area.charCoords({line:line,ch:0},"page").y;
}
function setFirstLineNumber(area,number){
area.setOption("firstLineNumber",number);
}
function getText(area){
return area.getValue();
}
function setText(area,text){
area.setValue(text);
area.refresh();
}
function getTextOnLines(area,startLine,endLine){
return area.getRange(
{line:startLine-1,ch:0},
{line:endLine-1,ch:999999});
}
function setTextOnLines(area,startLine,endLine,text){
area.replaceRange(text,startLine,endLine);
}
function getTextOnRange(area,range){
return area.getRange(
{line:range.start-1,ch:0},
{line:range.end-1,ch:999999});
}
function setTextOnRange(area,range,text){
area.replaceRange(text,range.start,range.end);
}
function getRangeOfLines(startLine,endLine){
var range = {};
range.start = {line:startLine,ch:0};
range.end = {line:endLine,ch:999999};
return range;
}
function getPosFromIndex(area,index){
var pos = area.posFromIndex(index);
if(pos.ch==0 && pos.line!=0){
pos.line--;
pos.ch=999999;
}
return pos;
}
function styleText(area,startPos,endPos,style){
area.markText(startPos,endPos,style);
}
function reRender(area){
area.refresh();
}
function saveChanges(area){
area.save();
}
function comparePositions(a,b){
return b.range.start.line-a.range.start.line;
}
/********************
* Merging/Diffs *
********************/
function forkCode(){
var codeToSubmit;
var parent = codeId;
if(mergeArea){
codeToSubmit = getText(mergeArea);
}else{
codeToSubmit = getText(codeArea);
}
//submit code with POST somehow
}
function computeMerge(){
if(!mergeArea){
var area = $("<textarea>");
$("#merge-output").append(area);
mergeArea = createArea(area.get(0),codeOptions);
}
setText(mergeArea,getText(codeArea));
appliedDiffs.sort(comparePositions);
for(var i in appliedDiffs){
var diffSet = appliedDiffs[i];
var result = "";
for(var j=0; j<diffSet.length; j++){
var diff = diffSet[j];
var type = diff[0];
var text = diff[1];
if(type!=-1){
result+=text;
}
}
setTextOnRange(mergeArea,diffSet.range,result);
}
reRender(mergeArea);
hideComments();
closeCommentBox();
$("#merge-discard-button").show();
}
function discardMerge(){
$("#merge-output").empty();
$("#merge-discard-button").hide();
mergeArea = null;
}
function computeDiffs(originalText,newText){
var rawDiffs = diffComputer.diff_main(originalText,newText);
diffComputer.diff_cleanupSemantic(rawDiffs);
return rawDiffs;
}
function computeDiffText(rawDiffs){
var str = "";
for(var index = 0; index<rawDiffs.length; index++){
var diff = rawDiffs[index];
str+=diff[1];
}
return str;
}
function styleDiffArea(area,rawDiffs){
var curIndex = 0;
var curPos = getPosFromIndex(area,curIndex);
for(var index = 0; index<rawDiffs.length; index++){
var diff = rawDiffs[index];
var type = diff[0];
var text = diff[1];
var newIndex = curIndex+text.length;
var newPos = getPosFromIndex(area,newIndex);
styleText(area,curPos,newPos,"diffStyle_"+type);
curIndex = newIndex;
curPos = newPos;
}
}
/******************************************************************************
* Code Display *
******************************************************************************/
function writeCodeLines(code) {
if(code === null) return;
if((typeof code) === "string"){
code = jQuery.parseJSON(code);
}
codeId = code.id;
$('#code-id').val(code.id);
var lines = code.text.split('\n');
num_lines = lines.length;
$("#code-view").text(code.text);
if(!codeArea){
getLanguage(code.language_id,function(language_ob) {
var language = language_data.data[language_ob.mode];
var req_ob = {};
var requirements = [];
resolveRequirements(language_data.data,
language_ob.mode,
req_ob,
requirements);
if(req_ob[language_ob.mode] === undefined)
requirements.push(language_ob.mode);
for(var index in requirements) {
var lang = requirements[index];
var file = language_data.data[lang].file;
if(file !== undefined) {
include(language_data.include_path+file);
}
}
//codeOptions, diffOptions, commentOptions are globals
codeOptions = {
lineNumbers: true,
lineWrapping: true,
fixedGutter: true,
readOnly: true,
mode: language.mode,
onCursorActivity: handleSelection
};
diffOptions = {
lineNumbers: true,
lineWrapping: true,
fixedGutter: true,
readOnly: false,
smartIndent:false,
mode: language.mode
};
commentOptions = {
lineNumbers: true,
lineWrapping: true,
fixedGutter: true,
readOnly: true,
mode: language.mode
};
for(var index in language.options) {
diffOptions[index] =
codeOptions[index] =
commentOptions[index] = language.options[index];
}
codeArea = createArea(
document.getElementById("code-view"),codeOptions);
diffArea = createArea(
document.getElementById("diffs"),diffOptions);
// TODO: Make the code appear in the minimap
getComments(code.id,writeComments,handleAjaxError);
setTimeout(rustleMyJimmmies,1000);
},handleAjaxError);
}else{
comments = [];
$(".comment-set").remove();
getComments(code.id,writeComments,handleAjaxError);
}
}
function rustleMyJimmmies(){ //cludge to try to fix code mirror issues
console.log("rustling all the jimmies");
reRender(codeArea);
reRender(diffArea);
for(var lineNumber in commentAreas){
var areaList = commentAreas[lineNumber];
for(var i=0;i<areaList.length;i++){
reRender(areaList[i]);
}
}
$(".commentButton").each(function(){
var btn = $(this);
var top_line = getPositionOfLine(codeArea,
Number(btn.attr("lineNumber")));
btn.css("top",top_line);
});
}
/******************************************************************************
* Run when display ready *
******************************************************************************/
$(document).ready(function() {
var userName = readCookie('username');
if(userName !== null) {
$('#user').val(userName);
}
$('#user').change(function() {
createCookie('username',$('#user').val());
});
$('#comment-new').hide();
$('#error').hide();
// retrieve and display code
var query = URI(document.URL).query(true);
if(query.error != undefined) {
reportError(query.error);
}
if(query.id === undefined) {
reportError("Code ID not found");
return;
}
$('#comment-form').ajaxForm({
beforeSerialize: function() {
saveChanges(diffArea);
},
success:function(){
getCode(query.id,writeCodeLines,handleAjaxError);
$('#text').val('');
closeCommentBox();
},
error:handleAjaxError
});
$('#merge-compute-button').click(computeMerge);
$('#merge-discard-button').click(discardMerge).hide();
$('#fork-code-button').click(forkCode);
getLanguageData(function(language_ob) {
language_data = language_ob;
getCode(query.id,writeCodeLines,handleAjaxError);
},handleAjaxError);
});
return CodeReview;
})( CodeReview || {});