|
| 1 | +<script> |
| 2 | +import { onMount } from 'svelte' |
| 3 | +import generateRandomID from '../../../random' |
| 4 | +
|
| 5 | +export let id = generateRandomID('form-') |
| 6 | +export let saveToLocalStorage = false |
| 7 | +
|
| 8 | +let form = {} |
| 9 | +
|
| 10 | +onMount(() => { |
| 11 | + saveToLocalStorage && listenForBlurOnForm(form) |
| 12 | +}) |
| 13 | +
|
| 14 | +$: saveToLocalStorage && restoreFormValues(form) |
| 15 | +
|
| 16 | +const getValuesFromForm = (form) => Object.fromEntries(new FormData(form)) |
| 17 | +
|
| 18 | +const storeFormValues = (formId, valuesFromForm) => { |
| 19 | + sessionStorage.setItem(formId, JSON.stringify(valuesFromForm)) |
| 20 | +} |
| 21 | +
|
| 22 | +const setValuesOnForm = (form, valuesForForm) => { |
| 23 | + Object.entries(valuesForForm).forEach((keyValuePair) => { |
| 24 | + const [key, value] = keyValuePair |
| 25 | + form[key].value = value |
| 26 | + }) |
| 27 | +} |
| 28 | +
|
| 29 | +const restoreFormValues = (form) => { |
| 30 | + const sessionStorageKey = form.id |
| 31 | + const formValuesJson = sessionStorage.getItem(sessionStorageKey) |
| 32 | + if (formValuesJson) { |
| 33 | + const valuesForForm = JSON.parse(formValuesJson) |
| 34 | + if (valuesForForm) { |
| 35 | + setValuesOnForm(form, valuesForForm) |
| 36 | + sessionStorage.removeItem(sessionStorageKey) |
| 37 | + } |
| 38 | + } |
| 39 | +} |
| 40 | +
|
| 41 | +const onBlur = (value) => { |
| 42 | + if (value) { |
| 43 | + storeFormValues(form.id, getValuesFromForm(form)) |
| 44 | + } |
| 45 | +} |
| 46 | +
|
| 47 | +const listenForBlurOnForm = (form) => { |
| 48 | + const inputs = form.querySelectorAll('input, textarea') |
| 49 | + inputs.forEach((input) => { |
| 50 | + input.addEventListener('blur', function () { |
| 51 | + onBlur(this.value) |
| 52 | + }) |
| 53 | + }) |
| 54 | +} |
| 55 | +</script> |
| 56 | + |
1 | 57 | <style>
|
2 | 58 | :global(form > *) {
|
3 | 59 | margin-top: 2rem;
|
4 | 60 | }
|
5 | 61 | </style>
|
6 | 62 |
|
7 |
| -<form class="w-100 {$$props.class}" on:submit|preventDefault autocomplete="off"> |
| 63 | +<form bind:this={form} {id} class="w-100 {$$props.class}" on:submit|preventDefault autocomplete="off"> |
8 | 64 | <slot />
|
9 | 65 | </form>
|
0 commit comments