1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
5 import * as React from 'react';
6 import { Chips } from '~/components/chips/chips';
7 import { Input as MuiInput, withStyles, WithStyles } from '@material-ui/core';
8 import { StyleRulesCallback } from '@material-ui/core/styles';
9 import { InputProps } from '@material-ui/core/Input';
11 interface ChipsInputProps<Value> {
13 getLabel?: (value: Value) => string;
14 onChange: (value: Value[]) => void;
15 createNewValue: (value: string) => Value;
16 inputComponent?: React.ComponentType<InputProps>;
17 inputProps?: InputProps;
20 type CssRules = 'chips' | 'input' | 'inputContainer';
22 const styles: StyleRulesCallback = ({ spacing }) => ({
24 minHeight: spacing.unit * 5,
38 export const ChipsInput = withStyles(styles)(
39 class ChipsInput<Value> extends React.Component<ChipsInputProps<Value> & WithStyles<CssRules>> {
45 filler = React.createRef<HTMLDivElement>();
48 setText = (event: React.ChangeEvent<HTMLInputElement>) => {
49 this.setState({ text: event.target.value });
52 handleKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
53 if (key === 'Enter') {
54 this.createNewValue();
55 } else if (key === 'Backspace') {
56 this.deleteLastValue();
60 createNewValue = () => {
61 if (this.state.text) {
62 const newValue = this.props.createNewValue(this.state.text);
63 this.setState({ text: '' });
64 this.props.onChange([...this.props.value, newValue]);
68 deleteLastValue = () => {
69 if (this.state.text.length === 0 && this.props.value.length > 0) {
70 this.props.onChange(this.props.value.slice(0, -1));
74 updateCursorPosition = () => {
76 clearTimeout(this.timeout);
78 this.timeout = setTimeout(() => this.setState({ ...this.state }));
81 getInputStyles = (): React.CSSProperties => ({
82 width: this.filler.current
83 ? this.filler.current.offsetWidth
85 right: this.filler.current
86 ? `calc(${this.filler.current.offsetWidth}px - 100%)`
92 this.updateCursorPosition();
103 const { classes, value, ...props } = this.props;
104 return <div className={classes.chips}>
108 filler={<div ref={this.filler} />}
114 const { inputProps: InputProps, inputComponent: Input = MuiInput, classes } = this.props;
117 value={this.state.text}
118 onChange={this.setText}
119 onKeyDown={this.handleKeyPress}
121 ...(InputProps && InputProps.inputProps),
122 className: classes.input,
123 style: this.getInputStyles(),
126 className={classes.inputContainer} />;
129 componentDidUpdate(prevProps: ChipsInputProps<Value>) {
130 if (prevProps.value !== this.props.value) {
131 this.updateCursorPosition();
134 componentWillUnmount() {
135 clearTimeout(this.timeout);