// import React, { useState, useEffect } from 'react'; // import CodeBlock from '@theme/CodeBlock'; // import Icon from '@site/src/components/Icon'; // const CodeEmbed = ({ src }) => { // const [code, setCode] = useState(''); // const [loading, setLoading] = useState(true); // const [error, setError] = useState(null); // useEffect(() => { // let isMounted = true; // const fetchCodeFromUrl = async (url) => { // if (!isMounted) return; // setLoading(true); // setError(null); // try { // const response = await fetch(url); // if (!response.ok) { // throw new Error(`HTTP error! status: ${response.status}`); // } // const data = await response.text(); // if (isMounted) { // setCode(data); // } // } catch (err) { // console.error('Failed to fetch code:', err); // if (isMounted) { // setError(err); // setCode(`// Failed to load code from ${url}\n// ${err.message}`); // } // } finally { // if (isMounted) { // setLoading(false); // } // } // }; // if (src) { // fetchCodeFromUrl(src); // } // return () => { // isMounted = false; // }; // }, [src]); // const githubUrl = src ? src.replace('https://raw.githubusercontent.com', 'https://github.com').replace('/refs/heads/', '/blob/') : null; // const fileName = src ? src.substring(src.lastIndexOf('/') + 1) : null; // return ( // loading ? ( //
Loading code...
// ) : error ? ( //
Error: {error.message}
// ) : ( //
//
// {githubUrl && ( // // View on GitHub // // // )} //
// {code} //
// ) // ); // }; // export default CodeEmbed; import React, { useState, useEffect } from 'react'; import CodeBlock from '@theme/CodeBlock'; import Icon from '@site/src/components/Icon'; const CodeEmbed = ({ src }) => { const [code, setCode] = useState(''); const [loading, setLoading] = useState(true); const [error, setError] = useState(null); useEffect(() => { let isMounted = true; const fetchCodeFromUrl = async (url) => { if (!isMounted) return; setLoading(true); setError(null); try { const response = await fetch(url); if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } const data = await response.text(); if (isMounted) { setCode(data); } } catch (err) { console.error('Failed to fetch code:', err); if (isMounted) { setError(err); setCode(`// Failed to load code from ${url}\n// ${err.message}`); } } finally { if (isMounted) { setLoading(false); } } }; if (src) { fetchCodeFromUrl(src); } return () => { isMounted = false; }; }, [src]); const githubUrl = src ? src.replace('https://raw.githubusercontent.com', 'https://github.com').replace('/refs/heads/', '/blob/') : null; const fileName = src ? src.substring(src.lastIndexOf('/') + 1) : null; const title = (
{ e.target.style.textDecoration = 'underline'; }} onMouseOut={e => { e.target.style.textDecoration = 'none'; }} > {fileName} {githubUrl && ( View on GitHub )}
); return ( loading ? (
Loading code...
) : error ? (
Error: {error.message}
) : (
{code}
) ); }; export default CodeEmbed;