NTP_V2/web/src/components/DateField.tsx

86 lines
3.4 KiB
TypeScript

import { useEffect, useRef, useState } from 'react';
import { IconButton, InputAdornment, TextField, type TextFieldProps } from '@mui/material';
import CalendarMonthIcon from '@mui/icons-material/CalendarMonth';
/** yyyy-mm-dd (or an ISO date/time) -> dd/mm/yyyy ('' when not a date). */
export function isoToDisplay(v: unknown): string {
const m = /^(\d{4})-(\d{2})-(\d{2})/.exec(String(v ?? ''));
return m ? `${m[3]}/${m[2]}/${m[1]}` : '';
}
/** dd/mm/yyyy -> yyyy-mm-dd, or '' when incomplete / not a real calendar date. */
function displayToIso(text: string): string {
const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(text);
if (!m) return '';
const d = Number(m[1]), mo = Number(m[2]), y = Number(m[3]);
const dt = new Date(y, mo - 1, d);
return dt.getFullYear() === y && dt.getMonth() === mo - 1 && dt.getDate() === d ? `${m[3]}-${m[2]}-${m[1]}` : '';
}
/** Digits typed so far -> dd, dd/mm, dd/mm/yyyy. */
function mask(raw: string): string {
const d = raw.replace(/\D/g, '').slice(0, 8);
if (d.length <= 2) return d;
if (d.length <= 4) return `${d.slice(0, 2)}/${d.slice(2)}`;
return `${d.slice(0, 2)}/${d.slice(2, 4)}/${d.slice(4)}`;
}
type Props = Omit<TextFieldProps, 'value' | 'onChange' | 'type'> & {
/** yyyy-mm-dd (the form / API format) */
value: string;
onChange: (value: string) => void;
};
/**
* Date input that always reads and shows dd/mm/yyyy (the native date input follows the browser language).
* The value going in and out is yyyy-mm-dd; it is '' until a complete, valid date is typed. A calendar button opens the picker.
*/
export function DateField({ value, onChange, slotProps, disabled, ...rest }: Props) {
const [text, setText] = useState(isoToDisplay(value));
const picker = useRef<HTMLInputElement>(null);
// follow the outside value (form reset, prefill) without fighting the user's typing
useEffect(() => {
if (displayToIso(text) !== (value ? value.slice(0, 10) : '')) setText(isoToDisplay(value));
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [value]);
const typed = (raw: string) => {
const next = mask(raw);
setText(next);
onChange(displayToIso(next));
};
const inputSlot = (slotProps as { htmlInput?: object } | undefined)?.htmlInput;
return (
<TextField
{...rest}
disabled={disabled}
value={text}
onChange={(e) => typed(e.target.value)}
placeholder="dd/mm/yyyy"
slotProps={{
...slotProps,
inputLabel: { shrink: true },
htmlInput: { ...inputSlot, dir: 'ltr', inputMode: 'numeric', maxLength: 10, style: { textAlign: 'start' } },
input: {
endAdornment: (
<InputAdornment position="end">
<IconButton size="small" edge="end" tabIndex={-1} disabled={disabled} onClick={() => picker.current?.showPicker?.()}>
<CalendarMonthIcon fontSize="small" />
</IconButton>
{/* the native picker only supplies the calendar; its value is converted to the text above */}
<input
ref={picker} type="date" tabIndex={-1} aria-hidden
value={value ? value.slice(0, 10) : ''}
onChange={(e) => { setText(isoToDisplay(e.target.value)); onChange(e.target.value); }}
style={{ position: 'absolute', opacity: 0, width: 0, height: 0, pointerEvents: 'none' }}
/>
</InputAdornment>
),
},
}}
/>
);
}