import React, { useState, useRef, useEffect } from 'react'; import { createPortal } from 'react-dom'; import { More } from 'iconsax-react'; export interface RowActionItem { label: string; icon?: React.ReactNode; onClick: () => void; className?: string; } interface RowActionsDropdownProps { actions: RowActionItem[]; className?: string; } const RowActionsDropdown: React.FC = ({ actions, className = '' }) => { const [isOpen, setIsOpen] = useState(false); const [position, setPosition] = useState({ top: 0, left: 0 }); const dropdownRef = useRef(null); const buttonRef = useRef(null); useEffect(() => { const handleClickOutside = (event: MouseEvent) => { if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) { setIsOpen(false); } }; document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; }, []); const handleToggle = (e: React.MouseEvent) => { e.stopPropagation(); if (!isOpen && buttonRef.current) { const rect = buttonRef.current.getBoundingClientRect(); const isMobile = window.innerWidth < 768; const dropdownWidth = isMobile ? 140 : 150; const dropdownHeight = actions.length * (isMobile ? 36 : 40); // تخمین ارتفاع منو let left = rect.left + window.scrollX - dropdownWidth + rect.width; let top = rect.bottom + window.scrollY; // بررسی اینکه منو از سمت راست خارج نشود if (left + dropdownWidth > window.innerWidth) { left = rect.left + window.scrollX - dropdownWidth; } // بررسی اینکه منو از سمت چپ خارج نشود if (left < 0) { left = isMobile ? 20 : 40; } // بررسی اینکه منو از پایین خارج نشود if (top + dropdownHeight > window.innerHeight + window.scrollY) { top = rect.top + window.scrollY - dropdownHeight; } setPosition({ top, left }); } setIsOpen(!isOpen); }; const handleActionClick = (action: RowActionItem) => { action.onClick(); setIsOpen(false); }; const renderDropdown = () => { if (!isOpen) return null; return createPortal(
{actions.map((action, index) => ( ))}
, document.body ); }; return (
{renderDropdown()}
); }; export default RowActionsDropdown;