UNPKG

@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

49 lines (40 loc) 1.94 kB
import { contains, ensureFocus, getActiveElement, getDocument, isTabbable, useUpdateEffect } from "reakit-utils"; import { warning } from "reakit-warning"; function hidByFocusingAnotherElement(dialogRef) { var dialog = dialogRef.current; if (!dialog) return false; var activeElement = getActiveElement(dialog); if (!activeElement) return false; if (contains(dialog, activeElement)) return false; if (isTabbable(activeElement)) return true; if (activeElement.getAttribute("data-dialog") === "true") return true; return false; } export function useFocusOnHide(dialogRef, disclosureRef, options) { var shouldFocus = options.unstable_autoFocusOnHide && !options.visible; useUpdateEffect(() => { var _options$unstable_fin; if (!shouldFocus) return; if (options.animating) return; console.log("%canimating", "color: #ffa280", options.animating); // Hide was triggered by a click/focus on a tabbable element outside // the dialog or on another dialog. We won't change focus then. if (hidByFocusingAnotherElement(dialogRef)) { return; } var finalFocusEl = ((_options$unstable_fin = options.unstable_finalFocusRef) === null || _options$unstable_fin === void 0 ? void 0 : _options$unstable_fin.current) || disclosureRef.current; if (finalFocusEl) { if (finalFocusEl.id) { var document = getDocument(finalFocusEl); var compositeElement = document.querySelector("[aria-activedescendant='".concat(finalFocusEl.id, "']")); if (compositeElement) { ensureFocus(compositeElement); return; } } ensureFocus(finalFocusEl); return; } warning(true, "Can't return focus after closing dialog. Either render a disclosure component or provide a `unstable_finalFocusRef` prop.", dialogRef.current); }, [shouldFocus, options.animating, dialogRef, disclosureRef]); } //# sourceMappingURL=useFocusOnHide.js.map