# Progress

A progress bar for a task that takes a while, whose value lives in your Model.

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

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

type ProgressParts = Component.Headless.Parts<typeof Progress>

const sizes = { sm: "sm", md: "md", lg: "lg" } as const
const variants = { default: "default", success: "success", destructive: "destructive" } as const

export type ProgressSize = keyof typeof sizes
export type ProgressVariant = keyof typeof variants

interface ClassOption {
  readonly class?: string | undefined
}

/**
 * The `role="progressbar"` root: a two-column grid with the label and the value
 * above the track. `size` sets the track's height and `variant` the fill.
 * Without a label, chain an `aria-label`.
 */
export const ProgressRoot = <Msg>(
  h: Html.H<Msg>,
  progress: ProgressParts,
  options: ClassOption & {
    readonly size?: ProgressSize | undefined
    readonly variant?: ProgressVariant | undefined
  } = {}
) =>
  progress.root(
    h.div
      .class(cn("group/progress grid w-full grid-cols-[1fr_auto] items-baseline gap-x-3 gap-y-2", options.class))
      .attrs({ "data-size": sizes[options.size ?? "md"], "data-variant": variants[options.variant ?? "default"] })
  )

export const ProgressLabel = <Msg>(h: Html.H<Msg>, progress: ProgressParts, options: ClassOption = {}) =>
  progress.label(h.span.class(cn("text-[13px] font-medium text-foreground", options.class)))

/** The value's text. The kit fills it in when it has no children. */
export const ProgressValue = <Msg>(h: Html.H<Msg>, progress: ProgressParts, options: ClassOption = {}) =>
  progress.value(h.span.class(cn("text-[13px] text-muted-foreground tabular-nums", options.class)))

export const ProgressTrack = <Msg>(h: Html.H<Msg>, progress: ProgressParts, options: ClassOption = {}) =>
  progress.track(
    h.div.class(cn(
      "col-span-2 h-2 overflow-hidden rounded-full bg-secondary group-data-[size=sm]/progress:h-1 " +
        "group-data-[size=lg]/progress:h-3",
      options.class
    ))
  )

/**
 * The fill. The kit sets its width, and none while indeterminate, when a
 * short bar slides across the track (`animate-indeterminate` is defined in
 * `styles/tailwind.css`).
 */
export const ProgressIndicator = <Msg>(h: Html.H<Msg>, progress: ProgressParts, options: ClassOption = {}) =>
  progress.indicator(
    h.div.class(cn(
      "h-full rounded-full bg-brand transition-[width] duration-300 ease-out " +
        "data-[indeterminate]:w-2/5 data-[indeterminate]:animate-indeterminate " +
        "group-data-[variant=success]/progress:bg-success group-data-[variant=destructive]/progress:bg-destructive",
      options.class
    ))
  )
```

```ts
import { ProgressRoot, ProgressLabel, ProgressValue, ProgressTrack, ProgressIndicator } from "#ui/progress"
```

## Usage

A Subscription ticks the value in the Model, and stops once it reaches the end.

```ts
import { Subscription, UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema, Stream } from "effect"
import { Button } from "#ui/button"
import { ProgressIndicator, ProgressLabel, ProgressRoot, ProgressTrack, ProgressValue } from "#ui/progress"

const ProgressUploadMessage = UiSchema.TaggedEnum({ Ticked: {}, PressedRestart: {} })

export const ProgressUpload = Html.component({
  name: "ProgressUpload",
  model: Schema.Struct({ sent: Schema.Number }),
  message: ProgressUploadMessage
}).make({
  init: () => ({ sent: 12 }),
  update: {
    Ticked: ($) => $.evolve({ sent: (sent) => Math.min(100, sent + 4) }),
    PressedRestart: ($) => $.evolve({ sent: 0 })
  },
  subscriptions: ({ model }) => [
    model.sent < 100 &&
    Subscription.make("tick", Stream.tick("300 millis").pipe(Stream.as(ProgressUploadMessage.Ticked())))
  ],
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-4").children(
      Progress(h, {
        props: { value: model.sent },
        view: (progress) =>
          ProgressRoot(h, progress).children(
            ProgressLabel(h, progress).children(
              progress.status === "complete" ? "Uploaded" : "Uploading report.pdf"
            ),
            ProgressValue(h, progress),
            ProgressTrack(h, progress).children(
              ProgressIndicator(h, progress)
            )
          )
      }),
      h.div.class("flex items-center gap-2").children(
        Button(h, { variant: "outline", size: "sm", onPress: ProgressUploadMessage.PressedRestart() })
          .children("Restart")
      )
    )
})
```

## Examples

### Controlled

The bar alone, named with aria-label, following a value that buttons change.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { ProgressIndicator, ProgressRoot, ProgressTrack } from "#ui/progress"

const ProgressControlledMessage = UiSchema.TaggedEnum({ PressedDecrease: {}, PressedIncrease: {} })

export const ProgressControlled = Html.component({
  name: "ProgressControlled",
  model: Schema.Struct({ value: Schema.Number }),
  message: ProgressControlledMessage
}).make({
  init: () => ({ value: 40 }),
  update: {
    PressedDecrease: ($) => $.evolve({ value: (value) => Math.max(0, value - 10) }),
    PressedIncrease: ($) => $.evolve({ value: (value) => Math.min(100, value + 10) })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-4").children(
      // Without a label part, the root needs a name of its own.
      Progress(h, {
        props: { value: model.value },
        view: (progress) =>
          ProgressRoot(h, progress).attr("aria-label", "Profile completed").children(
            ProgressTrack(h, progress).children(
              ProgressIndicator(h, progress)
            )
          )
      }),
      h.div.class("flex items-center gap-2").children(
        Button(h, { variant: "outline", size: "sm", onPress: ProgressControlledMessage.PressedDecrease() })
          .children("-10"),
        Button(h, { variant: "outline", size: "sm", onPress: ProgressControlledMessage.PressedIncrease() })
          .children("+10"),
        h.span.class("text-xs text-muted-foreground tabular-nums").children(`${model.value}%`)
      )
    )
})
```

### Indeterminate

A null value is unknown progress: the kit sets data-indeterminate and no width.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { ProgressIndicator, ProgressLabel, ProgressRoot, ProgressTrack } from "#ui/progress"

const ProgressIndeterminateMessage = UiSchema.TaggedEnum({ PressedConnect: {}, PressedReset: {} })

export const ProgressIndeterminate = Html.component({
  name: "ProgressIndeterminate",
  model: Schema.Struct({ value: Schema.NullOr(Schema.Number) }),
  message: ProgressIndeterminateMessage
}).make({
  init: () => ({ value: null }),
  update: {
    PressedConnect: ($) => $.evolve({ value: 100 }),
    PressedReset: ($) => $.evolve({ value: null })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-4").children(
      // A null value is unknown progress: the kit sets data-indeterminate and no width.
      Progress(h, {
        props: { value: model.value },
        view: (progress) =>
          ProgressRoot(h, progress).children(
            ProgressLabel(h, progress).children(
              progress.status === "indeterminate" ? "Connecting to the server" : "Connected"
            ),
            ProgressTrack(h, progress).children(
              ProgressIndicator(h, progress)
            )
          )
      }),
      h.div.class("flex items-center gap-2").children(
        model.value === null
          ? Button(h, { variant: "outline", size: "sm", onPress: ProgressIndeterminateMessage.PressedConnect() })
            .children("Finish connecting")
          : Button(h, { variant: "outline", size: "sm", onPress: ProgressIndeterminateMessage.PressedReset() })
            .children("Start over")
      )
    )
})
```

### Sizes

Three track heights from the size option of the root.

```ts
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema } from "effect"
import { ProgressIndicator, ProgressLabel, ProgressRoot, ProgressTrack, ProgressValue } from "#ui/progress"

const sizes = [
  { size: "sm", value: 30 },
  { size: "md", value: 55 },
  { size: "lg", value: 80 }
] as const

export const ProgressSizes = Html.component({
  name: "ProgressSizes",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.div.class("flex w-full max-w-sm flex-col gap-6").children(
      sizes.map(({ size, value }) =>
        Progress(h, {
          key: size,
          props: { value },
          view: (progress) =>
            ProgressRoot(h, progress, { size }).children(
              ProgressLabel(h, progress).children(size),
              ProgressValue(h, progress),
              ProgressTrack(h, progress).children(
                ProgressIndicator(h, progress)
              )
            )
        })
      )
    )
})
```

### Colours by state

The variant option of the root picks the fill: brand, success or destructive.

```ts
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema } from "effect"
import { ProgressIndicator, ProgressLabel, ProgressRoot, ProgressTrack, ProgressValue } from "#ui/progress"

const jobs = [
  { id: "build", label: "Building", value: 64, variant: "default" },
  { id: "tests", label: "Tests passed", value: 100, variant: "success" },
  { id: "deploy", label: "Deploy failed", value: 38, variant: "destructive" },
  { id: "queue", label: "Waiting for a runner", value: null, variant: "default" }
] as const

export const ProgressStates = Html.component({
  name: "ProgressStates",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.div.class("flex w-full max-w-sm flex-col gap-6").children(
      jobs.map((job) =>
        Progress(h, {
          key: job.id,
          props: { value: job.value },
          view: (progress) =>
            ProgressRoot(h, progress, { variant: job.variant }).children(
              ProgressLabel(h, progress).children(job.label),
              ProgressValue(h, progress),
              ProgressTrack(h, progress).children(
                ProgressIndicator(h, progress)
              )
            )
        })
      )
    )
})
```

### Steps in a card

min, max and valueText turn the percentage into a step count.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Progress } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { ProgressIndicator, ProgressLabel, ProgressRoot, ProgressTrack, ProgressValue } from "#ui/progress"

const ProgressStepsMessage = UiSchema.TaggedEnum({ PressedBack: {}, PressedNext: {} })

const steps = ["Account", "Workspace", "Team", "Billing", "Review"]

export const ProgressSteps = Html.component({
  name: "ProgressSteps",
  model: Schema.Struct({ step: Schema.Number }),
  message: ProgressStepsMessage
}).make({
  init: () => ({ step: 2 }),
  update: {
    PressedBack: ($) => $.evolve({ step: (step) => Math.max(1, step - 1) }),
    PressedNext: ($) => $.evolve({ step: (step) => Math.min(steps.length, step + 1) })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-5 rounded-lg border bg-card p-5 shadow-sm").children(
      // min, max and valueText turn the percentage into "Step 2 of 5".
      Progress(h, {
        props: {
          value: model.step,
          min: 0,
          max: steps.length,
          valueText: `Step ${model.step} of ${steps.length}`
        },
        view: (progress) =>
          ProgressRoot(h, progress).children(
            ProgressLabel(h, progress).children(steps[model.step - 1]),
            ProgressValue(h, progress),
            ProgressTrack(h, progress).children(
              ProgressIndicator(h, progress)
            )
          )
      }),
      h.div.class("flex items-center justify-between").children(
        Button(h, {
          variant: "outline",
          size: "sm",
          props: { disabled: model.step === 1 },
          onPress: ProgressStepsMessage.PressedBack()
        }).children("Back"),
        Button(h, {
          size: "sm",
          props: { disabled: model.step === steps.length },
          onPress: ProgressStepsMessage.PressedNext()
        }).children(model.step === steps.length ? "Done" : "Next")
      )
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | The <div role="progressbar">. Its aria-labelledby points at the label. |
| `label` | A <span> inside the root that names the bar. |
| `value` | A <span> that shows the value text when it has no children. |
| `track` | The <div> the indicator fills. |
| `indicator` | The <div> inside the track. The kit sets its width while the value is known. |
| `status, percentage, valueText` | Plain values for markup that depends on them. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `number \| null` | How far the task has got. Required. null means unknown (indeterminate). |
| `min` | `number` | The start of the range. 0 by default. |
| `max` | `number` | The end of the range. 100 by default. |
| `valueText` | `string` | The text for aria-valuetext and the value part. The rounded percentage when left out. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-progressing` | On every part while the value is below max. |
| `data-complete` | On every part once the value is max. |
| `data-indeterminate` | On every part while the value is null. |

## Related components

- [Button](https://www.effectcn.com/components/button.md): A native button that can stay focusable while disabled.
