65 lines
2.3 KiB
TypeScript
65 lines
2.3 KiB
TypeScript
import { useEffect, useState } from "react";
|
|
|
|
/**
|
|
* ช่องกรอกหลายค่า คั่นด้วย "," (เช่น หมวด, ช่องทางชำระเงิน)
|
|
*
|
|
* ทำไมต้องมี draft: ถ้าผูก value เข้ากับ array ตรง ๆ แล้ว split/join ทุกคีย์
|
|
* ตัว "," ที่เพิ่งพิมพ์จะถูกตัดทิ้งทันที ( join(", ") ไม่มีตัวคั่นให้ค่าว่าง )
|
|
* ทำให้พิมพ์คั่นค่าไม่ได้เลย — draft เก็บข้อความดิบระหว่างพิมพ์ แล้วค่อย
|
|
* normalize เป็น ", " เมื่อออกจากช่อง
|
|
*/
|
|
|
|
/** แปลงข้อความ → รายการ (รับ , , 、 และขึ้นบรรทัดใหม่เป็นตัวคั่นด้วย) */
|
|
export function parseCommaList(value: string): string[] {
|
|
return value
|
|
.replace(/[,、]/g, ",")
|
|
.split(/[,\n]/)
|
|
.map((item) => item.trim())
|
|
.filter((item) => item !== "");
|
|
}
|
|
|
|
export function formatList(value: string[]): string {
|
|
return value.join(", ");
|
|
}
|
|
|
|
type CommaListInputProps = {
|
|
value: string[];
|
|
onChangeValue: (next: string[]) => void;
|
|
className?: string;
|
|
placeholder?: string;
|
|
id?: string;
|
|
};
|
|
|
|
export function CommaListInput({
|
|
value,
|
|
onChangeValue,
|
|
className,
|
|
placeholder,
|
|
id,
|
|
}: CommaListInputProps) {
|
|
const canonical = formatList(value);
|
|
const [draft, setDraft] = useState<string | null>(null);
|
|
|
|
// ค่าถูกเปลี่ยนจากที่อื่น (เช่น เปลี่ยนโรง / ใช้ JSON / คืนค่า) → ทิ้ง draft
|
|
useEffect(() => {
|
|
if (draft === null) return;
|
|
if (formatList(parseCommaList(draft)) !== canonical) setDraft(null);
|
|
}, [canonical, draft]);
|
|
|
|
return (
|
|
<input
|
|
id={id}
|
|
className={className}
|
|
placeholder={placeholder}
|
|
value={draft ?? canonical}
|
|
spellCheck={false}
|
|
onChange={(event) => {
|
|
const text = event.target.value;
|
|
setDraft(text);
|
|
onChangeValue(parseCommaList(text));
|
|
}}
|
|
onBlur={() => setDraft(null)}
|
|
/>
|
|
);
|
|
}
|