Added auto import of services to the composite

This commit is contained in:
Samuel Andert
2023-07-25 11:20:51 +02:00
parent 70fe76279e
commit ab92110970
6 changed files with 101 additions and 13 deletions

View File

@ -1,6 +1,7 @@
<script lang="ts">
import Composite from './Composite.svelte';
import components from '$lib/componentLoader';
import services from '$lib/servicesLoader';
import { createComponentStore, getComponentStore } from '$lib/stores/componentStores.ts';
export let componentsData = {
@ -9,7 +10,6 @@
};
function initializeComponentState(child) {
// This will either retrieve the existing store or create a default one
child.store = createComponentStore(child.id, child.state || {});
if (child.children) {
@ -37,11 +37,10 @@
localStore.update((storeValue) => {
storeValue = storeValue || {};
if (storeValue[localKey] !== externalState[externalKey]) {
// Only update if there's a change
storeValue[localKey] = externalState[externalKey];
return storeValue;
}
return storeValue; // Return existing state if no change
return storeValue;
});
}
});
@ -65,14 +64,43 @@
}
return null;
}
async function loadService(serviceName) {
if (services[serviceName]) {
const module = await services[serviceName]();
return module.default || module;
}
return null;
}
async function getServiceProps(component) {
const loadedServices = [];
if (component.services) {
for (const serviceName of component.services) {
const loadedService = await loadService(serviceName);
if (loadedService) {
loadedServices.push(loadedService);
}
}
}
return loadedServices;
}
</script>
<div class="grid w-full h-full" style="display: grid; {componentsData.layout || ''}">
{#each componentsData.children as component (component.id)}
{#await getComponent(component.componentName) then Component}
{#await Promise.all( [getComponent(component.componentName), getServiceProps(component)] ) then [Component, loadedServices]}
{#if Component}
<div class="w-full h-full overflow-hidden {component.slot}">
<svelte:component this={Component} id={component.id} {...component.props} />
<svelte:component
this={Component}
id={component.id}
{...component.props}
{...loadedServices.reduce((acc, currFn, idx) => {
acc[component.services[idx]] = currFn;
return acc;
}, {})}
/>
{#if component.actions}
<div class="flex justify-end p-4">
@ -88,7 +116,6 @@
</div>
{/if}
<!-- Recursive rendering of children -->
{#if component.children && component.children.length}
<Composite componentsData={component} />
{/if}