forked from Skyrat-SS13/Skyrat-tg
-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.js
547 lines (516 loc) · 16.3 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
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
/**
* @file
* @copyright 2020 Aleksej Komarov
* @license MIT
*/
import { EventEmitter } from 'common/events';
import { classes } from 'common/react';
import { createLogger } from 'tgui/logging';
import { COMBINE_MAX_MESSAGES, COMBINE_MAX_TIME_WINDOW, IMAGE_RETRY_DELAY, IMAGE_RETRY_LIMIT, IMAGE_RETRY_MESSAGE_AGE, MAX_PERSISTED_MESSAGES, MAX_VISIBLE_MESSAGES, MESSAGE_PRUNE_INTERVAL, MESSAGE_TYPES, MESSAGE_TYPE_INTERNAL, MESSAGE_TYPE_UNKNOWN } from './constants';
import { render } from 'inferno';
import { canPageAcceptType, createMessage, isSameMessage } from './model';
import { highlightNode, linkifyNode } from './replaceInTextNode';
import { Tooltip } from "../../tgui/components";
const logger = createLogger('chatRenderer');
// We consider this as the smallest possible scroll offset
// that is still trackable.
const SCROLL_TRACKING_TOLERANCE = 24;
// List of injectable component names to the actual type
export const TGUI_CHAT_COMPONENTS = {
Tooltip,
};
// List of injectable attibute names mapped to their proper prop
// We need this because attibutes don't support lowercase names
export const TGUI_CHAT_ATTRIBUTES_TO_PROPS = {
"position": "position",
"content": "content",
};
const findNearestScrollableParent = startingNode => {
const body = document.body;
let node = startingNode;
while (node && node !== body) {
// This definitely has a vertical scrollbar, because it reduces
// scrollWidth of the element. Might not work if element uses
// overflow: hidden.
if (node.scrollWidth < node.offsetWidth) {
return node;
}
node = node.parentNode;
}
return window;
};
const createHighlightNode = (text, color) => {
const node = document.createElement('span');
node.className = 'Chat__highlight';
node.setAttribute('style', 'background-color:' + color);
node.textContent = text;
return node;
};
const createMessageNode = () => {
const node = document.createElement('div');
node.className = 'ChatMessage';
return node;
};
const createReconnectedNode = () => {
const node = document.createElement('div');
node.className = 'Chat__reconnected';
return node;
};
const handleImageError = e => {
setTimeout(() => {
/** @type {HTMLImageElement} */
const node = e.target;
const attempts = parseInt(node.getAttribute('data-reload-n'), 10) || 0;
if (attempts >= IMAGE_RETRY_LIMIT) {
logger.error(`failed to load an image after ${attempts} attempts`);
return;
}
const src = node.src;
node.src = null;
node.src = src + '#' + attempts;
node.setAttribute('data-reload-n', attempts + 1);
}, IMAGE_RETRY_DELAY);
};
/**
* Assigns a "times-repeated" badge to the message.
*/
const updateMessageBadge = message => {
const { node, times } = message;
if (!node || !times) {
// Nothing to update
return;
}
const foundBadge = node.querySelector('.Chat__badge');
const badge = foundBadge || document.createElement('div');
badge.textContent = times;
badge.className = classes([
'Chat__badge',
'Chat__badge--animate',
]);
requestAnimationFrame(() => {
badge.className = 'Chat__badge';
});
if (!foundBadge) {
node.appendChild(badge);
}
};
class ChatRenderer {
constructor() {
/** @type {HTMLElement} */
this.loaded = false;
/** @type {HTMLElement} */
this.rootNode = null;
this.queue = [];
this.messages = [];
this.visibleMessages = [];
this.page = null;
this.events = new EventEmitter();
// Scroll handler
/** @type {HTMLElement} */
this.scrollNode = null;
this.scrollTracking = true;
this.handleScroll = type => {
const node = this.scrollNode;
const height = node.scrollHeight;
const bottom = node.scrollTop + node.offsetHeight;
const scrollTracking = (
Math.abs(height - bottom) < SCROLL_TRACKING_TOLERANCE
);
if (scrollTracking !== this.scrollTracking) {
this.scrollTracking = scrollTracking;
this.events.emit('scrollTrackingChanged', scrollTracking);
logger.debug('tracking', this.scrollTracking);
}
};
this.ensureScrollTracking = () => {
if (this.scrollTracking) {
this.scrollToBottom();
}
};
// Periodic message pruning
setInterval(() => this.pruneMessages(), MESSAGE_PRUNE_INTERVAL);
}
isReady() {
return this.loaded && this.rootNode && this.page;
}
mount(node) {
// Mount existing root node on top of the new node
if (this.rootNode) {
node.appendChild(this.rootNode);
}
// Initialize the root node
else {
this.rootNode = node;
}
// Find scrollable parent
this.scrollNode = findNearestScrollableParent(this.rootNode);
this.scrollNode.addEventListener('scroll', this.handleScroll);
setImmediate(() => {
this.scrollToBottom();
});
// Flush the queue
this.tryFlushQueue();
}
onStateLoaded() {
this.loaded = true;
this.tryFlushQueue();
}
tryFlushQueue() {
if (this.isReady() && this.queue.length > 0) {
this.processBatch(this.queue);
this.queue = [];
}
}
assignStyle(style = {}) {
for (let key of Object.keys(style)) {
this.rootNode.style.setProperty(key, style[key]);
}
}
setHighlight(text, color, matchWord, matchCase) {
if (!text || !color) {
this.highlightRegex = null;
this.highlightColor = null;
return;
}
const lines = String(text)
.split(',')
// eslint-disable-next-line no-useless-escape
.map(str => str.trim().replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&'))
.filter(str => (
// Must be longer than one character
str && str.length > 1
));
// Nothing to match, reset highlighting
if (lines.length === 0) {
this.highlightRegex = null;
this.highlightColor = null;
return;
}
const pattern = `${(matchWord ? '\\b' : '')}(${lines.join('|')})${(matchWord ? '\\b' : '')}`;
const flags = 'g' + (matchCase ? '' : 'i');
this.highlightRegex = new RegExp(pattern, flags);
this.highlightColor = color;
}
scrollToBottom() {
// scrollHeight is always bigger than scrollTop and is
// automatically clamped to the valid range.
this.scrollNode.scrollTop = this.scrollNode.scrollHeight;
}
changePage(page) {
if (!this.isReady()) {
this.page = page;
this.tryFlushQueue();
return;
}
this.page = page;
// Fast clear of the root node
this.rootNode.textContent = '';
this.visibleMessages = [];
// Re-add message nodes
const fragment = document.createDocumentFragment();
let node;
for (let message of this.messages) {
if (canPageAcceptType(page, message.type)) {
node = message.node;
fragment.appendChild(node);
this.visibleMessages.push(message);
}
}
if (node) {
this.rootNode.appendChild(fragment);
node.scrollIntoView();
}
}
getCombinableMessage(predicate) {
const now = Date.now();
const len = this.visibleMessages.length;
const from = len - 1;
const to = Math.max(0, len - COMBINE_MAX_MESSAGES);
for (let i = from; i >= to; i--) {
const message = this.visibleMessages[i];
const matches = (
// Is not an internal message
!message.type.startsWith(MESSAGE_TYPE_INTERNAL)
// Text payload must fully match
&& isSameMessage(message, predicate)
// Must land within the specified time window
&& now < message.createdAt + COMBINE_MAX_TIME_WINDOW
);
if (matches) {
return message;
}
}
return null;
}
processBatch(batch, options = {}) {
const {
prepend,
notifyListeners = true,
} = options;
const now = Date.now();
// Queue up messages until chat is ready
if (!this.isReady()) {
if (prepend) {
this.queue = [...batch, ...this.queue];
}
else {
this.queue = [...this.queue, ...batch];
}
return;
}
// Insert messages
const fragment = document.createDocumentFragment();
const countByType = {};
let node;
for (let payload of batch) {
const message = createMessage(payload);
// Combine messages
const combinable = this.getCombinableMessage(message);
if (combinable) {
combinable.times = (combinable.times || 1) + 1;
updateMessageBadge(combinable);
continue;
}
// Reuse message node
if (message.node) {
node = message.node;
}
// Reconnected
else if (message.type === 'internal/reconnected') {
node = createReconnectedNode();
}
// Create message node
else {
node = createMessageNode();
// Payload is plain text
if (message.text) {
node.textContent = message.text;
}
// Payload is HTML
else if (message.html) {
node.innerHTML = message.html;
}
else {
logger.error('Error: message is missing text payload', message);
}
// Get all nodes in this message that want to be rendered like jsx
const nodes = node.querySelectorAll("[data-component]");
for (let i = 0; i < nodes.length; i++) {
const childNode = nodes[i];
const targetName = childNode.getAttribute("data-component");
// Let's pull out the attibute info we need
let outputProps = {};
for (let j = 0; j < childNode.attributes.length; j++) {
const attribute = childNode.attributes[j];
let working_value = attribute.nodeValue;
// We can't do the "if it has no value it's truthy" trick
// Because getAttribute returns "", not null. Hate IE
if (working_value === "$true") {
working_value = true;
}
else if (working_value === "$false") {
working_value = false;
}
else if (!isNaN(working_value)) {
const parsed_float = parseFloat(working_value);
if (!isNaN(parsed_float)) {
working_value = parsed_float;
}
}
let canon_name = attribute.nodeName.replace("data-", "");
// html attributes don't support upper case chars, so we need to map
canon_name = TGUI_CHAT_ATTRIBUTES_TO_PROPS[canon_name];
outputProps[canon_name] = working_value;
}
const oldHtml = { __html: childNode.innerHTML };
while (childNode.firstChild) {
childNode.removeChild(childNode.firstChild);
}
const Element = TGUI_CHAT_COMPONENTS[targetName];
/* eslint-disable react/no-danger */
render(
<Element {...outputProps}>
<span dangerouslySetInnerHTML={oldHtml} />
</Element>, childNode);
/* eslint-enable react/no-danger */
}
// Highlight text
if (!message.avoidHighlighting && this.highlightRegex) {
const highlighted = highlightNode(node,
this.highlightRegex,
text => (
createHighlightNode(text, this.highlightColor)
));
if (highlighted) {
node.className += ' ChatMessage--highlighted';
}
}
// Linkify text
const linkifyNodes = node.querySelectorAll('.linkify');
for (let i = 0; i < linkifyNodes.length; ++i) {
linkifyNode(linkifyNodes[i]);
}
// Assign an image error handler
if (now < message.createdAt + IMAGE_RETRY_MESSAGE_AGE) {
const imgNodes = node.querySelectorAll('img');
for (let i = 0; i < imgNodes.length; i++) {
const imgNode = imgNodes[i];
imgNode.addEventListener('error', handleImageError);
}
}
}
// Store the node in the message
message.node = node;
// Query all possible selectors to find out the message type
if (!message.type) {
// IE8: Does not support querySelector on elements that
// are not yet in the document.
const typeDef = !Byond.IS_LTE_IE8 && MESSAGE_TYPES
.find(typeDef => (
typeDef.selector && node.querySelector(typeDef.selector)
));
message.type = typeDef?.type || MESSAGE_TYPE_UNKNOWN;
}
updateMessageBadge(message);
if (!countByType[message.type]) {
countByType[message.type] = 0;
}
countByType[message.type] += 1;
// TODO: Detect duplicates
this.messages.push(message);
if (canPageAcceptType(this.page, message.type)) {
fragment.appendChild(node);
this.visibleMessages.push(message);
}
}
if (node) {
const firstChild = this.rootNode.childNodes[0];
if (prepend && firstChild) {
this.rootNode.insertBefore(fragment, firstChild);
}
else {
this.rootNode.appendChild(fragment);
}
if (this.scrollTracking) {
setImmediate(() => this.scrollToBottom());
}
}
// Notify listeners that we have processed the batch
if (notifyListeners) {
this.events.emit('batchProcessed', countByType);
}
}
pruneMessages() {
if (!this.isReady()) {
return;
}
// Delay pruning because user is currently interacting
// with chat history
if (!this.scrollTracking) {
logger.debug('pruning delayed');
return;
}
// Visible messages
{
const messages = this.visibleMessages;
const fromIndex = Math.max(0,
messages.length - MAX_VISIBLE_MESSAGES);
if (fromIndex > 0) {
this.visibleMessages = messages.slice(fromIndex);
for (let i = 0; i < fromIndex; i++) {
const message = messages[i];
this.rootNode.removeChild(message.node);
// Mark this message as pruned
message.node = 'pruned';
}
// Remove pruned messages from the message array
this.messages = this.messages.filter(message => (
message.node !== 'pruned'
));
logger.log(`pruned ${fromIndex} visible messages`);
}
}
// All messages
{
const fromIndex = Math.max(0,
this.messages.length - MAX_PERSISTED_MESSAGES);
if (fromIndex > 0) {
this.messages = this.messages.slice(fromIndex);
logger.log(`pruned ${fromIndex} stored messages`);
}
}
}
rebuildChat() {
if (!this.isReady()) {
return;
}
// Make a copy of messages
const fromIndex = Math.max(0,
this.messages.length - MAX_PERSISTED_MESSAGES);
const messages = this.messages.slice(fromIndex);
// Remove existing nodes
for (let message of messages) {
message.node = undefined;
}
// Fast clear of the root node
this.rootNode.textContent = '';
this.messages = [];
this.visibleMessages = [];
// Repopulate the chat log
this.processBatch(messages, {
notifyListeners: false,
});
}
saveToDisk() {
// Allow only on IE11
if (Byond.IS_LTE_IE10) {
return;
}
// Compile currently loaded stylesheets as CSS text
let cssText = '';
const styleSheets = document.styleSheets;
for (let i = 0; i < styleSheets.length; i++) {
const cssRules = styleSheets[i].cssRules;
for (let i = 0; i < cssRules.length; i++) {
const rule = cssRules[i];
cssText += rule.cssText + '\n';
}
}
cssText += 'body, html { background-color: #141414 }\n';
// Compile chat log as HTML text
let messagesHtml = '';
for (let message of this.visibleMessages) {
if (message.node) {
messagesHtml += message.node.outerHTML + '\n';
}
}
// Create a page
const pageHtml = '<!doctype html>\n'
+ '<html>\n'
+ '<head>\n'
+ '<title>SS13 Chat Log</title>\n'
+ '<style>\n' + cssText + '</style>\n'
+ '</head>\n'
+ '<body>\n'
+ '<div class="Chat">\n'
+ messagesHtml
+ '</div>\n'
+ '</body>\n'
+ '</html>\n';
// Create and send a nice blob
const blob = new Blob([pageHtml]);
const timestamp = new Date()
.toISOString()
.substring(0, 19)
.replace(/[-:]/g, '')
.replace('T', '-');
window.navigator.msSaveBlob(blob, `ss13-chatlog-${timestamp}.html`);
}
}
// Make chat renderer global so that we can continue using the same
// instance after hot code replacement.
if (!window.__chatRenderer__) {
window.__chatRenderer__ = new ChatRenderer();
}
/** @type {ChatRenderer} */
export const chatRenderer = window.__chatRenderer__;