# 边框光束

- 页面: https://jiguang132.com/zh/resources/libraries-dev/docs/border-beam
- 资源: Libraries.dev (https://jiguang132.com/zh/resources/libraries-dev.md)
- 全部指南: https://jiguang132.com/zh/resources/libraries-dev/docs.md

Libraries.dev 的独立组件，请不要替换为 JGuang UI/Base UI 的同名 API。

## 安装

```bash
npm install border-beam@1.4.1
```

安装包后使用它自己的导出组件，支持 React 18+。Canvas/WebGL 组件需要浏览器环境；提供静态降级，并尊重减少动画偏好。声音预览使用模拟信号，不会自动申请麦克风。

## 使用与验证

在左侧选择组件，在预览中操作它的状态；使用“查看代码”检查真实源码。安装后执行类型检查和构建，再验证键盘焦点、手机布局与深浅色主题。

## 来源

https://github.com/Jakubantalik/Libraries.dev/tree/b7f44b8744f4e09ff088d824719636a513110e2a
MIT 许可证；不包括付费内容。下方提供上游英文参考内容，中文使用指南已适配；上游详细参考暂保留英文。

---



## 适用场景

在输入框、按钮或卡片边缘增加光束，不改变内容本身的交互语义。

## 关键原生参数

| 参数 | 说明 |
|---|---|
| `size` | sm/md/line 为移动光束，pulse-outside/pulse-inner 为呼吸光；这是特效形态预设，不是像素宽度。 |
| `colorVariant` | 选择八种公开配色之一。staticColors 停止色相变化，不等于暂停全部动画。 |
| `theme` | 传入应用的 light/dark；auto 跟随系统偏好，可能与网页手动主题开关不同。 |
| `active` | 淡入/淡出特效，内部控件仍可操作。onActivate/onDeactivate 表示动画完成，不是后端动作。 |
| `strength` | 特效透明强度为 0–1；形态、duration 和 borderRadius 应与包裹内容匹配。 |

## 交互与状态检查

检查五种形态和八种配色，用键盘开关 active，并检查外部容器是否裁切光晕。包裹层不会替内容补充名称、焦点或禁用语义。

## 业务接入边界

仅提供 CSS/SVG 装饰，不提交表单，也不表示真实处理进度。补充减少动画行为，通过原生包导入，不替换成 JGuang 的同名组件。

## 示例文件与宿主配置

从源码面板复制 examples 下的组件文件和 shared.tsx，保留它们的相对位置；不是只复制原生上游实现。先安装固定版本 npm 包，在浏览器组件中使用它自己的导出。示例不需要 Tailwind 或新的主题 Provider，采用宿主 html 的语言和主题，并提供减少动画与图形不可用降级。原生实现参考仅供阅读，通过 npm 导入，不要求手工复制内部引擎。示例场景名称不是新增的原生组件属性。下方上游详细参考保留英文，不宣称全文中文化。


## 可运行用法

以下代码使用资源原生 API；不是把其他设计系统的同名组件替换进来。

```tsx
"use client";
import { useState } from "react";
import { BorderBeam, type BorderBeamColorVariant, type BorderBeamSize } from "border-beam";
import { DemoFrame, GraphicsGuard, control, demoTheme, panel, t } from "./shared";
export default function Example({ variant = "Default" }: { variant?: string }) {
  const sizes: Record<string, BorderBeamSize> = { Default: "md", Small: "sm", Line: "line", "Pulse outside": "pulse-outside", "Pulse inner": "pulse-inner", Inactive: "md" };
  const [size, setSize] = useState<BorderBeamSize>(sizes[variant] ?? "md");
  const [color, setColor] = useState<BorderBeamColorVariant>("ocean"), [active, setActive] = useState(variant !== "Inactive");
  return <DemoFrame status={`size=${size}, colorVariant=${color}, active=${active}`} controls={<>
    <label>{t("Shape", "形态")} <select style={control} aria-label={t("Beam shape", "光束形态")} value={size} onChange={e => setSize(e.target.value as BorderBeamSize)}>{Object.entries(sizes).filter(([key]) => key !== "Inactive").map(([key, value]) => <option key={key} value={value}>{value}</option>)}</select></label>
    <label>{t("Palette", "配色")} <select style={control} aria-label={t("Beam palette", "光束配色")} value={color} onChange={e => setColor(e.target.value as BorderBeamColorVariant)}>{["colorful", "mono", "ocean", "sunset", "forest", "candy", "ice", "gold"].map(value => <option key={value}>{value}</option>)}</select></label>
    <button type="button" style={control} aria-pressed={active} onClick={() => setActive(!active)}>{active ? t("Deactivate", "关闭特效") : t("Activate", "开启特效")}</button>
  </>}><GraphicsGuard kind="svg"><BorderBeam size={size} colorVariant={color} theme={demoTheme()} active={active} style={{ width: "100%", maxWidth: 320 }}><div style={panel}>{t("A native border effect around your content", "环绕内容的原生边框特效")}</div></BorderBeam></GraphicsGuard></DemoFrame>;
}

```


## 可用状态与示例

完整边框、紧凑边框、底部光束、外部呼吸光、内部呼吸光、关闭特效

组件中的状态与数据为演示用途，不包含后端接口。接入实际项目时请检查源码中的公开参数，再连接业务数据。
# border-beam

Animated border beam effect for React. A lightweight component that adds a traveling or breathing glow animation around any element — cards, buttons, inputs, or search bars.

## Install

```bash
npm install border-beam
```

## Quick start

```tsx
import { BorderBeam } from 'border-beam';

function App() {
  return (
    <BorderBeam>
      <div style={{ padding: 32, borderRadius: 16, background: '#1d1d1d' }}>
        Your content here
      </div>
    </BorderBeam>
  );
}
```

The component wraps your content and overlays the animated beam effect. It auto-detects the `border-radius` of the first child element.

## Types

Built-in presets control the glow style and motion. They fall into two families:

### Rotate (traveling beam)

```tsx
<BorderBeam size="md">  {/* Full border glow (default) */}
  <Card />
</BorderBeam>

<BorderBeam size="sm">  {/* Compact glow for small elements */}
  <IconButton />
</BorderBeam>

<BorderBeam size="line">  {/* Bottom-only traveling glow */}
  <SearchBar />
</BorderBeam>
```

### Pulse (breathing glow, no rotation)

```tsx
<BorderBeam size="pulse-inner">    {/* Contained breathing border glow */}
  <Card />
</BorderBeam>

<BorderBeam size="pulse-outside">  {/* Outward-blooming halo around the element */}
  <Card />
</BorderBeam>
```

Both pulse types support all color variants, `strength`, `theme`, and the breathe
speed via `duration` (defaults to `2.3`).

> **`pulse-outside` requires an opaque wrapped child.** The colorful core and halo
> render *behind* your content (`z-index: -1`) and bloom outward, so only the part
> that spills beyond the element shows. If your child is transparent, the inner glow
> will show through. The wrapper uses `overflow: visible`, so make sure the
> surrounding layout has room (or `overflow: visible`) for the halo to spill.

> **`pulse-outside` relies on the wrapped element's own 1px border as the idle
> hairline.** It does not paint its own hairline by default, so the colored stroke
> rides directly on top of your element's existing edge instead of doubling it. If
> your child has no border, add a subtle 1px border (or `box-shadow: inset 0 0 0 1px`)
> so the edge stays defined while the beam is faded out.

## Color variants

Four color palettes are available:

```tsx
<BorderBeam colorVariant="colorful" />  {/* Rainbow spectrum (default) */}
<BorderBeam colorVariant="mono" />      {/* Grayscale */}
<BorderBeam colorVariant="ocean" />     {/* Blue-purple tones */}
<BorderBeam colorVariant="sunset" />    {/* Orange-yellow-red tones */}
```

All variants except `mono` animate through a hue-shift cycle.

## Theme

Adapts beam colors for dark or light backgrounds:

```tsx
<BorderBeam theme="dark" />   {/* Dark background (default) */}
<BorderBeam theme="light" />  {/* Light background */}
<BorderBeam theme="auto" />   {/* Detects system preference */}
```

## Strength

Control the overall intensity of the effect without affecting the wrapped content:

```tsx
<BorderBeam strength={0.7}>  {/* 70% intensity */}
  <Card />
</BorderBeam>
```

`strength` accepts a value from `0` (invisible) to `1` (full intensity, default).

## Play / pause

Toggle the animation on and off with smooth fade transitions:

```tsx
const [active, setActive] = useState(true);

<BorderBeam active={active} onDeactivate={() => console.log('faded out')}>
  <Card />
</BorderBeam>
```

## Props

| Prop | Type | Default | Description |
|------|------|---------|-------------|
| `children` | `ReactNode` | — | Content to wrap |
| `size` | `'sm' \| 'md' \| 'line' \| 'pulse-outside' \| 'pulse-inner'` | `'md'` | Size/type preset |
| `colorVariant` | `'colorful' \| 'mono' \| 'ocean' \| 'sunset'` | `'colorful'` | Color palette |
| `theme` | `'dark' \| 'light' \| 'auto'` | `'dark'` | Background adaptation |
| `strength` | `number` | `1` | Effect opacity (0–1), only affects the beam layers |
| `duration` | `number` | `1.96` / `3.1` / `2.3` | Animation cycle duration in seconds (rotate / line / pulse) |
| `active` | `boolean` | `true` | Whether the animation is playing |
| `borderRadius` | `number` | auto-detected | Custom border radius in px |
| `brightness` | `number` | per-type (`1.3`) | Glow brightness multiplier; falls back to the type's preset default |
| `saturation` | `number` | `1.2` | Glow saturation multiplier |
| `hueRange` | `number` | `30` | Hue rotation range in degrees |
| `staticColors` | `boolean` | `false` | Disable hue-shift animation |
| `className` | `string` | — | Additional class on the wrapper |
| `style` | `CSSProperties` | — | Additional inline styles on the wrapper |
| `onActivate` | `() => void` | — | Called when fade-in completes |
| `onDeactivate` | `() => void` | — | Called when fade-out completes |

All standard `HTMLDivElement` attributes are also forwarded to the wrapper.

## How it works

`BorderBeam` renders a wrapper `<div>` with:

- **`::after`** — the beam stroke (rotate: conic gradient masked to the border; pulse: the colored perimeter ring / hairline)
- **`::before`** — inner glow layer (pulse-outside pushes this outward behind the content)
- **`[data-beam-bloom]`** — outer bloom/glow child div

All effect layers are absolutely positioned and use `pointer-events: none`, so they never interfere with your content. The rotate and line types animate via CSS `@property` keyframes for smooth GPU-accelerated transitions; because the keyframes also declare explicit `0% / 50% / 100%` stops, browsers without `@property` support degrade gracefully (stepped instead of interpolated motion) rather than breaking. The pulse types drive their slow breathing from a single shared, frame-rate-capped (~30fps) `requestAnimationFrame` loop that writes plain CSS custom properties — so the breathing works even without `@property` support, repaints less often, and automatically pauses when the instance is inactive, offscreen, or the user prefers reduced motion. The pulse types also isolate their stacking context, cap blur radii, and hint `will-change` on the animated layers for performance.

## Project structure

```
border-beam/
├── src/
│   ├── index.ts          # Public exports
│   ├── BorderBeam.tsx     # React component
│   ├── types.ts           # TypeScript type definitions
│   ├── styles.ts          # CSS generation engine
│   └── pulseDriver.ts     # Shared rAF loop driving the pulse breathing
├── demo/                  # Vite + React demo site
├── dist/                  # Built output (ESM + CJS + types)
├── package.json
├── LICENSE
└── README.md
```

## Requirements

- React 18+
- Modern browser with CSS `@property` support (Chrome 85+, Safari 15.4+, Firefox 128+)

## Accessibility

The effect layers are purely decorative and use `pointer-events: none`. They do not affect keyboard navigation or screen readers. The pulse types ship a built-in `prefers-reduced-motion: reduce` block that disables their animations; the rotate types respect `prefers-reduced-motion` when implemented by the consumer.

## License

[MIT](https://github.com/Jakubantalik/Libraries.dev/blob/b7f44b8744f4e09ff088d824719636a513110e2a/packages/border-beam/LICENSE)


## 源码参数参考

以下实现签名和类型从本地固定版本源码生成。保留可选属性、原生继承类型、联合分支和 never 限制；不会将其他设计系统的 API 混入。forwardRef 实现中的 ref 属于 React 引用，不是新增业务属性。此区域是原始类型参考，不是上游说明的全文翻译。


```ts
BorderBeam({
      children,
      size = 'md',
      colorVariant = 'colorful',
      theme = 'dark',
      staticColors = false,
      duration,
      active = true,
      borderRadius: customBorderRadius,
      brightness: brightnessProp,
      saturation,
      hueRange = 30,
      glowSize = 1,
      strength = 1,
      className,
      style,
      css: extraCss,
      onActivate,
      onDeactivate,
      onAnimationEnd: consumerOnAnimationEnd,
      ...props
    }: BorderBeamProps, ref: ForwardedRef<HTMLDivElement>)
```



```ts
export type BorderBeamSize = 'sm' | 'md' | 'line' | 'pulse-outside' | 'pulse-inner';

export type BorderBeamTheme = 'dark' | 'light' | 'auto';

export type BorderBeamColorVariant =
  | 'colorful'
  | 'mono'
  | 'ocean'
  | 'sunset'
  | 'forest'
  | 'candy'
  | 'ice'
  | 'gold';

export interface BorderBeamProps extends Omit<HTMLAttributes<HTMLDivElement>, 'children'> {
  /** Content to wrap with the border beam effect */
  children: ReactNode;

  /**
   * Size/type preset
   * Rotate family: 'sm' (compact), 'md' (full border, default), 'line' (bottom traveling).
   * Pulse family: 'pulse-outside' (outward bloom), 'pulse-inner' (contained breathe).
   * @default 'md'
   */
  size?: BorderBeamSize;

  /**
   * Color variant for the beam effect
   * - 'colorful': Full rainbow spectrum (default)
   * - 'mono': Monochromatic grayscale
   * - 'ocean': Blue and purple tones
   * - 'sunset': Warm orange, yellow, and red tones
   * @default 'colorful'
   */
  colorVariant?: BorderBeamColorVariant;

  /**
   * Theme mode - adapts beam/glow colors for dark or light backgrounds
   * 'auto' detects system preference via prefers-color-scheme
   * @default 'dark'
   */
  theme?: BorderBeamTheme;

  /**
   * Disable the hue-shift animation for static colors (e.g., monochrome)
   * @default false
   */
  staticColors?: boolean;

  /**
   * Rotation/travel duration in seconds
   * @default 1.96 for border, 2.4 for line
   */
  duration?: number;

  /**
   * Whether the animation is active
   * @default true
   */
  active?: boolean;

  /**
   * Custom border radius in pixels. When omitted, the component
   * auto-detects the border-radius of the first child element.
   * Falls back to the size preset default if detection fails.
   */
  borderRadius?: number;

  /**
   * Brightness multiplier for the glow effect.
   * Falls back to the type's preset default (1.3 for most types).
   * @default 1.3
   */
  brightness?: number;

  /**
   * Saturation multiplier for the glow effect
   * @default 1.2 for dark, varies for light
   */
  saturation?: number;

  /**
   * Multiplies the blur radius of every glow layer, so the halo reads
   * tighter (< 1) or wider and softer (> 1). Each layer keeps its own
   * tuned proportion — the core stays tighter than the bloom — because
   * this scales the presets rather than replacing them.
   * @default 1
   */
  glowSize?: number;

  /**
   * Hue rotation range in degrees for the hue-shift animation
   * @default 30
   */
  hueRange?: number;

  /**
   * Overall strength/opacity of the effect (0-1).
   * Only affects the beam, glow, and bloom layers -- not the children.
   * @default 1
   */
  strength?: number;

  /**
   * Additional class name for the container
   */
  className?: string;

  /**
   * Additional inline styles for the container
   */
  style?: CSSProperties;

  /**
   * Extra CSS appended after the beam's own generated stylesheet, so it can
   * override or add layers and keyframes. Write `{id}` wherever the
   * instance id belongs — the root is `[data-beam="{id}"]`, its layers are
   * the `::before` / `::after` pseudo-elements and `[data-beam-bloom]`, and
   * keyframes are named `*-{id}` — and it is substituted per instance.
   */
  css?: string;

  /**
   * Callback when fade-in animation completes
   */
  onActivate?: () => void;

  /**
   * Callback when fade-out animation completes
   */
  onDeactivate?: () => void;
}
```


### 源码中的解构默认值

只列出直接写在参数或 props 解构中的默认表达式。条件表达式、运行时主题和其他计算值请结合源码；这里不是全部行为的默认值清单。


```ts
// BorderBeam
size = 'md'

// BorderBeam
colorVariant = 'colorful'

// BorderBeam
theme = 'dark'

// BorderBeam
staticColors = false

// BorderBeam
active = true

// BorderBeam
hueRange = 30

// BorderBeam
glowSize = 1

// BorderBeam
strength = 1
```


### 原生与外部类型

以下外部类型仍由 React 或资源自身依赖定义，没有手工展开为虚构属性。实际可用类型以安装版本的 TypeScript 检查为准。


```ts
HTMLDivElement
Omit<HTMLAttributes<HTMLDivElement>, 'children'>
HTMLAttributes<HTMLDivElement>
ReactNode
CSSProperties
ForwardedRef<HTMLDivElement>
```

---

JGuang 全部资源索引: https://jiguang132.com/llms.txt
