# Animated Waterfall for UI SDK (/docs/components/waterfall)

Request bars grow from their start time one row after another, and nested spans cascade in.

```tsx title="example.tsx"
import * as React from "react"

import {
  visibleWaterfallRows,
  Waterfall,
  WaterfallAxis,
  WaterfallBar,
  WaterfallCell,
  WaterfallColumnHeader,
  WaterfallHeaderRow,
  WaterfallIndicator,
  WaterfallMark,
  WaterfallRow,
  WaterfallRowHeader,
  type WaterfallData,
} from "@/components/keyframery/waterfall"

type Load = "cold" | "cached"

/* [start, duration] per request, for a first visit and a repeat visit. */
const timings: Record<Load, Record<string, [number, number]>> = {
  cold: {
    doc: [0, 180], css: [190, 110], app: [195, 430], vendor: [210, 300], home: [240, 220],
    font: [320, 240], feed: [640, 380], me: [650, 120], posts: [665, 290], likes: [800, 170], hero: [700, 420],
  },
  cached: {
    doc: [0, 60], css: [64, 14], app: [66, 96], vendor: [70, 62], home: [74, 48],
    font: [80, 22], feed: [150, 230], me: [154, 70], posts: [160, 160], likes: [236, 110], hero: [170, 150],
  },
}
const loadedAt: Record<Load, number> = { cold: 630, cached: 168 }

const names: Record<string, string> = {
  doc: "/", css: "app.css", app: "app.js", vendor: "vendor.js", home: "home.js", font: "inter.woff2",
  feed: "api/feed", me: "api/me", posts: "api/posts", likes: "api/likes", hero: "hero.avif",
}

const tree: [string, string[]?][] = [["doc"], ["css"], ["app", ["vendor", "home"]], ["font"], ["feed", ["me", "posts", "likes"]], ["hero"]]

function build(load: Load): WaterfallData {
  const span = (id: string) => ({ value: id, label: names[id], start: timings[load][id][0], duration: timings[load][id][1] })
  return tree.map(([id, kids]) => ({ ...span(id), ...(kids ? { children: kids.map(span) } : {}) }))
}

const ms = { style: "unit", unit: "millisecond", unitDisplay: "narrow" } as const

const keySurface =
  "bg-background shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_1px_1px_rgb(0_0_0/0.05),0_3px_6px_-2px_rgb(0_0_0/0.1)] dark:bg-accent dark:shadow-[0_0_0_1px_rgb(255_255_255/0.07),inset_0_1px_0_rgb(255_255_255/0.08),0_2px_6px_-1px_rgb(0_0_0/0.6)]"

export default function WaterfallDemo() {
  const [load, setLoad] = React.useState<Load>("cold")
  const items = React.useMemo(() => build(load), [load])
  /* Render every row and let the waterfall hide the ones inside a closed span. */
  const rows = React.useMemo(() => visibleWaterfallRows(items, ["app", "feed"]), [items])
  const total = Math.max(...Object.values(timings[load]).map(([s, d]) => s + d))

  return (
    <div className="w-[560px]">
      <div className="mb-3 flex items-end justify-between">
        <div>
          <h3 className="text-[15px] font-semibold tracking-tight">lume.shop / home</h3>
          <p className="mt-1 text-[12px] text-muted-foreground tabular-nums">
            11 requests · finished in {total.toLocaleString("en")} ms
          </p>
        </div>
        <div className="flex gap-0.5 rounded-[11px] bg-muted p-0.5 shadow-[inset_0_1px_2px_rgb(0_0_0/0.07),inset_0_0_0_1px_rgb(0_0_0/0.035)] dark:shadow-[inset_0_1px_2px_rgb(0_0_0/0.5),inset_0_0_0_1px_rgb(255_255_255/0.04)]">
          {(["cold", "cached"] as const).map((l) => (
            <button
              key={l}
              type="button"
              data-load={l}
              aria-pressed={load === l}
              onClick={() => setLoad(l)}
              className={[
                "h-7 rounded-[9px] px-2.5 text-[12px] leading-none font-medium outline-none transition-[color,scale] duration-[calc(150ms*var(--kf-speed,1))] ease-house active:scale-[0.96] focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none",
                load === l ? `${keySurface} text-foreground` : "text-muted-foreground hover:text-foreground",
              ].join(" ")}
            >
              {l === "cold" ? "First visit" : "Repeat visit"}
            </button>
          ))}
        </div>
      </div>

      <Waterfall aria-label="Network requests" items={items} format={ms} className="grid-cols-[140px_56px_minmax(0,1fr)]">
        <WaterfallHeaderRow>
          <WaterfallColumnHeader>Request</WaterfallColumnHeader>
          <WaterfallColumnHeader className="justify-end">Time</WaterfallColumnHeader>
          <WaterfallColumnHeader aria-label="Timeline">
            <WaterfallAxis maxTicks={5} />
            <WaterfallMark time={loadedAt[load]}>DOMContentLoaded</WaterfallMark>
          </WaterfallColumnHeader>
        </WaterfallHeaderRow>
        {rows.map(({ item }) => (
          <WaterfallRow key={item.value} value={item.value} data-row={item.value}>
            <WaterfallRowHeader>
              {item.children && <WaterfallIndicator />}
              {item.label}
            </WaterfallRowHeader>
            <WaterfallCell className="justify-end">{item.duration} ms</WaterfallCell>
            <WaterfallBar />
          </WaterfallRow>
        ))}
      </Waterfall>
    </div>
  )
}
```

## Installation [#installation]

```bash
npx shadcn@latest add @keyframery/waterfall
```

This adds `components/keyframery/waterfall.tsx` and its primitive, `components/keyframery/primitives/waterfall.tsx`, to your project, and installs `@ui-sdk/react`. The motion tokens are added to your global CSS the first time you install a component.

## Usage [#usage]

```tsx
import {
  Waterfall,
  WaterfallAxis,
  WaterfallBar,
  WaterfallCell,
  WaterfallColumnHeader,
  WaterfallHeaderRow,
  WaterfallIndicator,
  WaterfallMark,
  WaterfallRow,
  WaterfallRowHeader,
  WaterfallTick,
} from "@/components/keyframery/waterfall"
```

The parts and props are the same as UI SDK's Waterfall. For every prop, see the [UI SDK waterfall reference](https://ui-sdk.dev/docs/components/waterfall).

## What moves [#what-moves]

| Move        | What you see                                                         |
| ----------- | -------------------------------------------------------------------- |
| **Cascade** | Rows arrive one after another; opening a span cascades its children. |
| **Spring**  | Bars grow from their start time, and glide when timings change.      |
| **Spring**  | The chevron turns on a spring.                                       |

Timing and springiness follow the [motion style](/docs/motion-styles) you set, so this component moves like the rest of your app.

## Swap the import [#swap-the-import]

Already using UI SDK's waterfall with your own styles? Keep your markup and change one line. The primitive adds motion and nothing else.

```tsx
// Before
import { … } from "@ui-sdk/react/waterfall"

// After: same parts, same props, now animated
import { … } from "@/components/keyframery/primitives/waterfall"
```

## Parts [#parts]

The finished component exports 11 parts:

`Waterfall`, `WaterfallAxis`, `WaterfallBar`, `WaterfallCell`, `WaterfallColumnHeader`, `WaterfallHeaderRow`, `WaterfallIndicator`, `WaterfallMark`, `WaterfallRow`, `WaterfallRowHeader`, `WaterfallTick`

## Accessibility [#accessibility]

Keyboard, focus and screen-reader behaviour come from UI SDK and are not changed. With reduced motion turned on, nothing in the waterfall moves: changes happen at once or with a short fade. More in [Accessibility](/docs/accessibility).

## Source [#source]

The code that lands in your project. It is yours to change.

**components/keyframery/waterfall.tsx**

```tsx
"use client"

/* Styled waterfall: the animated primitive plus the Keyframery look. */

import * as React from "react"

import {
  Waterfall as WaterfallRoot,
  WaterfallAxis as WaterfallAxisPrimitive,
  WaterfallBar as WaterfallBarPrimitive,
  WaterfallCell as WaterfallCellPrimitive,
  WaterfallColumnHeader as WaterfallColumnHeaderPrimitive,
  WaterfallHeaderRow as WaterfallHeaderRowPrimitive,
  WaterfallIndicator as WaterfallIndicatorPrimitive,
  WaterfallMark as WaterfallMarkPrimitive,
  WaterfallRow as WaterfallRowPrimitive,
  WaterfallRowHeader as WaterfallRowHeaderPrimitive,
  WaterfallTick as WaterfallTickPrimitive,
} from "@/components/keyframery/primitives/waterfall"
import { cn } from "@/lib/utils"

export { createWaterfallController, visibleWaterfallRows, type WaterfallData } from "@/components/keyframery/primitives/waterfall"

const focusRing = "outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-inset"

/* A sheet laid out as a grid; every row is a subgrid, so columns line up. Set the columns with
   a `grid-cols-[…]` class: the default is a name column and a timeline. */
function Waterfall({ className, ...props }: React.ComponentProps<typeof WaterfallRoot>) {
  return (
    <WaterfallRoot
      className={cn(
        "relative grid grid-cols-[minmax(8rem,auto)_minmax(0,1fr)] overflow-hidden rounded-[14px] bg-card py-1 text-[12.5px] text-card-foreground",
        "shadow-[0_0_0_1px_rgb(0_0_0/0.06),0_2px_6px_-2px_rgb(0_0_0/0.08),0_12px_32px_-8px_rgb(0_0_0/0.12)]",
        "dark:shadow-[0_0_0_1px_rgb(255_255_255/0.08),0_12px_32px_-8px_rgb(0_0_0/0.7)]",
        className as string,
      )}
      {...props}
    />
  )
}

const rowGrid = "col-span-full grid grid-cols-subgrid items-center gap-x-3 px-3"

function WaterfallHeaderRow({ className, ...props }: React.ComponentProps<typeof WaterfallHeaderRowPrimitive>) {
  return (
    <WaterfallHeaderRowPrimitive
      className={cn(rowGrid, "mb-1 h-12 border-b border-border text-[11px] font-medium text-muted-foreground", className as string)}
      {...props}
    />
  )
}

function WaterfallColumnHeader({ className, ...props }: React.ComponentProps<typeof WaterfallColumnHeaderPrimitive>) {
  return <WaterfallColumnHeaderPrimitive className={cn("relative flex h-full items-center", className as string)} {...props} />
}

/* Round times along the top of the timeline. */
function WaterfallAxis({ className, ...props }: React.ComponentProps<typeof WaterfallAxisPrimitive>) {
  return <WaterfallAxisPrimitive className={cn("relative h-full flex-1", className as string)} {...props} />
}

function WaterfallTick({ className, ...props }: React.ComponentProps<typeof WaterfallTickPrimitive>) {
  return (
    <WaterfallTickPrimitive
      className={cn(
        "top-2 -translate-x-1/2 text-[10.5px] leading-none font-normal whitespace-nowrap tabular-nums first:translate-x-0 last:-translate-x-full",
        className as string,
      )}
      {...props}
    />
  )
}

/* A moment across every row: a label in the header and a hairline running down the rows. */
function WaterfallMark({ className, ...props }: React.ComponentProps<typeof WaterfallMarkPrimitive>) {
  return (
    <WaterfallMarkPrimitive
      className={cn(
        "pointer-events-none bottom-1.5 z-10 -translate-x-1/2 rounded-full bg-ring/12 px-1.5 py-[3px] text-[10.5px] leading-none font-medium whitespace-nowrap text-ring",
        "after:absolute after:top-full after:left-1/2 after:h-[999px] after:w-px after:bg-ring/50 after:content-['']",
        className as string,
      )}
      {...props}
    />
  )
}

function WaterfallRow({ className, ...props }: React.ComponentProps<typeof WaterfallRowPrimitive>) {
  return (
    <WaterfallRowPrimitive
      className={cn(
        rowGrid,
        "h-8 cursor-default",
        "hover:bg-foreground/[0.03] data-selected:bg-accent dark:data-selected:bg-accent/70",
        focusRing,
        className as string,
      )}
      {...props}
    />
  )
}

/* The span's name, indented by its depth. Leaves line up with the names of spans beside a chevron. */
function WaterfallRowHeader({ className, ...props }: React.ComponentProps<typeof WaterfallRowHeaderPrimitive>) {
  return (
    <WaterfallRowHeaderPrimitive
      className={cn(
        "flex h-full min-w-0 items-center gap-1 truncate font-medium",
        "ps-[calc((var(--waterfall-level)-1)*14px)] not-data-branch:ps-[calc((var(--waterfall-level)-1)*14px+20px)]",
        "data-[level=2]:font-normal data-[level=2]:text-muted-foreground data-[level=2]:data-selected:text-foreground",
        focusRing,
        className as string,
      )}
      {...props}
    />
  )
}

function WaterfallIndicator({ className, children, ...props }: React.ComponentProps<typeof WaterfallIndicatorPrimitive>) {
  return (
    <WaterfallIndicatorPrimitive
      className={cn(
        "grid size-4 shrink-0 cursor-pointer place-items-center rounded-[5px] text-muted-foreground hover:bg-foreground/[0.06] hover:text-foreground",
        className as string,
      )}
      {...props}
    >
      {children ?? (
        <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden className="size-3.5">
          <path d="m6 4 4 4-4 4" />
        </svg>
      )}
    </WaterfallIndicatorPrimitive>
  )
}

function WaterfallCell({ className, ...props }: React.ComponentProps<typeof WaterfallCellPrimitive>) {
  return (
    <WaterfallCellPrimitive
      className={cn("flex h-full items-center whitespace-nowrap text-muted-foreground tabular-nums", focusRing, className as string)}
      {...props}
    />
  )
}

/* Top-level spans in the primary colour, nested ones quieter; the selected span takes the ring colour. */
function WaterfallBar({ className, ...props }: React.ComponentProps<typeof WaterfallBarPrimitive>) {
  return (
    <WaterfallBarPrimitive
      className={cn(
        "h-full",
        "before:inset-y-[10px] before:rounded-[3px] before:bg-primary/75",
        "data-[level=2]:before:bg-muted-foreground/40 data-[level=3]:before:bg-muted-foreground/30",
        "data-selected:before:bg-ring",
        focusRing,
        className as string,
      )}
      {...props}
    />
  )
}

export {
  Waterfall,
  WaterfallAxis,
  WaterfallBar,
  WaterfallCell,
  WaterfallColumnHeader,
  WaterfallHeaderRow,
  WaterfallIndicator,
  WaterfallMark,
  WaterfallRow,
  WaterfallRowHeader,
  WaterfallTick,
}
```

**components/keyframery/primitives/waterfall.tsx**

```tsx
"use client"

/* Animated drop-in for `@ui-sdk/react/waterfall`: same parts, same props. Swap the import and keep your
   code. This file adds motion only. Colours, radii, shadows and spacing stay yours. */

import {
  WaterfallAxis as WaterfallAxisPart,
  WaterfallBar as WaterfallBarPart,
  WaterfallIndicator as WaterfallIndicatorPart,
  WaterfallMark as WaterfallMarkPart,
  WaterfallRow as WaterfallRowPart,
  WaterfallTick as WaterfallTickPart,
} from "@ui-sdk/react/waterfall"
import * as React from "react"

import { cn } from "@/lib/utils"

export * from "@ui-sdk/react/waterfall"

/* UI SDK accepts a class name or a function of state; keep both working. */
function withClass<S>(base: string, className: string | ((state: S) => string | undefined) | undefined) {
  return typeof className === "function" ? (state: S) => cn(base, className(state)) : cn(base, className)
}

/* Keyframes rather than transitions: a row has no earlier state when it mounts, or when a collapsed
   span opens and its hidden rows show again. Both replay the animation. */
const keyframes = [
  "@keyframes kf-waterfall-row{from{opacity:0;translate:0 6px;filter:blur(3px)}}",
  "@keyframes kf-waterfall-bar{from{scale:0 1}}",
  "@keyframes kf-waterfall-mark{from{opacity:0;clip-path:inset(0 0 100% 0)}}",
].join("")

/* Cascade: each row rises in a little after the one before it among its siblings, so opening a
   span cascades its children from the first one. The place comes from the row's own
   `aria-posinset`; where a browser can't read it, every row simply arrives at once. */
function WaterfallRow({ className, ...props }: React.ComponentProps<typeof WaterfallRowPart>) {
  return (
    <>
      <style href="kf-waterfall" precedence="default">
        {keyframes}
      </style>
      <WaterfallRowPart
        className={withClass(
          cn(
            "[--kf-wf-i:attr(aria-posinset_type(<integer>),1)]",
            "[--kf-wf-delay:calc((min(var(--kf-wf-i),10)-1)*calc(36ms*var(--kf-speed,1)))]",
            "animate-[kf-waterfall-row_calc(420ms*var(--kf-speed,1))_var(--ease-spring)_backwards] [animation-delay:var(--kf-wf-delay)]",
            "motion-reduce:animate-none!",
          ),
          className,
        )}
        {...props}
      />
    </>
  )
}

/* The bar grows left to right from where its span starts, on a spring, just after its row arrives.
   When the range changes (a zoom, or new timings) it glides to its new place and length. It is
   drawn by `::before`, placed by `--waterfall-start` and `--waterfall-size`, with a neutral
   default surface you can restyle with `before:` classes. */
function WaterfallBar({ className, ...props }: React.ComponentProps<typeof WaterfallBarPart>) {
  return (
    <WaterfallBarPart
      className={withClass(
        cn(
          "relative",
          "before:absolute before:inset-y-2 before:start-(--waterfall-start) before:w-(--waterfall-size) before:min-w-0.5 before:content-['']",
          "before:bg-[color-mix(in_oklch,currentColor_40%,transparent)]",
          "before:origin-left rtl:before:origin-right",
          "before:animate-[kf-waterfall-bar_calc(620ms*var(--kf-speed,1))_var(--ease-spring)_backwards]",
          "before:[animation-delay:calc(var(--kf-wf-delay,0ms)+calc(90ms*var(--kf-speed,1)))]",
          "before:transition-[inset-inline-start,width] before:duration-[calc(560ms*var(--kf-speed,1))] before:ease-spring",
          "motion-reduce:before:animate-none! motion-reduce:before:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The chevron turns on a spring as its span opens. */
function WaterfallIndicator({ className, ...props }: React.ComponentProps<typeof WaterfallIndicatorPart>) {
  return (
    <WaterfallIndicatorPart
      className={withClass(
        cn(
          "transition-[rotate] duration-[calc(380ms*var(--kf-speed,1))] ease-spring data-expanded:rotate-90 rtl:data-expanded:-rotate-90",
          "motion-reduce:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* The mark glides to its new moment when the time changes or the range moves, draws down when it
   first appears, and fades while its moment is outside the range. */
function WaterfallMark({ className, ...props }: React.ComponentProps<typeof WaterfallMarkPart>) {
  return (
    <WaterfallMarkPart
      className={withClass(
        cn(
          "absolute start-(--waterfall-mark)",
          "transition-[inset-inline-start,opacity] duration-[calc(560ms*var(--kf-speed,1))] ease-spring data-outside:opacity-0",
          "animate-[kf-waterfall-mark_calc(520ms*var(--kf-speed,1))_var(--ease-house)_calc(240ms*var(--kf-speed,1))_backwards]",
          "motion-reduce:animate-none! motion-reduce:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Ticks sit at their time on the axis and glide when the range moves. */
function WaterfallTick({ className, ...props }: React.ComponentProps<typeof WaterfallTickPart>) {
  return (
    <WaterfallTickPart
      className={withClass(
        cn(
          "absolute start-(--waterfall-tick)",
          "transition-[inset-inline-start] duration-[calc(560ms*var(--kf-speed,1))] ease-spring motion-reduce:transition-none!",
        ),
        className,
      )}
      {...props}
    />
  )
}

/* Same as UI SDK's axis, but its default ticks are the gliding ones above. */
function WaterfallAxis({ children, ...props }: React.ComponentProps<typeof WaterfallAxisPart>) {
  return (
    <WaterfallAxisPart {...props}>
      {children ?? ((state) => state.ticks.map((tick) => <WaterfallTick key={tick.time} time={tick.time} />))}
    </WaterfallAxisPart>
  )
}

export { WaterfallAxis, WaterfallBar, WaterfallIndicator, WaterfallMark, WaterfallRow, WaterfallTick }
```

## Questions

### How does the animated Waterfall for UI SDK move?

Cascade: Rows arrive one after another; opening a span cascades its children. Spring: Bars grow from their start time, and glide when timings change. Spring: The chevron turns on a spring.

### Do I need Motion or Framer Motion for the animated Waterfall?

No. Every move is plain CSS, so there is nothing to install besides the component and UI SDK.

### Can I keep my own styling and only take the motion?

Yes. Import from `@/components/keyframery/primitives/waterfall` instead. It has the same parts and props as `@ui-sdk/react/waterfall` and adds motion only.

### What happens to the Waterfall when someone turns on reduced motion?

Nothing moves. State changes happen at once, or with a short fade.
