# Progress

> Segmented pill bar for a few steps, one continuous fill for many, and a sweeping capsule when the amount is unknown.

Docs: https://plumbago.ochotzas.com/components/progress

## Installation

```sh
npx plumbago add progress
```

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

## Usage

```tsx
import { Progress, ProgressLabel } from "@/components/ui/progress"

<Progress value={3} max={7}>
  <ProgressLabel>3 of 7 prep tasks done</ProgressLabel>
</Progress>
```

## Examples

### Preview

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { Checkbox } from "@/components/ui/checkbox"
import { Island } from "@/components/ui/island"
import { Progress, ProgressLabel } from "@/components/ui/progress"
import { useState } from "react"

const startingTasks = [
  { id: "stock", title: "Strain the chicken stock", done: true },
  { id: "herbs", title: "Pick the herbs", done: true },
  { id: "shallots", title: "Slice the shallots", done: true },
  { id: "butter", title: "Whip the brown butter", done: false },
  { id: "bread", title: "Proof the focaccia", done: false },
  { id: "tuile", title: "Bake the parmesan tuiles", done: false },
  { id: "fridge", title: "Label the walk-in", done: false },
]

export default function ProgressDemo() {
  const [tasks, setTasks] = useState(startingTasks)
  const done = tasks.filter((task) => task.done).length
  const toggle = (id: string, checked: boolean) => setTasks((list) => list.map((task) => (task.id === id ? { ...task, done: checked } : task)))
  return (
    <Island className="flex w-full max-w-sm flex-col gap-4">
      <Progress value={done} max={tasks.length}>
        <ProgressLabel>
          <BlurSwap text={String(done)} className="text-stat font-bold text-ink tabular-nums" />
          of {tasks.length} prep tasks done
        </ProgressLabel>
      </Progress>
      <div className="flex flex-col">
        {tasks.map((task) => (
          <label key={task.id} className="flex h-11 cursor-pointer items-center gap-3 text-body text-ink">
            <Checkbox checked={task.done} onCheckedChange={(checked) => toggle(task.id, checked)} />
            {task.title}
          </label>
        ))}
      </div>
    </Island>
  )
}
```

### Continuous

```tsx
import { Island } from "@/components/ui/island"
import { Progress, ProgressLabel } from "@/components/ui/progress"

export default function ProgressContinuous() {
  return (
    <Island className="w-full max-w-xs">
      <Progress value={64} max={120}>
        <ProgressLabel>
          <span className="text-stat font-bold text-ink tabular-nums">64</span>
          of 120 covers seated
        </ProgressLabel>
      </Progress>
    </Island>
  )
}
```

### Indeterminate

```tsx
import { BlurSwap } from "@/lib/blur-swap"
import { Button } from "@/components/ui/button"
import { Island } from "@/components/ui/island"
import { Progress, ProgressLabel } from "@/components/ui/progress"
import { useCallback, useEffect, useRef, useState } from "react"

const ORDERS = 120

function syncLabel(synced: number | null) {
  if (synced === null) return "Syncing tonight's orders…"
  if (synced === ORDERS) return `All ${ORDERS} orders synced`
  return `${synced} of ${ORDERS} orders synced`
}

export default function ProgressIndeterminate() {
  const [synced, setSynced] = useState<number | null>(null)
  const timers = useRef<ReturnType<typeof setTimeout>[]>([])

  const sync = useCallback(() => {
    setSynced(null)
    const steps = [0, 18, 42, 42, 77, 96, 120]
    timers.current = steps.map((count, index) => setTimeout(() => setSynced(count), 1800 + index * 500))
  }, [])

  useEffect(() => {
    sync()
    return () => timers.current.forEach(clearTimeout)
  }, [sync])

  return (
    <Island className="flex w-full max-w-xs flex-col gap-4">
      <Progress value={synced} max={ORDERS}>
        <ProgressLabel>
          <BlurSwap text={syncLabel(synced)} className="tabular-nums" />
        </ProgressLabel>
      </Progress>
      <Button variant="secondary" size="sm" className="self-start" disabled={synced !== ORDERS} onClick={sync}>
        Sync again
      </Button>
    </Island>
  )
}
```

## Built on Base UI

Progress wraps these Base UI parts and keeps their props:

- [Progress](https://base-ui.com/react/components/progress)

## Source

```tsx
import { Progress as BaseProgress } from "@base-ui/react/progress"
import { cn } from "@/lib/cn"
import { type ComponentProps, Fragment, useState } from "react"

const MAX_SEGMENTS = 10

const layerIn = "transition-[opacity,filter] delay-100 duration-spring ease-spring"
const layerOut = "transition-[opacity,filter] opacity-0 delay-0 duration-[120ms] ease-in motion-safe:blur-[3px]"

export type ProgressProps = Omit<ComponentProps<typeof BaseProgress.Root>, "className" | "min"> & {
  className?: string
}

export function Progress({ value, max = 100, className, children, ...props }: ProgressProps) {
  const segmented = Number.isInteger(max) && max <= MAX_SEGMENTS
  const [held, setHeld] = useState({ value: value ?? 0, waiting: value === null, arrival: 0 })
  if (value === null && !held.waiting) setHeld({ ...held, waiting: true })
  if (value !== null && (held.waiting || value !== held.value)) {
    setHeld({ value, waiting: false, arrival: held.waiting ? held.arrival + 1 : held.arrival })
  }
  return (
    <BaseProgress.Root data-slot="progress" value={value} max={max} className={cn("flex w-full flex-col gap-3", className)} {...props}>
      {children}
      <BaseProgress.Track data-slot="progress-track" className={cn("relative h-2 w-full", !segmented && "rounded-full bg-track")}>
        <span
          data-slot="progress-amount"
          className={cn("absolute inset-0 flex", segmented ? "gap-[3px]" : "overflow-hidden rounded-full bg-track", value === null ? layerOut : layerIn)}
        >
          <Fragment key={held.arrival}>
            {segmented ? <ProgressSegments value={held.value} max={max} /> : <ProgressFill value={held.value} max={max} />}
          </Fragment>
        </span>
        <span
          data-slot="progress-sweep"
          className={cn("absolute inset-0 overflow-hidden rounded-full bg-track", value === null ? layerIn : cn(layerOut, "pointer-events-none"))}
        >
          <span
            className={cn(
              "block h-full w-[40%] animate-progress-sweep rounded-full bg-ink motion-reduce:w-full motion-reduce:animate-none motion-reduce:opacity-60",
              value !== null && "[animation-play-state:paused]",
            )}
          />
        </span>
      </BaseProgress.Track>
    </BaseProgress.Root>
  )
}

export type ProgressLabelProps = Omit<ComponentProps<typeof BaseProgress.Label>, "className"> & {
  className?: string
}

export function ProgressLabel({ className, ...props }: ProgressLabelProps) {
  return <BaseProgress.Label data-slot="progress-label" className={cn("flex items-baseline gap-2 text-footnote text-ink-2", className)} {...props} />
}

export type ProgressValueProps = Omit<ComponentProps<typeof BaseProgress.Value>, "className"> & {
  className?: string
}

export function ProgressValue({ className, ...props }: ProgressValueProps) {
  return <BaseProgress.Value data-slot="progress-value" className={cn("text-footnote text-ink-2 tabular-nums", className)} {...props} />
}

function ProgressSegments({ value, max }: { value: number; max: number }) {
  const positions = Array.from({ length: max }, (_, index) => index)
  return positions.map((position) => {
    const share = Math.min(Math.max(value - position, 0), 1)
    return (
      <span key={position} data-slot="progress-segment" className="h-full flex-1 overflow-hidden rounded-full bg-track">
        <span
          data-filled={share === 1 ? "" : undefined}
          className="block size-full origin-left bg-ink transition-[scale] duration-spring ease-spring"
          style={{ scale: `${share} 1` }}
        />
      </span>
    )
  })
}

function ProgressFill({ value, max }: { value: number; max: number }) {
  const fraction = Math.min(Math.max(value / max, 0), 1)
  return (
    <span
      data-slot="progress-fill"
      className="h-full w-full rounded-full bg-ink transition-[translate] duration-spring ease-spring"
      style={{ translate: `${(fraction - 1) * 100}% 0` }}
    />
  )
}
```
