An open source design system that's fully customizable and agent ready
TypeScript
fix(core): a pinned table column draws its own row dividers (#8654)
Cindy Zhanga7044525d938
diff --git a/.changeset/table-pinned-dividers.md b/.changeset/table-pinned-dividers.mdnew file mode 100644index 0000000000..58e75b133f--- /dev/null+++ b/.changeset/table-pinned-dividers.md@@ -0,0 +1,7 @@+---+'@astryxdesign/core': patch+---++[fix] Table: a pinned column (`useTableStickyColumns`) now draws its own row dividers, so the line under it no longer goes missing while the table scrolls horizontally. A theme's border color and an app's own borders on a row or cell carry onto the pinned cells, and an open detail panel (`useTableRowExpansion`) carries its row's divider the same way.++@cixzhangdiff --git a/apps/storybook/stories/TableRowExpansion.stories.tsx b/apps/storybook/stories/TableRowExpansion.stories.tsxindex 93be197c4f..4f7532f233 100644--- a/apps/storybook/stories/TableRowExpansion.stories.tsx+++ b/apps/storybook/stories/TableRowExpansion.stories.tsx@@ -9,6 +9,8 @@ import {proportional,} from '@astryxdesign/core/Table';import type {TableColumn} from '@astryxdesign/core/Table';+import {Theme} from '@astryxdesign/core/theme';+import {neutralTheme} from '@astryxdesign/theme-neutral';import {VStack, HStack} from '@astryxdesign/core/Stack';import {Text, Heading} from '@astryxdesign/core/Text';import {Badge} from '@astryxdesign/core/Badge';@@ -136,6 +138,45 @@ export const DetailPanel: Story = {},};+/**+ * An open panel's divider is the one its row hands down, in the theme's+ * colour, and follows a switch between light and dark: the table sits in a+ * `system`-mode Theme, which follows the operating system. With `override`,+ * an app draws the row's cells dashed in a token colour, which the panel+ * carries and follows across the switch too.+ */+export const PanelDividerFollowsScheme: StoryObj<{override?: boolean}> = {+ args: {override: false},+ render: ({override}) => {+ const [expandedKeys, setExpandedKeys] = useState<Set<string>>(+ () => new Set(['ord-1001']),+ );+ const expansion = useTableRowExpansion<Order>({+ expandedKeys,+ onToggle: key => setExpandedKeys(prev => toggleKey(prev, key)),+ getRowKey: item => item.id,+ renderExpanded: item => <OrderItems order={item} />,+ });+ return (+ <Theme theme={neutralTheme} mode="system">+ <div+ data-testid="panel-divider-scheme"+ style={{backgroundColor: 'var(--color-background-surface)'}}>+ {override && (+ <style>{`[data-testid="panel-divider-scheme"] tbody tr:not([data-expansion-panel]) > td { border-bottom-color: var(--color-text-secondary); border-bottom-style: dashed; }`}</style>+ )}+ <Table+ data={orders}+ columns={columns}+ idKey="id"+ plugins={{expansion}}+ />+ </div>+ </Theme>+ );+ },+};+/*** `getIsItemExpandable` restricts which rows can expand. Here only orders with* more than one line item are expandable; the rest show no chevron and nodiff --git a/apps/storybook/stories/TableStickyColumns.stories.tsx b/apps/storybook/stories/TableStickyColumns.stories.tsxindex 6780e7f255..909221b30b 100644--- a/apps/storybook/stories/TableStickyColumns.stories.tsx+++ b/apps/storybook/stories/TableStickyColumns.stories.tsx@@ -1,6 +1,6 @@// Copyright (c) Meta Platforms, Inc. and affiliates.-import {useState} from 'react';+import React, {useState} from 'react';import type {Meta, StoryObj} from '@storybook/react';import {Table,@@ -9,6 +9,9 @@ import {pixel,} from '@astryxdesign/core/Table';import type {TableColumn} from '@astryxdesign/core/Table';+import {Theme} from '@astryxdesign/core/theme';+import {neutralTheme} from '@astryxdesign/theme-neutral';+import {stoneTheme} from '@astryxdesign/theme-stone';// =============================================================================// Sample Data — wide enough to require horizontal scroll@@ -138,6 +141,197 @@ export const PinStart: Story = {},};+/**+ * A pinned column draws each row's divider itself, so the line under it moves+ * with the column. A theme's border color (`--color-border`, set on the+ * wrapper here) and an app's own `border-bottom` on a row (the second row)+ * both carry over to the pinned cells.+ */+export const PinnedDividers: Story = {+ render: () => {+ const sticky = useTableStickyColumns<Employee>({startKeys: ['name']});+ return (+ <div+ data-testid="pinned-dividers"+ style={+ {+ maxWidth: 720,+ '--color-border': 'rgb(37, 99, 235)',+ } as React.CSSProperties+ }>+ <style>{`[data-testid="pinned-dividers"] tbody tr:nth-child(2) { border-bottom: 2px solid rgb(220, 38, 38); }`}</style>+ <p style={note}>+ A blue theme border color on every row and an app's red 2 px+ border on the second row, both on the pinned Name column as you+ scroll.+ </p>+ <Table+ data={employees}+ columns={columns}+ idKey="id"+ plugins={{stickyColumns: sticky}}+ />+ </div>+ );+ },+};++/**+ * A `system`-mode Theme on its own surface, with a control that switches it+ * to dark: its state lives here, so switching it re-renders only this and the+ * table, not the story that calls the table's hooks.+ */+function ThemeAroundTable({children}: {children: React.ReactNode}) {+ const [isDark, setIsDark] = useState(false);+ const [isStone, setIsStone] = useState(false);+ return (+ <Theme+ theme={isStone ? stoneTheme : neutralTheme}+ mode={isDark ? 'dark' : 'system'}>+ <div style={{backgroundColor: 'var(--color-background-surface)'}}>+ <button type="button" onClick={() => setIsDark(on => !on)}>+ Theme dark+ </button>+ <button type="button" onClick={() => setIsStone(on => !on)}>+ Theme stone+ </button>+ {children}+ </div>+ </Theme>+ );+}++/**+ * A border that changes after mount reaches the pinned cells, and the edge+ * shadows follow columns added without a resize. Hovering a row turns its+ * line purple (an app's `:hover` rule on the cells); "Highlight" sets the+ * third row's border through React state; "Thick top" gives the fourth row a+ * 3 px top border, which wins the collapse over the third row's bottom; "Row+ * borders" draws an app's 2 px blue border on the rows that turns red on+ * hover (`tr:hover`); "First row top" gives the first body row a 3 px top+ * border, which wins over the header's bottom; "Token top border" gives the+ * third row a 3 px top border in the theme's border token, which the pinned+ * cells above it carry as values and which follows a light/dark switch (the+ * table sits in a `system`-mode Theme); "Add columns" widens the table inside+ * the same wrapper.+ */+export const PinnedDividersLive: Story = {+ render: () => {+ const sticky = useTableStickyColumns<Employee>({+ startKeys: ['name'],+ endKeys: ['status'],+ });+ const [isHighlighted, setIsHighlighted] = useState(false);+ const [hasMoreColumns, setHasMoreColumns] = useState(false);+ const [hasThickTop, setHasThickTop] = useState(false);+ const [hasRowBorders, setHasRowBorders] = useState(false);+ const [hasFirstRowTop, setHasFirstRowTop] = useState(false);+ const [hasTokenTop, setHasTokenTop] = useState(false);+ const shown = hasMoreColumns+ ? columns+ : columns.filter(column => ['name', 'status'].includes(column.key));+ return (+ <div data-testid="pinned-dividers-live" style={{maxWidth: 720}}>+ <style>{`[data-testid="pinned-dividers-live"] tbody tr:hover td { border-bottom-color: rgb(147, 51, 234); }`}</style>+ {isHighlighted && (+ <style>{`[data-testid="pinned-dividers-live"] tbody tr:nth-child(3) td { border-bottom: 2px solid rgb(22, 163, 74); }`}</style>+ )}+ {hasRowBorders && (+ <style>{`[data-testid="pinned-dividers-live"] tbody tr { border-bottom: 2px solid rgb(37, 99, 235); } [data-testid="pinned-dividers-live"] tbody tr:hover { border-bottom-color: rgb(220, 38, 38); }`}</style>+ )}+ {hasTokenTop && (+ <style>{`[data-testid="pinned-dividers-live"] tbody tr:nth-child(3) td { border-top: 3px solid var(--color-border); }`}</style>+ )}+ {hasFirstRowTop && (+ <style>{`[data-testid="pinned-dividers-live"] tbody tr:first-child td { border-top: 3px solid rgb(234, 88, 12); }`}</style>+ )}+ {hasThickTop && (+ <style>{`[data-testid="pinned-dividers-live"] tbody tr:nth-child(4) td { border-top: 3px solid rgb(234, 88, 12); }`}</style>+ )}+ <p style={note}>+ <button type="button" onClick={() => setIsHighlighted(on => !on)}>+ Highlight+ </button>{' '}+ <button type="button" onClick={() => setHasThickTop(on => !on)}>+ Thick top+ </button>{' '}+ <button type="button" onClick={() => setHasRowBorders(on => !on)}>+ Row borders+ </button>{' '}+ <button type="button" onClick={() => setHasFirstRowTop(on => !on)}>+ First row top+ </button>{' '}+ <button type="button" onClick={() => setHasTokenTop(on => !on)}>+ Token top border+ </button>{' '}+ <button type="button" onClick={() => setHasMoreColumns(on => !on)}>+ Add columns+ </button>+ </p>+ {/* The table sits in its own Theme (`system` by default, so it+ follows the operating system), switched by a control inside it, so+ the switch does not re-render the component that calls the hooks. */}+ <ThemeAroundTable>+ <Table+ data={employees}+ columns={shown}+ idKey="id"+ plugins={{stickyColumns: sticky}}+ />+ </ThemeAroundTable>+ </div>+ );+ },+};++/**+ * The table appears from state below the component that calls the hooks+ * ("Show table"), the way a tab or a disclosure shows one: the pinned cells+ * still carry the app's red 2 px border on the second row, and follow it when+ * "Recolour row" turns it green from that same component; "Border on cells"+ * moves that border from the row onto its cells.+ */+function RevealBelowOwner({children}: {children: React.ReactNode}) {+ const [isShown, setIsShown] = useState(false);+ const [isGreen, setIsGreen] = useState(false);+ const [isOnCells, setIsOnCells] = useState(false);+ return (+ <div+ data-row-color={isGreen ? 'green' : 'red'}+ data-border-on={isOnCells ? 'cells' : 'row'}>+ <button type="button" onClick={() => setIsShown(on => !on)}>+ Show table+ </button>+ <button type="button" onClick={() => setIsGreen(on => !on)}>+ Recolour row+ </button>+ <button type="button" onClick={() => setIsOnCells(on => !on)}>+ Border on cells+ </button>+ {isShown && children}+ </div>+ );+}++export const PinnedDividersRevealed: Story = {+ render: () => {+ const sticky = useTableStickyColumns<Employee>({startKeys: ['name']});+ return (+ <div data-testid="pinned-dividers-revealed" style={{maxWidth: 720}}>+ <style>{`[data-testid="pinned-dividers-revealed"] tbody tr:nth-child(2) { border-bottom: 2px solid rgb(220, 38, 38); } [data-testid="pinned-dividers-revealed"] [data-row-color="green"] tbody tr:nth-child(2) { border-bottom-color: rgb(22, 163, 74); } [data-testid="pinned-dividers-revealed"] [data-border-on="cells"] tbody tr:nth-child(2) { border-bottom: 0; } [data-testid="pinned-dividers-revealed"] [data-border-on="cells"] tbody tr:nth-child(2) > td { border-bottom: 2px solid rgb(220, 38, 38); } [data-testid="pinned-dividers-revealed"] [data-border-on="cells"][data-row-color="green"] tbody tr:nth-child(2) > td { border-bottom-color: rgb(22, 163, 74); }`}</style>+ <RevealBelowOwner>+ <Table+ data={employees}+ columns={columns}+ idKey="id"+ plugins={{stickyColumns: sticky}}+ />+ </RevealBelowOwner>+ </div>+ );+ },+};+/*** Pin the trailing `Status` column to the end edge.*/diff --git a/packages/core/src/Table/TableCell.tsx b/packages/core/src/Table/TableCell.tsxindex f5a716e59b..b5b0076e0f 100644--- a/packages/core/src/Table/TableCell.tsx+++ b/packages/core/src/Table/TableCell.tsx@@ -145,6 +145,12 @@ const contextMenuCellStyles = stylex.create({const dividerRowStyles = stylex.create({cell: {+ // The width this cell's divider draws, for a pinned cell's own divider+ // to match (plugins/stickyColumns). Private plumbing, not a theme API.+ '--_table-row-divider-width': {+ default: borderVars['--border-width'],+ [stylex.when.ancestor(':last-child', tableRowMarker)]: '0px',+ },borderBottomWidth: {default: borderVars['--border-width'],// Skip border on cells in the last body row to avoid adiff --git a/packages/core/src/Table/TableHeaderCell.tsx b/packages/core/src/Table/TableHeaderCell.tsxindex 6d1670223d..9e1f60e65f 100644--- a/packages/core/src/Table/TableHeaderCell.tsx+++ b/packages/core/src/Table/TableHeaderCell.tsx@@ -83,6 +83,8 @@ const headerStyles = stylex.create({const headerDividerStyles = stylex.create({cell: {+ // For a pinned header cell's own divider to match (plugins/stickyColumns).+ '--_table-row-divider-width': borderVars['--border-width'],borderBottomWidth: borderVars['--border-width'],borderBottomStyle: 'solid',borderBottomColor: colorVars['--color-border'],diff --git a/packages/core/src/Table/__tests__/TableStickyDividers.a11y.browser.spec.ts b/packages/core/src/Table/__tests__/TableStickyDividers.a11y.browser.spec.tsnew file mode 100644index 0000000000..84de3d2e48--- /dev/null+++ b/packages/core/src/Table/__tests__/TableStickyDividers.a11y.browser.spec.ts@@ -0,0 +1,560 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.+// @pr-a11y scope ^packages/core/src/Table/ ^apps/storybook/stories/TableStickyColumns++/**+ * @file TableStickyDividers.a11y.browser.spec.ts+ * @input Built TableStickyColumns stories in real Chromium and WebKit+ * @output Browser evidence that a pinned column draws each row's divider+ * itself: the line under it moves with it, matches the row's own divider,+ * and carries a theme's divider color and an app's row border+ * @position Regression proof for the sticky-columns plugin's pinned dividers+ *+ * With collapsed borders the table paints every border at its cell's static+ * place. A sticky cell moves and its border does not, so the line under a+ * pinned column used to be whichever scrolled cell's border passed beneath it,+ * and was missing where that cell had none.+ */++import {expect, test, type Page} from '@playwright/test';+import {+ DEFAULT_STORYBOOK_DIR,+ serveStorybook,+ type StaticServer,+} from '@astryxdesign/a11y-spec/storybook';++let storybook: StaticServer;+test.beforeAll(async () => {+ storybook = await serveStorybook(+ process.env.ASTRYX_STORYBOOK_DIR ?? DEFAULT_STORYBOOK_DIR,+ );+});+test.afterAll(async () => {+ await storybook?.close();+});++async function mount(page: Page, story: string) {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablestickycolumns--${story}&viewMode=story`,+ );+ const wrapper = page.locator('.astryx-table-scroll-wrapper').first();+ await expect(wrapper).toBeVisible();+ return wrapper;+}++async function scrollTo(page: Page, left: number) {+ await page.evaluate(x => {+ const wrapper = document.querySelector(+ '.astryx-table-scroll-wrapper',+ ) as HTMLElement;+ wrapper.scrollLeft = x;+ }, left);+ // Two frames: the scroll lands and paints.+ await page.evaluate(+ async () =>+ new Promise(resolve =>+ requestAnimationFrame(() => requestAnimationFrame(resolve)),+ ),+ );+}++type Rgb = [number, number, number];++/**+ * The column of pixels within 3 px of a body row's bottom edge (-1: the+ * header row's), top to+ * bottom, at an x inside the pinned cell and at an x inside the first+ * unpinned cell visible past it.+ */+async function dividerPixels(+ page: Page,+ row: number,+): Promise<{pinned: Rgb[]; unpinned: Rgb[]}> {+ const points = await page.evaluate(index => {+ const tr = (+ index < 0+ ? document.querySelector('.astryx-table-scroll-wrapper thead tr')+ : document.querySelectorAll('.astryx-table-scroll-wrapper tbody tr')[+ index+ ]+ ) as HTMLElement;+ const pinned = tr.children[0].getBoundingClientRect();+ return {+ y: Math.round(pinned.bottom),+ pinnedX: Math.round(pinned.left + pinned.width / 2),+ unpinnedX: Math.round(pinned.right + 40),+ };+ }, row);+ const sample = async (x: number): Promise<Rgb[]> => {+ const shot = await page.screenshot({+ clip: {x, y: points.y - 3, width: 1, height: 6},+ scale: 'css',+ });+ return page.evaluate(async b64 => {+ const image = new Image();+ image.src = `data:image/png;base64,${b64}`;+ await image.decode();+ const canvas = document.createElement('canvas');+ canvas.width = image.width;+ canvas.height = image.height;+ const context = canvas.getContext('2d');+ if (context == null) {+ return [];+ }+ context.drawImage(image, 0, 0);+ const data = context.getImageData(0, 0, image.width, image.height).data;+ const column: [number, number, number][] = [];+ for (let i = 0; i < data.length; i += 4) {+ column.push([data[i], data[i + 1], data[i + 2]]);+ }+ return column;+ }, shot.toString('base64'));+ };+ return {+ pinned: await sample(points.pinnedX),+ unpinned: await sample(points.unpinnedX),+ };+}++/**+ * WebKit paints a translucent collapsed border twice, so a token divider+ * shows darker across the row than its colour; a pinned cell draws the+ * token's true colour once. The pixel comparisons against the row's own+ * divider at the token colour hold in Chromium only.+ */+const WEBKIT_DOUBLE_PAINT =+ 'WebKit paints translucent collapsed borders twice; the pinned divider draws the token once';++const near = (a: Rgb, b: Rgb, tolerance = 6) =>+ a.every((channel, i) => Math.abs(channel - b[i]) <= tolerance);+/** Every pixel of one column matches the other's, top to bottom. */+const sameColumn = (a: Rgb[], b: Rgb[], tolerance = 6) =>+ a.length === b.length && a.every((rgb, i) => near(rgb, b[i], tolerance));+/** The darkest pixel of a column: the divider's own color. */+const darkest = (column: Rgb[]): Rgb =>+ column.reduce((best, rgb) =>+ rgb[0] + rgb[1] + rgb[2] < best[0] + best[1] + best[2] ? rgb : best,+ );++test('the divider under a pinned cell matches its row, at rest and scrolled', async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ await mount(page, 'pin-start');+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ for (const row of [0, 1, 2]) {+ const {pinned, unpinned} = await dividerPixels(page, row);+ expect(sameColumn(pinned, unpinned), `row ${row} at ${left}px`).toBe(+ true,+ );+ expect(+ darkest(pinned)[0],+ `row ${row} at ${left}px is drawn`,+ ).toBeLessThan(250);+ }+ }+});++test('a pinned cell keeps its divider where the cell scrolled beneath it has none', async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ await mount(page, 'pin-start');+ await scrollTo(page, 150);+ const before = await dividerPixels(page, 1);+ await page.evaluate(() => {+ const row = document.querySelectorAll(+ '.astryx-table-scroll-wrapper tbody tr',+ )[1];+ const pinned = row.children[0].getBoundingClientRect();+ for (const cell of Array.from(row.children).slice(1)) {+ const rect = cell.getBoundingClientRect();+ if (rect.left <= pinned.right && rect.right >= pinned.left) {+ (cell as HTMLElement).style.borderBottomColor = 'transparent';+ }+ }+ });+ const after = await dividerPixels(page, 1);+ expect(sameColumn(after.pinned, before.pinned)).toBe(true);+});++test("a theme's divider color and an app's row border carry over to the pinned cells", async ({+ page,+}) => {+ await mount(page, 'pinned-dividers');+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ // Row 1: the theme's blue divider, under the pinned cell as elsewhere.+ const themed = await dividerPixels(page, 0);+ expect(+ sameColumn(themed.pinned, themed.unpinned, 24),+ `themed at ${left}px`,+ ).toBe(true);+ const blue = darkest(themed.pinned);+ expect(blue[2], `themed at ${left}px is blue`).toBeGreaterThan(+ blue[0] + 60,+ );+ // Row 2: the app's red row border wins the collapse; the pinned cell+ // draws it too.+ // Every pixel of the column: a pinned line of the theme's blue over the+ // app's red (the row's border not carried) fails here.+ const app = await dividerPixels(page, 1);+ expect(sameColumn(app.pinned, app.unpinned, 24), `app at ${left}px`).toBe(+ true,+ );+ const red = darkest(app.pinned);+ expect(red[0], `app at ${left}px is red`).toBeGreaterThan(red[2] + 60);+ }+});++test('a border that changes after mount reaches the pinned cell', async ({+ page,+}) => {+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await page.getByRole('button', {name: 'Highlight'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ const {pinned, unpinned} = await dividerPixels(page, 2);+ expect(sameColumn(pinned, unpinned, 24), `at ${left}px`).toBe(true);+ const green = darkest(pinned);+ expect(green[1], `at ${left}px is green`).toBeGreaterThan(green[0] + 60);+ }+});++test('the end shadow follows columns added without a resize', async ({+ page,+}) => {+ const wrapper = await mount(page, 'pinned-dividers-live');+ const shadow = async () =>+ wrapper.evaluate(el =>+ (el as HTMLElement).style.getPropertyValue('--table-sticky-shadow-end'),+ );+ expect(await shadow()).toBe('0');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await expect.poll(shadow).toBe('1');+});++test("an app's :hover rule on the cells reaches the pinned cell in CSS", async ({+ page,+}) => {+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await page+ .locator('.astryx-table-scroll-wrapper tbody tr')+ .nth(0)+ .hover({position: {x: 400, y: 10}});+ const {pinned, unpinned} = await dividerPixels(page, 0);+ expect(sameColumn(pinned, unpinned, 24), `at ${left}px`).toBe(true);+ const purple = darkest(pinned);+ expect(purple[2], `at ${left}px is purple`).toBeGreaterThan(purple[1] + 60);+ }+});++test('a pinned cell stops carrying a border once its own wins again', async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ const highlight = page.getByRole('button', {name: 'Highlight'});+ await highlight.click();+ await highlight.click();+ const pinnedCell = page+ .locator('.astryx-table-scroll-wrapper tbody tr')+ .nth(2)+ .locator('td')+ .first();+ // Nothing carried: the token (and a later theme change) reaches it in CSS.+ await expect(pinnedCell).toHaveAttribute('data-astryx-table-pinned', '');+ const {pinned, unpinned} = await dividerPixels(page, 2);+ expect(sameColumn(pinned, unpinned)).toBe(true);+});++test("the next row's wider top border wins under the pinned cell too", async ({+ page,+}) => {+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await page.getByRole('button', {name: 'Thick top'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ const {pinned, unpinned} = await dividerPixels(page, 2);+ expect(sameColumn(pinned, unpinned, 24), `at ${left}px`).toBe(true);+ const orange = darkest(pinned);+ expect(orange[0], `at ${left}px is orange`).toBeGreaterThan(orange[2] + 60);+ }+});++test('a row border recoloured by CSS state alone (tr:hover) reaches the pinned cell', async ({+ page,+}) => {+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await page.getByRole('button', {name: 'Row borders', exact: true}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await page+ .locator('.astryx-table-scroll-wrapper tbody tr')+ .nth(0)+ .hover({position: {x: 400, y: 10}});+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 0);+ const red = darkest(pinned);+ return sameColumn(pinned, unpinned, 24) && red[0] > red[2] + 60;+ }, `at ${left}px`)+ .toBe(true);+ }+});++test("the first body row's wider top border wins under the pinned header too", async ({+ page,+}) => {+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await page.getByRole('button', {name: 'First row top'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ // The header's bottom edge, under the pinned header cell and past it.+ const {pinned, unpinned} = await dividerPixels(page, -1);+ expect(sameColumn(pinned, unpinned, 24), `at ${left}px`).toBe(true);+ const orange = darkest(pinned);+ expect(orange[0], `at ${left}px is orange`).toBeGreaterThan(orange[2] + 60);+ }+});++test('a carried border follows an operating-system switch between light and dark', async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ // The story's table sits in a `system`-mode Theme.+ await page.emulateMedia({colorScheme: 'light'});+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ // The third row's wider top border, in the border token: the pinned cells+ // above it carry its colour as values, which the mode watch reads again.+ await page.getByRole('button', {name: 'Token top border'}).click();+ // Let the resize read that follows the border land first, so the switch+ // below is re-read by the mode watch alone.+ await page.waitForTimeout(200);+ await page.emulateMedia({colorScheme: 'dark'});+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 1);+ return sameColumn(pinned, unpinned, 12);+ }, `at ${left}px`)+ .toBe(true);+ }+});++test("an open panel's divider follows an operating-system switch between light and dark", async ({+ page,+}) => {+ await page.emulateMedia({colorScheme: 'light'});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablerowexpansion--panel-divider-follows-scheme&viewMode=story`,+ );+ await expect(page.locator('tr[data-expansion-panel]')).toBeVisible();+ // The colour the panel's divider draws, against its row's cells' (the+ // panel sits on its own surface, so its pixels differ from a row's).+ const colours = async () =>+ page.evaluate(() => {+ const panel = document.querySelector('tr[data-expansion-panel] > td');+ const row =+ panel?.parentElement?.previousElementSibling?.lastElementChild;+ return {+ panel: panel == null ? '' : getComputedStyle(panel).borderBottomColor,+ row: row == null ? '' : getComputedStyle(row).borderBottomColor,+ };+ });+ const light = await colours();+ expect(light.panel).toBe(light.row);+ // No override reaches the row, so the panel carries nothing: its divider+ // is the tokens, in CSS, and follows a theme change on its own.+ expect(+ await page.evaluate(() => {+ const panel = document.querySelector<HTMLElement>(+ 'tr[data-expansion-panel] > td',+ );+ return panel?.style.getPropertyValue('--_table-panel-divider-color');+ }),+ ).toBe('');+ await page.emulateMedia({colorScheme: 'dark'});+ await expect+ .poll(async () => {+ const dark = await colours();+ return dark.panel === dark.row && dark.panel !== light.panel;+ })+ .toBe(true);+});++test("a carried border follows a theme switched at the same mode between the hooks' owner and the table", async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ await page.emulateMedia({colorScheme: 'light'});+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ await page.getByRole('button', {name: 'Token top border'}).click();+ await page.waitForTimeout(200);+ // Another theme in the same mode, from the Theme around the table: the+ // component that calls the hooks does not re-render.+ await page.getByRole('button', {name: 'Theme stone'}).click();+ // The two themes' border tokens are a few levels apart in pixels, so the+ // pinned divider's computed colour is compared with the border it carries.+ await expect+ .poll(async () =>+ page.evaluate(() => {+ const row = document.querySelectorAll<HTMLTableRowElement>(+ '.astryx-table-scroll-wrapper tbody tr',+ );+ const pinned = row[1]?.querySelector('[data-astryx-table-pinned]');+ const below = row[2]?.cells[row[2].cells.length - 2];+ if (pinned == null || below == null) {+ return false;+ }+ return (+ getComputedStyle(pinned, '::before').borderBottomColor ===+ getComputedStyle(below).borderTopColor+ );+ }),+ )+ .toBe(true);+});++test("an open panel's carried override follows an operating-system switch between light and dark", async ({+ page,+}) => {+ await page.emulateMedia({colorScheme: 'light'});+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablerowexpansion--panel-divider-follows-scheme&viewMode=story&args=override:!true`,+ );+ await expect(page.locator('tr[data-expansion-panel]')).toBeVisible();+ const colours = async () =>+ page.evaluate(() => {+ const panel = document.querySelector('tr[data-expansion-panel] > td');+ const row =+ panel?.parentElement?.previousElementSibling?.lastElementChild;+ return {+ panel: panel == null ? '' : getComputedStyle(panel).borderBottomColor,+ row: row == null ? '' : getComputedStyle(row).borderBottomColor,+ style: panel == null ? '' : getComputedStyle(panel).borderBottomStyle,+ };+ });+ const light = await colours();+ expect(light.panel).toBe(light.row);+ expect(light.style).toBe('dashed');+ await page.emulateMedia({colorScheme: 'dark'});+ await expect+ .poll(async () => {+ const dark = await colours();+ return dark.panel === dark.row && dark.panel !== light.panel;+ })+ .toBe(true);+});++test("a carried border follows a Theme switched between the hooks' owner and the table", async ({+ page,+ browserName,+}) => {+ test.skip(browserName === 'webkit', WEBKIT_DOUBLE_PAINT);+ await page.emulateMedia({colorScheme: 'light'});+ await mount(page, 'pinned-dividers-live');+ await page.getByRole('button', {name: 'Add columns'}).click();+ // The third row's wider top border, in the border token: the pinned cells+ // above it carry its colour as values, which the mode watch reads again.+ await page.getByRole('button', {name: 'Token top border'}).click();+ // The Theme around the table switches on its own state: the component+ // that calls the hooks does not re-render.+ await page.getByRole('button', {name: 'Theme dark'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 1);+ return sameColumn(pinned, unpinned, 12);+ }, `at ${left}px`)+ .toBe(true);+ }+});++test("a table revealed from state below the hooks' owner carries a winning row border", async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablestickycolumns--pinned-dividers-revealed&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Show table'}).click();+ await expect(page.locator('.astryx-table-scroll-wrapper')).toBeVisible();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 1);+ const red = darkest(pinned);+ return sameColumn(pinned, unpinned, 24) && red[0] > red[2] + 60;+ }, `at ${left}px`)+ .toBe(true);+ }+});++test("a row border recoloured without re-rendering the hooks' owner stays whole under the pinned column", async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablestickycolumns--pinned-dividers-revealed&viewMode=story`,+ );+ await page.getByRole('button', {name: 'Show table'}).click();+ await expect(page.locator('.astryx-table-scroll-wrapper')).toBeVisible();+ await page.getByRole('button', {name: 'Recolour row'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 1);+ const green = darkest(pinned);+ return sameColumn(pinned, unpinned, 24) && green[1] > green[0] + 60;+ }, `at ${left}px`)+ .toBe(true);+ }+});++test("a cell border recoloured without re-rendering the hooks' owner stays whole under the pinned column", async ({+ page,+}) => {+ await page.goto(+ `${storybook.origin}/iframe.html?id=core-tablestickycolumns--pinned-dividers-revealed&viewMode=story`,+ );+ // The border is on the cells when the table first reads it, so the pinned+ // cells carry its width alone; the recolour then reaches them in CSS.+ await page.getByRole('button', {name: 'Border on cells'}).click();+ await page.getByRole('button', {name: 'Show table'}).click();+ await expect(page.locator('.astryx-table-scroll-wrapper')).toBeVisible();+ await expect(+ page+ .locator('tbody tr:has(> [data-astryx-table-pinned])')+ .nth(1)+ .locator('> [data-astryx-table-pinned]'),+ ).toHaveAttribute('data-astryx-table-pinned', 'width');+ await page.getByRole('button', {name: 'Recolour row'}).click();+ for (const left of [0, 150]) {+ await scrollTo(page, left);+ await expect+ .poll(async () => {+ const {pinned, unpinned} = await dividerPixels(page, 1);+ const green = darkest(pinned);+ return sameColumn(pinned, unpinned, 24) && green[1] > green[0] + 60;+ }, `at ${left}px`)+ .toBe(true);+ }+});diff --git a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsxindex 996cc039d2..1fcdad6c8e 100644--- a/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx+++ b/packages/core/src/Table/plugins/columnResize/useTableColumnResize.tsx@@ -781,6 +781,13 @@ export function useTableColumnResize<T extends Record<string, unknown>>(const dragStateRef = useRef<DragState | null>(null);const isDraggingRef = useRef(false);+ // The scroll container's merged ref, kept while the inner ref is the same,+ // so React does not detach and re-attach it (and every plugin's listeners+ // on it) on every render.+ const mergedScrollWrapperRef = useRef<{+ inner: ScrollWrapperRenderProps['htmlProps']['ref'] | null;+ merged: (node: HTMLDivElement | null) => void;+ } | null>(null);const tableRef = useRef<HTMLTableElement | null>(null);const globalMinWidth = config.minWidth;@@ -941,14 +948,22 @@ export function useTableColumnResize<T extends Record<string, unknown>>(): ScrollWrapperRenderProps {// Compose with any ref a prior plugin (e.g. sticky columns,// virtualization) already set on the scroll container.- const existingRef = props.htmlProps.ref;- const mergedRef = (node: HTMLDivElement | null) => {- attachScrollGate(node);- if (typeof existingRef === 'function') {- existingRef(node);- } else if (existingRef != null) {- existingRef.current = node;- }+ const existingRef = props.htmlProps.ref ?? null;+ const cached = mergedScrollWrapperRef.current;+ const mergedRef =+ cached != null && cached.inner === existingRef+ ? cached.merged+ : (node: HTMLDivElement | null) => {+ attachScrollGate(node);+ if (typeof existingRef === 'function') {+ existingRef(node);+ } else if (existingRef != null) {+ existingRef.current = node;+ }+ };+ mergedScrollWrapperRef.current = {+ inner: existingRef,+ merged: mergedRef,};return {...props,diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsxindex 47950ccc27..7ed74d16ac 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.test.tsx@@ -296,9 +296,10 @@ describe('useTableRowExpansion (detail panel)', () => {for (const cell of cellsOf('Ada')) {expect(cell).toHaveStyle({borderBottomWidth: '0'});}- expect(panelCell()).toHaveStyle({- borderBottomWidth: 'var(--border-width)',- });+ // The token width, unless the row hands down its own.+ expect(getComputedStyle(panelCell()).borderBottomWidth).toMatch(+ /var\(--_table-panel-divider-width,\s*var\(--border-width\)\)/,+ );});it('leaves collapsed rows keeping their own divider', () => {@@ -310,16 +311,97 @@ describe('useTableRowExpansion (detail panel)', () => {it('draws no panel divider on a table without row dividers', () => {render(<Harness initialExpanded={new Set(['a'])} dividers="none" />);- expect(panelCell()).not.toHaveStyle({- borderBottomWidth: 'var(--border-width)',- });+ expect(getComputedStyle(panelCell()).borderBottomWidth).not.toMatch(+ /--border-width/,+ );+ });++ it('reads the colour mode once per table, however many panels are open', () => {+ const original = window.matchMedia;+ const listeners = (open: Set<string>) => {+ let count = 0;+ window.matchMedia = (query: string) => {+ const list = original+ ? original(query)+ : ({matches: false, media: query} as MediaQueryList);+ return {+ ...list,+ matches: list.matches,+ media: query,+ addEventListener: () => {+ count += 1;+ },+ removeEventListener: () => {},+ addListener: () => {+ count += 1;+ },+ removeListener: () => {},+ } as MediaQueryList;+ };+ const {unmount} = render(<Harness initialExpanded={open} />);+ unmount();+ return count;+ };+ try {+ expect(listeners(new Set(['a', 'b', 'c']))).toBe(+ listeners(new Set(['a'])),+ );+ } finally {+ window.matchMedia = original;+ }+ });++ it("carries the row's own divider onto the panel (Table FR14)", () => {+ render(<Harness />);+ const row = cellsOf('Ada')[0].parentElement as HTMLTableRowElement;+ // An app's (or a theme's) border on the row's cells.+ for (const cell of row.cells) {+ cell.style.borderBottomColor = 'rgb(255, 0, 0)';+ cell.style.borderBottomStyle = 'dashed';+ }+ fireEvent.click(screen.getAllByRole('button', {name: /expand/i})[0]);+ const cell = panelCell();+ expect(cell.style.getPropertyValue('--_table-panel-divider-color')).toBe(+ 'rgb(255, 0, 0)',+ );+ expect(cell.style.getPropertyValue('--_table-panel-divider-style')).toBe(+ 'dashed',+ );+ // The panel keeps its own width (a value, never inherited from a panel+ // around it) while the row's own border does not win.+ expect(cell.style.getPropertyValue('--_table-panel-divider-width')).toBe(+ 'initial',+ );+ // A width set on the row's cells is the divider's too.+ for (const rowCell of row.cells) {+ rowCell.style.borderBottomWidth = '3px';+ }+ fireEvent.click(screen.getAllByRole('button', {name: /expand/i})[0]);+ expect(cell.style.getPropertyValue('--_table-panel-divider-width')).toBe(+ '3px',+ );+ fireEvent.click(screen.getAllByRole('button', {name: /collapse/i})[1]);+ for (const rowCell of row.cells) {+ rowCell.style.borderBottomWidth = '';+ }+ // An app's wider border on the row itself wins; the next commit+ // (opening another row) reads it.+ row.style.borderBottom = '3px solid rgb(0, 0, 255)';+ fireEvent.click(screen.getAllByRole('button', {name: /expand/i})[0]);+ expect(cell.style.getPropertyValue('--_table-panel-divider-width')).toBe(+ '3px',+ );+ expect(cell.style.getPropertyValue('--_table-panel-divider-color')).toBe(+ 'rgb(0, 0, 255)',+ );});it('draws the panel divider under grid dividers too', () => {render(<Harness initialExpanded={new Set(['a'])} dividers="grid" />);- expect(panelCell()).toHaveStyle({- borderBottomWidth: 'var(--border-width)',- });+ // The token width, unless the row hands down its own.+ expect(getComputedStyle(panelCell()).borderBottomWidth).toMatch(+ /var\(--_table-panel-divider-width,\s*var\(--border-width\)\)/,+ );});});diff --git a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsxindex adabb5e997..095a49fae8 100644--- a/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx+++ b/packages/core/src/Table/plugins/rowExpansion/useTableRowExpansion.tsx@@ -18,7 +18,13 @@* - /packages/core/src/Table/useTableRowExpansion.doc.mjs*/-import {useMemo, useRef, type ReactNode} from 'react';+import {+ useLayoutEffect,+ useMemo,+ useRef,+ type ReactNode,+ type RefObject,+} from 'react';import * as stylex from '@stylexjs/stylex';import {spacingVars,@@ -29,6 +35,8 @@ import {easeVars,} from '../../../theme/tokens.stylex';import {tableRowMarker} from '../../table.stylex';+import {panelDividerFor} from '../../rowDivider';+import {useTheme, useThemeName} from '../../../theme/useTheme';import {Icon} from '../../../Icon';import {VisuallyHidden} from '../../../VisuallyHidden';import {resolveContextActions} from '../../tableContextMenu';@@ -216,16 +224,19 @@ const dividerStyles = stylex.create({expandedRowCell: {borderBottomWidth: 0,},+ // The row's divider, carried down: its row's themed or app-set border+ // reaches the panel through `--_table-panel-divider-*` on the panel's cell+ // (set after each commit, see ExpansionPanelCell), the tokens otherwise.panelCell: {borderBottomWidth: {- default: borderVars['--border-width'],+ default: `var(--_table-panel-divider-width, ${borderVars['--border-width']})`,// Same rule TableCell uses: no trailing line under the last row of the// table. Scoped to the marker so <tbody>, also a :last-child, does not// match and suppress every panel's border.[stylex.when.ancestor(':last-child', tableRowMarker)]: '0',},- borderBottomStyle: 'solid',- borderBottomColor: colorVars['--color-border'],+ borderBottomStyle: 'var(--_table-panel-divider-style, solid)',+ borderBottomColor: `var(--_table-panel-divider-color, ${colorVars['--color-border']})`,},});@@ -336,6 +347,73 @@ function ExpansionChevron({);}+const PANEL_DIVIDER_PROPERTIES = [+ '--_table-panel-divider-width',+ '--_table-panel-divider-style',+ '--_table-panel-divider-color',+] as const;++/**+ * Carries the row's divider onto a panel cell where an override makes it+ * differ from what the panel paints on its own (the divider tokens, in CSS),+ * and carries nothing otherwise, so a later token or theme change reaches+ * the panel the way it reaches the row.+ */+function carryPanelDivider(cell: HTMLTableCellElement): void {+ const row = cell.parentElement?.previousElementSibling;+ const edge = row == null ? null : panelDividerFor(row);+ if (edge == null) {+ return;+ }+ // What the panel paints with nothing carried.+ const carried = PANEL_DIVIDER_PROPERTIES.map(name =>+ cell.style.getPropertyValue(name),+ );+ if (carried.some(value => value !== '')) {+ for (const name of PANEL_DIVIDER_PROPERTIES) {+ cell.style.removeProperty(name);+ }+ }+ const own = getComputedStyle(cell);+ const isOverride =+ edge.color !== own.borderBottomColor ||+ edge.style !== own.borderBottomStyle ||+ (edge.width !== 'initial' && edge.width !== own.borderBottomWidth);+ if (!isOverride) {+ return;+ }+ const next = [edge.width, edge.style, edge.color];+ PANEL_DIVIDER_PROPERTIES.forEach((name, index) => {+ cell.style.setProperty(name, next[index]);+ });+}++/**+ * One per table: when the colour mode or the theme changes (a Theme's, or+ * the operating system's mode under `system`) the open panels' carried+ * dividers are read again. The panels register their cells with the hook.+ */+function PanelDividerModeWatch({+ cellsRef,+}: {+ cellsRef: RefObject<Set<HTMLTableCellElement>>;+}) {+ const {mode} = useTheme();+ const themeName = useThemeName();+ const lastRef = useRef({mode, themeName});+ useLayoutEffect(() => {+ const last = lastRef.current;+ if (last.mode === mode && last.themeName === themeName) {+ return;+ }+ lastRef.current = {mode, themeName};+ for (const cell of cellsRef.current) {+ carryPanelDivider(cell);+ }+ }, [mode, themeName, cellsRef]);+ return null;+}+/*** The detail panel's cell. A component rather than a bare `<td>` so it can* read the table's density and divider mode off the context — to indent itself@@ -345,15 +423,39 @@ function ExpansionChevron({*/function ExpansionPanelCell({colSpan,+ cellsRef,children,}: {colSpan: number;+ cellsRef: RefObject<Set<HTMLTableCellElement>>;children: ReactNode;}) {const ctx = useTableContext();const hasRowDividers = ctx?.dividers === 'rows' || ctx?.dividers === 'grid';+ const cellRef = useRef<HTMLTableCellElement>(null);+ // The panel carries its row's divider (a theme's `table-cell` border or an+ // app's own never reach this cell, which is not one of the row's cells).+ // Read after each commit, and on a colour-mode change by the table's one+ // PanelDividerModeWatch.+ useLayoutEffect(() => {+ if (hasRowDividers && cellRef.current != null) {+ carryPanelDivider(cellRef.current);+ }+ });+ useLayoutEffect(() => {+ const cell = cellRef.current;+ if (cell == null || !hasRowDividers) {+ return;+ }+ const cells = cellsRef.current;+ cells.add(cell);+ return () => {+ cells.delete(cell);+ };+ }, [cellsRef, hasRowDividers]);return (<td+ ref={cellRef}colSpan={colSpan}{...stylex.props(expansionStyles.expandedCell,@@ -414,6 +516,8 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(// Final rendered column count, captured in transformColumns (pipeline step// 1) and read in transformBodyRow for the detail panel's colSpan.const columnCountRef = useRef(1);+ // The open panels' cells, for the table's one colour-mode watch.+ const panelCellsRef = useRef(new Set<HTMLTableCellElement>());const expansionColumn = useMemo((): TableColumn<T> => ({@@ -448,6 +552,15 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(return useMemo((): TablePlugin<T> => ({+ // One colour-mode watch per table for the open panels' dividers.+ transformTableContext(children: ReactNode): ReactNode {+ return (+ <>+ {children}+ <PanelDividerModeWatch cellsRef={panelCellsRef} />+ </>+ );+ },transformColumns(columns: TableColumn<T>[]) {const withExpansion = [expansionColumn, ...columns];columnCountRef.current = withExpansion.length;@@ -591,7 +704,9 @@ export function useTableRowExpansion<T extends Record<string, unknown>>(tableRowMarker,panelVariant === 'muted' && expansionStyles.expandedRow,)}>- <ExpansionPanelCell colSpan={columnCountRef.current}>+ <ExpansionPanelCell+ colSpan={columnCountRef.current}+ cellsRef={panelCellsRef}>{renderExpanded(item)}</ExpansionPanelCell></tr>diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsxindex eb6454ec7c..ad888ddd14 100644--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.test.tsx@@ -13,7 +13,7 @@* jsdom-visible, plugin-owned signal that a column is pinned and at what offset.*/-import {describe, it, expect} from 'vitest';+import {afterEach, describe, it, expect, vi} from 'vitest';import {render, screen} from '@testing-library/react';import {Table} from '../../Table';import {useTableStickyColumns} from './useTableStickyColumns';@@ -281,4 +281,54 @@ describe('useTableStickyColumns', () => {expect(getHeaderCell('team').style.position).toBe('');});});++ describe('the scroll container attaches once', () => {+ afterEach(() => {+ vi.unstubAllGlobals();+ });++ it.each([true, false])(+ 'keeps one attach across renders with column resize composed (resize first: %s)',+ resizeFirst => {+ let observers = 0;+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ constructor() {+ observers += 1;+ }+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ function Harness({tick}: {tick: number}) {+ const sticky = useTableStickyColumns<Row>({startKeys: ['name']});+ const resize = useTableColumnResize<Row>({+ columns: columns as TableColumn<Record<string, unknown>>[],+ });+ return (+ <Table+ data={data}+ columns={columns}+ idKey="id"+ aria-describedby={`tick-${tick}`}+ plugins={+ resizeFirst+ ? {resize, stickyColumns: sticky}+ : {stickyColumns: sticky, resize}+ }+ />+ );+ }+ const {rerender} = render(<Harness tick={0} />);+ const attached = observers;+ rerender(<Harness tick={1} />);+ rerender(<Harness tick={2} />);+ rerender(<Harness tick={3} />);+ // Three plain re-renders: no plugin's scroll container re-attaches.+ expect(observers).toBe(attached);+ },+ );+ });});diff --git a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsxindex 9b900de6e0..a18acccd85 100644--- a/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx+++ b/packages/core/src/Table/plugins/stickyColumns/useTableStickyColumns.tsx@@ -13,7 +13,15 @@* - /packages/core/src/Table/index.ts (exports)*/-import {useCallback, useMemo, useRef, type CSSProperties} from 'react';+import {+ useCallback,+ useLayoutEffect,+ useMemo,+ useRef,+ type CSSProperties,+ type ReactNode,+ type RefObject,+} from 'react';import * as stylex from '@stylexjs/stylex';import {colorVars, durationVars, easeVars} from '../../../theme/tokens.stylex';import type {@@ -24,6 +32,8 @@ import type {ScrollWrapperRenderProps,} from '../../types';import {resolveColumnFloorWidths} from '../../columnUtils';+import {collapsedBottom} from '../../rowDivider';+import {useTheme, useThemeName} from '../../../theme/useTheme';// =============================================================================// Config@@ -159,6 +169,33 @@ function resolveStickySide(const SHADOW_VAR_START = '--table-sticky-shadow-start';const SHADOW_VAR_END = '--table-sticky-shadow-end';+// A pinned cell draws its own row divider. With collapsed borders the table+// paints every border at its cell's static place: a sticky cell moves, its+// border does not, so without this the line under a pinned column would be+// whichever scrolled cell's border passes beneath it, and missing where that+// cell has none. The cell's ::before (already the row overlay's layer) extends+// over the cell's border area, covers whatever the table painted there with+// the pinned base, and draws the divider in the cell's own border color and+// style (inherited, so a theme, a token switch or an app's rule on the cell,+// `:hover` included, carries over in CSS) at the cell's divider width+// (TableCell.tsx). Where another border wins the collapse instead (an app's+// border on the row, or the next row's top border), it is read after each+// commit and on resize and carried as the cell's `carry` state+// (syncPinnedDividers).+const PINNED_ATTRIBUTE = 'data-astryx-table-pinned';+/** Spread into a pinned cell's props: the attribute the divider sync finds. */+const PINNED_PROPS: Record<string, string> = {[PINNED_ATTRIBUTE]: ''};+const CARRY = 'carry';+const CARRYING = '[data-astryx-table-pinned="carry"]';+// The cell's own border wins at another width than its divider's: only the+// width is carried, and style and colour keep inheriting from the cell.+const CARRY_WIDTH = 'width';+const PINNED_DIVIDER_WIDTH = '--_table-row-divider-app-width';+const PINNED_DIVIDER_STYLE = '--_table-row-divider-app-style';+const PINNED_DIVIDER_COLOR = '--_table-row-divider-app-color';+const PINNED_BASE = `var(--table-sticky-background, ${colorVars['--color-background-card']})`;+const DIVIDER_WIDTH = `var(${PINNED_DIVIDER_WIDTH}, var(--_table-row-divider-width, 0px))`;+const stickyStyles = stylex.create({cell: {position: 'sticky',@@ -176,6 +213,25 @@ const stickyStyles = stylex.create({zIndex: -1,pointerEvents: 'none',backgroundColor: 'var(--table-row-overlay, transparent)',+ // The divider: the layer reaches the bottom of the cell's border area,+ // paints the pinned base there (hiding the table's static border and any+ // scrolled cell's border), then the divider over it.+ marginBottom: `calc(-1 * ${DIVIDER_WIDTH})`,+ borderBottomWidth: DIVIDER_WIDTH,+ borderBottomStyle: {+ default: 'inherit',+ [CARRYING]: `var(${PINNED_DIVIDER_STYLE}, solid)`,+ },+ borderBottomColor: {+ default: 'inherit',+ [CARRYING]: `var(${PINNED_DIVIDER_COLOR}, ${colorVars['--color-border']})`,+ },+ backgroundImage: `linear-gradient(${PINNED_BASE}, ${PINNED_BASE})`,+ backgroundSize: `100% ${DIVIDER_WIDTH}`,+ backgroundPosition: 'bottom',+ backgroundRepeat: 'no-repeat',+ backgroundOrigin: 'border-box',+ backgroundClip: 'border-box',transitionProperty: 'background-color',transitionDuration: durationVars['--duration-fast'],transitionTimingFunction: easeVars['--ease-standard'],@@ -256,6 +312,116 @@ const shadowStyles = stylex.create({},});+// =============================================================================+// Pinned dividers: app overrides+// =============================================================================++/**+ * The pinned divider draws the border the table would paint under the cell.+ * The cell's own border at its divider width: drawn in CSS, nothing carried.+ * The cell's own border at another width (an app's 2 px `td` border): only+ * the width is carried; style and colour inherit, so a restyle reaches it.+ * A row's or a row group's border: nothing drawn, since the table paints it+ * along the whole row. The next row's cell top: carried as values. Read after each commit and on resize, never on scroll.+ * Every read comes before any write, and a cell is written only when what it+ * carries changes.+ */+function syncPinnedDividers(+ root: HTMLElement,+ rows?: ReadonlySet<Element>,+): void {+ const changes: [HTMLTableCellElement, string, string[] | null][] = [];+ const cells =+ rows == null+ ? root.querySelectorAll<HTMLTableCellElement>(`[${PINNED_ATTRIBUTE}]`)+ : [...rows].flatMap(row => [+ ...row.querySelectorAll<HTMLTableCellElement>(+ `:scope > [${PINNED_ATTRIBUTE}]`,+ ),+ ]);+ for (const cell of cells) {+ const edge = collapsedBottom(cell);+ const dividerWidth =+ parseFloat(+ getComputedStyle(cell).getPropertyValue('--_table-row-divider-width'),+ ) || 0;+ const carried = cell.getAttribute(PINNED_ATTRIBUTE);+ if (edge.isOwn && edge.width === dividerWidth) {+ if (carried !== '') {+ changes.push([cell, '', null]);+ }+ continue;+ }+ // The cell's own border at another width: carry the width alone, so a+ // restyle of its colour or style reaches the pinned divider in CSS.+ if (edge.isOwn) {+ const width = `${edge.width}px`;+ if (+ carried !== CARRY_WIDTH ||+ cell.style.getPropertyValue(PINNED_DIVIDER_WIDTH) !== width+ ) {+ changes.push([cell, CARRY_WIDTH, [width]]);+ }+ continue;+ }+ // A row's border (or a row group's) is painted by the table along the+ // whole row, under the pinned cell too, and follows a restyle in CSS+ // alone: the pinned cell draws nothing over it. Only a cell's border is+ // copied as values.+ const value = edge.isRow+ ? ['0px', 'none', 'transparent']+ : [`${edge.width}px`, edge.style, edge.color];+ const isSame =+ carried === CARRY &&+ cell.style.getPropertyValue(PINNED_DIVIDER_WIDTH) === value[0] &&+ cell.style.getPropertyValue(PINNED_DIVIDER_STYLE) === value[1] &&+ cell.style.getPropertyValue(PINNED_DIVIDER_COLOR) === value[2];+ if (!isSame) {+ changes.push([cell, CARRY, value]);+ }+ }+ for (const [cell, mode, value] of changes) {+ cell.setAttribute(PINNED_ATTRIBUTE, mode);+ const [width, style, color] = value ?? [];+ for (const [name, next] of [+ [PINNED_DIVIDER_WIDTH, width],+ [PINNED_DIVIDER_STYLE, style],+ [PINNED_DIVIDER_COLOR, color],+ ] as const) {+ if (next == null) {+ cell.style.removeProperty(name);+ } else {+ cell.style.setProperty(name, next);+ }+ }+ }+}++/**+ * Rendered inside the table: when the colour mode or the theme around it+ * changes (a Theme's, wherever that Theme sits above the table, or the+ * operating system's mode under `system`), the colours resolve again with no+ * commit of the hook's owner, so the pinned dividers' carried borders are+ * read again.+ */+function PinnedDividerModeWatch({+ refreshRef,+}: {+ refreshRef: RefObject<(() => void) | null>;+}) {+ const {mode} = useTheme();+ const themeName = useThemeName();+ const lastRef = useRef({mode, themeName});+ useLayoutEffect(() => {+ const last = lastRef.current;+ if (last.mode !== mode || last.themeName !== themeName) {+ lastRef.current = {mode, themeName};+ refreshRef.current?.();+ }+ }, [mode, themeName, refreshRef]);+ return null;+}+// Stable empty default so an unset start/end doesn't allocate a fresh array// (and bust the memo) on every render.const EMPTY: string[] = [];@@ -288,9 +454,17 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(// listeners (synchronizing with the DOM) rather than React state, so// scrolling never triggers re-renders.const detachRef = useRef<(() => void) | null>(null);+ // Re-reads the edge shadows and the pinned dividers; set while attached.+ const refreshRef = useRef<(() => void) | null>(null);+ // The scroll container's merged ref, kept while the inner ref is the same.+ const mergedScrollWrapperRef = useRef<{+ inner: ScrollWrapperRenderProps['htmlProps']['ref'] | null;+ merged: (node: HTMLDivElement | null) => void;+ } | null>(null);const attachScrollShadow = useCallback((el: HTMLDivElement | null) => {detachRef.current?.();detachRef.current = null;+ refreshRef.current = null;if (!el) {return;}@@ -319,19 +493,110 @@ export function useTableStickyColumns<T extends Record<string, unknown>>();}};+ // Whether the pinned dividers were read since this attach.+ let hasRead = false;+ const resize = () => {+ update();+ syncPinnedDividers(el);+ hasRead = true;+ };+ // The observer's first callback reports the size at observe time. The+ // hook owner's after-commit read usually came first; a table mounted+ // from state below that owner (a tab, a disclosure) attached without it,+ // so the dividers are read here then.+ let hasObserved = false;+ const onResize = () => {+ if (hasObserved || !hasRead) {+ hasObserved = true;+ resize();+ return;+ }+ hasObserved = true;+ update();+ };el.addEventListener('scroll', update, {passive: true});+ // A row border can change by CSS state alone (`tr:hover`,+ // `:focus-within`): on pointer and focus changes, the rows they touch+ // (and the row above each, whose divider a row's top border joins) are+ // read again, once per frame.+ const touched = new Set<Element>();+ let frame = 0;+ const onStateChange = (event: Event) => {+ for (const target of [+ event.target,+ (event as PointerEvent | FocusEvent).relatedTarget,+ ]) {+ const row = target instanceof Element ? target.closest('tr') : null;+ if (row == null || !el.contains(row)) {+ continue;+ }+ touched.add(row);+ const above =+ row.previousElementSibling ??+ row.parentElement?.previousElementSibling?.lastElementChild;+ if (above != null) {+ touched.add(above);+ }+ }+ if (touched.size > 0 && frame === 0) {+ frame = requestAnimationFrame(() => {+ frame = 0;+ syncPinnedDividers(el, new Set(touched));+ touched.clear();+ });+ }+ };+ const stateEvents = [+ 'pointerover',+ 'pointerout',+ 'focusin',+ 'focusout',+ ] as const;+ for (const type of stateEvents) {+ el.addEventListener(type, onStateChange, {passive: true});+ }const resizeObserver =- typeof ResizeObserver !== 'undefined' ? new ResizeObserver(update) : null;+ typeof ResizeObserver !== 'undefined'+ ? new ResizeObserver(onResize)+ : null;resizeObserver?.observe(el);+ // The table too: columns added or widened change what scrolls without+ // resizing the wrapper.+ const table = el.querySelector('table');+ if (table != null) {+ resizeObserver?.observe(table);+ }+ // The pinned dividers are read after the commit that attached this+ // (the refresh layout effect below), not here as well.update();+ refreshRef.current = resize;detachRef.current = () => {el.removeEventListener('scroll', update);+ for (const type of stateEvents) {+ el.removeEventListener(type, onStateChange);+ }+ cancelAnimationFrame(frame);resizeObserver?.disconnect();};}, []);+ // After each commit: a border that changed with the render (a row+ // highlighted on click) reaches the pinned divider, and the edge shadows+ // follow content that changed without a resize.+ useLayoutEffect(() => {+ refreshRef.current?.();+ });+return useMemo((): TablePlugin<T> => ({+ transformTableContext(children: ReactNode): ReactNode {+ return (+ <>+ {children}+ <PinnedDividerModeWatch refreshRef={refreshRef} />+ </>+ );+ },transformHeaderCell(props: HeaderCellRenderProps,column: TableColumn<T>,@@ -361,6 +626,7 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(...props,htmlProps: {...props.htmlProps,+ ...PINNED_PROPS,style: {...props.htmlProps.style, ...offsetStyle},},xstyle: [@@ -389,6 +655,7 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(...props,htmlProps: {...props.htmlProps,+ ...PINNED_PROPS,style: {...props.htmlProps.style, ...offsetStyle},},xstyle: [@@ -408,16 +675,28 @@ export function useTableStickyColumns<T extends Record<string, unknown>>(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;- }+ // scroll container. One merged ref per inner ref, so React does not+ // re-attach it on every render while the plugins composed with this+ // one keep theirs stable too (column resize does): the scroll+ // listeners and the resize observer attach once, and the pinned+ // dividers are read after each commit (the refresh effect).+ const existingRef = props.htmlProps.ref ?? null;+ const cached = mergedScrollWrapperRef.current;+ const mergedRef =+ cached != null && cached.inner === existingRef+ ? cached.merged+ : (node: HTMLDivElement | null) => {+ attachScrollShadow(node);+ if (typeof existingRef === 'function') {+ existingRef(node);+ } else if (existingRef != null) {+ // RefObject — assign through its writable `.current`.+ existingRef.current = node;+ }+ };+ mergedScrollWrapperRef.current = {+ inner: existingRef,+ merged: mergedRef,};return {...props,diff --git a/packages/core/src/Table/rowDivider.ts b/packages/core/src/Table/rowDivider.tsnew file mode 100644index 0000000000..9de174f008--- /dev/null+++ b/packages/core/src/Table/rowDivider.ts@@ -0,0 +1,154 @@+// Copyright (c) Meta Platforms, Inc. and affiliates.++/**+ * @file rowDivider.ts+ * @input Table cells and rows, their computed borders+ * @output Exports `collapsedBottom` (the border the table paints under a+ * cell, by the collapsing rules) and `panelDividerFor` (the divider a+ * detail panel takes from its row)+ * @position Table internals, shared by the sticky-columns and row-expansion+ * plugins: a divider drawn somewhere else than the table paints it (a+ * pinned cell's, a detail panel's) reads here which border the table would+ * paint, so a theme's or an app's border carries over.+ *+ * SYNC: When modified, update plugins/stickyColumns and plugins/rowExpansion.+ */++/** Border styles by collapsed-border precedence, weakest first (CSS 2.1). */+const STYLE_RANK = [+ 'inset',+ 'groove',+ 'outset',+ 'ridge',+ 'dotted',+ 'dashed',+ 'solid',+ 'double',+];++export interface BottomEdge {+ width: number;+ style: string;+ color: string;+}++function edgeOf(element: Element | null, side: 'Bottom' | 'Top'): BottomEdge {+ if (element == null) {+ return {width: 0, style: 'none', color: ''};+ }+ const style = getComputedStyle(element);+ return {+ width:+ parseFloat(+ style.getPropertyValue(`border-${side.toLowerCase()}-width`),+ ) || 0,+ style: style.getPropertyValue(`border-${side.toLowerCase()}-style`),+ color: style.getPropertyValue(`border-${side.toLowerCase()}-color`),+ };+}++/** The row below `row`, across a section edge (thead to tbody) too. */+function rowBelow(row: Element | null): Element | null {+ if (row == null) {+ return null;+ }+ return (+ row.nextElementSibling ??+ row.parentElement?.nextElementSibling?.firstElementChild ??+ null+ );+}++/**+ * The border the table paints under a cell, by the collapsing rules (CSS 2.1+ * 17.6.2.1): of the cell's own bottom, the cell's below it (top), its row's+ * bottom, the next row's top, and at a section edge (thead to tbody) the two+ * row groups' borders, `hidden` wins, then the wider, then the stronger+ * style; a tie goes to a cell over a row over a row group, and to the upper+ * one. `isOwn` says the cell's own border won; `isRow` says a row's or a+ * row group's won, which the table paints along the whole row.+ */+export function collapsedBottom(cell: HTMLTableCellElement): BottomEdge & {+ isOwn: boolean;+ isRow: boolean;+} {+ const row = cell.parentElement;+ const nextRow = rowBelow(row);+ const nextCell = nextRow?.children[cell.cellIndex] ?? null;+ const isSectionEdge = row != null && row.nextElementSibling == null;+ // In tie order.+ const candidates = [+ edgeOf(cell, 'Bottom'),+ edgeOf(nextCell, 'Top'),+ edgeOf(row, 'Bottom'),+ edgeOf(nextRow, 'Top'),+ edgeOf(isSectionEdge ? (row?.parentElement ?? null) : null, 'Bottom'),+ edgeOf(isSectionEdge ? (nextRow?.parentElement ?? null) : null, 'Top'),+ ];+ const own = candidates[0];+ if (candidates.some(edge => edge.style === 'hidden')) {+ return {+ width: 0,+ style: 'none',+ color: own.color,+ isOwn: own.style === 'hidden',+ isRow: false,+ };+ }+ const strength = (edge: BottomEdge) =>+ edge.style === 'none' || edge.width === 0+ ? [-1, -1]+ : [edge.width, STYLE_RANK.indexOf(edge.style)];+ let winner = own;+ for (const edge of candidates.slice(1)) {+ const [width, rank] = strength(edge);+ const [bestWidth, bestRank] = strength(winner);+ if (width > bestWidth || (width === bestWidth && rank > bestRank)) {+ winner = edge;+ }+ }+ return {+ ...winner,+ isOwn: winner === own,+ isRow: candidates.indexOf(winner) >= 2,+ };+}++/**+ * The divider a detail panel takes from its row: the color and style of the+ * row's cells (a theme's `table-cell` styling or an app's own, which never+ * reach the panel's cell), with their width where they set one, at the+ * panel's own width otherwise, unless the row's own border wins the+ * collapse (an app styling the `<tr>`), as custom property+ * values for the panel's cell. Every value is written, `initial` where the+ * panel keeps its own, so a panel nested in another never inherits that+ * one's.+ */+export function panelDividerFor(row: Element): {+ width: string;+ style: string;+ color: string;+} | null {+ const rowCell = row.lastElementChild;+ if (rowCell == null) {+ return null;+ }+ const rowStyle = getComputedStyle(row);+ const rowWidth = parseFloat(rowStyle.borderBottomWidth) || 0;+ if (rowStyle.borderBottomStyle !== 'none' && rowWidth > 0) {+ return {+ width: `${rowWidth}px`,+ style: rowStyle.borderBottomStyle,+ color: rowStyle.borderBottomColor,+ };+ }+ const cellStyle = getComputedStyle(rowCell);+ // The row's cells hand their divider down (their own width is 0); a width+ // an app or a theme sets on them anyway is the divider's.+ const cellWidth = parseFloat(cellStyle.borderBottomWidth) || 0;+ return {+ width: cellWidth > 0 ? `${cellWidth}px` : 'initial',+ style: cellStyle.borderBottomStyle,+ color: cellStyle.borderBottomColor,+ };+}diff --git a/packages/core/src/theme/derivedVarRegistry.test.ts b/packages/core/src/theme/derivedVarRegistry.test.tsindex 5c012ed463..83d00323f2 100644--- a/packages/core/src/theme/derivedVarRegistry.test.ts+++ b/packages/core/src/theme/derivedVarRegistry.test.ts@@ -86,6 +86,10 @@ const STRUCTURAL_VARS = new Set([// replays on pinned cells. Structural/runtime, not themeable design tokens.'--table-sticky-background','--table-row-overlay',+ // The width a cell's row divider draws (0 on the last row), which a pinned+ // cell's or a detail panel's own divider reads (Table/rowDivider.ts).+ // Private runtime plumbing, never authored by a theme.+ '--_table-row-divider-width','--separator-display','--astryx-section-padding',// Private counterpart of the public token above: one ancestor Section's