UNPKG

@navikt/ds-react

Version:

React components from the Norwegian Labour and Welfare Administration.

63 lines 3.24 kB
var __rest = (this && this.__rest) || function (s, e) { var t = {}; for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p]; if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) t[p[i]] = s[p[i]]; } return t; }; import * as React from "react"; import { forwardRef, useEffect, useState } from "react"; import { Slot } from "../../../slot/Slot.js"; import { useCallbackRef, useMergeRefs } from "../../../util/hooks/index.js"; const AUTOFOCUS_ON_MOUNT = "focusScope.autoFocusOnMount"; const AUTOFOCUS_ON_UNMOUNT = "focusScope.autoFocusOnUnmount"; const EVENT_OPTIONS = { bubbles: false, cancelable: true }; /** * FocusScope manages focus on mount and unmount of container. * This is used to better handle autofocus of elements when mounted and unmounted. * Example usage: * - Focus first item in a list when mounted * - Focus a button when unmounted */ const FocusScope = forwardRef((_a, ref) => { var { onMountHandler: onMountHandlerCallback, onUnmountHandler: onUnmountHandlerCallback } = _a, rest = __rest(_a, ["onMountHandler", "onUnmountHandler"]); const [container, setContainer] = useState(null); const onMountHandler = useCallbackRef(onMountHandlerCallback); const onUnmountHandler = useCallbackRef(onUnmountHandlerCallback); const composedRefs = useMergeRefs(ref, setContainer); useEffect(() => { var _a; if (!container) return; const ownerDocument = (_a = container.ownerDocument) !== null && _a !== void 0 ? _a : globalThis === null || globalThis === void 0 ? void 0 : globalThis.document; const hasFocus = container.contains(ownerDocument.activeElement); if (!hasFocus) { const mountEvent = new CustomEvent(AUTOFOCUS_ON_MOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_MOUNT, onMountHandler); container.dispatchEvent(mountEvent); } return () => { container.removeEventListener(AUTOFOCUS_ON_MOUNT, onMountHandler); /** * https://github.com/facebook/react/issues/17894 * As usual when dealing with focus and useEffect, * we need to defer the focus to the next event-loop * setTimeout makes sure the code is ran after the next render-cycle */ setTimeout(() => { const unmountEvent = new CustomEvent(AUTOFOCUS_ON_UNMOUNT, EVENT_OPTIONS); container.addEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountHandler); container.dispatchEvent(unmountEvent); // we need to remove the listener after we `dispatchEvent` container.removeEventListener(AUTOFOCUS_ON_UNMOUNT, onUnmountHandler); }, 0); }; }, [container, onMountHandler, onUnmountHandler]); return React.createElement(Slot, Object.assign({ tabIndex: -1 }, rest, { ref: composedRefs })); }); export { FocusScope }; //# sourceMappingURL=FocusScope.js.map