1
0
Fork 0
mirror of synced 2024-09-19 18:59:06 +12:00
budibase/packages/client/src/createApp.js

106 lines
2.5 KiB
JavaScript
Raw Normal View History

import {
split,
last
} from "lodash/fp";
import {writable} from "svelte/store";
import { $ } from "./core/common";
import {
setupBinding
} from "./state/stateBinding";
2019-09-23 17:08:06 +12:00
import { createCoreApi } from "./core";
import { getStateOrValue } from "./state/getState";
import { trimSlash } from "./common/trimSlash";
2019-09-23 17:08:06 +12:00
export const createApp = (componentLibraries, appDefinition, user) => {
2019-10-01 17:57:45 +13:00
const initialiseComponent = (parentContext) => (props, htmlElement, context) => {
const {componentName, libName} = splitName(props._component);
2019-09-22 16:02:33 +12:00
if(!componentName || !libName) return;
2019-10-03 18:12:13 +13:00
const {initialProps, bind} = setupBinding(store, props, coreApi, context, appDefinition.appRootPath);
2019-09-22 16:02:33 +12:00
const component = new (componentLibraries[libName][componentName])({
target: htmlElement,
2019-10-01 17:57:45 +13:00
props: {...initialProps, _bb:bbInContext(context || parentContext)},
2019-09-26 16:40:58 +12:00
hydrate:true
});
2019-09-22 16:02:33 +12:00
bind(component);
2019-10-01 17:57:45 +13:00
return component;
}
2019-09-23 17:08:06 +12:00
const coreApi = createCoreApi(appDefinition, user);
2019-09-26 16:40:58 +12:00
const store = writable({
_bbuser: user
});
let globalState = null;
store.subscribe(s => {
globalState = s;
});
const relativeUrl = (url) =>
appDefinition.appRootPath
? appDefinition.appRootPath + "/" + trimSlash(url)
: url;
const apiCall = (method) => (url, body) =>
fetch(relativeUrl(url), {
method: method,
headers: {
'Content-Type': 'application/json',
},
body: body && JSON.stringify(body),
});
const api = {
post: apiCall("POST"),
get: apiCall("GET"),
patch: apiCall("PATCH"),
delete:apiCall("DELETE")
};
2019-10-01 17:57:45 +13:00
const bb = () => ({
initialiseComponent: initialiseComponent(),
store,
relativeUrl,
api,
getStateOrValue: (prop, currentContext) =>
getStateOrValue(globalState, prop, currentContext)
2019-10-01 17:57:45 +13:00
});
const bbRoot = bb();
const bbInContext = (context) => {
if(!context) return bbRoot;
const bbCxt = bb();
bbCxt.context = context;
bbCxt.initialiseComponent=initialiseComponent(context);
return bbCxt;
}
2019-10-01 17:57:45 +13:00
return bbRoot;
}
const splitName = fullname => {
const componentName = $(fullname, [
split("/"),
last
]);
const libName =fullname.substring(
0, fullname.length - componentName.length - 1);
return {libName, componentName};
}