forked from botgram/shell-bot
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrenderer.js
267 lines (217 loc) · 8.8 KB
/
renderer.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
/**
* This class keeps a logical mapping of lines to messages.
* It doesn't actually render or send messages, it delegates
* that task to the renderer.
*
* FIXME: do something to prevent extremely long messages to be
* sent (and rejected) when too many lines are inserted in between
* a message.
**/
var escapeHtml = require("escape-html");
var utils = require("./utils");
function Renderer(reply, state, options) {
if (!options) options = {};
this.reply = reply;
this.state = state;
this.options = options;
this.offset = 0;
this.messages = [];
this.orphanLines = [];
this.unfinishedLine = null;
this.totalLines = 0;
state.on("lineChanged", this._lineChanged.bind(this));
state.on("linesRemoving", this._linesRemoving.bind(this));
state.on("linesScrolling", this._linesScrolling.bind(this));
state.on("linesInserted", this._linesInserted.bind(this));
this.initTimers();
}
/** MESSAGE MAPPING **/
Renderer.prototype.ensureLinesCreated = function ensureLinesCreated(y) {
if (this.totalLines < y) {
this.orphanLines = this.orphanLines.concat(this.state.lines.slice(this.totalLines, y));
this.totalLines = y;
this.newLinesChanged = true;
}
};
Renderer.prototype._lineChanged = function _lineChanged(y) {
if (this.state.length - y <= this.orphanLines.length)
this.newLinesChanged = true;
};
Renderer.prototype._linesRemoving = function _linesRemoving(y, n) {
this.ensureLinesCreated(this.state.lines.length);
// Seek until we arrive at the wanted line
y += this.offset;
var idx = 0, lineIdx = 0;
while (y) {
var lines = (idx === this.messages.length) ? this.orphanLines : this.messages[idx].lines;
if (lineIdx < lines.length) { lineIdx++; y--; }
else { idx++; lineIdx = 0; }
}
// Remove following lines
this.totalLines -= n;
while (n) {
var lines = (idx === this.messages.length) ? this.orphanLines : this.messages[idx].lines;
if (lines.splice(lineIdx, 1).length) n--;
else { idx++; lineIdx = 0; }
}
if (idx >= this.messages.length) this.newLinesChanged = true;
};
Renderer.prototype._linesScrolling = function _linesScrolling(n) {
this.ensureLinesCreated(this.state.lines.length);
if (n > 0) {
// Scrolling up: increment offset, discarding message if necessary
this.offset += n;
this.totalLines -= n;
while (this.messages.length) {
var message = this.messages[0];
if (message.lines.length > this.offset) break;
if (message.rendered !== message.ref.lastText) break;
this.offset -= message.lines.length;
this.messages.shift();
}
} else {
// Scrolling down: just delete bottom lines (leaving them would complicate everything)
n = -n;
this._linesRemoving(this.state.lines.length - n, n);
}
};
Renderer.prototype._linesInserted = function _linesInserted(y, n) {
this.ensureLinesCreated(y);
var pos = y;
// Seek until we arrive at the wanted line, *just before the next one*
y += this.offset;
var idx = 0, lineIdx = 0;
while (true) {
var lines = (idx === this.messages.length) ? this.orphanLines : this.messages[idx].lines;
if (lineIdx < lines.length) {
if (!y) break;
lineIdx++; y--;
} else { idx++; lineIdx = 0; }
}
// Insert lines
this.totalLines += n;
while (n) {
var lines = (idx === this.messages.length) ? this.orphanLines : this.messages[idx].lines;
lines.splice(lineIdx, 0, this.state.lines[pos]);
n--, lineIdx++, pos++;
}
if (idx === this.messages.length) this.newLinesChanged = true;
};
Renderer.prototype.update = function update() {
this.ensureLinesCreated(this.state.lines.length);
// Rerender messages, scheduling flush if some changed
var linesChanged = false;
this.messages.forEach(function (message) {
var rendered = this.render(message);
if (rendered !== message.rendered) {
message.rendered = rendered;
linesChanged = true;
}
}.bind(this));
if (linesChanged) this.editedLineTimer.set();
if (this.newLinesChanged) this.newLineTimer.reset();
this.newLinesChanged = false;
// Make sure orphan lines are processed
this.orphanLinesUpdated();
};
Renderer.prototype.emitMessage = function emitMessage(count, silent, disablePreview) {
if (count < 0 || count > this.orphanLines.length) throw new Error("Should not happen.");
if (count > this.options.maxLinesEmitted)
count = this.options.maxLinesEmitted;
var lines = this.orphanLines.splice(0, count);
var message = { lines: lines };
this.messages.push(message);
message.rendered = this.render(message);
var reply = this.reply.silent(silent).disablePreview(disablePreview);
message.ref = new utils.EditedMessage(reply, message.rendered, "HTML");
this.orphanLinesUpdated();
};
/** HTML RENDERING **/
/* Given a line, return true if potentially monospaced */
Renderer.prototype.evaluateCode = function evaluateCode(str) {
//FIXME: line just between two code lines should be come code
if (str.indexOf(" ") !== -1 || /[-_,:;<>()/\\~|'"=^]{4}/.exec(str))
return true;
return false;
};
/* Given a message object, render to an HTML snippet */
Renderer.prototype.render = function render(message) {
var cursorString = this.state.getMode("cursorBlink") ? this.options.cursorBlinkString : this.options.cursorString;
var isWhitespace = true, x = this.state.cursor[0];
var html = message.lines.map(function (line, idx) {
var hasCursor = (this.state.getMode("cursor")) && (this.state.getLine() === line);
if (!line.code && this.evaluateCode(line.str)) line.code = true;
var content = line.str;
if (hasCursor || line.str.trim().length) isWhitespace = false;
if (idx === 0 && !content.substring(0, this.options.startFill.length).trim()) {
// The message would start with spaces, which would get trimmed by telegram
if (!(hasCursor && x < this.options.startFill.length))
content = this.options.startFill + content.substring(this.options.startFill.length);
}
if (hasCursor)
content = escapeHtml(content.substring(0, x)) + cursorString + escapeHtml(content.substring(x));
else
content = escapeHtml(content);
if (line.code) content = "<code>" + content + "</code>";
return content;
}.bind(this)).join("\n");
if (isWhitespace) return "<em>(empty)</em>";
return html;
};
/** FLUSH SCHEDULING **/
Renderer.prototype.initTimers = function initTimers() {
// Set when an existent line changes, cancelled when edited lines flushed
this.editedLineTimer = new utils.Timer(this.options.editTime).on("fire", this.flushEdited.bind(this));
// Set when a new line is added or changed, cancelled on new lines flush
this.newChunkTimer = new utils.Timer(this.options.chunkTime).on("fire", this.flushNew.bind(this));
// Reset when a new line is added or changed, cancelled on new lines flush
this.newLineTimer = new utils.Timer(this.options.lineTime).on("fire", this.flushNew.bind(this));
// Set when there is an unfinished nonempty line, cancelled when reference changes or line becomes empty
this.unfinishedLineTimer = new utils.Timer(this.options.unfinishedTime).on("fire", this.flushUnfinished.bind(this));
this.newChunkTimer.on("active", function () {
this.reply.action("typing");
}.bind(this));
//FIXME: should we emit actions on edits?
};
Renderer.prototype.orphanLinesUpdated = function orphanLinesUpdated() {
var newLines = this.orphanLines.length - 1;
if (newLines >= this.options.maxLinesWait) {
// Flush immediately
this.flushNew();
} else if (newLines > 0) {
this.newChunkTimer.set();
} else {
this.newChunkTimer.cancel();
this.newLineTimer.cancel();
}
// Update unfinished line
var unfinishedLine = this.orphanLines[this.orphanLines.length - 1];
if (unfinishedLine && this.totalLines === this.state.rows && unfinishedLine.str.length === this.state.columns)
unfinishedLine = null;
if (this.unfinishedLine !== unfinishedLine) {
this.unfinishedLine = unfinishedLine;
this.unfinishedLineTimer.cancel();
}
if (unfinishedLine && unfinishedLine.str.length) this.unfinishedLineTimer.set();
else this.unfinishedLineTimer.cancel();
};
Renderer.prototype.flushEdited = function flushEdited() {
this.messages.forEach(function (message) {
if (message.rendered !== message.ref.lastText)
message.ref.edit(message.rendered);
});
this.editedLineTimer.cancel();
};
Renderer.prototype.flushNew = function flushNew() {
this.flushEdited();
var count = this.orphanLines.length;
if (this.unfinishedLine) count--;
if (count <= 0) return;
this.emitMessage(count, !!this.options.silent, !!this.options.hidePreview);
};
Renderer.prototype.flushUnfinished = function flushUnfinished() {
do this.flushNew(); while (this.orphanLines.length > 1);
if (this.orphanLines.length < 1 || this.orphanLines[0].str.length === 0) return;
this.emitMessage(1, !!this.options.unfinishedSilent, !!this.options.unfinishedHidePreview);
};
exports.Renderer = Renderer;