"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { useUiText } from "@suphark/ui/components/shared/ui-text"; import { useIsMobile } from "@suphark/ui/hooks/use-mobile"; import { cn } from "@suphark/ui/lib/utils"; import { XIcon } from "lucide-react"; import { type KeyboardEvent, type ReactNode, type RefObject, useCallback, useEffect, useId, useLayoutEffect, useRef, useState, } from "react"; import { createPortal } from "react-dom"; export interface TourStep { /** สิ่งที่จะเน้น: CSS selector, ref หรือฟังก์ชันคืน element — หาไม่เจอ = ข้ามขั้นนี้ */ target: string | RefObject | (() => Element | null); title: ReactNode; body?: ReactNode; /** ตำแหน่งการ์ดบนจอกว้าง (ค่าเริ่มต้น auto = ล่าง ถ้าไม่พอใช้บน) — จอแคบเป็นแผ่นล่างเสมอ */ placement?: "auto" | "top" | "bottom"; /** ให้กดสิ่งที่เน้นได้ระหว่างทัวร์ (ค่าเริ่มต้น false = พื้นมืดกันการกดทั้งหมด) */ interactive?: boolean; } export interface TourProps { steps: ReadonlyArray; open?: boolean; onOpenChange?: (open: boolean) => void; /** เปิดเองตอน mount (uncontrolled) — ถ้ามี `storageKey` และเคยดูจบ/ข้ามแล้วจะไม่เปิด */ defaultOpen?: boolean; /** จำว่าดูแล้ว (localStorage) — ไม่ส่ง = ไม่จำ */ storageKey?: string; /** ดูครบทุกขั้น (กด "เสร็จสิ้น") */ onFinish?: () => void; className?: string; } const PAD = 6; const STORAGE_PREFIX = "ui:tour:"; function resolve(target: TourStep["target"]): Element | null { if (typeof document === "undefined") return null; if (typeof target === "string") return document.querySelector(target); if (typeof target === "function") return target(); return target.current; } /** ดูทัวร์นี้แล้วหรือยัง (localStorage) — ใช้ตัดสินว่าจะแสดงปุ่ม "ดูวิธี" ไหม ฯลฯ */ export function hasSeenTour(storageKey: string): boolean { try { return localStorage.getItem(STORAGE_PREFIX + storageKey) !== null; } catch { return false; } } /** * แนะนำการใช้งานทีละจุด — เน้นองค์ประกอบด้วยช่องสว่างกลางพื้นมืด + การ์ด "ชื่อ / คำอธิบาย / 2 จาก 4 / ย้อน · ถัดไป · ข้าม" * จอกว้างการ์ดลอยใต้/เหนือเป้าหมาย · จอแคบเป็นแผ่นล่าง (ปุ่ม 48px) · Esc/ข้าม = ปิด (และจำว่าดูแล้วถ้ามี `storageKey`) * กดพื้นมืดไม่ปิด (กันปิดพลาด) · เป้าหมายหาไม่เจอ = ข้ามขั้นนั้น · การ์ดเป็น dialog โฟกัสวนอยู่ในการ์ด * * */ export function Tour({ steps, open: controlled, onOpenChange, defaultOpen = false, storageKey, onFinish, className, }: TourProps) { const text = useUiText().tour; const isMobile = useIsMobile(); const [inner, setInner] = useState(false); const open = controlled ?? inner; const [index, setIndex] = useState(0); const [rect, setRect] = useState(null); const cardRef = useRef(null); const titleId = useId(); const bodyId = useId(); // เปิดเองครั้งแรก (ถ้ายังไม่เคยดู) useEffect(() => { if (controlled !== undefined || !defaultOpen) return; if (storageKey && hasSeenTour(storageKey)) return; setInner(true); }, [controlled, defaultOpen, storageKey]); const setOpen = useCallback( (next: boolean) => { if (controlled === undefined) setInner(next); onOpenChange?.(next); if (!next) setIndex(0); }, [controlled, onOpenChange], ); const markSeen = useCallback(() => { if (!storageKey) return; try { localStorage.setItem(STORAGE_PREFIX + storageKey, String(Date.now())); } catch {} }, [storageKey]); const close = useCallback(() => { markSeen(); setOpen(false); }, [markSeen, setOpen]); const step = steps[index]; const last = index === steps.length - 1; // มีขั้นที่ได้แสดงจริงแล้วหรือยัง — ไม่มีเลย (เป้ายังไม่ render) ห้ามจำว่า "ดูแล้ว" ไม่งั้นผู้ใช้ไม่เคยเห็นทัวร์อีก const shownAny = useRef(false); useEffect(() => { if (!open) shownAny.current = false; }, [open]); // ขั้นล่าสุดใน ref — effect ผูกกับ index ไม่ใช่ object `step` (แอปส่ง steps ใหม่ทุก render = เลื่อนหน้าทุก render) const stepRef = useRef(step); stepRef.current = step; const close_ = useRef(close); close_.current = close; const setOpen_ = useRef(setOpen); setOpen_.current = setOpen; // คืนโฟกัสให้ element ที่โฟกัสอยู่ก่อนเปิดทัวร์ (ปุ่ม "ดูทัวร์" ฯลฯ) — เดิมหลุดไป useEffect(() => { if (!open) return; const previous = document.activeElement as HTMLElement | null; return () => { if (previous?.isConnected) previous.focus?.(); }; }, [open]); // หาเป้าหมาย + วัดตำแหน่ง (ตามการเลื่อน/ย่อขยายจอ) · หาไม่เจอ = ข้ามไปขั้นถัดไป useLayoutEffect(() => { const step = stepRef.current; if (!open || !step) return; const el = resolve(step.target); if (!el) { if (process.env.NODE_ENV !== "production") { console.warn("[Tour] หาเป้าหมายของขั้นที่", index + 1, "ไม่เจอ — ข้าม", step.target); } if (index < steps.length - 1) setIndex(index + 1); else if (shownAny.current) close_.current(); else setOpen_.current(false); return; } shownAny.current = true; el.scrollIntoView?.({ block: "center", inline: "nearest" }); const measure = () => setRect(el.getBoundingClientRect()); measure(); window.addEventListener("resize", measure); window.addEventListener("scroll", measure, true); return () => { window.removeEventListener("resize", measure); window.removeEventListener("scroll", measure, true); }; }, [open, index, steps.length]); // โฟกัสการ์ดทุกครั้งที่เปลี่ยนขั้น // biome-ignore lint/correctness/useExhaustiveDependencies: index เป็นตัวกระตุ้น (เปลี่ยนขั้น = โฟกัสการ์ดใหม่) useEffect(() => { if (open) cardRef.current?.focus(); }, [open, index]); if (!open || !step || typeof document === "undefined") return null; const hole = rect ? { top: rect.top - PAD, left: rect.left - PAD, width: rect.width + PAD * 2, height: rect.height + PAD * 2, } : null; const viewportH = typeof window === "undefined" ? 800 : window.innerHeight; const viewportW = typeof window === "undefined" ? 1200 : window.innerWidth; const below = step.placement === "bottom" || (step.placement !== "top" && (!hole || hole.top + hole.height + 220 < viewportH)); const cardStyle = isMobile || !hole ? undefined : { top: below ? hole.top + hole.height + 12 : undefined, bottom: below ? undefined : viewportH - hole.top + 12, left: Math.min(Math.max(12, hole.left), viewportW - 332), }; const counter = (text?.step ?? "{current} / {total}") .replace("{current}", String(index + 1)) .replace("{total}", String(steps.length)); const onKeyDown = (event: KeyboardEvent) => { if (event.key === "Escape") { event.stopPropagation(); close(); return; } // โฟกัสวนอยู่ในการ์ด if (event.key !== "Tab" || !cardRef.current) return; const focusable = cardRef.current.querySelectorAll("button:not([disabled])"); const first = focusable[0]; const lastEl = focusable[focusable.length - 1]; if (!first || !lastEl) return; if (event.shiftKey && document.activeElement === first) { event.preventDefault(); lastEl.focus(); } else if (!event.shiftKey && document.activeElement === lastEl) { event.preventDefault(); first.focus(); } }; const blockers = hole && step.interactive ? [ { top: 0, left: 0, width: "100%", height: Math.max(0, hole.top) }, { top: hole.top + hole.height, left: 0, width: "100%", bottom: 0 }, { top: hole.top, left: 0, width: Math.max(0, hole.left), height: hole.height }, { top: hole.top, left: hole.left + hole.width, right: 0, height: hole.height }, ] : [{ top: 0, left: 0, right: 0, bottom: 0 }]; return createPortal(
{/* กันการกดหน้าหลัง (ไม่ปิดทัวร์ — กันปิดพลาด) */} {blockers.map((style, i) => ( // biome-ignore lint/suspicious/noArrayIndexKey: แผ่นกันกด 1–4 ชิ้นตามตำแหน่ง ไม่มีตัวตนอื่น