import type { LunaticComponentProps } from '../type'; import { ComponentErrors, getComponentErrors, } from '../shared/ComponentErrors/ComponentErrors'; import React, { type KeyboardEvent } from 'react'; import classnames from 'classnames'; import { slottableComponent } from '../shared/HOC/slottableComponent'; import { Label } from '../shared/Label/Label'; import { Declarations } from '../shared/Declarations/Declarations'; import type { LunaticError } from '../../use-lunatic/type'; const defaultLabel = { true: 'True', false: 'False' }; function LunaticSwitch({ handleChanges, response, errors, value, statusLabel, ...props }: LunaticComponentProps<'Switch'>) { const checked = value ?? false; return ( handleChanges([{ name: response.name, value: !checked }])} errors={getComponentErrors(errors, props.id)} /> ); } type CustomProps = Omit< LunaticComponentProps<'Switch'>, 'response' | 'handleChanges' | 'errors' | 'value' > & { onChange: () => void; errors?: LunaticError[]; checked: boolean; }; export const CustomSwitch = slottableComponent( 'Switch', (props) => { const { id, onChange, checked, statusLabel = defaultLabel, label, errors, disabled, declarations, } = props; const { true: labelTrue, false: labelFalse } = statusLabel; const labelId = `lunatic-switch-label-${id}`; const handleKeyDown = (e: KeyboardEvent) => { const { code } = e; if (code === 'Space') { onChange(); } }; return ( <>
{labelFalse}
{labelTrue}
); } ); export const Switch = slottableComponent('Switch', LunaticSwitch);