components/linyi/calendar.tsx
class-variance-authoritylucide-react
"use client"; import * as React from "react";import { cva, type VariantProps } from "class-variance-authority";import { ChevronLeft, ChevronRight } from "lucide-react";import { cn } from "@/lib/cn"; export interface DateRange { from: Date | null; to: Date | null;} export const calendarVariants = cva( "w-full max-w-[308px] rounded-[16px] border p-3 text-fg select-none", { variants: { variant: { surface: "border-line-strong bg-surface shadow-panel", well: "border-line-well bg-well", plain: "border-transparent bg-transparent p-0 shadow-none", }, size: { sm: "max-w-[268px] p-2.5", md: "max-w-[308px] p-3", }, }, defaultVariants: { variant: "surface", size: "md", }, }); export function normalizeDate(date: Date): Date { return new Date(date.getFullYear(), date.getMonth(), date.getDate());} export function isSameDay(a: Date | null | undefined, b: Date | null | undefined): boolean { if (!a || !b) return false; return ( a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate() );} export function addDays(date: Date, amount: number): Date { const next = new Date(date.getFullYear(), date.getMonth(), date.getDate() + amount); return normalizeDate(next);} export function addMonths(date: Date, amount: number): Date { const targetYear = date.getFullYear(); const targetMonth = date.getMonth() + amount; const maxDay = new Date(targetYear, targetMonth + 1, 0).getDate(); return new Date(targetYear, targetMonth, Math.min(date.getDate(), maxDay));} export function formatDateISO(date: Date | null | undefined): string { if (!date) return ""; const y = date.getFullYear(); const m = String(date.getMonth() + 1).padStart(2, "0"); const d = String(date.getDate()).padStart(2, "0"); return `${y}-${m}-${d}`;} export function formatDateCN(date: Date | null | undefined): string { if (!date) return ""; return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`;} function startOfCalendarGrid(year: number, month: number, weekStartsOn: 0 | 1): Date { const firstOfMonth = new Date(year, month, 1); const dayOfWeek = firstOfMonth.getDay(); const diff = (dayOfWeek - weekStartsOn + 7) % 7; return addDays(firstOfMonth, -diff);} const WEEKDAY_LABELS_MON = ["一", "二", "三", "四", "五", "六", "日"];const WEEKDAY_LABELS_SUN = ["日", "一", "二", "三", "四", "五", "六"];const MONTH_LABELS = [ "1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月",]; export interface CalendarProps extends Omit<React.ComponentPropsWithRef<"div">, "defaultValue">, VariantProps<typeof calendarVariants> { mode?: "single" | "range"; value?: Date | null; defaultValue?: Date | null; onValueChange?: (date: Date | null) => void; rangeValue?: DateRange; defaultRangeValue?: DateRange; onRangeValueChange?: (range: DateRange) => void; month?: Date; defaultMonth?: Date; onMonthChange?: (month: Date) => void; weekStartsOn?: 0 | 1; minDate?: Date; maxDate?: Date; disabledDates?: (date: Date) => boolean; showTodayButton?: boolean; yearSpan?: number;} export function Calendar({ mode = "single", value, defaultValue = null, onValueChange, rangeValue, defaultRangeValue = { from: null, to: null }, onRangeValueChange, month, defaultMonth, onMonthChange, weekStartsOn = 1, minDate, maxDate, disabledDates, showTodayButton = true, yearSpan = 20, variant = "surface", size = "md", className, ...props}: CalendarProps) { const today = React.useMemo(() => normalizeDate(new Date()), []); const isSingleControlled = value !== undefined; const [internalSingle, setInternalSingle] = React.useState<Date | null>( defaultValue ? normalizeDate(defaultValue) : null ); const selectedSingle = isSingleControlled ? value ? normalizeDate(value) : null : internalSingle; const isRangeControlled = rangeValue !== undefined; const [internalRange, setInternalRange] = React.useState<DateRange>({ from: defaultRangeValue.from ? normalizeDate(defaultRangeValue.from) : null, to: defaultRangeValue.to ? normalizeDate(defaultRangeValue.to) : null, }); // 受控模式下以时间戳作为依赖,避免每次渲染新建日期对象导致下游回调与缓存失效 const rangeFromTs = rangeValue?.from ? normalizeDate(rangeValue.from).getTime() : null; const rangeToTs = rangeValue?.to ? normalizeDate(rangeValue.to).getTime() : null; const selectedRange = React.useMemo<DateRange>( () => isRangeControlled ? { from: rangeFromTs !== null ? new Date(rangeFromTs) : null, to: rangeToTs !== null ? new Date(rangeToTs) : null, } : internalRange, [isRangeControlled, rangeFromTs, rangeToTs, internalRange] ); const initialMonth = React.useMemo(() => { const seed = month ?? defaultMonth ?? (mode === "range" ? selectedRange.from : selectedSingle) ?? today; return new Date(seed.getFullYear(), seed.getMonth(), 1); }, []); // eslint-disable-line react-hooks/exhaustive-deps const isMonthControlled = month !== undefined; const [internalMonth, setInternalMonth] = React.useState<Date>(initialMonth); const controlledMonthTs = month ? new Date(month.getFullYear(), month.getMonth(), 1).getTime() : null; const viewMonth = React.useMemo( () => (controlledMonthTs !== null ? new Date(controlledMonthTs) : internalMonth), [controlledMonthTs, internalMonth] ); const [focusedDate, setFocusedDate] = React.useState<Date>( (mode === "range" ? selectedRange.from : selectedSingle) ?? today ); const [hoveredDate, setHoveredDate] = React.useState<Date | null>(null); const cellRefs = React.useRef<Map<string, HTMLButtonElement>>(new Map()); const setViewMonth = React.useCallback( (next: Date) => { const normalized = new Date(next.getFullYear(), next.getMonth(), 1); if (!isMonthControlled) { setInternalMonth(normalized); } onMonthChange?.(normalized); }, [isMonthControlled, onMonthChange] ); const isDateDisabled = React.useCallback( (date: Date): boolean => { const d = normalizeDate(date).getTime(); if (minDate && d < normalizeDate(minDate).getTime()) return true; if (maxDate && d > normalizeDate(maxDate).getTime()) return true; if (disabledDates && disabledDates(date)) return true; return false; }, [minDate, maxDate, disabledDates] ); const weeks = React.useMemo(() => { const start = startOfCalendarGrid( viewMonth.getFullYear(), viewMonth.getMonth(), weekStartsOn ); const grid: Date[][] = []; for (let w = 0; w < 6; w++) { const row: Date[] = []; for (let d = 0; d < 7; d++) { row.push(addDays(start, w * 7 + d)); } grid.push(row); } return grid; }, [viewMonth, weekStartsOn]); const years = React.useMemo(() => { const centerYear = viewMonth.getFullYear(); const minY = minDate ? minDate.getFullYear() : centerYear - yearSpan; const maxY = maxDate ? maxDate.getFullYear() : centerYear + yearSpan; const list: number[] = []; for (let y = minY; y <= maxY; y++) { list.push(y); } return list; }, [viewMonth, minDate, maxDate, yearSpan]); const handleSelectDate = React.useCallback( (date: Date) => { if (isDateDisabled(date)) return; const clean = normalizeDate(date); setFocusedDate(clean); if ( clean.getMonth() !== viewMonth.getMonth() || clean.getFullYear() !== viewMonth.getFullYear() ) { setViewMonth(clean); } if (mode === "single") { if (!isSingleControlled) setInternalSingle(clean); onValueChange?.(clean); return; } // Range selection logic const { from, to } = selectedRange; let nextRange: DateRange; if (!from || (from && to)) { nextRange = { from: clean, to: null }; } else if (clean.getTime() < from.getTime()) { nextRange = { from: clean, to: from }; } else { nextRange = { from, to: clean }; } if (!isRangeControlled) setInternalRange(nextRange); onRangeValueChange?.(nextRange); }, [ isDateDisabled, viewMonth, setViewMonth, mode, isSingleControlled, onValueChange, selectedRange, isRangeControlled, onRangeValueChange, ] ); const moveFocus = React.useCallback( (target: Date) => { const clean = normalizeDate(target); setFocusedDate(clean); if ( clean.getMonth() !== viewMonth.getMonth() || clean.getFullYear() !== viewMonth.getFullYear() ) { setViewMonth(clean); } const key = formatDateISO(clean); window.requestAnimationFrame(() => { cellRefs.current.get(key)?.focus(); }); }, [viewMonth, setViewMonth] ); const handleCellKeyDown = ( e: React.KeyboardEvent<HTMLButtonElement>, date: Date ) => { switch (e.key) { case "ArrowLeft": e.preventDefault(); moveFocus(addDays(date, -1)); break; case "ArrowRight": e.preventDefault(); moveFocus(addDays(date, 1)); break; case "ArrowUp": e.preventDefault(); moveFocus(addDays(date, -7)); break; case "ArrowDown": e.preventDefault(); moveFocus(addDays(date, 7)); break; case "Home": { e.preventDefault(); const offset = (date.getDay() - weekStartsOn + 7) % 7; moveFocus(addDays(date, -offset)); break; } case "End": { e.preventDefault(); const offset = 6 - ((date.getDay() - weekStartsOn + 7) % 7); moveFocus(addDays(date, offset)); break; } case "PageUp": e.preventDefault(); moveFocus(addMonths(date, e.shiftKey ? -12 : -1)); break; case "PageDown": e.preventDefault(); moveFocus(addMonths(date, e.shiftKey ? 12 : 1)); break; case "Enter": case " ": e.preventDefault(); handleSelectDate(date); break; default: break; } }; // Compute effective range preview when hovering after picking `from` const effectiveRange = React.useMemo(() => { if (mode !== "range") return { start: null, end: null }; const { from, to } = selectedRange; if (!from) return { start: null, end: null }; if (to) return { start: from, end: to }; if (hoveredDate) { return hoveredDate.getTime() < from.getTime() ? { start: hoveredDate, end: from } : { start: from, end: hoveredDate }; } return { start: from, end: null }; }, [mode, selectedRange, hoveredDate]); const weekdayLabels = weekStartsOn === 1 ? WEEKDAY_LABELS_MON : WEEKDAY_LABELS_SUN; // Determine which date inside the visible grid gets tabIndex=0 const visibleFocusKey = React.useMemo(() => { const focusedKey = formatDateISO(focusedDate); const flatKeys = weeks.flat().map(formatDateISO); if (flatKeys.includes(focusedKey)) return focusedKey; return formatDateISO( new Date(viewMonth.getFullYear(), viewMonth.getMonth(), 1) ); }, [focusedDate, weeks, viewMonth]); return ( <div className={cn(calendarVariants({ variant, size }), className)} {...props} > {/* Header: prev/next + quick year/month select */} <div className="mb-2.5 flex items-center justify-between gap-1"> <button type="button" onClick={() => setViewMonth(addMonths(viewMonth, -1))} aria-label="上个月" className="inline-flex h-7 w-7 items-center justify-center rounded-[8px] border border-line bg-surface-2/60 text-fg-secondary transition-colors cursor-pointer hover:bg-surface-hover hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/30" > <ChevronLeft className="h-3.5 w-3.5" aria-hidden="true" /> </button> <div className="flex items-center gap-1"> <select aria-label="选择年份" value={viewMonth.getFullYear()} onChange={(e) => setViewMonth(new Date(Number(e.target.value), viewMonth.getMonth(), 1)) } className="h-7 rounded-[7px] border border-transparent bg-transparent px-1.5 font-mono-num text-xs font-medium text-fg transition-colors cursor-pointer hover:border-line hover:bg-surface-2 focus-visible:border-accent focus-visible:outline-none" > {years.map((y) => ( <option key={y} value={y} className="bg-surface text-fg"> {y}年 </option> ))} </select> <select aria-label="选择月份" value={viewMonth.getMonth()} onChange={(e) => setViewMonth(new Date(viewMonth.getFullYear(), Number(e.target.value), 1)) } className="h-7 rounded-[7px] border border-transparent bg-transparent px-1.5 font-mono-num text-xs font-medium text-fg transition-colors cursor-pointer hover:border-line hover:bg-surface-2 focus-visible:border-accent focus-visible:outline-none" > {MONTH_LABELS.map((label, idx) => ( <option key={label} value={idx} className="bg-surface text-fg"> {label} </option> ))} </select> </div> <button type="button" onClick={() => setViewMonth(addMonths(viewMonth, 1))} aria-label="下个月" className="inline-flex h-7 w-7 items-center justify-center rounded-[8px] border border-line bg-surface-2/60 text-fg-secondary transition-colors cursor-pointer hover:bg-surface-hover hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/30" > <ChevronRight className="h-3.5 w-3.5" aria-hidden="true" /> </button> </div> {/* Calendar grid */} <table role="grid" aria-label={`${viewMonth.getFullYear()}年${viewMonth.getMonth() + 1}月日历`} className="w-full border-collapse" onMouseLeave={() => setHoveredDate(null)} > <thead> <tr role="row"> {weekdayLabels.map((label) => ( <th key={label} scope="col" className="pb-1.5 text-center text-[11px] font-normal text-fg-muted" > {label} </th> ))} </tr> </thead> <tbody> {weeks.map((week, wIdx) => ( <tr key={wIdx} role="row"> {week.map((day) => { const key = formatDateISO(day); const outside = day.getMonth() !== viewMonth.getMonth(); const disabled = isDateDisabled(day); const isToday = isSameDay(day, today); const isSingleSelected = mode === "single" && isSameDay(day, selectedSingle); const isRangeStart = mode === "range" && isSameDay(day, effectiveRange.start); const isRangeEnd = mode === "range" && isSameDay(day, effectiveRange.end); const isInRange = mode === "range" && effectiveRange.start !== null && effectiveRange.end !== null && day.getTime() > effectiveRange.start.getTime() && day.getTime() < effectiveRange.end.getTime(); const isSelected = isSingleSelected || isRangeStart || isRangeEnd; return ( <td key={key} role="gridcell" aria-selected={isSelected || isInRange || undefined} className="p-[1px] text-center" > <button ref={(el) => { if (el) cellRefs.current.set(key, el); else cellRefs.current.delete(key); }} type="button" disabled={disabled} tabIndex={key === visibleFocusKey ? 0 : -1} aria-label={formatDateCN(day)} aria-current={isToday ? "date" : undefined} onClick={() => handleSelectDate(day)} onFocus={() => setFocusedDate(day)} onMouseEnter={() => { if (mode === "range" && !disabled) setHoveredDate(day); }} onKeyDown={(e) => handleCellKeyDown(e, day)} className={cn( "relative mx-auto inline-flex w-full items-center justify-center font-mono-num text-xs transition-colors outline-none cursor-pointer", size === "sm" ? "h-8" : "h-9", "focus-visible:z-10 focus-visible:ring-2 focus-visible:ring-accent/40", isSelected ? "rounded-[8px] bg-accent font-medium text-accent-fg" : isInRange ? "rounded-[4px] bg-accent-soft text-accent font-medium" : outside ? "rounded-[8px] text-fg-muted/55 hover:bg-well/70 hover:text-fg-secondary" : "rounded-[8px] text-fg hover:bg-well", isToday && !isSelected && "ring-1 ring-inset ring-accent/55 font-medium text-accent", disabled && "pointer-events-none opacity-30 line-through" )} > {day.getDate()} </button> </td> ); })} </tr> ))} </tbody> </table> {showTodayButton && ( <div className="mt-2 flex items-center justify-between border-t border-line pt-2 text-[11px]"> <span className="font-mono-num text-fg-muted"> 方向键跨周/月切换 </span> <button type="button" onClick={() => { setViewMonth(today); setFocusedDate(today); if (mode === "single" && !isDateDisabled(today)) { handleSelectDate(today); } }} className="rounded-badge px-2 py-0.5 text-[11px] font-medium text-accent transition-colors cursor-pointer hover:bg-accent-soft" > 回到今天 </button> </div> )} </div> );}