1
1
mirror of https://github.com/primer/css.git synced 2024-11-30 19:53:11 +03:00
css/docs/ClipboardCopy.js

48 lines
1.4 KiB
JavaScript
Raw Normal View History

2018-12-10 19:05:22 +03:00
import React from 'react'
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
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
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')
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()
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
}
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>
)
}
}