import { createSlice , PayloadAction } from '@reduxjs/toolkit' ; import { Meditation } from '../data/meditations' ; export interface Activity { duration : number ; } export interface MeditationState { activity : { [ key ] : Activity ; } ; filepaths : string [ ] ; favourites : Meditation [ ] ; } const initialState = { activity : { } , filepaths : [ ] , favourites : [ ] , } ; const meditationSlice = createSlice ( { name : 'meditation' , initialState , reducers : { completed ( state , action ) { state . activity [ Date . now ( ) ] = { duration : action . payload , } ; } , manualEntry ( state , action ) { const { duration , timestamp } = action . payload ; if ( duration === 0 ) { delete state . activity [ timestamp ] ; return ; } state . activity [ timestamp ] = { duration , } ; } , addFilePath ( state , action ) { if ( ! state . filepaths ) { state . filepaths = [ ] ; } state . filepaths . push ( action . payload ) ; } , reset : ( ) => initialState , updateFavourite : ( state , action ) => { if ( ! state . favourites ) { state . favourites = [ ] ; } const meditation = action . payload ; const meditationIndex = state . favourites . findIndex ( ( item ) => item . id === meditation . id ) ; const meditationAlreadyFavourited = meditationIndex !== - 1 ; if ( meditationAlreadyFavourited ) { state . favourites . splice ( meditationIndex , 1 ) ; } else { state . favourites . push ( meditation ) ; } } , } , } ) ; export const { completed , manualEntry , reset , addFilePath , updateFavourite } = meditationSlice . actions ; export default meditationSlice . reducer ;