-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.js
More file actions
300 lines (252 loc) · 8.53 KB
/
script.js
File metadata and controls
300 lines (252 loc) · 8.53 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
const socket = io();
let currentUser = null;
let otherUser = null;
let showDecoded = false;
// Encoding using katakana (from original)
const customEncoding = "サハー「」ツエヲ・、テイヤェワシンチトクナネノソタユ゙スロリハン゚ァィゥォャュョッアイウエオ";
// Emoticon to Emoji map
const emojiMap = {
':)': '😊', ':-)': '😊',
':(': '😢', ':-(': '😢',
':D': '😃', ':-D': '😃',
';)': '😉', ';-)': '😉',
':p': '😛', ':P': '😛', ':-p': '😛',
'<3': '❤️',
':o': '😮', ':O': '😮',
':cool:': '😎',
':thumbsup:': '👍'
};
function processText(text) {
if (!text) return '';
// Replace emoticons with emojis
let processed = text;
for (const [emoticon, emoji] of Object.entries(emojiMap)) {
// Escape special regex characters in emoticon
const escaped = emoticon.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
// distinct replace to avoid replacing parts of words (simple boundary check)
// using split/join is safer for simple string replacement than regex without complex lookaheads
processed = processed.split(emoticon).join(emoji);
}
return processed;
}
function encode(text) {
let result = '';
for (let i = 0; i < text.length; i++) {
const charCode = text.charCodeAt(i);
if (charCode >= 97 && charCode <= 122) {
result += customEncoding[charCode - 97];
} else if (charCode >= 65 && charCode <= 90) {
result += customEncoding[charCode - 65];
} else {
result += text[i];
}
}
return result;
}
function decode(encodedText, originalText) {
// We store original with message, so just return it
return originalText;
}
function showCustomNameInput() {
document.getElementById('custom-name-input').style.display = 'flex';
document.getElementById('custom-name').focus();
}
function joinWithCustomName() {
const name = document.getElementById('custom-name').value.trim();
if (name) {
selectUser(name);
}
}
// Allow Enter key to submit custom name
document.getElementById('custom-name').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
joinWithCustomName();
}
});
function selectUser(user) {
let password = null;
if (user === 'Dad' || user === 'Jared') {
password = prompt(`Enter password for ${user}:`);
if (password === null) return; // User cancelled
}
currentUser = user;
document.getElementById('user-select').style.display = 'none';
document.getElementById('chat-screen').style.display = 'flex';
// Tell server we joined with password (if any)
socket.emit('join', { username: currentUser, password: password });
// Focus input
document.getElementById('message-input').focus();
}
function updateUserList(users) {
const userListDiv = document.getElementById('user-list');
userListDiv.innerHTML = '';
users.forEach(user => {
const item = document.createElement('div');
item.className = 'user-list-item';
let avatarHtml;
if (user === 'Dad' || user === 'Jared') {
avatarHtml = `<img src="${user}.jpg" alt="${user}">`;
} else {
avatarHtml = `<div class="user-initial">${user.charAt(0).toUpperCase()}</div>`;
}
item.innerHTML = `
${avatarHtml}
<span>${user}</span>
<div class="online-dot"></div>
`;
userListDiv.appendChild(item);
});
}
function addAnnouncement(announcement) {
const messagesDiv = document.getElementById('messages');
const div = document.createElement('div');
div.className = 'announcement';
div.textContent = announcement.text;
messagesDiv.appendChild(div);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
function formatTime(timestamp) {
const date = new Date(timestamp);
return date.toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' });
}
function getAvatarHtml(user) {
if (user === 'Dad' || user === 'Jared') {
return `<img class="message-avatar" src="${user}.jpg" alt="${user}">`;
} else {
const initial = user.charAt(0).toUpperCase();
return `<div class="message-avatar-placeholder">${initial}</div>`;
}
}
function addMessage(msg, prepend = false) {
const messagesDiv = document.getElementById('messages');
const row = document.createElement('div');
const isSent = msg.user === currentUser;
row.className = 'message-row ' + (isSent ? 'sent' : 'received');
const processedText = processText(msg.text);
const imageHtml = msg.image ? `<img src="${msg.image}" class="message-image" onclick="window.open(this.src)">` : '';
const textHtml = msg.text ? `<div class="encoded">${msg.encoded}</div><div class="decoded">${processedText}</div>` : '';
row.innerHTML = `
${getAvatarHtml(msg.user)}
<div class="message">
<div class="sender">${msg.user}</div>
${imageHtml}
${textHtml}
<div class="time">${formatTime(msg.timestamp)}</div>
</div>
`;
// Only add click-to-reveal if there is text to reveal
if (msg.text) {
row.querySelector('.message').onclick = (e) => {
// Don't trigger reveal if clicking the image
if (e.target.tagName !== 'IMG') {
e.currentTarget.classList.toggle('revealed');
}
};
}
if (showDecoded) {
row.querySelector('.message').classList.add('revealed');
}
if (prepend) {
messagesDiv.insertBefore(row, messagesDiv.firstChild);
} else {
messagesDiv.appendChild(row);
messagesDiv.scrollTop = messagesDiv.scrollHeight;
}
}
function handleImageUpload(input) {
const file = input.files[0];
if (!file) return;
// Limit size to ~2MB
if (file.size > 2 * 1024 * 1024) {
alert('File is too large. Please select an image under 2MB.');
input.value = '';
return;
}
const reader = new FileReader();
reader.onload = function(e) {
const imageData = e.target.result;
// Emit message with image
socket.emit('message', {
user: currentUser,
text: '', // No text for image-only message
encoded: '',
image: imageData
});
};
reader.readAsDataURL(file);
input.value = ''; // Reset input
}
function sendMessage() {
const input = document.getElementById('message-input');
const text = input.value.trim();
if (!text) return;
const encoded = encode(text);
socket.emit('message', {
user: currentUser,
text: text,
encoded: encoded,
image: null
});
input.value = '';
socket.emit('stop-typing');
}
function toggleDecode() {
showDecoded = !showDecoded;
const btn = document.getElementById('decode-toggle');
btn.textContent = showDecoded ? 'Show Encoded' : 'Show Decoded';
btn.classList.toggle('active', showDecoded);
document.querySelectorAll('.message-row .message').forEach(msg => {
msg.classList.toggle('revealed', showDecoded);
});
}
// Socket events
socket.on('history', (messages) => {
messages.forEach(msg => {
if (msg.type === 'announcement') {
addAnnouncement(msg);
} else {
addMessage(msg);
}
});
});
socket.on('message', (msg) => {
addMessage(msg);
});
socket.on('announcement', (announcement) => {
addAnnouncement(announcement);
});
socket.on('user-list', (users) => {
updateUserList(users);
});
socket.on('typing', (user) => {
if (user !== currentUser) {
document.getElementById('status-text').innerHTML =
'<span class="typing-indicator">' + user + ' is typing...</span>';
}
});
socket.on('stop-typing', () => {
document.getElementById('status-text').textContent = 'Online';
});
socket.on('auth-error', (msg) => {
alert(msg);
// Reset UI to selection screen
document.getElementById('user-select').style.display = 'flex';
document.getElementById('chat-screen').style.display = 'none';
currentUser = null;
});
// Input handling
document.getElementById('message-input').addEventListener('keypress', (e) => {
if (e.key === 'Enter') {
sendMessage();
} else {
socket.emit('typing', currentUser);
}
});
// Stop typing after pause
let typingTimeout;
document.getElementById('message-input').addEventListener('input', () => {
clearTimeout(typingTimeout);
typingTimeout = setTimeout(() => {
socket.emit('stop-typing');
}, 1000);
});