1Row 1
2Row 2
3Row 3
4Row 4
5Row 5
6Row 6
7Row 7
8Row 8
9Row 9
10Row 10
11Row 11
12Row 12

Showing rows 1 to 1 of 10,000

Installation

  1. Set up the project

    Once per project: the packages, Tailwind CSS, the theme tokens and the cn helper. Follow Installation.

  2. Copy the component into your project

    The kit owns behaviour, ARIA and data attributes. This file is the look, written with Tailwind classes, and it is yours to change.

    src/ui/virtual-list.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))
    
  3. Import it

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

Usage

Ten thousand rows.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.

Ada · #1

Shipped the new onboarding flow.

Grace · #2

The nightly build failed on the integration tests, and the cause looks like a flaky network mock rather than the change itself.

Linus · #3

Renamed the billing module.

Margaret · #4

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.

Alan · #5

Fixed a typo.

Ada · #6

Paired on the calendar bug: the week started on Sunday for everyone, whatever their locale said.

Grace · #7

Shipped the new onboarding flow.

Linus · #8

The nightly build failed on the integration tests, and the cause looks like a flaky network mock rather than the change itself.

Grid

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

#1 · 0°
#2 · 137°
#3 · 274°
#4 · 51°
#5 · 188°
#6 · 325°
#7 · 102°
#8 · 239°
#9 · 16°
#10 · 153°
#11 · 290°
#12 · 67°
#13 · 204°
#14 · 341°
#15 · 118°
#16 · 255°
#17 · 32°
#18 · 169°
#19 · 306°
#20 · 83°
#21 · 220°
#22 · 357°
#23 · 134°
#24 · 271°

Chat log

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

Sounds good.
On it.
Let's take it to the standup tomorrow, there's more to it than fits in a chat.
Agreed.

Scroll to an item

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

1Row 1
2Row 2
3Row 3
4Row 4
5Row 5
6Row 6
7Row 7
8Row 8
9Row 9
10Row 10
11Row 11
12Row 12

Table body

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

InvoiceCustomerStatusAmount
INV-00001Ada LovelacePaid$20.00
INV-00002Margaret HamiltonFailed$99.19
INV-00003Grace HopperRefunded$178.38
INV-00004Alan TuringPending$257.57
INV-00005Linus TorvaldsPaid$336.76
INV-00006Ada LovelaceFailed$415.95
INV-00007Margaret HamiltonRefunded$495.14
INV-00008Grace HopperPending$574.33
INV-00009Alan TuringPaid$653.52
INV-00010Linus TorvaldsFailed$732.71
INV-00011Ada LovelaceRefunded$811.90
INV-00012Margaret HamiltonPending$891.09

Anatomy

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

PartDescription
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.
itemsThe indices to render, in order.
atStart / atEndWhether the list is scrolled to its start and to its end.
scrollingWhether the list is scrolling, for rows that skip costly content meanwhile.

API reference

Props

PropTypeDescription
countnumberHow many items the list has. Ignored when keys is passed.
itemSizenumberThe height of an item in pixels until it is measured, or always with measure: false.
keysstring[]A stable key per item. Sizes are kept by key, and items added before the visible ones leave them in place.
measurebooleanWhether to measure the rendered items. true by default.
sizesnumber[]The height of each item by index, in place of itemSize.
overscannumberRows rendered on each side of the visible ones. 3 by default.
initialCountnumberItems 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.
followEndboolean | { 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.
reserveStartnumberSpace held above the first item while earlier items load.
firstPosition / setSizenumberWhere the items sit in a larger set, for aria-posinset and aria-rowindex.
trackScrollbooleanEmits Scrolled for every change of the scroll offset.

Events

EventDescription
Scrolled{ first, last, atStart, atEnd, scrolling, offset, height, length }: the visible items, the edges and the position.

Data attributes

AttributeDescription
data-indexOn item: the item's index.
data-keyOn item: its key, when keys is given.
data-virtual-list-spacerOn each spacer row a <tbody> list adds.

The components this page's file and examples import.

  • Button: A native button that can stay focusable while disabled.

effectcn is built with Effect UI and @effect/ui-kit. Not affiliated with Effectful Technologies.