cal.pub0.org/components/ui/WeekdaySelect.tsx

64 lines
2.0 KiB
TypeScript
Raw Normal View History

import React, { useEffect, useState } from "react";
2021-06-14 18:53:20 +00:00
interface WeekdaySelectProps {
defaultValue: number[];
onSelect: (selected: number[]) => void;
}
export const WeekdaySelect = (props: WeekdaySelectProps) => {
const [activeDays, setActiveDays] = useState<boolean[]>(
Array.from(Array(7).keys()).map((v, i) => (props.defaultValue || []).includes(i))
);
2021-06-14 18:53:20 +00:00
const days = ["S", "M", "T", "W", "T", "F", "S"];
2021-06-14 18:53:20 +00:00
useEffect(() => {
props.onSelect(activeDays.map((v, idx) => (v ? idx : -1)).filter((v) => v !== -1));
}, [activeDays]);
const toggleDay = (idx: number) => {
2021-06-14 18:53:20 +00:00
activeDays[idx] = !activeDays[idx];
setActiveDays(([] as boolean[]).concat(activeDays));
};
2021-06-14 18:53:20 +00:00
return (
<div className="weekdaySelect">
<div className="inline-flex">
{days.map((day, idx) =>
activeDays[idx] ? (
<button
key={idx}
onClick={(e) => {
e.preventDefault();
toggleDay(idx);
}}
className={`
2021-08-02 15:24:01 +00:00
w-10 h-10
bg-brand text-white focus:outline-none px-3 py-1 rounded
${activeDays[idx + 1] ? "rounded-r-none" : ""}
${activeDays[idx - 1] ? "rounded-l-none" : ""}
${idx === 0 ? "rounded-l" : ""}
${idx === days.length - 1 ? "rounded-r" : ""}
2021-06-14 18:53:20 +00:00
`}>
{day}
</button>
) : (
<button
key={idx}
onClick={(e) => {
e.preventDefault();
toggleDay(idx);
}}
style={{ marginTop: "1px", marginBottom: "1px" }}
2021-08-02 15:24:01 +00:00
className={`w-10 h-10 bg-gray-50 focus:outline-none px-3 py-1 rounded-none ${
idx === 0 ? "rounded-l" : "border-l-0"
} ${idx === days.length - 1 ? "rounded-r" : ""}`}>
{day}
</button>
)
2021-06-14 18:53:20 +00:00
)}
</div>
</div>
);
};