1 | import React from "react";
|
2 | import { useDataObject } from "./context";
|
3 |
|
4 | function getTimeValueFromDate(date) {
|
5 | if (!date) return "";
|
6 |
|
7 | let hours = date.getHours();
|
8 | let minutes = date.getMinutes();
|
9 |
|
10 | hours = String(hours).padStart(2, "0");
|
11 | minutes = String(minutes).padStart(2, "0");
|
12 |
|
13 | return date ? hours + ":" + minutes : "";
|
14 | }
|
15 |
|
16 | function TimepickerBase({ className, field, ...rest }, ref) {
|
17 | const { currentRow, dataObject } = useDataObject();
|
18 |
|
19 | function updateField(evt) {
|
20 | let date = new Date(currentRow[field] || Date.now());
|
21 | let timePart = evt.target.value;
|
22 |
|
23 | if (timePart) {
|
24 | let [hours, minutes] = timePart.split(":");
|
25 | date.setHours(hours);
|
26 | date.setMinutes(minutes);
|
27 |
|
28 | dataObject.currentRow(field, date);
|
29 | } else {
|
30 | dataObject.currentRow(field, null);
|
31 | }
|
32 | }
|
33 |
|
34 | return (
|
35 | <input
|
36 | className={className}
|
37 | onChange={updateField}
|
38 | ref={ref}
|
39 | type="time"
|
40 | value={getTimeValueFromDate(currentRow[field])}
|
41 | {...rest}
|
42 | />
|
43 | );
|
44 | }
|
45 |
|
46 | export const Timepicker = React.forwardRef(TimepickerBase);
|