traintrape-moi/client/utils/features/location/locationSlice.ts

64 lines
2.1 KiB
TypeScript
Raw Normal View History

import { createSlice, PayloadAction } from '@reduxjs/toolkit'
import { LocationObject } from 'expo-location'
import { Constants } from '@/constants/Constants'
export type PlayerLocation = {
id?: number
playerId: number
longitude: number
latitude: number
speed: number
accuracy: number
altitude: number
altitudeAccuracy: number
timestamp: string
}
interface LocationState {
2024-12-11 00:30:21 +00:00
lastOwnLocation: LocationObject | null
lastSentLocation: LocationObject | null
queuedLocations: LocationObject[]
lastPlayerLocations: PlayerLocation[]
}
const initialState: LocationState = {
2024-12-11 00:30:21 +00:00
lastOwnLocation: null,
lastSentLocation: null,
queuedLocations: [],
lastPlayerLocations: []
}
export const locationSlice = createSlice({
name: 'location',
initialState: initialState,
reducers: {
2024-12-11 00:30:21 +00:00
setLastLocation: (state, action: PayloadAction<LocationObject>) => {
const location: LocationObject = action.payload
state.lastOwnLocation = location
if (state.lastSentLocation === null || (location.timestamp - state.lastSentLocation.timestamp) >= Constants.MIN_DELAY_LOCATION_SENT * 1000) {
state.lastSentLocation = location
state.queuedLocations.push(location)
}
},
unqueueLocation: (state, action: PayloadAction<LocationObject>) => {
2024-12-12 23:32:52 +00:00
const sentLoc = action.payload
state.queuedLocations = state.queuedLocations
.filter(loc => new Date(loc.timestamp).getTime() !== sentLoc.timestamp
&& loc.coords.latitude !== sentLoc.coords.latitude
&& loc.coords.longitude !== sentLoc.coords.longitude)
},
setLastPlayerLocations: (state, action: PayloadAction<PlayerLocation[]>) => {
state.lastPlayerLocations = action.payload
},
setLastPlayerLocation: (state, action: PayloadAction<PlayerLocation>) => {
state.lastPlayerLocations = state.lastPlayerLocations.filter(playerLoc => playerLoc.playerId !== action.payload.playerId)
state.lastPlayerLocations.push(action.payload)
}
},
})
export const { setLastLocation, unqueueLocation, setLastPlayerLocation, setLastPlayerLocations } = locationSlice.actions
export default locationSlice.reducer