Refactoring composite interface part1
This commit is contained in:
27
src/lib/components/refactor/ComposerAlice.svelte
Normal file
27
src/lib/components/refactor/ComposerAlice.svelte
Normal file
@ -0,0 +1,27 @@
|
||||
<script>
|
||||
export let services;
|
||||
export let store;
|
||||
|
||||
export let machineService;
|
||||
|
||||
let childStore;
|
||||
|
||||
$: if (services.core) {
|
||||
childStore = services.core.subscribeComposer('@ComposerBob');
|
||||
}
|
||||
|
||||
$: {
|
||||
if ($childStore && $childStore.machine.state) {
|
||||
console.log('learn color machine: ' + JSON.stringify(machineService));
|
||||
machineService.send($childStore.machine.state);
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<div class="p-2 border-2 border-blue-500">
|
||||
I am the parent, this is my state: {$store.machine.state}
|
||||
<div
|
||||
class="p-2 border-2"
|
||||
style="background-color: {$store.machine.state}; border-radius: 50%; width: 50px; height: 50px;"
|
||||
/>
|
||||
</div>
|
18
src/lib/components/refactor/ComposerBob.svelte
Normal file
18
src/lib/components/refactor/ComposerBob.svelte
Normal file
@ -0,0 +1,18 @@
|
||||
<script>
|
||||
export let store;
|
||||
export let machineService;
|
||||
|
||||
const handleButton = () => {
|
||||
console.log('learn ready machine: ' + JSON.stringify(machineService));
|
||||
console.log('Sending TOGGLE event to the machine');
|
||||
machineService.send('TOGGLE');
|
||||
};
|
||||
</script>
|
||||
|
||||
<div class="border-2 border-yellow-500">
|
||||
i am the child and this is my state: {$store.machine.state}
|
||||
<button
|
||||
class="px-4 py-2 font-bold text-white bg-blue-500 rounded hover:bg-blue-700"
|
||||
on:click={handleButton}>Switch</button
|
||||
>
|
||||
</div>
|
252
src/lib/core/refactor/Composer.svelte
Normal file
252
src/lib/core/refactor/Composer.svelte
Normal 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>
|
4
src/lib/core/refactor/FallBack.svelte
Normal file
4
src/lib/core/refactor/FallBack.svelte
Normal file
@ -0,0 +1,4 @@
|
||||
<script>
|
||||
export let id;
|
||||
console.log(`FallBack component rendered with id ${id}`);
|
||||
</script>
|
16
src/lib/core/refactor/composerStores.ts
Normal file
16
src/lib/core/refactor/composerStores.ts
Normal file
@ -0,0 +1,16 @@
|
||||
import { writable } from 'svelte/store';
|
||||
|
||||
const composerStores = new Map();
|
||||
|
||||
// Create or retrieve a composer store
|
||||
export function createComposerStore(composerId: string, initialState = {}) {
|
||||
if (!composerStores.has(composerId)) {
|
||||
composerStores.set(composerId, writable(initialState));
|
||||
}
|
||||
return composerStores.get(composerId);
|
||||
}
|
||||
|
||||
// Get composer store or create a default empty one if not exists
|
||||
export function getComposerStore(composerId: string) {
|
||||
return composerStores.get(composerId) || createComposerStore(composerId);
|
||||
}
|
23
src/lib/core/refactor/coreServices.ts
Normal file
23
src/lib/core/refactor/coreServices.ts
Normal file
@ -0,0 +1,23 @@
|
||||
// coreServices.ts
|
||||
import { getComposerStore } from './composerStores';
|
||||
|
||||
export const coreServices = {
|
||||
updateComposer: (mappings: Record<string, string>) => {
|
||||
for (const [mappingString, value] of Object.entries(mappings)) {
|
||||
const [storeID, key] = mappingString.replace('@', '').split(':');
|
||||
const store = getComposerStore(storeID);
|
||||
store.update(storeData => {
|
||||
storeData[key] = value;
|
||||
return storeData;
|
||||
});
|
||||
}
|
||||
},
|
||||
subscribeComposer: (mappingString: string) => {
|
||||
const [storeID] = mappingString.replace('@', '').split(':');
|
||||
const store = getComposerStore(storeID);
|
||||
return store;
|
||||
},
|
||||
testAlert: () => {
|
||||
alert("core service alert")
|
||||
}
|
||||
};
|
Reference in New Issue
Block a user