save work

This commit is contained in:
Red Adaya
2024-09-22 21:57:46 +08:00
parent dc0eb91902
commit aefefa8c9d
2 changed files with 156 additions and 150 deletions
+7 -7
View File
@@ -64,27 +64,27 @@ export const Test: Story = {
}, },
args: { args: {
items: [ items: [
{ label: "Option 1", onClick: () => console.log("Clicked Option 1") }, { label: "Option 1", onClick: () => null },
{ {
label: "Option 2", label: "Option 2",
onClick: () => console.log("Clicked Option 2"), onClick: () => console.log("Clicked Option 2"),
subItems: [ subItems: [
{ label: "Option 2 -> 1", onClick: () => console.log("Clicked Sub-option 1") }, { label: "Option 2 -> 1", onClick: () => null },
{ label: "Option 2 -> 2", onClick: () => console.log("Clicked Sub-option 2") }, { label: "Option 2 -> 2", onClick: () => null },
], ],
}, },
{ {
label: "Option 3", label: "Option 3",
onClick: () => console.log("Clicked Option 3"), onClick: () => console.log("Clicked Option 3"),
subItems: [ subItems: [
{ label: "Option 3 -> 1", onClick: () => console.log("Clicked Sub-option 1") }, { label: "Option 3 -> 1", onClick: () => null },
{ label: "Option 3 -> 2", onClick: () => console.log("Clicked Sub-option 2") }, { label: "Option 3 -> 2", onClick: () => null },
{ {
label: "Option 3 -> 3", label: "Option 3 -> 3",
onClick: () => console.log("Clicked Option 3"), onClick: () => console.log("Clicked Option 3"),
subItems: [ subItems: [
{ label: "Option 3 -> 3 -> 1", onClick: () => console.log("Clicked Sub-option 1") }, { label: "Option 3 -> 3 -> 1", onClick: () => null },
{ label: "Option 3 -> 3 -> 2", onClick: () => console.log("Clicked Sub-option 2") }, { label: "Option 3 -> 3 -> 2", onClick: () => null },
], ],
}, },
], ],
+149 -143
View File
@@ -6,6 +6,64 @@ import ReactDOM from "react-dom";
import "./dropdown.less"; import "./dropdown.less";
const SubMenu = ({
subItems,
parentKey,
parentRef,
subMenuPosition,
visibleSubMenus,
handleMouseEnterItem,
subMenuRefs,
}: {
subItems: DropdownItem[];
parentKey: string;
parentRef: React.RefObject<HTMLDivElement>;
subMenuPosition: any;
visibleSubMenus: any;
handleMouseEnterItem: any;
subMenuRefs: any;
}) => {
return (
<div
className="dropdown sub-dropdown"
ref={subMenuRefs.current[parentKey]}
style={{
top: subMenuPosition[parentKey]?.top || 0,
left: subMenuPosition[parentKey]?.left || 0,
position: "absolute",
zIndex: 1000, // Ensure the submenu is above other elements
}}
>
{subItems.map((item, idx) => {
const newKey = `${parentKey}-${idx}`; // Full hierarchical key
console.log("newKey===============", newKey, visibleSubMenus[newKey]);
console.log("visibleSubMenus************", visibleSubMenus);
return (
<div
key={newKey}
className="dropdown-item"
onMouseOver={(event) => handleMouseEnterItem(event, parentKey, idx, item)}
>
{item.label}
{item.subItems && <span className="arrow"></span>}
{visibleSubMenus[newKey]?.visible && item.subItems && (
<SubMenu
subItems={item.subItems}
parentKey={newKey}
parentRef={subMenuRefs.current[parentKey]}
subMenuPosition={subMenuPosition}
visibleSubMenus={visibleSubMenus}
handleMouseEnterItem={handleMouseEnterItem}
subMenuRefs={subMenuRefs}
/>
)}
</div>
);
})}
</div>
);
};
type DropdownItem = { type DropdownItem = {
label: string; label: string;
onClick?: () => void; onClick?: () => void;
@@ -20,22 +78,27 @@ interface DropdownProps {
} }
const Dropdown = memo(({ items, anchorRef, boundaryRef, className }: DropdownProps) => { const Dropdown = memo(({ items, anchorRef, boundaryRef, className }: DropdownProps) => {
const [visibleSubMenus, setVisibleSubMenus] = useState<{ [key: number]: any }>({}); // Track visibility of each submenu (nested object) const [visibleSubMenus, setVisibleSubMenus] = useState<{ [key: string]: any }>({}); // Track visibility of each submenu
const [subMenuPosition, setSubMenuPosition] = useState<{ [key: number]: { top: number; left: number } }>({}); const [subMenuPosition, setSubMenuPosition] = useState<{
[key: string]: { top: number; left: number; label: string };
}>({});
const [position, setPosition] = useState({ top: 0, left: 0 }); const [position, setPosition] = useState({ top: 0, left: 0 });
const dropdownRef = useRef<HTMLDivElement>(null); const dropdownRef = useRef<HTMLDivElement>(null);
const subMenuRefs = useRef<Array<React.RefObject<HTMLDivElement>>>([]); // Array of refs for each submenu const subMenuRefs = useRef<{ [key: string]: React.RefObject<HTMLDivElement> }>({}); // Store refs using flat structure
const effectiveBoundaryRef: React.RefObject<HTMLElement> = boundaryRef ?? { current: document.documentElement }; const effectiveBoundaryRef: React.RefObject<HTMLElement> = boundaryRef ?? { current: document.documentElement };
const width = useWidth(effectiveBoundaryRef); const width = useWidth(effectiveBoundaryRef);
const height = useHeight(effectiveBoundaryRef); const height = useHeight(effectiveBoundaryRef);
// Add ref for each submenu item dynamically // console.log("visibleSubMenus.............", visibleSubMenus);
if (subMenuRefs.current.length !== items.length) {
subMenuRefs.current = Array(items.length) // Add ref for each submenu dynamically
.fill(null) items.forEach((_, idx) => {
.map((_, i) => subMenuRefs.current[i] || React.createRef<HTMLDivElement>()); const key = `${idx}`;
} if (!subMenuRefs.current[key]) {
subMenuRefs.current[key] = React.createRef<HTMLDivElement>();
}
});
useLayoutEffect(() => { useLayoutEffect(() => {
if (anchorRef.current && dropdownRef.current) { if (anchorRef.current && dropdownRef.current) {
@@ -64,15 +127,20 @@ const Dropdown = memo(({ items, anchorRef, boundaryRef, className }: DropdownPro
} }
}, [width, height]); }, [width, height]);
// Position submenus based on available space
const handleSubMenuPosition = ( const handleSubMenuPosition = (
parentIndex: number, key: string,
index: number,
itemRect: DOMRect, itemRect: DOMRect,
parentRef: React.RefObject<HTMLDivElement> | React.RefObject<HTMLElement> parentRef: React.RefObject<HTMLDivElement>,
label: string
) => { ) => {
const subMenuRef = subMenuRefs.current[index].current; // Delay the position calculation to allow the subMenuRef to be populated
const parentMenuRef = parentRef.current; setTimeout(() => {
if (subMenuRef && parentMenuRef) { const subMenuRef = subMenuRefs.current[key]?.current;
if (!subMenuRef) {
return; // Avoid proceeding if the ref is still null
}
const boundaryRect = effectiveBoundaryRef.current?.getBoundingClientRect() || { const boundaryRect = effectiveBoundaryRef.current?.getBoundingClientRect() || {
top: 0, top: 0,
left: 0, left: 0,
@@ -80,170 +148,108 @@ const Dropdown = memo(({ items, anchorRef, boundaryRef, className }: DropdownPro
right: window.innerWidth, right: window.innerWidth,
}; };
// Position to the right of the hovered item const submenuWidth = subMenuRef.offsetWidth;
let left = itemRect.width - 5; const submenuHeight = subMenuRef.offsetHeight;
// Adjust to the left if overflowing right boundary let left = itemRect.width; // Default position to the right of the hovered item
if (left + subMenuRef.offsetWidth > boundaryRect.right) { let top = submenuHeight - itemRect.height;
left = itemRect.left - subMenuRef.offsetWidth; // Align left if overflow
// Adjust to the left if overflowing the right boundary
if (left + submenuWidth > window.innerWidth) {
left = itemRect.left - submenuWidth;
} }
// Calculate top based on parent's position // Adjust if the submenu overflows the bottom boundary
const parentRect = parentMenuRef.getBoundingClientRect(); if (top + submenuHeight > window.innerHeight) {
const top = itemRect.top - parentRect.top; top = window.innerHeight - submenuHeight - 10;
}
// Set the submenu position
setSubMenuPosition((prev) => ({ setSubMenuPosition((prev) => ({
...prev, ...prev,
[parentIndex]: { [key]: { top, left, label },
...prev[parentIndex],
[index]: { top, left },
},
})); }));
} }, 0); // Delay by 50 milliseconds to ensure the submenu has rendered
}; };
// Recursive function to update visibility for multi-level submenus // Handle submenu visibility updates
const updateVisibility = (currentState: any, parentIndex: number | null, index: number, item: DropdownItem) => { const updateVisibility = (currentState: any, key: string, item: DropdownItem) => {
// Recursively clone the current state const updatedState = Object.keys(currentState).reduce((acc, k) => {
const updatedState = { ...currentState }; acc[k] = { ...currentState[k], visible: false };
return acc;
}, {} as any);
// Handle the case where we need to update a nested level (parentIndex is not null) updatedState[key] = { visible: true, label: item.label };
if (parentIndex !== null) {
// Ensure that the parentIndex exists in the state
if (!updatedState[parentIndex]) {
updatedState[parentIndex] = {};
}
// Reset visibility for all nested submenus at this level
for (let key in updatedState[parentIndex]) {
if (updatedState[parentIndex][key]?.visible !== undefined) {
updatedState[parentIndex][key].visible = false;
}
}
// Update the submenu at the correct level
updatedState[parentIndex] = updateVisibility(
updatedState[parentIndex], // Pass the state for the current level
null, // Stop recursion when we reach the correct level
index,
item
);
} else {
// We're at the correct level (root or no parent), so set all siblings' visibility to false
for (let key in updatedState) {
if (updatedState[key]?.visible !== undefined) {
updatedState[key].visible = false;
}
}
// Set the current index submenu to visible
updatedState[index] = { visible: true, label: item.label };
}
return updatedState; return updatedState;
}; };
const handleMouseEnterItem = ( const handleMouseEnterItem = (
event: React.MouseEvent<HTMLDivElement, MouseEvent>, event: React.MouseEvent<HTMLDivElement, MouseEvent>,
parentIndex: number | null, parentKey: string | null,
index: number, index: number,
item: DropdownItem, item: DropdownItem
parentRef: React.RefObject<HTMLDivElement> | React.RefObject<HTMLElement>,
reason?: string
) => { ) => {
event.stopPropagation(); event.stopPropagation();
const key = parentKey ? `${parentKey}-${index}` : `${index}`; // Full hierarchical key
setVisibleSubMenus((prev) => { setVisibleSubMenus((prev) => {
return updateVisibility(prev, parentIndex, index, item); // Preserve the current hierarchy visibility and only update the current item
const updatedState = { ...prev };
// Ensure the current submenu is visible
updatedState[key] = { visible: true, label: item.label };
return updatedState;
}); });
if (subMenuRefs.current[index].current) { const itemRect = event.currentTarget.getBoundingClientRect();
const itemRect = subMenuRefs.current[index].current!.parentElement?.getBoundingClientRect(); handleSubMenuPosition(key, itemRect, dropdownRef, item.label);
if (itemRect) {
handleSubMenuPosition(parentIndex ?? index, index, itemRect, parentRef);
}
}
}; };
const handleMouseLeaveItem = (parentIndex: number | null, index: number) => { // Hide submenu on mouse leave
const handleMouseLeaveItem = (key: string) => {
setTimeout(() => { setTimeout(() => {
setVisibleSubMenus((prev) => ({ setVisibleSubMenus((prev) => ({
...prev, ...prev,
[parentIndex ?? index]: { [key]: { ...prev[key], visible: false },
...prev[parentIndex ?? index], }));
[index]: { visible: false, label: prev[parentIndex ?? index][index].label }, // Maintain label
},
})); // Hide the specific submenu
}, 200); }, 200);
}; };
// Recursive renderSubMenu to handle multiple nested submenus // Render the main dropdown and submenus
const renderSubMenu = (
subItems: DropdownItem[],
parentIndex: number | null,
index: number,
parentRef: React.RefObject<HTMLDivElement>
) => {
return (
<div
className="dropdown sub-dropdown"
ref={subMenuRefs.current[index]} // Use unique ref for each submenu
style={{
top: subMenuPosition[parentIndex ?? index]?.[index]?.top || 0,
left: subMenuPosition[parentIndex ?? index]?.[index]?.left || 0,
}}
>
{subItems.map((item, idx) => (
<div
key={`${index}-${idx}`}
className="dropdown-item"
onMouseOver={(event) =>
handleMouseEnterItem(
event,
index,
idx,
item,
subMenuRefs.current[index],
"submenu item hovered"
)
}
onClick={item.onClick}
>
{item.label}
{item.subItems && <span className="arrow"></span>}
{visibleSubMenus[index]?.[idx]?.visible &&
item.subItems &&
renderSubMenu(item.subItems, index, idx, subMenuRefs.current[index])}
</div>
))}
</div>
);
};
if (!anchorRef?.current) {
return null;
}
return ReactDOM.createPortal( return ReactDOM.createPortal(
<div <div
className={clsx("dropdown", className)} className={clsx("dropdown", className)}
ref={dropdownRef} ref={dropdownRef}
style={{ top: position.top, left: position.left }} style={{ top: position.top, left: position.left }}
> >
{items.map((item, index) => ( {items.map((item, index) => {
<div const key = `${index}`;
key={index} return (
className="dropdown-item" <div
onMouseOver={(event) => key={key}
handleMouseEnterItem(event, null, index, item, dropdownRef, "root menu item hovered") className="dropdown-item"
} onMouseOver={(event) => handleMouseEnterItem(event, null, index, item)}
onClick={item.onClick} >
> {item.label}
{item.label} {item.subItems && <span className="arrow"></span>}
{item.subItems && <span className="arrow"></span>} {visibleSubMenus[key]?.visible && item.subItems && (
{visibleSubMenus[index]?.visible && <SubMenu
item.subItems && subItems={item.subItems}
renderSubMenu(item.subItems, null, index, dropdownRef)} parentKey={key}
</div> parentRef={dropdownRef}
))} subMenuPosition={subMenuPosition}
visibleSubMenus={visibleSubMenus}
handleMouseEnterItem={handleMouseEnterItem}
// handleMouseLeaveItem={handleMouseLeaveItem}
subMenuRefs={subMenuRefs}
/>
)}
</div>
);
})}
</div>, </div>,
document.body document.body
); );