2017-12-05 21:47:10 +11:00
|
|
|
const chat = {
|
|
|
|
state: {
|
|
|
|
messages: [],
|
2019-03-11 05:23:27 +11:00
|
|
|
channel: {state: ''},
|
|
|
|
socket: null
|
2017-12-05 21:47:10 +11:00
|
|
|
},
|
|
|
|
mutations: {
|
|
|
|
setChannel (state, channel) {
|
|
|
|
state.channel = channel
|
|
|
|
},
|
2019-03-11 05:23:27 +11:00
|
|
|
setSocket (state, socket) {
|
|
|
|
state.socket = socket
|
|
|
|
},
|
2017-12-05 21:47:10 +11:00
|
|
|
addMessage (state, message) {
|
|
|
|
state.messages.push(message)
|
|
|
|
state.messages = state.messages.slice(-19, 20)
|
|
|
|
},
|
|
|
|
setMessages (state, messages) {
|
|
|
|
state.messages = messages.slice(-19, 20)
|
|
|
|
}
|
|
|
|
},
|
|
|
|
actions: {
|
2019-03-11 05:23:27 +11:00
|
|
|
disconnectFromChat (store) {
|
2019-06-20 13:12:25 +10:00
|
|
|
store.state.socket && store.state.socket.disconnect()
|
2019-03-11 05:23:27 +11:00
|
|
|
},
|
2017-12-05 21:47:10 +11:00
|
|
|
initializeChat (store, socket) {
|
|
|
|
const channel = socket.channel('chat:public')
|
2019-03-11 05:23:27 +11:00
|
|
|
store.commit('setSocket', socket)
|
2017-12-05 21:47:10 +11:00
|
|
|
channel.on('new_msg', (msg) => {
|
|
|
|
store.commit('addMessage', msg)
|
|
|
|
})
|
|
|
|
channel.on('messages', ({messages}) => {
|
|
|
|
store.commit('setMessages', messages)
|
|
|
|
})
|
|
|
|
channel.join()
|
|
|
|
store.commit('setChannel', channel)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default chat
|