Skip to content
Open
Show file tree
Hide file tree
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
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,8 @@ You can also check the
reloads, and announce search results
- Editor filters, legend filters and drag handles keep focus, and filter
switches and drag handles have specific names
- Table charts work with screen readers and the keyboard: columns sort by
keyboard, groups expand by keyboard, and search results are announced

## 6.5.7 - 2026-11-10

Expand Down
112 changes: 112 additions & 0 deletions app/browse/ui/data-table-preview.spec.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
import { ThemeProvider } from "@mui/material";
import {
cleanup,
fireEvent,
render,
screen,
within,
} from "@testing-library/react";
import { ReactNode } from "react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { DataTablePreview } from "@/browse/ui/data-table-preview";
import { NominalDimension, Observation } from "@/domain/data";
import { stringifyComponentId } from "@/graphql/make-component-id";
import { expectNoAxeViolations } from "@/test/axe";
import { theme } from "@/themes/theme";

vi.mock("@lingui/macro", () => ({
Trans: ({ children }: { children: ReactNode }) => children,
t: ({ message }: { message: string }) => message,
defineMessage: ({ message }: { message: string }) => message,
}));

vi.mock("@/locales/use-locale", () => ({
useLocale: () => "en",
}));

const CUBE_IRI = "https://example.org/cube";

const canton: NominalDimension = {
__typename: "NominalDimension",
cubeIri: CUBE_IRI,
id: stringifyComponentId({
unversionedCubeIri: CUBE_IRI,
unversionedComponentIri: `${CUBE_IRI}/canton`,
}),
label: "Canton",
isNumerical: false,
isKeyDimension: true,
values: [
{ value: "zh", label: "Zurich", position: 0 },
{ value: "be", label: "Bern", position: 1 },
{ value: "ag", label: "Aargau", position: 2 },
],
relatedLimitValues: [],
};

const observations: Observation[] = [
{ [canton.id]: "Bern" },
{ [canton.id]: "Aargau" },
{ [canton.id]: "Zurich" },
];

describe("DataTablePreview", () => {
afterEach(cleanup);

it("is named by its caption and has a sort button beside the column label", async () => {
const { container } = renderPreview();

const table = screen.getByRole("table", { name: "Cantons" });
const header = within(table).getByRole("columnheader");
const sortButton = within(header).getByRole("button", {
name: "Sort by Canton",
});

expect(sortButton.tagName).toBe("BUTTON");
expect(header.getAttribute("aria-label")).toBe("Canton");
expect(header.getAttribute("aria-sort")).toBeNull();
await expectNoAxeViolations(container);
});

it("sorts with the sort button and reports the direction with aria-sort", () => {
renderPreview();
const header = screen.getByRole("columnheader");
const sortButton = screen.getByRole("button", { name: "Sort by Canton" });

fireEvent.click(sortButton);
expect(header.getAttribute("aria-sort")).toBe("ascending");
expect(getCellTexts()).toEqual(["Zurich", "Bern", "Aargau"]);

fireEvent.click(sortButton);
expect(header.getAttribute("aria-sort")).toBe("descending");
expect(getCellTexts()).toEqual(["Aargau", "Bern", "Zurich"]);
});

it("still sorts when the header cell itself is clicked", () => {
renderPreview();
const header = screen.getByRole("columnheader");

fireEvent.click(header);

expect(header.getAttribute("aria-sort")).toBe("ascending");
});
});

const renderPreview = () => {
return render(
<ThemeProvider theme={theme}>
<DataTablePreview
title="Cantons"
dimensions={[canton]}
measures={[]}
observations={observations}
linkToMetadataPanel={false}
/>
</ThemeProvider>
);
};

const getCellTexts = () => {
return screen.getAllByRole("cell").map((cell) => cell.textContent);
};
54 changes: 42 additions & 12 deletions app/browse/ui/data-table-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { t } from "@lingui/macro";
import {
Box,
Table,
TableBody,
TableCell,
Expand All @@ -9,8 +11,10 @@ import {
import { ascending, descending } from "d3-array";
import { useCallback, useMemo, useRef, useState } from "react";

import { getLabelWithUnit } from "@/charts/shared/chart-helpers";
import { ComponentLabel } from "@/components/chart-data-table-preview/ui/component-label";
import { Loading } from "@/components/hint";
import { VisuallyHidden } from "@/components/visually-hidden";
import {
Component,
Dimension,
Expand Down Expand Up @@ -84,37 +88,63 @@ export const DataTablePreview = ({
return (
<div ref={tooltipContainerRef} style={{ width: "100%" }}>
<Table>
<caption style={{ display: "none" }}>{title}</caption>
<VisuallyHidden component="caption">{title}</VisuallyHidden>
<TableHead sx={{ position: "sticky", top: 0 }}>
<TableRow>
{sortedComponents.map((component) => {
const isSorted = sortBy?.id === component.id;
const headerText = getLabelWithUnit(component);

return (
<TableCell
key={component.id}
component="th"
role="columnheader"
aria-label={headerText}
aria-sort={
isSorted
? sortDirection === "asc"
? "ascending"
: "descending"
: undefined
}
onClick={() => handleSort(component)}
sx={{
textAlign: isNumericalMeasure(component) ? "right" : "left",
whiteSpace: "nowrap",
cursor: "pointer",
}}
>
<TableSortLabel
active={!sortBy || sortBy.id === component.id}
direction={!sortBy ? "desc" : sortDirection}
IconComponent={SvgIcChevronDown}
sx={{
"&:hover > svg": {
...(!sortBy ? { transform: "translateY(-15%)" } : {}),
},
}}
>
<Box sx={{ display: "inline-flex", alignItems: "center" }}>
<ComponentLabel
component={component}
tooltipProps={tooltipProps}
linkToMetadataPanel={linkToMetadataPanel}
/>
</TableSortLabel>
<TableSortLabel
component="button"
type="button"
active={!sortBy || isSorted}
direction={!sortBy ? "desc" : sortDirection}
IconComponent={SvgIcChevronDown}
aria-label={t({
id: "table.sort.by",
message: `Sort by ${headerText}`,
})}
onClick={(e) => {
e.stopPropagation();
handleSort(component);
}}
sx={{
margin: "0 0 0 2px",
padding: "4px",
"& .MuiTableSortLabel-icon": { margin: 0 },
"&:hover > svg": {
...(!sortBy ? { transform: "translateY(-15%)" } : {}),
},
}}
/>
</Box>
</TableCell>
);
})}
Expand Down
49 changes: 47 additions & 2 deletions app/charts/chart-data-wrapper.spec.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
import { render } from "@testing-library/react";
import { describe, expect, it, vi } from "vitest";
import { cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";

import { ChartDataWrapper } from "@/charts/chart-data-wrapper";
import { LoadingStateProvider } from "@/charts/shared/chart-loading-state";
import { ChartConfig } from "@/config-types";
import { useDataCubesObservationsQuery } from "@/graphql/hooks";

vi.mock("@/locales/use-locale", () => ({
useLocale: () => "en",
}));

vi.mock("@/graphql/hooks", () => ({
useDataCubesComponentsQuery: vi.fn().mockReturnValue([
Expand Down Expand Up @@ -75,4 +80,44 @@ describe("ChartDataWrapper", () => {
root.getByText("Loading overlay").innerHTML.includes("Loading overlay")
).toBeTruthy();
});

describe("the visually hidden data table for screen readers", () => {
const Chart = () => <div>My chart</div>;

const renderWithObservations = (chartType: ChartConfig["chartType"]) => {
vi.mocked(useDataCubesObservationsQuery).mockReturnValue([
{
data: { dataCubesObservations: { data: [{ x: "a" }] } },
error: undefined,
fetching: false,
},
] as unknown as ReturnType<typeof useDataCubesObservationsQuery>);

return render(
<LoadingStateProvider>
<ChartDataWrapper
chartConfig={{ cubes: [], chartType } as unknown as ChartConfig}
LoadingOverlayComponent={() => null}
Component={Chart}
dataSource={{ type: "sparql", url: "url" }}
observationQueryFilters={[]}
/>
</LoadingStateProvider>
);
};

afterEach(cleanup);

it("is rendered for charts drawn as graphics", () => {
const { container } = renderWithObservations("column");

expect(container.querySelector("table")).not.toBeNull();
});

it("is not rendered for table charts, which are accessible themselves", () => {
const { container } = renderWithObservations("table");

expect(container.querySelector("table")).toBeNull();
});
});
});
4 changes: 2 additions & 2 deletions app/charts/chart-data-wrapper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ import {
LoadingOverlay,
NoDataHint,
} from "@/components/hint";
import { ChartConfig, DataSource } from "@/configurator";
import { ChartConfig, DataSource, isTableConfig } from "@/configurator";
import {
useDataCubesComponentsQuery,
useDataCubesMetadataQuery,
Expand Down Expand Up @@ -178,7 +178,7 @@ const ChartDataWrapperInner = <
className={classes.dataWrapper}
data-chart-loaded={!chartLoadingState.loading}
>
{observations.length > 0 && (
{observations.length > 0 && !isTableConfig(chartConfig) && (
<A11yTable
title={title}
observations={observations}
Expand Down
18 changes: 15 additions & 3 deletions app/charts/shared/containers.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,15 @@ export const useStyles = makeStyles<{}, {}, "chartContainer">(() => ({
},
}));

export const ChartContainer = ({ children }: { children: ReactNode }) => {
export const ChartContainer = ({
children,
ariaHidden = true,
fitContent,
}: {
children: ReactNode;
ariaHidden?: boolean;
fitContent?: boolean;
}) => {
const [state] = useConfiguratorState(hasChartConfigs);
const chartConfig = getChartConfig(state);
const isFreeCanvas = isLayoutingFreeCanvas(state);
Expand All @@ -41,10 +49,14 @@ export const ChartContainer = ({ children }: { children: ReactNode }) => {
// chart types (that might have different sizes).
key={chartConfig.chartType}
ref={ref}
aria-hidden="true"
aria-hidden={ariaHidden || undefined}
className={classes.chartContainer}
style={{
height: isFreeCanvas ? "initial" : bounds.height,
height: isFreeCanvas
? "initial"
: fitContent
? undefined
: bounds.height,
overflow: "auto",
}}
>
Expand Down
16 changes: 11 additions & 5 deletions app/charts/table/cell-desktop.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -47,9 +47,11 @@ const useStyles = makeStyles((theme: Theme) => ({
export const CellDesktop = ({
cell,
columnMeta,
isRowHeader,
}: {
cell: Cell<Observation>;
columnMeta: ColumnMeta;
isRowHeader: boolean;
}) => {
const {
columnComponentType,
Expand All @@ -63,14 +65,18 @@ export const CellDesktop = ({
} = columnMeta;
const classes = useStyles();
const { links, shouldApplyWidthLimits } = useChartState() as TableChartState;
const cellProps = {
...cell.getCellProps(),
role: isRowHeader ? "rowheader" : "cell",
};

switch (columnMeta.type) {
case "text":
const textContent = columnMeta.formatter(cell);

return (
<Flex
{...cell.getCellProps()}
{...cellProps}
sx={{
alignItems: "center",
justifyContent:
Expand Down Expand Up @@ -107,7 +113,7 @@ export const CellDesktop = ({
const { colorScale: cColorScale } = columnMeta;
return (
<Flex
{...cell.getCellProps()}
{...cellProps}
sx={{ alignItems: "center", fontWeight: textStyle, pl: 1, pr: 3 }}
>
<LinkedCellWrapper cell={cell} columnMeta={columnMeta} links={links}>
Expand All @@ -132,7 +138,7 @@ export const CellDesktop = ({
backgroundColor: isNull ? "grey.100" : hColorScale(cell.value),
fontWeight: textStyle,
}}
{...cell.getCellProps()}
{...cellProps}
>
<LinkedCellWrapper cell={cell} columnMeta={columnMeta} links={links}>
{columnMeta.formatter(cell)}
Expand All @@ -151,7 +157,7 @@ export const CellDesktop = ({
// widthScale domain (see table state).
px: `${BAR_CELL_PADDING}px`,
}}
{...cell.getCellProps()}
{...cellProps}
>
<LinkedCellWrapper cell={cell} columnMeta={columnMeta} links={links}>
<Box>{columnMeta.formatter(cell)}</Box>
Expand Down Expand Up @@ -205,7 +211,7 @@ export const CellDesktop = ({
backgroundColor: columnColor,
fontWeight: textStyle,
}}
{...cell.getCellProps()}
{...cellProps}
>
<LinkedCellWrapper cell={cell} columnMeta={columnMeta} links={links}>
{columnMeta.formatter(cell)}
Expand Down
Loading
Loading