diff --git a/src/lib/elements/forms/inputSelectSearch.svelte b/src/lib/elements/forms/inputSelectSearch.svelte index 6a55fd773..ecb69de83 100644 --- a/src/lib/elements/forms/inputSelectSearch.svelte +++ b/src/lib/elements/forms/inputSelectSearch.svelte @@ -3,6 +3,13 @@ import { onMount } from 'svelte'; import { Label } from '.'; + type Option = $$Generic<{ + value: string | boolean | number; + label: string; + }>; + type OptionArray = Option[]; + + export let options: OptionArray; export let id: string; export let label: string; export let name: string = 'elements'; @@ -12,18 +19,13 @@ export let required = false; export let disabled = false; export let autofocus = false; - export let debounce = 250; - export let options: { - value: string | boolean | number; - label: string; - }[]; // Input value - export let search: string = null; + export let search = ''; // The actual selected value export let value: string | number | boolean; + $: selectedOption = options.find((option) => option.value === value); let element: HTMLInputElement; - let timer: ReturnType; let hasFocus = false; let selected: number = null; @@ -37,13 +39,8 @@ } }); - function handleInput(event: Event) { + function handleInput() { hasFocus = true; - clearTimeout(timer); - timer = setTimeout(() => { - const target = event.target as HTMLInputElement; - search = target.value; - }, debounce); } function handleKeydown(event: KeyboardEvent) { @@ -70,13 +67,26 @@ case 'Enter': if (selected !== null) { event.preventDefault(); - value = options[selected].value; - search = options[selected].label; - hasFocus = false; + selectOption(options[selected]); } break; } } + + function selectOption(option: Option) { + value = option.value; + search = option.label; + // It's not working without this line. + element.value = search; + hasFocus = false; + } + + function clearOption() { + value = null; + search = ''; + element.value = search; + hasFocus = false; + }
  • @@ -95,28 +105,31 @@
    - (hasFocus = true)} - on:click={() => (hasFocus = true)} - on:input={handleInput} - on:keydown={handleKeydown} /> + {#if $$slots.default && selectedOption} + + + + {:else} + (hasFocus = true)} + on:click={() => (hasFocus = true)} + on:input={handleInput} + on:keydown={handleKeydown} /> + {/if}
  • {:else}