-
Notifications
You must be signed in to change notification settings - Fork 34
/
ChatImprovements.user.js
2534 lines (2211 loc) · 77.3 KB
/
ChatImprovements.user.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
// ==UserScript==
// @name Chat Improvements
// @description New responsive user list with usernames and total count, more timestamps, use small signatures only, mods with diamonds, message parser (smart links), timestamps on every message, collapse room description and room tags, mobile improvements, expand starred messages on hover, highlight occurrences of same user link, room owner changelog, pretty print styles, and more...
// @homepage https://github.com/samliew/SO-mod-userscripts
// @author Samuel Liew
// @version 4.7.13
//
// @match https://chat.stackoverflow.com/*
// @match https://chat.stackexchange.com/*
// @match https://chat.meta.stackexchange.com/*
//
// @connect *
// @connect self
// @connect stackoverflow.com
// @connect serverfault.com
// @connect superuser.com
// @connect askubuntu.com
// @connect mathoverflow.com
// @connect stackexchange.com
//
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/se-ajax-common.js
// @require https://raw.githubusercontent.com/samliew/SO-mod-userscripts/master/lib/common.js
//
// @grant GM_xmlhttpRequest
// ==/UserScript==
/* globals StackExchange, store, fkey, MS, addStylesheet */
/// <reference types="./globals" />
'use strict';
const transcriptIndicatorText = ' (transcript)';
const chatDomains = [
{ host: 'chat.stackexchange.com', name: 'Chat.SE' },
{ host: 'chat.meta.stackexchange.com', name: 'Chat.MSE' },
{ host: 'chat.stackoverflow.com', name: 'Chat.SO' }
];
const tzOffset = new Date().getTimezoneOffset();
const now = new Date();
const dayAgo = Date.now() - MS.oneDay;
const weekAgo = Date.now() - MS.oneWeek;
const newUserList = $(`<div id="present-users-list"><span class="users-count"></span></div>`);
const isTranscriptPage = location.href.includes("/transcript/") || location.href.includes("/conversation/");
let messageEvents = [];
// Get room name for chat message id
async function getRoomForMessage(mid, hostname = location.hostname) {
mid = Number(mid);
if (isNaN(mid) || mid <= 0 || Math.round(mid) !== mid) { throw new Error('getRoomForMessage: Invalid message id', ...arguments); }
if (!['chat.stackoverflow.com', 'chat.stackexchange.com', 'chat.meta.stackexchange.com'].includes(hostname)) { throw new Error('getRoomForMessage: Invalid chat hostname', ...arguments); }
if (hostname !== location.hostname) { throw new Error('getMessage: No support for external hosts yet', ...arguments); }
const resp = await fetch(`${location.origin}/transcript/message/${mid}`);
const data = await resp.text();
const document = new DOMParser().parseFromString(data, 'text/html');
return {
name: document.title.split(' - ')?.shift() ?? document.title,
id: Number(document.querySelector('link[rel="canonical"]')?.getAttribute('href')?.match(/\/transcript\/(\d+)\//)?.pop()) || null,
hostname
}
}
// Get chat message details from history page
async function getMessage(mid, hostname = location.hostname) {
mid = Number(mid);
if (isNaN(mid) || mid <= 0 || Math.round(mid) !== mid) { throw new Error('getMessage: Invalid message id', ...arguments); }
if (!['chat.stackoverflow.com', 'chat.stackexchange.com', 'chat.meta.stackexchange.com'].includes(hostname)) { throw new Error('getMessage: Invalid chat hostname', ...arguments); }
if (hostname !== location.hostname) { throw new Error('getMessage: No support for external hosts yet', ...arguments); }
const resp = await fetch(`https://${hostname}/messages/${mid}/history`);
const data = await resp.text();
const document = new DOMParser().parseFromString(data, 'text/html');
const msg = document.querySelector('.message');
const msgContent = msg.querySelector('.content');
const userId = Number(msg.closest('.monologue')?.className.match(/(?<=user--?)\d+/)?.pop());
const username = msg.closest('.monologue').querySelector('.username a')?.innerText;
const timestamp = msg.parentElement.querySelector('.timestamp')?.innerText;
const permalink = msg.querySelector('a')?.getAttribute('href');
const parentId = Number(document.querySelector('.message-source')?.innerText.match(/(?<=^:)\d+/)?.pop()) || null;
const stars = Number(msg.querySelector('.stars .times')?.innerText) || 0;
const isPinned = !!msg.querySelector('.owner-star');
const { name: roomName, roomId: _rid } = await getRoomForMessage(mid, hostname);
const roomId = _rid || Number(permalink.match(/(?<=\/transcript\/)\d+/)?.pop()) || null;
return {
id: mid,
parentId,
roomId,
roomName,
hostname,
timestamp,
permalink,
userId,
username,
html: msgContent?.innerHTML.trim(),
text: msgContent?.innerText.trim(),
stars,
isPinned
};
}
// Get room name for chat message id
async function getRoomDetails(roomId, hostname = location.hostname) {
roomId = Number(roomId);
if (isNaN(roomId) || roomId <= 0 || Math.round(roomId) !== roomId) { throw new Error('getRoomDetails: Invalid room id', ...arguments); }
if (!['chat.stackoverflow.com', 'chat.stackexchange.com', 'chat.meta.stackexchange.com'].includes(hostname)) { throw new Error('getRoomDetails: Invalid chat hostname', ...arguments); }
if (hostname !== location.hostname) { throw new Error('getRoomDetails: No support for external hosts yet', ...arguments); }
const resp = await fetch(`https://${hostname}/rooms/info/${roomId}`);
const data = await resp.text();
const document = new DOMParser().parseFromString(data, 'text/html');
const [firstMessage, lastMessage] = [...document.querySelectorAll('.room-stats')[1].querySelectorAll('td:not(.room-keycell')].map(v => v.innerText.trim());
return {
roomName: document.querySelector('h1').innerText,
roomId,
hostname,
description: document.querySelector('.roomcard-xxl h1').nextElementSibling?.innerText.trim().replace(/\s+edit$/, ''),
totalMessages: Number(document.querySelector('.room-message-count-xxl')?.innerText.trim()) || 0,
allTimeUsers: Number(document.querySelector('.room-user-count-xxl')?.innerText.trim()) || 0,
firstMessage,
lastMessage,
};
}
// Send new message in current room
function sendMessage(message) {
return new Promise(function (resolve, reject) {
if (typeof message === 'undefined' || message == null) { reject(); return; }
$.post(`${location.origin}/chats/${CHAT.CURRENT_ROOM_ID}/messages/new`, {
fkey: fkey,
text: message
})
.done(function (v) {
resolve(v);
})
.fail(reject);
});
}
function processMessageTimestamps(events) {
if (typeof events === 'undefined') return;
// Remove existing "yst" timestamps in favour of ours for consistency
$('.timestamp').filter((i, el) => el.innerText.includes('yst')).remove();
/*
event: {
content
event_type
message_id
parent_id
room_id
time_stamp
user_id
user_name
}
*/
// Find messages for each event
events.forEach(function (event) {
const msgEl = $('#message-' + event.message_id).parent('.messages');
if (!msgEl.length) return;
// Remove existing timestamp so we can replace with a timestamp that contains seconds
msgEl.find('.timestamp').remove();
// Make and insert timestamp
const d = new Date(event.time_stamp * 1000);
let time = `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}`;
let prefix = '';
if (d < weekAgo) {
prefix = new Intl.DateTimeFormat('en-US', { month: 'short', day: 'numeric' }).format(d) + ', ';
}
else if (d.getDate() != now.getDate()) {
prefix = new Intl.DateTimeFormat('en-US', { weekday: 'short' }).format(d) + ' ';
}
msgEl.prepend(`<div class="timestamp js-dynamic-timestamp" title="${dateToIsoString(d)}">${prefix}${time}</div>`);
});
// Cache results
// Filter out the unique items, then merge with our cache
// https://stackoverflow.com/a/23080662
//messageEvents = messageEvents.concat(events.filter(function (item) {
// return messageEvents.indexOf(item) < 0;
//}));
}
function getMessageEvents(beforeMsgId = 0, num = 100) {
return new Promise(function (resolve, reject) {
if (typeof CHAT === 'undefined' || CHAT.CURRENT_ROOM_ID === 'undefined') { reject(); return; }
if (fkey == '') { reject(); return; }
$.post(`${location.origin}/chats/${CHAT.CURRENT_ROOM_ID}/events`, {
'fkey': fkey,
'since': beforeMsgId,
'mode': 'Messages',
'msgCount': num
})
.done(function (v) {
processMessageTimestamps(v.events);
resolve(v.events);
})
.fail(reject);
});
}
function updateUserlist(init = false) {
// Do not update new user list if mouse is on
if (newUserList.hasClass('mouseon')) return;
// Do not update user list if updated less than X seconds ago
if (init) {
newUserList.addClass('js-no-update');
}
else if (!init && newUserList.hasClass('js-no-update')) {
return;
}
// Add new list to parent if not initialized yet
const userlist = $('#present-users');
if (newUserList.parents('#present-users').length == 0) {
newUserList.insertAfter(userlist);
}
// Bugfix: remove dupes from original list, e.g.: when any new message posted
userlist.children('.user-container').each(function () {
$(this).siblings(`[id="${this.id}"]`).remove();
});
// Create new temp list with users
const templist = $(`<div id="present-users-list"></div>`);
// Clone remaining users into temp list
const users = userlist.children('.user-container').clone(true).each(function () {
// Get username from img title attribute
const username = $(this).find('img')[0].title;
// Apply a class to inactive users
$(this).toggleClass('inactive', this.style.opacity == "0.15");
// Remove other fluff, append username, then insert into list
$(this).off().removeAttr('style id alt width height').find('.data').remove();
$(this).appendTo(templist).append(`<span class="username" title="${username}">${username}</span>`);
});
if (init) {
// Redo list
newUserList.children('.user-container').remove();
newUserList.append(templist.children());
}
else {
// Compare list with temp list and copy changes over
templist.children().reverse().each(function () {
const clname = '.' + this.className.match(/(user-\d+)/)[0];
if (newUserList.find(clname).length == 0) {
newUserList.prepend(this);
}
});
}
//console.log('userlist updated', init, users.length);
// Add count of users below
newUserList.find('.users-count').text(users.length);
// Add "currentuser" class to own userlist items
$('#sidebar .user-' + CHAT.CURRENT_USER_ID).addClass('user-currentuser');
// Remove full update blocker after X seconds
setTimeout(() => {
newUserList.removeClass('js-no-update');
}, 10000);
}
function initLoadMoreLinks() {
// Always load more for long messages
// can't use this for some reason: $('.more-data').click();
// this opens the link in a new window sometimes: el.click();
// so we implement our own full text fetcher
$('.content .more-data').each(function (i, el) {
const parent = $(this).parent('.content');
$.get(el.href).done(function (data) {
const tagName = parent.find(".partial").prop("tagName");
let full;
if (tagName === 'PRE') {
// pre-formatted text, just remove leading spaces
const text = data.replace(/(^|\n)[ ]{4}/g, '$1');
full = $('<pre class="full"></pre>').html(text);
} else {
// normal text or a quote
const isQuote = /^>\s/.test(data);
const html = data.replace(/^(:\d+|>) /, '').replace(/\r\n?|\n/g, ' <br> ').replace(/(https?:\/\/(\S+))/gi, '<a href="$1">$2</a>');
full = $(`<div class="full {isQuote ? 'quote' : 'text'}"></div>`).append(html);
};
parent.empty().append(full);
});
});
}
function reapplyPersistentChanges() {
// Remove "switch to" from other room title tooltips
$('#my-rooms > li > a').each(function () {
if (this.classList.contains('reply-count')) return;
this.innerText = this.title.replace('switch to ', '');
});
// Show other room's latest message in a tooltip when hovered
$('#my-rooms .last-message .text').each(function () {
this.title = this.innerText;
});
// Expand more starred posts in AMA chatroom since we have a scrolling sidebar
$('#sidebar-content.wmx3 span.more').filter((i, el) => el.parentNode.innerText.includes('starred') && el.innerText.includes('more')).trigger('click');
// Apply class to starred posts usernames in sidebar
$('#starred-posts a[href^="/users/"]').addClass('starred-signature');
// Remove existing "yst" timestamps in favour of ours for consistency
$('.timestamp').filter((i, el) => el.innerText.includes('yst')).remove();
initLoadMoreLinks();
// If topbar is found
if ($('#topbar').length) {
$('.reply-info').off('click');
}
// Remove system messages if there are only ignored users messages between
$('.monologue:hidden').remove();
$('.system-message-container').prev('.system-message-container').hide();
}
function applyTimestampsToNewMessages() {
setInterval(function () {
// Append timestamps when new messages detected (after the last message with a timestamp!)
const lastMessage = $('.monologue').filter((i, el) => $(el).find('.timestamp').length > 0).last();
const newMsgs = lastMessage.nextAll().filter((i, el) => $(el).find('.timestamp').length == 0).find('.messages');
// No new messages, do nothing
if (newMsgs.length == 0) return;
// Apply timestamps
const d = new Date();
let time = d.getHours() + ':' + (d.getMinutes().toString().length != 2 ? '0' : '') + d.getMinutes();
newMsgs.each(function () {
$(this).prepend(`<div class="timestamp">${time}</div>`);
});
}, 1000);
}
/* Message parser functions */
async function _parseMessageLink(i, el) {
// Ignore links to bookmarked conversations
if (/\/rooms\/\d+\/conversation\//.test(el.href)) { }
// Ignore X messages moved links
else if (/^\d+ messages?$/.test(el.innerText)) { }
// Ignore room info links
else if (el.href.includes('/info/')) { }
// Convert all other chatroom links to the room transcript
else if (el.href.includes('chat.') && el.href.includes('/rooms/')) {
el.href = el.href.replace('/rooms/', '/transcript/');
el.innerText = el.innerText.replace('/rooms/', '/transcript/');
}
// Detect type of link
const textContainsUrl = /(^(?:https?:)?\/\/)/.test(el.innerText) || el.href.includes(el.innerText);
const isChatTranscript = /chat\.(?:meta\.)?stack(overflow|exchange)\.com\/(?:transcript(?:\/message)?\/\d+|\/rooms\/\d+\/conversation\/)/.test(el.href);
// Try to get room and message ID from link
let roomName, isPinned, stars;
let roomId = Number(el.href.match(/(?<=\/(?:rooms(?:\/message)?|transcript)\/)(\d+)/)?.pop()) || null;
let messageId = Number(el.href.match(/(?<=#|\?m=)\d+/)?.pop()) || null;
if (messageId && !roomId && el.hostname === location.hostname) {
const msg = await getMessage(messageId, el.hostname);
roomId = msg.roomId;
roomName = msg.roomName;
isPinned = msg.isPinned;
stars = msg.stars;
}
else if (roomId && !roomName && el.hostname === location.hostname) {
const room = await getRoomDetails(roomId);
roomName = room.roomName;
}
// Attempt to display chat domain, and room name or message id with (transcript) label
if (isChatTranscript) {
// If link text is a plain URL, change text to show room name
if (textContainsUrl) {
// Link has messageId and roomName
if (messageId && roomName) {
el.textContent = `${isPinned ? '📌 ' : ''}${stars > 1 ? `${stars}x⭐ ` : stars ? '⭐' : ''}#${messageId} in ${roomName}${transcriptIndicatorText}`;
}
else if (roomName) {
el.textContent = `${roomName}${transcriptIndicatorText}`;
}
else {
const { name: hostname } = chatDomains.filter(d => el.hostname === d.host)?.pop() || { name: el.hostname };
if (messageId && roomId) {
el.textContent = `#${messageId} in room #${roomId} ${hostname}${transcriptIndicatorText}`;
}
else if (messageId) {
el.textContent = `#${messageId} ${hostname}${transcriptIndicatorText}`;
}
else if (roomId) {
el.textContent = `Room #${roomId} ${hostname}${transcriptIndicatorText}`;
}
}
// Links should not wrap across lines
el.classList.add('nowrap');
}
}
// Shorten Q&A links
else if (((el.href.includes('/questions/') && !el.href.includes('/tagged/')) || el.href.includes('/q/') || el.href.includes('/a/')) && el.innerText.includes('…')) {
var displayUrl = el.href;
// Strip certain querystrings
displayUrl = displayUrl.replace(/[?&]noredirect=1/, '');
// Get comment target (is it on a question or answer), based on second parameter
let commentId = null, commentTarget = null;
if (/#comment\d+_\d+$/.test(el.href)) {
commentId = el.href.match(/#comment(\d+)_\d+$/)[1];
commentTarget = Number(el.href.match(/#comment\d+_(\d+)$/)[1]);
}
// If long answer link
if (el.href.includes('/questions/') && /\/\d+\/[\w-]+\/\d+/.test(el.href)) {
// If has comment in url, check if comment target is answer
if (commentId != null && commentTarget != null) {
const answerId = Number(el.href.match(/\/\d+\/[\w-]+\/(\d+)/)[1]);
if (commentTarget == answerId) {
// Convert to short answer link text with comment hash
displayUrl = displayUrl.replace(/\/questions\/\d+\/[^\/]+\/(\d+)(#\d+)?(#comment\d+_\d+)?$/i, '/a/$1') +
'#comment' + commentId;
}
else {
// Convert to short question link text with comment hash
displayUrl = displayUrl.replace(/\/questions\/(\d+)\/[^\/]+\/(\d+)(#\d+)?(#comment\d+_\d+)?$/i, '/q/$1') +
'#comment' + commentId;
}
}
else {
// Convert to short answer link text
displayUrl = displayUrl.replace(/\/questions\/\d+\/[^\/]+\/(\d+)(#\d+)?(#comment\d+_\d+)?$/i, '/a/$1');
}
}
// If long question link
else {
// Convert to short question link text
// Avoid truncating inline question links
displayUrl = displayUrl.replace('/questions/', '/q/').replace(/\?(&?(cb|noredirect)=\d+)+/i, '').replace(/(\/\D[\w-]*)+((\/\d+)?#comment\d+_\d+)?$/, '') +
(commentId != null ? '#comment' + commentId : '');
}
el.innerText = displayUrl;
}
// Shorten /questions/tagged links, but ignore tag inline-boxes
else if (el.href.includes('/questions/tagged/') && el.children.length == 0) {
el.innerText = el.href.replace('/questions/tagged/', '/tags/');
}
// Remove user id if question or answer
if ((el.href.includes('/q/') || el.href.includes('/a/')) && /\/\d+\/\d+$/.test(el.href)) {
el.href = el.href.replace(/\/\d+$/, '');
el.innerText = el.innerText.replace(/\/\d+$/, '');
}
// For all other links that are still truncated at this stage,
if (el.innerText.includes('…')) {
// display full url if url is <64 chars incl protocol
if (el.href.length < 64) {
el.innerText = el.href;
}
// else display next directory path if it's short enough
else {
let displayed = el.innerText.replace('…', '');
let hiddenPath = el.href.replace(/^https?:\/\/(www\.)?/, '').replace(displayed, '').replace(/\/$/, '').split('/');
let hiddenPathLastIndex = hiddenPath.length - 1;
let shown1;
//console.log(hiddenPath);
// If next hidden path is short, or is only hidden path
if (hiddenPath[0].length <= 25 || (hiddenPath.length == 1 && hiddenPath[hiddenPathLastIndex].length <= 50)) {
el.innerText = displayed + hiddenPath[0];
shown1 = true;
// if there are >1 hidden paths, continue displaying ellipsis at the end
if (hiddenPath.length > 1) {
el.innerText += '/…';
}
}
// Display last directory path if it's short enough
if (hiddenPath.length > 1 && hiddenPath[hiddenPathLastIndex].length <= 50) {
el.innerText += '/' + hiddenPath[hiddenPathLastIndex];
// if full url is shown at this stage, strip ellipsis
if (shown1 && hiddenPath.length <= 2) {
el.innerText = el.innerText.replace('/…', '');
}
}
}
}
// Finally we trim all protocols and trailing slashes for shorter URLs
if (/(^https?|\/$)/.test(el.innerText)) {
el.innerText = el.innerText.replace(/^https?:\/\//i, '').replace(/\/$/, '');
}
}
function _parseRoomMini(i, el) {
// Convert main chatroom title link to the room transcript
const roomLink = el.querySelector('a[href*="/rooms/"]');
roomLink.href = roomLink.href.replace('/rooms/', '/transcript/');
if (roomLink.title && roomLink.title.length > roomLink.textContent.trim()) {
roomLink.textContent = roomLink.title;
roomLink.title = '';
}
// Show longer description and link links
// This also allows SmartPostLinks to fetch post data
const desc = el.querySelector('.room-mini-description');
if (desc.title?.length) {
desc.innerHTML = desc.title?.replace(/https?:\/\/[^\s]+/gi, '<a href="$&">$&</a>');
desc.title = '';
}
}
function _parseMessagesForUsernames(i, el) {
const mentionRegex = /(^|\s)@([\w\u00C0-\u017F.-]+[^.\s])(\.?(?:\b|\s))/g;
// Ignore oneboxes
if ($(el).find('.onebox').length > 0) return;
// Has mentions, wrap in span tag so we can select and highlight it
// (\b|\s) instead of just \b so it allows usernames ending with periods '.'
if (el.textContent.includes('@')) {
// Loop through all child nodes
el.childNodes.forEach(function (node) {
// If text node and contains mention
if (node.nodeType == 3 && mentionRegex.test(node.textContent)) {
// Replace @username with <span class="mention-others" data-username="username">@username</span>
const replacedHtml = node.textContent.replace(mentionRegex, '$1<span class="mention-others" data-username="$2">@$2</span>$3');
// Insert new html before text node, then remove text node
node.parentNode.insertBefore(document.createRange().createContextualFragment(replacedHtml), node);
node.remove();
}
});
}
}
/*
This function is intended to check for new messages and parse the message text
- It converts non-transcript chatroom links to the room transcript
- Attempt to display chat domain, and room name or message id with (transcript) label
- Also unshortens Q&A links that are truncated by default with ellipsis
*/
function initMessageParser() {
setInterval(function () {
// Get new messages
const newMsgs = $('.message').not('.js-parsed').addClass('js-parsed');
if (newMsgs.length > 0) {
// Try to detect usernames and mentions in messages
newMsgs.find('.content').each(_parseMessagesForUsernames);
// Parse message links, but ignoring oneboxes, room minis, and quotes
newMsgs.find('.content a').filter(function () {
return $(this).parents('.onebox, .has-onebox, .quote, .room-mini').length == 0;
}).each(_parseMessageLink);
// Parse room minis
newMsgs.find('.room-mini').each(_parseRoomMini);
}
// Get new starred messages
const newStarredMsgs = $('#starred-posts li').not('.js-parsed').addClass('js-parsed');
if (newStarredMsgs.length > 0) {
// Parse links, but ignoring transcript links
newStarredMsgs.find('a').filter(function () {
return !this.href.includes('/transcript/');
}).each(_parseMessageLink);
}
// Parse user-popups, if it's a room link, convert to transcript link
const userpopup = $('.user-popup');
userpopup.find('a').filter(function () {
return this.pathname.indexOf('/rooms/') == 0 && $(this).attr('href') != '#';
}).each(_parseMessageLink);
// Parse notifications (room invites)
const notificationLinks = $('.notification-message a').filter(function () {
return this.pathname.indexOf('/rooms/') == 0 && $(this).attr('href') != '#';
}).each(_parseMessageLink);
}, 1000);
}
/* End message parser */
function initUserHighlighter() {
// Highlight elements with username on any mouse hover
const eventSelector = '.tiny-signature, .sidebar-widget .user-container, .mention-others, .content a[href*="/users/"]';
$('#widgets, #chat, #transcript').on('mouseover', eventSelector, function () {
const userName = (this.dataset.username || $(this).find('.username, .name').last().text() || this.innerText || "").replace(/[^\w\u00C0-\u017F.-]+/g, '').toLowerCase();
if (userName) {
$('.username .name, .username, .mention, .mention-others, .starred-signature')
.filter((i, el) => (el.dataset.username || el.title || el.innerText).replace(/[^\w\u00C0-\u017F.-]+/g, '').toLowerCase() == userName)
.closest('.mention, .mention-others, .signature, .sidebar-widget .user-container, a[href*="/users/"]').addClass('js-user-highlight');
$('#present-users-list').addClass('mouseon');
}
}).on('mouseout', eventSelector, function () {
$('.js-user-highlight').removeClass('js-user-highlight');
$('#present-users-list').removeClass('mouseon');
});
}
/**
* @summary factory for chat top navigation bar buttons
* @param {string} id button id
* @param {string} text button text
* @param {{
* onClick?: (event: MouseEvent) => void | Promise<void>,
* url?: string
* }} options configuration options
*/
const makeChatTopNavButton = (id, text, options) => {
const { url, onClick } = options;
const button = document.createElement('a');
button.classList.add('button')
button.rel = 'noopener noreferrer';
button.id = id;
button.textContent = text;
if (url) button.href = url;
if (typeof onClick === 'function') {
button.addEventListener('click', onClick);
}
return button;
}
function addLinksToOtherChatDomains() {
// Add links to other chat domains when on Chat.SO
const allrooms = $('#allrooms, #info a:first');
if (allrooms[0].href.includes('stackoverflow.com')) {
const buttons = [
makeChatTopNavButton('allrooms2', 'Chat.SE', { url: 'https://chat.stackexchange.com' }),
makeChatTopNavButton('allrooms3', 'Chat.MSE', { url: 'https://chat.meta.stackexchange.com' }),
]
allrooms.after(...buttons)
}
}
// Improve reply-info marker hover & click
function initBetterMessageLinks() {
const scrollOffset = 67 + 10; // 67px for header and nav, 10px for padding
window.hiTimeout = null;
if (!isTranscriptPage) {
// Try loading more messages once on page load
$('#chat').one('mouseover', '.reply-info', function (evt) {
$('#getmore').trigger('click');
});
// Re-implement scroll to message, but not transcripts (use ChatTranscriptHelper)
$('#chat').on('click', '.reply-info', function (evt) {
// Clear all message highlights on page
if (window.hiTimeout) clearTimeout(window.hiTimeout);
$('.highlight').removeClass('highlight');
const message = $(this).closest('.message');
const parentMid = Number(this.href.match(/#(\d+)/).pop());
const parentMsg = $('#message-' + parentMid).addClass('highlight');
const dialogMsg = $('#dialog-message-' + parentMid);
// Check if message is on page
if (parentMsg.length) {
$('html, body').animate({ scrollTop: parentMsg.offset().top - scrollOffset }, 400, function () {
window.hiTimeout = setTimeout(() => { parentMsg.removeClass('highlight'); }, 3000);
});
return false;
}
// Else message is off page, show in popup first
// second clicking will trigger default behaviour (open in new window)
else if (!dialogMsg.length) {
getMessage(parentMid).then(function (msg) {
const parentIcon = isNaN(msg.parentId) ? `<a class="reply-info" title="This is a reply to an earlier message" href="/transcript/message/${msg.parentId}#${msg.parentId}"> </a>` : '';
const parentDialog = $(`
<div class="dialog-message" id="dialog-message-${msg.id}">
<a class="action-link" href="/transcript/message/${msg.id}#${msg.id}"><span class="img menu"> </span></a>
${parentIcon}
<div class="content">${msg.html}</div>
<span class="meta"><span class="newreply" data-mid="${msg.id}" title="link my next chat message as a reply to this"></span></span>
<span class="flash"><span class="stars vote-count-container"><span class="img vote" title="star this message as useful / interesting for the transcript"></span><span class="times">${msg.stars > 0 ? msg.stars : ''}</span></span></span>
</div>`);
message.addClass('show-parent-dialog').prepend(parentDialog);
});
return false;
}
});
}
// Only for chat transcript and conversations
else if (isTranscriptPage) {
// Improve room mini
$('.room-mini').each(_parseRoomMini);
}
// Dialog message replies
// For live chat, implement additional helpers
const topbarOffset = 34 + 10; // 34px for topbar, 10px for padding
$('#chat, #transcript').on('mouseover', '.reply-info', function (evt) {
const parentMid = Number(this.href.match(/#(\d+)/).pop());
const parentMsg = $('#message-' + parentMid);
const parentMsgOnAnotherPage = parentMsg.length === 0;
if (parentMsgOnAnotherPage) return; // Parent message not on page, do nothing
const parentMsgTop = parentMsg.offset().top;
const parentMsgHeight = parentMsg.outerHeight();
const parentMsgBottom = parentMsgTop + parentMsgHeight;
// Check if message is off screen, show in popup
const scrollPos = window.scrollY;
const screenHeight = window.innerHeight;
const parentMsgAboveScreen = parentMsgBottom < scrollPos + topbarOffset;
const parentMsgBelowScreen = parentMsgTop > scrollPos + screenHeight;
if (parentMsg.length && (parentMsgAboveScreen || parentMsgBelowScreen)) {
// TODO
console.log('TODO: on hover, show parent message in popup', {
parentMsgAboveScreen,
parentMsgBelowScreen,
});
}
}).on('click', '.newreply', function (evt) {
// Clear all message highlights on page
$('.highlight').removeClass('highlight');
// Highlight selected message we are replying to
$(this).closest('.dialog-message, .message').addClass('highlight');
}).on('click', '.dialog-message', function (evt) {
$(this).closest('.message').find('.popup').remove();
$(this).remove();
return false;
}).on('click', '.dialog-message .newreply', function (evt) {
const input = document.getElementById('input');
input.value = ':' + this.dataset.mid + ' ' + input.value.replace(/^:\d+\s*/, '');
return false;
}).on('click', 'a', function (evt) {
evt.stopPropagation();
return true;
});
}
const chatHostnames = {
"chat.stackoverflow.com": "Chat.SO",
"chat.stackexchange.com": "Chat.SE",
"chat.meta.stackexchange.com": "Chat.MSE",
};
/**
* @summary creates a chat hostname switcher button set for the top bar
* @param {Record<string, string>} hostnames list of valid chat hostnames
*/
const makeChatHostnameSwitcher = (hostnames) => {
const wrapper = document.createElement("div");
wrapper.classList.add("network-chat-links");
wrapper.id = "network-chat-links";
wrapper.append(
...Object.entries(hostnames).map(([hostname, name], i) => {
const switcher = document.createElement("a");
switcher.classList.add("button");
switcher.href = `https://${hostname}`;
switcher.id = `allrooms${i + 1}`;
switcher.rel = "noopener noreferrer";
switcher.textContent = name;
if (location.hostname === hostname) {
switcher.classList.add("current-site");
}
return switcher;
})
);
return wrapper;
};
/**
* @summary makes a user profile link for the topbar
* @param {{ id: string, is_moderator: boolean, name: string }} user current user
*/
const makeUserProfileLink = (user) => {
const wrapper = document.createElement("div");
wrapper.classList.add("links-container");
const linkWrapper = document.createElement("span");
linkWrapper.classList.add("topbar-menu-links");
const modDiamond = user.is_moderator ? ' ♦' : '';
const userAnchor = document.createElement("a");
userAnchor.href = `/users/${user.id}`;
userAnchor.title = `${user.name + modDiamond}`;
userAnchor.textContent = `${user.name + modDiamond}`;
linkWrapper.append(userAnchor);
if (user.is_moderator) {
const modAnchor = document.createElement("a");
modAnchor.href = `/admin`;
modAnchor.textContent = "mod";
linkWrapper.append(modAnchor);
}
wrapper.append(linkWrapper);
return wrapper;
};
/**
* @summary inserts topbar shared and script-specific styles
*/
const addTopbarStyles = () => {
const chromeExternalStyles = document.createElement("link");
chromeExternalStyles.rel = "stylesheet";
chromeExternalStyles.type = "text/css";
chromeExternalStyles.href = "https://cdn.sstatic.net/shared/chrome/chrome.css";
document.head.append(chromeExternalStyles);
// Append styles
addStylesheet(`
#info > .fl,
#info > .fl + .clear-both,
#sidebar-menu .button {
display: none;
}
.transcript-nav {
position: sticky;
top: 33px;
margin-top: 23px;
z-index: 1;
background: linear-gradient(180deg, white, transparent);
}
#sidebar {
padding-top: 48px;
}
#transcript-body #container,
#chat-body #container {
padding-top: 50px;
}
.topbar {
position: fixed;
top: 0;
left: 0;
right: 0;
background: black;
}
.topbar > * {
opacity: 1;
transition: opacity 0.4s ease;
}
.topbar.js-loading-assets > * {
opacity: 0;
}
.topbar .topbar-wrapper {
width: auto;
height: 34px;
padding: 0 20px;
}
.topbar .topbar-links {
right: 20px;
}
.topbar .topbar-icon {
position: relative;
cursor: pointer;
}
a.topbar-icon .topbar-dialog {
display: none;
position: absolute;
top: 100%;
cursor: initial;
}
a.topbar-icon.topbar-icon-on .topbar-dialog,
.topbar .topbar-icon.topbar-icon-on .js-loading-indicator {
display: block !important;
}
.topbar .network-chat-links {
display: inline-flex;
flex-direction: row;
align-items: center;
height: 34px;
margin-left: 10px;
}
.topbar .network-chat-links > a {
flex: 0 0 auto;
margin: 0 3px;
padding: 3px 7px;
color: white;
background: #666;
font-weight: normal;
text-shadow: none !important;
border: none;
border-radius: 4px;
}
.topbar .network-chat-links > a:active,
.topbar .network-chat-links > a:hover {
background: #444;
border: none;
}
.topbar .network-chat-links > a.current-site {
background: #3667af !important;
}
.topbar .topbar-icon .js-loading-indicator {
display: none;
position: absolute;
top: 100%;
left: -12px;
background: white;
padding: 15px 20px 20px;
}
.topbar .topbar-icon .js-loading-indicator img {
float: left;
}
#chat-body #searchbox {
float: none;
width: 194px;
margin: 3px 0 0 20px;
padding: 2px 3px 2px 24px !important;
font-size: 13px;
}
.topbar-dialog .s-input.s-input__search {
box-sizing: border-box;
padding: .6em .7em !important;
padding-left: 32px !important;
}
@media screen and (max-width: 960px) {
.topbar .network-chat-links {