49 lines
1.5 KiB
JavaScript
49 lines
1.5 KiB
JavaScript
import React, { useState } from 'react';
|
|
import { Prism as SyntaxHighlighter } from 'react-syntax-highlighter';
|
|
import { vscDarkPlus } from 'react-syntax-highlighter/dist/esm/styles/prism';
|
|
import { CopyOutlined, CheckOutlined } from '@ant-design/icons';
|
|
import { Button, Tooltip } from 'antd';
|
|
|
|
const CodeBlock = ({ language, children, ...props }) => {
|
|
const [copied, setCopied] = useState(false);
|
|
|
|
const handleCopy = () => {
|
|
navigator.clipboard.writeText(String(children).replace(/\n$/, ''));
|
|
setCopied(true);
|
|
setTimeout(() => setCopied(false), 2000);
|
|
};
|
|
|
|
return (
|
|
<div style={{ position: 'relative', margin: '1em 0' }}>
|
|
<Tooltip title={copied ? "已复制" : "复制代码"}>
|
|
<Button
|
|
type="text"
|
|
icon={copied ? <CheckOutlined style={{ color: '#52c41a' }} /> : <CopyOutlined style={{ color: '#fff' }} />}
|
|
size="small"
|
|
onClick={handleCopy}
|
|
style={{
|
|
position: 'absolute',
|
|
top: 8,
|
|
right: 8,
|
|
zIndex: 1,
|
|
color: '#fff',
|
|
background: 'rgba(255, 255, 255, 0.1)',
|
|
border: 'none',
|
|
}}
|
|
/>
|
|
</Tooltip>
|
|
<SyntaxHighlighter
|
|
style={vscDarkPlus}
|
|
language={language}
|
|
PreTag="div"
|
|
customStyle={{ margin: 0, borderRadius: 8, padding: '1.5em 1em 1em 1em' }}
|
|
{...props}
|
|
>
|
|
{String(children).replace(/\n$/, '')}
|
|
</SyntaxHighlighter>
|
|
</div>
|
|
);
|
|
};
|
|
|
|
export default CodeBlock;
|