This repository has been archived by the owner on Nov 27, 2018. It is now read-only.
/
application.js
460 lines (385 loc) · 14.8 KB
/
application.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
$(function() {
//spawn a new worker to notify the changes
var diff_worker = new Worker('/public/javascripts/diff_worker.js');
var patch_worker = new Worker('/public/javascripts/patch_worker.js');
//var syntax_highlighting_worker = new Worker('/public/javascripts/syntax_highlighting_worker.js');
var get_editable_content = function(){
editable_content = "";
$("#editable_content").children("li").each(function(i){
editable_content = (editable_content + $(this).text() + "\n");
});
return editable_content
}
function getCursorNode() {
var cursorPos;
if (window.getSelection) {
var selObj = window.getSelection();
//var selRange = selObj.getRangeAt(0);
//cursorPos = findNode(selObj.anchorNode.parentNode.childNodes, selObj.anchorNode) + selObj.anchorOffset;
/* FIXME the following works wrong in Opera when the document is longer than 32767 chars */
if(selObj.anchorNode)
if(selObj.anchorNode.nodeName == "li")
return selObj.anchorNode;
else
return selObj.anchorNode.parentNode;
else
return false;
}
// else if (document.selection) {
// var range = document.selection.createRange();
// var bookmark = range.getBookmark();
// /* FIXME the following works wrong when the document is longer than 65535 chars */
// //cursorPos = bookmark.charCodeAt(2) - 11; /* Undocumented function [3] */
// //alert(cursorPos);
// }
}
var set_editable_content = function(field, content, highlight_color){
if(highlight_color != ""){
content = content.replace(/\[hl\]/g, "<span style='background-color:" + highlight_color + "'>")
content = content.replace(/\[ehl\]/g, "</span>")
}
$.each(content.split("\n"), function(i, val){
//if(val != ""){
editing_line = field.children()[i];
if(editing_line != undefined){
//check the curosr is at current updating line
if(editing_line == getCursorNode()){
//update the whole line if there are changes
if($(val).text() != ""){
// $(editing_line).hide();
// $(editing_line).before("<li>" + val + "</li>");
// $(editing_line).html(val);
}
}
else{
$(editing_line).html(val);
}
}
else {
field.append("<li>" + val + "</li>");
}
// }
})
patching_process_running = false;
}
var set_highlighted_content = function(field, content){
$.each(content.split("\n"), function(i, val){
//if(val != ""){
editing_line = field.children()[i];
if(editing_line != undefined){
//check the curosr is at current updating line
if(editing_line == getCursorNode()){
//update the whole line if there are changes
if($(val).text() != ""){
// $(editing_line).hide();
// $(editing_line).before("<li>" + val + "</li>");
// $(editing_line).html(val);
}
}
else{
$(editing_line).html(val);
}
}
else {
field.append("<li>" + val + "</li>");
}
// }
})
patching_process_running = false;
}
var previous_text = get_editable_content();
diff_worker.onmessage = function(ev){
console.log("received diff")
console.log(ev.data);
// send the diff to server via the open socket
//if(ev.data != "send_snapshot")
//socket.send('{"type": "diff", "message":' + JSON.stringify(ev.data) + '}');
//else
//takeSnapshot();
};
patch_worker.onmessage = function(ev){
patch_user_id = ev.data[0];
changed_content = ev.data[1];
if(changed_content != ""){
set_editable_content($("#editable_content"), changed_content, assigned_colors[patch_user_id]);
previous_text = get_editable_content();
}
}
// patch_worker.onmessage = function(ev){
// changed_content = ev.data;
//
// if(changed_content != ""){
// set_editable_content($("#editable_content"), changed_content, "");
// }
// }
var user_id;
var predefined_colors = ["#FFCFEA", "#E8FF9C", "#FFCC91", "#42C0FF", "#A7FF9E", "#7DEFFF",
"#BABDFF", "#FFD4EB", "#AAFF75", "#FF9EAB", "#DCFF91", "#8088FF"
];
var assigned_colors = {};
var diff_queue = [];
var patching_process_running = false;
var playback_mode = false;
var take_diffs = true;
//Client Socket Methods
// var socket = new WebSocket('ws://localhost:8080');
// socket.onmessage = function(ev){
// received_msg = JSON.parse(ev.data);
// switch(received_msg["channel"]){
// case "initial":
// user_id = received_msg["id"];
// for(var user_index in received_msg["users"]){
// addUser(received_msg["users"][user_index]);
// }
// break;
// case "join":
// if(received_msg["payload"]["user"] != user_id)
// addUser(received_msg["payload"]["user"]);
// break;
// case "chat":
// newChatMessage(received_msg["payload"]["user"], received_msg["payload"]["message"]);
// break;
// case "diff":
// //store the diff in a queue
// diff_queue.push({'user': received_msg["payload"]["user"], 'patch':received_msg["payload"]["message"]})
// break;
// default:
// console.log(received_msg);
// }
// }
// *Sending updates as users type*
var takeDiff = function(){
// when function is fired assign current text in editable area to a variable
current_text = get_editable_content(); //$("#editable_content").text();
// run the diff function with content stored in local storage, and in the current variable (run this in a worker)
change_notifier.postMessage([previous_text, current_text]);
//set the current text as previous text
previous_text = current_text;
};
//take a snapshot of current edit
var takeSnapshot = function(){
socket.send('{"type": "snapshot", "message":' + JSON.stringify(get_editable_content()) + '}');
};
var testSetContent = function(){
set_editable_content($('#editable_content'), 'hello\nim testing this');
}
// *Receiving updates*
var applyPatch = function(uid, patch){
// when function is fired assign current text in editable area to a variable
current_text = get_editable_content(); //$("#editable_content").text();
patch_worker.postMessage([uid, patch, current_text]);
};
var checkForPatches = function(){
if(diff_queue.length > 0 && patching_process_running == false) {
current_patch = diff_queue.shift();
if(!playback_mode && (current_patch["user"] == user_id))
return false;
applyPatch(current_patch["user"], current_patch["patch"]);
patching_process_running = true;
}
}
$("#editable_content").keydown(function(ev){
//don't delete the beyond p
if(ev.keyCode == 8 || ev.keyCode == 46){
var editing_lines = $("#editable_content").children("div").children("p");
if(editing_lines.length == 1 && $(editing_lines[0]).html() == ""){
$(editing_lines[0]).html(" ");
return false;
}
}
});
var stored_lines = {};
var generateUUID = function(){
//get the pad id
var padid = "1";
//get the user id
var userid = "1";
//get the current timestamp (in UTC)
var d = new Date();
var timestamp = $.map([d.getUTCFullYear(), d.getUTCMonth(), d.getUTCDate(),
d.getUTCHours(), d.getUTCMinutes(), d.getUTCSeconds(), d.getUTCMilliseconds()],
function(n, i){
return (n < 10) ? "0"+n : n;
}).join("");
//combine them and generate the UUID
//format: padid_userid_timestamp
return padid + "_" + userid + "_" + timestamp;
};
var applySyntaxHighlighting = function(line){
//get the id of the line
//(jquery confuses the lines when the content changes, we can avoid it by explicitly calling the line id)
var line_id = "#" + $(line).attr("id");
//keep checking whether the line is still edited by user
$(line_id).everyTime(500, function(){
if(window.getSelection){
var selObj = window.getSelection();
var selParent = (selObj.anchorNode && selObj.anchorNode.parentNode);
var thisLine = $(line_id);
//if the line is or its child elements are currently focused;
//done attempt to highlight
if(thisLine[0] == selParent || $.contains(thisLine[0], selParent)){
console.log(selObj);
return false
}
//if the cursor is not on the line;
//apply syntax highlighting;
//stop this timer loop
else {
thisLine.html(prettyPrintOne(thisLine.text()));
$(this).stopTime();
}
}
});
}
var inspectLineChanges = function(i){
//get all lines inside editable area
var editable_lines = $("#editable_content").children("div").children("p");
removed_lines_uuids = [];
//first get the uuids of all the stored lines in to an array
for(var line_uuid in stored_lines){
removed_lines_uuids.push(line_uuid);
}
//iterate throught all lines in the editable area
editable_lines.each(function(i){
//get the uuid of the line
var uuid = $(this).attr('data-uuid');
//is this a newly added line?
//all previously stored lines will have a unique uuid
//when a new line is added browser copies the attributes of the previous line as is
//also a new line could be without a uuid (first line & pasted lines)
if(uuid == undefined || uuid == $(this).prev('p').attr('data-uuid')){
//this is a newly added line
//give it a new id
$(this).attr('id', "line" + editable_lines.length);
//give it a new uuid
new_uuid = generateUUID();
$(this).attr('data-uuid', new_uuid);
//apply syntax highlighting
applySyntaxHighlighting(this);
//store it in the hash
stored_lines[new_uuid] = {"content": $(this).text()}
//send 'add line' message to server
console.log("added line");
console.log(stored_lines[new_uuid]);
}
else {
//check whether this exisiting line was updated
if(stored_lines[uuid].content.length != $(this).text().length ||
stored_lines[uuid].content != $(this).text()){
//send off to diff worker to take the diff and update the server
diff_worker.postMessage([uuid, stored_lines[uuid].content, $(this).text()]);
//update the stored line in hash
stored_lines[uuid] = {"content": $(this).text()}
//re-apply syntax highlighting
applySyntaxHighlighting(this);
}
//uncheck this lines uuid from removed lines array
removed_lines_uuids.splice(removed_lines_uuids.indexOf(uuid), 1);
}
});
//work with deleted lines
if(removed_lines_uuids.length > 0){
//iterate through the stale uuids
$.each(removed_lines_uuids, function(){
//remove the line from hash
delete stored_lines[this];
//send 'remove line' message to server
console.log("removed line" + this);
});
}
}
var workOnDirtyNodes = function(){
$("#editable_content").children("div").children("p").each(function(i){
//add the new element to array
if(dirty_nodes[i] == undefined){
addToDirtyNodes(i, this)
}
//update existing element
else if(dirty_nodes[i].content.length != $(this).text().length ||
dirty_nodes[i].content != $(this).text()){
addToDirtyNodes(i, this)
}
});
}
var addToDirtyNodes = function(index, node){
var node_id = "line"+index;
$(node).attr("id", node_id );
//call highlight function
$("#" + node_id).everyTime(500, function(){
if(window.getSelection){
var selObj = window.getSelection();
var selParent = (selObj.anchorNode && selObj.anchorNode.parentNode);
var thisLine = $("#" + node_id);
if(thisLine[0] == selParent || $.contains(thisLine[0], selParent)){
return false
}
else {
thisLine.html(prettyPrintOne(thisLine.text()));
$(this).stopTime();
}
}
});
//calculate the diff
diff_worker.postMessage([node_id, (dirty_nodes[index] ? dirty_nodes[index].content : ""), $(node).text()]);
//add to array
dirty_nodes[index] = {"id": node_id, "content": $(node).text()}
}
// set an interval to invoke taking diffs (every 500ms)
//window.setInterval(takeDiff, 500);
// periodically check for available patches and apply them
//window.setInterval(checkForPatches, 100);
// periodically send the content for syntax highlighting
//window.setInterval(markAsDirty, 500);
window.setInterval(inspectLineChanges, 500);
var addUser = function(id){
new_user_li = $("<li></li>");
assigned_colors[id] = predefined_colors.pop();
new_user_li.append("<span class='user_color' style='background-color:" + assigned_colors[id] + "; color: " + assigned_colors[id] + "'>.</span>");
new_user_li.append("<span class='user_name'>User-" + id + "</span>");
$("#users_list").append(new_user_li);
}
var play_chat_sound = true;
$("#chat_sound_control").toggle(function(){
$(this).children("img").attr("src", "/images/chat_mute_icon.png");
play_chat_sound = false;
},
function(){
$(this).children("img").attr("src", "/images/chat_sound_icon.png");
play_chat_sound = true;
});
var newChatMessage = function(uid, msg){
chat_user = $("<span class='user' style='color:" + assigned_colors[uid] + "'>User-" + uid + "</span>")
chat_message = $("<span class='message'>" + msg + "</span>");
chat_timestamp = $("<span class='timestamp'>6.53am</span>");
chat_line = $("<li class='chat_message unread'></li>");
chat_line.append(chat_user);
chat_line.append(chat_message);
chat_line.append(chat_timestamp);
$("ul#chat_messages").append(chat_line)
//TODO: set focus on last line added
$(chat_line).scroll();
//TODO: sound doesn't play in chrome
if(play_chat_sound)
$("#chat_alert_sound")[0].play();
}
var doPlayback = function(){
//send a request to get all the diffs available
socket.send('{"type": "playback", "message":""}');
//turn on the playback mode
playback_mode = true;
//clear the pad
previous_text = "";
$("#editable_content").html("<li></li>");
}
$("#input_chat_message").keypress(function(ev){
if((ev.keyCode || ev.which) == 13){
ev.preventDefault();
socket.send('{"type": "chat", "message":"' + $(this).val() + '"}');
$(this).val("");
}
});
$("#pad_playback").click(function(){
doPlayback();
return false;
})
});