81 lines
2.5 KiB
TypeScript
81 lines
2.5 KiB
TypeScript
import { p as P } from 'web-components'
|
|
|
|
interface DateTimeInputProps {
|
|
value: Date | null
|
|
setValue: (d: Date | null) => void
|
|
showLabels?: boolean
|
|
timeOnly?: boolean
|
|
testID?: string
|
|
}
|
|
|
|
function toDateStr(d: Date | null): string {
|
|
if (!d) return ''
|
|
const y = d.getFullYear()
|
|
const m = String(d.getMonth() + 1).padStart(2, '0')
|
|
const day = String(d.getDate()).padStart(2, '0')
|
|
return `${y}-${m}-${day}`
|
|
}
|
|
|
|
function toTimeStr(d: Date | null): string {
|
|
if (!d) return ''
|
|
return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
|
|
}
|
|
|
|
export default function DateTimeInput({ value, setValue, showLabels = true, timeOnly = false, testID }: DateTimeInputProps) {
|
|
const handleDateChange = (dateStr: string) => {
|
|
if (!dateStr) {
|
|
setValue(null)
|
|
return
|
|
}
|
|
const base = value ? new Date(value) : new Date()
|
|
const [y, m, day] = dateStr.split('-').map((n) => parseInt(n, 10))
|
|
base.setFullYear(y, m - 1, day)
|
|
setValue(base)
|
|
}
|
|
|
|
const handleTimeChange = (timeStr: string) => {
|
|
if (!timeStr) return
|
|
const base = value ? new Date(value) : new Date()
|
|
const [h, min] = timeStr.split(':').map((n) => parseInt(n, 10))
|
|
base.setHours(h, min, 0, 0)
|
|
setValue(base)
|
|
}
|
|
|
|
if (timeOnly) {
|
|
return (
|
|
<div className="w-full mb-4" data-testid={testID}>
|
|
{showLabels ? <P className="text-xs mb-1">Select Time</P> : null}
|
|
<input
|
|
type="time"
|
|
value={toTimeStr(value)}
|
|
onChange={(e) => handleTimeChange(e.target.value)}
|
|
className="w-full rounded border border-gray-300 px-2 py-1 text-sm font-medium text-gray-800"
|
|
/>
|
|
</div>
|
|
)
|
|
}
|
|
|
|
return (
|
|
<div className="w-full flex flex-row items-stretch mb-4" data-testid={testID}>
|
|
<div className="w-1/2">
|
|
{showLabels ? <P className="text-xs mb-1">Select Date</P> : null}
|
|
<input
|
|
type="date"
|
|
value={toDateStr(value)}
|
|
onChange={(e) => handleDateChange(e.target.value)}
|
|
className="w-full rounded border border-gray-300 px-2 py-1 text-sm font-medium text-gray-800"
|
|
/>
|
|
</div>
|
|
<div className="w-2" />
|
|
<div className="w-1/2">
|
|
{showLabels ? <P className="text-xs mb-1">Select Time</P> : null}
|
|
<input
|
|
type="time"
|
|
value={toTimeStr(value)}
|
|
onChange={(e) => handleTimeChange(e.target.value)}
|
|
className="w-full rounded border border-gray-300 px-2 py-1 text-sm font-medium text-gray-800"
|
|
/>
|
|
</div>
|
|
</div>
|
|
)
|
|
}
|