"use client"; import { Toaster } from "@suphark/ui/components/ui/sonner"; import { cn } from "@suphark/ui/lib/utils"; import { useTheme } from "next-themes"; import { type ComponentProps, useSyncExternalStore } from "react"; type ToasterTheme = "light" | "dark" | "system"; const THEME_ATTRIBUTES = ["class", "data-theme"]; /** ติดตามธีมที่ `` และ `` (class + data-theme) — ใช้เมื่อไม่มี ThemeProvider เท่านั้น */ function subscribeDocumentTheme(onChange: () => void) { const observer = new MutationObserver(onChange); for (const el of [document.documentElement, document.body]) { if (el) observer.observe(el, { attributes: true, attributeFilter: THEME_ATTRIBUTES }); } return () => observer.disconnect(); } const subscribeNothing = () => () => {}; function themeOf(el: Element | null): ToasterTheme | null { if (!el) return null; const attr = el.getAttribute("data-theme"); if (attr === "dark" || attr === "light") return attr; if (el.classList.contains("dark")) return "dark"; if (el.classList.contains("light")) return "light"; return null; } /** * ธีมของหน้าเมื่อแอปสลับเอง (ไม่มี ThemeProvider): `.dark`/`.light` หรือ `data-theme="dark|light"` ที่ `` * (ก่อน) หรือ `` — สัญญาของแพ็กเกจคือ `.dark` (ตรง `@custom-variant dark`) · ไม่พบ = ตามระบบ */ function getDocumentTheme(): ToasterTheme { return themeOf(document.documentElement) ?? themeOf(document.body) ?? "system"; } const getServerTheme = (): ToasterTheme => "system"; /** * `Toaster` ที่ไม่ชนแถบแท็บล่างบนมือถือ: ยกตำแหน่งบนจอแคบขึ้นเหนือ `MobileTabBar` (ตัวแปร `--tab-bar-height` ที่ `styles.css` * ตั้งให้เองเมื่อหน้ามีแถบแท็บ) + safe-area ล่าง; ไม่มีแถบแท็บ = เหนือขอบล่างเหมือนเดิม · จอกว้างไม่เปลี่ยน * ใช้แทน `` ที่ root layout (รับ props เดียวกัน) * * - ธีม: มี `ThemeProvider` (next-themes) = ตามนั้น · ไม่มี (แอปสลับธีมเอง) = อ่านจาก `.dark`/`.light`/`data-theme` * ของ `` หรือ `` และตามเมื่อเปลี่ยน · ส่ง `theme` เองได้เสมอ * - `richColors` ใช้สีโทนของแพ็กเกจ (ผ่าน AA ทั้งสองธีม) จากคลาส `app-toaster` ใน styles.css — ปรับเองด้วยตัวแปร * `--toast-success-bg` / `--toast-success-text` / `--toast-success-border` (info/warning/error เช่นเดียวกัน) ที่ `:root` * * {children} */ export function AppToaster({ theme, className, ...props }: ComponentProps) { // next-themes ไม่มี provider = context ตั้งต้นที่ไม่มี theme → ไม่มี provider เท่านั้นที่ต้องเฝ้า DOM const { theme: providerTheme } = useTheme(); const watchDocument = theme === undefined && providerTheme === undefined; const documentTheme = useSyncExternalStore( watchDocument ? subscribeDocumentTheme : subscribeNothing, getDocumentTheme, getServerTheme, ); const resolvedTheme = theme ?? (watchDocument ? documentTheme : undefined); return ( ); }