1
0
Fork 0
mirror of synced 2024-09-17 01:38:40 +12:00
budibase/packages/client/src/store/routes.js

57 lines
1.4 KiB
JavaScript

import { writable } from "svelte/store"
import { push } from "svelte-spa-router"
import * as API from "../api"
const createRouteStore = () => {
const initialState = {
routes: [],
routeParams: {},
activeRoute: null,
routeSessionId: Math.random(),
}
const store = writable(initialState)
const fetchRoutes = async () => {
const routeConfig = await API.fetchRoutes()
let routes = []
Object.values(routeConfig.routes).forEach(route => {
Object.entries(route.subpaths).forEach(([path, config]) => {
routes.push({
path,
screenId: config.screenId,
})
})
})
// Sort route by paths so that the router matches correctly
routes.sort((a, b) => {
return a.path > b.path ? -1 : 1
})
store.update(state => {
state.routes = routes
state.routeSessionId = Math.random()
return state
})
}
const setRouteParams = routeParams => {
store.update(state => {
state.routeParams = routeParams
return state
})
}
const setActiveRoute = route => {
store.update(state => {
state.activeRoute = state.routes.find(x => x.path === route)
return state
})
}
const navigate = push
return {
subscribe: store.subscribe,
actions: { fetchRoutes, navigate, setRouteParams, setActiveRoute },
}
}
export const routeStore = createRouteStore()