"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` ใน `
`) — `null` / `""` = เริ่มว่าง */ defaultValue?: DateInput; onChange?: (date: Date | null) => void; /** * ชื่อฟิลด์ในฟอร์ม — ส่งค่า `YYYY-MM-DD` (วันที่ local) ไปกับ FormData ของ ``/server action * ว่าง = ส่ง `""` */ name?: string; /** แสดงวันที่สัมพัทธ์ต่อท้าย เช่น "(พรุ่งนี้)" — ค่าเริ่มต้น true */ showRelative?: boolean; } /** ช่วงวันที่ — ทั้งสองฝั่งรวมวันนั้นด้วย (`to` = วันสุดท้ายของช่วง) */ export interface DatePickerRange { from: Date; to: Date; } export interface DatePickerRangeProps extends DatePickerBaseProps { mode: "range"; /** ควบคุมจากภายนอก — แต่ละฝั่งรับ Date หรือ `"YYYY-MM-DD"` · `null` = ว่าง */ value?: { from: DateInput; to: DateInput } | null; /** ค่าเริ่มต้นแบบไม่ควบคุม (ใช้คู่ `name`) */ defaultValue?: { from: DateInput; to: DateInput } | null; onChange?: (range: DatePickerRange | null) => void; /** * ชื่อฟิลด์สองช่อง `[ชื่อวันเริ่ม, ชื่อวันสุดท้าย]` เช่น `["from", "to"]` — ส่ง `YYYY-MM-DD` แยกกัน * (ใช้กับ `` ของตัวกรองได้ตรง ๆ) · ว่าง = `""` ทั้งคู่ */ name?: [string, string]; } export type DatePickerProps = DatePickerSingleProps | DatePickerRangeProps; /** * เลือกวันที่ — วันเดียว (ค่าเริ่มต้น) หรือ `mode="range"` เป็นช่วง · **พิมพ์ในช่องได้เลย** * ("15/3", "15/3/69", "t+3", "t+1m", ช่วง "1/7-5/7", "t-7..t") เห็นผลที่อ่านออกทันทีใต้ช่อง * กด Enter หรือกดผลนั้นเพื่อยืนยัน · ปฏิทินเป็นตัวช่วย (คลิกวัน / คลิกวันเริ่มแล้ววันสุดท้าย) * ใช้ในฟอร์มด้วย `name` · `showSmartInput={false}` = ช่องอ่านอย่างเดียว เปิดปฏิทินอย่างเดียว (แบบเดิม) */ export function DatePicker(props: DatePickerProps) { return props.mode === "range" ? : ; } /** ช่องที่มองไม่เห็นสำหรับส่งค่าไปกับฟอร์ม — ไม่ใช้ type="hidden" เพราะ hidden ไม่ถูกตรวจ `required` */ function FormValue({ name, value, required, disabled, }: { name: string; value: string; required: boolean; disabled: boolean; }) { // อยู่หลังช่องพิมพ์เสมอ: label ที่ครอบ (LabeledField) คลิกแล้วไปที่ช่องพิมพ์ ไม่ใช่ช่องนี้ · ตาข่ายฟอร์มอ่านชื่อจาก label เดียวกัน return ( {}} required={required} disabled={disabled} tabIndex={-1} aria-hidden className="sr-only" /> ); } // ---------- ช่องพิมพ์ + ป๊อปอัปปฏิทิน (ใช้ร่วมกันทั้งวันเดียวและช่วง) ---------- const WEEKDAY_TH = ["อา", "จ", "อ", "พ", "พฤ", "ศ", "ส"]; const WEEKDAY_TH_DOT = ["อา.", "จ.", "อ.", "พ.", "พฤ.", "ศ.", "ส."]; const isThai = (locale?: string) => !locale || locale.toLowerCase().startsWith("th"); /** "จ." / "Mon" ตาม locale — ไม่ส่ง locale = ไทย */ function weekdayShort(date: Date, locale?: string): string { return isThai(locale) ? (WEEKDAY_TH_DOT[date.getDay()] ?? "") : date.toLocaleString(locale, { weekday: "short" }); } /** * ปฏิทินใช้ locale เดียวกับช่อง (ชื่อเดือน/ปี/วัน) — เดิมไม่ส่ง locale แล้วปฏิทินขึ้น "Oct 2026" อังกฤษ * ทั้งที่ช่องแสดง พ.ศ. ไทย · หัวคอลัมน์วันไทยใช้ 2 ตัว (อา จ อ พ พฤ ศ ส) เพราะตัวเดียว "อ"/"พ" กำกวม */ function calendarFormatters(locale?: string) { const tag = locale ?? "th"; return { formatMonthDropdown: (d: Date) => d.toLocaleString(tag, { month: "short" }), formatYearDropdown: (d: Date) => d.toLocaleString(tag, { year: "numeric" }), formatWeekdayName: (d: Date) => isThai(locale) ? (WEEKDAY_TH[d.getDay()] ?? "") : d.toLocaleString(tag, { weekday: "short" }), formatCaption: (d: Date) => d.toLocaleString(tag, { month: "long", year: "numeric" }), }; } /** คลิกชื่อเดือนในหัวปฏิทิน → สลับไปตารางเลือกเดือน/ปี (อยู่ใน shell) */ const OpenMonthsContext = createContext<(() => void) | null>(null); /** หัวปฏิทินแบบ "ตุลาคม 2569 ▾" เป็นปุ่มเดียว (แทนเมนูเลือกเดือน/ปีสองอัน) */ function CaptionButton({ children }: ComponentProps<"span">) { const open = useContext(OpenMonthsContext); if (!open) return {children}; return ( ); } /** ตารางเลือกเดือน (12 ช่อง) + ปีเลื่อนซ้าย/ขวา — ใช้แทนปฏิทินชั่วคราวเมื่อกดหัวปฏิทิน */ function MonthGrid({ month, locale, onPick, startMonth, endMonth, }: { month: Date; locale: string | undefined; onPick: (month: Date) => void; startMonth: Date; endMonth: Date; }) { const tag = locale ?? "th"; const [year, setYear] = useState(month.getFullYear()); const today = new Date(); const yearLabel = (y: number) => new Date(y, 0, 1).toLocaleString(tag, { year: "numeric" }); const step = "flex size-7 items-center justify-center rounded-md text-muted-foreground outline-none hover:bg-accent focus-visible:ring-3 focus-visible:ring-ring/50"; return (
{yearLabel(year)}
{Array.from({ length: 12 }, (_, m) => { const current = year === month.getFullYear() && m === month.getMonth(); const thisMonth = year === today.getFullYear() && m === today.getMonth(); const at = new Date(year, m, 1).getTime(); const outside = at < startMonth.getTime() || at > endMonth.getTime(); const label = new Date(2000, m, 1).toLocaleString(tag, { month: "short" }); return ( ); })}
); } /** ช่วงวันที่ที่เลือกได้ (`minDate`/`maxDate`) — ใช้กับ disabled ของปฏิทิน เดือนที่เลื่อนไปได้ และเหตุผลของค่าที่พิมพ์ */ interface Bounds { lo: Date | undefined; hi: Date | undefined; /** ข้อความเหตุผลที่วันนี้เลือกไม่ได้ (null = เลือกได้) */ reason: (date: Date) => string | null; matchers: Matcher[]; startMonth: Date; endMonth: Date; } function makeBounds( minDate: DateInput, maxDate: DateInput, locale: string | undefined, text: { beforeMin?: string; afterMax?: string } | undefined, ): Bounds { const day = (d: Date) => new Date(d.getFullYear(), d.getMonth(), d.getDate()); const min = toDate(minDate); const max = toDate(maxDate); const lo = min && day(min); const hi = max && day(max); const reason = (date: Date) => { const d = day(date); if (lo && d.getTime() < lo.getTime()) return (text?.beforeMin ?? "เลือกได้ตั้งแต่วันที่ {date}").replace("{date}", formatDate(lo, locale)); if (hi && d.getTime() > hi.getTime()) return (text?.afterMax ?? "เลือกได้ถึงวันที่ {date}").replace("{date}", formatDate(hi, locale)); return null; }; const matchers: Matcher[] = []; if (lo) matchers.push({ before: lo }); if (hi) matchers.push({ after: hi }); return { lo, hi, reason, matchers, // ไม่จำกัด = 1900 ถึงอีก 50 ปีข้างหน้า (เดิม 1990–2040: วันเกิดก่อน 1990 เลื่อนปฏิทินไปไม่ถึง ต้องพิมพ์เอง) startMonth: lo ? new Date(lo.getFullYear(), lo.getMonth(), 1) : new Date(1900, 0), endMonth: hi ? new Date(hi.getFullYear(), hi.getMonth(), 1) : new Date(new Date().getFullYear() + 50, 11), }; } /** ผลอ่านจากข้อความที่พิมพ์ — `label` ที่คนอ่านออก + เดือนที่ปฏิทินควรเลื่อนไปแสดง */ interface DatePreview { label: string; month: Date; /** อ่านออกแต่อยู่นอก `minDate`/`maxDate` — ข้อความเหตุผล (ไม่ยืนยัน ไม่ไฮไลต์ในปฏิทิน) */ blocked?: string; } interface SinglePreview extends DatePreview { date: Date; } interface RangePreview extends DatePreview { range: DatePickerRange; } interface ShellApi { month: Date; setMonth: (month: Date) => void; /** ผลอ่านของข้อความที่กำลังพิมพ์ (null = ไม่ได้พิมพ์/อ่านไม่ออก) */ preview: T | null; /** ปิดป๊อปอัปและจบการพิมพ์ (เรียกหลังเลือกจากปฏิทิน) */ close: () => void; } interface ShellProps { id?: string; locale?: string; /** ค่าที่เลือกอยู่อยู่นอก `minDate`/`maxDate` — ช่องขึ้นสถานะผิด */ invalid?: boolean; startMonth: Date; endMonth: Date; disabled: boolean; className?: string; required: boolean; placeholder: string; /** false = ช่องอ่านอย่างเดียว กดแล้วเปิดปฏิทิน (`showSmartInput={false}`) */ typing: boolean; /** ข้อความของค่าที่เลือกอยู่ ("" = ว่าง) */ display: string; relative: string | null; allowClear: boolean; onClear: () => void; /** เดือนที่ปฏิทินเปิดเมื่อไม่มีอะไรให้โฟกัส (ค่าที่เลือกอยู่ หรือวันนี้) */ initialMonth: Date; parse: (text: string) => T | null; /** ยืนยันข้อความ — คืน false = ใช้ไม่ได้ (อ่านไม่ออก) · ข้อความว่าง = ล้างค่า */ commit: (text: string) => boolean; chips: string[]; sheet: Array<{ code: string; text: string }>; onClose?: () => void; children: (api: ShellApi) => ReactNode; } function DateFieldShell({ id, locale, invalid = false, startMonth, endMonth, disabled, className, required, placeholder, typing, display, relative, allowClear, onClear, initialMonth, parse, commit, chips, sheet, onClose, children, }: ShellProps) { const text = useUiText().datePicker; const previewId = useId(); const [open, setOpen] = useState(false); const [editing, setEditing] = useState(false); // ผูกกับ state แบบทันที — onFocus ที่ถูกเรียกในจังหวะเดียวกับ fill()/onChange ต้องเห็นว่ากำลังพิมพ์อยู่แล้ว // (อ่านจาก state จะได้ค่าเก่า แล้วเขียนทับข้อความที่เพิ่งเติมด้วยค่าเดิม) const editingRef = useRef(false); const markEditing = (value: boolean) => { editingRef.current = value; setEditing(value); }; const [draft, setDraft] = useState(""); const [showSheet, setShowSheet] = useState(false); const [view, setView] = useState<"days" | "months">("days"); const [month, setMonth] = useState(initialMonth); const wrapperRef = useRef(null); const inputRef = useRef(null); const popupRef = useRef(null); // กดเมาส์ในช่องตอน "ยังไม่ได้อยู่ในโหมดพิมพ์" (โฟกัสใหม่ หรือโฟกัสค้างอยู่หลังกด Enter) — เลือกทั้งข้อความตอน // mouseup ให้พิมพ์ทับได้ (เลือกตอน mousedown/focus ไม่ได้ผล: เบราว์เซอร์เคลียร์ทิ้งเมื่อปล่อยเมาส์ แล้วพิมพ์ต่อท้ายค่าเดิม) // โฟกัสด้วย Tab ไม่มี mouseup เลือกได้ทันที const pointerFocus = useRef(false); // โฟกัสที่เราคืนให้ช่องเองหลังเลือกจากปฏิทิน — ห้ามเริ่ม "โหมดพิมพ์" ใหม่ (draft จะเป็นค่าเก่าก่อนยืนยัน) const returningFocus = useRef(false); const shown = editing ? draft : display; const trimmed = draft.trim(); const preview = typing && editing && trimmed !== "" ? parse(draft) : null; const unreadable = typing && editing && trimmed !== "" && preview === null; const example = chips[1] ?? chips[0] ?? "15/3"; const shut = () => { setOpen(false); setShowSheet(false); setView("days"); onClose?.(); }; const openCalendar = () => { if (disabled) return; if (!open) setMonth(preview?.month ?? initialMonth); setOpen(true); }; /** จบการพิมพ์: ข้อความใช้ได้และต่างจากเดิม = ยืนยัน · อ่านไม่ออก = คืนค่าเดิม */ const settle = () => { if (editing && trimmed !== display.trim()) commit(draft); markEditing(false); }; const apply = () => { if (!editing || trimmed === display.trim() || commit(draft)) { markEditing(false); shut(); selectSoon(); } }; const refocusInput = () => { returningFocus.current = true; inputRef.current?.focus(); returningFocus.current = false; }; /** * ยืนยัน/ยกเลิกแล้วช่องยังโฟกัสอยู่ — เลือกข้อความรอไว้ ให้พิมพ์ครั้งต่อไปทับค่าเดิมเลย (ไม่ใช่ต่อท้าย) * รอเฟรมถัดไปให้ช่องแสดงค่าใหม่ก่อน · ข้ามถ้าผู้ใช้เริ่มพิมพ์ไปแล้ว */ const selectSoon = () => { requestAnimationFrame(() => { const el = inputRef.current; if (el && document.activeElement === el && !editingRef.current) el.select(); }); }; /** คีย์บอร์ด: ลูกศรลงตอนปฏิทินเปิดอยู่ = ย้ายโฟกัสเข้าปฏิทิน (ลูกศร/Enter เลือกวันได้ตามปกติของ DayPicker) */ const focusCalendar = () => { const popup = popupRef.current; const day = popup?.querySelector("button[data-day][tabindex='0']") ?? popup?.querySelector("button[data-day]:not([disabled])"); day?.focus(); }; const fill = (value: string) => { markEditing(true); setDraft(value); const next = parse(value); if (next) setMonth(next.month); inputRef.current?.focus(); }; return ( { if (next) return; // คลิกในช่อง/ปุ่มปฏิทินของเราเองนับเป็น "outside press" ของ popover — ไม่ปิด (ไม่งั้นปิดแล้วเปิดกระพริบ) const target = details.event?.target; if ( details.reason === "outside-press" && target instanceof Node && wrapperRef.current?.contains(target) ) { details.cancel(); return; } settle(); shut(); // Escape ตอนโฟกัสอยู่ในปฏิทิน: คืนโฟกัสให้ช่อง ไม่ให้หลุดไป body if (details.reason === "escape-key") refocusInput(); }} > { // Tab ออกจากช่อง = ปิดป๊อปอัป "ก่อน" เบราว์เซอร์ย้ายโฟกัส: ระหว่างเปิด Base UI วางตัวดักโฟกัส // () ต่อท้ายช่อง ถ้ายังอยู่ Tab จะตกไปที่มันแล้วโฟกัสหลุดไป body ไม่ไปช่องถัดไป // (ป๊อปอัปไม่มี animation ตอนปิดโดยตั้งใจ — Base UI รอ animation จบก่อนถอด ตัวดักจึงค้างอยู่ระหว่างนั้น) if (event.key === "Tab" && !event.shiftKey && open) { settle(); shut(); } }} onBlur={(event) => { const next = event.relatedTarget; if ( next instanceof Node && (wrapperRef.current?.contains(next) || popupRef.current?.contains(next)) ) return; settle(); shut(); }} > { pointerFocus.current = !editingRef.current; }} onMouseUp={(event) => { if (!pointerFocus.current) return; pointerFocus.current = false; if (typing && !disabled) { if (!editingRef.current) { markEditing(true); setDraft(display); } event.preventDefault(); inputRef.current?.select(); } }} onFocus={() => { if (!typing || disabled || returningFocus.current) return; if (!editingRef.current) { markEditing(true); setDraft(display); } // โฟกัสด้วย Tab = เลือกทั้งข้อความทันที (พิมพ์ทับได้เลย) · ด้วยเมาส์ เลือกตอน mouseup (ด้านบน) // ไม่เปิดปฏิทินตอนโฟกัส — เปิดเมื่อพิมพ์/คลิก/กดลูกศรลง if (!pointerFocus.current) inputRef.current?.select(); }} onClick={openCalendar} onChange={(event) => { const value = event.target.value; markEditing(true); setDraft(value); const next = parse(value); if (next) setMonth(next.month); setShowSheet(false); setOpen(true); }} onKeyDown={(event) => { if (event.key === "ArrowDown") { event.preventDefault(); if (open) focusCalendar(); else openCalendar(); } else if (event.key === "Enter") { // ยืนยันค่าที่พิมพ์ — ไม่ปล่อยให้ Enter ส่งฟอร์มแม่ระหว่างพิมพ์ if (editing && typing) { event.preventDefault(); apply(); } else if (open) { event.preventDefault(); shut(); } } else if (event.key === "Escape" && (open || editing)) { event.preventDefault(); event.stopPropagation(); markEditing(false); shut(); selectSoon(); } }} /> { if (open) { settle(); shut(); } else { openCalendar(); inputRef.current?.focus(); } }} > {editing && typing && preview && !preview.blocked && ( Enter )} {relative && !editing && ( ({relative}) )} {allowClear && display !== "" && !disabled && ( { markEditing(false); onClear(); // ปุ่มนี้หายเมื่อช่องว่าง — โฟกัสกลับช่องหลัง render (โฟกัสก่อนจะดึงค่าเดิมเข้า draft) requestAnimationFrame(() => inputRef.current?.focus()); }} > )} {/* ใช้ primitive ตรง ๆ ไม่ผ่าน PopoverContent ของ shadcn (ห้ามแก้ไฟล์นั้น): ต้องผูกกับช่องพิมพ์ด้วย `anchor` และ `initialFocus={false}` ให้โฟกัสอยู่ที่ช่อง พิมพ์ต่อได้ตอนปฏิทินเปิด */} เดือน/ปี ที่ต้องรับโฟกัสถึงจะเปิดรายการ) onMouseDown={(event) => { if (!(event.target as Element).closest("select, option, input, textarea")) { event.preventDefault(); } }} className="z-50 flex w-[306px] pointer-coarse:w-[min(340px,calc(100vw-1rem))] origin-(--transform-origin) flex-col gap-2 text-sm text-popover-foreground outline-hidden duration-100 data-[side=bottom]:slide-in-from-top-2 data-[side=top]:slide-in-from-bottom-2 data-open:animate-in data-open:fade-in-0 data-open:zoom-in-95" > {typing && trimmed !== "" && editing && (
{preview?.blocked ? (

{preview.blocked}

) : preview ? ( ) : ( unreadable && (

{(text?.cannotRead ?? "อ่านไม่ออก — ลองพิมพ์ {example}").replace( "{example}", example, )}

) )}
)}
{showSheet ? (
{text?.allShortcuts ?? "พิมพ์ลัดทั้งหมด"} {text?.tapToFill ?? "กดเพื่อเติมในช่อง"}
{sheet.map((row) => (
{row.text}
))}
) : view === "months" ? ( { setMonth(next); setView("days"); }} /> ) : ( setView("months")}> {children({ month, setMonth, preview, close: () => { markEditing(false); shut(); refocusInput(); selectSoon(); }, })} )} {typing && (
{showSheet ? ( ) : ( <> {text?.shortcutsLabel ?? "พิมพ์ลัด"} {chips.map((chip) => ( ))} )}
)}
); } // ---------- วันเดียว ---------- function SingleDatePicker({ id, value, defaultValue, onChange, name, required = false, locale, placeholder, disabled = false, allowClear = true, className, showSmartInput = true, showRelative = true, minDate, maxDate, }: DatePickerSingleProps) { const text = useUiText().datePicker; const bounds = makeBounds(minDate, maxDate, locale, text); const mounted = useMounted(); // ไม่ควบคุม = มี defaultValue หรือไม่มีทั้ง value และ onChange (เช่นใช้แค่ name ในฟอร์ม) const controlled = value !== undefined || (defaultValue === undefined && onChange !== undefined); const [own, setOwn] = useState(() => toDate(defaultValue) ?? null); const selectedDate = controlled ? toDate(value) : (own ?? undefined); const change = (date: Date | null) => { if (!controlled) setOwn(date); onChange?.(date); }; const parse = (input: string): SinglePreview | null => { const date = parseSmartDateInput(input); if (!date) return null; return { date, month: date, label: `${weekdayShort(date, locale)} ${formatDate(date, locale)} · ${formatRelative(date, locale)}`, blocked: bounds.reason(date) ?? undefined, }; }; const sheet = [ { code: "15/3", text: text?.helpDate ?? "15 มี.ค. ปีนี้ (ไม่ใส่ปี = ปีปัจจุบัน)" }, { code: "15/3/69 · 15/3/2026", text: text?.helpYear ?? "ใส่ปี พ.ศ. หรือ ค.ศ. ได้ (2 หรือ 4 หลัก)" }, { code: "t", text: text?.helpToday ?? "วันนี้" }, { code: "t+3 · t-2", text: text?.helpDays ?? "อีก 3 วัน · 2 วันก่อน (d = วัน)" }, { code: "t+2w · t+1m · t+1y", text: text?.helpUnits ?? "สัปดาห์ · เดือน · ปี" }, ]; return ( <> id={id} locale={locale} invalid={Boolean(selectedDate && bounds.reason(selectedDate))} startMonth={bounds.startMonth} endMonth={bounds.endMonth} disabled={disabled} className={className} required={required} typing={showSmartInput} placeholder={ placeholder ?? (showSmartInput ? (text?.smartPlaceholder ?? "เช่น 15/3, t+3, t+1m") : (text?.placeholder ?? "เลือกวันที่")) } display={selectedDate ? formatDate(selectedDate, locale) : ""} // วันที่สัมพัทธ์ขึ้นกับ "วันนี้" ของเครื่องผู้ใช้ — แสดงหลัง mount กัน hydration mismatch relative={ showRelative && mounted && selectedDate ? formatRelative(selectedDate, locale) : null } allowClear={allowClear} onClear={() => change(null)} initialMonth={selectedDate ?? new Date()} parse={parse} commit={(input) => { if (input.trim() === "") { if (!allowClear) return false; change(null); return true; } const next = parse(input); if (!next || next.blocked) return false; change(next.date); return true; }} chips={["t", "t+3", "t+1m", "15/3"]} sheet={sheet} > {(api) => ( { change(date ?? api.preview?.date ?? selectedDate ?? null); api.close(); }} month={api.month} onMonthChange={api.setMonth} disabled={disabled ? true : bounds.matchers} captionLayout="label" startMonth={bounds.startMonth} endMonth={bounds.endMonth} formatters={calendarFormatters(locale)} components={{ DayButton: FocusableDayButton, CaptionLabel: CaptionButton }} className="p-0 [--cell-size:--spacing(10)]" /> )} {name !== undefined && ( )} ); } // ---------- ช่วงวันที่ ---------- /** "1 – 5 ก.ค. 2569" / "1–5 Jul 2026" — ใช้ formatRange ของ Intl (ย่อเดือน/ปีที่ซ้ำให้เอง) */ function formatRange(range: DatePickerRange, locale: string | undefined): string { const fmt = new Intl.DateTimeFormat(locale ?? "th-TH", { day: "numeric", month: "short", year: "numeric", }); return fmt.formatRange(range.from, range.to); } function toRange(value: { from: DateInput; to: DateInput } | null | undefined) { const from = toDate(value?.from); const to = toDate(value?.to); if (!from || !to) return undefined; return from.getTime() <= to.getTime() ? { from, to } : { from: to, to: from }; } function RangeDatePicker({ id, value, defaultValue, onChange, name, required = false, locale, placeholder, disabled = false, className, allowClear = true, showSmartInput = true, minDate, maxDate, }: DatePickerRangeProps) { const text = useUiText().datePicker; const bounds = makeBounds(minDate, maxDate, locale, text); const controlled = value !== undefined || (defaultValue === undefined && onChange !== undefined); const [own, setOwn] = useState(() => toRange(defaultValue) ?? null); // ระหว่างคลิกเลือก: คลิกแรก = วันเริ่ม (ยังไม่ปิด) คลิกที่สอง = วันสุดท้าย แล้วปิด const [start, setStart] = useState(null); const selected = controlled ? toRange(value) : (own ?? undefined); const change = (range: DatePickerRange | null) => { if (!controlled) setOwn(range); onChange?.(range); }; const parse = (input: string): RangePreview | null => { // พิมพ์วันเดียว ("t", "15/3") ในช่องช่วง = ช่วงหนึ่งวัน const range = parseSmartDateRange(input) ?? (() => { const day = parseSmartDateInput(input); return day ? { from: day, to: day } : null; })(); if (!range) return null; const days = differenceInCalendarDays(range.to, range.from) + 1; return { range, month: range.from, blocked: bounds.reason(range.from) ?? bounds.reason(range.to) ?? undefined, label: days === 1 ? `${weekdayShort(range.from, locale)} ${formatDate(range.from, locale)}` : `${formatRange(range, locale)} · ${(text?.dayCount ?? "{count} วัน").replace("{count}", String(days))}`, }; }; const sheet = [ { code: "t-7..t", text: text?.helpRangeShortcut ?? "ช่วงจากตัวย่อ (คั่นด้วย .. ~ ถึง to)" }, { code: "1/7-5/7 · 1-5/7", text: text?.helpRange ?? "1–5 ก.ค." }, { code: "15/3", text: text?.helpDate ?? "15 มี.ค. ปีนี้ (ไม่ใส่ปี = ปีปัจจุบัน)" }, { code: "t+3 · t-2", text: text?.helpDays ?? "อีก 3 วัน · 2 วันก่อน (d = วัน)" }, { code: "t+2w · t+1m · t+1y", text: text?.helpUnits ?? "สัปดาห์ · เดือน · ปี" }, ]; return ( <> id={id} locale={locale} invalid={Boolean(selected && (bounds.reason(selected.from) || bounds.reason(selected.to)))} startMonth={bounds.startMonth} endMonth={bounds.endMonth} disabled={disabled} className={className} required={required} typing={showSmartInput} placeholder={ placeholder ?? (showSmartInput ? (text?.rangeSmartPlaceholder ?? "เช่น 1/7-5/7, t-7..t") : (text?.rangePlaceholder ?? "เลือกช่วงวันที่")) } display={selected ? formatRange(selected, locale) : ""} relative={null} allowClear={allowClear} onClear={() => change(null)} initialMonth={selected?.from ?? new Date()} parse={parse} commit={(input) => { if (input.trim() === "") { if (!allowClear) return false; change(null); return true; } const next = parse(input); if (!next || next.blocked) return false; change(next.range); return true; }} chips={["t-7..t", "1/7-5/7", "t ~ t+1m"]} sheet={sheet} onClose={() => setStart(null)} > {(api) => ( <> { // คุมสองคลิกเอง: react-day-picker คลิกแรกให้ from = to (ช่วงหนึ่งวัน) จึงแยกคลิกแรกไม่ออก if (!start) { setStart(day); return; } change( day.getTime() < start.getTime() ? { from: day, to: start } : { from: start, to: day }, ); api.close(); }} month={api.month} onMonthChange={api.setMonth} disabled={disabled ? true : bounds.matchers} captionLayout="label" startMonth={bounds.startMonth} endMonth={bounds.endMonth} formatters={calendarFormatters(locale)} components={{ DayButton: FocusableDayButton, CaptionLabel: CaptionButton }} className="p-0 [--cell-size:--spacing(10)]" /> {start && (

{text?.pickEnd ?? "เลือกวันสุดท้ายของช่วง"}

)} )} {name !== undefined && ( <> )} ); }