File size: 1,169 Bytes
ec245fc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import { useState } from 'react'

interface CodeBlockProps {
  code: string
  /** Small label shown in the bar, e.g. "curl" or "python". */
  label?: string
}

/**
 * A monospace code block on the second neutral surface with a copy-to-clipboard
 * affordance. Wide lines scroll horizontally inside the block so the page never does.
 */
export default function CodeBlock({ code, label }: CodeBlockProps) {
  const [copied, setCopied] = useState(false)

  async function copy() {
    try {
      await navigator.clipboard.writeText(code)
      setCopied(true)
      window.setTimeout(() => setCopied(false), 1600)
    } catch {
      setCopied(false)
    }
  }

  return (
    <figure className="codeblock">
      <div className="codeblock-bar">
        {label && <span className="codeblock-label">{label}</span>}
        <button
          type="button"
          className="codeblock-copy"
          onClick={copy}
          aria-label={copied ? 'Copied to clipboard' : 'Copy to clipboard'}
        >
          {copied ? 'Copied' : 'Copy'}
        </button>
      </div>
      <pre className="codeblock-pre">
        <code>{code}</code>
      </pre>
    </figure>
  )
}