@navikt/ds-react
Version:
React components from the Norwegian Labour and Welfare Administration.
54 lines • 2.72 kB
JavaScript
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 React, { forwardRef } from "react";
import { Slot } from "../../../slot/Slot.js";
import { composeEventHandlers } from "../../composeEventHandlers.js";
import { useMergeRefs } from "../../hooks/index.js";
import { useVirtualFocusDescendant, useVirtualFocusInternalContext, } from "../Context.js";
/**
* Must have a single child that is an input element.
*/
export const VirtualFocusAnchor = forwardRef((_a, ref) => {
var { onSelect, onActive, children } = _a, rest = __rest(_a, ["onSelect", "onActive", "children"]);
const { virtualFocusIdx, setVirtualFocusIdx, loop, uniqueId } = useVirtualFocusInternalContext();
const { register, descendants, index } = useVirtualFocusDescendant({
handleOnActive: () => {
setVirtualFocusIdx(0);
onActive();
},
handleOnSelect: onSelect,
});
const mergedRefs = useMergeRefs(ref, register);
return (React.createElement(Slot, Object.assign({ ref: mergedRefs, tabIndex: 0 }, rest, { id: `virtualfocus-${uniqueId}-${index}`, "aria-owns": `virtualfocus-${uniqueId}-content`, "aria-controls": `virtualfocus-${uniqueId}-content`, "aria-activedescendant": `virtualfocus-${uniqueId}-${virtualFocusIdx}`, onKeyDown: composeEventHandlers(rest.onKeyDown, (event) => {
if (event.key === "ArrowDown") {
event.preventDefault();
const to_focus_descendant = descendants.next(virtualFocusIdx, loop);
if (to_focus_descendant) {
to_focus_descendant.handleOnActive();
}
}
else if (event.key === "ArrowUp") {
event.preventDefault();
const to_focus_descendant = descendants.prev(virtualFocusIdx, loop);
if (to_focus_descendant) {
to_focus_descendant.handleOnActive();
}
}
else if (event.key === "Enter") {
const curr = descendants.item(virtualFocusIdx);
if (curr === null || curr === void 0 ? void 0 : curr.handleOnSelect) {
curr.handleOnSelect();
}
}
}) }), children));
});
//# sourceMappingURL=VirtualFocusAnchor.js.map