83 lines
2.7 KiB
TypeScript
83 lines
2.7 KiB
TypeScript
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 (
|
|
<div className="flex flex-wrap gap-2">
|
|
{options.map((option) => {
|
|
const active = chosen.has(option.value);
|
|
return (
|
|
<button
|
|
key={option.value}
|
|
type="button"
|
|
aria-pressed={active}
|
|
onClick={() => onToggle(option.value)}
|
|
className={`rounded-full border px-3 py-1 text-xs transition ${
|
|
active
|
|
? "border-[#A92626] bg-[rgba(143,8,8,0.18)] text-[#D47272]"
|
|
: "border-[#303030] text-[#999] hover:border-[#A92626] hover:text-white"
|
|
}`}
|
|
>
|
|
{option.label}
|
|
</button>
|
|
);
|
|
})}
|
|
{extras.map((value) => (
|
|
<button
|
|
key={value}
|
|
type="button"
|
|
aria-pressed
|
|
onClick={() => onToggle(value)}
|
|
className="rounded-full border border-[#A92626] bg-[rgba(143,8,8,0.18)] px-3 py-1 text-xs text-[#D47272] transition hover:border-[#D47272]"
|
|
>
|
|
{value}
|
|
</button>
|
|
))}
|
|
{options.length === 0 && extras.length === 0 && emptyHint ? (
|
|
<span className="text-xs text-[#777]">{emptyHint}</span>
|
|
) : null}
|
|
</div>
|
|
);
|
|
}
|
|
|
|
/**
|
|
* สลับค่าหนึ่งตัวในลิสต์ แล้วเรียงตามลำดับ 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));
|
|
}
|