ds-markdown 1.0.0 β†’ 1.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.en.md DELETED
@@ -1,753 +0,0 @@
1
- # ds-markdown
2
-
3
- > πŸš€ React Markdown typing animation component for modern chat interface effects
4
-
5
- **πŸ‡ΊπŸ‡Έ English | [πŸ‡¨πŸ‡³ δΈ­ζ–‡](./README.md)**
6
-
7
- A React component designed specifically for modern AI applications, providing smooth real-time typing animations and complete Markdown rendering capabilities.
8
-
9
- [![npm version](https://img.shields.io/npm/v/ds-markdown)](https://www.npmjs.com/package/ds-markdown)
10
- [![npm downloads](https://img.shields.io/npm/dm/ds-markdown.svg)](https://www.npmjs.com/package/ds-markdown)
11
- [![bundle size](https://img.shields.io/bundlephobia/minzip/ds-markdown)](https://bundlephobia.com/package/ds-markdown)
12
- [![React](https://img.shields.io/badge/React-18.0.0+-blue)](https://react.dev)
13
- [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue)](https://www.typescriptlang.org/)
14
-
15
- - [Documentation](https://onshinpei.github.io/ds-markdown/)
16
- - Usage Examples
17
- - [Basic Usage](https://stackblitz.com/edit/vitejs-vite-ddfw8avb?file=src%2FApp.tsx)
18
- - [Streaming Data Usage](https://stackblitz.com/edit/vitejs-vite-2ri8kex3?file=src%2FApp.tsx)
19
- - [Mermaid Charts](https://stackblitz.com/edit/vitejs-vite-iqbyta3j?file=index.html)
20
- - [Math Formulas Demo 1](https://stackblitz.com/edit/vitejs-vite-iqbyta3j?file=index.html)
21
- - [Math Formulas Demo 2](https://stackblitz.com/edit/vitejs-vite-xk9lxagc?file=src%2FApp.tsx)
22
-
23
- If you want a clean `react markdown` typing component, you can use [react-markdown-typer](https://github.com/onshinpei/react-markdown-typer)
24
-
25
- ---
26
-
27
- ## ❓ Why use ds-markdown?
28
-
29
- ### 🎯 **Core Problems Solved**
30
-
31
- - **Streaming Data Typing Stuttering Issues**
32
- Traditional typewriter components experience stuttering and character jumping when processing AI backend streaming data, as each chunk contains multiple characters. ds-markdown intelligently splits each chunk to ensure smooth typing for every character.
33
-
34
- - **Markdown Rendering and Typing Animation Disconnection**
35
- Most typewriter components only support plain text and cannot render Markdown syntax, mathematical formulas, charts, and other rich media content in real-time during typing.
36
-
37
- ### πŸš€ **Value Delivered**
38
-
39
- - **Enhanced User Immersion**
40
- Provides professional-level AI chat experience, allowing users to feel authentic AI interaction processes, greatly improving product professionalism and user satisfaction.
41
-
42
- - **Out-of-the-box, Reduces Development Complexity**
43
- Complete solution that requires no additional configuration to support streaming data, Markdown rendering, mathematical formulas, charts, and other complex features.
44
-
45
- - **Adapts to Multiple Application Scenarios**
46
- From AI chatbots to educational content display, from technical documentation to product demos, one component meets multiple needs.
47
-
48
- ---
49
-
50
- ## Table of Contents
51
-
52
- - [ds-markdown](#ds-markdown)
53
- - [❓ Why use ds-markdown?](#-why-use-ds-markdown)
54
- - [🎯 **Core Problems Solved**](#-core-problems-solved)
55
- - [πŸš€ **Value Delivered**](#-value-delivered)
56
- - [Table of Contents](#table-of-contents)
57
- - [✨ Core Features](#-core-features)
58
- - [πŸ€– **AI Chat Scenarios**](#-ai-chat-scenarios)
59
- - [πŸ“Š **Content Display Scenarios**](#-content-display-scenarios)
60
- - [🎨 **UI Component System πŸ†•**](#-ui-component-system-)
61
- - [πŸ”§ **Development Experience**](#-development-experience)
62
- - [🎬 **Smooth Animation**](#-smooth-animation)
63
- - [⚑ **Performance Optimization**](#-performance-optimization)
64
- - [πŸ“¦ Quick Installation](#-quick-installation)
65
- - [Using via ESM CDN](#using-via-esm-cdn)
66
- - [πŸš€ 5-Minute Quick Start](#-5-minute-quick-start)
67
- - [Basic Usage](#basic-usage)
68
- - [Disable Typing Animation](#disable-typing-animation)
69
- - [Mathematical Formula Support](#mathematical-formula-support)
70
- - [AI Chat Scenarios](#ai-chat-scenarios)
71
- - [Code Block Features πŸ†•](#code-block-features-)
72
- - [Mermaid Chart Support](#mermaid-chart-support)
73
- - [πŸ“š Complete API Documentation](#-complete-api-documentation)
74
- - [Default export DsMarkdown and MarkdownCMD props](#default-export-dsmarkdown-and-markdowncmd-props)
75
- - [IBeforeTypedChar](#ibeforetypedchar)
76
- - [ITypedChar](#itypedchar)
77
- - [IMarkdownMath](#imarkdownmath)
78
- - [IMarkdownCode πŸ†•](#imarkdowncode-)
79
- - [IMarkdownPlugin](#imarkdownplugin)
80
- - [Component Exposed Methods](#component-exposed-methods)
81
- - [Default export DsMarkdown](#default-export-dsmarkdown)
82
- - [MarkdownCMD Exposed Methods](#markdowncmd-exposed-methods)
83
- - [πŸ”Œ Plugin System](#-plugin-system)
84
- - [Built-in Plugins](#built-in-plugins)
85
- - [KaTeX Mathematical Formula Plugin](#katex-mathematical-formula-plugin)
86
- - [Mermaid Chart Plugin πŸ†•](#mermaid-chart-plugin-)
87
- - [Custom Plugins](#custom-plugins)
88
- - [🎨 UI Component System πŸ†•](#-ui-component-system--1)
89
- - [Core Components](#core-components)
90
- - [Style Customization](#style-customization)
91
- - [Multi-language Configuration](#multi-language-configuration)
92
- - [πŸ’‘ Practical Examples](#-practical-examples)
93
- - [πŸ“ AI Streaming Chat](#-ai-streaming-chat)
94
- - [πŸ”§ Best Practices](#-best-practices)
95
- - [1. Performance Optimization](#1-performance-optimization)
96
- - [2. Streaming Data Processing](#2-streaming-data-processing)
97
- - [3. Mathematical Formula Optimization](#3-mathematical-formula-optimization)
98
- - [4. Mermaid Chart Best Practices πŸ†•](#4-mermaid-chart-best-practices-)
99
-
100
- ## ✨ Core Features
101
-
102
- ### πŸ€– **AI Chat Scenarios**
103
-
104
- - Professional-level AI chat response effects, comparable to mainstream AI platform experiences
105
- - Supports thinking process (`thinking`) and answer content `answer`) dual modes
106
- - Perfect streaming data adaptation with zero-delay response to user input
107
-
108
- ### πŸ“Š **Content Display Scenarios**
109
-
110
- - Complete Markdown syntax support, including code highlighting, tables, lists, etc.
111
- - Mathematical formula rendering (KaTeX), supporting `$...$` and `\[...\]` syntax
112
- - Mermaid chart support, including flowcharts, sequence diagrams, Gantt charts, class diagrams, etc. πŸ†•
113
- - Supports light/dark themes, adapting to different product styles
114
- - Plugin architecture supporting remark/rehype plugin extensions
115
-
116
- ### 🎨 **UI Component System πŸ†•**
117
-
118
- - Code block and chart enhancement features: copy, download, language, etc.
119
- - Built-in rich UI components: Button, IconButton, ToolTip, Segmented, etc.
120
- - Complete interactive experience and accessibility support
121
-
122
- ### πŸ”§ **Development Experience**
123
-
124
- - Rich imperative API: `start`, `stop`, `resume`, `restart`, etc.
125
- - Supports typing interruption and continuation, flexible control of animation states
126
- - Supports typing on/off, meeting different scenario requirements
127
- - Complete TypeScript type support
128
-
129
- ### 🎬 **Smooth Animation**
130
-
131
- - Dual-mode timer optimization, supporting `requestAnimationFrame` and `setTimeout` modes
132
- - High-frequency typing support (typing interval can be as low as close to `0ms` in `requestAnimationFrame` mode)
133
- - Frame-synchronized rendering, perfectly coordinated with browser refresh
134
- - Intelligent character batch processing for more natural visual effects
135
-
136
- ### ⚑ **Performance Optimization**
137
-
138
- - Lightweight design, small size and excellent performance
139
- - Core dependency [react-markdown](https://github.com/remarkjs/react-markdown), no heavyweight dependencies
140
-
141
- ---
142
-
143
- ## πŸ“¦ Quick Installation
144
-
145
- ```bash
146
- # npm
147
- npm install ds-markdown
148
-
149
- # yarn
150
- yarn add ds-markdown
151
-
152
- # pnpm
153
- pnpm add ds-markdown
154
- ```
155
-
156
- ### Using via ESM CDN
157
-
158
- No installation required, use directly in the browser:
159
-
160
- [DEMO](https://stackblitz.com/edit/stackblitz-starters-7vcclcw7?file=index.html)
161
-
162
- ```html
163
- <!-- Import styles, required -->
164
- <link rel="stylesheet" href="https://esm.sh/ds-markdown/dist/style.css" />
165
-
166
- <!-- Import KaTeX math formula styles, only import if needed -->
167
- <link rel="stylesheet" href="https://esm.sh/ds-markdown/dist/katex.css" />
168
-
169
- <!-- Import component -->
170
- <script type="module">
171
- import Markdown from 'https://esm.sh/ds-markdown';
172
- </script>
173
- ```
174
-
175
- ## πŸš€ 5-Minute Quick Start
176
-
177
- > βœ… Starting from v1.0+, you no longer need to manually import `ds-markdown/style.css`; the component automatically injects the required base styles.
178
-
179
- ### Basic Usage
180
-
181
- [DEMO](https://stackblitz.com/edit/vitejs-vite-z94syu8j?file=src%2FApp.tsx)
182
-
183
- ```tsx
184
- import DsMarkdown from 'ds-markdown';
185
-
186
- function App() {
187
- return (
188
- <DsMarkdown interval={20} answerType="answer">
189
- # Hello ds-markdown This is a **high-performance** typing animation component! ## Features - ⚑ Zero-delay streaming processing - 🎬 Smooth typing animation - 🎯 Perfect syntax support
190
- </DsMarkdown>
191
- );
192
- }
193
- ```
194
-
195
- ### Disable Typing Animation
196
-
197
- ```tsx
198
- import DsMarkdown from 'ds-markdown';
199
-
200
- function StaticDemo() {
201
- const [disableTyping, setDisableTyping] = useState(false);
202
-
203
- return (
204
- <div>
205
- <button onClick={() => setDisableTyping(!disableTyping)}>{disableTyping ? 'Enable' : 'Disable'} Typewriter Effect</button>
206
-
207
- <DsMarkdown interval={20} answerType="answer" disableTyping={disableTyping}>
208
- # Static Display Mode When `disableTyping` is `true`, content will be displayed immediately without typing animation effects. This is very useful in certain scenarios: - πŸ“„ Static document
209
- display - πŸ”„ Switching display modes - ⚑ Quick content preview
210
- </DsMarkdown>
211
- </div>
212
- );
213
- }
214
- ```
215
-
216
- ### Mathematical Formula Support
217
-
218
- ```tsx
219
- import DsMarkdown from 'ds-markdown';
220
- // If you need to display formulas, you need to import the formula conversion plugin
221
- import { katexPlugin } from 'ds-markdown/plugins';
222
- import 'ds-markdown/style.css';
223
- // If you need to display formulas, you need to import math formula styles
224
- import 'ds-markdown/katex.css';
225
-
226
- function MathDemo() {
227
- return (
228
- <DsMarkdown interval={20} answerType="answer" plugins={[katexPlugin]} math={{ splitSymbol: 'dollar' }}>
229
- # Pythagorean Theorem In a right triangle, the square of the hypotenuse equals the sum of the squares of the two legs: $a^2 + b^2 = c^2$ Where: - $a$ and $b$ are the legs - $c$ is the hypotenuse
230
- For the classic "3-4-5 triangle": $c = \sqrt{3 ^ (2 + 4) ^ 2} = \sqrt{25} = 5$
231
- </DsMarkdown>
232
- );
233
- }
234
- ```
235
-
236
- ### AI Chat Scenarios
237
-
238
- ```tsx
239
- function ChatDemo() {
240
- const [thinking, setThinking] = useState('');
241
- const [answer, setAnswer] = useState('');
242
-
243
- const handleAsk = () => {
244
- setThinking('πŸ€” Thinking about your question...');
245
-
246
- setTimeout(() => {
247
- setAnswer(`# About React 19
248
-
249
- React 19 brings many exciting new features:
250
-
251
- ## πŸš€ Major Updates
252
- 1. **React Compiler** - Automatic performance optimization
253
- 2. **Actions** - Simplified form handling
254
- 3. **Document Metadata** - Built-in SEO support
255
-
256
- Let's explore these new features together!`);
257
- }, 2000);
258
- };
259
-
260
- return (
261
- <div>
262
- <button onClick={handleAsk}>Ask AI</button>
263
-
264
- {thinking && (
265
- <DsMarkdown answerType="thinking" interval={30}>
266
- {thinking}
267
- </DsMarkdown>
268
- )}
269
-
270
- {answer && (
271
- <DsMarkdown answerType="answer" interval={15}>
272
- {answer}
273
- </DsMarkdown>
274
- )}
275
- </div>
276
- );
277
- }
278
- ```
279
-
280
- ### Code Block Features πŸ†•
281
-
282
- ```tsx
283
- import DsMarkdown from 'ds-markdown';
284
-
285
- function CodeBlockDemo() {
286
- const codeContent = `# Hello World
287
-
288
- \`\`\`javascript
289
- function greet(name) {
290
- console.log(\`Hello, \${name}!\`);
291
- }
292
-
293
- greet('ds-markdown');
294
- \`\`\`
295
-
296
- Supports code highlighting, copying, and downloading!`;
297
-
298
- return (
299
- <DsMarkdown
300
- interval={20}
301
- answerType="answer"
302
- codeBlock={{
303
- headerActions: true, // Enable code block header action buttons
304
- }}
305
- >
306
- {codeContent}
307
- </DsMarkdown>
308
- );
309
- }
310
- ```
311
-
312
- ### Mermaid Chart Support
313
-
314
- [DEMO](https://stackblitz.com/edit/vitejs-vite-iqbyta3j?file=README.md)
315
-
316
- ```tsx
317
- import DsMarkdown from 'ds-markdown';
318
- import { ConfigProvider } from 'ds-markdown';
319
- import mermaidPlugin from 'ds-markdown-mermaid-plugin';
320
- import 'ds-markdown/style.css';
321
-
322
- function MermaidDemo() {
323
- const chartContent = `Here's a simplified learning to drive flowchart, keeping only the **most core steps**, suitable for quickly mastering key nodes:
324
-
325
- \`\`\`mermaid
326
- graph TD
327
- A[Start] --> B[Subject 1: Theory Exam]
328
- B --> C[Subject 2: Field Five Items]
329
- C --> D[Subject 3: Road Test]
330
- D --> E[Subject 4: Safety Written Test]
331
- E --> F[Get Driver's License]
332
- F --> G[Actual Driving Practice]
333
- \`\`\`
334
-
335
- ### Minimalist Explanation:
336
- 1. **Theory First**: Pass traffic rules written test (Subject 1).
337
- 2. **Field Basics**: Practice reversing, hill starts, etc. (Subject 2).
338
- 3. **Road Combat**: Actual road driving test (Subject 3).
339
- 4. **Safety Finish**: Pass Subject 4 to get license.
340
- 5. **Continuous Proficiency**: Continue practicing after getting license to adapt to real road conditions.
341
-
342
- ### Visualization Suggestions:
343
- - When sketching with phone memo or white paper, write steps in **arrow order**.
344
- - Want more intuitive? Use circular sticky notes for each subject, connect them into a flow.`;
345
-
346
- return (
347
- <ConfigProvider>
348
- <DsMarkdown interval={20} answerType="answer" plugins={[mermaidPlugin]}>
349
- {chartContent}
350
- </DsMarkdown>
351
- </ConfigProvider>
352
- );
353
- }
354
- ```
355
-
356
- ![Effect Preview](./assets/images/mermaid.gif)
357
-
358
- ---
359
-
360
- ## πŸ“š Complete API Documentation
361
-
362
- ### Default export DsMarkdown and MarkdownCMD props
363
-
364
- ```js
365
- import DsMarkdown, { MarkdownCMD } from 'ds-markdown';
366
- ```
367
-
368
- | Property | Type | Description | Default Value |
369
- | ------------------- | ------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------- |
370
- | `interval` | `number` | Typing interval (milliseconds) | `30` |
371
- | `timerType` | `'setTimeout'` \| `'requestAnimationFrame'` | Timer type, does not support dynamic modification | Current default is `setTimeout`, will change to `requestAnimationFrame` later |
372
- | `answerType` | `'thinking'` \| `'answer'` | Content type (affects style theme), does not support dynamic modification | `'answer'` |
373
- | `theme` | `'light'` \| `'dark'` | Theme type | `'light'` |
374
- | `plugins` | `IMarkdownPlugin[]` | Plugin configuration | `[]` |
375
- | `math` | [IMarkdownMath](#IMarkdownMath) | Mathematical formula configuration | `{ splitSymbol: 'dollar' }` |
376
- | `onEnd` | `(data: EndData) => void` | Typing completion callback | - |
377
- | `onStart` | `(data: StartData) => void` | Typing start callback | - |
378
- | `onBeforeTypedChar` | `(data: IBeforeTypedChar) => Promise<void>` | Callback before character typing, supports async operations, blocks subsequent typing | - |
379
- | `onTypedChar` | `(data: ITypedChar) => void` | Callback after each character typing | - |
380
- | `disableTyping` | `boolean` | Disable typing animation effects | `false` |
381
- | `autoStartTyping` | `boolean` | Whether to automatically start typing animation, set to false for manual trigger, does not support dynamic modification | `true` |
382
- | `codeBlock` | `IMarkdownCode` | Code block configuration | `{headerActions: true}` |
383
-
384
- > Note: If `disableTyping` changes from `true` to `false` during typing
385
-
386
- ### IBeforeTypedChar
387
-
388
- | Property | Type | Description | Default Value |
389
- | -------------- | ------------ | -------------------------------------------- | ------------- |
390
- | `currentIndex` | `number` | Current character index in the entire string | `0` |
391
- | `currentChar` | `string` | Current character about to be typed | - |
392
- | `answerType` | `AnswerType` | Content type (thinking/answer) | - |
393
- | `prevStr` | `string` | Prefix string of current type content | - |
394
- | `percent` | `number` | Typing progress percentage (0-100) | `0` |
395
-
396
- ### ITypedChar
397
-
398
- | Property | Type | Description | Default Value |
399
- | -------------- | ------------ | -------------------------------------------- | ------------- |
400
- | `currentIndex` | `number` | Current character index in the entire string | `0` |
401
- | `currentChar` | `string` | Current typed character | - |
402
- | `answerType` | `AnswerType` | Content type (thinking/answer) | - |
403
- | `prevStr` | `string` | Prefix string of current type content | - |
404
- | `currentStr` | `string` | Complete string of current type content | - |
405
- | `percent` | `number` | Typing progress percentage (0-100) | `0` |
406
-
407
- #### IMarkdownMath
408
-
409
- | Property | Type | Description | Default Value |
410
- | ------------- | ------------------------- | --------------------------- | ------------- |
411
- | `splitSymbol` | `'dollar'` \| `'bracket'` | Math formula delimiter type | `'dollar'` |
412
-
413
- **Delimiter Description:**
414
-
415
- - `'dollar'`: Uses `$...$` and `$$...$$` syntax
416
- - `'bracket'`: Uses `\(...\)` and `\[...\]` syntax
417
-
418
- #### IMarkdownCode πŸ†•
419
-
420
- | Property | Type | Description | Default Value |
421
- | --------------- | --------- | ------------------------------------- | ------------- |
422
- | `headerActions` | `boolean` | Whether to show header action buttons | `true` |
423
-
424
- #### IMarkdownPlugin
425
-
426
- | Property | Type | Description | Default Value |
427
- | -------------- | ---------------------------------------------- | --------------------------- | ------------- |
428
- | `remarkPlugin` | `Pluggable` | remark plugin | - |
429
- | `rehypePlugin` | `Pluggable` | rehype plugin | - |
430
- | `type` | `'buildIn'` \| `'custom'` | Plugin type | - |
431
- | `id` | `any` | Plugin unique identifier | - |
432
- | `components` | `Record<string, React.ComponentType<unknown>>` | Custom component mapping πŸ†• | - |
433
-
434
- ### Component Exposed Methods
435
-
436
- #### Default export DsMarkdown
437
-
438
- | Method | Parameters | Description |
439
- | --------- | ---------- | ------------------------------------------------------------- |
440
- | `start` | - | Start typing animation |
441
- | `stop` | - | Pause typing animation |
442
- | `resume` | - | Resume typing animation |
443
- | `restart` | - | Restart typing animation, play current content from beginning |
444
-
445
- #### MarkdownCMD Exposed Methods
446
-
447
- | Method | Parameters | Description |
448
- | ----------------- | ------------------------------------------- | ------------------------------------------------------------- |
449
- | `push` | `(content: string, answerType: AnswerType)` | Add content and start typing |
450
- | `clear` | - | Clear all content and state |
451
- | `triggerWholeEnd` | - | Manually trigger completion callback |
452
- | `start` | - | Start typing animation |
453
- | `stop` | - | Pause typing animation |
454
- | `resume` | - | Resume typing animation |
455
- | `restart` | - | Restart typing animation, play current content from beginning |
456
-
457
- **Usage Examples:**
458
-
459
- ```tsx
460
- markdownRef.current?.start(); // Start animation
461
- markdownRef.current?.stop(); // Pause animation
462
- markdownRef.current?.resume(); // Resume animation
463
- markdownRef.current?.restart(); // Restart animation
464
- ```
465
-
466
- ---
467
-
468
- ## πŸ”Œ Plugin System
469
-
470
- ### Built-in Plugins
471
-
472
- #### KaTeX Mathematical Formula Plugin
473
-
474
- [DEMO](https://stackblitz.com/edit/vitejs-vite-iqbyta3j?file=index.html)
475
-
476
- ```tsx
477
- import { katexPlugin } from 'ds-markdown/plugins';
478
-
479
- // Enable mathematical formula support
480
- <DsMarkdown plugins={[katexPlugin]}>Math formula: $E = mc^2$</DsMarkdown>;
481
- ```
482
-
483
- #### Mermaid Chart Plugin πŸ†•
484
-
485
- **Install Mermaid Plugin:**
486
-
487
- ```bash
488
- npm install ds-markdown-mermaid-plugin
489
- ```
490
-
491
- **Basic Usage:**
492
-
493
- ```tsx
494
- import { ConfigProvider, Markdown } from 'ds-markdown';
495
- import mermaidPlugin from 'ds-markdown-mermaid-plugin';
496
-
497
- function App() {
498
- const content = `
499
- # Flowchart Example
500
-
501
- \`\`\`mermaid
502
- flowchart TD
503
- A[Start] --> B{Decision}
504
- B -->|Yes| C[Process A]
505
- B -->|No| D[Process B]
506
- C --> E[End]
507
- D --> E
508
- \`\`\`
509
- `;
510
-
511
- return (
512
- <ConfigProvider>
513
- <Markdown plugins={[mermaidPlugin]}>{content}</Markdown>
514
- </ConfigProvider>
515
- );
516
- }
517
- ```
518
-
519
- **Supported Chart Types:**
520
-
521
- - πŸ”„ **Flowchart** - Display processes and decision paths
522
- - πŸ“‹ **Sequence Diagram** - Display interaction timing between objects
523
- - πŸ“… **Gantt Chart** - Project planning and timelines
524
- - πŸ—οΈ **Class Diagram** - Object-oriented design
525
- - πŸ₯§ **Pie Chart** - Data proportion display
526
- - πŸ”€ **State Diagram** - State transition processes
527
- - πŸ“Š **Git Graph** - Code branch history
528
- - πŸ—ΊοΈ **User Journey** - User experience flow
529
-
530
- **Configure Mermaid:**
531
-
532
- ```tsx
533
- import { ConfigProvider } from 'ds-markdown';
534
-
535
- const mermaidConfig = {
536
- theme: 'default', // Theme: default, neutral, dark, forest
537
- flowchart: {
538
- useMaxWidth: true,
539
- htmlLabels: true,
540
- },
541
- sequence: {
542
- diagramMarginX: 50,
543
- diagramMarginY: 10,
544
- },
545
- };
546
-
547
- return (
548
- <ConfigProvider mermaidConfig={mermaidConfig}>
549
- <Markdown plugins={[mermaidPlugin]}>{chartContent}</Markdown>
550
- </ConfigProvider>
551
- );
552
- ```
553
-
554
- **Related Links:**
555
-
556
- - [ds-markdown-mermaid-plugin GitHub](https://github.com/onshinpei/ds-markdown-mermaid-plugin)
557
- - [Mermaid Official Documentation](https://mermaid.js.org/)
558
-
559
- ### Custom Plugins
560
-
561
- ```tsx
562
- import { createBuildInPlugin } from 'ds-markdown/plugins';
563
-
564
- // Create custom plugin
565
- const customPlugin = createBuildInPlugin({
566
- remarkPlugin: yourRemarkPlugin,
567
- rehypePlugin: yourRehypePlugin,
568
- id: Symbol('custom-plugin'),
569
- components: {
570
- // Custom component mapping πŸ†•
571
- CustomComponent: MyCustomComponent,
572
- },
573
- });
574
-
575
- // Use custom plugin
576
- <DsMarkdown plugins={[katexPlugin, customPlugin]}>Content</DsMarkdown>;
577
- ```
578
-
579
- ---
580
-
581
- ## 🎨 UI Component System πŸ†•
582
-
583
- ds-markdown provides rich UI components that can be used individually or in combination with markdown components.
584
-
585
- ### Core Components
586
-
587
- ```tsx
588
- import {
589
- Button,
590
- IconButton,
591
- ToolTip,
592
- Segmented,
593
- CopyButton,
594
- DownloadButton
595
- } from 'ds-markdown';
596
-
597
- // Button component
598
- <Button icon={<span>πŸ“„</span>} onClick={() => {}}>
599
- Click Button
600
- </Button>
601
-
602
- // Tooltip
603
- <ToolTip title="Tooltip information">
604
- <IconButton icon={<span>πŸ“‹</span>} onClick={() => {}} />
605
- </ToolTip>
606
-
607
- // Segmented controller
608
- <Segmented
609
- options={[
610
- { label: 'Chart', value: 'diagram' },
611
- { label: 'Code', value: 'code' }
612
- ]}
613
- value={value}
614
- onChange={setValue}
615
- />
616
-
617
- // Code block operations
618
- <CopyButton codeContent="console.log('Hello')" />
619
- <DownloadButton codeContent="console.log('Hello')" language="javascript" />
620
- ```
621
-
622
- ### Style Customization
623
-
624
- ```css
625
- :root {
626
- --ds-button-bg-color: #f5f5f5;
627
- --ds-button-hover-color: #e0e0e0;
628
- --ds-tooltip-bg-color: rgba(0, 0, 0, 0.8);
629
- }
630
- ```
631
-
632
- ---
633
-
634
- ## Multi-language Configuration
635
-
636
- ```tsx
637
- import { ConfigProvider } from 'ds-markdown';
638
- import zhCN from 'ds-markdown/i18n/zh';
639
- import enUS from 'ds-markdown/i18n/en';
640
-
641
- // Chinese
642
- <ConfigProvider locale={zhCN}>
643
- <DsMarkdown {...props} />
644
- </ConfigProvider>
645
-
646
- // English
647
- <ConfigProvider locale={enUS}>
648
- <DsMarkdown {...props} />
649
- </ConfigProvider>
650
- ```
651
-
652
- ---
653
-
654
- ## πŸ’‘ Practical Examples
655
-
656
- ### πŸ“ AI Streaming Chat
657
-
658
- [DEMO: πŸ”§ StackBlitz Experience](https://stackblitz.com/edit/vitejs-vite-2ri8kex3?file=src%2FApp.tsx)
659
-
660
- ```tsx
661
- import { useRef } from 'react';
662
- import { MarkdownCMD, MarkdownCMDRef } from 'ds-markdown';
663
-
664
- function StreamingChat() {
665
- const markdownRef = useRef<MarkdownCMDRef>(null);
666
-
667
- // Simulate AI streaming response
668
- const simulateAIResponse = async () => {
669
- markdownRef.current?.clear();
670
-
671
- // Thinking phase
672
- markdownRef.current?.push('πŸ€” Analyzing your question...', 'thinking');
673
- await delay(1000);
674
- markdownRef.current?.push('\n\nβœ… Analysis complete, starting to answer', 'thinking');
675
-
676
- // Streaming answer
677
- const chunks = [
678
- '# React 19 New Features Analysis\n\n',
679
- '## πŸš€ React Compiler\n',
680
- 'The biggest highlight of React 19 is the introduction of **React Compiler**:\n\n',
681
- '- 🎯 **Automatic Optimization**: No need for manual memo and useMemo\n',
682
- '- ⚑ **Performance Boost**: Compile-time optimization, zero runtime overhead\n',
683
- '- πŸ”§ **Backward Compatible**: Existing code requires no modification\n\n',
684
- 'Hope this answer helps you! πŸŽ‰',
685
- ];
686
-
687
- for (const chunk of chunks) {
688
- await delay(100);
689
- markdownRef.current?.push(chunk, 'answer');
690
- }
691
- };
692
-
693
- const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
694
-
695
- return (
696
- <div className="chat-container">
697
- <button onClick={simulateAIResponse}>πŸ€– Ask about React 19 New Features</button>
698
- <MarkdownCMD ref={markdownRef} interval={10} timerType="requestAnimationFrame" />
699
- </div>
700
- );
701
- }
702
- ```
703
-
704
- ## πŸ”§ Best Practices
705
-
706
- ### 1. Performance Optimization
707
-
708
- ```tsx
709
- // βœ… Recommended configuration
710
- <DsMarkdown
711
- timerType="requestAnimationFrame"
712
- interval={15} // 15-30ms for best experience
713
- />
714
- ```
715
-
716
- ### 2. Streaming Data Processing
717
-
718
- ```tsx
719
- // βœ… Recommended: Imperative API
720
- const ref = useRef<MarkdownCMDRef>(null);
721
- useEffect(() => {
722
- ref.current?.push(newChunk, 'answer');
723
- }, [newChunk]);
724
- ```
725
-
726
- ### 3. Mathematical Formula Optimization
727
-
728
- ```tsx
729
- // βœ… Recommended: Load on demand
730
- import { katexPlugin } from 'ds-markdown/plugins';
731
- import 'ds-markdown/katex.css'; // Only import when needed
732
-
733
- <DsMarkdown plugins={[katexPlugin]}>Mathematical formula content</DsMarkdown>;
734
- ```
735
-
736
- ### 4. Mermaid Chart Best Practices πŸ†•
737
-
738
- ```tsx
739
- // βœ… Recommended: Install plugin separately
740
- npm install ds-markdown-mermaid-plugin
741
-
742
- // βœ… Recommended: Configure suitable themes
743
- const mermaidConfig = {
744
- theme: 'default', // Choose based on application theme
745
- flowchart: { useMaxWidth: true },
746
- };
747
-
748
- <ConfigProvider mermaidConfig={mermaidConfig}>
749
- <DsMarkdown plugins={[mermaidPlugin]} />
750
- </ConfigProvider>
751
- ```
752
-
753
- [![Visitors](https://api.visitorbadge.io/api/visitors?path=https%3A%2F%2Fgithub.com%2Fonshinpei%2Fds-markdown&label=Visitors&countColor=%23263759&style=flat)](https://visitorbadge.io/status?path=https%3A%2F%2Fgithub.com%2Fonshinpei%2Fds-markdown)