-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathEditor.js
807 lines (803 loc) · 21.2 KB
/
Editor.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
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
var LightEditor;
(function(){
var instances = [];
LightEditor = function(args){
var n = args.node, c;
this.scrollMode = args.scrollMode || "scroll";
(this.domNode = document.createElement("div")).className = "LightEditor";
(this.containerNode = (typeof n === "string" && (n = document.getElementById(n)))).className += "LightEditorContainer";
this.domNode.innerHTML = n.innerHTML;
n.innerHTML = "";
n.appendChild(this.domNode);
this.domNode.appendChild(this.caret = c = this.createCaret());
this.registerPlugins();
this.connectEvents();
LightEditor.Keyboard.registerObserver(this);
instances[instances.length] = this;
this.getComputedStyle();
this.setDimensions();
};
LightEditor.prototype = {
/**
* @description If true, the first char will be uppercase
* @type {boolean}
*/
_upperCase: false,
/**
* @description Contains the intervalId for the blink
* @Type {number}
* */
_blink: 0,
/**
* @description Contains the modifiers to add after the next keystroke
* @type {Array}
*/
_modifiers: [],
/**
* @description timeoutId for the autoscroll
* @type {number}
*/
_autoscrollTimeout: null,
/**
* @description Interval for the caret blink
* @type {number}
*/
blinkInterval: 500,
/**
* @description Active plugins for this editor instance
* @type {Array}
*/
plugins: [],
/**
* @description Node containing the editable text
* @type {Node}
*/
domNode: null,
/**
* @description The caret node
* @type {Node}
*/
caret: null,
/**
* @description true when the current editor is focused
* @type {boolean}
*/
focused: false,
/**
* @description Editor width
* @type {number}
*/
width: 0,
/**
* @description Editor height
* @type {number}
*/
height: 0,
/**
* @description Scroll mode: "scroll" or "autoexpand".
* @default "scroll"
* @type {String}
*/
scrollMode: "scroll",
/**
* @description When a finger is near the editor border, the text is scrolled in that direction after
* autoscrollDelay ms
* @type {number}
*/
autoscrollDelay: 1000,
/**
* @description Interval for the scroll animation (ms)
* @type {number}
*/
viewportMoveTime: 50,
/**
* @description intervalId for the scroll animation
* @type {number}
*/
viewportMoveInterval: null,
/**
* @description The domNode.parentNode
* @type {Node}
*/
containerNode: null,
/**
* @description Contains the mapping for the supported text modifiers
* @type {Object}
*/
modifiersMap: {
B:{
tagName: "span",
style:{
fontWeight: "bold"
}
},
I:{
tagName: "span",
style:{
fontStyle: "italic"
}
},
U:{
tagName: "span",
style:{
textDecoration: "underline"
}
}
},
/**
* @description Registers the plugins passed as space separated list in the plugins attribute
*/
registerPlugins: function(){
this.plugins = [];
var plugins = this.containerNode.getAttribute("data-plugins").replace(/\s/g, "").split(","),
availablePlugins = LightEditor.plugins
;
for(var i = 0, l = plugins.length; i < l; i++){
this.plugins[i] = new availablePlugins[plugins[i]]({ editor: this });
}
},
/**
* @description Sets the domNode height
*/
setDimensions: function(){
var i = this.plugins.length, cumulativeHeight = parseInt(window.getComputedStyle(this.domNode.parentNode, null).getPropertyValue("height"));
while(i--){
if(this.plugins[i].hasLayout){
cumulativeHeight -= this.plugins[i].getHeight();
}
}
this.domNode.style.height = cumulativeHeight + "px";
},
/**
* @description Returns the domNode
* @return The editor domNode
*/
getDomNode: function(){
return this.domNode;
},
/**
* @description Returns the containerNode
* @return The editor containerNode
*/
getContainerNode: function(){
return this.containerNode;
},
/**
* @description Creates the caret node
* @return the caret node
*/
createCaret: function(){
var c = document.createElement("span");
c.className = "caret";
return c;
},
/**
* @description Creates and connects the event handlers
*/
connectEvents: function(){
var n = this.domNode, self = this;
n.addEventListener("touchmove", function(){ self.onTouchMove.apply(self, arguments) }, false);
n.addEventListener("touchstart", function(){ self.onTouchMove.apply(self, arguments) }, false);
n.addEventListener("touchstart", function(evt){
self.stopViewportTimeout.apply(self, arguments);
self._autoscrollTimeout = setTimeout(function(){ self.startViewportTimeout.call(self, evt) }, self.autoscrollDelay);
}, false);
n.addEventListener("touchend", function(){
self.stopViewportTimeout.apply(self, arguments)
}, false);
n.addEventListener("touchstart", function(){
if(self.focused){
return;
}
self.onFocus.apply(self, arguments);
}, false);
document.addEventListener("touchstart", function(e){
if(e.target !== n){
self.onBlur.apply(self, arguments);
}
}, false);
},
/**
* @description Computes height and width for this editor
*/
getComputedStyle: function(){
var s = window.getComputedStyle(this.domNode, null);
this.height = parseInt(s.getPropertyValue("height"));
this.width = parseInt(s.getPropertyValue("width"));
},
/**
* @description Notifies this editor about a topic
* @param {String} topic
* @param {Array} args
*/
notify: function(topic, args){
if(!this.focused){
return;
}
switch(topic){
case "KeyPress":
var data = args[0], type = args[1], active = args[2];
switch(type){
case "":
data && this.write(data);
break;
case "meta":
this.handleMeta(data);
break;
case "modifier":
this.handleModifier(data, active);
break;
default:
break;
}
break;
default:
break;
}
},
/**
* @description Returns the previous or the next textNode
* @param {Node} n
* @param {String} pos "next" or "previous"
* @return The previous or the next textNode, or null
*/
getRelativeTextNode: function(n, pos){
var sibling = {
previous: "previousSibling",
next: "nextSibling"
}[pos],
child = {
previous: "lastChild",
next: "firstChild"
}[pos]
;
if(n[sibling]){
if(n[sibling].nodeType === 3){
return n[sibling];
}else{
n = n[sibling][child];
while(n && n.nodeType != 3){
n = n[child];
}
return n; // node or null
}
}else{
return n.parentNode === this.domNode ? null : this.getRelativeTextNode(n.parentNode, pos);
}
},
/**
* @description Returns the next textNode
* @param {Node} n
* @return The next textNode, or null
*/
getNextTextNode: function(n){
return this.getRelativeTextNode(n, "next");
},
/**
* @description Returns the previous textNode
* @param {Node} n
* @return The next previousNode, or null
*/
getPreviousTextNode: function(n){
return this.getRelativeTextNode(n, "previous");
},
/**
* @description Returns the previous textNode or the previous EOL node
* @param {Node} n
* @return A node or null
*/
getPreviousValidNode: function(n){
var
validNode = null,
vnode = null,
isEOL = this.isEOL, isTextNode = this.isTextNode,
nodeIterator = document.createNodeIterator(
this.domNode,
NodeFilter.SHOW_TEXT + NodeFilter.SHOW_ELEMENT,
{ acceptNode: function(node){
if(!!(node.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_FOLLOWING) && (isEOL(node) || isTextNode(node))){
return NodeFilter.FILTER_ACCEPT;
}else{
return NodeFilter.FILTER_REJECT;
}
}},
false
);
while(vnode = nodeIterator.nextNode()){
if(!!(vnode.compareDocumentPosition(n) & Node.DOCUMENT_POSITION_FOLLOWING) && (isEOL(vnode) || isTextNode(vnode))){
validNode = vnode;
}
}
return validNode;
},
/**
* @description Adds or remove modifier to/from the current queue
* @param {String} data (eg "B", "I"...)
* @param {boolean} active
*/
handleModifier: function(data, active){
var _modifiers = this._modifiers;
if(active){
_modifiers[_modifiers.length] = data;
}else{
var i = _modifiers.length;
while(i--){
if(_modifiers[i] === data){
_modifiers.splice(i, 1);
break;
}
}
this.removeModifier(data);
}
switch(data){
case "left-shift":
case "right-shift":
this._upperCase = !this._upperCase;
break;
default:
break;
}
},
/**
* @description Removes a modifier from the nodes surrounding the caret
* @param {String} data
*/
removeModifier: function(data){
var c = this.caret, node = c.parentNode, domNode = this.domNode, found = false, matches, counter,
currentModifier = this.modifiersMap[data]
;
if(!node || !currentModifier){
// for example, pressing SHIFT
return;
}
while(node && node != domNode && !found){
counter = matches = 0;
for(var j in currentModifier.style){
counter++;
if(node.style[j] === currentModifier.style[j]){
matches++;
}
}
if(node.tagName.toLowerCase() === currentModifier.tagName && counter === matches){
found = true;
this.unwrap(node);
}
node && (node = node.parentNode);
}
},
/**
* @description Removes a wrapper from a node
* @param {Node} node
*/
unwrap: function(node){
for(var i = 0, l = node.childNodes.length; i < l; i++){
node.parentNode.insertBefore(node.firstChild, node);
}
node.parentNode.removeChild(node);
},
/**
* @description Remove nodes without children
*/
removeEmptyNodes: function(){
var nodes, node, domNode = this.domNode, i, c = this.caret;
while((nodes = domNode.querySelectorAll("*:empty")).length > 1){
i = nodes.length;
while(i--){
node = nodes[i];
(node != c) && (node.parentNode.removeChild(node));
}
}
},
/**
* @description Remove empty nodes from the document
*/
normalizeDocument: function(){
// var nodes, node, i, domNode = this.domNode, N = 0;
this.removeEmptyNodes();
// while((nodes = domNode.querySelectorAll("br:only-child")).length - N){
//
// for(i = nodes.length; i--;){
// node = nodes[i];
// if(node.parentNode.childNodes.length === 1){
// node.parentNode.parentNode.replaceChild(document.createElement("br"), node.parentNode);
// }else{
// N++;
// }
// }
// }
},
/**
* @description Handles the meta keys, eg the .?123 and ABC on the keyboard
* @param {String} data
*/
handleMeta: function(data){
var c = this.caret, deltaY = 0, caretHeight, eols, lastEOL, domNode = this.domNode, cstyle, ofs = 0, pn;
switch(data){
case "backspace":
var validNode = this.getPreviousValidNode(c), d;
if(this.isTextNode(validNode)){
d = validNode.data;
validNode.data = d.substring(0, d.length-1);
pn = validNode.parentNode;
validNode.parentNode.normalize();
}else if(this.isEOL(validNode)){
validNode.parentNode.removeChild(validNode);
}
// TODO: normalize a subnode, if possible
this.domNode.normalize();
break;
case "enter":
c.parentNode.insertBefore(this.createEOL(), c);
this.showCaret();
if(this.scrollMode === "scroll"){
// scroll
caretHeight = parseInt(window.getComputedStyle(c, null).getPropertyValue("font-size"));
if((deltaY = c.offsetTop - this.height) > 0){
this.domNode.scrollTop = deltaY + caretHeight;
}
}else{
// autoExpand
eols = this.getEOLs();
lastEOL = eols[eols.length-1];
cstyle = window.getComputedStyle(lastEOL, false);
ofs = this.computeOffsetTop(lastEOL);
domNode.style.height = this.height + lastEOL.offsetTop + parseInt(cstyle.getPropertyValue("height")) + "px";
}
domNode.scrollLeft = 0;
break;
case "hidekbd":
this.blurAllInstances();
this.hideKeyboard();
break;
default:
break;
}
},
/**
* @description Returns the html contained in this editor
* @return {String} the html contained in this editor
*/
getContent: function(){
return this.domNode.innerHTML;
},
/**
* @description Removes the focus from all the instances
*/
blurAllInstances: function(){
var i = instances.length;
while(i--){
instances[i].blur();
}
},
/**
* @description Creates a End Of Line node
* @return {Node}
*/
createEOL: function(){
var EOL;
(EOL = document.createElement("span")).appendChild(document.createTextNode("\n"));
EOL.className = "EOL";
return EOL;
},
/**
* @description True if node is EOL
* @param {Node} node
* @return {boolean} True if the node is a EOL, false otherwise
*/
isEOL: function(node){
if(!node){
return false;
}
var tagName, child;
return !!((tagName = node.tagName) && tagName.toLowerCase() === "span" && (child = node.firstChild) &&
child.nodeType === 3 && child.data.charCodeAt(0) === 10);
},
/**
* @description True if node is a text node
* @param node
* @return True if node is a text node, false otherwise
*/
isTextNode: function(node){
if(!node){
return false;
}
return node.nodeType === 3;
},
/**
* @description Writes a character
* @param {String} chr
*/
write: function(chr){
var c = this.caret,
ps = c.previousSibling,
tn = this.getPreviousTextNode(c),
deltaX = 0,
_modifiers = this._modifiers,
node, modifiersMap = this.modifiersMap,
currentModifier,
prevNode, st, nodeStyle
;
this._upperCase && (chr = chr.toUpperCase());
if(tn && !this.isEOL(ps) && !_modifiers.length){
tn.data = tn.data + chr;
this.showCaret();
}else{
node = document.createTextNode(chr);
for(var i = _modifiers.length; i--;){
prevNode = node;
currentModifier = modifiersMap[_modifiers[i]];
if(!currentModifier){
// left and right shift
break;
}
node = document.createElement(currentModifier.tagName), nodeStyle = node.style;
st = currentModifier.style;
for(var j in st){
nodeStyle[j] = st[j];
}
node.appendChild(prevNode);
}
_modifiers.length = 0;
c.parentNode.insertBefore(node, c);
}
LightEditor.Keyboard.setKeyActive("left-shift", false);
LightEditor.Keyboard.setKeyActive("right-shift", false);
this._upperCase = false;
this.getModifiersFromCaret();
c.style.display = "inline";
if((deltaX = this.computeOffsetLeft(c) - this.width)>0){
this.domNode.scrollLeft = deltaX;
}
},
/**
* @description Finds the modifiers around the caret and notifies the plugins
*/
getModifiersFromCaret: function(){
var domNode = this.domNode, pvn = this.getPreviousValidNode(this.caret);
if(!pvn){
return;
}
var node = pvn.parentNode,
modifiersMap = this.modifiersMap, currentModifier, matches, c
;
for(var i in modifiersMap){
this.notifyModifiers(i, false);
}
while(node != domNode){
for(i in modifiersMap){
matches = c = 0;
currentModifier = modifiersMap[i];
for(var j in currentModifier.style){
c++;
if(node.style[j] === currentModifier.style[j]){
matches++;
}
}
if(matches === c && node.tagName.toLowerCase() === currentModifier.tagName){
this.notifyModifiers(i, true, currentModifier.group);
}
}
node = node.parentNode;
}
},
/**
* @description Notifies all subscribed plugins about the modifiers around the caret
*/
notifyModifiers: function(){
var plugins = this.plugins, i = plugins.length, h;
while(i--){
if(h = plugins[i].subscriptions.notifyModifiers){
plugins[i][h].apply(plugins[i], arguments);
}
}
},
/**
* @description Computes the left/top offsets
* @param {Node} node
* @param {String} which "top" or "left"
*/
computeOffset: function(node, which){
var ofs = 0, w = "offset" + which;
do{
ofs += node[w];
}while(node = node.offsetParent); // thanks ppk!
return ofs;
},
/**
* @description Computes the top offset
* @param {Node} node
*/
computeOffsetTop: function(node){
return this.computeOffset(node, "Top");
},
/**
* @description Computes the left offset
* @param {Node} node
*/
computeOffsetLeft: function(node){
return this.computeOffset(node, "Left");
},
/**
* @description moves the caret in the given position
* @param {number} x
* @param {number} y
*/
moveCaret: function(x, y){
var c = this.caret, t = document.elementFromPoint(x, y), cn = t.childNodes, i, l, j, m, tn,
curNode, minNode, testNode = document.createElement("span"), dx = window.screen.width, curX, abs = Math.abs,
delta, currentChild, index = 0, scrollLeft = this.domNode.scrollLeft
;
testNode.style.position = "absolute";
// I need cn.length here, not a static var
for(i = 0; i < cn.length; i++){
// de-normalize
tn = cn[i];
if(tn.nodeType === 3){
for(j = 0, m = tn.textContent.length; j < m; j++){
tn.splitText(1);
tn = tn.nextSibling;
}
}
}
for(i = 0, l = cn.length; i <= l; i++){
currentChild = cn[i], curX = 0;
currentChild ? t.insertBefore(testNode, currentChild) : t.appendChild(testNode);
curNode = testNode;
do{
curX += curNode.offsetLeft;
}while(curNode = curNode.offsetParent);
if((delta = abs(curX-x-scrollLeft)) < dx && testNode != c && testNode.firstChild != c && testNode.parentNode != c){
dx = delta;
index = i;
}
testNode.parentNode && t.removeChild(testNode);
}
if(index < l){
minNode = cn[index];
minNode && minNode != c && minNode != c.firstChild && t.insertBefore(c, minNode);
}else{
c != t && t.appendChild(c);
}
t.normalize();
this.getModifiersFromCaret();
},
/**
* @description Starts the viewport animation timeout
* @param {Event} evt
*/
startViewportTimeout: function(evt){
var self = this;
this.viewportMoveInterval = setInterval(function(){ self.adjustViewport(evt) }, this.viewportMoveTime);
},
/**
* @description Stops the viewport animation timeout
*/
stopViewportTimeout: function(){
this._autoscrollTimeout && clearTimeout(this._autoscrollTimeout);
this._autoscrollTimeout = null;
this.viewportMoveInterval && clearInterval(this.viewportMoveInterval);
this.viewportMoveInterval = null;
},
/**
* @description Changes the viewport scroll
* @param {Event} evt
*/
adjustViewport: function(evt){
var tt = evt.targetTouches[0], x = tt.clientX, y = tt.clientY, domNode = this.domNode,
oT = domNode.offsetTop, oL = domNode.offsetLeft
;
if(y - oT < 20){
domNode.scrollTop -= 10;
}else if(y - oT > this.height - 20){
domNode.scrollTop += 10;
}
if(x - oL < 20){
domNode.scrollLeft -= 10;
}else if(x - oL > this.width - 20){
domNode.scrollLeft += 10;
}
},
/**
* @description Returns the EOLs
* @returns {NodeList} EOLs
*/
getEOLs: function(){
return this.domNode.querySelectorAll("span.EOL");
},
/**
* @description Handler for the touchMove event: moves the caret
* @param {Event} evt
*/
onTouchMove: function(evt){
// touch
var trg = evt.target, tt = evt.targetTouches[0], domNode = this.domNode, x = tt.clientX, y = tt.clientY, lines,
line, curY = 0, deltaY = this.height,
abs = Math.abs, minNode, c = this.caret, scrollTop = domNode.scrollTop, curNode
;
if(trg === domNode){
lines = this.getEOLs();
lines.length && (minNode = lines[0]);
for(var i = 0, l = lines.length; i < l; i++){
line = lines[i];
curNode = line;
curY = 0;
do{
curY += curNode.offsetTop;
}while(curNode = curNode.offsetParent);
if(abs(curY - y - scrollTop) < abs(deltaY) ){
minNode = line;
deltaY = curY - y - scrollTop;
}
}
minNode && minNode.parentNode.insertBefore(c, minNode);
}else{
this.moveCaret(x, y);
}
evt.preventDefault();
evt.stopPropagation();
},
/**
* @description Make the caret blinking
*/
blinkCaret: function(){
this.caret.style.display = this.caret.style.display === "inline" ? "none" : "inline";
},
/**
* @description Shows the caret
*/
showCaret: function(){
var self = this;
this._blink && clearInterval(this._blink);
this._blink = setInterval(function(){ self.blinkCaret() }, this.blinkInterval);
},
/**
* @description Hides the caret
*/
hideCaret: function(){
clearInterval(this._blink);
this._blink = 0;
this.caret.style.display = "none";
},
/**
* @description Removes the focus from this editor
*/
blur: function(){
this.domNode.blur();
this.onBlur();
},
/**
* @description onBlur handler
*/
onBlur: function(){
var dn = this.domNode;
this.focused = false;
dn.className = dn.className.replace(" focused", "");
this.hideKeyboard();
this.hideCaret();
},
/**
* @description onFocus handler
*/
onFocus: function(){
var dn = this.domNode;
this.blurAllInstances();
this.focused = true;
this.showKeyboard();
this.showCaret();
dn.className = dn.className.replace(" focused", "") + " focused";
},
/**
* @description Hides the keyboard
*/
hideKeyboard: function(){
LightEditor.Keyboard.hide();
},
/**
* @description Shows the keyboard
*/
showKeyboard: function(){
LightEditor.Keyboard.show();
}
};
LightEditor.plugins = {};
})();