# Segmented Control

> Optical-sized segmented track with a sliding raised indicator for exclusive filters, view modes, or route links.

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

## Use when
- Switching between three compact view filters such as 24h, 7d, and 30d without rendering tab panels
- Rendering top-level route links inside a raised-key navigation track with aria-current="page"
- Aligning an exclusive mode toggle beside standard sm, md, or lg buttons

## Avoid when
- Each item swaps a local content panel in the same page; use tabs for full tabpanel ARIA semantics
- Selecting an option inside a submitted HTML form; use toggle-group or radio-group

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

## Props

| Name | Type | Default | Required | Description |
|---|---|---|---|---|
| label | `string` |  | yes | Accessible label applied to the nav or group landmark. |
| items | `{ value: string; label: string; href?: string; disabled?: boolean }[]` |  | yes | Segments rendered as links when href is provided, otherwise exclusive toggle buttons. |
| value | `string` |  | no | Active segment value; defaults to the first enabled item. |
| size | `"sm" \| "md" \| "lg"` | "md" | no | Height and padding matched to Haze button and tab sizes. |
| fullWidth | `boolean` | false | no | Distributes segments equally across the container width. |
| class | `string` |  | no | Extra classes on the outer track. |

## Accessibility
- Uses <nav> with aria-current="page" for linked items and role="group" with aria-pressed for mode buttons.
- Emits a custom haze:segmented-change event carrying { value } when a button segment is activated.
- Places the sliding indicator synchronously on first paint and honors prefers-reduced-motion.
- Key Tab: Move focus between enabled segment links or buttons
- Key Enter / Space: Activate the focused segment

## Agent prompts

### Install and use

Install the Haze UI component "Segmented Control" with `npx shadcn@latest add @haze/segmented-control`. 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 SegmentedControl from "@/components/haze/ui/segmented-control.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/segmented-control.md

### Customize with real content

Adapt the Haze segmented-control ui for our product. Replace the demo values of these props with our real content: label, items, value, size, fullWidth, class. Keep the layout, the heading level rules and these accessibility details: Uses <nav> with aria-current="page" for linked items and role="group" with aria-pressed for mode buttons. Emits a custom haze:segmented-change event carrying { value } when a button segment is activated. Places the sliding indicator synchronously on first paint and honors prefers-reduced-motion. Do not add raw color classes; use the Haze tokens.

### Choose the right block

Before using segmented-control, check it fits: use it when switching between three compact view filters such as 24h, 7d, and 30d without rendering tab panels; rendering top-level route links inside a raised-key navigation track with aria-current="page"; aligning an exclusive mode toggle beside standard sm, md, or lg buttons. Avoid it when each item swaps a local content panel in the same page; use tabs for full tabpanel aria semantics; selecting an option inside a submitted html form; use toggle-group or radio-group. Alternatives: @haze/tabs, @haze/toggle-group, @haze/radio-group.

## Example requests that should lead here
- Add a SegmentedControl above the metrics chart to switch between 24h, 7d, and 30d
- Render Stable, Beta, and Canary channel filters in a small segmented control

## Source

```astro
---
import { cn } from "../../../lib/haze/utils";

interface Segment {
  value: string;
  label: string;
  href?: string;
  disabled?: boolean;
}

interface Props {
  /** Accessible name for the segmented control. */
  label: string;
  items: Segment[];
  /** Currently active item value. Defaults to the first enabled item. */
  value?: string;
  /** Size aligned optically with Haze buttons and tabs. */
  size?: "sm" | "md" | "lg";
  /** Expands segments evenly to fill the container width. */
  fullWidth?: boolean;
  class?: string;
}

const { label, items, value, size = "md", fullWidth = false, class: className } = Astro.props;
const isNav = items.some((item) => Boolean(item.href));
const fallbackValue = items.find((item) => !item.disabled)?.value ?? items[0]?.value;
const activeValue = value ?? fallbackValue;

const sizes = {
  sm: "h-6 px-2 text-xs/4 sm:px-2.5",
  md: "h-8 px-2.5 text-[0.8125rem]/5 sm:px-3",
  lg: "h-9 px-3 text-sm/5 sm:px-3.5",
};
const itemBase =
  "relative inline-flex items-center justify-center rounded-sm border border-transparent font-medium whitespace-nowrap text-muted-foreground select-none transition-[color,scale] duration-150 ease-snappy hover:text-foreground focus-visible:outline-2 focus-visible:-outline-offset-2 focus-visible:outline-ring data-[active]:border-border data-[active]:bg-card data-[active]:text-foreground data-[active]:shadow-key [[data-haze-segmented][data-enhanced]_&]:data-[active]:border-transparent [[data-haze-segmented][data-enhanced]_&]:data-[active]:bg-transparent [[data-haze-segmented][data-enhanced]_&]:data-[active]:shadow-none";
---

{
  isNav ? (
    <nav
      data-haze-segmented
      aria-label={label}
      class={cn(
        "relative isolate inline-flex max-w-full items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden rounded-lg border border-frame bg-muted p-1",
        fullWidth && "w-full",
        className,
      )}
    >
      <span
        data-sc-indicator
        aria-hidden="true"
        class="pointer-events-none absolute top-0 left-0 -z-10 hidden h-(--sc-h) w-(--sc-w) translate-x-(--sc-x) translate-y-(--sc-y) rounded-sm border border-frame bg-background shadow-key [[data-enhanced]_&]:block [[data-ready]_&]:transition-[translate,width] [[data-ready]_&]:duration-200 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none"
      ></span>
      {items.map((item) => {
        const active = item.value === activeValue;
        return (
          <a
            href={item.disabled ? undefined : item.href}
            data-sc-item
            data-value={item.value}
            data-active={active ? "" : undefined}
            aria-current={active ? "page" : undefined}
            aria-disabled={item.disabled ? "true" : undefined}
            class={cn(
              itemBase,
              sizes[size],
              fullWidth ? "min-w-0 flex-1" : "shrink-0",
              item.disabled ? "pointer-events-none opacity-45" : "cursor-pointer active:scale-[0.97] active:duration-75",
            )}
          >
            <span class="truncate">{item.label}</span>
          </a>
        );
      })}
    </nav>
  ) : (
    <div
      data-haze-segmented
      role="group"
      aria-label={label}
      class={cn(
        "relative isolate inline-flex max-w-full items-center gap-1 overflow-x-auto [scrollbar-width:none] [&::-webkit-scrollbar]:hidden rounded-lg border border-frame bg-muted p-1",
        fullWidth && "w-full",
        className,
      )}
    >
      <span
        data-sc-indicator
        aria-hidden="true"
        class="pointer-events-none absolute top-0 left-0 -z-10 hidden h-(--sc-h) w-(--sc-w) translate-x-(--sc-x) translate-y-(--sc-y) rounded-sm border border-frame bg-background shadow-key [[data-enhanced]_&]:block [[data-ready]_&]:transition-[translate,width] [[data-ready]_&]:duration-200 [[data-ready]_&]:ease-snappy motion-reduce:[[data-ready]_&]:transition-none"
      ></span>
      {items.map((item) => {
        const active = item.value === activeValue;
        return (
          <button
            type="button"
            disabled={item.disabled}
            data-sc-item
            data-value={item.value}
            data-active={active ? "" : undefined}
            aria-pressed={active ? "true" : "false"}
            class={cn(
              itemBase,
              sizes[size],
              fullWidth ? "min-w-0 flex-1" : "shrink-0",
              "cursor-pointer active:scale-[0.97] active:duration-75 disabled:pointer-events-none disabled:opacity-45",
            )}
          >
            <span class="truncate">{item.label}</span>
          </button>
        );
      })}
    </div>
  )
}

<script>
  function enhanceSegmentedControls() {
    document.querySelectorAll<HTMLElement>("[data-haze-segmented]:not([data-enhanced])").forEach((root) => {
      const indicator = root.querySelector<HTMLElement>("[data-sc-indicator]");
      const items = Array.from(root.querySelectorAll<HTMLElement>("[data-sc-item]"));
      if (!indicator || items.length === 0) return;

      const place = (slide = false) => {
        const current = items.find((el) => el.hasAttribute("data-active"));
        root.toggleAttribute("data-ready", slide);
        if (!current) {
          indicator.style.visibility = "hidden";
          return;
        }
        indicator.style.visibility = "";
        indicator.style.setProperty("--sc-x", `${current.offsetLeft}px`);
        indicator.style.setProperty("--sc-y", `${current.offsetTop}px`);
        indicator.style.setProperty("--sc-w", `${current.offsetWidth}px`);
        indicator.style.setProperty("--sc-h", `${current.offsetHeight}px`);
      };

      const isNav = root.tagName === "NAV";
      if (!isNav) {
        items.forEach((btn) => {
          btn.addEventListener("click", () => {
            if (btn.hasAttribute("disabled")) return;
            items.forEach((other) => {
              const on = other === btn;
              other.toggleAttribute("data-active", on);
              other.setAttribute("aria-pressed", String(on));
            });
            place(true);
            root.dispatchEvent(new CustomEvent("haze:segmented-change", { detail: { value: btn.dataset.value }, bubbles: true }));
          });
        });
      }

      root.setAttribute("data-enhanced", "");
      place(false);
      if ("ResizeObserver" in window) {
        const ro = new ResizeObserver(() => requestAnimationFrame(() => place(false)));
        ro.observe(root);
        items.forEach((el) => ro.observe(el));
      }
      window.addEventListener("resize", () => requestAnimationFrame(() => place(false)), { passive: true });
      document.fonts?.ready.then(() => { if (root.isConnected) place(false); });
    });
  }

  enhanceSegmentedControls();
  if (!document.documentElement.hasAttribute("data-haze-segmented-listener")) {
    document.documentElement.setAttribute("data-haze-segmented-listener", "");
    document.addEventListener("astro:page-load", enhanceSegmentedControls);
  }
</script>
```
