react-virtualized icon indicating copy to clipboard operation
react-virtualized copied to clipboard

Faster onScroll with Scrollsync

Open martinpesout opened this issue 10 years ago • 44 comments

I'm using your example https://bvaughn.github.io/react-virtualized/ to create big datatable with fixed table header. Problem is when I start scrolling to the sides. You can see it on your example (tested in MacOS Chrome with magic mouse). If you scroll to the side you can see that header is updated with some delay. Is there any chance how to improve this speed. I know that it's Javascript solution that calculations take some time, but if you check different solution from Facebook http://facebook.github.io/fixed-data-table/example-object-data.html it's also achieved by Javascript and scrolling is fluid.

Thanks for your help.

martinpesout avatar Jun 22 '16 10:06 martinpesout

Hey @martinpesout,

Unfortunately fixed-data-table is kind of an apples-to-oranges comparison. ScrollSync is synchronizing the scroll offsets between multiple, individually-scrollable items. Because scrolling is managed by a separate thread, and JavaScript is only periodically notified of the updated position, there's some latency issues with this. Unfortunately they can't be avoided (at least not to my knowledge, having spent a great deal of time trying to optimize things like this).

That being said, I'm always trying to reduce latency and increase FPS. (I spent most of this past weekend working on FPS improvements for FlexTable.) And I'd welcome any PRs or contributions that you or others would like to make to help out in this regard.

But I'm going to close this issue for now. There isn't any direct action I can take to resolve it- at least none that I'm aware of. If you find some time to experiment and you have suggestions though- let's talk! :)

bvaughn avatar Jun 22 '16 14:06 bvaughn

(We can keep talking here too. I'll see and respond to comments on this issue.)

bvaughn avatar Jun 22 '16 14:06 bvaughn

Out of curiosity: why doesn't this happen when using the scrollbar? (It moves in sync then)

vincent-io avatar Jun 22 '16 14:06 vincent-io

I think scrollbar dragging is done in the UI thread. The reason scroll-wheel scrolling is in a separate thread is so they can do the smooth animation (without it being janky).

bvaughn avatar Jun 22 '16 14:06 bvaughn

Hi, if I understand it correctly, ScrollSync is relying on native scrolling and synchronization of the scroll position is happening ex post? Therefore to achieve sooner synchronization one would have to sacrifice benefits of native scrolling - is that the problem?

vojtech-dobes avatar Jun 22 '16 14:06 vojtech-dobes

So, as a work-around, can we actually artificially drag the scrollbar when scrolling?

vincent-io avatar Jun 22 '16 14:06 vincent-io

You are both correct.

There are things you could do to force the browser to scroll in the UI thread (eg adding a mousewheel handler somewhere in the DOM ancestry) but this can cause the UI to feel unresponsive in other ways.

bvaughn avatar Jun 22 '16 15:06 bvaughn

Hi Brian, I've been thinking :).

ScrollSync seems having its own way and reasons, and it's probably not worth to hack it. Adding something on top of it will only lead to performance downgrade, so that doesn't seem like right way to solve our problem.

So I think about Grid itself. If I am not omitting some important factor, fixed header is just a "row" that is special because:

  1. Is never removed from table unlike regular rows going out of "viewport".
  2. Its vertical position remains untouched.

Maybe fixed header functionality could be achieved in Grid itself in the end :). It would be extra "row" that would stay rendered regardless scroll position and would keep its vertical position (it would be independent on vertical scroll). When we would scroll horizontally, same "momentum" would be applied on it as on other rows.

Do you think something like this would be acceptable approach?

vojtech-dobes avatar Jun 23 '16 09:06 vojtech-dobes

Have considered that before but could not think of an Api for it that wasn't clunky.

I tend to think that overriding the cellRangeRenderer may be the best/easiest way for someone who wants fixed rows or columns. Because there are a lot of possible things you might want. Fixed left or right column or both? Fixed header or footer row or both? More than one fixed row/column? All of the above?

bvaughn avatar Jun 23 '16 15:06 bvaughn

Thanks, this looks very interesting, will look into it first. The combinations you mention are all desired after all as well :).

vojtech-dobes avatar Jun 23 '16 15:06 vojtech-dobes

Hi @bvaughn

I've found solution for this problem. We don't need to "hack" your Grid. Solution is in clever trick. I'll never render table with smaller width than is summary width of all columns. So you won't have horizontal scrollbars in your Grid. I'll add another wrapper around your Grid which contains header and allow us only to scroll horizontally (so you will scroll horizontally together with header and Grid). With this trick you can do table with fixed header and native scrollbars. And you don't need ScrollSync.

There is one small problem with vertical scrollbar which is positioned on the right end of table. So if you have a lot of columns it will be outside screen. This can be fixed by transparent element which will be always on the right side and will be looking Grid vertical scrollbar.

snimek obrazovky 2016-06-27 v 12 02 33

This solution works when you have the same height for each row (for now). But can be easily updated.

/*global document */

import classNames from 'classnames';
import React, { PropTypes } from 'react';
import { Grid } from 'react-virtualized';
import { $ } from '../../../../globals.js';

import scrollbarSize from 'dom-helpers/util/scrollbarSize';



export default React.createClass({

    propTypes: {
        bodyCellRenderer: PropTypes.func.isRequired,
        columnCount: PropTypes.number.isRequired,
        columnWidth: PropTypes.oneOfType([
            PropTypes.number,
            PropTypes.func,
        ]).isRequired,
        headerCellRenderer: PropTypes.func.isRequired,
        headerHeight: PropTypes.number.isRequired,
        height: PropTypes.number.isRequired,
        overscanColumnCount: PropTypes.number,
        onScroll: PropTypes.func,
        rowCount: PropTypes.number.isRequired,
        rowHeight: PropTypes.number.isRequired,
        scrollTop: PropTypes.number,
        width: PropTypes.number.isRequired,
    },



    _wrapPropertyGetter (value) {
        return value instanceof Function
        ? value
        : () => value
    },



    _wrapSizeGetter (size) {
        return this._wrapPropertyGetter(size)
    },



    getInitialState: function() {
        return {
            scrollTop: 0,
        };
    },



    _getAllColumnsWidth: function() {
        const {
            columnCount,
            columnWidth,
        } = this.props;

        var width = 0;
        var columnWidthGetter = this._wrapSizeGetter(columnWidth);

        for (var i = 0; i < columnCount; i++) {
            width += columnWidthGetter({index: i});
        }

        return width + scrollbarSize();
    },



    _handleGridScroll(props) {
        const {
            onScroll,
        } = this.props;

        this.setState({
            scrollTop: props.scrollTop,
        });

        this.refs.Scrollbar.scrollTop = props.scrollTop;

        if (onScroll) {
            onScroll(props);
        }
    },



    componentDidMount: function() {
        $(this.refs.Scrollbar).on('scroll.FixedHeaderGrid', (e) => {
            this.setState({
                scrollTop: e.target.scrollTop,
            });
        });
    },



    componentWillUnmount: function() {
        $(document).unbind('.FixedHeaderGrid');
    },



    componentWillReceiveProps: function(nextProps) {
        const {
            scrollTop,
        } = this.props;

        const {
            scrollTop: nextScrollTop,
        } = nextProps;

        if (scrollTop !== nextScrollTop) {
            this.setState({
                scrollTop: nextScrollTop,
            });

            this.refs.Scrollbar.scrollTop = scrollTop;
            this.refs.BodyGrid.forceUpdate();
        }
    },



    _renderHeader() {
        const {
            columnCount,
            headerCellRenderer,
        } = this.props;

        var cells = [];

        for (var i = 0; i < columnCount; i++) {
            cells.push(
                <div key={'hcell' + i}>
                    {headerCellRenderer({columnIndex: i})}
                </div>
            );
        }

        return cells;
    },



    render: function() {
        const {
            bodyCellRenderer,
            columnCount,
            columnWidth,
            headerHeight,
            height,
            overscanColumnCount,
            rowCount,
            rowHeight,
            width,
        } = this.props;

        const {
            scrollTop,
        } = this.state;

        return (
            <div
                className="rv-table"
                style={{
                    width: width,
                    height: height - scrollbarSize(),
                }}
            >
                <div
                    className="rv-table__scrollbar"
                    ref="Scrollbar"
                    style={{
                        top: headerHeight,
                    }}
                >
                    <div
                        style={{
                            height: rowHeight * rowCount,
                        }}
                    >
                    </div>
                </div>
                <div className="rv-table__content">
                    <div
                        className={classNames({
                            'rv-table__grid': true,
                            'rv-table__grid--header': true,
                            'rv-table__grid--bottom-shadow': scrollTop > 0,
                        })}
                        style={{
                            top: 0,
                            left: 0,
                            width: this._getAllColumnsWidth(),
                            height: headerHeight,
                        }}
                    >
                        {this._renderHeader()}
                    </div>

                    <Grid
                        cellRenderer={bodyCellRenderer}
                        className="rv-table__grid"
                        columnCount={columnCount}
                        columnWidth={columnWidth}
                        height={height - headerHeight - scrollbarSize()}
                        onScroll={this._handleGridScroll}
                        overscanColumnCount={overscanColumnCount}
                        ref="BodyGrid"
                        rowHeight={rowHeight}
                        rowCount={rowCount}
                        scrollTop={scrollTop}
                        width={this._getAllColumnsWidth()}
                    />
                </div>
            </div>
        );
    },

});

Important SCSS:

/**
 * react-virtualized table
 *
 * 1. Never use box-shadow because scrolling performance will be bad
 * 2. Hide scrollbars
 */

.rv-table {
    position: relative;



    &__content {
        position: relative;
        overflow: auto;
        z-index: 950;
    }



    &__grid {
        &::-webkit-scrollbar {
            display: none; /* [2] */
        }



        &--header {
            display: flex;
            position: relative;
            z-index: 10000;

            will-change: all;
            transform: translate3d(0, 0, 0);

            background-color: map-get($table, bg-header);
        }



        &--bottom-shadow { /*[1]*/
            &:after {
                content: "";
                display: block;
                height: 4px;
                left: 0;
                right: 0;
                bottom: -4px;
                position: absolute;
                right: 0;
                z-index: 1000000;

                background: 0 0 url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAAECAYAAABP2FU6AAAAF0lEQVR4AWPUkNeSBhHCjJoK2twgFisAFagCCp3pJlAAAAAASUVORK5CYII=) repeat-x;
            }
        }
    }



    &__scrollbar {
        position: absolute;
        right: 0;
        top: 0;
        bottom: 0;
        overflow: auto;
        width: 20px;
        z-index: 1000;

        pointer-events: auto;
    }
}

martinpesout avatar Jun 27 '16 10:06 martinpesout

Hey @martinpesout,

Thanks for sharing your solution. Don't suppose it's anywhere online that I could access to see for myself? :)

bvaughn avatar Jun 27 '16 15:06 bvaughn

I'll try to give you an access to our app as soon as possible. So you will be able to see it in action. But we have to solve something before release. I'll let you know.

martinpesout avatar Jun 27 '16 15:06 martinpesout

Sounds great! I look forward to seeing it.

Didn't sleep well last night so my brain's a bit fuzzy this morning. But when I'm a bit more alert, I want to look at what you mentioned above and try to see if there's something generic / reusable there for others.

bvaughn avatar Jun 27 '16 16:06 bvaughn

Fun fact: placing a canvas above the element which fires the scroll events removes the delay in scroll event firing (and, consequently, delay in fixed column/row scrolling). Easiest way to reproduce: enable "Trace React updates" in React DevTools (it works by overlaying a viewport-wide canvas over the document).

This, of course, comes at a small (negligible IMO) performance cost.

sbichenko avatar Jul 24 '16 09:07 sbichenko

There are other ways of forcing scrolling to happen in the UI thread as well (eg attaching position: fixed to a Grid) but the performance cost probably makes them not worth it. At least in my limited testing, it really slows down how responsive a grid feels. :(

I think in the case you described, it's the position: fixed style of the <canvas> that's forcing the synchronous scrolling.

bvaughn avatar Jul 24 '16 12:07 bvaughn

Nope, it actually works even without position: fixed (at least with position: absolute). I feel like the performance cost is not that noticeable, actually! However, I haven't tested this with React Virtualized, just with a custom-made table with "frozen" header and first column. Anyway, something to maybe investigate.

On Sun, Jul 24, 2016 at 3:53 PM, Brian Vaughn [email protected] wrote:

There are other ways of forcing scrolling to happen in the UI thread as well (eg attaching position: fixed to a Grid) but the performance cost probably makes them not worth it. At least in my limited testing, it really slows down how responsive a grid feels. :(

I think in the case you described, it's the position: fixed style of the that's forcing the synchronous scrolling.

— You are receiving this because you commented. Reply to this email directly, view it on GitHub https://github.com/bvaughn/react-virtualized/issues/291#issuecomment-234775690, or mute the thread https://github.com/notifications/unsubscribe-auth/ADjAaxzsmXm4u6doG5ljKe4DdjsvaxbCks5qY2BUgaJpZM4I7n39 .

sbichenko avatar Jul 24 '16 13:07 sbichenko

I see! That didn't seem to be the case for me when I looked earlier but I just confirmed you are correct. :)

Any time in the past I've forced scrolling to be in the UI thread (like I assume this is causing) it has opened up some performance problems for larger grids.

Doing some quit spot-testing now with one of my playground files. It does seem to negatively impact performance. But not a huge amount. May be worth exploring further! :D

bvaughn avatar Jul 24 '16 21:07 bvaughn

If you place something above grid, this will solve scrolling detail, but you won't be able to select text inside cells, implement onRowClick events. Maybe I'm wrong but this is really big disadvantage I see in @sbichenko's suggestion.

martinpesout avatar Jul 25 '16 11:07 martinpesout

You can if you set pointer-events: none on the top layer.

bvaughn avatar Jul 25 '16 11:07 bvaughn