pleroma-fe/src/stores/shout.js

54 lines
1.5 KiB
JavaScript
Raw Normal View History

import { Socket } from 'phoenix'
2023-04-04 21:17:54 -06:00
import { defineStore } from 'pinia'
2026-09-01 18:02:38 +03:00
import { useInstanceCapabilitiesStore } from 'src/stores/instance_capabilities.js'
import { useUsersStore } from 'src/stores/users.js'
2023-04-04 21:17:54 -06:00
// Maybe rename it to PhoenixSocket if we ever utilize this socket more
2023-04-04 21:17:54 -06:00
export const useShoutStore = defineStore('shout', {
state: () => ({
messages: [],
channel: { state: '' },
2026-01-06 16:22:52 +02:00
joined: false,
socket: null,
2023-04-04 21:17:54 -06:00
}),
getters: {
2026-09-01 18:02:38 +03:00
token: () => useUsersStore().currentUser?.token,
},
2023-04-04 21:17:54 -06:00
actions: {
initializeSocket() {
if (this.token === null) return
if (!useInstanceCapabilitiesStore().shoutAvailable) return
2026-09-03 16:55:41 +03:00
if (this.socket !== null) return
this.socket = new Socket('/socket', { params: { token: this.token } })
this.socket.connect()
},
initializeShout() {
const channel = this.socket.channel('chat:public')
2023-04-04 21:17:54 -06:00
channel.joinPush.receive('ok', () => {
this.joined = true
})
channel.onClose(() => {
this.joined = false
})
channel.onError(() => {
this.joined = false
})
channel.on('new_msg', (msg) => {
this.messages.push(msg)
this.messages = this.messages.slice(-19, 20)
})
channel.on('messages', ({ messages }) => {
this.messages = messages.slice(-19, 20)
})
channel.join()
this.channel = channel
2026-01-06 16:22:52 +02:00
},
disconnectSocket() {
this.socket?.disconnect()
this.socket = null
2026-09-01 18:02:38 +03:00
},
2026-01-06 16:22:52 +02:00
},
2023-04-04 21:17:54 -06:00
})