diff --git a/src/lib/components/Input/Search.svelte b/src/lib/components/Input/Search.svelte index c167129..840bd4d 100644 --- a/src/lib/components/Input/Search.svelte +++ b/src/lib/components/Input/Search.svelte @@ -2,7 +2,6 @@ let { id, value = $bindable(), - inputValue = $bindable(), suggestionRequired = false, emptyAllowed = false, searchSuggestionFunc = () => Promise.resolve([]), @@ -13,8 +12,7 @@ onsubmit }: { id?: string; - value?: string; - inputValue?: string; + value: string; suggestionRequired?: boolean; emptyAllowed?: boolean; searchSuggestionFunc?: (input: string) => Promise<{ name: string; value: string }[]>; @@ -25,10 +23,8 @@ onsubmit?: (event: Event & { input: string; value: string }) => void; } = $props(); + let elemValue = $state(value); let searchSuggestions: { name: string; value: string }[] = $state([]); - $effect(() => { - if (!suggestionRequired) value = inputValue; - });
@@ -45,6 +41,7 @@ {/if} { - value = ''; - searchSuggestionFunc(inputValue).then((v) => { - searchSuggestions = v; - const searchSuggestion = v.find((v) => v.name === inputValue); - if (searchSuggestion !== undefined) { - inputValue = searchSuggestion.name; - value = searchSuggestion.value; - searchSuggestions = []; - e.currentTarget.setCustomValidity(''); - onsubmit?.(Object.assign(e, { input: inputValue, value: value })); - } else if (inputValue === '' && emptyAllowed) { - onsubmit?.(Object.assign(e, { input: '', value: '' })); - } - }); + bind:value={elemValue} + oninput={async (e: Event & { currentTarget: EventTarget & HTMLInputElement }) => { + searchSuggestions = await searchSuggestionFunc(elemValue); + const searchSuggestion = searchSuggestions.find((v) => v.name === elemValue); + if (searchSuggestion !== undefined) { + elemValue = searchSuggestion.name; + value = searchSuggestion.value; + searchSuggestions = []; + (e.currentTarget || e.target).setCustomValidity(''); + onsubmit?.(Object.assign(e, { input: elemValue, value: value })); + } else if (elemValue === '' && emptyAllowed) { + onsubmit?.(Object.assign(e, { input: '', value: '' })); + } else { + value = ''; + } }} oninvalid={(e: Event & { currentTarget: EventTarget & HTMLInputElement }) => { if (invalidMessage) e.currentTarget.setCustomValidity(invalidMessage); }} + onfocus={() => searchSuggestionFunc(elemValue).then((v) => (searchSuggestions = v))} pattern={suggestionRequired - ? `${value ? inputValue : 'a^' + (emptyAllowed ? '|$^' : '')}` + ? `${value ? elemValue : 'a^' + (emptyAllowed ? '|$^' : '')}` : null} />
- {#if inputValue && searchSuggestions.length !== 0} + {#if elemValue && searchSuggestions.length !== 0}