npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

deepbi-chat

v0.3.2

Published

DeepBI Chat Widget for websites (React 18, TypeScript)

Readme

deepbi-chat

React 18 聊天挂件(可嵌入官网/任何 React 站点)。支持 ESM/CJS,自动生成类型声明,样式独立输出。

特性

  • 🚀 React 18 兼容 - 使用最新的 React 特性
  • 📱 响应式设计 - 适配各种屏幕尺寸
  • 🎨 现代化 UI - 美观的聊天界面
  • 🔄 实时消息 - 支持轮询获取新消息
  • 💾 会话缓存 - 自动保存用户会话信息
  • 📝 表单验证 - 内置邮箱和姓名验证
  • 🎯 TypeScript - 完整的类型支持
  • 📦 轻量级 - 最小化依赖

安装

npm i deepbi-chat
# 或
pnpm add deepbi-chat
# 或
yarn add deepbi-chat

基础使用

import { ChatWidget } from 'deepbi-chat';
import 'deepbi-chat/dist/style.css';

export default function App() {
  return (
    <ChatWidget
      position="bottom-right"
      apiEndpoint="https://your.api/prefix"
      apiKey="YOUR_API_KEY"
    />
  );
}

完整配置示例

import { ChatWidget } from 'deepbi-chat';
import 'deepbi-chat/dist/style.css';

export default function App() {
  return (
    <ChatWidget
      // 基础配置
      position="bottom-right"
      apiEndpoint="https://your-api-endpoint.com/api"
      apiKey="YOUR_API_KEY"
      
      // API 端点配置
      sendMessageEndpoint="/collect_message"
      getMessagesEndpoint="/get_new_message"
      setReadEndpoint="/set_message_read"
      
      // 轮询配置
      pollingInterval={10000}
      enablePolling={true}
      
      // 客户端标识
      fromClient="website"
      
      // 用户信息(可选)
      userName="张三"
      userEmail="[email protected]"
      
      // UI 文本自定义
      texts={{
        headerTitle: 'DeepBI 客服',
        headerSubtitle: '我们随时为您服务!',
        welcomeMessage: '您好!👋\n欢迎使用DeepBI客服系统,有什么可以帮助您的吗?',
        welcomeBackMessage: '欢迎回来,{userName}!👋\n今天有什么可以帮助您的吗?',
        initializationMessage: '太好了!我已经准备好为您服务了。请告诉我您需要什么帮助?',
        namePlaceholder: '请输入您的姓名 *',
        emailPlaceholder: '请输入您的邮箱 *',
        messagePlaceholder: '输入消息...',
        startButtonText: '开始聊天',
        loadingText: '处理中...',
        loadingHistoryText: '加载历史消息...',
        retryText: '重试'
      }}
      
      // 功能开关
      features={{
        enableHistoryLoading: true,    // 启用历史消息加载
        enableAutoScroll: true,        // 启用自动滚动
        enableSessionCache: true,      // 启用会话缓存
        enableMessageReadTracking: true, // 启用消息已读跟踪
        enableMessageRetry: true,      // 启用消息重试
        enableFormValidation: true     // 启用表单验证
      }}
      
      // 回调函数
      callbacks={{
        onMessageSent: (message) => {
          console.log('消息已发送:', message);
        },
        onMessageReceived: (message) => {
          console.log('收到新消息:', message);
        },
        onError: (error, context) => {
          console.error('聊天错误:', error, '上下文:', context);
        },
        onSessionStart: (userInfo) => {
          console.log('会话开始:', userInfo);
        },
        onSessionEnd: () => {
          console.log('会话结束');
        },
        onMessageRead: (messageKey) => {
          console.log('消息已读:', messageKey);
        }
      }}
      
      // 其他配置
      showCloseButton={true}
      className="my-custom-chat-widget"
    />
  );
}

API 参考

ChatWidgetProps

| 属性 | 类型 | 默认值 | 描述 | |------|------|--------|------| | apiEndpoint | string | - | 必需 - API 基础端点 | | apiKey | string | - | 必需 - API 密钥 | | position | 'bottom-right' \| 'bottom-left' \| 'top-right' \| 'top-left' | 'bottom-right' | 组件位置 | | sendMessageEndpoint | string | '/collect_message' | 发送消息端点 | | getMessagesEndpoint | string | '/get_new_message' | 获取消息端点 | | setReadEndpoint | string | '/set_message_read' | 设置已读端点 | | pollingInterval | number | 50000 | 轮询间隔(毫秒) | | enablePolling | boolean | true | 是否启用轮询 | | fromClient | string | 'manage_site' | 客户端标识 | | userName | string | - | 预设用户名 | | userEmail | string | - | 预设用户邮箱 | | tempUserKey | string | - | 预设临时用户标识 | | showCloseButton | boolean | false | 是否显示关闭按钮 | | className | string | - | 自定义 CSS 类名 | | texts | ChatWidgetTexts | - | 自定义文本 | | features | ChatWidgetFeatures | - | 功能开关 | | callbacks | ChatWidgetCallbacks | - | 回调函数 |

位置选项

  • bottom-right - 右下角(默认)
  • bottom-left - 左下角
  • top-right - 右上角
  • top-left - 左上角

自定义样式

组件使用 CSS 类名,您可以通过覆盖这些类来自定义样式:

.chat-widget {
  /* 主容器样式 */
}

.chat-widget__toggle {
  /* 切换按钮样式 */
}

.chat-widget__container {
  /* 聊天容器样式 */
}

.chat-widget__header {
  /* 头部样式 */
}

.chat-widget__messages {
  /* 消息区域样式 */
}

.chat-widget__message {
  /* 消息样式 */
}

.chat-widget__input-area {
  /* 输入区域样式 */
}

外部控制方法

插件支持通过 ref 暴露方法,让你可以从外部控制聊天组件:

使用 ref 控制组件

import React, { useRef } from 'react';
import { ChatWidget, ChatWidgetRef } from 'deepbi-chat';
import 'deepbi-chat/dist/style.css';

export default function App() {
  const chatRef = useRef<ChatWidgetRef>(null);

  const resetSession = () => {
    chatRef.current?.resetSession();
  };

  const openChat = () => {
    chatRef.current?.openChat();
  };

  const closeChat = () => {
    chatRef.current?.closeChat();
  };

  const sendMessage = () => {
    chatRef.current?.sendMessage('你好,我需要帮助!');
  };

  const getSessionInfo = () => {
    const info = chatRef.current?.getSessionInfo();
    console.log('会话信息:', info);
  };

  return (
    <div>
      <div>
        <button onClick={resetSession}>重置会话</button>
        <button onClick={openChat}>打开聊天</button>
        <button onClick={closeChat}>关闭聊天</button>
        <button onClick={sendMessage}>发送消息</button>
        <button onClick={getSessionInfo}>获取会话信息</button>
      </div>

      <ChatWidget
        ref={chatRef}
        apiEndpoint="https://your-api-endpoint.com/api"
        apiKey="YOUR_API_KEY"
        userName="用户名"
        userEmail="[email protected]"
      />
    </div>
  );
}

ChatWidgetRef 方法

| 方法 | 参数 | 描述 | |------|------|------| | resetSession() | - | 重置会话状态,清除消息但保留 localStorage 缓存 | | openChat() | - | 打开聊天窗口 | | closeChat() | - | 关闭聊天窗口 | | sendMessage(message: string) | message - 要发送的消息内容 | 编程方式发送消息 | | getSessionInfo() | - | 获取当前会话状态信息 |

会话状态信息

getSessionInfo() 返回的对象包含:

{
  isOpen: boolean;           // 聊天窗口是否打开
  isInitialized: boolean;    // 会话是否已初始化
  messageCount: number;      // 消息总数
  unreadCount: number;       // 未读消息数
  userInfo: {               // 用户信息
    name: string;
    email: string;
    tempUserKey: string;
  };
}

缓存机制

插件使用基于邮箱的 localStorage 缓存机制:

缓存 Key 格式

缓存内容

每个用户的缓存包含:

  • 用户姓名和邮箱
  • 临时用户标识 (temp_user_key)
  • 消息标识 (message_key)

重置行为

  • resetSession() 不会清除 localStorage 缓存
  • 缓存会在用户下次访问时自动恢复会话信息
  • 如需清除特定用户缓存,可调用 ChatCache.clear(email)
import { ChatCache } from 'deepbi-chat/dist/utils/cache';

// 清除特定用户的缓存
ChatCache.clear('[email protected]');

// 清除所有缓存
ChatCache.clear();

// 获取所有缓存的邮箱
const emails = ChatCache.getAllCachedEmails();

开发

安装依赖

npm install

本地开发和测试

1. 启动本地测试服务器

npm run dev:test

这会启动一个本地开发服务器,默认在 http://localhost:5173 运行,您可以在浏览器中实时预览和测试组件。

2. 修改测试配置

测试文件位于 src/SimpleTest.tsx,您可以修改其中的配置来测试不同的场景:

<ChatWidget
  apiEndpoint="https://your-api-endpoint.com/api"
  apiKey="YOUR_API_KEY"
  userName="测试用户"
  userEmail="[email protected]"
  enablePolling={true}
  pollingInterval={10000}
/>

3. 查看示例

项目提供了多个示例文件,位于 examples/ 目录:

  • examples/with-minimize-feature.tsx - 最小化功能示例
  • examples/with-reset-methods.tsx - 重置方法和外部控制示例

4. 构建包

# 清理旧的构建文件并重新构建
npm run build

构建产物会输出到 dist/ 目录。

5. 预览构建产物

npm run preview

6. 开发模式(监听文件变化)

npm run dev

这会启动 Rollup 监听模式,当源文件发生变化时自动重新构建。

发布新版本

# 1. 更新版本号(在 package.json 中)
# 2. 构建项目
npm run build

# 3. 发布到 npm
npm publish

项目结构

deepbi-chat/
├── src/
│   ├── widget/              # 聊天组件源码
│   │   ├── ChatWidget.tsx   # 主组件
│   │   ├── components/      # 子组件
│   │   ├── hooks/           # 自定义 Hooks
│   │   ├── services/        # API 服务
│   │   ├── utils/           # 工具函数
│   │   └── types.ts         # TypeScript 类型定义
│   ├── SimpleTest.tsx       # 简单测试组件
│   └── index.ts             # 入口文件
├── examples/                # 示例文件
├── dist/                    # 构建产物(发布到 npm)
└── package.json

许可证

MIT