wix-style-react
Version:
wix-style-react
59 lines • 3.13 kB
JavaScript
import * as React from 'react';
import { st, classes } from './ToggleSwitchCore.st.css';
import { dataHooks } from './constants';
import { filterDataProps } from './utils/filter-data-props';
import { StatusContext, getAriaAttributesFromContext, } from '../../FormField/StatusContext';
/**
* Toggle Switch
*/
class ToggleSwitchCore extends React.PureComponent {
constructor() {
super(...arguments);
this.state = {
focus: false,
focusVisible: false,
};
// We don't want to show outline when the component is focused by mouse.
this.focusedByMouse = false;
this.handleKeyDown = () => {
// Pressing any key should make the focus visible, even if the checkbox
// was initially focused by mouse.
this.setState({ focusVisible: true });
};
// Doesn't get invoked if the input is disabled.
this.handleMouseDown = e => {
if (e.button === 0) {
this.focusedByMouse = true;
}
};
this.handleFocus = () => {
this.setState({ focus: true, focusVisible: !this.focusedByMouse });
};
this.handleBlur = () => {
this.setState({ focus: false, focusVisible: false });
this.focusedByMouse = false;
};
}
render() {
const { checked, disabled, styles: inlineStyles, className, dataHook, } = this.props;
return (React.createElement(StatusContext.Consumer, null, statusContext => (React.createElement("div", { className: st(classes.root, {
checked,
disabled,
focus: this.state.focus,
'focus-visible': this.state.focusVisible,
}, className), style: inlineStyles?.root, "data-disabled": disabled, "data-hook": dataHook, ...filterDataProps(this.props) },
React.createElement("div", { "data-hook": dataHooks.track, className: classes.track, style: inlineStyles?.track }),
React.createElement("div", { "data-hook": dataHooks.knob, className: classes.knob, style: inlineStyles?.knob },
React.createElement("div", { "data-hook": dataHooks.knobIcon, className: classes.knobIcon, style: inlineStyles?.knobIcon }, checked ? this.props.checkedIcon : this.props.uncheckedIcon)),
React.createElement("input", { id: this.props.id, className: classes.input, type: "checkbox", checked: checked, readOnly: disabled, tabIndex: disabled ? -1 : this.props.tabIndex, onChange: disabled ? undefined : this.props.onChange, onFocus: disabled ? undefined : this.handleFocus, onBlur: disabled ? undefined : this.handleBlur, onMouseDown: this.handleMouseDown, onKeyDown: this.handleKeyDown, "aria-label": this.props['aria-label'], "data-hook": dataHooks.toggleSwitchInput, ...getAriaAttributesFromContext(statusContext) })))));
}
}
ToggleSwitchCore.displayName = 'ToggleSwitchCore';
ToggleSwitchCore.defaultProps = {
checked: false,
styles: {},
tabIndex: 0,
onChange: () => null,
};
export default ToggleSwitchCore;
//# sourceMappingURL=ToggleSwitchCore.js.map