small refactoring of oForm machine

This commit is contained in:
Samuel Andert 2023-08-01 17:59:17 +02:00
parent 1716cb41f7
commit 48903fbe7d
4 changed files with 64 additions and 3 deletions

View File

@ -0,0 +1,35 @@
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,7 +1,8 @@
// src/lib/components/Recipies/machines/authMachine.ts
import { createMachine } from 'xstate';
import { formMachine } from './formMachine';
export const authMachine = createMachine(
export const recipeMachine = createMachine(
{
id: 'auth',
initial: 'notAuthenticated',
@ -82,6 +83,14 @@ export const authMachine = createMachine(
},
logout: (context, event) => {
console.log('Logging out...');
},
setValidated: (context, event) => {
console.log('Form is validated');
// Add your logic here to update the visual representation
},
setNotValidated: (context, event) => {
console.log('Form is not validated');
// Add your logic here to update the visual representation
}
}
}

View File

@ -4,6 +4,8 @@
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;
@ -32,6 +34,14 @@
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 = !(
@ -41,6 +51,13 @@
$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() {

View File

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