Skip to content
Merged
8 changes: 8 additions & 0 deletions .changeset/table-infinite-loading.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
---
'@astryxdesign/core': patch
'@astryxdesign/cli': patch
---

[feature] Add Table infinite loading with `useTableInfiniteScroll({hasMore, isLoading, onLoadMore})`. One Promise request latch coordinates automatic and manual loading, failures pause automatic retry, and the persistent busy Button owns progress announcements and focus continuity.

@humbertovirtudes
1 change: 1 addition & 0 deletions apps/sandbox/scripts/next-export-routes.json
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,7 @@
"/templates/IconShowcase/",
"/templates/IconSizes/",
"/templates/IconStatusIcons/",
"/templates/InfiniteScrollHookUsage/",
"/templates/InfoTipMetricDefinitions/",
"/templates/InfoTipPermissionNotes/",
"/templates/InfoTipShowcase/",
Expand Down
38 changes: 38 additions & 0 deletions apps/storybook/stories/TableInfiniteScroll.stories.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {useState} from 'react';
import type {Meta, StoryObj} from '@storybook/react-vite';
import {Table, useTableInfiniteScroll} from '@astryxdesign/core';
const rows = Array.from({length: 20}, (_, index) => ({
id: String(index),
name: `Product ${index + 1}`,
}));
const meta: Meta = {
title: 'Core/Table infinite loading',
component: Table,
};
export default meta;
function Example() {
const [data, setData] = useState(rows.slice(0, 4));
const [isLoading, setIsLoading] = useState(false);
const loading = useTableInfiniteScroll({
hasMore: data.length < 20,
isLoading,
onLoadMore: async () => {
setIsLoading(true);
await new Promise(resolve => setTimeout(resolve, 400));
setData(previous => rows.slice(0, previous.length + 4));
setIsLoading(false);
},
});
return (
<Table
data={data}
columns={[{key: 'name', header: 'Product'}]}
idKey="id"
plugins={{loading}}
/>
);
}
export const ManualAndAutomaticLoading: StoryObj = {
render: () => <Example />,
};
10 changes: 10 additions & 0 deletions internal/shadcn-registry/routes.lock.json
Original file line number Diff line number Diff line change
Expand Up @@ -3901,6 +3901,11 @@
"path": "examples/use-table-grouped-rows/collapsible-groups",
"aliases": []
},
{
"name": "example-use-table-infinite-scroll-load-more-products",
"path": "examples/use-table-infinite-scroll/load-more-products",
"aliases": []
},
{
"name": "example-use-table-row-expansion-tree-table",
"path": "examples/use-table-row-expansion/tree-table",
Expand Down Expand Up @@ -4276,6 +4281,11 @@
"path": "hooks/use-table-grouped-rows",
"aliases": []
},
{
"name": "hook-use-table-infinite-scroll",
"path": "hooks/use-table-infinite-scroll",
"aliases": []
},
{
"name": "hook-use-table-pagination",
"path": "hooks/use-table-pagination",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

/** @type {import('@astryxdesign/cli/authoring').TemplateDoc} */
export const doc = {
type: 'block',
exampleFor: 'useTableInfiniteScroll',
name: 'useTableInfiniteScroll - Load More Products',
displayName: 'useTableInfiniteScroll - Load More Products',
description:
'A Table appends product batches automatically or through its Load more command. The caller owns the rows, loading state and Promise-returning request. The command disappears when all products are loaded.',
isReady: true,
aspectRatio: 16 / 9,
componentsUsed: ['Table'],
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.

'use client';

import {useState} from 'react';
import {Table, useTableInfiniteScroll} from '@astryxdesign/core/Table';

const products = Array.from({length: 20}, (_, index) => ({
id: `product-${index}`,
name: `Product ${index + 1}`,
}));
const columns = [{key: 'name', header: 'Product'}];

export default function InfiniteScrollHookUsage() {
const [data, setData] = useState(products.slice(0, 4));
const [isLoading, setIsLoading] = useState(false);
const loading = useTableInfiniteScroll({
hasMore: data.length < products.length,
isLoading,
onLoadMore: async () => {
setIsLoading(true);
try {
const nextBatch = await Promise.resolve(
products.slice(data.length, data.length + 4),
);
setData(previous => [...previous, ...nextBatch]);
} finally {
setIsLoading(false);
}
},
});
return <Table data={data} columns={columns} idKey="id" plugins={{loading}} />;
}
13 changes: 13 additions & 0 deletions packages/core/api-report.md
Original file line number Diff line number Diff line change
Expand Up @@ -2968,6 +2968,7 @@ hook useTableColumnSettingsState: <TColumnKey extends string = string>(config: U
hook useTableFilterState: (initialState?: TableFilterState) => UseTableFilterStateResult
hook useTableFiltering: <T extends Record<string, unknown>>(config: UseTableFilteringConfig) => TablePlugin<T>
hook useTableGroupedRows: <T extends Record<string, unknown>>(config: UseTableGroupedRowsConfig<T>) => UseTableGroupedRowsResult<T>
hook useTableInfiniteScroll: <T extends Record<string, unknown>>(config: UseTableInfiniteScrollConfig) => TablePlugin<T>
hook useTablePagination: <T extends Record<string, unknown>>(config: UseTablePaginationConfig) => TablePlugin<T>
hook useTableRowExpansion: <T extends Record<string, unknown>>(config: UseTableRowExpansionConfig<T>) => TablePlugin<T>
hook useTableRowIndex: <T extends Record<string, unknown>>(config?: UseTableRowIndexConfig<T>) => TablePlugin<T>
Expand Down Expand Up @@ -5462,6 +5463,7 @@ interface TableFooterProps extends BaseProps<HTMLTableSectionElement> (props of
interface TableHeaderCellProps extends BaseProps<HTMLTableCellElement> (props of TableHeaderCell)
interface TableHeaderProps extends BaseProps<HTMLTableSectionElement> (props of TableHeader)
interface TablePlugin<T extends Record<string, unknown> = Record<string, unknown>>
renderState?: TablePluginRenderState
rowModel?: TableRenderContext['rowModel']
transformBodyCell?: (props: BodyCellRenderProps, column: TableColumn<T>, item: T, columnIndex: number, columns: ReadonlyArray<TableColumn<T>>, context?: TableRowContext) => BodyCellRenderProps
transformBodyRow?: (props: BodyRowRenderProps, item: T, index: number, context?: TableRowContext) => BodyRowRenderProps
Expand All @@ -5471,6 +5473,10 @@ interface TablePlugin<T extends Record<string, unknown> = Record<string, unknown
transformScrollWrapper?: (props: ScrollWrapperRenderProps, context?: TableRenderContext) => ScrollWrapperRenderProps
transformTable?: (props: TableRenderProps) => TableRenderProps
transformTableContext?: (children: ReactNode) => ReactNode
interface TablePluginRenderState
getServerSnapshot: () => Readonly<{ isLoading: boolean; hasMore?: boolean }>
getSnapshot: () => Readonly<{ isLoading: boolean; hasMore?: boolean }>
subscribe: (onChange: () => void) => () => void
interface TableProps<T extends Record<string, unknown>> extends Omit<BaseTableProps<T>, 'plugins' | 'components'>
children?: ReactNode
columns?: TableColumn<T>[]
Expand Down Expand Up @@ -6217,6 +6223,10 @@ interface UseTableGroupedRowsResult<T extends Record<string, unknown>>
data: T[]
idKey: (item: T) => string
plugin: TablePlugin<T>
interface UseTableInfiniteScrollConfig
hasMore: boolean
isLoading: boolean
onLoadMore: () => Promise<void>
interface UseTablePaginationConfig
align?: 'start' | 'center' | 'end' = 'center'
hasMore?: boolean
Expand Down Expand Up @@ -8726,6 +8736,7 @@ TableHeaderCell (.)
TableHeaderCellProps (.)
TableHeaderProps (.)
TablePlugin (.)
TablePluginRenderState (.)
TableProps (.)
TableRenderProps (.)
TableRow (.)
Expand All @@ -8752,6 +8763,7 @@ UseTableFilteringConfig (.)
TableRowContext (.)
UseTableGroupedRowsConfig (.)
UseTableGroupedRowsResult (.)
UseTableInfiniteScrollConfig (.)
UseTablePaginationConfig (.)
UseTableRowExpansionConfig (.)
UseTableRowIndexConfig (.)
Expand Down Expand Up @@ -8780,6 +8792,7 @@ useTableColumnSettingsState (.)
useTableFilterState (.)
useTableFiltering (.)
useTableGroupedRows (.)
useTableInfiniteScroll (.)
useTablePagination (.)
useTableRowExpansion (.)
useTableRowIndex (.)
Expand Down
4 changes: 4 additions & 0 deletions packages/core/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -955,6 +955,10 @@
"defaultMessage": "Table",
"description": "Fallback screen-reader-only accessible name for a data-table region when the consumer provides none. Noun (\"a table\"), not the verb \"to table\"."
},
"@astryx.table.loadMore": {
"defaultMessage": "Load more",
"description": "Button that requests another batch of table rows. Verb phrase; shown while additional rows are available."
},
"@astryx.table.noData": {
"defaultMessage": "No data",
"description": "Fallback empty-state text in the table body when there are zero rows. Neutral tone (not error-y); consumers commonly override with something specific like \"No results\"."
Expand Down
39 changes: 38 additions & 1 deletion packages/core/src/Table/BaseTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ import {
useId,
useMemo,
useRef,
useSyncExternalStore,
type ReactElement,
type ReactNode,
type Ref,
Expand All @@ -38,6 +39,7 @@ import type {
BodyCellRenderProps,
ScrollWrapperRenderProps,
TableRenderContext,
TablePluginRenderState,
TableRowContext,
TableRowComponentProps,
TableCellComponentProps,
Expand Down Expand Up @@ -533,6 +535,38 @@ function BaseTableInner<T extends Record<string, unknown>>({
[mode, rowModel, logicalRowCount, headerRowCount],
);

// A loading plugin publishes its request state through `renderState`. Table
// reads it before it builds the sections, and only where loading is
// admitted: data mode, a flat row model, and the default scroll wrapper.
const loadingSource = useMemo(() => {
const sources = plugins.flatMap(plugin =>
plugin.renderState ? [plugin.renderState] : [],
);
// The snapshot is a number, so the store compares it by value.
const readIsLoading = (
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
read: (source: TablePluginRenderState) => {isLoading: boolean},
) => (sources.some(source => read(source).isLoading) ? 1 : 0);
return {
subscribe(onChange: () => void) {
const cleanups = sources.map(source => source.subscribe(onChange));
return () => cleanups.forEach(cleanup => cleanup());
},
getSnapshot: () => readIsLoading(source => source.getSnapshot()),
getServerSnapshot: () =>
readIsLoading(source => source.getServerSnapshot()),
};
}, [plugins]);
const loadingSnapshot = useSyncExternalStore(
loadingSource.subscribe,
loadingSource.getSnapshot,
loadingSource.getServerSnapshot,
);
const isLoading =
mode === 'data' &&
rowModel === 'flat' &&
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
ScrollWrapper != null &&
loadingSnapshot === 1;

// Resolve all column widths in a single pass — produces per-column
// inline styles and the aggregate table min-width.
const resolvedWidths = resolveColumnWidths(resolvedColumns);
Expand Down Expand Up @@ -746,7 +780,10 @@ function BaseTableInner<T extends Record<string, unknown>>({
);
})
: data != null &&
emptyState !== false && (
emptyState !== false &&
// While the first rows load, the default "no data" message
// would be wrong. Caller-owned empty content still shows.
!(isLoading && emptyState == null) && (
<tr>
<td colSpan={resolvedColumns.length}>
{emptyState ?? (
Expand Down
107 changes: 107 additions & 0 deletions packages/core/src/Table/TablePluginLoading.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,107 @@
// Copyright (c) Meta Platforms, Inc. and affiliates.
import {useState} from 'react';
import {render, screen, cleanup} from '@testing-library/react';
import {afterEach, describe, expect, it, vi} from 'vitest';
import {useTableInfiniteScroll} from './plugins/infiniteScroll/useTableInfiniteScroll';
import type {TableColumn} from './types';
import {Table} from './Table';

const columns = [{key: 'id', header: 'ID'}];
afterEach(cleanup);

describe('Table plugin loading source', () => {
it('renders only appended rows when a real loading plugin owns wrapper state', () => {
vi.stubGlobal('IntersectionObserver', undefined);
vi.spyOn(console, 'warn').mockImplementation(() => {});
interface Item extends Record<string, unknown> {
id: string;
name: string;
}
const renderCell = vi.fn((item: Item) => item.name);
const itemColumns: TableColumn<Item>[] = [
{key: 'name', header: 'Name', renderCell},
];
const rows: Item[] = Array.from({length: 200}, (_, index) => ({
id: String(index),
name: `Item ${index}`,
}));
const appended: Item[] = Array.from({length: 50}, (_, index) => ({
id: String(index + 200),
name: `Item ${index + 200}`,
}));
const onLoadMore = async () => {};
function Fixture({
data,
isLoading = false,
}: {
data: Item[];
isLoading?: boolean;
}) {
const loading = useTableInfiniteScroll<Item>({
hasMore: true,
isLoading,
onLoadMore,
});
return (
<Table
data={data}
columns={itemColumns}
idKey="id"
plugins={{loading}}
/>
);
}
const view = render(<Fixture data={rows} />);
renderCell.mockClear();
view.rerender(<Fixture data={rows} isLoading />);
expect(renderCell).not.toHaveBeenCalled();
view.rerender(<Fixture data={[...rows, ...appended]} />);
expect(renderCell.mock.calls).toEqual(appended.map(item => [item]));
renderCell.mockClear();
view.rerender(<Fixture data={rows} />);
expect(renderCell).not.toHaveBeenCalled();
view.unmount();
vi.unstubAllGlobals();
vi.restoreAllMocks();
});
it('reacts to a stable loading source before rendering the default empty state', () => {
let notify: (() => void) | undefined;
let snapshot = {isLoading: true};
const source = {
subscribe(fn: () => void) {
notify = fn;
return () => {
notify = undefined;
};
},
getSnapshot: () => snapshot,
getServerSnapshot: () => snapshot,
};
function Host() {
const [, bump] = useState(0);
return (
<>
<button
type="button"
onClick={() => {
snapshot = {isLoading: false};
notify?.();
bump(n => n + 1);
}}>
Settle
</button>
<Table
data={[]}
columns={columns}
plugins={{load: {rowModel: 'flat', renderState: source}}}
/>
</>
);
}
const {rerender} = render(<Host />);
expect(screen.queryByText('No data')).not.toBeInTheDocument();
snapshot = {isLoading: false};
rerender(<Host />);
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
expect(screen.getByText('No data')).toBeInTheDocument();
});
});
Loading