Skip to content
Source
Sign inSign up
TanStack/ai
Open History to see the last commit

text-part.tsx

95 lines2.7 KB

1import { Markdown } from '@tanstack/markdown/react'
2import { streamingMarkdownExtension } from '@tanstack/markdown/extensions/streaming'
3import type { CodeHighlighter, MarkdownExtension } from '@tanstack/markdown'
4import type { MarkdownComponents } from '@tanstack/markdown/react'
5​
6const DEFAULT_EXTENSIONS: Array<MarkdownExtension> = [
7 streamingMarkdownExtension(),
8]
9​
10export interface TextPartProps {
11 /** The text content to render */
12 content: string
13 /** The role of the message (user, assistant, or system) - optional for standalone use */
14 role?: 'user' | 'assistant' | 'system'
15 /** Base className applied to all text parts */
16 className?: string
17 /** Additional className for user messages */
18 userClassName?: string
19 /** Additional className for assistant messages (also used for system messages) */
20 assistantClassName?: string
21 /**
22 * Additional TanStack Markdown extensions, appended after the built-in
23 * streaming extension.
24 */
25 extensions?: Array<MarkdownExtension>
26 /**
27 * Synchronous code highlighter. Its output is inserted as trusted HTML,
28 * so use only a highlighter that escapes source text (for example
29 * `createTanStackMarkdownHighlighter` from `@tanstack/highlight/markdown`).
30 */
31 highlighter?: CodeHighlighter
32 /** Replace intrinsic elements (e.g. custom `a`, `img`) by tag name. */
33 components?: MarkdownComponents
35​
36/**
37 * TextPart component - renders markdown text with TanStack Markdown.
38 *
39 * Raw HTML is escaped and executable URLs are removed, so AI output can be
40 * rendered without a separate sanitizer.
41 *
42 * @example Standalone usage
43 * ```tsx
44 * <TextPart
45 * content="Hello **world**!"
46 * role="user"
47 * className="p-4 rounded"
48 * userClassName="bg-blue-500"
49 * assistantClassName="bg-gray-500"
50 * />
51 * ```
52 *
53 * @example Syntax highlighting
54 * ```tsx
55 * import { highlightMarkdownCode } from './markdown-highlighter'
56 *
57 * <TextPart content={content} highlighter={highlightMarkdownCode} />
58 * ```
59 */
60export function TextPart({
61 content,
62 role,
63 className = '',
64 userClassName = '',
65 assistantClassName = '',
66 extensions,
67 highlighter,
68 components,
69}: TextPartProps) {
70 const roleClassName =
71 role === 'user'
72 ? userClassName
73 : role === 'assistant'
74 ? assistantClassName
75 : ''
76 const combinedClassName = [className, roleClassName].filter(Boolean).join(' ')
77​
78 return (
79 <div className={combinedClassName || undefined}>
80 <Markdown
81 extensions={
82 extensions
83 ? [...DEFAULT_EXTENSIONS, ...extensions]
84 : DEFAULT_EXTENSIONS
85 }
86 frontmatter={false}
87 headingIds={false}
88 highlighter={highlighter}
89 components={components}
90 >
91 {content}
92 </Markdown>
93 </div>
94 )