signal-desktop/ts/components/hooks.ts

31 lines
731 B
TypeScript
Raw Normal View History

2020-01-17 22:23:19 +00:00
import * as React from 'react';
// Restore focus on teardown
export const useRestoreFocus = (
// The ref for the element to receive initial focus
focusRef: React.RefObject<any>,
// Allow for an optional root element that must exist
root: boolean | HTMLElement | null = true
) => {
React.useEffect(() => {
if (!root) {
return;
}
const lastFocused = document.activeElement as any;
if (focusRef.current) {
focusRef.current.focus();
}
return () => {
2020-02-27 02:09:19 +00:00
// This ensures that the focus is returned to
// previous element
setTimeout(() => {
if (lastFocused && lastFocused.focus) {
lastFocused.focus();
}
});
2020-01-17 22:23:19 +00:00
};
}, [focusRef, root]);
};