|
| 1 | +import { useRef, useState } from 'react'; |
| 2 | +import PropTypes from 'prop-types'; |
| 3 | +import './CodeBlockWithCopy.scss'; |
| 4 | + |
| 5 | +export default function CodeBlockWithCopy({ children }) { |
| 6 | + const preRef = useRef(null); |
| 7 | + const [copyStatus, setCopyStatus] = useState('copy'); |
| 8 | + |
| 9 | + const handleCopy = async () => { |
| 10 | + if (!preRef.current) return; |
| 11 | + |
| 12 | + const codeElement = preRef.current.querySelector('code'); |
| 13 | + if (!codeElement) return; |
| 14 | + |
| 15 | + const codeText = codeElement.textContent; |
| 16 | + let successfulCopy = false; |
| 17 | + |
| 18 | + // Try modern API (navigator.clipboard) -> as document.execCommand() deprecated |
| 19 | + try { |
| 20 | + if (navigator.clipboard && window.isSecureContext) { |
| 21 | + await navigator.clipboard.writeText(codeText); |
| 22 | + successfulCopy = true; |
| 23 | + } |
| 24 | + } catch (err) { |
| 25 | + console.log(err); |
| 26 | + } |
| 27 | + |
| 28 | + // If modern API failed, fall back to deprecated document.execCommand('copy') |
| 29 | + if (!successfulCopy) { |
| 30 | + const textarea = document.createElement('textarea'); |
| 31 | + textarea.value = codeText; |
| 32 | + textarea.style.position = 'fixed'; |
| 33 | + textarea.style.opacity = '0'; |
| 34 | + |
| 35 | + document.body.appendChild(textarea); |
| 36 | + textarea.select(); |
| 37 | + |
| 38 | + try { |
| 39 | + // This deprecated method is kept as a fallback for compatibility/iframe environments. |
| 40 | + successfulCopy = document.execCommand('copy'); |
| 41 | + } catch (err) { |
| 42 | + successfulCopy = false; |
| 43 | + console.log(err); |
| 44 | + } |
| 45 | + |
| 46 | + document.body.removeChild(textarea); |
| 47 | + } |
| 48 | + |
| 49 | + setCopyStatus(successfulCopy ? 'copied' : 'error'); |
| 50 | + setTimeout(() => setCopyStatus('copy'), 2000); |
| 51 | + }; |
| 52 | + |
| 53 | + return ( |
| 54 | + <div className="code-block-wrapper"> |
| 55 | + <button onClick={handleCopy} className={`copy-button ${copyStatus}`}> |
| 56 | + {copyStatus === 'copied' |
| 57 | + ? 'Copied!' |
| 58 | + : copyStatus === 'error' |
| 59 | + ? 'Error' |
| 60 | + : 'Copy'} |
| 61 | + </button> |
| 62 | + |
| 63 | + <pre ref={preRef} className="code-block"> |
| 64 | + {children} |
| 65 | + </pre> |
| 66 | + </div> |
| 67 | + ); |
| 68 | +} |
| 69 | + |
| 70 | +CodeBlockWithCopy.propTypes = { |
| 71 | + children: PropTypes.node.isRequired, |
| 72 | +}; |
0 commit comments