# ToggleGroup

A row of toggle buttons that share one value, with one tab stop and arrow-key focus.

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

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

type ToggleGroupParts = Component.Headless.Parts<typeof ToggleGroup>

export type ToggleGroupVariant = "default" | "outline"
export type ToggleGroupSize = "default" | "sm" | "lg"

/**
 * The group. `variant` and `size` are set once here, and the items follow
 * them: `outline` joins the items into one bordered control.
 */
export const ToggleGroupRoot = <Msg>(
  h: Html.H<Msg>,
  toggleGroup: ToggleGroupParts,
  options: {
    readonly variant?: ToggleGroupVariant | undefined
    readonly size?: ToggleGroupSize | undefined
    readonly class?: string | undefined
  } = {}
) =>
  toggleGroup.root(
    h.div
      .class(cn(
        "group/toggle-group inline-flex items-center gap-0.5 rounded-md " +
          "data-[orientation=vertical]:flex-col data-[orientation=vertical]:items-stretch " +
          "data-[variant=outline]:gap-0 data-[variant=outline]:shadow-sm",
        options.class
      ))
      .attrs({ "data-variant": options.variant ?? "default", "data-size": options.size ?? "default" })
  )

const item =
  "inline-flex h-8.5 min-w-8.5 shrink-0 items-center justify-center gap-1.5 rounded-md border border-transparent " +
  "bg-transparent px-2 text-[13px] leading-none font-medium whitespace-nowrap text-foreground select-none " +
  "transition-colors duration-150 hover:bg-muted hover:text-muted-foreground focus-visible:relative focus-visible:z-10 " +
  "data-[pressed]:bg-brand-soft data-[pressed]:text-brand-soft-foreground " +
  "data-[disabled]:cursor-not-allowed data-[disabled]:opacity-50 [&_svg]:size-[15px] [&_svg]:shrink-0 " +
  "group-data-[size=sm]/toggle-group:h-7 group-data-[size=sm]/toggle-group:min-w-7 " +
  "group-data-[size=sm]/toggle-group:px-1.5 group-data-[size=sm]/toggle-group:text-xs " +
  "group-data-[size=lg]/toggle-group:h-10 group-data-[size=lg]/toggle-group:min-w-10 " +
  "group-data-[size=lg]/toggle-group:px-3 group-data-[size=lg]/toggle-group:text-sm " +
  "group-data-[variant=outline]/toggle-group:rounded-none group-data-[variant=outline]/toggle-group:border-input"

const joined = {
  horizontal: "group-data-[variant=outline]/toggle-group:not-first:-ml-px " +
    "group-data-[variant=outline]/toggle-group:first:rounded-l-md " +
    "group-data-[variant=outline]/toggle-group:last:rounded-r-md",
  vertical: "justify-start group-data-[variant=outline]/toggle-group:not-first:-mt-px " +
    "group-data-[variant=outline]/toggle-group:first:rounded-t-md " +
    "group-data-[variant=outline]/toggle-group:last:rounded-b-md"
} as const

/** One item, for the `value` of an entry in the group's `items` prop. Chain its label or icon as children. */
export const ToggleGroupItem = <Msg>(
  h: Html.H<Msg>,
  toggleGroup: ToggleGroupParts,
  options: { readonly value: string; readonly class?: string | undefined }
) =>
  toggleGroup.item({
    element: h.button.class(cn(item, joined[toggleGroup.orientation], options.class)),
    value: options.value
  })
```

```ts
import { ToggleGroupRoot, ToggleGroupItem } from "#ui/toggle-group"
```

## Usage

One item at a time: pressing another releases the first.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupSingleMessage = UiSchema.TaggedEnum({
  ToggledAlignment: { value: Schema.Array(Schema.String) }
})

const alignments = [
  { value: "left", label: "Align left", d: "M21 6H3M15 12H3M17 18H3" },
  { value: "center", label: "Align center", d: "M21 6H3M17 12H7M19 18H5" },
  { value: "right", label: "Align right", d: "M21 6H3M21 12H9M21 18H7" }
]

export const ToggleGroupSingle = Html.component({
  name: "ToggleGroupSingle",
  model: Schema.Struct({ alignment: Schema.Array(Schema.String) }),
  message: ToggleGroupSingleMessage
}).make({
  init: () => ({ alignment: ["left"] }),
  update: {
    ToggledAlignment: ($, { value }) => $.evolve({ alignment: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      ToggleGroup(h, {
        props: { value: model.alignment, items: alignments.map(({ value }) => ({ value })) },
        onEmit: { Toggled: ({ value }) => ToggleGroupSingleMessage.ToggledAlignment({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup).attr("aria-label", "Text alignment").children(
            alignments.map(({ d, label, value }) =>
              ToggleGroupItem(h, toggleGroup, { value })
                .attr("aria-label", label)
                .children(
                  h.el("svg")
                    .attrs({
                      viewBox: "0 0 24 24",
                      fill: "none",
                      stroke: "currentColor",
                      "stroke-width": "2",
                      "stroke-linecap": "round",
                      "aria-hidden": "true"
                    })
                    .children(h.el("path").attr("d", d))
                )
            )
          )
      }),
      // Pressing the pressed item releases it, so the value can be empty.
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.alignment.length === 0 ? "No alignment" : `Aligned ${model.alignment.join(", ")}`
      )
    )
})
```

## Examples

### Multiple

With multiple, several items stay pressed at once.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupMultipleMessage = UiSchema.TaggedEnum({
  ToggledFormat: { value: Schema.Array(Schema.String) }
})

const formats = [
  { value: "bold", label: "Bold", d: "M7 5h6a3.5 3.5 0 0 1 0 7H7zM7 12h7a3.5 3.5 0 0 1 0 7H7z" },
  { value: "italic", label: "Italic", d: "M19 4h-9M14 20H5M15 4 9 20" },
  { value: "underline", label: "Underline", d: "M6 4v6a6 6 0 0 0 12 0V4M4 20h16" },
  { value: "strike", label: "Strikethrough", d: "M16 5H9a3 3 0 0 0-2.8 4M4 12h16M14 12a3.5 3.5 0 0 1 0 7H6" }
]

export const ToggleGroupMultiple = Html.component({
  name: "ToggleGroupMultiple",
  model: Schema.Struct({ formats: Schema.Array(Schema.String) }),
  message: ToggleGroupMultipleMessage
}).make({
  init: () => ({ formats: ["bold", "italic"] }),
  update: {
    ToggledFormat: ($, { value }) => $.evolve({ formats: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      ToggleGroup(h, {
        props: { value: model.formats, items: formats.map(({ value }) => ({ value })), multiple: true },
        onEmit: { Toggled: ({ value }) => ToggleGroupMultipleMessage.ToggledFormat({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup).attr("aria-label", "Text formatting").children(
            formats.map(({ d, label, value }) =>
              ToggleGroupItem(h, toggleGroup, { value })
                .attr("aria-label", label)
                .children(
                  h.el("svg")
                    .attrs({
                      viewBox: "0 0 24 24",
                      fill: "none",
                      stroke: "currentColor",
                      "stroke-width": "2",
                      "stroke-linecap": "round",
                      "stroke-linejoin": "round",
                      "aria-hidden": "true"
                    })
                    .children(h.el("path").attr("d", d))
                )
            )
          )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        model.formats.length === 0 ? "Plain text" : model.formats.join(", ")
      )
    )
})
```

### Outline

A joined, bordered control with text labels that always keeps one item pressed.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupOutlineMessage = UiSchema.TaggedEnum({
  ToggledView: { value: Schema.Array(Schema.String) }
})

const views = [
  { value: "list", label: "List" },
  { value: "board", label: "Board" },
  { value: "calendar", label: "Calendar" }
]

export const ToggleGroupOutline = Html.component({
  name: "ToggleGroupOutline",
  model: Schema.Struct({ view: Schema.String }),
  message: ToggleGroupOutlineMessage
}).make({
  init: () => ({ view: "board" }),
  update: {
    // Releasing the pressed item asks for an empty value. Keeping the Model as it is makes one always pressed.
    ToggledView: ($, { value }) => {
      const [view] = value
      return view === undefined ? $.model : $.evolve({ view })
    }
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      ToggleGroup(h, {
        props: { value: [model.view], items: views.map(({ value }) => ({ value })) },
        onEmit: { Toggled: ({ value }) => ToggleGroupOutlineMessage.ToggledView({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup, { variant: "outline" }).attr("aria-label", "View")
            .children(
              views.map(({ label, value }) =>
                ToggleGroupItem(h, toggleGroup, { value }).children(label)
              )
            )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(`Showing the ${model.view}`)
    )
})
```

### Sizes

Small, default and large, set with data-size on the root.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupSizesMessage = UiSchema.TaggedEnum({
  ToggledRange: { size: Schema.String, value: Schema.Array(Schema.String) }
})

const sizes = ["sm", "default", "lg"] as const

const ranges = ["1D", "1W", "1M", "1Y"]

export const ToggleGroupSizes = Html.component({
  name: "ToggleGroupSizes",
  model: Schema.Struct({ ranges: Schema.Record(Schema.String, Schema.Array(Schema.String)) }),
  message: ToggleGroupSizesMessage
}).make({
  init: () => ({ ranges: { sm: ["1D"], default: ["1W"], lg: ["1M"] } }),
  update: {
    ToggledRange: ($, { size, value }) => $.evolve({ ranges: (current) => ({ ...current, [size]: value }) })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      // Three groups in one view, so each has a key.
      sizes.map((size) =>
        ToggleGroup(h, {
          key: size,
          props: { value: model.ranges[size] ?? [], items: ranges.map((value) => ({ value })) },
          onEmit: { Toggled: ({ value }) => ToggleGroupSizesMessage.ToggledRange({ size, value }) },
          view: (toggleGroup) =>
            ToggleGroupRoot(h, toggleGroup, { variant: "outline", size })
              .attr("aria-label", `Range, ${size}`)
              .children(
                ranges.map((value) =>
                  ToggleGroupItem(h, toggleGroup, { value }).children(value)
                )
              )
        })
      )
    )
})
```

### Vertical

A column of items that moves with the Down and Up keys.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupVerticalMessage = UiSchema.TaggedEnum({
  ToggledTool: { value: Schema.Array(Schema.String) }
})

const tools = [
  { value: "select", label: "Select", d: "M5 3l14 7-6 2-2 6z" },
  { value: "pen", label: "Pen", d: "M4 20h4L19 9l-4-4L4 16v4zM13.5 6.5l4 4" },
  { value: "shape", label: "Rectangle", d: "M5 5h14v14H5z" },
  { value: "text", label: "Text", d: "M5 6V4h14v2M12 4v16M9 20h6" }
]

export const ToggleGroupVertical = Html.component({
  name: "ToggleGroupVertical",
  model: Schema.Struct({ tool: Schema.Array(Schema.String) }),
  message: ToggleGroupVerticalMessage
}).make({
  init: () => ({ tool: ["select"] }),
  update: {
    ToggledTool: ($, { value }) => $.evolve({ tool: value })
  },
  view: (h, model) =>
    // A vertical group moves with Down and Up instead of Right and Left.
    ToggleGroup(h, {
      props: { value: model.tool, items: tools.map(({ value }) => ({ value })), orientation: "vertical" },
      onEmit: { Toggled: ({ value }) => ToggleGroupVerticalMessage.ToggledTool({ value }) },
      view: (toggleGroup) =>
        ToggleGroupRoot(h, toggleGroup, { variant: "outline" }).attr("aria-label", "Tool")
          .children(
            tools.map(({ d, label, value }) =>
              ToggleGroupItem(h, toggleGroup, { value }).children(
                h.el("svg")
                  .attrs({
                    viewBox: "0 0 24 24",
                    fill: "none",
                    stroke: "currentColor",
                    "stroke-width": "2",
                    "stroke-linecap": "round",
                    "stroke-linejoin": "round",
                    "aria-hidden": "true"
                  })
                  .children(h.el("path").attr("d", d)),
                label
              )
            )
          )
    })
})
```

### Disabled

One disabled item, and a group that is disabled as a whole.

```ts
import { UiSchema } from "@effect/ui"
import { Html } from "@effect/ui/html"
import { ToggleGroup } from "@effect/ui-kit"
import { Schema } from "effect"
import { ToggleGroupItem, ToggleGroupRoot } from "#ui/toggle-group"

const ToggleGroupDisabledMessage = UiSchema.TaggedEnum({
  ToggledPlan: { value: Schema.Array(Schema.String) },
  ToggledRegion: { value: Schema.Array(Schema.String) }
})

const plans = [
  { value: "monthly", label: "Monthly" },
  { value: "yearly", label: "Yearly" },
  { value: "lifetime", label: "Lifetime", disabled: true }
]

const regions = ["EU", "US", "Asia"]

export const ToggleGroupDisabled = Html.component({
  name: "ToggleGroupDisabled",
  model: Schema.Struct({ plan: Schema.Array(Schema.String), region: Schema.Array(Schema.String) }),
  message: ToggleGroupDisabledMessage
}).make({
  init: () => ({ plan: ["monthly"], region: ["EU"] }),
  update: {
    ToggledPlan: ($, { value }) => $.evolve({ plan: value }),
    ToggledRegion: ($, { value }) => $.evolve({ region: value })
  },
  view: (h, model) =>
    h.div.class("flex flex-col items-center gap-4").children(
      // The arrow keys skip a disabled item.
      ToggleGroup(h, {
        key: "plan",
        props: { value: model.plan, items: plans.map(({ disabled, value }) => ({ value, disabled })) },
        onEmit: { Toggled: ({ value }) => ToggleGroupDisabledMessage.ToggledPlan({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup, { variant: "outline" }).attr("aria-label", "Billing")
            .children(
              plans.map(({ label, value }) =>
                ToggleGroupItem(h, toggleGroup, { value }).children(label)
              )
            )
      }),
      ToggleGroup(h, {
        key: "region",
        props: { value: model.region, items: regions.map((value) => ({ value })), disabled: true },
        onEmit: { Toggled: ({ value }) => ToggleGroupDisabledMessage.ToggledRegion({ value }) },
        view: (toggleGroup) =>
          ToggleGroupRoot(h, toggleGroup, { variant: "outline" }).attr("aria-label", "Region")
            .children(
              regions.map((value) =>
                ToggleGroupItem(h, toggleGroup, { value }).children(value)
              )
            )
      }),
      h.p.class("text-xs text-muted-foreground tabular-nums").children(
        `Billing ${model.plan.join(", ") || "not picked"}. The region group is disabled.`
      )
    )
})
```

## Anatomy

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

| Part | Description |
| --- | --- |
| `root` | A <div> with role="group". Add the items as its children. |
| `item` | item({ element: h.button, value }): one <button> per entry in items. It writes the same attributes as Toggle. |
| `value, disabled, multiple, orientation` | The group's state, for markup that depends on it. |

## API reference

### Props

| Prop | Type | Description |
| --- | --- | --- |
| `value` | `ReadonlyArray<string>` | The values of the pressed items. Required. |
| `items` | `ReadonlyArray<{ value: string; disabled?: boolean }>` | Every item, in the order they are drawn. Required. |
| `disabled` | `boolean` | Disables every item. |
| `multiple` | `boolean` | Lets several items be pressed at once. Off by default. |
| `orientation` | `"horizontal" \| "vertical"` | Which arrow keys move focus. "horizontal" by default. |
| `loopFocus` | `boolean` | The arrow keys wrap from the last item to the first. On by default. |

### Events

| Event | Description |
| --- | --- |
| `Toggled` | { value }: the pressed values the user asked for. Empty when the pressed item was released. |

### Data attributes

| Attribute | Description |
| --- | --- |
| `data-orientation` | On the root: "horizontal" or "vertical". |
| `data-multiple` | On the root when several items can be pressed. |
| `data-disabled` | On the root while the group is disabled, and on each disabled item. |
| `data-pressed` | On each pressed item. |
