import React, { useState, useEffect, useRef } from 'react'; import PropTypes from 'prop-types'; import i18next from 'i18next'; import { get } from 'lodash'; import { ThemeProvider } from 'styled-components'; import { getTheme } from '../../../utils/theme'; import { Props } from './interfaces'; import Button from '../../../Button/index'; import iconDropDown from '../../../images/icon-carret-down-action-black.svg'; import { getRandomInt } from '../../../utils/format'; import { DropdownContainer, DropdownList, DropdownItem, DropdownItemText, CustomButton, Icon, IconContainer, ToolTipText, } from './styledComponents'; const Dropdown = (props: Props): JSX.Element => { const { theme, label, actions, customButton, setIsActionOpened, index } = props; const [isDropdownOpen, setIsDropdownOpen] = useState(false); const dropdownRef = useRef(null); const updatedTheme = getTheme(theme, 'listView'); const [dropdownListXPos, setDropdownListXPos] = useState(0); // eslint-disable-next-line @typescript-eslint/no-explicit-any const actionsAnyType: any[] = actions; const randomDropdownListId = `dropdownList-${getRandomInt()}`; const areAllActionsHidden = actionsAnyType.every( (action) => action.isHidden && action.isHidden() ); const close = () => { setIsDropdownOpen(false); if (setIsActionOpened) { setIsActionOpened(undefined); } }; const toggle = (e) => { e.stopPropagation(); if (isDropdownOpen) { close(); return; } setIsDropdownOpen(true); if (setIsActionOpened) { setIsActionOpened(index); } }; const handleClick = (event) => (handleAction) => { event.stopPropagation(); setIsDropdownOpen(false); handleAction(); }; useEffect(() => { function handleClickOutside(event) { const currentRef = get(dropdownRef, 'current'); if (currentRef && !currentRef.contains(event.target)) { close(); } } document.addEventListener('mousedown', handleClickOutside); return () => { document.removeEventListener('mousedown', handleClickOutside); }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [dropdownRef]); useEffect(() => { if (!isDropdownOpen) { setDropdownListXPos(0); return; } const dropdownListElem = document.getElementById(randomDropdownListId); if (dropdownListElem) { const dropdownListPos = dropdownListElem.getBoundingClientRect(); setDropdownListXPos(dropdownListPos.left); } }, [isDropdownOpen, randomDropdownListId]); return ( {actions.length && !areAllActionsHidden && ( {customButton ? ( toggle(e)}> {customButton(index || 0)} ) : (