2020-12-15 21:48:38 +01:00
|
|
|
import { writable } from 'svelte/store'
|
|
|
|
|
2020-12-20 15:24:25 +01:00
|
|
|
import { STORAGE_KEYS } from '../constants'
|
2020-12-15 22:42:43 +01:00
|
|
|
import { migrateRecord, sortRecord } from '../utils'
|
2020-12-15 21:48:38 +01:00
|
|
|
|
|
|
|
const createEventStore = () => {
|
2020-12-15 22:56:39 +01:00
|
|
|
const storedState = JSON.parse(localStorage.getItem(STORAGE_KEYS.EVENTS) || '[]')
|
2020-12-15 22:06:45 +01:00
|
|
|
.map(migrateRecord)
|
|
|
|
.sort(sortRecord)
|
2020-12-15 21:48:38 +01:00
|
|
|
|
2020-12-15 22:56:39 +01:00
|
|
|
let state = { events: storedState }
|
|
|
|
|
|
|
|
const getState = () => state
|
|
|
|
|
2020-12-15 21:48:38 +01:00
|
|
|
const { subscribe, set, update } = writable(state)
|
|
|
|
|
|
|
|
const setCalculation = ({ id, link, createdAt, startTime, title }) => {
|
2020-12-15 22:56:39 +01:00
|
|
|
update((prevState) => {
|
|
|
|
const nextState = {
|
|
|
|
...prevState,
|
|
|
|
events: [
|
|
|
|
...prevState.events,
|
|
|
|
{
|
|
|
|
id,
|
|
|
|
link,
|
|
|
|
createdAt: createdAt.toString(),
|
|
|
|
startTime: startTime.toString(),
|
|
|
|
title,
|
|
|
|
},
|
|
|
|
]
|
|
|
|
}
|
|
|
|
|
|
|
|
state = nextState
|
|
|
|
return nextState
|
|
|
|
})
|
2020-12-15 21:48:38 +01:00
|
|
|
}
|
|
|
|
|
2020-12-15 22:42:43 +01:00
|
|
|
const clearCalculation = (id) => {
|
2020-12-15 22:56:39 +01:00
|
|
|
const calculationIndex = getState().events.findIndex((event) => event.id === id)
|
2020-12-15 22:42:43 +01:00
|
|
|
|
|
|
|
if (calculationIndex === -1) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-15 22:56:39 +01:00
|
|
|
const nextEvents = [ ...getState().events ]
|
|
|
|
nextEvents.splice(calculationIndex, 1)
|
|
|
|
|
|
|
|
const nextState = { ...getState(), events: nextEvents }
|
|
|
|
state = nextState
|
2020-12-15 22:42:56 +01:00
|
|
|
|
|
|
|
set(nextState)
|
2020-12-15 22:42:43 +01:00
|
|
|
}
|
|
|
|
|
2020-12-15 21:48:38 +01:00
|
|
|
return {
|
|
|
|
...state,
|
|
|
|
subscribe,
|
|
|
|
set,
|
|
|
|
update,
|
|
|
|
setCalculation,
|
2020-12-15 22:42:43 +01:00
|
|
|
clearCalculation,
|
2020-12-15 21:48:38 +01:00
|
|
|
getState,
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export default createEventStore()
|