2023-11-01 15:32:44 +00:00
|
|
|
import React, { useState, useEffect } from "react";
|
|
|
|
import RenderCodeBlock from "@theme/CodeBlock";
|
2022-07-16 11:59:20 +02:00
|
|
|
|
2023-11-01 16:08:40 +01:00
|
|
|
const CodeBlock = ({ example, file, section, language }) => {
|
2023-11-01 15:32:44 +00:00
|
|
|
const [code, setCode] = useState("");
|
2023-11-01 16:08:40 +01:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
let isMounted = true;
|
|
|
|
|
|
|
|
const path =
|
2023-11-01 15:32:44 +00:00
|
|
|
file === "manifest" ? "Cargo.toml" : `src/${file ?? "main.rs"}`;
|
2023-11-01 16:08:40 +01:00
|
|
|
|
|
|
|
import(`!!raw-loader!@site/examples/${example}/${path}`)
|
|
|
|
.then((source) => {
|
|
|
|
source = source.default.match(
|
|
|
|
new RegExp(
|
2023-11-01 15:32:44 +00:00
|
|
|
`(?:\/\/|#) <${section}>\n([\\s\\S]*)(?:\/\/|#) <\/${section}>`,
|
|
|
|
),
|
2023-11-01 16:08:40 +01:00
|
|
|
)[1];
|
|
|
|
|
|
|
|
if (isMounted) setCode(source);
|
|
|
|
})
|
|
|
|
.catch((err) => console.log(err));
|
|
|
|
|
|
|
|
return () => {
|
|
|
|
isMounted = false;
|
|
|
|
};
|
|
|
|
}, []);
|
|
|
|
|
|
|
|
return (
|
2023-11-01 15:32:44 +00:00
|
|
|
<RenderCodeBlock className={`language-${language ?? "rust"}`}>
|
2023-11-01 16:08:40 +01:00
|
|
|
{code}
|
|
|
|
</RenderCodeBlock>
|
|
|
|
);
|
|
|
|
};
|
2022-07-16 11:59:20 +02:00
|
|
|
|
|
|
|
export default CodeBlock;
|