mm
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
import {
|
||||
autoUpdate,
|
||||
flip,
|
||||
offset,
|
||||
safePolygon,
|
||||
shift,
|
||||
useClick,
|
||||
useDismiss,
|
||||
useFloating,
|
||||
useFloatingNodeId,
|
||||
useFloatingParentNodeId,
|
||||
useHover,
|
||||
useInteractions,
|
||||
useListNavigation,
|
||||
useRole,
|
||||
} from "@floating-ui/react";
|
||||
import { useRef, useState } from "react";
|
||||
|
||||
export function useMenuFloating() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [activeIndex, setActiveIndex] = useState<number | null>(null);
|
||||
const [selectedIndex, setSelectedIndex] = useState<number | null>(null);
|
||||
|
||||
const nodeId = useFloatingNodeId();
|
||||
const parentId = useFloatingParentNodeId();
|
||||
const isNested = parentId != null;
|
||||
|
||||
const elementsRef = useRef<Array<HTMLElement | null>>([]);
|
||||
|
||||
const { refs, floatingStyles, context } = useFloating({
|
||||
nodeId,
|
||||
placement: isNested ? "right-start" : "bottom-start",
|
||||
open: isOpen,
|
||||
onOpenChange: setIsOpen,
|
||||
whileElementsMounted: autoUpdate,
|
||||
middleware: [
|
||||
offset({
|
||||
mainAxis: isNested ? 0 : 4,
|
||||
alignmentAxis: isNested ? -4 : 0,
|
||||
}),
|
||||
flip(),
|
||||
shift(),
|
||||
],
|
||||
});
|
||||
|
||||
const hover = useHover(context, {
|
||||
enabled: isNested,
|
||||
delay: { open: 75 },
|
||||
handleClose: safePolygon({ blockPointerEvents: true }),
|
||||
});
|
||||
|
||||
const click = useClick(context, {
|
||||
event: "mousedown",
|
||||
toggle: !isNested,
|
||||
ignoreMouse: isNested,
|
||||
});
|
||||
|
||||
const role = useRole(context, { role: "menu" });
|
||||
|
||||
const dismiss = useDismiss(context, { bubbles: true });
|
||||
|
||||
const listNav = useListNavigation(context, {
|
||||
listRef: elementsRef,
|
||||
activeIndex,
|
||||
selectedIndex,
|
||||
nested: isNested,
|
||||
onNavigate: setActiveIndex,
|
||||
});
|
||||
|
||||
const { getReferenceProps, getFloatingProps, getItemProps } = useInteractions(
|
||||
[hover, click, dismiss, role, listNav],
|
||||
);
|
||||
|
||||
return {
|
||||
nodeId,
|
||||
parentId,
|
||||
isNested,
|
||||
refs,
|
||||
floatingStyles,
|
||||
context,
|
||||
getReferenceProps,
|
||||
getFloatingProps,
|
||||
getItemProps,
|
||||
elementsRef,
|
||||
selectedIndex,
|
||||
setSelectedIndex,
|
||||
activeIndex,
|
||||
isOpen,
|
||||
setIsOpen
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user