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, Tooltip, Typography
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';
16 import { isGroup } from 'common/isGroup';
17 import { sortByKey } from 'common/objects';
18 import classNames from 'classnames';
20 export interface AutocompleteProps<Item, Suggestion> {
25 suggestions?: Suggestion[];
29 onChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
30 onBlur?: (event: React.FocusEvent<HTMLInputElement>) => void;
31 onFocus?: (event: React.FocusEvent<HTMLInputElement>) => void;
32 onCreate?: () => void;
33 onDelete?: (item: Item, index: number) => void;
34 onSelect?: (suggestion: Suggestion) => void;
35 renderChipValue?: (item: Item) => string;
36 renderChipTooltip?: (item: Item) => string;
37 renderSuggestion?: (suggestion: Suggestion) => React.ReactNode;
38 category?: AutocompleteCat;
41 type AutocompleteClasses = 'sharingList' | 'emptyList' | 'listSubHeader' | 'numFound';
43 const autocompleteStyles: StyleRulesCallback<AutocompleteClasses> = theme => ({
47 scrollbarColor: 'rgba(0, 0, 0, 0.3) rgba(0, 0, 0, 0)',
48 '&::-webkit-scrollbar': {
51 '&::-webkit-scrollbar-thumb': {
52 backgroundColor: 'rgba(0, 0, 0, 0.3)',
55 '&::-webkit-scrollbar-track': {
56 backgroundColor: 'rgba(0, 0, 0, 0)',
66 alignItems: 'flex-end',
67 justifyContent: 'space-between',
75 export enum AutocompleteCat {
79 export interface AutocompleteState {
80 suggestionsOpen: boolean;
81 selectedSuggestionIndex: number;
84 export const Autocomplete = withStyles(autocompleteStyles)(
85 class Autocomplete<Value, Suggestion> extends React.Component<AutocompleteProps<Value, Suggestion> & WithStyles<AutocompleteClasses>, AutocompleteState> {
88 suggestionsOpen: false,
89 selectedSuggestionIndex: 0,
92 containerRef = React.createRef<HTMLDivElement>();
93 inputRef = React.createRef<HTMLInputElement>();
97 <RootRef rootRef={this.containerRef}>
98 <FormControl fullWidth error={this.props.error}>
101 {this.renderHelperText()}
102 {this.props.category === AutocompleteCat.SHARING ? this.renderSharingSuggestions() : this.renderSuggestions()}
109 const { label } = this.props;
110 return label && <InputLabel>{label}</InputLabel>;
115 disabled={this.props.disabled}
116 autoFocus={this.props.autofocus}
117 inputRef={this.inputRef}
118 value={this.props.value}
119 startAdornment={this.renderChips()}
120 onFocus={this.handleFocus}
121 onBlur={this.handleBlur}
122 onChange={this.props.onChange}
123 onKeyPress={this.handleKeyPress}
124 onKeyDown={this.handleNavigationKeyPress}
129 return <FormHelperText>{this.props.helperText}</FormHelperText>;
132 renderSuggestions() {
133 const { suggestions = [] } = this.props;
136 open={this.isSuggestionBoxOpen()}
137 anchorEl={this.inputRef.current}
138 key={suggestions.length}>
139 <Paper onMouseDown={this.preventBlur}>
140 <List dense style={{ width: this.getSuggestionsWidth() }}>
142 (suggestion, index) =>
146 onClick={this.handleSelect(suggestion)}
147 selected={index === this.state.selectedSuggestionIndex}>
148 {this.renderSuggestion(suggestion)}
157 renderSharingSuggestions() {
158 const { suggestions = [], classes } = this.props;
159 const users = sortByKey<Suggestion>(suggestions.filter(item => !isGroup(item)), 'fullName');
160 const groups = sortByKey<Suggestion>(suggestions.filter(item => isGroup(item)), 'name');
164 open={this.isSuggestionBoxOpen()}
165 anchorEl={this.inputRef.current}
166 key={suggestions.length}>
167 <Paper onMouseDown={this.preventBlur}>
168 <div className={classes.listSubHeader}>
169 Groups {<span className={classes.numFound}>{groups.length} {groups.length === 1 ? 'match' : 'matches'} found</span>}
171 <List dense className={classes.sharingList} style={{width: this.getSuggestionsWidth()}}>
173 (suggestion, index) =>
176 id={`groups-${index}`}
177 key={`groups-${index}`}
178 onClick={this.handleSelect(suggestion)}>
179 {this.renderSharingSuggestion(suggestion)}
183 <div className={classes.listSubHeader}>
184 Users {<span className={classes.numFound}>{users.length} {users.length === 1 ? 'match' : 'matches'} found</span>}
186 <List dense className={classes.sharingList} style={{width: this.getSuggestionsWidth()}}>
188 (suggestion, index) =>
191 id={`users-${index}`}
192 key={`users-${index}`}
193 onClick={this.handleSelect(suggestion)}>
194 {this.renderSharingSuggestion(suggestion)}
203 isSuggestionBoxOpen() {
204 const { suggestions = [] } = this.props;
205 return this.state.suggestionsOpen && suggestions.length > 0;
208 handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
209 const { onFocus = noop } = this.props;
210 this.setState({ suggestionsOpen: true });
214 handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
216 const { onBlur = noop } = this.props;
217 this.setState({ suggestionsOpen: false });
222 handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
223 const { onCreate = noop, onSelect = noop, suggestions = [] } = this.props;
224 const { selectedSuggestionIndex } = this.state;
225 if (event.key === 'Enter') {
226 if (this.isSuggestionBoxOpen() && selectedSuggestionIndex < suggestions.length) {
227 // prevent form submissions when selecting a suggestion
228 event.preventDefault();
229 onSelect(suggestions[selectedSuggestionIndex]);
230 } else if (this.props.value.length > 0) {
236 handleNavigationKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
237 if (key === 'ArrowUp') {
238 this.updateSelectedSuggestionIndex(-1);
239 } else if (key === 'ArrowDown') {
240 this.updateSelectedSuggestionIndex(1);
244 updateSelectedSuggestionIndex(value: -1 | 1) {
245 const { suggestions = [] } = this.props;
246 this.setState(({ selectedSuggestionIndex }) => ({
247 selectedSuggestionIndex: (selectedSuggestionIndex + value) % suggestions.length
252 const { items, onDelete } = this.props;
255 * If input startAdornment prop is not undefined, input's label will stay above the input.
256 * If there is not items, we want the label to go back to placeholder position.
257 * That why we return without a value instead of returning a result of a _map_ which is an empty array.
259 if (items.length === 0) {
265 const tooltip = this.props.renderChipTooltip ? this.props.renderChipTooltip(item) : '';
266 if (tooltip && tooltip.length) {
267 return <span key={index}>
268 <Tooltip title={tooltip}>
270 label={this.renderChipValue(item)}
272 onDelete={onDelete && !this.props.disabled ? (() => onDelete(item, index)) : undefined} />
275 return <span key={index}><Chip
276 label={this.renderChipValue(item)}
277 onDelete={onDelete && !this.props.disabled ? (() => onDelete(item, index)) : undefined} /></span>
283 renderChipValue(value: Value) {
284 const { renderChipValue } = this.props;
285 return renderChipValue ? renderChipValue(value) : JSON.stringify(value);
288 preventBlur = (event: React.MouseEvent<HTMLElement>) => {
289 event.preventDefault();
292 handleClickAway = (event: React.MouseEvent<HTMLElement>) => {
293 if (event.target !== this.inputRef.current) {
294 this.setState({ suggestionsOpen: false });
298 handleSelect(suggestion: Suggestion) {
300 const { onSelect = noop } = this.props;
301 const { current } = this.inputRef;
305 onSelect(suggestion);
309 renderSuggestion(suggestion: Suggestion) {
310 const { renderSuggestion } = this.props;
311 return renderSuggestion
312 ? renderSuggestion(suggestion)
313 : <ListItemText>{JSON.stringify(suggestion)}</ListItemText>;
316 renderSharingSuggestion(suggestion: Suggestion) {
317 if (isGroup(suggestion)) {
318 return <ListItemText>
320 {(suggestion as any).name}
323 return <ListItemText>
325 {`${(suggestion as any).fullName} (${(suggestion as any).username})`}
330 getSuggestionsWidth() {
331 return this.containerRef.current ? this.containerRef.current.offsetWidth : 'auto';
335 type ChipClasses = 'root';
337 const chipStyles: StyleRulesCallback<ChipClasses> = theme => ({
339 marginRight: theme.spacing.unit / 4,
340 height: theme.spacing.unit * 3,
344 const Chip = withStyles(chipStyles)(MuiChip);
346 type PopperClasses = 'root';
348 const popperStyles: StyleRulesCallback<PopperClasses> = theme => ({
350 zIndex: theme.zIndex.modal,
354 const Popper = withStyles(popperStyles)(
355 ({ classes, ...props }: PopperProps & WithStyles<PopperClasses>) =>
356 <MuiPopper {...props} className={classes.root} />
359 type InputClasses = 'root';
361 const inputStyles: StyleRulesCallback<InputClasses> = () => ({
372 const Input = withStyles(inputStyles)(MuiInput);
374 const Paper = withStyles({