75 lines
1.7 KiB
TypeScript
Raw Normal View History

2018-08-06 12:04:08 +03:00
import * as moment from "moment";
import * as React from "react";
import { Input, InputOnChangeData } from "semantic-ui-react";
import { TimeOfDay } from "@common/sprinklersRpc";
const HTML_TIME_INPUT_FORMAT = "HH:mm";
function timeOfDayToHtmlDateInput(tod: TimeOfDay): string {
2018-09-02 02:57:55 -06:00
return moment(tod).format(HTML_TIME_INPUT_FORMAT);
2018-08-06 12:04:08 +03:00
}
export interface TimeInputProps {
2018-09-02 02:57:55 -06:00
value: TimeOfDay;
index: number;
onChange: (newValue: TimeOfDay, index: number) => void;
2018-08-06 12:04:08 +03:00
}
export interface TimeInputState {
2018-09-02 02:57:55 -06:00
rawValue: string;
lastTime: TimeOfDay | null;
2018-08-06 12:04:08 +03:00
}
2018-09-02 02:57:55 -06:00
export default class TimeInput extends React.Component<
TimeInputProps,
TimeInputState
> {
static getDerivedStateFromProps(
props: TimeInputProps,
state: TimeInputState
): Partial<TimeInputState> {
if (!TimeOfDay.equals(props.value, state.lastTime)) {
return {
lastTime: props.value,
rawValue: timeOfDayToHtmlDateInput(props.value)
};
2018-08-06 12:04:08 +03:00
}
2018-09-02 02:57:55 -06:00
return {};
}
2018-08-06 12:10:34 +03:00
2018-09-02 02:57:55 -06:00
constructor(p: any) {
super(p);
this.state = { rawValue: "", lastTime: null };
}
2018-08-06 12:10:34 +03:00
2018-09-02 02:57:55 -06:00
render() {
return (
<Input
type="time"
value={this.state.rawValue}
onChange={this.onChange}
onBlur={this.onBlur}
/>
);
}
2018-08-06 12:10:34 +03:00
2018-09-02 02:57:55 -06:00
private onChange = (
e: React.SyntheticEvent<HTMLInputElement>,
data: InputOnChangeData
) => {
this.setState({
rawValue: data.value
});
};
2018-08-06 12:10:34 +03:00
2018-09-02 02:57:55 -06:00
private onBlur: React.FocusEventHandler<HTMLInputElement> = e => {
const m = moment(this.state.rawValue, HTML_TIME_INPUT_FORMAT);
if (m.isValid()) {
this.props.onChange(TimeOfDay.fromMoment(m), this.props.index);
} else {
this.setState({ rawValue: timeOfDayToHtmlDateInput(this.props.value) });
2018-08-06 12:10:34 +03:00
}
2018-09-02 02:57:55 -06:00
};
2018-08-06 12:10:34 +03:00
}