Skip to content
Open
4 changes: 4 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -63,8 +63,12 @@ jobs:
- name: Install Chromium
run: npx playwright install --with-deps chromium
- name: Build Storybook
env:
STORYBOOK_BROWSER_TESTS: 1
run: npm run build-storybook
- name: Run Browser Regressions
env:
STORYBOOK_BROWSER_TESTS: 1
shell: bash
run: |
set -euo pipefail
Expand Down
82 changes: 82 additions & 0 deletions .storybook/browser-tests/nativeWidths/NativeWidths.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import * as React from 'react';

import {Table} from '../../../src/components';
import {useRowVirtualizer} from '../../../src/hooks/useRowVirtualizer';
import {useTable} from '../../../src/hooks/useTable';
import type {ColumnDef} from '../../../src/types/base';

const cases = [
'Hello world',
'Long first line of text\nLong second line of text',
'Кириллица и длинное значение',
'🛠️ 😀 🛠️ 😀 🛠️ 😀 🛠️ 😀',
'0',
];
const columns: ColumnDef<{value: string}>[] = [
{
accessorKey: 'value',
width: 'max-content',
cell: ({getValue}) => (
<span
data-qa="native-text"
style={{whiteSpace: 'pre', fontFamily: 'Arial', fontSize: 16}}
>
{getValue<string>()}
</span>
),
},
];
function Fixture({
value,
virtual = false,
initiallyHidden = false,
}: {
value: string;
virtual?: boolean;
initiallyHidden?: boolean;
}) {
const container = React.useRef<HTMLDivElement>(null);
const data = React.useMemo(
() => Array.from({length: virtual ? 100 : 1}, () => ({value})),
[value, virtual],
);
const table = useTable({
columns,
data,
defaultColumn: {minSize: 100},
enableColumnResizing: true,
});
const virtualizer = useRowVirtualizer({
count: data.length,
estimateSize: () => 32,
getScrollElement: () => container.current,
overscan: 2,
});
return (
<div
data-qa="native-fixture"
ref={container}
style={{width: 600, height: 100, overflow: 'auto'}}
>
<Table
table={table}
withHeader={false}
attributes={{hidden: initiallyHidden}}
rowVirtualizer={virtual ? virtualizer : undefined}
/>
</div>
);
}
function Regression() {
return (
<div>
{cases.map((value) => (
<Fixture key={value} value={value} />
))}
<Fixture virtual value={cases[0]} />
<Fixture initiallyHidden value="Initially hidden long text" />
</div>
);
}
export default {title: 'Browser tests/Native widths', tags: ['browser-regression', '!autodocs']};
export const Layout = {render: () => <Regression />};
58 changes: 58 additions & 0 deletions .storybook/browser-tests/nativeWidths/testNativeWidths.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type {TestRunnerConfig} from '@storybook/test-runner';
type Page = Parameters<NonNullable<TestRunnerConfig['postVisit']>>[0];
export async function testNativeWidths(page: Page) {
await page.waitForFunction(
() => document.querySelectorAll('[data-qa="native-fixture"] td').length >= 6,
);
await page.waitForTimeout(50);
await page
.locator('[data-qa="native-fixture"] table[hidden]')
.evaluateAll((tables) => tables.forEach((table) => table.removeAttribute('hidden')));
const verify = async () => {
await page.waitForFunction(() =>
Array.from(document.querySelectorAll('[data-qa="native-fixture"]')).every((fixture) => {
const cell = fixture.querySelector('td');
const text = cell?.querySelector('[data-qa="native-text"]');
if (!cell || !text) return false;
const style = getComputedStyle(cell);
const expected = Math.max(
100,
text.getBoundingClientRect().width +
parseFloat(style.paddingLeft) +
parseFloat(style.paddingRight),
);
const actual = parseFloat(style.width);
return Math.abs(expected - actual) < 2;
}),
);
};
await verify();
const initial = await page
.locator('[data-qa="native-fixture"] td')
.evaluateAll((cells) => cells.map((cell) => getComputedStyle(cell).width));
// Hide only tables: parent viewport dimensions stay unchanged.
await page.locator('[data-qa="native-fixture"] table').evaluateAll((tables) =>
tables.forEach((table) => {
(table as HTMLElement).style.display = 'none';
}),
);
await page.waitForTimeout(50);
await page.locator('[data-qa="native-fixture"] table').evaluateAll((tables) =>
tables.forEach((table) => {
(table as HTMLElement).style.display = '';
}),
);
await verify();
await page.locator('[data-qa="native-fixture"]').evaluateAll((fixtures) =>
fixtures.forEach((fixture) => {
(fixture as HTMLElement).style.transform = 'scale(.5)';
(fixture as HTMLElement).style.width = '620px';
}),
);
await page.waitForTimeout(100);
const scaled = await page
.locator('[data-qa="native-fixture"] td')
.evaluateAll((cells) => cells.map((cell) => getComputedStyle(cell).width));
if (JSON.stringify(initial) !== JSON.stringify(scaled))
throw new Error('Scale changed native column widths');
}
8 changes: 7 additions & 1 deletion .storybook/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,13 @@ const config: StorybookConfig = {
'@storybook/addon-webpack5-compiler-babel',
],
framework: '@storybook/react-webpack5',
stories: ['../src/**/*.mdx', '../src/**/*.stories.@(ts|tsx)'],
stories: [
'../src/**/*.mdx',
'../src/**/*.stories.@(ts|tsx)',
...(process.env.STORYBOOK_BROWSER_TESTS === '1'
? ['./browser-tests/**/*.stories.tsx']
: []),
],
typescript: {
reactDocgen: 'react-docgen-typescript',
},
Expand Down
5 changes: 5 additions & 0 deletions .storybook/test-runner.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import type {TestRunnerConfig} from '@storybook/test-runner';
import {toMatchImageSnapshot} from 'jest-image-snapshot';

import {testNativeWidths} from './browser-tests/nativeWidths/testNativeWidths';
import {testAdaptiveVirtualization} from './browser-tests/testAdaptiveVirtualization/testAdaptiveVirtualization';
import {testVirtualizedTreeReordering} from './browser-tests/testVirtualizedTreeReordering/testVirtualizedTreeReordering';

Expand All @@ -13,6 +14,10 @@ const config: TestRunnerConfig = {
expect.extend({toMatchImageSnapshot});
},
async postVisit(page, context) {
if (context.id === 'browser-tests-native-widths--layout') {
await testNativeWidths(page);
return;
}
if (context.id === ADAPTIVE_VIRTUALIZATION_STORY) {
await testAdaptiveVirtualization(page);
return;
Expand Down
7 changes: 5 additions & 2 deletions src/components/BaseCell/BaseCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,10 @@ import {b} from '../BaseTable/BaseTable.classname';

import {areMemoizedCellPropsEqual} from './utils/areMemoizedCellPropsEqual';

export interface BaseCellProps<TData>
extends Omit<React.TdHTMLAttributes<HTMLTableCellElement>, 'className'> {
export interface BaseCellProps<TData> extends Omit<
React.TdHTMLAttributes<HTMLTableCellElement>,
'className'
> {
cell?: Cell<TData, unknown>;
className?: string | ((cell?: Cell<TData, unknown>) => string);
attributes?:
Expand Down Expand Up @@ -48,6 +50,7 @@ const BaseCellComponent = <TData,>({
className={b('cell', getCellClassModes(cell), className)}
{...restProps}
{...attributes}
data-column-id={cell?.column.id}
data-virtualization-cell-content={deferContent ? 'deferred' : undefined}
style={getCellStyles(cell, {...style, ...attributes?.style})}
>
Expand Down
3 changes: 3 additions & 0 deletions src/components/BaseFooterCell/BaseFooterCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,9 @@ export const BaseFooterCell = <TData, TValue>({
colSpan={header.colSpan > 1 ? header.colSpan : undefined}
rowSpan={rowSpan > 1 ? rowSpan : undefined}
{...attributes}
data-column-id={
header.colSpan === 1 && !header.isPlaceholder ? header.column.id : undefined
}
style={getCellStyles(header, attributes?.style)}
>
{flexRender(header.column.columnDef.footer, header.getContext())}
Expand Down
6 changes: 4 additions & 2 deletions src/components/BaseHeaderCell/BaseHeaderCell.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,7 @@ import {b} from '../BaseTable/BaseTable.classname';

export interface BaseHeaderCellProps<TData, TValue> {
className?:
| string
| ((header: Header<TData, TValue>, parentHeader?: Header<TData, unknown>) => string);
string | ((header: Header<TData, TValue>, parentHeader?: Header<TData, unknown>) => string);
header: Header<TData, TValue>;
parentHeader?: Header<TData, unknown>;
renderHeaderCellContent?: (props: {header: Header<TData, TValue>}) => React.ReactNode;
Expand Down Expand Up @@ -114,6 +113,9 @@ export const BaseHeaderCell = React.forwardRef(
aria-sort={getAriaSort(header.column.getIsSorted())}
aria-colindex={getHeaderCellAriaColIndex(header)}
{...attributes}
data-column-id={
header.colSpan === 1 && !header.isPlaceholder ? header.column.id : undefined
}
style={getCellStyles(header, attributes?.style)}
>
{renderContent()}
Expand Down
5 changes: 4 additions & 1 deletion src/components/BaseResizeHandle/BaseResizeHandle.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {Header} from '../../types/base';
import {autoSizeColumn} from '../BaseTable/hooks/useColumnWidths';

import {b} from './BaseResizeHandle.classname';

Expand Down Expand Up @@ -28,7 +29,9 @@ export const BaseResizeHandle = <TData, TValue>({
},
className,
)}
onDoubleClick={() => header.column.resetSize()}
onDoubleClick={() => {
if (!autoSizeColumn(table, header.column.id)) header.column.resetSize();
}}
onMouseDown={header.getResizeHandler()}
onTouchStart={header.getResizeHandler()}
style={{
Expand Down
12 changes: 9 additions & 3 deletions src/components/BaseTable/BaseTable.tsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import * as React from 'react';

import {useForkRef} from '@gravity-ui/uikit';
import type {QAProps} from '@gravity-ui/uikit';
import type {Row, Table} from '@tanstack/react-table';
import type {VirtualItem, Virtualizer} from '@tanstack/react-virtual';
Expand All @@ -18,13 +19,16 @@ import {LastSelectedRowContextProvider} from '../LastSelectedRowContext';
import {SortableListContext} from '../SortableListContext';

import {b} from './BaseTable.classname';
import {useColumnWidths} from './hooks/useColumnWidths';
import {useTableVirtualization} from './hooks/useTableVirtualization';
import type {CanDeferOffscreenCellContent} from './types';

import './BaseTable.scss';

export interface BaseTableProps<TData, TScrollElement extends Element | Window = HTMLDivElement>
extends QAProps {
export interface BaseTableProps<
TData,
TScrollElement extends Element | Window = HTMLDivElement,
> extends QAProps {
/** The table instance returned from the `useTable` hook */
table: Table<TData>;
/** HTML attributes for the `<table>` element */
Expand Down Expand Up @@ -175,6 +179,8 @@ export const BaseTable = React.forwardRef(
}: BaseTableProps<TData, TScrollElement>,
ref: React.Ref<HTMLTableElement>,
) => {
const {tableRef} = useColumnWidths(table);
const resolvedTableRef = useForkRef(tableRef, ref);
const draggableContext = React.useContext(SortableListContext);
const columnReorderingContext = React.useContext(ColumnReorderingContext);
const draggingRowIndex = draggableContext?.activeItemIndex ?? -1;
Expand Down Expand Up @@ -302,7 +308,7 @@ export const BaseTable = React.forwardRef(
return (
<LastSelectedRowContextProvider>
<table
ref={ref}
ref={resolvedTableRef}
className={b({'with-row-virtualization': Boolean(rowVirtualizer)}, className)}
data-dragging-row-index={draggingRowIndex > -1 ? draggingRowIndex : undefined}
data-column-drag-active={isColumnDragActive || undefined}
Expand Down
Loading