/** * @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ĩ */ /* ============================================================================= * 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(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) => { 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(
); } 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( ); } const timeValue = dateObj && !isNaN(dateObj.getTime()) ? `${String(dateObj.getHours()).padStart(2, "0")}:${String(dateObj.getMinutes()).padStart(2, "0")}` : ""; return (
{/* A sibling, not a child: a button inside a button is not reachable by keyboard. */} {dateObj && ( )} {isOpen && (
{/* Calendar Header */}
{viewDate.toLocaleString(locale, { month: "long", year: "numeric" })}
{/* Calendar Grid */}
{/* 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) => (
{day}
))}
{days}
{/* Time Picker */}
{t("datePicker.time")}
)}
); }