Refactor next part, updated Form to the new Composer

This commit is contained in:
Samuel Andert 2023-08-07 09:05:51 +02:00
parent 28b55dee79
commit 25f214612e
16 changed files with 211 additions and 484 deletions

View File

@ -1,27 +0,0 @@
<script>
export let services;
export let store;
export let machineService;
let childStore;
$: if (services.core) {
childStore = services.core.subscribeComposite('@learnready');
}
$: {
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>
<div
class="p-2 border-2"
style="background-color: {$store.machine.state}; border-radius: 50%; width: 50px; height: 50px;"
/>

View File

@ -1,19 +0,0 @@
<script>
export let store;
export let services;
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>

View File

@ -1,35 +0,0 @@
import { createMachine } from 'xstate';
export const formMachine = createMachine(
{
id: 'validation',
initial: 'notValidated',
context: {
isValidated: false
},
states: {
notValidated: {
on: {
VALIDATE: {
target: 'isValidated',
actions: 'setValidated'
}
}
},
isValidated: {
on: {
INVALIDATE: {
target: 'notValidated',
actions: 'setNotValidated'
}
}
}
}
},
{
actions: {
setValidated: (context) => (context.isValidated = true),
setNotValidated: (context) => (context.isValidated = false)
}
}
);

View File

@ -1,185 +0,0 @@
<script lang="ts">
import { superForm } from 'sveltekit-superforms/client';
import { UserSchema } from '$lib/types/UserSchema';
import { afterUpdate } from 'svelte';
import { writable } from 'svelte/store';
import { RangeSlider, SlideToggle } from '@skeletonlabs/skeleton';
import { interpret } from 'xstate';
import { formMachine } from './machines/formMachine';
export let store;
export let services;
let isStoreLoaded = false;
$: if ($store) isStoreLoaded = true;
const initialFormData = {
name: '',
email: '',
about: '',
age: '',
favoriteFood: ''
};
const fields = ['name', 'email', 'about', 'age', 'favoriteFood'];
const { form, errors, validate, constraints } = superForm(initialFormData, {
validators: UserSchema,
warnings: {
noValidationAndConstraints: false
},
validationMethod: 'oninput', // Trigger validation on input events
clearOnSubmit: 'errors-and-message'
});
const successMessage = writable<string | null>(null);
// Create a service to interpret the machine
const validationService = interpret(formMachine).start();
// Subscribe to state changes
validationService.subscribe((state) => {
$store.isValidated = state.context.isValidated;
});
// Update the isValidated property of the store whenever the errors object changes
$: {
$store.isValidated = !(
$errors.name ||
$errors.email ||
$errors.about ||
$errors.age ||
$errors.favoriteFood
);
// Send events to the state machine based on the validation status
if ($store.isValidated) {
validationService.send('VALIDATE');
} else {
validationService.send('INVALIDATE');
}
}
async function handleSubmit() {
// Manually validate the form
const validationResult = await validate();
// Prevent submission if there are errors
if (!validationResult.valid) {
return;
}
// Here, we'll just log the form data
console.log(form);
// Set the success message after successful submission
successMessage.set('Form submitted successfully!');
}
function handleReset() {
// Reset the form and remove the message
form.set({});
successMessage.set(null);
}
// After update, scroll to the message container for better user experience
afterUpdate(() => {
const messageContainer = document.getElementById('message-container');
if (messageContainer) {
messageContainer.scrollIntoView({ behavior: 'smooth' });
}
});
</script>
{#if isStoreLoaded}
<div class="w-full">
{#if $successMessage}
<aside class="w-full max-w-md p-4 alert variant-ghost" id="message-container">
<div class="alert-message">
<h3 class="h3">Success</h3>
<p>{$successMessage}</p>
</div>
<div class="alert-actions">
<button
class="px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
on:click={handleReset}
>
Reset
</button>
</div>
</aside>
{:else}
<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
{#each fields as field}
<div class="mb-4">
{#if $errors[field]}
<span class="block mb-2 font-semibold text-red-500">{$errors[field]}</span>
{:else}
<label for={field} class="block mb-2 font-semibold text-white"
>{field.charAt(0).toUpperCase() + field.slice(1)}
</label>
{/if}
{#if field === 'about'}
<textarea
name={field}
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{:else if field === 'favoriteFood'}
<select
name={field}
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
>
<option value="">Select...</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="coconut">Coconut</option>
<option value="strawberry">Strawberry</option>
<option value="mango">Mango</option>
</select>
{:else if field === 'age'}
<input
name={field}
type="number"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{:else if field === 'slider'}
<RangeSlider name={field} bind:value={$form[field]} min={0} max={100} step={1} ticked>
<div class="flex items-center justify-between">
<div class="text-xs">{$form[field]} / 100</div>
</div>
</RangeSlider>
{:else if field === 'toggle'}
<SlideToggle name={field} bind:checked={$form[field]} />
{:else}
<input
name={field}
type="text"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{/if}
</div>
{/each}
<button
type="submit"
class="w-full px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={!$store.isValidated}
>
Submit
</button>
</form>
{/if}
</div>
{/if}

View File

@ -1,102 +0,0 @@
<!-- src/lib/components/Recipies/oRecipe.svelte -->
<script>
import Composite from '$lib/core/Composite.svelte';
let composite = {
id: 'testingstuff',
layout: {
columns: '1fr 1fr',
areas: `
"left right"
`
},
children: [
{
id: 'learnready',
component: 'LearnReady',
slot: 'left',
store: {
machine: { state: 'NOTREADY' }
},
machine: {
initial: 'NOTREADY',
states: {
NOTREADY: {
on: { TOGGLE: 'READY' }
},
READY: {
on: { TOGGLE: 'NOTREADY' }
}
}
}
},
{
id: 'learncolor',
component: 'LearnColor',
slot: 'right',
machine: {
initial: 'RED',
states: {
GREEN: {
on: { SWITCH: 'YELLOW' }
},
YELLOW: {
on: { SWITCH: 'RED' }
},
RED: {
on: { SWITCH: 'GREEN' }
}
},
on: {
READY: 'GREEN',
NOTREADY: 'RED'
}
}
}
]
};
// let current = machine.initialState.value;
// const service = interpret(machine)
// .onTransition((state) => {
// current = state.value;
// })
// .start();
// Derive possible actions from the current state
// $: possibleActions = machine.states[current]?.meta.buttons || [];
</script>
<div class="h-1/4">
<Composite {composite} />
</div>
<!--
<main class="grid w-full h-full grid-rows-layout">
<div class="w-full h-full p-4 overflow-scroll">
<p>Current state: {current}</p>
<h1>{machine.states[current].meta.title}</h1>
{#if machine.states[current].meta.composite}
<Composite composite={machine.states[current].meta.composite} />
{/if}
</div>
<div class="p-4">
{#each possibleActions as { type, label, disabled } (type)}
<button
class="px-4 py-2 text-white bg-blue-500 rounded"
on:click={() => service.send(type)}
{disabled}
>
{label}
</button>
{/each}
</div>
</main>
<style>
.grid-rows-layout {
grid-template-rows: 1fr auto;
}
</style> -->

View File

@ -39,7 +39,7 @@
context: {
name: '',
email: '',
constraints: {} // <- New addition
constraints: {}
},
states: {
start: {

View File

@ -25,6 +25,12 @@
{/each}
{/if}
</section>
<button
class="self-center px-4 py-2 font-bold text-white rounded hover:bg-blue-700"
on:click={sendMessage}
>
Send
</button>
<section class="flex-grow p-8 overflow-y-auto">
{#if $data.store.messages}
{#each $data.store.messages as message}
@ -32,10 +38,4 @@
{/each}
{/if}
</section>
<button
class="self-center px-4 py-2 mb-4 font-bold text-white rounded hover:bg-blue-700"
on:click={sendMessage}
>
Send
</button>
</div>

View File

@ -0,0 +1,163 @@
<script lang="ts">
import { superForm } from 'sveltekit-superforms/client';
import { UserSchema } from '$lib/types/UserSchema';
import { afterUpdate } from 'svelte';
import { writable } from 'svelte/store';
import { RangeSlider, SlideToggle } from '@skeletonlabs/skeleton';
export let data;
export let me;
const initialFormData = {
name: '',
email: '',
about: '',
age: '',
favoriteFood: ''
};
const fields = ['name', 'email', 'about', 'age', 'favoriteFood'];
const { form, errors, validate, constraints } = superForm(initialFormData, {
validators: UserSchema,
warnings: {
noValidationAndConstraints: false
},
validationMethod: 'oninput', // Trigger validation on input events
clearOnSubmit: 'errors-and-message'
});
const successMessage = writable<string | null>(null);
// Update the isValidated property of the store whenever the errors object changes
$: {
// Send events to the state machine based on the validation status
if (!($errors.name || $errors.email || $errors.about || $errors.age || $errors.favoriteFood)) {
me.do.machine.send('VALIDATE');
} else {
me.do.machine.send('INVALIDATE');
}
}
async function handleSubmit() {
// Manually validate the form
const validationResult = await validate();
// Prevent submission if there are errors
if (!validationResult.valid) {
return;
}
// Here, we'll just log the form data
console.log(form);
// Set the success message after successful submission
successMessage.set('Form submitted successfully!');
}
function handleReset() {
// Reset the form and remove the message
form.set({});
successMessage.set(null);
}
// After update, scroll to the message container for better user experience
afterUpdate(() => {
const messageContainer = document.getElementById('message-container');
if (messageContainer) {
messageContainer.scrollIntoView({ behavior: 'smooth' });
}
});
</script>
<div class="w-full p-6 border-2 border-red-500">
My state is: {$data.state}
{#if $successMessage}
<aside class="w-full max-w-md p-4 alert variant-ghost" id="message-container">
<div class="alert-message">
<h3 class="h3">Success</h3>
<p>{$successMessage}</p>
</div>
<div class="alert-actions">
<button
class="px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
on:click={handleReset}
>
Reset
</button>
</div>
</aside>
{:else}
<form on:submit|preventDefault={handleSubmit} class="w-full max-w-md">
{#each fields as field}
<div class="mb-4">
{#if $errors[field]}
<span class="block mb-2 font-semibold text-red-500">{$errors[field]}</span>
{:else}
<label for={field} class="block mb-2 font-semibold text-white"
>{field.charAt(0).toUpperCase() + field.slice(1)}
</label>
{/if}
{#if field === 'about'}
<textarea
name={field}
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{:else if field === 'favoriteFood'}
<select
name={field}
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
>
<option value="">Select...</option>
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="coconut">Coconut</option>
<option value="strawberry">Strawberry</option>
<option value="mango">Mango</option>
</select>
{:else if field === 'age'}
<input
name={field}
type="number"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{:else if field === 'slider'}
<RangeSlider name={field} bind:value={$form[field]} min={0} max={100} step={1} ticked>
<div class="flex items-center justify-between">
<div class="text-xs">{$form[field]} / 100</div>
</div>
</RangeSlider>
{:else if field === 'toggle'}
<SlideToggle name={field} bind:checked={$form[field]} />
{:else}
<input
name={field}
type="text"
class="w-full px-3 py-2 bg-transparent border-gray-100 rounded-md border-1 ring-0 ring-white focus:outline-none focus:ring-2 focus:ring-blue-500"
bind:value={$form[field]}
aria-invalid={$errors[field] ? 'true' : undefined}
{...constraints[field]}
/>
{/if}
</div>
{/each}
<button
type="submit"
class="w-full px-4 py-2 mt-4 text-white bg-blue-500 rounded-md hover:bg-blue-600 focus:outline-none focus:ring-2 focus:ring-blue-500"
disabled={$data.state === 'notValidated'}
>
Submit
</button>
</form>
{/if}
</div>

View File

@ -18,17 +18,17 @@
},
layout: {
columns: '1fr 1fr',
rows: '1fr 1fr',
rows: 'auto 1fr',
areas: `
"top aside"
"bottom aside"
"topleft topright"
"mainleft mainright"
`
},
children: [
{
id: 'ComposerCharly',
component: 'ComposerCharly',
slot: 'aside',
slot: 'mainright',
data: {
map: {
todos: queryTodos,
@ -58,7 +58,7 @@
{
id: 'ComposerBob',
component: 'ComposerBob',
slot: 'top',
slot: 'topleft',
machine: {
initial: 'READY',
states: {
@ -74,7 +74,7 @@
{
id: 'ComposerAlice',
component: 'ComposerAlice',
slot: 'bottom',
slot: 'topright',
machine: {
initial: 'RED',
states: {
@ -93,6 +93,40 @@
NOTREADY: 'RED'
}
}
},
{
id: 'ComposerForm',
component: 'ComposerForm',
slot: 'mainleft',
machine: {
id: 'validation',
initial: 'notValidated',
context: {
isValidated: false
},
states: {
notValidated: {
on: {
VALIDATE: {
target: 'isValidated',
actions: 'setValidated'
}
}
},
isValidated: {
on: {
INVALIDATE: {
target: 'notValidated',
actions: 'setNotValidated'
}
}
}
},
services: {
setValidated: (context) => (context.isValidated = true),
setNotValidated: (context) => (context.isValidated = false)
}
}
}
]
};

View File

@ -64,8 +64,6 @@
}
);
const machineService = interpret(machine).onTransition((state) => {
console.log(`${composer.id} State transitioned to: ${state.value}`);
console.log('Context:', state.context); // Log the context
getComposerStore(composer.id).update((storeValue) => ({
...storeValue,
state: state.value,

View File

@ -4,7 +4,6 @@ import { getComposerStore } from './composerStores';
export const coreServices = {
mutateStore: (storeID: string, value: any) => {
const store = getComposerStore(storeID);
console.log(`mutateData called with storeID: ${storeID} and value: ${JSON.stringify(value)}`);
store.update(storeData => {
storeData.store = { ...storeData.store, ...value };
return storeData;

View File

@ -1,6 +1,6 @@
// dataLoader.ts
import { writable } from 'svelte/store';
import dataSources from 'virtual:data-sources-list';
import { writable } from 'svelte/store';
import { coreServices } from './coreServices';
// The store that holds the data sets
@ -9,9 +9,7 @@ export const queryStore = writable({});
// Dynamically import the data modules and assign them to the store
dataSources.forEach(src => {
import(`/src/lib/data/${src}.ts`).then(module => {
// Here, explicitly extract the required data or function from the module
const moduleData = module[src] || module.default;
queryStore.update(store => ({ ...store, [src]: moduleData }));
});
});

View File

@ -1,6 +0,0 @@
<script lang="ts">
import { recipeMachine } from '$lib/components/Recipies/machines/recipeMachine';
import ORecipe from '$lib/components/Recipies/oRecipe.svelte';
</script>
<ORecipe machine={recipeMachine} />

View File

@ -1,39 +0,0 @@
<!-- src/routes/form/+page.svelte -->
<script lang="ts">
import Composite from '$lib/core/Composite.svelte';
let composite = {
id: 'testform',
store: {
isValidated: false
},
layout: {
areas: `
"checkvalidation form"
`,
columns: '1fr 3fr',
rows: 'auto'
},
children: [
{
id: 'checkvalidation',
component: 'CheckValidation',
slot: 'checkvalidation',
map: {
isValidated: '@testform:isValidated'
}
},
{
id: 'form',
component: 'Form',
slot: 'form',
map: {
isValidated: '@testform:isValidated'
},
services: ['validationRecipe', 'helloEarthAlert']
}
]
};
</script>
<Composite {composite} />

View File

@ -1,52 +0,0 @@
<script>
import Composite from '$lib/core/Composite.svelte';
let composite = {
id: 'hello',
store: {
title: 'Hello Earth',
description:
'how to use the store and mapping logic of store to store and data to store maps',
helloMapMe: 'this is going to be mapped'
},
layout: {
areas: `
"main aside"
"footer footer";
`,
columns: '1fr 1fr',
rows: '1fr auto'
},
children: [
{
id: 'earth',
component: 'HelloEarth',
slot: 'main',
store: {
hello: 'define me directly',
hello2: 'overwrite me with the mapping value'
},
map: {
title: '@hello:title',
description: '@hello:description',
hello2: '@hello:helloMapMe',
pkpWallet: '@wallet:pkpWallet',
todos: '@data:queryTodos'
},
services: ['helloEarthAlert']
},
{
id: 'form',
component: 'Form',
slot: 'aside'
},
{
id: 'terminal',
component: 'Terminal',
slot: 'footer'
}
]
};
</script>
<Composite {composite} />