101 lines
4.1 KiB
TypeScript
101 lines
4.1 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]}` : '';
|
|
}
|
|
|
|
/**
|
|
* Typed / pasted text -> dd/mm/yyyy as far as it goes. Digits only auto-insert the slashes (0101 -> 01/01); with slashes
|
|
* (or - .) a single-digit day or month is padded as soon as the next separator is typed (1/1/2026 -> 01/01/2026).
|
|
*/
|
|
function mask(raw: string, growing = true): string {
|
|
const clean = raw.replace(/[^\d/.\-]/g, '').replace(/[.\-]/g, '/');
|
|
if (!clean.includes('/')) {
|
|
const d = clean.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)}`;
|
|
}
|
|
const parts = clean.split('/').slice(0, 3);
|
|
const out = parts.map((p, i) => {
|
|
const max = i === 2 ? 4 : 2;
|
|
const v = p.slice(0, max);
|
|
return i < parts.length - 1 && v.length === 1 ? `0${v}` : v; // pad once a later separator exists
|
|
});
|
|
// two digits of the month typed: move on to the year
|
|
if (growing && out.length === 2 && out[1]!.length === 2) out.push('');
|
|
return out.join('/');
|
|
}
|
|
|
|
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, raw.length > text.length);
|
|
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>
|
|
),
|
|
},
|
|
}}
|
|
/>
|
|
);
|
|
}
|