budibase/packages/standard-components/src/Div.svelte

108 lines
2.6 KiB
Svelte
Raw Normal View History

2019-10-14 09:32:20 +02:00
<script>
export let children = [];
export let className="";
export let data=[];
export let dataItemComponent;
export let onLoad;
export let _bb;
let rootDiv;
let staticComponentsApplied=false;
let dataBoundComponents = [];
let previousData;
let onLoadCalled = false;
2019-10-19 08:24:20 +02:00
let staticHtmlElements = {};
2019-10-14 09:32:20 +02:00
const hasData = () =>
Array.isArray(data) && data.length > 0;
2019-10-19 08:24:20 +02:00
const staticElementsInitialised = () => {
if(!children) return false;
if(children.filter(c => c.className).length === Object.keys(staticHtmlElements).length)
return true;
}
const getStaticAnchor = (elementIndex) => {
const nextElements = Object.keys(staticHtmlElements).filter(k => k > elementIndex);
return nextElements.length === 0
? null
: staticHtmlElements[Math.min(...nextElements)];
}
2019-10-14 09:32:20 +02:00
$: {
2019-10-18 18:32:03 +02:00
if(rootDiv) {
2019-10-19 08:24:20 +02:00
if(children && children.length > 0
&& !staticComponentsApplied
&& staticElementsInitialised()) {
let index = 0;
for(let child of _bb.props.children) {
if(child.className) {
_bb.hydrateComponent(
child.component,
staticHtmlElements[index]);
} else {
const anchor = getStaticAnchor(index);
if(!anchor) {
_bb.appendComponent(
child.component,
rootDiv);
} else {
_bb.insertComponent(
child.component,
rootDiv,
anchor);
}
}
index += 1;
2019-10-18 18:32:03 +02:00
}
staticComponentsApplied = true;
2019-10-14 09:32:20 +02:00
}
2019-10-18 18:32:03 +02:00
2019-10-14 09:32:20 +02:00
2019-10-18 18:32:03 +02:00
if(previousData !== data) {
2019-10-14 09:32:20 +02:00
2019-10-18 18:32:03 +02:00
for(let c of dataBoundComponents) {
dataBoundComponents[c].$destroy();
}
dataBoundComponents = [];
2019-10-14 09:32:20 +02:00
2019-10-18 18:32:03 +02:00
if(hasData()) {
let index = 0;
for(let dataItem of data) {
_bb.appendComponent(
2019-10-19 08:24:20 +02:00
_bb.props.dataItemComponent,
2019-10-18 18:32:03 +02:00
rootDiv,
dataItem
);
}
2019-10-14 09:32:20 +02:00
}
}
2019-10-18 18:32:03 +02:00
if(!onLoadCalled && onLoad && !onLoad.isPlaceholder) {
_bb.call(onLoad);
onLoadCalled = true;
}
2019-10-14 09:32:20 +02:00
}
}
</script>
<div class="{className}" bind:this={rootDiv}>
2019-10-19 08:24:20 +02:00
{#each children as child, index}
{#if child.className}
<div class="{child.className}"
bind:this={staticHtmlElements[index]}>
</div>
{/if}
{/each}
2019-10-14 09:32:20 +02:00
</div>