vite-bolt/plugin/common/Code.tsx
2023-02-01 17:52:53 +08:00

54 lines
1.4 KiB
TypeScript

import { useEffect, useRef, useState } from "react";
import Code20Regular from "@ricons/fluent/Code20Regular";
import Prism from "prismjs";
import "prismjs/plugins/line-numbers/prism-line-numbers";
import "prismjs/plugins/line-numbers/prism-line-numbers.css";
// import "prismjs/components/prism";
import "prismjs/components/prism-javascript";
import "prismjs/components/prism-typescript";
import "prismjs/components/prism-bash";
import "prismjs/components/prism-css";
interface IProps {
/**
* @description prism 渲染的代码文档字符串
*/
raw: string;
/**
* 语言类型
*/
lang: string;
}
export default function Code(props: IProps) {
const [visible, setVisible] = useState(false);
const codeRef = useRef<any>();
useEffect(() => {
Prism.highlightElement(codeRef.current);
}, [props.raw]);
return (
<div className="code-container">
<div style={{ paddingTop: "10px", textAlign: "right" }}>
<span
data-placement="示例代码"
className={`btn ${visible ? "active" : ""}`}
onClick={() => setVisible((v) => !v)}
>
<Code20Regular />
</span>
</div>
<pre
className="line-numbers"
data-lang={props.lang}
style={{ display: visible ? "block" : "none" }}
>
<code ref={codeRef} className={`language-${props.lang}`}>
{props.raw}
</code>
</pre>
</div>
);
}