RendyUI English

组件 / 日期选择器

日期选择器

选择 · React / TypeScript Free

录制演示

日期选择器 实现预览

源码

date-picker.tsx
"use client";

/**
 * Date picker — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { AnimatePresence, motion, useReducedMotion } from "motion/react";
import { Calendar, ChevronDown, ChevronLeft, ChevronRight } from "lucide-react";
import { cn, useControllable, useOnClickOutside } from "../internal";

export type DateRange = { from: Date | null; to: Date | null };

export type DatePickerMark = {
  date: Date;
  label: string;
  tone?: "default" | "success" | "warning" | "danger";
};

export interface DatePickerProps {
  mode?: "single" | "range";
  /** A Date in single mode, { from, to } in range mode. */
  value?: Date | DateRange | null;
  defaultValue?: Date | DateRange | null;
  onValueChange?: (value: Date | DateRange) => void;
  /** Muted text inside the field. */
  label?: string;
  /** The text before a pick. */
  placeholder?: string;
  marks?: DatePickerMark[];
  isDateDisabled?: (date: Date) => boolean;
  min?: Date;
  max?: Date;
  footnote?: React.ReactNode | ((value: Date | DateRange | null) => React.ReactNode);
  /** The ringed day; pass it for a stable server render. */
  today?: Date;
  open?: boolean;
  defaultOpen?: boolean;
  onOpenChange?: (open: boolean) => void;
  disabled?: boolean;
  name?: string;
  locale?: "en" | "zh-CN";
  className?: string;
}

const WEEKDAYS = ["S", "M", "T", "W", "T", "F", "S"];
const WEEKDAY_NAMES = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];

const WEEKDAYS_ZH = ["日", "一", "二", "三", "四", "五", "六"];
const WEEKDAY_NAMES_ZH = WEEKDAYS_ZH.map((day) => `星期${day}`);

const TONE_DOT: Record<NonNullable<DatePickerMark["tone"]> | "default", string> = {
  default: "bg-fg",
  success: "bg-success",
  warning: "bg-warning",
  danger: "bg-danger",
};

function startOfDay(date: Date) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate());
}

function sameDay(a: Date, b: Date) {
  return (
    a.getFullYear() === b.getFullYear() &&
    a.getMonth() === b.getMonth() &&
    a.getDate() === b.getDate()
  );
}

function addDays(date: Date, days: number) {
  return new Date(date.getFullYear(), date.getMonth(), date.getDate() + days);
}

function addMonths(date: Date, months: number) {
  const target = new Date(date.getFullYear(), date.getMonth() + months, 1);
  const lastDay = new Date(target.getFullYear(), target.getMonth() + 1, 0).getDate();
  return new Date(target.getFullYear(), target.getMonth(), Math.min(date.getDate(), lastDay));
}

function daysInMonth(date: Date) {
  return new Date(date.getFullYear(), date.getMonth() + 1, 0).getDate();
}

function dateKey(date: Date) {
  return `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}`;
}

function fmtFull(date: Date, locale: string) {
  return date.toLocaleDateString(locale, {
    weekday: "long",
    year: "numeric",
    month: "long",
    day: "numeric",
  });
}

function fmtField(date: Date, locale: string) {
  return date.toLocaleDateString(locale, { weekday: "short", month: "short", day: "numeric" });
}

function fmtShort(date: Date, locale: string) {
  return date.toLocaleDateString(locale, { month: "short", day: "numeric" });
}

function fmtMonth(date: Date, locale: string) {
  return date.toLocaleDateString(locale, { month: "long", year: "numeric" });
}

/**
 * Date picker: a date field with a calendar that slides between months,
 * picks a day or a range, and marks holidays with a dot.
 */
export function DatePicker({
  mode = "single",
  value,
  defaultValue,
  onValueChange,
  label,
  locale = "en",
  placeholder = locale === "zh-CN" ? "选择日期" : "Pick a date",
  marks,
  isDateDisabled,
  min,
  max,
  footnote,
  today = new Date(),
  open,
  defaultOpen = false,
  onOpenChange,
  disabled,
  name,
  className,
}: DatePickerProps) {
  const reduce = useReducedMotion();
  const isRange = mode === "range";
  const zh = locale === "zh-CN";
  const formatLocale = zh ? "zh-CN" : "en-US";
  const weekdays = zh ? WEEKDAYS_ZH : WEEKDAYS;
  const weekdayNames = zh ? WEEKDAY_NAMES_ZH : WEEKDAY_NAMES;
  const todayDate = startOfDay(today);

  const [selected, setSelected] = useControllable<Date | DateRange | null>(
    value,
    defaultValue ?? (isRange ? { from: null, to: null } : null),
  );
  const [isOpen, setOpenState] = useControllable<boolean>(open, defaultOpen, (next) =>
    onOpenChange?.(next),
  );
  const [viewMonth, setViewMonth] = React.useState<Date>(() => new Date(todayDate.getFullYear(), todayDate.getMonth(), 1));
  const [focusedDate, setFocusedDate] = React.useState<Date>(todayDate);
  const [hoverDate, setHoverDate] = React.useState<Date | null>(null);
  const [direction, setDirection] = React.useState<1 | -1>(1);
  const rootRef = React.useRef<HTMLDivElement>(null);
  const triggerRef = React.useRef<HTMLButtonElement>(null);
  const gridRef = React.useRef<HTMLDivElement>(null);
  const listId = React.useId();

  const singleValue = !isRange && selected instanceof Date ? selected : null;
  const rangeValue = isRange
    ? (selected as DateRange | null) ?? { from: null, to: null }
    : null;

  const change = (next: Date | DateRange | null) => {
    setSelected(next);
    if (next != null) onValueChange?.(next);
  };

  const isUnavailable = React.useCallback(
    (date: Date) => {
      const day = startOfDay(date);
      if (min && day < startOfDay(min)) return true;
      if (max && day > startOfDay(max)) return true;
      return isDateDisabled ? isDateDisabled(day) : false;
    },
    [min, max, isDateDisabled],
  );

  const anchor = singleValue ?? rangeValue?.from ?? rangeValue?.to ?? todayDate;

  useOnClickOutside(rootRef, () => setOpenState(false), isOpen);

  React.useEffect(() => {
    if (!isOpen) return;
    setViewMonth(new Date(anchor.getFullYear(), anchor.getMonth(), 1));
    setFocusedDate(anchor);
  }, [isOpen]); // eslint-disable-line react-hooks/exhaustive-deps

  React.useEffect(() => {
    if (!isOpen) return;
    setViewMonth((month) =>
      month.getFullYear() === focusedDate.getFullYear() && month.getMonth() === focusedDate.getMonth()
        ? month
        : new Date(focusedDate.getFullYear(), focusedDate.getMonth(), 1),
    );
  }, [isOpen, focusedDate]);

  React.useEffect(() => {
    if (!isOpen) return;
    const node = gridRef.current?.querySelector<HTMLElement>(`[data-date="${dateKey(focusedDate)}"]`);
    node?.focus({ preventScroll: true });
  }, [isOpen, focusedDate, viewMonth]);

  const stepAvailable = (start: Date, deltaDays: number): Date | null => {
    const sign = deltaDays >= 0 ? 1 : -1;
    let next = addDays(start, deltaDays);
    for (let i = 0; i < 800; i += 1) {
      if (!isUnavailable(next)) return next;
      next = addDays(next, sign);
    }
    return null;
  };

  const moveFocused = (deltaDays: number) => {
    const next = stepAvailable(focusedDate, deltaDays);
    if (next) setFocusedDate(next);
  };

  const shiftMonthFocused = (months: number) => {
    const candidate = addMonths(focusedDate, months);
    const delta = months >= 0 ? 1 : -1;
    let next: Date | null = candidate;
    for (let i = 0; i < 62; i += 1) {
      if (!isUnavailable(next)) {
        setFocusedDate(next);
        return;
      }
      next = addDays(next, delta);
    }
    setFocusedDate(candidate);
  };

  const pick = (date: Date) => {
    if (isUnavailable(date)) return;
    if (!isRange) {
      change(date);
      setOpenState(false);
      triggerRef.current?.focus();
      return;
    }
    const from = rangeValue?.from ?? null;
    const to = rangeValue?.to ?? null;
    if (!from || (from && to)) {
      change({ from: date, to: null });
      return;
    }
    if (date < from) {
      change({ from: date, to: null });
      return;
    }
    change({ from, to: date });
    setOpenState(false);
    triggerRef.current?.focus();
  };

  const onGridKeyDown = (event: React.KeyboardEvent) => {
    switch (event.key) {
      case "ArrowLeft":
        event.preventDefault();
        moveFocused(-1);
        break;
      case "ArrowRight":
        event.preventDefault();
        moveFocused(1);
        break;
      case "ArrowUp":
        event.preventDefault();
        moveFocused(-7);
        break;
      case "ArrowDown":
        event.preventDefault();
        moveFocused(7);
        break;
      case "Home":
        event.preventDefault();
        moveFocused(-focusedDate.getDay());
        break;
      case "End":
        event.preventDefault();
        moveFocused(6 - focusedDate.getDay());
        break;
      case "PageUp":
        event.preventDefault();
        shiftMonthFocused(event.shiftKey ? -12 : -1);
        break;
      case "PageDown":
        event.preventDefault();
        shiftMonthFocused(event.shiftKey ? 12 : 1);
        break;
      case "Enter":
      case " ":
        event.preventDefault();
        pick(focusedDate);
        break;
      case "Escape":
        event.preventDefault();
        setOpenState(false);
        triggerRef.current?.focus();
        break;
    }
  };

  const page = (months: number) => {
    setDirection(months >= 0 ? 1 : -1);
    setViewMonth((month) => addMonths(month, months));
  };

  const markMap = React.useMemo(() => {
    const map = new Map<string, DatePickerMark>();
    (marks ?? []).forEach((mark) => map.set(dateKey(startOfDay(mark.date)), mark));
    return map;
  }, [marks]);

  const lead = viewMonth.getDay();
  const totalDays = daysInMonth(viewMonth);
  const cells: Array<Date | null> = [];
  for (let i = 0; i < lead; i += 1) cells.push(null);
  for (let day = 1; day <= totalDays; day += 1) {
    cells.push(new Date(viewMonth.getFullYear(), viewMonth.getMonth(), day));
  }
  while (cells.length % 7 !== 0) cells.push(null);

  const previewEnd =
    isRange && rangeValue?.from && !rangeValue?.to && hoverDate && hoverDate > rangeValue.from
      ? hoverDate
      : null;
  const rangeStart = isRange ? rangeValue?.from ?? null : null;
  const rangeEnd = isRange ? (rangeValue?.to ?? previewEnd) : null;

  const monthMarks = (marks ?? []).filter(
    (mark) =>
      mark.date.getFullYear() === viewMonth.getFullYear() &&
      mark.date.getMonth() === viewMonth.getMonth(),
  );

  const fieldText = isRange
    ? rangeValue?.from && rangeValue?.to
      ? `${fmtShort(rangeValue.from, formatLocale)} – ${fmtShort(rangeValue.to, formatLocale)}`
      : rangeValue?.from
        ? `${fmtShort(rangeValue.from, formatLocale)} – …`
        : placeholder
    : singleValue
      ? fmtField(singleValue, formatLocale)
      : placeholder;

  const serialized = isRange
    ? `${rangeValue?.from?.toISOString().slice(0, 10) ?? ""}/${rangeValue?.to?.toISOString().slice(0, 10) ?? ""}`
    : (singleValue?.toISOString().slice(0, 10) ?? "");

  const footnoteNode =
    typeof footnote === "function"
      ? footnote(isRange ? rangeValue ?? { from: null, to: null } : singleValue)
      : footnote;

  return (
    <div ref={rootRef} data-date-picker={mode} className={cn("flex flex-col gap-1.5", className)}>
      <button
        type="button"
        ref={triggerRef}
        disabled={disabled}
        data-date-picker-trigger={mode}
        aria-haspopup="dialog"
        aria-expanded={isOpen}
        aria-controls={isOpen ? listId : undefined}
        onClick={() => setOpenState(!isOpen)}
        onKeyDown={(event) => {
          if (event.key === "ArrowDown") {
            event.preventDefault();
            setOpenState(true);
          }
        }}
        className={cn(
          "flex h-9 w-full items-center gap-2 rounded-[8px] border border-border bg-surface px-3 text-left text-[14px] transition-colors",
          "outline-none focus-visible:ring-2 focus-visible:ring-select/60",
          disabled && "cursor-not-allowed opacity-50",
        )}
      >
        <Calendar className="size-4 shrink-0 text-fg-subtle" aria-hidden />
        {label ? <span className="shrink-0 text-[13px] text-fg-subtle">{label}</span> : null}
        <span
          className={cn(
            "min-w-0 flex-1 truncate",
            (isRange ? rangeValue?.from : singleValue) ? "font-medium text-fg" : "text-fg-subtle",
          )}
        >
          {fieldText}
        </span>
        <ChevronDown
          className={cn("size-4 shrink-0 text-fg-subtle transition-transform", isOpen && "rotate-180")}
          aria-hidden
        />
      </button>
      {name ? <input type="hidden" name={name} value={serialized} /> : null}

      <AnimatePresence>
        {isOpen ? (
          <motion.div
            id={listId}
            role="dialog"
            aria-label={fmtMonth(viewMonth, formatLocale)}
            initial={reduce ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.98 }}
            animate={{ opacity: 1, y: 0, scale: 1 }}
            exit={reduce ? { opacity: 0 } : { opacity: 0, y: -6, scale: 0.98 }}
            transition={{ duration: 0.15, ease: [0.2, 0, 0, 1] }}
            className="relative z-50 mt-1 w-full min-w-[300px] rounded-[12px] bg-surface p-3 shadow-[var(--shadow-overlay)]"
          >
            <div className="flex items-center justify-between px-1 pb-2">
              <span className="text-[14px] font-semibold text-fg">{fmtMonth(viewMonth, formatLocale)}</span>
              <span className="flex items-center gap-1">
                <button
                  type="button"
                  data-date-picker-month="previous"
                  aria-label={zh ? "上个月" : "Previous month"}
                  onClick={() => page(-1)}
                  className="grid size-7 place-items-center rounded-[7px] text-fg-muted transition-colors hover:bg-subtle focus-visible:ring-2 focus-visible:ring-select/60 focus-visible:outline-none"
                >
                  <ChevronLeft className="size-4" aria-hidden />
                </button>
                <button
                  type="button"
                  data-date-picker-month="next"
                  aria-label={zh ? "下个月" : "Next month"}
                  onClick={() => page(1)}
                  className="grid size-7 place-items-center rounded-[7px] text-fg-muted transition-colors hover:bg-subtle focus-visible:ring-2 focus-visible:ring-select/60 focus-visible:outline-none"
                >
                  <ChevronRight className="size-4" aria-hidden />
                </button>
              </span>
            </div>

            <div
              ref={gridRef}
              role="grid"
              aria-label={fmtMonth(viewMonth, formatLocale)}
              onKeyDown={onGridKeyDown}
              onPointerLeave={() => setHoverDate(null)}
              className="overflow-hidden"
            >
              <div role="row" aria-hidden className="grid grid-cols-7">
                {weekdays.map((day, index) => (
                  <div
                    key={`${day}-${index}`}
                    role="columnheader"
                    aria-label={weekdayNames[index]}
                    className="grid h-7 place-items-center text-[11px] font-medium text-fg-subtle"
                  >
                    {day}
                  </div>
                ))}
              </div>
              <AnimatePresence mode="popLayout" initial={false}>
                <motion.div
                  key={`${viewMonth.getFullYear()}-${viewMonth.getMonth()}`}
                  role="rowgroup"
                  initial={reduce ? { opacity: 0 } : { opacity: 0, x: direction * 24 }}
                  animate={{ opacity: 1, x: 0 }}
                  exit={reduce ? { opacity: 0 } : { opacity: 0, x: direction * -24 }}
                  transition={{ duration: 0.18, ease: [0.2, 0, 0, 1] }}
                  className="grid grid-cols-7"
                >
                  {cells.map((date, index) => {
                    if (!date) {
                      return <div key={`blank-${index}`} aria-hidden className="h-9 w-9" />;
                    }
                    const key = dateKey(date);
                    const mark = markMap.get(key);
                    const off = isUnavailable(date);
                    const isSelectedSingle = !isRange && singleValue ? sameDay(date, singleValue) : false;
                    const isFrom = isRange && rangeValue?.from ? sameDay(date, rangeValue.from) : false;
                    const isTo = isRange && rangeValue?.to ? sameDay(date, rangeValue.to) : false;
                    const isEndpoint = isSelectedSingle || isFrom || isTo;
                    const inRange =
                      rangeStart && rangeEnd && date > rangeStart && date < rangeEnd;
                    const isToday = sameDay(date, todayDate);
                    const isFocused = sameDay(date, focusedDate);
                    return (
                      <div
                        key={key}
                        role="gridcell"
                        data-date={key}
                        aria-selected={isEndpoint || undefined}
                        aria-disabled={off || undefined}
                        aria-current={isToday ? "date" : undefined}
                        aria-label={`${fmtFull(date, formatLocale)}${mark ? ` (${mark.label})` : ""}${off ? (zh ? ",不可选" : ", unavailable") : ""}`}
                        tabIndex={isFocused ? 0 : -1}
                        onClick={() => {
                          setFocusedDate(date);
                          pick(date);
                        }}
                        onPointerEnter={() => setHoverDate(date)}
                        className={cn(
                          "relative grid h-9 w-9 place-items-center outline-none",
                          inRange && "bg-muted",
                          !off && "cursor-pointer",
                          off && "cursor-not-allowed",
                        )}
                      >
                        <span
                          className={cn(
                            "grid size-7 place-items-center rounded-full text-[13px] tabular-nums transition-colors",
                            isEndpoint
                              ? "bg-inverse font-semibold text-inverse-fg"
                              : off
                                ? "text-fg-subtle opacity-40"
                                : "text-fg hover:bg-subtle",
                            !isEndpoint && isToday && "shadow-[inset_0_0_0_1px_var(--track-strong)]",
                            isEndpoint && isToday && "shadow-[inset_0_0_0_1px_var(--inverse-fg)]",
                          )}
                        >
                          {date.getDate()}
                        </span>
                        {mark ? (
                          <span
                            aria-hidden
                            className={cn(
                              "absolute bottom-[3px] left-1/2 size-1 -translate-x-1/2 rounded-full",
                              TONE_DOT[mark.tone ?? "default"],
                            )}
                          />
                        ) : null}
                      </div>
                    );
                  })}
                </motion.div>
              </AnimatePresence>
            </div>

            {monthMarks.length > 0 ? (
              <div className="mt-2 flex flex-col gap-1 border-t border-border px-1 pt-2">
                {monthMarks.map((mark) => (
                  <div key={dateKey(mark.date)} className="flex items-center gap-2 text-[12px] text-fg-muted">
                    <span
                      aria-hidden
                      className={cn("size-1.5 rounded-full", TONE_DOT[mark.tone ?? "default"])}
                    />
                    <span className="font-medium text-fg">{mark.label}</span>
                    <span aria-hidden>·</span>
                    <span>{fmtShort(mark.date, formatLocale)}</span>
                  </div>
                ))}
              </div>
            ) : null}

            {footnoteNode ? (
              <div className="mt-2 border-t border-border px-1 pt-2 text-[12px] text-fg-subtle">
                {footnoteNode}
              </div>
            ) : null}
          </motion.div>
        ) : null}
      </AnimatePresence>

      <div aria-live="polite" className="sr-only">
        {fmtMonth(viewMonth, formatLocale)}
      </div>
    </div>
  );
}

export default DatePicker;

使用说明

把 TSX 加入 React 项目,并安装组件引用的依赖。页面样式依赖 Tailwind CSS 与 主题变量。

包依赖 · lucide-react、motion、react

共享源码 · internal.ts

参数

名称类型说明
`mode``"single" \| "range"`One day, or a start and an end (the range previews on hover).
`value / defaultValue``Date \| null / { from; to }`A Date in single mode, { from, to } in range mode.
`onValueChange``(value) => void`Called on every pick; a range calls it for the start, then the end.
`label / placeholder``string`Muted text inside the field, and the text before a pick.
`marks``{ date; label; tone? }[]`Days with a dot; their labels list under the month they belong to.
`isDateDisabled``(date) => boolean`Days that can’t be picked, like weekends or bank holidays.
`min / max``Date`First and last day that can be picked.
`footnote``ReactNode \| (value) => ReactNode`A line under the calendar, e.g. when a payment sent that day arrives.
`today``Date`The ringed day; pass it for a stable server render.
`open / defaultOpen / onOpenChange``boolean / boolean / (open) => void`Control the calendar.
locale"en" | "zh-CN"Optional interface language. Defaults to English.