type ChipOption = {
value: string;
label: string;
};
type ChipPickerProps = {
options: ChipOption[];
selected: string[];
onToggle: (value: string) => void;
/** ข้อความเมื่อยังไม่ได้เลือกอะไร */
emptyHint?: string;
};
/**
* ปุ่มเลือกหลายค่าแบบชิป สำหรับหลังบ้าน (หมวดหมู่ / สิ่งอำนวยความสะดวก)
* ค่าที่เลือกจะถูกเก็บตามลำดับ options เสมอ เพื่อให้ข้อมูลในไฟล์นิ่ง
*/
export function ChipPicker({
options,
selected,
onToggle,
emptyHint,
}: ChipPickerProps) {
const chosen = new Set(selected);
const known = new Set(options.map((option) => option.value));
const extras = selected.filter((value) => !known.has(value));
return (
{options.map((option) => {
const active = chosen.has(option.value);
return (
);
})}
{extras.map((value) => (
))}
{options.length === 0 && extras.length === 0 && emptyHint ? (
{emptyHint}
) : null}
);
}
/**
* สลับค่าหนึ่งตัวในลิสต์ แล้วเรียงตามลำดับ options (ค่าที่ไม่รู้จักต่อท้าย)
*/
export function toggleValue(
selected: string[],
value: string,
order: string[],
): string[] {
const next = selected.includes(value)
? selected.filter((item) => item !== value)
: [...selected, value];
const rank = (item: string) => {
const index = order.indexOf(item);
return index < 0 ? order.length + 1 : index;
};
return [...next].sort((a, b) => rank(a) - rank(b));
}