"use client"; import { Button } from "@suphark/ui/components/shared/button/button"; import { Spinner } from "@suphark/ui/components/ui/spinner"; import { errorMessage, failedResult, isNavigationError } from "@suphark/ui/lib/action-result"; import { cn } from "@suphark/ui/lib/utils"; import { CheckIcon } from "lucide-react"; import { type FormEvent, type ReactNode, useEffect, useRef, useState } from "react"; import { useUiText } from "./ui-text"; export interface StepFormStep { id: string; title: ReactNode; description?: ReactNode; /** ช่องกรอกของขั้นนี้ — ใส่ `name` ตามปกติ ค่าทุกขั้นรวมใน FormData เดียวตอนส่ง */ content: ReactNode; /** ตรวจเพิ่มจาก required/pattern ของ input — คืน string = ข้อความ error (ไม่ไปต่อ) */ validate?: (formData: FormData) => string | null | undefined | Promise; } const CONTROLS = "input, select, textarea"; const FOCUSABLE = 'input, select, textarea, button, [tabindex]:not([tabindex="-1"])'; /** สิ่งที่โฟกัสได้ (มองเห็น ไม่ใช่ตัวแทนที่ซ่อน) ตัวก่อนหน้าที่ใกล้ `el` ที่สุดในกล่อง */ function precedingFocusable(section: HTMLElement, el: Element): HTMLElement | undefined { const all = [...section.querySelectorAll(FOCUSABLE)].filter( (c) => c !== el && c.getAttribute("aria-hidden") !== "true" && (c as HTMLInputElement).type !== "hidden" && !(c as HTMLButtonElement).disabled && c.compareDocumentPosition(el) & Node.DOCUMENT_POSITION_FOLLOWING, ); return all[all.length - 1]; } /** * ตรวจ constraint ของ input ในกล่อง (required, pattern, min…) — แสดง bubble ของเบราว์เซอร์ที่ช่องแรกที่ผิด * input ที่ซ่อนไว้ (ตัวแทนของ Base UI เช่น NumberField, aria-hidden) แสดง bubble ไม่ได้ → คืนข้อความให้แสดงใต้ฟอร์มแทน * คืน true = ผ่าน, string = ข้อความ error, false = แสดง bubble แล้ว */ function reportSection(section: HTMLElement | null): true | false | string { if (!section) return true; const controls = [...section.querySelectorAll(CONTROLS)]; for (const el of controls) { if (el.type === "hidden" || el.disabled) continue; if (!el.checkValidity()) { if (el.getAttribute("aria-hidden") === "true") { // input ซ่อนของ Base UI (NumberField/Select/Checkbox/Switch/Radio) อยู่ถัดจากตัวควบคุมที่มองเห็นของมัน // → โฟกัสสิ่งที่โฟกัสได้ตัวก่อนหน้าที่ใกล้ที่สุด (ปุ่ม combobox/checkbox ก็นับ ไม่ใช่แค่ input) precedingFocusable(section, el)?.focus(); return el.validationMessage || "ค่าไม่ถูกต้อง"; } el.reportValidity(); el.focus(); return false; } } return true; } /** * ฟอร์มหลายขั้น (wizard) สำเร็จรูป — แถบขั้นตอน + เนื้อหาทีละขั้น + ปุ่มย้อนกลับ/ถัดไป/ส่ง ในตัว * ทุกขั้นอยู่ใน `
` เดียว (ขั้นที่ไม่แสดงถูกซ่อนไว้ ค่ายังอยู่) → `onSubmit(formData)` ได้ค่าครบทุกขั้น ส่งต่อ server action ได้ตรง ๆ * กด "ถัดไป" ตรวจ required/pattern ของขั้นนั้น + `validate` ก่อนไปต่อ; ขั้นที่ผ่านแล้วกดที่แถบเพื่อย้อนกลับได้ * ขั้นสุดท้ายใช้เป็นหน้าตรวจทานได้ (content อ่านค่าจาก state ของแอปเอง) * * }, * { id: "oauth", title: "OAuth", content: , * validate: (fd) => (fd.getAll("redirectUris").length ? null : "ต้องมี redirect URI อย่างน้อย 1 รายการ") }, * ]} /> */ export function StepForm({ steps, onSubmit, submitLabel, initialStep = 0, step: stepProp, onStepChange, footer, className, }: { steps: ReadonlyArray; /** เรียกเมื่อกดส่งที่ขั้นสุดท้าย — throw / reject = แสดงข้อความ error ใต้ฟอร์ม */ onSubmit: (formData: FormData) => unknown | Promise; submitLabel?: ReactNode; initialStep?: number; /** * คุมขั้นจากภายนอก (เช่น เก็บใน URL `?step=2`) — ต้องใช้คู่กับ `onStepChange` ที่ตั้งค่าใหม่ * ปุ่มถัดไป/ย้อนกลับ/แถบขั้นยังตรวจขั้นก่อนไปต่อเหมือนเดิม แล้วเรียก `onStepChange` แทนการเปลี่ยนเอง */ step?: number; onStepChange?: (index: number, id: string) => void; /** ต่อท้ายแถวปุ่มฝั่งซ้าย เช่น ปุ่มยกเลิก */ footer?: ReactNode; className?: string; }) { const ui = useUiText(); const text = ui.stepForm; const [internalStep, setInternalStep] = useState(initialStep); const current = Math.min(Math.max(stepProp ?? internalStep, 0), Math.max(steps.length - 1, 0)); const [reachedState, setReached] = useState(initialStep); // ขั้นที่ไปถึงแล้ว (กดย้อนกลับไปได้) — คุมจากภายนอกแล้วกระโดดไปข้างหน้าก็นับว่าถึงแล้ว const reached = Math.max(reachedState, current); const [error, setError] = useState(null); const [pending, setPending] = useState(false); const formRef = useRef(null); const sectionRefs = useRef<(HTMLElement | null)[]>([]); const headingRefs = useRef<(HTMLHeadingElement | null)[]>([]); const moved = useRef(false); /** กันส่งซ้ำแบบ synchronous (state pending อัปเดตไม่ทันดับเบิลคลิก) */ const busy = useRef(false); /** เวลาที่เปลี่ยนขั้นล่าสุด — คลิกที่สองของดับเบิลคลิก "ถัดไป" ตกที่ปุ่ม "ส่ง" ตำแหน่งเดิม */ const movedAt = useRef(0); /** เวลาที่ส่งเสร็จล่าสุด — กันคลิกซ้ำเมื่อ onSubmit จบเร็ว */ const submittedAt = useRef(0); const last = steps.length - 1; const step = steps[current]; // ย้ายโฟกัสไปหัวข้อของขั้นใหม่ (screen reader รู้ว่าเปลี่ยนขั้น) — ไม่ทำตอน mount useEffect(() => { if (!moved.current) return; headingRefs.current[current]?.focus(); }, [current]); const go = (index: number) => { moved.current = true; movedAt.current = Date.now(); setError(null); if (stepProp === undefined) setInternalStep(index); setReached((r) => Math.max(r, index, current)); const target = steps[index]; if (target) onStepChange?.(index, target.id); }; /** ตรวจขั้น index — คืน true ถ้าผ่าน */ const check = async (index: number): Promise => { const native = reportSection(sectionRefs.current[index] ?? null); if (native !== true) { if (typeof native === "string") setError(native); return false; } const s = steps[index]; if (s?.validate && formRef.current) { const message = await s.validate(new FormData(formRef.current)); if (message) { setError(message); return false; } } return true; }; const handleSubmit = async (e: FormEvent) => { e.preventDefault(); if (busy.current) return; // คลิกที่สองของดับเบิลคลิก: หลังเปลี่ยนขั้น (ปุ่มเดิมกลายเป็น "ถัดไป"/"ส่ง" ของขั้นใหม่ — ข้ามขั้นหรือข้ามหน้าตรวจทาน) // และหลังส่งเสร็จ (onSubmit ที่ sync/เร็ว ปล่อย busy ก่อนคลิกที่สองมาถึง) ไม่นับ const now = Date.now(); if (now - movedAt.current < 500 || now - submittedAt.current < 500) return; busy.current = true; try { await submitStep(); } finally { busy.current = false; } }; const submitStep = async () => { setError(null); if (current < last) { if (await check(current)) go(current + 1); return; } // ขั้นสุดท้าย: ตรวจทุกขั้นอีกครั้งแบบเงียบ ขั้นไหนไม่ผ่านพากลับไปขั้นนั้นแล้วค่อยแสดงจุดที่ผิด for (let i = 0; i <= last; i++) { const section = sectionRefs.current[i]; const invalid = section ? [...section.querySelectorAll(CONTROLS)].some( (el) => el.type !== "hidden" && !el.disabled && !el.checkValidity(), ) : false; const s = steps[i]; const message = !invalid && s?.validate && formRef.current ? await s.validate(new FormData(formRef.current)) : null; if (invalid || message) { if (i !== current) go(i); if (message) setError(message); else requestAnimationFrame(() => { const native = reportSection(sectionRefs.current[i] ?? null); if (typeof native === "string") setError(native); }); return; } } if (!formRef.current) return; setPending(true); const fallback = ui.actionFailed ?? "ดำเนินการไม่สำเร็จ"; try { // server action ที่คืน { ok: false, error } (FormState) = ล้มเหลว เหมือน throw const failed = failedResult(await onSubmit(new FormData(formRef.current)), fallback); if (failed) setError(failed); } catch (err) { // redirect() ใน server action = สำเร็จ (Next นำทางให้แล้ว) if (!isNavigationError(err)) setError(errorMessage(err, fallback)); } finally { submittedAt.current = Date.now(); setPending(false); } }; return ( {steps.map((s, i) => (
{ sectionRefs.current[i] = el; }} hidden={i !== current} aria-labelledby={`${s.id}-step-title`} className="flex flex-col gap-4" >

{ headingRefs.current[i] = el; }} tabIndex={-1} className="font-semibold text-base outline-none" > {s.title}

{s.description &&

{s.description}

}
{s.content}
))} {error && (

{error}

)}
{footer}
{current > 0 && ( )}
); }