Skip to content

Commit

Permalink
fix(highlight-code): handle mousewheel events properly (#7554)
Browse files Browse the repository at this point in the history
SyntaxHighlighter component doesn't support ref. We had
to use different approach to finds it's DOM Node using
ref of the root Node of the render tree for HighlightCode
component.

Refs #7497
  • Loading branch information
char0n committed Oct 12, 2021
1 parent 5ada9ef commit 0fc429f
Showing 1 changed file with 16 additions and 10 deletions.
26 changes: 16 additions & 10 deletions src/core/components/highlight-code.jsx
Expand Up @@ -16,17 +16,26 @@ export default class HighlightCode extends Component {
canCopy: PropTypes.bool
}

#syntaxHighlighter;
#pre;
#childNodes

downloadText = () => {
saveAs(this.props.value, this.props.fileName || "response.txt")
}

handleRootRef = (node) => {
if (node === null) {
this.#childNodes = node
} else {
this.#childNodes = Array
.from(node.childNodes)
.filter(node => !!node.nodeType && node.classList.contains("microlight"))
}
}

preventYScrollingBeyondElement = (e) => {
const target = e.target

var deltaY = e.nativeEvent.deltaY
var deltaY = e.deltaY
var contentHeight = target.scrollHeight
var visibleHeight = target.offsetHeight
var scrollTop = target.scrollTop
Expand All @@ -43,13 +52,11 @@ export default class HighlightCode extends Component {
}

componentDidMount() {
[this.#syntaxHighlighter, this.#pre]
.map(element => element?.addEventListener("mousewheel", this.preventYScrollingBeyondElement, { passive: false }))
this.#childNodes?.forEach(node => node.addEventListener("mousewheel", this.preventYScrollingBeyondElement, { passive: false }))
}

componentWillUnmount() {
[this.#syntaxHighlighter, this.#pre]
.map(element => element?.removeEventListener("mousewheel", this.preventYScrollingBeyondElement))
this.#childNodes?.forEach(node => node.removeEventListener("mousewheel", this.preventYScrollingBeyondElement))
}

render () {
Expand All @@ -61,17 +68,16 @@ export default class HighlightCode extends Component {

const codeBlock = get(config, "syntaxHighlight.activated")
? <SyntaxHighlighter
ref={elem => this.#syntaxHighlighter = elem}
language={language}
className={className + " microlight"}
style={getStyle(get(config, "syntaxHighlight.theme"))}
>
{value}
</SyntaxHighlighter>
: <pre ref={elem => this.#pre = elem} className={className + " microlight"}>{value}</pre>
: <pre className={className + " microlight"}>{value}</pre>

return (
<div className="highlight-code">
<div className="highlight-code" ref={this.handleRootRef}>
{ !downloadable ? null :
<div className="download-contents" onClick={this.downloadText}>
Download
Expand Down

0 comments on commit 0fc429f

Please sign in to comment.