Skip to content

An open source design system that's fully customizable and agent ready

TypeScript

feat(core): add useTableStickyColumns plugin (#3118)

Humberto Virtudes1eed8622169b
diff --git a/.changeset/table-sticky-columns.md b/.changeset/table-sticky-columns.md
new file mode 100644
index 0000000000..16e25cddd1
--- /dev/null
+++ b/.changeset/table-sticky-columns.md
@@ -0,0 +1,18 @@
+---
+'@astryxdesign/core': patch
+---
+
+[feat] Add `useTableStickyColumns` — pin a contiguous run of `Table` columns to
+the start and/or end edge with cumulative offsets and scroll-aware drop shadows.
+Configure with `{ startKeys, endKeys }`; an empty config is a valid no-op.
+
+This also extends the `TablePlugin` contract so plugins can reach the layout
+region and reason about column position:
+
+- New `transformScrollWrapper` hook (+ `ScrollWrapperRenderProps`) lets plugins attach a `ref`
+ to the horizontal scroll container and inject before/after chrome.
+- `transformHeaderCell` / `transformBodyCell` now receive `columnIndex` and the
+ full ordered `columns` list (also surfaced on the render props), enabling
+ position-aware plugins such as sticky columns. Existing plugins are unaffected
+ — the new args and methods are additive and optional.
+ @humbertovirtudes
diff --git a/apps/storybook/stories/TableStickyColumns.stories.tsx b/apps/storybook/stories/TableStickyColumns.stories.tsx
new file mode 100644
index 0000000000..2b8aeb74ba
--- /dev/null
+++ b/apps/storybook/stories/TableStickyColumns.stories.tsx
@@ -0,0 +1,246 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+import {useState} from 'react';
+import type {Meta, StoryObj} from '@storybook/react';
+import {
+ Table,
+ useTableStickyColumns,
+ useTableColumnResize,
+ pixel,
+} from '@astryxdesign/core/Table';
+import type {TableColumn} from '@astryxdesign/core/Table';
+
+// =============================================================================
+// Sample Data — wide enough to require horizontal scroll
+// =============================================================================
+
+interface Employee extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ team: string;
+ role: string;
+ location: string;
+ startDate: string;
+ manager: string;
+ status: string;
+}
+
+const employees: Employee[] = [
+ {
+ id: '1',
+ name: 'Alice Nguyen',
+ email: '[email protected]',
+ team: 'Design Systems',
+ role: 'Staff Engineer',
+ location: 'San Francisco',
+ startDate: '2019-03-12',
+ manager: 'Priya Patel',
+ status: 'Active',
+ },
+ {
+ id: '2',
+ name: 'Bob Martinez',
+ email: '[email protected]',
+ team: 'Design Systems',
+ role: 'Senior Designer',
+ location: 'New York',
+ startDate: '2020-07-01',
+ manager: 'Priya Patel',
+ status: 'Active',
+ },
+ {
+ id: '3',
+ name: 'Charlie Okafor',
+ email: '[email protected]',
+ team: 'Platform',
+ role: 'Engineering Manager',
+ location: 'London',
+ startDate: '2017-11-20',
+ manager: 'Sam Lee',
+ status: 'On leave',
+ },
+ {
+ id: '4',
+ name: 'Diana Rossi',
+ email: '[email protected]',
+ team: 'Platform',
+ role: 'Staff Engineer',
+ location: 'Remote',
+ startDate: '2021-01-15',
+ manager: 'Sam Lee',
+ status: 'Active',
+ },
+ {
+ id: '5',
+ name: 'Ehsan Karimi',
+ email: '[email protected]',
+ team: 'Growth',
+ role: 'Product Engineer',
+ location: 'Berlin',
+ startDate: '2022-05-30',
+ manager: 'Mei Chen',
+ status: 'Active',
+ },
+];
+
+// Wide columns so the table overflows its container and scrolls horizontally.
+const columns: TableColumn<Employee>[] = [
+ {key: 'name', header: 'Name', width: pixel(180)},
+ {key: 'email', header: 'Email', width: pixel(220)},
+ {key: 'team', header: 'Team', width: pixel(180)},
+ {key: 'role', header: 'Role', width: pixel(200)},
+ {key: 'location', header: 'Location', width: pixel(160)},
+ {key: 'startDate', header: 'Start date', width: pixel(140)},
+ {key: 'manager', header: 'Manager', width: pixel(180)},
+ {key: 'status', header: 'Status', width: pixel(140)},
+];
+
+// =============================================================================
+// Stories
+// =============================================================================
+
+const meta: Meta = {
+ title: 'Core/TableStickyColumns',
+ tags: ['autodocs'],
+};
+
+export default meta;
+type Story = StoryObj;
+
+const note = {marginBottom: 8, fontSize: 14, color: '#666'} as const;
+
+/**
+ * Pin the leading `Name` column to the start edge. Scroll horizontally — the
+ * name stays put and a drop shadow appears over the scrolling content.
+ */
+export const PinStart: Story = {
+ render: () => {
+ const sticky = useTableStickyColumns<Employee>({startKeys: ['name']});
+ return (
+ <div style={{maxWidth: 720}}>
+ <p style={note}>
+ <code>startKeys: ['name']</code> — scroll right to see the Name column
+ stay pinned with a drop shadow.
+ </p>
+ <Table
+ data={employees}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Pin the trailing `Status` column to the end edge.
+ */
+export const PinEnd: Story = {
+ render: () => {
+ const sticky = useTableStickyColumns<Employee>({endKeys: ['status']});
+ return (
+ <div style={{maxWidth: 720}}>
+ <p style={note}>
+ <code>endKeys: ['status']</code> — the Status column stays pinned to
+ the right edge while the rest scrolls.
+ </p>
+ <Table
+ data={employees}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Pin both edges at once. `startKeys`/`endKeys` each define a contiguous run
+ * from their edge inward; columns get cumulative offsets so multiple pinned
+ * columns stack correctly.
+ */
+export const PinBothEdges: Story = {
+ render: () => {
+ const sticky = useTableStickyColumns<Employee>({
+ startKeys: ['name', 'email'],
+ endKeys: ['status'],
+ });
+ return (
+ <div style={{maxWidth: 720}}>
+ <p style={note}>
+ <code>startKeys: ['name', 'email']</code> +{' '}
+ <code>endKeys: ['status']</code> — two columns pinned left with
+ cumulative offsets, one pinned right.
+ </p>
+ <Table
+ data={employees}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Sticky columns composed with column resize. Resizing a pinned column keeps it
+ * pinned; the plugin order (sticky after resize) ensures the sticky inline
+ * offset wins over the resize handle's inline width.
+ */
+export const WithColumnResize: Story = {
+ render: () => {
+ const [columnWidths, setColumnWidths] = useState<Record<string, number>>(
+ {},
+ );
+ const resize = useTableColumnResize<Employee>({
+ columnWidths,
+ columns: columns as TableColumn<Record<string, unknown>>[],
+ onColumnResizeEnd: updates =>
+ setColumnWidths(prev => ({...prev, ...updates})),
+ });
+ const sticky = useTableStickyColumns<Employee>({startKeys: ['name']});
+ return (
+ <div style={{maxWidth: 720}}>
+ <p style={note}>
+ Resize columns by dragging header edges; the pinned Name column stays
+ sticky. Plugins compose: <code>{'{ columnResize, stickyColumns }'}</code>.
+ </p>
+ <Table
+ data={employees}
+ columns={columns}
+ idKey="id"
+ plugins={{columnResize: resize, stickyColumns: sticky}}
+ />
+ </div>
+ );
+ },
+};
+
+/**
+ * Empty config is a valid no-op — nothing is pinned, every cell passes through
+ * untouched. Lets callers compute keys conditionally without branching on
+ * whether to install the plugin.
+ */
+export const NoOpEmptyConfig: Story = {
+ render: () => {
+ const sticky = useTableStickyColumns<Employee>({});
+ return (
+ <div style={{maxWidth: 720}}>
+ <p style={note}>
+ <code>useTableStickyColumns({'{}'})</code> — no pinned columns; the
+ table behaves as if the plugin weren't installed.
+ </p>
+ <Table
+ data={employees}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ </div>
+ );
+ },
+};
diff --git a/packages/core/src/Table/BaseTable.tsx b/packages/core/src/Table/BaseTable.tsx
index 1175f39dcc..a20508e0af 100644
--- a/packages/core/src/Table/BaseTable.tsx
+++ b/packages/core/src/Table/BaseTable.tsx
@@ -26,6 +26,7 @@ import type {
HeaderCellRenderProps,
BodyRowRenderProps,
BodyCellRenderProps,
+ ScrollWrapperRenderProps,
TableRowComponentProps,
TableCellComponentProps,
TableHeaderCellComponentProps,
@@ -152,22 +153,27 @@ function TableRowInner<T extends Record<string, unknown>>({
CellComponent,
}: TableRowProps<T>): ReactElement {
// Build cells first
- const cells = columns.map(col => {
+ const cells = columns.map((col, columnIndex) => {
// Apply column alignment to body cells
const initialCellHtmlProps: Record<string, unknown> = {};
if (col.align) {
initialCellHtmlProps.style = {textAlign: col.align};
}
+ const initialBodyCellRenderProps: BodyCellRenderProps = {
+ htmlProps: initialCellHtmlProps,
+ styles: [],
+ columnIndex,
+ columns: columns as ReadonlyArray<TableColumn<Record<string, unknown>>>,
+ };
const cellRenderProps = applyPlugins(
plugins,
p => p.transformBodyCell,
- {
- htmlProps: initialCellHtmlProps,
- styles: [],
- } satisfies BodyCellRenderProps,
+ initialBodyCellRenderProps,
col,
item,
+ columnIndex,
+ columns,
);
const isDefaultRenderer = !col.renderCell;
@@ -313,8 +319,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
// Use stable empty array when no plugins provided
const plugins = pluginsProp ?? (EMPTY_PLUGINS as TablePlugin<T>[]);
- const RowComponent =
- TableRow as React.ComponentType<TableRowComponentProps>;
+ const RowComponent = TableRow as React.ComponentType<TableRowComponentProps>;
const CellComponent =
TableCell as React.ComponentType<TableCellComponentProps>;
const HeaderCellComponent =
@@ -354,7 +359,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
} satisfies TableRenderProps);
// --- Plugin pipeline: header cells ---
- const headerCells = resolvedColumns.map(col => {
+ const headerCells = resolvedColumns.map((col, columnIndex) => {
const headerContent = col.header ?? col.key;
// Build initial htmlProps with column alignment if specified
@@ -365,15 +370,22 @@ function BaseTableInner<T extends Record<string, unknown>>({
initialHeaderHtmlProps.style = {textAlign: col.align};
}
+ const initialHeaderRenderProps: HeaderCellRenderProps = {
+ htmlProps: initialHeaderHtmlProps,
+ styles: [],
+ content: headerContent,
+ columnIndex,
+ columns: resolvedColumns as ReadonlyArray<
+ TableColumn<Record<string, unknown>>
+ >,
+ };
const cellRenderProps = applyPlugins(
plugins,
p => p.transformHeaderCell,
- {
- htmlProps: initialHeaderHtmlProps,
- styles: [],
- content: headerContent,
- } satisfies HeaderCellRenderProps,
+ initialHeaderRenderProps,
col,
+ columnIndex,
+ resolvedColumns,
);
// Apply pre-computed column width styles on the <th>.
@@ -497,9 +509,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
emptyState !== false && (
<tr>
<td colSpan={resolvedColumns.length}>
- {emptyState ?? (
- <EmptyState title="No data" isCompact />
- )}
+ {emptyState ?? <EmptyState title="No data" isCompact />}
</td>
</tr>
)}
@@ -513,8 +523,29 @@ function BaseTableInner<T extends Record<string, unknown>>({
// when columns exceed the container width. This wrapper sits between
// the <table> and transformTableContext, so plugin chrome (pagination,
// toolbars) renders outside the scroll area.
+ //
+ // Before rendering the wrapper, run the plugin `transformScrollWrapper`
+ // pipeline so plugins can attach a ref to the scroll container (scroll-aware
+ // sticky shadows, virtualization) and inject before/after chrome.
if (ScrollWrapper) {
- tableElement = <ScrollWrapper>{tableElement}</ScrollWrapper>;
+ const scrollWrapperRenderProps = applyPlugins(
+ plugins,
+ p => p.transformScrollWrapper,
+ {
+ htmlProps: {},
+ styles: [],
+ } satisfies ScrollWrapperRenderProps,
+ );
+
+ tableElement = (
+ <ScrollWrapper
+ htmlProps={scrollWrapperRenderProps.htmlProps}
+ styles={scrollWrapperRenderProps.styles}
+ beforeTable={scrollWrapperRenderProps.beforeTable}
+ afterTable={scrollWrapperRenderProps.afterTable}>
+ {tableElement}
+ </ScrollWrapper>
+ );
}
// Apply transformTableContext from each plugin.
@@ -527,10 +558,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
try {
tableElement = plugin.transformTableContext(tableElement);
} catch (error) {
- console.error(
- '[Table] Plugin threw in transformTableContext:',
- error,
- );
+ console.error('[Table] Plugin threw in transformTableContext:', error);
}
}
}
@@ -556,9 +584,7 @@ function BaseTableInner<T extends Record<string, unknown>>({
* />
* ```
*/
-export const BaseTable = BaseTableInner as <
- T extends Record<string, unknown>,
->(
+export const BaseTable = BaseTableInner as <T extends Record<string, unknown>>(
props: BaseTableProps<T> & {ref?: Ref<HTMLTableElement>},
) => ReactElement;
diff --git a/packages/core/src/Table/Table.tsx b/packages/core/src/Table/Table.tsx
index 4ba0a3a25d..b8f94fc700 100644
--- a/packages/core/src/Table/Table.tsx
+++ b/packages/core/src/Table/Table.tsx
@@ -30,6 +30,7 @@ import type {
TablePlugin,
TableRenderProps,
} from './types';
+import type {StyleXStyles} from '../theme/types';
// =============================================================================
// Table Types
@@ -131,17 +132,37 @@ const scrollWrapperStyles = stylex.create({
},
});
-function TableScrollWrapper({children}: {children: React.ReactNode}) {
+function TableScrollWrapper({
+ children,
+ htmlProps,
+ styles: pluginStyles,
+ beforeTable,
+ afterTable,
+}: {
+ children: React.ReactNode;
+ htmlProps?: React.HTMLAttributes<HTMLDivElement> & {
+ ref?: React.Ref<HTMLDivElement>;
+ };
+ styles?: StyleXStyles[];
+ beforeTable?: React.ReactNode;
+ afterTable?: React.ReactNode;
+}) {
+ const {ref, ...restHtmlProps} = htmlProps ?? {};
return (
<div
+ ref={ref}
+ {...restHtmlProps}
{...mergeProps(
themeProps('table-scroll-wrapper'),
stylex.props(
scrollWrapperStyles.base,
scrollWrapperStyles.containerBleed,
+ ...(pluginStyles ?? []),
),
)}>
+ {beforeTable}
{children}
+ {afterTable}
</div>
);
}
diff --git a/packages/core/src/Table/index.ts b/packages/core/src/Table/index.ts
index fe452a435d..0b537c3c66 100644
--- a/packages/core/src/Table/index.ts
+++ b/packages/core/src/Table/index.ts
@@ -27,6 +27,7 @@ export {useTablePagination, paginateData} from './plugins/pagination';
export {useTableColumnSettings} from './plugins/columnSettings';
export {useTableColumnSettingsState} from './plugins/columnSettings';
export {useTableColumnResize} from './plugins/columnResize';
+export {useTableStickyColumns} from './plugins/stickyColumns';
export {
useTableFiltering,
useTableFilterState,
@@ -53,6 +54,7 @@ export type {
HeaderCellRenderProps,
BodyRowRenderProps,
BodyCellRenderProps,
+ ScrollWrapperRenderProps,
BaseTableProps,
} from './types';
export type {
@@ -93,6 +95,7 @@ export type {
UseTableColumnSettingsStateReturn,
} from './plugins/columnSettings';
export type {UseTableColumnResizeConfig} from './plugins/columnResize';
+export type {UseTableStickyColumnsConfig} from './plugins/stickyColumns';
export type {
UseTableFilteringConfig,
TableFilterState,
diff --git a/packages/core/src/Table/plugins/stickyColumns/index.ts b/packages/core/src/Table/plugins/stickyColumns/index.ts
new file mode 100644
index 0000000000..97170f1932
--- /dev/null
+++ b/packages/core/src/Table/plugins/stickyColumns/index.ts
@@ -0,0 +1,4 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+export {useTableStickyColumns} from './useTableStickyColumns';
+export type {UseTableStickyColumnsConfig} from './useTableStickyColumns';
diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx
new file mode 100644
index 0000000000..ceedc02cbf
--- /dev/null
+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx
@@ -0,0 +1,163 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+/**
+ * @file useTableStickyColumns.test.tsx
+ * @input useTableStickyColumns, Table, React testing utilities
+ * @output Functional tests for the sticky-columns plugin
+ * @position Test file; validates pinning, cumulative offsets, edges, no-op
+ *
+ * Note: `position: sticky` and the z-index/background are applied via StyleX
+ * (compiled to classNames), which jsdom does not resolve to `element.style`.
+ * The plugin sets the per-column *offset* (`insetInlineStart`/`insetInlineEnd`)
+ * as an inline style, so these tests assert on those inline offsets — the
+ * jsdom-visible, plugin-owned signal that a column is pinned and at what offset.
+ */
+
+import {describe, it, expect} from 'vitest';
+import {render, screen} from '@testing-library/react';
+import {Table} from '../../Table';
+import {useTableStickyColumns} from './useTableStickyColumns';
+import {pixel} from '../../columnUtils';
+import type {TableColumn} from '../../types';
+
+// =============================================================================
+// Test Data
+// =============================================================================
+
+interface Row extends Record<string, unknown> {
+ id: string;
+ name: string;
+ email: string;
+ team: string;
+ status: string;
+}
+
+const data: Row[] = [
+ {id: '1', name: 'Alice', email: '[email protected]', team: 'DS', status: 'Active'},
+ {id: '2', name: 'Bob', email: '[email protected]', team: 'Plat', status: 'Away'},
+];
+
+const columns: TableColumn<Row>[] = [
+ {key: 'name', header: 'Name', width: pixel(180)},
+ {key: 'email', header: 'Email', width: pixel(220)},
+ {key: 'team', header: 'Team', width: pixel(160)},
+ {key: 'status', header: 'Status', width: pixel(140)},
+];
+
+function getHeader(name: string): HTMLElement {
+ return screen.getByRole('columnheader', {name});
+}
+
+// =============================================================================
+// Tests
+// =============================================================================
+
+describe('useTableStickyColumns', () => {
+ it('pins a start column at inset-inline-start: 0', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({startKeys: ['name']});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ expect(getHeader('Name').style.insetInlineStart).toBe('0px');
+ });
+
+ it('computes cumulative start offsets for contiguous pinned columns', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({
+ startKeys: ['name', 'email'],
+ });
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ // name is first → offset 0; email follows → offset = name width (180px)
+ expect(getHeader('Name').style.insetInlineStart).toBe('0px');
+ expect(getHeader('Email').style.insetInlineStart).toBe('180px');
+ });
+
+ it('pins an end column at inset-inline-end: 0', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({endKeys: ['status']});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ expect(getHeader('Status').style.insetInlineEnd).toBe('0px');
+ });
+
+ it('pins body cells, not just headers', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({startKeys: ['name']});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ const firstBodyCell = screen.getByText('Alice').closest('td');
+ expect(firstBodyCell).not.toBeNull();
+ expect(firstBodyCell!.style.insetInlineStart).toBe('0px');
+ });
+
+ it('is a no-op with an empty config — no cell gets an offset', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ for (const header of ['Name', 'Email', 'Team', 'Status']) {
+ const th = getHeader(header);
+ expect(th.style.insetInlineStart).toBe('');
+ expect(th.style.insetInlineEnd).toBe('');
+ }
+ });
+
+ it('only pins configured columns, leaving others unset', () => {
+ function Harness() {
+ const sticky = useTableStickyColumns<Row>({startKeys: ['name']});
+ return (
+ <Table
+ data={data}
+ columns={columns}
+ idKey="id"
+ plugins={{stickyColumns: sticky}}
+ />
+ );
+ }
+ render(<Harness />);
+ expect(getHeader('Name').style.insetInlineStart).toBe('0px');
+ expect(getHeader('Team').style.insetInlineStart).toBe('');
+ expect(getHeader('Team').style.insetInlineEnd).toBe('');
+ });
+});
diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
new file mode 100644
index 0000000000..89d3d411fb
--- /dev/null
+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx
@@ -0,0 +1,414 @@
+// Copyright (c) Meta Platforms, Inc. and affiliates.
+
+'use client';
+
+/**
+ * @file useTableStickyColumns.tsx
+ * @input React, StyleX, theme tokens, Table types
+ * @output Exports useTableStickyColumns hook and UseTableStickyColumnsConfig type
+ * @position Sticky-columns plugin; consumed by Table via plugins prop
+ *
+ * SYNC: When modified, update these files to stay in sync:
+ * - /packages/core/src/Table/Table.doc.mjs (sticky-columns documentation)
+ * - /packages/core/src/Table/index.ts (exports)
+ */
+
+import {useCallback, useMemo, useRef, type CSSProperties} from 'react';
+import * as stylex from '@stylexjs/stylex';
+import {colorVars} from '../../../theme/tokens.stylex';
+import type {
+ TableColumn,
+ TablePlugin,
+ HeaderCellRenderProps,
+ BodyCellRenderProps,
+ ScrollWrapperRenderProps,
+} from '../../types';
+import {DEFAULT_MIN_COLUMN_WIDTH} from '../../columnUtils';
+
+// =============================================================================
+// Config
+// =============================================================================
+
+/**
+ * Config for {@link useTableStickyColumns}. Provide at least one of
+ * `startKeys` / `endKeys` to pin columns.
+ *
+ * @remarks Every field is optional by design, so `useTableStickyColumns({})`
+ * compiles and is an intentional no-op that pins nothing — the hook returns a
+ * plugin that passes every cell through untouched. This lets callers compute
+ * the config conditionally (e.g. `endKeys: enabled ? ['notes'] : undefined`)
+ * without branching on whether to install the plugin at all.
+ */
+export interface UseTableStickyColumnsConfig {
+ /**
+ * Column keys pinned to the START (inline-start / left in LTR) edge — the
+ * contiguous run from the first column through the last listed key.
+ */
+ startKeys?: string[];
+ /**
+ * Column keys pinned to the END (inline-end / right in LTR) edge — the
+ * contiguous run from the first listed key through the last column.
+ */
+ endKeys?: string[];
+}
+
+// =============================================================================
+// Width helpers
+// =============================================================================
+
+/**
+ * Resolve a column's pixel width for cumulative offset math. Mirrors the
+ * resize plugin's fallback so offsets line up with rendered widths:
+ * pixel columns use their value; proportional columns use their declared
+ * minWidth (or the default); unknown widths use the default.
+ */
+function getColumnWidth(col: TableColumn<Record<string, unknown>>): number {
+ const w = col.width;
+ if (!w) {
+ return DEFAULT_MIN_COLUMN_WIDTH;
+ }
+ if (w.type === 'pixel') {
+ return w.value;
+ }
+ // proportional
+ return w.minWidth ?? DEFAULT_MIN_COLUMN_WIDTH;
+}
+
+/**
+ * Columns pinned to the START edge, keyed by column key → cumulative inline
+ * offset in pixels. The pinned block is the CONTIGUOUS run of leading columns
+ * from index 0 through the last column whose key is in `startKeys` (inclusive),
+ * INCLUDING synthetic columns (selection checkbox, row-index, …) that sit to
+ * the start of the user's sticky column. Returns `null` when no start-sticky
+ * column is present or column context is unavailable.
+ */
+function computeStartOffsets(
+ columns: ReadonlyArray<TableColumn<Record<string, unknown>>> | undefined,
+ startKeys: string[],
+): Map<string, number> | null {
+ if (!columns || columns.length === 0 || startKeys.length === 0) {
+ return null;
+ }
+ let lastStickyIndex = -1;
+ for (let i = 0; i < columns.length; i++) {
+ if (startKeys.includes(columns[i].key)) {
+ lastStickyIndex = i;
+ }
+ }
+ if (lastStickyIndex === -1) {
+ return null;
+ }
+ const offsets = new Map<string, number>();
+ let cumulative = 0;
+ for (let i = 0; i <= lastStickyIndex; i++) {
+ offsets.set(columns[i].key, cumulative);
+ cumulative += getColumnWidth(columns[i]);
+ }
+ return offsets;
+}
+
+/**
+ * Mirror image of {@link computeStartOffsets} — columns pinned to the END edge,
+ * keyed by column key → cumulative inline-end offset. The pinned block is the
+ * CONTIGUOUS run of trailing columns from the FIRST column whose key is in
+ * `endKeys` through the last column (inclusive). Offsets accumulate from the
+ * end edge — the last column gets `0`, its neighbor gets that column's width,
+ * etc. Returns `null` when no end-sticky column is present.
+ */
+function computeEndOffsets(
+ columns: ReadonlyArray<TableColumn<Record<string, unknown>>> | undefined,
+ endKeys: string[],
+): Map<string, number> | null {
+ if (!columns || columns.length === 0 || endKeys.length === 0) {
+ return null;
+ }
+ let firstStickyIndex = -1;
+ for (let i = 0; i < columns.length; i++) {
+ if (endKeys.includes(columns[i].key)) {
+ firstStickyIndex = i;
+ break;
+ }
+ }
+ if (firstStickyIndex === -1) {
+ return null;
+ }
+ const offsets = new Map<string, number>();
+ let cumulative = 0;
+ for (let i = columns.length - 1; i >= firstStickyIndex; i--) {
+ offsets.set(columns[i].key, cumulative);
+ cumulative += getColumnWidth(columns[i]);
+ }
+ return offsets;
+}
+
+type StickySide = {edge: 'start' | 'end'; offset: number};
+
+/**
+ * Resolve how a single column should be pinned given the start/end configs and
+ * the full column list. A key (mis)configured on both edges resolves to start.
+ * Returns `null` for columns that should not be pinned.
+ */
+function resolveStickySide(
+ columns: ReadonlyArray<TableColumn<Record<string, unknown>>> | undefined,
+ columnKey: string,
+ startKeys: string[],
+ endKeys: string[],
+): StickySide | null {
+ const startOffsets = computeStartOffsets(columns, startKeys);
+ if (startOffsets?.has(columnKey)) {
+ return {edge: 'start', offset: startOffsets.get(columnKey) ?? 0};
+ }
+ const endOffsets = computeEndOffsets(columns, endKeys);
+ if (endOffsets?.has(columnKey)) {
+ return {edge: 'end', offset: endOffsets.get(columnKey) ?? 0};
+ }
+ return null;
+}
+
+// =============================================================================
+// Styles
+// =============================================================================
+
+// CSS variables toggled on the scroll container by the layout ref. The cell
+// ::after shadows read these, so each edge's shadow only shows when there is
+// horizontally-scrolled content hidden behind that edge. We use CSS variables
+// (not stylex.when.ancestor) because StyleX ancestor selectors support pseudo-
+// classes only, not attribute/className matching — a CSS variable inherited
+// from the scroll container is the supported way to gate descendant styles on
+// container scroll state.
+const SHADOW_VAR_START = '--table-sticky-shadow-start';
+const SHADOW_VAR_END = '--table-sticky-shadow-end';
+
+const stickyStyles = stylex.create({
+ cell: {
+ position: 'sticky',
+ // Pinned cells must be opaque so scrolling content doesn't show through.
+ backgroundColor: colorVars['--color-background-surface'],
+ // Clip the background to the padding box so it doesn't paint over the
+ // cell's (translucent, collapsed) bottom/right divider border. Sticky cells
+ // sit above regular cells, so without this the opaque background would hide
+ // the row divider on the pinned column.
+ backgroundClip: 'padding-box',
+ // Default table cells are `overflow: hidden` (for text truncation), which
+ // would clip the shadow ::after that bleeds past the pinned edge. Sticky
+ // cells opt back into visible overflow so the shadow can render outside.
+ // Text truncation on sticky columns still works because the cell width is
+ // fixed and the inner content wraps/ellipsizes within it.
+ overflow: 'visible',
+ },
+ headerCell: {
+ // Header cells stack above body cells; both stack above non-sticky cells.
+ zIndex: 3,
+ },
+ bodyCell: {
+ zIndex: 1,
+ },
+});
+
+// A soft drop shadow over the scrolling region, matching the EPS sticky-column
+// treatment. `border-collapse: collapse` tables (Astryx Table uses
+// table-layout: fixed + border-collapse: collapse) do NOT paint `box-shadow`
+// on the cells themselves in Chromium, so the shadow is cast by a ::after strip
+// positioned just outside the pinned edge, filled with a soft gradient that
+// fades from a shadow tint to transparent over the scrolled content. Sticky
+// cells set `overflow: visible` (above) so this strip isn't clipped. Its
+// opacity reads a CSS variable inherited from the scroll container, which the
+// layout ref toggles between 0 and 1 on scroll so the shadow only shows when
+// there is hidden content behind that edge.
+const SHADOW_WIDTH = '6px';
+// A subtle tint that fades to transparent. --color-shadow is only ~10% alpha,
+// which reads too faintly here, so use a slightly stronger but still soft tint.
+const SHADOW_TINT = 'light-dark(rgba(0, 0, 0, 0.12), rgba(0, 0, 0, 0.32))';
+const shadowStyles = stylex.create({
+ // start-pinned: shadow falls to the right (inline-end), over scrolled content
+ start: {
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ top: 0,
+ bottom: 0,
+ insetInlineEnd: 0,
+ width: SHADOW_WIDTH,
+ transform: 'translateX(100%)',
+ pointerEvents: 'none',
+ transition: 'opacity 150ms ease',
+ opacity: `var(${SHADOW_VAR_START}, 0)`,
+ backgroundImage: `linear-gradient(to right, ${SHADOW_TINT}, transparent)`,
+ },
+ },
+ // end-pinned: shadow falls to the left (inline-start), over scrolled content
+ end: {
+ '::after': {
+ content: '""',
+ position: 'absolute',
+ top: 0,
+ bottom: 0,
+ insetInlineStart: 0,
+ width: SHADOW_WIDTH,
+ transform: 'translateX(-100%)',
+ pointerEvents: 'none',
+ transition: 'opacity 150ms ease',
+ opacity: `var(${SHADOW_VAR_END}, 0)`,
+ backgroundImage: `linear-gradient(to left, ${SHADOW_TINT}, transparent)`,
+ },
+ },
+});
+
+// Stable empty default so an unset start/end doesn't allocate a fresh array
+// (and bust the memo) on every render.
+const EMPTY: string[] = [];
+
+// =============================================================================
+// Hook
+// =============================================================================
+
+export function useTableStickyColumns<T extends Record<string, unknown>>(
+ config: UseTableStickyColumnsConfig,
+): TablePlugin<T> {
+ const {startKeys, endKeys} = config;
+ const start = startKeys ?? EMPTY;
+ const end = endKeys ?? EMPTY;
+
+ const hasStart = start.length > 0;
+ const hasEnd = end.length > 0;
+
+ // Live snapshot of the resolved config, read inside the (memoized) transforms
+ // and the scroll-shadow callback. Keeping these in a ref lets the plugin memo
+ // be computed once (deps: only the stable scroll-shadow callback) while never
+ // reading stale config — consumers typically pass fresh array literals each
+ // render, so we never want array identity in the deps.
+ const stateRef = useRef({start, end, hasStart, hasEnd});
+ stateRef.current = {start, end, hasStart, hasEnd};
+
+ // Scroll-aware shadows: toggle CSS variables on the scroll container so each
+ // edge's shadow only paints when there is hidden, horizontally-scrolled
+ // content behind that edge. Implemented with a callback ref + scroll/resize
+ // listeners (synchronizing with the DOM) rather than React state, so
+ // scrolling never triggers re-renders.
+ const detachRef = useRef<(() => void) | null>(null);
+ const attachScrollShadow = useCallback((el: HTMLDivElement | null) => {
+ detachRef.current?.();
+ detachRef.current = null;
+ if (!el) {
+ return;
+ }
+ const update = () => {
+ const {hasStart: hs, hasEnd: he} = stateRef.current;
+ const maxScroll = el.scrollWidth - el.clientWidth;
+ const hasOverflow = maxScroll > 1;
+ if (hs) {
+ el.style.setProperty(
+ SHADOW_VAR_START,
+ hasOverflow && el.scrollLeft > 1 ? '1' : '0',
+ );
+ }
+ if (he) {
+ el.style.setProperty(
+ SHADOW_VAR_END,
+ hasOverflow && el.scrollLeft < maxScroll - 1 ? '1' : '0',
+ );
+ }
+ };
+ el.addEventListener('scroll', update, {passive: true});
+ const resizeObserver =
+ typeof ResizeObserver !== 'undefined' ? new ResizeObserver(update) : null;
+ resizeObserver?.observe(el);
+ update();
+ detachRef.current = () => {
+ el.removeEventListener('scroll', update);
+ resizeObserver?.disconnect();
+ };
+ }, []);
+
+ return useMemo(
+ (): TablePlugin<T> => ({
+ transformHeaderCell(
+ props: HeaderCellRenderProps,
+ column: TableColumn<T>,
+ ): HeaderCellRenderProps {
+ const {start: s, end: e} = stateRef.current;
+ const side = resolveStickySide(props.columns, column.key, s, e);
+ if (!side) {
+ return props;
+ }
+ // position/inline-offset are runtime values → set via inline style so
+ // they are authoritative regardless of plugin composition order (the
+ // resize plugin also writes inline style on header cells).
+ const offsetStyle: CSSProperties =
+ side.edge === 'start'
+ ? {insetInlineStart: `${side.offset}px`}
+ : {insetInlineEnd: `${side.offset}px`};
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ style: {...props.htmlProps.style, ...offsetStyle},
+ },
+ styles: [
+ ...props.styles,
+ stickyStyles.cell,
+ stickyStyles.headerCell,
+ side.edge === 'start' ? shadowStyles.start : shadowStyles.end,
+ ],
+ };
+ },
+
+ transformBodyCell(
+ props: BodyCellRenderProps,
+ column: TableColumn<T>,
+ ): BodyCellRenderProps {
+ const {start: s, end: e} = stateRef.current;
+ const side = resolveStickySide(props.columns, column.key, s, e);
+ if (!side) {
+ return props;
+ }
+ const offsetStyle: CSSProperties =
+ side.edge === 'start'
+ ? {insetInlineStart: `${side.offset}px`}
+ : {insetInlineEnd: `${side.offset}px`};
+ return {
+ ...props,
+ htmlProps: {
+ ...props.htmlProps,
+ style: {...props.htmlProps.style, ...offsetStyle},
+ },
+ styles: [
+ ...props.styles,
+ stickyStyles.cell,
+ stickyStyles.bodyCell,
+ side.edge === 'start' ? shadowStyles.start : shadowStyles.end,
+ ],
+ };
+ },
+
+ transformScrollWrapper(
+ props: ScrollWrapperRenderProps,
+ ): ScrollWrapperRenderProps {
+ // No pinned edges → nothing to gate; leave the wrapper untouched.
+ if (!stateRef.current.hasStart && !stateRef.current.hasEnd) {
+ return props;
+ }
+ // Compose with any ref a prior plugin (e.g. virtualization) set on the
+ // scroll container.
+ const existingRef = props.htmlProps.ref;
+ const mergedRef = (node: HTMLDivElement | null) => {
+ attachScrollShadow(node);
+ if (typeof existingRef === 'function') {
+ existingRef(node);
+ } else if (existingRef != null) {
+ // RefObject — assign through its writable `.current`.
+ existingRef.current = node;
+ }
+ };
+ return {
+ ...props,
+ htmlProps: {...props.htmlProps, ref: mergedRef},
+ };
+ },
+ }),
+ // The returned plugin's transforms read live config from `stateRef` and
+ // `attachScrollShadow` is stable (empty deps), so the plugin object can be
+ // computed once and reused across renders.
+ [attachScrollShadow],
+ );
+}
diff --git a/packages/core/src/Table/types.ts b/packages/core/src/Table/types.ts
index 9b86473689..b846cec5cb 100644
--- a/packages/core/src/Table/types.ts
+++ b/packages/core/src/Table/types.ts
@@ -261,6 +261,20 @@ export interface HeaderCellRenderProps {
overlay?: ReactNode;
/** Content rendered below the header label row (e.g. inline filter controls). */
below?: ReactNode;
+ /**
+ * Index of this column within the final, ordered list of rendered columns
+ * (after column injection/reordering by other plugins). Populated by
+ * BaseTable. Optional for backward compatibility with hand-constructed
+ * renders in tests.
+ */
+ columnIndex?: number;
+ /**
+ * The full, final ordered list of columns being rendered (after column
+ * injection/reordering by other plugins). Populated by BaseTable so plugins
+ * can reason about column position — e.g. cumulative sticky offsets. Optional
+ * for backward compatibility.
+ */
+ columns?: ReadonlyArray<TableColumn<Record<string, unknown>>>;
}
/** Props passed through the plugin pipeline for each body `<tr>` */
@@ -276,6 +290,49 @@ export interface BodyRowRenderProps {
export interface BodyCellRenderProps {
htmlProps: TdHTMLAttributes<HTMLTableCellElement>;
styles: StyleXStyles[];
+ /**
+ * Index of this cell's column within the final ordered column list.
+ * Mirrors the `columnIndex` passed to `transformHeaderCell`. Populated by
+ * BaseTable. Optional for backward compatibility with hand-constructed
+ * renders in tests.
+ */
+ columnIndex?: number;
+ /**
+ * The full, final ordered list of columns being rendered. Populated by
+ * BaseTable so plugins can reason about column position — e.g. cumulative
+ * sticky offsets. Optional for backward compatibility.
+ */
+ columns?: ReadonlyArray<TableColumn<Record<string, unknown>>>;
+}
+
+/**
+ * Props passed through the plugin pipeline for the scroll-wrapper region — the
+ * `<div>` wrapping the `<table>` element (the horizontal scroll container, see
+ * the `scrollWrapper` prop on `BaseTableProps`). Lets plugins attach a `ref` to
+ * the scrollable element (e.g. for scroll-aware sticky-column shadows or
+ * virtualization) and inject chrome before/after the table.
+ *
+ * Named after `scrollWrapper` (not "layout") to avoid ambiguity: it transforms
+ * the wrapper element, not the internal header/body/footer layout of `<table>`.
+ *
+ * Runs after `transformTable`/cell transforms but inside `transformTableContext`,
+ * so plugin chrome added here stays within any context providers but wraps the
+ * scroll area.
+ */
+export interface ScrollWrapperRenderProps {
+ /**
+ * HTML attributes applied to the scroll container `<div>`, including an
+ * optional `ref`. Plugins compose refs by reading the existing `ref` and
+ * merging their own (see `useTableStickyColumns`).
+ */
+ htmlProps: HTMLAttributes<HTMLDivElement> & {
+ ref?: Ref<HTMLDivElement>;
+ };
+ styles: StyleXStyles[];
+ /** Content rendered before the `<table>`, inside the scroll container. */
+ beforeTable?: ReactNode;
+ /** Content rendered after the `<table>`, inside the scroll container. */
+ afterTable?: ReactNode;
}
// =============================================================================
@@ -294,7 +351,8 @@ export interface BodyCellRenderProps {
* 4. `transformHeaderCell` — transform each `<th>` props
* 5. `transformBodyRow` — transform each body `<tr>` props
* 6. `transformBodyCell` — transform each body `<td>` props
- * 7. `transformTableContext` — wrap the table output in context providers
+ * 7. `transformScrollWrapper` — transform the scroll-container wrapper around the table
+ * 8. `transformTableContext` — wrap the table output in context providers
*/
export interface TablePlugin<
T extends Record<string, unknown> = Record<string, unknown>,
@@ -309,10 +367,17 @@ export interface TablePlugin<
transformTable?: (props: TableRenderProps) => TableRenderProps;
/** Transform the header `<tr>` props */
transformHeaderRow?: (props: HeaderRowRenderProps) => HeaderRowRenderProps;
- /** Transform each `<th>` props */
+ /**
+ * Transform each `<th>` props.
+ *
+ * `columnIndex` and the full `columns` list are provided for plugins that
+ * need to reason about column position (e.g. cumulative sticky offsets).
+ */
transformHeaderCell?: (
props: HeaderCellRenderProps,
column: TableColumn<T>,
+ columnIndex: number,
+ columns: ReadonlyArray<TableColumn<T>>,
) => HeaderCellRenderProps;
/** Transform each body `<tr>` props */
transformBodyRow?: (
@@ -320,12 +385,28 @@ export interface TablePlugin<
item: T,
index: number,
) => BodyRowRenderProps;
- /** Transform each body `<td>` props */
+ /**
+ * Transform each body `<td>` props.
+ *
+ * `columnIndex` and the full `columns` list are provided for plugins that
+ * need to reason about column position (e.g. cumulative sticky offsets).
+ */
transformBodyCell?: (
props: BodyCellRenderProps,
column: TableColumn<T>,
item: T,
+ columnIndex: number,
+ columns: ReadonlyArray<TableColumn<T>>,
) => BodyCellRenderProps;
+ /**
+ * Transform the scroll-wrapper region — the `<div>` wrapping the `<table>`
+ * (see the `scrollWrapper` prop). Use to attach a `ref` to the scrollable
+ * element (scroll-aware shadows, virtualization) or to inject chrome
+ * before/after the table.
+ */
+ transformScrollWrapper?: (
+ props: ScrollWrapperRenderProps,
+ ) => ScrollWrapperRenderProps;
/** Wrap the table output in context providers */
transformTableContext?: (children: ReactNode) => ReactNode;
}
@@ -390,8 +471,19 @@ export interface BaseTableProps<
* plugin `transformTableContext` layer. Used by `Table` to add a
* horizontal scroll container so plugin chrome (pagination, toolbars)
* stays outside the scrollable area.
+ *
+ * Receives `htmlProps` (including an optional `ref`) and `styles` produced
+ * by the plugin `transformScrollWrapper` pipeline, plus `beforeTable`/`afterTable`
+ * chrome. The wrapper must spread `htmlProps` (and apply `styles`) onto its
+ * scroll-container element so plugins can attach refs / scroll listeners.
*/
- scrollWrapper?: ComponentType<{children: ReactNode}>;
+ scrollWrapper?: ComponentType<{
+ children: ReactNode;
+ htmlProps?: HTMLAttributes<HTMLDivElement> & {ref?: Ref<HTMLDivElement>};
+ styles?: StyleXStyles[];
+ beforeTable?: ReactNode;
+ afterTable?: ReactNode;
+ }>;
/**
* How default-rendered body cell text behaves when it exceeds column width.
*
diff --git a/packages/core/src/Table/useBaseTablePlugins.ts b/packages/core/src/Table/useBaseTablePlugins.ts
index 6dd0ae4097..21e13ec7ce 100644
--- a/packages/core/src/Table/useBaseTablePlugins.ts
+++ b/packages/core/src/Table/useBaseTablePlugins.ts
@@ -87,6 +87,7 @@ const VALID_TRANSFORM_KEYS = new Set([
'transformHeaderCell',
'transformBodyRow',
'transformBodyCell',
+ 'transformScrollWrapper',
'transformTableContext',
]);