400 lines
15 KiB
TypeScript
400 lines
15 KiB
TypeScript
import * as DialogPrimitive from "@radix-ui/react-dialog";
|
|
import { CalendarDays, ChevronLeft, ChevronRight } from "lucide-react";
|
|
import { useEffect, useId, useRef, useState } from "react";
|
|
|
|
import { Button } from "@/shared/ui/button";
|
|
import { cn } from "@/shared/ui/cn";
|
|
import { Dialog, DialogPortal, DialogTitle, DialogTrigger } from "@/shared/ui/dialog";
|
|
import { FieldSelect } from "@/shared/ui/field-select";
|
|
import { Input } from "@/shared/ui/input";
|
|
|
|
export interface DateTimeFieldProps {
|
|
label: string;
|
|
value: string;
|
|
onChange: (value: string) => void;
|
|
disabled?: boolean;
|
|
}
|
|
|
|
interface DateTimeParts {
|
|
year: number;
|
|
month: number;
|
|
day: number;
|
|
hour: number;
|
|
minute: number;
|
|
}
|
|
|
|
const MONTH_OPTIONS = Array.from({ length: 12 }, (_, index) => ({
|
|
value: String(index + 1),
|
|
label: `${index + 1}月`
|
|
}));
|
|
const HOUR_OPTIONS = Array.from({ length: 24 }, (_, hour) => ({
|
|
value: pad(hour),
|
|
label: pad(hour)
|
|
}));
|
|
const MINUTE_OPTIONS = Array.from({ length: 60 }, (_, minute) => ({
|
|
value: pad(minute),
|
|
label: pad(minute)
|
|
}));
|
|
const WEEKDAYS = ["一", "二", "三", "四", "五", "六", "日"];
|
|
|
|
function pad(value: number) {
|
|
return String(value).padStart(2, "0");
|
|
}
|
|
|
|
function daysInMonth(year: number, month: number) {
|
|
const date = new Date(0);
|
|
date.setHours(12, 0, 0, 0);
|
|
date.setFullYear(year, month, 0);
|
|
return date.getDate();
|
|
}
|
|
|
|
function calendarDate(year: number, monthIndex: number, day: number) {
|
|
const date = new Date(0);
|
|
date.setHours(12, 0, 0, 0);
|
|
date.setFullYear(year, monthIndex, day);
|
|
return date;
|
|
}
|
|
|
|
function isValidParts(parts: DateTimeParts) {
|
|
return (
|
|
Number.isInteger(parts.year) &&
|
|
parts.year >= 1 &&
|
|
parts.year <= 9999 &&
|
|
parts.month >= 1 &&
|
|
parts.month <= 12 &&
|
|
parts.day >= 1 &&
|
|
parts.day <= daysInMonth(parts.year, parts.month) &&
|
|
parts.hour >= 0 &&
|
|
parts.hour <= 23 &&
|
|
parts.minute >= 0 &&
|
|
parts.minute <= 59
|
|
);
|
|
}
|
|
|
|
function parseDateTimeValue(value: string): DateTimeParts | null {
|
|
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})$/.exec(value);
|
|
if (!match) return null;
|
|
const parts = {
|
|
year: Number(match[1]),
|
|
month: Number(match[2]),
|
|
day: Number(match[3]),
|
|
hour: Number(match[4]),
|
|
minute: Number(match[5])
|
|
};
|
|
return isValidParts(parts) ? parts : null;
|
|
}
|
|
|
|
function formatValue(parts: DateTimeParts) {
|
|
return `${String(parts.year).padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)}T${pad(parts.hour)}:${pad(parts.minute)}`;
|
|
}
|
|
|
|
function todayParts(): DateTimeParts {
|
|
const date = new Date();
|
|
return {
|
|
year: date.getFullYear(),
|
|
month: date.getMonth() + 1,
|
|
day: date.getDate(),
|
|
hour: date.getHours(),
|
|
minute: date.getMinutes()
|
|
};
|
|
}
|
|
|
|
function displayValue(value: string) {
|
|
const parts = parseDateTimeValue(value);
|
|
return parts
|
|
? `${String(parts.year).padStart(4, "0")}-${pad(parts.month)}-${pad(parts.day)} ${pad(parts.hour)}:${pad(parts.minute)}`
|
|
: value || "请选择日期和时间";
|
|
}
|
|
|
|
function sameDay(parts: DateTimeParts, date: Date) {
|
|
return (
|
|
parts.year === date.getFullYear() &&
|
|
parts.month === date.getMonth() + 1 &&
|
|
parts.day === date.getDate()
|
|
);
|
|
}
|
|
|
|
function moveDay(parts: DateTimeParts, amount: number): DateTimeParts {
|
|
const date = calendarDate(parts.year, parts.month - 1, parts.day + amount);
|
|
const year = date.getFullYear();
|
|
if (year < 1 || year > 9999) return parts;
|
|
return { ...parts, year, month: date.getMonth() + 1, day: date.getDate() };
|
|
}
|
|
|
|
export function DateTimeField({ label, value, onChange, disabled = false }: DateTimeFieldProps) {
|
|
const id = useId();
|
|
const [open, setOpen] = useState(false);
|
|
const [draft, setDraft] = useState<DateTimeParts>(
|
|
() => parseDateTimeValue(value) ?? todayParts()
|
|
);
|
|
const [yearText, setYearText] = useState(String(draft.year));
|
|
const [sourceInvalid, setSourceInvalid] = useState(Boolean(value && !parseDateTimeValue(value)));
|
|
const selectedDayRef = useRef<HTMLButtonElement>(null);
|
|
const focusDayAfterNavigation = useRef(false);
|
|
const validYear = /^\d{1,4}$/.test(yearText) && Number(yearText) >= 1;
|
|
const canConfirm = !disabled && !sourceInvalid && validYear && isValidParts(draft);
|
|
|
|
const resetDraft = (nextValue: string) => {
|
|
const parsed = parseDateTimeValue(nextValue);
|
|
const next = parsed ?? todayParts();
|
|
setDraft(next);
|
|
setYearText(String(next.year));
|
|
setSourceInvalid(Boolean(nextValue && !parsed));
|
|
};
|
|
|
|
useEffect(() => {
|
|
if (open) resetDraft(value);
|
|
}, [open, value]);
|
|
|
|
useEffect(() => {
|
|
if (!disabled) return;
|
|
setOpen(false);
|
|
}, [disabled]);
|
|
|
|
useEffect(() => {
|
|
if (!focusDayAfterNavigation.current) return;
|
|
focusDayAfterNavigation.current = false;
|
|
selectedDayRef.current?.focus();
|
|
}, [draft.year, draft.month, draft.day]);
|
|
|
|
const updateDraft = (next: DateTimeParts) => {
|
|
setDraft(next);
|
|
setYearText(String(next.year));
|
|
setSourceInvalid(false);
|
|
};
|
|
|
|
const changeMonth = (amount: number) => {
|
|
if (
|
|
(amount < 0 && draft.year === 1 && draft.month === 1) ||
|
|
(amount > 0 && draft.year === 9999 && draft.month === 12)
|
|
)
|
|
return;
|
|
const date = calendarDate(draft.year, draft.month - 1 + amount, 1);
|
|
const nextYear = date.getFullYear();
|
|
const nextMonth = date.getMonth() + 1;
|
|
updateDraft({
|
|
...draft,
|
|
year: nextYear,
|
|
month: nextMonth,
|
|
day: Math.min(draft.day, daysInMonth(nextYear, nextMonth))
|
|
});
|
|
};
|
|
|
|
const firstWeekday = (calendarDate(draft.year, draft.month - 1, 1).getDay() + 6) % 7;
|
|
const dayCount = daysInMonth(draft.year, draft.month);
|
|
const today = new Date();
|
|
|
|
return (
|
|
<div className="min-w-0">
|
|
<label id={`${id}-label`} className="mb-1 block text-xs font-medium text-slate-600">
|
|
{label}
|
|
</label>
|
|
<Dialog
|
|
open={open}
|
|
onOpenChange={(nextOpen) => {
|
|
if (disabled && nextOpen) return;
|
|
setOpen(nextOpen);
|
|
}}
|
|
>
|
|
<DialogTrigger asChild>
|
|
<button
|
|
type="button"
|
|
disabled={disabled}
|
|
aria-labelledby={`${id}-label`}
|
|
aria-describedby={`${id}-value`}
|
|
className="flex h-10 w-full min-w-0 items-center gap-2 rounded-lg border border-slate-200 bg-white px-3 text-left text-sm tabular-nums text-slate-800 shadow-xs transition-[border-color,box-shadow,scale] duration-150 [@media(hover:hover)]:hover:border-slate-300 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-500/30 active:scale-[0.99] motion-reduce:transition-none motion-reduce:active:scale-100 disabled:cursor-not-allowed disabled:opacity-50"
|
|
>
|
|
<CalendarDays className="size-4 shrink-0 text-slate-400" aria-hidden="true" />
|
|
<span id={`${id}-value`} className={cn("min-w-0 truncate", !value && "text-slate-400")}>
|
|
{displayValue(value)}
|
|
</span>
|
|
</button>
|
|
</DialogTrigger>
|
|
<DialogPortal>
|
|
<DialogPrimitive.Overlay className="fixed inset-0 z-[80] bg-slate-950/20 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0" />
|
|
<DialogPrimitive.Content
|
|
aria-describedby={undefined}
|
|
className="fixed left-1/2 top-1/2 z-[85] max-h-[calc(100dvh-1.5rem)] w-[352px] max-w-[calc(100vw-1.5rem)] -translate-x-1/2 -translate-y-1/2 overflow-y-auto rounded-2xl border border-slate-200 bg-white p-4 shadow-[0_20px_60px_rgba(15,23,42,0.22)] outline-hidden data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
|
onOpenAutoFocus={(event) => {
|
|
if (sourceInvalid) return;
|
|
event.preventDefault();
|
|
requestAnimationFrame(() => selectedDayRef.current?.focus());
|
|
}}
|
|
>
|
|
<DialogTitle className="pr-8 text-base text-slate-900">选择{label}</DialogTitle>
|
|
<div className="mt-3 flex min-w-0 items-end gap-2">
|
|
<FieldSelect
|
|
label="月份"
|
|
value={String(draft.month)}
|
|
options={MONTH_OPTIONS}
|
|
onValueChange={(month) => {
|
|
const nextMonth = Number(month);
|
|
updateDraft({
|
|
...draft,
|
|
month: nextMonth,
|
|
day: Math.min(draft.day, daysInMonth(draft.year, nextMonth))
|
|
});
|
|
}}
|
|
/>
|
|
<label className="min-w-0 flex-1 text-xs font-medium text-slate-600">
|
|
年份
|
|
<Input
|
|
type="text"
|
|
inputMode="numeric"
|
|
value={yearText}
|
|
aria-invalid={!validYear}
|
|
className="mt-1 h-10 rounded-lg border-slate-200 bg-white text-sm tabular-nums"
|
|
onChange={(event) => {
|
|
const nextText = event.target.value.replace(/\D/g, "").slice(0, 4);
|
|
setYearText(nextText);
|
|
const year = Number(nextText);
|
|
if (year >= 1) {
|
|
setDraft((current) => ({
|
|
...current,
|
|
year,
|
|
day: Math.min(current.day, daysInMonth(year, current.month))
|
|
}));
|
|
setSourceInvalid(false);
|
|
}
|
|
}}
|
|
/>
|
|
</label>
|
|
</div>
|
|
<div className="mt-3 flex items-center justify-between">
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
aria-label="上个月"
|
|
disabled={draft.year === 1 && draft.month === 1}
|
|
onClick={() => changeMonth(-1)}
|
|
>
|
|
<ChevronLeft />
|
|
</Button>
|
|
<span className="text-sm font-semibold tabular-nums text-slate-800">
|
|
{yearText || "----"}年 {draft.month}月
|
|
</span>
|
|
<Button
|
|
type="button"
|
|
variant="ghost"
|
|
size="icon-sm"
|
|
aria-label="下个月"
|
|
disabled={draft.year === 9999 && draft.month === 12}
|
|
onClick={() => changeMonth(1)}
|
|
>
|
|
<ChevronRight />
|
|
</Button>
|
|
</div>
|
|
<div
|
|
className="mt-2 grid grid-cols-7 text-center text-[11px] font-medium text-slate-400"
|
|
aria-hidden="true"
|
|
>
|
|
{WEEKDAYS.map((weekday) => (
|
|
<span key={weekday} className="py-1">
|
|
{weekday}
|
|
</span>
|
|
))}
|
|
</div>
|
|
<div
|
|
role="grid"
|
|
aria-label={`${draft.year}年${draft.month}月`}
|
|
className="grid grid-cols-7 gap-1"
|
|
>
|
|
{Array.from({ length: firstWeekday }, (_, index) => (
|
|
<span key={`blank-${index}`} />
|
|
))}
|
|
{Array.from({ length: dayCount }, (_, index) => {
|
|
const day = index + 1;
|
|
const selected = day === draft.day;
|
|
const isToday = sameDay({ ...draft, day }, today);
|
|
return (
|
|
<button
|
|
key={day}
|
|
ref={selected ? selectedDayRef : undefined}
|
|
type="button"
|
|
role="gridcell"
|
|
tabIndex={selected ? 0 : -1}
|
|
aria-selected={selected}
|
|
aria-label={`${draft.year}年${draft.month}月${day}日`}
|
|
className={cn(
|
|
"aspect-square w-full min-w-0 rounded-lg text-xs tabular-nums text-slate-700 transition-[background-color,color,scale] duration-150 [@media(hover:hover)]:hover:bg-blue-50 focus-visible:outline-hidden focus-visible:ring-2 focus-visible:ring-blue-500/40 active:scale-90 motion-reduce:transition-none motion-reduce:active:scale-100",
|
|
isToday &&
|
|
!selected &&
|
|
"font-semibold text-blue-600 ring-1 ring-inset ring-blue-200",
|
|
selected && "bg-blue-600 font-semibold text-white [@media(hover:hover)]:hover:bg-blue-700"
|
|
)}
|
|
onClick={() => updateDraft({ ...draft, day })}
|
|
onKeyDown={(event) => {
|
|
const offsets: Record<string, number> = {
|
|
ArrowLeft: -1,
|
|
ArrowRight: 1,
|
|
ArrowUp: -7,
|
|
ArrowDown: 7
|
|
};
|
|
if (event.key in offsets) {
|
|
event.preventDefault();
|
|
focusDayAfterNavigation.current = true;
|
|
updateDraft(moveDay({ ...draft, day }, offsets[event.key]));
|
|
} else if (event.key === "PageUp" || event.key === "PageDown") {
|
|
event.preventDefault();
|
|
focusDayAfterNavigation.current = true;
|
|
changeMonth(event.key === "PageUp" ? -1 : 1);
|
|
}
|
|
}}
|
|
>
|
|
{day}
|
|
</button>
|
|
);
|
|
})}
|
|
</div>
|
|
<div className="mt-3 grid grid-cols-2 gap-2 border-t border-slate-100 pt-3">
|
|
<FieldSelect
|
|
label="小时"
|
|
value={pad(draft.hour)}
|
|
options={HOUR_OPTIONS}
|
|
onValueChange={(hour) => {
|
|
setDraft({ ...draft, hour: Number(hour) });
|
|
setSourceInvalid(false);
|
|
}}
|
|
/>
|
|
<FieldSelect
|
|
label="分钟"
|
|
value={pad(draft.minute)}
|
|
options={MINUTE_OPTIONS}
|
|
onValueChange={(minute) => {
|
|
setDraft({ ...draft, minute: Number(minute) });
|
|
setSourceInvalid(false);
|
|
}}
|
|
/>
|
|
</div>
|
|
{sourceInvalid ? (
|
|
<p role="alert" className="mt-2 text-xs text-amber-700">
|
|
当前值格式无效,请重新选择日期和时间。
|
|
</p>
|
|
) : null}
|
|
<div className="mt-4 flex justify-end gap-2">
|
|
<DialogPrimitive.Close asChild>
|
|
<Button type="button" variant="outline" size="sm">
|
|
取消
|
|
</Button>
|
|
</DialogPrimitive.Close>
|
|
<Button
|
|
type="button"
|
|
size="sm"
|
|
disabled={!canConfirm}
|
|
onClick={() => {
|
|
if (!canConfirm) return;
|
|
onChange(formatValue({ ...draft, year: Number(yearText) }));
|
|
setOpen(false);
|
|
}}
|
|
>
|
|
确认
|
|
</Button>
|
|
</div>
|
|
</DialogPrimitive.Content>
|
|
</DialogPortal>
|
|
</Dialog>
|
|
</div>
|
|
);
|
|
}
|