Skip to content

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

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
jtlapp opened this issue Jun 8, 2022 · 4 comments

Comments

@jtlapp
Copy link

jtlapp commented Jun 8, 2022

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
Copy link
Author

jtlapp commented Jun 8, 2022

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
Copy link
Author

jtlapp commented Jun 9, 2022

And then to programmatically clear the autocomplete:

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

@jtlapp
Copy link
Author

jtlapp commented Jun 9, 2022

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
Copy link
Author

jtlapp commented Jun 10, 2022

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>

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant