Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

index.tsx 19KB

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