Compare commits

..
Author SHA1 Message Date
KenandCopilot ea94696a42 Storybook tests: run WebKit test files serially (#5571)
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 12:23:42 +01:00
KenandCopilot d1bb8ec012 Remove temporary Dialog diagnostics and ineffective DismissableLayer wait
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 10:35:50 +01:00
KenandCopilot 5ea403d1a1 Stabilize WebKit play tests; add temporary Dialog focus diagnostics
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 10:27:08 +01:00
KenandCopilot 2d93fa28ef Dialog: account for WebKit not focusing buttons on click in focus-trap test
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 10:18:11 +01:00
KenandCopilot b06b3a46f6 Fix cross-browser play test failures
- Data ResizeAuto: allow ±5% on measured column widths (text metrics differ per engine)
- DismissableLayer NestedPointerEvents: await waitFor before clicking outside

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-21 10:07:26 +01:00
KenandCopilot a4e97439ee Storybook tests: run in Chromium, Firefox and WebKit
CI runs one job per browser. Copilot CLI runs only Chromium, since
Firefox and WebKit can't launch inside the cplt sandbox on macOS.
Fix two Chromium-flaky play tests that raced the deferred initial focus.

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-20 22:23:46 +01:00
Ken 7dbf1d5382 fix(DataGrid): Focus is no longer locked inside table when using useTableKeyboardNav 2026-11-20 21:50:40 +01:00
14 changed files with 74 additions and 585 deletions

No files matched your search

+5
View File
@@ -0,0 +1,5 @@
---
"@navikt/ds-react": patch
---
DataGrid: Keyboard navigation in table no longer prevents shift+tabbing away from the table
+2 -2
View File
@@ -48,8 +48,8 @@
- `corepack yarn tsc --noEmit --incremental false --project <tsconfig>` - targeted type-check
- `corepack yarn workspace <name> <script>` - e.g. `@navikt/ds-react test` (Vitest + tsc), `website test`
- `corepack yarn lint` / `corepack yarn test` / `corepack yarn boot` - root suites (slow; cross-workspace changes only)
- `corepack yarn storybook` (:6006) / `corepack yarn storybook:aksel` (website examples, :6007, no secrets) / `corepack yarn storybook:test` (play tests, Playwright Firefox; Chromium when `COPILOT_CLI` is set) / `corepack yarn dev` (website, :3000, needs Sanity token)
- Targeted play tests: `corepack yarn storybook:test <path/to/X.tests.stories.tsx>` (repo root). Run after changing play tests. Under Copilot CLI this runs Chromium; if the browser can't launch, report tests as not run with the exact command.
- `corepack yarn storybook` (:6006) / `corepack yarn storybook:aksel` (website examples, :6007, no secrets) / `corepack yarn storybook:test` (play tests in Playwright Chromium, Firefox and WebKit; only Chromium when `COPILOT_CLI` is set; filter with `--browser.name=<browser>`) / `corepack yarn dev` (website, :3000, needs Sanity token)
- Targeted play tests: `corepack yarn storybook:test <path/to/X.tests.stories.tsx>` (repo root). Run after changing play tests. Under Copilot CLI this runs only Chromium (Firefox/WebKit can't launch in the cplt sandbox; CI covers them); if the browser can't launch, report tests as not run with the exact command.
## Where to edit
+1 -1
View File
@@ -17,4 +17,4 @@ applyTo: "**/*.test.ts,**/*.test.tsx,**/*.stories.tsx"
- Before removing or consolidating tests, map each meaningful old scenario/assertion to its replacement story or test. Keep coverage that still represents a supported behavior; explain when a scenario is intentionally obsolete.
- For state, accessibility, keyboard or focus behavior, use the [component-contract skill](../skills/component-contract/SKILL.md) to identify the contract and evidence to preserve.
- ds-react unit tests run with `TZ=UTC`. Date logic must not depend on the local timezone.
- Browser tests need Playwright Firefox (Chromium under Copilot CLI, see `vitest.config.mts`). Yarn has `enableScripts: false`, so if the browser is missing, report it instead of installing globally.
- Browser tests run in Playwright Chromium, Firefox and WebKit (one CI job each). Under Copilot CLI only Chromium runs, since Firefox/WebKit can't launch in the cplt sandbox (see `vitest.config.mts`). Run one browser with `--browser.name=<browser>`. Yarn has `enableScripts: false`, so if the browser is missing, report it instead of installing globally.
+6 -2
View File
@@ -71,11 +71,15 @@ jobs:
run: yarn test
ui:
name: UI tests (Storybook)
name: UI tests (Storybook, ${{ matrix.browser }})
runs-on: ubuntu-latest
timeout-minutes: 10
container:
image: mcr.microsoft.com/playwright:v1.61.1-noble
strategy:
fail-fast: false
matrix:
browser: [chromium, firefox, webkit]
steps:
- name: Checkout code
uses: actions/checkout@v7
@@ -89,6 +93,6 @@ jobs:
npm_auth_token: ${{ secrets.READER_TOKEN }}
- name: Test UI
run: yarn storybook:test --max-workers=2
run: yarn storybook:test --max-workers=2 --browser.name=${{ matrix.browser }}
env:
HOME: /root
@@ -1,200 +0,0 @@
import type { Meta, StoryObj } from "@storybook/react-vite";
import React, { useMemo, useState } from "react";
import { DataGrid } from "..";
import { Pagination } from "../../pagination";
import { HStack, VStack } from "../../primitives/stack";
import { Detail } from "../../typography";
import {
type DataGridPlugin,
type DataGridPlugins,
applyTableContext,
useDataGridPlugins,
} from "./useDataGridPlugins";
type InvoiceRow = {
id: string;
invoiceNumber: string;
category: string;
status: string;
amount: string;
};
const DEMO_ROWS: InvoiceRow[] = [
{
id: "1",
invoiceNumber: "INV-2026-001",
category: "Cloud Hosting",
status: "Paid",
amount: "12 400 kr",
},
{
id: "2",
invoiceNumber: "INV-2026-002",
category: "Software License",
status: "Pending",
amount: "4 850 kr",
},
{
id: "3",
invoiceNumber: "INV-2026-003",
category: "Office Supplies",
status: "Paid",
amount: "1 290 kr",
},
{
id: "4",
invoiceNumber: "INV-2026-004",
category: "Security Audit",
status: "Overdue",
amount: "28 000 kr",
},
{
id: "5",
invoiceNumber: "INV-2026-005",
category: "Hardware",
status: "Paid",
amount: "19 990 kr",
},
{
id: "6",
invoiceNumber: "INV-2026-006",
category: "Training",
status: "Pending",
amount: "7 500 kr",
},
{
id: "7",
invoiceNumber: "INV-2026-007",
category: "Domain Renewal",
status: "Paid",
amount: "640 kr",
},
{
id: "8",
invoiceNumber: "INV-2026-008",
category: "Monitoring",
status: "Pending",
amount: "3 200 kr",
},
];
const DEMO_COLUMNS: DataGrid.Columns<InvoiceRow> = [
{
id: "invoiceNumber",
header: "Invoice",
isRowHeader: true,
bodyCell: (row) => row.invoiceNumber,
},
{ id: "category", header: "Category", bodyCell: (row) => row.category },
{ id: "status", header: "Status", bodyCell: (row) => row.status },
{ id: "amount", header: "Amount", bodyCell: (row) => row.amount },
];
/**
* Preview of how `DataGrid` will integrate the plugin API.
* Only two lines are added around `DataGrid`'s children:
* 1. `useDataGridPlugins(userPlugins)` to order and stabilize plugins
* 2. `applyTableContext(plugins, children)` to wrap the grid output
*/
function PluginAwareDataGrid<RowT>({
plugins: userPlugins,
children,
...dataGridProps
}: DataGrid.Props<RowT> & { plugins?: DataGridPlugins }) {
const plugins = useDataGridPlugins(userPlugins);
return (
<DataGrid {...dataGridProps}>
{applyTableContext(plugins, children)}
</DataGrid>
);
}
/**
* Example first-party plugin hook.
* The consumer owns pagination state; the hook returns a memoized `DataGridPlugin`
* that wraps the table with Aksel's `<Pagination />`.
*/
function useDummyPaginationPlugin({
page,
pageSize,
totalItems,
onPageChange,
}: {
page: number;
pageSize: number;
totalItems: number;
onPageChange: (nextPage: number) => void;
}): DataGridPlugin {
return useMemo(() => {
const pageCount = Math.max(1, Math.ceil(totalItems / pageSize));
const start = (page - 1) * pageSize + 1;
const end = Math.min(page * pageSize, totalItems);
return {
transformTableContext: (children) => (
<VStack gap="space-12" data-plugin="pagination">
{children}
<HStack align="center" justify="space-between" gap="space-16" wrap>
<Detail>
Showing {start}–{end} of {totalItems}
</Detail>
<Pagination
page={page}
count={pageCount}
onPageChange={onPageChange}
size="small"
/>
</HStack>
</VStack>
),
};
}, [page, pageSize, totalItems, onPageChange]);
}
const meta: Meta = {
title: "ds-react/DataGrid/Plugins",
parameters: {
chromatic: { disable: true },
layout: "padded",
},
};
export default meta;
type Story = StoryObj;
/**
* Shows the intended consumer API for a first-party plugin hook:
* state stays in consumer code, the hook returns a memoized `DataGridPlugin`,
* and `DataGrid` renders it through `plugins={{ pagination }}`.
*/
export const PaginationPlugin: Story = {
render: function PaginationPluginDemo() {
const [page, setPage] = useState(1);
const pageSize = 3;
const paginationPlugin = useDummyPaginationPlugin({
page,
pageSize,
totalItems: DEMO_ROWS.length,
onPageChange: setPage,
});
const pageRows = useMemo(
() => DEMO_ROWS.slice((page - 1) * pageSize, page * pageSize),
[page],
);
return (
<PluginAwareDataGrid
columns={DEMO_COLUMNS}
data={pageRows}
getRowId={(row) => row.id}
plugins={{ pagination: paginationPlugin }}
>
<DataGrid.Table />
</PluginAwareDataGrid>
);
},
};
@@ -1,160 +0,0 @@
import { renderHook } from "@testing-library/react";
import { afterEach, describe, expect, test, vi } from "vitest";
import * as consoleWarningModule from "../../utils/helpers/consoleWarning";
import {
type DataGridPlugin,
type DataGridPlugins,
applyTableContext,
useDataGridPlugins,
} from "./useDataGridPlugins";
const createContextPlugin = (label: string): DataGridPlugin => ({
transformTableContext: (children) => `${label}(${children})`,
});
describe("useDataGridPlugins", () => {
test("returns a stable empty array when plugins are undefined or empty", () => {
const { result, rerender } = renderHook<
readonly DataGridPlugin[],
{ plugins?: DataGridPlugins }
>(({ plugins }) => useDataGridPlugins(plugins), {
initialProps: { plugins: undefined },
});
const initialResult = result.current;
expect(initialResult).toEqual([]);
rerender({ plugins: {} });
expect(result.current).toBe(initialResult);
});
test("orders known plugins before unknown plugins, ignores prototype keys, and skips non-object entries", () => {
const customFirst = createContextPlugin("first");
const customSecond = createContextPlugin("second");
const pagination = createContextPlugin("pagination");
const { result } = renderHook(() =>
useDataGridPlugins({
zCustom: customFirst,
aCustom: customSecond,
pagination,
}),
);
expect(result.current).toEqual([pagination, customFirst, customSecond]);
const inherited = Object.create({ pagination }) as DataGridPlugins;
inherited.custom = customFirst;
const { result: inheritedResult } = renderHook(() =>
useDataGridPlugins(inherited),
);
expect(inheritedResult.current).toEqual([customFirst]);
// Runtime guard: nullish or primitive entries on known or custom keys are skipped instead of crashing WeakMap
const { result: invalidEntriesResult } = renderHook(() =>
useDataGridPlugins({
pagination: undefined,
customUndefined: undefined,
customNull: null,
customPrimitive: "not-an-object",
valid: customFirst,
} as unknown as DataGridPlugins),
);
expect(invalidEntriesResult.current).toEqual([customFirst]);
});
test("interns array reference by plugin identity and order across inline objects", () => {
const pagination = createContextPlugin("pagination");
const customA = createContextPlugin("a");
const customB = createContextPlugin("b");
const { result, rerender } = renderHook<
readonly DataGridPlugin[],
{ plugins?: DataGridPlugins }
>(({ plugins }) => useDataGridPlugins(plugins), {
initialProps: { plugins: { customA, pagination } },
});
const first = result.current;
expect(Object.isFrozen(first)).toBe(true);
// New inline object with same plugin instances (even in different key order)
rerender({ plugins: { pagination, customA } });
expect(result.current).toBe(first);
// Removing a plugin returns a new array; restoring it returns the interned array
rerender({ plugins: { pagination } });
expect(result.current).not.toBe(first);
expect(result.current).toEqual([pagination]);
rerender({ plugins: { pagination, customA } });
expect(result.current).toBe(first);
// Changing plugin order or replacing an instance produces a new array
rerender({ plugins: { customA, customB } });
const ab = result.current;
rerender({ plugins: { customB, customA } });
expect(result.current).not.toBe(ab);
expect(result.current).toEqual([customB, customA]);
});
});
describe("applyTableContext", () => {
afterEach(() => {
vi.restoreAllMocks();
});
test("wraps children in reverse plugin order and skips plugins without a valid transform", () => {
const pagination = createContextPlugin("pagination");
const custom = createContextPlugin("custom");
const noopPlugin = {} as DataGridPlugin;
const invalidPlugin = {
transformTableContext: "not-a-function",
} as unknown as DataGridPlugin;
expect(applyTableContext([], "table")).toBe("table");
expect(
applyTableContext(
[pagination, noopPlugin, invalidPlugin, custom],
"table",
),
).toBe("pagination(custom(table))");
});
test("preserves previous content and warns when transformTableContext returns undefined", () => {
const warnSpy = vi
.spyOn(consoleWarningModule, "consoleWarning")
.mockImplementation(() => {});
const outer = createContextPlugin("outer");
const returnsUndefined: DataGridPlugin = {
transformTableContext: () => undefined,
};
const inner = createContextPlugin("inner");
expect(applyTableContext([outer, returnsUndefined, inner], "table")).toBe(
"outer(inner(table))",
);
expect(warnSpy).toHaveBeenCalledWith(
expect.stringContaining("transformTableContext returned undefined"),
);
});
test("catches plugin errors, logs them, and continues applying remaining plugins", () => {
const errorSpy = vi.spyOn(console, "error").mockImplementation(() => {});
const boom = new Error("plugin failure");
const outer = createContextPlugin("outer");
const broken: DataGridPlugin = {
transformTableContext: () => {
throw boom;
},
};
const inner = createContextPlugin("inner");
expect(applyTableContext([outer, broken, inner], "table")).toBe(
"outer(inner(table))",
);
expect(errorSpy).toHaveBeenCalledWith(
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
boom,
);
});
});
@@ -1,201 +0,0 @@
import type { ReactNode } from "react";
import { consoleWarning } from "../../utils/helpers/consoleWarning";
/**
* Plugin that extends DataGrid rendering (e.g. wrapping the table in providers
* or extra UI). Remember to memoize the plugin object (with `useMemo`) so
* DataGrid can skip unnecessary re-renders.
*/
interface DataGridPlugin {
/**
* Wraps the table output in context providers or surrounding UI (e.g. pagination).
* Runs as a plain function during render. Do not call React hooks directly
* inside this function; render a component or provider that calls hooks instead.
*/
transformTableContext: (children: ReactNode) => ReactNode;
}
/**
* Fixed order for built-in plugins so behavior doesn't depend on key order
* in `plugins={{ ... }}`. Custom plugins are placed after these, in their
* original order.
*/
const PLUGIN_ORDER = ["pagination"] as const;
const KNOWN_PLUGINS = new Set<string>(PLUGIN_ORDER);
type BuiltInDataGridPluginKey = (typeof PLUGIN_ORDER)[number];
/**
* Named plugins passed to DataGrid.
*
* Keep plugins always present rather than toggling entries conditionally:
* adding or removing a plugin that wraps children changes React's tree depth and remounts the grid.
* Control active/visible state inside the plugin instead.
*/
type DataGridPlugins = Partial<
Record<BuiltInDataGridPluginKey, DataGridPlugin>
> &
Record<string, DataGridPlugin>;
/**
* We freeze in dev-mode to enforce immutability of the empty plugin array.
* Based on React best practices: https://react.dev/reference/react/createElement#caveats
*/
const EMPTY_PLUGINS: readonly never[] =
process.env.NODE_ENV !== "production" ? Object.freeze([]) : [];
/**
* Turns a `plugins={{ ... }}` object into an ordered, stable plugin array.
*
* - Orders built-in plugins consistently (`orderPlugins`).
* - Keeps the same array reference even when the consumer passes an inline
* `plugins={{ pagination }}` object on every render (`internByIdentity`).
*/
function useDataGridPlugins(
userPlugins?: DataGridPlugins,
): readonly DataGridPlugin[] {
return internByIdentity(orderPlugins(userPlugins));
}
// WeakMap keys must be objects; guard against nullish/primitive entries at runtime.
function isPluginObject(value: unknown): value is DataGridPlugin {
return typeof value === "object" && value !== null;
}
/**
* Places known plugins first (in `PLUGIN_ORDER`), then unknown plugins in
* insertion order.
*/
function orderPlugins(
userPlugins?: DataGridPlugins,
): readonly DataGridPlugin[] {
if (!userPlugins) {
return EMPTY_PLUGINS;
}
const keys = Object.keys(userPlugins);
if (keys.length === 0) {
return EMPTY_PLUGINS;
}
const ordered: DataGridPlugin[] = [];
for (const name of PLUGIN_ORDER) {
/* TS target does not support Object.hasOwn */
if (Object.prototype.hasOwnProperty.call(userPlugins, name)) {
const plugin = userPlugins[name];
if (isPluginObject(plugin)) {
ordered.push(plugin);
}
}
}
for (const name of keys) {
if (!KNOWN_PLUGINS.has(name)) {
const plugin = userPlugins[name];
if (isPluginObject(plugin)) {
ordered.push(plugin);
}
}
}
return ordered;
}
interface InternNode {
readonly next: WeakMap<object, InternNode>;
array?: readonly object[];
}
/**
* Tree of WeakMaps where each path represents a sequence of plugin objects.
* WeakMap lets unused paths be garbage-collected when plugins go away.
*/
const internRoot: InternNode = { next: new WeakMap() };
/**
* Returns the same array instance whenever given the same objects in the same order
* using a WeakMap trie (prefix tree keyed by object identity).
*
* Solves inline `plugins={{ pagination }}` props: `useMemo` on the outer object
* would miss every render, and mutating a `useRef` during render is unsafe in
* StrictMode / concurrent React.
*
* Each item walks one step down `internRoot`:
* ```text
* internRoot
* └─ [pluginA] ──▶ nodeA (array: [pluginA])
* └─ [pluginB] ──▶ nodeAB (array: [pluginA, pluginB])
* └─ [pluginB] ──▶ nodeB
* └─ [pluginA] ──▶ nodeBA (array: [pluginB, pluginA])
* ```
*
* 1. Walk `internRoot` using each item as a `WeakMap` key, creating nodes as needed.
* 2. Cache a copy at the terminal node so future calls with the same sequence return the exact same (`===`) array.
* 3. Unused branches are garbage-collected automatically once any plugin object in the path is no longer referenced.
*/
function internByIdentity<T extends object>(items: readonly T[]): readonly T[] {
if (items.length === 0) {
return EMPTY_PLUGINS;
}
let node = internRoot;
for (const item of items) {
let child = node.next.get(item);
if (child === undefined) {
child = { next: new WeakMap() };
node.next.set(item, child);
}
node = child;
}
if (node.array === undefined) {
const copy = items.slice();
/* Freeze in dev so accidental mutation fails fast instead of corrupting the shared cache. */
node.array =
process.env.NODE_ENV !== "production" ? Object.freeze(copy) : copy;
}
return node.array as readonly T[];
}
/**
* Wraps `children` with each plugin's `transformTableContext`.
* Runs in reverse so the first plugin wraps outermost.
* Synchronous errors are caught and logged, and an `undefined` return preserves
* the previous content so one broken plugin doesn't blank or crash the grid.
*/
function applyTableContext(
plugins: readonly DataGridPlugin[],
children: ReactNode,
): ReactNode {
let content = children;
for (let i = plugins.length - 1; i >= 0; i--) {
const transform = plugins[i].transformTableContext;
if (typeof transform !== "function") {
continue;
}
try {
const next = transform(content);
if (next === undefined) {
consoleWarning(
"DataGrid: Plugin transformTableContext returned undefined. Preserving previous content.",
);
continue;
}
content = next;
} catch (error) {
console.error(
"[Aksel] DataGrid: Plugin threw in transformTableContext:",
error,
);
}
}
return content;
}
export { applyTableContext, useDataGridPlugins };
export type { DataGridPlugin, DataGridPlugins };
@@ -280,12 +280,19 @@ export const ResizeAuto: Story = {
const headers = canvas.getAllByRole("columnheader");
expect(headers.length).toBe(7);
expect(headers[0]).toHaveStyle({ width: "126px" });
expect(headers[1]).toHaveStyle({ width: "80px" });
expect(headers[2]).toHaveStyle({ width: "82px" });
expect(headers[3]).toHaveStyle({ width: "103px" });
expect(headers[4]).toHaveStyle({ width: "168px" });
expect(headers[5]).toHaveStyle({ width: "248px" });
expect(headers[6]).toHaveStyle({ width: "168px" });
expectWidthNear(headers[0], 126);
expectWidthNear(headers[1], 80);
expectWidthNear(headers[2], 82);
expectWidthNear(headers[3], 103);
expectWidthNear(headers[4], 168);
expectWidthNear(headers[5], 248);
expectWidthNear(headers[6], 168);
},
};
/* Auto-resized widths are measured from rendered text, which differs slightly between browser engines */
function expectWidthNear(element: HTMLElement, expected: number) {
const width = parseFloat(getComputedStyle(element).width);
expect(width).toBeGreaterThanOrEqual(expected * 0.95);
expect(width).toBeLessThanOrEqual(expected * 1.05);
}
@@ -22,6 +22,7 @@ type UseTableKeyboardNavOptions = {
function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
const [tableRef, setTableRef] = useState<HTMLTableElement | null>(null);
const [isFocusWithin, setIsFocusWithin] = useState(false);
const { getTableGrid, activeCell, setActiveCell } = useGridCache(
tableRef,
enabled,
@@ -122,6 +123,7 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
* Make sure td/th elements have tabIndex={-1} so they can receive focus on click
*/
const handleTableFocusIn = useEventCallback((event: FocusEvent): void => {
setIsFocusWithin(true);
const target = event.target as Element | null;
if (tableRef && target === tableRef) {
@@ -146,6 +148,15 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
}
});
const handleTableFocusOut = useEventCallback((event: FocusEvent): void => {
if (
!(event.relatedTarget instanceof Node) ||
!tableRef?.contains(event.relatedTarget)
) {
setIsFocusWithin(false);
}
});
/**
* Attach event listeners for keyboard navigation and focus management.
*/
@@ -156,16 +167,27 @@ function useTableKeyboardNav({ enabled }: UseTableKeyboardNavOptions) {
tableRef.addEventListener("keydown", handleTableKeyDown);
tableRef.addEventListener("focusin", handleTableFocusIn);
tableRef.addEventListener("focusout", handleTableFocusOut);
return () => {
tableRef.removeEventListener("keydown", handleTableKeyDown);
tableRef.removeEventListener("focusin", handleTableFocusIn);
tableRef.removeEventListener("focusout", handleTableFocusOut);
};
}, [tableRef, handleTableKeyDown, handleTableFocusIn, enabled]);
}, [
tableRef,
handleTableKeyDown,
handleTableFocusIn,
handleTableFocusOut,
enabled,
]);
return {
/* Table should only have tabIndex until the focus is moved inside and is enabled */
tabIndex: enabled ? 0 : undefined,
/*
* Table should only have tabIndex until the focus is moved inside and is enabled
* This allows focus to "escape" the table and move to other elements on the page.
*/
tabIndex: enabled ? (isFocusWithin ? -1 : 0) : undefined,
setTableRef,
};
}
@@ -701,6 +701,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();
@@ -135,7 +135,7 @@ export const OpenDelay: Story = {
{ timeout: 250 },
);
await waitFor(() => expect(canvas.getByRole("tooltip")).toBeVisible(), {
timeout: 500,
timeout: 1000,
});
},
};
@@ -320,14 +320,14 @@ export const NestedPointerEvents: StoryObj<{
await fireEvent.pointerDown(outside);
waitFor(() => {
await waitFor(() => {
expect(args.root.onDismiss).not.toHaveBeenCalled();
expect(args.nested.onDismiss).toHaveBeenCalledTimes(1);
});
await userEvent.click(outside);
waitFor(() => {
await waitFor(() => {
expect(args.root.onDismiss).toHaveBeenCalledTimes(1);
expect(args.nested.onDismiss).toHaveBeenCalledTimes(1);
});
@@ -44,8 +44,7 @@ export const Loop: Story = {
const middle = canvas.getByLabelText(Field_TWO);
const last = canvas.getByText(BUTTON_THREE);
/* Regular focus */
first.focus();
/* Mount focus lands on the first field in the next frame. Wait so it can't steal focus mid-test */
await waitFor(() => expect(first).toHaveFocus());
await userEvent.tab();
+16 -4
View File
@@ -2,6 +2,14 @@ import { storybookTest } from "@storybook/addon-vitest/vitest-plugin";
import { playwright } from "@vitest/browser-playwright";
import { defineConfig } from "vitest/config";
/*
* Firefox and WebKit can't launch inside the cplt sandbox used by Copilot CLI on macOS,
* so agents only run Chromium. CI runs all three. Filter with `--browser.name=<browser>`.
*/
const browsers = process.env.COPILOT_CLI
? (["chromium"] as const)
: (["chromium", "firefox", "webkit"] as const);
// More info at: https://storybook.js.org/docs/next/writing-tests/integrations/vitest-addon
export default defineConfig({
test: {
@@ -23,10 +31,14 @@ export default defineConfig({
enabled: true,
headless: true,
provider: playwright(),
/* Firefox can't start inside the cplt sandbox used by Copilot CLI */
instances: [
{ browser: process.env.COPILOT_CLI ? "chromium" : "firefox" },
],
instances: browsers.map((browser) => ({
browser,
/*
* Parallel WebKit pages interfere with each other's focus, so focus
* assertions (e.g. Dialog mount focus) fail at random. Run WebKit files serially.
*/
fileParallelism: browser !== "webkit",
})),
},
},
},