"use client"; import { useEffect, useState } from "react"; /** ชิ้นส่วนของ `components/ui/drawer` (Drawer, DrawerContent, DrawerTitle …) */ export type DrawerParts = typeof import("@suphark/ui/components/ui/drawer"); let loaded: DrawerParts | null = null; let loading: Promise | null = null; /** โหลดโมดูล Drawer (ครั้งเดียวทั้งแอป) — เรียกล่วงหน้าได้ เช่นในเทสต์ หรือก่อนเปิดแผ่นแรก */ export function preloadDrawer(): Promise { loading ??= import("@suphark/ui/components/ui/drawer").then( (mod) => { loaded = mod; return mod; }, (error: unknown) => { // โหลด chunk ไม่ได้ (เน็ตหลุด/deploy ใหม่) — ให้ลองใหม่ได้ครั้งหน้า loading = null; throw error; }, ); return loading; } /** * Drawer (แผ่นล่างมือถือ) แบบโหลดเมื่อต้องใช้ (0.96.0, P4) — จอกว้างไม่โหลดโค้ด Drawer เลย * `enabled` = ต้องการแผ่นล่างหรือไม่ (ปกติ `sheetOnMobile && isMobile`) → เริ่มโหลด · คืน null จนกว่าจะโหลดเสร็จ * (โหลดแล้วคืนค่าเสมอแม้ `enabled` กลับเป็น false — แบบที่ตรึงไว้ระหว่างเปิดยัง render ต่อได้) * ระหว่างนั้น component แสดงแบบจอกว้างไปก่อน (แบบเดียวกับตอน hydrate) — ไม่มี Suspense ปุ่มเปิดไม่หายวูบ * โหลดแล้วครั้งหนึ่ง component ที่ mount ทีหลังได้ทันทีตั้งแต่ render แรก */ export function useLazyDrawer(enabled: boolean): DrawerParts | null { const [parts, setParts] = useState(loaded); useEffect(() => { if (!enabled || parts) return; let alive = true; preloadDrawer().then( (mod) => { if (alive) setParts(mod); }, // โหลดไม่ได้ = แสดงแบบจอกว้างต่อไป (ยังใช้งานได้ครบ) () => {}, ); return () => { alive = false; }; }, [enabled, parts]); // โหลดโดย component อื่นหลังตัวนี้ mount — ใช้ได้ทันทีใน render นี้ (ไม่ต้องรอ effect อีกรอบ) return parts ?? loaded; } /** ชิ้นส่วน Drawer ถ้าโหลดแล้ว (ไม่ subscribe) — สำหรับ component จำนวนมากที่ไม่อยาก re-render พร้อมกันตอนโหลดเสร็จ */ export function getLoadedDrawer(): DrawerParts | null { return loaded; }