Skip to content

Commit

Permalink
mermaid front-end rendering initialization exception handling logic o…
Browse files Browse the repository at this point in the history
…ptimization
  • Loading branch information
luowei authored and luowei committed Oct 24, 2023
1 parent fe14130 commit 423560b
Showing 1 changed file with 20 additions and 7 deletions.
27 changes: 20 additions & 7 deletions web/app/components/app/chat/mermaid/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ const Flowchart = React.forwardRef((props: {
const chartId = useRef(`flowchart_${CryptoJS.MD5(props.PrimitiveCode).toString()}`)
const [isRender, setIsRender] = useState(true)

const clearFlowchartCache = () => {
for (let i = localStorage.length - 1; i >= 0; --i) {
const key = localStorage.key(i)
if (key && key.startsWith('flowchart_'))
localStorage.removeItem(key)
}
}

const renderFlowchart = async (PrimitiveCode: string) => {
try {
const cachedSvg: any = localStorage.getItem(chartId.current)
Expand All @@ -44,15 +52,15 @@ const Flowchart = React.forwardRef((props: {
const svgGraph = await mermaidAPI.render(chartId.current, PrimitiveCode)
// eslint-disable-next-line @typescript-eslint/no-use-before-define
const base64Svg: any = await svgToBase64(svgGraph.svg)
localStorage.setItem(chartId.current, base64Svg)
setSvgCode(base64Svg)
if (chartId.current && base64Svg)
localStorage.setItem(chartId.current, base64Svg)
}
}
catch (error) {
localStorage.clear()
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
console.error(error.toString())
clearFlowchartCache()
// eslint-disable-next-line @typescript-eslint/no-use-before-define
handleReRender()
}
}

Expand All @@ -70,7 +78,9 @@ const Flowchart = React.forwardRef((props: {
const handleReRender = () => {
setIsRender(false)
setSvgCode(null)
localStorage.removeItem(chartId.current)
if (chartId.current)
localStorage.removeItem(chartId.current)

setTimeout(() => {
setIsRender(true)
renderFlowchart(props.PrimitiveCode)
Expand All @@ -90,7 +100,10 @@ const Flowchart = React.forwardRef((props: {
// @ts-expect-error
<div ref={ref}>
{
isRender && <div id={chartId.current} className="mermaid" style={style}>{svgCode && (<img src={svgCode} style={{ width: '100%', height: 'auto' }} alt="Mermaid chart" />)}</div>
isRender
&& <div id={chartId.current} className="mermaid" style={style}>
{svgCode && <img src={svgCode} style={{ width: '100%', height: 'auto' }} alt="Mermaid chart" />}
</div>
}
<button onClick={handleReRender}>{t('appApi.merMaind.rerender')}</button>
</div>
Expand Down

0 comments on commit 423560b

Please sign in to comment.