├── .gitignore
├── LICENSE
├── README.md
├── demo.html
├── dist
└── react-dvl.min.js
├── index.d.ts
├── index.js
├── package-lock.json
├── package.json
├── source.tsx
├── tsconfig.json
└── webpack.config.js
/.gitignore:
--------------------------------------------------------------------------------
1 | # Logs
2 | logs
3 | *.log
4 | npm-debug.log*
5 | yarn-debug.log*
6 | yarn-error.log*
7 |
8 | # Runtime data
9 | pids
10 | *.pid
11 | *.seed
12 | *.pid.lock
13 |
14 | # Directory for instrumented libs generated by jscoverage/JSCover
15 | lib-cov
16 |
17 | # Coverage directory used by tools like istanbul
18 | coverage
19 |
20 | # nyc test coverage
21 | .nyc_output
22 |
23 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files)
24 | .grunt
25 |
26 | # Bower dependency directory (https://bower.io/)
27 | bower_components
28 |
29 | # node-waf configuration
30 | .lock-wscript
31 |
32 | # Compiled binary addons (http://nodejs.org/api/addons.html)
33 | build/Release
34 |
35 | # Dependency directories
36 | node_modules/
37 | jspm_packages/
38 |
39 | # Typescript v1 declaration files
40 | typings/
41 |
42 | # Optional npm cache directory
43 | .npm
44 |
45 | # Optional eslint cache
46 | .eslintcache
47 |
48 | # Optional REPL history
49 | .node_repl_history
50 |
51 | # Output of 'npm pack'
52 | *.tgz
53 |
54 | # Yarn Integrity file
55 | .yarn-integrity
56 |
57 | # dotenv environment variables file
58 | .env
59 |
60 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2018 Scott Lott
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # react-dynamic-virtual-list
2 | React virtual list component that aims to be the most flexible and performant.
3 |
4 | ### Features
5 | - Super simple setup.
6 | - Just over 2 KB Gzipped.
7 | - Server side render support.
8 | - Supports variable element heights.
9 | - Supports a grid layouts with flexbox.
10 | - Automatically detects element heights.
11 | - Renders with requestAnimationFrame for good scroll performance.
12 | - Multiple lifecycle events and hooks.
13 | - Typescript, Babel and ES5 support.
14 |
15 | # Installation
16 |
17 | ```
18 | npm i react-dynamic-virtual-list
19 | ```
20 |
21 | Using in Typescript/Babel project:
22 |
23 | ```js
24 | import { DVL } from "react-dynamic-virtual-list";
25 | ```
26 |
27 | Using in Node:
28 |
29 | ```js
30 | const DVL = require("react-dynamic-virtual-list").DVL;
31 | ```
32 |
33 | To use directly in the browser, drop the tag below into your `
`.
34 |
35 | ```html
36 |
37 | ```
38 |
39 |
40 | ## Quick Start
41 |
42 | ```tsx
43 | import { DVL } from "react-dynamic-virtual-list";
44 | import * as React from "react";
45 |
46 | class App extends React.Component {
47 | render() {
48 | return {item.name}
}
50 | items={[{name: "Billy"}, {name: "Joel"}]}
51 | windowContainer={true}
52 | />
53 | }
54 | }
55 | ```
56 |
57 | ## API
58 |
59 | The Dynamic Virtual List will render your items 100 at a time onto the dom and measure their height using `.clientHeight`, then use that cached value to render the actual virtual list. The virtual list will grow in size appropriately as it completes measuring each block.
60 |
61 | Callbacks can be used to hide the element while it's doing this, or the behavior can be avoided entirely by passing different values into the `calculateHeight` prop.
62 |
63 | Grid layouts are supported provided each element is a fixed width.
64 |
65 | ## Props
66 | \* Required
67 |
68 |
69 | ### *onRender: `(item: any, index: number, columns?: number) => JSX.Element`
70 | Function to use to render each element, must return a JSX Element. If using a grid layout make sure you set fixed widths to your elements. DO NOT use margins, if you need spacing between the elements create an inner element that contains the actual content, creating the margins with an outer div.
71 |
72 | If using grid layout, the number of columns currently being displayed is passed into this prop as well. Keep in mind the initial render won't provide a columns argument so even with a grid layout you should set up your render prop to handle `undefined` column values.
73 |
74 | ### *items: `any[]`
75 | Array of items to render into the list.
76 |
77 | ### calculateHeight: `number | (container: HTMLDivElement, item: any, index: number) => number`
78 | If this prop is unused, the library will render every element onto the page to discover it's height with `.clientHeight`, then display it in the virtual list, 100 items at a time. You can change this behavior completely by either passing in a function to use for calculating heights or a number that will be used as a fixed height for all elements.
79 |
80 | Passing in a fixed number is by far the most performant option while the function is a good second choice.
81 |
82 | **IMPORTANT!** The library makes *zero* attempts to resolve height conflicts. If you give a fixed height to the `calculateHeight` prop and the elements aren't actually fixed to that height, you're gonna have a bad time.
83 |
84 | ### windowContainer: `boolean`
85 | Pass "true" to use the window as the scroll container.
86 |
87 | ### buffer: `number`
88 | Default is 5, number of rows to render below and above the visual area.
89 |
90 | ### containerRef: (ref: `HTMLDviElement`) => void
91 | The ref of the container DIV generated by the library to contain the inner container div and it's list.
92 |
93 | ### containerStyle: `React.CSSProperties`
94 | Pass through styles to the container DIV. If you aren't using the window as a container then set a fixed height and `overflowY: "scroll"` here.
95 |
96 | ### containerClass: `string`
97 | Pass through classes to the container DIV.
98 |
99 | ### innerContainerStyle: `React.CSSProperties`
100 | Pass through styles to the inner container DIV. This div holds the list of rendered elements. If you plan to do Flexbox this is the place to put your styles. `paddingTop` and `height` styles will be ignored/overwritten.
101 |
102 | ### innerContainerClass: `string`
103 | Pass through classes to the inner container DIV that holds the list elements.
104 |
105 | ### doUpdate: `(calcVisible: (scrollTop?: number, containerHeight?: number) => void) => void`
106 | By default the library attaches the method to calculate the visible space to the scroll event and renders onRequestAnimationFrame. You can disable and override this behavior by using this prop, the only argument is the method that calculates what should be visible on the screen. You can even pass in manually generated height and scrollTop values into the method. When you use this prop the library will only update it's visible area when the provided function is called or on window resize.
107 |
108 | If no `scrollTop` or `containerHeight` arguments are passed in the library will fall back to it's default behavior, using the window or container to measure what should show up.
109 |
110 | ### gridItemWidth: `number`
111 | Leave blank if you're doing one item per row. If you're doing a grid layout then pass in the fixed width of your grid items here.
112 |
113 | ### onResizeStart: `(doResize: () => void) => void`
114 | On the first render and each time the screen resizes the height of every element is checked and the list is re rendered from scratch. This prop is called just after the resize has triggered. The callback method triggers the actual resize methods, so you can decide when the layout should be recalculated, useful for transitions and the like.
115 |
116 | ### onResizeFinish: `(scrollHeight: number, columns: number) => void`
117 | Once the resize is done being calculated this prop will be called. The total height of all elements and the number of columns calculated is also passed in as the single argument.
118 |
119 |
120 | # MIT License
121 |
122 | Copyright (c) 2018 Scott Lott
123 |
124 | Permission is hereby granted, free of charge, to any person obtaining a copy
125 | of this software and associated documentation files (the "Software"), to deal
126 | in the Software without restriction, including without limitation the rights
127 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
128 | copies of the Software, and to permit persons to whom the Software is
129 | furnished to do so, subject to the following conditions:
130 |
131 | The above copyright notice and this permission notice shall be included in all
132 | copies or substantial portions of the Software.
133 |
134 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
135 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
136 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
137 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
138 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
139 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
140 | SOFTWARE.
141 |
--------------------------------------------------------------------------------
/demo.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | Document
9 |
10 |
13 |
14 |
15 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
81 |
82 |
83 |
--------------------------------------------------------------------------------
/dist/react-dvl.min.js:
--------------------------------------------------------------------------------
1 | !function(t,e){if("object"==typeof exports&&"object"==typeof module)module.exports=e(require("react"));else if("function"==typeof define&&define.amd)define(["react"],e);else{var i="object"==typeof exports?e(require("react")):e(t.react);for(var s in i)("object"==typeof exports?exports:t)[s]=i[s]}}(window,function(t){return function(t){var e={};function i(s){if(e[s])return e[s].exports;var n=e[s]={i:s,l:!1,exports:{}};return t[s].call(n.exports,n,n.exports,i),n.l=!0,n.exports}return i.m=t,i.c=e,i.d=function(t,e,s){i.o(t,e)||Object.defineProperty(t,e,{configurable:!1,enumerable:!0,get:s})},i.r=function(t){Object.defineProperty(t,"__esModule",{value:!0})},i.n=function(t){var e=t&&t.t?function(){return t.default}:function(){return t};return i.d(e,"a",e),e},i.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},i.p="",i(i.s=1)}([function(e,i){e.exports=t},function(t,e,i){"use strict";var s,n=this&&this.h||(s=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var i in e)e.hasOwnProperty(i)&&(t[i]=e[i])},function(t,e){function i(){this.constructor=t}s(t,e),t.prototype=null===e?Object.create(e):(i.prototype=e.prototype,new i)}),o=this&&this.e||Object.assign||function(t){for(var e,i=1,s=arguments.length;ir-1?h:e.props.gridItemWidth?(e.j[c]=o,p||(c%s==0&&(i=0),i=Math.max(i,e.f[c])),c===e.f.length-1?(n[o]=i,h+i):c%s==s-1?(n[o]=i,o++,h+i):h):h+a},0);if(this.props.gridItemWidth?this.a=n:this.a=this.f,t)this.props.cacheKey&&(h[String(this.props.cacheKey)]||(h[String(this.props.cacheKey)]={}),h[String(this.props.cacheKey)][window.innerWidth]={rows:this.a,items:this.f,height:a}),this.setState({M:!1,q:s,T:0},function(){e.setState({H:a},function(){e.S()}),e.props.onResizeFinish&&e.props.onResizeFinish(a,s,e.f)});else{var c=Math.round(a/r),u=(this.props.items.length-r)*c;this.setState({H:a+u,q:s},function(){e.S()})}},e.prototype.D=function(t){this.O?window.requestAnimationFrame(function(){t()}):setTimeout(function(){t()},16)},e.prototype.S=function(){this.F||(this.F=!0,this.D(this.b))},e.prototype.b=function(t,e){var i=this,s=e||this.state.I.clientHeight,n=0,o=t||this.state.I.scrollTop,r=0;if(this.R&&this.O){var p=this.state.I.getBoundingClientRect().top,h=document.documentElement,a=p+(o=(window.pageYOffset||h.scrollTop)-(h.clientTop||0));if(s=window.innerHeight,(o-=a)<0&&o<-1*s)return void(this.F=!1)}for(var c=[],u=0;u=o){if(c[0]=Math.max(0,u-this.u),n=r,c[0]!==u)for(var d=1,y=u-c[0];y>0&&d<=y;)n-=this.a[u-d],d++}else!l&&f&&r>o+s&&(c[1]=Math.min(u+this.u,this.a.length));r+=this.a[u],u++}}void 0===c[1]&&(c[1]=this.a.length),this.F=!1,this.setState({z:c,N:n,B:function(){if(void 0!==i.props.calculateHeight){var t=i.props.gridItemWidth?c.map(function(t){return t*i.state.q}):c;return i.props.items.slice.apply(i.props.items,t)}return i.props.items.filter(function(t,e){return!(i.state.T&&e>i.state.T-1)&&(i.props.gridItemWidth?i.j[e]>=c[0]&&i.j[e]<=c[1]:e>=c[0]&&e<=c[1])})}()})},e.prototype.G=function(){this.state.I&&!this.props.doUpdate&&this.O&&(this.R?this.k=window:this.k=this.state.I,this.k.addEventListener("scroll",this.S)),this.g()},e.prototype.render=function(){var t=this,e=this.state.T,i=this.state.T+100,s=this.props.gridItemWidth?this.state.z[0]*this.state.q:this.state.z[0];return"undefined"==typeof window?r.createElement("div",{className:this.props.containerClass,style:o({marginBottom:"10px"},this.props.containerStyle)},r.createElement("div",{className:this.props.innerContainerClass||"",style:this.props.innerContainerStyle||{}},this.props.items.map(function(e,i){return t.props.onRender(e,i,0)}))):r.createElement("div",{className:this.props.containerClass,style:o({marginBottom:"10px",boxSizing:"content-box",height:!this.state.I&&this.state.H?this.state.H:""},this.props.containerStyle),ref:function(e){e&&e!==t.state.I&&t.setState({I:e},function(){t.O&&"scroll"!==window.getComputedStyle(e).overflow&&"scroll"!==window.getComputedStyle(e).overflowY&&(t.R=!0),t.G(),t.props.containerRef&&t.props.containerRef(e)})}},this.state.I?r.createElement("div",{className:this.props.innerContainerClass||"",style:o({height:this.state.H>0?this.state.H-this.state.N:"unset",paddingTop:this.state.N},this.props.innerContainerStyle)},!this.state.M||this.state.T?this.state.B.map(function(e,i){return t.props.onRender(e,s+i,t.state.q)}):null):null,this.state.M&&void 0===this.props.calculateHeight&&this.props.items&&this.props.items.length?r.createElement("div",{style:p},this.props.items.filter(function(t,s){return s>=e&&s0&&t.w%100==0&&t.D(function(){t.setState({T:t.w},function(){t.C(!1)})}))}},t.props.onRender(i,e+s,0))})):null)},e}(r.PureComponent);e.DVL=a}])});
--------------------------------------------------------------------------------
/index.d.ts:
--------------------------------------------------------------------------------
1 | ///
2 | import * as React from "react";
3 | export declare class DVL extends React.PureComponent<{
4 | onRender: (item: any, index: number, columns?: number) => JSX.Element;
5 | items: any[];
6 | calculateHeight?: (container: HTMLDivElement, item: any, index: number) => number | number;
7 | windowContainer?: boolean;
8 | buffer?: number;
9 | containerRef?: (ref: HTMLDivElement) => void;
10 | containerStyle?: React.CSSProperties;
11 | containerClass?: string;
12 | innerContainerClass?: string;
13 | innerContainerStyle?: React.CSSProperties;
14 | cacheKey: string | number;
15 | doUpdate?: (calcVisible: (scrollTop?: number, containerHeight?: number) => void) => void;
16 | gridItemWidth?: number;
17 | onResizeStart?: (doResize: () => void) => void;
18 | onResizeFinish?: (scrollHeight: number, columns: number, heights: number[]) => void;
19 | }, {
20 | _loading: boolean;
21 | _scrollHeight: number;
22 | _topSpacer: number;
23 | _renderRange: number[];
24 | _columns: number;
25 | _progress: number;
26 | _renderItems: any[];
27 | _ref: HTMLDivElement;
28 | }> {
29 | private _buffer;
30 | private _itemHeight;
31 | private _itemRows;
32 | private _doResize;
33 | private _hasWin;
34 | private _scrollDone;
35 | private _ticking;
36 | private _rowCache;
37 | private _counter;
38 | private _firstRender;
39 | private _calcTimer;
40 | private _scrollContainer;
41 | private _oldScroll;
42 | private _progressCounter;
43 | private _useWindow;
44 | constructor(p: any);
45 | componentWillMount(): void;
46 | componentDidUpdate(prevProps: any, prevState: any, snapshot: any): void;
47 | componentWillUnmount(): void;
48 | private _debounceResize();
49 | private _doReflow();
50 | private _reflowLayout();
51 | private _reflowComplete(doFinalPass);
52 | private _nextFrame(cb);
53 | private _scheduleVisibleUpdate();
54 | private _calcVisible(scrollTopIn?, heightIn?);
55 | private _addEventListener();
56 | render(): JSX.Element;
57 | }
58 |
--------------------------------------------------------------------------------
/index.js:
--------------------------------------------------------------------------------
1 | "use strict";
2 | var __extends = (this && this.__extends) || (function () {
3 | var extendStatics = Object.setPrototypeOf ||
4 | ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
5 | function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
6 | return function (d, b) {
7 | extendStatics(d, b);
8 | function __() { this.constructor = d; }
9 | d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
10 | };
11 | })();
12 | var __assign = (this && this.__assign) || Object.assign || function(t) {
13 | for (var s, i = 1, n = arguments.length; i < n; i++) {
14 | s = arguments[i];
15 | for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
16 | t[p] = s[p];
17 | }
18 | return t;
19 | };
20 | Object.defineProperty(exports, "__esModule", { value: true });
21 | var React = require("react");
22 | var invisible = { opacity: 0, height: 0 };
23 | var memoizeCache = {};
24 | var DVL = (function (_super) {
25 | __extends(DVL, _super);
26 | function DVL(p) {
27 | var _this = _super.call(this, p) || this;
28 | _this._buffer = 5;
29 | _this._itemHeight = [];
30 | _this._itemRows = [];
31 | _this._counter = 0;
32 | _this._progressCounter = 0;
33 | _this._reflowLayout = _this._reflowLayout.bind(_this);
34 | _this._debounceResize = _this._debounceResize.bind(_this);
35 | _this._calcVisible = _this._calcVisible.bind(_this);
36 | _this._doReflow = _this._doReflow.bind(_this);
37 | _this._scheduleVisibleUpdate = _this._scheduleVisibleUpdate.bind(_this);
38 | _this._rowCache = [];
39 | _this._firstRender = 0;
40 | _this._hasWin = typeof window !== "undefined";
41 | _this.state = {
42 | _loading: false,
43 | _progress: 0,
44 | _scrollHeight: 0,
45 | _topSpacer: 0,
46 | _renderRange: [],
47 | _columns: 0,
48 | _renderItems: [],
49 | _ref: null
50 | };
51 | return _this;
52 | }
53 | DVL.prototype.componentWillMount = function () {
54 | this._buffer = this.props.buffer !== undefined ? this.props.buffer : 5;
55 | this._useWindow = this.props.windowContainer;
56 | if (this.props.doUpdate) {
57 | this.props.doUpdate(this._calcVisible);
58 | }
59 | if (this._hasWin) {
60 | window.addEventListener("resize", this._debounceResize);
61 | }
62 | };
63 | DVL.prototype.componentDidUpdate = function (prevProps, prevState, snapshot) {
64 | if (prevProps.items !== this.props.items) {
65 | if (this.props.cacheKey) {
66 | memoizeCache[String(this.props.cacheKey)] = {};
67 | }
68 | this._reflowLayout();
69 | }
70 | };
71 | DVL.prototype.componentWillUnmount = function () {
72 | if (this._hasWin) {
73 | window.removeEventListener("resize", this._debounceResize);
74 | }
75 | if (this._scrollContainer) {
76 | this._scrollContainer.removeEventListener("scroll", this._scheduleVisibleUpdate);
77 | }
78 | };
79 | DVL.prototype._debounceResize = function () {
80 | var _this = this;
81 | if (this._doResize) {
82 | clearTimeout(this._doResize);
83 | }
84 | this._doResize = setTimeout(function () {
85 | if (_this.props.cacheKey) {
86 | memoizeCache[String(_this.props.cacheKey)] = {};
87 | }
88 | _this._reflowLayout();
89 | }, 250);
90 | };
91 | DVL.prototype._doReflow = function () {
92 | var _this = this;
93 | if (this.props.cacheKey && memoizeCache[String(this.props.cacheKey)]) {
94 | if (memoizeCache[String(this.props.cacheKey)][window.innerWidth]) {
95 | this._itemRows = memoizeCache[String(this.props.cacheKey)][window.innerWidth].rows;
96 | this._itemHeight = memoizeCache[String(this.props.cacheKey)][window.innerWidth].items;
97 | this.setState({
98 | _scrollHeight: memoizeCache[String(this.props.cacheKey)][window.innerWidth].height
99 | }, function () {
100 | _this._calcVisible();
101 | });
102 | return;
103 | }
104 | }
105 | this._progressCounter = 0;
106 | this._itemHeight = [];
107 | this._itemRows = [];
108 | setTimeout(function () {
109 | _this.setState({ _loading: true }, function () {
110 | var calcHeight = _this.props.calculateHeight;
111 | if (calcHeight !== undefined) {
112 | _this.props.items.forEach(function (item, i) {
113 | if (typeof calcHeight === "number") {
114 | _this._itemHeight[i] = calcHeight;
115 | }
116 | else {
117 | _this._itemHeight[i] = calcHeight(_this.state._ref, item, i);
118 | }
119 | });
120 | _this._reflowComplete(true);
121 | }
122 | });
123 | }, 0);
124 | };
125 | DVL.prototype._reflowLayout = function () {
126 | this.props.onResizeStart ? this.props.onResizeStart(this._doReflow) : this._doReflow();
127 | };
128 | DVL.prototype._reflowComplete = function (doFinalPass) {
129 | var _this = this;
130 | var maxHeight = 0;
131 | var columns = Math.floor(this.state._ref.clientWidth / (this.props.gridItemWidth || 100));
132 | var rowHeights = [];
133 | var rowCounter = 0;
134 | this._rowCache = [];
135 | var progress = this.state._progress;
136 | var fixedHeight = typeof this.props.calculateHeight === "number";
137 | if (fixedHeight) {
138 | maxHeight = this.props.calculateHeight;
139 | }
140 | var scrollHeight = this._itemHeight.reduce(function (p, c, i) {
141 | if (!doFinalPass && progress && i > progress - 1)
142 | return p;
143 | if (_this.props.gridItemWidth) {
144 | _this._rowCache[i] = rowCounter;
145 | if (!fixedHeight) {
146 | if (i % columns === 0) {
147 | maxHeight = 0;
148 | }
149 | maxHeight = Math.max(maxHeight, _this._itemHeight[i]);
150 | }
151 | if (i === _this._itemHeight.length - 1) {
152 | rowHeights[rowCounter] = maxHeight;
153 | return p + maxHeight;
154 | }
155 | if (i % columns === (columns - 1)) {
156 | rowHeights[rowCounter] = maxHeight;
157 | rowCounter++;
158 | return p + maxHeight;
159 | }
160 | return p;
161 | }
162 | else {
163 | return p + c;
164 | }
165 | }, 0);
166 | if (this.props.gridItemWidth) {
167 | this._itemRows = rowHeights;
168 | }
169 | else {
170 | this._itemRows = this._itemHeight;
171 | }
172 | if (doFinalPass) {
173 | if (this.props.cacheKey) {
174 | if (!memoizeCache[String(this.props.cacheKey)]) {
175 | memoizeCache[String(this.props.cacheKey)] = {};
176 | }
177 | memoizeCache[String(this.props.cacheKey)][window.innerWidth] = {
178 | rows: this._itemRows,
179 | items: this._itemHeight,
180 | height: scrollHeight
181 | };
182 | }
183 | this.setState({
184 | _loading: false,
185 | _columns: columns,
186 | _progress: 0
187 | }, function () {
188 | _this.setState({ _scrollHeight: scrollHeight }, function () {
189 | _this._scheduleVisibleUpdate();
190 | });
191 | _this.props.onResizeFinish ? _this.props.onResizeFinish(scrollHeight, columns, _this._itemHeight) : null;
192 | });
193 | }
194 | else {
195 | var avg = Math.round(scrollHeight / progress);
196 | var remainingHight = ((this.props.items.length - progress) * avg);
197 | this.setState({
198 | _scrollHeight: scrollHeight + remainingHight,
199 | _columns: columns
200 | }, function () {
201 | _this._scheduleVisibleUpdate();
202 | });
203 | }
204 | };
205 | DVL.prototype._nextFrame = function (cb) {
206 | if (this._hasWin) {
207 | window.requestAnimationFrame(function () {
208 | cb();
209 | });
210 | }
211 | else {
212 | setTimeout(function () {
213 | cb();
214 | }, 16);
215 | }
216 | };
217 | DVL.prototype._scheduleVisibleUpdate = function () {
218 | if (!this._ticking) {
219 | this._ticking = true;
220 | this._nextFrame(this._calcVisible);
221 | }
222 | };
223 | DVL.prototype._calcVisible = function (scrollTopIn, heightIn) {
224 | var _this = this;
225 | var height = heightIn || this.state._ref.clientHeight;
226 | var topHeight = 0;
227 | var scrollTop = scrollTopIn || this.state._ref.scrollTop;
228 | var top = 0;
229 | if (this._useWindow && this._hasWin) {
230 | var relTop = this.state._ref.getBoundingClientRect().top;
231 | var doc = document.documentElement;
232 | scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
233 | var containerDistanceFromTopOfDoc = relTop + scrollTop;
234 | height = window.innerHeight;
235 | scrollTop -= containerDistanceFromTopOfDoc;
236 | if (scrollTop < 0 && scrollTop < height * -1) {
237 | this._ticking = false;
238 | return;
239 | }
240 | }
241 | var renderRange = [];
242 | var i = 0;
243 | while (i < this._itemRows.length) {
244 | var start = renderRange[0] !== undefined;
245 | var end = renderRange[1] !== undefined;
246 | if (!start || !end) {
247 | if (!start && (top + this._itemRows[i]) >= scrollTop) {
248 | renderRange[0] = Math.max(0, i - this._buffer);
249 | topHeight = top;
250 | if (renderRange[0] !== i) {
251 | var goUp = 1;
252 | var diff = (i - renderRange[0]);
253 | while (diff > 0 && goUp <= diff) {
254 | topHeight -= this._itemRows[i - goUp];
255 | goUp++;
256 | }
257 | }
258 | }
259 | else if (!end && start && top > scrollTop + height) {
260 | renderRange[1] = Math.min(i + this._buffer, this._itemRows.length);
261 | }
262 | top += this._itemRows[i];
263 | i++;
264 | }
265 | else {
266 | i = this._itemRows.length;
267 | }
268 | }
269 | if (renderRange[1] === undefined) {
270 | renderRange[1] = this._itemRows.length;
271 | }
272 | this._ticking = false;
273 | this.setState({
274 | _renderRange: renderRange,
275 | _topSpacer: topHeight,
276 | _renderItems: (function () {
277 | if (_this.props.calculateHeight !== undefined) {
278 | var ranges = _this.props.gridItemWidth ? renderRange.map(function (r) { return r * _this.state._columns; }) : renderRange;
279 | return _this.props.items.slice.apply(_this.props.items, ranges);
280 | }
281 | return _this.props.items.filter(function (v, i) {
282 | if (_this.state._progress && i > _this.state._progress - 1)
283 | return false;
284 | if (_this.props.gridItemWidth) {
285 | return _this._rowCache[i] >= renderRange[0] && _this._rowCache[i] <= renderRange[1];
286 | }
287 | else {
288 | return i >= renderRange[0] && i <= renderRange[1];
289 | }
290 | });
291 | })()
292 | });
293 | };
294 | DVL.prototype._addEventListener = function () {
295 | if (this.state._ref && !this.props.doUpdate && this._hasWin) {
296 | if (this._useWindow) {
297 | this._scrollContainer = window;
298 | }
299 | else {
300 | this._scrollContainer = this.state._ref;
301 | }
302 | this._scrollContainer.addEventListener("scroll", this._scheduleVisibleUpdate);
303 | }
304 | this._reflowLayout();
305 | };
306 | DVL.prototype.render = function () {
307 | var _this = this;
308 | var low = this.state._progress;
309 | var high = this.state._progress + 100;
310 | var startIdx = this.props.gridItemWidth ? this.state._renderRange[0] * this.state._columns : this.state._renderRange[0];
311 | if (typeof window === "undefined") {
312 | return (React.createElement("div", { className: this.props.containerClass, style: __assign({ marginBottom: "10px" }, this.props.containerStyle) },
313 | React.createElement("div", { className: this.props.innerContainerClass || "", style: this.props.innerContainerStyle || {} }, this.props.items.map(function (e, j) { return _this.props.onRender(e, j, 0); }))));
314 | }
315 | return (React.createElement("div", { className: this.props.containerClass, style: __assign({ marginBottom: "10px", boxSizing: "content-box", height: !this.state._ref && this.state._scrollHeight ? this.state._scrollHeight : "" }, this.props.containerStyle), ref: function (ref) {
316 | if (ref && ref !== _this.state._ref) {
317 | _this.setState({ _ref: ref }, function () {
318 | if (_this._hasWin && window.getComputedStyle(ref).overflow !== "scroll" && window.getComputedStyle(ref).overflowY !== "scroll") {
319 | _this._useWindow = true;
320 | }
321 | _this._addEventListener();
322 | _this.props.containerRef ? _this.props.containerRef(ref) : null;
323 | });
324 | }
325 | } },
326 | this.state._ref ? React.createElement("div", { className: this.props.innerContainerClass || "", style: __assign({ height: this.state._scrollHeight > 0 ? this.state._scrollHeight - this.state._topSpacer : "unset", paddingTop: this.state._topSpacer }, this.props.innerContainerStyle) }, (!this.state._loading || this.state._progress) ? this.state._renderItems.map(function (item, i) { return _this.props.onRender(item, startIdx + i, _this.state._columns); }) : null) : null,
327 | this.state._loading && this.props.calculateHeight === undefined && this.props.items && this.props.items.length ? React.createElement("div", { style: invisible }, this.props.items.filter(function (v, i) { return i >= low && i < high; }).map(function (e, j) {
328 | return _this._itemHeight[(low + j)] ? null : React.createElement("div", { key: j, ref: function (ref) {
329 | if (ref && !_this._itemHeight[(low + j)]) {
330 | _this._itemHeight[(low + j)] = ref.clientHeight;
331 | _this._progressCounter++;
332 | if (_this._progressCounter === _this.props.items.length) {
333 | _this._nextFrame(function () {
334 | _this._reflowComplete(true);
335 | });
336 | }
337 | else if (_this._progressCounter > 0 && _this._progressCounter % 100 === 0) {
338 | _this._nextFrame(function () {
339 | _this.setState({ _progress: _this._progressCounter }, function () {
340 | _this._reflowComplete(false);
341 | });
342 | });
343 | }
344 | }
345 | } }, _this.props.onRender(e, low + j, 0));
346 | })) : null));
347 | };
348 | return DVL;
349 | }(React.PureComponent));
350 | exports.DVL = DVL;
351 |
--------------------------------------------------------------------------------
/package.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "react-dynamic-virtual-list",
3 | "version": "1.7.0",
4 | "description": "React virtual list component that supports elements of any size.",
5 | "main": "index.js",
6 | "typings": "index.d.ts",
7 | "scripts": {
8 | "build": "rm -rf index.js index.d.ts && tsc && mv source.js index.js && mv source.d.ts index.d.ts && webpack"
9 | },
10 | "repository": {
11 | "type": "git",
12 | "url": "git+https://github.com/ClickSimply/react-dynamic-virtual-list.git"
13 | },
14 | "author": "",
15 | "license": "MIT",
16 | "keywords": [
17 | "react",
18 | "reactjs",
19 | "react-component",
20 | "virtual",
21 | "list",
22 | "scrolling",
23 | "infinite",
24 | "virtualized",
25 | "virtualization",
26 | "windowing",
27 | "table",
28 | "fixed",
29 | "header",
30 | "flex",
31 | "flexbox",
32 | "grid",
33 | "spreadsheet"
34 | ],
35 | "bugs": {
36 | "url": "https://github.com/ClickSimply/react-dynamic-virtual-list/issues"
37 | },
38 | "homepage": "https://github.com/ClickSimply/react-dynamic-virtual-list#readme",
39 | "devDependencies": {
40 | "@types/react": "^16.3.8",
41 | "typescript": "^2.8.1",
42 | "uglifyjs-webpack-plugin": "^1.2.4",
43 | "webpack": "^4.5.0",
44 | "webpack-cli": "^2.0.14"
45 | },
46 | "peerDependencies": {
47 | "react": "^16.3.1"
48 | }
49 | }
50 |
--------------------------------------------------------------------------------
/source.tsx:
--------------------------------------------------------------------------------
1 | import * as React from "react";
2 |
3 | const invisible = { opacity: 0, height: 0 };
4 |
5 | const memoizeCache: {[key: string]: {
6 | [width: number]: {rows: number[], items: number[], height: number};
7 | }} = {};
8 |
9 | export class DVL extends React.PureComponent<{
10 | onRender: (item: any, index: number, columns?: number) => JSX.Element;
11 | items: any[];
12 | calculateHeight?: (container: HTMLDivElement, item: any, index: number) => number | number;
13 | windowContainer?: boolean;
14 | buffer?: number;
15 | containerRef?: (ref: HTMLDivElement) => void;
16 | containerStyle?: React.CSSProperties;
17 | containerClass?: string;
18 | innerContainerClass?: string;
19 | innerContainerStyle?: React.CSSProperties;
20 | cacheKey: string|number;
21 | doUpdate?: (calcVisible: (scrollTop?: number, containerHeight?: number) => void) => void;
22 | gridItemWidth?: number;
23 | onResizeStart?: (doResize: () => void) => void;
24 | onResizeFinish?: (scrollHeight: number, columns: number, heights: number[]) => void;
25 | }, {
26 | _loading: boolean;
27 | _scrollHeight: number;
28 | _topSpacer: number;
29 | _renderRange: number[];
30 | _columns: number;
31 | _progress: number;
32 | _renderItems: any[];
33 | _ref: HTMLDivElement;
34 | }> {
35 |
36 | private _buffer = 5;
37 | private _itemHeight: number[] = [];
38 | private _itemRows: number[] = [];
39 | private _doResize: number;
40 | private _hasWin: boolean;
41 | private _scrollDone: number;
42 | private _ticking: boolean;
43 | private _rowCache: number[];
44 | private _counter: number = 0;
45 | private _firstRender: number;
46 | private _calcTimer: number;
47 | private _scrollContainer: any;
48 | private _oldScroll: number;
49 | private _progressCounter: number = 0;
50 | private _useWindow: boolean;
51 |
52 | constructor(p) {
53 | super(p);
54 | this._reflowLayout = this._reflowLayout.bind(this);
55 | this._debounceResize = this._debounceResize.bind(this);
56 | this._calcVisible = this._calcVisible.bind(this);
57 | this._doReflow = this._doReflow.bind(this);
58 | this._scheduleVisibleUpdate = this._scheduleVisibleUpdate.bind(this);
59 | this._rowCache = [];
60 | this._firstRender = 0;
61 |
62 | this._hasWin = typeof window !== "undefined";
63 | this.state = {
64 | _loading: false,
65 | _progress: 0,
66 | _scrollHeight: 0,
67 | _topSpacer: 0,
68 | _renderRange: [],
69 | _columns: 0,
70 | _renderItems: [],
71 | _ref: null
72 | };
73 | }
74 |
75 | public componentWillMount(): void {
76 |
77 | this._buffer = this.props.buffer !== undefined ? this.props.buffer : 5;
78 |
79 | this._useWindow = this.props.windowContainer;
80 |
81 | if (this.props.doUpdate) {
82 | this.props.doUpdate(this._calcVisible);
83 | }
84 |
85 | if (this._hasWin) {
86 | window.addEventListener("resize", this._debounceResize);
87 | }
88 |
89 | }
90 |
91 | public componentDidUpdate(prevProps, prevState, snapshot) {
92 | if (prevProps.items !== this.props.items) {
93 | if (this.props.cacheKey) {
94 | memoizeCache[String(this.props.cacheKey)] = {};
95 | }
96 | this._reflowLayout();
97 | }
98 | }
99 |
100 | public componentWillUnmount() {
101 | if (this._hasWin) {
102 | window.removeEventListener("resize", this._debounceResize);
103 | }
104 | if (this._scrollContainer) {
105 | this._scrollContainer.removeEventListener("scroll", this._scheduleVisibleUpdate);
106 | }
107 | }
108 |
109 | private _debounceResize() {
110 | if (this._doResize) {
111 | clearTimeout(this._doResize);
112 | }
113 | this._doResize = setTimeout(() => {
114 | if (this.props.cacheKey) {
115 | memoizeCache[String(this.props.cacheKey)] = {};
116 | }
117 | this._reflowLayout();
118 | }, 250);
119 | }
120 |
121 | private _doReflow() {
122 |
123 | if (this.props.cacheKey && memoizeCache[String(this.props.cacheKey)]) {
124 | if (memoizeCache[String(this.props.cacheKey)][window.innerWidth]) {
125 | this._itemRows = memoizeCache[String(this.props.cacheKey)][window.innerWidth].rows;
126 | this._itemHeight = memoizeCache[String(this.props.cacheKey)][window.innerWidth].items;
127 | this.setState({
128 | _scrollHeight: memoizeCache[String(this.props.cacheKey)][window.innerWidth].height
129 | }, () => {
130 | this._calcVisible();
131 | })
132 | return;
133 | }
134 | }
135 |
136 | this._progressCounter = 0;
137 | this._itemHeight = [];
138 | this._itemRows = [];
139 | /*
140 | if (this._hasWin && !this._oldScroll && this._scrollContainer) {
141 | if (this._scrollContainer !== window) {
142 | this._oldScroll = this._scrollContainer.scrollTop;
143 | this._scrollContainer.scrollTop = 0;
144 | } else {
145 | const doc = document.documentElement;
146 | this._oldScroll = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
147 | this._scrollContainer.scrollTo(0, 0);
148 | }
149 | }
150 | */
151 | setTimeout(() => {
152 | this.setState({ _loading: true }, () => {
153 | const calcHeight = this.props.calculateHeight;
154 | if (calcHeight !== undefined) {
155 | this.props.items.forEach((item, i) => {
156 | if (typeof calcHeight === "number") {
157 | this._itemHeight[i] = calcHeight;
158 | } else {
159 | this._itemHeight[i] = calcHeight(this.state._ref, item, i);
160 | }
161 | })
162 | this._reflowComplete(true);
163 | }
164 | });
165 | }, 0);
166 |
167 | }
168 |
169 | private _reflowLayout(): void {
170 | this.props.onResizeStart ? this.props.onResizeStart(this._doReflow) : this._doReflow();
171 | }
172 |
173 | private _reflowComplete(doFinalPass: boolean) {
174 |
175 | let maxHeight = 0;
176 | const columns = Math.floor(this.state._ref.clientWidth / (this.props.gridItemWidth || 100));
177 | let rowHeights: number[] = [];
178 | let rowCounter: number = 0;
179 | this._rowCache = [];
180 | const progress = this.state._progress;
181 | const fixedHeight = typeof this.props.calculateHeight === "number";
182 | if (fixedHeight) {
183 | maxHeight = this.props.calculateHeight as any;
184 | }
185 |
186 | const scrollHeight = this._itemHeight.reduce((p, c, i) => {
187 | if (!doFinalPass && progress && i > progress - 1) return p;
188 | if (this.props.gridItemWidth) {
189 |
190 | this._rowCache[i] = rowCounter;
191 |
192 | if (!fixedHeight) {
193 | if (i % columns === 0) {
194 | maxHeight = 0;
195 | }
196 | maxHeight = Math.max(maxHeight, this._itemHeight[i]);
197 | }
198 |
199 | // very last row
200 | if (i === this._itemHeight.length - 1) {
201 | rowHeights[rowCounter] = maxHeight;
202 | return p + maxHeight;
203 | }
204 |
205 | if (i % columns === (columns - 1)) {
206 | rowHeights[rowCounter] = maxHeight;
207 | rowCounter++;
208 | return p + maxHeight;
209 | }
210 |
211 | return p;
212 | } else {
213 | return p + c;
214 | }
215 | }, 0);
216 |
217 | if (this.props.gridItemWidth) {
218 | this._itemRows = rowHeights;
219 | } else {
220 | this._itemRows = this._itemHeight;
221 | }
222 |
223 | if (doFinalPass) {
224 |
225 | if (this.props.cacheKey) {
226 | if (!memoizeCache[String(this.props.cacheKey)]) {
227 | memoizeCache[String(this.props.cacheKey)] = {};
228 | }
229 | memoizeCache[String(this.props.cacheKey)][window.innerWidth] = {
230 | rows: this._itemRows,
231 | items: this._itemHeight,
232 | height: scrollHeight
233 | }
234 | }
235 |
236 | this.setState({
237 | _loading: false,
238 | _columns: columns,
239 | _progress: 0
240 | }, () => {
241 | this.setState({ _scrollHeight: scrollHeight }, () => {
242 | this._scheduleVisibleUpdate();
243 | })
244 | this.props.onResizeFinish ? this.props.onResizeFinish(scrollHeight, columns, this._itemHeight) : null;
245 | })
246 | } else {
247 | const avg = Math.round(scrollHeight / progress);
248 | const remainingHight = ((this.props.items.length - progress) * avg);
249 | /*const items = this._itemRows.length * (this.props.gridItemWidth && columns ? columns : 1);
250 | let remainingItems = Math.ceil((this.props.items.length - items) / (this.props.gridItemWidth && columns ? columns : 1));
251 | while(remainingItems--) {
252 | this._itemRows.push(avg);
253 | }*/
254 | this.setState({
255 | _scrollHeight: scrollHeight + remainingHight,
256 | _columns: columns
257 | }, () => {
258 | this._scheduleVisibleUpdate();
259 | })
260 | }
261 | }
262 |
263 | private _nextFrame(cb: () => void) {
264 | if (this._hasWin) {
265 | window.requestAnimationFrame(() => {
266 | cb();
267 | });
268 | } else {
269 | setTimeout(() => {
270 | cb();
271 | }, 16);
272 | }
273 | }
274 |
275 | private _scheduleVisibleUpdate() {
276 | if (!this._ticking) {
277 | this._ticking = true;
278 | this._nextFrame(this._calcVisible);
279 | }
280 | }
281 |
282 | private _calcVisible(scrollTopIn?: number, heightIn?: number) {
283 |
284 | let height = heightIn || this.state._ref.clientHeight;
285 | /*
286 | if (this._oldScroll && this._hasWin) {
287 | if (this._scrollContainer !== window) {
288 | this._scrollContainer.scrollTop = Math.min(this._oldScroll, this.state._scrollHeight - height);
289 | } else {
290 | this._scrollContainer.scrollTo(0, Math.min(this._oldScroll, this.state._scrollHeight));
291 | }
292 | this._oldScroll = undefined;
293 | }
294 | */
295 | let topHeight = 0;
296 | let scrollTop = scrollTopIn || this.state._ref.scrollTop;
297 |
298 | let top = 0;
299 | if (this._useWindow && this._hasWin) {
300 | let relTop = this.state._ref.getBoundingClientRect().top;
301 | const doc = document.documentElement;
302 | scrollTop = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
303 | const containerDistanceFromTopOfDoc = relTop + scrollTop;
304 | height = window.innerHeight;
305 |
306 | scrollTop -= containerDistanceFromTopOfDoc;
307 |
308 | // element is below visible window area
309 | if (scrollTop < 0 && scrollTop < height * -1) {
310 | this._ticking = false;
311 | return;
312 | }
313 | }
314 |
315 | let renderRange: number[] = [];
316 | let i = 0;
317 | while (i < this._itemRows.length) {
318 |
319 | const start = renderRange[0] !== undefined;
320 | const end = renderRange[1] !== undefined;
321 | if (!start || !end) {
322 | if (!start && (top + this._itemRows[i]) >= scrollTop) {
323 | renderRange[0] = Math.max(0, i - this._buffer);
324 | topHeight = top;
325 | if (renderRange[0] !== i) {
326 | let goUp = 1;
327 | const diff = (i - renderRange[0]);
328 | while (diff > 0 && goUp <= diff) {
329 | topHeight -= this._itemRows[i - goUp];
330 | goUp++;
331 | }
332 | }
333 |
334 | } else if (!end && start && top > scrollTop + height) {
335 | renderRange[1] = Math.min(i + this._buffer, this._itemRows.length);
336 | }
337 | top += this._itemRows[i];
338 | i++;
339 | } else {
340 | i = this._itemRows.length;
341 | }
342 | }
343 |
344 | if (renderRange[1] === undefined) {
345 | renderRange[1] = this._itemRows.length;
346 | }
347 |
348 | this._ticking = false;
349 |
350 | // if (this.state._renderRange[0] !== renderRange[0] || this.state._renderRange[1] !== renderRange[1] || topHeight !== this.state._topSpacer) {
351 | this.setState({
352 | _renderRange: renderRange,
353 | _topSpacer: topHeight,
354 | _renderItems: (() => {
355 |
356 | if (this.props.calculateHeight !== undefined) {
357 | const ranges = this.props.gridItemWidth ? renderRange.map(r => r * this.state._columns) : renderRange;
358 | return this.props.items.slice.apply(this.props.items, ranges);
359 | }
360 |
361 | return this.props.items.filter((v, i) => {
362 | if (this.state._progress && i > this.state._progress - 1) return false;
363 | if (this.props.gridItemWidth) {
364 | return this._rowCache[i] >= renderRange[0] && this._rowCache[i] <= renderRange[1];
365 | } else {
366 | return i >= renderRange[0] && i <= renderRange[1];
367 | }
368 | });
369 | })()
370 | });
371 | // }
372 | }
373 |
374 | private _addEventListener(): void {
375 |
376 | if (this.state._ref && !this.props.doUpdate && this._hasWin) {
377 | if (this._useWindow) {
378 | this._scrollContainer = window;
379 | } else {
380 | this._scrollContainer = this.state._ref;
381 | }
382 | this._scrollContainer.addEventListener("scroll", this._scheduleVisibleUpdate);
383 | }
384 | this._reflowLayout();
385 | }
386 |
387 | public render() {
388 |
389 | const low = this.state._progress;
390 | const high = this.state._progress + 100;
391 | const startIdx = this.props.gridItemWidth ? this.state._renderRange[0] * this.state._columns : this.state._renderRange[0];
392 |
393 | // SSR
394 | if (typeof window === "undefined") {
395 | return (
396 |
400 |
401 | {this.props.items.map((e, j) => this.props.onRender(e, j, 0))}
402 |
403 |
404 | );
405 | }
406 |
407 | return (
408 | {
414 | if (ref && ref !== this.state._ref) {
415 | this.setState({ _ref: ref }, () => {
416 | if (this._hasWin && window.getComputedStyle(ref).overflow !== "scroll" && window.getComputedStyle(ref).overflowY !== "scroll") {
417 | this._useWindow = true;
418 | }
419 | this._addEventListener();
420 | this.props.containerRef ? this.props.containerRef(ref) : null;
421 | })
422 | }
423 | }}>
424 | {this.state._ref ?
0 ? this.state._scrollHeight - this.state._topSpacer : "unset",
426 | paddingTop: this.state._topSpacer,
427 | ...this.props.innerContainerStyle
428 | }}>
429 | {(!this.state._loading || this.state._progress) ? this.state._renderItems.map((item, i) => this.props.onRender(item, startIdx + i, this.state._columns)) : null}
430 |
: null}
431 | {this.state._loading && this.props.calculateHeight === undefined && this.props.items && this.props.items.length ?
432 | {this.props.items.filter((v, i) => i >= low && i < high).map((e, j) => {
433 | return this._itemHeight[(low + j)] ? null :
{
434 | if (ref && !this._itemHeight[(low + j)]) {
435 | this._itemHeight[(low + j)] = ref.clientHeight;
436 | this._progressCounter++;
437 | if (this._progressCounter === this.props.items.length) {
438 | this._nextFrame(() => {
439 | this._reflowComplete(true);
440 | });
441 | } else if (this._progressCounter > 0 && this._progressCounter % 100 === 0) {
442 | this._nextFrame(() => {
443 | this.setState({ _progress: this._progressCounter }, () => {
444 | this._reflowComplete(false);
445 | });
446 | });
447 | }
448 | }
449 | }}>{this.props.onRender(e, low + j, 0)}
;
450 | })}
451 |
: null}
452 |
453 | )
454 | }
455 | }
--------------------------------------------------------------------------------
/tsconfig.json:
--------------------------------------------------------------------------------
1 | {
2 | "compilerOptions": {
3 | "target": "es5",
4 | "module": "commonjs",
5 | "moduleResolution": "node",
6 | "stripInternal": true,
7 | "removeComments": true,
8 | "declaration": true,
9 | "declarationDir": "./",
10 | "jsx": "react"
11 | },
12 | "files": [
13 | "./source.tsx"
14 | ],
15 | "include": []
16 | }
--------------------------------------------------------------------------------
/webpack.config.js:
--------------------------------------------------------------------------------
1 | const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
2 |
3 | module.exports = {
4 | entry: './index.js',
5 | output: {
6 | filename: 'react-dvl.min.js',
7 | libraryTarget: 'umd',
8 | umdNamedDefine: true
9 | },
10 | externals: ["react"],
11 | plugins: [
12 | new UglifyJSPlugin({
13 | uglifyOptions: {
14 | mangle: {
15 | properties: { regex: new RegExp(/^_/) }
16 | }
17 | }
18 | })
19 | ],
20 | };
--------------------------------------------------------------------------------