-
Notifications
You must be signed in to change notification settings - Fork 4
/
Gui.js
executable file
·2589 lines (2363 loc) · 97.4 KB
/
Gui.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
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// to create bookmarklet
// goto http://marijnhaverbeke.nl/uglifyjs
// put in tokenizer.js and zeparser.js
// (optionally) put in unicode.js
// put in zeon.js
// put in gui.js
// put in gui.nav.js
// put in gui.config.js
// (optionally) copy result and paste in http://pcd.qfox.nl/ and copy result back in uglify
// make sure that at the bottom, there's a Zeon.start(); being called
// compress with uglify
// the result is bookmarklet-ready
// Function.prototype.bind polyfill
if (!Function.prototype.bind) {
Function.prototype.bind = function(obj){
var slice = [].slice, args = slice.call(arguments, 1), self = this, nop = function(){
}, bound = function(){
return self.apply(this instanceof nop ? this : (obj || {}), args.concat(slice.call(arguments)));
};
nop.prototype = self.prototype;
bound.prototype = new nop();
return bound;
};
}
var Gui = function(textarea){
this.textarea = textarea;
this.config = Gui.getCurrentConfig();
if (!BOOKMARKLET) { //#ifndef BOOKMARKLET
// set directly to textarea.value because we havent parsed anything yet at this point
if (this.config['load saved code at start']) textarea.value = localStorage.getItem('doc');
if (document.location.hash.length > 1) {
var val = document.location.hash.slice(1);
textarea.value = val;
}
} //#endif
this.initUI();
this.computeFontSizes();
this.fixTextareLinePadding();
this.textarea.value += this.minLinePadding;
this.autoUpdater();
this.searchHistory = [];
this.navPos = {};
};
Gui.css = function(e,p,v){
if (e instanceof Array) {
return e.map(function(o){ return Gui.css(o,p,v); }, this);
} else if (p instanceof Object) {
for (var key in p) Gui.css(e,key,p[key]);
} else if (v) {
var camel = p.replace(/-./g, function(r){ return r.substring(1).toUpperCase(); });
e.style[camel] = v;
} else {
var t = document.defaultView.getComputedStyle(e, null);
return t.getPropertyValue(p);
}
};
Gui.copyCss = function(e,f, p){
if (f instanceof Array) {
for (var i=0; i<f.length; ++i) Gui.copyCss(e,f[i],p);
} else if (p instanceof Array) {
for (var i=0; i<p.length; ++i) Gui.copyCss(e,f,p[i]);
} else if (e instanceof Array) {
for (var i=0; i<e.length; ++i) Gui.copyCss(e[i],f,p);
} else {
var camel = p.replace(/-./g, function(r){ return r.substring(1).toUpperCase(); });
var dash = p.replace(/[A-Z]/g, function(r){ return '-'+r.toLowerCase(); });
f.style[camel] = Gui.css(e, dash);
}
};
Gui.getSize = function(e){
// you better make sure e exists.
return {w:parseInt(Gui.css(e,"width"),10),h:parseInt(Gui.css(e,"height"),10)};
};
Gui.getSizef = function(e){
// you better make sure e exists.
return {w:parseFloat(Gui.css(e,"width")),h:parseFloat(Gui.css(e,"height"))};
};
Gui.escape = function(s){
if (typeof s != 'string') return s;
return s.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>');
};
Gui.noctrl = function(s){
if (typeof s != 'string') return s;
return s.replace(/\n/g, '\u21b5').replace(/\t/g, '\\t'); // return = \u21b5
};
Gui.getCurrentConfig = function(){
if (window.localStorage) {
var str = window.localStorage.getItem('zeon-config');
if (str) try { return JSON.parse(str); } catch(e) {}
}
return Zeon.getNewConfig();
};
Gui.zeonify = function(textarea, expose){
var gui = new Gui(textarea);
textarea.focus();
// i debug through console :)
if (expose) window.gui = gui;
return gui;
};
/**
* Convert all textarea's on the current page to a Zeon
* @param {boolean} expose
*/
Gui.start = function(expose, textarea){
var lastZeon = false;
if (textarea) {
lastZeon = Gui.zeonify(textarea, expose);
} else {
Array.prototype.slice.call(document.getElementsByTagName('textarea'), 0).forEach(function(textarea){ lastZeon = Gui.zeonify(textarea, expose); });
}
return lastZeon;
};
Gui.webkit = function(expose){
// textarea is actually a table
var table = document.getElementsByClassName('text-editor')[0];
var content = Array.prototype.slice.call(document.querySelectorAll('.webkit-line-content', table), 0).map(function(e){ return e.textContent; }).join('\n');
var textarea = document.createElement('textarea');
textarea.value = content;
var s = textarea.style;
s.position = 'absolute';
s.top = '0';
s.left = '0';
s.fontFamily = 'Menlo, monospace';
s.fontSize = '11px';
s.paddingTop = '4px'; // alignment...
textarea.setAttribute('rows', 60);
textarea.setAttribute('cols', 150);
table.appendChild(textarea);
return Zeon.start(expose);
};
/**
* Construct a new textarea+zeon for the list of files (objects {data,src?})
* @param {Array<data,src>} files
* @param {Object} afterElement=false When given, the textarea is added after this element
* @param {Object} expose Create global zeon var with handle
*/
Gui.files = function(files, afterElement, expose){
console.log("Zeon.files", files.slice(0))
// textarea is actually a table
var content = files.map(function(o){ return '\n; //! '+(o.src || 'inline script')+' !//\n'+o.data; }).join('');
var textarea = document.createElement('textarea');
textarea.value = content;
var s = textarea.style;
s.position = 'absolute';
s.top = '0';
s.left = '0';
s.fontFamily = 'Menlo, monospace';
s.fontSize = '11px';
//textarea.setAttribute('rows', 60);
//textarea.setAttribute('cols', 150);
if (afterElement) afterElement.parentElement.insertBefore(textarea, afterElement);
else document.body.appendChild(textarea);
var z = Zeon.start(expose);
return z;
};
Gui.prototype = {
config: null,
fontSize:0,
charsX:0,
charsY:0,
caret: null,
caretCol: 0,
caretRow: 0,
caretStale: true,
caretVisible: false,
rootContainer: null,
layerContainer: null,
textarea: null,
caretLayer: null,
syntaxLayer: null,
markLayerUnder: null,
sourceLayer: null,
markLayerOver: null,
sourceLayer: null,
ruler: null,
baseLeftPadding: 0,
defaultLeftPadding: 5,
showLineNumbers: true,
lineNumberPadding: 10,
minLines: null, // number of newlines added to textarea to make sure you can scroll another page down. should be superfluous to the user.
minLinePadding: null, // cached padding string
guiNav: null,
navMessage: null,
navMessageTimer: null,
navPos: null,
caretTimer: null,
updateTimer: null,
_originalWrapAttr: null,
_originalNoWrapAttr: null,
_originalSpellcheckAttr: null,
_originalAutocapitalizeAttr: null,
_originalAutoCorrectAttr: null,
removed: false, // has this zeon instance been knifed?
regexPragmaHead: /^(\/\/#\w+\s+)(\w+)/,
regexPragmaMacro: /^(\/\/#\w+\s+)(\w+)(\s+)(.+)?/,
regexTwinMark: null,
bubbleCache: null, // when set, new calls to bubble() are put in here
markCache: null, // when set, new calls to addMark() are put in here
zeonClassPrefix: 'zeon-prefix-',
styleCache: null,
styleSheet: null,
searchHistory: null,
autoUpdater: function(){
try {
this.update(false);
} finally {
this.updateTimer = setTimeout(this.autoUpdater.bind(this), 20);
}
},
update: function(forced){
var input = this.getValue();
if (!forced && input == this.lastInput) return;
this.lastInput = input;
var dbg = document.getElementById('dbg');
if (dbg) dbg.innerHTML = '';
var failed = false;
this.zeon = new Zeon(input, this.config);
this.parse();
this.process();
this.refreshSyntaxHighlight();
this.onTextareaSizeChange();
this.startCaretBlink();
this.autoScroll();
this.guiNav.updateNav();
clearTimeout(this.navMessageTimer);
Gui.css(this.navMessage, 'display', 'none');
},
parse: function(input){
this.input = input;
var start = +new Date;
this.zeon.parse(input);
this.debug("parse time: "+((+new Date) - start)+' ms');
if (this.zeon.parser.errorStack.length) {
this.debug('<span style="color:red;">Found '+this.zeon.tokenizer.errorStack.length+" tokenizer & "+this.zeon.parser.errorStack.length+' parser errors. First:</span> '+this.zeon.parser.errorStack[0].msg);
} else if (this.zeon.tokenizer.errorStack.length) {
this.debug('<span style="color:red;">Found '+this.zeon.tokenizer.errorStack.length+" tokenizer & "+this.zeon.parser.errorStack.length+' parser errors. First:</span> Tokenizer: '+(this.zeon.tokenizer.errorStack[0].error.msg||this.zeon.tokenizer.errorStack[0].error.error.msg));
}
},
process: function(){
// preprocess result. sort by lines, find last match
var start = +new Date;
var times = this.zeon.startProcess();
this.debug("post process time: "+((+new Date) - start)+' ms ('+times.join(', ')+')');
},
showMessage: function(msg){
var nm = this.navMessage;
nm.innerHTML = msg;
Gui.css(nm, 'display', 'inline');
clearTimeout(this.navMessageTimer);
this.navMessageTimer = setTimeout(function(){ Gui.css(nm, 'display', 'none'); }, 5000);
},
initUI: function(){
var textarea = this.textarea;
this.initTextareaAttributes(textarea);
this.createLayers();
this.initContainer();
this.initLayerContainer();
this.initLayers();
this.initLineNumberBar();
this.guiNav = new Gui.Nav(this);
this.addTopMessage();
this.updatePaddingLeft();
if (!this.config['markers']) {
Gui.css([this.markLayerUnder, this.markLayerOver], 'display', 'none');
}
this.addLayersToDom();
// this.createTestButton();
this.initTextareaEvents();
},
initTextareaAttributes: function(textarea){
// firefox doesnt listen to the word-wrap property...
this._originalWrapAttr = textarea.getAttribute('wrap');
textarea.setAttribute('wrap', 'off');
// IE9 does it differently
this._originalNoWrapAttr = textarea.getAttribute('nowrap');
textarea.setAttribute('nowrap', 'true'); // IE9
// spell checker will get it wrong
this._originalSpellcheckAttr = textarea.getAttribute('spellcheck');
textarea.setAttribute('spellcheck', 'false'); // iew.
// this aint java
this._originalAutocapitalizeAttr = textarea.getAttribute('autocapitalize');
textarea.setAttribute('autocapitalize', 'off'); // ios meh.
// if only...
this._originalAutoCorrectAttr = textarea.getAttribute('autocorrect');
textarea.setAttribute('autocorrect', 'off'); // ios meh.
},
createLayers: function(){
// contains all elements, replaces the original textarea
this.rootContainer = document.createElement('div');
this.rootContainer.className = 'zeon-root-container';
// all elements are relative to this element... we cant safely set position of the root to 'relative', even though we really want to.
this.layerContainer = document.createElement('div');
this.layerContainer.className = 'zeon-layer-container';
// contains the highlighted text, but none of the marks
this.syntaxLayer = document.createElement('div');
this.syntaxLayer.className = 'zeon-syntax-layer';
// contains all the marks (pretty much any indicator except the text color)
this.markLayerUnder = document.createElement('div');
this.markLayerUnder.className = 'zeon-mark-layer-under';
this.sourceLayer = document.createElement('div');
this.sourceLayer.className = 'zeon-source-layer';
this.markLayerOver = document.createElement('div');
this.markLayerOver.className = 'zeon-mark-layer-over';
this.syntaxLayer.appendChild(this.markLayerUnder);
this.syntaxLayer.appendChild(this.sourceLayer);
this.syntaxLayer.appendChild(this.markLayerOver);
// only contains the caret
this.caretLayer = document.createElement('div');
this.caretLayer.className = 'zeon-caret-layer';
// have to simulate this because the textarea becomes invisible (and that includes the caret)
this.caret = document.createElement('span');
this.caret.className = 'zeon-caret';
},
initContainer: function(){
// set up root.
Gui.css(this.rootContainer, {padding:'0'});
var parentStyles = [
'position', 'top', 'left', 'width', 'height', 'float', 'display',
'margin-left','margin-top','margin-right','margin-bottom',
'background-color'
];
Gui.copyCss(this.textarea, this.rootContainer, parentStyles);
Gui.css(this.rootContainer,{border:'0', overflow: 'visible'}); // prevent scrollbars in firefox
},
initLayerContainer: function(){
// now set up parent. it will be position relative and span the entire width/height of the root
// it will hold all the other layers and is relative to the outer zeon container
Gui.css(this.layerContainer, {
position:'relative',
overflow:'hidden',
border: '1px solid black',
'-moz-box-sizing': 'border-box',
'-webkit-box-sizing': 'border-box',
'box-sizing': 'border-box'
});
Gui.copyCss(this.textarea, this.layerContainer, ['width','height']);
},
initLayers: function(){
// set the position affecting css properties on all the layers
// put all layers at the top-left corner, spanning the entire layerContainer.
// we also must have whitespace:pre;wordwrap: because we can't cope with breaking mid-sentence.
// we reset float here, because if the original textarea was floating, only the parent will need to float.
var requiredStyles = {
position: 'absolute', left: '0', top: '0', width: '100%', height: '100%',
'white-space':'pre', 'word-wrap':'normal',
'float':'none',
margin:'0', padding: '0',
'background-color':'transparent',
resize: 'none',
'-moz-box-sizing': 'border-box',
'-webkit-box-sizing': 'border-box',
'box-sizing': 'border-box'
};
Gui.css([this.textarea, this.caretLayer, this.syntaxLayer, this.markLayerUnder, this.sourceLayer, this.markLayerOver], requiredStyles);
// the syntax layer must mimic all the properties from the textarea that affect text size/positioning
var stylesToCopy = [
'font-family', 'font-size', 'line-height', 'vertical-align',
'word-spacing', 'letter-spacing', 'text-align'
];
Gui.copyCss(this.textarea, this.syntaxLayer, stylesToCopy);
// the syntax and caret layer should not overflow and be otherwise invisible
Gui.css([this.syntaxLayer, this.caretLayer], {overflow:'hidden', 'background-color':'transparent'});
// only the layerContainer should have a border.
Gui.css([this.textarea, this.markLayerUnder, this.sourceLayer, this.markLayerOver, this.syntaxLayer, this.caretLayer],'border', '0');
// the textarea should generate scrollbars because onscroll will cause scroll effect on other layers
Gui.css(this.textarea, {color: 'transparent', outline: 'none', overflow:'auto' });
// the actual caret should move around the caret layer like a butterfly!
Gui.css(this.caret, {position: 'absolute', top: '0', left: '0', width: '1px', height: '15px', 'background-color': 'blue' });
},
initLineNumberBar: function(){
this.ruler = document.createElement('div');
this.ruler.className = 'zeon-line-number-bar';
// this is the gutter on the left side of the gui (if visible at all)
Gui.css(this.ruler, {position:'absolute', top:'0', left:'0', 'min-height':'100%', color:'black', 'background-color':'#ccc', 'font-size': '12px', 'white-space':'pre', 'text-align':'right', padding: '0 3px 0 2px'});
// the gutter must also mimic any text size/position affecting properties
var stylesToCopy = ['box-sizing','font-family','font-size', 'font-weight', 'line-height', 'vertical-align', 'white-space'];
Gui.copyCss(this.textarea, this.ruler, stylesToCopy);
},
getValue: function(){
return this.textarea.value.slice(0,-this.minLines);
},
setValue: function(val){
this.textarea.value = val+this.minLinePadding;
},
addTopMessage: function(){
var msgp = document.createElement('div');
msgp.className = 'zeon-top-message';
Gui.css(msgp, {
position: 'absolute',
top: '15px',
left: '5px',
right: '20px',
'text-align': 'center'
});
this.layerContainer.appendChild(msgp);
this.navMessage = document.createElement('span');
Gui.css(this.navMessage, {
'background-color': 'white',
color: 'red',
'font-weight': 900,
border: '1px solid red',
padding: '5px',
display: 'none',
'-webkit-border-radius':'10px',
'border-radius': '10px'
});
msgp.appendChild(this.navMessage);
},
updatePaddingLeft: function(){
// increase left padding, optionally also take line numbers into account
var newPadding = this.defaultLeftPadding+(this.showLineNumbers?this.lineNumberPadding:0);
Gui.css([this.syntaxLayer, this.caretLayer, this.textarea], 'padding-left', newPadding+'px');
//Gui.css(this.textarea, 'width', (parseInt(Gui.css(this.layerContainer, 'width'),10) - (newPadding)) + 'px');
// the mark layer needs margin, because absolutely positioned elements see the border as 0x0, and ignore the padding.
Gui.css([this.markLayerUnder, this.sourceLayer, this.markLayerOver], 'margin-left', newPadding+'px');
this.onTextareaSizeChange();
},
addLayersToDom: function(){
var parent = this.textarea.parentNode;
// put main container in position of textarea
parent.insertBefore(this.rootContainer, this.textarea);
// put all layers in the layer container (textarea on top!)
var lc = this.layerContainer;
lc.appendChild(this.syntaxLayer);
lc.appendChild(this.caretLayer);
lc.appendChild(this.textarea); // last!
// and the caret
this.caretLayer.appendChild(this.caret);
// put the layer container in the main container
this.rootContainer.appendChild(this.layerContainer);
},
/*
createTestButton: function(){
var testbtn = document.createElement('div');
Gui.css(testbtn, {
position:'absolute',
top:'25px',
right:'25px',
'background-color':'white',
border: '1px solid red',
cursor: 'pointer',
color:'black',
padding:'3px'
});
testbtn.innerHTML = 'test';
testbtn.onclick = function(){
var tree = new Ast(this.zeon.tree, this.zeon.btree); // this will be my new structure in the next iteration
// window.btoken = tree;
// console.log('window.btoken', tree);
var inp = document.createElement('input');
inp.value = Ast.getHeatPlate()+tree.heatmap();
document.body.insertBefore(inp, document.body.firstChild);
inp.focus();
inp.select();
}.bind(this);
this.layerContainer.appendChild(testbtn);
//console.log("remove me! testbtn");
//setTimeout(this.beautifyButton.onclick, 500)
},
*/
initTextareaEvents: function(){
var textarea = this.textarea;
textarea.onkeydown = this.onTextareaKeyDown.bind(this);
textarea.onkeyup = this.onTextareaKeyUp.bind(this);
textarea.onkeypress = this.onTextareaKeyPress.bind(this);
textarea.onclick = this.onTextareaClick.bind(this);
textarea.onscroll = this.autoScroll.bind(this); // also does this.updateCaretPos();
textarea.onchange = this.onTextareaSizeChange.bind(this);
textarea.onselect = this.onTextareaSelectionChange.bind(this);
},
onTextareaKeyDown: function(e){
if (e.keyCode == 9) { // Tab key. we want it to insert an actual tab.
e.preventDefault(); // dont jump. unfortunately, also/still doesnt insert the tab.
var textarea = this.textarea;
var input = this.getValue();
var remove = e.shiftKey;
var posstart = textarea.selectionStart;
var posend = textarea.selectionEnd;
// if anything has been selected, add one tab in front of any line in the selection
if (posstart != posend) {
posstart = input.lastIndexOf('\n', posstart) + 1;
var compensateForNewline = input[posend-1] == '\n';
var before = input.substring(0,posstart);
var after = input.substring(posend-(compensateForNewline?1:0));
var selection = input.substring(posstart,posend);
// now add or remove tabs at the start of each selected line, depending on shift key state
// note: this might not work so good on mobile, as shiftKey is a little unreliable...
if (remove) {
if (selection[0] == '\t') selection = selection.substring(1);
selection = selection.split('\n\t').join('\n');
} else {
selection = selection.split('\n');
if (compensateForNewline) selection.pop();
selection = '\t'+selection.join('\n\t');
}
// put it all back in...
this.setValue(before+selection+after);
// reselect area
textarea.selectionStart = posstart;
textarea.selectionEnd = posstart + selection.length;
} else {
var val = this.getValue();
this.setValue(val.substring(0,posstart) + '\t' + val.substring(posstart));
textarea.selectionEnd = textarea.selectionStart = posstart + 1;
}
} else if (e.keyCode == 71 && e.ctrlKey){ // ctrl+g, go to line
var line = null;
if (line = parseInt(prompt('line?'), 10)) {
this.textarea.scrollTop = this.fontSize.h * (line-3);
this.textarea.selectionStart = this.textarea.selectionEnd = this.zeon.lines[Math.max(0, line-1)].start
}
} else if (e.keyCode == 66 && e.ctrlKey){ // ctrl+b, go to pos
var pos = null;
if (pos = parseInt(prompt('pos?'), 10)) {
var token = this.computeCaretPosAt(pos);
if (token) {
this.textarea.scrollTop = this.fontSize.h * (token.startLineId-3);
} else {
this.textarea.scrollTop = this.fontSize.h * (lines.length-1);
}
this.textarea.selectionStart = this.textarea.selectionEnd = pos;
}
} else if (e.keyCode == 70 && e.ctrlKey) { // ctrl+f, find. check for 70, even though lower case f is 102...
new Gui.Search(this);
e.preventDefault();
return false;
} else if (e.keyCode == 114) { // F3, find next/prev.
var target = false;
// find prev
if (this.textarea.selectionStart != this.textarea.selectionEnd) {
target = this.getValue().substring(this.textarea.selectionStart,this.textarea.selectionEnd);
} else if (this.searchHistory.length) {
target = this.searchHistory[0];
}
if (target) {
// create search object, press next/prev and close it.
var search = new Gui.Search(this);
search.setSearch(target);
if (e.ctrlKey) search.searchPrev();
else search.searchNext();
search.close();
}
e.preventDefault(); // prevents browser search box behavior
return false;
} else if (e.keyCode == 83 && e.ctrlKey) { // ctrl+s
localStorage.setItem('doc', this.getValue());
e.preventDefault(); // prevents browser search box behavior
this.showMessage('Source saved to local storage');
return false;
} else if (e.keyCode == 76 && e.ctrlKey) { // ctrl+l
this.setValue(localStorage.getItem('doc'));
e.preventDefault(); // prevents browser search box behavior
this.showMessage('Source loaded from local storage');
return false;
}
//console.log(e.keyCode)
this.caretStale = true;
this.startCaretBlink();
},
onTextareaKeyUp: function(e){
this.caretStale = true;
this.startCaretBlink();
this.onTextareaSizeChange();
},
onTextareaKeyPress: function(e){
var textarea = this.textarea;
if (e.keyCode == 13) { // return: match indentation of previous line
var input = this.getValue();
var posstart = textarea.selectionStart;
var posend = textarea.selectionEnd;
var before = input.substring(0,posstart);
var after = input.substring(posend);
var ws = '';
var star = '';
if (before) {
// scan from start of current line
var start = before.lastIndexOf('\n', posstart)+1;
var pos = start;
// put pos after whitespace
while (before[pos] && Tokenizer.regexWhiteSpace.test(before[pos])) ++pos;
var postoken = this.computeCaretPosAt(before.length);
var token = postoken;
// skip to first token that starts _before_ the current position
while (token && token.start >= before.length && token.tokposw) token = this.zeon.wtree[token.tokposw-1];
if (token && token.start < before.length) {
if ((token.isComment || token.name == 14/*error*/) && token.value.substring(0,3) == '/**' && token.value.slice(-2) != '*/') {
// indentation of the comment
ws = before.substring(start,pos);
// check if jsdoccing a function...
var pos = 0;
// skip whitespace
while (after[pos] && (Tokenizer.regexWhiteSpace.test(after[pos]) || Tokenizer.regexLineTerminator.test(after[pos]))) ++pos;
// if next non-white char is a star, just add a star. you're in a multi line comment, it must be a related star.
if (after[pos] == '*') {
// get the whitespace before that star we found, we'll mimic it.
var wsBegin = pos;
while (after[wsBegin-1] && Tokenizer.regexWhiteSpace.test(after[wsBegin-1])) --wsBegin;
ws = after.substring(wsBegin,pos);
// add the star and the indentation, put the caret one space after the new star
star = '* ';
this.setValue(before+'\n'+ws + star + after);
textarea.selectionStart = textarea.selectionEnd = posstart+ws.length+star.length+1;
return false; // prevent return being added to textarea. we'll do that, thanks!
} else {
// if (after.substring(pos, pos+8) == 'function' && (Tokenizer.regexWhiteSpace.test(after[pos+8]) || Tokenizer.regexLineTerminator.test(after[pos+8])) || after[pos+8] == '(')
// look for next token. we're looking for one of the following patterns:
// - Func: function
// - Func: var x = function
// - else Var(s): var x
// - Func: x = function
// - else Var: x =
// - Func: x: function
// - else Var: x:
// we must first move to the first black token...
var current = token;
while (current.isWhite && (current = this.zeon.wtree[current.tokposw+1]));
// first next black token is now in current. check patterns from above...
var tree = this.zeon.btree;
var target = false;
var isFunction = false;
if (current.isFuncDeclKeyword) {
target = current;
isFunction = true;
} else if (current.isVarKeyword) {
// func if var name and assignment follow
// var(s) otherwise
var pos = current.tokposb;
if (tree[pos+1] && tree[pos+1].name == 2/*identifier*/ && tree[pos+2] && tree[pos+2].value == '=' && tree[pos+3] && tree[pos+3].isFuncExprKeyword) {
target = tree[pos+3]; // func
isFunction = true;
} else {
// var
target = current;
}
} else if (current.isPropertyOf) {
var pos = current.tokposb;
if (tree[pos+1] && tree[pos+1].value == ':' && tree[pos+2] && tree[pos+2].isFuncExprKeyword) {
target = tree[pos+2]; // func
isFunction = true;
} else {
// var
target = current;
}
} else if (current.leadValue) {
target = current; // regular variable
}
if (target) {
if (isFunction) var jsdoc = this.zeon.generateFunctionJsdoc(target);
else {
var jsdoc = this.zeon.generateVarJsdoc(target);
if (jsdoc && !target.isPropertyOf) jsdoc = '\n'+jsdoc;
}
if (jsdoc) {
// replace existing /** too...
this.setValue(before.slice(0, -4)+jsdoc + after.slice(1));
textarea.selectionStart = textarea.selectionEnd = posstart+ws.length+3+1;
return false; // prevent return being added to textarea. we'll do that, thanks!
}
}
}
} else if (before[pos] == '*' && token && token.name == 8/*COMMENT_MULTI*/ && posstart < token.stop) {
// add a star if you pressed enter in a multi line comment and the current line "starts" with a star
star = '*';
if (after[0] != '/') star += ' '; // pressing it between the closing */ of the comment...
ws = before.substring(start,pos);
after = ws + star + after;
this.setValue(before+'\n'+after);
textarea.selectionStart = textarea.selectionEnd = posstart+ws.length+star.length+1;
return false; // prevent return being added to textarea. we'll do that, thanks!
} else if (before[pos] == '/' && token && token.name == 8/*COMMENT_MULTI*/ && posstart < token.stop) { // pressing return after the /** while still IN the comment
// add a star if you pressed enter in a multi line comment and the current line "starts" with a star
star = ' * ';
ws = before.substring(start,pos);
after = ws + star + after;
this.setValue(before+'\n'+after);
textarea.selectionStart = textarea.selectionEnd = posstart+ws.length+star.length+1;
return false; // prevent return being added to textarea. we'll do that, thanks!
}
}
// if code reaches here, we were not in a multi-line comment line starting with a star or forward slash + star + star (else it will have returned)
// match previous indentation. if we returned from {, increase indentation.
if (postoken) {
var index = postoken.tokposw-1;
while (index > 0 && this.zeon.wtree[index].isWhite && this.zeon.wtree[index].name != 10/*line_terminator*/) --index;
}
var extraIndentation = postoken && index > 0 && this.zeon.wtree[index].value == '{';
var start = before.lastIndexOf('\n', posstart)+1;
if (start < 0) start = 0;
var pos = start;
// find whitespace up to first non-whitespace
while (before[pos] && Tokenizer.regexWhiteSpace.test(before[pos])) ++pos;
ws = before.substring(start,pos);
after = ws + (extraIndentation?'\t':'') + after;
this.setValue(before+'\n'+after);
textarea.selectionStart = textarea.selectionEnd = posstart+ws.length+(extraIndentation?1:0)+1;
return false; // prevent return being added to textarea. we'll do that, thanks!
}
}
},
onTextareaClick: function(e){
if (e.ctrlKey) {
var pos = this.textarea.selectionStart;
var token = this.computeCaretPosAt(pos);
if (token) {
if (token.trackingObject && token.trackingObject.refs && token.trackingObject.refs.length) {
token.trackingObject.refs.some(function(target){
if (target.meta == 'var name' || target.meta == 'func decl name' || target.meta == 'func expr name' || target.meta == 'parameter') {
this.textarea.selectionEnd = this.textarea.selectionStart = token.start;
setTimeout(function(){
this.textarea.selectionStart = this.textarea.selectionEnd = target.start;
this.caretStale = true;
this.startCaretBlink();
}.bind(this), 1);
this.showCircleAtMatch(target);
return true;
}
},this);
} else if (token.twin) {
setTimeout(function(){
this.textarea.selectionEnd = this.textarea.selectionStart = token.twin.start;
this.caretStale = true;
this.startCaretBlink();
}.bind(this), 1);
this.showCircleAtMatch(token.twin);
return true;
}
}
}
this.caretStale = true;
this.startCaretBlink();
},
onTextareaSizeChange: function(){
this.guiNav.resize();
if (typeof this.minLines == 'number') {
var val = this.getValue();
this.fixTextareLinePadding();
this.setValue(val);
}
},
onTextareaSelectionChange: function(){
this.fixCaretBounds();
},
autoScroll: function(){
this.syntaxLayer.scrollLeft = this.textarea.scrollLeft;
this.syntaxLayer.scrollTop = Math.floor(this.textarea.scrollTop);
this.updateCaretPos();
},
fixCaretBounds: function(){
var len = this.getValue().length;
if (this.textarea.selectionStart > len) this.textarea.selectionStart = len;
if (this.textarea.selectionEnd > len) this.textarea.selectionEnd = len;
},
remove: function(){
this.removed = true;
// copy some events such that the textarea wont jump around
Gui.copyCss(this.rootContainer, this.textarea, ['color','background-color','position','top','left','width','height','display','margin-left','margin-top','margin-right','margin-bottom']);
Gui.css(this.textarea, {'border': '1px solid black', padding: '3px'});
// replace root with textarea. all other nodes will be recycled.
this.rootContainer.parentNode.replaceChild(this.textarea, this.rootContainer);
// detach events
this.textarea.onclick = null;
this.textarea.onscroll = null;
this.textarea.onmousedown = null;
this.textarea.onmousemove = null;
this.textarea.onmouseup = null;
this.textarea.onkeydown = null;
this.textarea.onkeyup = null;
this.textarea.onkeypress = null;
this.textarea.onchange = null;
this.textarea.ondragenter = null;
this.textarea.ondragover = null;
this.textarea.ondragleave = null;
this.textarea.ondrop = null;
// reset certain attributes
this.resetTextareaAttributes();
// remove all running timers
clearTimeout(this.caretTimer);
clearTimeout(this.updateTimer);
// clear circular reference
this.guiNav = null;
},
resetTextareaAttributes: function(textarea){
this.textarea.setAttribute('wrap', this._originalWrapAttr);
this.textarea.setAttribute('nowrap', this._originalNoWrapAttr); // IE9
this.textarea.setAttribute('spellcheck', this._originalSpellcheckAttr); // iew.
this.textarea.setAttribute('autocapitalize', this._originalAutocapitalizeAttr); // ios meh.
this.textarea.setAttribute('autocorrect', this._originalAutoCorrectAttr); // ios meh.
},
resize: function(width, height){
Gui.css([this.layerContainer, this.syntaxLayer, this.markLayerUnder, this.sourceLayer, this.markLayerOver, this.caretLayer, this.rootContainer], {width:width+'px', height:height+'px'});
return this;
},
setPaddingTop: function(n){
// this method will create padding and set the proper styles to the proper components to make that magic happen
Gui.css([this.textarea, this.syntaxLayer, this.ruler], 'padding-top', n+'px');
Gui.css([this.markLayerOver, this.markLayerUnder, this.caretLayer, this.sourceLayer], 'margin-top', n+'px');
return this;
},
debug: function(){
var e = document.getElementById('dbg');
if (e) {
var f = document.createElement('div');
f.innerHTML = Array.prototype.slice.call(arguments).join(', ');
e.appendChild(f);
}
return arguments[0];
},
output: function(){
var e = document.getElementById('out');
if (e) {
var f = document.createElement('div');
f.innerHTML = Array.prototype.slice.call(arguments).join(', ');
e.appendChild(f);
}
return arguments[0];
},
computeFontSizes: function(){
this.fontSize = this.getFontSize();
this.charsX = Gui.getSize(this.textarea).w / this.fontSize.w;
this.charsY = Gui.getSize(this.textarea).h / this.fontSize.h;
},
fixTextareLinePadding: function(){
// number of lines to populate the textarea with at all times
var min = this.minLines = (Math.floor(this.charsY) == this.charsY ? this.charsY - 1 : Math.floor(this.charsY))-2;
var val = '';
for (var i=0; i<min; ++i) val += '\n';
this.minLinePadding = val;
},
getFontSize: function(){
var e = document.createElement('span');
// we need to copy a bunch of styles from the textarea to get the correct size.
var toCopy = [
'box-sizing', 'white-space',
'font-family', 'font-size', 'font-weight', 'line-height', 'vertical-align', 'word-spacing', 'letter-spacing', 'text-align'
];
Gui.copyCss(this.textarea, e, toCopy);
// make sure the width/height can change
Gui.css(e, {position:'absolute', width:'auto', height:'auto'});
document.body.appendChild(e);
// now measure the difference before and after for one x. since we'll assume 'pre', x has the same size as any other character.
var before = Gui.getSizef(e);
e.innerHTML = 'x';
var after = Gui.getSizef(e);
document.body.removeChild(e); // cleanup
// that's it :)
return {w:after.w-before.w, h:after.h-before.h};
},
matchToColRow: function(match){
var lineStart = this.zeon.lines[match.startLineId].start;
var lastPosOnLine = Math.min(this.zeon.lines[match.startLineId].stop, match.stop);
var col = this.tabMagic(this.lastInput, lineStart, lastPosOnLine);
return {col:col, row:match.startLineId};
},
colRowToXY: function(c,r){
return {x:c * this.fontSize.w, y:r * this.fontSize.h};
},
tabMagic: function(input, lineStart, stop, startCol){
// given input, which column would stop be if we use tab stops
// (tabs arent static 8 chars, they are the remaining number of chars
// up to the next tabstop, which for browsers is always at 8 byte
// interval, which you cant really reliably change)
var pos = lineStart;
var col = startCol || 0;
while (pos < stop) {
if (input[pos] == '\t') col += 8-(col % 8);
else ++col;
++pos;
}
return col;
},
syntaxColorSettings: {
regex: 'color:green;', // regex
identifier: 'color:black;', // identifiers
keyword: 'color:blue;',
hex: 'color:green;',
dec: 'color:green;',
singleString: 'color:green;',
doubleString: 'color:green;',
singleComment: 'color:#c1ad3e;',
multiComment: 'color:grey;',
whitespace: 'border-bottom:1px solid #eee;',
lineTerminator: '',
punctuator: 'color:orange;',
label: '',
error: 'background-color:red;color:white;',
varDecl: '',
undefinedVar: 'text-decoration:line-through;',
unusedVar: 'text-decoration:line-through;',
prematureUsage: 'font-style:italic;',
duplicateProperty: 'text-decoration:line-through;',
leadValue: '',
ecma: 'text-decoration:none;color: pink;',
browser: 'text-decoration:none;color:orange;',
relic: '',