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.

index.tsx 19KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590
  1. import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react'
  2. import mermaid 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. mermaid.initialize({
  68. startOnLoad: false,
  69. fontFamily: 'sans-serif',
  70. securityLevel: 'loose',
  71. flowchart: {
  72. htmlLabels: true,
  73. useMaxWidth: true,
  74. diagramPadding: 10,
  75. curve: 'basis',
  76. nodeSpacing: 50,
  77. rankSpacing: 70,
  78. },
  79. gantt: {
  80. titleTopMargin: 25,
  81. barHeight: 20,
  82. barGap: 4,
  83. topPadding: 50,
  84. leftPadding: 75,
  85. gridLineStartPadding: 35,
  86. fontSize: 11,
  87. numberSectionStyles: 4,
  88. axisFormat: '%Y-%m-%d',
  89. },
  90. maxTextSize: 50000,
  91. })
  92. isMermaidInitialized = true
  93. }
  94. catch (error) {
  95. console.error('Mermaid initialization error:', error)
  96. return null
  97. }
  98. }
  99. return isMermaidInitialized
  100. }
  101. const Flowchart = React.forwardRef((props: {
  102. PrimitiveCode: string
  103. theme?: 'light' | 'dark'
  104. }, ref) => {
  105. const { t } = useTranslation()
  106. const [svgCode, setSvgCode] = useState<string | null>(null)
  107. const [look, setLook] = useState<'classic' | 'handDrawn'>('classic')
  108. const [isInitialized, setIsInitialized] = useState(false)
  109. const [currentTheme, setCurrentTheme] = useState<'light' | 'dark'>(props.theme || 'light')
  110. const containerRef = useRef<HTMLDivElement>(null)
  111. const chartId = useRef(`mermaid-chart-${Math.random().toString(36).substr(2, 9)}`).current
  112. const [isLoading, setIsLoading] = useState(true)
  113. const renderTimeoutRef = useRef<NodeJS.Timeout>()
  114. const [errMsg, setErrMsg] = useState('')
  115. const [imagePreviewUrl, setImagePreviewUrl] = useState('')
  116. const [isCodeComplete, setIsCodeComplete] = useState(false)
  117. const codeCompletionCheckRef = useRef<NodeJS.Timeout>()
  118. // Create cache key from code, style and theme
  119. const cacheKey = useMemo(() => {
  120. return `${props.PrimitiveCode}-${look}-${currentTheme}`
  121. }, [props.PrimitiveCode, look, currentTheme])
  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. const errorMsg = (error as Error).message
  159. if (errorMsg.includes('getAttribute')) {
  160. diagramCache.clear()
  161. mermaid.initialize({
  162. startOnLoad: false,
  163. securityLevel: 'loose',
  164. })
  165. }
  166. else {
  167. setErrMsg(`Rendering chart failed, please refresh and try again ${look === 'handDrawn' ? 'Or try using classic mode' : ''}`)
  168. }
  169. if (look === 'handDrawn') {
  170. try {
  171. // Clear possible cache issues
  172. diagramCache.delete(`${props.PrimitiveCode}-handDrawn-${currentTheme}`)
  173. // Reset mermaid configuration
  174. mermaid.initialize({
  175. startOnLoad: false,
  176. securityLevel: 'loose',
  177. theme: 'default',
  178. maxTextSize: 50000,
  179. })
  180. // Try rendering with standard mode
  181. setLook('classic')
  182. setErrMsg('Hand-drawn mode is not supported for this diagram. Switched to classic mode.')
  183. // Delay error clearing
  184. setTimeout(() => {
  185. if (containerRef.current) {
  186. // Try rendering again with standard mode, but can't call renderFlowchart directly due to circular dependency
  187. // Instead set state to trigger re-render
  188. setIsCodeComplete(true) // This will trigger useEffect re-render
  189. }
  190. }, 500)
  191. }
  192. catch (e) {
  193. console.error('Reset after handDrawn error failed:', e)
  194. }
  195. }
  196. setIsLoading(false)
  197. }
  198. // Initialize mermaid
  199. useEffect(() => {
  200. const api = initMermaid()
  201. if (api)
  202. setIsInitialized(true)
  203. }, [])
  204. // Update theme when prop changes
  205. useEffect(() => {
  206. if (props.theme)
  207. setCurrentTheme(props.theme)
  208. }, [props.theme])
  209. // Validate mermaid code and check for completeness
  210. useEffect(() => {
  211. if (codeCompletionCheckRef.current)
  212. clearTimeout(codeCompletionCheckRef.current)
  213. // Reset code complete status when code changes
  214. setIsCodeComplete(false)
  215. // If no code or code is extremely short, don't proceed
  216. if (!props.PrimitiveCode || props.PrimitiveCode.length < 10)
  217. return
  218. // Check if code already in cache - if so we know it's valid
  219. if (diagramCache.has(cacheKey)) {
  220. setIsCodeComplete(true)
  221. return
  222. }
  223. // Initial check using the extracted isMermaidCodeComplete function
  224. const isComplete = isMermaidCodeComplete(props.PrimitiveCode)
  225. if (isComplete) {
  226. setIsCodeComplete(true)
  227. return
  228. }
  229. // Set a delay to check again in case code is still being generated
  230. codeCompletionCheckRef.current = setTimeout(() => {
  231. setIsCodeComplete(isMermaidCodeComplete(props.PrimitiveCode))
  232. }, 300)
  233. return () => {
  234. if (codeCompletionCheckRef.current)
  235. clearTimeout(codeCompletionCheckRef.current)
  236. }
  237. }, [props.PrimitiveCode, cacheKey])
  238. /**
  239. * Renders flowchart based on provided code
  240. */
  241. const renderFlowchart = useCallback(async (primitiveCode: string) => {
  242. if (!isInitialized || !containerRef.current) {
  243. setIsLoading(false)
  244. setErrMsg(!isInitialized ? 'Mermaid initialization failed' : 'Container element not found')
  245. return
  246. }
  247. // Don't render if code is not complete yet
  248. if (!isCodeComplete) {
  249. setIsLoading(true)
  250. return
  251. }
  252. // Return cached result if available
  253. if (diagramCache.has(cacheKey)) {
  254. setSvgCode(diagramCache.get(cacheKey) || null)
  255. setIsLoading(false)
  256. return
  257. }
  258. setIsLoading(true)
  259. setErrMsg('')
  260. try {
  261. let finalCode: string
  262. // Check if it's a gantt chart
  263. const isGanttChart = primitiveCode.trim().startsWith('gantt')
  264. if (isGanttChart) {
  265. // For gantt charts, ensure each task is on its own line
  266. // and preserve exact whitespace/format
  267. finalCode = primitiveCode.trim()
  268. }
  269. else {
  270. // Step 1: Clean and prepare Mermaid code using the extracted prepareMermaidCode function
  271. finalCode = prepareMermaidCode(primitiveCode, look)
  272. }
  273. // Step 2: Render chart
  274. const svgGraph = await renderMermaidChart(finalCode, look)
  275. // Step 3: Apply theme to SVG using the extracted processSvgForTheme function
  276. const processedSvg = processSvgForTheme(
  277. svgGraph.svg,
  278. currentTheme === Theme.dark,
  279. look === 'handDrawn',
  280. THEMES,
  281. )
  282. // Step 4: Clean SVG code and convert to base64 using the extracted functions
  283. const cleanedSvg = cleanUpSvgCode(processedSvg)
  284. const base64Svg = await svgToBase64(cleanedSvg)
  285. if (base64Svg && typeof base64Svg === 'string') {
  286. diagramCache.set(cacheKey, base64Svg)
  287. setSvgCode(base64Svg)
  288. }
  289. setIsLoading(false)
  290. }
  291. catch (error) {
  292. // Error handling
  293. handleRenderError(error)
  294. }
  295. }, [chartId, isInitialized, cacheKey, isCodeComplete, look, currentTheme, t])
  296. /**
  297. * Configure mermaid based on selected style and theme
  298. */
  299. const configureMermaid = useCallback(() => {
  300. if (typeof window !== 'undefined' && isInitialized) {
  301. const themeVars = THEMES[currentTheme]
  302. const config: any = {
  303. startOnLoad: false,
  304. securityLevel: 'loose',
  305. fontFamily: 'sans-serif',
  306. maxTextSize: 50000,
  307. gantt: {
  308. titleTopMargin: 25,
  309. barHeight: 20,
  310. barGap: 4,
  311. topPadding: 50,
  312. leftPadding: 75,
  313. gridLineStartPadding: 35,
  314. fontSize: 11,
  315. numberSectionStyles: 4,
  316. axisFormat: '%Y-%m-%d',
  317. },
  318. }
  319. if (look === 'classic') {
  320. config.theme = currentTheme === 'dark' ? 'dark' : 'neutral'
  321. config.flowchart = {
  322. htmlLabels: true,
  323. useMaxWidth: true,
  324. diagramPadding: 12,
  325. nodeSpacing: 60,
  326. rankSpacing: 80,
  327. curve: 'linear',
  328. ranker: 'tight-tree',
  329. }
  330. }
  331. else {
  332. config.theme = 'default'
  333. config.themeCSS = `
  334. .node rect { fill-opacity: 0.85; }
  335. .edgePath .path { stroke-width: 1.5px; }
  336. .label { font-family: 'sans-serif'; }
  337. .edgeLabel { font-family: 'sans-serif'; }
  338. .cluster rect { rx: 5px; ry: 5px; }
  339. `
  340. config.themeVariables = {
  341. fontSize: '14px',
  342. fontFamily: 'sans-serif',
  343. }
  344. config.flowchart = {
  345. htmlLabels: true,
  346. useMaxWidth: true,
  347. diagramPadding: 10,
  348. nodeSpacing: 40,
  349. rankSpacing: 60,
  350. curve: 'basis',
  351. }
  352. config.themeVariables.primaryBorderColor = currentTheme === 'dark' ? THEMES.dark.connectionColor : THEMES.light.connectionColor
  353. }
  354. if (currentTheme === 'dark' && !config.themeVariables) {
  355. config.themeVariables = {
  356. background: themeVars.background,
  357. primaryColor: themeVars.primaryColor,
  358. primaryBorderColor: themeVars.primaryBorderColor,
  359. primaryTextColor: themeVars.primaryTextColor,
  360. secondaryColor: themeVars.secondaryColor,
  361. tertiaryColor: themeVars.tertiaryColor,
  362. fontFamily: 'sans-serif',
  363. }
  364. }
  365. try {
  366. mermaid.initialize(config)
  367. return true
  368. }
  369. catch (error) {
  370. console.error('Config error:', error)
  371. return false
  372. }
  373. }
  374. return false
  375. }, [currentTheme, isInitialized, look])
  376. // Effect for theme and style configuration
  377. useEffect(() => {
  378. if (diagramCache.has(cacheKey)) {
  379. setSvgCode(diagramCache.get(cacheKey) || null)
  380. setIsLoading(false)
  381. return
  382. }
  383. if (configureMermaid() && containerRef.current && isCodeComplete)
  384. renderFlowchart(props.PrimitiveCode)
  385. }, [look, props.PrimitiveCode, renderFlowchart, isInitialized, cacheKey, currentTheme, isCodeComplete, configureMermaid])
  386. // Effect for rendering with debounce
  387. useEffect(() => {
  388. if (diagramCache.has(cacheKey)) {
  389. setSvgCode(diagramCache.get(cacheKey) || null)
  390. setIsLoading(false)
  391. return
  392. }
  393. if (renderTimeoutRef.current)
  394. clearTimeout(renderTimeoutRef.current)
  395. if (isCodeComplete) {
  396. renderTimeoutRef.current = setTimeout(() => {
  397. if (isInitialized)
  398. renderFlowchart(props.PrimitiveCode)
  399. }, 300)
  400. }
  401. else {
  402. setIsLoading(true)
  403. }
  404. return () => {
  405. if (renderTimeoutRef.current)
  406. clearTimeout(renderTimeoutRef.current)
  407. }
  408. }, [props.PrimitiveCode, renderFlowchart, isInitialized, cacheKey, isCodeComplete])
  409. // Cleanup on unmount
  410. useEffect(() => {
  411. return () => {
  412. if (containerRef.current)
  413. containerRef.current.innerHTML = ''
  414. if (renderTimeoutRef.current)
  415. clearTimeout(renderTimeoutRef.current)
  416. if (codeCompletionCheckRef.current)
  417. clearTimeout(codeCompletionCheckRef.current)
  418. }
  419. }, [])
  420. const toggleTheme = () => {
  421. setCurrentTheme(prevTheme => prevTheme === 'light' ? Theme.dark : Theme.light)
  422. diagramCache.clear()
  423. }
  424. // Style classes for theme-dependent elements
  425. const themeClasses = {
  426. container: cn('relative', {
  427. 'bg-white': currentTheme === Theme.light,
  428. 'bg-slate-900': currentTheme === Theme.dark,
  429. }),
  430. mermaidDiv: cn('mermaid cursor-pointer h-auto w-full relative', {
  431. 'bg-white': currentTheme === Theme.light,
  432. 'bg-slate-900': currentTheme === Theme.dark,
  433. }),
  434. errorMessage: cn('py-4 px-[26px]', {
  435. 'text-red-500': currentTheme === Theme.light,
  436. 'text-red-400': currentTheme === Theme.dark,
  437. }),
  438. errorIcon: cn('w-6 h-6', {
  439. 'text-red-500': currentTheme === Theme.light,
  440. 'text-red-400': currentTheme === Theme.dark,
  441. }),
  442. segmented: cn('msh-segmented msh-segmented-sm css-23bs09 css-var-r1', {
  443. 'text-gray-700': currentTheme === Theme.light,
  444. 'text-gray-300': currentTheme === Theme.dark,
  445. }),
  446. themeToggle: cn('flex items-center justify-center w-10 h-10 rounded-full transition-all duration-300 shadow-md backdrop-blur-sm', {
  447. 'bg-white/80 hover:bg-white hover:shadow-lg text-gray-700 border border-gray-200': currentTheme === Theme.light,
  448. 'bg-slate-800/80 hover:bg-slate-700 hover:shadow-lg text-yellow-300 border border-slate-600': currentTheme === Theme.dark,
  449. }),
  450. }
  451. // Style classes for look options
  452. const getLookButtonClass = (lookType: 'classic' | 'handDrawn') => {
  453. return cn(
  454. 'flex items-center justify-center mb-4 w-[calc((100%-8px)/2)] h-8 rounded-lg border border-components-option-card-option-border bg-components-option-card-option-bg cursor-pointer system-sm-medium text-text-secondary',
  455. look === lookType && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary',
  456. currentTheme === Theme.dark && 'border-slate-600 bg-slate-800 text-slate-300',
  457. look === lookType && currentTheme === Theme.dark && 'border-blue-500 bg-slate-700 text-white',
  458. )
  459. }
  460. return (
  461. <div ref={ref as React.RefObject<HTMLDivElement>} className={themeClasses.container}>
  462. <div className={themeClasses.segmented}>
  463. <div className="msh-segmented-group">
  464. <label className="msh-segmented-item flex items-center space-x-1 m-2 w-[200px]">
  465. <div
  466. key='classic'
  467. className={getLookButtonClass('classic')}
  468. onClick={() => setLook('classic')}
  469. >
  470. <div className="msh-segmented-item-label">{t('app.mermaid.classic')}</div>
  471. </div>
  472. <div
  473. key='handDrawn'
  474. className={getLookButtonClass('handDrawn')}
  475. onClick={() => setLook('handDrawn')}
  476. >
  477. <div className="msh-segmented-item-label">{t('app.mermaid.handDrawn')}</div>
  478. </div>
  479. </label>
  480. </div>
  481. </div>
  482. <div ref={containerRef} style={{ position: 'absolute', visibility: 'hidden', height: 0, overflow: 'hidden' }} />
  483. {isLoading && !svgCode && (
  484. <div className='py-4 px-[26px]'>
  485. <LoadingAnim type='text'/>
  486. {!isCodeComplete && (
  487. <div className="mt-2 text-sm text-gray-500">
  488. {t('common.wait_for_completion', 'Waiting for diagram code to complete...')}
  489. </div>
  490. )}
  491. </div>
  492. )}
  493. {svgCode && (
  494. <div className={themeClasses.mermaidDiv} style={{ objectFit: 'cover' }} onClick={() => setImagePreviewUrl(svgCode)}>
  495. <div className="absolute left-2 bottom-2 z-[100]">
  496. <button
  497. onClick={(e) => {
  498. e.stopPropagation()
  499. toggleTheme()
  500. }}
  501. className={themeClasses.themeToggle}
  502. title={(currentTheme === Theme.light ? t('app.theme.switchDark') : t('app.theme.switchLight')) || ''}
  503. style={{ transform: 'translate3d(0, 0, 0)' }}
  504. >
  505. {currentTheme === Theme.light ? <MoonIcon className="h-5 w-5" /> : <SunIcon className="h-5 w-5" />}
  506. </button>
  507. </div>
  508. <img
  509. src={svgCode}
  510. alt="mermaid_chart"
  511. style={{ maxWidth: '100%' }}
  512. onError={() => { setErrMsg('Chart rendering failed, please refresh and retry') }}
  513. />
  514. </div>
  515. )}
  516. {errMsg && (
  517. <div className={themeClasses.errorMessage}>
  518. <div className="flex items-center">
  519. <ExclamationTriangleIcon className={themeClasses.errorIcon}/>
  520. <span className="ml-2">{errMsg}</span>
  521. </div>
  522. </div>
  523. )}
  524. {imagePreviewUrl && (
  525. <ImagePreview title='mermaid_chart' url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} />
  526. )}
  527. </div>
  528. )
  529. })
  530. Flowchart.displayName = 'Flowchart'
  531. export default Flowchart