Update input components

This commit is contained in:
2026-02-14 16:24:04 -05:00
parent f40845723d
commit aaa15b1cfc
6 changed files with 161 additions and 32 deletions

View File

@@ -1,15 +1,33 @@
import type { DateInputProps } from "$/types/InputTypes";
import clsx from "clsx";
import moment from "moment";
import type { ChangeEvent } from "react";
export default function TimeInput({
id,
className,
defaultValue,
step = 60,
value,
onChange
}: DateInputProps){
onChange,
...inputProps
}: Readonly<DateInputProps>){
const changeTime = (e: ChangeEvent<HTMLInputElement>) => {
const match = new RegExp(/^(\d+):(\d+)(?::(\d+)(?:\.(\d+))?)?$/).exec(e.target.value);
if(!match){
onChange(undefined);
return;
}
const [ , h, m, s = "0", ms = "0"] = match;
const newDate = new Date();
newDate.setHours(Number(h), Number(m), Number(s), Number(ms));
onChange(Number.isNaN(newDate) ? undefined : newDate);
}
return (
<input
type="time"
@@ -18,9 +36,32 @@ export default function TimeInput({
"border rounded-lg px-2 py-1 outline-none",
className
)}
defaultValue={defaultValue ? moment(defaultValue).format("YYYY-MM-DDTHH:mm") : undefined}
value={value ? moment(value).format("YYYY-MM-DDTHH:mm") : undefined}
onChange={(e) => onChange?.(new Date(moment(e.target.value, "YYYY-MM-DDTHH:mm").toDate()))}
value={formatTime(value, step)}
onChange={changeTime}
step={step}
{...inputProps}
/>
);
}
function formatTime(date: Date | undefined, step: number){
if(!date || Number.isNaN(date.getTime())){
return "";
}
const h = String(date.getHours()).padStart(2, "0");
const m = String(date.getMinutes()).padStart(2, "0");
const s = String(date.getSeconds()).padStart(2, "0");
const ms = String(date.getMilliseconds()).padStart(3, "0");
let time = `${h}:${m}`;
if(step < 60){
time += `:${s}`;
}
if(step < 1){
time += `.${ms}`;
}
return time;
}