import clsx from 'clsx'
import { FieldValues, UseFormSetValue, UseFormWatch } from 'react-hook-form'
import { useTranslation } from 'react-i18next'
import { BooleanFieldNames } from '@dao-dao/types'
import { Loader } from '../logo'
import {
TooltipInfoIcon,
TooltipInfoIconProps,
} from '../tooltip/TooltipInfoIcon'
export interface SwitchProps {
enabled: boolean
onClick?: () => void
className?: string
sizing?: 'sm' | 'md' | 'lg'
readOnly?: boolean
loading?: boolean
}
export const Switch = ({
enabled,
onClick,
className,
sizing = 'lg',
readOnly,
loading,
}: SwitchProps) => {
readOnly ||= loading
return (
)
}
export interface SwitchCardProps extends SwitchProps {
containerClassName?: string
// Fallback for both on and off. Use if label should not change.
label?: string
onLabel?: string
offLabel?: string
tooltip?: string
tooltipIconSize?: TooltipInfoIconProps['size']
}
export const SwitchCard = ({
containerClassName,
label,
onLabel: _onLabel,
offLabel: _offLabel,
tooltip,
tooltipIconSize,
...props
}: SwitchCardProps) => {
const { t } = useTranslation()
const onLabel = _onLabel ?? label ?? t('info.enabled')
const offLabel = _offLabel ?? label ?? t('info.disabled')
return (
{tooltip &&
}
{props.enabled ? onLabel : offLabel}
)
}
export type FormSwitchWrapperProps<
Props,
FV extends FieldValues,
BooleanFieldName extends BooleanFieldNames,
> = Omit & {
fieldName: BooleanFieldName
setValue: UseFormSetValue
onToggle?: (newValue: boolean) => void
} & (
| {
value: boolean | undefined
watch?: never
}
| {
value?: never
watch: UseFormWatch
}
)
export const FormSwitch = <
FV extends FieldValues,
BooleanFieldName extends BooleanFieldNames,
>({
fieldName,
value: _value,
watch,
setValue,
onToggle,
...props
}: FormSwitchWrapperProps) => {
const value = _value ?? watch?.(fieldName)
return (
{
const newValue = !value
setValue(fieldName, newValue as any)
onToggle?.(newValue)
}}
{...props}
/>
)
}
export const FormSwitchCard = <
FV extends FieldValues,
BooleanFieldName extends BooleanFieldNames,
>({
fieldName,
value: _value,
watch,
setValue,
onToggle,
...props
}: FormSwitchWrapperProps) => {
const value = _value ?? watch?.(fieldName)
return (
{
const newValue = !value
setValue(fieldName, newValue as any)
onToggle?.(newValue)
}}
sizing="sm"
tooltipIconSize="sm"
{...props}
/>
)
}