-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy patheditor.js
More file actions
426 lines (372 loc) · 11.7 KB
/
editor.js
File metadata and controls
426 lines (372 loc) · 11.7 KB
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
/*!
* HTML5 editor - 0.0.1
*
* Copyright (c) 2011 Evgeni Gordejev
*/
function htmlspecialchars(str){
return str.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
}
function getFirstTextNode(node){
if(node.nodeType == 3){
return node;
}else{
var iter = node.firstChild;
while(iter){
if(iter.nodeType == 3){
return iter;
}
iter = iter.nextSibling;
}
}
return null;
}
//slightly faster than native innerHTML method
function replaceHtml(oldNode, html) {
var newNode = oldNode.cloneNode(false);
newNode.innerHTML = html;
oldNode.parentNode.replaceChild(newNode, oldNode);
return newNode;
}
//handy module loader
function loadModule(obj, values){
for(var property in values){
if(values.hasOwnProperty(property)){
obj[property] = values[property];
}
}
}
function TextEngine(container){
this.range = document.createRange();
this.elem = container;
this.eof = true;
this.startLine = false;
this.startNode;
//inits selection
this.initSelection = function(){
this.currentNode = getFirstTextNode(this.elem);
this.currentOffset = 0;
this.range.setStart(this.currentNode,this.currentOffset);
this.eof = false;
this.startLine = true;
}
//selects line depending on cursor
//returns cursor position
this.lineByCursorPos = function(cursorNode, cursorOffset){
this.currentOffset = cursorOffset;
//new line character's parent is always contenteditable element,this is strict rule
while(cursorNode.parentNode != this.elem){
cursorNode = cursorNode.parentNode;
this.currentOffset = -1;
}
var cursorPos = 0;
var node = cursorNode;
var str,pos,offset;
offset = this.currentOffset;
//searching start of the line
while(node){
if(node.nodeType == 3){
str = node.nodeValue;
if(offset != -1){
str = str.slice(0, offset);
}
pos = str.lastIndexOf('\n');
if(pos != -1){
this.range.setStart(node,pos+1);
cursorPos += str.length-pos-1;
break;
}else{
cursorPos += str.length;
offset = -1;
}
}else if(node.nodeType == 1){
if(node == cursorNode){
cursorPos += cursorOffset;
}else{
cursorPos += node.textContent.length;
}
}
if(!node.previousSibling){
this.range.setStart(node,0);
break;
}
node = node.previousSibling;
}
node = cursorNode;
offset = this.currentOffset;
//searching end of the line
while(node){
if(node.nodeType == 3){
str = node.nodeValue;
if(offset != -1){
str = str.slice(offset);
}
pos = str.indexOf('\n');
if(pos != -1){
this.currentNode = node;
this.range.setEnd(node,(offset != -1)?offset+pos:pos);
break;
}else{
offset = -1;
}
}
if(!node.nextSibling){
if(node.nodeType == 3){this.currentNode = node;
this.range.setEnd(node,node.nodeValue.length);
}else if(node.nodeType == 1){this.currentNode = node;
this.range.setEnd(node,1);
}
break;
}
node = node.nextSibling;
}
//str = this.range.cloneContents().textContent;
return cursorPos;
};
//selects next number of lines
//returns true if lines are found
this.nextLines = function(num){
var node = this.currentNode;
while(node.nextSibling){
this.currentNode = node;
if(node.nodeType == 3){
str = node.nodeValue;
if(this.currentOffset){
str = str.slice(this.currentOffset);
}
pos = str.indexOf('\n');
if(pos != -1){
this.currentOffset += pos;
if(!this.startLine){
this.currentOffset++;
this.range.setStart(this.currentNode,this.currentOffset);
this.startLine = true;
continue;
}else{
num--;
if(num != 0){
this.currentOffset++;
continue;
}
this.range.setEnd(this.currentNode,this.currentOffset);
this.startLine = false;
return true;
}
}else{
this.currentOffset = 0;
}
}
node = node.nextSibling;
}
this.eof = true;
if(this.currentNode && this.startLine){
node = this.currentNode;
if(node.nodeType == 3){
this.range.setEnd(node,node.nodeValue.length);
}else if(node.nodeType == 1){
this.range.setEnd(node,getFirstTextNode(node)?1:0);
}else{
return false;
}
}else{
return false;
}
return true;
};
//returns range by cursor position,
//starts searching from the beginning of current line
this.getRangeByCursor = function(cursorPos){
var node = this.startNode;
var offset = 0;
var textNode;
while(node){
textNode = getFirstTextNode(node);
offset += textNode.nodeValue.length;
if(offset >= cursorPos){
var range = document.createRange();
var pos = textNode.nodeValue.length-offset+cursorPos;
range.setEnd(textNode,pos);
range.collapse(false);
return range;
}
node = node.nextSibling;
}
return null;
};
//replace current selection with new html string
this.setLine = function(html){
this.currentOffset = 0;
this.range.deleteContents();
if(html.length){
this.range.deleteContents();
var frag = document.createDocumentFragment();
var dummy = document.createElement('span');
dummy.innerHTML = html;
frag.appendChild(dummy);
//unwrap
for(var i = 0; dummy.childNodes[i]; i++){
frag.appendChild(dummy.childNodes[i].cloneNode(true));
}
frag.removeChild(dummy);
this.currentNode = frag.lastChild;
this.startNode = frag.firstChild;
this.range.insertNode(frag);
}else{
this.range.deleteContents();
this.currentNode = document.createTextNode('');
this.startNode = this.currentNode;
this.range.insertNode(this.currentNode);
}
};
//returns selection html string
this.getLineHTML = function(){
var frag = this.range.cloneContents();
var div = document.createElement('div');
div.appendChild(frag);
return div.innerHTML;
};
//returns selection text
this.getLineText = function(){
return this.range.cloneContents().textContent;
};
//sets selection
this.setRange = function(range){
this.range = range;
};
//gets selection
this.getRange = function(){
return this.range;
};
}
function Editor(elementId, module){
//---------------------------------------------------------------
//------------------module template start------------------------
var TEMPLATE = {
prettifyInit: function(){},
prettify: function(str){return str},
indentInit: function(indentSize, offset){},
indentOffset: function(str){return 0}
};
//-------------------module template end-------------------------
//---------------------------------------------------------------
var self = this;
//editor's container element
this.elem = document.getElementById(elementId);
this.textEngine = new TextEngine(this.elem);
//---------------------------------------------------------------
//---------------------main program start------------------------
loadModule(this, TEMPLATE);
loadModule(this, module);
this.selection = window.getSelection();
this.elem.addEventListener("keydown", function(event){
if(event.keyCode == 13){
event.preventDefault();
self.prettifyInit();
var node = self.selection.anchorNode;
var localPos = self.textEngine.lineByCursorPos(node,self.selection.anchorOffset);
var str = self.textEngine.getLineText();
//if caret at the very end of the text, newline insertion requires atleast two
//characters to work(Chrome), for example '\n\n' or '\n ' will work.
//It is a mystery to me...should ask on stackoverflow guys
if(localPos == str.length && self.textEngine.currentNode.nextSibling == null){
self.textEngine.setLine(self.prettify(str)+'\n ');
}else{
self.textEngine.setLine(self.prettify(str.slice(0,localPos))+'\n'+self.prettify(str.slice(localPos)));
}
var range = self.textEngine.getRangeByCursor(localPos+1);
if(range){
self.selection.removeAllRanges();
self.selection.addRange(range);
}
}
});
//automatic highlighting on keyup event
this.elem.addEventListener("keyup", function(){
var node = self.selection.anchorNode;
var localPos = self.textEngine.lineByCursorPos(node,self.selection.anchorOffset);
var unmodified = self.textEngine.getLineHTML();
//TODO recognize multiline comment
self.prettifyInit();
var modified = self.prettify(self.textEngine.getLineText());
if(unmodified == modified){
return;
}
self.textEngine.setLine(modified);
var range = self.textEngine.getRangeByCursor(localPos);
if(range){
self.selection.removeAllRanges();
//when document is big, addrange method is quite slow
self.selection.addRange(range);
}
});
this.elem.addEventListener("paste", function(event){
event.preventDefault();
var paste = event.clipboardData.getData ? event.clipboardData.getData('text/plain') : false;
if(paste) {
//TODO clean start node and end node
self.textEngine.setRange(self.selection.getRangeAt(0));
self.textEngine.setLine(htmlspecialchars(paste));
var range = self.textEngine.getRange();
range.collapse(false);
self.selection.removeAllRanges();
self.selection.addRange(range);
setTimeout(function(){
self.highlight();
},50);
}
});
this.indent = function(){
var startSpacesPattern = new RegExp("^(\\s*( )*)+");
this.indentInit(2,0);
var pos,val,str;
var spPattern = new RegExp("\\S");
var res = []
var ts = new Date();
ts = ts.getTime();
this.textEngine.initSelection();
while(!this.textEngine.eof){
this.textEngine.nextLines(1);
str = this.textEngine.getLineText();
pos = str.search(spPattern);
val = this.indentOffset(str);
if(pos != val){
var intendStr = '';
for(var j = 0; j < val; ++j){
intendStr += ' ';
}
this.textEngine.setLine(intendStr+this.textEngine.getLineHTML().replace(startSpacesPattern,''));
//res.push(intendStr+str.replace(startSpacesPattern,''));
//this.setLine(intendStr+str.replace(startSpacesPattern,''));
}else{
//res.push(str);
}
}
//this.elem = replaceHtml(this.elem,htmlspecialchars(res.join('\n')));
var te = new Date();
te = te.getTime();
console.log('time(ms)',te-ts);
setTimeout(function(){
self.highlight();
},50);
}
this.highlight = function(){
var ts = new Date();
ts = ts.getTime();
this.prettifyInit();
this.textEngine.initSelection();
while(!this.textEngine.eof){
//TODO highlight by lines
this.textEngine.nextLines(100);
var unmodified = this.textEngine.getLineHTML();
//var modified = this.prettify(htmlspecialchars(this.textEngine.getLineText()));
var modified = this.prettify(this.textEngine.getLineText());
if(unmodified != modified){
this.textEngine.setLine(modified);
}
}
var te = new Date();
te = te.getTime();
console.log('time(ms)',te-ts);
}
//-----------------------main program end------------------------
//---------------------------------------------------------------
};