components/linyi/date-picker.tsx
@base-ui/reactclass-variance-authoritylucide-react
"use client"; import * as React from "react";import { Popover as BasePopover } from "@base-ui/react/popover";import { cva, type VariantProps } from "class-variance-authority";import { Calendar as CalendarIcon, X } from "lucide-react";import { cn } from "@/lib/cn";import { Calendar, addDays, formatDateISO, normalizeDate, type DateRange,} from "@/components/linyi/calendar"; export interface DatePreset { label: string; getValue: () => Date | DateRange;} export const datePickerTriggerVariants = cva( [ "inline-flex w-full items-center justify-between gap-2 rounded-control border text-fg transition-[border-color,background-color,box-shadow] duration-150 cursor-pointer outline-none", "focus-visible:border-accent focus-visible:ring-2 focus-visible:ring-accent/20", "disabled:opacity-45 disabled:pointer-events-none", ].join(" "), { variants: { variant: { surface: "border-line-strong bg-surface hover:border-fg/30", well: "border-line-well bg-well hover:border-line-strong", }, size: { sm: "h-control-sm px-2.5 text-xs", md: "h-control-md px-3 text-xs", lg: "h-control-lg px-3.5 text-sm", }, invalid: { true: "border-danger focus-visible:border-danger focus-visible:ring-danger/20", false: "", }, }, defaultVariants: { variant: "surface", size: "md", invalid: false, }, }); function getDefaultRangePresets(): DatePreset[] { return [ { label: "今天", getValue: () => { const t = normalizeDate(new Date()); return { from: t, to: t }; }, }, { label: "近 7 天", getValue: () => { const t = normalizeDate(new Date()); return { from: addDays(t, -6), to: t }; }, }, { label: "近 30 天", getValue: () => { const t = normalizeDate(new Date()); return { from: addDays(t, -29), to: t }; }, }, { label: "本月", getValue: () => { const t = normalizeDate(new Date()); return { from: new Date(t.getFullYear(), t.getMonth(), 1), to: t }; }, }, ];} function getDefaultSinglePresets(): DatePreset[] { return [ { label: "今天", getValue: () => normalizeDate(new Date()) }, { label: "明天", getValue: () => addDays(normalizeDate(new Date()), 1) }, { label: "7 天后", getValue: () => addDays(normalizeDate(new Date()), 7) }, ];} export interface DatePickerProps extends Omit< React.ComponentPropsWithRef<"button">, "value" | "defaultValue" | "onChange" >, VariantProps<typeof datePickerTriggerVariants> { mode?: "single" | "range"; value?: Date | null; defaultValue?: Date | null; onValueChange?: (date: Date | null) => void; rangeValue?: DateRange; defaultRangeValue?: DateRange; onRangeValueChange?: (range: DateRange) => void; placeholder?: string; showPresets?: boolean; presets?: DatePreset[]; weekStartsOn?: 0 | 1; minDate?: Date; maxDate?: Date; disabledDates?: (date: Date) => boolean; clearable?: boolean; align?: React.ComponentProps<typeof BasePopover.Positioner>["align"]; side?: React.ComponentProps<typeof BasePopover.Positioner>["side"];} export function DatePicker({ mode = "single", value, defaultValue = null, onValueChange, rangeValue, defaultRangeValue = { from: null, to: null }, onRangeValueChange, placeholder, showPresets = true, presets, weekStartsOn = 1, minDate, maxDate, disabledDates, clearable = true, variant = "surface", size = "md", invalid = false, disabled = false, align = "start", side = "bottom", className, ...props}: DatePickerProps) { const [open, setOpen] = React.useState(false); const [viewMonth, setViewMonth] = React.useState<Date>(() => normalizeDate(new Date()) ); const isSingleControlled = value !== undefined; const [internalSingle, setInternalSingle] = React.useState<Date | null>( defaultValue ? normalizeDate(defaultValue) : null ); const currentSingle = isSingleControlled ? value : internalSingle; const isRangeControlled = rangeValue !== undefined; const [internalRange, setInternalRange] = React.useState<DateRange>(defaultRangeValue); const currentRange = isRangeControlled ? rangeValue : internalRange; const resolvedPresets = React.useMemo( () => presets ?? (mode === "range" ? getDefaultRangePresets() : getDefaultSinglePresets()), [presets, mode] ); const handleSingleChange = (next: Date | null) => { if (!isSingleControlled) setInternalSingle(next); onValueChange?.(next); if (next) setOpen(false); }; const handleRangeChange = (next: DateRange) => { if (!isRangeControlled) setInternalRange(next); onRangeValueChange?.(next); if (next.from && next.to) setOpen(false); }; const applyPreset = (preset: DatePreset) => { const val = preset.getValue(); if (mode === "range" && val && typeof val === "object" && "from" in val) { handleRangeChange(val); if (val.from) setViewMonth(val.from); } else if (mode === "single" && val instanceof Date) { handleSingleChange(val); setViewMonth(val); } }; const hasValue = mode === "single" ? currentSingle !== null : currentRange.from !== null || currentRange.to !== null; const displayText = React.useMemo(() => { if (mode === "single") { return currentSingle ? formatDateISO(currentSingle) : ""; } if (!currentRange.from && !currentRange.to) return ""; if (currentRange.from && currentRange.to) { return `${formatDateISO(currentRange.from)} ~ ${formatDateISO(currentRange.to)}`; } return `${formatDateISO(currentRange.from)} ~ 选择结束日期`; }, [mode, currentSingle, currentRange]); const fallbackPlaceholder = placeholder ?? (mode === "range" ? "选择开始与结束日期" : "选择日期"); return ( <BasePopover.Root open={open} onOpenChange={setOpen}> <div className="relative flex w-full items-center"> <BasePopover.Trigger disabled={disabled} aria-invalid={invalid || undefined} className={cn( datePickerTriggerVariants({ variant, size, invalid }), clearable && hasValue && !disabled && "pr-8", className )} {...props} > <span className="flex min-w-0 items-center gap-2"> <CalendarIcon className="h-3.5 w-3.5 flex-shrink-0 text-fg-muted" aria-hidden="true" /> <span className={cn( "truncate font-mono-num", hasValue ? "text-fg" : "font-sans text-fg-muted" )} > {displayText || fallbackPlaceholder} </span> </span> </BasePopover.Trigger> {clearable && hasValue && !disabled && ( <button type="button" aria-label="清空已选日期" onClick={(e) => { e.stopPropagation(); if (mode === "single") { if (!isSingleControlled) setInternalSingle(null); onValueChange?.(null); } else { const empty: DateRange = { from: null, to: null }; if (!isRangeControlled) setInternalRange(empty); onRangeValueChange?.(empty); } }} className="absolute right-2 inline-flex h-5 w-5 items-center justify-center rounded-[5px] text-fg-muted transition-colors cursor-pointer hover:bg-well hover:text-fg" > <X className="h-3 w-3" aria-hidden="true" /> </button> )} </div> <BasePopover.Portal> <BasePopover.Positioner side={side} align={align} sideOffset={6} className="z-[var(--z-popover)] outline-none" > <BasePopover.Popup className={cn( "max-w-[calc(100vw-24px)] rounded-[16px] border border-line-strong bg-surface/96 p-3 text-fg shadow-popover backdrop-blur-md outline-none", "origin-[var(--transform-origin)] transition-[opacity,transform] duration-150 ease-[cubic-bezier(0.16,1,0.3,1)] motion-reduce:transition-none", "data-[starting-style]:opacity-0 data-[starting-style]:scale-95", "data-[ending-style]:opacity-0 data-[ending-style]:scale-95" )} > <div className="flex flex-col gap-3 sm:flex-row"> {showPresets && resolvedPresets.length > 0 && ( <div className="flex flex-row flex-wrap gap-1 border-b border-line pb-2.5 sm:w-[104px] sm:flex-col sm:border-b-0 sm:border-r sm:pb-0 sm:pr-2.5"> <span className="hidden px-2 pb-1 text-[10px] font-mono-num text-fg-muted sm:block"> 快捷区间 </span> {resolvedPresets.map((preset) => ( <button key={preset.label} type="button" onClick={() => applyPreset(preset)} className="rounded-[8px] px-2.5 py-1.5 text-left text-xs text-fg-secondary transition-colors cursor-pointer hover:bg-well hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/30" > {preset.label} </button> ))} </div> )} <Calendar mode={mode} variant="plain" month={viewMonth} onMonthChange={setViewMonth} weekStartsOn={weekStartsOn} minDate={minDate} maxDate={maxDate} disabledDates={disabledDates} value={currentSingle} onValueChange={handleSingleChange} rangeValue={currentRange} onRangeValueChange={handleRangeChange} /> </div> </BasePopover.Popup> </BasePopover.Positioner> </BasePopover.Portal> </BasePopover.Root> );}