-
Notifications
You must be signed in to change notification settings - Fork 82
/
chat.js
882 lines (756 loc) · 34.3 KB
/
chat.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
easyrpgPlayer["onRuntimeInitialized"] = initChat;
if (typeof ENV === "undefined")
initChat();
const MESSAGE_TYPE = {
SYSTEM: 0,
MAP: 1,
GLOBAL: 2,
PARTY: 3
};
const SCREENSHOT_FLAGS = {
SPOILER: 1 << 0,
};
const mentionSe = new Audio('./audio/mention.wav');
function chatboxAddMessage(msg, type, player, ignoreNotify, mapId, prevMapId, prevLocationsStr, x, y, msgId, timestamp, shouldScroll = true) {
const messages = document.getElementById("messages");
if (msgId && messages.querySelector(`.messageContainer[data-msg-id="${msgId}"]`))
return null;
const msgContainer = document.createElement("div");
msgContainer.classList.add("messageContainer");
const message = document.createElement("div");
message.classList.add("message");
const messageSender = document.createElement("div");
messageSender.classList.add("messageSender");
const messageContents = document.createElement("span");
messageContents.classList.add("messageContents");
let uuid = player?.uuid;
if (player && typeof player === 'string') {
uuid = player;
player = globalPlayerData[uuid];
}
const system = !type;
const map = type === MESSAGE_TYPE.MAP;
const global = type === MESSAGE_TYPE.GLOBAL;
const party = type === MESSAGE_TYPE.PARTY;
let systemThemeProm = Promise.resolve();
if (!system) {
let rankIcon;
let friendIcon;
let chatTypeIcon;
const msgHeader = document.createElement("div");
msgHeader.classList.add("messageHeader");
if (global || party) {
const showLocation = (mapId || "0000") !== "0000" && (localizedMapLocations || gameId === "2kki");
msgContainer.classList.add(global ? "global" : "party");
msgContainer.dataset.msgId = msgId;
msgContainer.dataset.senderUuid = uuid;
if (showLocation) {
const playerLocation = document.createElement("bdi");
if (gameId === "2kki" && (!localizedMapLocations.hasOwnProperty(mapId))) {
const prevLocations = prevLocationsStr && prevMapId !== "0000" ? decodeURIComponent(window.atob(prevLocationsStr)).split("|").map(l => { return { title: l }; }) : null;
set2kkiGlobalChatMessageLocation(playerLocation, mapId, prevMapId, prevLocations);
} else {
const locationsHtml = getLocalizedMapLocationsHtml(gameId, mapId, prevMapId, x, y, getInfoLabel(" | "));
fastdom.mutate(() => playerLocation.innerHTML = locationsHtml);
}
playerLocation.classList.add("playerLocation");
msgHeader.appendChild(playerLocation);
} else
msgHeader.appendChild(document.createElement('span'));
if (global) {
chatTypeIcon = getSvgIcon("global", true);
addTooltip(chatTypeIcon, document.createTextNode(getMassagedLabel(localizedMessages.chat.globalMessage)), true, true);
} else {
chatTypeIcon = getSvgIcon("party", true);
if (joinedPartyCache)
addTooltip(chatTypeIcon, getPartyName(joinedPartyCache, false, true), true, true);
}
messageSender.appendChild(chatTypeIcon);
} else
msgHeader.appendChild(document.createElement('span'));
if (blockedPlayerUuids.indexOf(uuid) > -1)
msgContainer.classList.add('blockedHidden');
const defaultDate = !timestamp;
if (defaultDate)
timestamp = new Date();
const msgTimestamp = document.createElement("bdi");
msgTimestamp.classList.add('messageTimestamp', 'infoLabel');
msgTimestamp.dataset.time = timestamp.getTime();
const timestampLabel = getChatMessageTimestampLabel(timestamp, defaultDate);
fastdom.mutate(() => {
msgTimestamp.innerHTML = timestampLabel;
});
// msgTimestamp.innerHTML = getChatMessageTimestampLabel(timestamp, defaultDate);
msgHeader.appendChild(msgTimestamp);
msgContainer.appendChild(msgHeader);
const name = document.createElement("bdi");
name.classList.add("nameText");
name.innerText = getPlayerName(player);
const nameBeginMarker = document.createElement("span");
nameBeginMarker.classList.add("nameMarker");
nameBeginMarker.textContent = player?.account ? "[" : "<";
const nameEndMarker = document.createElement("span");
nameEndMarker.classList.add("nameMarker");
nameEndMarker.textContent = player?.account ? "]" : ">";
messageSender.appendChild(nameBeginMarker);
messageSender.appendChild(name);
addPlayerContextMenu(name, player, uuid, global ? MESSAGE_TYPE.GLOBAL : party ? MESSAGE_TYPE.PARTY : MESSAGE_TYPE.MAP, {msg, msgId});
if (player?.rank) {
const rank = Math.min(player.rank, 2);
rankIcon = getSvgIcon(rank === 1 ? "mod" : "dev", true);
rankIcon.classList.add("rankIcon");
addTooltip(rankIcon, getMassagedLabel(localizedMessages.roles[Object.keys(localizedMessages.roles)[rank - 1]], true), true, true);
messageSender.appendChild(rankIcon);
}
if (playerFriendsCache.find(pf => pf.accepted && pf.uuid === uuid)) {
friendIcon = getSvgIcon('friend', true);
friendIcon.classList.add('friendIcon');
addTooltip(friendIcon, getMassagedLabel(localizedMessages.friends.friend, true), true, true);
messageSender.appendChild(friendIcon);
}
if (party) {
let partyOwnerIcon;
if (joinedPartyCache && player?.uuid === joinedPartyCache.ownerUuid) {
partyOwnerIcon = getSvgIcon("partyOwner", true);
addTooltip(partyOwnerIcon, getMassagedLabel(localizedMessages.parties.partyOwner, true), true, true);
messageSender.appendChild(partyOwnerIcon);
}
if (joinedPartyCache?.systemName) {
const parsedPartySystemName = joinedPartyCache.systemName.replace(" ", "_");
const iconStyle = `fill: var(--svg-base-gradient-${parsedPartySystemName}); filter: var(--svg-shadow-${parsedPartySystemName});`;
chatTypeIcon.querySelector("path").setAttribute("style", iconStyle);
if (partyOwnerIcon)
partyOwnerIcon.querySelector("path").setAttribute("style", iconStyle);
}
}
let systemName = player?.systemName;
const badge = player?.badge ? badgeCache?.find(b => b.badgeId === player.badge) : null;
const badgeEl = badge ? document.createElement('div') : null;
const badgeOverlayEl = badge?.overlayType ? document.createElement('div') : null;
const badgeOverlay2El = badge?.overlayType & BadgeOverlayType.DUAL ? document.createElement('div') : null;
if (badge) {
badgeEl.classList.add('badge', 'nameBadge');
if (localizedBadges) {
const badgeGame = localizedBadges[badge?.game]?.[player.badge] && badge.game;
if (badgeGame) {
const badgeTippy = addTooltip(badgeEl, document.createTextNode(getMassagedLabel(localizedBadges[badgeGame][player.badge].name)), true, true);
if (!badge || badge.hidden)
badgeTippy.popper.querySelector('.tooltipContent').classList.add('altText');
}
}
if (player.name) {
addOrUpdatePlayerBadgeGalleryTooltip(badgeEl, player.name, (systemName || getDefaultUiTheme()).replace(/'/g, ''), mapId, prevMapId, prevLocationsStr, x, y);
badgeEl.classList.toggle('badgeButton', player.name);
}
const badgeUrl = getBadgeUrl(player.badge, true);
badgeEl.style.backgroundImage = `url('${badgeUrl}')`;
if (badgeOverlayEl) {
badgeEl.classList.add('overlayBadge');
badgeOverlayEl.classList.add('badgeOverlay');
if (badge.overlayType & BadgeOverlayType.MULTIPLY)
badgeOverlayEl.classList.add('badgeOverlayMultiply');
badgeEl.appendChild(badgeOverlayEl);
const badgeMaskUrl = badge.overlayType & BadgeOverlayType.MASK
? badgeUrl.replace('.', badge.overlayType & BadgeOverlayType.DUAL ? '_mask_fg.' : '_mask.')
: badgeUrl;
badgeOverlayEl.setAttribute('style', `-webkit-mask-image: url('${badgeMaskUrl}'); mask-image: url('${badgeMaskUrl}');`);
if (badgeOverlay2El) {
const badgeMask2Url = badge.overlayType & BadgeOverlayType.MASK
? badgeUrl.replace('.', '_mask_bg.')
: badgeUrl;
badgeOverlay2El.classList.add('badgeOverlay', 'badgeOverlay2');
if (badge.overlayType & BadgeOverlayType.MULTIPLY)
badgeOverlay2El.classList.add('badgeOverlayMultiply');
badgeEl.appendChild(badgeOverlay2El);
badgeOverlay2El.setAttribute('style', `-webkit-mask-image: url('${badgeMask2Url}'); mask-image: url('${badgeMask2Url}');`);
}
}
}
if (systemName) {
let completeSystemThemeProm;
systemThemeProm = new Promise(res => completeSystemThemeProm = res);
systemName = systemName.replace(/'|\s$/g, "");
const parsedSystemName = systemName.replace(/ /g, "_");
initUiThemeContainerStyles(systemName, null, false, () => {
initUiThemeFontStyles(systemName, null, 0, false, () => {
applyThemeStyles(name, parsedSystemName).finally(completeSystemThemeProm);
if (rankIcon)
applyThemeStyles(rankIcon, parsedSystemName);
if (badgeOverlayEl) {
badgeOverlayEl.style.background = badge.overlayType & BadgeOverlayType.GRADIENT
? `var(--base-gradient-${parsedSystemName})`
: `rgb(var(--base-color-${parsedSystemName}))`;
if (badgeOverlay2El) {
if (getStylePropertyValue(`--base-color-${parsedSystemName}`) !== getStylePropertyValue(`--alt-color-${parsedSystemName}`)) {
badgeOverlay2El.style.background = badge.overlayType & BadgeOverlayType.GRADIENT
? `var(--alt-gradient-${parsedSystemName})`
: `rgb(var(--alt-color-${parsedSystemName}))`;
} else
badgeOverlay2El.style.background = `var(--base-bg-color-${parsedSystemName})`;
}
if (badge.overlayType & BadgeOverlayType.LOCATION)
handleBadgeOverlayLocationColorOverride(badgeOverlayEl, badgeOverlay2El, null, player?.name, mapId, prevMapId, prevLocationsStr, x, y);
}
});
});
}
if (badgeEl)
messageSender.appendChild(badgeEl);
messageSender.appendChild(nameEndMarker);
message.appendChild(messageSender);
message.appendChild(document.createTextNode(" "));
}
if (playerName && new RegExp(`(^|[^a-z\d])@${playerName}($|[^a-z\d])`, 'i').test(msg)) {
msgContainer.classList.add("highlight");
if (globalConfig.playMentionSound && blockedPlayerUuids.indexOf(uuid) === -1)
mentionSe.play();
}
populateMessageNodes(parseMessageTextForMarkdown(msg), messageContents, system);
wrapMessageEmojis(messageContents);
tryEmbedScreenshot(messageContents, uuid);
if (!messageContents.innerText.trim())
messageContents.classList.add("notext");
if (localizedMapLocations && !global) {
const mapMessages = messages.querySelectorAll(".messageContainer:not(.global):not(.party)");
if (mapMessages.length) {
const lastMapMessage = mapMessages[mapMessages.length - 1];
if (lastMapMessage.classList.contains("locMessage"))
lastMapMessage.classList.remove("hidden");
}
}
const messageContentsWrapper = document.createElement('div');
messageContentsWrapper.classList.add('messageContentsWrapper');
messageContentsWrapper.appendChild(messageContents);
messageContentsWrapper.dir = "auto";
message.appendChild(messageContentsWrapper);
msgContainer.appendChild(message);
let task = Promise.resolve(shouldScroll);
if (shouldScroll)
task = fastdom.measure(() => Math.abs((messages.scrollHeight - messages.scrollTop) - messages.clientHeight) <= 60);
const didPopulateMessage = task.then(() => fastdom.mutate(() => {
messages.appendChild(msgContainer);
}));
Promise.allSettled([didPopulateMessage, systemThemeProm]).then(() => {
if (player)
addGameChatMessage(message.innerHTML, type, uuid);
});
const chatbox = document.getElementById("chatbox");
const mapChat = chatbox.classList.contains("mapChat");
const globalChat = chatbox.classList.contains("globalChat");
const partyChat = chatbox.classList.contains("partyChat");
if (!ignoreNotify) {
if ((globalChat || partyChat) && (system || map))
document.getElementById("chatTabMap").classList.add("unread");
else if ((mapChat || partyChat) && global)
document.getElementById("chatTabGlobal").classList.add("unread");
else if ((mapChat || globalChat) && party)
document.getElementById("chatTabParty").classList.add("unread");
else if (!system && !document.querySelector(".chatboxTab.active[data-tab-section='chat']")) {
const unreadMessageCountContainer = document.getElementById("unreadMessageCountContainer");
const unreadMessageCountLabel = unreadMessageCountContainer.querySelector(".notificationCountLabel");
if (unreadMessageCountContainer.classList.contains("hidden")) {
unreadMessageCountLabel.textContent = "0";
unreadMessageCountContainer.classList.remove("hidden");
}
let unreadMessageCount = parseInt(unreadMessageCountLabel.textContent);
if (!unreadMessageCount || unreadMessageCount < 9)
unreadMessageCountLabel.textContent = ++unreadMessageCount < 9 ? unreadMessageCount : `${unreadMessageCount}+`;
}
}
let tabMessagesLimit;
if (global)
tabMessagesLimit = parseInt(globalConfig.globalChatHistoryLimit);
else if (party)
tabMessagesLimit = parseInt(globalConfig.partyChatHistoryLimit);
else
tabMessagesLimit = parseInt(globalConfig.mapChatHistoryLimit);
if (tabMessagesLimit) {
let tabMessages;
if (global)
tabMessages = [...messages.querySelectorAll('.messageContainer.global')];
else if (party)
tabMessages = [...messages.querySelectorAll('.messageContainer.party')];
else
tabMessages = [...messages.querySelectorAll('.messageContainer:not(.global):not(.party)')];
const oldTask = task;
task = fastdom.mutate(() => {
while (tabMessages.length > tabMessagesLimit)
tabMessages.shift().replaceWith(tabMessages[0]);
return oldTask;
})
}
task.then(shouldScroll => shouldScroll && scrollChatMessages());
return msgContainer;
}
function scrollChatMessages() {
// force the scroll to work in the next task,
// avoiding a costly style invalidation on startup.
setTimeout(() => {
const messages = document.getElementById('messages');
const scrollHeight = messages.scrollHeight;
fastdom.mutate(() => {
messages.scrollTop = scrollHeight;
});
});
}
let gameChatModeIndex = 0;
function addGameChatMessage(messageHtml, messageType, senderUuid) {
const gameChatContainer = document.getElementById('gameChatContainer');
const messageContainer = document.createElement('div');
messageContainer.classList.add('gameChatMessageContainer');
if (messageType === 2) {
if (!globalConfig.gameChatGlobal)
messageContainer.classList.add('hidden');
} else if (messageType === 3) {
if (!globalConfig.gameChatParty || !joinedPartyId)
messageContainer.classList.add('hidden');
}
messageContainer.dataset.messageType = messageType;
messageContainer.dataset.senderUuid = senderUuid;
if (blockedPlayerUuids.indexOf(senderUuid) > -1)
messageContainer.classList.add('blockedHidden');
const message = document.createElement('div');
message.classList.add('gameChatMessage', 'message');
message.innerHTML = messageHtml;
messageContainer.appendChild(message);
fastdom.mutate(() => {
gameChatContainer.insertBefore(messageContainer, gameChatContainer.children[gameChatContainer.childElementCount - 1]);
const typeMessages = Array.from(gameChatContainer.children).filter(m => m.dataset.messageType == messageType);
if (typeMessages.length > 10)
typeMessages[0].remove();
});
setTimeout(() => {
messageContainer.classList.add('fade');
setTimeout(() => {
messageContainer.classList.remove('fade');
messageContainer.classList.add('expired');
}, 1000);
}, 10000);
}
function setGameChatMode(modeIndex) {
const chatModeIcon = document.getElementById('gameChatModeIcon');
gameChatModeIndex = modeIndex;
if (modeIndex) {
if (modeIndex === 1) {
if (globalConfig.gameChatGlobal)
chatModeIcon.innerHTML = getSvgIcon('global', true).outerHTML;
else
cycleGameChatMode();
} else {
if (globalConfig.gameChatParty && joinedPartyId)
chatModeIcon.innerHTML = getSvgIcon('party', true).outerHTML;
else
cycleGameChatMode();
}
} else
chatModeIcon.innerHTML = '';
document.getElementById('gameChatInputContainer').querySelector('.globalCooldownIcon').classList.toggle('hidden', modeIndex !== 1);
}
function cycleGameChatMode() {
if (gameChatModeIndex < 2)
setGameChatMode(gameChatModeIndex + 1);
else
setGameChatMode(0);
}
function updateGameChatMessageVisibility() {
const gameChatMessageContainers = document.getElementsByClassName('gameChatMessageContainer');
for (let messageContainer of gameChatMessageContainers) {
if (messageContainer.dataset.messageType == 2)
messageContainer.classList.toggle('hidden', !globalConfig.gameChatGlobal);
else if (messageContainer.dataset.messageType == 3)
messageContainer.classList.toggle('hidden', !globalConfig.gameChatParty || !joinedPartyId);
}
}
function chatInputActionFired() {
const chatInput = document.getElementById("chatInput");
if (!chatInput?.value.trim().length)
return;
const htmlTextEl = document.createElement("span");
htmlTextEl.innerHTML = parseMessageTextForMarkdown(chatInput.value);
if (!htmlTextEl.innerText.trim().length)
return;
const partyChat = document.getElementById("chatbox").classList.contains("partyChat");
if (!chatInput.dataset.global && !partyChat && (connStatus != 1 && connStatus != 3))
return;
if (chatInput.dataset.global && chatInput.dataset.blockGlobal)
return;
const chatTab = document.querySelector(".chatboxTab[data-tab-section='chat']");
if (!chatTab.classList.contains("active"))
chatTab.click();
let message = chatInput.value.trim();
if (message.includes('[screenshot]') && chatInput.dataset.screenshotId) {
const flags = +chatInput.dataset.screenshotFlags;
message = message.replace('[screenshot]', `[${chatInput.dataset.screenshotTemp ? 't' : ''}${chatInput.dataset.screenshotId}${flags ? `:${flags}` : ''}]`);
delete chatInput.dataset.screenshotId;
delete chatInput.dataset.screenshotTemp;
delete chatInput.dataset.screenshotFlags;
}
if (!chatInput.dataset.global || partyChat) {
if (!joinedPartyId || !partyChat) {
sendSessionCommand("say", [ message ]);
} else
sendSessionCommand("psay", [ message ]);
} else if (!trySendGlobalMessage(message))
return;
chatInput.value = "";
document.getElementById("ynomojiContainer").classList.add("hidden");
}
/** @param {number} length */
function constrainByteLength(length) {
const buf = new Uint8Array(length + 1);
const enc = new TextEncoder();
const dec = new TextDecoder(undefined, { fatal: false });
return event => {
const target = event?.target;
if (!target) return;
if (enc.encodeInto(target.value, buf).read <= length) return;
let recovered = dec.decode(buf.slice(0, length));
const invalid = recovered.indexOf('�');
if (invalid > -1) recovered = recovered.slice(0, invalid);
target.value = recovered;
};
}
document.getElementById('chatInput').addEventListener('input', constrainByteLength(150));
function chatNameCheck() {
trySetChatName(document.getElementById("nameInput").value);
}
function trySetChatName(name) {
if (name && !(/^[A-Za-z0-9]+$/.test(name)))
return;
playerName = name;
document.getElementById("enterNameContainer").style.display = playerName ? "none" : null;
document.getElementById("chatInput").disabled = !playerName;
document.getElementById("chatInputContainer").setAttribute("style", playerName ? "" : "display: none");
updateYnomojiContainerPos();
if (playerName) {
if (playerData) {
playerData.name = playerName;
globalPlayerData[playerData.uuid].name = playerName;
}
addOrUpdatePlayerListEntry(null, playerData, false, true);
if (!loginToken)
sendSessionCommand('name', [ playerName ]);
}
}
function initChat() {
document.getElementById("chatboxContainer").style.display = "table-cell";
const gameChatContainer = document.getElementById('gameChatContainer');
const gameChatInput = document.getElementById('gameChatInput');
gameChatInput.onfocus = function() {
gameChatContainer.classList.add('focused');
document.execCommand('selectAll', false, null);
document.getSelection().collapseToEnd();
};
gameChatInput.onblur = () => gameChatContainer.classList.remove('focused');
gameChatInput.onkeydown = function (e) {
if (e.key === 'Tab') {
e.preventDefault();
cycleGameChatMode();
} else if (e.key === 'Enter') {
const chatMessageContent = e.target.innerText.trim();
if (!chatMessageContent) {
document.getElementById('canvas').focus();
return;
}
e.preventDefault();
if (!playerName)
return;
switch (gameChatModeIndex) {
case 0:
sendSessionCommand('say', [ chatMessageContent ]);
break;
case 1:
if (!trySendGlobalMessage(chatMessageContent))
return;
break;
case 2:
sendSessionCommand('psay', [ chatMessageContent ]);
break;
}
e.target.innerHTML = '';
} else if (e.key === 'Escape') {
document.getElementById('canvas').focus();
return;
}
};
}
function trySendGlobalMessage(content) {
const chatInput = document.getElementById("chatInput");
if (chatInput.blockGlobal)
return false;
const chatInputContainer = document.getElementById("chatInputContainer");
if (!chatInputContainer.classList.contains("globalCooldown")) {
const chatInputContainers = [ chatInputContainer, document.getElementById("gameChatInputContainer") ];
const chatInputs = [ chatInput, document.getElementById('gameChatInput') ];
sendSessionCommand("gsay", [ content ]);
chatInputs.forEach(el => el.dataset.blockGlobal = true);
chatInputContainers.forEach(el => el.classList.add("globalCooldown"));
window.setTimeout(function () {
chatInputContainers.forEach(el => el.classList.remove("globalCooldown"));
chatInputs.forEach(el => delete el.dataset.blockGlobal);
}, 5000);
return true;
}
return false;
}
function addChatTip() {
const tips = localizedMessages.chatTips.tips;
if (++globalConfig.chatTipIndex >= Object.keys(tips).length)
globalConfig.chatTipIndex = 0;
const tipIndex = globalConfig.chatTipIndex;
chatboxAddMessage(getMassagedLabel(localizedMessages.chatTips.template.replace("{CONTENT}", tips[Object.keys(tips)[tipIndex]])), null, null, true);
updateConfig(globalConfig, true);
}
function addChatMapLocation(locations) {
const locationHtml = cached2kkiLocations
? getLocalized2kkiLocations(cached2kkiLocations, " | ")
: getLocalizedMapLocations(gameId, cachedMapId, cachedPrevMapId, tpX, tpY, " | ");
if (eventPeriodCache)
getOrQueryLocationColors(locations)
.then(colors => updateLocationDisplay(cached2kkiLocations
? getLocalized2kkiLocations(cached2kkiLocations, " / ", true)
: getLocalizedMapLocations(gameId, cachedMapId, cachedPrevMapId, tpX, tpY, " / ", true),
Array.isArray(colors) && colors.length === 2 ? colors : null))
else
updateLocationDisplay(getLocalizedMapLocations(gameId, cachedMapId, cachedPrevMapId, tpX, tpY, " / ", true));
const locMessages = document.getElementById("messages").querySelectorAll(".messageContainer.locMessage");
let lastLocMessage = locMessages.length ? locMessages[locMessages.length - 1] : null;
if (lastLocMessage?.classList.contains("hidden")) {
lastLocMessage.remove();
lastLocMessage = locMessages.length > 1 ? locMessages[locMessages.length - 2] : null;
}
if (lastLocMessage && new DOMParser().parseFromString(locationHtml, "text/html").documentElement.textContent === lastLocMessage.innerText)
return;
const locMessage = chatboxAddMessage(locationHtml, null, null, true);
if (locMessage) {
locMessage.classList.add("locMessage", "map", "hidden");
}
}
function markMapUpdateInChat() {
const messages = document.getElementById("messages");
const allTabMessageContainers = messages.querySelectorAll(".messageContainer:not(.map)");
const mapTabMessageContainers = messages.querySelectorAll(".messageContainer:not(.global)");
if (allTabMessageContainers.length) {
const allTabLocMessages = messages.querySelectorAll("lastAllTabMessageInLoc");
if (!allTabLocMessages.length)
allTabMessageContainers[allTabMessageContainers.length - 1].classList.add("lastAllTabMessageInLoc");
}
if (mapTabMessageContainers.length) {
const mapTabLocMessages = messages.querySelectorAll("lastMapTabMessageInLoc");
if (!mapTabLocMessages.length)
mapTabMessageContainers[mapTabMessageContainers.length - 1].classList.add("lastMapTabMessageInLoc");
}
}
function getChatMessageTimestampLabel(timestamp, defaultDate) {
const timeString = timestamp.toLocaleString(globalConfig.lang === 'en' ? [] : globalConfig.lang, { "timeStyle": "short" });
const weekdayString = !defaultDate && new Date().toDateString() !== timestamp.toDateString() ? timestamp.toLocaleString(globalConfig.lang === 'en' ? [] : globalConfig.lang, { "weekday": "short" }) : null;
let timestampLabel = getMassagedLabel(localizedMessages.timestamp[weekdayString ? "timeAndWeekday" : "time"], true).replace("{TIME}", timeString);
if (weekdayString)
timestampLabel = timestampLabel.replace("{WEEKDAY}", weekdayString);
return timestampLabel;
}
function updateChatMessageTimestamps() {
const timestamps = document.getElementById("messages").querySelectorAll('.messageTimestamp');
for (let timestamp of timestamps)
timestamp.innerHTML = getChatMessageTimestampLabel(new Date(parseInt(timestamp.dataset.time)));
}
async function syncChatHistory() {
const messages = document.getElementById("messages");
const idMessages = messages.querySelectorAll('.messageContainer[data-msg-id]');
const lastMessageId = idMessages.length ? idMessages[idMessages.length - 1].dataset.msgId : null;
updateChatMessageTimestamps();
const chatHistory = await apiFetch(`chathistory?globalMsgLimit=${globalConfig.globalChatHistoryLimit}&partyMsgLimit=${globalConfig.partyChatHistoryLimit}${lastMessageId ? `&lastMsgId=${lastMessageId}` : ''}`)
.then(response => {
if (!response.ok)
throw new Error(response.statusText);
return response.json();
});
if (chatHistory.players) {
for (let player of chatHistory.players) {
let badge = player.badge;
if (badge === 'null')
badge = null;
globalPlayerData[player.uuid] = {
name: player.name,
systemName: player.systemName,
rank: player.rank,
account: player.account,
badge: badge,
medals: player.medals
};
}
}
if (chatHistory.messages) {
// don't yield to any other task here, since we may be loading at least
// a hundred of these and each yield will cause a decent amount of layout thrasing
for (let message of chatHistory.messages) {
chatboxAddMessage(message.contents, message.party ? MESSAGE_TYPE.PARTY : MESSAGE_TYPE.GLOBAL, message.uuid, true, message.mapId, message.prevMapId, message.prevLocations, message.x, message.y, message.msgId, new Date(message.timestamp), false);
}
scrollChatMessages();
}
}
const markdownSyntax = [
{ p: /<\/?[bisux] *>/ig, r: '' },
{ p: /(?:^|([^\\]))(\*{3,})([^*_~|\\]+)\2/g, r: '$1<b><i>$3</i></b>' },
{ p: /(?:^|([^\\]))(\*{2})([^*_~|\\]+)\2/g, r: '$1<b>$3</b>' },
{ p: /(?:^|([^\\]))\*([^*_~|\\]+)\*/g, r: '$1<i>$2</i>' },
{ p: /(?:^|([^\\]))(_{3,})([^*_~|\\]+)\2(?= |$)/g, r: '$1<u><i>$3</i></u>' },
{ p: /(?:^|([^\\]))(_{2})([^*_~|\\]+)\2(?= |$)/g, r: '$1<u>$3</u>' },
{ p: /(?:^|([^\\]))_([^*_~|\\]+)_(?= |$)/g, r: '$1<i>$2</i>' },
{ p: /(?:^|([^\\]))(~{2,})([^*_~|\\]+)\2/g, r: '$1<s>$3</s>' },
{ p: /(?:^|([^\\]))(\|{2,})([^*_~|\\]+)\2/g, r: '$1<x>$3</x>' },
{ p: /\\\*/g, r: '*' },
{ p: /\\_/g, r: '_' },
{ p: /\\~/g, r: '~' },
{ p: /\\\|/g, r: '|' },
];
/** @param {string} msg */
function parseMessageTextForMarkdown(msg) {
for (let syntax of markdownSyntax)
msg = msg.replace(syntax.p, syntax.r);
return msg;
}
function populateMessageNodes(msg, node, asHtml) {
const tagPattern = /<([bisux])>(.*?)<\/\1>/;
let cursor = 0;
let result;
while ((result = tagPattern.exec(msg.slice(cursor)))) {
if (result.index) {
const content = msg.slice(cursor, cursor + result.index);
let textNode;
if (asHtml) {
textNode = document.createElement("span");
textNode.innerHTML = content;
} else
textNode = document.createTextNode(content);
node.appendChild(textNode);
}
const isSpoiler = result[1] === "x";
const childNode = document.createElement(isSpoiler ? "span" : result[1]);
const innerMsg = msg.substr(cursor + result.index + 3, result[2].length);
if (isSpoiler) {
childNode.classList.add("spoiler");
childNode.onclick = function () { this.classList.add("show"); };
}
populateMessageNodes(innerMsg, childNode, asHtml);
node.appendChild(childNode);
cursor += result.index + result[2].length + 7;
}
if (cursor < msg.length) {
const content = msg.slice(cursor);
let textNode;
if (asHtml) {
textNode = document.createElement("span");
textNode.innerHTML = content;
} else
textNode = document.createTextNode(content);
node.appendChild(textNode);
}
}
function wrapMessageEmojis(node, force) {
if (node.childNodes.length && !force) {
for (let childNode of node.childNodes) {
if (/\p{Extended_Pictographic}/u.test(childNode.textContent) || /:([a-z0-9_\-]+):/i.test(childNode.textContent)) {
if (childNode.nodeType === Node.TEXT_NODE) {
const newChildNode = document.createElement("span");
newChildNode.innerText = childNode.textContent;
node.replaceChild(newChildNode, childNode);
wrapMessageEmojis(newChildNode, true);
} else
wrapMessageEmojis(childNode);
}
}
} else {
node.innerHTML = node.innerHTML.replace(/(\p{Extended_Pictographic}+)/ug, '<span class="emoji">$1</span>');
const ynomojiPattern = /:([a-z0-9_\-]+):/gi;
let ynomojiMatch;
while (ynomojiMatch = ynomojiPattern.exec(node.innerHTML)) {
const ynomojiId = Object.keys(ynomojiConfig).find(id => id === ynomojiMatch[1]);
if (ynomojiId)
node.innerHTML = `${node.innerHTML.slice(0, ynomojiMatch.index)}<span class="ynomojiWrapper"><img src="${ynomojiUrlPrefix}${ynomojiConfig[ynomojiId]}" class="ynomoji" title="${ynomojiId}" /></span>${node.innerHTML.slice(ynomojiMatch.index + ynomojiId.length + 2)}`;
}
}
}
const screenshotPattern = /\[(t?)(\w{16})(?::(\d+))?\]/;
/** Decodes the message constructed by {@linkcode chatInputActionFired} */
function tryEmbedScreenshot(node, uuid) {
if (node.childNodes.length) {
for (let childNode of node.childNodes) {
if (childNode.nodeType === Node.TEXT_NODE) {
let screenshotResult;
if ((screenshotResult = screenshotPattern.exec(childNode.textContent)) !== null) {
let isTemp = !!screenshotResult[1];
const flags = +screenshotResult[3] || 0;
const imageNode = document.createElement('img');
imageNode.classList.add('screenshotEmbed');
imageNode.classList.toggle('screenshotBlur', globalConfig.blurScreenshotEmbeds || !!(flags & SCREENSHOT_FLAGS.SPOILER));
imageNode.src = `${serverUrl}/screenshots/${isTemp ? 'temp/' : ''}${uuid}/${screenshotResult[2]}.png`;
const date = new Date();
imageNode.onclick = function () {
sendSessionCommand('psi', [ uuid, screenshotResult[2] ], args => {
const screenshotInfo = JSON.parse(args[0]);
viewScreenshot(imageNode.src, date, screenshotInfo);
});
};
let offset = 18;
if (isTemp) offset++;
if (flags) offset += 1 + screenshotResult[3].length;
const beforeNode = screenshotResult.index ? document.createTextNode('') : null;
if (beforeNode)
beforeNode.textContent = childNode.textContent.slice(0, screenshotResult.index);
const afterNode = childNode.textContent.length > screenshotResult.index + offset ? document.createTextNode('') : null;
if (afterNode)
afterNode.textContent = childNode.textContent.slice(screenshotResult.index + offset);
node.replaceChild(imageNode, childNode);
if (beforeNode)
node.insertBefore(beforeNode, imageNode);
if (afterNode) {
if (childNode !== node.childNodes[node.childElementCount - 1])
node.insertBefore(afterNode, imageNode.nextSibling);
else
node.appendChild(afterNode);
}
return true;
}
} else if (tryEmbedScreenshot(childNode, uuid))
return true;
}
} else if (node.nodeType === Node.TEXT_NODE && /\[t?\w{16}\]/.test(node.textContent)) {
const newParentNode = document.createElement('span');
newParentNode.appendChild(node);
tryEmbedScreenshot(newParentNode, uuid);
}
return false;
}
(function () {
addSessionCommandHandler('say', args => {
const uuid = args[0];
const msg = args[1];
chatboxAddMessage(msg, MESSAGE_TYPE.MAP, uuid)
});
addSessionCommandHandler('gsay', args => {
const uuid = args[0];
const mapId = args[1];
const prevMapId = args[2];
const prevLocationsStr = args[3];
const x = parseInt(args[4]);
const y = parseInt(args[5]);
const msg = args[6];
const msgId = args[7]
chatboxAddMessage(msg, MESSAGE_TYPE.GLOBAL, uuid, false, mapId, prevMapId, prevLocationsStr, x, y, msgId);
});
addSessionCommandHandler('psay', args => {
const uuid = args[0];
const msg = args[1];
const msgId = args[2];
let partyMember = joinedPartyCache ? joinedPartyCache.members.find(m => m.uuid === uuid) : null;
if (partyMember)
chatboxAddMessage(msg, MESSAGE_TYPE.PARTY, partyMember, false, partyMember.mapId, partyMember.prevMapId, partyMember.prevLocations, partyMember.x, partyMember.y, msgId);
else {
updateJoinedParty(() => {
partyMember = joinedPartyCache.members.find(m => m.uuid === uuid);
chatboxAddMessage(msg, MESSAGE_TYPE.PARTY, partyMember, false, partyMember.mapId, partyMember.prevMapId, partyMember.prevLocations, partyMember.x, partyMember.y, msgId);
});
}
});
})();