An open source design system that's fully customizable and agent ready
TypeScript
fix(Table): a plugin can suppress a body cell's content, so group headers never reach your cell renderers (#5363)
Cindy Zhang88f38f823c8a
diff --git a/.changeset/table-suppress-cell-content.md b/.changeset/table-suppress-cell-content.mdnew file mode 100644index 0000000000..2b04dbf936--- /dev/null+++ b/.changeset/table-suppress-cell-content.md@@ -0,0 +1,22 @@+---+'@astryxdesign/core': patch+---++[fix] Table: a plugin can suppress a body cell's content, and grouped rows use it to keep synthetic group headers out of your cell renderers (#5363)++`useTableGroupedRows` injects section-header rows into the flattened data, and+`BaseTable` evaluates every column's `renderCell` against every row. A renderer+that keys a lookup off a field — `STATUS_META[item.status].dot` — was therefore+handed a row that is not yours and threw, blanking the page the moment grouping+was switched on. The header Proxy answering unknown fields with `''` only ever+rescued a renderer that _prints_ a field; `''` fails a lookup exactly as+`undefined` does.++`BodyCellRenderProps` gains `isContentSuppressed?: boolean`. A plugin sets it in+`transformBodyCell` for a row whose cells it is about to replace wholesale in+`transformBodyRow`, and the table renders that cell empty without calling the+column's renderer or the default one. It is decided per cell at render time+against the final column list, so it also covers columns other plugins+contributed — whatever order the plugins were listed in.++@ernesttdiff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsxindex 2420413be5..d58f56a6dc 100644--- a/packages/core/src/Table/BaseTable.tsx+++ b/packages/core/src/Table/BaseTable.tsx@@ -183,9 +183,12 @@ function TableRowInner<T extends Record<string, unknown>>({);const isDefaultRenderer = !col.renderCell;- const rawContent = isDefaultRenderer- ? defaultCellRenderer(item, col.key)- : (col.renderCell?.(item) ?? null);+ let rawContent: ReactNode = null;+ if (!cellRenderProps.isContentSuppressed) {+ rawContent = isDefaultRenderer+ ? defaultCellRenderer(item, col.key)+ : (col.renderCell?.(item) ?? null);+ }// In truncate mode, wrap default-rendered string content in// <Text maxLines={1}> for smart tooltips that only appeardiff --git a/packages/core/src/Table/Table.test.tsx b/packages/core/src/Table/Table.test.tsxindex 4922462b5b..ae83dd1112 100644--- a/packages/core/src/Table/Table.test.tsx+++ b/packages/core/src/Table/Table.test.tsx@@ -602,6 +602,41 @@ describe('BaseTable', () => {expect(calls[0]).toEqual({col: 'name', name: 'Alice'});});+ it('isContentSuppressed renders an empty cell and never calls the column renderer', () => {+ const rendered: string[] = [];+ const withRenderer: TableColumn<User>[] = [+ {+ key: 'name',+ header: 'Name',+ renderCell: item => {+ rendered.push(item.name);+ return <b>{item.name}</b>;+ },+ },+ ];+ const plugin: TablePlugin<User> = {+ transformBodyCell: (props, _column, item) =>+ item.name === 'Bob' ? {...props, isContentSuppressed: true} : props,+ };+ render(+ <BaseTable data={users} columns={withRenderer} plugins={[plugin]} />,+ );+ expect(rendered).toEqual(['Alice', 'Charlie']);+ const cells = screen.getAllByRole('cell');+ expect(cells[1]).toBeEmptyDOMElement();+ expect(cells[0]).toHaveTextContent('Alice');+ });++ it('isContentSuppressed also suppresses the default renderer', () => {+ const plugin: TablePlugin<User> = {+ transformBodyCell: props => ({...props, isContentSuppressed: true}),+ };+ render(<BaseTable data={users} columns={columns} plugins={[plugin]} />);+ for (const cell of screen.getAllByRole('cell')) {+ expect(cell).toBeEmptyDOMElement();+ }+ });+it('composes multiple plugins sequentially', () => {const plugin1: TablePlugin<User> = {transformTable: props => ({diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows-perf.test.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows-perf.test.tsxnew file mode 100644index 0000000000..a83136b054--- /dev/null+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows-perf.test.tsx@@ -0,0 +1,112 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file useTableGroupedRows-perf.test.tsx+ * @input Table, useTableGroupedRows, React testing utilities+ * @output Performance tests for grouped-rows render behavior+ * @position Test file; validates that grouping costs no extra row renders+ *+ * The plugin keeps group headers out of cell renderers per cell, at render+ * time. Doing it by rewriting the columns instead would hand BaseTable a new+ * column object on every render, and its element-by-element check on the+ * resolved column array is what stops every row re-rendering.+ */++import {describe, it, expect} from 'vitest';+import {render, screen, act} from '@testing-library/react';+import {useCallback, useMemo, useState} from 'react';+import userEvent from '@testing-library/user-event';+import {Table} from '../../Table';+import type {TableColumn} from '../../types';+import {useTableGroupedRows} from './useTableGroupedRows';++interface Person extends Record<string, unknown> {+ id: string;+ name: string;+ team: string;+}++const people: Person[] = [+ {id: 'a', name: 'Alice', team: 'Core'},+ {id: 'b', name: 'Bob', team: 'Core'},+ {id: 'c', name: 'Carol', team: 'Infra'},+];++const EMPTY = new Set<string>();++function GroupedRenderCountTable({+ renderCounts,+}: {+ renderCounts: Record<string, number>;+}) {+ const [tick, setTick] = useState(0);+ const [collapsedGroups, setCollapsedGroups] = useState<Set<string>>(EMPTY);++ const columns = useMemo<TableColumn<Person>[]>(+ () => [+ {+ key: 'name',+ header: 'Name',+ renderCell: (item: Person) => {+ renderCounts[item.id] = (renderCounts[item.id] ?? 0) + 1;+ return item.name;+ },+ },+ ],+ [renderCounts],+ );++ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: useCallback((p: Person) => p.team, []),+ collapsedGroups,+ onToggleGroup: useCallback(+ (key: string) =>+ setCollapsedGroups(prev => {+ const next = new Set(prev);+ if (!next.delete(key)) {+ next.add(key);+ }+ return next;+ }),+ [],+ ),+ getRowKey: useCallback((p: Person) => p.id, []),+ });++ return (+ <>+ <button type="button" onClick={() => setTick(t => t + 1)}>+ bump {tick}+ </button>+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ plugins={{grouped: grouped.plugin}}+ />+ </>+ );+}++describe('Grouped rows render performance', () => {+ it('renders each real row once and no group header at all', () => {+ const renderCounts: Record<string, number> = {};+ render(<GroupedRenderCountTable renderCounts={renderCounts} />);+ expect(renderCounts).toEqual({a: 1, b: 1, c: 1});+ });++ it('a re-render of the surrounding component re-renders no rows', async () => {+ const user = userEvent.setup();+ const renderCounts: Record<string, number> = {};+ render(<GroupedRenderCountTable renderCounts={renderCounts} />);+ const before = {...renderCounts};++ await act(async () => {+ await user.click(screen.getByRole('button', {name: /bump/}));+ });++ expect(screen.getByRole('button', {name: 'bump 1'})).toBeInTheDocument();+ expect(renderCounts).toEqual(before);+ });+});diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsxindex cc5bffd7da..305f224f5e 100644--- a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsx+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.test.tsx@@ -5,6 +5,7 @@ import {render, screen, fireEvent, within} from '@testing-library/react';import {useState, useCallback} from 'react';import {Table} from '../../Table';import type {TableColumn} from '../../types';+import {useTableRowStatus, type TableRowStatus} from '../rowStatus';import {useTableGroupedRows} from './useTableGroupedRows';interface Person extends Record<string, unknown> {@@ -175,6 +176,105 @@ describe('useTableGroupedRows', () => {).not.toBeInTheDocument();});+ it('never runs a column renderCell against a group header row', () => {+ // The renderer that breaks: it keys a lookup off a field rather than+ // printing it, so the header Proxy answering `''` is no better than+ // `undefined`.+ const TEAM_META: Record<string, {dot: string}> = {+ Core: {dot: 'green'},+ Infra: {dot: 'blue'},+ };+ const seen: Person[] = [];+ const lookupColumns: TableColumn<Person>[] = [+ {+ key: 'team',+ header: 'Team',+ renderCell: item => {+ seen.push(item);+ return <span>{TEAM_META[item.team].dot}</span>;+ },+ },+ ];++ function LookupHarness() {+ const [collapsed, setCollapsed] = useState<Set<string>>(EMPTY);+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups: collapsed,+ onToggleGroup: k => setCollapsed(new Set([k])),+ getRowKey: p => p.id,+ });+ return (+ <Table+ data={grouped.data}+ columns={lookupColumns}+ idKey={grouped.idKey}+ plugins={{grouped: grouped.plugin}}+ />+ );+ }++ expect(() => render(<LookupHarness />)).not.toThrow();+ expect(seen.map(p => p.name)).toEqual(['Alice', 'Bob', 'Carol']);+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.getByText('Infra')).toBeInTheDocument();+ });++ describe.each([+ ['grouped first', true],+ ['rowStatus first', false],+ ])(+ 'with a column contributed by another plugin (%s)',+ (_label, groupedFirst) => {+ // `grouped` and `rowStatus` are both absent from PLUGIN_ORDER, so the+ // record's insertion order is the pipeline order. Whichever way round+ // the consumer types it, the status column's renderCell must not see a+ // header row.+ const STATUS_BY_TEAM: Record<string, TableRowStatus> = {+ Core: {color: 'success', label: 'Healthy'},+ Infra: {color: 'error', label: 'Paging'},+ };++ function StatusHarness() {+ const [collapsed, setCollapsed] = useState<Set<string>>(EMPTY);+ const grouped = useTableGroupedRows<Person>({+ data: people,+ groupBy: p => p.team,+ collapsedGroups: collapsed,+ onToggleGroup: k => setCollapsed(new Set([k])),+ getRowKey: p => p.id,+ });+ const rowStatus = useTableRowStatus<Person>({+ getStatus: useCallback((item: Person) => {+ const {color, label} = STATUS_BY_TEAM[item.team];+ return {color, label};+ }, []),+ });+ return (+ <Table+ data={grouped.data}+ columns={columns}+ idKey={grouped.idKey}+ plugins={+ groupedFirst+ ? {grouped: grouped.plugin, rowStatus}+ : {rowStatus, grouped: grouped.plugin}+ }+ />+ );+ }++ it('renders the group headers without throwing', () => {+ expect(() => render(<StatusHarness />)).not.toThrow();+ expect(screen.getByText('Core')).toBeInTheDocument();+ expect(screen.getByText('Infra')).toBeInTheDocument();+ // One indicator per real row, none on the two headers.+ expect(screen.getAllByRole('img')).toHaveLength(3);+ });+ },+ );+it('keeps a group collapsed across a data change (state keyed by group)', () => {function ChangingHarness() {const [collapsed, setCollapsed] = useState<Set<string>>(diff --git a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsxindex 804e30495a..5edb1a1194 100644--- a/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx+++ b/packages/core/src/Table/plugins/groupedRows/useTableGroupedRows.tsx@@ -41,8 +41,11 @@ function isGroupHeader(item: unknown): item is GroupHeader {);}-// Proxy handler: any field access beyond the marker fields resolves to `''`-// so user cell renderers (`item.name.toUpperCase()`) never throw on a header.+// Proxy handler: any field access beyond the marker fields resolves to `''`,+// which keeps anything that reads a header's data — the sortable and filtering+// plugins, a consumer's own row handler — off `undefined`. Cell renderers are+// handled at render time instead (see `transformBodyCell` below); the Proxy+// never protected them, because `''` fails a lookup exactly as `undefined` does.const HEADER_PROXY_HANDLER: ProxyHandler<Record<string | symbol, unknown>> = {// eslint-disable-next-line @typescript-eslint/promise-function-async -- Proxy get trap, not a promise-returning fnget(t: Record<string | symbol, unknown>, prop: string | symbol): unknown {@@ -54,12 +57,9 @@ const HEADER_PROXY_HANDLER: ProxyHandler<Record<string | symbol, unknown>> = {};/**- * Build a synthetic header row wrapped in a Proxy so arbitrary field access- * from user cell renderers (e.g. `item.name.toUpperCase()`) resolves to `''`- * instead of throwing — BaseTable evaluates `col.renderCell(item)` on every- * row (including synthetic headers) before `transformBodyRow` can replace the- * row's cells. `transformBodyRow` then discards those cells and renders a- * single full-width header cell.+ * Build a synthetic header row wrapped in a Proxy so field access resolves to+ * `''` instead of `undefined`. `transformBodyRow` then discards the row's+ * cells and renders a single full-width header cell.*/function makeHeader<T extends Record<string, unknown>>(groupKey: string,@@ -301,6 +301,15 @@ export function useTableGroupedRows<T extends Record<string, unknown>>(const plugin = useMemo((): TablePlugin<T> => ({+ // A header row is not one of the caller's rows, so running a cell+ // renderer against it can only misread it or throw — and the cells are+ // discarded by `transformBodyRow` below regardless.+ transformBodyCell(props, _column, item) {+ if (!isGroupHeader(item)) {+ return props;+ }+ return {...props, isContentSuppressed: true};+ },// Replace a header row's pre-rendered cells with one full-width cell.transformBodyRow(props, item) {if (!isGroupHeader(item)) {diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.tsindex 2b73fed981..ee936beabe 100644--- a/packages/core/src/Table/types.ts+++ b/packages/core/src/Table/types.ts@@ -322,6 +322,19 @@ export interface BodyCellRenderProps {* sticky offsets. Optional for backward compatibility.*/columns?: ReadonlyArray<TableColumn<Record<string, unknown>>>;+ /**+ * When true, the cell renders empty: BaseTable calls neither the column's+ * `renderCell` nor the default renderer. Set it for a row whose cells a+ * plugin is going to replace wholesale in `transformBodyRow` (a grouped-rows+ * section header, a summary row) — the row is not one the consumer supplied,+ * so their renderer can only misread it or throw, and its output is+ * discarded moments later anyway.+ *+ * Applies to this cell only, and is decided per render against the final+ * column list, so it covers columns other plugins contributed regardless of+ * where in the pipeline this plugin sits.+ */+ isContentSuppressed?: boolean;}/**@@ -414,13 +427,18 @@ export type TableContextActions =** 1. `transformColumns` — filter, reorder, or inject columns before rendering* 2. `transformTable` — transform the root `<table>` element props- * 3. `transformHeaderRow` — transform the header `<tr>` props- * 4. `transformHeaderCell` — transform each `<th>` props- * 5. `transformBodyRow` — transform each body `<tr>` props- * 6. `transformBodyCell` — transform each body `<td>` props+ * 3. `transformHeaderCell` — transform each `<th>` props+ * 4. `transformHeaderRow` — transform the header `<tr>` props+ * 5. `transformBodyCell` — transform each body `<td>` props+ * 6. `transformBodyRow` — transform each body `<tr>` props* 7. `transformScrollWrapper` — transform the scroll-container wrapper around the table* 8. `transformTableContext` — wrap the table output in context providers*+ * A row's cells are built before its row transform runs, and reach it as+ * `children`: the cell hook is the earliest per-cell interception point, and a+ * row transform can discard cells but cannot stop them being built (see+ * `isContentSuppressed` on `BodyCellRenderProps` for that).+ ** Plugins may also contribute right-click menu actions by appending to* `contextMenuActions` in `transformHeaderCell` / `transformBodyCell`* (aggregated into one menu per header cell / row).diff --git a/packages/core/src/Table/useBaseTablePlugins.ts b/packages/core/src/Table/useBaseTablePlugins.tsindex 2463024715..a86796a0a8 100644--- a/packages/core/src/Table/useBaseTablePlugins.ts+++ b/packages/core/src/Table/useBaseTablePlugins.ts@@ -46,6 +46,11 @@ import {devWarn} from '../utils/devWarning';* Canonical ordering for first-party plugin names.* Plugins are sorted by their position in this array.* Unknown names are appended after the known set.+ *+ * This decides LAYOUT — which column lands left of which, who wraps whom. It+ * must never decide whether the table works: a plugin that renders in one+ * order and crashes in the other is broken, and adding it here buys a lucky+ * order rather than a fix.*/const PLUGIN_ORDER: ReadonlyArray<string> = ['columnSettings',diff --git a/packages/core/src/Table/useTableGroupedRows.doc.mjs b/packages/core/src/Table/useTableGroupedRows.doc.mjsindex f181e47b4c..df802e0716 100644--- a/packages/core/src/Table/useTableGroupedRows.doc.mjs+++ b/packages/core/src/Table/useTableGroupedRows.doc.mjs@@ -7,7 +7,7 @@ export const docs = {subComponentOf: 'Table',displayName: 'useTableGroupedRows',description:- 'Hook that groups a flat data array into collapsible section rows. Each distinct groupBy value becomes a full-width section-header row with a chevron toggle, the group label, and a member count; collapsing hides that group\'s data rows while keeping the header visible. Mirrors useTableTreeState: the consumer owns the collapsedGroups set and the hook returns {data, plugin, idKey}: pass all three to Table (data, plugins, and idKey respectively).',+ "Hook that groups a flat data array into collapsible section rows. Each distinct groupBy value becomes a full-width section-header row with a chevron toggle, the group label, and a member count; collapsing hides that group's data rows while keeping the header visible. Mirrors useTableTreeState: the consumer owns the collapsedGroups set and the hook returns {data, plugin, idKey}: pass them to Table as data, plugins, and idKey respectively.",props: [{name: 'data',@@ -58,13 +58,14 @@ export const docs = {/** @type {import('@astryxdesign/cli/authoring').ComponentTranslationDoc} */export const docsDense = {description:- 'Groups a flat data array into collapsible section rows. Each groupBy value becomes a full-width header (chevron + label + count); collapsing hides its rows. Returns {data, plugin, idKey}: pass to Table data / plugins / idKey. Consumer owns the collapsedGroups set.',+ 'Groups a flat data array into collapsible section rows. Each groupBy value becomes a full-width header (chevron + label + count); collapsing hides its rows. Returns {data, plugin, idKey}: pass them to Table data / plugins / idKey. Consumer owns the collapsedGroups set.',propDescriptions: {data: 'The flat data to group.',- groupBy: 'Derive a row\'s group key. Same key = same section.',+ groupBy: "Derive a row's group key. Same key = same section.",collapsedGroups: 'Set of currently-collapsed group keys.',onToggleGroup: 'Called with the group key when a header is toggled.',- renderGroupHeader: "Custom header content (right of chevron). Default '<key> (<count>)'.",+ renderGroupHeader:+ "Custom header content (right of chevron). Default '<key> (<count>)'.",getRowKey: 'Stable key for a real row; positional fallback when omitted.',groupOrder: 'Pin these group keys first; others keep first-seen order.',},