forked from The-Sawfish/chat1234567890
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchat.html
More file actions
428 lines (385 loc) · 16.1 KB
/
Copy pathchat.html
File metadata and controls
428 lines (385 loc) · 16.1 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
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Hybrid Chat — Fixed</title>
<meta name="viewport" content="width=device-width,initial-scale=1" />
<script src="https://unpkg.com/peerjs@1.4.7/dist/peerjs.min.js"></script>
<style>
:root{
--bg:#f5f7fa; --sidebar:#2c3e50; --sidebar-active:#34495e; --accent:#3498db;
--text:#222; --card:#fff; --self:#2ecc71; --other:#bdc3c7;
}
[data-theme="dark"]{
--bg:#0f1112; --sidebar:#16202b; --sidebar-active:#25343e; --accent:#256aa2;
--text:#eaeef0; --card:#151718; --self:#27ae60; --other:#4b5563;
}
html,body{height:100%;margin:0;background:var(--bg);color:var(--text);font-family:Inter, Arial, sans-serif}
.stage{display:flex;justify-content:center;align-items:center;height:100vh;padding:12px;box-sizing:border-box}
#app{display:flex;width:95%;max-width:1000px;height:84vh;border-radius:12px;overflow:hidden;box-shadow:0 8px 30px rgba(2,6,23,.12)}
/* SIDEBAR */
#sidebar{width:220px;background:var(--sidebar);color:#fff;padding:12px;box-sizing:border-box;display:flex;flex-direction:column}
#sidebar h3{margin:0 0 12px;text-align:center;font-size:16px}
.room-btn{display:flex;align-items:center;justify-content:space-between;padding:8px;border-radius:8px;border:0;background:transparent;color:#fff;margin:6px 0;cursor:pointer;font-weight:600}
.room-btn:hover{background:rgba(255,255,255,0.04)}
.room-btn.active{background:var(--sidebar-active)}
.room-label{flex:1;text-align:left;padding-right:6px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
.badge{background:#ff4d4f;border-radius:999px;padding:2px 7px;font-size:12px;margin-left:8px}
.controls{margin-top:auto;display:flex;gap:8px}
.btn-flat{background:var(--accent);border:0;color:#fff;padding:8px 10px;border-radius:8px;cursor:pointer;font-weight:700}
.small-flat{background:transparent;border:1px solid rgba(255,255,255,0.08);color:#fff;padding:6px 8px;border-radius:8px;cursor:pointer}
/* MAIN */
#main{flex:1;display:flex;flex-direction:column;background:var(--card)}
header{display:flex;align-items:center;justify-content:space-between;padding:10px 14px;background:var(--accent);color:#fff}
#headerLeft{display:flex;flex-direction:column}
#title{font-weight:800}
#subtitle{font-size:12px;opacity:.95}
#headerRight{display:flex;gap:8px;align-items:center}
#chat{flex:1;overflow:auto;padding:14px;box-sizing:border-box;background:linear-gradient(180deg, rgba(0,0,0,0.02), transparent)}
.msg{clear:both;max-width:72%;padding:10px 12px;border-radius:12px;margin:8px 0;word-break:break-word}
.self{background:var(--self);color:#fff;float:right;border-bottom-right-radius:4px}
.other{background:var(--other);float:left;color:#111;border-bottom-left-radius:4px}
.meta{font-size:11px;color:rgba(0,0,0,0.45);margin-top:6px}
footer{display:flex;gap:8px;padding:10px;background:transparent;border-top:1px solid rgba(0,0,0,0.06)}
input.message{flex:1;padding:10px;border-radius:10px;border:1px solid #d6dbe0;font-size:14px}
button.send{padding:10px 12px;border-radius:10px;border:0;background:var(--accent);color:#fff;font-weight:700;cursor:pointer}
.delete-btn{background:none;border:0;color:rgba(255,255,255,.8);cursor:pointer;padding:6px;border-radius:6px}
@media(max-width:800px){
#sidebar{width:110px;padding:8px} .room-label{display:none}
#app{height:92vh}
}
</style>
</head>
<body data-theme="light">
<div class="stage">
<div id="app">
<aside id="sidebar">
<h3>Chats</h3>
<div id="roomsContainer">
<button class="room-btn active" data-room="Global"><span class="room-label">🌍 Global</span></button>
</div>
<div class="controls">
<button id="addFriend" class="btn-flat">+ New Chat</button>
<button id="logout" class="small-flat">Logout</button>
</div>
</aside>
<main id="main">
<header>
<div id="headerLeft">
<div id="title">—</div>
<div id="subtitle">—</div>
</div>
<div id="headerRight">
<div id="typing" style="font-size:13px;opacity:.92"></div>
<button id="themeToggle" class="delete-btn">🌙</button>
</div>
</header>
<section id="chat"></section>
<footer>
<input id="msgInput" class="message" placeholder="Type a message…" disabled>
<button id="sendBtn" class="send" disabled>Send</button>
</footer>
</main>
</div>
</div>
<script>
/* ======= Initialization & storage keys ======= */
const username = sessionStorage.getItem('username');
if(!username) { window.location.href='login.html'; throw ''; }
const ROOMS_KEY = username + '_rooms';
const UNREAD_KEY = username + '_unread';
const GLOBAL_KEY = 'globalMessages';
const SEEN_KEY = username + '_seen'; // small persistent store of seen message ids (optional)
let rooms = JSON.parse(localStorage.getItem(ROOMS_KEY) || '{"Global":[]}'); // {roomKey: [{who,msg,id,time}]}
let unread = JSON.parse(localStorage.getItem(UNREAD_KEY) || '{}');
let seen = new Set(JSON.parse(localStorage.getItem(SEEN_KEY) || '[]'));
// UI refs
const roomsContainer = document.getElementById('roomsContainer');
const chatEl = document.getElementById('chat');
const titleEl = document.getElementById('title');
const subtitleEl = document.getElementById('subtitle');
const typingEl = document.getElementById('typing');
const msgInput = document.getElementById('msgInput');
const sendBtn = document.getElementById('sendBtn');
const addFriendBtn = document.getElementById('addFriend');
const logoutBtn = document.getElementById('logout');
const themeToggle = document.getElementById('themeToggle');
// state
let currentRoom = 'Global';
let peer = null;
let connections = {}; // peerId => DataConnection
/* ======= Utilities ======= */
function saveState(){
localStorage.setItem(ROOMS_KEY, JSON.stringify(rooms));
localStorage.setItem(UNREAD_KEY, JSON.stringify(unread));
localStorage.setItem(SEEN_KEY, JSON.stringify(Array.from(seen)));
}
function roomKey(a,b){ return [a,b].sort().join('_'); }
function otherNameFromRoomKey(rk){
if(rk === 'Global') return 'Global';
const parts = rk.split('_');
return parts[0] === username ? parts[1] : parts[0];
}
function makeId(){ return Date.now().toString(36) + '-' + Math.random().toString(36).slice(2,9); }
/* ======= Rendering ======= */
function renderRooms(){
// remove all except Global button
roomsContainer.innerHTML = '';
// Global button (first)
const globalBtn = document.createElement('button');
globalBtn.className = 'room-btn' + (currentRoom === 'Global' ? ' active' : '');
globalBtn.dataset.room = 'Global';
globalBtn.innerHTML = `<span class="room-label">🌍 Global</span>` + (unread['Global'] ? `<span class="badge">${unread['Global']}</span>` : '');
globalBtn.onclick = ()=>switchRoom('Global');
roomsContainer.appendChild(globalBtn);
// other rooms (sorted: most recent message timestamp desc)
const list = Object.keys(rooms).filter(r=>r!=='Global').sort((a,b)=>{
const la = (rooms[a].length && rooms[a][rooms[a].length-1].time) || 0;
const lb = (rooms[b].length && rooms[b][rooms[b].length-1].time) || 0;
return lb - la;
});
for(const rk of list){
const label = otherNameFromRoomKey(rk);
const btn = document.createElement('button');
btn.className = 'room-btn' + (currentRoom === rk ? ' active' : '');
btn.dataset.room = rk;
const badgeHTML = (unread[rk] ? `<span class="badge">${unread[rk]}</span>` : '');
btn.innerHTML = `<span class="room-label">💬 ${label}</span>${badgeHTML}`;
btn.onclick = ()=>switchRoom(rk);
// delete icon (private only)
const del = document.createElement('button');
del.className = 'delete-btn';
del.innerHTML = '🗑';
del.onclick = (e)=>{ e.stopPropagation(); deleteChat(rk); };
btn.appendChild(del);
roomsContainer.appendChild(btn);
}
}
function renderChat(){
titleEl.innerText = username + ' • ' + (currentRoom==='Global' ? 'Global' : otherNameFromRoomKey(currentRoom));
subtitleEl.innerText = currentRoom === 'Global' ? 'Public chat — last 20 stored locally' : 'Private chat';
chatEl.innerHTML = '';
if(!rooms[currentRoom]) rooms[currentRoom] = [];
for(const m of rooms[currentRoom]){
appendMsgDOM(m);
}
chatEl.scrollTop = chatEl.scrollHeight;
unread[currentRoom] = 0;
saveState();
renderRooms();
}
function appendMsgDOM(obj){
const d = document.createElement('div');
d.className = 'msg ' + (obj.who === username ? 'self' : 'other');
const text = document.createElement('div'); text.innerText = obj.msg;
const meta = document.createElement('div'); meta.className='meta'; meta.innerText = `${obj.who} • ${new Date(obj.time).toLocaleTimeString()}`;
d.appendChild(text); d.appendChild(meta); chatEl.appendChild(d);
}
/* ======= Messaging primitives (with flood + dedupe) ======= */
function handleIncomingMessage(data, fromPeer){
if(!data || !data.id) return;
if(seen.has(data.id)) return;
seen.add(data.id);
// append to local store
if(!rooms[data.room]) rooms[data.room] = [];
rooms[data.room].push({who: data.from, msg: data.text, id: data.id, time: data.time});
// keep last 20 for global
if(data.room === 'Global'){ rooms['Global'] = rooms['Global'].slice(-40); localStorage.setItem(GLOBAL_KEY, JSON.stringify(rooms['Global'].slice(-20))); }
// UI
if(currentRoom === data.room){
appendMsgDOM({who:data.from,msg:data.text,time:data.time});
chatEl.scrollTop = chatEl.scrollHeight;
} else {
unread[data.room] = (unread[data.room]||0) + 1;
renderRooms();
}
saveState();
// Flood: forward to other connected peers except the peer we got it from
for(const pid in connections){
if(pid === fromPeer) continue;
const c = connections[pid];
if(c && c.open) c.send(data);
}
}
function sendMessage(text){
const id = makeId();
const time = Date.now();
const packet = { type:'msg', id, from: username, text, room: currentRoom, time };
// mark seen locally and store
seen.add(id);
if(!rooms[currentRoom]) rooms[currentRoom] = [];
rooms[currentRoom].push({who: username, msg: text, id, time});
if(currentRoom === 'Global'){ rooms['Global'] = rooms['Global'].slice(-40); localStorage.setItem(GLOBAL_KEY, JSON.stringify(rooms['Global'].slice(-20))); }
renderChat();
if(currentRoom === 'Global'){
// send to all connected peers
for(const pid in connections){
const c = connections[pid];
if(c && c.open) try{ c.send(packet); }catch(e){}
}
} else {
// private: send to the friend (ensure connection exists)
const parts = currentRoom.split('_');
const friend = parts[0] === username ? parts[1] : parts[0];
const c = connections[friend];
if(c && c.open) c.send(packet);
}
saveState();
}
/* ======= Connections handling ======= */
function setupConnection(conn){
const peerId = conn.peer;
connections[peerId] = conn;
// ensure a roomKey exists (shared key)
const rk = roomKey(username, peerId);
if(!rooms[rk]) rooms[rk] = [];
if(!document.querySelector(`.room-btn[data-room="${rk}"]`)) addRoomButton(rk);
conn.on('data', (data) => {
// expected packet shape: {type, id, from, text, room, time}
if(!data || !data.type) return;
if(data.type === 'msg') handleIncomingMessage(data, peerId);
else if(data.type === 'typing') {
if(data.room === currentRoom) showTyping(data.from);
}
});
conn.on('open', () => {
// optional: exchange current global cache — to help late joiners
// send last 20 global messages to newly connected peer so they can store/show them
const toSend = (rooms['Global']||[]).slice(-20);
for(const m of toSend){
try{ conn.send({type:'msg', id: m.id || makeId(), from: m.who, text: m.msg, room:'Global', time: m.time || Date.now()}); } catch(e){}
}
renderRooms();
});
conn.on('close', () => { delete connections[peerId]; });
conn.on('error', ()=>{ delete connections[peerId]; });
}
/* ======= UI actions ======= */
function addRoomButton(roomKey){
// create button with label = otherUser
const label = otherNameFromRoomKey(roomKey);
const btn = document.createElement('button');
btn.className = 'room-btn';
btn.dataset.room = roomKey;
const badgeHTML = (unread[roomKey] ? `<span class="badge">${unread[roomKey]}</span>` : '');
btn.innerHTML = `<span class="room-label">💬 ${label}</span>${badgeHTML}`;
btn.onclick = () => switchRoom(roomKey);
// delete icon for private
if(roomKey !== 'Global'){
const del = document.createElement('button');
del.className = 'delete-btn';
del.innerText = '🗑';
del.onclick = (e) => { e.stopPropagation(); deleteChat(roomKey); };
btn.appendChild(del);
}
roomsContainer.appendChild(btn);
renderRooms();
}
function switchRoom(roomKey){
currentRoom = roomKey;
renderChat();
}
function deleteChat(roomKey){
if(roomKey === 'Global') return;
if(!confirm('Delete conversation with ' + otherNameFromRoomKey(roomKey) + '?')) return;
delete rooms[roomKey];
delete unread[roomKey];
saveState();
// remove button
const b = document.querySelector(`.room-btn[data-room="${roomKey}"]`);
if(b) b.remove();
// if current, switch to Global
if(currentRoom === roomKey) currentRoom = 'Global';
renderChat();
}
function showTyping(who){
typingEl.innerText = who + ' is typing...';
clearTimeout(window._typingTO);
window._typingTO = setTimeout(()=> typingEl.innerText = '', 1400);
}
/* ======= Add friend UI ======= */
addFriendBtn.onclick = async () => {
const friend = prompt('Enter username to chat with (exact):');
if(!friend || friend === username) return;
const rk = roomKey(username, friend);
if(!rooms[rk]) rooms[rk] = [];
unread[rk] = 0;
saveState();
if(!document.querySelector(`.room-btn[data-room="${rk}"]`)) addRoomButton(rk);
// try to connect
if(!connections[friend]){
try {
const conn = peer.connect(friend, { reliable: true });
conn.on('open', ()=> setupConnection(conn));
conn.on('error', ()=> console.warn('conn error'));
} catch(e){ console.warn('connect error', e); }
}
};
/* ======= Typing indicator send ======= */
msgInput.addEventListener('input', ()=>{
if(currentRoom === 'Global') return; // skip global typing
const parts = currentRoom.split('_');
const friend = parts[0] === username ? parts[1] : parts[0];
const conn = connections[friend];
if(conn && conn.open){
try{ conn.send({type:'typing', from: username, room: currentRoom}); } catch(e){}
}
});
/* ======= Send button ======= */
sendBtn.onclick = ()=> {
const text = msgInput.value.trim();
if(!text) return;
sendMessage(text);
msgInput.value = '';
};
/* ======= Logout ======= */
logoutBtn.onclick = ()=>{
sessionStorage.clear();
window.location.href = 'login.html';
};
/* ======= Theme toggle ======= */
themeToggle.onclick = ()=>{
const cur = document.body.getAttribute('data-theme') || 'light';
document.body.setAttribute('data-theme', cur === 'light' ? 'dark' : 'light');
};
/* ======= PeerJS setup & auto-connect existing rooms ======= */
function loadInitial(){
// load persisted global messages if present (helpful for single-device tests)
if(!rooms['Global'] || rooms['Global'].length === 0){
rooms['Global'] = JSON.parse(localStorage.getItem(GLOBAL_KEY) || '[]');
}
// ensure unread keys exist
for(const rk of Object.keys(rooms)) if(!unread[rk]) unread[rk] = 0;
// render initial UI
renderRooms();
renderChat();
}
loadInitial();
peer = new Peer(username); // username used as peer id
peer.on('open', id => {
// attempt to auto-connect to any known private rooms (so reload won't require manual re-add)
Object.keys(rooms).forEach(rk=>{
if(rk === 'Global') return;
const friend = otherNameFromRoomKey(rk);
if(friend && friend !== username && !connections[friend]){
try{
const conn = peer.connect(friend, { reliable: true });
conn.on('open', ()=> setupConnection(conn));
}catch(e){}
}
});
renderRooms();
});
peer.on('connection', conn => {
// Accept incoming connection
conn.on('open', ()=> setupConnection(conn));
});
/* ======= make sure UI enabled ======= */
peer.on('open', ()=> {
msgInput.disabled = false; sendBtn.disabled = false;
});
/* ======= save state on unload ======= */
window.addEventListener('beforeunload', ()=> saveState());
</script>
</body>
</html>