2020-12-15 21:48:38 +01:00
|
|
|
import { writable } from 'svelte/store'
|
|
|
|
|
|
|
|
import { STORAGE_KEYS } from '../services/storageListener'
|
2020-12-15 22:42:43 +01:00
|
|
|
import { migrateRecord, sortRecord } from '../utils'
|
2020-12-15 21:48:38 +01:00
|
|
|
|
|
|
|
const createEventStore = () => {
|
|
|
|
const state = 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
|
|
|
|
|
|
|
const { subscribe, set, update } = writable(state)
|
|
|
|
|
|
|
|
const setCalculation = ({ id, link, createdAt, startTime, title }) => {
|
|
|
|
update((prevState) => ([
|
|
|
|
...prevState,
|
|
|
|
{
|
|
|
|
id,
|
|
|
|
link,
|
|
|
|
createdAt: createdAt.toString(),
|
|
|
|
startTime: startTime.toString(),
|
|
|
|
title,
|
|
|
|
},
|
|
|
|
]))
|
|
|
|
}
|
|
|
|
|
2020-12-15 22:42:43 +01:00
|
|
|
const clearCalculation = (id) => {
|
|
|
|
const calculationIndex = state.findIndex((event) => event.id === id)
|
|
|
|
|
|
|
|
if (calculationIndex === -1) {
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-15 22:42:56 +01:00
|
|
|
const nextState = [ ...state ]
|
|
|
|
nextState.splice(calculationIndex, 1)
|
|
|
|
|
|
|
|
set(nextState)
|
2020-12-15 22:42:43 +01:00
|
|
|
}
|
|
|
|
|
2020-12-15 21:48:38 +01:00
|
|
|
const getState = () => state
|
|
|
|
|
|
|
|
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()
|