# Toggle Group

> Buttons that stay pressed and share one value, such as text styles.

Page: https://uicontext.com/docs/components/toggle-group

Group: Primitives.

## When to use

Buttons that stay pressed and share one value, such as text styles. Use [Segmented Control](https://uicontext.com/docs/components/segmented-control.md) instead when exactly one choice is on and the row reads as a single control.

## Usage

```ts
import { ToggleGroup } from "./ui/uicontext/components/ToggleGroup.ts"

const Message = UiSchema.TaggedEnum({ ChangedMarks: { marks: Schema.Array(Schema.String) } })

export const Marks = (h: Html.H<typeof Message.Type>, marks: ReadonlyArray<string>) =>
	ToggleGroup(h, {
		label: "Text style",
		multiple: true,
		value: marks,
		items: [
			{ value: "bold", label: "Bold", shortcut: "mod+b" },
			{ value: "italic", label: "Italic", shortcut: "mod+i" },
		],
		onChange: (next) => Message.ChangedMarks({ marks: next }),
	})
```

## Examples

Each example is a complete file. Its imports point where the CLI installs the source.

### Text toolbar

The example the page opens with: Toggle Group in “Text toolbar”.

```ts title="src/demo.ts" source="www/src/examples/toggle-group/demo.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { mirrorInRtl } from "./ui/uicontext/components/Direction.ts"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { ToggleGroup } from "./ui/uicontext/components/ToggleGroup.ts"
import { space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	bar: { display: "flex", flexWrap: "wrap", alignItems: "center", gap: space.sm },
	icon: { inlineSize: 16, blockSize: 16 },
})

// alignment icons point along the line, so they flip in right-to-left text
const icon = <M>(h: Html.H<M>, d: string, mirror = false) =>
	h.svg.attrs({ viewBox: "0 0 16 16", fill: "none", stroke: "currentColor", "stroke-width": "1.6", "stroke-linecap": "round", "stroke-linejoin": "round", ...sx(styles.icon, mirror && mirrorInRtl) }).children(h.path.attr("d", d))

const marks = [
	{ value: "bold", label: "Bold", shortcut: "mod+b", d: "M4.5 3h4.25a2.5 2.5 0 0 1 0 5H4.5zM4.5 8h5a2.5 2.5 0 0 1 0 5h-5z" },
	{ value: "italic", label: "Italic", shortcut: "mod+i", d: "M10 3H6.5M9.5 13H6M8.75 3l-1.5 10" },
	{ value: "underline", label: "Underline", shortcut: "mod+u", d: "M4.5 3v4.5a3.5 3.5 0 0 0 7 0V3M3.5 13.5h9" },
	{ value: "strike", label: "Strikethrough", shortcut: "mod+shift+x", d: "M3 8h10M10.5 4.5C10 3.6 9.1 3 8 3 6.5 3 5.25 3.9 5.25 5.25 5.25 6.5 6.25 7.1 8 8c1.75.9 2.75 1.5 2.75 2.75C10.75 12.1 9.5 13 8 13c-1.25 0-2.25-.6-2.75-1.5" },
]

const alignments = [
	{ value: "start", label: "Align start", d: "M3 4h10M3 8h6M3 12h8" },
	{ value: "center", label: "Align center", d: "M3 4h10M5 8h6M4 12h8" },
	{ value: "end", label: "Align end", d: "M3 4h10M7 8h6M5 12h8" },
]

const Message = UiSchema.TaggedEnum({
	ChangedMarks: { marks: Schema.Array(Schema.String) },
	ChangedAlign: { align: Schema.Array(Schema.String) },
})

// a text toolbar: any marks at once, and one alignment at a time
export const TextToolbar = Html.component({
	name: "TextToolbar",
	model: Schema.Struct({ marks: Schema.Array(Schema.String), align: Schema.Array(Schema.String) }),
	message: Message,
}).make({
	init: () => ({ marks: ["bold"], align: ["start"] }),
	update: {
		ChangedMarks: ($, { marks }) => $.evolve({ marks }),
		// alignment always has one: pressing the current one again keeps it
		ChangedAlign: ($, { align }) => (align.length === 0 ? $.model : $.evolve({ align })),
	},
	view: (h, model) =>
		h.div.attrs(sx(styles.bar)).children(
			ToggleGroup(h, {
				key: "marks",
				label: "Text style",
				multiple: true,
				iconOnly: true,
				value: model.marks,
				items: marks.map((m) => ({ value: m.value, label: m.label, shortcut: m.shortcut, icon: icon(h, m.d) })),
				onChange: (next) => Message.ChangedMarks({ marks: next }),
			}),
			ToggleGroup(h, {
				key: "align",
				label: "Alignment",
				iconOnly: true,
				value: model.align,
				items: alignments.map((a) => ({ value: a.value, label: a.label, icon: icon(h, a.d, true) })),
				onChange: (next) => Message.ChangedAlign({ align: next }),
			}),
		),
})
```

### Labels, several on

Without icons each button shows its label. A disabled one stays in place but can't be pressed.

```ts title="src/columns.ts" source="www/src/examples/toggle-group/columns.ts"
import { UiSchema } from "effect/ui"
import { Html } from "effect/ui/html"
import * as stylex from "@stylexjs/stylex"
import { Schema } from "effect"
import { sx } from "./ui/uicontext/components/Sx.ts"
import { ToggleGroup } from "./ui/uicontext/components/ToggleGroup.ts"
import { color, font, space } from "./ui/uicontext/components/tokens.stylex.ts"

const styles = stylex.create({
	wrap: { display: "grid", gap: space.sm, justifyItems: "start", maxInlineSize: "100%" },
	label: { fontSize: font.sm, fontWeight: 500, color: color.fg },
	note: { margin: 0, fontSize: font.sm, color: color.muted },
})

const channels = [
	{ value: "organic", label: "Organic search" },
	{ value: "paid", label: "Paid" },
	{ value: "email", label: "Email" },
	{ value: "referral", label: "Referral" },
	{ value: "social", label: "Social", disabled: true },
]

const Message = UiSchema.TaggedEnum({ ChangedChannels: { channels: Schema.Array(Schema.String) } })

// which channels a traffic report shows: several at once, and Social isn't connected yet
export const ReportChannels = Html.component({
	name: "ReportChannels",
	model: Schema.Struct({ channels: Schema.Array(Schema.String) }),
	message: Message,
}).make({
	init: () => ({ channels: ["organic", "paid", "email"] }),
	update: { ChangedChannels: ($, { channels: next }) => $.evolve({ channels: next }) },
	view: (h, model) =>
		h.div.attrs(sx(styles.wrap)).children(
			h.span.attrs({ "aria-hidden": "true", ...sx(styles.label) }).children("Channels"),
			ToggleGroup(h, {
				label: "Channels",
				multiple: true,
				value: model.channels,
				items: channels,
				onChange: (next) => Message.ChangedChannels({ channels: next }),
			}),
			h.p.attrs(sx(styles.note)).children(model.channels.length === 0 ? "Pick a channel to see its traffic." : `Showing ${new Intl.ListFormat("en", { type: "conjunction" }).format(model.channels.map((c) => channels.find((x) => x.value === c)?.label ?? c))}.`),
		),
})
```

## API reference

**Options**

| Name | Type | Description |
| --- | --- | --- |
| `key` | `string` | Names the group among others in the same view; needed for more than one. |
| `label` (required) | `string` | The group's accessible name: "Text style", "Columns". |
| `items` (required) | `ToggleGroupItem<Message>[]` | — |
| `value` (required) | `string[]` | The pressed items' values. The caller keeps them. |
| `onChange` (required) | `(value: string[]) => Message` | What a press asks for: the values to store and pass back as `value`. |
| `multiple` | `boolean` | Any number on at once; at most one by default. |
| `iconOnly` | `boolean` | Icons alone, each named by its label: an editor's toolbar. |
| `bare` | `boolean` | No frame around the buttons, for a group inside a toolbar that has one. |
| `orientation` | `"horizontal" \| "vertical"` | — |
| `disabled` | `boolean` | — |
| `style` | `Style` | StyleX styles applied after the group's own. |

## Keyboard and accessibility

### Keys

| Keys | Does |
| --- | --- |
| Right arrow, Left arrow | Move to the next or the previous button |
| Home, End | Go to the first or the last button |
| Space, Enter | Press or release the button |

On a Mac, Control is Command and Alt is Option. Left and Right trade places in right-to-left text.

## Installation

```sh
pnpm dlx shadcn@latest add checkfu/uicontext/toggle-group
```

With npm: `npx shadcn@latest add checkfu/uicontext/toggle-group`. With yarn: `yarn dlx shadcn@latest add checkfu/uicontext/toggle-group`. With bun: `bunx --bun shadcn@latest add checkfu/uicontext/toggle-group`.

It writes these files:

- `src/ui/uicontext/components/Direction.ts`
- `src/ui/uicontext/components/IconStroke.ts`
- `src/ui/uicontext/components/InlineNotice.ts`
- `src/ui/uicontext/components/Kbd.ts`
- `src/ui/uicontext/components/Sx.ts`
- `src/ui/uicontext/components/ToggleGroup.ts`
- `src/ui/uicontext/components/tokens.stylex.ts`
- `src/ui/uicontext/components/touch.stylex.ts`

And installs the npm packages `@stylexjs/stylex`, `effect`.

## Source

- [src/ToggleGroup.ts](https://github.com/checkfu/uicontext/blob/main/src/ToggleGroup.ts)

## Related

- [Button](https://uicontext.com/docs/components/button.md) (`button`): A button, and a link that looks like one, in every tone and three sizes.
- [Toggle](https://uicontext.com/docs/components/toggle.md) (`toggle`): A button that stays pressed, such as Bold or Pin.
- [Input](https://uicontext.com/docs/components/input.md) (`input`): Text inputs, selects and textareas in a labeled field with a hint and an error, and their styles for controls you lay out yourself.
- [Status](https://uicontext.com/docs/components/status.md) (`status`): Status badges and tags for runs and records.
- [Glyphs](https://uicontext.com/docs/components/glyphs.md) (`glyphs`): Small marks for status, priority, color and people.
- [Action Toolbar](https://uicontext.com/docs/components/action-toolbar.md) (`action-toolbar`): A row of grouped buttons with one Tab stop, such as formatting toggles or bulk actions.
