form provider

This commit is contained in:
Jan Prochazka
2021-03-04 10:56:58 +01:00
parent 593e61abb9
commit 7acea0f4ac
7 changed files with 98 additions and 11 deletions

View File

@@ -0,0 +1,12 @@
<script lang="ts">
import { writable } from 'svelte/store';
import FormProviderCore from './FormProviderCore.svelte';
export let initivalValues = {};
const values = writable(initivalValues);
</script>
<FormProviderCore {values}>
<slot />
</FormProviderCore>

View File

@@ -0,0 +1,32 @@
<script lang="ts" context="module">
import { getContext, setContext } from 'svelte';
const contextKey = 'formProviderContextKey';
export function getFormContext(): any {
return getContext(contextKey);
}
</script>
<script lang="ts">
import keycodes from '../utility/keycodes';
export let values;
const context = {
values,
submitActionRef: { current: null },
};
setContext(contextKey, context);
function handleEnter(e) {
if (e.keyCode == keycodes.enter && context.submitActionRef.current) {
e.preventDefault();
context.submitActionRef.current(values);
}
}
</script>
<slot />
<svelte:window on:keydown={handleEnter} />

View File

@@ -1,5 +1,15 @@
<script>
<script lang="ts">
import FormStyledButton from '../widgets/FormStyledButton.svelte';
import { getFormContext } from './FormProviderCore.svelte';
import { createEventDispatcher } from 'svelte';
const dispatch = createEventDispatcher();
const { submitActionRef } = getFormContext();
submitActionRef.current = () => {
dispatch('click');
};
</script>
<FormStyledButton type="submit" on:click {...$$props} />