Compare commits

..
Author SHA1 Message Date
Ken d5cd1d3bc5 fix: Handle flaky dialog-test 2026-11-18 15:49:22 +01:00
Ken 97777fd182 fix: popover dismissal in nested shadow roots 2026-11-18 15:46:56 +01:00
Ken 070d0a4623 feat: DismissableLayer now handles use within web-components 2026-11-18 15:33:19 +01:00
30 changed files with 703 additions and 132 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@navikt/ds-react": patch
---
Popover and other floating components: Dismiss when focus leaves the overlay and its trigger, including inside web components.
@@ -8,7 +8,9 @@ import {
waitFor,
within,
} from "storybook/test";
import { ActionMenu } from "../action-menu";
import { Button } from "../button";
import { Popover } from "../popover";
import { Provider } from "../provider";
import {
Dialog,
@@ -701,6 +703,7 @@ export const TabToLinks: Story = {
play: async ({ canvasElement, args }) => {
const { canvas } = testUtils(canvasElement, args);
await waitFor(() => expect(canvas.getByTestId("popup")).toHaveFocus());
await userEvent.tab();
expect(canvas.getByPlaceholderText("test")).toHaveFocus();
await userEvent.tab();
@@ -712,6 +715,128 @@ export const TabToLinks: Story = {
},
};
/* ----------------------- Nested dismissable layers ------------------------ */
function PopoverInDialog() {
const [anchorEl, setAnchorEl] = React.useState<HTMLButtonElement | null>(
null,
);
const [open, setOpen] = React.useState(false);
return (
<>
<button
type="button"
ref={setAnchorEl}
aria-expanded={open}
onClick={() => setOpen((prev) => !prev)}
>
Popover trigger
</button>
<Popover open={open} anchorEl={anchorEl} onClose={() => setOpen(false)}>
<Popover.Content>
<button type="button">Inside popover</button>
</Popover.Content>
</Popover>
<button type="button">Dialog button</button>
</>
);
}
export const PopoverInsideDialog: Story = {
render: BaseDialogComponent,
beforeEach: withoutAnimations,
play: async ({ canvasElement, args }) => {
const { canvas, expectPopupOpen, expectOpenChangeCalls } = testUtils(
canvasElement,
args,
);
await waitFor(() => expect(canvas.getByTestId("popup")).toHaveFocus());
const popoverTrigger = canvas.getByRole("button", {
name: "Popover trigger",
});
const openPopover = async () => {
popoverTrigger.focus();
await userEvent.keyboard("{Enter}");
expect(popoverTrigger).toHaveAttribute("aria-expanded", "true");
};
await openPopover();
await userEvent.tab();
expect(
canvas.getByRole("button", { name: "Inside popover" }),
).toHaveFocus();
await userEvent.tab();
expect(canvas.getByRole("button", { name: "Dialog button" })).toHaveFocus();
await waitFor(() =>
expect(popoverTrigger).toHaveAttribute("aria-expanded", "false"),
);
expectPopupOpen();
await openPopover();
await userEvent.keyboard("{Escape}");
await waitFor(() =>
expect(popoverTrigger).toHaveAttribute("aria-expanded", "false"),
);
expectPopupOpen();
expectOpenChangeCalls(0);
},
args: {
rootProps: { defaultOpen: true, onOpenChange: fn() },
popupProps: { children: <PopoverInDialog /> },
},
};
export const ActionMenuInsideDialog: Story = {
render: BaseDialogComponent,
beforeEach: withoutAnimations,
play: async ({ canvasElement, args }) => {
const { canvas, expectPopupOpen, expectOpenChangeCalls } = testUtils(
canvasElement,
args,
);
await waitFor(() => expect(canvas.getByTestId("popup")).toHaveFocus());
const menuTrigger = canvas.getByRole("button", { name: "Menu" });
const expectMenuClosed = () =>
waitFor(() =>
expect(canvas.queryByRole("menuitem")).not.toBeInTheDocument(),
);
await userEvent.click(menuTrigger);
await canvas.findByRole("menuitem", { name: "Item" });
canvas.getByRole("button", { name: "Dialog button" }).focus();
await expectMenuClosed();
expectPopupOpen();
await userEvent.click(menuTrigger);
await canvas.findByRole("menuitem", { name: "Item" });
await userEvent.keyboard("{Escape}");
await expectMenuClosed();
await waitFor(() => expect(menuTrigger).toHaveFocus());
expectPopupOpen();
expectOpenChangeCalls(0);
},
args: {
rootProps: { defaultOpen: true, onOpenChange: fn() },
popupProps: {
children: (
<>
<ActionMenu>
<ActionMenu.Trigger>
<button type="button">Menu</button>
</ActionMenu.Trigger>
<ActionMenu.Content>
<ActionMenu.Item>Item</ActionMenu.Item>
</ActionMenu.Content>
</ActionMenu>
<button type="button">Dialog button</button>
</>
),
},
},
};
/* ------------------------------- Test setup ------------------------------- */
type BaseDialogProps = {
rootProps?: Omit<DialogProps, "children"> & { children?: React.ReactNode };
@@ -157,7 +157,6 @@ const Combobox = forwardRef(
interface ComboboxSingleProps<
T extends ComboboxOptionData[] | ComboboxGroupData<ComboboxOptionData>[],
> extends Omit<ComboboxProps<T>, "multiple" | "value" | "onToggleOption"> {
// TODO: Vurder å eksponere onToggleOption
/**
* Called when selected option changes.
*/
@@ -207,7 +206,7 @@ const ComboboxSingle = forwardRef(
isSelected,
) => {
setLocalValue(isSelected ? option.value : null);
};
}; // TODO: Dumt at ikke får hele option-objektet... Legge til i onChange? Hvis vi tilbyr onToggle så blir det så likt onChange...
return (
<Combobox
@@ -18,7 +18,7 @@ import {
import { ComboboxTrigger } from "./trigger/ComboboxTrigger";
const meta: Meta<typeof ComboboxSingle> = {
title: "ds-react/Combobox",
title: "ds-react/Combobox2",
component: ComboboxSingle,
parameters: {
chromatic: { disable: true },
@@ -12,7 +12,7 @@ import {
} from "./root/ComboboxRoot";
const meta: Meta<typeof ComboboxRoot> = {
title: "ds-react/Combobox/Tests",
title: "ds-react/Combobox2/Tests",
component: ComboboxRoot,
parameters: {
chromatic: { disable: true },
@@ -14,7 +14,7 @@ import {
} from "../root/ComboboxRoot";
const meta: Meta<typeof ComboboxRoot> = {
title: "ds-react/Combobox/Popup",
title: "ds-react/Combobox2/Popup",
component: ComboboxRoot,
parameters: {
chromatic: { disable: true },
@@ -10,7 +10,7 @@ import { Alert } from "../alert";
import { type ComboboxProps, UNSAFE_Combobox } from "./index";
export default {
title: "ds-react/Combobox legacy",
title: "ds-react/Combobox",
component: UNSAFE_Combobox,
decorators: [
(story) => (
@@ -4,7 +4,7 @@ import { expect, fn, userEvent, within } from "storybook/test";
import { UNSAFE_Combobox } from "./index";
export default {
title: "ds-react/Combobox legacy/Tests",
title: "ds-react/Combobox/Tests",
component: UNSAFE_Combobox,
decorators: [(story) => <div style={{ width: "300px" }}>{story()}</div>],
parameters: {
@@ -121,3 +121,37 @@ export const HideOnCloseButtonClick: Story = {
expect(trigger).toHaveFocus();
},
};
/* The focus trap moves focus back through guards outside the Popover tree. */
export const KeepOpenWhileTabbing: Story = {
render: () => (
<>
<button type="button">Before</button>
<Lookup {...defaultProps}>
A text with a <a href="#lookup">link</a>.
</Lookup>
<button type="button">After</button>
</>
),
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const page = within(document.body);
const trigger = canvas.getByRole("button", { name: "Lookup" });
trigger.focus();
await userEvent.keyboard("{Enter}");
const dialog = await page.findByRole("dialog");
await waitFor(() => expect(dialog).toHaveFocus());
for (const shift of [false, false, false, false, true, true, true]) {
await userEvent.tab({ shift });
expect(dialog).toContainElement(document.activeElement as HTMLElement);
}
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(dialog).toBeVisible();
await userEvent.keyboard("{Escape}");
await waitFor(() => expect(dialog).not.toBeInTheDocument());
expect(trigger).toHaveFocus();
},
};
@@ -48,6 +48,7 @@ export const Default = () => {
return (
<div tabIndex={-1}>
<Button>Before</Button>
<Button ref={setAnchorEl} onClick={() => setOpen((x) => !x)}>
Open
</Button>
@@ -1,6 +1,8 @@
import type { StoryObj } from "@storybook/react-vite";
import React, { useState } from "react";
import { expect, userEvent, waitFor, within } from "storybook/test";
import { createPortal } from "react-dom";
import { expect, fn, userEvent, waitFor, within } from "storybook/test";
import { Dialog, DialogPopup, DialogTitle, DialogTrigger } from "../dialog";
import { Popover } from "./root/PopoverRoot";
export default {
@@ -101,6 +103,367 @@ export const KeepOpenOnPopoverClick: Story = {
},
};
function ShadowFocusTestRender() {
const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
const [open, setOpen] = useState(false);
return (
<div>
<button type="button" ref={setAnchorEl} onClick={() => setOpen(true)}>
Open popover
</button>
<Popover open={open} anchorEl={anchorEl} onClose={() => setOpen(false)}>
<button type="button">Inside popover</button>
{open &&
anchorEl &&
createPortal(
<button type="button">Portaled popover content</button>,
anchorEl.ownerDocument.body,
)}
</Popover>
<button type="button">Another button</button>
</div>
);
}
export const DismissOnFocusLeavingShadowPopover: Story = {
globals: { webComponentWrapper: "open" },
render: () => <ShadowFocusTestRender />,
play: async ({ canvasElement }) => {
const root = canvasElement.firstElementChild?.shadowRoot;
const mount = root?.querySelector("div");
if (!root || !mount) {
throw new Error("Expected the open shadow root Storybook decorator");
}
const canvas = within(mount);
const anchor = canvas.getByRole("button", { name: "Open popover" });
const outside = canvas.getByRole("button", { name: "Another button" });
anchor.focus();
await userEvent.click(anchor);
const inside = canvas.getByRole("button", { name: "Inside popover" });
expect(inside).toBeVisible();
inside.focus();
expect(root.activeElement).toBe(inside);
const portaled = within(canvasElement.ownerDocument.body).getByRole(
"button",
{ name: "Portaled popover content" },
);
portaled.focus();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(portaled).toHaveFocus();
expect(inside).toBeVisible();
anchor.focus();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(root.activeElement).toBe(anchor);
expect(inside).toBeVisible();
// Like tabbing past a Popover with no tabbable content, leaving the anchor
// directly should close it too.
outside.focus();
expect(root.activeElement).toBe(outside);
await waitFor(() => expect(inside).not.toBeVisible());
await userEvent.click(anchor);
inside.focus();
expect(root.activeElement).toBe(inside);
expect(inside).toBeVisible();
outside.focus();
await waitFor(() => expect(inside).not.toBeVisible());
expect(root.activeElement).toBe(outside);
},
};
export const DismissOnFocusMovingToEnclosingShadowRoot: Story = {
globals: { webComponentWrapper: "open" },
render: function NestedShadowPopover() {
const [root, setRoot] = useState<ShadowRoot | null>(null);
const attachRoot = React.useCallback((host: HTMLDivElement | null) => {
if (host) {
setRoot(host.shadowRoot ?? host.attachShadow({ mode: "open" }));
}
}, []);
return (
<>
<div ref={attachRoot} data-testid="inner-host" />
{root && createPortal(<ShadowFocusTestRender />, root)}
<button type="button">Enclosing root button</button>
</>
);
},
play: async ({ canvasElement }) => {
const outerRoot = canvasElement.firstElementChild?.shadowRoot;
const outerMount = outerRoot?.querySelector("div");
if (!outerRoot || !outerMount) {
throw new Error("Expected the open shadow root Storybook decorator");
}
const outerCanvas = within(outerMount);
const innerRoot = outerCanvas.getByTestId("inner-host").shadowRoot;
const innerMount = innerRoot?.querySelector("div");
if (!innerRoot || !innerMount) {
throw new Error("Expected a popover in the nested shadow root");
}
const innerCanvas = within(innerMount);
await userEvent.click(
innerCanvas.getByRole("button", { name: "Open popover" }),
);
const inside = innerCanvas.getByRole("button", { name: "Inside popover" });
inside.focus();
await tick();
expect(innerRoot.activeElement).toBe(inside);
const enclosingButton = outerCanvas.getByRole("button", {
name: "Enclosing root button",
});
enclosingButton.focus();
await waitFor(() =>
expect(
innerCanvas.queryByRole("button", { name: "Inside popover" }),
).not.toBeInTheDocument(),
);
expect(outerRoot.activeElement).toBe(enclosingButton);
},
};
/* ------------------------- Focus outside scenarios ------------------------ */
function tick() {
return new Promise<void>((resolve) => setTimeout(resolve, 0));
}
function FocusScenarioRender({
onClose,
children,
}: {
onClose?: () => void;
children?: React.ReactNode;
}) {
const [anchorEl, setAnchorEl] = useState<HTMLButtonElement | null>(null);
const [open, setOpen] = useState(false);
return (
<div>
<button type="button">Before</button>
<button
type="button"
ref={setAnchorEl}
aria-expanded={open}
onClick={() => setOpen((prev) => !prev)}
>
Trigger
</button>
<Popover
open={open}
anchorEl={anchorEl}
onClose={() => {
onClose?.();
setOpen(false);
}}
>
<Popover.Content>
<button type="button">Inside</button>
{children}
</Popover.Content>
</Popover>
<button type="button">After</button>
</div>
);
}
function getFocusScenario(canvasElement: HTMLElement) {
const canvas = within(canvasElement);
const trigger = canvas.getByRole("button", { name: "Trigger" });
return {
canvas,
before: canvas.getByRole("button", { name: "Before" }),
trigger,
after: canvas.getByRole("button", { name: "After" }),
openWithKeyboard: async () => {
trigger.focus();
await userEvent.keyboard("{Enter}");
expect(trigger).toHaveAttribute("aria-expanded", "true");
},
expectClosed: () =>
waitFor(() => expect(trigger).toHaveAttribute("aria-expanded", "false")),
};
}
export const FocusOutsideWithoutFocusedTrigger: Story = {
render: (args) => <FocusScenarioRender onClose={args.onClose} />,
play: async ({ args, canvasElement }) => {
const { before, trigger, after, expectClosed } =
getFocusScenario(canvasElement);
before.focus();
after.focus();
await tick();
expect(args.onClose).not.toHaveBeenCalled();
// Safari and Firefox on macOS don't focus buttons on click
await userEvent.click(trigger);
trigger.blur();
expect(document.body).toHaveFocus();
expect(trigger).toHaveAttribute("aria-expanded", "true");
after.focus();
await expectClosed();
expect(args.onClose).toHaveBeenCalledOnce();
},
args: { onClose: fn() },
};
export const FocusOutsideWithKeyboard: Story = {
render: (args) => <FocusScenarioRender onClose={args.onClose} />,
play: async ({ args, canvasElement }) => {
const { canvas, before, trigger, after, openWithKeyboard, expectClosed } =
getFocusScenario(canvasElement);
await openWithKeyboard();
await userEvent.tab();
expect(canvas.getByRole("button", { name: "Inside" })).toHaveFocus();
await userEvent.tab({ shift: true });
expect(trigger).toHaveFocus();
await tick();
expect(args.onClose).not.toHaveBeenCalled();
await userEvent.tab({ shift: true });
expect(before).toHaveFocus();
await expectClosed();
expect(args.onClose).toHaveBeenCalledOnce();
await openWithKeyboard();
await userEvent.tab();
await userEvent.tab();
expect(after).toHaveFocus();
await expectClosed();
expect(args.onClose).toHaveBeenCalledTimes(2);
},
args: { onClose: fn() },
};
function SelfRemovingButton() {
const [visible, setVisible] = useState(true);
return visible ? (
<button type="button" onClick={() => setVisible(false)}>
Remove me
</button>
) : null;
}
export const FocusOutsideAfterFocusedContentIsRemoved: Story = {
render: (args) => (
<FocusScenarioRender onClose={args.onClose}>
<SelfRemovingButton />
</FocusScenarioRender>
),
play: async ({ args, canvasElement }) => {
const { canvas, after, openWithKeyboard, expectClosed } =
getFocusScenario(canvasElement);
await openWithKeyboard();
canvas.getByRole("button", { name: "Remove me" }).focus();
await userEvent.keyboard("{Enter}");
await waitFor(() =>
expect(
canvas.queryByRole("button", { name: "Remove me" }),
).not.toBeInTheDocument(),
);
await tick();
expect(args.onClose).not.toHaveBeenCalled();
after.focus();
await expectClosed();
expect(args.onClose).toHaveBeenCalledOnce();
},
args: { onClose: fn() },
};
function PortaledButton() {
return createPortal(<button type="button">Portaled</button>, document.body);
}
export const KeepOpenWhenFocusMovesIntoPortalOrIframe: Story = {
render: (args) => (
<FocusScenarioRender onClose={args.onClose}>
<PortaledButton />
<iframe title="Embedded" srcDoc="<button>Inside frame</button>" />
</FocusScenarioRender>
),
play: async ({ args, canvasElement }) => {
const { canvas, trigger, after, openWithKeyboard, expectClosed } =
getFocusScenario(canvasElement);
await openWithKeyboard();
within(document.body).getByRole("button", { name: "Portaled" }).focus();
await tick();
canvas.getByTitle("Embedded").focus();
await tick();
expect(args.onClose).not.toHaveBeenCalled();
expect(trigger).toHaveAttribute("aria-expanded", "true");
after.focus();
await expectClosed();
expect(args.onClose).toHaveBeenCalledOnce();
},
args: { onClose: fn() },
};
export const KeepOpenWhileNestedDialogIsOpen: Story = {
render: (args) => (
<FocusScenarioRender onClose={args.onClose}>
<Dialog>
<DialogTrigger>
<button type="button">Open dialog</button>
</DialogTrigger>
<DialogPopup aria-labelledby="nested-dialog-title">
<DialogTitle id="nested-dialog-title">Nested dialog</DialogTitle>
<button type="button">Dialog button</button>
</DialogPopup>
</Dialog>
</FocusScenarioRender>
),
beforeEach: () => {
globalThis.AKSEL_NO_EXIT_ANIMATIONS = true;
return () => {
globalThis.AKSEL_NO_EXIT_ANIMATIONS = false;
};
},
play: async ({ args, canvasElement }) => {
const { canvas, trigger, openWithKeyboard, expectClosed } =
getFocusScenario(canvasElement);
const page = within(document.body);
await openWithKeyboard();
const dialogTrigger = canvas.getByRole("button", { name: "Open dialog" });
dialogTrigger.focus();
await userEvent.keyboard("{Enter}");
const dialog = await page.findByRole("dialog", { name: "Nested dialog" });
await waitFor(() => expect(dialog).toHaveFocus());
await userEvent.tab();
expect(page.getByRole("button", { name: "Dialog button" })).toHaveFocus();
await userEvent.tab();
await userEvent.tab({ shift: true });
await tick();
expect(args.onClose).not.toHaveBeenCalled();
await userEvent.keyboard("{Escape}");
await waitFor(() => expect(dialog).not.toBeInTheDocument());
await waitFor(() => expect(dialogTrigger).toHaveFocus());
await tick();
expect(args.onClose).not.toHaveBeenCalled();
expect(trigger).toHaveAttribute("aria-expanded", "true");
await userEvent.keyboard("{Escape}");
await expectClosed();
},
args: { onClose: fn() },
};
function PopoverPlacementTestRender({
anchorTop,
popoverHeight,
@@ -47,20 +47,36 @@ export const FocusOutside: Story = {
render: (props) => {
return (
<div>
<button type="button">Before layer</button>
<DismissableLayer asChild {...props}>
<input type="text" />
<button type="button">Inside layer</button>
</DismissableLayer>
<input type="text" data-testid="outside" />
<button type="button">After layer</button>
</div>
);
},
play: async ({ args }) => {
const canvas = within(document.body);
const outsideInput = canvas.getByTestId("outside");
outsideInput.focus();
play: async ({ args, canvasElement }) => {
const canvas = within(canvasElement);
const before = canvas.getByRole("button", { name: "Before layer" });
const inside = canvas.getByRole("button", { name: "Inside layer" });
const after = canvas.getByRole("button", { name: "After layer" });
expect(args.onFocusOutside).toHaveBeenCalledOnce();
inside.focus();
expect(inside).toHaveFocus();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(args.onFocusOutside).not.toHaveBeenCalled();
after.focus();
expect(after).toHaveFocus();
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledOnce());
expect(args.onDismiss).toHaveBeenCalledOnce();
// Focus that never entered the layer, e.g. Safari leaving focus on body after a trigger click.
after.blur();
expect(document.body).toHaveFocus();
before.focus();
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledTimes(2));
expect(args.onDismiss).toHaveBeenCalledTimes(2);
},
args: {
onDismiss: fn(),
@@ -158,7 +174,9 @@ export const InteractOutside: Story = {
outsideFocus.focus();
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
await waitFor(() =>
expect(args.onInteractOutside).toHaveBeenCalledTimes(1),
);
expect(args.onDismiss).toHaveBeenCalledTimes(2);
await userEvent.click(outsideElement);
@@ -206,8 +224,6 @@ export const SafeZone: Story = {
const [safeAnchor, setSafeAnchor] = React.useState<HTMLDivElement | null>(
null,
);
const [safeContainer, setSafeContainer] =
React.useState<HTMLDivElement | null>(null);
return (
<div>
@@ -223,38 +239,42 @@ export const SafeZone: Story = {
{...props}
safeZone={{
anchor: safeAnchor,
dismissable: safeContainer,
}}
>
<div data-testid="safe-container" ref={setSafeContainer}>
<button type="button">test</button>
</div>
<button type="button">Inside layer</button>
</DismissableLayer>
<button type="button">Outside layer</button>
</div>
);
},
play: async ({ args }) => {
const canvas = within(document.body);
const outsideAnchor = canvas.getByTestId("safe-anchor");
const outsideContainer = canvas.getByTestId("safe-container");
const inside = canvas.getByRole("button", { name: "Inside layer" });
const outside = canvas.getByRole("button", { name: "Outside layer" });
expect(args.onDismiss).not.toHaveBeenCalled();
expect(args.onInteractOutside).not.toHaveBeenCalled();
outsideAnchor.focus();
inside.focus();
outsideAnchor.focus();
expect(outsideAnchor).toHaveFocus();
await new Promise<void>((resolve) => setTimeout(resolve, 0));
expect(args.onDismiss).not.toHaveBeenCalled();
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
outsideContainer.focus();
expect(args.onDismiss).not.toHaveBeenCalled();
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
expect(args.onInteractOutside).not.toHaveBeenCalled();
await userEvent.click(outsideAnchor);
expect(args.onDismiss).not.toHaveBeenCalled();
expect(args.onInteractOutside).toHaveBeenCalledTimes(2);
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
await userEvent.click(outsideContainer);
await userEvent.click(inside);
expect(args.onDismiss).not.toHaveBeenCalled();
expect(args.onInteractOutside).toHaveBeenCalledTimes(1);
outsideAnchor.focus();
outside.focus();
await waitFor(() => expect(args.onDismiss).toHaveBeenCalledOnce());
expect(args.onInteractOutside).toHaveBeenCalledTimes(2);
},
args: {
@@ -586,7 +606,7 @@ export const PreventEvents: Story = {
expect(args.onDismiss).not.toHaveBeenCalled();
outsideFocus.focus();
await waitFor(() => expect(args.onFocusOutside).toHaveBeenCalledOnce());
expect(args.onDismiss).not.toHaveBeenCalled();
await userEvent.click(outsideElement);
@@ -596,7 +616,7 @@ export const PreventEvents: Story = {
args: {
onDismiss: fn(),
onInteractOutside: (event) => event.preventDefault(),
onFocusOutside: (event) => event.preventDefault(),
onFocusOutside: fn((event) => event.preventDefault()),
onEscapeKeyDown: (event) => event.preventDefault(),
onPointerDownOutside: (event) => event.preventDefault(),
},
@@ -6,7 +6,7 @@ import React, {
useState,
} from "react";
import { composeEventHandlers, ownerDocument } from "../../helpers";
import { useMergeRefs, useTimeout } from "../../hooks";
import { useMergeRefs } from "../../hooks";
import type { AsChildProps } from "../../types";
import { Slot } from "../slot/Slot";
import type {
@@ -49,7 +49,7 @@ interface DismissableLayerBaseProps extends React.HTMLAttributes<HTMLDivElement>
*/
enablePointerUpOutside?: boolean;
/**
* Event handler called when the focus moves outside of the `DismissableLayer`.
* Event handler called when focus moves outside the layer and its anchor.
* Can be prevented.
*/
onFocusOutside?: (event: CustomFocusEvent) => void;
@@ -118,8 +118,6 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
const context = useContext(DismissableLayerContext);
const triggerPointerDownRef = useRef<boolean>(false);
const dismissedWithPointerRef = useRef<boolean>(false);
const timeout = useTimeout();
const [, forceRerender] = useState({});
const [node, setNode] = React.useState<DismissableLayerElement | null>(
@@ -146,14 +144,11 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
* We want to prevent the Layer from closing when the trigger/anchor element or its child elements are interacted with.
* To achieve this, we check if the event target is the trigger/anchor or a child. If it is, we prevent default event behavior.
*/
function handleOutsideEvent(event: CustomFocusEvent | CustomPointerEvent) {
function handleOutsidePointerEvent(event: CustomPointerEvent) {
if (!safeZone?.anchor) {
return;
}
const eventType = event.detail.originalEvent.type as
"pointerup" | "pointerdown" | "focusin";
const target = event.target as HTMLElement;
const targetIsAnchor =
@@ -168,7 +163,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
* Therefore, checking anchor.contains(target) etc. won't work in that case.
*/
if (
eventType === "pointerdown" &&
event.detail.originalEvent.type === "pointerdown" &&
triggerPointerDownRef.current === true
) {
event.preventDefault();
@@ -177,23 +172,29 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
triggerPointerDownRef.current = false;
}
const focusOutside = useFocusOutside(
(event) => {
onFocusOutside?.(event);
onInteractOutside?.(event);
if (!event.defaultPrevented) {
onDismiss?.(event);
}
},
node,
safeZone?.anchor,
enabled,
);
const pointerDownOutside = usePointerDownOutside(
(event) => {
if (!shouldEnablePointerEvents) {
return;
}
dismissedWithPointerRef.current = true;
focusOutside.ignoreFocusOutAfterPointerDown();
/**
* We reset dismissedWithPointerRef on the next tick.
* This allows pointerDown to run its effect, without re-running them here right after.
*/
timeout.start(0, () => {
dismissedWithPointerRef.current = false;
});
/**
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault.
* We call these before checking the safe zone to give consumers a chance to prevent dismissal.
*/
onPointerDownOutside?.(event);
onInteractOutside?.(event);
@@ -201,7 +202,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
/**
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
*/
safeZone && handleOutsideEvent(event);
safeZone && handleOutsidePointerEvent(event);
if (!event.defaultPrevented && onDismiss) {
onDismiss(event);
@@ -218,7 +219,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
}
/**
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault based certain cases.
* We call these before checking the safe zone to give consumers a chance to prevent dismissal.
*/
onPointerUpOutside?.(event);
onInteractOutside?.(event);
@@ -226,10 +227,10 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
/**
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
*/
safeZone && handleOutsideEvent(event);
safeZone && handleOutsidePointerEvent(event);
/**
* Both `onPointerUpOutside`, `onInteractOutside` and `handleOutsideEvent`
* Both `onPointerUpOutside`, `onInteractOutside` and `handleOutsidePointerEvent`
* are able to preventDefault the event, thus stopping call for `onDismiss`.
*/
if (!event.defaultPrevented && onDismiss) {
@@ -240,30 +241,6 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
enabled,
);
const focusOutside = useFocusOutside(
(event) => {
if (dismissedWithPointerRef.current) {
return;
}
/**
* We call these before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault.
*/
onFocusOutside?.(event);
onInteractOutside?.(event);
/**
* Add safeZone to prevent closing when interacting with trigger/anchor or its children.
*/
safeZone && handleOutsideEvent(event);
if (!event.defaultPrevented && onDismiss) {
onDismiss(event);
}
},
ownerDoc,
enabled,
);
useEscapeKeydown(
(event) => {
/**
@@ -276,7 +253,7 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
}
/**
* We call this before letting `handleOutsideEvent` do its checks to give consumer a chance to preventDefault based certain cases.
* Give consumers a chance to prevent dismissal.
*/
onEscapeKeyDown?.(event);
/**
@@ -450,16 +427,12 @@ const DismissableLayer = forwardRef<HTMLDivElement, DismissableLayerProps>(
restProps.onFocusCapture,
focusOutside.onFocusCapture,
)}
onBlurCapture={composeEventHandlers(
restProps.onBlurCapture,
focusOutside.onBlurCapture,
)}
onPointerDownCapture={composeEventHandlers(
restProps.onPointerDownCapture,
() => {
pointerDownOutside.onPointerDownCapture();
pointerUpOutside.onPointerDownCapture();
focusOutside.onPointerDownCapture();
focusOutside.ignoreFocusOutAfterPointerDown();
},
)}
onPointerUpCapture={composeEventHandlers(
@@ -18,11 +18,11 @@ function dispatchCustomEvent<
detail: { originalEvent: OriginalEvent } & (E extends CustomEvent<infer D>
? D
: never),
target = detail.originalEvent.target,
) {
if (!handler) {
return;
}
const target = detail.originalEvent.target;
const event = new CustomEvent(name, {
bubbles: false,
cancelable: true,
@@ -1,4 +1,4 @@
import { useEffect, useRef } from "react";
import { type FocusEvent as ReactFocusEvent, useEffect, useRef } from "react";
import { useEventCallback, useTimeout } from "../../../hooks";
import {
CUSTOM_EVENTS,
@@ -7,69 +7,122 @@ import {
} from "./dispatchCustomEvent";
/**
* Tracks focus outside a React subtree. Returns props for the subtree root.
* Tracks focus moving outside the layer's React subtree (including portals) and anchor.
*/
export function useFocusOutside(
callback?: (event: CustomFocusEvent) => void,
ownerDocument: Document = globalThis?.document,
enabled: boolean = true,
function useFocusOutside(
callback: (event: CustomFocusEvent) => void,
node: Element | null,
anchor: Element | null | undefined,
enabled: boolean,
) {
const handleFocusOutside = useEventCallback(callback) as EventListener;
const isFocusInsideReactTreeRef = useRef(false);
const handleFocusOutside = useEventCallback(callback);
const insideFocusEventRef = useRef<Event | null>(null);
const skipFocusCheckRef = useRef(false);
const timeout = useTimeout();
const focusCheck = useTimeout();
const pointerTimeout = useTimeout();
useEffect(() => {
if (!enabled) {
if (!enabled || !node) {
return;
}
const handleFocus = (event: FocusEvent) => {
if (
event.target &&
!isFocusInsideReactTreeRef.current &&
!skipFocusCheckRef.current
) {
const eventDetail = { originalEvent: event };
// Focus moving between siblings in a shadow root may only reach that root.
const roots = new Set<Node>([node.ownerDocument]);
for (const element of [node, anchor]) {
const view = element?.ownerDocument.defaultView;
let root = element?.getRootNode();
while (root && !roots.has(root)) {
roots.add(root);
root =
view && root instanceof view.ShadowRoot
? root.host.getRootNode()
: undefined;
}
}
const handleFocusIn = (event: FocusEvent) => {
// Read now: the browser clears targets in shadow trees after dispatch.
const target = event.target;
if (!target || skipFocusCheckRef.current) {
return;
}
/**
* Defer the check so React's `onFocusCapture` has seen the event. When React
* is rendered into `document` (e.g. Next.js App Router), its capture listener
* may run before this one, so match on the event instead of clearing the timeout.
*/
focusCheck.start(0, () => {
const activeElement = getDeepActiveElement(node.ownerDocument);
if (
insideFocusEventRef.current === event ||
!node.isConnected ||
hasFocusWithin(node) ||
hasFocusWithin(anchor) ||
/* Focus fell back to body, e.g. the outside target was removed before the check */
!activeElement ||
activeElement === node.ownerDocument.body ||
/* Focus guards redirect focus and are not real destinations */
activeElement.hasAttribute("data-aksel-focus-guard")
) {
return;
}
/**
* The `DismisableLayer`-API is based on the ability to stop events from propagating and in the end calling `onDismiss`
* if `useFocusOutside`-callback runs `event.preventDefault()`.
*
* Because of the `focusin`-event not being cancelable,
* we need to use a custom event to ensure that the event is cancelable.
* https://developer.mozilla.org/en-US/docs/Web/API/Element/focusin_event
* > The focusin event is not cancelable.
*/
dispatchCustomEvent(
CUSTOM_EVENTS.FOCUS_OUTSIDE,
handleFocusOutside,
eventDetail,
{ originalEvent: event },
target,
);
});
};
for (const root of roots) {
root.addEventListener("focusin", handleFocusIn as EventListener, true);
}
return () => {
for (const root of roots) {
root.removeEventListener(
"focusin",
handleFocusIn as EventListener,
true,
);
}
focusCheck.clear();
};
ownerDocument.addEventListener("focusin", handleFocus);
return () => {
ownerDocument.removeEventListener("focusin", handleFocus);
};
}, [ownerDocument, handleFocusOutside, enabled]);
}, [anchor, enabled, focusCheck, handleFocusOutside, node]);
/**
* By directly setting isFocusInsideReactTreeRef on focus-events at the root of the "dismissable" element,
* we can eliminate the need for DOM traversal to verify if the focused element is within the react tree.
*/
return {
onFocusCapture: () => {
isFocusInsideReactTreeRef.current = true;
onFocusCapture: (event: ReactFocusEvent) => {
insideFocusEventRef.current = event.nativeEvent;
},
onBlurCapture: () => {
isFocusInsideReactTreeRef.current = false;
},
onPointerDownCapture: () => {
ignoreFocusOutAfterPointerDown: () => {
focusCheck.clear();
skipFocusCheckRef.current = true;
timeout.start(0, () => {
pointerTimeout.start(0, () => {
skipFocusCheckRef.current = false;
});
},
};
}
/**
* Uses the active element of the element's own root, so focus inside shadow DOM is not retargeted away.
*/
function hasFocusWithin(element: Element | null | undefined) {
if (!element?.isConnected) {
return false;
}
const root = element.getRootNode() as Document | ShadowRoot;
return element.contains(root.activeElement);
}
function getDeepActiveElement(ownerDocument: Document) {
let activeElement = ownerDocument.activeElement;
while (activeElement?.shadowRoot?.activeElement) {
activeElement = activeElement.shadowRoot.activeElement;
}
return activeElement;
}
export { useFocusOutside };
@@ -32,9 +32,7 @@ export function usePointerDownOutside(
* The `DismisableLayer`-API is based on the ability to stop events from propagating and in the end calling `onDismiss`
* if `usePointerDownOutside` runs `event.preventDefault()`.
*
* Altrough `pointerdown` is already a cancelable event,
* to to make sure the batching of events works corretly with `focusIn` in `useFocusOutside`,
* we still use a custom event like in `useFocusOutside`.
* Use the same cancelable event contract as the other outside interactions.
*/
function dispatchPointerEvent() {
dispatchCustomEvent(