Skip to content
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
36 changes: 33 additions & 3 deletions src/components/dropdown-menu/DropdownMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,16 @@ import {
SubmenuTrigger,
} from "react-aria-components";
import { DropdownMenuItem, DropdownMenuOption } from "./types";
import { Fragment, PropsWithChildren, ReactNode, useId, useRef } from "react";
import {
cloneElement,
Fragment,
isValidElement,
PropsWithChildren,
ReactElement,
ReactNode,
useId,
useRef,
} from "react";
import { MenuItemSeparator } from "../menu/types";
import clsx from "clsx";

Expand Down Expand Up @@ -59,13 +68,29 @@ export const DropdownMenu = ({
}: PropsWithChildren<DropdownMenuProps>) => {
const id = useId();
const triggerRef = useRef(null);
const menuId = `${id}-menu`;
const menuClassName = `c__dropdown-menu${
variant === "tiny" ? " c__dropdown-menu--tiny" : ""
}`;
const onOpenChangeHandler = (isOpen: boolean) => {
onOpenChange?.(isOpen);
};

const renderTrigger = (children: ReactNode) => {
if (!isValidElement(children)) {
return children;
}

const triggerElement = children as ReactElement<Record<string, unknown>>;

return cloneElement(triggerElement, {
...triggerElement.props,
"aria-controls": isOpen ? menuId : undefined,
"aria-expanded": isOpen,
"aria-haspopup": "menu",
});
};

const renderMenuItems = (items: DropdownMenuItem[]) =>
items.map((option, index) => {
if (isSeparator(option)) {
Expand Down Expand Up @@ -145,7 +170,7 @@ export const DropdownMenu = ({
e.preventDefault();
}}
>
{children}
{renderTrigger(children)}
</div>

<Popover
Expand All @@ -159,7 +184,12 @@ export const DropdownMenu = ({
shouldCloseOnInteractOutside={shouldCloseOnInteractOutside}
onOpenChange={onOpenChangeHandler}
>
<Menu className={menuClassName} aria-labelledby={id} autoFocus="first">
<Menu
id={menuId}
className={menuClassName}
aria-labelledby={id}
autoFocus="first"
>
{topMessage && (
<Header
className="c__dropdown-menu-item-top-message"
Expand Down