@renderlesskit/react
Version:
Collection of headless components/hooks that are accessible, composable, customizable from low level to build your own UI & Design System powered by Reakit
38 lines (35 loc) • 1.3 kB
JavaScript
import * as React from "react";
import { getActiveElement, getDocument, isEmpty } from "reakit-utils";
/**
* When the focused child gets removed from the DOM, we make sure to move focus
* to the dialog.
*/
export function useFocusOnChildUnmount(dialogRef, options) {
React.useEffect(() => {
var dialog = dialogRef.current;
if (!options.visible || !dialog) return undefined;
var observer = new MutationObserver(mutations => {
var [{
target
}] = mutations; // If target is not this dialog, then this observer was triggered by a
// nested dialog, so we just ignore it here and let the nested dialog
// handle it there.
if (target !== dialog) return;
var document = getDocument(dialog);
var activeElement = getActiveElement(dialog); // We can check if the current focused element is the document body. On
// IE 11, it's an empty object when the current document is in a frame or
// iframe.
if (activeElement === document.body || isEmpty(activeElement)) {
dialog.focus();
}
});
observer.observe(dialog, {
childList: true,
subtree: true
});
return () => {
observer.disconnect();
};
}, [options.visible, dialogRef]);
}
//# sourceMappingURL=useFocusOnChildUnmount.js.map