"use client"; import { useMounted } from "@suphark/ui/hooks/use-mounted"; import { getNumberFormat } from "@suphark/ui/lib/intl-cache"; import { useMemo } from "react"; /** ค่าทศนิยมแบบ object (เช่น Prisma.Decimal, decimal.js) — ขอแค่ toString() ให้ตัวเลข */ export interface DecimalLike { toString(): string; } interface FormattedNumberProps { /** Decimal-like (Prisma.Decimal / decimal.js), number, string, null หรือ undefined */ value: DecimalLike | number | string | null | undefined; /** Intl.NumberFormatOptions — ค่าเริ่มต้น { style: 'decimal', minimumFractionDigits: 2, maximumFractionDigits: 2 } */ options?: Intl.NumberFormatOptions; /** ค่าเริ่มต้น th-TH */ locale?: string; /** ข้อความก่อน mount / ค่าไม่ถูกต้อง ค่าเริ่มต้น "-" */ placeholder?: string; className?: string; } const DEFAULT_OPTIONS: Intl.NumberFormatOptions = { style: "decimal", minimumFractionDigits: 2, maximumFractionDigits: 2, }; /** * รวม options ของผู้ใช้กับค่าเริ่มต้น — ตั้งแค่ฝั่งเดียว (เช่น `maximumFractionDigits: 0`) อีกฝั่งปรับตามให้ * (เดิม min 2 > max 0 → Intl โยน RangeError แล้วแสดง "-") */ export function resolveNumberOptions(user?: Intl.NumberFormatOptions): Intl.NumberFormatOptions { const opts = { ...DEFAULT_OPTIONS, ...user }; const min = user?.minimumFractionDigits; const max = user?.maximumFractionDigits; if (max !== undefined && min === undefined) { opts.minimumFractionDigits = Math.min(DEFAULT_OPTIONS.minimumFractionDigits ?? 0, max); } else if (min !== undefined && max === undefined) { opts.maximumFractionDigits = Math.max(DEFAULT_OPTIONS.maximumFractionDigits ?? 0, min); } return opts; } function toNumber(value: FormattedNumberProps["value"]): number { if (value === null || value === undefined || value === "") return Number.NaN; if (typeof value === "object") return Number(value.toString()); return Number(value); } /** * แสดงตัวเลขตาม locale ฝั่ง client หลัง mount (กัน hydration mismatch จาก locale ของ server) * ตัว Intl.NumberFormat ถูก cache ต่อ locale+options — ตารางหลายร้อยเซลล์ไม่สร้างซ้ำ * * * * */ export function FormattedNumber({ value, options: userOptions, locale = "th-TH", placeholder = "-", className, }: FormattedNumberProps) { const mounted = useMounted(); const optionsKey = userOptions ? JSON.stringify(userOptions) : ""; const numeric = toNumber(value); const text = useMemo(() => { if (!mounted || Number.isNaN(numeric)) return placeholder; try { const opts = resolveNumberOptions( optionsKey ? (JSON.parse(optionsKey) as Intl.NumberFormatOptions) : undefined, ); return getNumberFormat(locale, opts).format(numeric); } catch (error) { console.error("FormattedNumber:", error); return placeholder; } }, [mounted, numeric, optionsKey, locale, placeholder]); return {text}; }