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 @cixzhang
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 @@ -374,6 +374,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 @@ -3971,6 +3971,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 @@ -4391,6 +4396,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}} />;
}
4 changes: 4 additions & 0 deletions packages/core/locales/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -1035,6 +1035,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
51 changes: 49 additions & 2 deletions packages/core/src/Table/BaseTable.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import {
useId,
useMemo,
useRef,
useSyncExternalStore,
type ReactElement,
type ReactNode,
type Ref,
Expand Down Expand Up @@ -53,6 +54,7 @@ import type {
BodyCellRenderProps,
ScrollWrapperRenderProps,
TableRenderContext,
TablePluginRenderState,
TableRowContext,
TableRowComponentProps,
TableCellComponentProps,
Expand Down Expand Up @@ -705,6 +707,44 @@ function BaseTableInner<T extends Record<string, unknown>>({
const textOverflow =
textOverflowProp ?? (windowPlan.isWindowed ? 'truncate' : 'wrap');

// 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: bit 0 is
// set while a source loads, bit 1 while a source has more rows.
const readIsLoading = (
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
read: (source: TablePluginRenderState) => {
isLoading: boolean;
hasMore?: boolean;
},
) =>
(sources.some(source => read(source).isLoading) ? 1 : 0) |
(sources.some(source => read(source).hasMore === true) ? 2 : 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 isLoadingAdmitted =
mode === 'data' && admission.rowModel === 'flat' && ScrollWrapper != null;
Comment thread
astracat-bot[bot] marked this conversation as resolved.
Resolved
const isLoading = isLoadingAdmitted && (loadingSnapshot & 1) === 1;
// While any admitted source may load more rows, the total is unknown.
const hasMoreRows = isLoadingAdmitted && (loadingSnapshot & 2) === 2;

// Resolve all column widths in a single pass — produces per-column
// inline styles and the aggregate table min-width.
// A windowed table widens its row-number columns to the width measured for
Expand Down Expand Up @@ -886,7 +926,11 @@ function BaseTableInner<T extends Record<string, unknown>>({
<table
ref={useMergedRefs(ref, runtime.setTable)}
{...(windowPlan.isWindowed
? {'aria-rowcount': headerRowCount + (data?.length ?? 0)}
? {
'aria-rowcount': hasMoreRows
? -1
: headerRowCount + (data?.length ?? 0),
}
: ariaRowCount != null
? {'aria-rowcount': ariaRowCount}
: null)}
Expand Down Expand Up @@ -981,7 +1025,10 @@ function BaseTableInner<T extends Record<string, unknown>>({
return rows;
})
: 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
Loading
Loading