-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjava.js
More file actions
3256 lines (2853 loc) · 120 KB
/
Copy pathjava.js
File metadata and controls
3256 lines (2853 loc) · 120 KB
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
// =============================================
// FAVICON
// =============================================
(function() {
const canvas = document.createElement('canvas');
canvas.width = 32;
canvas.height = 32;
const ctx = canvas.getContext('2d');
const img = new Image();
img.onload = function() {
ctx.filter = 'brightness(0) invert(1)';
ctx.drawImage(img, 0, 0, 32, 32);
const link = document.querySelector("link[rel='icon']") || document.createElement('link');
link.rel = 'icon';
link.href = canvas.toDataURL();
document.head.appendChild(link);
};
img.src = 'assets/logo.svg';
})();
// =============================================
// 1. CONFIG
// =============================================
const SUPABASE_URL = 'https://afuwppfrljzmnbndizxz.supabase.co';
const SUPABASE_ANON = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6ImFmdXdwcGZybGp6bW5ibmRpenh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NzM4NDA4MzgsImV4cCI6MjA4OTQxNjgzOH0.-EK1da5r3n38YVs6pPPKMWiyWyzsVdGlUwX5iygY5LA';
const sb = supabase.createClient(SUPABASE_URL, SUPABASE_ANON);
// Curated identity color palette — terminal-safe, readable on dark backgrounds
const IDENTITY_COLORS = [
{ id: 1, name: 'Sage', hex: '#5A7A4A' },
{ id: 2, name: 'Warm Amber', hex: '#9A7040' },
{ id: 3, name: 'Seafoam', hex: '#3A8A7A' },
{ id: 4, name: 'Phosphor Green', hex: '#39FF14' },
{ id: 5, name: 'Mauve', hex: '#8A4A60' },
{ id: 6, name: 'Dusty Rose', hex: '#A05568' },
{ id: 7, name: 'Steel', hex: '#5A7498' },
{ id: 8, name: 'Sand', hex: '#9A8A6A' },
{ id: 9, name: 'Terracotta', hex: '#946048' },
];
function getColorHex(colorId) {
const entry = IDENTITY_COLORS.find(c => c.id === colorId);
return entry ? entry.hex : '#8A9A7A'; // fallback = Sage (id 1)
}
function formatLastSeen(ts) {
if (!ts) return 'a while ago';
const diff = Date.now() - new Date(ts).getTime();
const mins = Math.floor(diff / 60000);
if (mins < 1) return 'just now';
if (mins < 60) return `${mins}m ago`;
const hrs = Math.floor(mins / 60);
if (hrs < 24) return `${hrs}h ago`;
const days = Math.floor(hrs / 24);
return `${days}d ago`;
}
// UI color themes
const THEMES = [
{ id: 'default', name: 'Default', desc: 'Light terminal' },
{ id: 'dark', name: 'Dark', desc: 'Standard dark terminal' },
{ id: 'midnight', name: 'Midnight', desc: 'Blue-tinted dark' },
{ id: 'phosphor', name: 'Phosphor', desc: 'Classic green CRT' },
{ id: 'amber', name: 'Amber', desc: 'Warm amber CRT' },
];
function applyTheme(themeId) {
if (themeId === 'default') {
document.documentElement.removeAttribute('data-theme');
} else {
document.documentElement.setAttribute('data-theme', themeId);
}
localStorage.setItem('eye_theme', themeId);
}
function getStoredTheme() {
return localStorage.getItem('eye_theme') || 'default';
}
applyTheme(getStoredTheme());
// =============================================
// 2. STATE
// =============================================
let currentUser = null; // { id, username }
let activeContact = null; // { id, username }
let allUsers = []; // [{ id, username }, ...]
let onlineIds = new Set(); // user IDs currently online
let realtimeChannel = null;
let presenceChannel = null;
let profilesChannel = null;
let renderedMsgIds = new Set(); // dedup for self-echo
let conversationCache = new Map(); // userId|channelName → messages[]
let audioUnlocked = false;
let isMuted = false;
let notifAudio = new Audio('assets/notif.mp3');
let viewMode = 'dm'; // 'dm' or 'channel'
let activeChannel = null; // e.g. 'GLOBAL'
let channelRealtimeChannel = null;
let inputHistory = []; // sent messages (oldest → newest)
let inputHistoryIdx = -1; // -1 = not browsing history
let inputHistoryDraft = ''; // stash of unsent text when entering history
let isUserAtBottom = true; // auto-scroll tracking
let newMsgCount = 0; // unread count while scrolled up
let lockedMessages = new Set(JSON.parse(localStorage.getItem('locked_msgs') || '[]'));
function persistLockedMessages() { localStorage.setItem('locked_msgs', JSON.stringify(Array.from(lockedMessages))); }
let lockChannel = null; // realtime channel for lock sync (postgres UPDATE)
let lastMessageTime = new Map(); // userId → timestamp (ms) for sorting contacts
let unreadCounts = new Map(); // userId → unread message count
let favoriteIds = new Set(JSON.parse(localStorage.getItem('eye_favorites') || '[]'));
function persistFavorites() { localStorage.setItem('eye_favorites', JSON.stringify(Array.from(favoriteIds))); }
let lastSeenInterval = null;
function toggleFavorite(userId) {
if (favoriteIds.has(userId)) {
favoriteIds.delete(userId);
} else {
favoriteIds.add(userId);
}
persistFavorites();
renderContacts();
}
let typingChannel = null; // broadcast channel for typing indicators
let typingTimeout = null; // timeout to hide remote typing
let lastTypingSent = 0; // throttle outgoing typing events
function unlockAudio() {
if (audioUnlocked) return;
notifAudio.play().then(() => {
notifAudio.pause();
notifAudio.currentTime = 0;
audioUnlocked = true;
}).catch(() => {});
}
function playNotif() {
if (!audioUnlocked || isMuted) return;
notifAudio.currentTime = 0;
notifAudio.play().catch(() => {});
}
// =============================================
// 3. UTILS
// =============================================
function nowTime() {
return new Date().toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' });
}
function escapeHtml(text) {
return text
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>');
}
function scrollToBottom(force = false) {
const feed = document.getElementById('message-feed');
if (force || isUserAtBottom) {
feed.scrollTop = feed.scrollHeight;
resetNewMsgIndicator();
}
}
function checkIfAtBottom() {
const feed = document.getElementById('message-feed');
// Within 40px of the bottom counts as "at bottom"
isUserAtBottom = feed.scrollHeight - feed.scrollTop - feed.clientHeight < 40;
if (isUserAtBottom) resetNewMsgIndicator();
}
function showNewMsgIndicator() {
newMsgCount++;
const indicator = document.getElementById('new-msg-indicator');
document.getElementById('new-msg-count').textContent = newMsgCount;
indicator.classList.remove('hidden');
}
function resetNewMsgIndicator() {
newMsgCount = 0;
const indicator = document.getElementById('new-msg-indicator');
if (indicator) indicator.classList.add('hidden');
}
// =============================================
// 3c. TYPING INDICATORS
// =============================================
function subscribeToTyping() {
typingChannel = sb
.channel('typing-indicators')
.on('broadcast', { event: 'typing' }, ({ payload }) => {
if (!currentUser || payload.user_id === currentUser.id) return;
// DM mode: only show if the typer is the active contact
if (viewMode === 'dm') {
if (!activeContact || payload.user_id !== activeContact.id) return;
if (payload.context_type !== 'dm') return;
}
// Channel mode: only show if same channel
if (viewMode === 'channel') {
if (payload.context_type !== 'channel' || payload.context_id !== activeChannel) return;
}
showTypingIndicator(payload.username);
})
.subscribe();
}
function broadcastTyping() {
if (!typingChannel || !currentUser) return;
const now = Date.now();
if (now - lastTypingSent < 2000) return; // throttle to once per 2s
lastTypingSent = now;
const payload = {
user_id: currentUser.id,
username: currentUser.username,
};
if (viewMode === 'channel' && activeChannel) {
payload.context_type = 'channel';
payload.context_id = activeChannel;
} else if (viewMode === 'dm' && activeContact) {
payload.context_type = 'dm';
payload.context_id = activeContact.id;
} else {
return;
}
typingChannel.send({ type: 'broadcast', event: 'typing', payload });
}
function showTypingIndicator(username) {
const el = document.getElementById('typing-indicator');
el.innerHTML = `${escapeHtml(username)} is typing<span class="blink-cursor">_</span>`;
el.classList.remove('hidden');
clearTimeout(typingTimeout);
typingTimeout = setTimeout(hideTypingIndicator, 3000);
}
function hideTypingIndicator() {
const el = document.getElementById('typing-indicator');
el.classList.add('hidden');
clearTimeout(typingTimeout);
}
// =============================================
// 3b. SLASH COMMANDS
// =============================================
function appendSystemMsg(text, swatchColor = null) {
const feed = document.getElementById('message-feed');
const el = document.createElement('div');
el.className = 'system-msg';
if (swatchColor) {
// Render the ██ swatch in the actual color, rest in normal system-msg color
const colored = text.replace('██', `<span style="color:${swatchColor};font-style:normal">██</span>`);
el.innerHTML = colored;
} else {
el.textContent = text;
}
feed.appendChild(el);
scrollToBottom();
}
function appendSystemMsgHtml(html) {
const feed = document.getElementById('message-feed');
const el = document.createElement('div');
el.className = 'system-msg';
el.innerHTML = html;
feed.appendChild(el);
scrollToBottom();
}
const COMMANDS = {
help: { usage: '/help', description: 'Show available commands', handler: cmdHelp },
clear: { usage: '/clear', description: 'Clear the message feed', handler: cmdClear },
lock: { usage: '/lock [n]', description: 'Lock/unlock message (survives /clear)', handler: cmdLock },
who: { usage: '/who', description: 'Show online users', handler: cmdWho },
top: { usage: '/top', description: 'Show message leaderboard', handler: cmdTop },
color: { usage: '/color list', description: 'List or set your identity color', handler: cmdColor },
theme: { usage: '/theme list', description: 'List or set UI color theme', handler: cmdTheme },
mute: { usage: '/mute', description: 'Toggle all sound effects', handler: cmdMute },
b64: { usage: '/b64 encode|decode <text>', description: 'Base64 encode or decode text', handler: cmdB64 },
rot13: { usage: '/rot13 <text>', description: 'Apply ROT13 cipher to text', handler: cmdRot13 },
hex: { usage: '/hex encode|decode <text>', description: 'Hex encode or decode text', handler: cmdHex },
hash: { usage: '/hash <text>', description: 'SHA-256 hash of text', handler: cmdHash },
ts: { usage: '/ts', description: 'Show current timestamp', handler: cmdTs },
dice: { usage: '/dice <NdM>', description: 'Roll dice (e.g. 2d6, 1d20)', handler: cmdDice },
};
function cmdYase() {
const desktop = document.getElementById('wm-desktop');
const alreadyVisible = desktop && desktop.querySelector('.wm-icon[data-app-id="app-soundboard"]');
if (!alreadyVisible) {
// Add soundboard to the desktop app layout so it persists across relayouts
if (!WM_DESKTOP_APPS.includes('app-soundboard')) {
WM_DESKTOP_APPS.push('app-soundboard');
}
layoutDesktopIcons();
}
}
async function handleSlashCommand(body) {
if (!body.startsWith('/')) return false;
const spaceIdx = body.indexOf(' ');
const name = (spaceIdx === -1 ? body.slice(1) : body.slice(1, spaceIdx)).toLowerCase();
const args = spaceIdx === -1 ? '' : body.slice(spaceIdx + 1).trim();
// Secret commands — not listed in /help
if (name === 'yase') { cmdYase(); appendSystemMsg('SOUNDBOARD UNLOCKED — check the desktop.'); return true; }
const cmd = COMMANDS[name];
if (!cmd) {
appendSystemMsg('UNKNOWN COMMAND: /' + name + ' — type /help');
return true;
}
await cmd.handler(args);
return true;
}
function applyLockVisual(el, locked) {
const tag = el.querySelector('.msg-lock-tag');
const btn = el.querySelector('.msg-lock-btn');
if (locked) {
el.classList.add('locked');
tag.classList.remove('hidden');
btn.textContent = '[UNLOCK]';
} else {
el.classList.remove('locked');
tag.classList.add('hidden');
btn.textContent = '[LOCK]';
}
}
async function toggleLock(elId) {
const el = document.getElementById(elId);
if (!el || !el.dataset.msgId) return;
const lockKey = el.dataset.lockType + ':' + el.dataset.msgId;
const nowLocked = !lockedMessages.has(lockKey);
const table = el.dataset.lockType === 'ch' ? 'channel_messages' : 'messages';
// Update in database — realtime subscription will handle the visual update
const { error } = await sb.from(table).update({ locked: nowLocked }).eq('id', el.dataset.msgId);
if (error) {
console.error('toggleLock DB error:', error);
appendSystemMsg('ERROR: COULD NOT TOGGLE LOCK');
return undefined;
}
// Optimistic local update (realtime will confirm)
if (nowLocked) lockedMessages.add(lockKey); else lockedMessages.delete(lockKey);
persistLockedMessages();
applyLockVisual(el, nowLocked);
return nowLocked;
}
function handleLockUpdate(table, row) {
const lockType = table === 'channel_messages' ? 'ch' : 'dm';
const lockKey = lockType + ':' + row.id;
const el = document.querySelector(`.message[data-lock-type="${lockType}"][data-msg-id="${row.id}"]`);
if (row.locked) {
lockedMessages.add(lockKey);
} else {
lockedMessages.delete(lockKey);
}
persistLockedMessages();
if (el) applyLockVisual(el, row.locked);
}
function subscribeToLocks() {
lockChannel = sb
.channel('lock-sync')
.on('postgres_changes',
{ event: 'UPDATE', schema: 'public', table: 'messages' },
(payload) => {
if (payload.old.locked !== payload.new.locked) {
handleLockUpdate('messages', payload.new);
}
})
.on('postgres_changes',
{ event: 'UPDATE', schema: 'public', table: 'channel_messages' },
(payload) => {
if (payload.old.locked !== payload.new.locked) {
handleLockUpdate('channel_messages', payload.new);
}
})
.subscribe();
}
async function cmdLock(args) {
const feed = document.getElementById('message-feed');
const messages = Array.from(feed.querySelectorAll('.message:not(.skeleton)'));
if (!args) {
if (messages.length === 0) {
appendSystemMsg('NO MESSAGES TO LOCK');
return;
}
const last = messages[messages.length - 1];
const isLocked = await toggleLock(last.id);
if (isLocked !== undefined) appendSystemMsg(isLocked ? 'MESSAGE LOCKED' : 'MESSAGE UNLOCKED');
return;
}
const num = parseInt(args, 10);
if (isNaN(num) || num < 1 || num > messages.length) {
appendSystemMsg(`USAGE: /lock [1-${messages.length}] — message number from top`);
return;
}
const target = messages[num - 1];
const isLocked = await toggleLock(target.id);
if (isLocked !== undefined) appendSystemMsg(isLocked ? `MESSAGE #${num} LOCKED` : `MESSAGE #${num} UNLOCKED`);
}
function cmdClear() {
const feed = document.getElementById('message-feed');
// Collect locked message elements
const locked = Array.from(feed.querySelectorAll('.message.locked'));
// Detach locked messages before wiping
locked.forEach(el => el.remove());
feed.innerHTML = '';
renderedMsgIds.clear();
// Re-insert locked messages stacked at the top
locked.forEach(el => {
feed.appendChild(el);
// Re-add their IDs to renderedMsgIds so they don't get duped
const dbId = el.dataset.msgId;
if (dbId) {
const dedupKey = el.dataset.lockType === 'ch' ? 'ch-' + dbId : dbId;
renderedMsgIds.add(dedupKey);
}
});
let latestMsgTime = 0;
const cacheKey = viewMode === 'channel' ? 'ch:' + activeChannel : (activeContact ? activeContact.id : null);
if (cacheKey) {
const cached = conversationCache.get(cacheKey);
if (cached && cached.length > 0) {
for (let i = cached.length - 1; i >= 0; i--) {
if (cached[i].created_at) {
latestMsgTime = new Date(cached[i].created_at).getTime();
break;
}
}
}
if (cached) {
const lockType = viewMode === 'channel' ? 'ch' : 'dm';
const filteredCached = cached.filter(msg => msg.locked || lockedMessages.has(lockType + ':' + msg.id));
conversationCache.set(cacheKey, filteredCached);
}
}
const clearTime = latestMsgTime > 0 ? latestMsgTime + 1 : Date.now();
const clearKeyStr = viewMode === 'channel' ? `clear-${currentUser.id}-ch-${activeChannel}` : `clear-${currentUser.id}-dm-${activeContact.id}`;
localStorage.setItem(clearKeyStr, clearTime.toString());
appendSystemMsg(locked.length > 0
? `FEED CLEARED — ${locked.length} LOCKED MESSAGE${locked.length > 1 ? 'S' : ''} PRESERVED`
: 'FEED CLEARED');
}
function cmdWho() {
const online = allUsers.filter(u => onlineIds.has(u.id));
if (online.length === 0) {
appendSystemMsg('NO USERS ONLINE');
} else {
const names = online.map(u => u.username).sort().join(', ');
appendSystemMsg('ONLINE (' + online.length + '): ' + names);
}
}
async function cmdTop() {
appendSystemMsg('GLOBAL COMM METRICS: MESSAGES SENT');
const { data, error } = await sb.rpc('get_message_counts');
if (error || !data || data.length === 0) {
appendSystemMsg('NO DATA AVAILABLE');
return;
}
const top = data.slice(0, 10);
const maxCount = top[0].total_count;
const BAR_WIDTH = 20;
const maxName = Math.max(...top.map(r => {
const u = allUsers.find(u => u.id === r.sender_id);
return (u ? u.username : 'unknown').length;
}));
const maxDigits = maxCount.toLocaleString().length;
top.forEach((row, i) => {
const user = allUsers.find(u => u.id === row.sender_id);
const name = user ? user.username : 'unknown';
const color = getColorHex(user ? user.color_id : 1);
const filled = Math.max(1, Math.round((row.total_count / maxCount) * BAR_WIDTH));
const empty = BAR_WIDTH - filled;
const bar = '▓'.repeat(filled) + '░'.repeat(empty);
const rank = `[${i + 1}]`.padEnd(4);
const paddedName = name.padEnd(maxName);
const count = row.total_count.toLocaleString().padStart(maxDigits);
const nameHtml = `<span style="color:${color};font-style:normal">${paddedName}</span>`;
appendSystemMsgHtml(`${rank} ${nameHtml} ${bar} ${count}`);
});
}
function cmdHelp() {
appendSystemMsg('AVAILABLE COMMANDS:');
for (const [name, cmd] of Object.entries(COMMANDS)) {
appendSystemMsg(' /' + name + ' — ' + cmd.description);
}
}
/* ── Terminal Utility Commands ─────────────────────────────────── */
function cmdB64(args) {
const parts = args.trim().split(/\s+/);
const sub = (parts[0] || '').toLowerCase();
const text = parts.slice(1).join(' ');
if (sub === 'encode' && text) {
try {
const bytes = new TextEncoder().encode(text);
const binary = Array.from(bytes, b => String.fromCharCode(b)).join('');
appendSystemMsg('B64 ENCODE: ' + btoa(binary));
} catch { appendSystemMsg('ERROR: COULD NOT ENCODE'); }
} else if (sub === 'decode' && text) {
try {
const binary = atob(text);
const bytes = Uint8Array.from(binary, c => c.charCodeAt(0));
appendSystemMsg('B64 DECODE: ' + new TextDecoder().decode(bytes));
} catch { appendSystemMsg('ERROR: INVALID BASE64 INPUT'); }
} else {
appendSystemMsg('USAGE: /b64 encode <text> or /b64 decode <base64>');
}
}
function cmdRot13(args) {
if (!args.trim()) { appendSystemMsg('USAGE: /rot13 <text>'); return; }
const result = args.replace(/[a-zA-Z]/g, c => {
const base = c <= 'Z' ? 65 : 97;
return String.fromCharCode(((c.charCodeAt(0) - base + 13) % 26) + base);
});
appendSystemMsg('ROT13: ' + result);
}
function cmdHex(args) {
const parts = args.trim().split(/\s+/);
const sub = (parts[0] || '').toLowerCase();
const text = parts.slice(1).join(' ');
if (sub === 'encode' && text) {
const hex = Array.from(new TextEncoder().encode(text))
.map(b => b.toString(16).padStart(2, '0')).join(' ');
appendSystemMsg('HEX ENCODE: ' + hex);
} else if (sub === 'decode' && text) {
try {
const bytes = text.replace(/\s+/g, '').match(/.{1,2}/g).map(h => parseInt(h, 16));
appendSystemMsg('HEX DECODE: ' + new TextDecoder().decode(new Uint8Array(bytes)));
} catch { appendSystemMsg('ERROR: INVALID HEX INPUT'); }
} else {
appendSystemMsg('USAGE: /hex encode <text> or /hex decode <hex bytes>');
}
}
async function cmdHash(args) {
if (!args.trim()) { appendSystemMsg('USAGE: /hash <text>'); return; }
const data = new TextEncoder().encode(args);
const hashBuffer = await crypto.subtle.digest('SHA-256', data);
const hashHex = Array.from(new Uint8Array(hashBuffer))
.map(b => b.toString(16).padStart(2, '0')).join('');
appendSystemMsg('SHA-256: ' + hashHex);
}
function cmdTs() {
const now = new Date();
appendSystemMsg('UNIX: ' + Math.floor(now.getTime() / 1000));
appendSystemMsg('ISO: ' + now.toISOString());
appendSystemMsg('UTC: ' + now.toUTCString());
}
function cmdDice(args) {
const match = args.trim().match(/^(\d+)d(\d+)$/i);
if (!match) { appendSystemMsg('USAGE: /dice <NdM> — e.g. 2d6, 1d20, 4d8'); return; }
const count = Math.min(parseInt(match[1], 10), 100);
const sides = parseInt(match[2], 10);
if (count < 1 || sides < 2) { appendSystemMsg('ERROR: NEED AT LEAST 1 DIE WITH 2+ SIDES'); return; }
const rolls = Array.from({ length: count }, () => Math.floor(Math.random() * sides) + 1);
const total = rolls.reduce((a, b) => a + b, 0);
appendSystemMsg(`ROLL ${count}d${sides}: [${rolls.join(', ')}] = ${total}`);
}
/* ── End Terminal Utility Commands ─────────────────────────────── */
function cmdColorList() {
appendSystemMsg('AVAILABLE IDENTITY COLORS:');
for (const c of IDENTITY_COLORS) {
const num = String(c.id).padStart(1, ' ');
appendSystemMsg(` [ ${num} ] \u2588\u2588 ${c.name}`, c.hex);
}
appendSystemMsg(' > Type /color set [number] to apply');
}
async function cmdColor(args) {
const parts = args.trim().toLowerCase().split(/\s+/);
const sub = parts[0];
if (!sub || sub === 'list') {
cmdColorList();
return;
}
if (sub === 'set') {
const num = parseInt(parts[1], 10);
if (isNaN(num) || num < 1 || num > IDENTITY_COLORS.length) {
appendSystemMsg(`USAGE: /color set [1-${IDENTITY_COLORS.length}]`);
return;
}
const chosen = IDENTITY_COLORS.find(c => c.id === num);
const { error } = await sb.from('profiles').update({ color_id: num }).eq('id', currentUser.id);
if (error) {
appendSystemMsg('ERROR: COULD NOT SET COLOR');
console.error('cmdColor error:', error);
return;
}
currentUser.color_id = num;
// Update self-username color in sidebar
const selfEl = document.getElementById('self-username');
if (selfEl) selfEl.style.color = chosen.hex;
// Recolor any already-rendered messages by self
recolorRenderedMessages(currentUser.id);
appendSystemMsg(`COLOR SET: ${chosen.name}`);
return;
}
appendSystemMsg(`USAGE: /color list OR /color set [1-${IDENTITY_COLORS.length}]`);
}
function cmdThemeList() {
const current = getStoredTheme();
appendSystemMsg('AVAILABLE THEMES:');
for (const t of THEMES) {
const marker = t.id === current ? ' ←' : '';
appendSystemMsg(` [ ${t.id} ] ${t.name} — ${t.desc}${marker}`);
}
appendSystemMsg(' > Type /theme set <name> to apply');
}
async function cmdTheme(args) {
const parts = args.trim().toLowerCase().split(/\s+/);
const sub = parts[0];
if (!sub || sub === 'list') {
cmdThemeList();
return;
}
if (sub === 'set') {
const id = parts[1];
const theme = THEMES.find(t => t.id === id);
if (!theme) {
appendSystemMsg(`UNKNOWN THEME: ${id || '(none)'}`);
cmdThemeList();
return;
}
applyTheme(theme.id);
appendSystemMsg(`THEME SET: ${theme.name}`);
return;
}
appendSystemMsg('USAGE: /theme list OR /theme set <name>');
}
function cmdMute() {
toggleMute();
appendSystemMsg(isMuted ? 'AUDIO MUTED' : 'AUDIO UNMUTED');
}
function toggleMute() {
isMuted = !isMuted;
const btn = document.getElementById('audio-toggle');
const textSpan = document.getElementById('audio-toggle-text');
if (!btn || !textSpan) return;
if (isMuted) {
textSpan.textContent = '✗';
btn.classList.add('muted');
} else {
textSpan.textContent = '♪';
btn.classList.remove('muted');
}
}
// =============================================
// 3d. COMMAND HINTS
// =============================================
let cmdHintIdx = -1; // active hint index (-1 = none)
function showCmdHints(filter) {
const hintsEl = document.getElementById('cmd-hints');
const entries = Object.entries(COMMANDS)
.filter(([name]) => name.startsWith(filter));
if (entries.length === 0) {
hideCmdHints();
return;
}
cmdHintIdx = -1;
hintsEl.innerHTML = entries.map(([name, c]) =>
`<div class="cmd-hint" data-cmd="${name}">` +
`<span class="cmd-hint-name">/${name}</span>` +
`<span class="cmd-hint-desc">${c.description}</span>` +
`</div>`
).join('');
hintsEl.classList.remove('hidden');
}
function hideCmdHints() {
const hintsEl = document.getElementById('cmd-hints');
hintsEl.classList.add('hidden');
hintsEl.innerHTML = '';
cmdHintIdx = -1;
}
function selectCmdHint(name) {
const input = document.getElementById('message-input');
const needsArgs = name === 'status';
input.value = '/' + name + (needsArgs ? ' ' : '');
hideCmdHints();
input.focus();
}
function navigateCmdHints(direction) {
const items = document.querySelectorAll('#cmd-hints .cmd-hint');
if (items.length === 0) return false;
items.forEach(el => el.classList.remove('active'));
if (direction === 'down') {
cmdHintIdx = cmdHintIdx < items.length - 1 ? cmdHintIdx + 1 : 0;
} else {
cmdHintIdx = cmdHintIdx > 0 ? cmdHintIdx - 1 : items.length - 1;
}
items[cmdHintIdx].classList.add('active');
items[cmdHintIdx].scrollIntoView({ block: 'nearest' });
return true;
}
function confirmCmdHint() {
const items = document.querySelectorAll('#cmd-hints .cmd-hint');
if (cmdHintIdx >= 0 && cmdHintIdx < items.length) {
selectCmdHint(items[cmdHintIdx].dataset.cmd);
return true;
}
return false;
}
// =============================================
// 4. UI / RENDER
// =============================================
async function fetchLastMessageTimes() {
const { data: sent } = await sb
.from('messages')
.select('recipient_id, created_at')
.eq('sender_id', currentUser.id)
.order('created_at', { ascending: false });
const { data: received } = await sb
.from('messages')
.select('sender_id, created_at')
.eq('recipient_id', currentUser.id)
.order('created_at', { ascending: false });
const map = new Map();
for (const m of (sent || [])) {
const t = new Date(m.created_at).getTime();
if (!map.has(m.recipient_id) || t > map.get(m.recipient_id)) {
map.set(m.recipient_id, t);
}
}
for (const m of (received || [])) {
const t = new Date(m.created_at).getTime();
if (!map.has(m.sender_id) || t > map.get(m.sender_id)) {
map.set(m.sender_id, t);
}
}
lastMessageTime = map;
}
function sortByLastMessage(users) {
return users.slice().sort((a, b) => {
const tA = lastMessageTime.get(a.id) || 0;
const tB = lastMessageTime.get(b.id) || 0;
if (tA !== tB) return tB - tA;
return a.username.localeCompare(b.username);
});
}
function renderContacts() {
const list = document.querySelector('.contact-list');
list.innerHTML = '';
// Global channel entry
const globalEl = document.createElement('div');
globalEl.className = 'contact channel-entry' +
(viewMode === 'channel' && activeChannel === 'GLOBAL' ? ' active' : '');
globalEl.dataset.channel = 'GLOBAL';
globalEl.innerHTML =
`<span class="status-dot online"></span>` +
`<span class="contact-name"># GLOBAL</span>` +
`<span class="contact-badge">[CH]</span>`;
list.appendChild(globalEl);
// Separator
const sep = document.createElement('div');
sep.className = 'channel-separator';
list.appendChild(sep);
const others = allUsers.filter(u => u.id !== currentUser.id);
if (others.length === 0) {
const empty = document.createElement('div');
empty.className = 'system-msg';
empty.textContent = '// NO CONTACTS';
list.appendChild(empty);
return;
}
const favoriteUsers = sortByLastMessage(others.filter(u => favoriteIds.has(u.id)));
const onlineUsers = sortByLastMessage(others.filter(u => onlineIds.has(u.id) && !favoriteIds.has(u.id)));
const offlineUsers = sortByLastMessage(others.filter(u => !onlineIds.has(u.id) && !favoriteIds.has(u.id)));
function unreadBadge(userId) {
const count = unreadCounts.get(userId);
return count ? `<span class="contact-unread" data-count="${count}">[${count}]</span>` : '';
}
function nameGroup(user, isOnline) {
const color = getColorHex(user.color_id);
const lastSeen = isOnline ? '' : `<span class="contact-last-seen">seen ${formatLastSeen(user.last_seen_at)}</span>`;
return `<span class="contact-name-group"><span class="contact-name" data-username="${escapeHtml(user.username)}" style="color:${color}">${escapeHtml(user.username)}</span>${lastSeen}</span>`;
}
// Pinned section (only shown when there are pinned contacts)
if (favoriteUsers.length > 0) {
const pinnedHeader = document.createElement('div');
pinnedHeader.className = 'contact-section-header';
pinnedHeader.textContent = `Pinned \u2014 ${favoriteUsers.length}`;
list.appendChild(pinnedHeader);
for (const user of favoriteUsers) {
const isOnline = onlineIds.has(user.id);
const el = document.createElement('div');
el.className = 'contact ' + (isOnline ? 'contact-online' : 'contact-offline') +
(viewMode === 'dm' && activeContact && activeContact.id === user.id ? ' active' : '');
el.dataset.userId = user.id;
el.innerHTML =
`<span class="status-dot ${isOnline ? 'online' : 'offline'}"></span>` +
nameGroup(user, isOnline) +
unreadBadge(user.id) +
`<span class="contact-fav is-fav" data-fav-id="${user.id}" title="Remove from favorites">\u2605</span>`;
list.appendChild(el);
}
}
// Online section (only shown when there are online contacts)
if (onlineUsers.length > 0) {
const onlineHeader = document.createElement('div');
onlineHeader.className = 'contact-section-header';
onlineHeader.textContent = `Online \u2014 ${onlineUsers.length}`;
list.appendChild(onlineHeader);
for (const user of onlineUsers) {
const el = document.createElement('div');
el.className = 'contact contact-online' + (viewMode === 'dm' && activeContact && activeContact.id === user.id ? ' active' : '');
el.dataset.userId = user.id;
el.innerHTML =
`<span class="status-dot online"></span>` +
nameGroup(user, true) +
unreadBadge(user.id) +
`<span class="contact-fav" data-fav-id="${user.id}" title="Add to favorites">\u2606</span>`;
list.appendChild(el);
}
}
// Offline section header (collapsible, collapsed by default)
const offlineCollapsed = window._offlineCollapsed !== false; // default collapsed
const offlineHeader = document.createElement('div');
offlineHeader.className = 'contact-section-header contact-section-collapsible';
offlineHeader.dataset.section = 'offline';
offlineHeader.innerHTML = `Offline \u2014 ${offlineUsers.length} <span class="section-toggle">${offlineCollapsed ? '[+]' : '[\u2212]'}</span>`;
list.appendChild(offlineHeader);
for (const user of offlineUsers) {
const el = document.createElement('div');
el.className = 'contact contact-offline' + (viewMode === 'dm' && activeContact && activeContact.id === user.id ? ' active' : '');
el.dataset.userId = user.id;
el.dataset.offlineItem = '1';
if (offlineCollapsed) el.style.display = 'none';
el.innerHTML =
`<span class="status-dot offline"></span>` +
nameGroup(user, false) +
unreadBadge(user.id) +
`<span class="contact-fav" data-fav-id="${user.id}" title="Add to favorites">\u2606</span>`;
list.appendChild(el);
}
// Empty state hint when no pinned/online and offline is collapsed
const offlineCollapsedFinal = window._offlineCollapsed !== false;
if (favoriteUsers.length === 0 && onlineUsers.length === 0 && (offlineCollapsedFinal || offlineUsers.length === 0)) {
const hint = document.createElement('div');
hint.className = 'contact-list-empty-hint';
hint.textContent = 'no active conversations';
list.appendChild(hint);
}
// Re-apply filter if active
const filterVal = document.getElementById('contact-filter')?.value;
if (filterVal) applyContactFilter(filterVal);
}
function appendMessage(msg, animate = true) {
const feed = document.getElementById('message-feed');
const el = document.createElement('div');
const isSelf = msg.sender_id === currentUser.id;
el.className = 'message' + (isSelf ? ' self' : '');
const lastMsg = feed.lastElementChild;
if (lastMsg && lastMsg.dataset.senderId !== String(msg.sender_id)) {
el.classList.add('new-sender');
}
if (!animate) el.style.animation = 'none';
const senderName = isSelf ? currentUser.username : (msg.sender ? msg.sender.username : '???');
const senderUser = isSelf ? currentUser : allUsers.find(u => u.id === msg.sender_id);
const isAdmin = senderUser && senderUser.is_admin;
const senderColor = getColorHex(senderUser?.color_id);
const time = msg.created_at
? new Date(msg.created_at).toLocaleTimeString('en-GB', { hour: '2-digit', minute: '2-digit' })
: nowTime();
// Lock tracking: store DB id and table type on the element
const msgDbId = msg.id || (Date.now() + '-' + Math.random().toString(36).slice(2, 6));
const lockType = msg.channel ? 'ch' : 'dm';
const elId = 'msg-' + lockType + '-' + msgDbId;
el.id = elId;
el.dataset.msgId = msgDbId;
el.dataset.lockType = lockType;
el.dataset.senderId = msg.sender_id; // for recolorRenderedMessages
const lockKey = lockType + ':' + msgDbId;
// Check both DB field and local set (local set covers optimistic updates)
const isLocked = msg.locked || lockedMessages.has(lockKey);
if (isLocked && !lockedMessages.has(lockKey)) {
lockedMessages.add(lockKey);
persistLockedMessages();
} else if (isLocked) {
lockedMessages.add(lockKey);
}
const audioMatch = msg.body ? msg.body.match(/^\[AUDIO:(\d+)\]$/) : null;
const bodyContent = audioMatch
? `<button class="msg-audio-btn" data-audio-id="${audioMatch[1]}">[♪] AUDIO ${String(audioMatch[1]).padStart(2, '0')}</button>`
: `<span class="msg-text">${escapeHtml(msg.body)}</span>`;
el.innerHTML =
`<span class="msg-time">${time}</span>` +
` <span class="msg-sender" style="color:${senderColor}">${escapeHtml(senderName)}</span>` +
(isAdmin ? `<span class="msg-admin-tag">[ADMIN]</span>` : '') +
`<span class="msg-lock-tag${isLocked ? '' : ' hidden'}">[LOCKED]</span>` +
`<span class="msg-sep">></span>` +
bodyContent +
`<button class="msg-lock-btn" title="Lock message">${isLocked ? '[UNLOCK]' : '[LOCK]'}</button>`;
if (isLocked) el.classList.add('locked');
// Audio message play button
const audioBtn = el.querySelector('.msg-audio-btn');
if (audioBtn) {
audioBtn.addEventListener('click', () => {
const audio = new Audio(`Audios/audio${audioBtn.dataset.audioId}.mp3`);
audio.play();
});
}
// Lock button click
el.querySelector('.msg-lock-btn').addEventListener('click', (e) => {
e.stopPropagation();
toggleLock(elId);
});
feed.appendChild(el);
if (isUserAtBottom) {
scrollToBottom();
} else if (animate) {