import React, { HTMLAttributes, KeyboardEvent, RefObject, createRef } from 'react'; import SliderSwitchButton from './SliderSwitchButton'; import { classNames } from '../../lib/classNames'; import { HasPlatform } from '../../types'; export interface SliderSwitchOptionInterface { name: string; value: string | number; } export interface SliderSwitchProps extends HTMLAttributes, HasPlatform { options: Array<{ name: string; value: string | number; }>; activeValue?: SliderSwitchOptionInterface['value']; name?: string; onSwitch?: (value: SliderSwitchOptionInterface['value']) => void; } interface SliderSwitchState { activeValue: SliderSwitchOptionInterface['value']; hoveredOptionId: number; } export default class SliderSwitch extends React.Component { public constructor(props: SliderSwitchProps) { super(props); this.state = { activeValue: props.activeValue ?? '', hoveredOptionId: -1, }; this.firstButton = createRef(); this.secondButton = createRef(); } static defaultProps = { options: [{ name: '', value: '' }, { name: '', value: '' }], }; firstButton: RefObject; secondButton: RefObject; onSwitch = (value: SliderSwitchOptionInterface['value']) => { const { onSwitch } = this.props; this.setState(() => ({ activeValue: value, }), () => { onSwitch && onSwitch(value); }); }; handleFirstClick = () => { const { options } = this.props; const { value } = options[0]; this.onSwitch(value); }; handleSecondClick = () => { const { options } = this.props; const { value } = options[1]; this.onSwitch(value); }; handleFirstHover = () => { this.setState(() =>({ hoveredOptionId: 0, })); }; handleSecondHover = () => { this.setState(() =>({ hoveredOptionId: 1, })); }; resetFocusedOption = () => { this.setState(() => ({ hoveredOptionId: -1, })); }; switchByKey = (event: KeyboardEvent) => { if (event.key !== 'Enter' && event.key !== 'Spacebar' && event.key !== ' ') { return; } event.preventDefault(); const { options } = this.props; const { activeValue } = this.state; const { value } = options.find((option) => option.value !== activeValue); this.onSwitch(value); if (options[0].value === value) { this.firstButton.current.focus(); } else { this.secondButton.current.focus(); } }; static getDerivedStateFromProps(nextProps: SliderSwitchProps, prevState: SliderSwitchState) { if (nextProps.activeValue && nextProps.activeValue !== prevState.activeValue) { return { activeValue: nextProps.activeValue, }; } return null; } public render() { const { name, options, className, activeValue: _activeValue, ...restProps } = this.props; const { activeValue, hoveredOptionId } = this.state; const [firstOption, secondOption] = options; const firstActive = firstOption.value === activeValue; const secondActive = secondOption.value === activeValue; return (
{!firstActive && !secondActive &&
}
{firstOption.name} {secondOption.name}
); } }