@desource/context7-widget-react

中文文档
0.2.3发布于 2026/11/01MITTypeScriptES Module构建来源已验证近 30 天下载 1.7万

Native React component and hook for a customizable Context7 documentation chat widget.

原始使用文档
文档目录12 节
  1. Why Use This Widget?
  2. Before You Start
  3. Install
  4. Component
  5. Controlled Open State
  6. Hook
  7. Examples
  8. Props, Events, And Localization
  9. Data Flow And Privacy
  10. Customization
  11. Packaging
  12. Related packages

@desource/context7-widget-react

React Coverage SonarCloud Ask Context7 Ask DeepWiki License

Make Context7 docs chat look at home in your React app. Match your design with presets and CSS, open it from your own help button, and control it through React props, refs, or a hook.

Why Use This Widget?

Context7 provides its docs widget and hosted AI answers for free. This project adds a customizable interface around that service.

The official widget’s basic styling options can leave chat looking out of place on a carefully designed site. This package adds control over those details: custom fonts and spacing, flexible placement, copyable code, multiline input, and Stop and Retry actions.

If you use the official widget, replace its script URL or adopt the native React component below. Keep your existing Context7 library and domain settings. For a new integration, put docs help where visitors are choosing your library or working through setup.

React owns rendering and lifecycle. The shared core kit handles conversation state, transport, Markdown, and defaults.

Before You Start

Use a library you have claimed on Context7. In its Admin → Chat settings, enable the widget, add your site's domain to the allowed domains, and save. Replace /owner/repo in the examples with that library's id. A library being indexed alone does not enable chat on your site. See Context7's widget setup.

Install

npm install @desource/context7-widget-react

Import the stylesheet once:

import '@desource/context7-widget-react/styles.css';

Component

import { useRef } from 'react';
import { Context7Widget, type Context7WidgetHandle } from '@desource/context7-widget-react/component';
import '@desource/context7-widget-react/styles.css';

export function DocsAssistant() {
  const widget = useRef<Context7WidgetHandle>(null);

  return (
    <Context7Widget
      ref={widget}
      library="/owner/repo"
      position="anchor"
      preset="glass"
      customTrigger
      launcherLabel="Ask docs"
      onQuestion={(detail) => console.log(detail.question)}
    />
  );
}

customTrigger supports four modes: omit it for the built-in floating launcher, pass true for a React-managed button, pass an element id or CSS selector for an external trigger, or pass an Element/React ref. A function in the trigger prop can render custom contents inside the managed button.

Controlled Open State

Omit open for internal state initialized by defaultOpen. Use open and onOpenChange when application state owns the dialog:

const [docsOpen, setDocsOpen] = useState(false);

<Context7Widget library="/owner/repo" open={docsOpen} onOpenChange={setDocsOpen} />;

onOpen and onClose are lifecycle notifications emitted after an actual transition; onOpenChange is the controlled-state request.

Hook

useContext7Widget controls the newest React widget registered for its widgetId, or it can own a programmatically mounted React root:

import { useContext7Widget } from '@desource/context7-widget-react/hook';
import '@desource/context7-widget-react/styles.css';

export function DocsHelp() {
  const docs = useContext7Widget({
    autoMount: true,
    library: '/owner/repo',
    position: 'center',
    preset: 'terminal',
    widgetId: 'docs'
  });

  return (
    <button type="button" disabled={!docs.widget} onClick={() => void docs.send('Show the recommended setup')}>
      Explain setup
    </button>
  );
}

Automatic mounting happens after the owner mounts. Call send, open, and other controls from an event handler or after the widget is ready.

The hook returns widget, isOpen, isBusy, and messages, plus mount, unmount, open, close, toggle, send, cancel, retry, reset, and getMessages. mount(overrides) creates or updates an owned React widget. Every hook option remains reactive, including React children, trigger content, root props, and callbacks; explicit mount(overrides) values persist across those updates. Owned widgets are removed with their owner unless removeOnUnmount is false.

The registry is package-level, not based on React or DOM ancestry. widgetId defaults to default; when no default registration exists, that lookup falls back to the first available registered widget for single-widget applications. Duplicate ids form a stack: the newest registration wins, and unmounting it restores the previous registration.

Examples

Use a controlled widget when application state owns visibility:

import { useState } from 'react';
import { Context7Widget } from '@desource/context7-widget-react/component';
import '@desource/context7-widget-react/styles.css';

export function DocsHelp() {
  const [open, setOpen] = useState(false);

  return (
    <Context7Widget
      library="/owner/repo"
      open={open}
      onOpenChange={setOpen}
      position="center"
      backdrop
      preset="glass"
      customTrigger
    />
  );
}

Use useContext7Widget({ autoMount: true }) for route actions, command palettes, or other flows that need imperative control without placing a component in the current tree. More runnable patterns are available in the demo gallery.

Props, Events, And Localization

The component accepts the shared options: library, theme, preset, position, color, customTrigger, backdrop, closeOnOutsideClick, defaultOpen, initialMessage, labels, launcherLabel, launcherVariant, linkBaseUrl, panelHeight, panelWidth, placeholder, title, and widgetId.

Use labels to override any user-facing or assistive string, including attribution and library fallbacks. Context7WidgetLabels is exported for typed dictionaries. Relative Markdown links resolve against the Context7 library page by default; set linkBaseUrl to use your own documentation origin.

Lifecycle and stream callbacks are onReady, onOpen, onClose, onCancel, onQuestion, onFirstToken, onAnswer, onAnswerComplete, onToolCall, onToolResult, and onError. Every callback receives the typed detail object.

A component ref exposes open, close, toggle, send, cancel, retry, reset, isOpen, isBusy, getMessages, and subscribe. While a request is active, the multiline composer becomes read-only and its Send action becomes an enabled Stop action. Enter sends; Shift+Enter inserts a newline. Streaming follows the newest content while the conversation is near the bottom, preserves the reader's position after they scroll upward, and resumes when they return to the bottom or reset the conversation.

State listeners registered through subscribe are isolated from one another. If one throws, the error is reported without corrupting the request or skipping the remaining listeners.

Data Flow And Privacy

The browser posts the configured library id and current conversation messages directly to https://context7.com/api/v2/widget/chat. DeSource Labs does not proxy chat content. The package adds no analytics, cookies, or persistent browser storage; conversation state remains in the mounted widget until reset() or unmount. Callback payloads expose questions and answers to the host application, so any logging, analytics, or persistence added there is the integrator's data flow. Do not send secrets or sensitive personal data, and review Context7's policies for backend processing and retention.

Customization

The component renders native light DOM under .context7-widget. Apply shared CSS variables to that root and use [part~='send-button']-style selectors for stable component parts. Managed trigger tokens use --c7-trigger-background, --c7-trigger-border, --c7-trigger-color, --c7-trigger-focus, --c7-trigger-radius, and --c7-trigger-shadow.

.context7-widget.docs-assistant {
  --c7-accent: #7cffb2;
  --c7-panel-background: #101513;
  --c7-panel-color: #f7f2e8;
  --c7-panel-radius: 8px;
}

.context7-widget.docs-assistant [part~='send-button'] {
  min-width: 5rem;
}

Pass rootProps={{ className: 'docs-assistant' }} to scope these overrides. See the live customization guide for every public token and part.

Packaging

The package is ESM-only and SSR-import safe:

EntryContents
@desource/context7-widget-react/componentContext7Widget and component types; does not import React DOM
@desource/context7-widget-react/hookuseContext7Widget; requires React DOM for owned roots
@desource/context7-widget-reactCompatibility entry exporting both surfaces
@desource/context7-widget-react/styles.cssMinified widget and managed-trigger styles

Prefer /component when you only render Context7Widget. react-dom is an optional peer for that isolated entry and is required by /hook and by the package root, which also exports the hook. React, React DOM, and the core kit remain external so applications can deduplicate them. Rendering or programmatic mounting still requires a browser document. Every JavaScript entry and shared chunk preserves the React "use client" boundary for React Server Component and Next.js App Router consumers.

版本与发布记录

@desource/context7-widget-react 共发布 5 个版本,首次发布于 2026/09/10;过去 12 个月发布了 5 个版本。最新版本附带 npm provenance 构建来源证明,可追溯到公开的 CI 构建记录。

版本发布日期距今
0.2.3latest2026/11/0111 天前
0.2.22026/10/101 个月前
0.2.12026/10/011 个月前
0.2.02026/09/141 个月前
0.1.02026/09/102 个月前

关于 @desource/context7-widget-react 的常见问题

@desource/context7-widget-react 是什么?

Native React component and hook for a customizable Context7 documentation chat widget.

如何安装 @desource/context7-widget-react?

在项目目录运行 npm install @desource/context7-widget-react,或使用 pnpm add / yarn add / bun add。它还需要宿主项目提供 peer 依赖:react(^18.3.0 || ^19.0.0)。npm 7 及以上与 pnpm 8 及以上默认会自动安装必需的 peer 依赖,Yarn 需要手动安装。

@desource/context7-widget-react 支持 TypeScript 吗?

支持。包内自带 TypeScript 类型声明(package.json 声明了 types 入口),安装后即可获得类型提示,无需再安装 @types 包。

@desource/context7-widget-react 支持 ESM 还是 CommonJS?

以 ES Module 形式发布,推荐使用 import 引入。在 CommonJS 项目中,Node.js 20.19+ / 22.12+ 可以直接 require() 不含顶层 await 的 ES Module,更早的版本需要改用动态 import()。

@desource/context7-widget-react 可以商用吗?

@desource/context7-widget-react 使用 MIT 许可。宽松许可:允许商业使用、修改和再分发,通常只需在分发时保留原版权与许可声明。以上为概括,不构成法律意见,请以许可原文为准。

@desource/context7-widget-react 的下载量有多少?

根据 npm 官方下载统计,@desource/context7-widget-react 在 2026/10/12 – 2026/11/10 这 30 天内被下载 17,206 次,日均约 574 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入,适合横向比较热度,不能直接等同于使用人数。

@desource/context7-widget-react 还在维护吗?

最新版本 0.2.3 发布于 2026/11/01(11 天前);至今共发布 5 个版本,其中过去 12 个月发布了 5 个;首次发布于 2026/09/10。发布频率只是参考信号:功能稳定的工具可能很少需要更新,建议结合源码仓库的 issue 和提交记录判断。