Files
swagger-ui/src/core/components/highlight-code.jsx
Aldrin Abastillas 973e1f7a9b feat: Copy response to clipboard #4300 (#5278)
* Move next to download button and match styling

Co-authored-by: Aldrin Abastillas <AAbastillas@rcanalytics.com>
Co-authored-by: Tim Lai <timothy.lai@gmail.com>
2020-06-15 15:08:10 -07:00

79 lines
2.0 KiB
JavaScript

import React, { Component } from "react"
import PropTypes from "prop-types"
import { highlight } from "core/utils"
import saveAs from "js-file-download"
import { CopyToClipboard } from "react-copy-to-clipboard"
export default class HighlightCode extends Component {
static propTypes = {
value: PropTypes.string.isRequired,
className: PropTypes.string,
downloadable: PropTypes.bool,
fileName: PropTypes.string,
canCopy: PropTypes.bool
}
componentDidMount() {
highlight(this.el)
}
componentDidUpdate() {
highlight(this.el)
}
initializeComponent = (c) => {
this.el = c
}
downloadText = () => {
saveAs(this.props.value, this.props.fileName || "response.txt")
}
preventYScrollingBeyondElement = (e) => {
const target = e.target
var deltaY = e.nativeEvent.deltaY
var contentHeight = target.scrollHeight
var visibleHeight = target.offsetHeight
var scrollTop = target.scrollTop
const scrollOffset = visibleHeight + scrollTop
const isElementScrollable = contentHeight > visibleHeight
const isScrollingPastTop = scrollTop === 0 && deltaY < 0
const isScrollingPastBottom = scrollOffset >= contentHeight && deltaY > 0
if (isElementScrollable && (isScrollingPastTop || isScrollingPastBottom)) {
e.preventDefault()
}
}
render () {
let { value, className, downloadable, canCopy } = this.props
className = className || ""
return (
<div className="highlight-code">
{ !downloadable ? null :
<div className="download-contents" onClick={this.downloadText}>
Download
</div>
}
{ !canCopy ? null :
<div className="copy-to-clipboard">
<CopyToClipboard text={value}><button/></CopyToClipboard>
</div>
}
<pre
ref={this.initializeComponent}
onWheel={this.preventYScrollingBeyondElement}
className={className + " microlight"}>
{value}
</pre>
</div>
)
}
}