client/src/stores/game.ts

82 lines
2.1 KiB
TypeScript

import { defineStore } from 'pinia'
import { io, Socket } from 'socket.io-client'
import type { Character, User } from '@/types'
import config from '@/config'
import { useCookies } from '@vueuse/integrations/useCookies'
export const useGameStore = defineStore('game', {
state: () => ({
token: '' as string | null,
connection: null as Socket | null,
user: null as User | null,
character: null as Character | null,
isGmPanelOpen: false,
isMovingCamera: false,
isChatOpen: false,
isUserPanelOpen: false
}),
actions: {
setToken(token: string) {
this.token = token
},
setUser(user: User | null) {
this.user = user
},
setCharacter(character: Character | null) {
this.character = character
},
toggleGmPanel() {
this.isGmPanelOpen = !this.isGmPanelOpen
},
toggleMovingCamera() {
this.isMovingCamera = !this.isMovingCamera
},
setMovingCamera(moving: boolean) {
this.isMovingCamera = moving
},
toggleChat() {
this.isChatOpen = !this.isChatOpen
},
toggleUserPanel() {
this.isUserPanelOpen = !this.isUserPanelOpen
},
initConnection() {
this.connection = io(config.server_endpoint, {
secure: !config.development,
withCredentials: true,
transports: ['websocket'],
reconnectionAttempts: 5
})
// Let the server know the user is logged in
this.connection.emit('login')
// set user
this.connection.on('logged_in', (user: User) => {
this.setUser(user)
})
// When we can't reconnect, disconnect
this.connection.on('reconnect_failed', () => {
this.disconnectSocket()
})
},
disconnectSocket() {
if (!this.connection) return
this.connection.disconnect()
this.connection = null
this.token = null
this.user = null
this.character = null
this.isGmPanelOpen = false
this.isMovingCamera = false
this.isChatOpen = false
this.isUserPanelOpen = false
useCookies().remove('token')
}
}
})