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;
22 type CssRules = 'chips' | 'input' | 'inputContainer';
24 const styles: StyleRulesCallback = ({ spacing }) => ({
26 minHeight: spacing.unit * 5,
40 export const ChipsInput = withStyles(styles)(
41 class ChipsInput<Value> extends React.Component<ChipsInputProps<Value> & WithStyles<CssRules>> {
47 filler = React.createRef<HTMLDivElement>();
50 setText = (event: React.ChangeEvent<HTMLInputElement>) => {
51 this.setState({ text: event.target.value });
54 handleKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
55 if (key === 'Enter') {
56 this.createNewValue();
57 } else if (key === 'Backspace') {
58 this.deleteLastValue();
62 createNewValue = () => {
63 if (this.state.text) {
64 const newValue = this.props.createNewValue(this.state.text);
65 this.setState({ text: '' });
66 this.props.onChange([...this.props.value, newValue]);
70 deleteLastValue = () => {
71 if (this.state.text.length === 0 && this.props.value.length > 0) {
72 this.props.onChange(this.props.value.slice(0, -1));
76 updateCursorPosition = () => {
78 clearTimeout(this.timeout);
80 this.timeout = setTimeout(() => this.setState({ ...this.state }));
83 getInputStyles = (): React.CSSProperties => ({
84 width: this.filler.current
85 ? this.filler.current.offsetWidth
87 right: this.filler.current
88 ? `calc(${this.filler.current.offsetWidth}px - 100%)`
94 this.updateCursorPosition();
105 const { classes, value, ...props } = this.props;
106 return <div className={classes.chips}>
110 filler={<div ref={this.filler} />}
116 const { inputProps: InputProps, inputComponent: Input = MuiInput, classes } = this.props;
119 value={this.state.text}
120 onChange={this.setText}
121 onKeyDown={this.handleKeyPress}
123 ...(InputProps && InputProps.inputProps),
124 className: classes.input,
125 style: this.getInputStyles(),
128 className={classes.inputContainer} />;
131 componentDidUpdate(prevProps: ChipsInputProps<Value>) {
132 if (prevProps.value !== this.props.value) {
133 this.updateCursorPosition();
136 componentWillUnmount() {
137 clearTimeout(this.timeout);