vitalif / dynamic-virtual-scroll

Render-agnostic Dynamic Virtual Scroll Driver for JS
38 stars 11 forks source link

Dynamic Virtual Scroll Driver

Virtual scrolling is a technique for displaying long lists or tables when you render only a small number of visible items and skip items that are offscreen. You may also have heard about it like "buffered render" or "windowed render" - it's the same.

There are plenty of virtual scroll implementations for JS. Some of them are part of a larger UI library (ag-grid, ExtJS and so on), some of them are more standalone (react-virtualized, react-window, ngx-virtual-scroller, ngx-ui-scroll, react-dynamic-virtual-list).

However, there is a thing that they all miss: dynamic (and unknown apriori) row heights. Some implementations allow to set different row heights for items, but you must calculate all heights before rendering; some allow dynamic row heights, but have bugs and act weird or don't really work; others just force you to use fixed row height. Most implementations are also tied to some specific UI component or framework and are unusable with other ones.

Good news, everyone: we have a solution!

It is render-agnostic and implemented in this library. Basically, this library only does the maths for you while letting you render your component yourself. You can use it with React, Angular, pure JS or any other framework you want to. You can implement lists and grids (tables) with it. It works smoothly, does not break built-in browser scrolling and even works on mobile devices.

Usage

The library exports a single function:

import { virtualScrollDriver } from 'dynamic-virtual-scroll';

const newState = virtualScrollDriver(
    { totalItems, minRowHeight, viewportHeight, scrollTop },
    oldState,
    function getRenderedItemHeight(itemIndex) { ... }
);

You must call it after each render and also when the viewport, scroll position or items change.

Description of parameters:

Returned object is newState. It contains the render parameters for you and also some internal state variables. What to do with it:

Usage with React

There is a reference virtual list implementation for React.

It is usually sufficient for almost everything, including grids. Sad thing about grids (virtualized tables) in HTML is that automatic table-like layout is slow in browsers, so in fact the best way to implement them is via simple virtualized lists of \

's with absolutely positioned cells inside.

import React from 'react';
import { VirtualScrollList } from 'dynamic-virtual-scroll/VirtualScrollList.es5.js';

class MyList extends React.Component
{
    renderItem = (i) =>
    {
        if (!this.items[i])
            return null;
        return <div style={{minHeight: '20px'}}>{this.items[i].title}</div>;
    }

    render()
    {
        return <VirtualScrollList
            totalItems={this.items.length}
            renderItem={this.renderItem}
            minRowHeight={20}
        />;
    }
}

Description of VirtualScrollList parameters:

  • totalItems: required, total number of items in the list.
  • minRowHeight: required, minimal possible item height in the list.
  • renderItem: required, function that renders item by index as React element(s).
  • viewportHeight: optional, viewport height to use for virtual scrolling. May be used in case when it can't be determined automatically by VirtualScroll, for example inside an animated element with css maxHeight.
  • header: optional, React element(s) to unconditionally render in the beginning of the list. The intended usage is to render fixed header row with CSS position: sticky over the scrolled content.
  • headerHeight: optional. In case there is a fixed header, this must be its height in pixels.
  • All other parameters (className, style, onClick, etc) are passed as-is to the underlying root \
    of the list.

VirtualScrollList contains some extra shenanigans to make sure the scroll position preserves when the total number of items changes. Also it has two extra methods:

  • list.scrollToItem(itemIndex) - positions the list at itemIndex. The index may contain fractional part, in that case the list will be positioned at the corresponding % of height of the item.
  • list.getItemScrollPos() - returns current scroll position in items. The returned index may contain fractional part and may be used as input to list.scrollToItem().

Simpler React example

See DynamicVirtualScrollExample.js.

How to test it:

  • Clone this repository
  • npm install
  • npm run build
  • Open index.html in your browser

Demo

http://yourcmc.ru/dynamic-virtual-scroll/

Algorithm

  • Use reasonable fixed minimum row height
  • Always render screen/minHeight last rows
  • Find maximum possible viewport start in units of (item number + % of item)
  • Measure average height of last rows
  • avgHeight = max(minHeight, lastRowAvgHeight)
  • targetHeight = avgHeight*rowCount
  • Total scroll view height will be targetHeight
  • scrollPos = targetHeight > offsetHeight ? min(1, scrollTop / (targetHeight - offsetHeight)) : 0
  • First visible item will be Math.floor(scrollPos*maxPossibleViewportStart)
  • Additional scroll offset will be itemOffset = (scrollPos*maxPossibleViewportStart - Math.floor(scrollPos*maxPossibleViewportStart))*firstVisibleItemHeight
  • First (top) placeholder height will be scrollTop-itemOffset
  • Second (middle) placeholder height will be avgHeight*nodeCount - sum(heights of all rendered rows) - (first placeholder height)

License and author

Author: Vitaliy Filippov, 2018+

License: GNU LGPLv3.0 or newer