-
Notifications
You must be signed in to change notification settings - Fork 0
/
editor.js
119 lines (105 loc) · 3.09 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
function MonospaceTextEditor(
textConfig,
text
) {
this.text = new MonospaceText(
textConfig.letterWidth,
textConfig.lineHeight,
text
);
this.cursor = new EditorCursor(this, {
lineNumber: 0,
lineLetterNumber: 0
});
this.editorHolder = null;
return this;
}
MonospaceTextEditor.prototype.insert = function (letter) {
this.text.insert(this.cursor.position, letter);
this.editorHolder.innerHTML = "";
this.text.write(this.editorHolder);
this.cursor.right();
};
MonospaceTextEditor.prototype.newline = function () {
this.text.newline(this.cursor.position);
this.editorHolder.innerHTML = "";
this.text.write(this.editorHolder);
this.cursor.newline();
};
MonospaceTextEditor.prototype.backspace = function () {
var newCursorPosition = this.text.backspace(this.cursor);
this.editorHolder.innerHTML = "";
this.text.write(this.editorHolder);
this.cursor.set(
newCursorPosition.lineNumber,
newCursorPosition.lineLetterNumber
);
};
MonospaceTextEditor.prototype.endOfLine = function () {
var newCursorPosition = this.text.endOfLine(this.cursor.position.lineNumber);
this.cursor.set(
newCursorPosition.lineNumber,
newCursorPosition.lineLetterNumber
);
};
MonospaceTextEditor.prototype.beginOfLine = function () {
var newCursorPosition = this.text.beginOfLine(this.cursor.position.lineNumber);
this.cursor.set(
newCursorPosition.lineNumber,
newCursorPosition.lineLetterNumber
);
}
MonospaceTextEditor.prototype.edit = function (editorHolder) {
this.editorHolder = editorHolder;
this.text.write(this.editorHolder);
this.setCursor(this.cursor);
var that = this;
addEventListener('keypress', function (event) {
switch (event.keyCode) {
case 38:
that.cursor.up();
break;
case 40:
that.cursor.down();
break;
case 37:
that.cursor.left();
break;
case 39:
that.cursor.right();
break;
case 13:
that.newline();
break;
case 8:
that.backspace();
break;
case 35:
that.endOfLine();
break;
case 36:
that.beginOfLine();
break;
}
}, false);
addEventListener('keypress', function (event) {
if (event.charCode) {
var letter = String.fromCharCode(event.charCode);
that.insert(letter);
}
}, false);
};
MonospaceTextEditor.prototype.setCursor = function (lineNumber, lineLetterNumber) {
var lines = this.text.lines();
if (lines[lineNumber]) {
var glyphs = lines[lineNumber].glyphs();
if (glyphs[lineLetterNumber]) {
glyphs[lineLetterNumber].setActive();
return true;
} else {
glyphs[glyphs.length - 1].setActive();
return true;
}
}
return false;
};