Files
AgentHub/client/src/components/DateTimePicker.tsx
T
nntrivi2001 03f1673fce feat(dashboard): lazy routes, Needs-you strip, URL state, exact numbers
- Workspace, SettingsHub, SessionDetail and the Workflow sub-tab are lazy
  (main bundle 2,166 kB -> ~920 kB), wrapped in RouteErrorBoundary: a stale
  chunk after a self-update reloads once (vite:preloadError too), any other
  error shows a Reload panel instead of a blank page.
- Live refresh: lib/throttle.ts + hooks/useLiveRefresh.ts replace trailing
  debounces that froze under a steady event stream; refresh skips hidden
  tabs and refetches after a WebSocket reconnect. Monitor loads only while
  shown, with one batched GET /api/agents?session_ids= instead of N+1; a
  failing endpoint is an inline error, not a blank Dashboard.
- NeedsYouStrip on Monitor and above Analytics. Tabs, filters, page, sort
  and search live in the URL (Dashboard, Sessions, Activity, SessionDetail).
- Sessions: tool / workspace / date-range filters, CSV/JSON export
  (formula-neutralised), focusable row links, Open in workspace (the dead
  /run links are gone), stale responses dropped, error + Retry.
- Fixes: "NaNs" durations, 30/7-day charts skipping idle days, weekday
  labels west of UTC (now averages), cache hit rate denominator, billable
  tokens vs cache reads, exact tool-call counts, "To" date = end of day,
  invalid ?from= no longer throws, recent list no longer shrinks to 15,
  stable message keys, transcript switch races.
- Light-theme-unreadable bg-black code panels and dark-only DAG fills use
  tokens; status configs and chart colours use theme tokens; Health tab
  and other literals translated.
- Server (additive): GET /api/agents?session_ids=, GET /api/sessions
  awaiting=1&from=&to=, stats tool_call_count/distinct_tool_count, event
  rows carry session/agent labels.
2026-10-05 13:22:04 +07:00

312 lines
12 KiB
TypeScript

/**
* @file DateTimePicker.tsx
* @description A React component that provides a user-friendly interface for selecting both date and time. The component displays a button that shows the currently selected date and time in a human-readable format. When the button is clicked, a dropdown appears containing a calendar for date selection and an input for time selection. The component handles edge cases such as invalid dates and ensures that the dropdown is positioned correctly within the viewport. It also allows users to clear their selection easily. This component is designed to be reusable across the application wherever date and time input is required.
* @author Nguyễn Ngọc Trí Vĩ <vinnt@smartgift.vn>
*/
/* =============================================================================
* MODULE_GUIDE — extended in-file reference (comments only; safe to read, never executed)
* =============================================================================
* **Purpose:** Dashboard module consumed by the React client, MCP tools, or desktop shell depending on deployment mode.
*
* ## Design constraints
* - Local-first: no telemetry leaves the machine unless the user configures webhooks.
* - Fail-safe hooks path on the server must never block Claude Code; UI mirrors that
* philosophy by degrading gracefully (empty states, stale badges, reconnect loops).
* - Destructive flows stay behind explicit confirmation modals and server-side gates.
* - Internationalization: user-visible strings belong in i18n JSON, not literals here.
*
* ## Remote data & SSH
* Remote Data Sources let operators aggregate multiple machines. SSH entries describe
* how to reach a peer dashboard; the global data scope (`dataScope.ts`) narrows every
* scoped GET via `?sources=`. Health checks and import history surface in Settings.
*
* ## Public surface
* - `DateTimePicker` — exported API; see TSDoc on the symbol for behavior.
*
* ## Testing pointers
* - Prefer colocated `__tests__` with Vitest + Testing Library for UI.
* - Server contract changes require `npm run test:server` and OpenAPI sync.
*
* ## Related docs
* - `ARCHITECTURE.md` — hooks → API → SQLite → WebSocket → UI pipeline.
* - `docs/API.md` — REST reference.
* - `skills/file-headers/` — mandatory `@author` header policy.
* ============================================================================= */
/* -----------------------------------------------------------------------------
* EXPORT CATALOG — quick index of symbols defined below (documentation only).
* -----------------------------------------------------------------------------
* **DateTimePicker**
* Part of this module's public contract. Downstream imports should treat
* the signature and return type as stable unless release notes say otherwise.
* When behavior changes, update the `@file` overview and relevant tests.
*
* ----------------------------------------------------------------------------- */
import React, { useState, useRef, useEffect } from "react";
import { useTranslation } from "react-i18next";
import { Calendar, Clock, ChevronLeft, ChevronRight, X } from "lucide-react";
interface DateTimePickerProps {
value: string; // Expected format: YYYY-MM-DDTHH:mm
onChange: (value: string) => void;
placeholder?: string;
className?: string;
"aria-label"?: string;
title?: string;
/** A "to" bound: picking a day with no time yet means the END of that day
* (23:59), not its first minute. */
endOfDay?: boolean;
}
export function DateTimePicker({
value,
onChange,
placeholder,
className = "",
"aria-label": ariaLabel,
title,
endOfDay = false,
}: DateTimePickerProps) {
const { t, i18n } = useTranslation("sessions");
const locale = i18n.resolvedLanguage ?? i18n.language;
const [isOpen, setIsOpen] = useState(false);
const [alignment, setAlignment] = useState<"left" | "right">("left");
const containerRef = useRef<HTMLDivElement>(null);
// Parse value
const dateObj = value ? new Date(value) : null;
const [viewDate, setViewDate] = useState(dateObj || new Date());
useEffect(() => {
if (isOpen && containerRef.current) {
const rect = containerRef.current.getBoundingClientRect();
if (rect.left + 230 > window.innerWidth) {
setAlignment("right");
} else {
setAlignment("left");
}
}
}, [isOpen]);
useEffect(() => {
if (dateObj && !isNaN(dateObj.getTime())) {
setViewDate(dateObj);
}
}, [value]);
useEffect(() => {
function handleClickOutside(event: MouseEvent) {
if (containerRef.current && !containerRef.current.contains(event.target as Node)) {
setIsOpen(false);
}
}
document.addEventListener("mousedown", handleClickOutside);
return () => document.removeEventListener("mousedown", handleClickOutside);
}, []);
useEffect(() => {
if (!isOpen) return;
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setIsOpen(false);
};
document.addEventListener("keydown", onKey);
return () => document.removeEventListener("keydown", onKey);
}, [isOpen]);
const formatDisplay = (d: Date | null) => {
if (!d || isNaN(d.getTime())) return "";
return d.toLocaleString(locale, {
month: "short",
day: "numeric",
hour: "2-digit",
minute: "2-digit",
});
};
const handleDateClick = (day: number) => {
const newDate = new Date(viewDate.getFullYear(), viewDate.getMonth(), day);
if (dateObj && !isNaN(dateObj.getTime())) {
newDate.setHours(dateObj.getHours(), dateObj.getMinutes());
} else {
// Default: midnight, or 23:59 for an end bound so the day is included.
if (endOfDay) newDate.setHours(23, 59, 59, 999);
else newDate.setHours(0, 0);
}
updateValue(newDate);
};
const handleTimeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const timeStr = e.target.value;
if (!timeStr) return;
const parts = timeStr.split(":");
if (parts.length !== 2) return;
const h = parts[0] || "0";
const m = parts[1] || "0";
const newDate = dateObj && !isNaN(dateObj.getTime()) ? new Date(dateObj) : new Date();
newDate.setHours(parseInt(h, 10), parseInt(m, 10));
updateValue(newDate);
};
const updateValue = (d: Date) => {
const y = d.getFullYear();
const mo = String(d.getMonth() + 1).padStart(2, "0");
const day = String(d.getDate()).padStart(2, "0");
const h = String(d.getHours()).padStart(2, "0");
const mi = String(d.getMinutes()).padStart(2, "0");
// An end bound carries its :59.999 so the whole last minute is included.
const tail = endOfDay ? ":59.999" : "";
onChange(`${y}-${mo}-${day}T${h}:${mi}${tail}`);
};
const clearValue = (e: React.MouseEvent) => {
e.stopPropagation();
onChange("");
setIsOpen(false);
};
const daysInMonth = new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 0).getDate();
const firstDayOfMonth = new Date(viewDate.getFullYear(), viewDate.getMonth(), 1).getDay();
const days = [];
for (let i = 0; i < firstDayOfMonth; i++) {
days.push(<div key={`empty-${i}`} className="w-6 h-6" />);
}
for (let i = 1; i <= daysInMonth; i++) {
const isSelected = !!(
dateObj &&
dateObj.getDate() === i &&
dateObj.getMonth() === viewDate.getMonth() &&
dateObj.getFullYear() === viewDate.getFullYear()
);
const isToday =
new Date().getDate() === i &&
new Date().getMonth() === viewDate.getMonth() &&
new Date().getFullYear() === viewDate.getFullYear();
days.push(
<button
key={i}
type="button"
onClick={() => handleDateClick(i)}
aria-label={new Date(viewDate.getFullYear(), viewDate.getMonth(), i).toLocaleDateString(
locale,
{ weekday: "long", year: "numeric", month: "long", day: "numeric" }
)}
aria-pressed={isSelected}
className={`w-6 h-6 flex items-center justify-center rounded text-[11px] transition-colors
${
isSelected
? "bg-accent-solid text-white font-medium"
: isToday
? "bg-surface-3 text-accent font-medium"
: "hover:bg-surface-2 text-fg-secondary hover:text-fg-primary"
}`}
>
{i}
</button>
);
}
const timeValue =
dateObj && !isNaN(dateObj.getTime())
? `${String(dateObj.getHours()).padStart(2, "0")}:${String(dateObj.getMinutes()).padStart(2, "0")}`
: "";
return (
<div className={`relative ${className}`} ref={containerRef}>
<button
type="button"
onClick={() => setIsOpen(!isOpen)}
aria-label={ariaLabel}
aria-expanded={isOpen}
aria-haspopup="dialog"
title={title}
className={`flex items-center gap-2 bg-surface-2 border ${isOpen ? "border-accent" : "border-border"} rounded px-2 py-1.5 min-w-[150px] text-xs focus:outline-none focus:border-accent transition-colors w-full text-left ${dateObj ? "pr-7" : ""}`}
>
<Calendar className="w-3.5 h-3.5 text-fg-secondary shrink-0" />
<span className={`flex-1 truncate ${!dateObj ? "text-fg-muted" : "text-fg-secondary"}`}>
{dateObj ? formatDisplay(dateObj) : (placeholder ?? t("datePicker.placeholder"))}
</span>
</button>
{/* A sibling, not a child: a button inside a button is not reachable by keyboard. */}
{dateObj && (
<button
type="button"
onClick={clearValue}
aria-label={t("datePicker.clear")}
className="absolute right-1.5 top-1/2 -translate-y-1/2 p-0.5 rounded text-fg-muted hover:text-fg-primary"
>
<X className="w-3 h-3" />
</button>
)}
{isOpen && (
<div
className={`absolute top-full mt-1 ${alignment === "right" ? "right-0" : "left-0"} z-50 bg-surface-1 border border-border rounded-lg shadow-xl p-3 w-[220px] flex flex-col gap-3`}
>
{/* Calendar Header */}
<div className="flex items-center justify-between">
<button
type="button"
onClick={() =>
setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() - 1, 1))
}
aria-label={t("datePicker.prevMonth")}
className="p-1 hover:bg-surface-2 rounded text-fg-secondary hover:text-fg-primary"
>
<ChevronLeft className="w-4 h-4" />
</button>
<span className="text-xs font-medium text-fg-secondary">
{viewDate.toLocaleString(locale, { month: "long", year: "numeric" })}
</span>
<button
type="button"
onClick={() =>
setViewDate(new Date(viewDate.getFullYear(), viewDate.getMonth() + 1, 1))
}
aria-label={t("datePicker.nextMonth")}
className="p-1 hover:bg-surface-2 rounded text-fg-secondary hover:text-fg-primary"
>
<ChevronRight className="w-4 h-4" />
</button>
</div>
{/* Calendar Grid */}
<div>
<div className="grid grid-cols-7 gap-1 mb-1">
{/* 2026-01-04 is a Sunday: seven local days give the weekday initials. */}
{Array.from({ length: 7 }, (_, d) =>
new Date(2026, 0, 4 + d).toLocaleDateString(locale, { weekday: "narrow" })
).map((day, d) => (
<div
key={d}
aria-hidden
className="w-6 text-center text-[10px] font-medium text-fg-muted"
>
{day}
</div>
))}
</div>
<div className="grid grid-cols-7 gap-1">{days}</div>
</div>
{/* Time Picker */}
<div className="pt-3 border-t border-border flex items-center justify-between">
<div className="flex items-center gap-1.5 text-fg-secondary">
<Clock className="w-3.5 h-3.5" />
<span className="text-[11px] font-medium">{t("datePicker.time")}</span>
</div>
<input
type="time"
aria-label={t("datePicker.time")}
value={timeValue}
onChange={handleTimeChange}
className="bg-surface-2 border border-border rounded px-2 py-1 text-xs text-fg-secondary focus:outline-none focus:border-accent w-[85px] time-input-custom"
/>
</div>
</div>
)}
</div>
);
}