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;
23 type CssRules = 'chips' | 'input' | 'inputContainer';
25 const styles: StyleRulesCallback = ({ spacing }) => ({
27 minHeight: spacing.unit * 5,
41 export const ChipsInput = withStyles(styles)(
42 class ChipsInput<Value> extends React.Component<ChipsInputProps<Value> & WithStyles<CssRules>> {
48 filler = React.createRef<HTMLDivElement>();
51 setText = (event: React.ChangeEvent<HTMLInputElement>) => {
52 this.setState({ text: event.target.value });
55 handleKeyPress = ({ key }: React.KeyboardEvent<HTMLInputElement>) => {
56 if (key === 'Enter') {
57 this.createNewValue();
58 } else if (key === 'Backspace') {
59 this.deleteLastValue();
63 createNewValue = () => {
64 if (this.state.text) {
65 const newValue = this.props.createNewValue(this.state.text);
66 this.setState({ text: '' });
67 this.props.onChange([...this.props.values, newValue]);
71 deleteLastValue = () => {
72 if (this.state.text.length === 0 && this.props.values.length > 0) {
73 this.props.onChange(this.props.values.slice(0, -1));
77 updateCursorPosition = () => {
79 clearTimeout(this.timeout);
81 this.timeout = setTimeout(() => this.setState({ ...this.state }));
84 getInputStyles = (): React.CSSProperties => ({
85 width: this.filler.current
86 ? this.filler.current.offsetWidth
88 right: this.filler.current
89 ? `calc(${this.filler.current.offsetWidth}px - 100%)`
95 this.updateCursorPosition();
106 const { classes, ...props } = this.props;
107 return <div className={classes.chips}>
110 clickable={!props.disabled}
111 filler={<div ref={this.filler} />}
117 const { inputProps: InputProps, inputComponent: Input = MuiInput, classes } = this.props;
120 value={this.state.text}
121 onChange={this.setText}
122 disabled={this.props.disabled}
123 onKeyDown={this.handleKeyPress}
125 ...(InputProps && InputProps.inputProps),
126 className: classes.input,
127 style: this.getInputStyles(),
130 className={classes.inputContainer} />;
133 componentDidUpdate(prevProps: ChipsInputProps<Value>) {
134 if (prevProps.values !== this.props.values) {
135 this.updateCursorPosition();
138 componentWillUnmount() {
139 clearTimeout(this.timeout);