forked from snxraven/LinkUp-P2P-Chat
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:
parent
378aeb7469
commit
24ffe2a977
161
app.js
161
app.js
@ -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');
|
|
||||||
|
|
||||||
// if (savedUser) {
|
|
||||||
// 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');
|
const registerDiv = document.querySelector('#register');
|
||||||
if (registerDiv) {
|
if (registerDiv) {
|
||||||
registerDiv.classList.remove('hidden');
|
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));
|
|
||||||
|
|
||||||
// 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);
|
|
||||||
}
|
|
||||||
|
|
||||||
continueRegistration(regUsername);
|
continueRegistration(regUsername);
|
||||||
|
};
|
||||||
|
reader.readAsArrayBuffer(avatarFile);
|
||||||
|
} else {
|
||||||
|
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();
|
||||||
|
23
index.html
23
index.html
@ -18,6 +18,13 @@
|
|||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
<main>
|
<main>
|
||||||
|
<div id="sidebar">
|
||||||
|
<ul id="room-list">
|
||||||
|
<!-- Room list will be populated dynamically -->
|
||||||
|
</ul>
|
||||||
|
<button id="toggle-setup-btn">Create/Join Room</button>
|
||||||
|
</div>
|
||||||
|
<div id="content">
|
||||||
<div id="register" class="hidden">
|
<div id="register" class="hidden">
|
||||||
<form id="register-form">
|
<form id="register-form">
|
||||||
<input required id="reg-username" type="text" placeholder="Username" />
|
<input required id="reg-username" type="text" placeholder="Username" />
|
||||||
@ -30,14 +37,12 @@
|
|||||||
<div id="user-info">
|
<div id="user-info">
|
||||||
<!-- User info will be populated dynamically -->
|
<!-- User info will be populated dynamically -->
|
||||||
</div>
|
</div>
|
||||||
<button id="create-chat-room">Create</button>
|
<button id="create-chat-room">Create Room</button>
|
||||||
<div id="or">
|
<div id="or">- or -</div>
|
||||||
- or -
|
|
||||||
</div>
|
|
||||||
<div id="join-chat-room-container">
|
<div id="join-chat-room-container">
|
||||||
<label for="connection-topic">Topic:</label>
|
<label for="connection-topic">Topic:</label>
|
||||||
<input type="text" id="join-chat-room-topic" placeholder="connection topic">
|
<input type="text" id="join-chat-room-topic" placeholder="connection topic">
|
||||||
<button id="join-chat-room">Join</button> <!-- Changed id -->
|
<button id="join-chat-room">Join Room</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div id="chat" class="hidden">
|
<div id="chat" class="hidden">
|
||||||
@ -61,18 +66,18 @@
|
|||||||
<textarea id="message" rows="4"></textarea>
|
<textarea id="message" rows="4"></textarea>
|
||||||
<input type="submit" value="Send" />
|
<input type="submit" value="Send" />
|
||||||
</form>
|
</form>
|
||||||
|
<button id="remove-room-btn">Leave Room</button>
|
||||||
</div>
|
</div>
|
||||||
<div id="loading" class="hidden">Loading ...</div>
|
<div id="loading" class="hidden">Loading ...</div>
|
||||||
|
</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'));
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
71
style.css
71
style.css
@ -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;
|
||||||
|
Loading…
Reference in New Issue
Block a user