Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Mirror: Striped data grid rows (external #71960) (#84050)

Denis Berezinca73f2f8029a
diff --git a/.loki/reference/chrome_laptop_DataGrid_DataGrid_Striped_Grid.png b/.loki/reference/chrome_laptop_DataGrid_DataGrid_Striped_Grid.png
new file mode 100644
index 00000000000..8e852486a92
Binary files /dev/null and b/.loki/reference/chrome_laptop_DataGrid_DataGrid_Striped_Grid.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows.png b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows.png
new file mode 100644
index 00000000000..26c443cf3ae
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme.png b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme.png
new file mode 100644
index 00000000000..cf6956a4e91
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme_Stripe_Color.png b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme_Stripe_Color.png
new file mode 100644
index 00000000000..87d563da7cd
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Table_Dashboard_Table_Striped_Rows_Embedding_Theme_Stripe_Color.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Table_Striped_Rows_With_Conditional_Formatting.png b/.loki/reference/chrome_laptop_viz_Table_Striped_Rows_With_Conditional_Formatting.png
new file mode 100644
index 00000000000..5d91f1b996a
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Table_Striped_Rows_With_Conditional_Formatting.png differ
diff --git a/.loki/reference/chrome_laptop_viz_Table_Table_Striped_Rows.png b/.loki/reference/chrome_laptop_viz_Table_Table_Striped_Rows.png
new file mode 100644
index 00000000000..1e87b261314
Binary files /dev/null and b/.loki/reference/chrome_laptop_viz_Table_Table_Striped_Rows.png differ
diff --git a/docs/questions/visualizations/table.md b/docs/questions/visualizations/table.md
index e2f65d5afb3..144eb5992ef 100644
--- a/docs/questions/visualizations/table.md
+++ b/docs/questions/visualizations/table.md
@@ -47,6 +47,16 @@ To number the rows of a table, click on the **gear** icon in bottom left to brin
To change the width of a column, you can click and drag the edges of the column's header.
+## Stripe rows
+
+To make wide tables easier to read, you can shade every other row.
+
+1. Click the **gear** icon in the bottom left to open visualization settings.
+2. Switch to the **Display** tab.
+3. Toggle on **Striped rows**.
+
+Striped rows also apply when the table is sent in a [dashboard subscription or alert](../../dashboards/subscriptions.md). Any [conditional formatting](#conditional-table-formatting) colors take precedence over the striped row effect.
+
## Freeze columns or rows
You can freeze a number of columns and/or rows, so that they'd stay on the screen while you scroll. Sticky columns are especially useful when viewing wide tables, as you can keep the column that identifies the row (like `account_name`) on the screen as you scroll across the columns.
diff --git a/frontend/src/metabase-types/api/embedding-theme.ts b/frontend/src/metabase-types/api/embedding-theme.ts
index 06351553af1..643486b5389 100644
--- a/frontend/src/metabase-types/api/embedding-theme.ts
+++ b/frontend/src/metabase-types/api/embedding-theme.ts
@@ -155,6 +155,9 @@ export type MetabaseComponentTheme = {
/** Background color of the table header that stays fixed while scrolling. Defaults to `white` if no cell background color is set */
stickyBackgroundColor?: string;
+ /** Background color of every other row when the "Striped rows" table setting is enabled. Defaults to a subtle tint of the cell background color */
+ stripedBackgroundColor?: string;
+
cell: {
/** Text color of cells, defaults to `text-primary`. */
textColor: string;
diff --git a/frontend/src/metabase/data-grid/components/BaseCell/BaseCell.tsx b/frontend/src/metabase/data-grid/components/BaseCell/BaseCell.tsx
index e4c6890edff..684fb944c88 100644
--- a/frontend/src/metabase/data-grid/components/BaseCell/BaseCell.tsx
+++ b/frontend/src/metabase/data-grid/components/BaseCell/BaseCell.tsx
@@ -3,7 +3,7 @@ import type React from "react";
import { memo, useMemo } from "react";
import type { CellAlign } from "metabase/data-grid/types";
-import { isDark } from "metabase/ui/colors/palette";
+import { tryIsDark } from "metabase/ui/colors/palette";
import styles from "./BaseCell.module.css";
@@ -45,10 +45,7 @@ export const BaseCell = memo(function BaseCell({
} as React.CSSProperties;
}
- const isDarkColor = isDark(backgroundColor);
- const hoverColor = isDarkColor
- ? `color-mix(in srgb, ${backgroundColor} 95%, white)`
- : `color-mix(in srgb, ${backgroundColor} 97%, black)`;
+ const hoverColor = getHoverColor(backgroundColor);
// Unjustified type cast. FIXME
return {
@@ -75,3 +72,13 @@ export const BaseCell = memo(function BaseCell({
</div>
);
});
+
+function getHoverColor(backgroundColor: string) {
+ const isDarkColor = tryIsDark(backgroundColor);
+ if (isDarkColor == null) {
+ return `color-mix(in srgb, var(--mb-color-core-brand), transparent 90%)`;
+ }
+ return isDarkColor
+ ? `color-mix(in srgb, ${backgroundColor} 95%, white)`
+ : `color-mix(in srgb, ${backgroundColor} 97%, black)`;
+}
diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css
index 2ecbdca9d61..96b548320b7 100644
--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css
+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.module.css
@@ -86,6 +86,13 @@
width: 100%;
position: relative;
+ &.striped {
+ background-color: var(
+ --data-grid-striped-bg-color,
+ var(--mb-color-background-hover)
+ );
+ }
+
&.active {
background-color: color-mix(
in srgb,
diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx
index a0e3ec3b623..0ed2bd098d9 100644
--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx
+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.stories.tsx
@@ -108,6 +108,43 @@ export const BasicGrid: Story = () => {
return <DataGrid {...tableProps} />;
};
+export const StripedGrid: Story = () => {
+ const columns: ColumnOptions<SampleDataType>[] = useMemo(
+ () => [
+ {
+ id: "id",
+ name: "ID",
+ accessorFn: (row) => row.id,
+ },
+ {
+ id: "name",
+ name: "Name",
+ accessorFn: (row) => row.name,
+ },
+ {
+ id: "category",
+ name: "Category",
+ accessorFn: (row) => row.category,
+ },
+ {
+ id: "price",
+ name: "Price",
+ accessorFn: (row) => row.price,
+ formatter: (value) => `$${value}`,
+ align: "right",
+ },
+ ],
+ [],
+ );
+
+ const tableProps = useDataGridInstance({
+ data: sampleData,
+ columnsOptions: columns,
+ });
+
+ return <DataGrid {...tableProps} striped />;
+};
+
export const CustomStylesGrid: Story = () => {
const getHeaderTemplate = (name: string) => {
return function Header() {
diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx
index 23c4a627b9a..5b5bcd9933e 100644
--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx
+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.tsx
@@ -6,7 +6,7 @@ import {
import type { HeaderGroup } from "@tanstack/react-table";
import cx from "classnames";
import type React from "react";
-import { useCallback, useEffect, useState } from "react";
+import { useCallback, useEffect, useMemo, useState } from "react";
import _ from "underscore";
import { getScrollBarSize } from "metabase/utils/dom";
@@ -26,6 +26,7 @@ import type {
DataGridRowType,
DataGridTheme,
} from "../../types";
+import { getStripedBackgroundColor } from "../../utils/striped-background-color";
import { AddColumnButton } from "../AddColumnButton/AddColumnButton";
import { DataGridHeader } from "../DataGridHeader/DataGridHeader";
import { DataGridRow } from "../DataGridRow/DataGridRow";
@@ -38,6 +39,7 @@ export interface DataGridProps<TData>
extends DataGridInstance<TData>, DataGridStylesProps {
emptyState?: React.ReactNode;
showRowsCount?: boolean;
+ striped?: boolean;
isColumnReorderingDisabled?: boolean;
theme?: DataGridTheme;
zoomedRowIndex?: number;
@@ -58,6 +60,7 @@ export const DataGrid = function DataGrid<TData>({
styles,
enablePagination,
showRowsCount,
+ striped = false,
getPinnedRows,
getCenterRows,
getPinnedColumns,
@@ -105,6 +108,11 @@ export const DataGrid = function DataGrid<TData>({
? "var(--mb-color-background_page-primary)"
: backgroundColor);
+ const stripedBackgroundColor = useMemo(
+ () => getStripedBackgroundColor(theme),
+ [theme],
+ );
+
const centerRows = getCenterRows();
const pinnedRows = getPinnedRows();
const pinnedColumns = getPinnedColumns();
@@ -140,6 +148,7 @@ export const DataGrid = function DataGrid<TData>({
key={row.virtualItem?.key ?? row.origin.id}
row={row}
rowMeasureRef={measureRef}
+ striped={striped}
pinnedRowsCount={pinnedRows.length}
columns={columns}
datasetIndexAttributeName={datasetIndexAttributeName}
@@ -233,6 +242,8 @@ export const DataGrid = function DataGrid<TData>({
style={{
fontSize: theme?.fontSize ?? DEFAULT_FONT_SIZE,
backgroundColor,
+ // CSSProperties has no index signature for custom properties
+ ["--data-grid-striped-bg-color" as string]: stripedBackgroundColor,
...styles?.root,
}}
>
diff --git a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx
index 29ab97f8141..8d59f4640d4 100644
--- a/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx
+++ b/frontend/src/metabase/data-grid/components/DataGrid/DataGrid.unit.spec.tsx
@@ -1,3 +1,4 @@
+import Color from "color";
import { type MouseEvent, useMemo } from "react";
import {
@@ -10,6 +11,7 @@ import {
} from "__support__/ui";
import {
type ColumnOptions,
+ type DataGridTheme,
type RowIdColumnOptions,
useDataGridInstance,
} from "metabase/data-grid";
@@ -54,6 +56,8 @@ interface TestDataGridProps {
sortableColumns?: boolean;
wrapableColumns?: string[];
enableSelection?: boolean;
+ striped?: boolean;
+ theme?: DataGridTheme;
pinnedTopRowsCount?: number;
pinnedLeftColumnsCount?: number;
}
@@ -70,6 +74,8 @@ const TestDataGrid = ({
sortableColumns = false,
wrapableColumns = [],
enableSelection = false,
+ striped = false,
+ theme,
pinnedTopRowsCount,
pinnedLeftColumnsCount,
}: TestDataGridProps) => {
@@ -149,6 +155,8 @@ const TestDataGrid = ({
return (
<DataGrid
{...tableProps}
+ striped={striped}
+ theme={theme}
onHeaderCellClick={onHeaderCellClick}
onBodyCellClick={onBodyCellClick}
onAddColumnClick={onAddColumnClick}
@@ -455,4 +463,81 @@ describe("DataGrid", () => {
expect(cells.length).toBeGreaterThan(0);
});
});
+
+ it("applies striped class to alternating rows when enabled", () => {
+ renderWithProviders(<TestDataGrid striped={true} />);
+
+ const bodyRows = screen
+ .getByTestId("table-body")
+ .querySelectorAll('[role="row"]');
+
+ expect(bodyRows[0]).not.toHaveAttribute("data-row-striped", "true");
+ expect(bodyRows[1]).toHaveAttribute("data-row-striped", "true");
+ expect(bodyRows[2]).not.toHaveAttribute("data-row-striped", "true");
+ });
+
+ it("does not apply striped class when disabled", () => {
+ renderWithProviders(<TestDataGrid striped={false} />);
+
+ const bodyRows = screen
+ .getByTestId("table-body")
+ .querySelectorAll('[role="row"]');
+
+ bodyRows.forEach((row) => {
+ expect(row).not.toHaveAttribute("data-row-striped", "true");
+ });
+ });
+
+ describe("striped rows with a theme", () => {
+ const theme: DataGridTheme = {
+ stripedBackgroundColor: "rgb(10, 20, 30)",
+ cell: { backgroundColor: "rgb(40, 50, 60)" },
+ };
+
+ function getCellBackgroundColor(rowIndex: number, columnId: string) {
+ const row = screen
+ .getByTestId("table-body")
+ .querySelectorAll('[role="row"]')[rowIndex];
+ const cell = row.querySelector<HTMLElement>(
+ `[data-column-id="${columnId}"] [data-testid="body-cell-container"]`,
+ );
+ return cell?.style.getPropertyValue("--cell-bg-color");
+ }
+
+ it("paints striped cells with the theme stripe color", () => {
+ renderWithProviders(<TestDataGrid striped theme={theme} />);
+
+ expect(getCellBackgroundColor(0, "name")).toBe("rgb(40, 50, 60)");
+ expect(getCellBackgroundColor(1, "name")).toBe("rgb(10, 20, 30)");
+ expect(getCellBackgroundColor(2, "name")).toBe("rgb(40, 50, 60)");
+ });
+
+ it("keeps column background colors on striped rows", () => {
+ renderWithProviders(<TestDataGrid striped theme={theme} />);
+
+ expect(getCellBackgroundColor(1, "category")).toBe("rgb(246, 255, 237)");
+ });
+
+ it("derives a stripe color from the cell background when none is set", () => {
+ const cellBackgroundColor = "rgb(40, 50, 60)";
+ renderWithProviders(
+ <TestDataGrid
+ striped
+ theme={{ cell: { backgroundColor: cellBackgroundColor } }}
+ />,
+ );
+
+ const stripe = getCellBackgroundColor(1, "name") ?? "";
+ expect(stripe).not.toBe(cellBackgroundColor);
+ expect(Color(stripe).lightness()).toBeGreaterThan(
+ Color(cellBackgroundColor).lightness(),
+ );
+ });
+
+ it("ignores the stripe color when striping is disabled", () => {
+ renderWithProviders(<TestDataGrid striped={false} theme={theme} />);
+
+ expect(getCellBackgroundColor(1, "name")).toBe("rgb(40, 50, 60)");
+ });
+ });
});
diff --git a/frontend/src/metabase/data-grid/components/DataGridRow/DataGridRow.tsx b/frontend/src/metabase/data-grid/components/DataGridRow/DataGridRow.tsx
index cd3d41b0098..6261b91639f 100644
--- a/frontend/src/metabase/data-grid/components/DataGridRow/DataGridRow.tsx
+++ b/frontend/src/metabase/data-grid/components/DataGridRow/DataGridRow.tsx
@@ -19,6 +19,7 @@ import type { DataGridStylesProps } from "../DataGrid/types";
export interface DataGridRowProps<TData> extends DataGridStylesProps {
row: DataGridRowType<TData>;
columns: DataGridColumnType<TData>[];
+ striped?: boolean;
rowMeasureRef?: ((element: Element | null) => void) | undefined;
zoomedRowIndex: number | undefined;
pinnedRowsCount: number;
@@ -35,6 +36,7 @@ export interface DataGridRowProps<TData> extends DataGridStylesProps {
export const DataGridRow = <TData,>({
row,
columns,
+ striped = false,
rowMeasureRef,
pinnedRowsCount,
zoomedRowIndex,
@@ -45,6 +47,9 @@ export const DataGridRow = <TData,>({
classNames,
styles,
}: DataGridRowProps<TData>) => {
+ // Use displayIndex rather than the origin row index so that stripes follow
+ // the rendered order
+ const isStriped = striped && row.displayIndex % 2 === 1;
const rowPositionStyles = getRowPositionStyles(row);
const paddingLeft = columns[0]?.virtualItem?.start ?? 0;
@@ -67,9 +72,11 @@ export const DataGridRow = <TData,>({
}}
data-allow-page-break-after="true"
data-row-selected={row.origin.getIsSelected()}
+ data-row-striped={isStriped ? "true" : undefined}
className={cx(
S.row,
{
+ [S.striped]: isStriped,
[S.withSeparator]: row.origin.index === pinnedRowsCount - 1,
[S.active]: zoomedRowIndex === row.origin.index,
},
@@ -109,6 +116,7 @@ export const DataGridRow = <TData,>({
{flexRender(columnDef.cell, {
...cell.getContext(),
isSelected: selection.isCellSelected(cell),
+ isStriped,
})}
</div>
);
diff --git a/frontend/src/metabase/data-grid/types.ts b/frontend/src/metabase/data-grid/types.ts
index 99baf41d8ba..b94a2ad9194 100644
--- a/frontend/src/metabase/data-grid/types.ts
+++ b/frontend/src/metabase/data-grid/types.ts
@@ -154,6 +154,9 @@ export interface DataGridTheme {
/** Background color of the table header that stays fixed while scrolling. Defaults to `white` if no cell background color is set */
stickyBackgroundColor?: string;
+ /** Background color of every other row when striping is enabled. Defaults to a subtle tint of the cell background */
+ stripedBackgroundColor?: string;
+
cell?: {
/** Text color default body cells, defaults to `text-primary`. */
textColor?: string;
diff --git a/frontend/src/metabase/data-grid/utils/columns/data-column.tsx b/frontend/src/metabase/data-grid/utils/columns/data-column.tsx
index 6d8416faec9..1709213352c 100644
--- a/frontend/src/metabase/data-grid/utils/columns/data-column.tsx
+++ b/frontend/src/metabase/data-grid/utils/columns/data-column.tsx
@@ -8,10 +8,12 @@ import { memo } from "react";
import { BodyCell } from "metabase/data-grid/components/BodyCell/BodyCell";
import { HeaderCell } from "metabase/data-grid/components/HeaderCell/HeaderCell";
import { MIN_COLUMN_WIDTH } from "metabase/data-grid/constants";
+import { useDataGridTheme } from "metabase/data-grid/hooks";
import type {
ColumnOptions,
ExpandedColumnsState,
} from "metabase/data-grid/types";
+import { getDefaultCellBackgroundColor } from "metabase/data-grid/utils/striped-background-color";
const getDefaultCellTemplate = <TRow, TValue>({
id,
@@ -26,11 +28,17 @@ const getDefaultCellTemplate = <TRow, TValue>({
editingCell: EditingCellComponent,
}: ColumnOptions<TRow, TValue>) => {
return function Cell(
- props: CellContext<TRow, TValue> & { isSelected?: boolean },
+ props: CellContext<TRow, TValue> & {
+ isSelected?: boolean;
+ isStriped?: boolean;
+ },
) {
- const { getValue, row, column, isSelected } = props;
+ const { getValue, row, column, isSelected, isStriped } = props;
+ const theme = useDataGridTheme();
const value = getValue();
- const backgroundColor = getBackgroundColor?.(value, row?.index);
+ const backgroundColor =
+ getBackgroundColor?.(value, row?.index) ??
+ getDefaultCellBackgroundColor(theme, isStriped);
const isEditing = getIsEditing?.(id, row.index);
// Read from column meta so the component identity can stay stable across
// column width changes (metabase#78557)
diff --git a/frontend/src/metabase/data-grid/utils/striped-background-color.ts b/frontend/src/metabase/data-grid/utils/striped-background-color.ts
new file mode 100644
index 00000000000..20f49e4581f
--- /dev/null
+++ b/frontend/src/metabase/data-grid/utils/striped-background-color.ts
@@ -0,0 +1,35 @@
+import { adjustBrightness, tryIsDark } from "metabase/ui/colors/palette";
+
+import type { DataGridTheme } from "../types";
+
+export const DEFAULT_STRIPED_BACKGROUND_COLOR =
+ "var(--mb-color-background-hover)";
+
+const STRIPE_LIGHTEN_BY = 0.08;
+const STRIPE_DARKEN_BY = 0.04;
+
+export function getDefaultCellBackgroundColor(
+ theme: DataGridTheme | undefined,
+ isStriped: boolean | undefined,
+): string | undefined {
+ return isStriped
+ ? getStripedBackgroundColor(theme)
+ : theme?.cell?.backgroundColor;
+}
+
+export function getStripedBackgroundColor(theme?: DataGridTheme): string {
+ if (theme?.stripedBackgroundColor) {
+ return theme.stripedBackgroundColor;
+ }
+
+ const cellBackgroundColor = theme?.cell?.backgroundColor;
+ if (!cellBackgroundColor || tryIsDark(cellBackgroundColor) == null) {
+ return DEFAULT_STRIPED_BACKGROUND_COLOR;
+ }
+
+ return adjustBrightness(
+ cellBackgroundColor,
+ STRIPE_LIGHTEN_BY,
+ STRIPE_DARKEN_BY,
+ );
+}
diff --git a/frontend/src/metabase/data-grid/utils/striped-background-color.unit.spec.ts b/frontend/src/metabase/data-grid/utils/striped-background-color.unit.spec.ts
new file mode 100644
index 00000000000..2f94fed5785
--- /dev/null
+++ b/frontend/src/metabase/data-grid/utils/striped-background-color.unit.spec.ts
@@ -0,0 +1,56 @@
+import Color from "color";
+
+import {
+ DEFAULT_STRIPED_BACKGROUND_COLOR,
+ getStripedBackgroundColor,
+} from "./striped-background-color";
+
+const lightness = (color: string) => Color(color).lightness();
+
+describe("getStripedBackgroundColor", () => {
+ it("uses the theme stripe color when set", () => {
+ expect(
+ getStripedBackgroundColor({
+ stripedBackgroundColor: "#abcdef",
+ cell: { backgroundColor: "#000000" },
+ }),
+ ).toBe("#abcdef");
+ });
+
+ it("falls back to the default when there is no cell background", () => {
+ expect(getStripedBackgroundColor(undefined)).toBe(
+ DEFAULT_STRIPED_BACKGROUND_COLOR,
+ );
+ expect(getStripedBackgroundColor({ cell: {} })).toBe(
+ DEFAULT_STRIPED_BACKGROUND_COLOR,
+ );
+ });
+
+ it("lightens a dark cell background", () => {
+ const cellBackgroundColor = "#2f3640";
+ const stripe = getStripedBackgroundColor({
+ cell: { backgroundColor: cellBackgroundColor },
+ });
+
+ expect(lightness(stripe)).toBeGreaterThan(lightness(cellBackgroundColor));
+ expect(Color(stripe).isDark()).toBe(true);
+ });
+
+ it("darkens a light cell background", () => {
+ const cellBackgroundColor = "#ffffff";
+ const stripe = getStripedBackgroundColor({
+ cell: { backgroundColor: cellBackgroundColor },
+ });
+
+ expect(lightness(stripe)).toBeLessThan(lightness(cellBackgroundColor));
+ expect(Color(stripe).isLight()).toBe(true);
+ });
+
+ it("falls back to the default for CSS expressions it cannot parse", () => {
+ expect(
+ getStripedBackgroundColor({
+ cell: { backgroundColor: "var(--mb-color-background_page-primary)" },
+ }),
+ ).toBe(DEFAULT_STRIPED_BACKGROUND_COLOR);
+ });
+});
diff --git a/frontend/src/metabase/ui/colors/palette.ts b/frontend/src/metabase/ui/colors/palette.ts
index dbf2ca63624..6e4c13db303 100644
--- a/frontend/src/metabase/ui/colors/palette.ts
+++ b/frontend/src/metabase/ui/colors/palette.ts
@@ -119,6 +119,15 @@ export const isDark = (c: string) => {
return Color(color(c)).isDark();
};
+/** Returns undefined for CSS expressions or variables, which cannot be parsed */
+export const tryIsDark = (c: string): boolean | undefined => {
+ try {
+ return isDark(c);
+ } catch {
+ return undefined;
+ }
+};
+
/**
* Lighten or darken the color, based on whether it's dark or light.
* Can be used for deriving hover or highlight colors.
diff --git a/frontend/src/metabase/ui/component-theme.ts b/frontend/src/metabase/ui/component-theme.ts
index 74770c58c6c..cf02421982a 100644
--- a/frontend/src/metabase/ui/component-theme.ts
+++ b/frontend/src/metabase/ui/component-theme.ts
@@ -65,6 +65,9 @@ export type MetabaseComponentTheme = {
/** Background color of the table header that stays fixed while scrolling. Defaults to `white` if no cell background color is set */
stickyBackgroundColor?: string;
+ /** Background color of every other row when the "Striped rows" table setting is enabled. Defaults to a subtle tint of the cell background color */
+ stripedBackgroundColor?: string;
+
cell: {
/** Text color of cells, defaults to `text-primary`. */
textColor: string;
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
index 17c4d29ef17..fc21c788d73 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/TableInteractive.tsx
@@ -42,6 +42,7 @@ import type {
PlainCellFormatter,
RowIdColumnOptions,
} from "metabase/data-grid/types";
+import { getDefaultCellBackgroundColor } from "metabase/data-grid/utils/striped-background-color";
import { useDispatch } from "metabase/redux";
import { setUIControls } from "metabase/redux/query-builder";
import { Flex, type MantineTheme } from "metabase/ui";
@@ -503,6 +504,11 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
};
}, [isRawTable, mode, onVisualizationClick, question, isPivoted]);
+ const dataGridTheme: DataGridTheme = useMemo(
+ () => tableThemeToDataGridTheme(tableTheme, theme?.other?.fontSize),
+ [tableTheme, theme?.other?.fontSize],
+ );
+
const columnsOptions: ColumnOptions<RowValues, RowValue>[] = useMemo(() => {
return cols.map((col, columnIndex) => {
const columnSettings = settings.column?.(col) ?? {};
@@ -513,13 +519,8 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
const isImage = columnSettings["view_as"] === "image";
const headerVariant =
hasColumnReordering || isDashboard ? "light" : "outline";
- const getBackgroundColor = memoize(
- (value: RowValue, rowIndex: number) =>
- settings["table._cell_background_getter"]?.(
- value,
- rowIndex,
- col.name,
- ) ?? tableTheme?.cell?.backgroundColor,
+ const getBackgroundColor = memoize((value: RowValue, rowIndex: number) =>
+ settings["table._cell_background_getter"]?.(value, rowIndex, col.name),
);
const formatter = columnFormatters[columnIndex];
@@ -603,9 +604,12 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
options.cell = ({
getValue,
row,
- }: CellContext<RowValues, RowValue>) => {
+ isStriped,
+ }: CellContext<RowValues, RowValue> & { isStriped?: boolean }) => {
const value = getValue();
- const backgroundColor = getBackgroundColor(value, row?.index);
+ const backgroundColor =
+ getBackgroundColor(value, row?.index) ??
+ getDefaultCellBackgroundColor(dataGridTheme, isStriped);
const columnExtent = getColumnExtent(cols, rows, columnIndex);
const isHighlighted = highlightedCellKeys.has(
getHighlightedTableCellKey({ rowIndex: row.index, columnIndex }),
@@ -645,7 +649,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
isPivoted,
rows,
settings,
- tableTheme,
+ dataGridTheme,
isDashboard,
tc,
highlightedCellKeys,
@@ -726,11 +730,6 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
zoomedRowIndex,
]);
- const dataGridTheme: DataGridTheme = useMemo(
- () => tableThemeToDataGridTheme(tableTheme, theme?.other?.fontSize),
- [tableTheme, theme?.other?.fontSize],
- );
-
const dataGridStyles: DataGridStylesProps["styles"] = useMemo(() => {
return {
footer: {
@@ -894,6 +893,7 @@ export const TableInteractiveInner = forwardRef(function TableInteractiveInner(
>
<DataGrid
{...tableProps}
+ striped={settings["table.striped"]}
styles={dataGridStyles}
showRowsCount={isDashboard}
formatRowsCountMessage={formatRowsCountMessage}
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
index 6d142faedc3..e74bcbe82ac 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.ts
@@ -9,11 +9,10 @@ export function tableThemeToDataGridTheme(
): DataGridTheme {
return {
stickyBackgroundColor: tableTheme.stickyBackgroundColor,
+ stripedBackgroundColor: tableTheme.stripedBackgroundColor,
fontSize: resolveFontSizeToPx(tableTheme.cell.fontSize, baseFontSize),
cell: {
- backgroundColor:
- tableTheme.cell.backgroundColor ??
- "var(--mb-color-background_page-primary)",
+ backgroundColor: tableTheme.cell.backgroundColor,
textColor: tableTheme.cell.textColor,
},
pillCell: {
diff --git a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
index 6e296c9b13d..20f8fd6bef7 100644
--- a/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
+++ b/frontend/src/metabase/visualizations/components/TableInteractive/utils/table-theme-to-data-grid-theme.unit.spec.ts
@@ -5,6 +5,7 @@ import { tableThemeToDataGridTheme } from "./table-theme-to-data-grid-theme";
describe("tableThemeToDataGridTheme", () => {
const mockTableTheme: MantineTheme["other"]["table"] = {
stickyBackgroundColor: "#ffffff",
+ stripedBackgroundColor: "#eeeeee",
cell: {
fontSize: "14px",
backgroundColor: "#f5f5f5",
@@ -21,6 +22,7 @@ describe("tableThemeToDataGridTheme", () => {
expect(result).toEqual({
stickyBackgroundColor: "#ffffff",
+ stripedBackgroundColor: "#eeeeee",
fontSize: "14px",
cell: {
backgroundColor: "#f5f5f5",
@@ -33,7 +35,7 @@ describe("tableThemeToDataGridTheme", () => {
});
});
- it("replaces transparent backgroundColor with CSS variable", () => {
+ it("leaves cell.backgroundColor unset when the theme has none", () => {
const themeWithoutCellBg = {
...mockTableTheme,
cell: { ...mockTableTheme.cell, backgroundColor: undefined },
@@ -41,15 +43,7 @@ describe("tableThemeToDataGridTheme", () => {
const result = tableThemeToDataGridTheme(themeWithoutCellBg);
- expect(result.cell?.backgroundColor).toBe(
- "var(--mb-color-background_page-primary)",
- );
- });
-
- it("prefers cell.backgroundColor over provided backgroundColor", () => {
- const result = tableThemeToDataGridTheme(mockTableTheme);
-
- expect(result.cell?.backgroundColor).toBe("#f5f5f5");
+ expect(result.cell?.backgroundColor).toBeUndefined();
});
it("handles missing idColumn", () => {
diff --git a/frontend/src/metabase/visualizations/visualizations/Table/Table.stories.tsx b/frontend/src/metabase/visualizations/visualizations/Table/Table.stories.tsx
index 20519be9475..a6c33e22542 100644
--- a/frontend/src/metabase/visualizations/visualizations/Table/Table.stories.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Table/Table.stories.tsx
@@ -199,6 +199,90 @@ export const DashboardTable = {
},
};
+const stripedOrdersWithPeople = [
+ {
+ ...ordersWithPeople,
+ card: {
+ ...ordersWithPeople.card,
+ visualization_settings: {
+ ...ordersWithPeople.card.visualization_settings,
+ "table.striped": true,
+ },
+ },
+ },
+];
+
+export const DashboardTableStripedRows = {
+ render: DefaultTemplate,
+ args: {
+ series: stripedOrdersWithPeople,
+ isDashboard: true,
+ },
+};
+
+export const TableStripedRows = {
+ render: DefaultTemplate,
+ args: {
+ series: stripedOrdersWithPeople,
+ },
+};
+
+export const DashboardTableStripedRowsEmbeddingTheme = {
+ render: DefaultTemplate,
+ args: {
+ series: stripedOrdersWithPeople,
+ isDashboard: true,
+ theme: {
+ components: {
+ table: {
+ cell: { textColor: "#dfe4ea", backgroundColor: "#2f3640" },
+ },
+ },
+ },
+ hasDevWatermark: false,
+ },
+};
+
+export const DashboardTableStripedRowsEmbeddingThemeStripeColor = {
+ render: DefaultTemplate,
+ args: {
+ series: stripedOrdersWithPeople,
+ isDashboard: true,
+ theme: {
+ components: {
+ table: {
+ cell: { textColor: "#dfe4ea", backgroundColor: "#2f3640" },
+ stripedBackgroundColor: "#4b3a5a",
+ },
+ },
+ },
+ hasDevWatermark: false,
+ },
+};
+
+const STRIPED_CONDITIONAL_FORMATTING_SERIES = CONDITIONA_FORMATTING_SERIES.map(
+ (series) => ({
+ ...series,
+ card: {
+ ...series.card,
+ visualization_settings: {
+ ...series.card.visualization_settings,
+ "table.striped": true,
+ },
+ },
+ }),
+);
+
+export const StripedRowsWithConditionalFormatting = {
+ parameters: {
+ layout: "fullscreen",
+ },
+ render: ColumnFormattingTemplate,
+ args: {
+ series: STRIPED_CONDITIONAL_FORMATTING_SERIES,
+ },
+};
+
export const DashboardTableEmbeddingTheme = {
render: DefaultTemplate,
args: {
diff --git a/frontend/src/metabase/visualizations/visualizations/Table/Table.unit.spec.tsx b/frontend/src/metabase/visualizations/visualizations/Table/Table.unit.spec.tsx
index a7e565ab551..4a35877e263 100644
--- a/frontend/src/metabase/visualizations/visualizations/Table/Table.unit.spec.tsx
+++ b/frontend/src/metabase/visualizations/visualizations/Table/Table.unit.spec.tsx
@@ -325,6 +325,84 @@ describe("dashboard client-side sorting", () => {
});
});
+describe("table.striped", () => {
+ beforeAll(() => {
+ mockGetBoundingClientRect();
+ });
+
+ it("should be a display toggle disabled by default", () => {
+ const setting = Table.settings["table.striped"];
+
+ expect(setting).toBeDefined();
+ expect(setting.widget).toBe("toggle");
+ expect(setting.inline).toBe(true);
+ expect(setting.getDefault?.()).toBe(false);
+ });
+
+ function setupStripedTable() {
+ const series = [
+ createMockSingleSeries(
+ { display: "table" },
+ {
+ data: {
+ cols: [createMockNumericColumn({ display_name: "id", name: "id" })],
+ rows: [[1], [2], [3], [4]],
+ },
+ },
+ ),
+ ];
+
+ series[0].card.visualization_settings = {
+ ...series[0].card.visualization_settings,
+ "table.striped": true,
+ };
+
+ renderWithProviders(
+ <Visualization rawSeries={series} isDashboard width={600} height={400} />,
+ );
+ }
+
+ function getStripedRows() {
+ return screen
+ .getAllByRole("row")
+ .slice(1)
+ .map((row) => [
+ within(row).getAllByRole("gridcell")[0].textContent,
+ row.getAttribute("data-row-striped") === "true",
+ ]);
+ }
+
+ it("stripes every other rendered row", () => {
+ setupStripedTable();
+
+ expect(getStripedRows()).toEqual([
+ ["1", false],
+ ["2", true],
+ ["3", false],
+ ["4", true],
+ ]);
+ });
+
+ it("keeps stripes on alternating rendered rows after client-side sorting (#71960)", () => {
+ setupStripedTable();
+
+ const idHeader = screen.getByRole("columnheader", { name: "id" });
+ const clickTarget = within(idHeader).getByTestId("cell-data");
+
+ fireEvent.mouseDown(clickTarget, { clientX: 0, clientY: 0 });
+ fireEvent.mouseUp(clickTarget, { clientX: 0, clientY: 0 });
+
+ // Rows are now in descending order; the stripes must still alternate by
+ // display position rather than by position in the original dataset.
+ expect(getStripedRows()).toEqual([
+ ["4", false],
+ ["3", true],
+ ["2", false],
+ ["1", true],
+ ]);
+ });
+});
+
describe("text_wrapping", () => {
describe("line breaks in cells (#6178, #64697)", () => {
beforeAll(() => {
diff --git a/frontend/src/metabase/visualizations/visualizations/Table/definition.ts b/frontend/src/metabase/visualizations/visualizations/Table/definition.ts
index d01d3afecbf..a91263f6c9d 100644
--- a/frontend/src/metabase/visualizations/visualizations/Table/definition.ts
+++ b/frontend/src/metabase/visualizations/visualizations/Table/definition.ts
@@ -78,6 +78,15 @@ export const TABLE_DEFINITION = {
widget: "toggle",
getDefault: () => false,
},
+ "table.striped": {
+ getSection: () => t`Display`,
+ get title() {
+ return t`Striped rows`;
+ },
+ inline: true,
+ widget: "toggle",
+ getDefault: () => false,
+ },
"table.freeze_columns": {
getSection: () => t`Display`,
get title() {
diff --git a/src/metabase/channel/render/style.clj b/src/metabase/channel/render/style.clj
index e73fa479eb4..e00d35d5f7d 100644
--- a/src/metabase/channel/render/style.clj
+++ b/src/metabase/channel/render/style.clj
@@ -83,6 +83,10 @@
"Background fill for the row-label cells of a rendered `:pivot` table."
"#FAFAFA")
+(def ^:const color-row-stripe-bg
+ "Background fill for alternating rows of a rendered `:table` when `table.striped` is enabled."
+ "#F9FBFC")
+
;; don't try to improve the code and make this a plain variable, in EE it's customizable which is why it's a function.
;; Too much of a hassle to have it be a fn in one version of the code an a constant in another
(defn primary-color
diff --git a/src/metabase/channel/render/table.clj b/src/metabase/channel/render/table.clj
index 411b90fd835..ba7861cddd3 100644
--- a/src/metabase/channel/render/table.clj
+++ b/src/metabase/channel/render/table.clj
@@ -202,43 +202,51 @@
- viz-settings: Viz settings
- minibar-cols: Columns that should display mini-bar visualizations instead of raw values
- col->styles: Map of column names to their style specifications
- - row-index?: Boolean flag to include row index numbers (1-based)"
- [get-background-color column-names rows columns viz-settings minibar-cols col->styles row-index?]
+ - row-index?: Boolean flag to include row index numbers (1-based)
+ - striped?: Boolean flag to shade alternating rows"
+ [get-background-color column-names rows columns viz-settings minibar-cols col->styles row-index? striped?]
[:tbody
(for [[row-idx {:keys [row]}] (m/indexed rows)]
- [:tr {:style (style/style {:color style/color-gray-3})}
- (when row-index?
- [:td {:style (style/style
- (bar-td-row-index-style)
- (when (= row-idx (dec (count rows)))
- {:border-bottom 0}))}
- (inc row-idx)])
- (for [[col-idx cell] (m/indexed row)]
- (let [column (nth columns col-idx)
- column-name (get column-names col-idx)
- minibar-col (first (filter #(= (:name column) (:name %)) minibar-cols))
- col-settings (get-in viz-settings [::mb.viz/column-settings {::mb.viz/column-name column-name}] {})]
+ (let [stripe-bg (when (and striped? (odd? row-idx))
+ style/color-row-stripe-bg)]
+ [:tr {:style (style/style (cond-> {:color style/color-gray-3}
+ stripe-bg (assoc :background-color stripe-bg)))}
+ (when row-index?
[:td {:style (style/style
- (row-style-for-type cell)
- (get col->styles (:name column))
- {:background-color (get-background-color row-idx col-idx)}
+ (bar-td-row-index-style)
+ (when stripe-bg
+ {:background-color stripe-bg})
(when (= row-idx (dec (count rows)))
- {:border-bottom 0})
- (when (= col-idx (dec (count row)))
- {:border-right 0}))}
- (cond
- ;; Minibar column
- (some? minibar-col)
- (render-minibar cell (get-in minibar-col [:fingerprint :type :type/Number]) (get col->styles (:name column)))
-
- ;; View as image
- (and (= (get col-settings ::mb.viz/view-as) "image")
- (image-url? cell))
- [:img {:src (h cell)
- :style (style/style style/view-as-img-style)}]
-
- :else
- (h cell))]))])])
+ {:border-bottom 0}))}
+ (inc row-idx)])
+ (for [[col-idx cell] (m/indexed row)]
+ (let [column (nth columns col-idx)
+ column-name (get column-names col-idx)
+ minibar-col (first (filter #(= (:name column) (:name %)) minibar-cols))
+ col-settings (get-in viz-settings [::mb.viz/column-settings {::mb.viz/column-name column-name}] {})]
+ [:td {:style (style/style
+ (row-style-for-type cell)
+ (get col->styles (:name column))
+ ;; conditional formatting colors win over the stripe background
+ {:background-color (or (get-background-color row-idx col-idx)
+ stripe-bg)}
+ (when (= row-idx (dec (count rows)))
+ {:border-bottom 0})
+ (when (= col-idx (dec (count row)))
+ {:border-right 0}))}
+ (cond
+ ;; Minibar column
+ (some? minibar-col)
+ (render-minibar cell (get-in minibar-col [:fingerprint :type :type/Number]) (get col->styles (:name column)))
+
+ ;; View as image
+ (and (= (get col-settings ::mb.viz/view-as) "image")
+ (image-url? cell))
+ [:img {:src (h cell)
+ :style (style/style style/view-as-img-style)}]
+
+ :else
+ (h cell))]))]))])
(defn- get-min-width
"Get the min width for a column with text wrapping enabled. In the happy path, column widths are supplied in viz settings
@@ -327,6 +335,7 @@
([color-data {:keys [col-names cols-for-color-lookup]} [header & rows] columns viz-settings minibar-cols]
(let [col->styles (column->viz-setting-styles columns viz-settings)
row-index? (:table.row_index viz-settings)
+ striped? (boolean (:table.striped viz-settings))
pivot-grouping-idx (u/index-of #{"pivot-grouping"} col-names)
col-names (cond->> col-names
pivot-grouping-idx (m/remove-nth pivot-grouping-idx))
@@ -346,7 +355,7 @@
(mapv second keyed-cells)))
color-getter (fn [row-idx col-idx] (get cell-colors [row-idx col-idx]))
thead (render-table-head (vec col-names) header columns col->styles row-index?)
- tbody (render-table-body color-getter cols-for-color-lookup rows columns viz-settings minibar-cols col->styles row-index?)]
+ tbody (render-table-body color-getter cols-for-color-lookup rows columns viz-settings minibar-cols col->styles row-index? striped?)]
[:table {:style (style/style {:max-width "100%"
:white-space "nowrap"
:border (str "1px solid " style/color-border)
diff --git a/test/metabase/channel/render/table_test.clj b/test/metabase/channel/render/table_test.clj
index d3c67c4c618..5c6a9a3d388 100644
--- a/test/metabase/channel/render/table_test.clj
+++ b/test/metabase/channel/render/table_test.clj
@@ -6,6 +6,7 @@
[hickory.core :as hik]
[hickory.select :as hik.s]
[metabase.channel.render.core :as channel.render]
+ [metabase.channel.render.style :as style]
[metabase.channel.render.table :as table]
[metabase.formatter.core :as formatter]
[metabase.models.visualization-settings :as mb.viz]
@@ -237,6 +238,47 @@
(map #(first (:content %)) td-els))
"Body should include row indices as first column")))))))
+(deftest table-striped-rows-test
+ (mt/dataset test-data
+ (let [q (str "SELECT 1 AS A, 2 AS B"
+ " UNION ALL SELECT 3 AS A, 4 AS B"
+ " UNION ALL SELECT 5 AS A, 6 AS B"
+ " UNION ALL SELECT 7 AS A, 8 AS B")
+ body-row-backgrounds
+ (fn [viz]
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query {:database (mt/id)
+ :type :native
+ :native {:query q}}
+ :visualization_settings viz}]
+ (let [doc (render.tu/render-card-as-hickory! card-id)
+ tbodies (hik.s/select (hik.s/tag :tbody) doc)
+ rows (mapcat #(hik.s/select (hik.s/tag :tr) %) tbodies)]
+ (mapv (fn [row-el]
+ (->> (hik.s/select (hik.s/tag :td) row-el)
+ (mapv #(get-in % [:attrs :style]))
+ (every? (fn [style]
+ (str/includes? (or style "")
+ (str "background-color: " style/color-row-stripe-bg))))))
+ rows))))]
+ (testing "Alternating rows are shaded when table.striped is enabled"
+ (is (= [false true false true]
+ (body-row-backgrounds {:table.striped true}))))
+ (testing "Row index column also gets the stripe background"
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query {:database (mt/id)
+ :type :native
+ :native {:query q}}
+ :visualization_settings {:table.striped true
+ :table.row_index true}}]
+ (let [doc (render.tu/render-card-as-hickory! card-id)
+ tbodies (hik.s/select (hik.s/tag :tbody) doc)
+ rows (mapcat #(hik.s/select (hik.s/tag :tr) %) tbodies)
+ second-row-first-cell (first (hik.s/select (hik.s/tag :td) (second rows)))]
+ (is (str/includes? (get-in second-row-first-cell [:attrs :style])
+ (str "background-color: " style/color-row-stripe-bg))))))
+ (testing "No rows are shaded when table.striped is disabled or absent"
+ (is (every? false? (body-row-backgrounds {:table.striped false})))
+ (is (every? false? (body-row-backgrounds {})))))))
+
(deftest table-minibar-test
(mt/dataset test-data
(let [q (str "SELECT 5 AS A, 5 AS B"