Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

code-block.tsx 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  1. import { memo, useCallback, 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. // Define ECharts event parameter types
  61. interface EChartsEventParams {
  62. type: string;
  63. seriesIndex?: number;
  64. dataIndex?: number;
  65. name?: string;
  66. value?: any;
  67. currentIndex?: number; // Added for timeline events
  68. [key: string]: any;
  69. }
  70. const CodeBlock: any = memo(({ inline, className, children = '', ...props }: any) => {
  71. const { theme } = useTheme()
  72. const [isSVG, setIsSVG] = useState(true)
  73. const [chartState, setChartState] = useState<'loading' | 'success' | 'error'>('loading')
  74. const [finalChartOption, setFinalChartOption] = useState<any>(null)
  75. const echartsRef = useRef<any>(null)
  76. const contentRef = useRef<string>('')
  77. const processedRef = useRef<boolean>(false) // Track if content was successfully processed
  78. const instanceIdRef = useRef<string>(`chart-${Date.now()}-${Math.random().toString(36).substring(2, 9)}`) // Unique ID for logging
  79. const isInitialRenderRef = useRef<boolean>(true) // Track if this is initial render
  80. const chartInstanceRef = useRef<any>(null) // Direct reference to ECharts instance
  81. const resizeTimerRef = useRef<NodeJS.Timeout | null>(null) // For debounce handling
  82. const finishedEventCountRef = useRef<number>(0) // Track finished event trigger count
  83. const match = /language-(\w+)/.exec(className || '')
  84. const language = match?.[1]
  85. const languageShowName = getCorrectCapitalizationLanguageName(language || '')
  86. const isDarkMode = theme === Theme.dark
  87. const echartsStyle = useMemo(() => ({
  88. height: '350px',
  89. width: '100%',
  90. }), [])
  91. const echartsOpts = useMemo(() => ({
  92. renderer: 'canvas',
  93. width: 'auto',
  94. }) as any, [])
  95. // Debounce resize operations
  96. const debouncedResize = useCallback(() => {
  97. if (resizeTimerRef.current)
  98. clearTimeout(resizeTimerRef.current)
  99. resizeTimerRef.current = setTimeout(() => {
  100. if (chartInstanceRef.current)
  101. chartInstanceRef.current.resize()
  102. resizeTimerRef.current = null
  103. }, 200)
  104. }, [])
  105. // Handle ECharts instance initialization
  106. const handleChartReady = useCallback((instance: any) => {
  107. chartInstanceRef.current = instance
  108. // Force resize to ensure timeline displays correctly
  109. setTimeout(() => {
  110. if (chartInstanceRef.current)
  111. chartInstanceRef.current.resize()
  112. }, 200)
  113. }, [])
  114. // Store event handlers in useMemo to avoid recreating them
  115. const echartsEvents = useMemo(() => ({
  116. finished: (params: EChartsEventParams) => {
  117. // Limit finished event frequency to avoid infinite loops
  118. finishedEventCountRef.current++
  119. if (finishedEventCountRef.current > 3) {
  120. // Stop processing after 3 times to avoid infinite loops
  121. return
  122. }
  123. if (chartInstanceRef.current) {
  124. // Use debounced resize
  125. debouncedResize()
  126. }
  127. },
  128. }), [debouncedResize])
  129. // Handle container resize for echarts
  130. useEffect(() => {
  131. if (language !== 'echarts' || !chartInstanceRef.current) return
  132. const handleResize = () => {
  133. if (chartInstanceRef.current)
  134. // Use debounced resize
  135. debouncedResize()
  136. }
  137. window.addEventListener('resize', handleResize)
  138. return () => {
  139. window.removeEventListener('resize', handleResize)
  140. if (resizeTimerRef.current)
  141. clearTimeout(resizeTimerRef.current)
  142. }
  143. }, [language, debouncedResize])
  144. // Process chart data when content changes
  145. useEffect(() => {
  146. // Only process echarts content
  147. if (language !== 'echarts') return
  148. // Reset state when new content is detected
  149. if (!contentRef.current) {
  150. setChartState('loading')
  151. processedRef.current = false
  152. }
  153. const newContent = String(children).replace(/\n$/, '')
  154. // Skip if content hasn't changed
  155. if (contentRef.current === newContent) return
  156. contentRef.current = newContent
  157. const trimmedContent = newContent.trim()
  158. if (!trimmedContent) return
  159. // Detect if this is historical data (already complete)
  160. // Historical data typically comes as a complete code block with complete JSON
  161. const isCompleteJson
  162. = (trimmedContent.startsWith('{') && trimmedContent.endsWith('}')
  163. && trimmedContent.split('{').length === trimmedContent.split('}').length)
  164. || (trimmedContent.startsWith('[') && trimmedContent.endsWith(']')
  165. && trimmedContent.split('[').length === trimmedContent.split(']').length)
  166. // If the JSON structure looks complete, try to parse it right away
  167. if (isCompleteJson && !processedRef.current) {
  168. try {
  169. const parsed = JSON.parse(trimmedContent)
  170. if (typeof parsed === 'object' && parsed !== null) {
  171. setFinalChartOption(parsed)
  172. setChartState('success')
  173. processedRef.current = true
  174. return
  175. }
  176. }
  177. catch {
  178. try {
  179. // eslint-disable-next-line no-new-func, sonarjs/code-eval
  180. const result = new Function(`return ${trimmedContent}`)()
  181. if (typeof result === 'object' && result !== null) {
  182. setFinalChartOption(result)
  183. setChartState('success')
  184. processedRef.current = true
  185. return
  186. }
  187. }
  188. catch {
  189. // If we have a complete JSON structure but it doesn't parse,
  190. // it's likely an error rather than incomplete data
  191. setChartState('error')
  192. processedRef.current = true
  193. return
  194. }
  195. }
  196. }
  197. // If we get here, either the JSON isn't complete yet, or we failed to parse it
  198. // Check more conditions for streaming data
  199. const isIncomplete
  200. = trimmedContent.length < 5
  201. || (trimmedContent.startsWith('{')
  202. && (!trimmedContent.endsWith('}')
  203. || trimmedContent.split('{').length !== trimmedContent.split('}').length))
  204. || (trimmedContent.startsWith('[')
  205. && (!trimmedContent.endsWith(']')
  206. || trimmedContent.split('[').length !== trimmedContent.split('}').length))
  207. || (trimmedContent.split('"').length % 2 !== 1)
  208. || (trimmedContent.includes('{"') && !trimmedContent.includes('"}'))
  209. // Only try to parse streaming data if it looks complete and hasn't been processed
  210. if (!isIncomplete && !processedRef.current) {
  211. let isValidOption = false
  212. try {
  213. const parsed = JSON.parse(trimmedContent)
  214. if (typeof parsed === 'object' && parsed !== null) {
  215. setFinalChartOption(parsed)
  216. isValidOption = true
  217. }
  218. }
  219. catch {
  220. try {
  221. // eslint-disable-next-line no-new-func, sonarjs/code-eval
  222. const result = new Function(`return ${trimmedContent}`)()
  223. if (typeof result === 'object' && result !== null) {
  224. setFinalChartOption(result)
  225. isValidOption = true
  226. }
  227. }
  228. catch {
  229. // Both parsing methods failed, but content looks complete
  230. setChartState('error')
  231. processedRef.current = true
  232. }
  233. }
  234. if (isValidOption) {
  235. setChartState('success')
  236. processedRef.current = true
  237. }
  238. }
  239. }, [language, children])
  240. // Cache rendered content to avoid unnecessary re-renders
  241. const renderCodeContent = useMemo(() => {
  242. const content = String(children).replace(/\n$/, '')
  243. switch (language) {
  244. case 'mermaid':
  245. if (isSVG)
  246. return <Flowchart PrimitiveCode={content} />
  247. break
  248. case 'echarts': {
  249. // Loading state: show loading indicator
  250. if (chartState === 'loading') {
  251. return (
  252. <div style={{
  253. minHeight: '350px',
  254. width: '100%',
  255. display: 'flex',
  256. flexDirection: 'column',
  257. alignItems: 'center',
  258. justifyContent: 'center',
  259. borderBottomLeftRadius: '10px',
  260. borderBottomRightRadius: '10px',
  261. backgroundColor: isDarkMode ? 'var(--color-components-input-bg-normal)' : 'transparent',
  262. color: 'var(--color-text-secondary)',
  263. }}>
  264. <div style={{
  265. marginBottom: '12px',
  266. width: '24px',
  267. height: '24px',
  268. }}>
  269. {/* Rotating spinner that works in both light and dark modes */}
  270. <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' }}>
  271. <style>
  272. {`
  273. @keyframes spin {
  274. 0% { transform: rotate(0deg); }
  275. 100% { transform: rotate(360deg); }
  276. }
  277. `}
  278. </style>
  279. <circle opacity="0.2" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />
  280. <path d="M12 2C6.47715 2 2 6.47715 2 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
  281. </svg>
  282. </div>
  283. <div style={{
  284. fontFamily: 'var(--font-family)',
  285. fontSize: '14px',
  286. }}>Chart loading...</div>
  287. </div>
  288. )
  289. }
  290. // Success state: show the chart
  291. if (chartState === 'success' && finalChartOption) {
  292. // Reset finished event counter
  293. finishedEventCountRef.current = 0
  294. return (
  295. <div style={{
  296. minWidth: '300px',
  297. minHeight: '350px',
  298. width: '100%',
  299. overflowX: 'auto',
  300. borderBottomLeftRadius: '10px',
  301. borderBottomRightRadius: '10px',
  302. transition: 'background-color 0.3s ease',
  303. }}>
  304. <ErrorBoundary>
  305. <ReactEcharts
  306. ref={(e) => {
  307. if (e && isInitialRenderRef.current) {
  308. echartsRef.current = e
  309. isInitialRenderRef.current = false
  310. }
  311. }}
  312. option={finalChartOption}
  313. style={echartsStyle}
  314. theme={isDarkMode ? 'dark' : undefined}
  315. opts={echartsOpts}
  316. notMerge={false}
  317. lazyUpdate={false}
  318. onEvents={echartsEvents}
  319. onChartReady={handleChartReady}
  320. />
  321. </ErrorBoundary>
  322. </div>
  323. )
  324. }
  325. // Error state: show error message
  326. const errorOption = {
  327. title: {
  328. text: 'ECharts error - Wrong option.',
  329. },
  330. }
  331. return (
  332. <div style={{
  333. minWidth: '300px',
  334. minHeight: '350px',
  335. width: '100%',
  336. overflowX: 'auto',
  337. borderBottomLeftRadius: '10px',
  338. borderBottomRightRadius: '10px',
  339. transition: 'background-color 0.3s ease',
  340. }}>
  341. <ErrorBoundary>
  342. <ReactEcharts
  343. ref={echartsRef}
  344. option={errorOption}
  345. style={echartsStyle}
  346. theme={isDarkMode ? 'dark' : undefined}
  347. opts={echartsOpts}
  348. notMerge={true}
  349. />
  350. </ErrorBoundary>
  351. </div>
  352. )
  353. }
  354. case 'svg':
  355. if (isSVG) {
  356. return (
  357. <ErrorBoundary>
  358. <SVGRenderer content={content} />
  359. </ErrorBoundary>
  360. )
  361. }
  362. break
  363. case 'abc':
  364. return (
  365. <ErrorBoundary>
  366. <MarkdownMusic children={content} />
  367. </ErrorBoundary>
  368. )
  369. default:
  370. return (
  371. <SyntaxHighlighter
  372. {...props}
  373. style={theme === Theme.light ? atelierHeathLight : atelierHeathDark}
  374. customStyle={{
  375. paddingLeft: 12,
  376. borderBottomLeftRadius: '10px',
  377. borderBottomRightRadius: '10px',
  378. backgroundColor: 'var(--color-components-input-bg-normal)',
  379. }}
  380. language={match?.[1]}
  381. showLineNumbers
  382. PreTag="div"
  383. >
  384. {content}
  385. </SyntaxHighlighter>
  386. )
  387. }
  388. }, [children, language, isSVG, finalChartOption, props, theme, match, chartState, isDarkMode, echartsStyle, echartsOpts, handleChartReady, echartsEvents])
  389. if (inline || !match)
  390. return <code {...props} className={className}>{children}</code>
  391. return (
  392. <div className='relative'>
  393. <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'>
  394. <div className='system-xs-semibold-uppercase text-text-secondary'>{languageShowName}</div>
  395. <div className='flex items-center gap-1'>
  396. {(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  397. <ActionButton>
  398. <CopyIcon content={String(children).replace(/\n$/, '')} />
  399. </ActionButton>
  400. </div>
  401. </div>
  402. {renderCodeContent}
  403. </div>
  404. )
  405. })
  406. CodeBlock.displayName = 'CodeBlock'
  407. export default CodeBlock