Skip to content

Commit 38581b9

Browse files
authored
Fix hljs highlighting in AI answer (#2042)
* AI answer hljs fallback * Reuse existing hljs instance
1 parent 92c0a51 commit 38581b9

File tree

2 files changed

+13
-4
lines changed

2 files changed

+13
-4
lines changed

src/Elastic.Documentation.Site/Assets/hljs.ts

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -176,3 +176,6 @@ export function initHighlight() {
176176
hljs.highlightElement
177177
)
178178
}
179+
180+
// Export the configured hljs instance for reuse
181+
export { hljs }

src/Elastic.Documentation.Site/Assets/web-components/SearchOrAskAi/AskAi/ChatMessage.tsx

Lines changed: 10 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { initCopyButton } from '../../../copybutton'
2+
import { hljs } from '../../../hljs'
23
import { GeneratingStatus } from './GeneratingStatus'
34
import { References } from './RelatedResources'
45
import { ChatMessage as ChatMessageType } from './chat.store'
@@ -19,7 +20,6 @@ import {
1920
} from '@elastic/eui'
2021
import { css } from '@emotion/react'
2122
import DOMPurify from 'dompurify'
22-
import hljs from 'highlight.js/lib/core'
2323
import { Marked, RendererObject, Tokens } from 'marked'
2424
import * as React from 'react'
2525
import { useEffect, useMemo } from 'react'
@@ -28,9 +28,15 @@ import { useEffect, useMemo } from 'react'
2828
const createMarkedInstance = () => {
2929
const renderer: RendererObject = {
3030
code({ text, lang }: Tokens.Code): string {
31-
const highlighted = lang
32-
? hljs.highlight(text, { language: lang }).value
33-
: hljs.highlightAuto(text).value
31+
let highlighted: string
32+
try {
33+
highlighted = lang
34+
? hljs.highlight(text, { language: lang }).value
35+
: hljs.highlightAuto(text).value
36+
} catch {
37+
// Fallback to auto highlighting if the specified language is not found
38+
highlighted = hljs.highlightAuto(text).value
39+
}
3440
return `<div class="highlight">
3541
<pre>
3642
<code class="language-${lang}">${highlighted}</code>

0 commit comments

Comments
 (0)