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, Tabs, Tab
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 { TabbedList } from 'components/tabbedList/tabbed-list';
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.renderTabbedSuggestions() : this.renderSuggestions()}
103 {/* {this.props.category === AutocompleteCat.SHARING ? this.renderSharingSuggestions() : this.renderSuggestions()} */}
110 const { label } = this.props;
111 return label && <InputLabel>{label}</InputLabel>;
116 disabled={this.props.disabled}
117 autoFocus={this.props.autofocus}
118 inputRef={this.inputRef}
119 value={this.props.value}
120 startAdornment={this.renderChips()}
121 onFocus={this.handleFocus}
122 onBlur={this.handleBlur}
123 onChange={this.props.onChange}
124 onKeyPress={this.handleKeyPress}
125 onKeyDown={this.handleNavigationKeyPress}
130 return <FormHelperText>{this.props.helperText}</FormHelperText>;
133 renderSuggestions() {
134 const { suggestions = [] } = this.props;
137 open={this.isSuggestionBoxOpen()}
138 anchorEl={this.inputRef.current}
139 key={suggestions.length}>
140 <Paper onMouseDown={this.preventBlur}>
141 <List dense style={{ width: this.getSuggestionsWidth() }}>
143 (suggestion, index) =>
147 onClick={this.handleSelect(suggestion)}
148 selected={index === this.state.selectedSuggestionIndex}>
149 {this.renderSuggestion(suggestion)}
158 renderSharingSuggestions() {
159 const { suggestions = [], classes } = this.props;
160 const users = sortByKey<Suggestion>(suggestions.filter(item => !isGroup(item)), 'fullName');
161 const groups = sortByKey<Suggestion>(suggestions.filter(item => isGroup(item)), 'name');
165 open={this.isSuggestionBoxOpen()}
166 anchorEl={this.inputRef.current}
167 key={suggestions.length}>
168 <Paper onMouseDown={this.preventBlur}>
169 <div className={classes.listSubHeader}>
170 Groups {<span className={classes.numFound}>{groups.length} {groups.length === 1 ? 'match' : 'matches'} found</span>}
172 <List dense className={classes.sharingList} style={{width: this.getSuggestionsWidth()}}>
174 (suggestion, index) =>
177 id={`groups-${index}`}
178 key={`groups-${index}`}
179 onClick={this.handleSelect(suggestion)}>
180 {this.renderSharingSuggestion(suggestion)}
184 <div className={classes.listSubHeader}>
185 Users {<span className={classes.numFound}>{users.length} {users.length === 1 ? 'match' : 'matches'} found</span>}
187 <List dense className={classes.sharingList} style={{width: this.getSuggestionsWidth()}}>
189 (suggestion, index) =>
192 id={`users-${index}`}
193 key={`users-${index}`}
194 onClick={this.handleSelect(suggestion)}>
195 {this.renderSharingSuggestion(suggestion)}
204 renderTabbedSuggestions() {
205 const { suggestions = [] } = this.props;
206 const users = sortByKey<Suggestion>(suggestions.filter(item => !isGroup(item)), 'fullName');
207 const groups = sortByKey<Suggestion>(suggestions.filter(item => isGroup(item)), 'name');
209 const parsedSugggestions = [{label: 'Users', items: users}, {label: 'Groups', items: groups}];
213 open={this.isSuggestionBoxOpen()}
214 anchorEl={this.inputRef.current}
215 key={suggestions.length}
216 style={{ height: '4rem'}}
218 <Paper onMouseDown={this.preventBlur}>
219 <TabbedList tabbedListContents={parsedSugggestions} renderListItem={this.renderSharingSuggestion}/>
225 isSuggestionBoxOpen() {
226 const { suggestions = [] } = this.props;
227 return this.state.suggestionsOpen && suggestions.length > 0;
230 handleFocus = (event: React.FocusEvent<HTMLInputElement>) => {
231 const { onFocus = noop } = this.props;
232 this.setState({ suggestionsOpen: true });
236 handleBlur = (event: React.FocusEvent<HTMLInputElement>) => {
238 const { onBlur = noop } = this.props;
239 this.setState({ suggestionsOpen: false });
244 handleKeyPress = (event: React.KeyboardEvent<HTMLInputElement>) => {
245 const { onCreate = noop, onSelect = noop, suggestions = [] } = this.props;
246 const { selectedSuggestionIndex } = this.state;
247 if (event.key === 'Enter') {
248 if (this.isSuggestionBoxOpen() && selectedSuggestionIndex < suggestions.length) {
249 // prevent form submissions when selecting a suggestion
250 event.preventDefault();
251 onSelect(suggestions[selectedSuggestionIndex]);
252 } else if (this.props.value.length > 0) {
258 handleNavigationKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
259 if (key === 'ArrowUp') {
260 this.updateSelectedSuggestionIndex(-1);
261 } else if (key === 'ArrowDown') {
262 this.updateSelectedSuggestionIndex(1);
266 updateSelectedSuggestionIndex(value: -1 | 1) {
267 const { suggestions = [] } = this.props;
268 this.setState(({ selectedSuggestionIndex }) => ({
269 selectedSuggestionIndex: (selectedSuggestionIndex + value) % suggestions.length
274 const { items, onDelete } = this.props;
277 * If input startAdornment prop is not undefined, input's label will stay above the input.
278 * If there is not items, we want the label to go back to placeholder position.
279 * That why we return without a value instead of returning a result of a _map_ which is an empty array.
281 if (items.length === 0) {
287 const tooltip = this.props.renderChipTooltip ? this.props.renderChipTooltip(item) : '';
288 if (tooltip && tooltip.length) {
289 return <span key={index}>
290 <Tooltip title={tooltip}>
292 label={this.renderChipValue(item)}
294 onDelete={onDelete && !this.props.disabled ? (() => onDelete(item, index)) : undefined} />
297 return <span key={index}><Chip
298 label={this.renderChipValue(item)}
299 onDelete={onDelete && !this.props.disabled ? (() => onDelete(item, index)) : undefined} /></span>
305 renderChipValue(value: Value) {
306 const { renderChipValue } = this.props;
307 return renderChipValue ? renderChipValue(value) : JSON.stringify(value);
310 preventBlur = (event: React.MouseEvent<HTMLElement>) => {
311 event.preventDefault();
314 handleClickAway = (event: React.MouseEvent<HTMLElement>) => {
315 if (event.target !== this.inputRef.current) {
316 this.setState({ suggestionsOpen: false });
320 handleSelect(suggestion: Suggestion) {
322 const { onSelect = noop } = this.props;
323 const { current } = this.inputRef;
327 onSelect(suggestion);
331 renderSuggestion(suggestion: Suggestion) {
332 const { renderSuggestion } = this.props;
333 return renderSuggestion
334 ? renderSuggestion(suggestion)
335 : <ListItemText>{JSON.stringify(suggestion)}</ListItemText>;
338 renderSharingSuggestion(suggestion: Suggestion) {
339 if (isGroup(suggestion)) {
340 return <ListItemText>
341 <Typography noWrap data-cy="sharing-suggestion">
342 {(suggestion as any).name}
345 return <ListItemText>
346 <Typography data-cy="sharing-suggestion">
347 {`${(suggestion as any).fullName} (${(suggestion as any).username})`}
352 getSuggestionsWidth() {
353 return this.containerRef.current ? this.containerRef.current.offsetWidth : 'auto';
357 type ChipClasses = 'root';
359 const chipStyles: StyleRulesCallback<ChipClasses> = theme => ({
361 marginRight: theme.spacing.unit / 4,
362 height: theme.spacing.unit * 3,
366 const Chip = withStyles(chipStyles)(MuiChip);
368 type PopperClasses = 'root';
370 const popperStyles: StyleRulesCallback<PopperClasses> = theme => ({
372 zIndex: theme.zIndex.modal,
376 const Popper = withStyles(popperStyles)(
377 ({ classes, ...props }: PopperProps & WithStyles<PopperClasses>) =>
378 <MuiPopper {...props} className={classes.root} />
381 type InputClasses = 'root';
383 const inputStyles: StyleRulesCallback<InputClasses> = () => ({
394 const Input = withStyles(inputStyles)(MuiInput);
396 const Paper = withStyles({