From 8b8c84a2269ce0a6675247063203f67baedd852b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BD=97=E5=A8=81?= Date: Fri, 13 Sep 2024 21:46:13 +0800 Subject: [PATCH 1/5] add svg render & Image preview optimization --- .../base/image-uploader/image-preview.tsx | 232 ++++++++++++++++-- web/app/components/base/markdown.tsx | 85 +++++-- web/package.json | 1 + web/yarn.lock | 5 + 4 files changed, 283 insertions(+), 40 deletions(-) diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsx index 41f29fda2e5113..ffd6296fc91b26 100644 --- a/web/app/components/base/image-uploader/image-preview.tsx +++ b/web/app/components/base/image-uploader/image-preview.tsx @@ -1,26 +1,41 @@ import type { FC } from 'react' -import { useRef } from 'react' +import React, { useCallback, useEffect, useRef, useState } from 'react' import { t } from 'i18next' import { createPortal } from 'react-dom' -import { RiCloseLine, RiExternalLinkLine } from '@remixicon/react' +import { RiAddBoxLine, RiCloseLine, RiDownloadCloud2Line, RiFileCopyLine, RiZoomInLine, RiZoomOutLine } from '@remixicon/react' import Tooltip from '@/app/components/base/tooltip' -import { randomString } from '@/utils' +import Toast from '@/app/components/base/toast' type ImagePreviewProps = { url: string title: string onCancel: () => void } + +const isBase64 = (str: string): boolean => { + try { + return btoa(atob(str)) === str + } + catch (err) { + return false + } +} + const ImagePreview: FC = ({ url, title, onCancel, }) => { - const selector = useRef(`copy-tooltip-${randomString(4)}`) + const [scale, setScale] = useState(1) + const [position, setPosition] = useState({ x: 0, y: 0 }) + const [isDragging, setIsDragging] = useState(false) + const imgRef = useRef(null) + const dragStartRef = useRef({ x: 0, y: 0 }) + const [isCopied, setIsCopied] = useState(false) const openInNewTab = () => { // Open in a new window, considering the case when the page is inside an iframe - if (url.startsWith('http')) { + if (url.startsWith('http') || url.startsWith('https')) { window.open(url, '_blank') } else if (url.startsWith('data:image')) { @@ -29,34 +44,205 @@ const ImagePreview: FC = ({ win?.document.write(`${title}`) } else { - console.error('Unable to open image', url) + Toast.notify({ + type: 'error', + message: `Unable to open image: ${url}`, + }) + } + } + const downloadImage = () => { + // Open in a new window, considering the case when the page is inside an iframe + if (url.startsWith('http') || url.startsWith('https')) { + const a = document.createElement('a') + a.href = url + a.download = title + a.click() + } + else if (url.startsWith('data:image')) { + // Base64 image + const a = document.createElement('a') + a.href = url + a.download = title + a.click() + } + else { + Toast.notify({ + type: 'error', + message: `Unable to open image: ${url}`, + }) } } + const zoomIn = () => { + setScale(prevScale => Math.min(prevScale * 1.2, 15)) + } + + const zoomOut = () => { + setScale((prevScale) => { + const newScale = Math.max(prevScale / 1.2, 0.5) + if (newScale === 1) + setPosition({ x: 0, y: 0 }) // Reset position when fully zoomed out + + return newScale + }) + } + + const imageTobase64ToBlob = (base64: string, type = 'image/png'): Blob => { + const byteCharacters = atob(base64) + const byteArrays = [] + + for (let offset = 0; offset < byteCharacters.length; offset += 512) { + const slice = byteCharacters.slice(offset, offset + 512) + const byteNumbers = new Array(slice.length) + for (let i = 0; i < slice.length; i++) + byteNumbers[i] = slice.charCodeAt(i) + + const byteArray = new Uint8Array(byteNumbers) + byteArrays.push(byteArray) + } + + return new Blob(byteArrays, { type }) + } + + const imageCopy = useCallback(() => { + const shareImage = async () => { + try { + const base64Data = url.split(',')[1] + const blob = imageTobase64ToBlob(base64Data, 'image/png') + + await navigator.clipboard.write([ + new ClipboardItem({ + [blob.type]: blob, + }), + ]) + setIsCopied(true) + + Toast.notify({ + type: 'success', + message: t('common.operation.imageCopied'), + }) + } + catch (err) { + console.error('Failed to copy image:', err) + + const link = document.createElement('a') + link.href = url + link.download = `${title}.png` + document.body.appendChild(link) + link.click() + document.body.removeChild(link) + + Toast.notify({ + type: 'info', + message: t('common.operation.imageDownloaded'), + }) + } + } + shareImage() + }, [title, url]) + + const handleWheel = useCallback((e: React.WheelEvent) => { + if (e.deltaY < 0) + zoomIn() + else + zoomOut() + }, []) + + const handleMouseDown = useCallback((e: React.MouseEvent) => { + if (scale > 1) { + setIsDragging(true) + dragStartRef.current = { x: e.clientX - position.x, y: e.clientY - position.y } + } + }, [scale, position]) + + const handleMouseMove = useCallback((e: React.MouseEvent) => { + if (isDragging && scale > 1) { + const deltaX = e.clientX - dragStartRef.current.x + const deltaY = e.clientY - dragStartRef.current.y + + // Calculate boundaries + const imgRect = imgRef.current?.getBoundingClientRect() + const containerRect = imgRef.current?.parentElement?.getBoundingClientRect() + + if (imgRect && containerRect) { + const maxX = (imgRect.width * scale - containerRect.width) / 2 + const maxY = (imgRect.height * scale - containerRect.height) / 2 + + setPosition({ + x: Math.max(-maxX, Math.min(maxX, deltaX)), + y: Math.max(-maxY, Math.min(maxY, deltaY)), + }) + } + } + }, [isDragging, scale]) + + const handleMouseUp = useCallback(() => { + setIsDragging(false) + }, []) + + useEffect(() => { + document.addEventListener('mouseup', handleMouseUp) + return () => { + document.removeEventListener('mouseup', handleMouseUp) + } + }, [handleMouseUp]) + return createPortal( -
e.stopPropagation()}> +
e.stopPropagation()} + onWheel={handleWheel} + onMouseDown={handleMouseDown} + onMouseMove={handleMouseMove} + onMouseUp={handleMouseUp} + style={{ cursor: scale > 1 ? 'move' : 'default' }}> {/* eslint-disable-next-line @next/next/no-img-element */} {title} -
- -
- + +
+ {isCopied + ? + : } +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+ +
+ +
+
+
- + className='absolute top-6 right-6 flex items-center justify-center w-8 h-8 bg-white/8 rounded-lg backdrop-blur-[2px] cursor-pointer' + onClick={onCancel}> +
, diff --git a/web/app/components/base/markdown.tsx b/web/app/components/base/markdown.tsx index c0a3332a3cf0b5..141d537024205c 100644 --- a/web/app/components/base/markdown.tsx +++ b/web/app/components/base/markdown.tsx @@ -6,6 +6,7 @@ import RemarkBreaks from 'remark-breaks' import RehypeKatex from 'rehype-katex' import RehypeRaw from 'rehype-raw' import RemarkGfm from 'remark-gfm' +import { SVG } from '@svgdotjs/svg.js' import SyntaxHighlighter from 'react-syntax-highlighter' import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs' import type { RefObject } from 'react' @@ -19,6 +20,7 @@ import ImageGallery from '@/app/components/base/image-gallery' import { useChatContext } from '@/app/components/base/chat/chat/context' import VideoGallery from '@/app/components/base/video-gallery' import AudioGallery from '@/app/components/base/audio-gallery' +import ImagePreview from '@/app/components/base/image-uploader/image-preview' // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD const capitalizationLanguageNameMap: Record = { @@ -41,6 +43,7 @@ const capitalizationLanguageNameMap: Record = { powershell: 'PowerShell', json: 'JSON', latex: 'Latex', + svg: 'SVG', } const getCorrectCapitalizationLanguageName = (language: string) => { if (!language) @@ -96,6 +99,56 @@ const useLazyLoad = (ref: RefObject): boolean => { return isIntersecting } +const SVGRenderer = ({ content }: { content: string }) => { + const svgRef = useRef(null) + const [imagePreview, setImagePreview] = useState('') + + const svgToDataURL = (svgElement: Element): string => { + const svgString = new XMLSerializer().serializeToString(svgElement) + return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}` + } + + useEffect(() => { + if (svgRef.current) { + try { + svgRef.current.innerHTML = '' + const draw = SVG().addTo(svgRef.current).size('100%', '100%') + + const parser = new DOMParser() + const svgDoc = parser.parseFromString(content, 'image/svg+xml') + const svgElement = svgDoc.documentElement + + const width = svgElement.getAttribute('width') || '100%' + const height = svgElement.getAttribute('height') || '100%' + + draw.size(width, height) + const rootElement = draw.svg(content) + + // Optional: If you want to support custom fonts, add the following code + // document.fonts.ready.then(() => { + // draw.font('family', 'STKaiti, SimKai, SimSun, serif', '/path/to/font.ttf') + // }) + + rootElement.click(() => { + setImagePreview(svgToDataURL(svgElement as Element)) + }) + } + catch (error) { + console.error('Error rendering SVG:', error) + if (svgRef.current) + svgRef.current.innerHTML = 'Error rendering SVG. Please check the console for details.' + } + } + }, [content]) + + return ( + <> +
+ {imagePreview && ( setImagePreview('')} />)} + + ) +} + // **Add code block // Avoid error #185 (Maximum update depth exceeded. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. @@ -108,6 +161,7 @@ const useLazyLoad = (ref: RefObject): boolean => { // Error: Minified React error 185; // visit https://reactjs.org/docs/error-decoder.html?invariant=185 for the full message // or use the non-minified dev environment for full errors and additional helpful warnings. + const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props }) => { const [isSVG, setIsSVG] = useState(true) const match = /language-(\w+)/.exec(className || '') @@ -135,7 +189,7 @@ const CodeBlock: CodeComponent = memo(({ inline, className, children, ...props } >
{languageShowName}
- {language === 'mermaid' && } + {language === 'mermaid' && } {(language === 'mermaid' && isSVG) ? () - : ( - (language === 'echarts') - ? (
-
) + : (language === 'echarts' + ? (
) + : (language === 'svg' + ? () : ( {String(children).replace(/\n$/, '')} - ))} + )))}
) - : ( - - {children} - - ) + : ({children}) }, [chartData, children, className, inline, isSVG, language, languageShowName, match, props]) }) - CodeBlock.displayName = 'CodeBlock' const VideoBlock: CodeComponent = memo(({ node }) => { @@ -268,19 +315,23 @@ export function Markdown(props: { content: string; className?: string }) { // This can happen when a component attempts to access an undefined object that references an unregistered map, causing the program to crash. export default class ErrorBoundary extends Component { - constructor(props) { + constructor(props: any) { super(props) this.state = { hasError: false } } - componentDidCatch(error, errorInfo) { + componentDidCatch(error: any, errorInfo: any) { this.setState({ hasError: true }) console.error(error, errorInfo) } render() { + // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error if (this.state.hasError) - return
Oops! ECharts reported a runtime error.
(see the browser console for more information)
+ return
Oops! An error occurred. This could be due to an ECharts runtime error or invalid SVG content.
(see the browser console for more information)
+ // eslint-disable-next-line @typescript-eslint/ban-ts-comment + // @ts-expect-error return this.props.children } } diff --git a/web/package.json b/web/package.json index b6275f20aeb738..047d71135af4b9 100644 --- a/web/package.json +++ b/web/package.json @@ -44,6 +44,7 @@ "classnames": "^2.3.2", "copy-to-clipboard": "^3.3.3", "crypto-js": "^4.2.0", + "@svgdotjs/svg.js": "^3.2.4", "dayjs": "^1.11.7", "echarts": "^5.4.1", "echarts-for-react": "^3.0.2", diff --git a/web/yarn.lock b/web/yarn.lock index 3c020c9664c61c..bec2059a470839 100644 --- a/web/yarn.lock +++ b/web/yarn.lock @@ -1489,6 +1489,11 @@ dependencies: "@sinonjs/commons" "^3.0.0" +"@svgdotjs/svg.js@^3.2.4": + version "3.2.4" + resolved "https://registry.yarnpkg.com/@svgdotjs/svg.js/-/svg.js-3.2.4.tgz#4716be92a64c66b29921b63f7235fcfb953fb13a" + integrity sha512-BjJ/7vWNowlX3Z8O4ywT58DqbNRyYlkk6Yz/D13aB7hGmfQTvGX4Tkgtm/ApYlu9M7lCQi15xUEidqMUmdMYwg== + "@swc/counter@^0.1.3": version "0.1.3" resolved "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz" From 0c8eefa515a7e4b76b5f3b595ed05283403e0ac4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BD=97=E5=A8=81?= Date: Fri, 13 Sep 2024 23:52:36 +0800 Subject: [PATCH 2/5] Add Zoom layer esc exit, svg page size fit --- .../base/image-uploader/image-preview.tsx | 22 +++++++++- web/app/components/base/markdown.tsx | 44 ++++++++++++++----- 2 files changed, 55 insertions(+), 11 deletions(-) diff --git a/web/app/components/base/image-uploader/image-preview.tsx b/web/app/components/base/image-uploader/image-preview.tsx index ffd6296fc91b26..e5bd4c1bbc0dc5 100644 --- a/web/app/components/base/image-uploader/image-preview.tsx +++ b/web/app/components/base/image-uploader/image-preview.tsx @@ -32,6 +32,7 @@ const ImagePreview: FC = ({ const imgRef = useRef(null) const dragStartRef = useRef({ x: 0, y: 0 }) const [isCopied, setIsCopied] = useState(false) + const containerRef = useRef(null) const openInNewTab = () => { // Open in a new window, considering the case when the page is inside an iframe @@ -187,6 +188,24 @@ const ImagePreview: FC = ({ } }, [handleMouseUp]) + useEffect(() => { + const handleKeyDown = (event: KeyboardEvent) => { + if (event.key === 'Escape') + onCancel() + } + + window.addEventListener('keydown', handleKeyDown) + + // Set focus to the container element + if (containerRef.current) + containerRef.current.focus() + + // Cleanup function + return () => { + window.removeEventListener('keydown', handleKeyDown) + } + }, [onCancel]) + return createPortal(
e.stopPropagation()} @@ -194,7 +213,8 @@ const ImagePreview: FC = ({ onMouseDown={handleMouseDown} onMouseMove={handleMouseMove} onMouseUp={handleMouseUp} - style={{ cursor: scale > 1 ? 'move' : 'default' }}> + style={{ cursor: scale > 1 ? 'move' : 'default' }} + tabIndex={-1}> {/* eslint-disable-next-line @next/next/no-img-element */} ): boolean => { const SVGRenderer = ({ content }: { content: string }) => { const svgRef = useRef(null) const [imagePreview, setImagePreview] = useState('') + const [windowSize, setWindowSize] = useState({ + width: typeof window !== 'undefined' ? window.innerWidth : 0, + height: typeof window !== 'undefined' ? window.innerHeight : 0, + }) const svgToDataURL = (svgElement: Element): string => { const svgString = new XMLSerializer().serializeToString(svgElement) return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}` } + useEffect(() => { + const handleResize = () => { + setWindowSize({ width: window.innerWidth, height: window.innerHeight }) + } + + window.addEventListener('resize', handleResize) + return () => window.removeEventListener('resize', handleResize) + }, []) + useEffect(() => { if (svgRef.current) { try { @@ -117,16 +130,18 @@ const SVGRenderer = ({ content }: { content: string }) => { const svgDoc = parser.parseFromString(content, 'image/svg+xml') const svgElement = svgDoc.documentElement - const width = svgElement.getAttribute('width') || '100%' - const height = svgElement.getAttribute('height') || '100%' + if (!(svgElement instanceof SVGElement)) + throw new Error('Invalid SVG content') - draw.size(width, height) - const rootElement = draw.svg(content) + const originalWidth = parseInt(svgElement.getAttribute('width') || '400', 10) + const originalHeight = parseInt(svgElement.getAttribute('height') || '600', 10) + const scale = Math.min(windowSize.width / originalWidth, windowSize.height / originalHeight, 1) + const scaledWidth = originalWidth * scale + const scaledHeight = originalHeight * scale + draw.size(scaledWidth, scaledHeight) - // Optional: If you want to support custom fonts, add the following code - // document.fonts.ready.then(() => { - // draw.font('family', 'STKaiti, SimKai, SimSun, serif', '/path/to/font.ttf') - // }) + const rootElement = draw.svg(content) + rootElement.scale(scale) rootElement.click(() => { setImagePreview(svgToDataURL(svgElement as Element)) @@ -138,11 +153,20 @@ const SVGRenderer = ({ content }: { content: string }) => { svgRef.current.innerHTML = 'Error rendering SVG. Please check the console for details.' } } - }, [content]) + }, [content, windowSize]) return ( <> -
+
{imagePreview && ( setImagePreview('')} />)} ) From 6217d4782bf6d46a2e506ed5ea4a441e63805cd4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BD=97=E5=A8=81?= Date: Sat, 14 Sep 2024 15:36:55 +0800 Subject: [PATCH 3/5] RehypeRaw Adds blacklist filtering --- web/app/components/base/markdown.tsx | 3 +++ 1 file changed, 3 insertions(+) diff --git a/web/app/components/base/markdown.tsx b/web/app/components/base/markdown.tsx index e5b47d42408006..09fee724a0ae02 100644 --- a/web/app/components/base/markdown.tsx +++ b/web/app/components/base/markdown.tsx @@ -5,6 +5,7 @@ import RemarkMath from 'remark-math' import RemarkBreaks from 'remark-breaks' import RehypeKatex from 'rehype-katex' import RemarkGfm from 'remark-gfm' +import RehypeRaw from 'rehype-raw' import { SVG } from '@svgdotjs/svg.js' import SyntaxHighlighter from 'react-syntax-highlighter' import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs' @@ -301,6 +302,7 @@ export function Markdown(props: { content: string; className?: string }) { remarkPlugins={[[RemarkGfm, RemarkMath, { singleDollarTextMath: false }], RemarkBreaks]} rehypePlugins={[ RehypeKatex, + RehypeRaw as any, // The Rehype plug-in is used to remove the ref attribute of an element () => { return (tree) => { @@ -315,6 +317,7 @@ export function Markdown(props: { content: string; className?: string }) { } }, ]} + disallowedElements={['script', 'iframe', 'head', 'html', 'meta', 'link', 'style', 'body']} components={{ code: CodeBlock, img: Img, From 30ffe19ecbfb61dbb92c973a6976098bafd50c4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=BD=97=E5=A8=81?= Date: Sat, 14 Sep 2024 19:08:20 +0800 Subject: [PATCH 4/5] Split SVG rendering --- web/app/components/base/markdown.tsx | 77 +----------------- web/app/components/base/svg-gallery/index.tsx | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+), 76 deletions(-) create mode 100644 web/app/components/base/svg-gallery/index.tsx diff --git a/web/app/components/base/markdown.tsx b/web/app/components/base/markdown.tsx index 09fee724a0ae02..443ee3410c4de4 100644 --- a/web/app/components/base/markdown.tsx +++ b/web/app/components/base/markdown.tsx @@ -6,7 +6,6 @@ import RemarkBreaks from 'remark-breaks' import RehypeKatex from 'rehype-katex' import RemarkGfm from 'remark-gfm' import RehypeRaw from 'rehype-raw' -import { SVG } from '@svgdotjs/svg.js' import SyntaxHighlighter from 'react-syntax-highlighter' import { atelierHeathLight } from 'react-syntax-highlighter/dist/esm/styles/hljs' import type { RefObject } from 'react' @@ -20,7 +19,7 @@ import ImageGallery from '@/app/components/base/image-gallery' import { useChatContext } from '@/app/components/base/chat/chat/context' import VideoGallery from '@/app/components/base/video-gallery' import AudioGallery from '@/app/components/base/audio-gallery' -import ImagePreview from '@/app/components/base/image-uploader/image-preview' +import SVGRenderer from '@/app/components/base/svg-gallery' // Available language https://github.com/react-syntax-highlighter/react-syntax-highlighter/blob/master/AVAILABLE_LANGUAGES_HLJS.MD const capitalizationLanguageNameMap: Record = { @@ -99,80 +98,6 @@ const useLazyLoad = (ref: RefObject): boolean => { return isIntersecting } -const SVGRenderer = ({ content }: { content: string }) => { - const svgRef = useRef(null) - const [imagePreview, setImagePreview] = useState('') - const [windowSize, setWindowSize] = useState({ - width: typeof window !== 'undefined' ? window.innerWidth : 0, - height: typeof window !== 'undefined' ? window.innerHeight : 0, - }) - - const svgToDataURL = (svgElement: Element): string => { - const svgString = new XMLSerializer().serializeToString(svgElement) - return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}` - } - - useEffect(() => { - const handleResize = () => { - setWindowSize({ width: window.innerWidth, height: window.innerHeight }) - } - - window.addEventListener('resize', handleResize) - return () => window.removeEventListener('resize', handleResize) - }, []) - - useEffect(() => { - if (svgRef.current) { - try { - svgRef.current.innerHTML = '' - const draw = SVG().addTo(svgRef.current).size('100%', '100%') - - const parser = new DOMParser() - const svgDoc = parser.parseFromString(content, 'image/svg+xml') - const svgElement = svgDoc.documentElement - - if (!(svgElement instanceof SVGElement)) - throw new Error('Invalid SVG content') - - const originalWidth = parseInt(svgElement.getAttribute('width') || '400', 10) - const originalHeight = parseInt(svgElement.getAttribute('height') || '600', 10) - const scale = Math.min(windowSize.width / originalWidth, windowSize.height / originalHeight, 1) - const scaledWidth = originalWidth * scale - const scaledHeight = originalHeight * scale - draw.size(scaledWidth, scaledHeight) - - const rootElement = draw.svg(content) - rootElement.scale(scale) - - rootElement.click(() => { - setImagePreview(svgToDataURL(svgElement as Element)) - }) - } - catch (error) { - console.error('Error rendering SVG:', error) - if (svgRef.current) - svgRef.current.innerHTML = 'Error rendering SVG. Please check the console for details.' - } - } - }, [content, windowSize]) - - return ( - <> -
- {imagePreview && ( setImagePreview('')} />)} - - ) -} - // **Add code block // Avoid error #185 (Maximum update depth exceeded. // This can happen when a component repeatedly calls setState inside componentWillUpdate or componentDidUpdate. diff --git a/web/app/components/base/svg-gallery/index.tsx b/web/app/components/base/svg-gallery/index.tsx new file mode 100644 index 00000000000000..0a4e7ecea8e638 --- /dev/null +++ b/web/app/components/base/svg-gallery/index.tsx @@ -0,0 +1,78 @@ +import { useEffect, useRef, useState } from 'react' +import { SVG } from '@svgdotjs/svg.js' +import ImagePreview from '@/app/components/base/image-uploader/image-preview' + +export const SVGRenderer = ({ content }: { content: string }) => { + const svgRef = useRef(null) + const [imagePreview, setImagePreview] = useState('') + const [windowSize, setWindowSize] = useState({ + width: typeof window !== 'undefined' ? window.innerWidth : 0, + height: typeof window !== 'undefined' ? window.innerHeight : 0, + }) + + const svgToDataURL = (svgElement: Element): string => { + const svgString = new XMLSerializer().serializeToString(svgElement) + return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}` + } + + useEffect(() => { + const handleResize = () => { + setWindowSize({ width: window.innerWidth, height: window.innerHeight }) + } + + window.addEventListener('resize', handleResize) + return () => window.removeEventListener('resize', handleResize) + }, []) + + useEffect(() => { + if (svgRef.current) { + try { + svgRef.current.innerHTML = '' + const draw = SVG().addTo(svgRef.current).size('100%', '100%') + + const parser = new DOMParser() + const svgDoc = parser.parseFromString(content, 'image/svg+xml') + const svgElement = svgDoc.documentElement + + if (!(svgElement instanceof SVGElement)) + throw new Error('Invalid SVG content') + + const originalWidth = parseInt(svgElement.getAttribute('width') || '400', 10) + const originalHeight = parseInt(svgElement.getAttribute('height') || '600', 10) + const scale = Math.min(windowSize.width / originalWidth, windowSize.height / originalHeight, 1) + const scaledWidth = originalWidth * scale + const scaledHeight = originalHeight * scale + draw.size(scaledWidth, scaledHeight) + + const rootElement = draw.svg(content) + rootElement.scale(scale) + + rootElement.click(() => { + setImagePreview(svgToDataURL(svgElement as Element)) + }) + } + catch (error) { + if (svgRef.current) + svgRef.current.innerHTML = 'Error rendering SVG. Wait for the image content to complete.' + } + } + }, [content, windowSize]) + + return ( + <> +
+ {imagePreview && ( setImagePreview('')} />)} + + ) +} + +export default SVGRenderer From 422cac7d470ed444b3c017a9559781acb55dbb45 Mon Sep 17 00:00:00 2001 From: crazywoola <427733928@qq.com> Date: Sat, 14 Sep 2024 19:16:48 +0800 Subject: [PATCH 5/5] Fix: deprecated usage --- web/app/components/base/svg-gallery/index.tsx | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/web/app/components/base/svg-gallery/index.tsx b/web/app/components/base/svg-gallery/index.tsx index 0a4e7ecea8e638..81e8e876550097 100644 --- a/web/app/components/base/svg-gallery/index.tsx +++ b/web/app/components/base/svg-gallery/index.tsx @@ -12,7 +12,8 @@ export const SVGRenderer = ({ content }: { content: string }) => { const svgToDataURL = (svgElement: Element): string => { const svgString = new XMLSerializer().serializeToString(svgElement) - return `data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(svgString)))}` + const base64String = Buffer.from(svgString).toString('base64') + return `data:image/svg+xml;base64,${base64String}` } useEffect(() => {