RendyUI 中文

Components / Toggle group

Toggle group

Choice · React / TypeScript Free

Recorded demo

Toggle group preview

Source

toggle-group.tsx
"use client";

/**
 * Toggle group — replica of the public UI Stacks spec.
 * Original implementation written from the public API docs.
 */
import * as React from "react";
import { motion, useReducedMotion } from "motion/react";
import { cn, useControllable } from "../internal";

export type ToggleGroupItem = {
  value: string;
  /** Required; names icon-only toggles for screen readers and the tooltip. */
  label: string;
  icon?: React.ReactNode;
  disabled?: boolean;
};

/** A value (or null) for single, an array for multiple. */
export type ToggleGroupValue = string | string[] | null;

export interface ToggleGroupProps {
  /** Single works like radios (arrows move and select); multiple is a set of pressed buttons. */
  type: "single" | "multiple";
  items: ToggleGroupItem[];
  value?: ToggleGroupValue;
  defaultValue?: ToggleGroupValue;
  onValueChange?: (value: ToggleGroupValue) => void;
  /** Single only: clicking the pressed toggle turns it off. Default false. */
  allowEmpty?: boolean;
  /** What each toggle shows. Default icon-label. */
  content?: "label" | "icon" | "icon-label";
  /** 36 or 40 px track. Icons 16 or 20 px. */
  size?: "sm" | "md";
  /** Disable the whole group. */
  disabled?: boolean;
  "aria-label"?: string;
  "aria-labelledby"?: string;
  className?: string;
}

function normalize(v: ToggleGroupValue | undefined, type: "single" | "multiple") {
  if (v === undefined) return undefined;
  if (type === "single") return typeof v === "string" ? [v] : [];
  return Array.isArray(v) ? v : [];
}

/**
 * Toggle group: a row of toggles on one track, single or multiple, with a
 * pill that slides between them and pops in with a little bounce.
 */
export function ToggleGroup({
  type,
  items,
  value,
  defaultValue,
  onValueChange,
  allowEmpty = false,
  content = "icon-label",
  size = "md",
  disabled,
  "aria-label": ariaLabel,
  "aria-labelledby": ariaLabelledBy,
  className,
}: ToggleGroupProps) {
  const reduce = useReducedMotion();
  const containerRef = React.useRef<HTMLDivElement>(null);
  const pillId = React.useId();

  const [selection, setSelection] = useControllable<string[]>(
    normalize(value, type),
    normalize(defaultValue, type) ?? [],
    (next) => {
      if (type === "single") onValueChange?.(next[0] ?? null);
      else onValueChange?.(next);
    },
  );

  // Keep the emitted array in the order of items.
  const ordered = React.useCallback(
    (values: string[]) => items.map((item) => item.value).filter((v) => values.includes(v)),
    [items],
  );

  const pressed = (item: ToggleGroupItem) => selection.includes(item.value);

  const press = React.useCallback(
    (item: ToggleGroupItem, viaKeyboardIsRadio = false) => {
      if (disabled || item.disabled) return;
      if (type === "single") {
        if (!viaKeyboardIsRadio && pressed(item) && allowEmpty) {
          setSelection([]);
          return;
        }
        setSelection([item.value]);
        return;
      }
      setSelection(
        pressed(item)
          ? selection.filter((v) => v !== item.value)
          : ordered([...selection, item.value]),
      );
    },
    [allowEmpty, disabled, ordered, pressed, selection, setSelection, type],
  );

  const enabledIndexes = items
    .map((item, index) => (item.disabled ? -1 : index))
    .filter((index) => index >= 0);

  const focusItem = (index: number) => {
    const node = containerRef.current?.querySelector<HTMLElement>(
      `[data-value="${CSS.escape(items[index].value)}"]`,
    );
    node?.focus();
  };

  const move = (from: number, delta: number | "first" | "last", select: boolean) => {
    if (!enabledIndexes.length) return;
    let next: number;
    if (delta === "first") next = enabledIndexes[0];
    else if (delta === "last") next = enabledIndexes[enabledIndexes.length - 1];
    else {
      const position = enabledIndexes.indexOf(from);
      const start = position >= 0 ? position : delta > 0 ? -1 : 0;
      next = enabledIndexes[(start + delta + enabledIndexes.length) % enabledIndexes.length];
    }
    focusItem(next);
    if (select) press(items[next], true);
  };

  const onKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {
    const current = Array.from(
      containerRef.current?.querySelectorAll<HTMLElement>("[data-value]") ?? [],
    ).findIndex((node) => node === document.activeElement);
    switch (event.key) {
      case "ArrowRight":
        event.preventDefault();
        move(current, 1, type === "single");
        break;
      case "ArrowLeft":
        event.preventDefault();
        move(current, -1, type === "single");
        break;
      case "Home":
        event.preventDefault();
        move(current, "first", type === "single");
        break;
      case "End":
        event.preventDefault();
        move(current, "last", type === "single");
        break;
    }
  };

  // Icons are 16 or 20 px depending on size.
  const iconClass = size === "sm" ? "[&>svg]:size-4 [&>svg]:shrink-0" : "[&>svg]:size-5 [&>svg]:shrink-0";
  const itemSize =
    size === "sm" ? "h-7 px-2 text-[12px] gap-1" : "h-8 px-2.5 text-[13px] gap-1.5";

  // Tab enters the group on the pressed toggle (or the first enabled one).
  const tabStopIndex =
    items.findIndex((item) => !item.disabled && pressed(item)) >= 0
      ? items.findIndex((item) => !item.disabled && pressed(item))
      : enabledIndexes[0] ?? -1;

  const pill = (
    <motion.span
      aria-hidden="true"
      layoutId={type === "single" && !reduce ? pillId : undefined}
      initial={reduce ? false : { opacity: 0, scale: 0.75 }}
      animate={{ opacity: 1, scale: 1 }}
      exit={reduce ? { opacity: 0 } : { opacity: 0, scale: 0.75 }}
      transition={reduce ? { duration: 0.12 } : { type: "spring", stiffness: 520, damping: 32 }}
      className="absolute inset-0 rounded-full border border-border bg-surface shadow-[var(--shadow-btn-secondary)]"
    />
  );

  return (
    <div
      ref={containerRef}
      role={type === "single" ? "radiogroup" : "group"}
      aria-label={ariaLabel}
      aria-labelledby={ariaLabelledBy}
      onKeyDown={onKeyDown}
      className={cn(
        "inline-flex w-fit items-center gap-0.5 rounded-full bg-muted p-1",
        disabled && "cursor-not-allowed opacity-50",
        className,
      )}
    >
      {items.map((item, index) => {
        const isPressed = pressed(item);
        const iconOnly = content === "icon";
        return (
          <button
            key={item.value}
            type="button"
            data-value={item.value}
            role={type === "single" ? "radio" : undefined}
            aria-checked={type === "single" ? isPressed : undefined}
            aria-pressed={type === "multiple" ? isPressed : undefined}
            aria-label={iconOnly ? item.label : undefined}
            title={iconOnly ? item.label : undefined}
            tabIndex={index === tabStopIndex && !disabled ? 0 : -1}
            disabled={disabled || item.disabled}
            onClick={() => press(item)}
            className={cn(
              "relative flex min-w-8 items-center justify-center rounded-full font-medium transition-colors",
              "outline-none focus-visible:ring-2 focus-visible:ring-select/60",
              itemSize,
              isPressed ? "text-fg" : "text-fg-muted hover:text-fg",
              (disabled || item.disabled) && "cursor-not-allowed opacity-50",
            )}
          >
            {isPressed ? pill : null}
            <span className="relative z-10 flex items-center">
              {item.icon ? <span className={cn("grid place-items-center", iconClass)}>{item.icon}</span> : null}
              {content !== "icon" ? <span className="whitespace-nowrap">{item.label}</span> : null}
              {content === "icon" && !item.icon ? <span>{item.label}</span> : null}
            </span>
          </button>
        );
      })}
    </div>
  );
}

export default ToggleGroup;

Usage

Add the TSX to your React project and install the required dependencies. Styles use Tailwind CSS and theme tokens。

Package dependencies · motion、react

Shared source · internal.ts

Props

NameTypeDescription
`type``"single" \| "multiple"`Single works like radios (arrows move and select); multiple is a set of pressed buttons (arrows only move focus).
`items``{ value; label; icon?; disabled? }[]`label is required; it names icon-only toggles for screen readers and the tooltip.
`value / defaultValue / onValueChange``string \| null / string[]`A value (or null) for single, an array for multiple, kept in the order of items.
`allowEmpty``boolean`Single only: clicking the pressed toggle turns it off. Default false.
`content``"label" \| "icon" \| "icon-label"`What each toggle shows. Default icon-label.
`size``"sm" \| "md"`36 or 40 px track. Icons 16 or 20 px.
`disabled / aria-label / aria-labelledby / className``boolean / string`Disable the whole group; name it for screen readers.