aboutsummaryrefslogtreecommitdiffstats
path: root/web/src/js/components/helpers/AutoScroll.js
blob: d37b9f374437f85b8f9354fae913a2748d75ea26 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import React from "react";
import ReactDOM from "react-dom";

const symShouldStick = Symbol("shouldStick");
const isAtBottom = v => v.scrollTop + v.clientHeight === v.scrollHeight;

export default Component => Object.assign(class AutoScrollWrapper extends Component {

    static displayName = Component.name;

    componentWillUpdate() {
        const viewport = ReactDOM.findDOMNode(this);
        this[symShouldStick] = viewport.scrollTop && isAtBottom(viewport);
        super.componentWillUpdate && super.componentWillUpdate();
    }

    componentDidUpdate() {
        const viewport = ReactDOM.findDOMNode(this);
        if (this[symShouldStick] && !isAtBottom(viewport)) {
            viewport.scrollTop = viewport.scrollHeight;
        }
        super.componentDidUpdate && super.componentDidUpdate();
    }

}, Component);