import React from 'react'; import { MenuToggle, Menu, MenuContent, MenuList, MenuItem, Popper } from '@patternfly/react-core'; import text from '@patternfly/react-styles/css/utilities/Text/text'; export const ComposableSimpleDropdown: React.FunctionComponent = () => { const [isOpen, setIsOpen] = React.useState(false); const [selected, setSelected] = React.useState(0); const toggleRef = React.useRef(); const menuRef = React.useRef(); const handleMenuKeys = (event: KeyboardEvent) => { if (!isOpen) { return; } if (menuRef?.current?.contains(event.target as Node) || toggleRef?.current?.contains(event.target as Node)) { if (event.key === 'Escape' || event.key === 'Tab') { setIsOpen(!isOpen); toggleRef?.current?.focus(); } } }; const handleClickOutside = (event: MouseEvent) => { if (isOpen && !menuRef?.current?.contains(event.target as Node)) { setIsOpen(false); } }; React.useEffect(() => { window.addEventListener('keydown', handleMenuKeys); window.addEventListener('click', handleClickOutside); return () => { window.removeEventListener('keydown', handleMenuKeys); window.removeEventListener('click', handleClickOutside); }; }, [isOpen, menuRef]); const onToggleClick = (ev: React.MouseEvent) => { ev.stopPropagation(); // Stop handleClickOutside from handling setTimeout(() => { if (menuRef.current) { const firstElement = menuRef.current.querySelector('li > button:not(:disabled)'); firstElement && (firstElement as HTMLElement).focus(); } }, 0); setIsOpen(!isOpen); }; const monthStrings = [ 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December' ]; const dateString = (date: Date) => `${monthStrings[date.getMonth()]} ${date.getDate()}, ${date.getFullYear()}`; const date = new Date(); const toggleText = { 0: 'Today ', 1: 'Yesterday ', 2: 'Last 7 days ', 3: 'Last 14 days ' }; const dateText = { 0: ({dateString(date)}), 1: ( ({dateString(new Date(new Date().setDate(date.getDate() - 1)))} - {dateString(date)}) ), 2: ( ({dateString(new Date(new Date().setDate(date.getDate() - 7)))} - {dateString(date)}) ), 3: ( ({dateString(new Date(new Date().setDate(date.getDate() - 14)))} - {dateString(date)}) ) }; const toggle = ( {toggleText[selected]} {dateText[selected]} ); const menu = ( // eslint-disable-next-line no-console setSelected(itemId as number)} selected={selected}> Today Yesterday Last 7 days Last 14 days ); return ; };