Você não pode selecionar mais de 25 tópicos Os tópicos devem começar com uma letra ou um número, podem incluir traços ('-') e podem ter até 35 caracteres.

index.tsx 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579
  1. import React, { useCallback, useEffect, useRef, useState } from 'react'
  2. import mermaid, { type MermaidConfig } from 'mermaid'
  3. import { useTranslation } from 'react-i18next'
  4. import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
  5. import { MoonIcon, SunIcon } from '@heroicons/react/24/solid'
  6. import {
  7. cleanUpSvgCode,
  8. isMermaidCodeComplete,
  9. prepareMermaidCode,
  10. processSvgForTheme,
  11. svgToBase64,
  12. waitForDOMElement,
  13. } from './utils'
  14. import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'
  15. import cn from '@/utils/classnames'
  16. import ImagePreview from '@/app/components/base/image-uploader/image-preview'
  17. import { Theme } from '@/types/app'
  18. // Global flags and cache for mermaid
  19. let isMermaidInitialized = false
  20. const diagramCache = new Map<string, string>()
  21. let mermaidAPI: any = null
  22. if (typeof window !== 'undefined')
  23. mermaidAPI = mermaid.mermaidAPI
  24. // Theme configurations
  25. const THEMES = {
  26. light: {
  27. name: 'Light Theme',
  28. background: '#ffffff',
  29. primaryColor: '#ffffff',
  30. primaryBorderColor: '#000000',
  31. primaryTextColor: '#000000',
  32. secondaryColor: '#ffffff',
  33. tertiaryColor: '#ffffff',
  34. nodeColors: [
  35. { bg: '#f0f9ff', color: '#0369a1' },
  36. { bg: '#f0fdf4', color: '#166534' },
  37. { bg: '#fef2f2', color: '#b91c1c' },
  38. { bg: '#faf5ff', color: '#7e22ce' },
  39. { bg: '#fffbeb', color: '#b45309' },
  40. ],
  41. connectionColor: '#74a0e0',
  42. },
  43. dark: {
  44. name: 'Dark Theme',
  45. background: '#1e293b',
  46. primaryColor: '#334155',
  47. primaryBorderColor: '#94a3b8',
  48. primaryTextColor: '#e2e8f0',
  49. secondaryColor: '#475569',
  50. tertiaryColor: '#334155',
  51. nodeColors: [
  52. { bg: '#164e63', color: '#e0f2fe' },
  53. { bg: '#14532d', color: '#dcfce7' },
  54. { bg: '#7f1d1d', color: '#fee2e2' },
  55. { bg: '#581c87', color: '#f3e8ff' },
  56. { bg: '#78350f', color: '#fef3c7' },
  57. ],
  58. connectionColor: '#60a5fa',
  59. },
  60. }
  61. /**
  62. * Initializes mermaid library with default configuration
  63. */
  64. const initMermaid = () => {
  65. if (typeof window !== 'undefined' && !isMermaidInitialized) {
  66. try {
  67. const config: MermaidConfig = {
  68. startOnLoad: false,
  69. fontFamily: 'sans-serif',
  70. securityLevel: 'loose',
  71. flowchart: {
  72. htmlLabels: true,
  73. useMaxWidth: true,
  74. curve: 'basis',
  75. nodeSpacing: 50,
  76. rankSpacing: 70,
  77. },
  78. gantt: {
  79. titleTopMargin: 25,
  80. barHeight: 20,
  81. barGap: 4,
  82. topPadding: 50,
  83. leftPadding: 75,
  84. gridLineStartPadding: 35,
  85. fontSize: 11,
  86. numberSectionStyles: 4,
  87. axisFormat: '%Y-%m-%d',
  88. },
  89. mindmap: {
  90. useMaxWidth: true,
  91. padding: 10,
  92. },
  93. maxTextSize: 50000,
  94. }
  95. mermaid.initialize(config)
  96. isMermaidInitialized = true
  97. }
  98. catch (error) {
  99. console.error('Mermaid initialization error:', error)
  100. return null
  101. }
  102. }
  103. return isMermaidInitialized
  104. }
  105. const Flowchart = React.forwardRef((props: {
  106. PrimitiveCode: string
  107. theme?: 'light' | 'dark'
  108. }, ref) => {
  109. const { t } = useTranslation()
  110. const [svgString, setSvgString] = useState<string | null>(null)
  111. const [look, setLook] = useState<'classic' | 'handDrawn'>('classic')
  112. const [isInitialized, setIsInitialized] = useState(false)
  113. const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>(props.theme || 'light')
  114. const containerRef = useRef<HTMLDivElement>(null)
  115. const chartId = useRef(`mermaid-chart-${Math.random().toString(36).slice(2, 11)}`).current
  116. const [isLoading, setIsLoading] = useState(true)
  117. const renderTimeoutRef = useRef<NodeJS.Timeout>()
  118. const [errMsg, setErrMsg] = useState('')
  119. const [imagePreviewUrl, setImagePreviewUrl] = useState('')
  120. /**
  121. * Renders Mermaid chart
  122. */
  123. const renderMermaidChart = async (code: string, style: 'classic' | 'handDrawn') => {
  124. if (style === 'handDrawn') {
  125. // Special handling for hand-drawn style
  126. if (containerRef.current)
  127. containerRef.current.innerHTML = `<div id="${chartId}"></div>`
  128. await new Promise(resolve => setTimeout(resolve, 30))
  129. if (typeof window !== 'undefined' && mermaidAPI) {
  130. // Prefer using mermaidAPI directly for hand-drawn style
  131. return await mermaidAPI.render(chartId, code)
  132. }
  133. else {
  134. // Fall back to standard rendering if mermaidAPI is not available
  135. const { svg } = await mermaid.render(chartId, code)
  136. return { svg }
  137. }
  138. }
  139. else {
  140. // Standard rendering for classic style - using the extracted waitForDOMElement function
  141. const renderWithRetry = async () => {
  142. if (containerRef.current)
  143. containerRef.current.innerHTML = `<div id="${chartId}"></div>`
  144. await new Promise(resolve => setTimeout(resolve, 30))
  145. const { svg } = await mermaid.render(chartId, code)
  146. return { svg }
  147. }
  148. return await waitForDOMElement(renderWithRetry)
  149. }
  150. }
  151. /**
  152. * Handle rendering errors
  153. */
  154. const handleRenderError = (error: any) => {
  155. console.error('Mermaid rendering error:', error)
  156. // On any render error, assume the mermaid state is corrupted and force a re-initialization.
  157. try {
  158. diagramCache.clear() // Clear cache to prevent using potentially corrupted SVGs
  159. isMermaidInitialized = false // <-- THE FIX: Force re-initialization
  160. initMermaid() // Re-initialize with the default safe configuration
  161. }
  162. catch (reinitError) {
  163. console.error('Failed to re-initialize Mermaid after error:', reinitError)
  164. }
  165. setErrMsg(`Rendering failed: ${(error as Error).message || 'Unknown error. Please check the console.'}`)
  166. setIsLoading(false)
  167. }
  168. // Initialize mermaid
  169. useEffect(() => {
  170. const api = initMermaid()
  171. if (api)
  172. setIsInitialized(true)
  173. }, [])
  174. // Update theme when prop changes, but allow internal override.
  175. const prevThemeRef = useRef<string>()
  176. useEffect(() => {
  177. // Only react if the theme prop from the outside has actually changed.
  178. if (props.theme && props.theme !== prevThemeRef.current) {
  179. // When the global theme prop changes, it should act as the source of truth,
  180. // overriding any local theme selection.
  181. diagramCache.clear()
  182. setSvgString(null)
  183. setCurrentTheme(props.theme)
  184. // Reset look to classic for a consistent state after a global change.
  185. setLook('classic')
  186. }
  187. // Update the ref to the current prop value for the next render.
  188. prevThemeRef.current = props.theme
  189. }, [props.theme])
  190. const renderFlowchart = useCallback(async (primitiveCode: string) => {
  191. if (!isInitialized || !containerRef.current) {
  192. setIsLoading(false)
  193. setErrMsg(!isInitialized ? 'Mermaid initialization failed' : 'Container element not found')
  194. return
  195. }
  196. // Return cached result if available
  197. const cacheKey = `${primitiveCode}-${look}-${currentTheme}`
  198. if (diagramCache.has(cacheKey)) {
  199. setErrMsg('')
  200. setSvgString(diagramCache.get(cacheKey) || null)
  201. setIsLoading(false)
  202. return
  203. }
  204. setIsLoading(true)
  205. setErrMsg('')
  206. try {
  207. let finalCode: string
  208. const trimmedCode = primitiveCode.trim()
  209. const isGantt = trimmedCode.startsWith('gantt')
  210. const isMindMap = trimmedCode.startsWith('mindmap')
  211. const isSequence = trimmedCode.startsWith('sequenceDiagram')
  212. if (isGantt || isMindMap || isSequence) {
  213. if (isGantt) {
  214. finalCode = trimmedCode
  215. .split('\n')
  216. .map((line) => {
  217. // Gantt charts have specific syntax needs.
  218. const taskMatch = line.match(/^\s*([^:]+?)\s*:\s*(.*)/)
  219. if (!taskMatch)
  220. return line // Not a task line, return as is.
  221. const taskName = taskMatch[1].trim()
  222. let paramsStr = taskMatch[2].trim()
  223. // Rule 1: Correct multiple "after" dependencies ONLY if they exist.
  224. // This is a common mistake, e.g., "..., after task1, after task2, ..."
  225. const afterCount = (paramsStr.match(/after /g) || []).length
  226. if (afterCount > 1)
  227. paramsStr = paramsStr.replace(/,\s*after\s+/g, ' ')
  228. // Rule 2: Normalize spacing between parameters for consistency.
  229. const finalParams = paramsStr.replace(/\s*,\s*/g, ', ').trim()
  230. return `${taskName} :${finalParams}`
  231. })
  232. .join('\n')
  233. }
  234. else {
  235. // For mindmap and sequence charts, which are sensitive to syntax,
  236. // pass the code through directly.
  237. finalCode = trimmedCode
  238. }
  239. }
  240. else {
  241. // Step 1: Clean and prepare Mermaid code using the extracted prepareMermaidCode function
  242. // This function handles flowcharts appropriately.
  243. finalCode = prepareMermaidCode(primitiveCode, look)
  244. }
  245. // Step 2: Render chart
  246. const svgGraph = await renderMermaidChart(finalCode, look)
  247. // Step 3: Apply theme to SVG using the extracted processSvgForTheme function
  248. const processedSvg = processSvgForTheme(
  249. svgGraph.svg,
  250. currentTheme === Theme.dark,
  251. look === 'handDrawn',
  252. THEMES,
  253. )
  254. // Step 4: Clean up SVG code
  255. const cleanedSvg = cleanUpSvgCode(processedSvg)
  256. if (cleanedSvg && typeof cleanedSvg === 'string') {
  257. diagramCache.set(cacheKey, cleanedSvg)
  258. setSvgString(cleanedSvg)
  259. }
  260. setIsLoading(false)
  261. }
  262. catch (error) {
  263. // Error handling
  264. handleRenderError(error)
  265. }
  266. }, [chartId, isInitialized, look, currentTheme, t])
  267. const configureMermaid = useCallback((primitiveCode: string) => {
  268. if (typeof window !== 'undefined' && isInitialized) {
  269. const themeVars = THEMES[currentTheme]
  270. const config: any = {
  271. startOnLoad: false,
  272. securityLevel: 'loose',
  273. fontFamily: 'sans-serif',
  274. maxTextSize: 50000,
  275. gantt: {
  276. titleTopMargin: 25,
  277. barHeight: 20,
  278. barGap: 4,
  279. topPadding: 50,
  280. leftPadding: 75,
  281. gridLineStartPadding: 35,
  282. fontSize: 11,
  283. numberSectionStyles: 4,
  284. axisFormat: '%Y-%m-%d',
  285. },
  286. mindmap: {
  287. useMaxWidth: true,
  288. padding: 10,
  289. },
  290. }
  291. const isFlowchart = primitiveCode.trim().startsWith('graph') || primitiveCode.trim().startsWith('flowchart')
  292. if (look === 'classic') {
  293. config.theme = currentTheme === 'dark' ? 'dark' : 'neutral'
  294. if (isFlowchart) {
  295. config.flowchart = {
  296. htmlLabels: true,
  297. useMaxWidth: true,
  298. nodeSpacing: 60,
  299. rankSpacing: 80,
  300. curve: 'linear',
  301. ranker: 'tight-tree',
  302. }
  303. }
  304. if (currentTheme === 'dark') {
  305. config.themeVariables = {
  306. background: themeVars.background,
  307. primaryColor: themeVars.primaryColor,
  308. primaryBorderColor: themeVars.primaryBorderColor,
  309. primaryTextColor: themeVars.primaryTextColor,
  310. secondaryColor: themeVars.secondaryColor,
  311. tertiaryColor: themeVars.tertiaryColor,
  312. }
  313. }
  314. }
  315. else { // look === 'handDrawn'
  316. config.theme = 'default'
  317. config.themeCSS = `
  318. .node rect { fill-opacity: 0.85; }
  319. .edgePath .path { stroke-width: 1.5px; }
  320. .label { font-family: 'sans-serif'; }
  321. .edgeLabel { font-family: 'sans-serif'; }
  322. .cluster rect { rx: 5px; ry: 5px; }
  323. `
  324. config.themeVariables = {
  325. fontSize: '14px',
  326. fontFamily: 'sans-serif',
  327. primaryBorderColor: currentTheme === 'dark' ? THEMES.dark.connectionColor : THEMES.light.connectionColor,
  328. }
  329. if (isFlowchart) {
  330. config.flowchart = {
  331. htmlLabels: true,
  332. useMaxWidth: true,
  333. nodeSpacing: 40,
  334. rankSpacing: 60,
  335. curve: 'basis',
  336. }
  337. }
  338. }
  339. try {
  340. mermaid.initialize(config)
  341. return true
  342. }
  343. catch (error) {
  344. console.error('Config error:', error)
  345. return false
  346. }
  347. }
  348. return false
  349. }, [currentTheme, isInitialized, look])
  350. // This is the main rendering effect.
  351. // It triggers whenever the code, theme, or style changes.
  352. useEffect(() => {
  353. if (!isInitialized)
  354. return
  355. // Don't render if code is too short
  356. if (!props.PrimitiveCode || props.PrimitiveCode.length < 10) {
  357. setIsLoading(false)
  358. setSvgString(null)
  359. return
  360. }
  361. // Use a timeout to handle streaming code and debounce rendering
  362. if (renderTimeoutRef.current)
  363. clearTimeout(renderTimeoutRef.current)
  364. setIsLoading(true)
  365. renderTimeoutRef.current = setTimeout(() => {
  366. // Final validation before rendering
  367. if (!isMermaidCodeComplete(props.PrimitiveCode)) {
  368. setIsLoading(false)
  369. setErrMsg('Diagram code is not complete or invalid.')
  370. return
  371. }
  372. const cacheKey = `${props.PrimitiveCode}-${look}-${currentTheme}`
  373. if (diagramCache.has(cacheKey)) {
  374. setErrMsg('')
  375. setSvgString(diagramCache.get(cacheKey) || null)
  376. setIsLoading(false)
  377. return
  378. }
  379. if (configureMermaid(props.PrimitiveCode))
  380. renderFlowchart(props.PrimitiveCode)
  381. }, 300) // 300ms debounce
  382. return () => {
  383. if (renderTimeoutRef.current)
  384. clearTimeout(renderTimeoutRef.current)
  385. }
  386. }, [props.PrimitiveCode, look, currentTheme, isInitialized, configureMermaid, renderFlowchart])
  387. // Cleanup on unmount
  388. useEffect(() => {
  389. return () => {
  390. if (containerRef.current)
  391. containerRef.current.innerHTML = ''
  392. if (renderTimeoutRef.current)
  393. clearTimeout(renderTimeoutRef.current)
  394. }
  395. }, [])
  396. const handlePreviewClick = async () => {
  397. if (svgString) {
  398. const base64 = await svgToBase64(svgString)
  399. setImagePreviewUrl(base64)
  400. }
  401. }
  402. const toggleTheme = () => {
  403. const newTheme = currentTheme === 'light' ? 'dark' : 'light'
  404. // Ensure a full, clean re-render cycle, consistent with global theme change.
  405. diagramCache.clear()
  406. setSvgString(null)
  407. setCurrentTheme(newTheme)
  408. }
  409. // Style classes for theme-dependent elements
  410. const themeClasses = {
  411. container: cn('relative', {
  412. 'bg-white': currentTheme === Theme.light,
  413. 'bg-slate-900': currentTheme === Theme.dark,
  414. }),
  415. mermaidDiv: cn('mermaid relative h-auto w-full cursor-pointer', {
  416. 'bg-white': currentTheme === Theme.light,
  417. 'bg-slate-900': currentTheme === Theme.dark,
  418. }),
  419. errorMessage: cn('px-[26px] py-4', {
  420. 'text-red-500': currentTheme === Theme.light,
  421. 'text-red-400': currentTheme === Theme.dark,
  422. }),
  423. errorIcon: cn('h-6 w-6', {
  424. 'text-red-500': currentTheme === Theme.light,
  425. 'text-red-400': currentTheme === Theme.dark,
  426. }),
  427. segmented: cn('msh-segmented msh-segmented-sm css-23bs09 css-var-r1', {
  428. 'text-gray-700': currentTheme === Theme.light,
  429. 'text-gray-300': currentTheme === Theme.dark,
  430. }),
  431. themeToggle: cn('flex h-10 w-10 items-center justify-center rounded-full shadow-md backdrop-blur-sm transition-all duration-300', {
  432. 'bg-white/80 hover:bg-white hover:shadow-lg text-gray-700 border border-gray-200': currentTheme === Theme.light,
  433. 'bg-slate-800/80 hover:bg-slate-700 hover:shadow-lg text-yellow-300 border border-slate-600': currentTheme === Theme.dark,
  434. }),
  435. }
  436. // Style classes for look options
  437. const getLookButtonClass = (lookType: 'classic' | 'handDrawn') => {
  438. return cn(
  439. 'system-sm-medium mb-4 flex h-8 w-[calc((100%-8px)/2)] cursor-pointer items-center justify-center rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg text-text-secondary',
  440. look === lookType && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary',
  441. currentTheme === Theme.dark && 'border-slate-600 bg-slate-800 text-slate-300',
  442. look === lookType && currentTheme === Theme.dark && 'border-blue-500 bg-slate-700 text-white',
  443. )
  444. }
  445. return (
  446. <div ref={ref as React.RefObject<HTMLDivElement>} className={themeClasses.container}>
  447. <div className={themeClasses.segmented}>
  448. <div className="msh-segmented-group">
  449. <label className="msh-segmented-item m-2 flex w-[200px] items-center space-x-1">
  450. <div
  451. key='classic'
  452. className={getLookButtonClass('classic')}
  453. onClick={() => {
  454. if (look !== 'classic') {
  455. diagramCache.clear()
  456. setSvgString(null)
  457. setLook('classic')
  458. }
  459. }}
  460. >
  461. <div className="msh-segmented-item-label">{t('app.mermaid.classic')}</div>
  462. </div>
  463. <div
  464. key='handDrawn'
  465. className={getLookButtonClass('handDrawn')}
  466. onClick={() => {
  467. if (look !== 'handDrawn') {
  468. diagramCache.clear()
  469. setSvgString(null)
  470. setLook('handDrawn')
  471. }
  472. }}
  473. >
  474. <div className="msh-segmented-item-label">{t('app.mermaid.handDrawn')}</div>
  475. </div>
  476. </label>
  477. </div>
  478. </div>
  479. <div ref={containerRef} style={{ position: 'absolute', visibility: 'hidden', height: 0, overflow: 'hidden' }} />
  480. {isLoading && !svgString && (
  481. <div className='px-[26px] py-4'>
  482. <LoadingAnim type='text'/>
  483. <div className="mt-2 text-sm text-gray-500">
  484. {t('common.wait_for_completion', 'Waiting for diagram code to complete...')}
  485. </div>
  486. </div>
  487. )}
  488. {svgString && (
  489. <div className={themeClasses.mermaidDiv} style={{ objectFit: 'cover' }} onClick={handlePreviewClick}>
  490. <div className="absolute bottom-2 left-2 z-[100]">
  491. <button
  492. onClick={(e) => {
  493. e.stopPropagation()
  494. toggleTheme()
  495. }}
  496. className={themeClasses.themeToggle}
  497. title={(currentTheme === Theme.light ? t('app.theme.switchDark') : t('app.theme.switchLight')) || ''}
  498. style={{ transform: 'translate3d(0, 0, 0)' }}
  499. >
  500. {currentTheme === Theme.light ? <MoonIcon className="h-5 w-5" /> : <SunIcon className="h-5 w-5" />}
  501. </button>
  502. </div>
  503. <div
  504. style={{ maxWidth: '100%' }}
  505. dangerouslySetInnerHTML={{ __html: svgString }}
  506. />
  507. </div>
  508. )}
  509. {errMsg && (
  510. <div className={themeClasses.errorMessage}>
  511. <div className="flex items-center">
  512. <ExclamationTriangleIcon className={themeClasses.errorIcon}/>
  513. <span className="ml-2">{errMsg}</span>
  514. </div>
  515. </div>
  516. )}
  517. {imagePreviewUrl && (
  518. <ImagePreview title='mermaid_chart' url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} />
  519. )}
  520. </div>
  521. )
  522. })
  523. Flowchart.displayName = 'Flowchart'
  524. export default Flowchart