Refactoring composite interface part1

This commit is contained in:
Samuel Andert
2023-08-03 14:03:02 +02:00
parent 37b915cef6
commit dcb94e7c58
8 changed files with 399 additions and 180 deletions

View File

@ -0,0 +1,252 @@
<script lang="ts">
import { onDestroy } from 'svelte';
import Composer from './Composer.svelte';
import FallBack from './FallBack.svelte';
import components from '$lib/core/componentLoader';
import services from '$lib/core/servicesLoader';
import { dataStore } from '$lib/core/dataLoader';
import { createComposerStore, getComposerStore } from './composerStores';
import { coreServices } from './coreServices';
import { Machine, interpret } from 'xstate';
interface IComposerLayout {
areas: string;
columns?: string;
rows?: string;
gap?: string;
tailwindClasses?: string;
}
interface IComposer {
layout?: IComposerLayout;
id: string;
slot?: string;
component?: string;
services?: string[];
map?: Record<string, string>;
store?: Record<string, any>;
children?: IComposer[];
servicesLoaded?: boolean;
machine?: any;
machineService?: any;
}
export let composer: IComposer;
let loadedServices: Record<string, any> = {
core: coreServices
};
let layoutStyle = '';
let machineService;
$: {
layoutStyle = computeLayoutStyle(composer?.layout);
initializeAndLoadServices(composer);
initializeComposerState(composer);
mapAndSubscribe(composer);
if (composer?.children) {
composer.children.forEach((child) => {
initializeComposerState(child);
initializeAndLoadServices(child);
mapAndSubscribe(child);
});
}
if (composer?.machine) {
const machine = Machine({ ...composer.machine, id: composer.id });
machineService = interpret(machine).onTransition((state) => {
getComposerStore(composer.id).update((storeValue) => ({
...storeValue,
machine: { state: state.value }
}));
});
machineService.start();
composer.machineService = machineService;
}
if (composer?.children) {
composer.children.forEach((child) => {
if (child.machine) {
const childMachine = Machine({ ...child.machine, id: child.id });
machineService = interpret(childMachine).onTransition((state) => {
getComposerStore(child.id).update((storeValue) => ({
...storeValue,
machine: { state: state.value }
}));
});
machineService.start();
child.machineService = machineService;
}
});
}
}
function computeLayoutStyle(layout?: IComposerLayout): string {
if (!layout) return '';
return `
grid-template-areas: ${layout.areas};
${layout.gap ? `gap: ${layout.gap};` : ''}
${layout.columns ? `grid-template-columns: ${layout.columns};` : ''}
${layout.rows ? `grid-template-rows: ${layout.rows};` : ''}
`;
}
function initializeAndLoadServices(component: IComposer) {
if (!component) return;
if (component.services) {
let servicePromises = component.services.map((serviceName) =>
loadedServices[serviceName]
? Promise.resolve(loadedServices[serviceName])
: loadService(serviceName)
);
Promise.all(servicePromises).then((loaded) => {
loaded.forEach((service, index) => {
loadedServices[component.services[index]] = service;
});
component.servicesLoaded = true;
});
} else {
component.servicesLoaded = true;
}
}
function initializeComposerState(child: IComposer) {
if (!child) return; // Add this line
if (child.id) {
child.store = createComposerStore(child.id, child.store || {});
}
if (child.children) {
child.children.forEach(initializeComposerState);
}
}
let unsubscribers = [];
function mapAndSubscribe(component: IComposer) {
if (!component) return;
if (component.map) {
const localStore = getComposerStore(component.id);
for (const [localKey, mapping] of Object.entries(component.map)) {
const isDataMapping = mapping.startsWith('@data:');
const isStoreMapping = mapping.startsWith('@');
if (isDataMapping) {
const externalKey = mapping.replace('@data:', '').trim();
const unsubscribe = dataStore.subscribe((store) => {
if (externalKey in store) {
if (store[externalKey] && typeof store[externalKey].subscribe === 'function') {
let innerUnsub = store[externalKey].subscribe((value) => {
localStore.update((storeValue) => ({ ...storeValue, [localKey]: value }));
});
unsubscribers.push(innerUnsub);
} else {
localStore.update((storeValue) => ({
...storeValue,
[localKey]: store[externalKey]
}));
}
}
});
unsubscribers.push(unsubscribe);
} else if (isStoreMapping) {
const [externalID, externalKey] = mapping
.replace('@', '')
.split(':')
.map((item) => item.trim());
const externalStore = getComposerStore(externalID);
if (externalStore) {
const unsubscribe = externalStore.subscribe((externalState) => {
if (externalState && externalKey in externalState) {
localStore.update((storeValue) => ({
...storeValue,
[localKey]: externalState[externalKey]
}));
}
});
unsubscribers.push(unsubscribe);
}
}
}
}
if (component.children) {
component.children.forEach(mapAndSubscribe);
}
}
onDestroy(() => {
unsubscribers.forEach((unsub) => unsub());
});
async function getComponent(componentName: string) {
if (components[componentName]) {
const module = await components[componentName]();
return module.default;
}
return FallBack;
}
async function loadService(serviceName: string) {
if (services[serviceName]) {
const module = await services[serviceName]();
return module.default || module;
}
return null;
}
async function loadComponentAndService(component: IComposer) {
const componentName = component.component || 'FallBack';
return await getComponent(componentName);
}
</script>
<div
class={`grid w-full h-full overflow-hidden ${composer?.layout?.tailwindClasses || ''}`}
style={layoutStyle}
>
{#if composer?.servicesLoaded}
{#await loadComponentAndService(composer) then Component}
<svelte:component
this={Component}
id={composer.id}
store={getComposerStore(composer.id)}
machine={composer.machine}
services={loadedServices}
machineService={child.machineService}
/>
{/await}
{/if}
{#if composer?.children}
{#each composer.children as child (child.id)}
<div
class="grid w-full h-full overflow-hidden ${composer?.layout?.tailwindClasses || ''}"
style={`grid-area: ${child.slot}`}
>
{#if child.servicesLoaded}
{#await loadComponentAndService(child) then ChildComponent}
<svelte:component
this={ChildComponent}
id={child.id}
store={getComposerStore(child.id)}
machine={child.machine}
services={loadedServices}
machineService={child.machineService}
/>
{#if child.children && child.children.length}
<Composer composer={child} />
{/if}
{/await}
{/if}
</div>
{/each}
{/if}
</div>