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

markdown.md

202 lines6.3 KB

1---
2title: Highlight markdown code
3id: ui-markdown-highlight
4order: 9
5description: "Color the fenced code blocks in model replies. Pass a TanStack Highlight highlighter to TextPart."
6keywords:
7 - tanstack ai
8 - TextPart
9 - markdown
10 - highlight
11 - syntax highlighting
12---
13​
14Pass a TanStack Highlight `highlighter` to `TextPart`. Fenced code then renders with token colors.
15​
16`TextPart` is in the React, Vue, and Solid UI packages. If your app still passes `remarkPlugins` or `rehypePlugins`, start with [TextPart markdown](../migration/text-part-markdown).
17​
18## Quick setup
19​
20These steps use React. For Vue and Solid, steps 1 to 3 are the same. Step 4 is different. See [Vue and Solid](#vue-and-solid).
21​
22### 1. Install TanStack Highlight
23​
24<!-- ::start:tabs variant="package-manager" mode="install" -->
25​
26react: @tanstack/highlight
27vue: @tanstack/highlight
28solid: @tanstack/highlight
29​
30<!-- ::end:tabs -->
31​
32Use `@tanstack/highlight` 0.0.6 or newer. The markdown adapter is in that package.
33​
34### 2. Create the highlighter
35​
36Create `src/markdown-highlighter.ts`. Register only the languages that your models write:
37​
38```ts
39import { createHighlighter } from '@tanstack/highlight/core'
40import { js } from '@tanstack/highlight/languages/js'
41import { json } from '@tanstack/highlight/languages/json'
42import { plaintext } from '@tanstack/highlight/languages/plaintext'
43import { ts } from '@tanstack/highlight/languages/ts'
44import { tsx } from '@tanstack/highlight/languages/tsx'
45import { createTanStackMarkdownHighlighter } from '@tanstack/highlight/markdown'
46​
47const highlighter = createHighlighter({
48 languages: [plaintext, js, json, ts, tsx],
49})
50​
51export const highlightMarkdownCode =
52 createTanStackMarkdownHighlighter(highlighter)
53```
54​
55A fence with an unknown language renders as escaped plain text.
56​
57> [!WARNING]
58> Use `createTanStackMarkdownHighlighter`. `TextPart` inserts the highlighter output as trusted HTML. A highlighter that returns unescaped source text lets model output inject HTML.
59​
60### 3. Create the theme CSS
61​
62Create `src/markdown-highlight-theme.ts`. Point the selectors at a `.markdown-renderer` wrapper:
63​
64```ts
65import { createThemeCss } from '@tanstack/highlight/theme'
66import { githubDarkTheme } from '@tanstack/highlight/themes/github-dark'
67import { githubLightTheme } from '@tanstack/highlight/themes/github-light'
68​
69export const markdownHighlightCss = createThemeCss({
70 light: githubLightTheme,
71 dark: githubDarkTheme,
72 lightSelector: '.markdown-renderer',
73 darkSelector: '.dark .markdown-renderer',
74 codeBlockSelector: '.markdown-renderer pre.tm-code',
75 lineNumbersSelector: '.markdown-renderer .tm-code--line-numbers',
76})
77```
78​
79### 4. Use it in the chat
80​
81Register `TextPart` as `partsComponents.text`. Pass the highlighter, and put `markdown-renderer` on the wrapper so that the theme CSS matches. Inject the CSS once in `layout`:
82​
83```tsx
84import { fetchServerSentEvents } from '@tanstack/ai-react'
85import { createChatHook, TextPart } from '@tanstack/ai-react/ui'
86import { highlightMarkdownCode } from './markdown-highlighter'
87import { markdownHighlightCss } from './markdown-highlight-theme'
88​
89const chatOptions = {
90 connection: fetchServerSentEvents('/api/chat'),
92​
93const { useAppChat, useChatContext } = createChatHook({
94 options: chatOptions,
95 components: {
96 input: () => {
97 const chat = useChatContext()
98 return (
99 <form
100 onSubmit={(event) => {
101 event.preventDefault()
102 const field = event.currentTarget.elements.namedItem('message')
103 if (!(field instanceof HTMLInputElement)) return
104 const text = field.value.trim()
105 if (!text) return
106 field.value = ''
107 void chat.sendMessage(text)
108 }}
109 >
110 <input name="message" />
111 <button type="submit">Send</button>
112 </form>
113 )
114 },
115 layout: ({ Messages, Input }) => (
116 <main>
117 <style>{markdownHighlightCss}</style>
118 <Messages />
119 <Input />
120 </main>
121 ),
122 message: ({ message, Parts }) => (
123 <article data-role={message.role}>
124 <Parts />
125 </article>
126 ),
127 },
128 partsComponents: {
129 text: ({ part }) => (
130 <TextPart
131 content={part.content}
132 highlighter={highlightMarkdownCode}
133 className="markdown-renderer"
134 />
135 ),
136 fallback: () => null,
137 },
138})
139​
140export function ChatScreen() {
141 const chat = useAppChat({ threadId: 'support-chat' })
142 return <chat.AppChat />
144```
145​
146Send a prompt that returns a fenced `ts` block. The fence now shows token colors.
147​
148## How it works
149​
150- `createHighlighter` tokenizes code for the languages that you register.
151- `createTanStackMarkdownHighlighter` turns it into the `CodeHighlighter` that TanStack Markdown calls for each fence. It escapes the source text.
152- `createThemeCss` writes CSS for the token classes, one theme for light mode and one for dark mode.
153​
154## Vue and Solid
155​
156Use the same highlighter file and the same theme file. Inject `markdownHighlightCss` once, at the app root. Then pass the highlighter to `TextPart` from your UI package.
157​
158Vue:
159​
160```ts
161import { defineComponent, h } from 'vue'
162import { TextPart } from '@tanstack/ai-vue/ui'
163import { highlightMarkdownCode } from './markdown-highlighter'
164​
165export default defineComponent({
166 props: { content: { type: String, required: true } },
167 setup(props) {
168 return () =>
169 h(TextPart, {
170 content: props.content,
171 highlighter: highlightMarkdownCode,
172 class: 'markdown-renderer',
173 })
174 },
175})
176```
177​
178Solid:
179​
180```tsx
181import { TextPart } from '@tanstack/ai-solid/ui'
182import { highlightMarkdownCode } from './markdown-highlighter'
183​
184export function Reply(props: { content: string }) {
185 return (
186 <TextPart
187 content={props.content}
188 highlighter={highlightMarkdownCode}
189 class="markdown-renderer"
190 />
191 )
193```
194​
195You now have colored code in model replies.
196​
197## Advanced
198​
199- **More languages:** import them from `@tanstack/highlight/languages/*` and add them to `createHighlighter`.
200- **Fence metadata and line numbers:** read the [TanStack Markdown highlighting guide](https://tanstack.com/markdown/latest/docs/guides/syntax-highlighting).
201- **Tag swaps in React** (`a`, `img`): pass `components` to `TextPart`. That map uses normal HTML props.
202- **Tag swaps in Vue and Solid:** these `TextPart` components have no `components` map. Use a TanStack Markdown extension.