2022-01-25 20:22:43 +01:00
|
|
|
import { API } from "api"
|
2022-06-09 16:03:43 +02:00
|
|
|
import { get, writable, derived } from "svelte/store"
|
2021-06-30 21:35:02 +02:00
|
|
|
|
2021-11-26 14:25:02 +01:00
|
|
|
const initialState = {
|
|
|
|
appId: null,
|
|
|
|
isDevApp: false,
|
2022-02-24 15:14:55 +01:00
|
|
|
clientLoadTime: window.INIT_TIME ? Date.now() - window.INIT_TIME : null,
|
2023-06-16 13:30:08 +02:00
|
|
|
embedded: false,
|
2021-11-26 14:25:02 +01:00
|
|
|
}
|
|
|
|
|
2021-06-30 21:35:02 +02:00
|
|
|
const createAppStore = () => {
|
2021-11-26 14:25:02 +01:00
|
|
|
const store = writable(initialState)
|
2022-06-09 16:03:43 +02:00
|
|
|
const derivedStore = derived(store, $store => {
|
|
|
|
return {
|
|
|
|
...$store,
|
|
|
|
isDevApp: $store.appId?.startsWith("app_dev"),
|
|
|
|
}
|
|
|
|
})
|
2021-06-30 21:35:02 +02:00
|
|
|
|
|
|
|
// Fetches the app definition including screens, layouts and theme
|
|
|
|
const fetchAppDefinition = async () => {
|
2021-07-25 14:43:07 +02:00
|
|
|
const appId = get(store)?.appId
|
|
|
|
if (!appId) {
|
|
|
|
throw "Cannot fetch app definition without app ID set"
|
|
|
|
}
|
2022-01-20 10:40:53 +01:00
|
|
|
try {
|
|
|
|
const appDefinition = await API.fetchAppPackage(appId)
|
|
|
|
store.set({
|
2022-02-24 15:14:55 +01:00
|
|
|
...initialState,
|
2022-01-20 10:40:53 +01:00
|
|
|
...appDefinition,
|
|
|
|
appId: appDefinition?.application?.appId,
|
|
|
|
})
|
|
|
|
} catch (error) {
|
2022-02-24 15:03:29 +01:00
|
|
|
store.set(initialState)
|
2022-01-20 10:40:53 +01:00
|
|
|
}
|
2021-06-30 21:35:02 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
// Sets the initial app ID
|
2022-06-09 16:03:43 +02:00
|
|
|
const setAppId = id => {
|
2021-06-30 21:35:02 +02:00
|
|
|
store.update(state => {
|
2022-01-20 10:40:53 +01:00
|
|
|
if (state) {
|
|
|
|
state.appId = id
|
|
|
|
} else {
|
|
|
|
state = { appId: id }
|
|
|
|
}
|
2021-06-30 21:35:02 +02:00
|
|
|
return state
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2023-06-16 13:30:08 +02:00
|
|
|
const setAppEmbedded = embeddded => {
|
|
|
|
store.update(state => {
|
|
|
|
if (state) {
|
|
|
|
state.embedded = embeddded
|
|
|
|
} else {
|
|
|
|
state = { embeddded }
|
|
|
|
}
|
|
|
|
return state
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
2021-06-30 21:35:02 +02:00
|
|
|
return {
|
2022-06-09 16:03:43 +02:00
|
|
|
subscribe: derivedStore.subscribe,
|
2023-06-16 13:30:08 +02:00
|
|
|
actions: { setAppId, setAppEmbedded, fetchAppDefinition },
|
2021-06-30 21:35:02 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
export const appStore = createAppStore()
|