2020-09-10 18:45:02 +03:00
|
|
|
import React, {
|
|
|
|
ChangeEventHandler,
|
|
|
|
Component,
|
|
|
|
FocusEventHandler,
|
|
|
|
KeyboardEventHandler,
|
|
|
|
} from 'react';
|
2018-12-22 17:20:04 +03:00
|
|
|
import PropTypes from 'prop-types';
|
|
|
|
import classnames from 'classnames';
|
|
|
|
|
2020-09-10 18:45:02 +03:00
|
|
|
interface State {
|
|
|
|
text: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
interface Props {
|
|
|
|
onSave: (text: string) => void;
|
|
|
|
text?: string;
|
|
|
|
placeholder?: string;
|
|
|
|
editing?: boolean;
|
|
|
|
newTodo?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export default class TodoTextInput extends Component<Props, State> {
|
2018-12-22 17:20:04 +03:00
|
|
|
static propTypes = {
|
|
|
|
onSave: PropTypes.func.isRequired,
|
|
|
|
text: PropTypes.string,
|
|
|
|
placeholder: PropTypes.string,
|
|
|
|
editing: PropTypes.bool,
|
2020-08-08 23:26:39 +03:00
|
|
|
newTodo: PropTypes.bool,
|
2018-12-22 17:20:04 +03:00
|
|
|
};
|
|
|
|
|
|
|
|
static defaultProps = {
|
|
|
|
text: '',
|
|
|
|
placeholder: '',
|
|
|
|
editing: false,
|
2020-08-08 23:26:39 +03:00
|
|
|
newTodo: false,
|
2018-12-22 17:20:04 +03:00
|
|
|
};
|
|
|
|
|
2020-09-10 18:45:02 +03:00
|
|
|
state = {
|
|
|
|
text: this.props.text || '',
|
|
|
|
};
|
2018-12-22 17:20:04 +03:00
|
|
|
|
2020-09-10 18:45:02 +03:00
|
|
|
handleSubmit: KeyboardEventHandler<HTMLInputElement> = (e) => {
|
|
|
|
const text = e.currentTarget.value.trim();
|
2018-12-22 17:20:04 +03:00
|
|
|
if (e.which === 13) {
|
|
|
|
this.props.onSave(text);
|
|
|
|
if (this.props.newTodo) {
|
|
|
|
this.setState({ text: '' });
|
|
|
|
}
|
|
|
|
}
|
2019-01-10 21:51:14 +03:00
|
|
|
};
|
2018-12-22 17:20:04 +03:00
|
|
|
|
2020-09-10 18:45:02 +03:00
|
|
|
handleChange: ChangeEventHandler<HTMLInputElement> = (e) => {
|
2018-12-22 17:20:04 +03:00
|
|
|
this.setState({ text: e.target.value });
|
2019-01-10 21:51:14 +03:00
|
|
|
};
|
2018-12-22 17:20:04 +03:00
|
|
|
|
2020-09-10 18:45:02 +03:00
|
|
|
handleBlur: FocusEventHandler<HTMLInputElement> = (e) => {
|
2018-12-22 17:20:04 +03:00
|
|
|
if (!this.props.newTodo) {
|
|
|
|
this.props.onSave(e.target.value);
|
|
|
|
}
|
2019-01-10 21:51:14 +03:00
|
|
|
};
|
2018-12-22 17:20:04 +03:00
|
|
|
|
|
|
|
render() {
|
|
|
|
return (
|
|
|
|
<input
|
2019-01-10 21:51:14 +03:00
|
|
|
className={classnames({
|
|
|
|
edit: this.props.editing,
|
2020-08-08 23:26:39 +03:00
|
|
|
'new-todo': this.props.newTodo,
|
2019-01-10 21:51:14 +03:00
|
|
|
})}
|
2019-01-10 20:23:33 +03:00
|
|
|
type="text"
|
2018-12-22 17:20:04 +03:00
|
|
|
placeholder={this.props.placeholder}
|
2020-08-01 22:40:19 +03:00
|
|
|
autoFocus={true}
|
2018-12-22 17:20:04 +03:00
|
|
|
value={this.state.text}
|
|
|
|
onBlur={this.handleBlur}
|
|
|
|
onChange={this.handleChange}
|
|
|
|
onKeyDown={this.handleSubmit}
|
|
|
|
/>
|
|
|
|
);
|
|
|
|
}
|
|
|
|
}
|