# Meter

A measurement within a known range, such as disk usage or a battery level.

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

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

type MeterParts = Component.Headless.Parts<typeof Meter>

const sizes = { sm: "sm", md: "md", lg: "lg" } as const
const levels = { low: "low", medium: "medium", high: "high" } as const

export type MeterSize = keyof typeof sizes
export type MeterLevel = keyof typeof levels

interface ClassOption {
  readonly class?: string | undefined
}

/**
 * The `role="meter"` root: a two-column grid with the label and the value above
 * the track. `size` sets the track's height. The kit's meter has no states, so
 * pass a `level` computed from your value to colour the fill: `low` is the
 * success colour, `medium` the warning and `high` the destructive one.
 */
export const MeterRoot = <Msg>(
  h: Html.H<Msg>,
  meter: MeterParts,
  options: ClassOption & {
    readonly size?: MeterSize | undefined
    readonly level?: MeterLevel | undefined
  } = {}
) =>
  meter.root(
    h.div
      .class(cn("group/meter 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-level": options.level === undefined ? undefined : levels[options.level]
      })
  )

export const MeterLabel = <Msg>(h: Html.H<Msg>, meter: MeterParts, options: ClassOption = {}) =>
  meter.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 MeterValue = <Msg>(h: Html.H<Msg>, meter: MeterParts, options: ClassOption = {}) =>
  meter.value(h.span.class(cn("text-[13px] text-muted-foreground tabular-nums", options.class)))

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

/** The fill, whose width the kit sets. */
export const MeterIndicator = <Msg>(h: Html.H<Msg>, meter: MeterParts, options: ClassOption = {}) =>
  meter.indicator(
    h.div.class(cn(
      "h-full rounded-full bg-brand transition-[width] duration-300 ease-out " +
        "group-data-[level=low]/meter:bg-success group-data-[level=medium]/meter:bg-warning " +
        "group-data-[level=high]/meter:bg-destructive",
      options.class
    ))
  )

/**
 * The meter as a ring: a root that draws the fill from `meter.percentage`
 * instead of an indicator. Put the value and the label inside it.
 */
export const MeterRing = <Msg>(h: Html.H<Msg>, meter: MeterParts, options: ClassOption = {}) =>
  meter.root(
    h.div
      .class(cn(
        "relative grid size-28 place-content-center justify-items-center gap-0.5 rounded-full " +
          "bg-[conic-gradient(var(--brand)_calc(var(--meter-percentage)*1%),var(--secondary)_0)] " +
          "before:absolute before:inset-2 before:rounded-full before:bg-background *:relative",
        options.class
      ))
      .style({ "--meter-percentage": String(meter.percentage) })
  )
```

```ts
import { MeterRoot, MeterLabel, MeterValue, MeterTrack, MeterIndicator, MeterRing } from "#ui/meter"
```

## Usage

max and valueText turn 12 of 16 into a three-quarter bar that reads in gigabytes.

```ts
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { MeterIndicator, MeterLabel, MeterRoot, MeterTrack, MeterValue } from "#ui/meter"

export const MeterStorage = Html.component({
  name: "MeterStorage",
  model: Schema.Struct({ used: Schema.Number, quota: Schema.Number }),
  message: Schema.Never
}).make({
  init: () => ({ used: 12, quota: 16 }),
  update: ($) => $.model,
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-4").children(
      Meter(h, {
        props: { value: model.used, max: model.quota, valueText: `${model.used} of ${model.quota} GB` },
        view: (meter) =>
          MeterRoot(h, meter).children(
            MeterLabel(h, meter).children("Storage"),
            MeterValue(h, meter),
            MeterTrack(h, meter).children(
              MeterIndicator(h, meter)
            )
          )
      })
    )
})
```

## Examples

### Thresholds

The meter has no states, so the level option colours the fill from the Model's value.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { MeterIndicator, MeterLabel, MeterRoot, MeterTrack, MeterValue } from "#ui/meter"

const MeterThresholdsMessage = UiSchema.TaggedEnum({ UpdatedLoad: { value: Schema.String } })

const levelOf = (load: number) => load >= 85 ? "high" as const : load >= 60 ? "medium" as const : "low" as const

export const MeterThresholds = Html.component({
  name: "MeterThresholds",
  model: Schema.Struct({ load: Schema.Number }),
  message: MeterThresholdsMessage
}).make({
  init: () => ({ load: 72 }),
  update: {
    UpdatedLoad: ($, { value }) => $.evolve({ load: Number(value) })
  },
  view: (h, model) =>
    h.div.class("flex w-full max-w-sm flex-col gap-4").children(
      // The meter has no states of its own, so the level comes from the Model.
      Meter(h, {
        props: { value: model.load },
        view: (meter) =>
          MeterRoot(h, meter, { level: levelOf(model.load) }).children(
            MeterLabel(h, meter).children("CPU load"),
            MeterValue(h, meter),
            MeterTrack(h, meter).children(
              MeterIndicator(h, meter)
            )
          )
      }),
      h.input.class("w-full accent-brand").attrs({ type: "range", min: "0", max: "100", "aria-label": "Simulated load" })
        .value(String(model.load))
        .on("input", ({ value }) => MeterThresholdsMessage.UpdatedLoad({ value })),
      h.p.class("m-0 text-xs text-muted-foreground").children("Below 60 is low, from 60 medium, from 85 high.")
    )
})
```

### Sizes

Three track heights from the size option of the root.

```ts
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { MeterIndicator, MeterLabel, MeterRoot, MeterTrack, MeterValue } from "#ui/meter"

const sizes = [
  { size: "sm", value: 35 },
  { size: "md", value: 60 },
  { size: "lg", value: 85 }
] as const

export const MeterSizes = Html.component({
  name: "MeterSizes",
  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 }) =>
        Meter(h, {
          key: size,
          props: { value },
          view: (meter) =>
            MeterRoot(h, meter, { size }).children(
              MeterLabel(h, meter).children(size),
              MeterValue(h, meter),
              MeterTrack(h, meter).children(
                MeterIndicator(h, meter)
              )
            )
        })
      )
    )
})
```

### Password strength

Five checks on what was typed, as a meter from 0 to 5 with a name for each score.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { MeterIndicator, MeterLabel, MeterRoot, MeterTrack, MeterValue } from "#ui/meter"

const MeterPasswordMessage = UiSchema.TaggedEnum({ UpdatedPassword: { value: Schema.String } })

const checks = [/.{8,}/, /[a-z]/, /[A-Z]/, /[0-9]/, /[^a-zA-Z0-9]/]
const names = ["Too short", "Weak", "Fair", "Good", "Strong", "Very strong"]

const scoreOf = (password: string) => checks.filter((check) => check.test(password)).length

export const MeterPassword = Html.component({
  name: "MeterPassword",
  model: Schema.Struct({ password: Schema.String }),
  message: MeterPasswordMessage
}).make({
  init: () => ({ password: "effect" }),
  update: {
    UpdatedPassword: ($, { value }) => $.evolve({ password: value })
  },
  view: (h, model) => {
    const score = scoreOf(model.password)
    return h.div.class("flex w-full max-w-xs flex-col gap-2.5").children(
      h.label.class("text-[13px] font-medium").attr("for", "meter-password").children("New password"),
      h.input
        .class("h-9 w-full rounded-md border border-input bg-background px-3 text-[13px] shadow-sm")
        .attrs({ id: "meter-password", type: "text", autocomplete: "off" })
        .value(model.password)
        .on("input", ({ value }) => MeterPasswordMessage.UpdatedPassword({ value })),
      Meter(h, {
        props: { value: score, max: checks.length, valueText: names[score]! },
        view: (meter) =>
          MeterRoot(h, meter, {
            size: "sm",
            level: score <= 2 ? "high" : score <= 3 ? "medium" : "low"
          }).children(
            MeterLabel(h, meter).children("Strength"),
            MeterValue(h, meter),
            MeterTrack(h, meter).children(
              MeterIndicator(h, meter)
            )
          )
      })
    )
  }
})
```

### In a card

Several meters in a usage card. The ones near their quota change colour.

```ts
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { MeterIndicator, MeterLabel, MeterRoot, MeterTrack, MeterValue } from "#ui/meter"

const stats = [
  { id: "requests", label: "Requests", used: 8200, quota: 10000, unit: "" },
  { id: "bandwidth", label: "Bandwidth", used: 38, quota: 100, unit: " GB" },
  { id: "seats", label: "Seats", used: 9, quota: 10, unit: "" }
]

export const MeterStatCard = Html.component({
  name: "MeterStatCard",
  model: Schema.Struct({}),
  message: Schema.Never
}).make({
  init: () => ({}),
  update: ($) => $.model,
  view: (h) =>
    h.div.class("flex w-full max-w-sm flex-col gap-5 rounded-lg border bg-card p-5 shadow-sm").children(
      h.div.children(
        h.h4.class("m-0 text-sm font-medium").children("Usage this month"),
        h.p.class("m-0 text-[13px] text-muted-foreground").children("The plan renews on the 1st.")
      ),
      stats.map((stat) =>
        Meter(h, {
          key: stat.id,
          props: {
            value: stat.used,
            max: stat.quota,
            valueText: `${stat.used.toLocaleString("en")} / ${stat.quota.toLocaleString("en")}${stat.unit}`
          },
          view: (meter) =>
            MeterRoot(h, meter, {
              size: "sm",
              level: meter.percentage >= 90 ? "high" : meter.percentage >= 75 ? "medium" : undefined
            }).children(
              MeterLabel(h, meter).children(stat.label),
              MeterValue(h, meter),
              MeterTrack(h, meter).children(
                MeterIndicator(h, meter)
              )
            )
        })
      )
    )
})
```

### Ring

MeterRing skips the indicator and draws a ring from meter.percentage.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { Meter } from "@effect/ui-kit"
import { Schema } from "effect"
import { Button } from "#ui/button"
import { MeterLabel, MeterRing, MeterValue } from "#ui/meter"

const MeterBatteryMessage = UiSchema.TaggedEnum({ PressedCharge: {}, PressedDrain: {} })

export const MeterBattery = Html.component({
  name: "MeterBattery",
  model: Schema.Struct({ battery: Schema.Number }),
  message: MeterBatteryMessage
}).make({
  init: () => ({ battery: 68 }),
  update: {
    PressedCharge: ($) => $.evolve({ battery: (battery) => Math.min(100, battery + 8) }),
    PressedDrain: ($) => $.evolve({ battery: (battery) => Math.max(0, battery - 8) })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-5").children(
      // MeterRing skips the indicator part and draws from meter.percentage.
      Meter(h, {
        props: { value: model.battery },
        view: (meter) =>
          MeterRing(h, meter).children(
            MeterValue(h, meter, { class: "text-xl font-semibold text-foreground" }),
            MeterLabel(h, meter, { class: "text-xs font-normal text-muted-foreground" })
              .children("Battery")
          )
      }),
      h.div.class("flex items-center gap-2").children(
        Button(h, { variant: "outline", size: "sm", onPress: MeterBatteryMessage.PressedDrain() })
          .children("Drain"),
        Button(h, { variant: "outline", size: "sm", onPress: MeterBatteryMessage.PressedCharge() })
          .children("Charge")
      )
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | The <div role="meter">. Its aria-labelledby points at the label. |
| `label` | A <span> inside the root that names the meter. |
| `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, whose width the kit sets. |
| `percentage, valueText` | Plain values, for a vertical meter or a ring. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `number` | The measurement. Required. A value outside the range is clamped to it. |
| `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 |
| --- | --- |
| `(none)` | A meter has no states to style. The ui file writes data-size and data-level on the root from its options. |

## Related components

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