mango-v4-ui/components/forms/ButtonGroup.tsx

66 lines
1.8 KiB
TypeScript
Raw Normal View History

type Values = string | number
2022-07-17 04:48:33 -07:00
interface ButtonGroupProps<T extends Values> {
activeValue: T
2022-07-17 04:48:33 -07:00
className?: string
2022-11-16 19:51:08 -08:00
disabled?: boolean
onChange: (x: T) => void
2022-07-17 04:48:33 -07:00
unit?: string
values: T[]
2022-07-17 04:48:33 -07:00
names?: Array<string>
2022-07-24 20:12:50 -07:00
large?: boolean
2022-07-17 04:48:33 -07:00
}
const ButtonGroup = <T extends Values>({
2022-07-17 04:48:33 -07:00
activeValue,
className,
2022-11-16 19:51:08 -08:00
disabled,
2022-07-17 04:48:33 -07:00
unit,
values,
onChange,
names,
2022-07-24 20:12:50 -07:00
large,
}: ButtonGroupProps<T>) => {
2022-07-17 04:48:33 -07:00
return (
2023-08-23 15:17:04 -07:00
<div className={`rounded-md bg-th-bkg-3 ${disabled ? 'opacity-50' : ''}`}>
2022-07-17 04:48:33 -07:00
<div className="relative flex">
{activeValue && values.includes(activeValue) ? (
<div
2023-08-23 15:17:04 -07:00
className={`absolute left-0 top-0 h-full transform rounded-md bg-th-bkg-4`}
2022-07-17 04:48:33 -07:00
style={{
transform: `translateX(${
values.findIndex((v) => v === activeValue) * 100
}%)`,
width: `${100 / values.length}%`,
}}
/>
) : null}
{values.map((v, i) => (
<button
2023-08-23 15:17:04 -07:00
className={`${className} relative w-1/2 cursor-pointer rounded-md px-3 text-center focus-visible:bg-th-bkg-4 focus-visible:text-th-fgd-2 disabled:cursor-not-allowed ${
2022-07-24 20:12:50 -07:00
large ? 'h-12 text-sm' : 'h-10 text-xs'
} font-normal
2022-07-17 04:48:33 -07:00
${
v === activeValue
2023-04-19 18:01:31 -07:00
? `text-th-active`
: `text-th-fgd-2 md:hover:text-th-fgd-1`
2022-07-17 04:48:33 -07:00
}
`}
2022-11-16 19:51:08 -08:00
disabled={disabled}
2022-07-17 04:48:33 -07:00
key={`${v}${i}`}
onClick={() => onChange(v)}
style={{
width: `${100 / values.length}%`,
}}
type="button"
2022-07-17 04:48:33 -07:00
>
{names ? (unit ? names[i] + unit : names[i]) : unit ? v + unit : v}
</button>
))}
</div>
</div>
)
}
export default ButtonGroup