(fix/mermaid loading): load only the diagrams which stream

This commit is contained in:
ManishMadan2882
2025-05-06 15:16:14 +05:30
parent 72e51bb072
commit f37ca95c10
4 changed files with 73 additions and 65 deletions

View File

@@ -10,6 +10,7 @@ import { useDarkTheme } from '../hooks';
const MermaidRenderer: React.FC<MermaidRendererProps> = ({
code,
isLoading,
}) => {
const [isDarkTheme] = useDarkTheme();
const diagramId = useRef(`mermaid-${crypto.randomUUID()}`);
@@ -21,70 +22,70 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
const containerRef = useRef<HTMLDivElement>(null);
const [hoverPosition, setHoverPosition] = useState<{ x: number, y: number } | null>(null);
const [isHovering, setIsHovering] = useState<boolean>(false);
const handleMouseMove = (event: React.MouseEvent) => {
if (!containerRef.current) return;
const rect = containerRef.current.getBoundingClientRect();
const x = (event.clientX - rect.left) / rect.width;
const y = (event.clientY - rect.top) / rect.height;
setHoverPosition({ x, y });
};
const handleMouseEnter = () => setIsHovering(true);
const handleMouseLeave = () => {
setIsHovering(false);
setHoverPosition(null);
};
const getTransformOrigin = () => {
if (!hoverPosition) return 'center center';
return `${hoverPosition.x * 100}% ${hoverPosition.y * 100}%`;
};
useEffect(() => {
if (status === 'loading' || !code) return;
if ((isLoading !== undefined ? isLoading : status === 'loading') || !code) return;
mermaid.initialize({
startOnLoad: true,
theme: isDarkTheme ? 'dark' : 'default',
securityLevel: 'loose',
suppressErrorRendering: true,
});
const renderDiagram = async (): Promise<void> => {
try {
await mermaid.parse(code); //throws syntax errors
const element = document.getElementById(diagramId.current);
if (element) {
element.removeAttribute('data-processed');
mermaid.contentLoaded();
const svgElement = element.querySelector('svg');
if (svgElement) {
svgElement.setAttribute('width', '100%');
svgElement.setAttribute('height', 'auto');
svgElement.style.maxWidth = '100%';
svgElement.style.width = '100%';
svgElement.removeAttribute('viewBox');
}
setError(null);
}
} catch (err) {
setError(
`Failed to render Mermaid diagram: ${err instanceof Error ? err.message : String(err)}`
);
}
};
renderDiagram();
}, [code, isDarkTheme]);
}, [code, isDarkTheme, isLoading]);
useEffect(() => {
@@ -109,13 +110,13 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
if (!element) return;
const svgElement = element.querySelector('svg');
if (!svgElement) return;
const svgClone = svgElement.cloneNode(true) as SVGElement;
if (!svgClone.hasAttribute('xmlns')) {
svgClone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
if (!svgClone.hasAttribute('width') || !svgClone.hasAttribute('height')) {
const viewBox = svgClone.getAttribute('viewBox')?.split(' ') || [];
if (viewBox.length === 4) {
@@ -123,15 +124,15 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
svgClone.setAttribute('height', viewBox[3]);
}
}
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgClone);
const svgBlob = new Blob(
[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n${svgString}`],
[`<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n${svgString}`],
{ type: 'image/svg+xml' }
);
const url = URL.createObjectURL(svgBlob);
const link = document.createElement('a');
link.href = url;
@@ -145,19 +146,19 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
const downloadPng = (): void => {
const element = document.getElementById(diagramId.current);
if (!element) return;
const svgElement = element.querySelector('svg');
if (!svgElement) return;
const svgClone = svgElement.cloneNode(true) as SVGElement;
if (!svgClone.hasAttribute('xmlns')) {
svgClone.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
}
let width = parseInt(svgClone.getAttribute('width') || '0');
let height = parseInt(svgClone.getAttribute('height') || '0');
if (!width || !height) {
const viewBox = svgClone.getAttribute('viewBox')?.split(' ') || [];
if (viewBox.length === 4) {
@@ -172,30 +173,30 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
svgClone.setAttribute('height', height.toString());
}
}
const serializer = new XMLSerializer();
const svgString = serializer.serializeToString(svgClone);
const svgBase64 = btoa(unescape(encodeURIComponent(svgString)));
const dataUrl = `data:image/svg+xml;base64,${svgBase64}`;
const img = new Image();
img.crossOrigin = 'anonymous';
img.onload = function(): void {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
const ctx = canvas.getContext('2d');
if (!ctx) {
console.error('Could not get canvas context');
return;
}
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(img, 0, 0, width, height);
try {
const pngUrl = canvas.toDataURL('image/png');
const link = document.createElement('a');
@@ -210,7 +211,7 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
downloadSvg();
}
};
img.src = dataUrl;
};
@@ -225,16 +226,17 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
document.body.removeChild(link);
URL.revokeObjectURL(url);
};
const downloadOptions = [
{ label: 'Download as SVG', action: downloadSvg },
{ label: 'Download as PNG', action: downloadPng },
{ label: 'Download as MMD', action: downloadMmd },
];
const showDiagramOptions = status !== 'loading' && !error;
const errorRender = status !== 'loading' && error;
const isCurrentlyLoading = isLoading !== undefined ? isLoading : status === 'loading';
const showDiagramOptions = !isCurrentlyLoading && !error;
const errorRender = !isCurrentlyLoading && error;
@@ -246,7 +248,7 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
</span>
<div className="flex items-center gap-2">
<CopyButton text={String(code).replace(/\n$/, '')} />
{showDiagramOptions && (
<div className="relative" ref={downloadMenuRef}>
<button
@@ -277,7 +279,7 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
)}
</div>
)}
{showDiagramOptions && (
<button
onClick={() => setShowCode(!showCode)}
@@ -293,8 +295,8 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
)}
</div>
</div>
{status === 'loading' ? (
{isCurrentlyLoading ? (
<div className="p-4 bg-white dark:bg-eerie-black flex justify-center items-center">
<div className="text-sm text-gray-500 dark:text-gray-400">
Loading diagram...
@@ -308,24 +310,24 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
</div>
) : (
<>
<div
<div
ref={containerRef}
className=" no-scrollbar p-4 block w-full bg-white dark:bg-eerie-black "
style={{
style={{
overflow: 'auto',
scrollbarWidth: 'none',
msOverflowStyle: 'none',
width: '100%',
}}
onMouseMove={handleMouseMove}
onMouseEnter={handleMouseEnter}
onMouseLeave={handleMouseLeave}
>
<pre
className="mermaid select-none w-full"
<pre
className="mermaid select-none w-full"
id={diagramId.current}
style={{
style={{
transform: isHovering ? `scale(2)` : `scale(1)`,
transformOrigin: getTransformOrigin(),
transition: 'transform 0.2s ease',
@@ -338,7 +340,7 @@ const MermaidRenderer: React.FC<MermaidRendererProps> = ({
{code}
</pre>
</div>
{showCode && (
<div className="border-t border-light-silver dark:border-raisin-black">
<div className="p-2 bg-platinum dark:bg-eerie-black-2">