import * as React from 'react'; import I18n from 'i18n-js'; import Button from '../../shared/Button'; import padStart from '../../../helpers/padStart'; interface Props { mode: 'create' | 'update'; id?: number; name?: string; color?: string; handleSubmit?( name: string, color: string, onSuccess: Function, ): void; handleUpdate?( id: number, name: string, color: string, ): void; } interface State { name: string; color: string; } class PostStatusForm extends React.Component { initialState: State = { name: '', color: this.getRandomColor(), }; constructor(props: Props) { super(props); this.state = this.props.mode === 'create' ? this.initialState : { name: this.props.name, color: this.props.color, }; this.onSubmit = this.onSubmit.bind(this); } getRandomColor() { return '#' + padStart((Math.random() * 0xFFFFFF << 0).toString(16), 6, '0'); } isFormValid() { return this.state.name && this.state.name.length > 0 && this.state.color && this.state.color.length === 7; } onNameChange(nameText: string) { this.setState({ name: nameText, }); } onColorChange(colorText: string) { this.setState({ color: colorText, }); } onSubmit() { if (this.props.mode === 'create') { this.props.handleSubmit( this.state.name, this.state.color, () => this.setState({...this.initialState, color: this.getRandomColor()}), ); } else { this.props.handleUpdate(this.props.id, this.state.name, this.state.color); } } render() { const {mode} = this.props; const {name, color} = this.state; return (
this.onNameChange(e.target.value)} className="form-control" /> this.onColorChange(e.target.value)} className="form-control postStatusColorInput" />
); } } export default PostStatusForm;