pstanoev / simple-svelte-autocomplete

Simple Autocomplete / typeahead component for Svelte
http://simple-svelte-autocomplete.surge.sh/
MIT License
464 stars 78 forks source link

How to manually clear input? How to only show X when there's something to clear? #174

Open jtlapp opened 2 years ago

jtlapp commented 2 years ago

I have two questions about clearing the input field, not both applying to the same autocomplete.

  1. How do I manually clear the input from JS?
  2. How do I only show the X button when there is text in the input?

In the first case, setting the bound variable doesn't do the job.

In the second case, setting showClear={!!selection} is not responsive to the user's typing.

P.S. Regardless, this component is awesome!

jtlapp commented 2 years ago

It took some work, but I found a solution. I'm having to make other on-screen controls appear and disappear according to whether the autocomplete box contains a valid name, in addition to only wanting the 'x' when there is something to clear. In TypeScript:

  let selection: string | undefined;
  let autocompleteClearButton: Element;

  onMount(() => {
    const autocompleteInput = document.querySelector('input.autocomplete-input')!;
    autocompleteInput.addEventListener('input', _inputChanged);

    const autocompleteList = document.querySelector('div.autocomplete-list')!;
    autocompleteList.addEventListener('click', _setAutocomplete);

    autocompleteClearButton = document.querySelector('span.autocomplete-clear-button')!;
    autocompleteClearButton.addEventListener('click', _clearedAutocomplete);
    _toggleClearButton(false);
  });

  function _inputChanged() {
    // doesn't catch changes made from JS (e.g. clearing)
    // @ts-ignore
    const newValue = this.value;
    _toggleClearButton(!!newValue);
    if (newValue.toLowerCase() != selection?.toLowerCase()) {
      selection = undefined;
    }
  }

  function _clearedAutocomplete() {
    selection = undefined;
    _toggleClearButton(false);
  }

  function _setAutocomplete() {
    _toggleClearButton(true);
  }

  function _toggleClearButton(show: boolean) {
    autocompleteClearButton.setAttribute(
      'style',
      'display:' + (show ? 'block' : 'none')
    );
  }

Also, I found the boldness of the clear button drawing my eye away from more important elements of the page. I was unable to change much via CSS, but changing the opacity did the job:

  :global(span.autocomplete-clear-button) {
    opacity: 0.6;
  }

UPDATE: It wasn't restoring the clear button upon selecting a value from the dropdown, so I had to detect and handle this.

jtlapp commented 2 years ago

And then to programmatically clear the autocomplete:

  function clearInput() {
    autocompleteClearButton.click();
  }
jtlapp commented 2 years ago

I'm attempting to create a component that wraps AutoComplete to provide this additional functionality, but I can't figure out how to propagate slots forward to AutoComplete while also back-propagating slot values to make them available via let:.

jtlapp commented 2 years ago

I figured it out. I'm not using Svelte slot forwarding because it doesn't forward default slots and because it's not supported well in TypeScript.

The caller optionally provides a setClearer property for receiving a function that can be called to clear the input. And if there is more than one autocomplete on the same page, the caller can provide an inputSelector to uniquely identify the present one. (bind:this can't be used to access the underlying DOM unless it's used on a DOM element.)

<script lang="ts">
  import { onMount } from 'svelte';
  import AutoComplete from 'simple-svelte-autocomplete';

  export let inputSelector = '';
  export let value: string | undefined = undefined;
  export let setClearer: (clearer: () => void) => void = () => {};

  setClearer(clearInput);
  const reducedProps = Object.assign($$props);
  delete reducedProps['inputSelector'];
  delete reducedProps['setClearer'];

  let autocompleteClearButton: HTMLButtonElement;

  onMount(() => {
    const autocompleteInput = document.querySelector(
      inputSelector + ' .autocomplete-input'
    )!;
    autocompleteInput.addEventListener('input', _inputChanged);

    const autocompleteList = document.querySelector(
      inputSelector + ' .autocomplete-list'
    )!;
    autocompleteList.addEventListener('click', _setAutocomplete);

    autocompleteClearButton = document.querySelector(
      inputSelector + ' .autocomplete-clear-button'
    )!;
    autocompleteClearButton.addEventListener('click', _clearedAutocomplete);
    _toggleClearButton(false);
  });

  function clearInput() {
    autocompleteClearButton.click();
  }

  function _inputChanged() {
    // doesn't catch changes made from JS (e.g. clearing or list selection)
    // @ts-ignore
    const newValue = this.value;
    _toggleClearButton(!!newValue);
    if (newValue.toLowerCase() != value?.toLowerCase()) {
      value = undefined;
    }
  }

  function _clearedAutocomplete() {
    value = undefined;
    _toggleClearButton(false);
  }

  function _setAutocomplete() {
    _toggleClearButton(true);
  }

  function _toggleClearButton(show: boolean) {
    autocompleteClearButton.setAttribute(
      'style',
      'display:' + (show ? 'block' : 'none')
    );
  }
</script>

<AutoComplete bind:value {...reducedProps} showClear={true}>
  <svelte:fragment slot="item" let:label let:item>
    {#if $$slots['item']}
      <slot name="item" {label} {item} />
    {/if}
  </svelte:fragment>
  <svelte:fragment slot="no-results" let:noResultsText>
    {#if $$slots['no-results']}
      <slot name="no-results" {noResultsText} />
    {/if}
  </svelte:fragment>
  <svelte:fragment slot="loading" let:loadingText>
    {#if $$slots['loading']}
      <slot name="loading" {loadingText} />
    {/if}
  </svelte:fragment>
  <svelte:fragment slot="tag" let:label let:item let:unselectItem>
    {#if $$slots['tag']}
      <slot name="tag" {label} {item} {unselectItem} />
    {/if}
  </svelte:fragment>
  <svelte:fragment slot="menu-header" let:nbItems let:maxItemsToShowInList>
    {#if $$slots['menu-header']}
      <slot name="menu-header" {nbItems} {maxItemsToShowInList} />
    {/if}
  </svelte:fragment>
  <svelte:fragment slot="dropdown-footer" let:nbItems let:maxItemsToShowInList>
    {#if $$slots['dropdown-footer']}
      <slot name="dropdown-footer" {nbItems} {maxItemsToShowInList} />
    {/if}
  </svelte:fragment>
</AutoComplete>

<style>
  :global(span.autocomplete-clear-button) {
    opacity: 0.6;
  }
</style>