2023-11-01 15:32:44 +00:00
|
|
|
import React, { useState, useEffect } from "react";
|
|
|
|
import RenderCodeBlock from "@theme/CodeBlock";
|
2024-05-28 20:23:34 +01:00
|
|
|
import { useIsMounted } from "usehooks-ts";
|
2022-07-16 11:59:20 +02:00
|
|
|
|
2024-05-28 20:23:34 +01:00
|
|
|
type Props = {
|
|
|
|
example: string;
|
|
|
|
file?: string;
|
|
|
|
section: string;
|
|
|
|
language?: string;
|
|
|
|
};
|
|
|
|
|
|
|
|
const CodeBlock = ({ example, file, section, language }: Props) => {
|
|
|
|
const isMounted = useIsMounted();
|
2023-11-01 15:32:44 +00:00
|
|
|
const [code, setCode] = useState("");
|
2023-11-01 16:08:40 +01:00
|
|
|
|
|
|
|
useEffect(() => {
|
|
|
|
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) => {
|
2024-05-28 20:23:34 +01:00
|
|
|
if (!isMounted()) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
2023-11-01 16:08:40 +01:00
|
|
|
source = source.default.match(
|
|
|
|
new RegExp(
|
2024-05-28 20:23:34 +01:00
|
|
|
`(?:\/\/|#) <${section}>\n([\\s\\S]*)(?:\/\/|#) <\/${section}>`
|
|
|
|
)
|
2023-11-01 16:08:40 +01:00
|
|
|
)[1];
|
|
|
|
|
2024-05-28 20:23:34 +01:00
|
|
|
setCode(source);
|
2023-11-01 16:08:40 +01:00
|
|
|
})
|
|
|
|
.catch((err) => console.log(err));
|
2024-05-28 20:23:34 +01:00
|
|
|
}, [isMounted]);
|
2023-11-01 16:08:40 +01:00
|
|
|
|
|
|
|
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;
|