All files / Autocomplete Autocomplete.tsx

85.48% Statements 53/62
59.45% Branches 22/37
100% Functions 15/15
85.48% Lines 53/62

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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315                      1x   1x                         1x                                                                                                                                 3x                       2x   2x 2x               2x   2x 2x 2x             25x       9x 9x               1x   1x   1x         1x 1x   1x 1x       1x         1x                   2x   2x 1x   1x     1x     1x         8x 8x 8x         1x 1x 1x         8x 8x                       23x   23x   23x 23x   23x                                                               18x               13x   13x         13x 13x                   13x 4x                 13x 13x                 13x         298x                      
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'lodash';
import { createClass, StandardProps } from '../../util/component-types';
import { lucidClassNames } from '../../util/style-helpers';
import { buildHybridComponent } from '../../util/state-management';
import { partitionText } from '../../util/text-manipulation';
import * as reducers from './Autocomplete.reducers';
import * as KEYCODE from '../../constants/key-code';
import { DropMenuDumb as DropMenu, IDropMenuProps } from '../DropMenu/DropMenu';
 
const cx = lucidClassNames.bind('&-Autocomplete');
 
const { arrayOf, bool, func, object, shape, string } = PropTypes;
 
export interface IAutocompleteProps extends StandardProps {
	isDisabled?: boolean;
	suggestions?: string[];
	value?: any;
	onChange?: any;
	onSelect?: any;
	onExpand?: any;
	DropMenu?: IDropMenuProps;
	placeholder?: any;
}
 
const Autocomplete = createClass<IAutocompleteProps>({
	statics: {
		peek: {
			description: `A text input with suggested values displayed in an attached menu.`,
			categories: ['controls', 'text'],
			madeFrom: ['DropMenu'],
		},
	},
 
	displayName: 'Autocomplete',
 
	reducers: reducers as any, // TODO: typescript hack that should be removed
 
	propTypes: {
		/**
			Appended to the component-specific class names set on the root elements.
		*/
		className: string,
 
		/**
			Styles that are passed through to root element.
		*/
		style: object,
 
		/**
			Disables the Autocomplete from being clicked or focused.
		*/
		isDisabled: bool,
 
		/**
			Array of suggested text input values shown in drop menu.
		*/
		suggestions: arrayOf(string),
 
		/**
			Text value of the input.
		*/
		value: string,
 
		/**
			Object of DropMenu props which are passed thru to the underlying DropMenu
			component.
		*/
		DropMenu: shape(DropMenu.propTypes),
 
		/**
			Called when the input value changes. Has the signature
			\`(value, {props, event}) => {}\` where value is a string.
		*/
		onChange: func,
 
		/**
			Called when a suggstion is selected from the menu. Has the signature
			\`(optionIndex, {props, event}) => {}\` where optionIndex is a number.
		*/
		onSelect: func,
 
		/**
			Called when menu is expected to expand. Has the signature
			\`({props, event}) => {}\`.
		*/
		onExpand: func,
	} as any, // TODO: typescript hack that should be removed
 
	getDefaultProps() {
		return {
			isDisabled: false,
			suggestions: [],
			value: '',
			onChange: _.noop,
			onSelect: _.noop,
			onExpand: _.noop,
			DropMenu: DropMenu.defaultProps,
		} as any; // TODO: typescript hack that should be removed
	},
 
	handleSelect(optionIndex: number, { event }: any) {
		const { suggestions, onChange, onSelect } = this.props;
 
		onChange(suggestions[optionIndex], { event, props: this.props });
		onSelect(optionIndex, { event, props: this.props });
	},
 
	handleInput(event: any) {
		const {
			onChange,
			onExpand,
			DropMenu: { onCollapse },
		} = this.props;
 
		onChange(event.target.value, { event, props: this.props });
		if (!_.isEmpty(event.target.value)) {
			onExpand({ event, props: this.props });
		} else E{
			onCollapse();
		}
	},
 
	getInputValue() {
		return _.get(this, 'inputRef.value', this.props.value);
	},
 
	setInputValue(value: any) {
		if (this.inputRef) {
			this.inputRef.value = value;
		}
	},
 
	handleInputKeydown(event: React.KeyboardEvent<HTMLInputElement>) {
		const {
			onExpand,
			DropMenu: { isExpanded, focusedIndex, onCollapse },
		} = this.props;
 
		const value = this.getInputValue();
 
		Iif (event.keyCode === KEYCODE.Tab && isExpanded && focusedIndex !== null) {
			this.handleSelect(focusedIndex, { event, props: this.props });
			event.preventDefault();
		}
 
		if (event.keyCode === KEYCODE.ArrowDown && !isExpanded) {
			event.stopPropagation();
 
			if (_.isEmpty(value)) {
				onExpand({ event, props: this.props });
			}
		}
 
		Iif (event.keyCode === KEYCODE.Escape) {
			event.stopPropagation();
			onCollapse(event);
		}
 
		Iif (event.keyCode === KEYCODE.Enter && focusedIndex === null) {
			event.stopPropagation();
			onCollapse(event);
		}
	},
 
	handleControlClick(event: React.MouseEvent<Element, MouseEvent>) {
		const {
			onExpand,
			DropMenu: { isExpanded, onCollapse },
		} = this.props;
 
		if (event.target === this.inputRef) {
			onExpand({ event, props: this.props });
		} else {
			Iif (isExpanded) {
				onCollapse(event);
			} else {
				onExpand({ event, props: this.props });
			}
 
			this.inputRef.focus();
		}
	},
 
	componentDidMount() {
		const { value } = this.props;
		this.inputRef.addEventListener('input', this.handleInput);
		this.setInputValue(value);
	},
 
	UNSAFE_componentWillReceiveProps(nextProps: any) {
		// TODO: typescript hack that should be removed
		const { value } = nextProps;
		if (value !== this.getInputValue()) {
			this.setInputValue(value);
		}
	},
 
	componentWillUnmount() {
		if (this.inputRef) {
			this.inputRef.removeEventListener('input', this.handleInput);
		}
	},
 
	render() {
		const {
			style,
			className,
			isDisabled,
			DropMenu: dropMenuProps,
			suggestions,
			...passThroughs
		} = this.props as any; // TODO: typescript hack that should be removed
 
		const { isExpanded } = dropMenuProps;
 
		const value = this.getInputValue();
		const valuePattern = new RegExp(_.escapeRegExp(value), 'i');
 
		return (
			<DropMenu
				{...dropMenuProps}
				isDisabled={isDisabled}
				selectedIndices={[]}
				className={cx('&', className)}
				onSelect={this.handleSelect}
				style={style}
			>
				<DropMenu.Control
					{
						...{
							onClick: this.handleControlClick,
						} /* TODO: typescript hack that should be removed */
					}
				>
					<div
						className={cx('&-Control', {
							'&-Control-is-expanded': isExpanded,
							'&-Control-is-disabled': isDisabled,
						})}
					>
						<input
							{...(_.omit(passThroughs, [
								'onChange',
								'onSelect',
								'onExpand',
								'value',
								'children',
							]) as any)} // TODO: typescript hack that should be removed
							type='text'
							className={cx('&-Control-input')}
							ref={(ref) => (this.inputRef = ref)}
							onKeyDown={this.handleInputKeydown}
							disabled={isDisabled}
						/>
					</div>
				</DropMenu.Control>
				{value
					? _.map(suggestions, (suggestion) => (
							<DropMenu.Option key={'AutocompleteOption' + suggestion}>
								{(() => {
									const [pre, match, post] = partitionText(
										suggestion,
										valuePattern,
										value.length
									);
									const formattedSuggestion: any = [];
									Iif (pre) {
										formattedSuggestion.push(
											<span
												key={`AutocompleteOption-suggestion-pre-${suggestion}`}
												className={cx('&-Option-suggestion-pre')}
											>
												{pre}
											</span>
										);
									}
									if (match) {
										formattedSuggestion.push(
											<span
												key={`AutocompleteOption-suggestion-match-${suggestion}`}
												className={cx('&-Option-suggestion-match')}
											>
												{match}
											</span>
										);
									}
									if (post) {
										formattedSuggestion.push(
											<span
												key={`AutocompleteOption-suggestion-post-${suggestion}`}
												className={cx('&-Option-suggestion-post')}
											>
												{post}
											</span>
										);
									}
									return formattedSuggestion;
								})()}
							</DropMenu.Option>
					  ))
					: _.map(suggestions, (suggestion) => (
							<DropMenu.Option key={'AutocompleteOption' + suggestion}>
								{suggestion}
							</DropMenu.Option>
					  ))}
			</DropMenu>
		);
	},
});
 
export default buildHybridComponent(Autocomplete);
export { Autocomplete as AutocompleteDumb };