fix components #2

Open
tsr wants to merge 11 commits from tsr/ircz:components into master
7 changed files with 561 additions and 188 deletions

View File

@ -1,50 +1,86 @@
const users = {}
module.exports = io => {
io.on('connection', async socket => {
console.log(`A socket connection to the server has been made: ${socket.id}`)
socket.join('#projex', () => {
sendUsers()
sendNamespaces()
})
users[socket.id] = { socketId: socket.id, nick: socket.id }
// announce to all
socket.broadcast.emit('user connected', users[socket.id])
// send all users TODO remove
socket.emit(
'got users',
Object.keys(io.sockets.sockets).map(socketId => users[socketId])
)
socket.on('message', message => {
console.log('sending message to namespace', message.namespace, message)
io.to(message.namespace).emit('message', message)
if (!message) {
console.log('Weird. Received empty message.')
return
}
console.log('sending message to ', message.to, message)
io.to(message.to).emit('message', message)
})
socket.on('get users', () => {
console.log('get users')
sendUsers()
socket.on('join', room => {
console.log(`${socket.id} joins ${room}`)
socket.join(room, () => {
sendNamespace(room)
io.to(room).emit('user joined', { room, socketId: socket.id })
io.of(room).clients((error, clients) => {
if (error) throw error
socket.emit('got client list', clients)
})
})
})
socket.on('join', namespace => {
console.log('join:', namespace)
socket.join(namespace, () => {
sendNamespaces()
socket.on('get all clients', () => {
io.clients((e, c) => {
if (e) console.log(e)
console.log('all clients:', c)
})
})
socket.on('part', room => {
console.log('part', socket.id, room)
socket.leave(room, () => {
console.log(Object.keys(io.sockets.adapter.rooms))
if (io.sockets.adapter.rooms[room]) {
Object.keys(io.sockets.adapter.rooms[room]['sockets']).map(s => {
sendNamespace(room, s)
return s
})
} else {
console.log(`room ${room} disappeared`)
}
io.to(room).emit('user left', { room, socketId: socket.id })
})
})
socket.on('part', () => {
console.log('part')
socket.on('change nick', nick => {
console.log(`${users[socket.id]['nick']} changed nick to ${nick}`)
socket.broadcast.emit('changed nick', { socketId: socket.id, nick: nick })
users[socket.id]['nick'] = nick
})
socket.on('get namespaces', () => sendNamespaces())
const sendNamespaces = () => {
const namespaces = Object.keys(io.sockets.adapter.rooms).map(k => ({
namespace: k,
sockets: Object.keys(io.sockets.adapter.rooms[k]['sockets']),
}))
io.emit('got namespaces', namespaces)
const sendNamespace = (room, socketId) => {
if (io.sockets.adapter.rooms[room]) {
const namespace = {
namespace: room,
sockets: Object.keys(io.sockets.adapter.rooms[room]['sockets']),
}
if (socketId) {
socket.emit('got namespace', namespace)
} else {
io.emit('got namespace', namespace)
}
}
}
const sendUsers = () =>
socket.emit('got users', Object.keys(io.sockets.sockets))
socket.on('disconnect', async () => {
io.emit('user disconnected', { socketId: socket.id })
console.log(`${socket.id} has disconnected.`)
sendNamespaces()
sendUsers()
io.emit('user disconnected', socket.id)
// OPTIMIZE if there's an easy way to inform rooms the socket was part of
// they should be informed here
//socket.rooms.map(r => r.sockets.map(s => sendNamespace(r, s)))
})
})
}

View File

@ -1,18 +1,21 @@
import React from 'react'
import socket from './socket'
import { Topbar, Sidebar, Messages } from './components'
import { Navbar, Nav, Dropdown, Button } from 'react-bootstrap'
import uuid from 'uuid'
import moment from 'moment'
const initialState = {
loading: true,
messages: [],
message: '',
namespaces: [],
namespace: '/',
allNamespaces: [],
chats: [],
room: '/',
allUsers: [],
user: {},
allSockets: [],
allMessages: [],
buffers: [],
buffer: '/',
}
class App extends React.Component {
@ -20,9 +23,12 @@ class App extends React.Component {
super()
this.state = initialState
this.socket = socket
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
this.join = this.join.bind(this)
this.formatMessage = this.formatMessage.bind(this)
this.countUnreadMessages = this.countUnreadMessages.bind(this)
this.readMessages = this.readMessages.bind(this)
this.activateChat = this.activateChat.bind(this)
this.query = this.query.bind(this)
}
async fetchData() {
@ -31,23 +37,99 @@ class App extends React.Component {
componentDidMount() {
this.fetchData()
// EVENTS
this.socket.on('connect', () => {
console.log('connected!')
const user = { socketId: this.socket.id }
this.setState({ user })
console.log(`I am ${this.socket.id}`)
this.join('#projex')
this.socket.nick = this.socket.id
})
this.socket.on('user connected', payload => {
console.log('a new user connected!', payload)
this.socket.on('user connected', user => {
console.log(`${user.nick} connected.`)
const allUsers = this.state.allUsers.concat(user)
this.setState({ allUsers })
})
this.socket.on('user disconnected', payload => {
console.log('a user disconnected.', payload)
this.socket.on('user disconnected', socketId => {
// mark user as offline
const oldNick = this.state.allUsers.find(u => u.socketId === socketId)
.nick
console.log(`${oldNick} disconnected.`)
const allUsers = this.state.allUsers.map(u => {
// TODO find a better way to preserve existing chat windows
if (u.socketId === socketId) u.offline = true
return u
})
this.setState({ allUsers })
// inform sockets the user was chatting with
this.state.chats
.filter(c => c === socketId)
.map(c => {
this.addNotification(`${oldNick} disconnected`, this.socket.id, c)
return c
})
// inform channels the user was part of and update their socket list
const allNamespaces = this.state.allNamespaces.map(n => {
if (n.sockets.find(s => s === socketId)) {
n.sockets = n.sockets.filter(s => s === socketId)
this.addNotification(`${oldNick} disconnected`, n.namespace)
}
return n
})
this.setState({ allNamespaces })
})
this.socket.on('got namespaces', namespaces => {
console.log('got namespaces:', namespaces)
this.setState({ namespaces })
this.socket.on('user joined', data => {
const { room, socketId } = data
const user = this.state.allUsers.find(u => u.socketId === socketId)
console.log(`${user.nick} joined ${room}`)
this.addNotification(`${user.nick} joined ${room}`, room)
})
this.socket.on('user left', data => {
const { room, socketId } = data
const user = this.state.allUsers.find(u => u.socketId === socketId)
console.log(`${user.nick} left ${room}`)
this.addNotification(`${user.nick} left ${room}`, room)
})
this.socket.on('changed nick', user => {
console.log(`${user.socketId} is now known as ${user.nick}.`)
const allUsers = this.state.allUsers
const oldNick = allUsers.find(u => u.socketId === user.socketId).nick
// inform channels user is part of
this.state.chats.map(c => {
if (c === user.socketId) {
this.addNotification(
`${oldNick} is now known as ${user.nick}`,
this.socket.id,
c
)
}
this.state.allNamespaces.map(n => {
if (n.namespace === c && n.sockets.find(s => s === user.socketId)) {
this.addNotification(`${oldNick} is now known as ${user.nick}`, c)
}
return n
})
return c
})
// update nick
allUsers.map(u => {
if (u.socketId === user.socketId) u.nick = this.socket.nick
return u
})
this.setState({ allUsers })
})
this.socket.on('got namespace', namespace => {
console.log('got namespace:', namespace)
const allNamespaces = this.state.allNamespaces
.filter(n => n.namespace !== namespace.namespace)
.concat(namespace)
this.setState({ allNamespaces })
})
this.socket.on('got users', allUsers => {
@ -56,37 +138,82 @@ class App extends React.Component {
})
this.socket.on('message', msg => {
if (
msg.to === this.socket.id &&
!this.state.chats.find(c => c === msg.from)
) {
console.log(`${msg.from} wants to chat with me.`)
const chats = this.state.chats.concat(msg.from)
this.setState({ chats })
}
if (
(msg.to[0] === '#' && msg.to === this.state.buffer) ||
(msg.to[0] !== '#' && msg.from === this.state.buffer)
)
msg.read = true
const messages = this.state.messages.concat(msg)
this.setState({ messages })
})
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
// FUNCTIONS
parseCommand() {
const args = this.state.message.split(' ')
const cmd = args[0].slice(1)
console.log('command:', cmd)
if (cmd === 'join') this.join(args[1])
join(room) {
if (room[0] !== '#') return alert('Use a leading #, silly!')
if (this.state.chats.find(c => c === room)) return
console.log('joining', room)
const chats = this.state.chats.concat(room)
this.socket.emit('join', room, ack => console.log('ack', ack))
this.activateChat(room, chats)
}
query(user) {
if (this.state.chats.find(c => c === user.socketId)) {
this.activateChat(user.socketId)
return
}
this.setState({ message: '' })
console.log(`starting chat with ${user.nick}`)
const chats = this.state.chats.concat(user.socketId)
this.activateChat(user.socketId, chats)
}
handleSubmit(e) {
e.preventDefault()
if (this.state.message[0] === '/') return this.parseCommand()
const message = {
addNotification(text, to, from) {
if (!text || !to) {
console.log('[addNotification] Missing parameter(s)', text, to)
return
}
const messages = this.state.messages.concat(
this.formatMessage(
text,
from ? from : 'server',
'server',
to,
to === this.state.buffer ? true : false
)
)
this.setState({ messages })
}
formatMessage(text, from, nick, to, read) {
if (!text || !from || !to || !nick) {
console.log(
'[formatMessage] Dropping malformed message (requiring text, from, nick and to).',
text,
from,
nick,
to,
read
)
return
}
return {
id: uuid(),
date: moment().format('MMMM D YYYY, h:mm a'),
socketId: this.socket.id,
text: this.state.message,
namespace: this.state.namespace,
text: text,
from: from,
nick: nick,
to: to,
read: read,
}
this.sendMessage(message)
this.setState({ message: '' })
}
renderLoading() {
return <div>loading...</div>
@ -95,136 +222,58 @@ class App extends React.Component {
renderError() {
return <div>something went wrong.</div>
}
join(namespace) {
if (namespace.slice(0, 1) !== '#') return alert('Use a leading #, silly!')
console.log('joining', namespace)
this.socket.emit('join', namespace)
this.setState({ namespace })
countUnreadMessages(nsp) {
return this.state.messages.filter(
m =>
!m.read && (m.to === nsp || (m.to === this.socket.id && m.from === nsp))
).length
}
sendMessage(msg) {
this.socket.emit('message', msg)
readMessages(nsp) {
const messages = this.state.messages
messages.map(m => {
if (!m.read && (m.to === nsp || m.from === nsp)) {
m.read = true
}
return m
})
this.setState({ messages })
}
activateChat(buffer, chats) {
this.readMessages(buffer)
this.setState({ buffer })
if (chats) this.setState({ chats })
}
renderApp() {
const title =
this.state.namespace[0] === '#'
this.state.buffer[0] === '#'
? 'Channel'
: this.state.namespace[0] === '/'
? 'server messages'
: 'User'
: this.state.buffer === this.socket.id
? 'buffer'
: 'Chat with'
return (
<main role="main" className="d-flex h-100 flex-column">
{/*Navbar*/}
<Navbar bg="dark" variant="dark" expand="lg">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto mr-3">
<Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic">
Users
</Dropdown.Toggle>
<Dropdown.Menu className="bg-dark">
{this.state.allUsers.map(u => (
<Dropdown.Item key={u} className="bg-dark text-light">
{u}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
<Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic">
Channels
</Dropdown.Toggle>
<Dropdown.Menu className="bg-dark">
{this.state.namespaces.map(r => (
<Dropdown.Item
key={r.namespace}
className="bg-dark text-light"
onClick={() => this.join(r.namespace)}
>
{r.namespace}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
<Topbar
query={this.query}
join={this.join}
socket={this.socket}
{...this.state}
/>
<div className="d-flex h-100">
{/*Side Bar 2*/}
<div
className="d-flex flex-column col-sm-2 bg-dark text-light p-2"
id="sidebar2"
>
<h5 className=" border-bottom pb-2">User Channels</h5>
<Button
key="/"
className="btn btn-dark d-flex"
onClick={() => this.setState({ namespace: '/' })}
>
<div className="mr-auto">server</div>
{/*<div className="ml-auto">{this.state.allUsers.length}</div>*/}
</Button>
{this.state.namespaces
.filter(
r =>
r.namespace[0] === '#' &&
r.sockets.includes(this.state.user.socketId)
)
.map(r => (
<Button
key={r.namespace}
className="btn btn-dark d-flex"
onClick={() => this.setState({ namespace: r.namespace })}
>
<div className="mr-auto">{r.namespace}</div>
<div className="ml-auto">{r.sockets.length}</div>
</Button>
))}
</div>
{/*Main Section*/}
<div className="bg-secondary d-flex flex-column flex-grow-1 px-2 pb-4">
{/*Main Section Header*/}
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap pt-3 pb-2 mb-3 border-bottom">
<h4 className="mr-auto ml-3">
{title}: {this.state.namespace}
</h4>
</div>
{/*Main Section Content*/}
<div className="d-flex flex-column border border-secondary flex-grow-1">
<div className="bg-dark flex-grow-1 p-2 text-light">
{this.state.messages
.filter(m => m.namespace === this.state.namespace)
.map(m => (
<div className="d-flex justify-content-between" key={m.id}>
<div>{m.date}</div>
<div>{m.socketId}</div>
<div>{m.text}</div>
</div>
))}
</div>
<form onSubmit={this.handleSubmit}>
<input
className="bg-light p-2 w-100"
name="message"
value={this.state.message}
placeholder="Enter message"
onChange={this.handleChange}
/>
<Button
className="btn btn-dark"
type="submit"
onSubmit={this.handleSubmit}
>
submit
</Button>
</form>
</div>
</div>
<Sidebar
activateChat={this.activateChat}
countUnreadMessages={this.countUnreadMessages}
{...this.state}
/>
<Messages
title={title}
socket={this.socket}
activateChat={this.activateChat}
join={this.join}
formatMessage={this.formatMessage}
{...this.state}
/>
</div>
</main>
)

View File

@ -0,0 +1,107 @@
import React from 'react'
import { Button } from 'react-bootstrap'
class MessageEntryForm extends React.Component {
constructor() {
super()
this.state = { message: '' }
this.handleChange = this.handleChange.bind(this)
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(e) {
this.setState({ [e.target.name]: e.target.value })
}
handleSubmit(e) {
e.preventDefault()
this.submitMessage(this.state.message)
}
submitMessage(msg) {
if (msg[0] === '/') return this.parseCommand()
if (!msg.length > 0) return
this.sendMessage(
this.props.formatMessage(
msg,
this.props.socket.id,
this.props.socket.nick,
this.props.buffer
)
)
this.setState({ message: '' })
}
sendMessage(msg) {
if (!msg) {
console.log('[sendMessage] Got no message. Fix your code!')
return
}
this.props.socket.emit('message', msg)
if (msg.to[0] !== '#') {
if (msg.to === this.props.buffer) msg.read = true
const messages = this.props.messages.concat(msg)
this.setState({ messages })
}
}
parseCommand() {
const args = this.state.message.split(' ')
const cmd = args[0].slice(1)
if (cmd === 'join') {
if (!args[1]) {
alert('did you forget a channel to join?')
return
}
this.props.join(args[1])
} else if (cmd === 'part' || cmd === 'leave') {
this.part(args[1] ? args[1] : this.props.buffer)
} else if (cmd === 'nick') {
if (!args[1]) {
alert('A new nick could be useful.')
return
}
this.nick(args[1])
} else {
alert(`unknown command: ${cmd}`)
}
this.setState({ message: '' })
}
part(room) {
console.log(`leaving ${room}`)
this.props.socket.emit('part', room)
const chats = this.props.chats.filter(c => c !== room)
this.props.activateChat('/', chats)
}
nick(nick) {
if (nick[0] === '#') {
alert('nick cannot start with #, sorry!')
return
}
console.log(`Changing nick to ${nick}`)
this.props.socket.nick = nick
this.props.socket.emit('change nick', nick)
}
render() {
return this.props.socket.id ? (
<form onSubmit={this.handleSubmit}>
<input
className="bg-light p-2 w-100"
name="message"
value={this.state.message}
placeholder="Enter message"
onChange={this.handleChange}
/>
<Button
className="btn btn-dark"
type="submit"
onSubmit={this.handleSubmit}
>
submit as {this.props.socket.nick}
</Button>
</form>
) : (
<div>Disconnected</div>
)
}
}
export default MessageEntryForm

View File

@ -0,0 +1,62 @@
import React from 'react'
import MessageEntryForm from './MessageEntryForm'
const Messages = props => {
const {
title,
buffer,
chats,
messages,
socket,
activateChat,
join,
formatMessage,
submitMessage,
} = props
return (
<div className="bg-secondary d-flex flex-column flex-grow-1 px-2 pb-4">
{/*Main Section Header*/}
<div className="d-flex justify-content-between flex-wrap flex-md-nowrap pt-3 pb-2 mb-3 border-bottom">
<h4 className="mr-auto ml-3">
{title} {buffer}
</h4>
</div>
{/*Main Section Content*/}
<div className="d-flex flex-column border border-secondary flex-grow-1">
<div className="bg-dark flex-grow-1 p-2 text-light">
{messages
.filter(
m =>
(m.to[0] === '#' && m.to === buffer) ||
(m.to[0] !== '#' && m.from === buffer) ||
(m.from === socket.socketId && m.to === buffer)
)
.map(m => {
console.log(m)
const rowColor = m.nick === 'server' ? 'text-secondary' : ''
return (
<div className={`d-flex ${rowColor}`} key={m.id}>
<div className="pr-3 text-nowrap">{m.date}</div>
{m.nick === 'server' ? null : (
<div className="pr-3 text-nowrap">{m.nick}:</div>
)}
<div className="pr-3 flex-grow-1">{m.text}</div>
</div>
)
})}
</div>
<MessageEntryForm
activateChat={activateChat}
formatMessage={formatMessage}
submitMessage={submitMessage}
join={join}
buffer={buffer}
chats={chats}
messages={messages}
socket={socket}
/>
</div>
</div>
)
}
export default Messages

60
src/components/Sidebar.js Normal file
View File

@ -0,0 +1,60 @@
import React from 'react'
import { Button } from 'react-bootstrap'
const Sidebar = props => {
const {
activateChat,
chats,
allUsers,
countUnreadMessages,
allNamespaces,
} = props
return (
<div
className="d-flex flex-column col-sm-2 bg-dark text-light p-2"
id="sidebar2"
>
<h5 className=" border-bottom pb-2">Chats</h5>
<Button
key="/"
className="btn btn-dark d-flex"
onClick={() => activateChat('/')}
>
<div className="mr-auto">server</div>
{/*<div className="ml-auto">{allUsers.length}</div>*/}
</Button>
{chats.map(c => (
<Button
key={c}
className="btn btn-dark d-flex"
onClick={() => activateChat(c)}
>
<div
className={`mr-auto ${
countUnreadMessages(c) > 0 ? 'text-danger' : ''
}`}
>
{c[0] === '#' || !allUsers.find(u => u.socketId === c)
? c
: allUsers.find(u => u.socketId === c)['nick']}
</div>
{countUnreadMessages(c) > 0 ? (
<div className="mr-auto badge bg-danger">
{countUnreadMessages(c)}
</div>
) : null}
{/* user count for channels */}
{c[0] === '#' &&
allNamespaces &&
allNamespaces.find(n => n.namespace === c) ? (
<div className="ml-auto">
{allNamespaces.find(n => n.namespace === c).sockets.length}
</div>
) : null}
</Button>
))}
</div>
)
}
export default Sidebar

56
src/components/Topbar.js Normal file
View File

@ -0,0 +1,56 @@
import React from 'react'
import { Navbar, Nav, Dropdown } from 'react-bootstrap'
const Topbar = props => {
const { allUsers, socket, allNamespaces, query, join } = props
return (
<Navbar bg="dark" variant="dark" expand="lg">
<Navbar.Toggle aria-controls="basic-navbar-nav" />
<Navbar.Collapse id="basic-navbar-nav">
<Nav className="ml-auto mr-3">
<Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic">
Users
</Dropdown.Toggle>
<Dropdown.Menu className="bg-dark">
{allUsers
.filter(u => u.socketId !== socket.id && u.offline !== true)
.map(u => (
<Dropdown.Item
key={u.socketId}
className="bg-dark text-light"
onClick={() => query(u)}
>
{u.nick}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
<Dropdown>
<Dropdown.Toggle variant="dark" id="dropdown-basic">
Channels
</Dropdown.Toggle>
<Dropdown.Menu className="bg-dark">
{allNamespaces
.filter(n => n.namespace[0] === '#')
.map(r => (
<Dropdown.Item
key={r.namespace}
className="bg-dark text-light"
onClick={() => join(r.namespace)}
>
{r.namespace}
</Dropdown.Item>
))}
</Dropdown.Menu>
</Dropdown>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
export default Topbar

3
src/components/index.js Normal file
View File

@ -0,0 +1,3 @@
export { default as Messages } from './Messages'
export { default as Sidebar } from './Sidebar'
export { default as Topbar } from './Topbar'