11import { DiffsHighlighter , getSharedHighlighter , SupportedLanguages } from "@pierre/diffs" ;
22import { CheckIcon , CopyIcon } from "lucide-react" ;
3- import React , {
3+ import {
44 Children ,
5- Suspense ,
65 type MouseEvent as ReactMouseEvent ,
76 isValidElement ,
8- use ,
97 useCallback ,
108 memo ,
119 useEffect ,
@@ -34,27 +32,6 @@ import {
3432import { readLocalApi } from "../localApi" ;
3533import { cn } from "../lib/utils" ;
3634
37- class CodeHighlightErrorBoundary extends React . Component <
38- { fallback : ReactNode ; children : ReactNode } ,
39- { hasError : boolean }
40- > {
41- constructor ( props : { fallback : ReactNode ; children : ReactNode } ) {
42- super ( props ) ;
43- this . state = { hasError : false } ;
44- }
45-
46- static getDerivedStateFromError ( ) {
47- return { hasError : true } ;
48- }
49-
50- override render ( ) {
51- if ( this . state . hasError ) {
52- return this . props . fallback ;
53- }
54- return this . props . children ;
55- }
56- }
57-
5835interface ChatMarkdownProps {
5936 text : string ;
6037 cwd : string | undefined ;
@@ -69,12 +46,26 @@ const highlightedCodeCache = new LRUCache<string>(
6946 MAX_HIGHLIGHT_CACHE_MEMORY_BYTES ,
7047) ;
7148const highlighterPromiseCache = new Map < string , Promise < DiffsHighlighter > > ( ) ;
49+ const unsupportedHighlightLanguages = new Set < string > ( ) ;
50+ const HIGHLIGHT_LANGUAGE_ALIASES : Readonly < Record < string , string > > = {
51+ baml : "text" ,
52+ gitignore : "ini" ,
53+ plaintext : "text" ,
54+ txt : "text" ,
55+ } ;
56+
57+ function normalizeHighlightLanguage ( language : string ) : string {
58+ const normalizedLanguage = language . trim ( ) . toLowerCase ( ) ;
59+ if ( ! normalizedLanguage ) {
60+ return "text" ;
61+ }
62+ return HIGHLIGHT_LANGUAGE_ALIASES [ normalizedLanguage ] ?? normalizedLanguage ;
63+ }
7264
7365function extractFenceLanguage ( className : string | undefined ) : string {
7466 const match = className ?. match ( CODE_FENCE_LANGUAGE_REGEX ) ;
7567 const raw = match ?. [ 1 ] ?? "text" ;
76- // Shiki doesn't bundle a gitignore grammar; ini is a close match (#685)
77- return raw === "gitignore" ? "ini" : raw ;
68+ return normalizeHighlightLanguage ( raw ) ;
7869}
7970
8071function nodeToPlainText ( node : ReactNode ) : string {
@@ -121,27 +112,70 @@ function estimateHighlightedSize(html: string, code: string): number {
121112}
122113
123114function getHighlighterPromise ( language : string , themeName : string ) : Promise < DiffsHighlighter > {
124- const cacheKey = `${ language } :${ themeName } ` ;
115+ const highlighterLanguage = unsupportedHighlightLanguages . has ( language ) ? "text" : language ;
116+ const cacheKey = `${ highlighterLanguage } :${ themeName } ` ;
125117 const cached = highlighterPromiseCache . get ( cacheKey ) ;
126118 if ( cached ) return cached ;
127119
128120 const promise = getSharedHighlighter ( {
129121 themes : [ themeName ] ,
130- langs : [ language as SupportedLanguages ] ,
122+ langs : [ highlighterLanguage as SupportedLanguages ] ,
131123 preferredHighlighter : "shiki-js" ,
132124 } ) . catch ( ( err ) => {
133125 highlighterPromiseCache . delete ( cacheKey ) ;
134- if ( language === "text" ) {
126+ if ( highlighterLanguage === "text" ) {
135127 // "text" itself failed — Shiki cannot initialize at all, surface the error
136128 throw err ;
137129 }
138130 // Language not supported by Shiki — fall back to "text"
131+ unsupportedHighlightLanguages . add ( highlighterLanguage ) ;
139132 return getHighlighterPromise ( "text" , themeName ) ;
140133 } ) ;
141134 highlighterPromiseCache . set ( cacheKey , promise ) ;
142135 return promise ;
143136}
144137
138+ function renderHighlightedHtml (
139+ highlighter : DiffsHighlighter ,
140+ code : string ,
141+ language : string ,
142+ themeName : string ,
143+ ) : string {
144+ const highlightLanguage = unsupportedHighlightLanguages . has ( language ) ? "text" : language ;
145+ try {
146+ return highlighter . codeToHtml ( code , {
147+ lang : highlightLanguage as SupportedLanguages ,
148+ theme : themeName ,
149+ } ) ;
150+ } catch ( error ) {
151+ if ( highlightLanguage === "text" ) {
152+ throw error ;
153+ }
154+ unsupportedHighlightLanguages . add ( highlightLanguage ) ;
155+ return highlighter . codeToHtml ( code , { lang : "text" , theme : themeName } ) ;
156+ }
157+ }
158+
159+ function scheduleHighlightWork ( callback : ( ) => void ) : ( ) => void {
160+ if ( typeof window === "undefined" ) {
161+ callback ( ) ;
162+ return ( ) => undefined ;
163+ }
164+
165+ const idleWindow = window as Window & {
166+ requestIdleCallback ?: ( callback : ( ) => void , options ?: { timeout : number } ) => number ;
167+ cancelIdleCallback ?: ( handle : number ) => void ;
168+ } ;
169+
170+ if ( idleWindow . requestIdleCallback && idleWindow . cancelIdleCallback ) {
171+ const idleHandle = idleWindow . requestIdleCallback ( callback , { timeout : 1500 } ) ;
172+ return ( ) => idleWindow . cancelIdleCallback ?.( idleHandle ) ;
173+ }
174+
175+ const timeoutHandle = window . setTimeout ( callback , 0 ) ;
176+ return ( ) => window . clearTimeout ( timeoutHandle ) ;
177+ }
178+
145179function MarkdownCodeBlock ( { code, children } : { code : string ; children : ReactNode } ) {
146180 const [ copied , setCopied ] = useState ( false ) ;
147181 const copiedTimerRef = useRef < ReturnType < typeof setTimeout > | null > ( null ) ;
@@ -190,85 +224,94 @@ function MarkdownCodeBlock({ code, children }: { code: string; children: ReactNo
190224 ) ;
191225}
192226
193- interface SuspenseShikiCodeBlockProps {
227+ interface ShikiCodeBlockProps {
194228 className : string | undefined ;
195229 code : string ;
196230 themeName : string ;
197231 isStreaming : boolean ;
232+ fallback : ReactNode ;
198233}
199234
200- function SuspenseShikiCodeBlock ( {
235+ type HighlightedCodeState = {
236+ cacheKey : string ;
237+ html : string ;
238+ } ;
239+
240+ function ShikiCodeBlock ( {
201241 className,
202242 code,
203243 themeName,
204244 isStreaming,
205- } : SuspenseShikiCodeBlockProps ) {
245+ fallback,
246+ } : ShikiCodeBlockProps ) {
206247 const language = extractFenceLanguage ( className ) ;
207248 const cacheKey = createHighlightCacheKey ( code , language , themeName ) ;
208- const cachedHighlightedHtml = ! isStreaming ? highlightedCodeCache . get ( cacheKey ) : null ;
249+ const [ highlightedCode , setHighlightedCode ] = useState < HighlightedCodeState | null > ( ( ) => {
250+ const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache . get ( cacheKey ) ;
251+ return cachedHighlightedHtml == null ? null : { cacheKey, html : cachedHighlightedHtml } ;
252+ } ) ;
209253
210- if ( cachedHighlightedHtml != null ) {
211- return (
212- < div
213- className = "chat-markdown-shiki"
214- dangerouslySetInnerHTML = { { __html : cachedHighlightedHtml } }
215- />
216- ) ;
217- }
254+ useEffect ( ( ) => {
255+ if ( isStreaming ) {
256+ setHighlightedCode ( null ) ;
257+ return ;
258+ }
218259
219- return (
220- < UncachedShikiCodeBlock
221- code = { code }
222- language = { language }
223- themeName = { themeName }
224- cacheKey = { cacheKey }
225- isStreaming = { isStreaming }
226- />
227- ) ;
228- }
260+ const cachedHighlightedHtml = highlightedCodeCache . get ( cacheKey ) ;
261+ if ( cachedHighlightedHtml != null ) {
262+ setHighlightedCode ( { cacheKey, html : cachedHighlightedHtml } ) ;
263+ return ;
264+ }
229265
230- interface UncachedShikiCodeBlockProps {
231- code : string ;
232- language : string ;
233- themeName : string ;
234- cacheKey : string ;
235- isStreaming : boolean ;
236- }
266+ let isCancelled = false ;
267+ let cancelHighlightWork : ( ( ) => void ) | null = null ;
268+ setHighlightedCode ( null ) ;
269+
270+ void getHighlighterPromise ( language , themeName )
271+ . then ( ( highlighter ) => {
272+ if ( isCancelled ) return ;
273+ cancelHighlightWork = scheduleHighlightWork ( ( ) => {
274+ if ( isCancelled ) return ;
275+ let highlightedHtml : string ;
276+ try {
277+ highlightedHtml = renderHighlightedHtml ( highlighter , code , language , themeName ) ;
278+ } catch {
279+ return ;
280+ }
281+ if ( isCancelled ) return ;
282+ highlightedCodeCache . set (
283+ cacheKey ,
284+ highlightedHtml ,
285+ estimateHighlightedSize ( highlightedHtml , code ) ,
286+ ) ;
287+ setHighlightedCode ( { cacheKey, html : highlightedHtml } ) ;
288+ } ) ;
289+ } )
290+ . catch ( ( ) => {
291+ if ( ! isCancelled ) {
292+ setHighlightedCode ( null ) ;
293+ }
294+ } ) ;
237295
238- function UncachedShikiCodeBlock ( {
239- code,
240- language,
241- themeName,
242- cacheKey,
243- isStreaming,
244- } : UncachedShikiCodeBlockProps ) {
245- const highlighter = use ( getHighlighterPromise ( language , themeName ) ) ;
246- const highlightedHtml = useMemo ( ( ) => {
247- try {
248- return highlighter . codeToHtml ( code , { lang : language , theme : themeName } ) ;
249- } catch ( error ) {
250- // Log highlighting failures for debugging while falling back to plain text
251- console . warn (
252- `Code highlighting failed for language "${ language } ", falling back to plain text.` ,
253- error instanceof Error ? error . message : error ,
254- ) ;
255- // If highlighting fails for this language, render as plain text
256- return highlighter . codeToHtml ( code , { lang : "text" , theme : themeName } ) ;
257- }
258- } , [ code , highlighter , language , themeName ] ) ;
296+ return ( ) => {
297+ isCancelled = true ;
298+ cancelHighlightWork ?.( ) ;
299+ } ;
300+ } , [ cacheKey , code , isStreaming , language , themeName ] ) ;
259301
260- useEffect ( ( ) => {
261- if ( ! isStreaming ) {
262- highlightedCodeCache . set (
263- cacheKey ,
264- highlightedHtml ,
265- estimateHighlightedSize ( highlightedHtml , code ) ,
266- ) ;
267- }
268- } , [ cacheKey , code , highlightedHtml , isStreaming ] ) ;
302+ const cachedHighlightedHtml = isStreaming ? null : highlightedCodeCache . get ( cacheKey ) ;
303+ const activeHighlightedHtml =
304+ cachedHighlightedHtml ?? ( highlightedCode ?. cacheKey === cacheKey ? highlightedCode . html : null ) ;
305+
306+ if ( activeHighlightedHtml == null ) {
307+ return < > { fallback } </ > ;
308+ }
269309
270310 return (
271- < div className = "chat-markdown-shiki" dangerouslySetInnerHTML = { { __html : highlightedHtml } } />
311+ < div
312+ className = "chat-markdown-shiki"
313+ dangerouslySetInnerHTML = { { __html : activeHighlightedHtml } }
314+ />
272315 ) ;
273316}
274317
@@ -576,16 +619,13 @@ function ChatMarkdown({ text, cwd, isStreaming = false }: ChatMarkdownProps) {
576619
577620 return (
578621 < MarkdownCodeBlock code = { codeBlock . code } >
579- < CodeHighlightErrorBoundary fallback = { < pre { ...props } > { children } </ pre > } >
580- < Suspense fallback = { < pre { ...props } > { children } </ pre > } >
581- < SuspenseShikiCodeBlock
582- className = { codeBlock . className }
583- code = { codeBlock . code }
584- themeName = { codeBlockThemeName }
585- isStreaming = { isStreaming }
586- />
587- </ Suspense >
588- </ CodeHighlightErrorBoundary >
622+ < ShikiCodeBlock
623+ className = { codeBlock . className }
624+ code = { codeBlock . code }
625+ themeName = { codeBlockThemeName }
626+ isStreaming = { isStreaming }
627+ fallback = { < pre { ...props } > { children } </ pre > }
628+ />
589629 </ MarkdownCodeBlock >
590630 ) ;
591631 } ,
0 commit comments