2018-12-10 19:05:22 +03:00
|
|
|
import React from 'react'
|
2018-12-18 01:43:38 +03:00
|
|
|
import {findDOMNode} from 'react-dom'
|
|
|
|
import {Button} from '@primer/components'
|
|
|
|
import Octicon, {Clippy} from '@githubprimer/octicons-react'
|
2018-12-10 19:05:22 +03:00
|
|
|
|
2018-12-18 01:43:38 +03:00
|
|
|
export default class ClipboardCopy extends React.Component {
|
|
|
|
copy() {
|
|
|
|
const {value = ''} = this.props
|
|
|
|
const {clipboard} = window.navigator
|
|
|
|
const done = () => {
|
2018-12-18 01:48:29 +03:00
|
|
|
// eslint-disable-next-line react/no-find-dom-node
|
2018-12-18 01:43:38 +03:00
|
|
|
findDOMNode(this).dispatchEvent(new CustomEvent('copy', {bubbles: false}))
|
|
|
|
}
|
|
|
|
if (clipboard) {
|
|
|
|
return clipboard.writeText(value).then(done)
|
|
|
|
} else if (!document.body) {
|
|
|
|
return
|
|
|
|
} else {
|
2018-12-18 01:48:29 +03:00
|
|
|
const node = document.createElement('pre')
|
2018-12-18 01:43:38 +03:00
|
|
|
node.style.width = '1px'
|
|
|
|
node.style.height = '1px'
|
|
|
|
node.style.position = 'fixed'
|
|
|
|
node.style.top = '5px'
|
|
|
|
node.textContent = value
|
2018-12-10 19:05:22 +03:00
|
|
|
|
2018-12-18 01:48:29 +03:00
|
|
|
const selection = window.getSelection()
|
2018-12-18 01:43:38 +03:00
|
|
|
document.body.appendChild(node)
|
|
|
|
selection.removeAllRanges()
|
|
|
|
const range = document.createRange()
|
|
|
|
range.selectNodeContents(node)
|
|
|
|
selection.addRange(range)
|
|
|
|
document.execCommand('copy')
|
|
|
|
selection.removeAllRanges()
|
|
|
|
document.body.removeChild(node)
|
|
|
|
}
|
2018-12-14 08:39:59 +03:00
|
|
|
}
|
2018-12-18 01:43:38 +03:00
|
|
|
|
|
|
|
render() {
|
|
|
|
// eslint-disable-next-line no-unused-vars
|
|
|
|
const {value = '', ...rest} = this.props
|
|
|
|
return (
|
|
|
|
<Button onClick={() => this.copy()} type="button" {...rest}>
|
|
|
|
<Octicon icon={Clippy} />
|
|
|
|
</Button>
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|