azure-devops-ui
Version:
React components for building web UI in Azure DevOps
43 lines (42 loc) • 1.7 kB
JavaScript
import "../../CommonImports";
import "../../Core/core.css";
import * as React from "react";
import { getSafeId, noop } from '../../Util';
export const FocusGroupContext = React.createContext({
onFocus: noop
});
export class FocusGroup extends React.Component {
constructor(props) {
super(props);
this.onFocus = (focusedElementId) => {
// Only setState if the focusedElement is changing. This prevents us from setting the state
// when focus keeps getting fired on the same element. Example: Browser keeps losing and
// getting focus.
if (this.state.focusedElementId !== focusedElementId) {
this.setState({ focusedElementId });
}
};
this.state = { defaultElementId: props.defaultElementId, focusedElementId: props.defaultElementId };
}
static getDerivedStateFromProps(props, state) {
if (state.defaultElementId !== props.defaultElementId) {
return Object.assign(Object.assign({}, state), { defaultElementId: props.defaultElementId, focusedElementId: props.defaultElementId });
}
return null;
}
render() {
return (React.createElement(FocusGroupContext.Provider, { value: {
focusedElementId: this.state.focusedElementId,
onFocus: this.onFocus
} }, this.props.children));
}
focus(elementId) {
const id = getSafeId(elementId || this.state.focusedElementId);
if (id) {
const element = document.getElementById(id);
if (element) {
element.focus();
}
}
}
}