/** @format */ /** * External dependencies */ import { __, sprintf } from '@wordpress/i18n'; import { Component, createRef } from '@wordpress/element'; import { withInstanceId } from '@wordpress/compose'; import { findIndex, noop } from 'lodash'; import Gridicon from 'gridicons'; import PropTypes from 'prop-types'; import classnames from 'classnames'; /** * Internal dependencies */ import Autocomplete from './autocomplete'; import { product, productCategory, coupons } from './autocompleters'; import Tag from 'components/tag'; import './style.scss'; /** * A search box which autocompletes results while typing, allowing for the user to select an existing object * (product, order, customer, etc). Currently only products are supported. */ class Search extends Component { constructor( props ) { super( props ); this.state = { value: '', isActive: false, }; this.input = createRef(); this.selectResult = this.selectResult.bind( this ); this.removeResult = this.removeResult.bind( this ); this.updateSearch = this.updateSearch.bind( this ); this.onFocus = this.onFocus.bind( this ); this.onBlur = this.onBlur.bind( this ); } selectResult( value ) { const { selected, onChange } = this.props; // Check if this is already selected const isSelected = findIndex( selected, { id: value.id } ); if ( -1 === isSelected ) { this.setState( { value: '' } ); onChange( [ ...selected, value ] ); } } removeResult( id ) { return () => { const { selected, onChange } = this.props; const i = findIndex( selected, { id } ); onChange( [ ...selected.slice( 0, i ), ...selected.slice( i + 1 ) ] ); }; } updateSearch( onChange ) { return event => { const value = event.target.value || ''; this.setState( { value } ); onChange( event ); }; } getAutocompleter() { switch ( this.props.type ) { case 'products': return product; case 'product_cats': return productCategory; case 'coupons': return coupons; default: return {}; } } renderTags() { const { selected } = this.props; return selected.length ? (