diff --git a/CHANGELOG.md b/CHANGELOG.md
index 878121ea8..eba61277b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -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
diff --git a/app/browse/ui/data-table-preview.spec.tsx b/app/browse/ui/data-table-preview.spec.tsx
new file mode 100644
index 000000000..a6432076f
--- /dev/null
+++ b/app/browse/ui/data-table-preview.spec.tsx
@@ -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(
+
+
+
+ );
+};
+
+const getCellTexts = () => {
+ return screen.getAllByRole("cell").map((cell) => cell.textContent);
+};
diff --git a/app/browse/ui/data-table-preview.tsx b/app/browse/ui/data-table-preview.tsx
index 2ffc2b763..e109acfe9 100644
--- a/app/browse/ui/data-table-preview.tsx
+++ b/app/browse/ui/data-table-preview.tsx
@@ -1,4 +1,6 @@
+import { t } from "@lingui/macro";
import {
+ Box,
Table,
TableBody,
TableCell,
@@ -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,
@@ -84,37 +88,63 @@ export const DataTablePreview = ({
return (
- {title}
+ {title}
{sortedComponents.map((component) => {
+ const isSorted = sortBy?.id === component.id;
+ const headerText = getLabelWithUnit(component);
+
return (
handleSort(component)}
sx={{
textAlign: isNumericalMeasure(component) ? "right" : "left",
whiteSpace: "nowrap",
+ cursor: "pointer",
}}
>
- svg": {
- ...(!sortBy ? { transform: "translateY(-15%)" } : {}),
- },
- }}
- >
+
-
+ {
+ e.stopPropagation();
+ handleSort(component);
+ }}
+ sx={{
+ margin: "0 0 0 2px",
+ padding: "4px",
+ "& .MuiTableSortLabel-icon": { margin: 0 },
+ "&:hover > svg": {
+ ...(!sortBy ? { transform: "translateY(-15%)" } : {}),
+ },
+ }}
+ />
+
);
})}
diff --git a/app/charts/chart-data-wrapper.spec.tsx b/app/charts/chart-data-wrapper.spec.tsx
index b6f2c3e3f..b06b96fee 100644
--- a/app/charts/chart-data-wrapper.spec.tsx
+++ b/app/charts/chart-data-wrapper.spec.tsx
@@ -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([
@@ -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 = () => My chart
;
+
+ const renderWithObservations = (chartType: ChartConfig["chartType"]) => {
+ vi.mocked(useDataCubesObservationsQuery).mockReturnValue([
+ {
+ data: { dataCubesObservations: { data: [{ x: "a" }] } },
+ error: undefined,
+ fetching: false,
+ },
+ ] as unknown as ReturnType);
+
+ return render(
+
+ null}
+ Component={Chart}
+ dataSource={{ type: "sparql", url: "url" }}
+ observationQueryFilters={[]}
+ />
+
+ );
+ };
+
+ 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();
+ });
+ });
});
diff --git a/app/charts/chart-data-wrapper.tsx b/app/charts/chart-data-wrapper.tsx
index a31e13d9e..fbbdc26c8 100644
--- a/app/charts/chart-data-wrapper.tsx
+++ b/app/charts/chart-data-wrapper.tsx
@@ -20,7 +20,7 @@ import {
LoadingOverlay,
NoDataHint,
} from "@/components/hint";
-import { ChartConfig, DataSource } from "@/configurator";
+import { ChartConfig, DataSource, isTableConfig } from "@/configurator";
import {
useDataCubesComponentsQuery,
useDataCubesMetadataQuery,
@@ -178,7 +178,7 @@ const ChartDataWrapperInner = <
className={classes.dataWrapper}
data-chart-loaded={!chartLoadingState.loading}
>
- {observations.length > 0 && (
+ {observations.length > 0 && !isTableConfig(chartConfig) && (
(() => ({
},
}));
-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);
@@ -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",
}}
>
diff --git a/app/charts/table/cell-desktop.tsx b/app/charts/table/cell-desktop.tsx
index ef0afadde..4f8ea0a4a 100644
--- a/app/charts/table/cell-desktop.tsx
+++ b/app/charts/table/cell-desktop.tsx
@@ -47,9 +47,11 @@ const useStyles = makeStyles((theme: Theme) => ({
export const CellDesktop = ({
cell,
columnMeta,
+ isRowHeader,
}: {
cell: Cell;
columnMeta: ColumnMeta;
+ isRowHeader: boolean;
}) => {
const {
columnComponentType,
@@ -63,6 +65,10 @@ 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":
@@ -70,7 +76,7 @@ export const CellDesktop = ({
return (
@@ -132,7 +138,7 @@ export const CellDesktop = ({
backgroundColor: isNull ? "grey.100" : hColorScale(cell.value),
fontWeight: textStyle,
}}
- {...cell.getCellProps()}
+ {...cellProps}
>
{columnMeta.formatter(cell)}
@@ -151,7 +157,7 @@ export const CellDesktop = ({
// widthScale domain (see table state).
px: `${BAR_CELL_PADDING}px`,
}}
- {...cell.getCellProps()}
+ {...cellProps}
>
{columnMeta.formatter(cell)}
@@ -205,7 +211,7 @@ export const CellDesktop = ({
backgroundColor: columnColor,
fontWeight: textStyle,
}}
- {...cell.getCellProps()}
+ {...cellProps}
>
{columnMeta.formatter(cell)}
diff --git a/app/charts/table/chart-table.tsx b/app/charts/table/chart-table.tsx
index 1a6dbb85b..0a958ebe5 100644
--- a/app/charts/table/chart-table.tsx
+++ b/app/charts/table/chart-table.tsx
@@ -35,7 +35,7 @@ const ChartTable = memo(function ChartTable(props: ChartProps) {
return (
-
+
{showTimeBrush && (
);
})}
@@ -165,6 +214,7 @@ export const TableContent = ({ children }: { children: ReactNode }) => {
})}
{
>
);
};
+
+const getAriaSort = (column: HeaderGroup) => {
+ if (column.sortedIndex !== 0) {
+ return undefined;
+ }
+
+ return column.isSortedDesc ? "descending" : "ascending";
+};
diff --git a/app/charts/table/table-mobile.tsx b/app/charts/table/table-mobile.tsx
new file mode 100644
index 000000000..35c74b117
--- /dev/null
+++ b/app/charts/table/table-mobile.tsx
@@ -0,0 +1,244 @@
+import { Box, Theme } from "@mui/material";
+import { makeStyles } from "@mui/styles";
+import {
+ forwardRef,
+ HTMLAttributes,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+} from "react";
+import { ColumnInstance, Row } from "react-table";
+import AutoSizer from "react-virtualized-auto-sizer";
+import { ListChildComponentProps, VariableSizeList } from "react-window";
+
+import { useChartState } from "@/charts/shared/chart-state";
+import { DDContent } from "@/charts/table/cell-mobile";
+import { FOCUS_RING_ROOM, TABLE_HEIGHT } from "@/charts/table/constants";
+import { GroupHeader } from "@/charts/table/group-header";
+import { TableChartState } from "@/charts/table/table-state";
+import { useHeightWhileSearching } from "@/charts/table/use-table-heights";
+import { Flex } from "@/components/flex";
+import { Observation } from "@/domain/data";
+import { FOCUS_OUTLINE_INSET } from "@/themes/focus";
+
+const MOBILE_ROW_HEIGHT = 32;
+
+const useStyles = makeStyles((theme: Theme) => ({
+ list: {
+ width: "100%",
+ height: "100%",
+ boxSizing: "border-box",
+ padding: FOCUS_RING_ROOM,
+ position: "relative",
+ backgroundColor: theme.palette.grey[100],
+ marginBottom: theme.spacing(4),
+ fontSize: "0.875rem",
+ "&:has([role=region]:focus-visible)": FOCUS_OUTLINE_INSET,
+ },
+ mobileRow: {
+ borderBottom: "1px solid",
+ borderBottomColor: theme.palette.monochrome[300],
+
+ "&:first-of-type": {
+ borderTop: "1px solid",
+ borderTopColor: theme.palette.monochrome[300],
+ },
+ },
+}));
+
+export const TableMobile = ({
+ rows,
+ prepareRow,
+ visibleColumns,
+ groupingLevels,
+ fillsTile,
+ isSearching,
+}: {
+ rows: Row[];
+ prepareRow: (row: Row) => void;
+ visibleColumns: ColumnInstance[];
+ groupingLevels: number;
+ fillsTile: boolean;
+ isSearching: boolean;
+}) => {
+ const { rowHeight, tableColumnsMeta } = useChartState() as TableChartState;
+ const classes = useStyles();
+
+ const getItemSize = useCallback(
+ (index: number) => {
+ return rows[index].isGrouped
+ ? rowHeight
+ : visibleColumns.length * MOBILE_ROW_HEIGHT;
+ },
+ [rows, rowHeight, visibleColumns.length]
+ );
+
+ const listRef = useRef(null);
+
+ useEffect(() => {
+ listRef.current?.resetAfterIndex(0);
+ }, [rows]);
+
+ const contentHeight = useMemo(() => {
+ let height = 0;
+
+ for (let i = 0; i < rows.length && height < TABLE_HEIGHT; i++) {
+ height += getItemSize(i);
+ }
+
+ return Math.min(TABLE_HEIGHT, height);
+ }, [rows.length, getItemSize]);
+ const listHeight = useHeightWhileSearching(
+ contentHeight + 2 * FOCUS_RING_ROOM,
+ isSearching
+ );
+
+ const itemData = useMemo(() => {
+ return {
+ rows,
+ prepareRow,
+ tableColumnsMeta,
+ rowHeight,
+ groupingLevels,
+ className: classes.mobileRow,
+ };
+ }, [
+ rows,
+ prepareRow,
+ tableColumnsMeta,
+ rowHeight,
+ groupingLevels,
+ classes.mobileRow,
+ ]);
+
+ return (
+
+
+ {({ width, height }: { width: number; height: number }) => (
+
+ {MobileRow}
+
+ )}
+
+
+ );
+};
+
+type MobileRowData = {
+ rows: Row[];
+ prepareRow: (row: Row) => void;
+ tableColumnsMeta: TableChartState["tableColumnsMeta"];
+ rowHeight: number;
+ groupingLevels: number;
+ className: string;
+};
+
+const MobileRow = ({
+ index,
+ style,
+ data,
+}: ListChildComponentProps) => {
+ const row = data.rows[index];
+ data.prepareRow(row);
+
+ return (
+
+ {row.subRows.length === 0 ? (
+
+ {row.cells.map((cell, i) => (
+
+
+ {cell.column.Header}
+
+
+
+
+
+ ))}
+
+ ) : (
+
+
+
+ )}
+
+ );
+};
+
+const MobileListScrollArea = forwardRef<
+ HTMLDivElement,
+ HTMLAttributes
+>(function MobileListScrollArea(props, ref) {
+ const { tableLabel } = useChartState() as TableChartState;
+
+ return (
+
+ );
+});
+
+const MobileList = forwardRef<
+ HTMLUListElement,
+ HTMLAttributes
+>(function MobileList({ style, ...props }, ref) {
+ return (
+
+ );
+});
diff --git a/app/charts/table/table-state.tsx b/app/charts/table/table-state.tsx
index 9c88fb5ef..0b8bc1825 100644
--- a/app/charts/table/table-state.tsx
+++ b/app/charts/table/table-state.tsx
@@ -1,3 +1,4 @@
+import { t } from "@lingui/macro";
import { ascending, extent, max, min } from "d3-array";
import {
ScaleDiverging,
@@ -31,7 +32,6 @@ import {
LIMITED_COLUMN_WIDTH,
TABLE_HEIGHT,
} from "@/charts/table/constants";
-import { getTableUIElementsOffset } from "@/charts/table/table";
import {
TableStateVariables,
useTableStateData,
@@ -56,6 +56,7 @@ import {
TemporalEntityDimension,
} from "@/domain/data";
import { useDimensionFormatters, useFormatNumber } from "@/formatters";
+import { useLocale } from "@/locales/use-locale";
import { getColorInterpolator } from "@/palettes";
import { getTextWidth } from "@/utils/get-text-width";
import { makeDimensionValueSorters } from "@/utils/sorting-values";
@@ -116,6 +117,8 @@ type TableInteractiveTimeRangeState = {
export type TableChartState = CommonChartState &
TableInteractiveTimeRangeState & {
chartType: "table";
+ /** The chart title, or a generic name when the chart has none. */
+ tableLabel: string;
rowHeight: number;
showSearch: boolean;
tableColumns: Column[];
@@ -137,6 +140,7 @@ const useTableState = (
const { chartData, allData, timeRangeData } = data;
const { fields, settings, links, sorting } = chartConfig;
const formatNumber = useFormatNumber();
+ const locale = useLocale();
const hasBar = Object.values(fields).some(
(fValue) => fValue.columnStyle.type === "bar"
@@ -151,21 +155,10 @@ const useTableState = (
left: 10,
};
const chartWidth = width - margins.left - margins.right;
- const chartHeight = Math.min(
- TABLE_HEIGHT,
- // + 1 for the header row
- (chartData.length + 1) * rowHeight
- );
+ // The table sizes itself to its rows, see `Table`.
+ const chartHeight = TABLE_HEIGHT;
- const height =
- chartHeight +
- margins.top +
- margins.bottom +
- getTableUIElementsOffset({
- showSearch: settings.showSearch,
- width,
- showTimeRange: chartConfig.interactiveFiltersConfig.timeRange.active,
- });
+ const height = chartHeight + margins.top + margins.bottom;
const bounds = {
width,
height,
@@ -472,6 +465,9 @@ const useTableState = (
return {
chartType: "table",
+ tableLabel:
+ chartConfig.meta.title[locale] ||
+ t({ id: "chart.table.label", message: "Table" }),
chartData: memoizedData,
allData,
bounds,
diff --git a/app/charts/table/table.tsx b/app/charts/table/table.tsx
index d4cc43d73..c399400f4 100644
--- a/app/charts/table/table.tsx
+++ b/app/charts/table/table.tsx
@@ -1,9 +1,11 @@
-import { t, Trans } from "@lingui/macro";
+import { plural, t, Trans } from "@lingui/macro";
import { Box, Theme, Typography } from "@mui/material";
import { makeStyles } from "@mui/styles";
+import { useId } from "@reach/auto-id";
import FlexSearch from "flexsearch";
-import { forwardRef, useCallback, useMemo, useState } from "react";
+import { FocusEvent, forwardRef, useMemo, useState } from "react";
import {
+ Row,
useExpanded,
useFlexLayout,
useGroupBy,
@@ -11,20 +13,36 @@ import {
useTable,
} from "react-table";
import AutoSizer from "react-virtualized-auto-sizer";
-import { FixedSizeList, VariableSizeList } from "react-window";
+import { FixedSizeList, ListChildComponentProps } from "react-window";
import { useChartState } from "@/charts/shared/chart-state";
import { CellDesktop } from "@/charts/table/cell-desktop";
-import { DDContent } from "@/charts/table/cell-mobile";
+import {
+ FOCUS_RING_ROOM,
+ TABLE_HEADER_HEIGHT,
+ TABLE_HEIGHT,
+} from "@/charts/table/constants";
import { GroupHeader } from "@/charts/table/group-header";
import {
TableContent,
TableContentProvider,
+ useTableContent,
} from "@/charts/table/table-content";
+import { TableMobile } from "@/charts/table/table-mobile";
import { TableChartState } from "@/charts/table/table-state";
-import { Flex } from "@/components/flex";
+import {
+ readHeight,
+ useHeightWhileSearching,
+ useObservedHeight,
+} from "@/charts/table/use-table-heights";
import { Input, Switch } from "@/components/form";
-import { Observation } from "@/domain/data";
+import { LiveRegion } from "@/components/live-region";
+import {
+ hasChartConfigs,
+ isLayoutingFreeCanvas,
+ useConfiguratorState,
+} from "@/configurator";
+import { isMeasure, Observation } from "@/domain/data";
import { Icon } from "@/icons";
import {
FOCUS_OUTLINE_INSET,
@@ -36,13 +54,25 @@ const MOBILE_VIEW_THRESHOLD = 384;
const TableContentWrapper = forwardRef(
({ children, ...props }, ref) => {
+ const { tableAriaProps, header } = useTableContent();
+
return (
{children}
@@ -57,15 +87,6 @@ const useStyles = makeStyles((theme: Theme) => {
borderBottom: "1px solid",
borderBottomColor: theme.palette.monochrome[300],
},
- mobileRow: {
- borderBottom: "1px solid",
- borderBottomColor: theme.palette.monochrome[300],
-
- "&:first-of-type": {
- borderTop: "1px solid",
- borderTopColor: theme.palette.monochrome[300],
- },
- },
};
});
@@ -75,26 +96,16 @@ const shouldShowCompactMobileView = (width: number) => {
export const TABLE_TIME_RANGE_HEIGHT = 40;
-/** Use to make sure we don't cut the table off by having other UI elements enabled */
-export const getTableUIElementsOffset = ({
- showSearch,
- width,
- showTimeRange,
-}: {
- showSearch: boolean;
- width: number;
- showTimeRange: boolean;
-}) => {
- return (
- (showSearch ? 48 : 0) +
- (shouldShowCompactMobileView(width) ? 48 : 0) +
- (showTimeRange ? TABLE_TIME_RANGE_HEIGHT : 0) +
- 54
- );
+// Browsers don't scroll partly visible elements on focus, which leaves their focus ring clipped.
+const scrollFocusedControlIntoView = (e: FocusEvent) => {
+ if (e.target !== e.currentTarget && e.target.matches(":focus-visible")) {
+ e.target.scrollIntoView({ block: "nearest", inline: "nearest" });
+ }
};
export const Table = () => {
const {
+ tableLabel,
bounds,
rowHeight,
chartData,
@@ -108,7 +119,17 @@ export const Table = () => {
} = useChartState() as TableChartState;
const classes = useStyles();
+ const [configuratorState] = useConfiguratorState(hasChartConfigs);
+ const fillsTile = isLayoutingFreeCanvas(configuratorState);
const [compactMobileViewEnabled, setCompactMobileView] = useState(false);
+ const [headerElement, setHeaderElement] = useState(
+ null
+ );
+ const headerHeight = useObservedHeight({
+ element: headerElement,
+ read: readHeight,
+ initial: TABLE_HEADER_HEIGHT,
+ });
const showCompactMobileView = shouldShowCompactMobileView(bounds.width);
@@ -143,8 +164,6 @@ export const Table = () => {
}, [chartData, searchTerm, searchIndex]);
const {
- getTableProps,
- getTableBodyProps,
headerGroups,
rows,
totalColumnsWidth,
@@ -181,125 +200,51 @@ export const Table = () => {
// If the table has a custom sort, the tableState.sortBy has these items prepended.
const customSortCount = tableState.sortBy.length - sortingIds.length;
- // Desktop row
- const renderDesktopRow = useCallback(
- ({ index, style }) => {
- const row = rows[index];
- prepareRow(row);
- return (
-
- {row.subRows.length === 0 ? (
- row.cells.map((cell, i) => {
- return (
-
- );
- })
- ) : (
-
- )}
-
- );
- },
- [classes.desktopRow, groupingIds.length, prepareRow, rows, tableColumnsMeta]
- );
+ const rowHeaderColumnId = useMemo(() => {
+ return visibleColumns.find(
+ (column) => !isMeasure(tableColumnsMeta[column.id].dim)
+ )?.id;
+ }, [visibleColumns, tableColumnsMeta]);
- // Mobile row
- const MOBILE_ROW_HEIGHT = 32;
- const getMobileItemSize = useCallback(
- (index: number) => {
- return rows[index].isGrouped
- ? rowHeight
- : visibleColumns.length * MOBILE_ROW_HEIGHT;
- },
- [rows, rowHeight, visibleColumns.length]
- );
+ const tableAriaProps = useMemo(() => {
+ return {
+ "aria-label": tableLabel,
+ "aria-rowcount": rows.length + 1,
+ "aria-colcount": visibleColumns.length,
+ };
+ }, [tableLabel, rows.length, visibleColumns.length]);
- const renderMobileRow = useCallback(
- ({ index, style }) => {
- const row = rows[index];
- prepareRow(row);
+ const searchId = `table-search-${useId()}`;
- return (
- <>
-
- {row.subRows.length === 0 ? (
- row.cells.map((cell, i) => {
- return (
-
-
- {cell.column.Header}
-
-
-
-
-
- );
- })
- ) : (
- // Group
-
-
-
- )}
-
- >
- );
- },
- [
- classes.mobileRow,
- groupingIds.length,
- prepareRow,
- rowHeight,
+ const tableHeader = useMemo(
+ () => ({ height: headerHeight, ref: setHeaderElement }),
+ [headerHeight]
+ );
+ const tableHeight = useHeightWhileSearching(
+ Math.min(TABLE_HEIGHT, headerHeight + rows.length * rowHeight) +
+ 2 * FOCUS_RING_ROOM,
+ searchTerm !== ""
+ );
+
+ const desktopRowData = useMemo(() => {
+ return {
rows,
+ prepareRow,
tableColumnsMeta,
- ]
- );
+ rowHeaderColumnId,
+ groupingLevels: groupingIds.length,
+ columnCount: visibleColumns.length,
+ className: classes.desktopRow,
+ };
+ }, [
+ rows,
+ prepareRow,
+ tableColumnsMeta,
+ rowHeaderColumnId,
+ groupingIds.length,
+ visibleColumns.length,
+ classes.desktopRow,
+ ]);
return (
<>
@@ -310,7 +255,7 @@ export const Table = () => {
>
{
id: "table.search.placeholder",
message: "Search...",
})}
- endAdornment={}
+ endAdornment={}
// The chart container scrolls and would clip an outside ring.
sx={{ [FOCUS_VISIBLE_WITHIN_FIELD]: FOCUS_OUTLINE_INSET }}
value={searchTerm}
onChange={(e) => setSearchTerm(e.currentTarget.value)}
/>
+
)}
{
{showCompactMobileView && compactMobileViewEnabled ? (
- /* Compact Mobile View */
-
-
- {({ width, height }: { width: number; height: number }) => (
-
- {renderMobileRow}
-
- )}
-
-
+
) : (
/* Regular table view */
-
+
{({ height }: { height: number }) => (
- {renderDesktopRow}
+ {DesktopRow}
)}
-
+
)}
{
>
);
};
+
+type DesktopRowData = {
+ rows: Row[];
+ prepareRow: (row: Row) => void;
+ tableColumnsMeta: TableChartState["tableColumnsMeta"];
+ rowHeaderColumnId: string | undefined;
+ groupingLevels: number;
+ columnCount: number;
+ className: string;
+};
+
+/** Defined once, so react-window keeps rows mounted (and focus inside them) when the data changes. Same for `MobileRow`. */
+const DesktopRow = ({
+ index,
+ style,
+ data,
+}: ListChildComponentProps) => {
+ const row = data.rows[index];
+ data.prepareRow(row);
+
+ return (
+
+ {row.subRows.length === 0 ? (
+ row.cells.map((cell, i) => {
+ return (
+
+ );
+ })
+ ) : (
+
+ )}
+
+ );
+};
diff --git a/app/charts/table/use-table-heights.ts b/app/charts/table/use-table-heights.ts
new file mode 100644
index 000000000..8b3e89a57
--- /dev/null
+++ b/app/charts/table/use-table-heights.ts
@@ -0,0 +1,51 @@
+import { ResizeObserver } from "@juggle/resize-observer";
+import { useEffect, useRef, useState } from "react";
+
+export const readHeight = (element: HTMLElement) => element.offsetHeight;
+
+/** Keeps a measured height up to date while the element resizes. `read` must be stable. */
+export const useObservedHeight = ({
+ element,
+ read,
+ initial,
+}: {
+ element: HTMLElement | null;
+ read: (element: HTMLElement) => number;
+ initial: number;
+}) => {
+ const [height, setHeight] = useState(initial);
+
+ useEffect(() => {
+ if (!element) {
+ return;
+ }
+
+ const update = () => {
+ setHeight(read(element));
+ };
+
+ update();
+ const observer = new ResizeObserver(update);
+ observer.observe(element);
+
+ return () => {
+ observer.disconnect();
+ };
+ }, [element, read]);
+
+ return height;
+};
+
+/** While searching, keeps at least the height from before the search, so content below doesn't move with every keystroke. */
+export const useHeightWhileSearching = (
+ height: number,
+ isSearching: boolean
+) => {
+ const heightBeforeSearch = useRef(height);
+
+ if (!isSearching) {
+ heightBeforeSearch.current = height;
+ }
+
+ return isSearching ? Math.max(height, heightBeforeSearch.current) : height;
+};
diff --git a/app/locales/de/messages.po b/app/locales/de/messages.po
index 4b1ba6d2a..9145e32a5 100644
--- a/app/locales/de/messages.po
+++ b/app/locales/de/messages.po
@@ -85,6 +85,10 @@ msgstr "[ Text hinzufügen ]"
msgid "annotator.add.title"
msgstr "[ Titel hinzufügen ]"
+#: app/charts/table/table.tsx
+msgid "table.search.results"
+msgstr "{0, plural, =0 {Keine passenden Zeilen} one {# passende Zeile} other {# passende Zeilen}}"
+
#: app/browse/ui/search-dataset-results-count.tsx
msgid "dataset.results"
msgstr "{0, plural, zero {Keine Datensätze} one {# Datensatz} other {# Datensätze}}"
@@ -2079,6 +2083,11 @@ msgstr "Sortieren nach"
msgid "controls.sorting.sortBy"
msgstr "Sortieren nach"
+#: app/browse/ui/data-table-preview.tsx
+#: app/charts/table/table-content.tsx
+msgid "table.sort.by"
+msgstr "Sortieren nach {headerText}"
+
#: app/configurator/table/table-chart-configurator.tsx
msgid "controls.table.sorting"
msgstr "Sortierung"
@@ -2169,6 +2178,10 @@ msgstr "Tab-Titel"
msgid "controls.layout.tab"
msgstr "Tab Layout"
+#: app/charts/table/table-state.tsx
+msgid "chart.table.label"
+msgstr "Tabelle"
+
#: app/configurator/components/field-i18n.ts
msgid "controls.chart.type.table"
msgstr "Tabelle"
diff --git a/app/locales/en/messages.po b/app/locales/en/messages.po
index c258c0833..1a58d4054 100644
--- a/app/locales/en/messages.po
+++ b/app/locales/en/messages.po
@@ -85,6 +85,10 @@ msgstr "[ Add text ]"
msgid "annotator.add.title"
msgstr "[ Add Title ]"
+#: app/charts/table/table.tsx
+msgid "table.search.results"
+msgstr "{0, plural, =0 {No matching rows} one {# matching row} other {# matching rows}}"
+
#: app/browse/ui/search-dataset-results-count.tsx
msgid "dataset.results"
msgstr "{0, plural, zero {No datasets} one {# dataset} other {# datasets}}"
@@ -2079,6 +2083,11 @@ msgstr "Sort by"
msgid "controls.sorting.sortBy"
msgstr "Sort by"
+#: app/browse/ui/data-table-preview.tsx
+#: app/charts/table/table-content.tsx
+msgid "table.sort.by"
+msgstr "Sort by {headerText}"
+
#: app/configurator/table/table-chart-configurator.tsx
msgid "controls.table.sorting"
msgstr "Sorting"
@@ -2169,6 +2178,10 @@ msgstr "Tab label"
msgid "controls.layout.tab"
msgstr "Tab Layout"
+#: app/charts/table/table-state.tsx
+msgid "chart.table.label"
+msgstr "Table"
+
#: app/configurator/components/field-i18n.ts
msgid "controls.chart.type.table"
msgstr "Table"
diff --git a/app/locales/fr/messages.po b/app/locales/fr/messages.po
index 3541961f9..077bf5dee 100644
--- a/app/locales/fr/messages.po
+++ b/app/locales/fr/messages.po
@@ -85,6 +85,10 @@ msgstr "[ Ajouter du texte ]"
msgid "annotator.add.title"
msgstr "[ Ajouter de titre ]"
+#: app/charts/table/table.tsx
+msgid "table.search.results"
+msgstr "{0, plural, =0 {Aucune ligne correspondante} one {# ligne correspondante} other {# lignes correspondantes}}"
+
#: app/browse/ui/search-dataset-results-count.tsx
msgid "dataset.results"
msgstr "{0, plural, zero {Aucun jeu de données} one {# jeu de données} other {# jeux de données}}"
@@ -2079,6 +2083,11 @@ msgstr "Trier par"
msgid "controls.sorting.sortBy"
msgstr "Trier par"
+#: app/browse/ui/data-table-preview.tsx
+#: app/charts/table/table-content.tsx
+msgid "table.sort.by"
+msgstr "Trier par {headerText}"
+
#: app/configurator/table/table-chart-configurator.tsx
msgid "controls.table.sorting"
msgstr "Tri"
@@ -2169,6 +2178,10 @@ msgstr "Nom de l'onglet"
msgid "controls.layout.tab"
msgstr "Tab Layout"
+#: app/charts/table/table-state.tsx
+msgid "chart.table.label"
+msgstr "Tableau"
+
#: app/configurator/components/field-i18n.ts
msgid "controls.chart.type.table"
msgstr "Tableau"
diff --git a/app/locales/it/messages.po b/app/locales/it/messages.po
index a974172fe..88f8a85ca 100644
--- a/app/locales/it/messages.po
+++ b/app/locales/it/messages.po
@@ -85,6 +85,10 @@ msgstr "[ Aggiungi testo ]"
msgid "annotator.add.title"
msgstr "[ Aggiungi titolo ]"
+#: app/charts/table/table.tsx
+msgid "table.search.results"
+msgstr "{0, plural, =0 {Nessuna riga corrispondente} one {# riga corrispondente} other {# righe corrispondenti}}"
+
#: app/browse/ui/search-dataset-results-count.tsx
msgid "dataset.results"
msgstr "{0, plural, zero {Nessun set di dati} one {# set di dati} other {# set di dati}}"
@@ -2079,6 +2083,11 @@ msgstr "Ordina per"
msgid "controls.sorting.sortBy"
msgstr "Ordina per"
+#: app/browse/ui/data-table-preview.tsx
+#: app/charts/table/table-content.tsx
+msgid "table.sort.by"
+msgstr "Ordina per {headerText}"
+
#: app/configurator/table/table-chart-configurator.tsx
msgid "controls.table.sorting"
msgstr "Ordinamento"
@@ -2169,6 +2178,10 @@ msgstr "Etichetta della scheda"
msgid "controls.layout.tab"
msgstr "Tab Layout"
+#: app/charts/table/table-state.tsx
+msgid "chart.table.label"
+msgstr "Tabella"
+
#: app/configurator/components/field-i18n.ts
msgid "controls.chart.type.table"
msgstr "Tabella"
diff --git a/e2e/keyboard-focus.spec.ts b/e2e/keyboard-focus.spec.ts
index 502d83611..352153575 100644
--- a/e2e/keyboard-focus.spec.ts
+++ b/e2e/keyboard-focus.spec.ts
@@ -51,8 +51,12 @@ test.describe("keyboard focus", () => {
`/en/browse?dataset=${encodeURIComponent(RED_LIST_CUBE)}&dataSource=Prod`
);
await page.getByRole("table").waitFor();
+ // Wait for expanding sections; visually hidden text also clips its overflow.
await page.waitForFunction(
- () => !document.querySelector("main [style*='overflow: hidden']")
+ () =>
+ !document.querySelector(
+ "main [style*='overflow: hidden']:not([style*='clip'])"
+ )
);
await expectVisibleFocusRings({ page });
});
diff --git a/e2e/table-chart-keyboard.spec.ts b/e2e/table-chart-keyboard.spec.ts
new file mode 100644
index 000000000..57864fdd9
--- /dev/null
+++ b/e2e/table-chart-keyboard.spec.ts
@@ -0,0 +1,188 @@
+import { Page } from "@playwright/test";
+
+import { expectNoAxeViolations } from "./a11y";
+import { loadChartInLocalStorage } from "./charts-utils";
+import { setup } from "./common";
+import forestFire from "./fixtures/forest-fire-danger-chart-config.json";
+
+const { expect, test } = setup();
+
+const CANTON_FIELD = Object.keys(forestFire.chartConfig.fields).find((id) =>
+ id.endsWith("/canton")
+)!;
+
+test.describe("Table chart", () => {
+ test("is a named table with column headers, row headers and no axe violations", async ({
+ page,
+ }) => {
+ await openTable({ page, key: "table-semantics" });
+ const table = page.getByRole("table", { name: "Table" });
+
+ await expect(page.getByRole("table")).toHaveCount(1);
+ // 143 data rows plus the header row.
+ await expect(table).toHaveAttribute("aria-rowcount", "144");
+ await expect(table.getByRole("columnheader")).toHaveCount(4);
+ await expect(
+ table.getByRole("rowheader", { name: "Canton of Aargau" })
+ ).toBeVisible();
+ await expectNoAxeViolations({ page, include: '[role="table"]' });
+ });
+
+ test("sorts a column by keyboard and reports it with aria-sort", async ({
+ page,
+ }) => {
+ await openTable({ page, key: "table-sort" });
+ const table = page.getByRole("table", { name: "Table" });
+ const header = table.getByRole("columnheader", { name: /^Canton/ });
+
+ await expect(header).not.toHaveAttribute("aria-sort");
+ await page.getByRole("textbox", { name: "Search table" }).focus();
+ // The table itself, then the label and sort buttons of each column up to Canton.
+ for (let i = 0; i < 7; i++) {
+ await page.keyboard.press("Tab");
+ }
+ await expect(
+ table.getByRole("button", { name: "Sort by Canton" })
+ ).toBeFocused();
+ await page.keyboard.press("Enter");
+ await expect(header).toHaveAttribute("aria-sort", "ascending");
+
+ await page.keyboard.press("Enter");
+ await expect(header).toHaveAttribute("aria-sort", "descending");
+ await expect(
+ table.getByRole("button", { name: "Sort by Canton" })
+ ).toBeFocused();
+
+ // Mouse users can still click the header to sort; the label opens the metadata panel instead.
+ const { width } = (await header.boundingBox())!;
+ await header.click({ position: { x: width - 4, y: 4 } });
+ await expect(header).not.toHaveAttribute("aria-sort");
+ await header.click({ position: { x: width - 4, y: 4 } });
+ await expect(header).toHaveAttribute("aria-sort", "ascending");
+ await table.getByRole("button", { name: "Canton", exact: true }).click();
+ const details = page.getByRole("dialog", { name: "Details" });
+ await expect(details).toBeVisible();
+ await page.keyboard.press("Escape");
+ await expect(details).toBeHidden();
+ await expect(header).toHaveAttribute("aria-sort", "ascending");
+ });
+
+ test("scrolls a partly hidden control fully into view when it gets focus", async ({
+ page,
+ }) => {
+ await openTable({ page, key: "table-scroll", groupBy: CANTON_FIELD });
+ const lastSortButton = page.getByRole("button", {
+ name: "Sort by Danger ratings",
+ });
+ const firstGroup = page.getByRole("button", { name: "Zurich" });
+
+ // Reaching the last column scrolls the table sideways, which hides part of the first group.
+ await lastSortButton.focus();
+ await expect(lastSortButton).toBeInViewport({ ratio: 1 });
+ await page.keyboard.press("Tab");
+
+ await expect(firstGroup).toBeFocused();
+ await expect(firstGroup).toBeInViewport({ ratio: 1 });
+ });
+
+ test("expands group rows by keyboard and reaches groups below the fold with Tab", async ({
+ page,
+ }) => {
+ await openTable({ page, key: "table-groups", groupBy: CANTON_FIELD });
+ const table = page.getByRole("table", { name: "Table" });
+ const firstGroup = table.getByRole("button", { name: "Zurich" });
+
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "false");
+ const groupCount = Number(await table.getAttribute("aria-rowcount")) - 1;
+ await firstGroup.focus();
+ await page.keyboard.press("Enter");
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "true");
+ await page.keyboard.press("Enter");
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "false");
+
+ // Mouse users can still click anywhere on the group row.
+ const groupCell = firstGroup.locator("xpath=..");
+ const { width } = (await groupCell.boundingBox())!;
+ await groupCell.click({ position: { x: width - 20, y: 10 } });
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "true");
+ await groupCell.click({ position: { x: width - 20, y: 10 } });
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "false");
+ await firstGroup.focus();
+
+ // Wait for each group to render and scroll into view, as a person would.
+ for (let i = 1; i < groupCount; i++) {
+ await page.keyboard.press("Tab");
+ await expect(table.locator(":focus")).toBeInViewport();
+ }
+
+ const lastGroup = page.locator(":focus");
+ await expect(lastGroup).toHaveAttribute("aria-expanded", "false");
+ await expect(lastGroup).toBeInViewport();
+ await expect(lastGroup.locator("xpath=..")).toHaveAttribute("role", "cell");
+ await expect(
+ lastGroup.locator("xpath=../.."),
+ "the last group row is the last row of the table"
+ ).toHaveAttribute("aria-rowindex", `${groupCount + 1}`);
+ });
+
+ test("keeps focus on a group in the compact view when it is toggled", async ({
+ page,
+ }) => {
+ await page.setViewportSize({ width: 360, height: 800 });
+ await openTable({ page, key: "table-compact", groupBy: CANTON_FIELD });
+ await page.getByRole("checkbox", { name: "Compact view" }).check();
+ const list = page.getByRole("region", { name: "Table" });
+ const firstGroup = list.getByRole("button", { name: "Zurich" });
+
+ await firstGroup.focus();
+ await page.keyboard.press("Enter");
+
+ await expect(firstGroup).toHaveAttribute("aria-expanded", "true");
+ await expect(firstGroup).toBeFocused();
+ await expect(list.getByRole("listitem").nth(1)).toContainText(
+ "Warning region"
+ );
+ });
+
+ test("announces the number of matching rows after searching", async ({
+ page,
+ }) => {
+ await openTable({ page, key: "table-search" });
+
+ await page.getByRole("textbox", { name: "Search table" }).fill("Bern");
+
+ const total = page.getByText(/^Total number of (rows|lines):/);
+ await expect(total).not.toHaveText(/: 143$/);
+ const matches = (await total.textContent())!.match(/(\d+)$/)![1];
+ await expect(
+ page.getByRole("status").filter({ hasText: /matching/ })
+ ).toHaveText(`${matches} matching rows`);
+ });
+});
+
+const openTable = async ({
+ page,
+ key,
+ groupBy,
+}: {
+ page: Page;
+ key: string;
+ groupBy?: string;
+}) => {
+ const config = structuredClone(forestFire);
+
+ if (groupBy) {
+ const fields = config.chartConfig.fields as Record<
+ string,
+ { isGroup: boolean }
+ >;
+ fields[groupBy].isGroup = true;
+ }
+
+ await loadChartInLocalStorage(page, key, config);
+ await page.goto(`/en/create/${key}`);
+ await page.waitForSelector('[data-chart-loaded="true"]', {
+ timeout: 60_000,
+ });
+ await page.getByRole("table", { name: "Table" }).waitFor();
+};