# ScrollArea

A native scroll container with custom scrollbars, overflow state and edge-fade CSS variables.

- Page: https://www.effectcn.com/components/scroll-area
- Kind: Headless component with parts
- File: `src/ui/scroll-area.ts`
- Built on: `ScrollArea` 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/scroll-area.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/scroll-area.ts`

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

type ScrollAreaParts = Component.Headless.Parts<typeof ScrollArea>

// Each mask is one literal, so Tailwind's scanner sees the whole class.
const fades = {
  none: "",
  y: "[mask-image:linear-gradient(to_bottom,transparent,black_min(40px,var(--scroll-area-overflow-y-start,0px)),black_calc(100%_-_min(40px,var(--scroll-area-overflow-y-end,0px))),transparent)]",
  x: "[mask-image:linear-gradient(to_right,transparent,black_min(40px,var(--scroll-area-overflow-x-start,0px)),black_calc(100%_-_min(40px,var(--scroll-area-overflow-x-end,0px))),transparent)]"
} as const

const visibilities = {
  hover: "opacity-0 data-[hovering]:opacity-100 data-[scrolling]:opacity-100",
  always: "opacity-100"
} as const

export type ScrollAreaFade = keyof typeof fades
export type ScrollAreaScrollbarVisibility = keyof typeof visibilities

interface ClassOption {
  readonly class?: string | undefined
}

/** The frame. Give it a size with `class`: `ScrollAreaRoot(h, scrollArea, { class: "h-64 w-56" })`. */
export const ScrollAreaRoot = <Msg>(h: Html.H<Msg>, scrollArea: ScrollAreaParts, options: ClassOption = {}) =>
  scrollArea.root(h.div.class(cn("overflow-hidden rounded-md border bg-background", options.class)))

/**
 * The element that scrolls. `fade` masks the edges the content overflows,
 * from the kit's `--scroll-area-overflow-*` variables, so an edge with nothing
 * beyond it stays sharp.
 */
export const ScrollAreaViewport = <Msg>(
  h: Html.H<Msg>,
  scrollArea: ScrollAreaParts,
  options: ClassOption & { readonly fade?: ScrollAreaFade | undefined } = {}
) =>
  scrollArea.viewport(
    h.div.class(cn(
      "size-full overscroll-contain rounded-[inherit] -outline-offset-2 [&::-webkit-scrollbar]:hidden",
      fades[options.fade ?? "none"],
      options.class
    ))
  )

/** The content. Padding goes here, not on the viewport. */
export const ScrollAreaContent = <Msg>(h: Html.H<Msg>, scrollArea: ScrollAreaParts, options: ClassOption = {}) =>
  scrollArea.content(h.div.class(cn(options.class)))

/**
 * A scrollbar with its thumb. `undefined` while its axis doesn't overflow,
 * unless `keepMounted`. It shows on hover and while scrolling, or always.
 */
export const ScrollAreaScrollbar = <Msg>(
  h: Html.H<Msg>,
  scrollArea: ScrollAreaParts,
  options: ClassOption & {
    readonly orientation?: ScrollAreaOrientation | undefined
    readonly keepMounted?: boolean | undefined
    readonly visibility?: ScrollAreaScrollbarVisibility | undefined
  } = {}
) =>
  scrollArea.scrollbar({
    orientation: options.orientation,
    keepMounted: options.keepMounted,
    element: h.div.class(cn(
      "z-10 flex touch-none p-0.5 transition-opacity duration-150 select-none " +
        "data-[orientation=horizontal]:h-2.5 data-[orientation=horizontal]:flex-col " +
        "data-[orientation=vertical]:w-2.5",
      visibilities[options.visibility ?? "hover"],
      options.class
    )),
    thumb: h.div.class(
      "flex-1 rounded-full bg-foreground/25 transition-colors duration-150 hover:bg-foreground/40 " +
        "data-[scrolling]:bg-foreground/40"
    )
  })

/** The square where two scrollbars meet. `undefined` unless both axes overflow. */
export const ScrollAreaCorner = <Msg>(h: Html.H<Msg>, scrollArea: ScrollAreaParts, options: ClassOption = {}) =>
  scrollArea.corner(h.div.class(cn("bg-transparent", options.class)))
```

```ts
import { ScrollAreaRoot, ScrollAreaViewport, ScrollAreaContent, ScrollAreaScrollbar, ScrollAreaCorner } from "#ui/scroll-area"
```

## Usage

A list of releases. The scrollbar shows on hover and while scrolling.

```ts
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import { ScrollAreaContent, ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaViewport } from "#ui/scroll-area"
import { Separator } from "#ui/separator"

const versions = Array.from({ length: 30 }, (_, index) => `v0.${30 - index}.0`)

export const ScrollAreaVertical = Html.component({
  name: "ScrollAreaVertical",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ScrollArea(h, {
      view: (scrollArea) =>
        ScrollAreaRoot(h, scrollArea, { class: "h-72 w-56" }).children(
          ScrollAreaViewport(h, scrollArea).children(
            ScrollAreaContent(h, scrollArea, { class: "p-4" }).children(
              h.h4.class("m-0 mb-3 text-sm font-medium").children("Releases"),
              versions.flatMap((version, index) => [
                index > 0 ? Separator(h, { class: "my-2" }) : undefined,
                h.div.class("font-mono text-[13px]").children(version)
              ])
            )
          ),
          ScrollAreaScrollbar(h, scrollArea)
        )
    })
})
```

## Examples

### Horizontal gallery

A row of cards behind a horizontal scrollbar.

```ts
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import { ScrollAreaContent, ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaViewport } from "#ui/scroll-area"

const works = [
  { title: "Composition VIII", artist: "Wassily Kandinsky", fill: "bg-brand-wash" },
  { title: "The Great Wave", artist: "Katsushika Hokusai", fill: "bg-brand-soft" },
  { title: "Broadway Boogie Woogie", artist: "Piet Mondrian", fill: "bg-secondary" },
  { title: "The Starry Night", artist: "Vincent van Gogh", fill: "bg-brand-wash" },
  { title: "Water Lilies", artist: "Claude Monet", fill: "bg-brand-soft" },
  { title: "The Kiss", artist: "Gustav Klimt", fill: "bg-secondary" }
]

export const ScrollAreaHorizontal = Html.component({
  name: "ScrollAreaHorizontal",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ScrollArea(h, {
      view: (scrollArea) =>
        ScrollAreaRoot(h, scrollArea, { class: "w-full max-w-md" }).children(
          ScrollAreaViewport(h, scrollArea).children(
            ScrollAreaContent(h, scrollArea, { class: "flex w-max gap-4 p-4" }).children(
              works.map((work) =>
                h.figure.class("m-0 w-36 shrink-0").children(
                  h.div.class(`h-44 rounded-md border ${work.fill}`),
                  h.figcaption.class("pt-2").children(
                    h.span.class("block truncate text-[13px] font-medium").children(work.title),
                    h.span.class("block truncate text-xs text-muted-foreground").children(work.artist)
                  )
                )
              )
            )
          ),
          ScrollAreaScrollbar(h, scrollArea, { orientation: "horizontal" })
        )
    })
})
```

### Both axes

A wide table with two scrollbars and the corner where they meet.

```ts
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import {
  ScrollAreaContent,
  ScrollAreaCorner,
  ScrollAreaRoot,
  ScrollAreaScrollbar,
  ScrollAreaViewport
} from "#ui/scroll-area"

const months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
const regions = [
  "Oslo", "Bergen", "Trondheim", "Stavanger", "Tromsø", "Bodø", "Ålesund", "Drammen",
  "Kristiansand", "Fredrikstad", "Sandnes", "Molde", "Hamar", "Narvik"
]

const sales = (row: number, column: number) => String(((row + 3) * (column + 7) * 37) % 900 + 100)

export const ScrollAreaBoth = Html.component({
  name: "ScrollAreaBoth",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ScrollArea(h, {
      view: (scrollArea) =>
        ScrollAreaRoot(h, scrollArea, { class: "h-72 w-full max-w-md" }).children(
          ScrollAreaViewport(h, scrollArea).children(
            ScrollAreaContent(h, scrollArea).children(
              h.table.class("border-separate border-spacing-0 text-[13px] whitespace-nowrap tabular-nums").children(
                h.thead.children(
                  h.tr.class("text-muted-foreground").children(
                    h.th.class("border-b px-4 py-2.5 text-left font-medium").attr("scope", "col").children("Region"),
                    months.map((month) =>
                      h.th.class("border-b px-4 py-2.5 text-right font-medium").attr("scope", "col").children(month)
                    )
                  )
                ),
                h.tbody.children(
                  regions.map((region, row) =>
                    h.tr.children(
                      h.th.class("border-b px-4 py-2 text-left font-medium").attr("scope", "row").children(region),
                      months.map((_, column) =>
                        h.td.class("border-b px-4 py-2 text-right").children(sales(row, column))
                      )
                    )
                  )
                )
              )
            )
          ),
          ScrollAreaScrollbar(h, scrollArea),
          ScrollAreaScrollbar(h, scrollArea, { orientation: "horizontal" }),
          ScrollAreaCorner(h, scrollArea)
        )
    })
})
```

### Edge fade

A mask built from the kit's overflow variables fades only the edges with more content beyond them.

```ts
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import { ScrollAreaContent, ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaViewport } from "#ui/scroll-area"

const paragraphs = [
  "The viewport carries four CSS variables: how far the content overflows at the start and at the end of each axis, in px.",
  "A mask that fades over min(40px, that distance) is invisible at an edge with nothing beyond it, and grows in as the content scrolls under it.",
  "The kit writes the variables straight to the element's inline style, so scrolling doesn't render the view again.",
  "The same state is also in data attributes, data-overflow-y-start and data-overflow-y-end, for styles that only need on and off.",
  "Scroll to either end and the fade at that edge is gone."
]

export const ScrollAreaFade = Html.component({
  name: "ScrollAreaFade",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ScrollArea(h, {
      view: (scrollArea) =>
        ScrollAreaRoot(h, scrollArea, { class: "h-56 w-80" }).children(
          ScrollAreaViewport(h, scrollArea, { fade: "y" }).children(
            ScrollAreaContent(h, scrollArea, { class: "flex flex-col gap-3 p-4" }).children(
              paragraphs.map((text) => h.p.class("m-0 text-[13px] leading-relaxed").children(text))
            )
          ),
          ScrollAreaScrollbar(h, scrollArea)
        )
    })
})
```

### In a card

A list of notifications that scrolls between a card's header and footer.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { ScrollAreaContent, ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaViewport } from "#ui/scroll-area"

const ScrollAreaCardMessage = UiSchema.TaggedEnum({
  PressedMarkAllRead: {},
  ClickedNotification: { id: Schema.Number }
})

const notifications = [
  "Ada commented on Quarterly report",
  "Grace invited you to Compilers",
  "The build of main passed",
  "Alan mentioned you in Decidability",
  "Your export is ready to download",
  "Edsger approved Shortest paths",
  "Barbara requested a review",
  "The staging deploy finished",
  "Donald pushed 3 commits to tex",
  "Margaret assigned you Flight software",
  "The weekly digest is ready",
  "Linus closed Scheduler regression"
]

export const ScrollAreaCard = Html.component({
  name: "ScrollAreaCard",
  model: Schema.Struct({ read: Schema.Array(Schema.Number) }),
  message: ScrollAreaCardMessage
}).make({
  init: () => ({ read: [2, 5] }),
  update: {
    PressedMarkAllRead: ($) => $.evolve({ read: notifications.map((_, id) => id) }),
    ClickedNotification: ($, { id }) => $.evolve({ read: (read) => read.includes(id) ? read : [...read, id] })
  },
  view: (h, model) => {
    const unread = notifications.length - model.read.length
    return h.div.class("w-full max-w-xs overflow-hidden rounded-lg border bg-card shadow-sm").children(
      h.div.class("flex items-center justify-between gap-3 border-b px-4 py-3").children(
        h.div.children(
          h.h4.class("m-0 text-sm font-medium").children("Notifications"),
          h.p.class("m-0 text-xs text-muted-foreground tabular-nums").children(
            unread === 0 ? "All caught up" : `${unread} unread`
          )
        ),
        Button(h, {
          variant: "ghost",
          size: "sm",
          props: { disabled: unread === 0 },
          onPress: ScrollAreaCardMessage.PressedMarkAllRead()
        }).children("Mark all read")
      ),
      ScrollArea(h, {
        view: (scrollArea) =>
          ScrollAreaRoot(h, scrollArea, { class: "h-60 rounded-none border-0 bg-transparent" }).children(
            ScrollAreaViewport(h, scrollArea).children(
              ScrollAreaContent(h, scrollArea, { class: "grid p-1.5" }).children(
                notifications.map((text, id) =>
                  h.button
                    .class(
                      "flex items-center gap-2.5 rounded-sm px-2.5 py-2 text-left text-[13px] hover:bg-accent " +
                        (model.read.includes(id) ? "text-muted-foreground" : "font-medium text-foreground")
                    )
                    .on("click", ScrollAreaCardMessage.ClickedNotification({ id }))
                    .children(
                      h.span.class(
                        "size-1.5 shrink-0 rounded-full " + (model.read.includes(id) ? "bg-transparent" : "bg-brand")
                      ),
                      text
                    )
                )
              )
            ),
            ScrollAreaScrollbar(h, scrollArea)
          )
      }),
      h.div.class("border-t px-4 py-2.5 text-xs text-muted-foreground").children(
        `${notifications.length} notifications this week`
      )
    )
  }
})
```

### Always visible

A scrollbar that stays mounted and visible, and a hint read from the overflow state.

```ts
import { Html } from "@effect/ui/html"
import { ScrollArea } from "@effect/ui-kit"
import { Schema } from "effect"
import { ScrollAreaContent, ScrollAreaRoot, ScrollAreaScrollbar, ScrollAreaViewport } from "#ui/scroll-area"

const lines = Array.from({ length: 24 }, (_, index) => `${String(index + 1).padStart(2, "0")}  log line ${index + 1}`)

export const ScrollAreaAlwaysVisible = Html.component({
  name: "ScrollAreaAlwaysVisible",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    ScrollArea(h, {
      // The end edge counts as reached 24px early.
      props: { overflowEdgeThreshold: { yEnd: 24 } },
      view: (scrollArea) =>
        h.div.class("flex flex-col items-center gap-4").children(
          ScrollAreaRoot(h, scrollArea, { class: "h-52 w-64 bg-muted" }).children(
            ScrollAreaViewport(h, scrollArea).children(
              ScrollAreaContent(h, scrollArea, { class: "p-3 pr-5 font-mono text-xs leading-6 whitespace-pre" }).children(
                lines.map((line) => h.div.children(line))
              )
            ),
            ScrollAreaScrollbar(h, scrollArea, { keepMounted: true, visibility: "always" })
          ),
          h.p.class("m-0 text-xs text-muted-foreground").children(
            !scrollArea.hasOverflowY
              ? "Everything fits"
              : scrollArea.overflowYEnd
              ? "More below"
              : "You reached the end"
          )
        )
    })
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | The <div> frame, position: relative. |
| `viewport` | The <div> that scrolls. Focusable while the content overflows. |
| `content` | The <div> around the content, which the kit measures. |
| `scrollbar({ element, thumb, orientation?, keepMounted? })` | The track with its thumb inside. undefined while that axis doesn't overflow, unless keepMounted. |
| `corner` | The <div> where two scrollbars meet. undefined unless both axes overflow. |
| `hasOverflowX, overflowYEnd, scrolling, hovering ...` | Plain values for markup that depends on the state. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `overflowEdgeThreshold` | `number \| { xStart?, xEnd?, yStart?, yEnd? }` | Pixels that must be scrolled past before an overflow edge attribute applies. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-has-overflow-x / data-has-overflow-y` | On root, viewport, content and scrollbar while that axis overflows. |
| `data-overflow-x-start / -x-end / -y-start / -y-end` | While there is content beyond that edge. |
| `data-scrolling` | While the user scrolls. Per axis on a scrollbar and its thumb. |
| `data-hovering` | On a scrollbar while the pointer is over the scroll area. |
| `data-orientation` | "vertical" or "horizontal", on a scrollbar and its thumb. |
| `--scroll-area-overflow-x-start / -x-end / -y-start / -y-end` | CSS variables on the viewport: the distance to each edge in px. |
| `--scroll-area-thumb-height / --scroll-area-thumb-width` | CSS variables on a scrollbar: the size of its thumb. |
| `--scroll-area-corner-width / --scroll-area-corner-height` | CSS variables on the root: the size of the corner. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
- [Separator](https://www.effectcn.com/components/separator.md): A horizontal or vertical divider between sections of content.
