1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import React from 'react';
11 FormControl, InputLabel, StyleRulesCallback, withStyles, RootRef, ListItemText, ListItem, List, FormHelperText
12 } from '@material-ui/core';
13 import { PopperProps } from '@material-ui/core/Popper';
14 import { WithStyles } from '@material-ui/core/styles';
15 import { noop } from 'lodash';
17 export interface AutocompleteProps<Item, Suggestion> {
22 suggestions?: Suggestion[];
26 onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
27 onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
28 onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
29 onCreate?: () => void;
30 onDelete?: (item: Item, index: number) => void;
31 onSelect?: (suggestion: Suggestion) => void;
32 renderChipValue?: (item: Item) => string;
33 renderSuggestion?: (suggestion: Suggestion) => React.ReactNode;
36 export interface AutocompleteState {
37 suggestionsOpen: boolean;
38 selectedSuggestionIndex: number;
41 export class Autocomplete<Value, Suggestion> extends React.Component<AutocompleteProps<Value, Suggestion>, AutocompleteState> {
44 suggestionsOpen: false,
45 selectedSuggestionIndex: 0,
48 containerRef = React.createRef<HTMLDivElement>();
49 inputRef = React.createRef<HTMLInputElement>();
53 <RootRef rootRef={this.containerRef}>
54 <FormControl fullWidth error={this.props.error}>
57 {this.renderHelperText()}
58 {this.renderSuggestions()}
65 const { label } = this.props;
66 return label && <InputLabel>{label}</InputLabel>;
71 disabled={this.props.disabled}
72 autoFocus={this.props.autofocus}
73 inputRef={this.inputRef}
74 value={this.props.value}
75 startAdornment={this.renderChips()}
76 onFocus={this.handleFocus}
77 onBlur={this.handleBlur}
78 onChange={this.props.onChange}
79 onKeyPress={this.handleKeyPress}
80 onKeyDown={this.handleNavigationKeyPress}
85 return <FormHelperText>{this.props.helperText}</FormHelperText>;
89 const { suggestions = [] } = this.props;
92 open={this.isSuggestionBoxOpen()}
93 anchorEl={this.inputRef.current}
94 key={suggestions.length}>
95 <Paper onMouseDown={this.preventBlur}>
96 <List dense style={{ width: this.getSuggestionsWidth() }}>
98 (suggestion, index) =>
102 onClick={this.handleSelect(suggestion)}
103 selected={index === this.state.selectedSuggestionIndex}>
104 {this.renderSuggestion(suggestion)}
113 isSuggestionBoxOpen() {
114 const { suggestions = [] } = this.props;
115 return this.state.suggestionsOpen && suggestions.length > 0;
118 handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
119 const { onFocus = noop } = this.props;
120 this.setState({ suggestionsOpen: true });
124 handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
126 const { onBlur = noop } = this.props;
127 this.setState({ suggestionsOpen: false });
132 handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
133 const { onCreate = noop, onSelect = noop, suggestions = [] } = this.props;
134 const { selectedSuggestionIndex } = this.state;
135 if (event.key === 'Enter') {
136 if (this.isSuggestionBoxOpen() && selectedSuggestionIndex < suggestions.length) {
137 // prevent form submissions when selecting a suggestion
138 event.preventDefault();
139 onSelect(suggestions[selectedSuggestionIndex]);
140 } else if (this.props.value.length > 0) {
146 handleNavigationKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
147 if (key === 'ArrowUp') {
148 this.updateSelectedSuggestionIndex(-1);
149 } else if (key === 'ArrowDown') {
150 this.updateSelectedSuggestionIndex(1);
154 updateSelectedSuggestionIndex(value: -1 | 1) {
155 const { suggestions = [] } = this.props;
156 this.setState(({ selectedSuggestionIndex }) => ({
157 selectedSuggestionIndex: (selectedSuggestionIndex + value) % suggestions.length
162 const { items, onDelete } = this.props;
165 * If input startAdornment prop is not undefined, input's label will stay above the input.
166 * If there is not items, we want the label to go back to placeholder position.
167 * That why we return without a value instead of returning a result of a _map_ which is an empty array.
169 if (items.length === 0) {
176 label={this.renderChipValue(item)}
178 onDelete={() => onDelete ? onDelete(item, index) : undefined} />
182 renderChipValue(value: Value) {
183 const { renderChipValue } = this.props;
184 return renderChipValue ? renderChipValue(value) : JSON.stringify(value);
187 preventBlur = (event: React.MouseEvent<HTMLElement>) => {
188 event.preventDefault();
191 handleClickAway = (event: React.MouseEvent<HTMLElement>) => {
192 if (event.target !== this.inputRef.current) {
193 this.setState({ suggestionsOpen: false });
197 handleSelect(suggestion: Suggestion) {
199 const { onSelect = noop } = this.props;
200 const { current } = this.inputRef;
204 onSelect(suggestion);
208 renderSuggestion(suggestion: Suggestion) {
209 const { renderSuggestion } = this.props;
210 return renderSuggestion
211 ? renderSuggestion(suggestion)
212 : <ListItemText>{JSON.stringify(suggestion)}</ListItemText>;
215 getSuggestionsWidth() {
216 return this.containerRef.current ? this.containerRef.current.offsetWidth : 'auto';
220 type ChipClasses = 'root';
222 const chipStyles: StyleRulesCallback<ChipClasses> = theme => ({
224 marginRight: theme.spacing.unit / 4,
225 height: theme.spacing.unit * 3,
229 const Chip = withStyles(chipStyles)(MuiChip);
231 type PopperClasses = 'root';
233 const popperStyles: StyleRulesCallback<ChipClasses> = theme => ({
235 zIndex: theme.zIndex.modal,
239 const Popper = withStyles(popperStyles)(
240 ({ classes, ...props }: PopperProps & WithStyles<PopperClasses>) =>
241 <MuiPopper {...props} className={classes.root} />
244 type InputClasses = 'root';
246 const inputStyles: StyleRulesCallback<InputClasses> = () => ({
257 const Input = withStyles(inputStyles)(MuiInput);
259 const Paper = withStyles({