react-markdown-typer 0.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.zh.md ADDED
@@ -0,0 +1,846 @@
1
+ # react-markdown-typer
2
+
3
+ > 🚀 高性能 React Markdown 打字动画组件,完美复刻 DeepSeek 聊天界面效果
4
+
5
+ **🇨🇳 中文 | [🇺🇸 English](./README.en.md) | [🇯🇵 日本語](./README.ja.md) | [🇰🇷 한국어](./README.ko.md)**
6
+
7
+ 一个专为现代 AI 应用设计的 React 组件,提供流畅的实时打字动画和完整的 Markdown 渲染能力。
8
+
9
+ [![npm version](https://img.shields.io/npm/v/react-markdown-typer)](https://www.npmjs.com/package/react-markdown-typer)
10
+ [![npm downloads](https://img.shields.io/npm/dm/react-markdown-typer.svg)](https://www.npmjs.com/package/react-markdown-typer)
11
+ [![bundle size](https://img.shields.io/bundlephobia/minzip/react-markdown-typer)](https://bundlephobia.com/package/react-markdown-typer)
12
+ [![React](https://img.shields.io/badge/React-16.8+-blue)](https://react.dev)
13
+ [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)](https://www.typescriptlang.org/)
14
+
15
+ [📖 在线演示](https://onshinpei.github.io/react-markdown-typer/)
16
+
17
+ [DEMO:🔧 StackBlitz 体验](https://stackblitz.com/edit/vitejs-vite-ddfw8avb?file=src%2FApp.tsx)
18
+
19
+ ---
20
+
21
+ ## ❓ 为什么要用 react-markdown-typer?
22
+
23
+ - **后端流式数据完美适配**
24
+ 很多 AI/LLM 后端接口(如 OpenAI、DeepSeek 等)推送的数据 chunk 往往一次包含多个字符,普通打字机实现会出现卡顿、跳字等问题。
25
+ **react-markdown-typer 会自动将每个 chunk 拆分为单个字符,逐字流畅渲染动画,无论后端一次推送多少字,都能保证每个字都流畅打字。**
26
+
27
+ - **极致开发体验**
28
+ 丰富的命令式 API,支持流式数据、异步回调、插件扩展,开发者可灵活控制动画和内容。
29
+
30
+ - **轻量高性能**
31
+ 体积小、性能优,适配移动端和桌面端。核心依赖 [react-markdown](https://github.com/remarkjs/react-markdown)(业界主流、成熟的 Markdown 渲染库),无其它重量级依赖,开箱即用。
32
+
33
+ - **多主题与插件化架构**
34
+ 支持亮/暗主题切换,兼容 remark/rehype 插件,满足个性化和高级扩展需求。
35
+
36
+ - **适用场景广泛**
37
+ - AI 聊天机器人/助手
38
+ - 实时问答/知识库
39
+ - 教育/数学/编程内容展示
40
+ - 产品演示、交互式文档
41
+ - 任何需要"打字机"动画和流式 Markdown 渲染的场景
42
+
43
+ ---
44
+
45
+ ## 📋 目录
46
+
47
+ - [✨ 核心特性](#-核心特性)
48
+ - [📦 快速安装](#-快速安装)
49
+ - [🚀 5分钟上手](#-5分钟上手)
50
+ - [基础用法](#基础用法)
51
+ - [禁用打字动画](#禁用打字动画)
52
+ - [数学公式支持](#数学公式支持)
53
+ - [AI 对话场景](#ai-对话场景)
54
+ - [🎯 高级回调控制](#-高级回调控制)
55
+ - [🔄 重新开始动画演示](#-重新开始动画演示)
56
+ - [▶️ 手动开始动画演示](#️-手动开始动画演示)
57
+ - [📚 完整 API 文档](#-完整-api-文档)
58
+ - [🧮 数学公式使用指南](#-数学公式使用指南)
59
+ - [🔌 插件系统](#-插件系统)
60
+ - [🎛️ 定时器模式详解](#️-定时器模式详解)
61
+ - [💡 实战示例](#-实战示例)
62
+
63
+ ---
64
+
65
+ ## ✨ 核心特性
66
+
67
+ ### 🤖 **AI 对话场景**
68
+
69
+ - 1:1 复刻 [DeepSeek 官网](https://chat.deepseek.com/) 聊天响应效果
70
+ - 支持思考过程 (`thinking`) 和回答内容 (`answer`) 双模式
71
+ - 流式数据完美适配,零延迟响应用户输入
72
+
73
+ ### 📊 **内容展示场景**
74
+
75
+ - 完整 Markdown 语法支持,包括代码高亮、表格、列表等
76
+ - 数学公式渲染 (KaTeX),支持 `$...$` 和 `\[...\]` 语法
77
+ - 支持亮色/暗色主题,适配不同产品风格
78
+ - 插件化架构,支持 remark/rehype 插件扩展
79
+
80
+ ### 🔧 **开发体验**
81
+
82
+ - 支持打字中断 `stop` 和继续 `resume`
83
+ - 支持打字关闭与开启
84
+
85
+ ### 🎬 **流畅动画**
86
+
87
+ - 双模式定时器优化,支持`requestAnimationFrame`和`setTimeout`模式
88
+ - 高频打字支持(`requestAnimationFrame`模式下打字间隔最低可接近于`0ms`)
89
+ - 帧同步渲染,与浏览器刷新完美配合
90
+ - 智能字符批量处理,视觉效果更自然
91
+
92
+ ---
93
+
94
+ ## 📦 快速安装
95
+
96
+ ```bash
97
+ # npm
98
+ npm install react-markdown-typer
99
+
100
+ # yarn
101
+ yarn add react-markdown-typer
102
+
103
+ # pnpm
104
+ pnpm add react-markdown-typer
105
+ ```
106
+
107
+ ### 通过 ESM CDN 使用
108
+
109
+ 无需安装,直接在浏览器中使用:
110
+
111
+ <!-- [DEMO](https://stackblitz.com/edit/stackblitz-starters-7vcclcw7?file=index.html) -->
112
+
113
+ ```html
114
+ <!-- 导入组件 -->
115
+ <script type="module">
116
+ import Markdown from 'https://esm.sh/react-markdown-typer';
117
+ </script>
118
+ ```
119
+
120
+ ## 🚀 5分钟上手
121
+
122
+ ### 基础用法
123
+
124
+ <!-- [DEMO](https://stackblitz.com/edit/vitejs-vite-z94syu8j?file=src%2FApp.tsx) -->
125
+
126
+ ```tsx
127
+ import MarkdownTyper from 'react-markdown-typer';
128
+ import 'react-markdown-typer/style.css';
129
+
130
+ function App() {
131
+ return (
132
+ <MarkdownTyper interval={20} answerType="answer">
133
+ # Hello react-markdown-typer 这是一个**高性能**的打字动画组件! ## 特性 - ⚡ 零延迟流式处理 - 🎬 流畅打字动画 - 🎯 完美语法支持
134
+ </MarkdownTyper>
135
+ );
136
+ }
137
+ ```
138
+
139
+ ### 禁用打字动画
140
+
141
+ ```tsx
142
+ import MarkdownTyper from 'react-markdown-typer';
143
+ import 'react-markdown-typer/style.css';
144
+
145
+ function StaticDemo() {
146
+ const [disableTyping, setDisableTyping] = useState(false);
147
+
148
+ return (
149
+ <div>
150
+ <button onClick={() => setDisableTyping(!disableTyping)}>{disableTyping ? '开启' : '关闭'}打字机效果</button>
151
+
152
+ <MarkdownTyper interval={20} disableTyping={disableTyping}>
153
+ # 静态展示模式 当 `disableTyping` 为 `true` 时,内容会立即全部显示,无打字动画效果。 这在某些场景下非常有用: - 📄 静态文档展示 - 🔄 切换显示模式 - ⚡ 快速预览内容
154
+ </MarkdownTyper>
155
+ </div>
156
+ );
157
+ }
158
+ ```
159
+
160
+ ### 数学公式支持
161
+
162
+ ```tsx
163
+ import MarkdownTyper from 'react-markdown-typer';
164
+ // 如果需要展示公式,则需要引入公式转换插件
165
+ import remarkMath from 'remark-math';
166
+ import rehypeKatex from 'rehype-katex';
167
+
168
+ function MathDemo() {
169
+ return (
170
+ <MarkdownTyper interval={20} reactMarkdownProps={{ remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex] }} math={{ splitSymbol: 'dollar' }}>
171
+ # 勾股定理 在直角三角形中,斜边的平方等于两条直角边的平方和: $a^2 + b^2 = c^2$ 其中: - $a$ 和 $b$ 是直角边 - $c$ 是斜边 对于经典的"勾三股四弦五": $c = \sqrt{3 ^ (2 + 4) ^ 2} = \sqrt{25} = 5$
172
+ </MarkdownTyper>
173
+ );
174
+ }
175
+ ```
176
+
177
+ ### AI 对话场景
178
+
179
+ ```tsx
180
+ function ChatDemo() {
181
+ const [answer, setAnswer] = useState('');
182
+
183
+ const handleAsk = () => {
184
+ setAnswer(`# 关于 React 19
185
+
186
+ React 19 带来了许多激动人心的新特性:
187
+
188
+ ## 🚀 主要更新
189
+ 1. **React Compiler** - 自动优化性能
190
+ 2. **Actions** - 简化表单处理
191
+ 3. **Document Metadata** - 内置 SEO 支持
192
+
193
+ 让我们一起探索这些新功能!`);
194
+ };
195
+
196
+ return (
197
+ <div>
198
+ <button onClick={handleAsk}>询问 AI</button>
199
+
200
+ {answer && <MarkdownTyper interval={15}>{answer}</MarkdownTyper>}
201
+ </div>
202
+ );
203
+ }
204
+ ```
205
+
206
+ ### 🎯 高级回调控制
207
+
208
+ ```tsx
209
+ import { useRef, useState } from 'react';
210
+ import { MarkdownCMD, MarkdownCMDRef } from 'react-markdown-typer';
211
+
212
+ function AdvancedCallbackDemo() {
213
+ const markdownRef = useRef<MarkdownCMDRef>(null);
214
+ const [typingStats, setTypingStats] = useState({ progress: 0, currentChar: '', totalChars: 0 });
215
+
216
+ const handleBeforeTypedChar = async (data) => {
217
+ // 在字符打字前进行异步操作
218
+ console.log('即将打字:', data.currentChar);
219
+
220
+ // 可以在这里进行网络请求、数据验证等异步操作
221
+ if (data.currentChar === '!') {
222
+ await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟延迟
223
+ }
224
+ };
225
+
226
+ const handleTypedChar = (data) => {
227
+ // 更新打字统计信息
228
+ setTypingStats({
229
+ progress: Math.round(data.percent),
230
+ currentChar: data.currentChar,
231
+ totalChars: data.currentIndex + 1,
232
+ });
233
+
234
+ // 可以在这里添加音效、动画等效果
235
+ if (data.currentChar === '.') {
236
+ // 播放句号音效
237
+ console.log('播放句号音效');
238
+ }
239
+ };
240
+
241
+ const handleStart = (data) => {
242
+ console.log('开始打字:', data.currentChar);
243
+ };
244
+
245
+ const handleEnd = (data) => {
246
+ console.log('打字完成:', data.str);
247
+ };
248
+
249
+ const startDemo = () => {
250
+ markdownRef.current?.clear();
251
+ markdownRef.current?.push(
252
+ '# 高级回调演示\n\n' +
253
+ '这个示例展示了如何使用 `onBeforeTypedChar` 和 `onTypedChar` 回调:\n\n' +
254
+ '- 🎯 **打字前回调**:可以在字符显示前进行异步操作\n' +
255
+ '- 📊 **打字后回调**:可以实时更新进度和添加特效\n' +
256
+ '- ⚡ **性能优化**:支持异步操作,不影响打字流畅度\n\n' +
257
+ '当前进度:' +
258
+ typingStats.progress +
259
+ '%\n' +
260
+ '已打字数:' +
261
+ typingStats.totalChars +
262
+ '\n\n' +
263
+ '这是一个非常强大的功能!',
264
+ 'answer',
265
+ );
266
+ };
267
+
268
+ return (
269
+ <div>
270
+ <button onClick={startDemo}>🚀 开始高级演示</button>
271
+
272
+ <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', borderRadius: '4px' }}>
273
+ <strong>打字统计:</strong> 进度 {typingStats.progress}% | 当前字符: "{typingStats.currentChar}" | 总字符数: {typingStats.totalChars}
274
+ </div>
275
+
276
+ <MarkdownCMD ref={markdownRef} interval={30} onBeforeTypedChar={handleBeforeTypedChar} onTypedChar={handleTypedChar} onStart={handleStart} onEnd={handleEnd} />
277
+ </div>
278
+ );
279
+ }
280
+ ```
281
+
282
+ ### 🔄 重新开始动画演示
283
+
284
+ ```tsx
285
+ import { useRef, useState } from 'react';
286
+ import { MarkdownCMD, MarkdownCMDRef } from 'react-markdown-typer';
287
+
288
+ function RestartDemo() {
289
+ const markdownRef = useRef<MarkdownCMDRef>(null);
290
+ const [isPlaying, setIsPlaying] = useState(false);
291
+ const [hasStarted, setHasStarted] = useState(false);
292
+
293
+ const startContent = () => {
294
+ markdownRef.current?.clear();
295
+ markdownRef.current?.push(
296
+ '# 重新开始动画演示\n\n' +
297
+ '这个示例展示了如何使用 `restart()` 方法:\n\n' +
298
+ '- 🔄 **重新开始**:从头开始播放当前内容\n' +
299
+ '- ⏸️ **暂停恢复**:可以随时暂停和恢复\n' +
300
+ '- 🎯 **精确控制**:完全控制动画播放状态\n\n' +
301
+ '当前状态:' +
302
+ (isPlaying ? '播放中' : '已暂停') +
303
+ '\n\n' +
304
+ '这是一个非常实用的功能!',
305
+ 'answer',
306
+ );
307
+ setIsPlaying(true);
308
+ };
309
+
310
+ const handleStart = () => {
311
+ if (hasStarted) {
312
+ // 如果已经开始过,则重新开始
313
+ markdownRef.current?.restart();
314
+ } else {
315
+ // 第一次开始
316
+ markdownRef.current?.start();
317
+ setHasStarted(true);
318
+ }
319
+ setIsPlaying(true);
320
+ };
321
+
322
+ const handleStop = () => {
323
+ markdownRef.current?.stop();
324
+ setIsPlaying(false);
325
+ };
326
+
327
+ const handleResume = () => {
328
+ markdownRef.current?.resume();
329
+ setIsPlaying(true);
330
+ };
331
+
332
+ const handleRestart = () => {
333
+ markdownRef.current?.restart();
334
+ setIsPlaying(true);
335
+ };
336
+
337
+ const handleEnd = () => {
338
+ setIsPlaying(false);
339
+ };
340
+
341
+ return (
342
+ <div>
343
+ <div style={{ marginBottom: '10px', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
344
+ <button onClick={startContent}>🚀 开始内容</button>
345
+ <button onClick={handleStart} disabled={isPlaying}>
346
+ {hasStarted ? '🔄 重新开始' : '▶️ 开始'}
347
+ </button>
348
+ <button onClick={handleStop} disabled={!isPlaying}>
349
+ ⏸️ 暂停
350
+ </button>
351
+ <button onClick={handleResume} disabled={isPlaying}>
352
+ ▶️ 恢复
353
+ </button>
354
+ <button onClick={handleRestart}>🔄 重新开始</button>
355
+ </div>
356
+
357
+ <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', borderRadius: '4px' }}>
358
+ <strong>动画状态:</strong> {isPlaying ? '🟢 播放中' : '🔴 已暂停'}
359
+ </div>
360
+
361
+ <MarkdownCMD ref={markdownRef} interval={25} onEnd={handleEnd} />
362
+ </div>
363
+ );
364
+ }
365
+ ```
366
+
367
+ ### ▶️ 手动开始动画演示
368
+
369
+ ```tsx
370
+ import { useRef, useState } from 'react';
371
+ import { MarkdownCMD, MarkdownCMDRef } from 'react-markdown-typer';
372
+
373
+ function StartDemo() {
374
+ const markdownRef = useRef<MarkdownCMDRef>(null);
375
+ const [isPlaying, setIsPlaying] = useState(false);
376
+ const [hasStarted, setHasStarted] = useState(false);
377
+
378
+ const loadContent = () => {
379
+ markdownRef.current?.clear();
380
+ markdownRef.current?.push(
381
+ '# 手动开始动画演示\n\n' +
382
+ '这个示例展示了如何使用 `start()` 方法:\n\n' +
383
+ '- 🎯 **手动控制**:当 `autoStartTyping=false` 时,需要手动调用 `start()`\n' +
384
+ '- ⏱️ **延迟开始**:可以在用户交互后开始动画\n' +
385
+ '- 🎮 **游戏化**:适合需要用户主动触发的场景\n\n' +
386
+ '点击"开始动画"按钮来手动启动打字效果!',
387
+ 'answer',
388
+ );
389
+ setIsPlaying(false);
390
+ };
391
+
392
+ const handleStart = () => {
393
+ if (hasStarted) {
394
+ // 如果已经开始过,则重新开始
395
+ markdownRef.current?.restart();
396
+ } else {
397
+ // 第一次开始
398
+ markdownRef.current?.start();
399
+ setHasStarted(true);
400
+ }
401
+ setIsPlaying(true);
402
+ };
403
+
404
+ const handleEnd = () => {
405
+ setIsPlaying(false);
406
+ };
407
+
408
+ return (
409
+ <div>
410
+ <div style={{ marginBottom: '10px', display: 'flex', gap: '10px', flexWrap: 'wrap' }}>
411
+ <button onClick={loadContent}>📝 加载内容</button>
412
+ <button onClick={handleStart} disabled={isPlaying}>
413
+ {hasStarted ? '🔄 重新开始' : '▶️ 开始动画'}
414
+ </button>
415
+ </div>
416
+
417
+ <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', borderRadius: '4px' }}>
418
+ <strong>状态:</strong> {isPlaying ? '🟢 动画播放中' : '🔴 等待开始'}
419
+ </div>
420
+
421
+ <MarkdownCMD ref={markdownRef} interval={30} autoStartTyping={false} onEnd={handleEnd} />
422
+ </div>
423
+ );
424
+ }
425
+ ```
426
+
427
+ ---
428
+
429
+ ## 📚 完整 API 文档
430
+
431
+ ### 默认导出 MarkdownTyper 和 MarkdownCMD 的 props
432
+
433
+ ```js
434
+ import MarkdownTyper, { MarkdownCMD } from 'react-markdown-typer';
435
+ ```
436
+
437
+ | 属性 | 类型 | 说明 | 默认值 |
438
+ | ------------------- | ------------------------------------------- | ------------------------------------------------------------- | ----------------------------------------------------------- |
439
+ | `interval` | `number` | 打字间隔 (毫秒) | `30` |
440
+ | `timerType` | `'setTimeout'` \| `'requestAnimationFrame'` | 定时器类型,不支持动态修改 | 当前默认值是`setTimeout`,后期会改为`requestAnimationFrame` |
441
+ | `theme` | `'light'` \| `'dark'` | 主题类型 | `'light'` |
442
+ | `plugins` | `IMarkdownPlugin[]` | 插件配置 | `[]` |
443
+ | `math` | [IMarkdownMath](#IMarkdownMath) | 数学公式配置 | `{ splitSymbol: 'dollar' }` |
444
+ | `onEnd` | `(data: EndData) => void` | 打字结束回调 | - |
445
+ | `onStart` | `(data: StartData) => void` | 打字开始回调 | - |
446
+ | `onBeforeTypedChar` | `(data: IBeforeTypedChar) => Promise<void>` | 字符打字前的回调,支持异步操作,会阻塞之后的打字 | - |
447
+ | `onTypedChar` | `(data: ITypedChar) => void` | 每字符打字后的回调 | - |
448
+ | `disableTyping` | `boolean` | 禁用打字动画效果 | `false` |
449
+ | `autoStartTyping` | `boolean` | 是否自动开始打字动画,设为 false 时需手动触发,不支持动态修改 | `true` |
450
+
451
+ > 注意: 如果当在打字中 `disableTyping`从 `true` 变为 `false`,则在下一个打字触发时,会把剩下的所有字一次性显示
452
+
453
+ ### IBeforeTypedChar
454
+
455
+ | 属性 | 类型 | 说明 | 默认值 |
456
+ | -------------- | -------- | ---------------------------- | ------ |
457
+ | `currentIndex` | `number` | 当前字符在整个字符串中的索引 | `0` |
458
+ | `currentChar` | `string` | 当前即将打字的字符 | - |
459
+ | `prevStr` | `string` | 当前类型内容的前缀字符串 | - |
460
+ | `percent` | `number` | 打字进度百分比 (0-100) | `0` |
461
+
462
+ ### ITypedChar
463
+
464
+ | 属性 | 类型 | 说明 | 默认值 |
465
+ | -------------- | -------- | ---------------------------- | ------ |
466
+ | `currentIndex` | `number` | 当前字符在整个字符串中的索引 | `0` |
467
+ | `currentChar` | `string` | 当前已打字的字符 | - |
468
+ | `prevStr` | `string` | 当前类型内容的前缀字符串 | - |
469
+ | `currentStr` | `string` | 当前类型内容的完整字符串 | - |
470
+ | `percent` | `number` | 打字进度百分比 (0-100) | `0` |
471
+
472
+ #### IMarkdownMath
473
+
474
+ | 属性 | 类型 | 说明 | 默认值 |
475
+ | ------------- | ------------------------- | ------------------ | ---------- |
476
+ | `splitSymbol` | `'dollar'` \| `'bracket'` | 数学公式分隔符类型 | `'dollar'` |
477
+
478
+ **分隔符说明:**
479
+
480
+ - `'dollar'`:使用 `$...$` 和 `$$...$$` 语法
481
+ - `'bracket'`:使用 `\(...\)` 和 `\[...\]` 语法
482
+
483
+ #### IMarkdownPlugin
484
+
485
+ 可以通过 `reactMarkdownProps` 传入 react-markdown 所有的属性来支持
486
+
487
+ ### 组件暴露的方法
488
+
489
+ #### 默认导出 MarkdownTyper
490
+
491
+ | 方法 | 参数 | 说明 |
492
+ | --------- | ---- | -------------------------------------- |
493
+ | `start` | - | 开始打字动画 |
494
+ | `stop` | - | 暂停打字动画 |
495
+ | `resume` | - | 恢复打字动画 |
496
+ | `restart` | - | 重新开始打字动画,从头开始播放当前内容 |
497
+
498
+ #### MarkdownCMD 暴露的方法
499
+
500
+ | 方法 | 参数 | 说明 |
501
+ | ----------------- | ------------------------------------------- | -------------------------------------- |
502
+ | `push` | `(content: string, answerType: AnswerType)` | 添加内容并开始打字 |
503
+ | `clear` | - | 清空所有内容和状态 |
504
+ | `triggerWholeEnd` | - | 手动触发完成回调 |
505
+ | `start` | - | 开始打字动画 |
506
+ | `stop` | - | 暂停打字动画 |
507
+ | `resume` | - | 恢复打字动画 |
508
+ | `restart` | - | 重新开始打字动画,从头开始播放当前内容 |
509
+
510
+ **用法示例:**
511
+
512
+ ```tsx
513
+ markdownRef.current?.start(); // 开始动画
514
+ markdownRef.current?.stop(); // 暂停动画
515
+ markdownRef.current?.resume(); // 恢复动画
516
+ markdownRef.current?.restart(); // 重新开始动画
517
+ ```
518
+
519
+ ---
520
+
521
+ ## 🧮 数学公式使用指南
522
+
523
+ <!-- [DEMO1:勾股定理](https://stackblitz.com/edit/vitejs-vite-z94syu8j?file=src%2FApp.tsx) -->
524
+
525
+ <!-- [DEMO2:题目解答](https://stackblitz.com/edit/vitejs-vite-xk9lxagc?file=README.md) -->
526
+
527
+ ### 基本语法
528
+
529
+ ```tsx
530
+ import remarkMath from 'remark-math';
531
+ import rehypeKatex from 'rehype-katex';
532
+
533
+ // 1. 启用数学公式支持
534
+ <MarkdownTyper reactMarkdownProps={{ remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex]}}>
535
+ # 数学公式示例
536
+
537
+ // 行内公式
538
+ 这是一个行内公式:$E = mc^2$
539
+
540
+ // 块级公式
541
+ $$\int_{-\infty}^{\infty} e^{-x^2} dx = \sqrt{\pi}$$
542
+ </MarkdownTyper>
543
+ ```
544
+
545
+ ### 分隔符选择
546
+
547
+ ```tsx
548
+ // 使用美元符号分隔符(默认)
549
+ <MarkdownTyper
550
+ reactMarkdownProps={{ remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex]}}
551
+ math={{ splitSymbol: 'dollar' }}
552
+ >
553
+ 行内:$a + b = c$
554
+ 块级:$$\sum_{i=1}^{n} x_i = x_1 + x_2 + \cdots + x_n$$
555
+ </MarkdownTyper>
556
+
557
+ // 使用括号分隔符
558
+ <MarkdownTyper
559
+ reactMarkdownProps={{ remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex]}}
560
+ math={{ splitSymbol: 'bracket' }}
561
+ >
562
+ 行内:\(a + b = c\)
563
+ 块级:\[\sum_{i=1}^{n} x_i = x_1 + x_2 + \cdots + x_n\]
564
+ </MarkdownTyper>
565
+ ```
566
+
567
+ ### 流式数学公式
568
+
569
+ ```tsx
570
+ // 完美支持流式输出中的数学公式
571
+ const mathContent = [
572
+ '勾股定理:',
573
+ '$a^2 + b^2 = c^2$',
574
+ '\n\n',
575
+ '其中:',
576
+ '- $a$ 和 $b$ 是直角边\n',
577
+ '- $c$ 是斜边\n\n',
578
+ '对于经典的"勾三股四弦五":\n',
579
+ '$c = \\sqrt{3^2 + 4^2} = \\sqrt{25} = 5$\n\n',
580
+ '这个定理在几何学中有着广泛的应用!',
581
+ ];
582
+
583
+ mathContent.forEach((chunk) => {
584
+ markdownRef.current?.push(chunk, 'answer');
585
+ });
586
+ ```
587
+
588
+ ### 样式定制
589
+
590
+ ```css
591
+ /* 数学公式样式定制 */
592
+ .katex {
593
+ font-size: 1.1em;
594
+ }
595
+
596
+ .katex-display {
597
+ margin: 1em 0;
598
+ text-align: center;
599
+ }
600
+
601
+ /* 暗色主题适配 */
602
+ [data-theme='dark'] .katex {
603
+ color: #e1e1e1;
604
+ }
605
+ ```
606
+
607
+ ---
608
+
609
+ ## 🔌 插件系统
610
+
611
+ 可查看 [react-markdown](https://github.com/remarkjs/react-markdown)
612
+
613
+ ---
614
+
615
+ ## 🎛️ 定时器模式详解
616
+
617
+ ### `requestAnimationFrame` 模式 🌟 (推荐)
618
+
619
+ ```typescript
620
+ // 🎯 特性
621
+ - 时间驱动:基于真实经过时间计算字符数量
622
+ - 批量处理:单帧内可处理多个字符
623
+ - 帧同步:与浏览器 60fps 刷新率同步
624
+ - 高频优化:完美支持 interval < 16ms 的高速打字
625
+
626
+ // 🎯 适用场景
627
+ - 现代 Web 应用的默认选择
628
+ - 追求流畅动画效果
629
+ - 高频打字 (interval > 0 即可)
630
+ - AI 实时对话场景
631
+ ```
632
+
633
+ ### `setTimeout` 模式 📟 (兼容)
634
+
635
+ ```typescript
636
+ // 🎯 特性
637
+ - 单字符:每次精确处理一个字符
638
+ - 固定间隔:严格按设定时间执行
639
+ - 节拍感:经典打字机的节奏感
640
+ - 精确控制:适合特定时序要求
641
+
642
+ // 🎯 适用场景
643
+ - 需要精确时间控制
644
+ - 营造复古打字机效果
645
+ - 兼容性要求较高的场景
646
+ ```
647
+
648
+ ### 📊 性能对比
649
+
650
+ | 特性 | requestAnimationFrame | setTimeout |
651
+ | ------------ | ---------------------------- | ---------------- |
652
+ | **字符处理** | 每帧可处理多个字符 | 每次处理一个字符 |
653
+ | **高频间隔** | ✅ 优秀 (5ms → 每帧3字符) | ❌ 可能卡顿 |
654
+ | **低频间隔** | ✅ 正常 (100ms → 6帧后1字符) | ✅ 精确 |
655
+ | **视觉效果** | 🎬 流畅动画感 | ⚡ 精确节拍感 |
656
+ | **性能开销** | 🟢 低 (帧同步) | 🟡 中等 (定时器) |
657
+
658
+ 高频推荐`requestAnimationFrame`,低频推荐 `setTimeout`
659
+
660
+ ---
661
+
662
+ ## 💡 实战示例
663
+
664
+ ### 📝 AI 流式对话
665
+
666
+ <!-- [DEMO: 🔧 StackBlitz 体验](https://stackblitz.com/edit/vitejs-vite-2ri8kex3?file=src%2FApp.tsx) -->
667
+
668
+ ````tsx
669
+ import { useRef } from 'react';
670
+ import { MarkdownCMD, MarkdownCMDRef } from 'react-markdown-typer';
671
+
672
+ function StreamingChat() {
673
+ const markdownRef = useRef<MarkdownCMDRef>(null);
674
+
675
+ // 模拟 AI 流式响应
676
+ const simulateAIResponse = async () => {
677
+ markdownRef.current?.clear();
678
+
679
+ // 思考阶段
680
+ markdownRef.current?.push('🤔 正在分析您的问题...', 'thinking');
681
+ await delay(1000);
682
+ markdownRef.current?.push('\n\n✅ 分析完成,开始回答', 'thinking');
683
+
684
+ // 流式回答
685
+ const chunks = [
686
+ '# React 19 新特性解析\n\n',
687
+ '## 🚀 React Compiler\n',
688
+ 'React 19 最大的亮点是引入了 **React Compiler**:\n\n',
689
+ '- 🎯 **自动优化**:无需手动 memo 和 useMemo\n',
690
+ '- ⚡ **性能提升**:编译时优化,运行时零开销\n',
691
+ '- 🔧 **向后兼容**:现有代码无需修改\n\n',
692
+ '## 📝 Actions 简化表单\n',
693
+ '新的 Actions API 让表单处理变得更简单:\n\n',
694
+ '```tsx\n',
695
+ 'function ContactForm({ action }) {\n',
696
+ ' const [state, formAction] = useActionState(action, null);\n',
697
+ ' return (\n',
698
+ ' <form action={formAction}>\n',
699
+ ' <input name="email" type="email" />\n',
700
+ ' <button>提交</button>\n',
701
+ ' </form>\n',
702
+ ' );\n',
703
+ '}\n',
704
+ '```\n\n',
705
+ '希望这个解答对您有帮助!🎉',
706
+ ];
707
+
708
+ for (const chunk of chunks) {
709
+ await delay(100);
710
+ markdownRef.current?.push(chunk, 'answer');
711
+ }
712
+ };
713
+
714
+ return (
715
+ <div className="chat-container">
716
+ <button onClick={simulateAIResponse}>🤖 询问 React 19 新特性</button>
717
+
718
+ <MarkdownCMD ref={markdownRef} interval={10} timerType="requestAnimationFrame" onEnd={(data) => console.log('段落完成:', data)} />
719
+ </div>
720
+ );
721
+ }
722
+
723
+ const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
724
+ ````
725
+
726
+ ### 🧮 数学公式流式渲染
727
+
728
+ ```tsx
729
+ import remarkMath from 'remark-math';
730
+ import rehypeKatex from 'rehype-katex';
731
+
732
+ function MathStreamingDemo() {
733
+ const markdownRef = useRef<MarkdownCMDRef>(null);
734
+
735
+ const simulateMathResponse = async () => {
736
+ markdownRef.current?.clear();
737
+
738
+ const mathChunks = [
739
+ '# 勾股定理详解\n\n',
740
+ '在直角三角形中,斜边的平方等于两条直角边的平方和:\n\n',
741
+ '$a^2 + b^2 = c^2$\n\n',
742
+ '其中:\n',
743
+ '- $a$ 和 $b$ 是直角边\n',
744
+ '- $c$ 是斜边\n\n',
745
+ '对于经典的"勾三股四弦五":\n',
746
+ '$c = \\sqrt{3^2 + 4^2} = \\sqrt{25} = 5$\n\n',
747
+ '这个定理在几何学中有着广泛的应用!',
748
+ ];
749
+
750
+ for (const chunk of mathChunks) {
751
+ await delay(150);
752
+ markdownRef.current?.push(chunk, 'answer');
753
+ }
754
+ };
755
+
756
+ return (
757
+ <div>
758
+ <button onClick={simulateMathResponse}>📐 讲解勾股定理</button>
759
+
760
+ <MarkdownCMD
761
+ ref={markdownRef}
762
+ interval={20}
763
+ timerType="requestAnimationFrame"
764
+ reactMarkdownProps={{ remarkPlugins: [remarkMath], rehypePlugins: [rehypeKatex] }}
765
+ math={{ splitSymbol: 'dollar' }}
766
+ />
767
+ </div>
768
+ );
769
+ }
770
+ ```
771
+
772
+ ### 🎯 高级回调控制
773
+
774
+ ```tsx
775
+ import { useRef, useState } from 'react';
776
+ import { MarkdownCMD, MarkdownCMDRef } from 'react-markdown-typer';
777
+
778
+ function AdvancedCallbackDemo() {
779
+ const markdownRef = useRef<MarkdownCMDRef>(null);
780
+ const [typingStats, setTypingStats] = useState({ progress: 0, currentChar: '', totalChars: 0 });
781
+
782
+ const handleBeforeTypedChar = async (data) => {
783
+ // 在字符打字前进行异步操作
784
+ console.log('即将打字:', data.currentChar);
785
+
786
+ // 可以在这里进行网络请求、数据验证等异步操作
787
+ if (data.currentChar === '!') {
788
+ await new Promise((resolve) => setTimeout(resolve, 500)); // 模拟延迟
789
+ }
790
+ };
791
+
792
+ const handleTypedChar = (data) => {
793
+ // 更新打字统计信息
794
+ setTypingStats({
795
+ progress: Math.round(data.percent),
796
+ currentChar: data.currentChar,
797
+ totalChars: data.currentIndex + 1,
798
+ });
799
+
800
+ // 可以在这里添加音效、动画等效果
801
+ if (data.currentChar === '.') {
802
+ // 播放句号音效
803
+ console.log('播放句号音效');
804
+ }
805
+ };
806
+
807
+ const handleStart = (data) => {
808
+ console.log('开始打字:', data.currentChar);
809
+ };
810
+
811
+ const handleEnd = (data) => {
812
+ console.log('打字完成:', data.str);
813
+ };
814
+
815
+ const startDemo = () => {
816
+ markdownRef.current?.clear();
817
+ markdownRef.current?.push(
818
+ '# 高级回调演示\n\n' +
819
+ '这个示例展示了如何使用 `onBeforeTypedChar` 和 `onTypedChar` 回调:\n\n' +
820
+ '- 🎯 **打字前回调**:可以在字符显示前进行异步操作\n' +
821
+ '- 📊 **打字后回调**:可以实时更新进度和添加特效\n' +
822
+ '- ⚡ **性能优化**:支持异步操作,不影响打字流畅度\n\n' +
823
+ '当前进度:' +
824
+ typingStats.progress +
825
+ '%\n' +
826
+ '已打字数:' +
827
+ typingStats.totalChars +
828
+ '\n\n' +
829
+ '这是一个非常强大的功能!',
830
+ 'answer',
831
+ );
832
+ };
833
+
834
+ return (
835
+ <div>
836
+ <button onClick={startDemo}>🚀 开始高级演示</button>
837
+
838
+ <div style={{ margin: '10px 0', padding: '10px', background: '#f5f5f5', borderRadius: '4px' }}>
839
+ <strong>打字统计:</strong> 进度 {typingStats.progress}% | 当前字符: "{typingStats.currentChar}" | 总字符数: {typingStats.totalChars}
840
+ </div>
841
+
842
+ <MarkdownCMD ref={markdownRef} interval={30} onBeforeTypedChar={handleBeforeTypedChar} onTypedChar={handleTypedChar} onStart={handleStart} onEnd={handleEnd} />
843
+ </div>
844
+ );
845
+ }
846
+ ```