-
Notifications
You must be signed in to change notification settings - Fork 53
/
index.js
49 lines (43 loc) · 1.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Based on https://github.com/facebook/docusaurus/blob/ed9d2a26f5a7b8096804ae1b3a4fffc504f8f90d/packages/docusaurus-theme-classic/src/theme/CodeBlock/index.tsx
// which is under MIT License as per the banner
import "./styles.css"
import copy from "copy-text-to-clipboard"
import React, { useRef, useState } from "react"
import Translate, { translate } from "@docusaurus/Translate"
const CodeBlock = ({ children, ...props }) => {
const pre = useRef(null)
const [showCopied, setShowCopied] = useState(false)
const handleCopyCode = () => {
if (pre.current) {
copy(Array.from(pre.current.querySelectorAll("code div.line")).map(el => el.textContent).join("\n"))
}
setShowCopied(true)
setTimeout(() => setShowCopied(false), 2000)
}
return (
<pre {...props} ref={pre}>
{children}
<button
type="button"
aria-label={translate({
id: "theme.CodeBlock.copyButtonAriaLabel",
message: "Copy code to clipboard",
description: "The ARIA label for copy code blocks button",
})}
className="copy-button"
onClick={handleCopyCode}
>
{showCopied ? (
<Translate id="theme.CodeBlock.copied" description="The copied button label on code blocks">
Copied
</Translate>
) : (
<Translate id="theme.CodeBlock.copy" description="The copy button label on code blocks">
Copy
</Translate>
)}
</button>
</pre>
)
}
export default CodeBlock