-
Notifications
You must be signed in to change notification settings - Fork 0
/
n-trigger.js
26 lines (24 loc) · 1.03 KB
/
n-trigger.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
import React, { Children, cloneElement, useContext } from "react";
import { ContextForTrigger } from "./context";
export default function Trigger({ children, ...triggerWrapperProps }) {
const { wrapperRef, openedMenuIdx, headFocusItemInContent, panelsRef } = useContext(ContextForTrigger);
const focusBackToSlateFromTrigger = (e) => {
if (openedMenuIdx > -1 && (e.key === "Tab" || e.keyCode === 9)) {
const head = headFocusItemInContent.current[openedMenuIdx];
e.preventDefault();
if (head) head.focus({ preventScroll: true });
else panelsRef.current[openedMenuIdx].focus({ preventScroll: true });
}
};
let relatedIdx = -1;
const mapped = Children.map(children, child => {
const dn = (child.type || {}).displayName;
if (dn === "Item") {
++ relatedIdx;
return cloneElement(child, { type: "T", orderI: relatedIdx });
}
return child;
});
return <div {...triggerWrapperProps} ref={wrapperRef} onKeyDown={focusBackToSlateFromTrigger}>{mapped}</div>;
}
Trigger.displayName = "Trigger";