# Button group

> Related actions share joined borders, or sit in a sunken track where a raised key slides to the pressed button.

- Kind: ui · Category: Actions · Interactivity: script
- Install: `npx shadcn@latest add @haze/button-group`
- File: `src/components/haze/ui/button-group.astro`
- npm dependencies: none
- Registry dependencies: @haze/utils
- Docs page: https://hazeui.com/ui/button-group

## Use when
- Related actions that read as one control, such as Day, Week and Month
- A split of a primary action and a secondary one that belong together
- A small cluster of outline buttons that should share borders

## Avoid when
- Choosing one option from a set that stays selected; toggle-group tracks pressed state
- Unrelated actions, which need their own spacing and visual weight
- More than about five buttons, which wrap badly on narrow screens

## Alternatives
- [button](https://hazeui.com/ui/button.md)
- [toggle-group](https://hazeui.com/ui/toggle-group.md)
- [tabs](https://hazeui.com/ui/tabs.md)

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` |  | yes | Accessible name of the group, set as aria-label on the role="group" wrapper. |
| orientation | `"horizontal" \| "vertical"` | "horizontal" | no | Row or column. The outer corners stay round, inner corners go square and borders overlap by 1 px. |
| variant | `"joined" \| "segmented"` | "joined" | no | Joined shares borders between outline buttons. Segmented is a sunken track of ghost buttons; a raised key slides to the child with aria-pressed="true", which your own script toggles. |
| class | `string` |  | no | Extra classes on the wrapper. |
| default slot | `slot` |  | yes | Button components; the outline variant looks best because it has a border to share. |

## Accessibility
- role="group" with a required label tells a screen reader that the buttons belong together, for example "Time range, group".
- A focused or hovered button is raised with z-10 so its ring and border are not covered by the neighbor that overlaps it by 1 px.
- Buttons in the group do not shrink when pressed, so the joined edges stay aligned.
- The group sets no pressed state itself; for a single choice that manages its own state, use toggle-group or segmented-control.
- In the segmented variant the sliding key is decorative; the state is the aria-pressed attribute on each button, which your script must keep in sync, and the key follows it.
- Every action keeps its native activation and tab stop; the key never takes pointer events.
- Key Tab: Each button in the group is its own tab stop; Enter or Space activates the focused one

## Agent prompts

### Install and use

Install the Haze UI component "Button group" with `npx shadcn@latest add @haze/button-group`. If components.json has no "@haze" registry yet, add "registries": { "@haze": "https://hazeui.com/r/{name}.json" }. If src/styles/haze.css does not exist yet, run `npx shadcn@latest add @haze/theme` once and import it from the global stylesheet after Tailwind. The CLI stops at an overwrite question when a Haze file already exists and differs, even with --yes, and then installs nothing after it: read its output. If the user has not edited their Haze files, re-run with --overwrite to take the registry versions; if they have, ask them before overwriting. Then import ButtonGroup from "@/components/haze/ui/button-group.astro" (or the relative path) and render it where it fits the page. Keep Haze token classes (bg-background, text-muted-foreground, border-border...) and never hardcode colors. Docs: https://hazeui.com/ui/button-group.md

### Customize with real content

Adapt the Haze button-group ui for our product. Replace the demo values of these props with our real content: label, orientation, variant, class, default slot. Keep the layout, the heading level rules and these accessibility details: role="group" with a required label tells a screen reader that the buttons belong together, for example "Time range, group". A focused or hovered button is raised with z-10 so its ring and border are not covered by the neighbor that overlaps it by 1 px. Buttons in the group do not shrink when pressed, so the joined edges stay aligned. The group sets no pressed state itself; for a single choice that manages its own state, use toggle-group or segmented-control. In the segmented variant the sliding key is decorative; the state is the aria-pressed attribute on each button, which your script must keep in sync, and the key follows it. Every action keeps its native activation and tab stop; the key never takes pointer events. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using button-group, check it fits: use it when related actions that read as one control, such as day, week and month; a split of a primary action and a secondary one that belong together; a small cluster of outline buttons that should share borders. Avoid it when choosing one option from a set that stays selected; toggle-group tracks pressed state; unrelated actions, which need their own spacing and visual weight; more than about five buttons, which wrap badly on narrow screens. Alternatives: @haze/button, @haze/toggle-group, @haze/tabs.

## Example requests that should lead here
- Group Day, Week and Month into one segmented control
- Stack Zoom in and Zoom out as a vertical button group

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Props {
  /** Accessible name of the group, for example "Text alignment". */
  label: string;
  /** Row or column. Only the outer corners stay round, and the buttons overlap by 1 px. */
  orientation?: "horizontal" | "vertical";
  /** "joined" shares borders between outline buttons. "segmented" is a sunken track with a raised key that slides to the button marked aria-pressed="true". */
  variant?: "joined" | "segmented";
  class?: string;
}

const { label, orientation = "horizontal", variant = "joined", class: className } = Astro.props;
// Each class is a whole literal string. Joined: the group owns the key shadow; children give up their own. Segmented: a sunken track, flat buttons and one sliding raised key.
const orientations = {
  horizontal:
    "flex-row [&>*:first-child]:rounded-l-lg [&>*:last-child]:rounded-r-lg [&>*:not(:first-child)]:-ml-px",
  vertical:
    "flex-col [&>*:first-child]:rounded-t-lg [&>*:last-child]:rounded-b-lg [&>*:not(:first-child)]:-mt-px",
};
const segmented =
  "flex-row gap-1 rounded-lg border border-frame bg-muted p-1 [&>*]:rounded-sm [&>[aria-pressed=true]]:text-foreground [&>[aria-pressed=true]:hover]:bg-transparent [&:not([data-enhanced])>[aria-pressed=true]]:border-frame [&:not([data-enhanced])>[aria-pressed=true]]:bg-background [&:not([data-enhanced])>[aria-pressed=true]]:shadow-key before:pointer-events-none before:absolute before:top-0 before:left-0 before:-z-10 before:h-(--group-h) before:w-(--group-w) before:translate-x-(--group-x) before:translate-y-(--group-y) before:rounded-sm before:border before:border-frame before:bg-background before:shadow-key before:opacity-0 before:content-[''] data-[active]:before:opacity-100 data-[moving]:before:transition-[translate,width,height,opacity] data-[moving]:before:duration-200 data-[moving]:before:ease-snappy motion-reduce:data-[moving]:before:transition-none";
---

<div
  data-haze-button-group
  data-variant={variant}
  role="group"
  aria-label={label}
  class={cn(
    "relative isolate inline-flex w-fit max-w-full rounded-lg [&>*]:relative [&>*]:shadow-none [&>*]:active:scale-100 [&>*:hover]:z-10 [&>*:focus-visible]:z-10",
    variant === "segmented" ? segmented : cn("[&>*]:rounded-none", orientations[orientation]),
    className,
  )}
>
  <slot />
</div>

<script>
  function initButtonGroups() {
    document.querySelectorAll<HTMLElement>("[data-haze-button-group]").forEach(root => {
      if (root.hasAttribute("data-enhanced")) return;
      root.setAttribute("data-enhanced", "");
      if (root.dataset.variant !== "segmented") return;
      let placed = false;
      const place = (slide: boolean) => {
        const item = Array.from(root.children).find((child): child is HTMLElement => child instanceof HTMLElement && child.getAttribute("aria-pressed") === "true");
        root.toggleAttribute("data-active", Boolean(item));
        root.toggleAttribute("data-moving", placed && slide);
        if (!item) return;
        root.style.setProperty("--group-x", `${item.offsetLeft}px`);
        root.style.setProperty("--group-y", `${item.offsetTop}px`);
        root.style.setProperty("--group-w", `${item.offsetWidth}px`);
        root.style.setProperty("--group-h", `${item.offsetHeight}px`);
        placed = true;
      };
      place(false);
      new MutationObserver(() => place(true)).observe(root, { attributes: true, attributeFilter: ["aria-pressed"], subtree: true });
      if ("ResizeObserver" in window) new ResizeObserver(() => place(false)).observe(root);
      document.fonts?.ready.then(() => { if (root.isConnected) place(false); });
    });
  }
  initButtonGroups();
  if (!document.documentElement.hasAttribute("data-haze-button-group-listener")) {
    document.documentElement.setAttribute("data-haze-button-group-listener", "");
    document.addEventListener("astro:page-load", initButtonGroups);
  }
</script>
```
