1
0
mirror of https://github.com/actix/actix-website synced 2025-02-02 12:19:04 +01:00
actix-website/src/components/code_block.tsx

45 lines
1.0 KiB
TypeScript
Raw Normal View History

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