You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  1. import { memo, useEffect, useMemo, useRef, useState } from 'react'
  2. import ReactEcharts from 'echarts-for-react'
  3. import SyntaxHighlighter from 'react-syntax-highlighter'
  4. import {
  5. atelierHeathDark,
  6. atelierHeathLight,
  7. } from 'react-syntax-highlighter/dist/esm/styles/hljs'
  8. import ActionButton from '@/app/components/base/action-button'
  9. import CopyIcon from '@/app/components/base/copy-icon'
  10. import SVGBtn from '@/app/components/base/svg'
  11. import Flowchart from '@/app/components/base/mermaid'
  12. import { Theme } from '@/types/app'
  13. import useTheme from '@/hooks/use-theme'
  14. import SVGRenderer from '../svg-gallery' // Assumes svg-gallery.tsx is in /base directory
  15. import MarkdownMusic from '@/app/components/base/markdown-blocks/music'
  16. import ErrorBoundary from '@/app/components/base/markdown/error-boundary'
  17. // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD
  18. const capitalizationLanguageNameMap: Record<string, string> = {
  19. sql: 'SQL',
  20. javascript: 'JavaScript',
  21. java: 'Java',
  22. typescript: 'TypeScript',
  23. vbscript: 'VBScript',
  24. css: 'CSS',
  25. html: 'HTML',
  26. xml: 'XML',
  27. php: 'PHP',
  28. python: 'Python',
  29. yaml: 'Yaml',
  30. mermaid: 'Mermaid',
  31. markdown: 'MarkDown',
  32. makefile: 'MakeFile',
  33. echarts: 'ECharts',
  34. shell: 'Shell',
  35. powershell: 'PowerShell',
  36. json: 'JSON',
  37. latex: 'Latex',
  38. svg: 'SVG',
  39. abc: 'ABC',
  40. }
  41. const getCorrectCapitalizationLanguageName = (language: string) => {
  42. if (!language)
  43. return 'Plain'
  44. if (language in capitalizationLanguageNameMap)
  45. return capitalizationLanguageNameMap[language]
  46. return language.charAt(0).toUpperCase() + language.substring(1)
  47. }
  48. // **Add code block
  49. // Avoid error #185 (Maximum update depth exceeded.
  50. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate.
  51. // React limits the number of nested updates to prevent infinite loops.)
  52. // Reference A: https://reactjs.org/docs/error-decoder.html?invariant=185
  53. // Reference B1: https://react.dev/reference/react/memo
  54. // Reference B2: https://react.dev/reference/react/useMemo
  55. // ****
  56. // The original error that occurred in the streaming response during the conversation:
  57. // Error: Minified React error 185;
  58. // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message
  59. // or use the non-minified dev environment for full errors and additional helpful warnings.
  60. const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any) => {
  61. const { theme } = useTheme()
  62. const [isSVG, setIsSVG] = useState(true)
  63. const [chartState, setChartState] = useState<'loading' | 'success' | 'error'>('loading')
  64. const [finalChartOption, setFinalChartOption] = useState<any>(null)
  65. const echartsRef = useRef<any>(null)
  66. const contentRef = useRef<string>('')
  67. const processedRef = useRef<boolean>(false) // Track if content was successfully processed
  68. const match = /language-(\w+)/.exec(className || '')
  69. const language = match?.[1]
  70. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  71. const isDarkMode = theme === Theme.dark
  72. const echartsStyle = useMemo(() => ({
  73. height: '350px',
  74. width: '100%',
  75. }), [])
  76. const echartsOpts = useMemo(() => ({
  77. renderer: 'canvas',
  78. width: 'auto',
  79. }) as any, [])
  80. const echartsOnEvents = useMemo(() => ({
  81. finished: () => {
  82. const instance = echartsRef.current?.getEchartsInstance?.()
  83. if (instance)
  84. instance.resize()
  85. },
  86. }), [echartsRef]) // echartsRef is stable, so this effectively runs once.
  87. // Handle container resize for echarts
  88. useEffect(() => {
  89. if (language !== 'echarts' || !echartsRef.current) return
  90. const handleResize = () => {
  91. // This gets the echarts instance from the component
  92. const instance = echartsRef.current?.getEchartsInstance?.()
  93. if (instance)
  94. instance.resize()
  95. }
  96. window.addEventListener('resize', handleResize)
  97. // Also manually trigger resize after a short delay to ensure proper sizing
  98. const resizeTimer = setTimeout(handleResize, 200)
  99. return () => {
  100. window.removeEventListener('resize', handleResize)
  101. clearTimeout(resizeTimer)
  102. }
  103. }, [language, echartsRef.current])
  104. // Process chart data when content changes
  105. useEffect(() => {
  106. // Only process echarts content
  107. if (language !== 'echarts') return
  108. // Reset state when new content is detected
  109. if (!contentRef.current) {
  110. setChartState('loading')
  111. processedRef.current = false
  112. }
  113. const newContent = String(children).replace(/\n$/, '')
  114. // Skip if content hasn't changed
  115. if (contentRef.current === newContent) return
  116. contentRef.current = newContent
  117. const trimmedContent = newContent.trim()
  118. if (!trimmedContent) return
  119. // Detect if this is historical data (already complete)
  120. // Historical data typically comes as a complete code block with complete JSON
  121. const isCompleteJson
  122. = (trimmedContent.startsWith('{') && trimmedContent.endsWith('}')
  123. && trimmedContent.split('{').length === trimmedContent.split('}').length)
  124. || (trimmedContent.startsWith('[') && trimmedContent.endsWith(']')
  125. && trimmedContent.split('[').length === trimmedContent.split(']').length)
  126. // If the JSON structure looks complete, try to parse it right away
  127. if (isCompleteJson && !processedRef.current) {
  128. try {
  129. const parsed = JSON.parse(trimmedContent)
  130. if (typeof parsed === 'object' && parsed !== null) {
  131. setFinalChartOption(parsed)
  132. setChartState('success')
  133. processedRef.current = true
  134. return
  135. }
  136. }
  137. catch {
  138. try {
  139. // eslint-disable-next-line no-new-func, sonarjs/code-eval
  140. const result = new Function(`return ${trimmedContent}`)()
  141. if (typeof result === 'object' && result !== null) {
  142. setFinalChartOption(result)
  143. setChartState('success')
  144. processedRef.current = true
  145. return
  146. }
  147. }
  148. catch {
  149. // If we have a complete JSON structure but it doesn't parse,
  150. // it's likely an error rather than incomplete data
  151. setChartState('error')
  152. processedRef.current = true
  153. return
  154. }
  155. }
  156. }
  157. // If we get here, either the JSON isn't complete yet, or we failed to parse it
  158. // Check more conditions for streaming data
  159. const isIncomplete
  160. = trimmedContent.length < 5
  161. || (trimmedContent.startsWith('{')
  162. && (!trimmedContent.endsWith('}')
  163. || trimmedContent.split('{').length !== trimmedContent.split('}').length))
  164. || (trimmedContent.startsWith('[')
  165. && (!trimmedContent.endsWith(']')
  166. || trimmedContent.split('[').length !== trimmedContent.split('}').length))
  167. || (trimmedContent.split('"').length % 2 !== 1)
  168. || (trimmedContent.includes('{"') && !trimmedContent.includes('"}'))
  169. // Only try to parse streaming data if it looks complete and hasn't been processed
  170. if (!isIncomplete && !processedRef.current) {
  171. let isValidOption = false
  172. try {
  173. const parsed = JSON.parse(trimmedContent)
  174. if (typeof parsed === 'object' && parsed !== null) {
  175. setFinalChartOption(parsed)
  176. isValidOption = true
  177. }
  178. }
  179. catch {
  180. try {
  181. // eslint-disable-next-line no-new-func, sonarjs/code-eval
  182. const result = new Function(`return ${trimmedContent}`)()
  183. if (typeof result === 'object' && result !== null) {
  184. setFinalChartOption(result)
  185. isValidOption = true
  186. }
  187. }
  188. catch {
  189. // Both parsing methods failed, but content looks complete
  190. setChartState('error')
  191. processedRef.current = true
  192. }
  193. }
  194. if (isValidOption) {
  195. setChartState('success')
  196. processedRef.current = true
  197. }
  198. }
  199. }, [language, children])
  200. const renderCodeContent = useMemo(() => {
  201. const content = String(children).replace(/\n$/, '')
  202. switch (language) {
  203. case 'mermaid':
  204. if (isSVG)
  205. return <Flowchart PrimitiveCode={content} />
  206. break
  207. case 'echarts': {
  208. // Loading state: show loading indicator
  209. if (chartState === 'loading') {
  210. return (
  211. <div style={{
  212. minHeight: '350px',
  213. width: '100%',
  214. display: 'flex',
  215. flexDirection: 'column',
  216. alignItems: 'center',
  217. justifyContent: 'center',
  218. borderBottomLeftRadius: '10px',
  219. borderBottomRightRadius: '10px',
  220. backgroundColor: isDarkMode ? 'var(--color-components-input-bg-normal)' : 'transparent',
  221. color: 'var(--color-text-secondary)',
  222. }}>
  223. <div style={{
  224. marginBottom: '12px',
  225. width: '24px',
  226. height: '24px',
  227. }}>
  228. {/* Rotating spinner that works in both light and dark modes */}
  229. <svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg" style={{ animation: 'spin 1.5s linear infinite' }}>
  230. <style>
  231. {`
  232. @keyframes spin {
  233. 0% { transform: rotate(0deg); }
  234. 100% { transform: rotate(360deg); }
  235. }
  236. `}
  237. </style>
  238. <circle opacity="0.2" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />
  239. <path d="M12 2C6.47715 2 2 6.47715 2 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
  240. </svg>
  241. </div>
  242. <div style={{
  243. fontFamily: 'var(--font-family)',
  244. fontSize: '14px',
  245. }}>Chart loading...</div>
  246. </div>
  247. )
  248. }
  249. // Success state: show the chart
  250. if (chartState === 'success' && finalChartOption) {
  251. return (
  252. <div style={{
  253. minWidth: '300px',
  254. minHeight: '350px',
  255. width: '100%',
  256. overflowX: 'auto',
  257. borderBottomLeftRadius: '10px',
  258. borderBottomRightRadius: '10px',
  259. transition: 'background-color 0.3s ease',
  260. }}>
  261. <ErrorBoundary>
  262. <ReactEcharts
  263. ref={echartsRef}
  264. option={finalChartOption}
  265. style={echartsStyle}
  266. theme={isDarkMode ? 'dark' : undefined}
  267. opts={echartsOpts}
  268. notMerge={true}
  269. onEvents={echartsOnEvents}
  270. />
  271. </ErrorBoundary>
  272. </div>
  273. )
  274. }
  275. // Error state: show error message
  276. const errorOption = {
  277. title: {
  278. text: 'ECharts error - Wrong option.',
  279. },
  280. }
  281. return (
  282. <div style={{
  283. minWidth: '300px',
  284. minHeight: '350px',
  285. width: '100%',
  286. overflowX: 'auto',
  287. borderBottomLeftRadius: '10px',
  288. borderBottomRightRadius: '10px',
  289. transition: 'background-color 0.3s ease',
  290. }}>
  291. <ErrorBoundary>
  292. <ReactEcharts
  293. ref={echartsRef}
  294. option={errorOption}
  295. style={echartsStyle}
  296. theme={isDarkMode ? 'dark' : undefined}
  297. opts={echartsOpts}
  298. notMerge={true}
  299. />
  300. </ErrorBoundary>
  301. </div>
  302. )
  303. }
  304. case 'svg':
  305. if (isSVG) {
  306. return (
  307. <ErrorBoundary>
  308. <SVGRenderer content={content} />
  309. </ErrorBoundary>
  310. )
  311. }
  312. break
  313. case 'abc':
  314. return (
  315. <ErrorBoundary>
  316. <MarkdownMusic children={content} />
  317. </ErrorBoundary>
  318. )
  319. default:
  320. return (
  321. <SyntaxHighlighter
  322. {...props}
  323. style={theme === Theme.light ? atelierHeathLight : atelierHeathDark}
  324. customStyle={{
  325. paddingLeft: 12,
  326. borderBottomLeftRadius: '10px',
  327. borderBottomRightRadius: '10px',
  328. backgroundColor: 'var(--color-components-input-bg-normal)',
  329. }}
  330. language={match?.[1]}
  331. showLineNumbers
  332. PreTag="div"
  333. >
  334. {content}
  335. </SyntaxHighlighter>
  336. )
  337. }
  338. }, [children, language, isSVG, finalChartOption, props, theme, match, chartState, isDarkMode, echartsStyle, echartsOpts, echartsOnEvents])
  339. if (inline || !match)
  340. return <code {...props} className={className}>{children}</code>
  341. return (
  342. <div className='relative'>
  343. <div className='flex h-8 items-center justify-between rounded-t-[10px] border-b border-divider-subtle bg-components-input-bg-normal p-1 pl-3'>
  344. <div className='system-xs-semibold-uppercase text-text-secondary'>{languageShowName}</div>
  345. <div className='flex items-center gap-1'>
  346. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  347. <ActionButton>
  348. <CopyIcon content={String(children).replace(/\n$/, '')} />
  349. </ActionButton>
  350. </div>
  351. </div>
  352. {renderCodeContent}
  353. </div>
  354. )
  355. })
  356. CodeBlock.displayName = 'CodeBlock'
  357. export default CodeBlock