feat: improved SVG output UX (#8765)

This commit is contained in:
Hash Brown 2024-09-26 19:41:59 +08:00 committed by GitHub
parent 9a4b53a212
commit 3dfbc348e3
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 95 additions and 61 deletions

View File

@ -85,6 +85,19 @@ const Answer: FC<AnswerProps> = ({
getContentWidth() getContentWidth()
}, [responding]) }, [responding])
// Recalculate contentWidth when content changes (e.g., SVG preview/source toggle)
useEffect(() => {
if (!containerRef.current)
return
const resizeObserver = new ResizeObserver(() => {
getContentWidth()
})
resizeObserver.observe(containerRef.current)
return () => {
resizeObserver.disconnect()
}
}, [])
return ( return (
<div className='flex mb-2 last:mb-0'> <div className='flex mb-2 last:mb-0'>
<div className='shrink-0 relative w-10 h-10'> <div className='shrink-0 relative w-10 h-10'>

View File

@ -116,59 +116,80 @@ const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }
const match = /language-(\w+)/.exec(className || '') const match = /language-(\w+)/.exec(className || '')
const language = match?.[1] const language = match?.[1]
const languageShowName = getCorrectCapitalizationLanguageName(language || '') const languageShowName = getCorrectCapitalizationLanguageName(language || '')
let chartData = JSON.parse(String('{"title":{"text":"ECharts error - Wrong JSON format."}}').replace(/\n$/, '')) const chartData = useMemo(() => {
if (language === 'echarts') { if (language === 'echarts') {
try { try {
chartData = JSON.parse(String(children).replace(/\n$/, '')) return JSON.parse(String(children).replace(/\n$/, ''))
}
catch (error) {}
} }
catch (error) { return JSON.parse('{"title":{"text":"ECharts error - Wrong JSON format."}}')
} }, [language, children])
}
// Use `useMemo` to ensure that `SyntaxHighlighter` only re-renders when necessary const renderCodeContent = useMemo(() => {
return useMemo(() => { const content = String(children).replace(/\n$/, '')
return (!inline && match) if (language === 'mermaid' && isSVG) {
? ( return <Flowchart PrimitiveCode={content} />
<div> }
<div else if (language === 'echarts') {
className='flex justify-between h-8 items-center p-1 pl-3 border-b' return (
style={{ <div style={{ minHeight: '350px', minWidth: '700px' }}>
borderColor: 'rgba(0, 0, 0, 0.05)', <ErrorBoundary>
}} <ReactEcharts option={chartData} />
> </ErrorBoundary>
<div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
<div style={{ display: 'flex' }}>
{language === 'mermaid' && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG}/>}
<CopyBtn
className='mr-1'
value={String(children).replace(/\n$/, '')}
isPlain
/>
</div>
</div>
{(language === 'mermaid' && isSVG)
? (<Flowchart PrimitiveCode={String(children).replace(/\n$/, '')} />)
: (language === 'echarts'
? (<div style={{ minHeight: '350px', minWidth: '700px' }}><ErrorBoundary><ReactEcharts option={chartData} /></ErrorBoundary></div>)
: (language === 'svg'
? (<ErrorBoundary><SVGRenderer content={String(children).replace(/\n$/, '')} /></ErrorBoundary>)
: (<SyntaxHighlighter
{...props}
style={atelierHeathLight}
customStyle={{
paddingLeft: 12,
backgroundColor: '#fff',
}}
language={match[1]}
showLineNumbers
PreTag="div"
>
{String(children).replace(/\n$/, '')}
</SyntaxHighlighter>)))}
</div> </div>
) )
: (<code {...props} className={className}>{children}</code>) }
}, [chartData, children, className, inline, isSVG, language, languageShowName, match, props]) else if (language === 'svg' && isSVG) {
return (
<ErrorBoundary>
<SVGRenderer content={content} />
</ErrorBoundary>
)
}
else {
return (
<SyntaxHighlighter
{...props}
style={atelierHeathLight}
customStyle={{
paddingLeft: 12,
backgroundColor: '#fff',
}}
language={match?.[1]}
showLineNumbers
PreTag="div"
>
{content}
</SyntaxHighlighter>
)
}
}, [language, match, props, children, chartData, isSVG])
if (inline || !match)
return <code {...props} className={className}>{children}</code>
return (
<div>
<div
className='flex justify-between h-8 items-center p-1 pl-3 border-b'
style={{
borderColor: 'rgba(0, 0, 0, 0.05)',
}}
>
<div className='text-[13px] text-gray-500 font-normal'>{languageShowName}</div>
<div style={{ display: 'flex' }}>
{(['mermaid', 'svg']).includes(language!) && <SVGBtn isSVG={isSVG} setIsSVG={setIsSVG}/>}
<CopyBtn
className='mr-1'
value={String(children).replace(/\n$/, '')}
isPlain
/>
</div>
</div>
{renderCodeContent}
</div>
)
}) })
CodeBlock.displayName = 'CodeBlock' CodeBlock.displayName = 'CodeBlock'

View File

@ -29,7 +29,7 @@ export const SVGRenderer = ({ content }: { content: string }) => {
if (svgRef.current) { if (svgRef.current) {
try { try {
svgRef.current.innerHTML = '' svgRef.current.innerHTML = ''
const draw = SVG().addTo(svgRef.current).size('100%', '100%') const draw = SVG().addTo(svgRef.current)
const parser = new DOMParser() const parser = new DOMParser()
const svgDoc = parser.parseFromString(content, 'image/svg+xml') const svgDoc = parser.parseFromString(content, 'image/svg+xml')
@ -40,13 +40,11 @@ export const SVGRenderer = ({ content }: { content: string }) => {
const originalWidth = parseInt(svgElement.getAttribute('width') || '400', 10) const originalWidth = parseInt(svgElement.getAttribute('width') || '400', 10)
const originalHeight = parseInt(svgElement.getAttribute('height') || '600', 10) const originalHeight = parseInt(svgElement.getAttribute('height') || '600', 10)
const scale = Math.min(windowSize.width / originalWidth, windowSize.height / originalHeight, 1) draw.viewbox(0, 0, originalWidth, originalHeight)
const scaledWidth = originalWidth * scale
const scaledHeight = originalHeight * scale svgRef.current.style.width = `${Math.min(originalWidth, 298)}px`
draw.size(scaledWidth, scaledHeight)
const rootElement = draw.svg(content) const rootElement = draw.svg(content)
rootElement.scale(scale)
rootElement.click(() => { rootElement.click(() => {
setImagePreview(svgToDataURL(svgElement as Element)) setImagePreview(svgToDataURL(svgElement as Element))
@ -54,7 +52,7 @@ export const SVGRenderer = ({ content }: { content: string }) => {
} }
catch (error) { catch (error) {
if (svgRef.current) if (svgRef.current)
svgRef.current.innerHTML = 'Error rendering SVG. Wait for the image content to complete.' svgRef.current.innerHTML = '<span style="padding: 1rem;">Error rendering SVG. Wait for the image content to complete.</span>'
} }
} }
}, [content, windowSize]) }, [content, windowSize])
@ -62,14 +60,14 @@ export const SVGRenderer = ({ content }: { content: string }) => {
return ( return (
<> <>
<div ref={svgRef} style={{ <div ref={svgRef} style={{
width: '100%',
height: '100%',
minHeight: '300px',
maxHeight: '80vh', maxHeight: '80vh',
display: 'flex', display: 'flex',
justifyContent: 'center', justifyContent: 'center',
alignItems: 'center', alignItems: 'center',
cursor: 'pointer', cursor: 'pointer',
wordBreak: 'break-word',
whiteSpace: 'normal',
margin: '0 auto',
}} /> }} />
{imagePreview && (<ImagePreview url={imagePreview} title='Preview' onCancel={() => setImagePreview('')} />)} {imagePreview && (<ImagePreview url={imagePreview} title='Preview' onCancel={() => setImagePreview('')} />)}
</> </>

View File

@ -90,7 +90,7 @@ const ChatRecord = () => {
return ( return (
<div <div
className={` className={`
flex flex-col w-[400px] rounded-l-2xl h-full border border-black/2 shadow-xl flex flex-col w-[420px] rounded-l-2xl h-full border border-black/2 shadow-xl
`} `}
style={{ style={{
background: 'linear-gradient(156deg, rgba(242, 244, 247, 0.80) 0%, rgba(242, 244, 247, 0.00) 99.43%), var(--white, #FFF)', background: 'linear-gradient(156deg, rgba(242, 244, 247, 0.80) 0%, rgba(242, 244, 247, 0.00) 99.43%), var(--white, #FFF)',
@ -121,7 +121,7 @@ const ChatRecord = () => {
supportCitationHitInfo: true, supportCitationHitInfo: true,
} as any} } as any}
chatList={chatList} chatList={chatList}
chatContainerClassName='px-4' chatContainerClassName='px-3'
chatContainerInnerClassName='pt-6 w-full max-w-full mx-auto' chatContainerInnerClassName='pt-6 w-full max-w-full mx-auto'
chatFooterClassName='px-4 rounded-b-2xl' chatFooterClassName='px-4 rounded-b-2xl'
chatFooterInnerClassName='pb-4 w-full max-w-full mx-auto' chatFooterInnerClassName='pb-4 w-full max-w-full mx-auto'
@ -129,6 +129,8 @@ const ChatRecord = () => {
noChatInput noChatInput
allToolIcons={{}} allToolIcons={{}}
showPromptLog showPromptLog
noSpacing
chatAnswerContainerInner='!pr-2'
/> />
</div> </div>
</> </>