wui
组件

键盘提示 Kbd

用紧凑、克制的按键样式展示快捷键与键盘操作。

基础示例

Loading…
pnpm dlx wui@latest add @wui/kbd
components/ui/kbd.tsx
import * as React from "react"
import { cva, type VariantProps } from "class-variance-authority"

import { cn } from "@/lib/utils"

const kbdVariants = cva(
  "inline-flex shrink-0 items-center justify-center rounded-sm border border-border bg-muted/70 font-sans font-medium leading-none text-muted-foreground select-none",
  {
    variants: {
      size: {
        sm: "min-h-5 min-w-5 px-1 text-[10px]",
        default: "min-h-6 min-w-6 px-1.5 text-[11px]",
      },
    },
    defaultVariants: {
      size: "default",
    },
  }
)

export interface KbdProps
  extends React.ComponentProps<"kbd">,
    VariantProps<typeof kbdVariants> {
  /** Physical size of the key hint. @default "default" */
  size?: "sm" | "default"
}

/** A compact visual hint for one keyboard key. */
function Kbd({ className, size = "default", ...props }: KbdProps) {
  return (
    <kbd
      data-slot="kbd"
      data-size={size}
      className={cn(kbdVariants({ size }), className)}
      {...props}
    />
  )
}

/** Keeps multiple key hints aligned as one shortcut. */
function KbdGroup({ className, ...props }: React.ComponentProps<"span">) {
  return (
    <span
      data-slot="kbd-group"
      className={cn("inline-flex items-center gap-1", className)}
      {...props}
    />
  )
}

export { Kbd, KbdGroup, kbdVariants }

组件作用

Kbd 用于展示单个键位,KbdGroup 用于对齐组合快捷键。它是说明性内容,不可点击,也不应该承担 Button 的交互职责。组件只使用细边框和语义底色,不添加内高光或厚重拟物阴影。

组件属性

PropTypeDefaultDescription
size"sm" | "default"defaultPhysical size of the key hint.

Kbd 继承原生 <kbd> 属性,并提供 size="sm | default"KbdGroup 继承原生 <span> 属性。

事件

键盘提示本身不触发操作,但原生指针、焦点及数据属性仍会透传。需要响应快捷键时,应在页面或功能逻辑中单独注册键盘事件。

拓展使用

组合键使用多个 Kbd 包裹在 KbdGroup 中,并为仅由符号组成的组合提供清晰的 aria-label

<KbdGroup aria-label="Shortcut: Control K">
  <Kbd>Ctrl</Kbd>
  <Kbd>K</Kbd>
</KbdGroup>