# VirtualList

A list that renders only the items near the visible part of its scroll container, and leaves room for the rest.

- Page: https://www.effectcn.com/components/virtual-list
- Kind: Headless component with parts
- File: `src/ui/virtual-list.ts`
- Built on: `VirtualList` from `@effect/ui-kit`

## Installation

1. Set up the project once: the packages, Tailwind CSS, the theme tokens and the `cn` helper. See [Installation](https://www.effectcn.com/docs/installation.md).
2. Copy the file below to `src/ui/virtual-list.ts`. The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.
3. Import it.

`src/ui/virtual-list.ts`

```ts
import type { Component } from "@effect/ui"
import type { Html } from "@effect/ui/html"
import type { VirtualList } from "@effect/ui-kit"
import { cn } from "#lib/cn"

/** What the `view` closure of the kit's `VirtualList` receives. */
export type VirtualListParts = Component.Headless.Parts<typeof VirtualList>

type ClassOption = { readonly class?: string | undefined }

type ItemOptions = ClassOption & {
  /** The item's index, from `virtualList.items`. */
  readonly index: number
  /** The item's own id, so its element follows it as the list scrolls. */
  readonly key: string
}

/**
 * The element that scrolls. It needs a bounded height: `h-80` unless `class`
 * says otherwise. Leave it out for a list that scrolls with the page.
 */
export const VirtualListViewport = <Msg>(
  h: Html.H<Msg>,
  virtualList: VirtualListParts,
  options: ClassOption = {}
) =>
  virtualList.viewport(
    h.div.class(cn("h-80 overflow-y-auto overscroll-contain rounded-md border bg-background text-[13px]", options.class))
  )

/**
 * The list. The kit writes its block padding inline to stand in for the rows
 * left out, so pad an element around it, and space the rows with `gap`, not
 * margins. Pass grid classes for a grid: the kit reads the columns itself.
 */
export const VirtualListItems = <Msg>(h: Html.H<Msg>, virtualList: VirtualListParts, options: ClassOption = {}) =>
  virtualList.list(h.div.class(cn("flex flex-col", options.class)))

/** One row. Draw one for each index in `virtualList.items`, in order. */
export const VirtualListItem = <Msg>(h: Html.H<Msg>, virtualList: VirtualListParts, options: ItemOptions) =>
  virtualList.item({
    element: h.div
      .key(options.key)
      .class(cn("flex min-h-9 shrink-0 items-center gap-3 border-b border-border/60 px-3", options.class)),
    index: options.index
  })

/** A table whose body is virtual. Put `VirtualListTableHeader` and `VirtualListTableBody` inside. */
export const VirtualListTable = <Msg>(h: Html.H<Msg>, virtualList: VirtualListParts, options: ClassOption = {}) =>
  virtualList.table(h.table.class(cn("w-full border-separate border-spacing-0 text-left", options.class)))

/** A header that stays at the top of the viewport. Its row is row 1 of the table. */
export const VirtualListTableHeader = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.thead.class(cn("sticky top-0 z-10 bg-muted text-xs text-muted-foreground", options.class))

export const VirtualListTableHead = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.th.class(cn("h-9 border-b px-3 font-medium whitespace-nowrap", options.class)).attr("scope", "col")

/** The `<tbody>`. The kit adds empty spacer rows to it instead of padding. */
export const VirtualListTableBody = <Msg>(h: Html.H<Msg>, virtualList: VirtualListParts) => virtualList.list(h.tbody)

export const VirtualListTableRow = <Msg>(h: Html.H<Msg>, virtualList: VirtualListParts, options: ItemOptions) =>
  virtualList.item({
    element: h.tr.key(options.key).class(cn("transition-colors duration-150 hover:bg-accent/60", options.class)),
    index: options.index
  })

export const VirtualListTableCell = <Msg>(h: Html.H<Msg>, options: ClassOption = {}) =>
  h.td.class(cn("h-9 border-b border-border/60 px-3 whitespace-nowrap", options.class))
```

```ts
import { VirtualListViewport, VirtualListItems, VirtualListItem, VirtualListTable, VirtualListTableHeader, VirtualListTableHead, VirtualListTableBody, VirtualListTableRow, VirtualListTableCell } from "#ui/virtual-list"
```

## Usage

A few dozen elements stand for 10,000 rows. With measure: false every row is exactly itemSize tall.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualList } from "@effect/ui-kit"
import { Schema } from "effect"
import { VirtualListItem, VirtualListItems, VirtualListViewport } from "#ui/virtual-list"

const VirtualListBasicMessage = UiSchema.TaggedEnum({
  ScrolledList: { first: Schema.Number, last: Schema.Number }
})

const count = 10_000

export const VirtualListBasic = Html.component({
  name: "VirtualListBasic",
  model: Schema.Struct({ first: Schema.Number, last: Schema.Number }),
  message: VirtualListBasicMessage
}).make({
  init: () => ({ first: 0, last: 0 }),
  update: {
    ScrolledList: ($, { first, last }) => $.evolve({ first, last })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-3").children(
      VirtualList(h, {
        props: { count, itemSize: 36, measure: false, initialCount: 12 },
        onEmit: { Scrolled: ({ first, last }) => VirtualListBasicMessage.ScrolledList({ first, last }) },
        view: (virtualList) =>
          VirtualListViewport(h, virtualList).children(
            VirtualListItems(h, virtualList).children(
              virtualList.items.map((index) =>
                VirtualListItem(h, virtualList, { index, key: String(index) }).children(
                  h.span.class("w-12 font-mono text-xs text-muted-foreground tabular-nums").children(String(index + 1)),
                  `Row ${(index + 1).toLocaleString("en-US")}`
                )
              )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        `Showing rows ${model.first + 1} to ${model.last + 1} of ${count.toLocaleString("en-US")}`
      )
    )
})
```

## Examples

### Measured heights

Rows of any height: itemSize is the estimate until a row renders and is measured.

```ts
import { Html } from "@effect/ui/html"
import { VirtualList } from "@effect/ui-kit"
import { Schema } from "effect"
import { VirtualListItem, VirtualListItems, VirtualListViewport } from "#ui/virtual-list"

const sentences = [
  "Shipped the new onboarding flow.",
  "The nightly build failed on the integration tests, and the cause looks like a flaky network mock rather than the change itself.",
  "Renamed the billing module.",
  "Reviewed the proposal for the search index. It needs a migration plan, a rollback plan and numbers from a production-sized dataset before we can say yes, so I asked for all three.",
  "Fixed a typo.",
  "Paired on the calendar bug: the week started on Sunday for everyone, whatever their locale said."
]

const authors = ["Ada", "Grace", "Linus", "Margaret", "Alan"]

const notes = Array.from({ length: 2000 }, (_, index) => ({
  id: `note-${index}`,
  author: authors[index % authors.length]!,
  text: sentences[(index * 7) % sentences.length]!
}))

export const VirtualListVariable = Html.component({
  name: "VirtualListVariable",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    // `itemSize` is only the estimate: each row is measured once it renders.
    VirtualList(h, {
      props: { keys: notes.map((note) => note.id), itemSize: 72, initialCount: 8 },
      view: (virtualList) =>
        VirtualListViewport(h, virtualList, { class: "w-full max-w-md" }).children(
          VirtualListItems(h, virtualList).children(
            virtualList.items.map((index) => {
              const note = notes[index]!
              return VirtualListItem(h, virtualList, {
                index,
                key: note.id,
                class: "flex-col items-start gap-1 py-2.5"
              }).children(
                h.div.class("text-xs font-medium text-muted-foreground").children(`${note.author} · #${index + 1}`),
                h.p.class("leading-relaxed").children(note.text)
              )
            })
          )
        )
    })
})
```

### Grid

The list is a CSS grid. The columns are read from the rendered boxes, so they follow the width.

```ts
import { Html } from "@effect/ui/html"
import { VirtualList } from "@effect/ui-kit"
import { Schema } from "effect"
import { VirtualListItem, VirtualListItems, VirtualListViewport } from "#ui/virtual-list"

const swatches = Array.from({ length: 3000 }, (_, index) => ({
  id: `swatch-${index}`,
  hue: (index * 137) % 360
}))

export const VirtualListGrid = Html.component({
  name: "VirtualListGrid",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    // The list is a CSS grid. The kit reads the lanes from the rendered
    // boxes, so it takes no column count.
    VirtualList(h, {
      props: { count: swatches.length, itemSize: 96, initialCount: 24 },
      view: (virtualList) =>
        VirtualListViewport(h, virtualList, { class: "w-full max-w-lg px-2.5" }).children(
          VirtualListItems(h, virtualList, {
            class: "my-2.5 grid grid-cols-[repeat(auto-fill,minmax(5.5rem,1fr))] gap-2.5"
          }).children(
            virtualList.items.map((index) => {
              const swatch = swatches[index]!
              return VirtualListItem(h, virtualList, {
                index,
                key: swatch.id,
                class: "flex-col items-stretch gap-1.5 rounded-md border p-1.5"
              }).children(
                h.div.class("h-14 rounded-sm").style({ background: `oklch(0.75 0.12 ${swatch.hue})` }),
                h.span.class("font-mono text-xs text-muted-foreground").children(`#${index + 1} · ${swatch.hue}°`)
              )
            })
          )
        )
    })
})
```

### Chat log

followEnd keeps new messages in view while you are at the end. Scroll up and it leaves you where you are.

```ts
import { Subscription, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualList, VirtualListScrollTarget } from "@effect/ui-kit"
import { Schema, Stream } from "effect"
import { Button } from "#ui/button"
import { VirtualListItem, VirtualListItems, VirtualListViewport } from "#ui/virtual-list"

const ChatMessage = Schema.Struct({ id: Schema.String, mine: Schema.Boolean, text: Schema.String })

const VirtualListChatMessage = UiSchema.TaggedEnum({
  ArrivedReply: {},
  UpdatedDraft: { value: Schema.String },
  SubmittedDraft: {},
  PressedJumpToLatest: {},
  PressedToggleReplies: {}
})

const replies = [
  "Sounds good.",
  "Can you send me the link?",
  "I'm looking at the logs now. The spike at 14:02 lines up with the deploy, so I'd start there.",
  "Agreed.",
  "Let's take it to the standup tomorrow, there's more to it than fits in a chat.",
  "On it."
]

const history = Array.from({ length: 400 }, (_, index) => ({
  id: `message-${index}`,
  mine: index % 3 === 0,
  text: replies[(index * 5) % replies.length]!
}))

export const VirtualListChat = Html.component({
  name: "VirtualListChat",
  model: Schema.Struct({
    messages: Schema.Array(ChatMessage),
    draft: Schema.String,
    live: Schema.Boolean,
    jumps: Schema.Number
  }),
  message: VirtualListChatMessage
}).make({
  init: () => ({ messages: history, draft: "", live: true, jumps: 0 }),
  update: {
    ArrivedReply: ($) =>
      $.evolve({
        messages: (messages) => [
          ...messages,
          { id: `message-${messages.length}`, mine: false, text: replies[messages.length % replies.length]! }
        ]
      }),
    UpdatedDraft: ($, { value }) => $.evolve({ draft: value }),
    // Your own message always scrolls to the end, wherever you were reading.
    SubmittedDraft: ($) =>
      $.model.draft.trim() === ""
        ? $.model
        : $.evolve({
          messages: (messages) => [
            ...messages,
            { id: `message-${messages.length}`, mine: true, text: $.model.draft.trim() }
          ],
          draft: "",
          jumps: (jumps) => jumps + 1
        }),
    PressedJumpToLatest: ($) => $.evolve({ jumps: (jumps) => jumps + 1 }),
    PressedToggleReplies: ($) => $.evolve({ live: (live) => !live })
  },
  subscriptions: ({ model }) => [
    model.live &&
    Subscription.make(
      "replies",
      Stream.tick("3 seconds").pipe(Stream.drop(1), Stream.as(VirtualListChatMessage.ArrivedReply()))
    )
  ],
  view: (h, model) =>
    h.div.class("flex w-full max-w-md flex-col overflow-hidden rounded-lg border bg-card").children(
      VirtualList(h, {
        props: {
          keys: model.messages.map((message) => message.id),
          itemSize: 44,
          initialCount: 12,
          // Follows new messages only while the reader is at the end.
          followEnd: { threshold: 24 },
          contentAlignment: "end",
          // A new `id` repeats the request for the same target.
          scrollTo: { target: VirtualListScrollTarget.End(), id: model.jumps }
        },
        view: (virtualList) =>
          h.div.class("relative").children(
            VirtualListViewport(h, virtualList, { class: "h-72 rounded-none border-0 bg-transparent px-3" }).children(
              // The list keeps a role that is already set, so this one is a log.
              VirtualListItems(h, virtualList, { class: "my-3 gap-1.5" })
                .attrs({ role: "log", "aria-label": "Chat" })
                .children(
                  virtualList.items.map((index) => {
                    const message = model.messages[index]!
                    return VirtualListItem(h, virtualList, {
                      index,
                      key: message.id,
                      class: message.mine ? "min-h-0 justify-end border-0 px-0" : "min-h-0 border-0 px-0"
                    }).children(
                      h.span
                        .class(
                          message.mine
                            ? "max-w-[80%] rounded-lg bg-primary px-3 py-1.5 text-primary-foreground"
                            : "max-w-[80%] rounded-lg bg-muted px-3 py-1.5"
                        )
                        .children(message.text)
                    )
                  })
                )
            ),
            !virtualList.atEnd &&
              Button(h, {
                variant: "outline",
                size: "sm",
                class: "absolute bottom-2 left-1/2 -translate-x-1/2 rounded-full shadow-float",
                onPress: VirtualListChatMessage.PressedJumpToLatest()
              }).children("Jump to latest")
          )
      }),
      h.form
        .class("flex items-center gap-2 border-t p-2.5")
        .on("submit", VirtualListChatMessage.SubmittedDraft())
        .children(
          h.input
            .class("h-7 min-w-0 flex-1 rounded-sm border border-input bg-background px-2.5 text-[13px]")
            .attrs({ placeholder: "Write a message", "aria-label": "Message" })
            .value(model.draft)
            .on("input", ({ value }) => VirtualListChatMessage.UpdatedDraft({ value })),
          Button(h, { size: "sm", props: { type: "submit" } }).children("Send"),
          Button(h, { variant: "outline", size: "sm", onPress: VirtualListChatMessage.PressedToggleReplies() })
            .children(model.live ? "Pause replies" : "Resume replies")
        )
    )
})
```

### Scroll to an item

scrollTo takes an index, a key, an offset or the end, and an align. A new id repeats a request.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { VirtualList, VirtualListAlign, VirtualListScrollTarget } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { VirtualListItem, VirtualListItems, VirtualListViewport } from "#ui/virtual-list"

const VirtualListScrollToMessage = UiSchema.TaggedEnum({
  UpdatedRow: { value: Schema.String },
  PickedAlign: { align: VirtualListAlign },
  SubmittedRow: {},
  PressedEnd: {}
})

const count = 5000

const aligns: ReadonlyArray<VirtualListAlign> = ["start", "center", "end", "nearest"]

export const VirtualListScrollTo = Html.component({
  name: "VirtualListScrollTo",
  model: Schema.Struct({
    row: Schema.String,
    align: VirtualListAlign,
    request: Schema.NullOr(Schema.Struct({ target: VirtualListScrollTarget, id: Schema.Number })),
    requests: Schema.Number
  }),
  message: VirtualListScrollToMessage
}).make({
  init: () => ({ row: "2500", align: "center", request: null, requests: 0 }),
  update: {
    UpdatedRow: ($, { value }) => $.evolve({ row: value }),
    PickedAlign: ($, { align }) => $.evolve({ align }),
    SubmittedRow: ($) => {
      const row = Math.min(count, Math.max(1, Math.round(Number($.model.row)) || 1))
      return $.evolve({
        row: String(row),
        request: { target: VirtualListScrollTarget.Index({ index: row - 1 }), id: $.model.requests },
        requests: (requests) => requests + 1
      })
    },
    PressedEnd: ($) =>
      $.evolve({
        request: { target: VirtualListScrollTarget.End(), id: $.model.requests },
        requests: (requests) => requests + 1
      })
  },
  view: (h, model) => {
    const target = model.request?.target
    const highlighted = target?._tag === "Index" ? target.index : -1
    return h.div.class("flex w-full max-w-sm flex-col gap-3").children(
      h.form.class("flex flex-wrap items-center gap-2").on("submit", VirtualListScrollToMessage.SubmittedRow()).children(
        h.input
          .class("h-7 w-20 rounded-sm border border-input bg-background px-2 text-[13px] tabular-nums")
          .attrs({ type: "number", min: "1", max: String(count), "aria-label": "Row number" })
          .value(model.row)
          .on("input", ({ value }) => VirtualListScrollToMessage.UpdatedRow({ value })),
        h.select
          .class("h-7 rounded-sm border border-input bg-background px-1.5 text-[13px]")
          .attr("aria-label", "Align")
          .value(model.align)
          .on("change", ({ value }) =>
            VirtualListScrollToMessage.PickedAlign({ align: aligns.find((align) => align === value) ?? "start" }))
          .children(aligns.map((align) => h.option.attr("value", align).children(align))),
        Button(h, { size: "sm", props: { type: "submit" } }).children("Go to row"),
        Button(h, { variant: "outline", size: "sm", onPress: VirtualListScrollToMessage.PressedEnd() }).children("End")
      ),
      VirtualList(h, {
        props: {
          count,
          itemSize: 36,
          measure: false,
          initialCount: 12,
          ...(model.request === null ? {} : { scrollTo: { ...model.request, align: model.align } })
        },
        view: (virtualList) =>
          VirtualListViewport(h, virtualList, { class: "h-72" }).children(
            VirtualListItems(h, virtualList).children(
              virtualList.items.map((index) =>
                VirtualListItem(h, virtualList, {
                  index,
                  key: String(index),
                  class: index === highlighted ? "bg-brand-wash font-medium" : ""
                }).children(
                  h.span.class("w-12 font-mono text-xs text-muted-foreground tabular-nums").children(String(index + 1)),
                  `Row ${index + 1}`
                )
              )
            )
          )
      })
    )
  }
})
```

### Table body

A <tbody> list with a sticky header. Rows carry aria-rowindex, counted after the header row.

```ts
import { Html } from "@effect/ui/html"
import { VirtualList } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  VirtualListTable as Table,
  VirtualListTableBody,
  VirtualListTableCell,
  VirtualListTableHead,
  VirtualListTableHeader,
  VirtualListTableRow,
  VirtualListViewport
} from "#ui/virtual-list"

const statuses = ["Paid", "Pending", "Refunded", "Failed"]
const customers = ["Ada Lovelace", "Grace Hopper", "Linus Torvalds", "Margaret Hamilton", "Alan Turing"]

const invoices = Array.from({ length: 5000 }, (_, index) => ({
  id: `INV-${String(index + 1).padStart(5, "0")}`,
  customer: customers[(index * 3) % customers.length]!,
  status: statuses[(index * 7) % statuses.length]!,
  amount: ((index * 7919) % 90000) / 100 + 20
}))

const money = new Intl.NumberFormat("en-US", { style: "currency", currency: "USD" })

export const VirtualListTable = Html.component({
  name: "VirtualListTable",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    // The header is row 1 of the table, so the body's rows count from 2.
    VirtualList(h, {
      props: {
        count: invoices.length,
        itemSize: 36,
        initialCount: 12,
        firstPosition: 2,
        setSize: invoices.length + 1
      },
      view: (virtualList) =>
        VirtualListViewport(h, virtualList, { class: "w-full max-w-xl" }).children(
          Table(h, virtualList).children(
            VirtualListTableHeader(h).children(
              h.tr.attr("aria-rowindex", "1").children(
                VirtualListTableHead(h).children("Invoice"),
                VirtualListTableHead(h).children("Customer"),
                VirtualListTableHead(h).children("Status"),
                VirtualListTableHead(h, { class: "text-right" }).children("Amount")
              )
            ),
            VirtualListTableBody(h, virtualList).children(
              virtualList.items.map((index) => {
                const invoice = invoices[index]!
                return VirtualListTableRow(h, virtualList, { index, key: invoice.id }).children(
                  VirtualListTableCell(h, { class: "font-mono text-xs" }).children(invoice.id),
                  VirtualListTableCell(h).children(invoice.customer),
                  VirtualListTableCell(h).children(
                    h.span
                      .class(
                        invoice.status === "Failed"
                          ? "rounded-sm bg-destructive/10 px-1.5 py-0.5 text-xs font-medium text-destructive"
                          : "rounded-sm bg-muted px-1.5 py-0.5 text-xs font-medium text-muted-foreground"
                      )
                      .children(invoice.status)
                  ),
                  VirtualListTableCell(h, { class: "text-right tabular-nums" }).children(money.format(invoice.amount))
                )
              })
            )
          )
        )
    })
})
```

## Anatomy

The parts the `view` closure receives. Apply each one to an element of your own.

| Part | Description |
| --- | --- |
| `viewport` | <div>, <ul> or <ol>: the element that scrolls. Leave it out and the list scrolls with scrollContainer or the page. |
| `table` | <table> around a <tbody> list, or a grid <div>: sets aria-rowcount. |
| `list` | <div>, <ul>, <ol> or <tbody>: holds the items and carries the mount. |
| `item` | <div>, <li> or <tr>: takes { element, index }. Key the element by the item's own id. |
| `items` | The indices to render, in order. |
| `atStart / atEnd` | Whether the list is scrolled to its start and to its end. |
| `scrolling` | Whether the list is scrolling, for rows that skip costly content meanwhile. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `count` | `number` | How many items the list has. Ignored when keys is passed. |
| `itemSize` | `number` | The height of an item in pixels until it is measured, or always with measure: false. |
| `keys` | `string[]` | A stable key per item. Sizes are kept by key, and items added before the visible ones leave them in place. |
| `measure` | `boolean` | Whether to measure the rendered items. true by default. |
| `sizes` | `number[]` | The height of each item by index, in place of itemSize. |
| `overscan` | `number` | Rows rendered on each side of the visible ones. 3 by default. |
| `initialCount` | `number` | Items rendered before the list is measured, as on the server. |
| `scrollTo` | `{ target, align?, id? }` | Scrolls to an Index, Key, Offset or End target once it is rendered. |
| `followEnd` | `boolean \| { threshold }` | Keeps the end in view as the list grows while the user is there. |
| `contentAlignment` | `"start" \| "end"` | Where a list shorter than its viewport sits. |
| `layout` | `"flow" \| "absolute"` | "absolute" places each item with a transform in a single lane. |
| `scrollContainer` | `"nearest" \| { selector }` | The element that scrolls when no viewport part is applied. |
| `reserveStart` | `number` | Space held above the first item while earlier items load. |
| `firstPosition / setSize` | `number` | Where the items sit in a larger set, for aria-posinset and aria-rowindex. |
| `trackScroll` | `boolean` | Emits Scrolled for every change of the scroll offset. |

### Events

| Event | Description |
| --- | --- |
| `Scrolled` | { first, last, atStart, atEnd, scrolling, offset, height, length }: the visible items, the edges and the position. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-index` | On item: the item's index. |
| `data-key` | On item: its key, when keys is given. |
| `data-virtual-list-spacer` | On each spacer row a <tbody> list adds. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
