Adding a sidebar that contains a room list that can switch chat views, a toggle button to access create/join settings

This commit is contained in:
Raven Scott 2024-06-08 01:21:25 -04:00
parent 378aeb7469
commit 24ffe2a977
3 changed files with 204 additions and 125 deletions

167
app.js
View File

@ -6,6 +6,7 @@ import Localdrive from 'localdrive';
import fs from 'fs'; import fs from 'fs';
import Hyperdrive from 'hyperdrive'; import Hyperdrive from 'hyperdrive';
import Corestore from 'corestore'; import Corestore from 'corestore';
const store = new Corestore('./storage'); const store = new Corestore('./storage');
const drive = new Hyperdrive(store); const drive = new Hyperdrive(store);
@ -16,6 +17,7 @@ let userName = 'Anonymous';
let userAvatar = ''; let userAvatar = '';
let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {}; let registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || {};
let peerCount = 0; let peerCount = 0;
let currentRoom = null;
async function initialize() { async function initialize() {
swarm = new Hyperswarm(); swarm = new Hyperswarm();
@ -28,8 +30,10 @@ async function initialize() {
const registerForm = document.querySelector('#register-form'); const registerForm = document.querySelector('#register-form');
const selectAvatarButton = document.querySelector('#select-avatar'); const selectAvatarButton = document.querySelector('#select-avatar');
const createChatRoomButton = document.querySelector('#create-chat-room'); const createChatRoomButton = document.querySelector('#create-chat-room');
const joinForm = document.querySelector('#join-form'); const joinChatRoomButton = document.querySelector('#join-chat-room');
const messageForm = document.querySelector('#message-form'); const messageForm = document.querySelector('#message-form');
const toggleSetupBtn = document.querySelector('#toggle-setup-btn');
const removeRoomBtn = document.querySelector('#remove-room-btn');
if (registerForm) { if (registerForm) {
registerForm.addEventListener('submit', registerUser); registerForm.addEventListener('submit', registerUser);
@ -42,35 +46,28 @@ async function initialize() {
if (createChatRoomButton) { if (createChatRoomButton) {
createChatRoomButton.addEventListener('click', createChatRoom); createChatRoomButton.addEventListener('click', createChatRoom);
} }
if (joinForm) { if (joinChatRoomButton) {
joinForm.addEventListener('submit', joinChatRoom); joinChatRoomButton.addEventListener('click', joinChatRoom);
} }
if (messageForm) { if (messageForm) {
messageForm.addEventListener('submit', sendMessage); messageForm.addEventListener('submit', sendMessage);
} }
if (toggleSetupBtn) {
toggleSetupBtn.addEventListener('click', toggleSetupView);
}
if (removeRoomBtn) {
removeRoomBtn.addEventListener('click', leaveRoom);
}
// const savedUser = localStorage.getItem('currentUser'); const registerDiv = document.querySelector('#register');
if (registerDiv) {
// if (savedUser) { registerDiv.classList.remove('hidden');
// const user = JSON.parse(savedUser); }
// userName = user.username;
// userAvatar = user.avatar || '';
// const setupDiv = document.querySelector('#setup');
// if (setupDiv) {
// setupDiv.classList.remove('hidden');
// }
// } else {
const registerDiv = document.querySelector('#register');
if (registerDiv) {
registerDiv.classList.remove('hidden');
}
// }
swarm.on('connection', async (connection, info) => { swarm.on('connection', async (connection, info) => {
peerCount++; peerCount++;
updatePeerCount(); updatePeerCount();
// Send the current user's icon to the new peer
const iconBuffer = await drive.get(`/icons/${userName}.png`); const iconBuffer = await drive.get(`/icons/${userName}.png`);
if (iconBuffer) { if (iconBuffer) {
const iconMessage = JSON.stringify({ const iconMessage = JSON.stringify({
@ -84,7 +81,6 @@ async function initialize() {
connection.on('data', async (data) => { connection.on('data', async (data) => {
const messageObj = JSON.parse(data.toString()); const messageObj = JSON.parse(data.toString());
if (messageObj.type === 'icon') { if (messageObj.type === 'icon') {
// Save icon to local directory
const username = messageObj.username; const username = messageObj.username;
const avatarBuffer = Buffer.from(messageObj.avatar, 'base64'); const avatarBuffer = Buffer.from(messageObj.avatar, 'base64');
await drive.put(`/icons/${username}.png`, avatarBuffer); await drive.put(`/icons/${username}.png`, avatarBuffer);
@ -105,67 +101,34 @@ async function initialize() {
}); });
swarm.on('close', () => { swarm.on('close', () => {
console.log('Swarm closed.'); console.log('Swarm closed');
}); });
} }
function updatePeerCount() { function registerUser(e) {
const peersCountElement = document.querySelector('#peers-count');
if (peersCountElement) {
peersCountElement.textContent = peerCount;
}
}
async function registerUser(e) {
e.preventDefault(); e.preventDefault();
const regUsername = document.querySelector('#reg-username').value;
const regUsernameInput = document.querySelector('#reg-username'); if (registeredUsers[regUsername]) {
if (!regUsernameInput) { alert('Username already taken. Please choose another.');
alert('Username input element not found.');
return; return;
} }
const regUsername = regUsernameInput.value.trim(); const avatarFile = document.querySelector('#avatar-file').files[0];
if (avatarFile) {
if (!regUsername) {
alert('Please enter a username.');
return;
}
const loadingDiv = document.querySelector('#loading');
loadingDiv.classList.remove('hidden');
const newUser = { username: regUsername, avatar: '' };
localStorage.setItem('currentUser', JSON.stringify(newUser));
const fileInput = document.querySelector('#avatar-file');
if (fileInput && fileInput.files.length > 0) {
const file = fileInput.files[0];
const reader = new FileReader(); const reader = new FileReader();
reader.onload = async () => { reader.onload = (event) => {
const fileBuffer = Buffer.from(reader.result); const buffer = new Uint8Array(event.target.result);
await drive.put(`/icons/${regUsername}.png`, fileBuffer); drive.put(`/icons/${regUsername}.png`, buffer);
userAvatar = `http://localhost:1337/icons/${regUsername}.png`; userAvatar = URL.createObjectURL(new Blob([buffer]));
// Save avatar URL to currentUser.avatar registeredUsers[regUsername] = userAvatar;
newUser.avatar = userAvatar; localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers));
localStorage.setItem('currentUser', JSON.stringify(newUser)); continueRegistration(regUsername);
// Broadcast the icon to all connected peers
const iconMessage = JSON.stringify({
type: 'icon',
username: regUsername,
avatar: fileBuffer.toString('base64'),
});
const peers = [...swarm.connections];
for (const peer of peers) {
peer.write(iconMessage);
}
}; };
reader.readAsArrayBuffer(file); reader.readAsArrayBuffer(avatarFile);
} else {
continueRegistration(regUsername);
} }
continueRegistration(regUsername);
} }
async function continueRegistration(regUsername) { async function continueRegistration(regUsername) {
@ -182,15 +145,14 @@ async function continueRegistration(regUsername) {
document.querySelector('#register').classList.add('hidden'); document.querySelector('#register').classList.add('hidden');
loadingDiv.classList.add('hidden'); loadingDiv.classList.add('hidden');
document.querySelector('#join-chat-room').addEventListener('click', joinChatRoom);
const randomTopic = crypto.randomBytes(32); const randomTopic = crypto.randomBytes(32);
document.querySelector('#chat-room-topic').innerText = b4a.toString(randomTopic, 'hex'); document.querySelector('#chat-room-topic').innerText = truncateHash(b4a.toString(randomTopic, 'hex'));
} }
async function createChatRoom() { async function createChatRoom() {
// Generate a new random topic (32 byte string)
const topicBuffer = crypto.randomBytes(32); const topicBuffer = crypto.randomBytes(32);
const topic = b4a.toString(topicBuffer, 'hex');
addRoomToList(topic);
joinSwarm(topicBuffer); joinSwarm(topicBuffer);
} }
@ -198,21 +160,51 @@ async function joinChatRoom(e) {
e.preventDefault(); e.preventDefault();
const topicStr = document.querySelector('#join-chat-room-topic').value; const topicStr = document.querySelector('#join-chat-room-topic').value;
const topicBuffer = b4a.from(topicStr, 'hex'); const topicBuffer = b4a.from(topicStr, 'hex');
addRoomToList(topicStr);
joinSwarm(topicBuffer); joinSwarm(topicBuffer);
} }
async function joinSwarm(topicBuffer) { async function joinSwarm(topicBuffer) {
if (currentRoom) {
currentRoom.destroy();
}
document.querySelector('#setup').classList.add('hidden'); document.querySelector('#setup').classList.add('hidden');
document.querySelector('#loading').classList.remove('hidden'); document.querySelector('#loading').classList.remove('hidden');
// Join the swarm with the topic. Setting both client/server to true means that this app can act as both.
const discovery = swarm.join(topicBuffer, { client: true, server: true }); const discovery = swarm.join(topicBuffer, { client: true, server: true });
await discovery.flushed(); await discovery.flushed();
const topic = b4a.toString(topicBuffer, 'hex'); const topic = b4a.toString(topicBuffer, 'hex');
document.querySelector('#chat-room-topic').innerText = topic; document.querySelector('#chat-room-topic').innerText = truncateHash(topic);
document.querySelector('#loading').classList.add('hidden'); document.querySelector('#loading').classList.add('hidden');
document.querySelector('#chat').classList.remove('hidden'); document.querySelector('#chat').classList.remove('hidden');
currentRoom = discovery;
clearMessages();
}
function addRoomToList(topic) {
const roomList = document.querySelector('#room-list');
const roomItem = document.createElement('li');
roomItem.textContent = truncateHash(topic);
roomItem.dataset.topic = topic;
roomItem.addEventListener('click', () => switchRoom(topic));
roomList.appendChild(roomItem);
}
function switchRoom(topic) {
const topicBuffer = b4a.from(topic, 'hex');
joinSwarm(topicBuffer);
}
function leaveRoom() {
if (currentRoom) {
currentRoom.destroy();
currentRoom = null;
}
document.querySelector('#chat').classList.add('hidden');
document.querySelector('#setup').classList.remove('hidden');
} }
function sendMessage(e) { function sendMessage(e) {
@ -222,7 +214,6 @@ function sendMessage(e) {
onMessageAdded(userName, message, userAvatar); onMessageAdded(userName, message, userAvatar);
// Send the message to all peers (that you are connected to)
const messageObj = JSON.stringify({ const messageObj = JSON.stringify({
type: 'message', type: 'message',
name: userName, name: userName,
@ -242,7 +233,6 @@ function scrollToBottom() {
container.scrollTop = container.scrollHeight; container.scrollTop = container.scrollHeight;
} }
function onMessageAdded(from, message, avatar) { function onMessageAdded(from, message, avatar) {
const $div = document.createElement('div'); const $div = document.createElement('div');
$div.classList.add('message'); $div.classList.add('message');
@ -261,7 +251,6 @@ function onMessageAdded(from, message, avatar) {
const $text = document.createElement('div'); const $text = document.createElement('div');
$text.classList.add('message-text'); $text.classList.add('message-text');
// Render Markdown content
const md = window.markdownit(); const md = window.markdownit();
const markdownContent = md.render(message); const markdownContent = md.render(message);
$text.innerHTML = markdownContent; $text.innerHTML = markdownContent;
@ -274,13 +263,27 @@ function onMessageAdded(from, message, avatar) {
scrollToBottom(); scrollToBottom();
} }
function truncateHash(hash) {
return `${hash.slice(0, 6)}...${hash.slice(-6)}`;
}
async function updateIcon(username, avatarBuffer) { async function updateIcon(username, avatarBuffer) {
// Update the icon in the local HTML if necessary
// This can be adjusted as per your needs
const userIcon = document.querySelector(`img[src*="${username}.png"]`); const userIcon = document.querySelector(`img[src*="${username}.png"]`);
if (userIcon) { if (userIcon) {
userIcon.src = URL.createObjectURL(new Blob([avatarBuffer])); userIcon.src = URL.createObjectURL(new Blob([avatarBuffer]));
} }
} }
function clearMessages() {
const messagesContainer = document.querySelector('#messages');
while (messagesContainer.firstChild) {
messagesContainer.removeChild(messagesContainer.firstChild);
}
}
function toggleSetupView() {
const setupDiv = document.querySelector('#setup');
setupDiv.classList.toggle('hidden');
}
initialize(); initialize();

View File

@ -18,64 +18,69 @@
</div> </div>
</header> </header>
<main> <main>
<div id="register" class="hidden"> <div id="sidebar">
<form id="register-form"> <ul id="room-list">
<input required id="reg-username" type="text" placeholder="Username" /> <!-- Room list will be populated dynamically -->
<input type="file" id="avatar-file" accept="image/*" style="display: none;" /> </ul>
<button type="button" id="select-avatar">Select Avatar</button> <button id="toggle-setup-btn">Create/Join Room</button>
<input type="submit" value="Register" />
</form>
</div> </div>
<div id="setup" class="hidden"> <div id="content">
<div id="user-info"> <div id="register" class="hidden">
<!-- User info will be populated dynamically --> <form id="register-form">
<input required id="reg-username" type="text" placeholder="Username" />
<input type="file" id="avatar-file" accept="image/*" style="display: none;" />
<button type="button" id="select-avatar">Select Avatar</button>
<input type="submit" value="Register" />
</form>
</div> </div>
<button id="create-chat-room">Create</button> <div id="setup" class="hidden">
<div id="or"> <div id="user-info">
- or - <!-- User info will be populated dynamically -->
</div>
<div id="join-chat-room-container">
<label for="connection-topic">Topic:</label>
<input type="text" id="join-chat-room-topic" placeholder="connection topic">
<button id="join-chat-room">Join</button> <!-- Changed id -->
</div>
</div>
<div id="chat" class="hidden">
<div id="header">
<div id="details">
<div>
Topic: <span id="chat-room-topic"></span>
</div>
<div>
Peers: <span id="peers-count">0</span>
</div>
</div> </div>
<div id="user-list"> <button id="create-chat-room">Create Room</button>
<!-- User list will be populated here --> <div id="or">- or -</div>
<div id="join-chat-room-container">
<label for="connection-topic">Topic:</label>
<input type="text" id="join-chat-room-topic" placeholder="connection topic">
<button id="join-chat-room">Join Room</button>
</div> </div>
</div> </div>
<div id="messages-container"> <div id="chat" class="hidden">
<div id="messages"></div> <div id="header">
<div id="details">
<div>
Topic: <span id="chat-room-topic"></span>
</div>
<div>
Peers: <span id="peers-count">0</span>
</div>
</div>
<div id="user-list">
<!-- User list will be populated here -->
</div>
</div>
<div id="messages-container">
<div id="messages"></div>
</div>
<form id="message-form">
<textarea id="message" rows="4"></textarea>
<input type="submit" value="Send" />
</form>
<button id="remove-room-btn">Leave Room</button>
</div> </div>
<form id="message-form"> <div id="loading" class="hidden">Loading ...</div>
<textarea id="message" rows="4"></textarea>
<input type="submit" value="Send" />
</form>
</div> </div>
<div id="loading" class="hidden">Loading ...</div>
</main> </main>
<script> <script>
// JavaScript to handle form submission on Enter key press and Shift + Enter for new line
document.addEventListener('DOMContentLoaded', function() { document.addEventListener('DOMContentLoaded', function() {
const messageInput = document.getElementById('message'); const messageInput = document.getElementById('message');
messageInput.addEventListener('keydown', function(event) { messageInput.addEventListener('keydown', function(event) {
if (event.key === 'Enter' && !event.shiftKey) { if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault(); // Prevent form submission event.preventDefault();
document.getElementById('message-form').dispatchEvent(new Event('submit')); // Trigger form submission event document.getElementById('message-form').dispatchEvent(new Event('submit'));
} }
}); });
}); });
</script> </script>
</body> </body>
</html> </html>

View File

@ -17,6 +17,77 @@ body {
overflow-y: auto; overflow-y: auto;
} }
/* body {
display: flex;
} */
#sidebar {
width: 200px;
background-color: #2f3136;
color: white;
height: 100vh;
padding: 10px;
box-sizing: border-box;
}
#room-list {
list-style: none;
padding: 0;
margin-bottom: 20px;
}
#room-list li {
padding: 10px;
cursor: pointer;
margin-bottom: 5px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
#room-list li:hover {
background-color: #40444b;
}
#content {
flex: 1;
padding: 10px;
}
#sidebar button {
width: 100%;
padding: 10px;
margin-bottom: 10px;
cursor: pointer;
background-color: #7289da;
border: none;
color: white;
font-size: 14px;
border-radius: 5px;
}
#sidebar button:hover {
background-color: #5b6eae;
}
#remove-room-btn {
margin-top: 10px;
padding: 10px;
background-color: #f04747;
border: none;
color: white;
cursor: pointer;
border-radius: 5px;
}
#remove-room-btn:hover {
background-color: #c03535;
}
.hidden {
display: none;
}
/* Header styles */ /* Header styles */
header { header {
display: flex; display: flex;