import { useRef, useState } from 'react'; import { IconButton, InputAdornment, TextField, type TextFieldProps } from '@mui/material'; import CalendarMonthOutlined from '@mui/icons-material/CalendarMonthOutlined'; import { useAuth } from '../auth/AuthContext'; import { isRtl, useUi } from '../i18n'; const isoToDisplay = (iso: string) => (/^\d{4}-\d{2}-\d{2}$/.test(iso) ? `${iso.slice(8, 10)}/${iso.slice(5, 7)}/${iso.slice(0, 4)}` : ''); /** keeps only digits and puts the slashes in while typing: 25122026 -> 25/12/2026 */ const mask = (raw: string) => { const d = raw.replace(/\D/g, '').slice(0, 8); return [d.slice(0, 2), d.slice(2, 4), d.slice(4, 8)].filter(Boolean).join('/'); }; const displayToIso = (display: string) => { const m = /^(\d{2})\/(\d{2})\/(\d{4})$/.exec(display); if (!m) return ''; const [, dd, mm, yyyy] = m; const date = new Date(Number(yyyy), Number(mm) - 1, Number(dd)); const real = date.getFullYear() === Number(yyyy) && date.getMonth() === Number(mm) - 1 && date.getDate() === Number(dd); return real ? `${yyyy}-${mm}-${dd}` : ''; }; /** * A date box that reads dd/mm/yyyy in the app's own language. The browser's native date input shows its own * placeholder ("mm/dd/yyyy") in the browser's language, which cannot be changed from the page, so the text is * typed here and the native calendar is only opened from the icon. `value` and `onChange` use ISO (yyyy-mm-dd). */ export function DateField({ value, onChange, ...rest }: { value: string; onChange: (iso: string) => void } & Omit) { const { lang } = useAuth(); const ui = useUi(); const [typed, setTyped] = useState(null); const native = useRef(null); const shown = typed ?? isoToDisplay(value); const placeholder = ui('datePlaceholder'); return ( { const text = mask(e.target.value); setTyped(text); // a complete, real date is committed at once; an incomplete one clears the value until it is finished onChange(displayToIso(text)); }} onBlur={(e) => { setTyped(null); rest.onBlur?.(e); }} slotProps={{ ...rest.slotProps, inputLabel: { shrink: true, ...(rest.slotProps as { inputLabel?: object } | undefined)?.inputLabel }, htmlInput: { inputMode: 'numeric', dir: 'ltr', style: { textAlign: isRtl(lang) ? 'right' : 'left' }, maxLength: 10 }, input: { endAdornment: ( { const el = native.current; if (!el) return; el.value = value; // showPicker is missing in older browsers; focusing is the fallback if (typeof el.showPicker === 'function') el.showPicker(); else el.click(); }} > { setTyped(null); onChange(e.target.value); }} /> ), }, }} /> ); }