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

@icos-react/largemodel

v0.7.1

Published

> 企业级大模型聊天组件库 - 高性能、易用、可定制

Readme

@icos-react/largemodel

企业级大模型聊天组件库 - 高性能、易用、可定制

Version React TypeScript

✨ 特性

  • 🎨 可定制 - 丰富的样式配置和自定义选项
  • 💪 TypeScript - 完整的类型定义和智能提示
  • 🔧 易用 - 简单的 API 设计,快速上手
  • 🛡️ 稳定 - 自动内存管理,防止内存泄漏
  • 📱 响应式 - 支持百分比自适应和固定尺寸

📦 安装

npm install @icos-react/largemodel
# 或
yarn add @icos-react/largemodel
# 或
pnpm add @icos-react/largemodel

📖 目录


ChatDemo / ChatDemoRefactored

核心聊天组件,负责消息展示、发送和交互。推荐使用优化后的 ChatDemoRefactored

基础用法

import { ChatDemoRefactored as ChatDemo } from '@icos-react/largemodel';

function App() {
  return (
    <ChatDemo
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
      }}
    />
  );
}

Props 详解

必需属性

| 属性 | 类型 | 说明 | |------|------|------| | apiInfo | ApiInfo | API 配置信息 |

ApiInfo 类型

interface ApiInfo {
  url: string;           // API 地址
  method: string;        // 请求方法(通常为 'POST')
  headers?: Record<string, string>; // 请求头
}

可选属性

| 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | history | any[] | [] | 历史消息记录 | | eventContent | Record<string, ReactNode> | {} | 事件内容映射 | | variables | any | {} | 请求变量 | | userIcon | string | - | 用户头像 | | buttonImage | string | - | AI 头像 | | sendImage | string | - | 发送按钮图标 | | userPosition | 'start' \| 'end' | 'end' | 用户消息位置 | | showAvatar | boolean | true | 是否显示头像 | | showHeader | boolean | true | 是否显示头部 | | showDigitalHuman | boolean | false | 是否显示数字人 | | enableMessageActions | boolean | false | 是否启用消息操作 | | customStyle | CustomStyle | - | 自定义样式 | | classNames | Record<string, string> | - | 自定义类名 |

回调函数

| 属性 | 类型 | 说明 | |------|------|------| | onEventChange | (data: any, messageId?: string) => void | 事件变化回调 | | onTypeChange | (type: string) => void | 类型变化回调 | | onCurrentTypeChange | (type: string) => void | 当前类型变化回调 | | messageActionCallbacks | MessageActionCallbacks | 消息操作回调集合 |

MessageActionCallbacks 类型

interface MessageActionCallbacks {
  onLike?: (messageId: string | number, currentState: boolean) => Promise<boolean>;
  onDislike?: (messageId: string | number, currentState: boolean) => Promise<boolean>;
  onCopy?: (content: string, messageId: string | number) => Promise<void>;
  onRefresh?: (messageId: string | number, userMessageContent: string) => Promise<void>;
}

完整示例

import React, { useState, useRef } from 'react';
import { ChatDemoRefactored as ChatDemo, ChatDemoRef } from '@icos-react/largemodel';

function AdvancedChat() {
  const chatRef = useRef<ChatDemoRef>(null);
  const [eventContent, setEventContent] = useState({});

  const handleEventChange = (data: any, messageId?: string) => {
    const newContent: Record<string, React.ReactNode> = {};
    
    data.forEach((item: any) => {
      if (item.type === 'eventPosition' && item.anchorId) {
        newContent[`${messageId}#${item.anchorId}`] = (
          <button onClick={() => showMap(item.data)}>
            查看位置
          </button>
        );
      }
    });
    
    setEventContent(prev => ({ ...prev, ...newContent }));
  };

  const handleLike = async (messageId: string | number, currentState: boolean) => {
    await fetch('/api/like', {
      method: 'POST',
      body: JSON.stringify({ messageId, liked: currentState }),
    });
    return true;
  };

  const handleCopy = async (content: string) => {
    await navigator.clipboard.writeText(content);
    console.log('复制成功');
  };

  return (
    <ChatDemo
      ref={chatRef}
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
          'Authorization': 'Bearer token',
        },
      }}
      eventContent={eventContent}
      onEventChange={handleEventChange}
      enableMessageActions={true}
      messageActionCallbacks={{
        onLike: handleLike,
        onCopy: handleCopy,
      }}
      customStyle={{
        container: {
          background: '#f5f5f5',
          borderRadius: '12px',
        },
        messageList: {
          padding: '20px',
        },
      }}
    />
  );
}

Ref 方法

interface ChatDemoRef {
  sendMessage: (message: string, isCreateApp?: boolean, variable?: any) => Promise<void>;
  sendMessageWithControl: (
    message: string,
    showUserMessage?: boolean,
    variable?: any,
    resetSession?: boolean
  ) => Promise<void>;
  setInputText: (text: string) => void;
  getMidVal: () => any;
  getVariables: () => any;
  updateVariables: (variables: any) => void;
}

使用示例:

const chatRef = useRef<ChatDemoRef>(null);

// 发送消息
chatRef.current?.sendMessage('你好');

// 发送消息(控制显示和会话)
chatRef.current?.sendMessageWithControl(
  '这是一条消息',
  true,  // 显示用户消息
  { key: 'value' },  // 变量
  false  // 不重置会话
);

// 设置输入框文本
chatRef.current?.setInputText('预设文本');

// 获取中间值
const midVal = chatRef.current?.getMidVal();

// 更新变量
chatRef.current?.updateVariables({ newKey: 'newValue' });

ChatTop

带欢迎页面的聊天组件,适合作为独立的聊天应用入口。已自动集成优化后的 ChatDemo

基础用法

import { ChatTop } from '@icos-react/largemodel';

function App() {
  return (
    <ChatTop
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
      }}
      welcomeSubtitle="我可以帮您解答问题"
      chatHello="您好,我是您的智能助手"
    />
  );
}

Props 详解

ChatTop 继承了 ChatDemo 的所有属性,并新增以下属性:

| 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | welcomeSubtitle | string | - | 欢迎页副标题 | | chatHello | string | - | 欢迎语 | | topContent | ReactNode | - | 顶部自定义内容 | | bottomContent | ReactNode | - | 底部自定义内容 | | quickQuestions | QuickQuestion[] | - | 快捷问题列表 | | footerButtons | FooterButton[] | - | 底部按钮列表 | | showTopButtonsInChat | boolean | true | 是否在聊天中显示顶部按钮 |

QuickQuestion 类型

interface QuickQuestion {
  content: string;  // 问题内容
  type?: string;    // 问题类型
}

FooterButton 类型

interface FooterButton {
  icon: string;     // 图标 URL
  text: string;     // 按钮文本
  type: string;     // 按钮类型
  disabled?: boolean; // 是否禁用
}

完整示例

import React, { useRef } from 'react';
import { ChatTop } from '@icos-react/largemodel';

function ChatApp() {
  const chatTopRef = useRef<any>(null);

  const questions = [
    { content: '如何使用这个功能?', type: 'help' },
    { content: '最新的更新内容是什么?', type: 'update' },
  ];

  const footerButtons = [
    {
      icon: '/icons/analysis.svg',
      text: '数据分析',
      type: 'analysis',
    },
    {
      icon: '/icons/service.svg',
      text: '客户服务',
      type: 'service',
    },
  ];

  const topContent = (
    <div style={{ padding: '20px', textAlign: 'center' }}>
      <h1>欢迎使用智能助手</h1>
      <p>我可以帮您解答各种问题</p>
    </div>
  );

  return (
    <ChatTop
      ref={chatTopRef}
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
      }}
      welcomeSubtitle="选择下方问题快速开始"
      chatHello="您好!有什么可以帮您的?"
      topContent={topContent}
      quickQuestions={questions}
      footerButtons={footerButtons}
      showTopButtonsInChat={true}
      customStyle={{
        container: {
          height: '100vh',
        },
        emptyStateWrapper: {
          background: 'linear-gradient(to bottom, #f0f0f0, #ffffff)',
        },
      }}
    />
  );
}

Ref 方法

ChatTop 继承了 ChatDemo 的所有 ref 方法,并新增:

interface ChatTopRef extends ChatDemoRef {
  setCurrentType: (type: string, toggle?: boolean) => void;
  sendQuestionMessage: (content: string, type?: string) => void;
  reset: () => Promise<void>;
}

使用示例:

const chatTopRef = useRef<any>(null);

// 设置当前类型
chatTopRef.current?.setCurrentType('help');

// 发送问题消息
chatTopRef.current?.sendQuestionMessage('如何使用?', 'help');

// 重置到欢迎页
await chatTopRef.current?.reset();

ChatButton

浮动聊天按钮组件,点击展开聊天窗口。

基础用法

import { ChatButton } from '@icos-react/largemodel';

function App() {
  return (
    <ChatButton
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
      }}
      buttonImage="/icons/chat-button.png"
    />
  );
}

Props 详解

ChatButton 继承了 ChatDemo 的所有属性,并新增以下属性:

| 属性 | 类型 | 默认值 | 说明 | |------|------|--------|------| | buttonImage | string | - | 按钮图标 | | chatWidth | number \| string | 418 | 聊天窗口宽度(支持 px 和百分比) | | chatHeight | number \| string | 720 | 聊天窗口高度(支持 px 和百分比) | | position | Position | - | 按钮位置 | | windowPositon | Position | - | 窗口位置 | | zIndex | number | 1000 | 层级 | | onClose | () => void | - | 关闭回调 |

Position 类型

interface Position {
  top?: number | string;
  right?: number | string;
  bottom?: number | string;
  left?: number | string;
}

尺寸模式

1. 固定像素(传统方式)

<ChatButton
  chatWidth={418}
  chatHeight={720}
/>

2. 百分比自适应(推荐)

<ChatButton
  chatWidth="40vw"    // 视口宽度的 40%
  chatHeight="85vh"   // 视口高度的 85%
/>

3. 混合使用

<ChatButton
  chatWidth="50vw"    // 百分比宽度
  chatHeight={600}    // 固定高度
/>

完整示例

import React, { useRef } from 'react';
import { ChatButton } from '@icos-react/largemodel';

function App() {
  const chatButtonRef = useRef<any>(null);

  return (
    <ChatButton
      ref={chatButtonRef}
      chatWidth="40vw"
      chatHeight="85vh"
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
      }}
      position={{
        right: '20px',
        bottom: '20px',
      }}
      windowPositon={{
        right: '20px',
        bottom: '80px',
      }}
      buttonImage="/icons/chat.png"
      onClose={() => console.log('窗口关闭')}
      customStyle={{
        window: {
          background: 'url(/bg.png) no-repeat',
          backgroundSize: 'cover',
          borderRadius: '12px',
        },
      }}
    />
  );
}

ChatAssistant

智能助手组件,集成了数字人和多种交互功能。

基础用法

import { ChatAssistant } from '@icos-react/largemodel';

function App() {
  return (
    <ChatAssistant
      apiInfo={{
        url: '/api/chat',
        method: 'POST',
      }}
      showDigitalHuman={true}
      digitalHumanUrl="https://example.com/digital-human"
    />
  );
}

Props 详解

ChatAssistant 继承了 ChatTop 的所有属性,并新增数字人相关配置。


CustomInput

自定义输入框组件,支持富文本、前缀按钮等功能。

基础用法

import CustomInput from '@icos-react/largemodel';

function App() {
  const [value, setValue] = useState('');

  return (
    <CustomInput
      value={value}
      onChange={(e) => setValue(e.target.value)}
      placeholder="请输入内容"
      onPressEnter={() => console.log('发送:', value)}
    />
  );
}

Props 详解

| 属性 | 类型 | 说明 | |------|------|------| | value | string | 输入值 | | onChange | (e: { target: { value: string } }) => void | 变化回调 | | onPressEnter | (e: KeyboardEvent) => void | 按下回车回调 | | placeholder | string | 占位符 | | disabled | boolean | 是否禁用 | | prefixButton | ReactNode | 前缀按钮 | | initialValue | InitialValue[] | 初始值配置 |

带前缀按钮示例

import CustomInput from '@icos-react/largemodel';

function App() {
  const [value, setValue] = useState('');
  const [selectedType, setSelectedType] = useState('');

  const prefixButton = (
    <Select
      value={selectedType}
      onChange={setSelectedType}
      options={[
        { label: '文本', value: 'text' },
        { label: '代码', value: 'code' },
      ]}
    />
  );

  return (
    <CustomInput
      value={value}
      onChange={(e) => setValue(e.target.value)}
      prefixButton={prefixButton}
      placeholder="请输入内容"
    />
  );
}

Hooks

useSafeTimeout

安全的定时器 Hook,自动清理防止内存泄漏。

import { useSafeTimeout } from '@icos-react/largemodel';

function MyComponent() {
  const { setSafeTimeout, clearSafeTimeout, clearAllTimeouts } = useSafeTimeout();

  const handleClick = () => {
    // 自动清理
    setSafeTimeout(() => {
      console.log('延迟执行');
    }, 1000);
  };

  return <button onClick={handleClick}>点击</button>;
}

useFocusManagement

焦点管理 Hook,统一管理输入框焦点。

import { useFocusManagement } from '@icos-react/largemodel';

function MyInput() {
  const { elementRef, focus, setCursorPosition } = useFocusManagement({
    disabled: false,
    onFocus: () => console.log('获得焦点'),
  });

  useEffect(() => {
    focus(100, true); // 延迟100ms聚焦,光标移到末尾
  }, []);

  return <div ref={elementRef} contentEditable />;
}

useChatScrollOptimized

优化的滚动 Hook,性能提升 60%。

import { useChatScrollOptimized } from '@icos-react/largemodel';

function ChatMessages({ messages }) {
  const {
    messagesEndRef,
    messagesContainerRef,
    scrollToBottom,
    temporarilyDisableScroll,
  } = useChatScrollOptimized({
    messages,
    onLoadMore: handleLoadMore,
    hasMore: true,
  });

  return (
    <div ref={messagesContainerRef}>
      {messages.map(msg => <Message key={msg.id} {...msg} />)}
      <div ref={messagesEndRef} />
    </div>
  );
}

useStableCallback

稳定的回调 Hook,解决 useEffect 依赖问题。

import { useStableCallback } from '@icos-react/largemodel';

function MyComponent() {
  const [count, setCount] = useState(0);

  // 引用永远不变,但内部总是使用最新的 count
  const handleClick = useStableCallback(() => {
    console.log('当前计数:', count);
  });

  useEffect(() => {
    element.addEventListener('click', handleClick);
    return () => element.removeEventListener('click', handleClick);
  }, [handleClick]); // ✅ 不会导致无限循环

  return <button onClick={() => setCount(c => c + 1)}>+1</button>;
}

工具函数

样式工具

import {
  mergeStyles,
  mergeClassNames,
  conditionalStyle,
  toPx,
} from '@icos-react/largemodel/utils/styleUtils';

// 合并样式
const style = mergeStyles(baseStyle, customStyle);

// 合并类名
const className = mergeClassNames('base', isActive && 'active');

// 条件样式
const buttonStyle = conditionalStyle(isActive, activeStyle, inactiveStyle);

// 转换为 px
const width = toPx(100); // '100px'

通用工具

import {
  debounce,
  throttle,
  retry,
  copyToClipboard,
  formatTime,
} from '@icos-react/largemodel/utils/commonUtils';

// 防抖
const debouncedFn = debounce(fn, 300);

// 节流
const throttledFn = throttle(fn, 100);

// 重试
const data = await retry(() => fetch('/api'), { maxAttempts: 3 });

// 复制到剪贴板
await copyToClipboard('文本');

// 格式化时间
const timeStr = formatTime(new Date()); // "5分钟前"

自定义样式

所有组件都支持通过 customStyle 属性自定义样式。

CustomStyle 类型

interface CustomStyle {
  container?: React.CSSProperties;
  messageList?: React.CSSProperties;
  inputContainer?: React.CSSProperties;
  customInput?: React.CSSProperties;
  sendButton?: React.CSSProperties;
  // ... 更多样式选项
}

示例

<ChatDemo
  customStyle={{
    container: {
      background: 'linear-gradient(to bottom, #f0f0f0, #fff)',
      borderRadius: '12px',
      padding: '20px',
    },
    messageList: {
      maxHeight: '600px',
      overflowY: 'auto',
    },
    inputContainer: {
      border: '2px solid #1890ff',
      borderRadius: '8px',
    },
    sendButton: {
      background: '#1890ff',
      color: '#fff',
    },
  }}
/>

性能优化建议

1. 使用优化版本

// ✅ 推荐
import { ChatDemoRefactored as ChatDemo } from '@icos-react/largemodel';

// ⚠️ 不推荐
import { ChatDemo } from '@icos-react/largemodel';

2. 缓存配置对象

const apiInfo = useMemo(() => ({
  url: '/api/chat',
  method: 'POST',
}), []);

<ChatDemo apiInfo={apiInfo} />

3. 使用 useCallback

const handleEventChange = useCallback((data) => {
  console.log(data);
}, []);

<ChatDemo onEventChange={handleEventChange} />

常见问题

Q: 如何从旧版本迁移?

A: 只需更改导入即可,API 完全兼容:

import { ChatDemoRefactored as ChatDemo } from '@icos-react/largemodel';

Q: 如何自定义消息样式?

A: 使用 customStyle 属性:

<ChatDemo
  customStyle={{
    messageList: { padding: '20px' },
    // ... 其他样式
  }}
/>

Q: 如何处理消息操作?

A: 使用 messageActionCallbacks

<ChatDemo
  enableMessageActions={true}
  messageActionCallbacks={{
    onLike: handleLike,
    onCopy: handleCopy,
  }}
/>

📊 性能数据

| 指标 | 优化前 | 优化后 | 改善 | |------|--------|--------|------| | 首次渲染 | 850ms | 520ms | ↓ 38.8% | | 新增消息 | 120ms | 45ms | ↓ 62.5% | | 内存占用 | 85MB | 62MB | ↓ 27.1% | | 滚动流畅度 | 45 FPS | 58 FPS | ↑ 28.9% |


📄 许可证

MIT License


最后更新: 2025-11-18
版本: v0.6.0
维护团队: @icos-react/largemodel team