eCourt-note/components/UserPicker.tsx

67 lines
2.5 KiB
TypeScript
Raw Normal View History

"use client";
// เลือก mock user ที่หน้าแรกก่อนเข้า annotate — เขียนลง localStorage key เดิม
// ที่ getLocalUser() อ่าน (PDFViewer ไม่ต้องแก้อะไร)
import { useEffect, useState } from "react";
import Select from "./Select";
import {
MOCK_USERS,
getStoredLocalUser,
setLocalUser,
type LocalUser,
} from "@/utils/user";
export default function UserPicker() {
const [current, setCurrent] = useState<LocalUser | null>(null);
// ต้องรันใน effect เพราะ SSR ไม่มี localStorage — ก่อน mount แสดงคนแรกไว้ก่อน
useEffect(() => {
const stored = getStoredLocalUser();
if (!stored) {
// ยังไม่เคยมี identity → เริ่มด้วย mock user คนแรก
setLocalUser(MOCK_USERS[0]);
setCurrent(MOCK_USERS[0]);
return;
}
setCurrent(stored);
}, []);
// identity สุ่มเดิมไม่อยู่ในรายการ mock → แสดงเป็น option ชั่วคราวให้เห็นว่าปัจจุบันคือใคร
const isMock = current !== null && MOCK_USERS.some((u) => u.userId === current.userId);
const select = (userId: string) => {
const user = MOCK_USERS.find((u) => u.userId === userId);
if (!user) return;
setLocalUser(user);
setCurrent(user);
};
return (
<section className="mt-6 rounded-lg border bg-white p-4 shadow-sm">
<h2 className="text-sm font-semibold text-primary">เลือกผู้ใช้ (mock)</h2>
<p className="mt-0.5 text-xs text-slate-400">
annotation ทั้งหมดจะบันทึกในชื่อผู้ใช้ที่เลือก
</p>
<Select
value={current ? (isMock ? current.userId : "") : MOCK_USERS[0].userId}
onChange={(e) => {
if (e.target.value) select(e.target.value);
}}
className="mt-3 block w-full rounded-md border bg-white py-2 pl-3 text-sm"
>
{current && !isMock && (
<option value="" disabled>
{current.userName} (สุ่มอัตโนมัติ)
</option>
)}
{MOCK_USERS.map((u) => (
<option key={u.userId} value={u.userId}>
{u.userName}
</option>
))}
</Select>
</section>
);
}