Skip to content

Commit

Permalink
fix: extended autocomplete with async options
Browse files Browse the repository at this point in the history
  • Loading branch information
KovaCro committed Dec 26, 2023
1 parent ded11c7 commit 6f5ac43
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 11 deletions.
2 changes: 2 additions & 0 deletions docs/docs/Form fields/autocomplete.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
| **Name** | **Required** | **Type** | **Description** |
| :----: | :----: | :----: | :---: |
| options | | `string[]` | list of autocomplete options |
| asyncOptions | | `(string) => Promise<array>` | async function that takes value of input and returns new options |
| lag | | `number` | time it takes for asyncOptions to be called after input stops changing |
| label | | `string` | shows at the top of an input |
| placeholder | | `string` | temporary text that appears in an <br></br> input field before any input is entered |
| name || `string` | name of the form control |
Expand Down
41 changes: 30 additions & 11 deletions packages/lib/src/form-fields/autocomplete.wc.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,10 @@
export let options: string[] | string = [];
export let value = '';
export let asyncOptions = null;
export let lag: number = 300;
let loading = false;
let lagTimeout;
export let label = 'autocomplete';
export let id: string | null = null;
export let name: string | null = null;
Expand Down Expand Up @@ -51,6 +55,18 @@
if (Array.isArray(options)) {
filteredOptions = options.filter((el) => el.toLowerCase().includes(value.toLowerCase()));
}
}
$: {
dispatch('value', value);
loading = true;
clearTimeout(lagTimeout);
lagTimeout = setTimeout(async () => {
options = await asyncOptions(value);
loading = false;
}, lag);
attachedInternals.checkValidity();
if (inputEl) {
if (inputEl.validity.patternMismatch) {
Expand Down Expand Up @@ -83,7 +99,6 @@
}
}
}
dispatch('value', value);
}
onMount(() => {
Expand Down Expand Up @@ -116,16 +131,20 @@

{#if open}
<div class="menu">
{#each filteredOptions as option}
<button
class="menu-button"
on:mousedown|preventDefault={() => {
value = option;
inputEl.blur();
}}
on:click|preventDefault>{option}</button
>
{/each}
{#if !loading}
{#each filteredOptions as option}
<button
class="menu-button"
on:mousedown|preventDefault={() => {
value = option;
inputEl.blur();
}}
on:click|preventDefault>{option}</button
>
{/each}
{:else}
Loading...
{/if}
</div>
{/if}
</label>
Expand Down

0 comments on commit 6f5ac43

Please sign in to comment.