Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(Table): add scrollToRowRef prop to the Table component #816

Merged
merged 7 commits into from
Dec 13, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/components/table/table_body.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -107,5 +107,6 @@ function getTrRenderProps<TData extends RowData>(
children: row
.getVisibleCells()
.map((cell) => <TableRowCell key={cell.id} cell={cell} />),
'data-row-id': row.id,
};
}
23 changes: 22 additions & 1 deletion src/components/table/table_root.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,14 @@ import { useRef } from 'react';
import { TableBody } from './table_body.js';
import { TableHeader } from './table_header.js';
import type { HeaderCellRenderer } from './table_header_cell.js';
import type { TableColumnDef, TableRowTrRenderer } from './table_utils.js';
import type {
Scroller,
TableColumnDef,
TableRowTrRenderer,
VirtualScroller,
} from './table_utils.js';
import { useTableColumns } from './use_table_columns.js';
import { useTableScroll } from './use_table_scroll.js';

const CustomHTMLTable = styled(HTMLTable, {
shouldForwardProp: (prop) => prop !== 'striped' && prop !== 'stickyHeader',
Expand Down Expand Up @@ -110,16 +116,26 @@ interface TableBaseProps<TData extends RowData> {
* Override the columns' header cell rendering.
*/
renderHeaderCell?: HeaderCellRenderer<TData>;

/**
* A ref which will be set with a callback to scroll to a row in the
* table, specified by the row's ID.
*/
scrollToRowRef?: RefObject<VirtualScroller | ScrollToOptions | undefined>;

getRowId?: TableOptions<TData>['getRowId'];
}

interface RegularTableProps<TData extends RowData>
extends TableBaseProps<TData> {
virtualizeRows?: false | undefined;
scrollToRowRef?: RefObject<Scroller | undefined>;
}

interface VirtualizedTableProps<TData extends RowData>
extends TableBaseProps<TData> {
virtualizeRows: true;
scrollToRowRef?: RefObject<VirtualScroller | undefined>;
/**
* For virtualization of the table rows, provide an estimate of the height of each row.
* @param index The index of the row in the data array.
Expand Down Expand Up @@ -150,6 +166,7 @@ export function Table<TData extends RowData>(props: TableProps<TData>) {
renderHeaderCell,

virtualizeRows,
getRowId,
} = props;

const scrollElementRef = useRef<HTMLDivElement>(null);
Expand All @@ -160,6 +177,7 @@ export function Table<TData extends RowData>(props: TableProps<TData>) {
columns: columnDefs,
getCoreRowModel: getCoreRowModel(),
getSortedRowModel: getSortedRowModel(),
getRowId,
});

const tanstackVirtualizer = useVirtualizer({
Expand All @@ -171,6 +189,8 @@ export function Table<TData extends RowData>(props: TableProps<TData>) {
overscan: 5,
});

const tableRef = useTableScroll(props, table, tanstackVirtualizer);

// Make the table component compatible with styled components libraries.
let finalClassName: string | undefined;
if (tableProps?.className && className) {
Expand All @@ -184,6 +204,7 @@ export function Table<TData extends RowData>(props: TableProps<TData>) {
return (
<Container virtualizeRows={virtualizeRows} scrollRef={scrollElementRef}>
<CustomHTMLTable
ref={tableRef}
bordered={bordered}
compact={compact}
interactive={interactive}
Expand Down
11 changes: 11 additions & 0 deletions src/components/table/table_utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { ColumnDef, Row, RowData } from '@tanstack/react-table';
import { createColumnHelper } from '@tanstack/react-table';
import type { ScrollToOptions } from '@tanstack/react-virtual';
import type { ReactNode } from 'react';

export type TableColumnDef<TData extends RowData, TValue = unknown> = ColumnDef<
Expand All @@ -14,9 +15,19 @@ export function createTableColumnHelper<TData extends RowData>() {
export interface TableRowTrProps {
className: string;
children: ReactNode;
// eslint-disable-next-line @typescript-eslint/naming-convention
'data-row-id': string;
}

export type TableRowTrRenderer<TData extends RowData> = (
trProps: TableRowTrProps,
row: Row<TData>,
) => ReactNode;

export interface VirtualScroller {
scrollIntoView: (id: string, options?: ScrollToOptions) => void;
}

export interface Scroller {
scrollIntoView: (id: string, options?: ScrollIntoViewOptions) => void;
}
55 changes: 55 additions & 0 deletions src/components/table/use_table_scroll.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
import type { RowData, Table } from '@tanstack/react-table';
import type {
ScrollToOptions,
ScrollToOptions as VirtualScrollToOptions,
Virtualizer,
} from '@tanstack/react-virtual';
import { useImperativeHandle, useRef } from 'react';

import type { TableProps } from './table_root.js';

export function useTableScroll<TData extends RowData>(
tableProps: TableProps<TData>,
table: Table<TData>,
virtualizer: Virtualizer<HTMLDivElement, Element>,
) {
const tableRef = useRef<HTMLTableElement>(null);
const { scrollToRowRef, virtualizeRows } = tableProps;

// @ts-expect-error We cannot call the hook conditionally to satisfy the type checker
useImperativeHandle(scrollToRowRef, () => {
if (virtualizeRows) {
return {
scrollIntoView(id: string, options?: VirtualScrollToOptions) {
const sortedRows = table.getRowModel().rows; // Get sorted rows
const rowIndex = sortedRows.findIndex((row) => row.id === id); // Find the index of the row by ID
if (rowIndex === -1) {
// We don't expect this situation, but it's not critical enough to throw an error.
// eslint-disable-next-line no-console
console.warn(
`Could not scroll to row with ID ${id}, the row does not exist`,
);
}
virtualizer.scrollToIndex(rowIndex, options);
},
};
} else {
return {
scrollIntoView(id: string, options?: ScrollToOptions) {
const element = tableRef.current?.querySelector(
`tr[data-row-id="${id}"]`,
);
if (!element) {
// eslint-disable-next-line no-console
console.warn(
`Could not scroll to row with ID ${id}, the row does not exist`,
);
}
element?.scrollIntoView(options);
},
};
}
}, [virtualizeRows, table, virtualizer]);

return tableRef;
}
158 changes: 158 additions & 0 deletions stories/components/table.stories.tsx
Original file line number Diff line number Diff line change
@@ -1,7 +1,11 @@
import { Button, Callout } from '@blueprintjs/core';
import styled from '@emotion/styled';
import type { Meta } from '@storybook/react';
import type { ComponentType } from 'react';
import { useRef, useState } from 'react';
import { IdcodeSvgRenderer } from 'react-ocl';

import type { Scroller, VirtualScroller } from '../../src/components/index.js';
import {
createTableColumnHelper,
Table,
Expand Down Expand Up @@ -187,3 +191,157 @@ export function StyledTable(props: ControlProps) {
/>
);
}

export const ScrollToVirtualRow = {
args: {
scrollBehavior: 'auto',
scrollAlign: 'start',
stickyHeader: true,
striped: true,
},
argTypes: {
scrollBehavior: {
control: {
type: 'select',
},
options: ['auto', 'smooth'],
},
scrollAlign: {
control: {
type: 'select',
},
options: ['auto', 'center', 'start', 'end'],
},
},
render: (props) => {
const buttons = useScrollButtons((index) => {
scrollToRef.current?.scrollIntoView(String(index), {
align: props.scrollAlign,
behavior: props.scrollBehavior,
});
});
const scrollToRef = useRef<VirtualScroller>();

return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100%' }}>
{buttons}
<div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
<Table
{...props}
virtualizeRows
data={table}
tableProps={{
style: { height: '100%' },
}}
columns={columns}
estimatedRowHeight={() => 172}
scrollToRowRef={scrollToRef}
/>
</div>
</div>
);
},
} satisfies Meta;

export const ScrollRowIntoView = {
args: {
scrollBehavior: 'instant',
scrollBlock: 'start',
stickyHeader: false,
striped: true,
},
argTypes: {
scrollBehavior: {
control: {
type: 'select',
},
options: ['auto', 'smooth', 'instant'],
},
scrollBlock: {
control: {
type: 'select',
},
options: ['nearest', 'center', 'start', 'end'],
},
virtualizeRows: {
table: {
disable: true,
},
},
},
render: (props) => {
const scrollToRef = useRef<Scroller>();
const buttons = useScrollButtons((index) =>
scrollToRef.current?.scrollIntoView(String(index), {
behavior: props.scrollBehavior,
block: props.scrollBlock,
}),
);

return (
<div
style={{
display: 'flex',
flexDirection: 'column',
height: '100%',
}}
>
{buttons}
<div style={{ flex: 1, overflow: 'auto', minHeight: 0 }}>
<Table
{...props}
virtualizeRows={false}
data={table}
tableProps={{
style: { height: '100%' },
}}
columns={columns}
scrollToRowRef={scrollToRef}
/>
</div>
</div>
);
},
} satisfies Meta;

function useScrollButtons(onIndexChanged: (index: number) => void) {
const [rowIndex, setRowIndex] = useState(0);

const buttons = (
<Callout title="Scroll to row">
<div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
<div>Last: {table[rowIndex].name}</div>
<div>Use controls to change scroll behavior and alignment</div>
<div style={{ display: 'flex', gap: 8, alignItems: 'center' }}>
<Button
onClick={() => {
const index = Math.floor(Math.random() * table.length);
setRowIndex(index);
onIndexChanged(index);
}}
>
Scroll to random row
</Button>
<Button
onClick={() => {
setRowIndex(0);
onIndexChanged(0);
}}
>
Scroll to first item
</Button>
<Button
onClick={() => {
const index = table.length - 1;
setRowIndex(index);
onIndexChanged(index);
}}
>
Scroll to last item
</Button>
</div>
</div>
</Callout>
);
return buttons;
}
Loading