index.tsx 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142
  1. import React, { useCallback, useEffect, useRef, useState } from 'react'
  2. import mermaid from 'mermaid'
  3. import { usePrevious } from 'ahooks'
  4. import { useTranslation } from 'react-i18next'
  5. import { ExclamationTriangleIcon } from '@heroicons/react/24/outline'
  6. import { cleanUpSvgCode } from './utils'
  7. import LoadingAnim from '@/app/components/base/chat/chat/loading-anim'
  8. import cn from '@/utils/classnames'
  9. import ImagePreview from '@/app/components/base/image-uploader/image-preview'
  10. let mermaidAPI: any
  11. mermaidAPI = null
  12. if (typeof window !== 'undefined')
  13. mermaidAPI = mermaid.mermaidAPI
  14. const svgToBase64 = (svgGraph: string) => {
  15. const svgBytes = new TextEncoder().encode(svgGraph)
  16. const blob = new Blob([svgBytes], { type: 'image/svg+xml;charset=utf-8' })
  17. return new Promise((resolve, reject) => {
  18. const reader = new FileReader()
  19. reader.onloadend = () => resolve(reader.result)
  20. reader.onerror = reject
  21. reader.readAsDataURL(blob)
  22. })
  23. }
  24. const Flowchart = React.forwardRef((props: {
  25. PrimitiveCode: string
  26. }, ref) => {
  27. const { t } = useTranslation()
  28. const [svgCode, setSvgCode] = useState(null)
  29. const [look, setLook] = useState<'classic' | 'handDrawn'>('classic')
  30. const prevPrimitiveCode = usePrevious(props.PrimitiveCode)
  31. const [isLoading, setIsLoading] = useState(true)
  32. const timeRef = useRef<number>()
  33. const [errMsg, setErrMsg] = useState('')
  34. const [imagePreviewUrl, setImagePreviewUrl] = useState('')
  35. const renderFlowchart = useCallback(async (PrimitiveCode: string) => {
  36. setSvgCode(null)
  37. setIsLoading(true)
  38. try {
  39. if (typeof window !== 'undefined' && mermaidAPI) {
  40. const svgGraph = await mermaidAPI.render('flowchart', PrimitiveCode)
  41. const base64Svg: any = await svgToBase64(cleanUpSvgCode(svgGraph.svg))
  42. setSvgCode(base64Svg)
  43. setIsLoading(false)
  44. }
  45. }
  46. catch (error) {
  47. if (prevPrimitiveCode === props.PrimitiveCode) {
  48. setIsLoading(false)
  49. setErrMsg((error as Error).message)
  50. }
  51. }
  52. }, [props.PrimitiveCode])
  53. useEffect(() => {
  54. if (typeof window !== 'undefined') {
  55. mermaid.initialize({
  56. startOnLoad: true,
  57. theme: 'neutral',
  58. look,
  59. flowchart: {
  60. htmlLabels: true,
  61. useMaxWidth: true,
  62. },
  63. })
  64. renderFlowchart(props.PrimitiveCode)
  65. }
  66. }, [look])
  67. useEffect(() => {
  68. if (timeRef.current)
  69. window.clearTimeout(timeRef.current)
  70. timeRef.current = window.setTimeout(() => {
  71. renderFlowchart(props.PrimitiveCode)
  72. }, 300)
  73. }, [props.PrimitiveCode])
  74. return (
  75. // eslint-disable-next-line ts/ban-ts-comment
  76. // @ts-expect-error
  77. <div ref={ref}>
  78. <div className="msh-segmented msh-segmented-sm css-23bs09 css-var-r1">
  79. <div className="msh-segmented-group">
  80. <label className="msh-segmented-item flex items-center space-x-1 m-2 w-[200px]">
  81. <div key='classic'
  82. className={cn('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',
  83. look === 'classic' && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary',
  84. )}
  85. onClick={() => setLook('classic')}
  86. >
  87. <div className="msh-segmented-item-label">{t('app.mermaid.classic')}</div>
  88. </div>
  89. <div key='handDrawn'
  90. className={cn(
  91. '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',
  92. look === 'handDrawn' && 'border-[1.5px] border-components-option-card-option-selected-border bg-components-option-card-option-selected-bg text-text-primary',
  93. )}
  94. onClick={() => setLook('handDrawn')}
  95. >
  96. <div className="msh-segmented-item-label">{t('app.mermaid.handDrawn')}</div>
  97. </div>
  98. </label>
  99. </div>
  100. </div>
  101. {
  102. svgCode
  103. && <div className="mermaid cursor-pointer h-auto w-full object-fit: cover" onClick={() => setImagePreviewUrl(svgCode)}>
  104. {svgCode && <img src={svgCode} alt="mermaid_chart" />}
  105. </div>
  106. }
  107. {isLoading
  108. && <div className='py-4 px-[26px]'>
  109. <LoadingAnim type='text'/>
  110. </div>
  111. }
  112. {
  113. errMsg
  114. && <div className='py-4 px-[26px]'>
  115. <ExclamationTriangleIcon className='w-6 h-6 text-red-500'/>
  116. &nbsp;
  117. {errMsg}
  118. </div>
  119. }
  120. {
  121. imagePreviewUrl && (<ImagePreview title='mermaid_chart' url={imagePreviewUrl} onCancel={() => setImagePreviewUrl('')} />)
  122. }
  123. </div>
  124. )
  125. })
  126. Flowchart.displayName = 'Flowchart'
  127. export default Flowchart