polaris icon indicating copy to clipboard operation
polaris copied to clipboard

[Autocomplete] Arrow keys don't function properly with short lists

Open solonaarmstrong-zz opened this issue 8 years ago • 0 comments

Issue summary

The arrow keys have funky behaviour.

autocomplete-keyboard

Expected behavior

Up should go up and down should go down.

Reduced test case

Playground
/* eslint-disable */

import * as React from 'react';
import {
  Page,
  AppProvider,
  Stack,
  Tag,
  TextContainer,
  // Icon,
} from '@shopify/polaris';
import Autocomplete from '../src/components/Autocomplete';
import _ from 'lodash';

interface Props {}
interface State {}

export default class DemoTagsAutocomplete extends React.Component<
  Props,
  State
> {
  // Quick Config
  ALLOW_MULTIPLE = false;
  RESULT_PAGE_LENGTH = 10;

  options = [
    {value: 'polyester', label: 'Polyester'},
    {value: 'wool', label: 'Wool'},
    {value: 'vinyl', label: 'Vinyl'},
    {value: 'vintage', label: 'Vintage'},
  ];

  state = {
    selected: [],
    inputText: '',
    options: this.options.slice(0, this.RESULT_PAGE_LENGTH),
    filteredOptions: this.options.slice(
      this.RESULT_PAGE_LENGTH,
      this.options.length - 1,
    ),
    loading: false,
  };

  updateText = (newValue: string) => {
    this.setState({inputText: newValue});
    this.filterAndUpdateOptions(newValue);
  };

  removeTag = (tag: string) => {
    let newSelected: string[] = this.state.selected;
    newSelected.splice(newSelected.indexOf(tag), 1);
    this.setState({selected: newSelected});
  };

  addTag = (tag: string) => {
    if (!tag || tag === '') {
      return;
    }
    let tagLabel = '';
    tagLabel = tag.replace('_', ' ');
    tagLabel = _.startCase(tagLabel);

    this.options.push({value: tag, label: tagLabel});
    this.filterAndUpdateOptions(tag);
  };

  renderTags = (): React.ReactNode => {
    return this.state.selected.map((option: string) => {
      let tagLabel = '';
      tagLabel = option.replace('_', ' ');
      tagLabel = _.startCase(tagLabel);
      return (
        <Tag key={'option' + option} onRemove={() => this.removeTag(option)}>
          {tagLabel}
        </Tag>
      );
    });
  };

  shouldLoadMoreResults = (): boolean => {
    const {filteredOptions, loading} = this.state;
    if (filteredOptions.length === 0 || loading) {
      return false;
    }
    this.setState({loading: true});
    return true;
  };

  loadMoreResults = () => {
    const {filteredOptions, options} = this.state;
    if (this.shouldLoadMoreResults()) {
      let currentlyLoadedOptions = options;
      let unloadedOptions = filteredOptions;

      const endIndex =
        currentlyLoadedOptions.length + this.RESULT_PAGE_LENGTH - 1;
      let optionsToLoad = unloadedOptions.slice(0, endIndex);

      currentlyLoadedOptions = currentlyLoadedOptions.concat(optionsToLoad);
      unloadedOptions = unloadedOptions.slice(
        endIndex,
        unloadedOptions.length - 1,
      );

      setTimeout(() => {
        this.setState({
          options: currentlyLoadedOptions,
          filteredOptions: unloadedOptions,
          loading: false,
        });
      }, 300);
    }
  };

  shouldShowRenderActionButton = (): boolean => {
    const {inputText} = this.state;
    return !(
      !inputText ||
      inputText === '' ||
      (this.ALLOW_MULTIPLE && containsOption(this.options, inputText))
    );
  };

  renderActionButton = (): ItemDescriptor | undefined => {
    if (this.shouldShowRenderActionButton()) {
      return {
        content: 'Add "' + this.state.inputText + '"',
        icon: 'circlePlus',
        onAction: () => this.addTag(this.state.inputText),
      };
    }
    return undefined;
  };

  // getListTitle = (): string | undefined => {
  //   if (this.shouldShowRenderActionButton()) {
  //     return undefined;
  //   }
  //   return 'Frequently Used Tags';
  // };

  render() {
    console.log(this.renderActionButton());

    return (
      <AppProvider>
        <Page title="Demo Tags Autocomplete">
          <br />
          <TextContainer>
            <Stack>{this.renderTags()}</Stack>
          </TextContainer>
          <br />
          <Autocomplete
            options={this.state.options}
            selected={this.state.selected}
            textField={
              <Autocomplete.ComboBox.TextField
                onChange={this.updateText}
                label=""
                value={this.state.inputText}
                placeholder="Vintage, cotton, summer"
                // prefix={<Icon source="search" color="inkLighter" />}
              />
            }
            onSelect={this.updateSelection}
            allowMultiple={this.ALLOW_MULTIPLE}
            loading={this.state.loading}
            willLoadMoreResults
            onLoadMoreResults={this.loadMoreResults}
            // actionBefore={this.renderActionButton()}
            // listTitle={this.getListTitle()}
          />
        </Page>
      </AppProvider>
    );
  }

  filterAndUpdateOptions = (inputString: string) => {
    if (inputString === '') {
      this.setState({
        options: this.options.slice(0, this.RESULT_PAGE_LENGTH),
        filteredOptions: this.options.slice(
          this.RESULT_PAGE_LENGTH,
          this.options.length,
        ),
      });
      return;
    }

    const filterRegex = new RegExp(inputString, 'i');
    const resultOptions = this.options.filter((option) =>
      option.label.match(filterRegex),
    );
    let endIndex = resultOptions.length - 1;
    if (resultOptions.length === 0) {
      endIndex = 0;
    }
    this.setState({
      options: resultOptions.slice(0, this.RESULT_PAGE_LENGTH),
      filteredOptions: resultOptions.slice(this.RESULT_PAGE_LENGTH, endIndex),
    });
  };

  updateSelection = (updatedSelection: string[]) => {
    const selectedText = updatedSelection.map((selectedItem: string) => {
      const matchedOption = this.options.filter((option) => {
        return option.value.match(selectedItem);
      });
      return matchedOption[0] && matchedOption[0].label;
    });
    if (this.ALLOW_MULTIPLE) {
      this.setState({selected: updatedSelection});
    } else {
      this.setState({selected: selectedText, inputText: selectedText});
    }
  };
}

function containsOption(a: any, optionString: string) {
  for (var i = 0; i < a.length; i++) {
    const filterRegex = new RegExp(
      '^' + optionString.replace(' ', '_') + '$',
      'i',
    );
    if (a[i].value.match(filterRegex)) {
      return true;
    }
  }
  return false;
}

/* eslint-enable */

solonaarmstrong-zz avatar Oct 25 '18 22:10 solonaarmstrong-zz