budibase/packages/client/src/createApp.js

92 lines
2.5 KiB
JavaScript
Raw Normal View History

import { attachChildren } from "./render/attachChildren"
import { createTreeNode } from "./render/prepareRenderComponent"
import { screenRouter } from "./render/screenRouter"
import { createStateManager } from "./state/stateManager"
2020-07-03 00:22:20 +02:00
import { parseAppIdFromCookie } from "./render/getAppId"
2020-05-29 15:06:10 +02:00
export const createApp = ({
componentLibraries,
frontendDefinition,
2020-06-01 11:41:28 +02:00
window,
2020-05-29 15:06:10 +02:00
}) => {
let routeTo
let currentUrl
let screenStateManager
2019-10-07 07:03:41 +02:00
const onScreenSlotRendered = screenSlotNode => {
2020-05-30 01:14:41 +02:00
const onScreenSelected = (screen, url) => {
const stateManager = createStateManager({
componentLibraries,
onScreenSlotRendered: () => {},
routeTo,
})
2020-05-30 01:14:41 +02:00
const getAttachChildrenParams = attachChildrenParams(stateManager)
screenSlotNode.props._children = [screen.props]
2020-05-30 01:14:41 +02:00
const initialiseChildParams = getAttachChildrenParams(screenSlotNode)
attachChildren(initialiseChildParams)(screenSlotNode.rootElement, {
hydrate: true,
force: true,
})
if (screenStateManager) screenStateManager.destroy()
screenStateManager = stateManager
currentUrl = url
}
2020-05-30 01:14:41 +02:00
routeTo = screenRouter({
screens: frontendDefinition.screens,
onScreenSelected,
2020-06-14 21:30:23 +02:00
window,
2020-05-30 01:14:41 +02:00
})
2020-06-14 21:30:23 +02:00
const fallbackPath = window.location.pathname.replace(
2020-07-03 00:22:20 +02:00
parseAppIdFromCookie(window.document.cookie),
2020-06-14 21:30:23 +02:00
""
)
routeTo(currentUrl || fallbackPath)
}
2020-05-30 01:14:41 +02:00
const attachChildrenParams = stateManager => {
const getInitialiseParams = treeNode => ({
componentLibraries,
treeNode,
onScreenSlotRendered,
setupState: stateManager.setup,
})
return getInitialiseParams
}
let rootTreeNode
const pageStateManager = createStateManager({
componentLibraries,
onScreenSlotRendered,
// seems weird, but the routeTo variable may not be available at this point
routeTo: url => routeTo(url),
})
const initialisePage = (page, target, urlPath) => {
currentUrl = urlPath
rootTreeNode = createTreeNode()
rootTreeNode.props = {
_children: [page.props],
}
2020-05-30 01:14:41 +02:00
const getInitialiseParams = attachChildrenParams(pageStateManager)
const initChildParams = getInitialiseParams(rootTreeNode)
attachChildren(initChildParams)(target, {
hydrate: true,
force: true,
})
return rootTreeNode
}
2020-04-06 18:06:04 +02:00
return {
initialisePage,
screenStore: () => screenStateManager.store,
pageStore: () => pageStateManager.store,
routeTo: () => routeTo,
rootNode: () => rootTreeNode,
}
}