Skip to content
Draft
Show file tree
Hide file tree
Changes from 1 commit
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
152 changes: 119 additions & 33 deletions src/__internal__/popover-menu/popover-menu.component.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -31,12 +31,12 @@ import combineRefs from "../utils/helpers/combine-refs";
import { TableBodyContext } from "../../components/table/__internal__/contexts";
import { nextElementToFocus } from "../../hooks/__internal__/useFocusPortalContent";
import { getWindow } from "../dom/globals";
import useMediaQuery from "../../hooks/useMediaQuery";
import useResizeObserver from "../../hooks/__internal__/useResizeObserver";

const useIsomorphicLayoutEffect = getWindow() ? useLayoutEffect : useEffect;

const PopoverControlWrapper = styled.div<{
$controlWrapperStyle?: CSSObject;
}>`
const PopoverControlWrapper = styled.div<{ $controlWrapperStyle?: CSSObject }>`
display: inline-block;
${({ $controlWrapperStyle }) => $controlWrapperStyle}
`;
Expand Down Expand Up @@ -79,18 +79,60 @@ const horizontalPaddingSize = {
large: "var(--global-space-comp-s)",
};

const MenuWrapper = styled.div<ListProps>`
box-sizing: border-box;
interface MenuWrapperProps extends Pick<ListProps, "$size"> {
$contentHeight?: number;
}

// set full height on outer wrapper - prevents menu from flipping during reveal animation
const MenuWrapper = styled.div<MenuWrapperProps>`
width: max-content;
z-index: calc(var(--carbon-zindex-overlay) + 2);

${({ $contentHeight, $size }) =>
$contentHeight !== undefined &&
css`
// MenuContent is content-box, so include top and bottom padding
height: calc(${$contentHeight}px + 2 * ${verticalPaddingSize[$size]});
`}
`;

interface MenuContentProps extends Pick<ListProps, "$size" | "$isButtonMenu"> {
$contentHeight?: number;
$isRevealing?: boolean;
}

const REVEAL_DURATION = 200;
const revealEasing = `${REVEAL_DURATION}ms cubic-bezier(0.22, 0.61, 0.36, 1)`;

const MenuContent = styled.div<MenuContentProps>`
box-shadow: var(--global-depth-lvl1);
border-radius: var(--global-radius-container-m);
background-color: var(--popover-bg-default);
width: max-content;
position: relative;
z-index: calc(var(--carbon-zindex-overlay) + 2);

padding: ${({ $size }) => css`
${verticalPaddingSize[$size]} ${horizontalPaddingSize[$size]}
`};
${({ $size }) => css`
padding: ${verticalPaddingSize[$size]} ${horizontalPaddingSize[$size]};
`}

${({ $isRevealing, $contentHeight }) =>
$isRevealing &&
css`
box-sizing: content-box;
overflow: clip;
Comment thread
nuria1110 marked this conversation as resolved.
Resolved
transition:
height ${revealEasing},
padding-top ${revealEasing},
padding-bottom ${revealEasing};
Comment on lines +129 to +132

${$contentHeight === undefined
? css`
height: 0;
padding: 0;
`
: css`
height: ${$contentHeight}px;
`}
`}

${({ $isButtonMenu }) =>
!$isButtonMenu &&
Expand Down Expand Up @@ -214,7 +256,7 @@ export const getSubmenuOffset = ({
elements: { reference: unknown };
}) => {
const parentMenu = (elements.reference as Element).closest(
'[data-role="menu-wrapper"]',
'[data-role="menu-content"]',
);

if (!parentMenu) return 0;
Expand Down Expand Up @@ -266,12 +308,14 @@ interface MenuProps {
referenceElement: HTMLElement | null;
size: PopoverMenuContextProps["size"];
listRef: React.Ref<HTMLUListElement>;
internalListRef: React.RefObject<HTMLUListElement>;
listboxAriaLabelledBy?: string;
isButtonMenu?: boolean;
children: React.ReactNode;
onKeyDown: (ev: React.KeyboardEvent<HTMLElement>) => void;
middleware: PopoverProps["middleware"];
scrollRef: React.RefObject<HTMLDivElement>;
menuWrapperRef: React.MutableRefObject<HTMLDivElement | null>;
menuTreeId: string;
listId: string;
disablePortal?: boolean;
Expand All @@ -290,13 +334,15 @@ const Menu = ({
referenceElement,
size,
listRef,
internalListRef,
listboxAriaLabelledBy,
listboxAriaLabel,
isButtonMenu,
children,
onKeyDown,
middleware,
scrollRef,
menuWrapperRef,
menuTreeId,
listId,
disablePortal,
Expand All @@ -307,6 +353,34 @@ const Menu = ({
menuWrapperDataElement,
listTabIndex,
}: MenuProps) => {
const [contentHeight, setContentHeight] = useState<number>();
const [isRevealing, setIsRevealing] = useState(true);

const allowMotion = useMediaQuery(
"screen and (prefers-reduced-motion: no-preference)",
);
const isRevealingActive = allowMotion && isRevealing;

const updateContentHeight = useCallback(() => {
setContentHeight(
(internalListRef.current as HTMLUListElement).offsetHeight,
);
}, [internalListRef]);

useResizeObserver(internalListRef, updateContentHeight, !isRevealingActive);

// restarts on each content height change so the reveal ends once the latest transition completes
useEffect(() => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment: The reveal should run once when the menu opens, with a fixed completion time. Depending on contentHeight here restarts the timeout on each resize and can extend the reveal beyond that window. Could we start the timer on the first measurement and avoid resetting it for subsequent height changes?

const hasMeasuredContent = contentHeight !== undefined;

useEffect(() => {
  if (!isRevealingActive || !hasMeasuredContent) return undefined;

  const timeoutId = setTimeout(
    () => setIsRevealing(false),
    REVEAL_DURATION + 50,
  );

  return () => clearTimeout(timeoutId);
}, [isRevealingActive, hasMeasuredContent]);

if (!isRevealingActive || contentHeight === undefined) return undefined;

const timeoutId = setTimeout(
() => setIsRevealing(false),
REVEAL_DURATION + 50,
);

return () => clearTimeout(timeoutId);
}, [isRevealingActive, contentHeight]);

return (
<Popover
placement={placement}
Expand All @@ -320,33 +394,42 @@ const Menu = ({
popoverStrategy={popoverStrategy}
>
<MenuWrapper
ref={menuWrapperRef}
$contentHeight={isRevealingActive ? contentHeight : undefined}
$size={size}
onKeyDown={onKeyDown}
data-role="menu-wrapper"
data-element={menuWrapperDataElement}
onMouseDown={(e) => e.preventDefault()}
$isButtonMenu={isButtonMenu}
>
<ScrollWrapper
ref={scrollRef}
data-component="scroll-wrapper"
data-menu-tree-id={menuTreeId}
<MenuContent
$size={size}
$isRevealing={isRevealingActive}
$contentHeight={contentHeight}
$isButtonMenu={isButtonMenu}
data-role="menu-content"
>
<List
$size={size}
ref={listRef}
role={isButtonMenu ? "list" : "listbox"}
id={listId}
aria-labelledby={listboxAriaLabelledBy}
$isButtonMenu={isButtonMenu}
aria-label={listboxAriaLabel}
$maxHeight={maxHeight}
style={listStyle}
tabIndex={listTabIndex}
<ScrollWrapper
ref={scrollRef}
data-component="scroll-wrapper"
data-menu-tree-id={menuTreeId}
>
{children}
</List>
</ScrollWrapper>
<List
$size={size}
ref={listRef}
role={isButtonMenu ? "list" : "listbox"}
id={listId}
aria-labelledby={listboxAriaLabelledBy}
$isButtonMenu={isButtonMenu}
aria-label={listboxAriaLabel}
$maxHeight={maxHeight}
style={listStyle}
tabIndex={listTabIndex}
>
{children}
</List>
</ScrollWrapper>
</MenuContent>
</MenuWrapper>
</Popover>
);
Expand Down Expand Up @@ -457,6 +540,7 @@ const PopoverMenuInner = <TRef extends FocusableHandle = HTMLElement>(
const popoverReference =
controlElement === undefined ? controlWrapperElement : controlElement;
const scrollRef = useRef<HTMLDivElement | null>(null);
const menuWrapperRef = useRef<HTMLDivElement | null>(null);
const internalListRef = useRef<HTMLUListElement | null>(null);
const combinedListRef = useMemo(
() => combineRefs(listRef, internalListRef),
Expand Down Expand Up @@ -750,10 +834,10 @@ const PopoverMenuInner = <TRef extends FocusableHandle = HTMLElement>(
const el = isSubmenu ? scrollRef.current : wrapperRef.current;
// Portalled root menus do not bubble native events through the control wrapper.
const portalledMenuEl =
!isSubmenu && !disablePortal ? scrollRef.current : null;
!isSubmenu && !disablePortal ? menuWrapperRef.current : null;
const clickEl = clickAwayWithinReference ? popoverReference : el;
const menuEl = clickAwayWithinReference
? scrollRef.current?.parentElement
? menuWrapperRef.current
: portalledMenuEl;

clickEl?.addEventListener("click", handleClickInside, { passive: true });
Expand Down Expand Up @@ -874,7 +958,7 @@ const PopoverMenuInner = <TRef extends FocusableHandle = HTMLElement>(
if (
ev?.type === "click" &&
ev.target instanceof Element &&
scrollRef.current?.parentElement?.contains(ev.target) &&
menuWrapperRef.current?.contains(ev.target) &&
!ev.target.closest("button, a[href], input, select, textarea")
) {
props.triggerElement
Expand Down Expand Up @@ -956,12 +1040,14 @@ const PopoverMenuInner = <TRef extends FocusableHandle = HTMLElement>(
referenceElement={popoverReference}
size={size}
listRef={combinedListRef}
internalListRef={internalListRef}
listboxAriaLabelledBy={listboxAriaLabelledBy}
listboxAriaLabel={listboxAriaLabel}
isButtonMenu={isButtonMenu}
onKeyDown={handleMenuKeyDown}
middleware={computedMiddleware}
scrollRef={scrollRef}
menuWrapperRef={menuWrapperRef}
menuTreeId={menuTreeId}
listId={listId.current}
disablePortal={disablePortal && !isSubmenu}
Expand Down
71 changes: 66 additions & 5 deletions src/__internal__/popover-menu/popover-menu.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import Icon from "../../components/icon";
import { PopoverControlProps } from "./contexts";
import * as floatingUi from "@floating-ui/dom";
import { useHandleDropdownMenuKeyDown } from "./hooks";
import { mockMatchMedia } from "../../__spec_helper__/__internal__/test-utils";

interface AdditionalControlProps extends PopoverControlProps {
onClick?: () => void;
Expand Down Expand Up @@ -2149,13 +2150,11 @@ test.each([
["medium", "s", "s"],
["large", "m", "s"],
] as const)(
"renders the menu wrapper with the expected padding when size is %s",
"renders the menu content with the expected padding when size is %s",
(size, verticalPadding, horizontalPadding) => {
renderPopoverMenu({ open: true, size });
const menuWrapper = screen.getByTestId("menu-wrapper");

expect(menuWrapper).toHaveStyleRule("box-sizing", "border-box");
expect(menuWrapper).toHaveStyleRule(
expect(screen.getByTestId("menu-content")).toHaveStyleRule(
"padding",
`var(--global-space-comp-${verticalPadding}) var(--global-space-comp-${horizontalPadding})`,
);
Expand All @@ -2169,7 +2168,7 @@ describe("getSubmenuOffset", () => {
if (wrapperPadding === undefined) return reference;

const wrapper = document.createElement("div");
wrapper.setAttribute("data-role", "menu-wrapper");
wrapper.setAttribute("data-role", "menu-content");
wrapper.style.paddingRight = wrapperPadding;
wrapper.appendChild(reference);
document.body.appendChild(wrapper);
Expand Down Expand Up @@ -2466,3 +2465,65 @@ test("menu width falls back to control wrapper width when controlElement is not

rectSpy.mockRestore();
});

describe("when animating the menu", () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment: I think we need to add a test that covers that resizes partway through the opening reveal and verify that it does not restart the timer: revealing should end at the original deadline. Also verify that content changes after completion do not reactivate the animation.

let heightSpy: jest.SpyInstance;

beforeEach(() => {
mockMatchMedia(true);
heightSpy = jest
.spyOn(HTMLUListElement.prototype, "offsetHeight", "get")
.mockReturnValue(100);
});

afterEach(() => {
jest.useRealTimers();
heightSpy.mockRestore();
mockMatchMedia(false);
});

it("animates the menu to the height of its content when reduced motion is not preferred", () => {
renderPopoverMenu({ open: true });

expect(screen.getByTestId("menu-content")).toHaveStyle({
boxSizing: "content-box",
height: "100px",
});
expect(screen.getByTestId("menu-wrapper")).toHaveStyleRule(
"height",
"calc(100px + 2 * var(--global-space-comp-s))",
);
});

it("does not animate the menu when reduced motion is preferred", () => {
mockMatchMedia(false);
renderPopoverMenu({ open: true });

expect(screen.getByTestId("menu-content")).not.toHaveStyleRule(
"transition",
);
expect(screen.getByTestId("menu-wrapper")).not.toHaveStyleRule("height");
});

it("ends the reveal after the animation duration", () => {
jest.useFakeTimers();
renderPopoverMenu({ open: true });

act(() => {
jest.advanceTimersByTime(249);
});

expect(screen.getByTestId("menu-content")).toHaveStyle({
height: "100px",
});

act(() => {
jest.advanceTimersByTime(1);
});

expect(screen.getByTestId("menu-content")).not.toHaveStyleRule(
"transition",
);
expect(screen.getByTestId("menu-wrapper")).not.toHaveStyleRule("height");
});
});
4 changes: 2 additions & 2 deletions src/components/action-popover/action-popover.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -169,14 +169,14 @@ test.each([
);

await user.click(screen.getByRole("button", { name: "Actions" }));
expect(screen.getByTestId("menu-wrapper")).toHaveStyleRule(
expect(screen.getByTestId("menu-content")).toHaveStyleRule(
"padding",
`var(--global-space-comp-${verticalPadding}) var(--global-space-comp-${horizontalPadding})`,
);

await user.click(screen.getByRole("button", { name: "Print options" }));

const menus = screen.getAllByTestId("menu-wrapper");
const menus = screen.getAllByTestId("menu-content");
expect(menus).toHaveLength(2);
menus.forEach((menu) => {
expect(menu).toHaveStyleRule(
Expand Down
3 changes: 2 additions & 1 deletion src/components/select/simple-select/simple-select.pw.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,8 @@ test.describe("Check virtual scrolling", () => {
await expect(lastOption).toBeAttached();
});

test("when reopening the select after selecting an option, the selected option is visible", async ({
// skip due to flakiness - FE-7905
test.skip("when reopening the select after selecting an option, the selected option is visible", async ({

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

comment: I don't think we can skip this as this PR is adding the change that's causing the regression. It leaves 18px clipped after the animation ends. I think it's that you removed max-width: 100% on the inner container, the list can initially render wider, scroll the selected option into view, then wrap text when its final width applies.

@edleeks87 edleeks87 Dec 4, 2026 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (non-blocking): add the following before we scroll in this test as it will prevent flakiness

await expect(page.getByTestId("menu-content")).toHaveCSS(
  "transition-duration",
  "0s",
);

mount,
page,
}) => {
Expand Down
Loading