|
| 1 | +import{makeStyles}from"@material-ui/core/styles" |
| 2 | +importButtonfrom"@material-ui/core/Button" |
| 3 | +importTooltipfrom"@material-ui/core/Tooltip" |
| 4 | +importCheckfrom"@material-ui/icons/Check" |
| 5 | +importReact,{useState}from"react" |
| 6 | +import{FileCopy}from"../Icons" |
| 7 | + |
| 8 | +interfaceCopyButtonProps{ |
| 9 | +text:string |
| 10 | +className?:string |
| 11 | +} |
| 12 | + |
| 13 | +/** |
| 14 | + * Copy button used inside the CodeBlock component internally |
| 15 | + */ |
| 16 | +exportconstCopyButton:React.FC<CopyButtonProps>=({ className="", text})=>{ |
| 17 | +conststyles=useStyles() |
| 18 | +const[isCopied,setIsCopied]=useState<boolean>(false) |
| 19 | + |
| 20 | +constcopyToClipboard=async():Promise<void>=>{ |
| 21 | +try{ |
| 22 | +awaitwindow.navigator.clipboard.writeText(text) |
| 23 | +setIsCopied(true) |
| 24 | + |
| 25 | +window.setTimeout(()=>{ |
| 26 | +setIsCopied(false) |
| 27 | +},1000) |
| 28 | +}catch(err){ |
| 29 | +constwrappedErr=newError("copyToClipboard: failed to copy text to clipboard") |
| 30 | +if(errinstanceofError){ |
| 31 | +wrappedErr.stack=err.stack |
| 32 | +} |
| 33 | +console.error(wrappedErr) |
| 34 | +} |
| 35 | +} |
| 36 | + |
| 37 | +return( |
| 38 | +<Tooltiptitle="Copy to Clipboard"placement="top"> |
| 39 | +<divclassName={`${styles.copyButtonWrapper}${className}`}> |
| 40 | +<ButtonclassName={styles.copyButton}onClick={copyToClipboard}size="small"> |
| 41 | +{isCopied ?<CheckclassName={styles.fileCopyIcon}/> :<FileCopyclassName={styles.fileCopyIcon}/>} |
| 42 | +</Button> |
| 43 | +</div> |
| 44 | +</Tooltip> |
| 45 | +) |
| 46 | +} |
| 47 | + |
| 48 | +constuseStyles=makeStyles((theme)=>({ |
| 49 | +copyButtonWrapper:{ |
| 50 | +display:"flex", |
| 51 | +marginLeft:theme.spacing(1), |
| 52 | +}, |
| 53 | +copyButton:{ |
| 54 | +borderRadius:7, |
| 55 | +background:theme.palette.codeBlock.button.main, |
| 56 | +color:theme.palette.codeBlock.button.contrastText, |
| 57 | +padding:theme.spacing(0.85), |
| 58 | +minWidth:32, |
| 59 | + |
| 60 | +"&:hover":{ |
| 61 | +background:theme.palette.codeBlock.button.hover, |
| 62 | +}, |
| 63 | +}, |
| 64 | +fileCopyIcon:{ |
| 65 | +width:20, |
| 66 | +height:20, |
| 67 | +}, |
| 68 | +})) |