# Toggle group (Notchset): prompt.md (v1.0.0)

- id: `toggle-group` · version 1.0.0 · component · free
- category: Buttons
- build: one set of files for every shadcn style
- install: `npx shadcn@latest add https://notchset.dev/r/toggle-group.json`
- npm dependencies: none
- registry dependencies: utils, https://notchset.dev/r/notchset-foundation.json, @notchset/keyboard-hint, @notchset/toolbar
- docs: https://notchset.dev/components/toggle-group
- The install command carries everything this item needs (files, CSS, tokens, npm and registry dependencies). Prefer it to copying source by hand.

A bar of 32px keys for formatting: independent toggles (bold, italic, a highlight) that sink while on, and one exclusive set (alignment) where one key is sunk at a time. The bar is one tab stop; the arrows roam every key, Space presses. Sunk keys side by side join into one well. It is Toolbar's radiogroup form..

## Build it
- Stack: React 18.3 or 19, TypeScript, Tailwind CSS v4 utility classes on the foundation's roles, a components.json (imports use its aliases).
- Packages: none beyond `react` and `react-dom`.
- Files: `components/ui/notchset/toggle-group.tsx`; shared code: `lib/notchset/controllable.ts`.
- Registry dependencies, installed with it automatically: shadcn `utils` (cn), `notchset-foundation`, `keyboard-hint`, `toolbar`.
- Builds: one set of files, the same for every shadcn style.
- Exports to keep: `ToggleGroup`, and every exported type.
- CSS: the install adds the notchset foundation (its roles, keyframes and motion switch, reading your shadcn tokens for colour) to your global stylesheet once. Nothing to import by hand.
- Re-running `add` (or `--overwrite`) re-applies those rules: put overrides in your own CSS, never in the installed rules.
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Retune it (on any ancestor) with the foundation's roles and hooks: `--ns-agent-b`, `--ns-agent-c`, `--ns-agent-d`, `--ns-agent-drift`, `--ns-agent-fill`, `--ns-agent-h1`, `--ns-agent-h2`, `--ns-agent-h3`, `--ns-agent-shift`, `--ns-avatar-card`, `--ns-avatar-lg`, `--ns-avatar-md`, `--ns-avatar-sm`, `--ns-avatar-xs`, `--ns-bad`, `--ns-bad-ink`, `--ns-band`, `--ns-band-edge`, `--ns-band-grade`, `--ns-band-optimal`, `--ns-banner-beat`, `--ns-banner-radius`, `--ns-beat`, `--ns-beat-ease`, `--ns-bezel`, `--ns-bloom-close`, `--ns-bloom-open`, `--ns-bloom-rise`, `--ns-btn-bad`, `--ns-btn-bad-hover`, `--ns-btn-bad-line`, `--ns-btn-bezel`, `--ns-btn-chosen`, `--ns-btn-gone`, `--ns-btn-morph`, `--ns-btn-ok`, `--ns-btn-press`, `--ns-btn-release`, `--ns-btn-result`, `--ns-btn-roll`, `--ns-btn-stagger`, `--ns-btn-stagger-step`, `--ns-btn-tick`, `--ns-btn-tonal`, `--ns-btn-tonal-edge`, `--ns-btn-tonal-hover`, `--ns-bulk-clear`, `--ns-button`, `--ns-button-field-inset`, `--ns-button-lg`, `--ns-button-sm`, `--ns-canvas`, `--ns-card-tilt`, `--ns-cat-1`, `--ns-cat-2`, `--ns-cat-3`, `--ns-cat-4`, `--ns-cat-5`, `--ns-cat-6`, `--ns-check`, `--ns-check-round`, `--ns-cheer-1`, `--ns-cheer-2`, `--ns-cheer-3`, `--ns-cheer-edge`, `--ns-cheer-fold`, `--ns-cheer-glow`, `--ns-cheer-lift`, `--ns-chip`, `--ns-chip-pick`, `--ns-control`, `--ns-control-lg`, `--ns-control-pad`, `--ns-control-sm`, `--ns-corner`, `--ns-danger`, `--ns-deep`, `--ns-deep-ink`, `--ns-deep-ink-2`, `--ns-deep-line`, `--ns-depth-card`, `--ns-depth-lift`, `--ns-depth-surface`, `--ns-dialog`, `--ns-dialog-grow`, `--ns-dialog-lg`, `--ns-dialog-max`, `--ns-dialog-shrink`, `--ns-dialog-sm`, `--ns-dialog-top`, `--ns-dock-bottom`, `--ns-drop`, `--ns-ease`, `--ns-ease-arrive`, `--ns-ease-breathe`, `--ns-ease-drum`, `--ns-ease-exit`, `--ns-ease-fling`, `--ns-ease-glide`, `--ns-ease-grow`, `--ns-ease-move`, `--ns-ease-panel`, `--ns-ease-pop`, `--ns-ease-press`, `--ns-ease-spring`, `--ns-ebg-arm`, `--ns-ebg-lit`, `--ns-emoji`, `--ns-emoji-md`, `--ns-emoji-sm`, `--ns-field`, `--ns-field-edge`, `--ns-field-h`, `--ns-fill`, `--ns-fill-time`, `--ns-flood-arc`, `--ns-flood-aurora`, `--ns-flood-behind-1`, `--ns-flood-behind-2`, `--ns-flood-bloom`, `--ns-flood-deep`, `--ns-flood-dial-bloom`, `--ns-flood-glass`, `--ns-flood-grain`, `--ns-flood-image`, `--ns-flood-ink`, `--ns-flood-ink-low`, `--ns-flood-light`, `--ns-flood-mid`, `--ns-flood-pale`, `--ns-flood-pane`, `--ns-flood-pane-edge`, `--ns-flood-pill-ink`, `--ns-flood-ribbon`, `--ns-flood-ribbon-core`, `--ns-flood-shadow`, `--ns-flood-sheen`, `--ns-flood-wash`, `--ns-font-body`, `--ns-font-display`, `--ns-font-mono`, `--ns-font-script`, `--ns-glass`, `--ns-glass-blur`, `--ns-glass-shadow`, `--ns-glow`, `--ns-glyph-pad`, `--ns-grain`, `--ns-gutter`, `--ns-header`, `--ns-help-max`, `--ns-hit`, `--ns-hover`, `--ns-icon`, `--ns-icon-lg`, `--ns-icon-sm`, `--ns-icon-stroke`, `--ns-info`, `--ns-info-ink`, `--ns-ink`, `--ns-ink-2`, `--ns-ink-3`, `--ns-ink-4`, `--ns-layer-bar`, `--ns-layer-modal`, `--ns-layer-panel`, `--ns-layer-popup`, `--ns-layer-sticky`, `--ns-layer-tip`, `--ns-layer-toast`, `--ns-layer-zoom`, `--ns-lead-body`, `--ns-lead-figure`, `--ns-lead-large`, `--ns-lead-meta`, `--ns-lead-small`, `--ns-lead-sub`, `--ns-lead-title`, `--ns-leading`, `--ns-leading-prose`, `--ns-leading-title`, `--ns-lift`, `--ns-light-1`, `--ns-light-2`, `--ns-light-3`, `--ns-light-spread`, `--ns-light-strength`, `--ns-line`, `--ns-line-soft`, `--ns-lit-edge`, `--ns-map-grass`, `--ns-map-water`, `--ns-mark-edge`, `--ns-mark-lifted`, `--ns-mark-rest`, `--ns-mark-swap`, `--ns-marker`, `--ns-marker-ink`, `--ns-mc-place`, `--ns-mc-roll`, `--ns-measure`, `--ns-menu-dy`, `--ns-menu-lit`, `--ns-menu-pad`, `--ns-menu-row`, `--ns-menu-rule`, `--ns-mesh`, `--ns-mesh-frost`, `--ns-nest-inset`, `--ns-nest-outer`, `--ns-nest-r`, `--ns-notch-ease`, `--ns-ok`, `--ns-ok-ink`, `--ns-on-fill`, `--ns-orb-body`, `--ns-orb-cool`, `--ns-orb-core`, `--ns-orb-dawn`, `--ns-orb-deep`, `--ns-orb-edge`, `--ns-orb-grain`, `--ns-orb-ground`, `--ns-orb-halo`, `--ns-orb-inner`, `--ns-orb-key`, `--ns-orb-lift`, `--ns-orb-limb`, `--ns-orb-limb-from`, `--ns-orb-rim`, `--ns-orb-skin-hi`, `--ns-orb-skin-lo`, `--ns-orb-skin-mid`, `--ns-orb-warm`, `--ns-palette-min`, `--ns-panel`, `--ns-panel-room`, `--ns-panel-w`, `--ns-panel-w-lg`, `--ns-pick-slot`, `--ns-pill-prop`, `--ns-play-fill`, `--ns-play-fill-color`, `--ns-play-lift`, `--ns-play-lift-y`, `--ns-play-open`, `--ns-play-open-content`, `--ns-play-press`, `--ns-play-press-box`, `--ns-play-reduced`, `--ns-play-ring`, `--ns-play-roll`, `--ns-play-shake`, `--ns-play-spring`, `--ns-play-swap`, `--ns-play-swap-blur`, `--ns-press-min`, `--ns-press-scale`, `--ns-press-x`, `--ns-press-y`, `--ns-primary-hover`, `--ns-primary-press`, `--ns-prism-edge`, `--ns-prism-glint`, `--ns-prism-sheen`, `--ns-prism-tint`, `--ns-pulse`, `--ns-radius`, `--ns-radius-2xl`, `--ns-radius-button`, `--ns-radius-button-lg`, `--ns-radius-button-sm`, `--ns-radius-card`, `--ns-radius-check`, `--ns-radius-control`, `--ns-radius-control-sm`, `--ns-radius-float`, `--ns-radius-full`, `--ns-radius-lg`, `--ns-radius-mark`, `--ns-radius-menu-row`, `--ns-radius-modal`, `--ns-radius-pill`, `--ns-radius-sm`, `--ns-radius-xl`, `--ns-radius-xs`, `--ns-raised`, `--ns-ramp-1`, `--ns-ramp-2`, `--ns-ramp-3`, `--ns-ramp-4`, `--ns-ramp-5`, `--ns-ramp-shine`, `--ns-range`, `--ns-rest-1`, `--ns-rest-2`, `--ns-rest-3`, `--ns-rise`, `--ns-row`, `--ns-row-compact`, `--ns-row-hue`, `--ns-scrim`, `--ns-search-h`, `--ns-segment`, `--ns-segment-inset`, `--ns-segment-lift`, `--ns-segment-sm`, `--ns-selected`, `--ns-series`, `--ns-series-core`, `--ns-series-glint`, `--ns-series-tint`, `--ns-shadow-dialog`, `--ns-shadow-float`, `--ns-shadow-lift`, `--ns-shadow-panel`, `--ns-sheet`, `--ns-sheet-back`, `--ns-sheet-bottom`, `--ns-sheet-drop`, `--ns-sheet-rise`, `--ns-shift`, `--ns-side`, `--ns-signal`, `--ns-signal-ink`, `--ns-signal-wash`, `--ns-sk-figure`, `--ns-sk-land`, `--ns-sk-p`, `--ns-sk-p0`, `--ns-sk-p1`, `--ns-sk-p2`, `--ns-sk-p3`, `--ns-sk-p4`, `--ns-sk-p5`, `--ns-sk-p6`, `--ns-sk-p7`, `--ns-sk-read`, `--ns-sk-sweep`, `--ns-skeleton`, `--ns-skeleton-bone`, `--ns-skeleton-bone-light`, `--ns-skeleton-light`, `--ns-slab`, `--ns-slab-edge`, `--ns-slab-ink`, `--ns-sleep-awake`, `--ns-sleep-deep`, `--ns-sleep-light`, `--ns-sleep-rem`, `--ns-space-1`, `--ns-space-2`, `--ns-space-3`, `--ns-space-4`, `--ns-space-5`, `--ns-space-6`, `--ns-space-8`, `--ns-space-section`, `--ns-stack-fan`, `--ns-stack-fan-gap`, `--ns-stack-fan-lag`, `--ns-stack-on`, `--ns-stagger-item`, `--ns-stagger-mark`, `--ns-stagger-max`, `--ns-standing-critical`, `--ns-standing-in`, `--ns-standing-out`, `--ns-state-doing`, `--ns-state-done`, `--ns-state-review`, `--ns-state-todo`, `--ns-step`, `--ns-step-from`, `--ns-step-sign`, `--ns-swipe-surface`, `--ns-switch-h`, `--ns-switch-w`, `--ns-text-body`, `--ns-text-control`, `--ns-text-control-lg`, `--ns-text-display`, `--ns-text-editorial`, `--ns-text-empty`, `--ns-text-figure`, `--ns-text-giant`, `--ns-text-heading`, `--ns-text-headline`, `--ns-text-input`, `--ns-text-large`, `--ns-text-lede`, `--ns-text-meta`, `--ns-text-record`, `--ns-text-sentence`, `--ns-text-small`, `--ns-text-sub`, `--ns-text-title`, `--ns-theme-fade`, `--ns-tile-shadow`, `--ns-time-born`, `--ns-time-color`, `--ns-time-confirm`, `--ns-time-dialog`, `--ns-time-fling`, `--ns-time-flip`, `--ns-time-glide`, `--ns-time-grow`, `--ns-time-hold`, `--ns-time-menu`, `--ns-time-page`, `--ns-time-panel`, `--ns-time-quick`, `--ns-time-roll`, `--ns-time-settle`, `--ns-time-snap`, `--ns-time-spin`, `--ns-time-spring`, `--ns-time-sweep`, `--ns-time-toast`, `--ns-tint`, `--ns-tint-c`, `--ns-tint-ease`, `--ns-tint-fill`, `--ns-tint-gap`, `--ns-tint-h1`, `--ns-tint-h2`, `--ns-tint-h3`, `--ns-tint-ink`, `--ns-tint-row`, `--ns-tip-fold`, `--ns-tip-grow`, `--ns-toast-bottom`, `--ns-toast-gap`, `--ns-toast-left`, `--ns-toast-lift`, `--ns-toast-peek`, `--ns-toast-scale`, `--ns-toast-w`, `--ns-touch`, `--ns-tracking-body`, `--ns-tracking-caps`, `--ns-tracking-control`, `--ns-tracking-display`, `--ns-tracking-headline`, `--ns-tracking-sub`, `--ns-tracking-title`, `--ns-warn`, `--ns-warn-ink`, `--ns-wash-clay`, `--ns-wash-dusk`, `--ns-wash-graphite`, `--ns-wash-ink`, `--ns-wash-sage`, `--ns-wash-sand`, `--ns-weight-light`, `--ns-weight-medium`, `--ns-weight-regular`, `--ns-weight-strong`, `--ns-well`, `--ns-width-lg`, `--ns-width-md`, `--ns-width-sm`, `--ns-width-xl`.
- Never add Tailwind colour classes inside the component.

```tsx
import { ToggleGroup } from "@/components/ui/notchset/toggle-group";
```

## Parts
- A single export that takes props.

## Match the original
- Read `components/ui/notchset/toggle-group.tsx` as the reference implementation before changing or recreating anything, and match it: sizes, colours per theme, motion timings, copy and behaviour.
- If you deviate (a prop you can't honour, a style you changed, a dependency you swapped), say so in your reply, part by part.
- Keep the accessibility contract, the keyboard map and the motion levels listed below.

## Use it when
- Formatting where some keys are on or off and one set is exclusive.

### Not when
- Actions that do not stay on are a Toolbar of Buttons; a choice of views is Segmented control.

## Built from
- keyboard-hint (`keyboard-hint`), installed with it: reuse it, don't rebuild it
- toolbar (`toolbar`), installed with it: reuse it, don't rebuild it
- Controllable (shared helper, ships with it)

## Mistakes
- Two exclusive sets in one bar without a name each
- Using colour as the on state: the state is depth

## Usage

```tsx
"use client";
import * as React from "react";
import { cn } from "@/lib/utils";
import { AlignCenter, AlignLeft, AlignRight, Bold, Highlighter, Italic } from "@/lib/notchset/icons";
import { EASE, useLessMotion } from "@/lib/notchset/motion";
import { ToggleGroup } from "@/components/ui/notchset/toggle-group";
import { ToolbarKey } from "@/components/ui/notchset/toolbar";
import { pressIn, useSelfPlay } from "./self-play";

/*
 * A format bar over one plain paragraph about writing. On view "why it matters" stands selected and the highlight
 * sweeps once over it, left to right, one band under its words on every line, and the Highlight key sinks. Then the hand
 * drives it: the bar acts on exactly the words the visitor selects (Bold, Italic, Highlight, ⌘B / ⌘I), and on nothing
 * when nothing is selected, which it says quietly. One tab stop; the arrows roam every key and Space presses. Two
 * neighbouring keys on at once join into one well.
 */
export const NOTE = "A good note says what changed, why it matters and what happens next, in that order, in as few words as it can.";
type Mark = "b" | "i" | "hl";
export type Marks = Record<Mark, boolean[]>;
export type Span = { start: number; end: number };
type Align = "left" | "center" | "right";
const SCRIPTED: Span = { start: NOTE.indexOf("why it matters"), end: NOTE.indexOf("why it matters") + "why it matters".length };
const SWEEP_MS = 520; /* --ns-time-sweep */

export const blank = (n = NOTE.length): Marks => ({ b: Array(n).fill(false), i: Array(n).fill(false), hl: Array(n).fill(false) });
/** true when every character of the span carries the mark (an empty span carries none) */
export const covers = (marks: Marks, k: Mark, s: Span | null) => !!s && s.end > s.start && marks[k].slice(s.start, s.end).every(Boolean);
/** a key press on a span: all marked -> unmark it; else mark all of it. Exactly the span, nothing else. */
export function flipSpan(marks: Marks, k: Mark, s: Span): Marks {
  const on = !covers(marks, k, s);
  return { ...marks, [k]: marks[k].map((v, i) => (i >= s.start && i < s.end ? on : v)) };
}
/** runs of the note that share their marks, cut at every word / space edge so a run never wraps */
export function runs(text: string, marks: Marks, tint: Span | null): Span[] {
  const out: Span[] = [];
  let start = 0;
  const key = (i: number) => `${/\s/.test(text[i]!)}${marks.b[i]}${marks.i[i]}${marks.hl[i]}${!!tint && i >= tint.start && i < tint.end}`;
  for (let i = 1; i <= text.length; i++) {
    if (i === text.length || key(i) !== key(i - 1)) {
      out.push({ start, end: i });
      start = i;
    }
  }
  return out;
}

/** neighbouring runs that share the highlight and the tint, gathered so each band is drawn by one inline box */
export function bands(all: Span[], marks: Marks, tint: Span | null): (Span & { runs: Span[] })[] {
  const out: (Span & { runs: Span[] })[] = [];
  const key = (r: Span) => `${marks.hl[r.start]}${!!tint && r.start >= tint.start && r.end <= tint.end}`;
  for (const r of all) {
    const last = out[out.length - 1];
    if (last && key(last) === key(r)) {
      last.end = r.end;
      last.runs.push(r);
    } else out.push({ start: r.start, end: r.end, runs: [r] });
  }
  return out;
}

/* the note's own text nodes (never the mark's copy of the words), in order */
function baseTexts(p: HTMLElement): Text[] {
  const out: Text[] = [];
  const w = document.createTreeWalker(p, NodeFilter.SHOW_TEXT);
  for (let n = w.nextNode(); n; n = w.nextNode()) if (!n.parentElement?.closest("[data-overlay]")) out.push(n as Text);
  return out;
}
/* a DOM point to its character offset in the note */
function offsetOf(p: HTMLElement, node: Node, offset: number): number {
  const at = document.createRange();
  at.setStart(node, offset);
  let sum = 0;
  for (const t of baseTexts(p)) {
    if (t === node) return sum + offset;
    if (at.comparePoint(t, 0) > 0) return sum;
    sum += t.length;
  }
  return sum;
}
/** the visitor's selection inside the note, as a span; null when nothing (or something elsewhere) is selected */
export function selectionIn(p: HTMLElement | null): Span | null {
  const s = typeof getSelection === "function" ? getSelection() : null;
  if (!p || !s || s.rangeCount === 0 || s.isCollapsed) return null;
  const r = s.getRangeAt(0);
  if (!p.contains(r.startContainer) || !p.contains(r.endContainer)) return null;
  const start = offsetOf(p, r.startContainer, r.startOffset);
  const end = offsetOf(p, r.endContainer, r.endOffset);
  return end > start ? { start, end } : null;
}
/* put the visitor's selection back after the runs re-cut (the old text nodes are gone) */
function select(p: HTMLElement, s: Span) {
  const sel = getSelection();
  if (!sel) return;
  const point = (o: number): [Node, number] => {
    let sum = 0;
    const texts = baseTexts(p);
    for (const t of texts) {
      if (o <= sum + t.length) return [t, o - sum];
      sum += t.length;
    }
    const last = texts[texts.length - 1]!;
    return [last, last.length];
  };
  const r = document.createRange();
  r.setStart(...point(s.start));
  r.setEnd(...point(s.end));
  sel.removeAllRanges();
  sel.addRange(r);
}

export default function ToggleGroupDemo() {
  const less = useLessMotion();
  const root = React.useRef<HTMLDivElement>(null);
  const note = React.useRef<HTMLParagraphElement>(null);
  /* the span the bar acts on: the scripted one (drawn as a tint) until the visitor selects or clears */
  const [sel, setSel] = React.useState<{ span: Span; own: boolean } | null>({ span: SCRIPTED, own: false });
  const [marks, setMarks] = React.useState<Marks>(blank);
  const [swept, setSwept] = React.useState<{ span: Span; n: number } | null>(null);
  const [align, setAlign] = React.useState<Align>("left");
  const [told, setTold] = React.useState(0);
  const self = useSelfPlay(root, { beats: [700], off: less });
  React.useEffect(() => {
    if (self.mine || self.step < 0) return;
    pressIn(root.current, '[aria-label="Highlight"]');
  }, [self.step, self.mine]);

  /* follow the visitor's selection: inside the note it is the target; a collapse or a selection elsewhere clears it */
  React.useEffect(() => {
    const on = () => {
      const span = selectionIn(note.current);
      if (span) return setSel((now) => (now?.own && now.span.start === span.start && now.span.end === span.end ? now : { span, own: true }));
      /* focus walking into the bar (Tab, a key) is not a new selection */
      const s = getSelection();
      if (s?.isCollapsed && root.current?.contains(document.activeElement) && !note.current?.contains(s.anchorNode)) return;
      setSel(null);
    };
    document.addEventListener("selectionchange", on);
    return () => document.removeEventListener("selectionchange", on);
  }, []);
  /* the runs re-cut when the marks or the tint change: put the visitor's own selection back on the same words */
  React.useLayoutEffect(() => {
    if (!sel?.own || !note.current) return;
    const now = selectionIn(note.current);
    if (!now || now.start !== sel.span.start || now.end !== sel.span.end) select(note.current, sel.span);
  });
  /* a sweep plays once: later re-cuts of the runs draw the mark at rest */
  React.useEffect(() => {
    if (!swept) return;
    const t = setTimeout(() => setSwept(null), SWEEP_MS);
    return () => clearTimeout(t);
  }, [swept]);
  React.useEffect(() => {
    if (!told) return;
    const t = setTimeout(() => setTold(0), 2400);
    return () => clearTimeout(t);
  }, [told]);

  const span = sel?.span ?? null;
  const flip = (k: Mark) => {
    if (!span) {
      setTold((n) => n + 1);
      return;
    }
    setTold(0);
    if (k === "hl" && !covers(marks, "hl", span)) setSwept((w) => ({ span, n: (w?.n ?? 0) + 1 }));
    setMarks((all) => flipSpan(all, k, span));
  };
  const flipRef = React.useRef(flip);
  React.useLayoutEffect(() => {
    flipRef.current = flip;
  });
  const { handOver } = self;
  /* ⌘B / ⌘I while focus is in the bar or the visitor's selection is in the note */
  React.useEffect(() => {
    const onKey = (e: KeyboardEvent) => {
      if (!(e.metaKey || e.ctrlKey)) return;
      const k = e.key.toLowerCase();
      if (k !== "b" && k !== "i") return;
      if (!root.current?.contains(document.activeElement) && !selectionIn(note.current)) return;
      e.preventDefault();
      handOver();
      flipRef.current(k);
    };
    document.addEventListener("keydown", onKey);
    return () => document.removeEventListener("keydown", onKey);
  }, [handOver]);

  const tint = sel && !sel.own ? sel.span : null;
  return (
    <div ref={root} onPointerDownCapture={self.handOver} onKeyDownCapture={self.handOver} className="flex w-full justify-center">
      <section className="w-[560px] max-w-full rounded-[var(--ns-radius-lg)] bg-[var(--ns-panel)] shadow-[inset_0_0_0_1px_var(--ns-line)]">
        {/* a press on the bar never takes the visitor's selection away */}
        <div className="flex items-center gap-3 border-b border-[var(--ns-line-soft)] px-2 py-2" onMouseDown={(e) => e.preventDefault()}>
          <ToggleGroup
            label="Format"
            setLabel="Alignment"
            value={align}
            onValueChange={setAlign}
            className="flex-wrap gap-3"
            options={[
              { value: "left", label: "Align left", icon: <AlignLeft aria-hidden /> },
              { value: "center", label: "Align centre", icon: <AlignCenter aria-hidden /> },
              { value: "right", label: "Align right", icon: <AlignRight aria-hidden /> },
            ]}
          >
            <div className="flex items-center gap-0.5">
              <ToolbarKey label="Bold" shortcut="⌘B" pressed={covers(marks, "b", span)} onClick={() => flip("b")}>
                <Bold aria-hidden />
              </ToolbarKey>
              <ToolbarKey label="Italic" shortcut="⌘I" pressed={covers(marks, "i", span)} onClick={() => flip("i")}>
                <Italic aria-hidden />
              </ToolbarKey>
              <ToolbarKey label="Highlight" swatch="var(--ns-marker)" pressed={covers(marks, "hl", span)} onClick={() => flip("hl")}>
                <Highlighter aria-hidden />
              </ToolbarKey>
            </div>
          </ToggleGroup>
          <span role="status" data-slot="toggle-group-status" className="ml-auto truncate pr-2 text-[length:var(--ns-text-small)] text-[var(--ns-ink-3)]">
            {told ? "Select some words first" : ""}
          </span>
        </div>
        <p ref={note} data-slot="toggle-group-note" className="m-0 px-5 py-5 text-[length:var(--ns-text-heading)] leading-[1.75] text-[var(--ns-ink)]" style={{ textAlign: align }}>
          {bands(runs(NOTE, marks, tint), marks, tint).map((band) => {
            const hl = marks.hl[band.start];
            const inTint = !!tint && band.start >= tint.start && band.end <= tint.end;
            const sweep = hl && !less && swept && band.start < swept.span.end && band.end > swept.span.start ? swept : null;
            return (
              /* one inline box per run of the same mark: the band is its own background, so it sits on the text's
                 line on every line it wraps to, one piece, with no copy of the words over it */
              <span
                key={`${band.start}-${band.end}-${hl ? "h" : ""}`}
                data-slot={hl ? "toggle-group-mark" : undefined}
                className={cn(
                  inTint && "bg-[color-mix(in_oklab,var(--ns-signal)_16%,transparent)] [transition:background-color_var(--ns-time-color)]",
                  hl && "bg-[image:linear-gradient(var(--ns-marker),var(--ns-marker))] bg-no-repeat text-[var(--ns-marker-ink)]",
                )}
                style={hl ? { backgroundSize: "100% 100%" } : undefined}
                ref={(el) => {
                  if (!el || !sweep || el.dataset.swept === String(sweep.n) || typeof el.animate !== "function") return;
                  el.dataset.swept = String(sweep.n);
                  const len = sweep.span.end - sweep.span.start;
                  const a = Math.max(0, (band.start - sweep.span.start) / len);
                  const b = Math.min(1, (band.end - sweep.span.start) / len);
                  /* one eased sweep over the span, left to right across its lines (the band is one strip) */
                  el.animate(
                    [
                      { backgroundSize: "0% 100%", color: "var(--ns-ink)", offset: 0 },
                      { backgroundSize: "0% 100%", color: "var(--ns-ink)", offset: a },
                      { backgroundSize: "100% 100%", color: "var(--ns-marker-ink)", offset: b },
                      { backgroundSize: "100% 100%", color: "var(--ns-marker-ink)", offset: 1 },
                    ],
                    { duration: SWEEP_MS, easing: EASE.move, fill: "backwards" },
                  );
                }}
              >
                {band.runs.map((r) => (
                  <span
                    key={`${r.start}-${r.end}`}
                    data-at={r.start}
                    data-slot="toggle-group-run"
                    data-marked={hl || undefined}
                    className={cn(marks.b[r.start] && "font-semibold", marks.i[r.start] && "italic")}
                  >
                    {NOTE.slice(r.start, r.end)}
                  </span>
                ))}
              </span>
            );
          })}
        </p>
      </section>
    </div>
  );
}
```

This example also uses `badge` (https://notchset.dev/components/badge). Installing this item doesn't bring them; to paste the example as it is: `npx shadcn@latest add https://notchset.dev/r/toggle-group.json https://notchset.dev/r/badge.json`.

## Props

| Prop | Type | Default | What it does |
|---|---|---|---|
| `setLabel` | `string` |  | names the exclusive set ("Alignment") |
| `options` | `ToggleGroupOption<V>[]` |  | the set's keys, two to five |
| `value` | `V` |  |  |
| `defaultValue` | `V` |  |  |
| `onValueChange` | `(v: V) => void` |  |  |

Full docs: https://notchset.dev/components/toggle-group

## Customising
- Colours: every part reads the foundation's roles (`--ns-canvas`, `--ns-ink`, `--ns-line`, `--ns-signal` …), which read your shadcn tokens (`--background`, `--foreground`, `--border`, `--destructive` …), plus the optional `--success` and `--warning`. Retheme on `:root` or any container; never add Tailwind colour classes inside the component.
- Dark mode follows the `.dark` class or `data-theme="dark"` on an ancestor (the shadcn and next-themes conventions).
- Update later: Commit or stash local changes first (or copy the files), so the update can be undone. Read https://notchset.dev/r/changelog.json for the new versions: a major version, an entry marked breaking or a merge says what to change. Then re-run the install with `--overwrite`, on a branch. It replaces the component's files, the shared helper files they import, and the item's CSS rules in the global stylesheet, so review the whole diff (components, shared files, CSS), re-apply your own edits, and run the app's typecheck, tests and build.

## Keyboard

| Keys | Action |
|---|---|
| ← → | move between every key in the bar |
| Space | press the focused key |
| Tab | into the bar at the last key focused, and out |

## Performance

- A handful of buttons; no measuring.

## Responsive

- phone: keys keep 32px
- desktop
- dark (tokens)

## Motion inventory

| Interaction | What moves |
|---|---|
| neighbouring sunk keys join | corner radius and a 2px bridge on --ns-time-color. Reduced motion: same (colour and corners only, nothing moves). |

## Accessibility contract (preserve when editing)
- A toolbar, one tab stop; the toggles are buttons with aria-pressed; the set is a radiogroup of radios with aria-checked, named by setLabel; each key is named by its label and shows it, with its keys, as a tip.

## Install

```bash
# npm
npx shadcn@latest add https://notchset.dev/r/toggle-group.json
# pnpm
pnpm dlx shadcn@latest add https://notchset.dev/r/toggle-group.json
# yarn
yarn dlx shadcn@latest add https://notchset.dev/r/toggle-group.json
# bun
bunx --bun shadcn@latest add https://notchset.dev/r/toggle-group.json
```

Or add the `@notchset` registry to components.json and run `npx shadcn@latest add @notchset/toggle-group`. Every components.json style gets the same files.

### Manual

1. Install the packages: none beyond `react` and `react-dom`.
2. Copy `components/ui/notchset/toggle-group.tsx`, `lib/notchset/controllable.ts` from https://notchset.dev/r/toggle-group.json (each file's `content`, at its `target`), keeping the `@/` path alias of your tsconfig.
3. Add what it builds on: shadcn `utils` (cn), `notchset-foundation`, `keyboard-hint`, `toolbar`.

## Continue the workflow

- [Action button](https://notchset.dev/components/action-button)
- [Action swap](https://notchset.dev/components/action-swap)
- [Button](https://notchset.dev/components/button)

## Source

### components/ui/notchset/toggle-group.tsx

```tsx
// Notchset toggle-group 1.0.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";
import { useControllable } from "@/lib/notchset/controllable";
import type { Shortcut } from "@/components/ui/notchset/keyboard-hint";
import { Toolbar, ToolbarKey, type ToolbarProps } from "@/components/ui/notchset/toolbar";

/*
 * Toggle group: a toolbar holding one exclusive set of keys (alignment: left, centre, right, justified), one sunk at a
 * time. It is Toolbar's radiogroup form: the set is a radiogroup of ToolbarKeys, so the bar stays one tab stop, the
 * arrows roam every key and Space presses. Independent toggles (Bold, Italic) go in `children`, before the set, as
 * ToolbarKeys with `pressed`. The choice is `value` with `onValueChange`, or `defaultValue`.
 *
 *   <ToggleGroup label="Format" setLabel="Alignment" defaultValue="left" options={[{ value: "left", label: "Align left", icon: <AlignLeft /> }, ...]} />
 */
type ToggleGroupOption<V extends string> = {
  value: V;
  /** the key's name and tip ("Align left") */
  label: string;
  icon: React.ReactNode;
  shortcut?: Shortcut | undefined;
  disabled?: boolean | undefined;
};
type ToggleGroupProps<V extends string> = Omit<ToolbarProps, "onChange" | "defaultValue"> & {
  /** names the exclusive set ("Alignment") */
  setLabel: string;
  /** the set's keys, two to five */
  options: ToggleGroupOption<V>[];
  value?: V | undefined;
  defaultValue?: V | undefined;
  onValueChange?: ((v: V) => void) | undefined;
};

function ToggleGroup<V extends string>({ setLabel, options, value: given, defaultValue, onValueChange, children, ...bar }: ToggleGroupProps<V>) {
  const [value, setValue] = useControllable<V | undefined>({ value: given, defaultValue: defaultValue ?? options[0]?.value, onChange: onValueChange && ((v) => v !== undefined && onValueChange(v)) });
  return (
    <Toolbar data-kind="toggle-group" {...bar}>
      {children}
      <div role="radiogroup" aria-label={setLabel} data-slot="toggle-group-set" className="flex items-center gap-0.5">
        {options.map((o) => (
          <ToolbarKey key={o.value} label={o.label} shortcut={o.shortcut} disabled={o.disabled} checked={o.value === value} onClick={() => setValue(o.value)}>
            {o.icon}
          </ToolbarKey>
        ))}
      </div>
    </Toolbar>
  );
}

export { ToggleGroup, type ToggleGroupOption, type ToggleGroupProps };
```

### lib/notchset/controllable.ts

```tsx
// Notchset toggle-group 1.0.0 · https://notchset.dev/changelog
"use client";
import * as React from "react";

/**
 * Controlled and uncontrolled, one source of truth: a piece takes `value` with `onValueChange` (controlled) or
 * `defaultValue` (uncontrolled), and reads and sets it through this hook. Controlled, it shows `value` and only asks
 * for a change; uncontrolled, it keeps its own state; it never switches between the two after its first render. On a
 * Base UI root it hands Base UI the controlled value. Controlled, two identical sets in one event can each call
 * onChange (the second is compared with what is shown, not with what was asked): harmless for open and close; a host
 * whose onChange has side effects makes it idempotent.
 * @example
 * const [value, setValue] = useControllable({ value: props.value, defaultValue: props.defaultValue ?? 0, onChange: props.onValueChange });
 * const [open, setOpen] = useControllableOpen(props);
 */
export function useControllable<T>({ value, defaultValue, onChange }: { value?: T | undefined; defaultValue: T; onChange?: ((next: T) => void) | undefined }): [T, (next: T | ((prev: T) => T)) => void] {
  const controlled = value !== undefined;
  const [own, setOwn] = React.useState(defaultValue);
  const current = controlled ? value : own;
  /* `asked` is what this event asked for so far, cleared by each render, so a refused request can be made again; written in an insertion effect so a layout effect reads this render's value. */
  const latest = React.useRef<{ current: T; controlled: boolean; onChange: typeof onChange; asked?: { v: T } | undefined }>({ current, controlled, onChange });
  React.useInsertionEffect(() => {
    latest.current = { current, controlled, onChange };
  });
  const set = React.useCallback((next: T | ((prev: T) => T)) => {
    const l = latest.current;
    const base = l.asked ? l.asked.v : l.current;
    const v = typeof next === "function" ? (next as (prev: T) => T)(base) : next;
    if (Object.is(v, base) && (!l.asked || Object.is(v, l.current))) return;
    l.asked = { v };
    if (!l.controlled) setOwn(v);
    l.onChange?.(v);
  }, []);
  return [current, set];
}

/** The same for a piece that opens: `open` with `onOpenChange`, or `defaultOpen`. */
export function useControllableOpen({ open, defaultOpen = false, onOpenChange }: { open?: boolean | undefined; defaultOpen?: boolean | undefined; onOpenChange?: ((open: boolean) => void) | undefined }) {
  return useControllable({ value: open, defaultValue: defaultOpen, onChange: onOpenChange });
}
```

The foundation (the tokens listed above, keyframes and motion levels) installs once with the first component; its CSS is public at https://notchset.dev/r/notchset-foundation.json.
