Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

code-block.tsx 15KB

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