# Scroll fade

> A scrolling area whose content dissolves softly into its edges, shown only where there is more to scroll to.

Docs: https://plumbago.ochotzas.com/components/scroll-fade

## Installation

```sh
npx plumbago add scroll-fade
```

This copies `components/ui/scroll-fade.tsx` into your project, along with `cn`, and installs `@base-ui/react`.

## Usage

```tsx
import { ScrollFade } from "@/components/ui/scroll-fade"

<ScrollFade className="h-72">
  {children}
</ScrollFade>
```

## Examples

### Preview

```tsx
import { Island, ListRow, ListRowText, ListRowTitle, ListRowValue } from "@/components/ui/island"
import { ScrollFade } from "@/components/ui/scroll-fade"

const tasks = [
  ["Order oat milk", "Today"],
  ["Prep tomato sauce", "Today"],
  ["Update the lunch menu", "Today"],
  ["Call the fish supplier", "Tomorrow"],
  ["Reply to catering request", "Tomorrow"],
  ["Count the wine cellar", "Wed"],
  ["Schedule weekend staff", "Wed"],
  ["Descale the espresso machine", "Thu"],
  ["Print new allergen cards", "Thu"],
  ["Book the pest inspection", "Fri"],
  ["Photograph the new desserts", "Fri"],
  ["Renew the food handler licence", "Sat"],
  ["Review last month's waste", "Sun"],
  ["Plan the autumn tasting menu", "Mon"],
  ["Reorder takeaway boxes", "Mon"],
]

export default function ScrollFadeDemo() {
  return (
    <Island variant="list" className="w-full max-w-md">
      <ScrollFade className="h-72">
        {tasks.map(([title, due]) => (
          <ListRow key={title}>
            <ListRowText>
              <ListRowTitle>{title}</ListRowTitle>
            </ListRowText>
            <ListRowValue>{due}</ListRowValue>
          </ListRow>
        ))}
      </ScrollFade>
    </Island>
  )
}
```

### On the page

```tsx
import { ScrollFade } from "@/components/ui/scroll-fade"

const notes = [
  "Fish arrives at 7:30, check the ice before signing.",
  "Switch the pasta special to the mushroom ragu on Thursday.",
  "The walk-in cooler logged 6 degrees overnight. Ask maintenance to look at the door seal.",
  "Two servers are out Saturday, so the patio closes at 9.",
  "Tasting menu tickets sell out fast, so open bookings at noon.",
  "Deep clean the hood filters before the inspection next week.",
  "Collect the new aprons from the print shop on Friday.",
  "Dessert photos are due to the website team by the end of the month.",
]

export default function ScrollFadeOnThePage() {
  return (
    <ScrollFade className="h-64 w-full max-w-md">
      <div className="flex flex-col gap-4 py-4">
        {notes.map((note) => (
          <p key={note} className="text-body text-ink">
            {note}
          </p>
        ))}
      </div>
    </ScrollFade>
  )
}
```

### Horizontal

```tsx
import { Chip } from "@/components/ui/chip"
import { ScrollFade } from "@/components/ui/scroll-fade"

const pairings = [
  "Chablis with the oysters",
  "Barolo with the lamb",
  "Sancerre with the goat cheese",
  "Rioja with the chorizo",
  "Sauternes with the tarte tatin",
  "Port with the stilton",
]

export default function ScrollFadeHorizontal() {
  return (
    <ScrollFade orientation="horizontal" scrollbar={false} className="w-full max-w-md">
      <div className="flex items-center gap-2 py-2">
        {pairings.map((pairing) => (
          <Chip key={pairing}>{pairing}</Chip>
        ))}
      </div>
    </ScrollFade>
  )
}
```

### Both ways

```tsx
import { Island } from "@/components/ui/island"
import { ScrollFade } from "@/components/ui/scroll-fade"

const days = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]

const rota = [
  { name: "Ana", shifts: ["Lunch", "Lunch", "Off", "Dinner", "Dinner", "Double", "Off"] },
  { name: "Marco", shifts: ["Dinner", "Off", "Dinner", "Dinner", "Double", "Double", "Lunch"] },
  { name: "Priya", shifts: ["Off", "Lunch", "Lunch", "Lunch", "Off", "Dinner", "Dinner"] },
  { name: "Tomás", shifts: ["Double", "Dinner", "Off", "Off", "Dinner", "Lunch", "Lunch"] },
  { name: "Lena", shifts: ["Lunch", "Double", "Dinner", "Off", "Lunch", "Off", "Dinner"] },
  { name: "Yusuf", shifts: ["Off", "Off", "Lunch", "Double", "Dinner", "Dinner", "Double"] },
  { name: "Chloé", shifts: ["Dinner", "Lunch", "Double", "Lunch", "Off", "Lunch", "Off"] },
  { name: "Kenji", shifts: ["Lunch", "Dinner", "Lunch", "Dinner", "Double", "Off", "Off"] },
]

export default function ScrollFadeBothWays() {
  return (
    <Island variant="list" className="w-full max-w-md">
      <ScrollFade orientation="both" className="h-64">
        <table className="text-body">
          <thead>
            <tr className="text-caption font-semibold text-ink-2">
              <th className="px-4 pt-4 pb-2 text-left">Staff</th>
              {days.map((day) => (
                <th key={day} className="px-4 pt-4 pb-2 text-left">
                  {day}
                </th>
              ))}
            </tr>
          </thead>
          <tbody>
            {rota.map((person) => (
              <tr key={person.name} className="border-t border-line">
                <td className="px-4 py-3 font-medium whitespace-nowrap text-ink">{person.name}</td>
                {person.shifts.map((shift, index) => (
                  <td key={days[index]} className={shift === "Off" ? "px-4 py-3 text-ink-3" : "px-4 py-3 text-ink"}>
                    {shift}
                  </td>
                ))}
              </tr>
            ))}
          </tbody>
        </table>
      </ScrollFade>
    </Island>
  )
}
```

## Built on Base UI

Scroll fade wraps these Base UI parts and keeps their props:

- [Scroll area](https://base-ui.com/react/components/scroll-area)

## Source

```tsx
import { ScrollArea } from "@base-ui/react/scroll-area"
import { cn } from "@/lib/cn"
import { type ComponentProps, type Ref, useCallback, useEffect, useRef } from "react"

type Edge = "top" | "bottom" | "left" | "right"

const edgeClasses: Record<Edge, string> = {
  top: "inset-x-0 top-0 h-(--pb-fade-size) bg-[linear-gradient(var(--fade-bg),transparent)] group-data-overflow-y-start/fade:opacity-100",
  bottom: "inset-x-0 bottom-0 h-(--pb-fade-size) bg-[linear-gradient(transparent,var(--fade-bg))] group-data-overflow-y-end/fade:opacity-100",
  left: "inset-y-0 left-0 w-(--pb-fade-size) bg-[linear-gradient(to_right,var(--fade-bg),transparent)] group-data-overflow-x-start/fade:opacity-100",
  right: "inset-y-0 right-0 w-(--pb-fade-size) bg-[linear-gradient(to_left,var(--fade-bg),transparent)] group-data-overflow-x-end/fade:opacity-100",
}

const layerAnchors: Record<Edge, string> = {
  top: "inset-x-0 top-0",
  bottom: "inset-x-0 bottom-0",
  left: "inset-y-0 left-0",
  right: "inset-y-0 right-0",
}

const blurLayers = [
  { reach: "70%", share: 12 },
  { reach: "55%", share: 6 },
  { reach: "40%", share: 3 },
  { reach: "25%", share: 1.5 },
]

function FadeEdge({ edge }: { edge: Edge }) {
  const along = edge === "top" || edge === "bottom" ? "height" : "width"
  return (
    <div
      data-slot="scroll-fade-edge"
      aria-hidden="true"
      className={cn("pointer-events-none absolute z-2 opacity-0 transition-opacity duration-base ease-out", edgeClasses[edge])}
    >
      {blurLayers.map((layer) => (
        <span
          key={layer.reach}
          className={cn("absolute [@media(prefers-reduced-transparency:reduce)]:hidden", layerAnchors[edge])}
          style={{
            [along]: layer.reach,
            backdropFilter: `blur(calc(var(--pb-fade-blur) / ${layer.share}))`,
            WebkitBackdropFilter: `blur(calc(var(--pb-fade-blur) / ${layer.share}))`,
          }}
        />
      ))}
    </div>
  )
}

function FadeScrollbar({ orientation }: { orientation: "vertical" | "horizontal" }) {
  return (
    <ScrollArea.Scrollbar
      data-slot="scroll-fade-scrollbar"
      orientation={orientation}
      className={cn(
        "pointer-events-none z-3 flex p-0.5 opacity-0 transition-[opacity,filter] duration-base ease-out motion-safe:blur-[2px]",
        "data-hovering:pointer-events-auto data-hovering:opacity-100 data-hovering:blur-none data-scrolling:pointer-events-auto data-scrolling:opacity-100 data-scrolling:blur-none data-scrolling:duration-fast",
        orientation === "vertical"
          ? "my-3 w-2 justify-center [mask-image:linear-gradient(to_bottom,transparent,#000_var(--fade-y-start),#000_calc(100%_-_var(--fade-y-end)),transparent)]"
          : "mx-3 h-2 flex-col justify-center [mask-image:linear-gradient(to_right,transparent,#000_var(--fade-x-start),#000_calc(100%_-_var(--fade-x-end)),transparent)]",
      )}
    >
      <ScrollArea.Thumb data-slot="scroll-fade-thumb" className={cn("rounded-full bg-ink-3", orientation === "vertical" ? "w-[3px]" : "h-[3px]")} />
    </ScrollArea.Scrollbar>
  )
}

function useWheelSideways(enabled: boolean) {
  const viewport = useRef<HTMLDivElement | null>(null)
  useEffect(() => {
    const element = viewport.current
    if (!enabled || !element) return
    const onWheel = (event: WheelEvent) => {
      if (event.ctrlKey || Math.abs(event.deltaX) >= Math.abs(event.deltaY)) return
      const room = element.scrollWidth - element.clientWidth
      if (room <= 0) return
      const atStart = element.scrollLeft <= 0 && event.deltaY < 0
      const atEnd = element.scrollLeft >= room - 1 && event.deltaY > 0
      if (atStart || atEnd) return
      event.preventDefault()
      element.scrollLeft += event.deltaMode === WheelEvent.DOM_DELTA_LINE ? event.deltaY * 16 : event.deltaY
    }
    element.addEventListener("wheel", onWheel, { passive: false })
    return () => element.removeEventListener("wheel", onWheel)
  }, [enabled])
  return viewport
}

export type ScrollFadeProps = Omit<ComponentProps<typeof ScrollArea.Root>, "className"> & {
  className?: string
  orientation?: "vertical" | "horizontal" | "both"
  scrollbar?: boolean
  sidewaysWheel?: boolean
  viewportClassName?: string
  viewportRef?: Ref<HTMLDivElement>
}

export function ScrollFade({
  orientation = "vertical",
  scrollbar = true,
  sidewaysWheel = orientation === "horizontal",
  className,
  viewportClassName,
  viewportRef,
  children,
  ...props
}: ScrollFadeProps) {
  const vertical = orientation !== "horizontal"
  const horizontal = orientation !== "vertical"
  const sideways = useWheelSideways(sidewaysWheel && orientation === "horizontal")
  const setViewport = useCallback(
    (node: HTMLDivElement | null) => {
      sideways.current = node
      if (typeof viewportRef === "function") viewportRef(node)
      else if (viewportRef) viewportRef.current = node
    },
    [sideways, viewportRef],
  )

  return (
    <ScrollArea.Root
      data-slot="scroll-fade"
      className={cn(
        "group/fade relative min-h-0 [--fade-bg:var(--pb-bg)] in-[.on-surface]:[--fade-bg:var(--pb-surface)]",
        "[--fade-x-end:0px] [--fade-x-start:0px] [--fade-y-end:0px] [--fade-y-start:0px] data-overflow-x-end:[--fade-x-end:calc(var(--pb-fade-size)_-_12px)] data-overflow-x-start:[--fade-x-start:calc(var(--pb-fade-size)_-_12px)] data-overflow-y-end:[--fade-y-end:calc(var(--pb-fade-size)_-_12px)] data-overflow-y-start:[--fade-y-start:calc(var(--pb-fade-size)_-_12px)]",
        "after:pointer-events-none after:absolute after:inset-0 after:z-4 after:rounded-[inherit] after:[corner-shape:inherit] after:content-[''] has-[[data-slot=scroll-fade-viewport]:focus-visible]:after:inset-ring-2 has-[[data-slot=scroll-fade-viewport]:focus-visible]:after:inset-ring-accent",
        className,
      )}
      {...props}
    >
      <ScrollArea.Viewport
        ref={setViewport}
        data-slot="scroll-fade-viewport"
        className={cn(
          "size-full rounded-[inherit] [corner-shape:inherit] outline-none focus-visible:outline-none",
          orientation === "both" ? "overscroll-contain" : horizontal ? "overscroll-x-contain" : "overscroll-y-contain",
          viewportClassName,
        )}
      >
        <ScrollArea.Content className={horizontal ? "w-max min-w-full" : undefined}>{children}</ScrollArea.Content>
      </ScrollArea.Viewport>
      {vertical && (
        <>
          <FadeEdge edge="top" />
          <FadeEdge edge="bottom" />
        </>
      )}
      {horizontal && (
        <>
          <FadeEdge edge="left" />
          <FadeEdge edge="right" />
        </>
      )}
      {scrollbar && vertical && <FadeScrollbar orientation="vertical" />}
      {scrollbar && horizontal && <FadeScrollbar orientation="horizontal" />}
      {scrollbar && orientation === "both" && <ScrollArea.Corner />}
    </ScrollArea.Root>
  )
}
```
