azure-devops-ui
Version:
React components for building web UI in Azure DevOps
59 lines (58 loc) • 3.3 kB
JavaScript
import "../../CommonImports";
import "../../Core/core.css";
import "./Toggle.css";
import * as React from "react";
import { ObservableLike } from '../../Core/Observable';
import { FocusGroupContext } from '../../FocusGroup';
import { FocusZoneContext } from '../../FocusZone';
import { Observer } from '../../Observer';
import { Tooltip } from '../../TooltipEx';
import { css, getSafeId, KeyCode } from '../../Util';
import { getTabIndex } from '../../Utilities/Focus';
let toggleId = 1;
export class Toggle extends React.Component {
constructor() {
super(...arguments);
this.toggleElement = React.createRef();
this.labelId = `toggle-${toggleId++}-label`;
this.onClick = (event) => {
if (this.props.onChange && !this.props.disabled) {
this.props.onChange(event, this.props.checked === undefined ? false : !ObservableLike.getValue(this.props.checked));
}
};
this.onFocus = () => {
if (this.props.id) {
this.context.onFocus(this.props.id);
}
};
this.onKeyDown = (event) => {
if (!event.defaultPrevented) {
if (event.which === KeyCode.space) {
this.onClick(event);
event.preventDefault();
}
}
};
}
render() {
const { onAriaLabel, offAriaLabel, className, disabled, excludeFocusZone, id, offText, onText, role, text, tooltipProps } = this.props;
return (React.createElement(FocusZoneContext.Consumer, null, (zoneContext) => (React.createElement(Observer, { checked: this.props.checked }, (props) => {
const ariaLabel = props.checked ? onAriaLabel || this.props.ariaLabel : offAriaLabel || this.props.ariaLabel;
const labelId = getSafeId(this.labelId);
let toggle = (React.createElement("div", { className: css(className, "bolt-toggle-button cursor-pointer", props.checked && "checked", disabled ? "disabled" : "enabled"), onClick: this.onClick, onFocus: this.onFocus, onKeyDown: this.onKeyDown },
React.createElement("div", { "aria-checked": props.checked, "aria-disabled": disabled, "aria-label": ariaLabel, "aria-labelledby": !ariaLabel ? labelId : undefined, "aria-describedby": this.props.ariaDescribedBy, className: "bolt-toggle-button-pill bolt-focus-treatment flex-noshrink", "data-focuszone": !disabled && !excludeFocusZone ? zoneContext.focuszoneId : undefined, "data-is-focusable": true, id: getSafeId(id), ref: this.toggleElement, role: role || "switch", tabIndex: getTabIndex(this.props, this.context) },
React.createElement("div", { className: "bolt-toggle-button-icon" })),
React.createElement("div", { className: "bolt-toggle-button-text body-m", id: labelId }, props.checked ? onText || text : offText || text)));
if (tooltipProps) {
toggle = React.createElement(Tooltip, Object.assign({}, tooltipProps), toggle);
}
return toggle;
}))));
}
focus() {
if (this.toggleElement.current) {
this.toggleElement.current.focus();
}
}
}
Toggle.contextType = FocusGroupContext;