Перейти до вмісту

Група кнопок

Fuses об’єднує кнопки, панелі інструментів та додатки для введення даних в один рамковий блок — з однією товстою рамкою, однією чіткою тінню та одним спільним натисканням.

"use client"

import * as React from "react"

Button group зливає сусідні кнопки, поля вводу та мітки в один сегментований контроль. Під ним немає примітиву — звичайний контейнер role="group" тримає необруталістську рамку (одна товста межа, одна різка тінь, одна спільна анімація натискання); лише ButtonGroupSeparator звертається до примітиву, обгортаючи Separator.

Коли це стане в пригоді:

  • Розділені кнопки — основна дія плюс DropdownMenu альтернатив: Save / Save as…, Merge / Squash.
  • Пейджери та панелі інструментів — Previous/Next, zoom in/out, перемикачі вигляду в одній рамці.
  • Додатки до полів — поле пошуку з кнопкою submit, префікс URL, суфікс «копіювати».

Встановлення

pnpm dlx shadcn@latest add https://neobrutalism.com/r/base/button-group.json
npx shadcn@latest add https://neobrutalism.com/r/base/button-group.json
yarn dlx shadcn@latest add https://neobrutalism.com/r/base/button-group.json
bunx --bun shadcn@latest add https://neobrutalism.com/r/base/button-group.json

Встановіть такі залежності:

pnpm add @base-ui/react
npm install @base-ui/react
yarn add @base-ui/react
bun add @base-ui/react

Скопіюйте та вставте наведений нижче код у свій проєкт.

components/ui/button-group.tsx
import { cva, type VariantProps } from "class-variance-authority"
import { Slot } from "radix-ui"

import { cn } from "@/lib/utils"
import { Separator } from "@/components/ui/separator"

const buttonGroupVariants = cva(
  cn(
    // The GROUP itself is the cohesive NeoBrutalist unit: a single bold border +
    // one hard offset shadow wrapping every segment, so it reads as ONE unit.
    // The frame animates so the whole group can press like a single Button.
    "relative inline-flex w-fit items-stretch border-2 border-foreground bg-background shadow-md transition-all duration-200",
    // Segments become flush fills — the frame owns the border, shadow and corners.
    "[&>*]:rounded-none",
    "[&>:is(button,a)]:border-0 [&>:is(button,a)]:shadow-none!",
    // Segments never translate on their own — only the whole frame moves.
    "[&>:is(button,a)]:hover:translate-y-0! [&>:is(button,a)]:active:translate-x-0! [&>:is(button,a)]:active:translate-y-0!",
    // The WHOLE group presses into its shadow like a single Button: hover sinks it
    // toward the shadow, press sits it flush (shadow gone).
    "has-[:is(button,a):hover]:translate-y-1 has-[:is(button,a):hover]:shadow",
    "has-[:is(button,a):active]:translate-y-2 has-[:is(button,a):active]:translate-x-1 has-[:is(button,a):active]:shadow-none",
    // When a group CONTAINS nested groups it becomes a plain gapped container
    // (no frame / shadow / press) so each nested sub-group is its own pressable
    // unit instead of pressing the whole outer frame.
    "has-[>[data-slot=button-group]]:gap-2 has-[>[data-slot=button-group]]:border-0 has-[>[data-slot=button-group]]:bg-transparent has-[>[data-slot=button-group]]:shadow-none! has-[>[data-slot=button-group]]:translate-x-0! has-[>[data-slot=button-group]]:translate-y-0!",
    // The hovered/pressed segment darkens in place via a full-bleed inset tint, so
    // you can still tell which segment you're acting on while the frame presses.
    "[&>:is(button,a):hover]:shadow-[inset_0_0_0_999px_#00000012]! [&>:is(button,a):active]:shadow-[inset_0_0_0_999px_#0000001f]!",

    "dark:[&>:is(button,a):hover]:shadow-[inset_0_0_0_999px_#ffffff1f]! dark:[&>:is(button,a):active]:shadow-[inset_0_0_0_999px_#ffffff33]!",
    // Solid dark segments (secondary) always lighten on hover — a dark tint would
    // be invisible on a black button in light mode.
    "[&>:is(button,a)[data-variant=secondary]:hover]:shadow-[inset_0_0_0_999px_#ffffff2b]! [&>:is(button,a)[data-variant=secondary]:active]:shadow-[inset_0_0_0_999px_#ffffff45]!",
    "[&>:is(button,a):focus-visible]:relative [&>:is(button,a):focus-visible]:z-10"
  ),
  {
    variants: {
      orientation: {
        // A single crisp seam between segments (logical side, so RTL-correct).
        horizontal:
          "flex-row [&>*:not(:first-child)]:border-s-2! [&>*:not(:first-child)]:border-foreground",
        vertical:
          "flex-col [&>*:not(:first-child)]:border-t-2! [&>*:not(:first-child)]:border-foreground",
      },
    },
    defaultVariants: {
      orientation: "horizontal",
    },
  }
)

function ButtonGroup({
  className,
  orientation,
  ...props
}: React.ComponentProps<"div"> & VariantProps<typeof buttonGroupVariants>) {
  return (
    <div
      role="group"
      data-slot="button-group"
      data-orientation={orientation ?? "horizontal"}
      className={cn(buttonGroupVariants({ orientation }), className)}
      {...props}
    />
  )
}

function ButtonGroupText({
  className,
  asChild = false,
  ...props
}: React.ComponentProps<"div"> & {
  asChild?: boolean
}) {
  const Comp = asChild ? Slot.Root : "div"

  return (
    <Comp
      data-slot="button-group-text"
      className={cn(
        "inline-flex items-center gap-2 bg-muted px-3 font-head text-sm font-medium text-foreground [&_svg]:pointer-events-none [&_svg:not([class*='size-'])]:size-4",
        className
      )}
      {...props}
    />
  )
}

function ButtonGroupSeparator({
  className,
  orientation = "vertical",
  ...props
}: React.ComponentProps<typeof Separator>) {
  return (
    <Separator
      data-slot="button-group-separator"
      orientation={orientation}
      className={cn(
        "relative z-10 self-stretch bg-border data-horizontal:h-0.5 data-horizontal:w-auto data-vertical:h-auto data-vertical:w-0.5",
        className
      )}
      {...props}
    />
  )
}

export {
  ButtonGroup,
  ButtonGroupSeparator,
  ButtonGroupText,
  buttonGroupVariants,
}

Оновіть шляхи імпорту відповідно до структури вашого проєкту.

Використання

import {
  ButtonGroup,
  ButtonGroupSeparator,
  ButtonGroupText,
} from "@/components/ui/button-group"
<ButtonGroup>
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</ButtonGroup>

Композиція

Використайте наведену композицію, щоб зібрати ButtonGroup:

ButtonGroup
├── Button or Input
├── ButtonGroupSeparator
└── ButtonGroupText

Доступність

  • Компонент ButtonGroup має атрибут role, встановлений на group.
  • Використайте Tab, щоб переміщатися між кнопками в групі.
  • Використайте aria-label або aria-labelledby, щоб надати мітку групі кнопок.
<ButtonGroup aria-label="Button group">
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</ButtonGroup>

ButtonGroup vs ToggleGroup

  • Використайте компонент ButtonGroup, коли хочете згрупувати кнопки, що виконують дію.
  • Використайте компонент ToggleGroup, коли хочете згрупувати кнопки, що перемикають стан.

Приклади

Орієнтація

Встановіть проп orientation, щоб змінити компонування групи кнопок.

import { MinusIcon, PlusIcon } from "lucide-react"

import { Button } from "@/components/ui/button"

Розмір

Керуйте розміром кнопок за допомогою пропа size на окремих кнопках.

import { PlusIcon } from "lucide-react"

import { Button } from "@/components/ui/button"

Вкладені

Вкладайте компоненти <ButtonGroup>, щоб створювати групи кнопок із відступами.

import { AudioLinesIcon, PlusIcon } from "lucide-react"

import { Button } from "@/components/ui/button"

Роздільник

Компонент ButtonGroupSeparator візуально розділяє кнопки в межах групи.

Кнопкам із варіантом outline роздільник не потрібен, оскільки вони вже мають рамку. Для інших варіантів роздільник рекомендовано, щоб покращити візуальну ієрархію.

import { Button } from "@/components/ui/button"
import {
  ButtonGroup,

Розділений

Створіть розділену групу кнопок, додавши дві кнопки, розділені ButtonGroupSeparator.

import { IconPlus } from "@tabler/icons-react"

import { Button } from "@/components/ui/button"

Input

Загорніть компонент Input кнопками.

import { SearchIcon } from "lucide-react"

import { Button } from "@/components/ui/button"

Input Group

Загорніть компонент InputGroup, щоб створити складні компонування введення.

"use client"

import * as React from "react"

Створіть розділену групу кнопок із компонентом DropdownMenu.

"use client"

import {

Select

Поєднайте з компонентом Select.

"use client"

import * as React from "react"

Popover

Використайте з компонентом Popover.

import { BotIcon, ChevronDownIcon } from "lucide-react"

import { Button } from "@/components/ui/button"

RTL

Щоб увімкнути підтримку RTL у Neobrutalism, перегляньте посібник з налаштування RTL.

"use client"

import * as React from "react"

Доступність

ButtonGroup рендерить role="group", що повідомляє допоміжним технологіям про належність кнопок до групи, не змінюючи клавіатурної поведінки — кожна кнопка зберігає власну tab stop і нативну активацію Enter / Space. Назвіть групу через aria-label або aria-labelledby, щоб програми зчитування з екрана оголошували контекст:

<ButtonGroup aria-label="Pagination">
  <Button>Previous</Button>
  <Button>Next</Button>
</ButtonGroup>

ButtonGroupSeparator обгортає Base UI Separator, який рендерить role="separator" із відповідним aria-orientation — оголошується як роздільник і ніколи не отримує фокус. Якщо потрібен один tab stop зі стрілковою навігацією між кнопками, це патерн WAI-ARIA Toolbar — цей компонент навмисно лишає звичайний порядок tab.

Довідник API

ButtonGroup

Компонент ButtonGroup — це контейнер, який групує пов'язані кнопки разом із однаковим стилем.

PropTypeDefault
orientation"horizontal" | "vertical""horizontal"
<ButtonGroup>
  <Button>Button 1</Button>
  <Button>Button 2</Button>
</ButtonGroup>

Вкладайте кілька груп кнопок, щоб створювати складні компонування з відступами. Докладніше див. у прикладі вкладені.

<ButtonGroup>
  <ButtonGroup />
  <ButtonGroup />
</ButtonGroup>

ButtonGroupSeparator

Компонент ButtonGroupSeparator візуально розділяє кнопки в межах групи.

PropTypeDefault
orientation"horizontal" | "vertical""vertical"
<ButtonGroup>
  <Button>Button 1</Button>
  <ButtonGroupSeparator />
  <Button>Button 2</Button>
</ButtonGroup>

ButtonGroupText

Використайте цей компонент, щоб показати текст у межах групи кнопок.

PropTypeDefault
asChildbooleanfalse
<ButtonGroup>
  <ButtonGroupText>Text</ButtonGroupText>
  <Button>Button</Button>
</ButtonGroup>

Використайте проп asChild, щоб відрендерити власний компонент як текст, наприклад label.

import { ButtonGroupText } from "@/components/ui/button-group"
import { Label } from "@/components/ui/label"
 
export function ButtonGroupTextDemo() {
  return (
    <ButtonGroup>
      <ButtonGroupText asChild>
        <Label htmlFor="name">Text</Label>
      </ButtonGroupText>
      <Input placeholder="Type something here..." id="name" />
    </ButtonGroup>
  )
}