# Paged List

A button that adds the next page to a list, in place, without the page jumping.

Source: [paged-list.tsx](https://github.com/jakejarvis/jarvis-ui/blob/main/src/components/ui/paged-list.tsx)

```tsx
"use client";

import * as React from "react";

import { Avatar, AvatarFallback, AvatarImage } from "@/components/ui/avatar";
import {
  Item,
  ItemContent,
  ItemDescription,
  ItemGroup,
  ItemMedia,
  ItemTitle,
} from "@/components/ui/item";
import {
  PagedList,
  PagedListButton,
  PagedListContent,
  PagedListCount,
} from "@/components/ui/paged-list";
import { people } from "@/examples/data";

const actions = [
  "rotated the API key prod-ingest",
  "updated the billing email",
  "invited sam@example.com",
  "turned on SSO",
  "changed the plan to Team, billed yearly",
  "removed a member from Platform",
];

const events = Array.from({ length: 18 }, (_, index) => ({
  id: index,
  person: people[index % people.length],
  action: actions[index % actions.length],
  time: `${(index + 1) * 7}m ago`,
}));

const pageSize = 5;

export default function PagedListAuditLog() {
  const [shown, setShown] = React.useState(pageSize);

  const loadMore = async () => {
    await new Promise((resolve) => setTimeout(resolve, 700));
    setShown((count) => Math.min(count + pageSize, events.length));
  };

  return (
    <PagedList
      onLoadMore={loadMore}
      hasMore={shown < events.length}
      count={shown}
      total={events.length}
      className="w-full max-w-md"
    >
      <PagedListContent render={<ItemGroup />} aria-label="Audit log">
        {events.slice(0, shown).map((event) => (
          <Item key={event.id} size="sm">
            <ItemMedia>
              <Avatar className="size-7">
                <AvatarImage src={event.person.image} alt="" />
                <AvatarFallback>{event.person.initials}</AvatarFallback>
              </Avatar>
            </ItemMedia>
            <ItemContent>
              <ItemTitle>{event.person.name}</ItemTitle>
              <ItemDescription>{event.action}</ItemDescription>
            </ItemContent>
            <span className="text-2xs text-faint">{event.time}</span>
          </Item>
        ))}
      </PagedListContent>
      <PagedListButton />
      <PagedListCount />
    </PagedList>
  );
}
```

## Installation

Add the registry, once per project:

```bash
npx shadcn@latest registry add @jarvis=https://ui.jarv.is/r/{name}.json
```

Then add the component:

```bash
npx shadcn@latest add @jarvis/paged-list
```

## Usage

```tsx
"use client";

import * as React from "react";

import {
  PagedList,
  PagedListButton,
  PagedListContent,
  PagedListCount,
} from "@/components/ui/paged-list";

type Entry = { id: string; text: string };

export function Activity({ firstPage, total }: { firstPage: Entry[]; total: number }) {
  const [events, setEvents] = React.useState(firstPage);

  const loadMore = async () => {
    const response = await fetch(`/api/events?after=${events.at(-1)?.id ?? ""}`);
    const next: Entry[] = await response.json();
    setEvents((loaded) => [...loaded, ...next]);
  };

  return (
    <PagedList
      onLoadMore={loadMore}
      hasMore={events.length < total}
      count={events.length}
      total={total}
    >
      <PagedListContent render={<ul />}>
        {events.map((event) => (
          <li key={event.id}>{event.text}</li>
        ))}
      </PagedListContent>
      <PagedListButton />
      <PagedListCount />
    </PagedList>
  );
}
```

`onLoadMore` fetches the next page and adds it to your state. Return a promise so the button knows
when loading is done. `PagedListContent` holds the rows, which are its direct children, in whatever
markup suits them, such as an [Item](https://ui.jarv.is/components/item.md) group, a list or a grid of cards. Pass
`render` to make it a `ul` or a `tbody`. `count` is the number of rows shown, and passing it makes
the count correct before the page loads its scripts. Without it, the rows are counted in the
browser. `locale` formats the numbers in the count and in screen reader announcements.

When a page of rows arrives, the rows fade in and focus moves to the first new row, so someone
using a keyboard or screen reader continues from where they asked for more. Screen readers also
announce how many rows arrived. The button and count opt out of scroll anchoring, so new rows push
them down rather than moving what users are reading. The [Spinner](https://ui.jarv.is/components/spinner.md) shows
only once a page has taken `pendingDelay` milliseconds, and then stays for at least `minPending`
milliseconds, so it never flickers. While it shows, the button is disabled but keeps focus, and a
second press while a page loads does nothing. Once `hasMore` is `false`, the button is replaced by
a marker at the end of the list.

## Composition

- `PagedList`
  - `PagedListContent`
  - `PagedListButton`
  - `PagedListCount`

## Examples

### Errors

If `onLoadMore` rejects, the rows loaded so far stay, and the button offers to try again, with a
message under it. In this example, the first attempt fails.

```tsx
"use client";

import * as React from "react";

import {
  PagedList,
  PagedListButton,
  PagedListContent,
  PagedListCount,
} from "@/components/ui/paged-list";

const builds = Array.from({ length: 12 }, (_, index) => ({
  id: 4120 - index,
  branch: ["main", "billing-flag", "sso-azure", "export-s3"][index % 4],
}));

export default function PagedListRetry() {
  const [shown, setShown] = React.useState(4);
  const attempts = React.useRef(0);

  const loadMore = async () => {
    await new Promise((resolve) => setTimeout(resolve, 600));
    attempts.current += 1;
    if (attempts.current === 1) throw new Error("Network error");
    setShown((count) => Math.min(count + 4, builds.length));
  };

  return (
    <PagedList
      onLoadMore={loadMore}
      hasMore={shown < builds.length}
      count={shown}
      total={builds.length}
      className="w-full max-w-sm"
    >
      <PagedListContent render={<ul />} className="divide-y-[0.5px] divide-border-muted">
        {builds.slice(0, shown).map((build) => (
          <li key={build.id} className="flex items-center justify-between py-2">
            <span className="font-mono">#{build.id}</span>
            <span className="text-muted-foreground">{build.branch}</span>
          </li>
        ))}
      </PagedListContent>
      <PagedListButton />
      <PagedListCount />
    </PagedList>
  );
}
```

### Loading on scroll

`auto` loads the next page automatically when the button comes within 200 pixels of view, in the
window or a scrolling container, so the list keeps going as users scroll. Focus stays where it is.
After a failure, or a page that adds no rows, it waits for a press rather than loading again on its
own.

```tsx
"use client";

import * as React from "react";

import { Card, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { PagedList, PagedListButton, PagedListContent } from "@/components/ui/paged-list";
import { ScrollArea } from "@/components/ui/scroll-area";

const projects = Array.from({ length: 24 }, (_, index) => ({
  id: index,
  name: `project-${String(index + 1).padStart(2, "0")}`,
  updated: `Updated ${index + 1}d ago`,
}));

export default function PagedListAuto() {
  const [shown, setShown] = React.useState(6);

  const loadMore = async () => {
    await new Promise((resolve) => setTimeout(resolve, 600));
    setShown((count) => Math.min(count + 6, projects.length));
  };

  return (
    <ScrollArea className="h-80 w-full rounded-lg shadow-[inset_0_0_0_0.5px_var(--border-muted)]">
      <PagedList onLoadMore={loadMore} hasMore={shown < projects.length} className="p-4">
        <PagedListContent className="grid grid-cols-2 gap-3">
          {projects.slice(0, shown).map((project) => (
            <Card key={project.id} size="sm">
              <CardHeader>
                <CardTitle className="font-mono">{project.name}</CardTitle>
                <CardDescription>{project.updated}</CardDescription>
              </CardHeader>
            </Card>
          ))}
        </PagedListContent>
        <PagedListButton auto />
      </PagedList>
    </ScrollArea>
  );
}
```

## Props

| Part | Extends |
| --- | --- |
| `PagedList` | `<div>` |
| `PagedListContent` | `<div>` |
| `PagedListButton` | [`Button`](https://ui.jarv.is/components/button.md) |
| `PagedListCount` | `<p>` |

Base UI's [styling](https://base-ui.com/react/handbook/styling) and [composition](https://base-ui.com/react/handbook/composition) guides say more about `className`, `style` and `render`.

### PagedList

| Prop            | Type                                                     | Default   | Description                                                                                                                                                                                                              |
| --------------- | -------------------------------------------------------- | --------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `onLoadMore`    | `() => unknown`                                          | —         | Called to fetch and add the next page. Return a promise: if it rejects, the button offers to try again.                                                                                                                  |
| `hasMore`       | `boolean`                                                | —         | Whether there's another page. Once it's `false`, a marker at the end replaces the button.                                                                                                                                |
| `count?`        | `number`                                                 | —         | How many rows are shown, for `PagedListCount` and screen reader announcements. Pass it to make the count correct in the server render. Without it, the direct children of `PagedListContent` are counted in the browser. |
| `total?`        | `number`                                                 | —         | How many rows there are in all, when it's known, for `PagedListCount`.                                                                                                                                                   |
| `pendingDelay?` | `number`                                                 | `150`     | How long a page can take to load, in milliseconds, before the spinner shows, so a quick load never flashes it.                                                                                                           |
| `minPending?`   | `number`                                                 | `400`     | How long the spinner stays once it shows, in milliseconds, so it never flickers.                                                                                                                                         |
| `locale?`       | `string`                                                 | `"en-US"` | The BCP 47 locale that formats the counts.                                                                                                                                                                               |
| `className?`    | `string`                                                 | —         | CSS class applied to the element.                                                                                                                                                                                        |
| `style?`        | `React.CSSProperties`                                    | —         | Style applied to the element.                                                                                                                                                                                            |
| `render?`       | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —         | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render.                                |

### PagedListContent

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### PagedListButton

| Prop                     | Type                                                                                 | Default                                                      | Description                                                                                                                                                                               |
| ------------------------ | ------------------------------------------------------------------------------------ | ------------------------------------------------------------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `focusableWhenDisabled?` | `boolean`                                                                            | `false`                                                      | Whether the button should be focusable when disabled.                                                                                                                                     |
| `nativeButton?`          | `boolean`                                                                            | `true`                                                       | Whether the component renders a native `<button>` element when replacing it via the `render` prop. Set to `false` if the rendered element is not a button (for example, `<div>`).         |
| `variant?`               | `"destructive" \| "ghost" \| "link" \| "outline" \| "primary" \| "secondary"`        | `"secondary"`                                                |                                                                                                                                                                                           |
| `size?`                  | `"default" \| "icon" \| "icon-lg" \| "icon-sm" \| "icon-xs" \| "lg" \| "sm" \| "xs"` | `"default"`                                                  |                                                                                                                                                                                           |
| `loadingLabel?`          | `React.ReactNode`                                                                    | `"Loading…"`                                                 | The label while a page loads.                                                                                                                                                             |
| `retryLabel?`            | `React.ReactNode`                                                                    | `"Try again"`                                                | The label after a page fails to load.                                                                                                                                                     |
| `endLabel?`              | `React.ReactNode`                                                                    | `"All caught up"`                                            | The marker that takes the button's place once there's nothing more.                                                                                                                       |
| `errorMessage?`          | `React.ReactNode`                                                                    | `"Couldn’t load more. Check your connection and try again."` | Shown under the button when a page fails to load.                                                                                                                                         |
| `auto?`                  | `boolean`                                                                            | `false`                                                      | Loads the next page automatically when the button comes within 200 pixels of view. After a failure, or a page that adds no rows, the button waits to be pressed.                          |
| `className?`             | `string \| ((state: ButtonState) => string \| undefined)`                            | —                                                            | CSS class applied to the element, or a function that returns a class based on the component's state.                                                                                      |
| `style?`                 | `React.CSSProperties \| ((state: ButtonState) => React.CSSProperties \| undefined)`  | —                                                            | Style applied to the element, or a function that returns a style object based on the component's state.                                                                                   |
| `render?`                | `ComponentRenderFn<HTMLProps, ButtonState> \| React.ReactElement`                    | —                                                            | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

### PagedListCount

| Prop         | Type                                                     | Default | Description                                                                                                                                                                               |
| ------------ | -------------------------------------------------------- | ------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `children?`  | `((count: number, total?: number) => React.ReactNode)`   | —       | Renders the count yourself, from the rows shown and the total.                                                                                                                            |
| `className?` | `string`                                                 | —       | CSS class applied to the element.                                                                                                                                                         |
| `style?`     | `React.CSSProperties`                                    | —       | Style applied to the element.                                                                                                                                                             |
| `render?`    | `ComponentRenderFn<HTMLProps, {}> \| React.ReactElement` | —       | Allows you to replace the component's HTML element with a different tag, or compose it with another component. Accepts a `ReactElement` or a function that returns the element to render. |

`PagedListButton` takes the props of [Button](https://ui.jarv.is/components/button.md) too, and its children are its
label while idle.

### usePagedList

`usePagedList()` reads the `PagedList` that your component renders in, and returns its state:

| Value     | Type                             | Description                                                                                       |
| --------- | -------------------------------- | ------------------------------------------------------------------------------------------------- |
| `status`  | `"error" \| "idle" \| "loading"` | `loading` while a page loads, and `error` after a page fails to load, until it's retried.         |
| `hasMore` | `boolean`                        | Whether there's another page.                                                                     |
| `count`   | `number \| null`                 | How many rows are shown, or `null` until they're counted in the browser.                          |
| `total`   | `number \| undefined`            | How many rows there are in all, when it's known.                                                  |
| `load`    | `() => void`                     | Loads the next page, as the button does, and moves focus to the page's first row once it's shown. |
