All files / src/ui/components SearchBox.tsx

87.5% Statements 28/32
58.33% Branches 7/12
92.86% Functions 13/14
87.1% Lines 27/31

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184                                                                                  10x                 3x                 4x   4x           4x 4x   4x 4x       6x                   2x     2x 1x   1x 1x     1x   4x         4x   4x         1x   1x         1x 1x                 10x 10x                             12x             1x                       6x                                            
/*
 * Copyright 2019 Red Hat, Inc. and/or its affiliates.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
import '@patternfly/patternfly/patternfly.css';
import { Button, Text, TextContent, TextInput, TextVariants } from '@patternfly/react-core';
import { PlusSquareIcon } from '@patternfly/react-icons';
import { OpenStreetMapProvider } from 'leaflet-geosearch';
import * as React from 'react';
import { LatLng } from 'store/route/types';
 
export interface Props {
  searchDelay: number;
  boundingBox: [LatLng, LatLng] | null;
  countryCodeSearchFilter: string[];
  addHandler: (result: Result) => void;
}
 
export interface State {
  query: string;
  results: Result[];
  attributions: string[];
}
 
export interface Result {
  address: string;
  latLng: LatLng;
}
 
const searchParams = (props: Props) => ({
  countrycodes: props.countryCodeSearchFilter,
  viewbox: props.boundingBox
    ? [props.boundingBox[0].lng, props.boundingBox[0].lat, props.boundingBox[1].lng, props.boundingBox[1].lat]
    : undefined,
  bounded: !!props.boundingBox,
});
 
class SearchBox extends React.Component<Props, State> {
  static defaultProps: Pick<Props, 'searchDelay'> = {
    searchDelay: 500,
  };
 
  private searchProvider: OpenStreetMapProvider;
 
  private timeoutId: number | null;
 
  constructor(props: Props) {
    super(props);
 
    this.state = {
      query: '',
      results: [],
      attributions: [],
    };
 
    this.searchProvider = new OpenStreetMapProvider({ params: searchParams(props) });
    this.timeoutId = null;
 
    this.handleTextInputChange = this.handleTextInputChange.bind(this);
    this.handleClick = this.handleClick.bind(this);
  }
 
  componentWillUpdate(nextProps: Readonly<Props>): void {
    this.searchProvider = new OpenStreetMapProvider({ params: searchParams(nextProps) });
  }
 
  componentWillUnmount() {
    if (this.timeoutId) {
      window.clearTimeout(this.timeoutId);
    }
  }
 
  handleTextInputChange(query: string): void {
    Iif (this.timeoutId) {
      window.clearTimeout(this.timeoutId);
    }
    if (query.trim() !== '') {
      this.timeoutId = window.setTimeout(
        async () => {
          const searchResults = await this.searchProvider.search({ query });
          Iif (this.state.query !== query) {
            return;
          }
          this.setState({
            results: searchResults
              .map(result => ({
                address: result.label,
                latLng: { lat: result.y, lng: result.x },
              })),
            attributions: searchResults
              .map(result => result.raw.licence)
              // filter out duplicate elements
              .filter((value, index, array) => array.indexOf(value) === index),
          });
        },
        this.props.searchDelay,
      );
      this.setState({ query });
    } else {
      this.setState({ query, results: [], attributions: [] });
    }
  }
 
  handleClick(index: number) {
    this.props.addHandler(this.state.results[index]);
    this.setState({
      query: '',
      results: [],
      attributions: [],
    });
    // TODO focus text input
  }
 
  render() {
    const { attributions, query, results } = this.state;
    return (
      <>
        <TextInput
          style={{ marginBottom: 10 }}
          value={query}
          type="search"
          placeholder="Search to add a location..."
          aria-label="geosearch text input"
          onChange={this.handleTextInputChange}
          data-cy="geosearch-text-input"
        />
        {results.length > 0 && (
          <div className="pf-c-options-menu pf-m-expanded" style={{ zIndex: 1100 }}>
            <ul className="pf-c-options-menu__menu">
              {results.map((result, index) => (
                <li key={`result: ${result}`}>
                  <div className="pf-c-options-menu__menu-item">
                    {result.address}
                    <Button
                      className="pf-c-options-menu__menu-item-icon"
                      variant="link"
                      type="button"
                      onClick={() => this.handleClick(index)}
                      data-cy={`geosearch-location-item-button-${index}`}
                    >
                      <PlusSquareIcon />
                    </Button>
                  </div>
                </li>
              ))}
 
              <li className="pf-c-options-menu__separator" role="separator" />
 
              {attributions.map(attribution => (
                <li
                  key={`attrib: ${attribution}`}
                  className="pf-c-options-menu__menu-item pf-m-disabled"
                >
                  <TextContent>
                    <Text
                      component={TextVariants.small}
                    >
                      {attribution}
                    </Text>
                  </TextContent>
                </li>
              ))}
            </ul>
          </div>
        )}
      </>
    );
  }
}
 
export default SearchBox;