2020-11-13 16:42:32 +01:00
|
|
|
import { writable } from "svelte/store"
|
|
|
|
import { push } from "svelte-spa-router"
|
2020-11-19 18:55:40 +01:00
|
|
|
import * as API from "../api"
|
2020-11-13 16:42:32 +01:00
|
|
|
|
2020-11-18 20:18:18 +01:00
|
|
|
const createRouteStore = () => {
|
2020-11-17 13:08:24 +01:00
|
|
|
const initialState = {
|
|
|
|
routes: [],
|
|
|
|
routeParams: {},
|
|
|
|
activeRoute: null,
|
2020-12-11 15:24:19 +01:00
|
|
|
routeSessionId: Math.random(),
|
2021-05-20 15:47:17 +02:00
|
|
|
routerLoaded: false,
|
2020-11-17 13:08:24 +01:00
|
|
|
}
|
2020-11-13 16:42:32 +01:00
|
|
|
const store = writable(initialState)
|
|
|
|
|
2020-11-19 18:55:40 +01:00
|
|
|
const fetchRoutes = async () => {
|
|
|
|
const routeConfig = await API.fetchRoutes()
|
2020-11-19 19:39:22 +01:00
|
|
|
let routes = []
|
2021-05-04 12:32:22 +02:00
|
|
|
Object.values(routeConfig.routes).forEach(route => {
|
2020-11-19 19:39:22 +01:00
|
|
|
Object.entries(route.subpaths).forEach(([path, config]) => {
|
|
|
|
routes.push({
|
|
|
|
path,
|
|
|
|
screenId: config.screenId,
|
|
|
|
})
|
|
|
|
})
|
2020-11-19 18:55:40 +01:00
|
|
|
})
|
2020-12-08 16:44:35 +01:00
|
|
|
|
|
|
|
// Sort route by paths so that the router matches correctly
|
|
|
|
routes.sort((a, b) => {
|
|
|
|
return a.path > b.path ? -1 : 1
|
|
|
|
})
|
|
|
|
|
2021-05-04 12:32:22 +02:00
|
|
|
store.update(state => {
|
2020-11-17 13:08:24 +01:00
|
|
|
state.routes = routes
|
2020-12-11 15:24:19 +01:00
|
|
|
state.routeSessionId = Math.random()
|
2020-11-17 13:08:24 +01:00
|
|
|
return state
|
|
|
|
})
|
|
|
|
}
|
2021-05-04 12:32:22 +02:00
|
|
|
const setRouteParams = routeParams => {
|
|
|
|
store.update(state => {
|
2020-11-17 13:08:24 +01:00
|
|
|
state.routeParams = routeParams
|
|
|
|
return state
|
|
|
|
})
|
|
|
|
}
|
2021-05-04 12:32:22 +02:00
|
|
|
const setActiveRoute = route => {
|
|
|
|
store.update(state => {
|
|
|
|
state.activeRoute = state.routes.find(x => x.path === route)
|
2020-11-17 13:08:24 +01:00
|
|
|
return state
|
|
|
|
})
|
2020-11-13 16:42:32 +01:00
|
|
|
}
|
|
|
|
const navigate = push
|
2021-05-20 15:47:17 +02:00
|
|
|
const setRouterLoaded = () => {
|
|
|
|
store.update(state => ({ ...state, routerLoaded: true }))
|
|
|
|
}
|
2020-11-13 16:42:32 +01:00
|
|
|
|
2020-11-17 13:08:24 +01:00
|
|
|
return {
|
|
|
|
subscribe: store.subscribe,
|
2021-05-20 15:47:17 +02:00
|
|
|
actions: {
|
|
|
|
fetchRoutes,
|
|
|
|
navigate,
|
|
|
|
setRouteParams,
|
|
|
|
setActiveRoute,
|
|
|
|
setRouterLoaded,
|
|
|
|
},
|
2020-11-17 13:08:24 +01:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2020-11-18 20:18:18 +01:00
|
|
|
export const routeStore = createRouteStore()
|