add 1 on 1 chat

This commit is contained in:
Bartal Laearsson
2026-07-24 21:42:06 +01:00
parent fb91a40032
commit 998d1b1b50
4 changed files with 285 additions and 128 deletions
+53 -4
View File
@@ -13,13 +13,52 @@ body {
color: #e0e0e0;
}
#messages {
.header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 0.5rem 1rem;
background: #0f0f23;
border-bottom: 1px solid #333;
}
.user-setup {
display: flex;
gap: 0.5rem;
}
#username {
padding: 0.4rem;
background: #16213e;
border: 1px solid #333;
border-radius: 4px;
color: #e0e0e0;
}
#login-btn {
padding: 0.4rem 0.8rem;
background: #6d4aff;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
}
.online-users {
font-size: 0.9rem;
}
#online-list {
color: #4ade80;
}
#message-log {
flex: 1;
overflow-y: auto;
padding: 1rem;
}
.message {
#message-log p {
padding: 0.4rem 0.6rem;
margin-bottom: 0.3rem;
background: #16213e;
@@ -32,9 +71,10 @@ body {
padding: 1rem;
background: #0f0f23;
border-top: 1px solid #333;
gap: 0.5rem;
}
#message-input {
#recipient-select {
flex: 1;
padding: 0.5rem;
background: #16213e;
@@ -44,8 +84,17 @@ body {
font-family: monospace;
}
#message-input {
flex: 2;
padding: 0.5rem;
background: #16213e;
border: 1px solid #333;
border-radius: 4px;
color: #e0e0e0;
font-family: monospace;
}
#publish-form button {
margin-left: 0.5rem;
padding: 0.5rem 1rem;
background: #6d4aff;
color: white;
+13 -2
View File
@@ -7,10 +7,21 @@
<link rel="stylesheet" href="index.css">
</head>
<body>
<div class="header">
<div class="user-setup">
<input type="text" id="username" placeholder="Your username" value="">
<button id="login-btn">Join Chat</button>
</div>
<div class="online-users">
<strong>Online:</strong> <span id="online-list"></span>
</div>
</div>
<div id="message-log"></div>
<form id="publish-form">
<input type="text" id="message-input" placeholder="Type a message..." autocomplete="off" autofocus>
<form id="publish-form" style="display:none;">
<input type="text" id="recipient-select" placeholder="Recipient..." autocomplete="off">
<input type="text" id="message-input" placeholder="Type a message..." autocomplete="off" autofocus disabled>
<button type="submit">Send</button>
</form>
+97 -28
View File
@@ -1,22 +1,54 @@
(() => {
let ws = null
let expectingMessage = false
const currentUserEl = document.getElementById('username')
const loginBtn = document.getElementById('login-btn')
const messageLog = document.getElementById('message-log')
const publishForm = document.getElementById('publish-form')
const recipientSelect = document.getElementById('recipient-select')
const messageInput = document.getElementById('message-input')
const onlineList = document.getElementById('online-list')
function dial() {
const conn = new WebSocket(`ws://${location.host}/ws/subscribe`)
// Auto-fill username from URL parameter
const urlParams = new URLSearchParams(window.location.search)
const urlUser = urlParams.get('user')
if (urlUser) {
currentUserEl.value = urlUser
}
conn.addEventListener('close', ev => {
appendLog(`WebSocket Disconnected code: ${ev.code}, reason: ${ev.reason}`, true)
if (ev.code !== 1001) {
appendLog('Reconnecting in 1s', true)
setTimeout(dial, 1000)
}
})
// Login button handler
loginBtn.addEventListener('click', () => {
const username = currentUserEl.value.trim()
if (!username) {
appendLog('Please enter a username', true)
return
}
conn.addEventListener('open', ev => {
// Connect to WebSocket with username
connect(username)
// Show publish form, hide login
loginBtn.style.display = 'none'
currentUserEl.style.display = 'none'
publishForm.style.display = 'flex'
messageInput.disabled = false
messageInput.focus()
appendLog(`Joined as ${username}`)
})
function connect(username) {
const encodedUser = encodeURIComponent(username)
ws = new WebSocket(`ws://${location.host}/ws/subscribe?user=${encodedUser}`)
ws.addEventListener('open', () => {
console.info('WebSocket connected')
refreshUsers()
// Refresh users every 5 seconds
setInterval(refreshUsers, 5000)
})
conn.addEventListener('message', ev => {
ws.addEventListener('message', (ev) => {
if (typeof ev.data !== 'string') {
console.error('unexpected message type', typeof ev.data)
return
@@ -27,47 +59,84 @@
expectingMessage = false
}
})
ws.addEventListener('close', (ev) => {
appendLog(`Disconnected (code: ${ev.code})`, true)
if (ev.code !== 1001) {
appendLog('Reconnecting...', true)
setTimeout(() => connect(username), 2000)
}
})
ws.addEventListener('error', (err) => {
console.error('WebSocket error:', err)
})
}
dial()
function refreshUsers() {
fetch('/ws/users')
.then(r => r.json())
.then(users => {
onlineList.textContent = users.join(', ') || 'none'
const messageLog = document.getElementById('message-log')
const publishForm = document.getElementById('publish-form')
const messageInput = document.getElementById('message-input')
// Update recipient dropdown
recipientSelect.innerHTML = ''
if (users.length > 0) {
users.forEach(user => {
const opt = document.createElement('option')
opt.value = user
opt.textContent = user
recipientSelect.appendChild(opt)
})
}
})
.catch(err => {
console.error('Failed to refresh users:', err)
})
}
function appendLog(text, error) {
function appendLog(text, error = false) {
const p = document.createElement('p')
p.innerText = `${new Date().toLocaleTimeString()}: ${text}`
const time = new Date().toLocaleTimeString()
p.innerText = `[${time}] ${text}`
if (error) {
p.style.color = 'red'
p.style.fontStyle = 'bold'
p.style.color = '#ff6b6b'
}
messageLog.append(p)
return p
}
appendLog('Submit a message to get started!')
publishForm.onsubmit = async ev => {
// Submit message
publishForm.onsubmit = async (ev) => {
ev.preventDefault()
const msg = messageInput.value
if (msg === '') {
const recipient = recipientSelect.value.trim()
const msg = messageInput.value.trim()
if (!recipient || !msg) {
appendLog('Please select a recipient and enter a message', true)
return
}
messageInput.value = ''
messageInput.value = ''
expectingMessage = true
try {
const payload = JSON.stringify({ to: recipient, message: msg })
const resp = await fetch('/ws/publish', {
method: 'POST',
body: msg,
headers: { 'Content-Type': 'application/json' },
body: payload,
})
if (resp.status !== 202) {
throw new Error(`Unexpected HTTP Status ${resp.status} ${resp.statusText}`)
const text = await resp.text()
throw new Error(`Failed: ${text}`)
}
} catch (err) {
appendLog(`Publish failed: ${err.message}`, true)
appendLog(`Send failed: ${err.message}`, true)
}
}
appendLog('Enter your username to join the chat')
})()