diff --git a/src/Button.tsx b/src/Button.tsx index 07b6ced..2d62592 100644 --- a/src/Button.tsx +++ b/src/Button.tsx @@ -38,24 +38,24 @@ const AriaMenuButtonButton: React.FC< const [isOpen, setIsOpen] = React.useState(false); React.useEffect(() => { const managerRef = menuManager.current; - if (innerRef.current) { - managerRef.button = { - element: innerRef.current, - functions: { - focus: () => { - innerRef.current?.focus(); - }, - setState: (state) => { - flushSync(() => { - if (managerRef) { - managerRef.isOpen = state.menuOpen; - setIsOpen(state.menuOpen); - } - }); - }, + + managerRef.button = { + element: innerRef.current, + functions: { + focus: () => { + innerRef.current?.focus(); }, - }; - } + setState: (state) => { + flushSync(() => { + if (managerRef) { + managerRef.isOpen = state.menuOpen; + setIsOpen(state.menuOpen); + } + }); + }, + }, + }; + return () => { managerRef.destroy(); }; diff --git a/src/Menu.test.tsx b/src/Menu.test.tsx index 35d5389..3e2781b 100644 --- a/src/Menu.test.tsx +++ b/src/Menu.test.tsx @@ -297,3 +297,35 @@ test("allows the user to pass an `id` to the `wrapper` and that `id` is rendered ); expect(screen.getByTestId("wrapper")).toHaveAttribute("id", "foo"); }); + +test("it should not render a menu if the menu is not open", async () => { + render( + + + + + + , + ); + expect(screen.queryByRole("menu")).not.toBeInTheDocument(); +}); + +test("when the menu opens the button should be aria-expanded=true", async () => { + render(); + expect(screen.getByRole("button", { name: "Select a word" })).toHaveAttribute( + "aria-expanded", + "false", + ); + const button = screen.getByRole("button", { name: "Select a word" }); + await userEvent.click(button); + expect(screen.getByRole("button", { name: "Select a word" })).toHaveAttribute( + "aria-expanded", + "true", + ); +}); diff --git a/src/Menu.tsx b/src/Menu.tsx index 8688a78..40ac640 100644 --- a/src/Menu.tsx +++ b/src/Menu.tsx @@ -25,11 +25,7 @@ const AriaMenuButtonMenu: React.FC< const listenerCleanupRef = React.useRef<() => void | undefined>(); React.useEffect(() => { - if (!el) { - return; - } const Manager = menuManagerRef.current; - Manager.menu = { element: el, functions: { @@ -100,6 +96,9 @@ const AriaMenuButtonMenu: React.FC< [forwardedRef, setEl], ); + if (menuManagerRef.current.isOpen === false) { + return; + } return (