"use client"; import { Popover as PopoverPrimitive } from "@base-ui/react/popover"; import { FocusableDayButton } from "@suphark/ui/components/shared/date/accessible-calendar"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { Calendar } from "@suphark/ui/components/ui/calendar"; import { InputGroup, InputGroupAddon, InputGroupButton, InputGroupInput, } from "@suphark/ui/components/ui/input-group"; import { useMounted } from "@suphark/ui/hooks/use-mounted"; import { formatRelativeCalendarDate, formatThaiFullDate } from "@suphark/ui/lib/formatters"; import { cn } from "@suphark/ui/lib/utils"; import { addDays, addMonths, addWeeks, addYears, differenceInCalendarDays } from "date-fns"; import { CalendarIcon, CheckIcon, ChevronDownIcon, ChevronLeftIcon, ChevronRightIcon, X, } from "lucide-react"; import { type ComponentProps, createContext, type ReactNode, useContext, useId, useRef, useState, } from "react"; import type { Matcher } from "react-day-picker"; /** * Smart date parser supporting intuitive Thai & international date inputs: * - "1/7" -> 1 July of current year * - "1/7/25" -> 1 July 2025 CE * - "1/7/68" -> 1 July 2025 CE (BE 2568) * - "1/7/2568" -> 1 July 2025 CE (BE 2568) */ export function parseSmartDateInput(input: string): Date | null { if (!input?.trim()) return null; const clean = input.trim().replace(/\s+/g, ""); const shortcut = parseDateShortcut(clean); if (shortcut) return shortcut; const parts = clean.split(/[/\-.]/); if (parts.length < 2 || parts.length > 3) return null; const day = parseInt(parts[0] ?? "", 10); const month = parseInt(parts[1] ?? "", 10); if (Number.isNaN(day) || Number.isNaN(month) || day < 1 || day > 31 || month < 1 || month > 12) { return null; } const currentYear = new Date().getFullYear(); let year = currentYear; if (parts.length === 3 && parts[2]) { const rawYear = parseInt(parts[2], 10); if (Number.isNaN(rawYear)) return null; if (rawYear > 2400) { // Full Buddhist Era year (e.g. 2568 -> 2025 CE) year = rawYear - 543; } else if (rawYear >= 50 && rawYear < 100) { // Short BE year (e.g. 68 -> 2568 -> 2025 CE) year = 2500 + rawYear - 543; } else if (rawYear < 50) { // Short AD year (e.g. 25 -> 2025 CE) year = 2000 + rawYear; } else { year = rawYear; } } const d = new Date(year, month - 1, day); if (d.getFullYear() === year && d.getMonth() === month - 1 && d.getDate() === day) { return d; } return null; } /** * ตัวย่อวันที่: `t` = วันนี้ · `t+3` / `t+3d` = อีก 3 วัน · `t-2` = 2 วันก่อน · `t+2w` สัปดาห์ · `t+1m` เดือน · `t+1y` ปี * (`today` / `วันนี้` แทน `t` ได้, หน่วยไทย วัน/สัปดาห์/เดือน/ปี ก็ได้) */ function parseDateShortcut(clean: string): Date | null { const match = /^(?:t|today|วันนี้)(?:([+-])(\d{1,4})(d|w|m|y|วัน|สัปดาห์|อาทิตย์|เดือน|ปี)?)?$/i.exec( clean, ); if (!match) return null; const now = new Date(); const today = new Date(now.getFullYear(), now.getMonth(), now.getDate()); if (!match[1]) return today; const amount = Number(match[2]) * (match[1] === "-" ? -1 : 1); switch ((match[3] ?? "d").toLowerCase()) { case "w": case "สัปดาห์": case "อาทิตย์": return addWeeks(today, amount); case "m": case "เดือน": return addMonths(today, amount); case "y": case "ปี": return addYears(today, amount); default: return addDays(today, amount); } } /** * พิมพ์ช่วงวันที่: "1/7-5/7" (1–5 ก.ค.), "1-5/7", "1/7 - 5/8/68", "1/7 ถึง 5/7", "1/7 to 5/7", "1/7–5/7", * ตัวย่อ "t-7..t", "t ~ t+1m" · ไม่ได้พิมพ์ปี = ปีปัจจุบัน · ใส่กลับด้านได้ (สลับให้) * `-` เป็นตัวคั่นช่วงเมื่อมี `/` หรือ `.` อยู่ด้วยเท่านั้น ("1-7-2568" และ "t-3" ยังเป็นวันเดียว) — ตัวย่อใช้ `..`/`~`/`ถึง`/`to` */ export function parseSmartDateRange(input: string): { from: Date; to: Date } | null { const raw = input?.trim(); if (!raw) return null; let parts = raw.split(/\s*(?:–|—|~|\.\.|ถึง|\bto\b)\s*|\s+-\s+/i).filter((p) => p.trim() !== ""); if (parts.length !== 2) { const dashes = raw.split("-"); if (dashes.length !== 2 || !/[/.]/.test(raw)) return null; parts = dashes; } const left = (parts[0] ?? "").trim(); const right = (parts[1] ?? "").trim(); const to = parseSmartDateInput(right); if (!to) return null; let from = parseSmartDateInput(left); if (!from) { // "1-5/7" → ฝั่งซ้ายมีแค่วัน ใช้เดือน/ปีของฝั่งขวา if (!/^\d{1,2}$/.test(left)) return null; from = new Date(to.getFullYear(), to.getMonth(), Number(left)); if (from.getMonth() !== to.getMonth()) return null; } else if (/^\d{1,2}[/.]\d{1,2}$/.test(left) && /^\d{1,2}[/.]\d{1,2}[/.]\d{2,4}$/.test(right)) { // "1/7 - 5/8/68" → ฝั่งซ้ายไม่ได้พิมพ์ปี ใช้ปีของฝั่งขวา (ถ้าเลยฝั่งขวา = ปีก่อนหน้า เช่น "20/12 - 5/1/69") from = new Date(to.getFullYear(), from.getMonth(), from.getDate()); if (from.getTime() > to.getTime()) { from = new Date(to.getFullYear() - 1, from.getMonth(), from.getDate()); } } return from.getTime() <= to.getTime() ? { from, to } : { from: to, to: from }; } type DateInput = Date | string | number | null | undefined; /** * แปลงค่าที่รับมาเป็น Date — `"YYYY-MM-DD"` อ่านเป็นวันที่ local * (`new Date("2027-10-02")` อ่านเป็น UTC เที่ยงคืน → ฝั่งตะวันตกของ UTC กลายเป็นวันก่อนหน้า) */ function toDate(value: DateInput): Date | undefined { if (value === null || value === undefined || value === "") return undefined; if (typeof value === "string") { const ymd = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value); if (ymd) return new Date(Number(ymd[1]), Number(ymd[2]) - 1, Number(ymd[3])); } const date = value instanceof Date ? value : new Date(value); return Number.isNaN(date.getTime()) ? undefined : date; } /** `YYYY-MM-DD` ตามวันที่ local (ไม่ใช่ toISOString ที่เลื่อนวันตาม timezone) — ค่าที่ส่งในฟอร์ม */ export function toDateInputValue(date: Date | null | undefined): string { if (!date) return ""; const pad = (n: number) => String(n).padStart(2, "0"); return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`; } /** "2 Oct 2027" / "2 ต.ค. 2570" ตาม locale — ไม่ส่ง locale = รูปแบบไทยเดิม (เดือนย่อ + พ.ศ.) */ function formatDate(date: Date, locale: string | undefined): string { // วันที่จาก DatePicker = เที่ยงคืนของเครื่อง → นับวันตามโซนของเครื่อง (โซนไทยจะเลื่อนวันในโซนที่อยู่ทางตะวันออก) if (!locale) return formatThaiFullDate(date, { timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone, }); return new Intl.DateTimeFormat(locale, { day: "numeric", month: "short", year: "numeric", }).format(date); } /** "พรุ่งนี้" / "in 3 days" — นับเป็นวันตามปฏิทิน (ไม่ส่ง locale = ไทย) */ function formatRelative(date: Date, locale: string | undefined): string { return formatRelativeCalendarDate(date, locale ?? "th"); } interface DatePickerBaseProps { id?: string; /** ต้องเลือกวันที่ก่อนส่งฟอร์ม — ไม่เลือกแล้วกดส่ง เบราว์เซอร์บล็อกและตาข่ายฟอร์มบอกชื่อช่องให้ */ required?: boolean; /** * ภาษาของวันที่ (BCP 47 เช่น "en", "th") — แสดงแบบ "2 Oct 2027" / "2 ต.ค. 2570" ทั้งในช่อง ปฏิทิน และวันที่สัมพัทธ์ * ไม่ส่ง = รูปแบบไทยเดิม · ข้อความอื่นมาจาก `UiText.datePicker` */ locale?: string; /** ไม่ส่ง = `UiText.datePicker.placeholder` */ placeholder?: string; disabled?: boolean; className?: string; allowClear?: boolean; /** @deprecated 0.42.0 — ปุ่มทางลัดถูกแทนด้วยการพิมพ์ลัด (`t`, `t+3`, `t+1m` …) ใส่ได้แต่ไม่มีผล */ showPresets?: boolean; /** พิมพ์ในช่องได้ (ค่าเริ่มต้น true) · false = ช่องอ่านอย่างเดียว กดแล้วเปิดปฏิทิน */ showSmartInput?: boolean; /** * วันต่ำสุด/สูงสุดที่เลือกได้ (`"YYYY-MM-DD"` | Date, รวมวันนั้นด้วย) — ใช้ได้ทั้งวันเดียวและ `mode="range"` (ทั้งสองฝั่งต้องอยู่ในช่วง) * ปฏิทินกดวันนอกช่วงไม่ได้ · ค่าที่พิมพ์แล้วอยู่นอกช่วง = ไม่ยืนยัน + บอกเหตุผลใต้ช่อง (`UiText.datePicker.beforeMin`/`afterMax`) * ค่าที่ส่งเข้ามาเองนอกช่วงไม่ถูกแก้ แค่ช่องขึ้นสถานะผิด (`aria-invalid`) */ minDate?: DateInput; maxDate?: DateInput; } export interface DatePickerSingleProps extends DatePickerBaseProps { /** `"single"` (ค่าเริ่มต้น) = วันเดียว · `"range"` = ช่วงวันที่ */ mode?: "single"; /** ควบคุมจากภายนอก (`"YYYY-MM-DD"` อ่านเป็นวันที่ local) — ใช้แบบไม่ควบคุมให้ส่ง `defaultValue` แทน */ value?: DateInput; /** ค่าเริ่มต้นแบบไม่ควบคุม (ใช้คู่ `name` ใน `