Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

21.9 KB
Raw Blame
import { useEffect, useMemo, useState } from "react";
import { useTranslation } from "react-i18next";
import {
  CalendarDays,
  ChevronDown,
  ChevronLeft,
  ChevronRight,
} from "lucide-react";
import { Button } from "@/components/ui/button";
import { HoverTip } from "@/components/ui/hover-tip";
import { Checkbox } from "@/components/ui/checkbox";
import { Input } from "@/components/ui/input";
import {
  Popover,
  PopoverContent,
  PopoverTrigger,
} from "@/components/ui/popover";
import { cn } from "@/lib/utils";
import { useUsageFirstDate } from "@/lib/query/usage";
import { getUsageRangePresetLabel, resolveUsageRange } from "@/lib/usageRange";
import { getLocaleFromLanguage } from "./format";
import type { UsageRangePreset, UsageRangeSelection } from "@/types/usage";

type DraftField = "start" | "end";

const PRESETS: UsageRangePreset[] = ["today", "1d", "7d", "14d", "30d", "all"];

interface UsageDateRangePickerProps {
  selection: UsageRangeSelection;
  onApply: (selection: UsageRangeSelection) => void;
  triggerLabel: string;
}

/* ── helpers ── */

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

function endOfDay(d: Date): Date {
  return new Date(d.getFullYear(), d.getMonth(), d.getDate(), 23, 59, 59);
}

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

function toTs(d: Date): number {
  return Math.floor(d.getTime() / 1000);
}

function fromTs(ts: number): Date {
  return new Date(ts * 1000);
}

function fmtDate(ts: number): string {
  const d = fromTs(ts);
  return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, "0")}-${String(d.getDate()).padStart(2, "0")}`;
}

function fmtTime(ts: number): string {
  const d = fromTs(ts);
  return `${String(d.getHours()).padStart(2, "0")}:${String(d.getMinutes()).padStart(2, "0")}`;
}

/** 开始取当天 00:00:00,结束取当天 23:59:59:选日期就是选整天 */
function getDayBoundaryTs(day: Date, field: DraftField): number {
  return toTs(field === "start" ? startOfDay(day) : endOfDay(day));
}

/**
 * 日期框的 `YYYY-MM-DD` 换成当天的边界时间戳(开始 00:00:00、结束 23:59:59);
 * 不是完整日期时返回 null。
 * 逐位键入年份时浏览器会先给出 `0002-11-18` 这样没打完的值,而 `new Date`
 * 把 0–99 年当成 1900 年代,提交它会把年份改成 1902 / 1905 并打断输入(#9699),
 * 所以四位数以下的年份一律当作还没打完。
 */
function parseDateInput(value: string, field: DraftField): number | null {
  const match = /^(\d{4,})-(\d{2})-(\d{2})$/.exec(value);
  if (!match) return null;
  const y = Number(match[1]);
  const m = Number(match[2]);
  const d = Number(match[3]);
  if (y < 1000) return null;
  const date = new Date(y, m - 1, d);
  if (date.getMonth() !== m - 1 || date.getDate() !== d) return null;
  return getDayBoundaryTs(date, field);
}

function parseTimeInput(ts: number, value: string): number {
  const [h, min] = value.split(":").map(Number);
  if (!Number.isFinite(h) || !Number.isFinite(min)) return ts;
  const base = fromTs(ts);
  return toTs(
    new Date(base.getFullYear(), base.getMonth(), base.getDate(), h, min),
  );
}

function setDateKeepTime(ts: number, day: Date): number {
  const base = fromTs(ts);
  return toTs(
    new Date(
      day.getFullYear(),
      day.getMonth(),
      day.getDate(),
      base.getHours(),
      base.getMinutes(),
    ),
  );
}

/** 本地日期 `YYYY-MM-DD` 当天 0 点的时间戳;认不出时为 null */
function parseLocalDayStart(value: string | null | undefined): number | null {
  const match = value ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(value) : null;
  if (!match) return null;
  return toTs(
    new Date(Number(match[1]), Number(match[2]) - 1, Number(match[3])),
  );
}

/** 今天最后一分钟:结束时间不能选到未来的日子 */
function endOfTodayTs(): number {
  const now = new Date();
  return toTs(
    new Date(now.getFullYear(), now.getMonth(), now.getDate(), 23, 59),
  );
}

function getCalendarDays(month: Date): Date[] {
  const first = new Date(month.getFullYear(), month.getMonth(), 1);
  const gridStart = new Date(first);
  gridStart.setDate(first.getDate() - first.getDay());
  return Array.from({ length: 42 }, (_, i) => {
    const d = new Date(gridStart);
    d.setDate(gridStart.getDate() + i);
    return d;
  });
}

/* ── component ── */

function resolveCalendarRange(selection: UsageRangeSelection) {
  const r = resolveUsageRange(selection);
  if (selection.preset !== "all") return r;
  return { startDate: r.endDate - 30 * 24 * 60 * 60, endDate: r.endDate };
}

export function UsageDateRangePicker({
  selection,
  onApply,
  triggerLabel,
}: UsageDateRangePickerProps) {
  const { t, i18n } = useTranslation();
  const [open, setOpen] = useState(false);
  const prevMonthLabel = t("usage.prevMonth", { defaultValue: "上个月" });
  const nextMonthLabel = t("usage.nextMonth", { defaultValue: "下个月" });
  const [activeField, setActiveField] = useState<DraftField>("start");
  // 「全部」的起点是 0,日历草稿改从结束日往前 30 天开始,避免跳到 1970 年
  const resolvedRange = useMemo(
    () => resolveCalendarRange(selection),
    [selection],
  );
  const [draftStart, setDraftStart] = useState(resolvedRange.startDate);
  const [draftEnd, setDraftEnd] = useState(resolvedRange.endDate);
  const [draftLiveEnd, setDraftLiveEnd] = useState(
    selection.preset === "custom" ? (selection.liveEndTime ?? false) : false,
  );
  // 还没动过日期时,选开始日期就当作只看这一天,结束跟着落到当天 23:59:59
  const [hasEditedCustomDraft, setHasEditedCustomDraft] = useState(
    selection.preset === "custom",
  );
  const [displayMonth, setDisplayMonth] = useState(
    () =>
      new Date(
        fromTs(resolvedRange.startDate).getFullYear(),
        fromTs(resolvedRange.startDate).getMonth(),
        1,
      ),
  );
  const [error, setError] = useState<string | null>(null);
  // 日期框正在输入时的原始文本:没打完的值不提交,但要原样留在框里,
  // 受控 value 一被改写浏览器就会重置正在编辑的年份段。失焦后回到格式化的值
  const [dateText, setDateText] = useState<Record<DraftField, string | null>>({
    start: null,
    end: null,
  });
  // 可选范围:最早到有用量记录的那天,最晚到今天。趋势图按天出柱,
  // 选到 1905 年这种起点会一次画四万多根柱子把界面卡死(#9691)。
  // 最早日期没查到之前不知道下界,先不让确认;查到 null(没有记录)时页面是空状态、不画图,不设下界。
  // 查询失败时不能让确认一直点不了:放开下界,只保留「不晚于今天」
  const firstUsageDateQuery = useUsageFirstDate(undefined, {
    refetchInterval: false,
  });
  const boundsReady =
    firstUsageDateQuery.isSuccess || firstUsageDateQuery.isError;
  const minTs = parseLocalDayStart(firstUsageDateQuery.data);
  const maxTs = endOfTodayTs();
  const clampTs = (ts: number) =>
    Math.min(Math.max(ts, minTs ?? Number.NEGATIVE_INFINITY), maxTs);

  const language = i18n.resolvedLanguage || i18n.language || "en";
  const locale = getLocaleFromLanguage(language);

  // Reset draft when popover opens
  useEffect(() => {
    if (!open) return;
    const r = resolveCalendarRange(selection);
    setDraftStart(r.startDate);
    setDraftEnd(r.endDate);
    setDraftLiveEnd(
      selection.preset === "custom" ? (selection.liveEndTime ?? false) : false,
    );
    setHasEditedCustomDraft(selection.preset === "custom");
    setDisplayMonth(
      new Date(
        fromTs(r.startDate).getFullYear(),
        fromTs(r.startDate).getMonth(),
        1,
      ),
    );
    setActiveField("start");
    setError(null);
    setDateText({ start: null, end: null });
  }, [open, selection]);

  // Keep draftEnd ticking when live mode is active and popover is open
  useEffect(() => {
    if (!open || !draftLiveEnd) return;
    const tick = () => setDraftEnd(Math.floor(Date.now() / 1000));
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [open, draftLiveEnd]);

  const calendarDays = useMemo(
    () => getCalendarDays(displayMonth),
    [displayMonth],
  );

  const weekdayLabels = useMemo(
    () =>
      Array.from({ length: 7 }, (_, i) =>
        new Intl.DateTimeFormat(locale, { weekday: "narrow" }).format(
          new Date(2024, 0, 7 + i),
        ),
      ),
    [locale],
  );

  const startDay = fromTs(draftStart);
  const endDay = fromTs(draftEnd);
  const today = new Date();

  /* Pick a date from the calendar */
  const handleDatePick = (day: Date) => {
    setError(null);
    setDateText({ start: null, end: null });

    // When live end time is active, calendar only controls start date
    if (draftLiveEnd) {
      const nextTs = clampTs(setDateKeepTime(draftStart, day));
      setDraftStart(nextTs);
      return;
    }

    const nextTs = clampTs(getDayBoundaryTs(day, activeField));

    if (activeField === "start") {
      setDraftStart(nextTs);
      // 第一次选、原本就是同一天、或开始越过了结束:结束落到这一天的末尾
      if (
        !hasEditedCustomDraft ||
        isSameDay(startDay, endDay) ||
        nextTs > draftEnd
      ) {
        setDraftEnd(clampTs(getDayBoundaryTs(day, "end")));
      }
      // Auto-advance to end field
      setActiveField("end");
    } else {
      // If picked end < start, treat as new start and auto-advance
      if (nextTs < draftStart) {
        setDraftStart(clampTs(getDayBoundaryTs(day, "start")));
        setDraftEnd(nextTs);
        setActiveField("end");
      } else {
        setDraftEnd(nextTs);
      }
    }
    setHasEditedCustomDraft(true);

    // Navigate calendar if the day is outside the displayed month
    if (
      day.getMonth() !== displayMonth.getMonth() ||
      day.getFullYear() !== displayMonth.getFullYear()
    ) {
      setDisplayMonth(new Date(day.getFullYear(), day.getMonth(), 1));
    }
  };

  const handleApply = () => {
    setError(null);
    if (!boundsReady) return;
    // 手输的日期不在输入时改写(会打断逐位输入年份),确认时再收进可选范围
    const start = clampTs(draftStart);
    const end = draftLiveEnd ? draftEnd : clampTs(draftEnd);
    if (start > end) {
      setError(t("usage.invalidTimeRangeOrder", "开始时间不能晚于结束时间"));
      return;
    }
    onApply({
      preset: "custom",
      customStartDate: start,
      customEndDate: end,
      liveEndTime: draftLiveEnd,
    });
    setOpen(false);
  };

  const goToToday = () => {
    setDisplayMonth(new Date(today.getFullYear(), today.getMonth(), 1));
  };

  /* ── Field card (start / end) ── */
  const renderField = (field: DraftField) => {
    const isActive = activeField === field;
    const isEndLive = field === "end" && draftLiveEnd;
    const ts = field === "start" ? draftStart : draftEnd;
    const setTs = field === "start" ? setDraftStart : setDraftEnd;
    const label =
      field === "start"
        ? t("usage.startTime", "开始时间")
        : t("usage.endTime", "结束时间");

    return (
      <div
        className={cn(
          "rounded-panel border px-3 py-2 transition-all",
          isEndLive
            ? "border-border bg-subtle cursor-not-allowed opacity-50"
            : isActive
              ? "border-ring ring-1 ring-ring bg-surface cursor-pointer"
              : "border-border hover:border-border cursor-pointer",
        )}
        onClick={() => {
          if (!isEndLive) setActiveField(field);
        }}
      >
        <div className="mb-1.5 text-badge font-medium uppercase tracking-wider text-fg-2">
          {label}
        </div>
        <div className="flex items-center gap-1.5">
          <Input
            type="date"
            className={cn(
              "h-7 flex-1 border-0 bg-transparent p-0 text-body shadow-none focus:ring-0 focus-visible:ring-0",
              isEndLive && "pointer-events-none",
            )}
            value={dateText[field] ?? fmtDate(ts)}
            min={minTs != null ? fmtDate(minTs) : undefined}
            max={fmtDate(maxTs)}
            onChange={(e) => {
              if (isEndLive) return;
              const raw = e.target.value;
              const next = parseDateInput(raw, field);
              // 完整日期格式化后与原文相同,直接交给 state,草稿只留没打完的值
              setDateText((prev) => ({
                ...prev,
                [field]: next == null ? raw : null,
              }));
              if (next == null) return;
              const d = fromTs(next);
              if (field === "start") {
                setDraftStart(next);
                if (
                  !hasEditedCustomDraft ||
                  isSameDay(startDay, endDay) ||
                  next > draftEnd
                ) {
                  setDraftEnd(getDayBoundaryTs(d, "end"));
                }
              } else if (next < draftStart) {
                setDraftStart(getDayBoundaryTs(d, "start"));
                setDraftEnd(next);
              } else {
                setDraftEnd(next);
              }
              setHasEditedCustomDraft(true);
              setDisplayMonth(new Date(d.getFullYear(), d.getMonth(), 1));
              setError(null);
            }}
            onFocus={() => {
              if (!isEndLive) setActiveField(field);
            }}
            onBlur={() => setDateText((prev) => ({ ...prev, [field]: null }))}
            readOnly={isEndLive}
          />
          <Input
            type="time"
            step={60}
            className={cn(
              "h-7 w-[90px] flex-none border-0 bg-transparent p-0 text-body shadow-none focus:ring-0 focus-visible:ring-0",
              isEndLive && "pointer-events-none",
            )}
            value={fmtTime(ts)}
            onChange={(e) => {
              if (isEndLive) return;
              setTs(parseTimeInput(ts, e.target.value));
              setError(null);
            }}
            onFocus={() => {
              if (!isEndLive) setActiveField(field);
            }}
            readOnly={isEndLive}
          />
        </div>
      </div>
    );
  };

  return (
    <Popover open={open} onOpenChange={setOpen}>
      <PopoverTrigger asChild>
        <Button
          type="button"
          variant="neutral"
          size="regular"
          className="max-w-[220px] shrink-0 gap-1.5 pe-2 ps-2.5"
          title={`${t("usage.timeRange")}: ${triggerLabel}`}
        >
          <CalendarDays
            aria-hidden="true"
            className="h-4 w-4 shrink-0 text-fg-3"
          />
          <span className="min-w-0 truncate">{triggerLabel}</span>
          <ChevronDown className="h-3.5 w-3.5 shrink-0 text-fg-2" />
        </Button>
      </PopoverTrigger>
      <PopoverContent
        className="usage-range-popover w-[620px] max-w-[calc(100vw-2rem)] rounded-panel border-border bg-surface p-3 shadow-v7-md"
        align="start"
      >
        {/* Preset shortcuts */}
        <div className="flex flex-wrap gap-1.5 pb-2 border-b border-border">
          {PRESETS.map((preset) => (
            <Button
              key={preset}
              type="button"
              size="compact"
              variant="neutral"
              aria-pressed={selection.preset === preset}
              className={cn(
                "px-2.5",
                selection.preset === preset &&
                  "border-fg-1 bg-selected font-semibold",
              )}
              onClick={() => {
                onApply({ preset });
                setOpen(false);
              }}
            >
              {getUsageRangePresetLabel(preset, t)}
            </Button>
          ))}
        </div>

        <div className="usage-range-layout mt-3 flex flex-col gap-3">
          {/* Left: date fields */}
          <div className="usage-range-fields space-y-2">
            <p className="text-caption text-fg-2">
              {t("usage.customRangeHint", "支持日期与时间,最长 30 天")}
            </p>
            {renderField("start")}
            {renderField("end")}

            <label className="flex items-center gap-2 cursor-pointer select-none">
              <Checkbox
                checked={draftLiveEnd}
                onCheckedChange={(checked) => {
                  const live = checked === true;
                  setDraftLiveEnd(live);
                  if (live) {
                    setDraftEnd(Math.floor(Date.now() / 1000));
                    setActiveField("start");
                  }
                }}
              />
              <span className="text-caption text-fg-2">
                {t("usage.liveEndTime", "结束时间跟随当前时刻")}
              </span>
            </label>

            {error && <p className="text-caption text-danger-text">{error}</p>}

            <div className="flex gap-2 pt-1">
              <Button
                type="button"
                variant="quiet"
                size="compact"
                className="flex-1"
                onClick={() => setOpen(false)}
              >
                {t("common.cancel")}
              </Button>
              <Button
                type="button"
                variant="solid"
                size="compact"
                className="flex-1"
                disabled={!boundsReady}
                onClick={handleApply}
              >
                {t("common.confirm")}
              </Button>
            </div>
          </div>

          {/* Right: calendar */}
          <div className="usage-range-calendar rounded-panel border border-border bg-subtle p-2.5">
            {/* Month navigation */}
            <div className="flex items-center justify-between mb-1.5">
              <HoverTip content={prevMonthLabel}>
                <Button
                  type="button"
                  size="icon-compact"
                  variant="quiet"
                  aria-label={prevMonthLabel}
                  onClick={() =>
                    setDisplayMonth(
                      new Date(
                        displayMonth.getFullYear(),
                        displayMonth.getMonth() - 1,
                        1,
                      ),
                    )
                  }
                >
                  <ChevronLeft className="h-3.5 w-3.5" />
                </Button>
              </HoverTip>
              {/* 点月份标题跳回本月:动作不在字面上,用 HoverTip 说明 */}
              <HoverTip
                content={t("usage.presetToday", { defaultValue: "当天" })}
              >
                <button
                  type="button"
                  className="text-body font-medium text-fg-1 transition-colors hover:text-fg-2"
                  onClick={goToToday}
                >
                  {displayMonth.toLocaleDateString(locale, {
                    year: "numeric",
                    month: "long",
                  })}
                </button>
              </HoverTip>
              <HoverTip content={nextMonthLabel}>
                <Button
                  type="button"
                  size="icon-compact"
                  variant="quiet"
                  aria-label={nextMonthLabel}
                  onClick={() =>
                    setDisplayMonth(
                      new Date(
                        displayMonth.getFullYear(),
                        displayMonth.getMonth() + 1,
                        1,
                      ),
                    )
                  }
                >
                  <ChevronRight className="h-3.5 w-3.5" />
                </Button>
              </HoverTip>
            </div>

            {/* Weekday headers */}
            <div className="grid grid-cols-7 text-center text-badge text-fg-2 mb-0.5">
              {weekdayLabels.map((label, i) => (
                <div key={i} className="py-0.5">
                  {label}
                </div>
              ))}
            </div>

            {/* Day grid */}
            <div className="grid grid-cols-7 gap-px">
              {calendarDays.map((day) => {
                const isCurrentMonth =
                  day.getMonth() === displayMonth.getMonth();
                const isToday = isSameDay(day, today);
                const isStart = isSameDay(day, startDay);
                const isEnd = isSameDay(day, endDay);
                const dayStart = startOfDay(day);
                const inRange =
                  dayStart >= startOfDay(startDay) &&
                  dayStart <= startOfDay(endDay);
                const isEndpoint = isStart || isEnd;
                const isOutOfBounds =
                  (minTs != null && dayStart < startOfDay(fromTs(minTs))) ||
                  dayStart > fromTs(maxTs);

                return (
                  <button
                    key={day.toISOString()}
                    type="button"
                    aria-label={day.toLocaleDateString(locale)}
                    aria-current={isToday ? "date" : undefined}
                    aria-pressed={isEndpoint}
                    disabled={isOutOfBounds}
                    className={cn(
                      "relative h-7 rounded text-caption transition-colors",
                      !isCurrentMonth && "text-fg-3",
                      isOutOfBounds &&
                        "cursor-not-allowed text-fg-3 opacity-40",
                      isCurrentMonth &&
                        !inRange &&
                        !isOutOfBounds &&
                        "hover:bg-subtle",
                      inRange && !isEndpoint && "bg-selected text-fg-1",
                      isEndpoint && "bg-action text-action-fg font-medium",
                      isToday && !isEndpoint && "ring-1 ring-border-strong",
                    )}
                    onClick={() => handleDatePick(day)}
                  >
                    {day.getDate()}
                  </button>
                );
              })}
            </div>
          </div>
        </div>
      </PopoverContent>
    </Popover>
  );
}