Created
March 6, 2023 14:37
-
-
Save tmikeschu/62bf4f56d9c5e891e44ae5432cf4a38a to your computer and use it in GitHub Desktop.
Mocking Chakra's menu for slightly better performance.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// __mocks__/@chakra-ui/react.js | |
const React = require('react'); | |
const actual = jest.requireActual('@chakra-ui/react'); | |
const MenuContext = React.createContext({}); | |
const useMenuItem = props => { | |
const { | |
onMouseEnter: onMouseEnterProp, | |
onMouseMove: onMouseMoveProp, | |
onMouseLeave: onMouseLeaveProp, | |
onClick: onClickProp, | |
isDisabled, | |
isFocusable, | |
closeOnSelect, | |
type: typeProp, | |
...htmlProps | |
} = props; | |
return { | |
...htmlProps, | |
role: 'menuitem', | |
}; | |
}; | |
const Menu = ({ children, isOpen: isOpenProp, defaultIsOpen, onClose: onCloseProp, onOpen: onOpenProp }) => { | |
const { isOpen, onOpen, onClose, onToggle } = actual.useDisclosure({ | |
isOpen: isOpenProp, | |
defaultIsOpen, | |
onClose: onCloseProp, | |
onOpen: onOpenProp, | |
}); | |
React.useEffect(() => { | |
return () => { | |
onClose(); | |
}; | |
}, []); | |
return ( | |
<MenuContext.Provider value={{ onToggle, isOpen, onClose, onOpen, setFocusedIndex: () => {} }}> | |
{children} | |
</MenuContext.Provider> | |
); | |
}; | |
const MenuButton = React.forwardRef((props, ref) => { | |
const { onToggle } = React.useContext(MenuContext); | |
return ( | |
<actual.Button | |
ref={ref} | |
{...props} | |
onClick={() => { | |
onToggle(); | |
}} | |
/> | |
); | |
}); | |
const MenuList = ({ children }) => { | |
const { isOpen } = React.useContext(MenuContext); | |
return isOpen ? <ul role="menu">{children}</ul> : null; | |
}; | |
const MenuItem = ({ closeOnSelect = true, onClick: onClickProp, ...props }) => { | |
const { onToggle } = React.useContext(MenuContext); | |
const onClick = e => { | |
if (closeOnSelect) { | |
onToggle(); | |
} | |
onClickProp(e); | |
}; | |
return <actual.Button {...props} role="menuitem" onClick={onClick} />; | |
}; | |
const MenuDivider = () => { | |
return <div aria-label="chakra-menu__divider" role="separator" />; | |
}; | |
const MenuGroup = ({ children, title }) => { | |
return ( | |
<div aria-label="chakra-menu__group" role="group"> | |
<span>{title}</span> | |
{children} | |
</div> | |
); | |
}; | |
module.exports = { | |
__esModule: true, // Use it when dealing with esModules | |
...actual, | |
useBreakpointValue: jest.fn(), | |
Menu, | |
MenuList, | |
MenuItem, | |
MenuButton, | |
MenuDivider, | |
MenuGroup, | |
useMenuItem, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment