mm
This commit is contained in:
@@ -0,0 +1,83 @@
|
||||
import { arrow, autoUpdate, flip, offset, shift, useClick, useDismiss, useFloating, useInteractions, useRole, useTransitionStyles } from "@floating-ui/react";
|
||||
import { useMemo, useRef, useState } from "react";
|
||||
|
||||
export function usePopoverFloating() {
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const arrowRef = useRef(null);
|
||||
|
||||
// 拉扯 svg 图像,让三角变得,更尖更长,或者更宽更扁
|
||||
const arrowWidth = 16
|
||||
const arrowHeight = 8
|
||||
|
||||
const { refs, floatingStyles, context, middlewareData } = useFloating({
|
||||
placement: "top-start",
|
||||
open: isOpen,
|
||||
onOpenChange: setIsOpen,
|
||||
whileElementsMounted: autoUpdate,
|
||||
middleware: [
|
||||
offset(arrowHeight),
|
||||
flip({ padding: 8 }),
|
||||
// 偏移完成后,再留 8px 空白,而不是紧贴着父容器
|
||||
shift({ padding: 8 }),
|
||||
arrow({
|
||||
element: arrowRef,
|
||||
}),
|
||||
],
|
||||
});
|
||||
|
||||
// 这两个是未经 useFloating 变换前的坐标
|
||||
// 也就是 arrow 悬浮,左对齐 floating,两者水平中线重合
|
||||
const arrowX = middlewareData.arrow?.x ?? 0;
|
||||
const arrowY = middlewareData.arrow?.y ?? 0;
|
||||
|
||||
// 变换中心的起始坐标就是 floating 的左上角
|
||||
const transformX = arrowX + arrowWidth / 2;
|
||||
const transformY = arrowY + arrowHeight;
|
||||
|
||||
// style 用于内容框,而不是 FloatingArrow
|
||||
const { isMounted, styles: transitionStyles } = useTransitionStyles(context, {
|
||||
duration: 150,
|
||||
initial: {
|
||||
opacity: 0,
|
||||
transform: "scale(0)"
|
||||
},
|
||||
close: {
|
||||
opacity: 0
|
||||
},
|
||||
common: ({ side }) => ({
|
||||
transitionTimingFunction: "ease",
|
||||
transformOrigin: {
|
||||
top: `${transformX}px calc(100% + ${arrowHeight}px)`,
|
||||
bottom: `${transformX}px ${-arrowHeight}px`,
|
||||
left: `calc(100% + ${arrowHeight}px) ${transformY}px`,
|
||||
right: `${-arrowHeight}px ${transformY}px`
|
||||
}[side]
|
||||
})
|
||||
})
|
||||
|
||||
const click = useClick(context);
|
||||
const dismiss = useDismiss(context);
|
||||
const role = useRole(context);
|
||||
|
||||
const { getReferenceProps, getFloatingProps } = useInteractions([
|
||||
click,
|
||||
dismiss,
|
||||
role,
|
||||
]);
|
||||
|
||||
return useMemo(() => ({
|
||||
isOpen,
|
||||
setIsOpen,
|
||||
/* only use at {isMounted && <FloatingPortal/>} */
|
||||
isMounted,
|
||||
arrowRef,
|
||||
arrowHeight,
|
||||
arrowWidth,
|
||||
refs,
|
||||
floatingStyles,
|
||||
transitionStyles,
|
||||
context,
|
||||
getReferenceProps,
|
||||
getFloatingProps
|
||||
}), [isOpen, setIsOpen, isMounted, refs, arrowHeight, arrowWidth, arrowRef, floatingStyles, transitionStyles, context, getReferenceProps, getFloatingProps])
|
||||
}
|
||||
Reference in New Issue
Block a user