"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { AccessibleCalendar } from "@suphark/ui/components/shared/date/accessible-calendar"; import { ResponsivePopover, ResponsivePopoverContent, ResponsivePopoverTrigger, } from "@suphark/ui/components/shared/responsive-popover"; import { useMounted } from "@suphark/ui/hooks/use-mounted"; import { cn } from "@suphark/ui/lib/utils"; import { CalendarClockIcon } from "lucide-react"; import { useState } from "react"; import { th } from "react-day-picker/locale/th"; import { useUiText } from "../ui-text"; import { pad, splitTime, TimeColumns, type TimeValue, toLocalDateTimeString, useControllable, } from "./time-picker"; /** "YYYY-MM-DDTHH:mm+07:00" — เวลาท้องถิ่นพร้อม offset (ISO 8601) ให้ server ที่อยู่โซนอื่น parse ได้ถูก */ function toOffsetDateTimeString(date: Date): string { const offset = -date.getTimezoneOffset(); const sign = offset >= 0 ? "+" : "-"; const abs = Math.abs(offset); return `${toLocalDateTimeString(date)}${sign}${pad(Math.floor(abs / 60))}:${pad(abs % 60)}`; } /** * เลือกวัน + เวลาในกล่องเดียว (ปฏิทิน + คอลัมน์ชั่วโมง/นาที) — นัดหมาย, กำหนดส่ง, เวลาเตือน * ค่าเป็น `Date | null`; เลือกวันก่อนเวลา = ใช้ `defaultTime`; `name` ส่ง "YYYY-MM-DDTHH:mm+07:00" (เวลาท้องถิ่น + offset) * ใน FormData → `new Date(formData.get(name))` บน server (UTC) ได้เวลาที่ถูกต้อง * ข้อความวัน/เวลาแสดงหลัง hydrate (server กับ browser อยู่คนละโซนเวลา — กัน hydration mismatch) * * */ export function DateTimePicker({ value, defaultValue = null, onValueChange, minuteStep = 5, defaultTime = "09:00", name, id, disabled, placeholder, className, "aria-label": ariaLabel, "aria-invalid": ariaInvalid, }: { value?: Date | null; defaultValue?: Date | null; onValueChange?: (value: Date | null) => void; minuteStep?: number; /** เวลาที่ใช้เมื่อเลือกวันครั้งแรก */ defaultTime?: TimeValue; name?: string; id?: string; disabled?: boolean; placeholder?: string; className?: string; "aria-label"?: string; "aria-invalid"?: boolean; }) { const ui = useUiText(); const text = ui.time; const [date, setDate] = useControllable(value, defaultValue, onValueChange); const [open, setOpen] = useState(false); const mounted = useMounted(); const time = date ? `${pad(date.getHours())}:${pad(date.getMinutes())}` : null; const withTime = (day: Date, t: TimeValue) => { const [h, m] = splitTime(t) ?? [9, 0]; const d = new Date(day); d.setHours(h, m, 0, 0); return d; }; const label = !date ? (placeholder ?? text?.dateTimePlaceholder ?? "เลือกวันและเวลา") : !mounted ? " " // ก่อน hydrate: เว้นที่ไว้ ไม่แสดงเวลาของ server : date.toLocaleString("th-TH", { dateStyle: "medium", timeStyle: "short" }); return ( } > {label} {name && ( )} setDate(null)} > {text?.clear ?? "ล้าง"} setOpen(false)}> {ui.done} } > day && setDate(withTime(day, time ?? defaultTime))} className="p-3" /> setDate(withTime(date ?? new Date(), t))} /> ); }