spaCy/website/src/components/copy.js

49 lines
1.5 KiB
JavaScript
Raw Normal View History

2020-07-05 17:11:16 +03:00
import React, { useState, useRef } from 'react'
import Icon from './icon'
import classes from '../styles/copy.module.sass'
2020-07-31 14:26:39 +03:00
export function copyToClipboard(ref, callback) {
const isClient = typeof window !== 'undefined'
if (ref.current && isClient) {
ref.current.select()
document.execCommand('copy')
callback(true)
ref.current.blur()
setTimeout(() => callback(false), 1000)
}
}
2020-08-06 02:22:49 +03:00
export default function CopyInput({ text, prefix }) {
2020-07-05 17:11:16 +03:00
const isClient = typeof window !== 'undefined'
const supportsCopy = isClient && document.queryCommandSupported('copy')
const textareaRef = useRef()
const [copySuccess, setCopySuccess] = useState(false)
2020-07-31 14:26:39 +03:00
const onClick = () => copyToClipboard(textareaRef, setCopySuccess)
2020-07-05 17:11:16 +03:00
function selectText() {
if (textareaRef.current && isClient) {
textareaRef.current.select()
}
}
return (
<div className={classes.root}>
{prefix && <span className={classes.prefix}>{prefix}</span>}
<textarea
ref={textareaRef}
readOnly
className={classes.textarea}
defaultValue={text}
rows={1}
onClick={selectText}
/>
{supportsCopy && (
2020-07-31 14:26:39 +03:00
<button title="Copy to clipboard" onClick={onClick}>
2020-07-05 17:11:16 +03:00
<Icon width={16} name={copySuccess ? 'accept' : 'clipboard'} />
</button>
)}
</div>
)
}