Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441
  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. type 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. return <Flowchart PrimitiveCode={content} theme={theme as 'light' | 'dark'} />
  246. case 'echarts': {
  247. // Loading state: show loading indicator
  248. if (chartState === 'loading') {
  249. return (
  250. <div style={{
  251. minHeight: '350px',
  252. width: '100%',
  253. display: 'flex',
  254. flexDirection: 'column',
  255. alignItems: 'center',
  256. justifyContent: 'center',
  257. borderBottomLeftRadius: '10px',
  258. borderBottomRightRadius: '10px',
  259. backgroundColor: isDarkMode ? 'var(--color-components-input-bg-normal)' : 'transparent',
  260. color: 'var(--color-text-secondary)',
  261. }}>
  262. <div style={{
  263. marginBottom: '12px',
  264. width: '24px',
  265. height: '24px',
  266. }}>
  267. {/* Rotating spinner that works in both light and dark modes */}
  268. <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' }}>
  269. <style>
  270. {`
  271. @keyframes spin {
  272. 0% { transform: rotate(0deg); }
  273. 100% { transform: rotate(360deg); }
  274. }
  275. `}
  276. </style>
  277. <circle opacity="0.2" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="2" />
  278. <path d="M12 2C6.47715 2 2 6.47715 2 12" stroke="currentColor" strokeWidth="2" strokeLinecap="round" />
  279. </svg>
  280. </div>
  281. <div style={{
  282. fontFamily: 'var(--font-family)',
  283. fontSize: '14px',
  284. }}>Chart loading...</div>
  285. </div>
  286. )
  287. }
  288. // Success state: show the chart
  289. if (chartState === 'success' && finalChartOption) {
  290. // Reset finished event counter
  291. finishedEventCountRef.current = 0
  292. return (
  293. <div style={{
  294. minWidth: '300px',
  295. minHeight: '350px',
  296. width: '100%',
  297. overflowX: 'auto',
  298. borderBottomLeftRadius: '10px',
  299. borderBottomRightRadius: '10px',
  300. transition: 'background-color 0.3s ease',
  301. }}>
  302. <ErrorBoundary>
  303. <ReactEcharts
  304. ref={(e) => {
  305. if (e && isInitialRenderRef.current) {
  306. echartsRef.current = e
  307. isInitialRenderRef.current = false
  308. }
  309. }}
  310. option={finalChartOption}
  311. style={echartsStyle}
  312. theme={isDarkMode ? 'dark' : undefined}
  313. opts={echartsOpts}
  314. notMerge={false}
  315. lazyUpdate={false}
  316. onEvents={echartsEvents}
  317. onChartReady={handleChartReady}
  318. />
  319. </ErrorBoundary>
  320. </div>
  321. )
  322. }
  323. // Error state: show error message
  324. const errorOption = {
  325. title: {
  326. text: 'ECharts error - Wrong option.',
  327. },
  328. }
  329. return (
  330. <div style={{
  331. minWidth: '300px',
  332. minHeight: '350px',
  333. width: '100%',
  334. overflowX: 'auto',
  335. borderBottomLeftRadius: '10px',
  336. borderBottomRightRadius: '10px',
  337. transition: 'background-color 0.3s ease',
  338. }}>
  339. <ErrorBoundary>
  340. <ReactEcharts
  341. ref={echartsRef}
  342. option={errorOption}
  343. style={echartsStyle}
  344. theme={isDarkMode ? 'dark' : undefined}
  345. opts={echartsOpts}
  346. notMerge={true}
  347. />
  348. </ErrorBoundary>
  349. </div>
  350. )
  351. }
  352. case 'svg':
  353. if (isSVG) {
  354. return (
  355. <ErrorBoundary>
  356. <SVGRenderer content={content} />
  357. </ErrorBoundary>
  358. )
  359. }
  360. break
  361. case 'abc':
  362. return (
  363. <ErrorBoundary>
  364. <MarkdownMusic children={content} />
  365. </ErrorBoundary>
  366. )
  367. default:
  368. return (
  369. <SyntaxHighlighter
  370. {...props}
  371. style={theme === Theme.light ? atelierHeathLight : atelierHeathDark}
  372. customStyle={{
  373. paddingLeft: 12,
  374. borderBottomLeftRadius: '10px',
  375. borderBottomRightRadius: '10px',
  376. backgroundColor: 'var(--color-components-input-bg-normal)',
  377. }}
  378. language={match?.[1]}
  379. showLineNumbers
  380. PreTag="div"
  381. >
  382. {content}
  383. </SyntaxHighlighter>
  384. )
  385. }
  386. }, [children, language, isSVG, finalChartOption, props, theme, match, chartState, isDarkMode, echartsStyle, echartsOpts, handleChartReady, echartsEvents])
  387. if (inline || !match)
  388. return <code {...props} className={className}>{children}</code>
  389. return (
  390. <div className='relative'>
  391. <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'>
  392. <div className='system-xs-semibold-uppercase text-text-secondary'>{languageShowName}</div>
  393. <div className='flex items-center gap-1'>
  394. {language === 'svg' && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG} />}
  395. <ActionButton>
  396. <CopyIcon content={String(children).replace(/\n$/, '')} />
  397. </ActionButton>
  398. </div>
  399. </div>
  400. {renderCodeContent}
  401. </div>
  402. )
  403. })
  404. CodeBlock.displayName = 'CodeBlock'
  405. export default CodeBlock