virtual-scroller 1.13.1 → 1.15.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +825 -578
- package/bundle/index-dom-bypass.html +198 -0
- package/bundle/index-dom-grid.html +204 -0
- package/bundle/index-dom-scrollableContainer.html +215 -0
- package/bundle/index-dom-tbody-scrollableContainer.html +81 -0
- package/bundle/index-dom-tbody.html +65 -0
- package/bundle/index-dom.html +116 -83
- package/bundle/{index-bypass.html → index-react-bypass.html} +83 -78
- package/bundle/{index-grid.html → index-react-grid.html} +78 -91
- package/bundle/{index-scrollableContainer.html → index-react-scrollableContainer.html} +96 -91
- package/bundle/index-react-strictMode.html +199 -0
- package/bundle/index-react-tbody-scrollableContainer.html +96 -0
- package/bundle/index-react-tbody.html +80 -0
- package/bundle/{messages.js → items.js} +1 -1
- package/bundle/lib/babel.min.js +25 -0
- package/bundle/lib/prop-types.min.js +1 -0
- package/bundle/lib/react-dom.development.js +29924 -0
- package/bundle/lib/react-dom.production.min.js +267 -0
- package/bundle/lib/react.development.js +3343 -0
- package/bundle/lib/react.production.min.js +31 -0
- package/bundle/style.base.css +33 -0
- package/{website/style.css → bundle/style.list.css} +10 -43
- package/bundle/style.list.grid.css +23 -0
- package/bundle/virtual-scroller-dom.js +1 -1
- package/bundle/virtual-scroller-dom.js.map +1 -1
- package/bundle/virtual-scroller-react.js +1 -1
- package/bundle/virtual-scroller-react.js.map +1 -1
- package/bundle/virtual-scroller.js +1 -1
- package/bundle/virtual-scroller.js.map +1 -1
- package/commonjs/BeforeResize.js +1 -2
- package/commonjs/BeforeResize.js.map +1 -1
- package/commonjs/DOM/VirtualScroller.js +67 -44
- package/commonjs/DOM/VirtualScroller.js.map +1 -1
- package/commonjs/DOM/tbody.js +15 -15
- package/commonjs/DOM/tbody.js.map +1 -1
- package/commonjs/ItemHeights.js +10 -13
- package/commonjs/ItemHeights.js.map +1 -1
- package/commonjs/Layout.defaults.js +21 -0
- package/commonjs/Layout.defaults.js.map +1 -0
- package/commonjs/Layout.js +78 -67
- package/commonjs/Layout.js.map +1 -1
- package/commonjs/Layout.test.js +8 -4
- package/commonjs/Layout.test.js.map +1 -1
- package/commonjs/Scroll.js +3 -3
- package/commonjs/Scroll.js.map +1 -1
- package/commonjs/ScrollableContainerResizeHandler.js +4 -5
- package/commonjs/ScrollableContainerResizeHandler.js.map +1 -1
- package/commonjs/VirtualScroller.constructor.js +53 -31
- package/commonjs/VirtualScroller.constructor.js.map +1 -1
- package/commonjs/VirtualScroller.items.js +50 -4
- package/commonjs/VirtualScroller.items.js.map +1 -1
- package/commonjs/VirtualScroller.js +44 -28
- package/commonjs/VirtualScroller.js.map +1 -1
- package/commonjs/VirtualScroller.layout.js +42 -31
- package/commonjs/VirtualScroller.layout.js.map +1 -1
- package/commonjs/VirtualScroller.onContainerResize.js +1 -2
- package/commonjs/VirtualScroller.onContainerResize.js.map +1 -1
- package/commonjs/VirtualScroller.onRender.js +1 -1
- package/commonjs/VirtualScroller.onRender.js.map +1 -1
- package/commonjs/VirtualScroller.state.js +18 -9
- package/commonjs/VirtualScroller.state.js.map +1 -1
- package/commonjs/VirtualScroller.verticalSpacing.js +39 -6
- package/commonjs/VirtualScroller.verticalSpacing.js.map +1 -1
- package/commonjs/react/VirtualScroller.js +98 -37
- package/commonjs/react/VirtualScroller.js.map +1 -1
- package/commonjs/react/useClassName.js +2 -2
- package/commonjs/react/useClassName.js.map +1 -1
- package/commonjs/react/useForwardedRef.js +50 -0
- package/commonjs/react/useForwardedRef.js.map +1 -0
- package/commonjs/react/useInstanceMethods.js +4 -4
- package/commonjs/react/useInstanceMethods.js.map +1 -1
- package/commonjs/react/useItemKeys.js +28 -5
- package/commonjs/react/useItemKeys.js.map +1 -1
- package/commonjs/react/useOnItemHeightDidChange.js +28 -12
- package/commonjs/react/useOnItemHeightDidChange.js.map +1 -1
- package/commonjs/react/useSetItemState.js +31 -12
- package/commonjs/react/useSetItemState.js.map +1 -1
- package/commonjs/react/useState.js +10 -11
- package/commonjs/react/useState.js.map +1 -1
- package/commonjs/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +3 -3
- package/commonjs/react/useStateWithRepeatableRead.js.map +1 -0
- package/commonjs/react/useStyle.js +10 -4
- package/commonjs/react/useStyle.js.map +1 -1
- package/commonjs/react/useValidateTableBodyItemsContainer.js +24 -0
- package/commonjs/react/useValidateTableBodyItemsContainer.js.map +1 -0
- package/commonjs/react/useVirtualScroller.js +12 -14
- package/commonjs/react/useVirtualScroller.js.map +1 -1
- package/commonjs/test/ItemsContainer.js +10 -10
- package/commonjs/test/ItemsContainer.js.map +1 -1
- package/commonjs/test/VirtualScroller.js +25 -10
- package/commonjs/test/VirtualScroller.js.map +1 -1
- package/dom/index.d.ts +11 -9
- package/index.d.ts +19 -9
- package/modules/BeforeResize.js +1 -2
- package/modules/BeforeResize.js.map +1 -1
- package/modules/DOM/VirtualScroller.js +67 -44
- package/modules/DOM/VirtualScroller.js.map +1 -1
- package/modules/DOM/tbody.js +14 -13
- package/modules/DOM/tbody.js.map +1 -1
- package/modules/ItemHeights.js +11 -14
- package/modules/ItemHeights.js.map +1 -1
- package/modules/Layout.defaults.js +11 -0
- package/modules/Layout.defaults.js.map +1 -0
- package/modules/Layout.js +77 -67
- package/modules/Layout.js.map +1 -1
- package/modules/Layout.test.js +8 -4
- package/modules/Layout.test.js.map +1 -1
- package/modules/Scroll.js +3 -3
- package/modules/Scroll.js.map +1 -1
- package/modules/ScrollableContainerResizeHandler.js +4 -5
- package/modules/ScrollableContainerResizeHandler.js.map +1 -1
- package/modules/VirtualScroller.constructor.js +53 -31
- package/modules/VirtualScroller.constructor.js.map +1 -1
- package/modules/VirtualScroller.items.js +51 -5
- package/modules/VirtualScroller.items.js.map +1 -1
- package/modules/VirtualScroller.js +44 -28
- package/modules/VirtualScroller.js.map +1 -1
- package/modules/VirtualScroller.layout.js +42 -31
- package/modules/VirtualScroller.layout.js.map +1 -1
- package/modules/VirtualScroller.onContainerResize.js +1 -2
- package/modules/VirtualScroller.onContainerResize.js.map +1 -1
- package/modules/VirtualScroller.onRender.js +1 -1
- package/modules/VirtualScroller.onRender.js.map +1 -1
- package/modules/VirtualScroller.state.js +18 -9
- package/modules/VirtualScroller.state.js.map +1 -1
- package/modules/VirtualScroller.verticalSpacing.js +38 -6
- package/modules/VirtualScroller.verticalSpacing.js.map +1 -1
- package/modules/react/VirtualScroller.js +97 -38
- package/modules/react/VirtualScroller.js.map +1 -1
- package/modules/react/useClassName.js +3 -3
- package/modules/react/useClassName.js.map +1 -1
- package/modules/react/useForwardedRef.js +42 -0
- package/modules/react/useForwardedRef.js.map +1 -0
- package/modules/react/useInstanceMethods.js +4 -4
- package/modules/react/useInstanceMethods.js.map +1 -1
- package/modules/react/useItemKeys.js +28 -5
- package/modules/react/useItemKeys.js.map +1 -1
- package/modules/react/useOnItemHeightDidChange.js +28 -12
- package/modules/react/useOnItemHeightDidChange.js.map +1 -1
- package/modules/react/useSetItemState.js +31 -12
- package/modules/react/useSetItemState.js.map +1 -1
- package/modules/react/useState.js +10 -11
- package/modules/react/useState.js.map +1 -1
- package/modules/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +2 -2
- package/modules/react/useStateWithRepeatableRead.js.map +1 -0
- package/modules/react/useStyle.js +10 -4
- package/modules/react/useStyle.js.map +1 -1
- package/modules/react/useValidateTableBodyItemsContainer.js +16 -0
- package/modules/react/useValidateTableBodyItemsContainer.js.map +1 -0
- package/modules/react/useVirtualScroller.js +10 -12
- package/modules/react/useVirtualScroller.js.map +1 -1
- package/modules/test/ItemsContainer.js +10 -10
- package/modules/test/ItemsContainer.js.map +1 -1
- package/modules/test/VirtualScroller.js +25 -10
- package/modules/test/VirtualScroller.js.map +1 -1
- package/package.json +1 -1
- package/react/as.d.ts +42 -0
- package/react/index.d.ts +204 -63
- package/source/BeforeResize.js +1 -2
- package/source/DOM/VirtualScroller.js +65 -40
- package/source/DOM/tbody.js +15 -14
- package/source/ItemHeights.js +11 -12
- package/source/Layout.defaults.js +8 -0
- package/source/Layout.js +69 -56
- package/source/Layout.test.js +7 -2
- package/source/Scroll.js +3 -3
- package/source/ScrollableContainerResizeHandler.js +4 -4
- package/source/VirtualScroller.constructor.js +40 -31
- package/source/VirtualScroller.items.js +47 -2
- package/source/VirtualScroller.js +49 -27
- package/source/VirtualScroller.layout.js +43 -30
- package/source/VirtualScroller.onContainerResize.js +1 -2
- package/source/VirtualScroller.onRender.js +1 -1
- package/source/VirtualScroller.state.js +18 -11
- package/source/VirtualScroller.verticalSpacing.js +32 -6
- package/source/react/VirtualScroller.js +111 -36
- package/source/react/useClassName.js +3 -3
- package/source/react/useForwardedRef.js +39 -0
- package/source/react/useInstanceMethods.js +12 -4
- package/source/react/useItemKeys.js +22 -4
- package/source/react/useOnItemHeightDidChange.js +29 -10
- package/source/react/useSetItemState.js +32 -10
- package/source/react/useState.js +7 -8
- package/source/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +1 -1
- package/source/react/useStyle.js +3 -2
- package/source/react/useValidateTableBodyItemsContainer.js +16 -0
- package/source/react/useVirtualScroller.js +4 -6
- package/source/test/ItemsContainer.js +10 -10
- package/source/test/VirtualScroller.js +16 -10
- package/website/index-dom-bypass.html +198 -0
- package/website/index-dom-grid.html +204 -0
- package/website/index-dom-scrollableContainer.html +215 -0
- package/website/index-dom-tbody-scrollableContainer.html +81 -0
- package/website/index-dom-tbody.html +65 -0
- package/website/index-dom.html +117 -84
- package/website/index-react-bypass.html +200 -0
- package/website/{index-grid.html → index-react-grid.html} +79 -92
- package/website/index-react-scrollableContainer.html +213 -0
- package/website/index-react-strictMode.html +199 -0
- package/website/index-react-tbody-scrollableContainer.html +96 -0
- package/website/index-react-tbody.html +80 -0
- package/website/{index-bypass.html → index-react.html} +84 -70
- package/website/index.html +84 -69
- package/website/{messages.js → items.js} +1 -1
- package/website/lib/babel.min.js +25 -0
- package/website/lib/prop-types.min.js +1 -0
- package/website/lib/react-dom.development.js +29924 -0
- package/website/lib/react-dom.production.min.js +267 -0
- package/website/lib/react.development.js +3343 -0
- package/website/lib/react.production.min.js +31 -0
- package/website/style.base.css +33 -0
- package/website/style.list.css +92 -0
- package/website/style.list.grid.css +23 -0
- package/bundle/index-tbody-scrollableContainer.html +0 -70
- package/bundle/index-tbody.html +0 -57
- package/bundle/on-scroll-to-dom.js +0 -2
- package/bundle/on-scroll-to-dom.js.map +0 -1
- package/bundle/on-scroll-to-react.js +0 -2
- package/bundle/on-scroll-to-react.js.map +0 -1
- package/bundle/on-scroll-to.js +0 -2
- package/bundle/on-scroll-to.js.map +0 -1
- package/commonjs/react/useStateNoStaleBug.js.map +0 -1
- package/modules/react/useStateNoStaleBug.js.map +0 -1
- package/website/index-scrollableContainer.html +0 -208
- package/website/index-tbody-scrollableContainer.html +0 -70
- package/website/index-tbody.html +0 -57
- package/website/lib/on-scroll-to-dom.js +0 -2
- package/website/lib/on-scroll-to-dom.js.map +0 -1
- package/website/lib/on-scroll-to-react.js +0 -2
- package/website/lib/on-scroll-to-react.js.map +0 -1
package/README.md
CHANGED
|
@@ -4,68 +4,595 @@ A universal open-source implementation of Twitter's [`VirtualScroller`](https://
|
|
|
4
4
|
|
|
5
5
|
<!-- Automatically measures items as they're rendered and supports items of variable/dynamic height. -->
|
|
6
6
|
|
|
7
|
-
* For React users,
|
|
8
|
-
* For those who prefer "vanilla" DOM,
|
|
9
|
-
* For everyone else,
|
|
7
|
+
* For React users, it exports a [React](#react) component from `virtual-scroller/react`.
|
|
8
|
+
* For those who prefer "vanilla" DOM, it exports a [DOM](#dom) component from `virtual-scroller/dom`.
|
|
9
|
+
* For everyone else, it exports a ["core"](#core) component from `virtual-scroller`. The "core" component supports any type of UI "framework", or even any type of [rendering engine](#rendering-engine), not just DOM. Use it to create your own implementation for any UI "framework" or non-browser environment.
|
|
10
10
|
|
|
11
11
|
## Demo
|
|
12
12
|
|
|
13
|
-
[DOM](#dom)
|
|
13
|
+
[DOM](#dom) component
|
|
14
14
|
|
|
15
|
-
* [
|
|
16
|
-
* [
|
|
15
|
+
* [List](https://catamphetamine.gitlab.io/virtual-scroller/index-dom.html)
|
|
16
|
+
* [Paginated List](https://catamphetamine.gitlab.io/virtual-scroller/index-dom.html?pagination=✓)
|
|
17
|
+
* [List in a scrollable container](https://catamphetamine.gitlab.io/virtual-scroller/index-dom-scrollableContainer.html)
|
|
18
|
+
* [Table](https://catamphetamine.gitlab.io/virtual-scroller/index-dom-tbody.html)
|
|
19
|
+
* [Table in a scrollable container](https://catamphetamine.gitlab.io/virtual-scroller/index-dom-tbody-scrollableContainer.html)
|
|
20
|
+
* [Grid](https://catamphetamine.gitlab.io/virtual-scroller/index-dom-grid.html)
|
|
21
|
+
* [Paginated Grid](https://catamphetamine.gitlab.io/virtual-scroller/index-dom-grid.html?pagination=✓)
|
|
17
22
|
|
|
18
|
-
[React](#react)
|
|
23
|
+
[React](#react) component
|
|
19
24
|
|
|
20
|
-
* [
|
|
21
|
-
* [
|
|
25
|
+
* [List](https://catamphetamine.gitlab.io/virtual-scroller/index-react.html)
|
|
26
|
+
* [Paginated List](https://catamphetamine.gitlab.io/virtual-scroller/index-react.html?pagination=✓)
|
|
27
|
+
* [List in a scrollable container](https://catamphetamine.gitlab.io/virtual-scroller/index-react-scrollableContainer.html)
|
|
28
|
+
* [Table](https://catamphetamine.gitlab.io/virtual-scroller/index-react-tbody.html)
|
|
29
|
+
* [Table in a scrollable container](https://catamphetamine.gitlab.io/virtual-scroller/index-react-tbody-scrollableContainer.html)
|
|
30
|
+
* [Grid](https://catamphetamine.gitlab.io/virtual-scroller/index-react-grid.html)
|
|
31
|
+
* [Paginated Grid](https://catamphetamine.gitlab.io/virtual-scroller/index-react-grid.html?pagination=✓)
|
|
22
32
|
|
|
23
|
-
|
|
33
|
+
## Rationale
|
|
34
|
+
|
|
35
|
+
Rendering extremely long lists in HTML can be performance-intensive and could lead to slow page load times and wasting mobile device battery. For example, consider a "messenger" app that renders a list of a thousand comments. Depending on the user's device and the complexity of the message component, the full render cycle could be anywhere from 100 milliseconds to 1 second. That kind of a delay results in degradation of the percieved performance and could lead to the user not wanting to use the website or the application.
|
|
36
|
+
|
|
37
|
+

|
|
38
|
+
|
|
39
|
+
Twitter was experiencing the same issues and in 2017 they completely redesigned their website with responsiveness and performance in mind using the latest performance-boosting techniques available at the time. Afterwards, they wrote an [article](https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3) where they briefly mentioned this:
|
|
40
|
+
|
|
41
|
+
> On slower devices, we noticed that it could take a long time for our main navigation bar to appear to respond to taps, often leading us to tap multiple times, thinking that perhaps the first tap didn’t register.
|
|
42
|
+
It turns out that mounting and unmounting large trees of components (like timelines of Tweets) is very expensive in React.
|
|
43
|
+
Over time, we developed a new infinite scrolling component called VirtualScroller. With this new component, we know exactly what slice of Tweets are being rendered into a timeline at any given time, avoiding the need to make expensive calculations as to where we are visually.
|
|
44
|
+
|
|
45
|
+
However, Twitter didn't share the code for their `VirtualScroller` component — unlike Facebook, Twitter doesn't share much of their code. This library is an attempt to create an open-source implementation of such `VirtualScroller` component for anyone to use in their projects.
|
|
46
|
+
|
|
47
|
+
<!-- There's also an ["RFC"](https://github.com/WICG/virtual-scroller) for a native `VirtualScroller` component where they try to formulate what is a `VirtualScroller` component and how it should behave. -->
|
|
48
|
+
|
|
49
|
+
## How it works
|
|
50
|
+
|
|
51
|
+
`VirtualScroller` works by measuring each list item's height. As soon as the total height of the list items surpasses the window height, it stops the rendering because the user won't see those other items anyway. The non-rendered items are replaced with an empty space: not-visible items at the top are replaced with `padding-top` on the list element, and not-visible items at the bottom are replaced with `padding-bottom` on the list element. Then it listens to `scroll` / `resize` events and re-renders the list when the user scrolls the page or when the browser window is resized.
|
|
52
|
+
|
|
53
|
+
To observe the whole process in real time, go to the [demo](https://catamphetamine.gitlab.io/virtual-scroller) page, open Developer Tools, switch to the "Elements" tab, find `<div id="messages"/>` element, expand it and observe how it changes while scrolling the page.
|
|
54
|
+
|
|
55
|
+
## Install
|
|
56
|
+
|
|
57
|
+
```
|
|
58
|
+
npm install virtual-scroller --save
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
Alternatively, one could include it on a web page [directly](#cdn) via a `<script/>` tag.
|
|
62
|
+
|
|
63
|
+
## Use
|
|
64
|
+
|
|
65
|
+
As it has been mentioned, this package exports three different components:
|
|
66
|
+
|
|
67
|
+
* For React framework — [`virtual-scroller/react`](#react)
|
|
68
|
+
* For "vanilla" DOM — [`virtual-scroller/dom`](#dom)
|
|
69
|
+
* For any other case ("core") — [`virtual-scroller`](#core)
|
|
70
|
+
|
|
71
|
+
Below is a description of each component.
|
|
72
|
+
|
|
73
|
+
## React
|
|
74
|
+
|
|
75
|
+
`virtual-scroller/react` exports a React component — `<VirtualScroller/>` — that implements a "virtual scroller" in a [React](https://reactjs.org/) environment.
|
|
76
|
+
|
|
77
|
+
The React component is based on the ["core"](#core) component, and it requires the following properties:
|
|
78
|
+
|
|
79
|
+
* `items` — an array of items.
|
|
80
|
+
|
|
81
|
+
* `itemComponent` — a React component that renders an item.
|
|
82
|
+
|
|
83
|
+
* The `itemComponent` will receive properties:
|
|
84
|
+
* `item` — The item object (an element of the `items` array). Use it to render the item.
|
|
85
|
+
* `state` and `setState()` — Item component state management properties.
|
|
86
|
+
* Use these instead of the standard `const [state, setState] = useState()`. The reason is that the standard `useState()` will always disappear when the item component is no longer rendered when it goes off-screen whereas this "special" state will always be preserved.
|
|
87
|
+
<!-- * `state` — The item component's "state". -->
|
|
88
|
+
<!-- * Curious readers may see the description of `itemStates` property of the `state` object in the ["core"](#core) component section. -->
|
|
89
|
+
<!-- * `setState(newState)` — Sets the item component's "state". -->
|
|
90
|
+
<!-- * Curious readers may see the description of `setItemState(item, newState)` function in the ["core"](#core) component section. -->
|
|
91
|
+
* `onHeightDidChange()` — Call this function whenever the item's height changes, if it ever does. For example, if the item could be "expanded" and the user clicks that button. The reason for manually calling this function is because `<VirtualScroller/>` only bothers measuring the item's height when the items is initially rendered. After that, it just assumes that the item's height always stays the same and doesn't track it in any way. Hence, a developer is responsible for manually telling it to re-measure the item's height if it has changed for whatever reason.
|
|
92
|
+
* When calling this function, do it immediately after the item's height has changed on the screen, i.e. do it in `useLayoutEffect()` hook.
|
|
93
|
+
|
|
94
|
+
* As an optional performance optimization, it is advised to wrap the `itemComponent` with a [`React.memo()`](https://react.dev/reference/react/memo) function. It will prevent needless re-renders of the component when its props haven't changed (and they never do). The rationale is that all visible items get frequently re-rendered during scroll.
|
|
95
|
+
|
|
96
|
+
* `itemComponentProps: object` — (optional) any additional props for the `itemComponent`.
|
|
97
|
+
|
|
98
|
+
* `itemsContainerComponent` — a React component that will be used as a container for the items.
|
|
99
|
+
* Must be either a simple string like `"div"` or a React component that "forwards" `ref` to the resulting `Element`.
|
|
100
|
+
* Edge case: when list items are rendered as `<tr/>`s and the items container is a `<tbody/>`, the `itemsContainerComponent` must be `"tbody"`, otherwise it won't work correctly.
|
|
101
|
+
|
|
102
|
+
* `itemsContainerComponentProps: object` — (optional) any additional props for the `itemsContainerComponent`.
|
|
103
|
+
|
|
104
|
+
Code example:
|
|
105
|
+
|
|
106
|
+
#####
|
|
107
|
+
|
|
108
|
+
```js
|
|
109
|
+
import React from 'react'
|
|
110
|
+
import VirtualScroller from 'virtual-scroller/react'
|
|
111
|
+
|
|
112
|
+
function List({ items }) {
|
|
113
|
+
return (
|
|
114
|
+
<VirtualScroller
|
|
115
|
+
items={items}
|
|
116
|
+
itemComponent={ListItem}
|
|
117
|
+
itemsContainerComponent="div"
|
|
118
|
+
/>
|
|
119
|
+
)
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function ListItem({ item }) {
|
|
123
|
+
const { username, date, text } = item
|
|
124
|
+
return (
|
|
125
|
+
<article>
|
|
126
|
+
<a href={`/users/${username}`}>
|
|
127
|
+
@{username}
|
|
128
|
+
</a>
|
|
129
|
+
<time dateTime={date.toISOString()}>
|
|
130
|
+
{date.toString()}
|
|
131
|
+
</time>
|
|
132
|
+
<p>
|
|
133
|
+
{text}
|
|
134
|
+
</p>
|
|
135
|
+
</article>
|
|
136
|
+
)
|
|
137
|
+
}
|
|
138
|
+
```
|
|
139
|
+
|
|
140
|
+
<!--
|
|
141
|
+
import PropTypes from 'prop-types'
|
|
142
|
+
|
|
143
|
+
const item = PropTypes.shape({
|
|
144
|
+
username: PropTypes.string.isRequired,
|
|
145
|
+
date: PropTypes.instanceOf(Date).isRequired,
|
|
146
|
+
text: PropTypes.string.isRequired
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
List.propTypes = {
|
|
150
|
+
items: PropTypes.arrayOf(item).isRequired
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
ListItem.propTypes = {
|
|
154
|
+
item: item.isRequired
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
function App() {
|
|
158
|
+
return (
|
|
159
|
+
<List items=[{
|
|
160
|
+
username: 'barackobama',
|
|
161
|
+
date: new Date(),
|
|
162
|
+
text: 'Hey hey people'
|
|
163
|
+
}]/>
|
|
164
|
+
)
|
|
165
|
+
}
|
|
166
|
+
-->
|
|
167
|
+
|
|
168
|
+
<details>
|
|
169
|
+
<summary>Available options (properties)</summary>
|
|
170
|
+
|
|
171
|
+
#####
|
|
172
|
+
|
|
173
|
+
<!-- Note: When passing any core `VirtualScroller` class options, only the initial values of those options will be applied, and any updates to those options will be ignored. That's because those options are only passed to the `VirtualScroller` base class constructor at initialization time. That means that none of those options should depend on any variable state or props. For example, if `getColumnsCount()` parameter was defined as `() => props.columnsCount`, then, if the `columnsCount` property changes, the underlying `VirtualScroller` instance won't see that change. -->
|
|
174
|
+
|
|
175
|
+
* `getColumnsCount(): number` — Returns the count of the columns.
|
|
176
|
+
* This is simply a proxy for the ["core"](#core) component's `getColumnsCount` [option](#options).
|
|
177
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
178
|
+
|
|
179
|
+
* `getInitialItemState(item): any?` — If you're using `state`/`setState()` properties, this function could be used to define the initial `state` for every item in the list. By default, the initial state of an item is `undefined`.
|
|
180
|
+
* This is simply a proxy for the ["core"](#core) component's `getInitialItemState` [option](#options).
|
|
181
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
182
|
+
|
|
183
|
+
* `initialState: object` — The initial state of the entire list, including the initial state of each item. For example, one could snapshot this state right before the list is unmounted and then pass it back in the form of the `initialState` property when the list is re-mounted, effectively preserving the list's state. This could be used, for example, to instantly restore the list and its scroll position when the user navigates "Back" to the list's page in a web browser. P.S. In that specific case of using `initialState` property for "Back" restoration, a developer might need to pass `readyToStart: false` property until the "Back" page's scroll position has been restored.
|
|
184
|
+
* This is simply a proxy for the ["core"](#core) component's `state` [option](#options).
|
|
185
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
186
|
+
|
|
187
|
+
<!-- * `initialCustomState: object` — (advanced) The initial "custom" state for `VirtualScroller`: the `initialCustomState` option of `VirtualScroller`. It can be used to initialize the "custom" part of `VirtualScroller` state in cases when `VirtualScroller` state is used to store some "custom" list state. -->
|
|
188
|
+
|
|
189
|
+
* `onStateChange(newState: object, previousState: object?)` — When this function is passed, it will be called every time the list's state is changed. Use it together with `initialState` property to preserve the list's state while it is unmounted.
|
|
190
|
+
* This is simply a proxy for the ["core"](#core) component's `onStateChange` [option](#options).
|
|
191
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
192
|
+
|
|
193
|
+
Example of using `initialState`/`onStateChange()`:
|
|
194
|
+
|
|
195
|
+
```js
|
|
196
|
+
function ListWithPreservedState() {
|
|
197
|
+
const listState = useRef()
|
|
198
|
+
|
|
199
|
+
const onListStateChange = useCallback(
|
|
200
|
+
(state) => {
|
|
201
|
+
listState.current = state
|
|
202
|
+
},
|
|
203
|
+
[]
|
|
204
|
+
)
|
|
205
|
+
|
|
206
|
+
useEffect(() => {
|
|
207
|
+
return () => {
|
|
208
|
+
saveListState(listState.current)
|
|
209
|
+
}
|
|
210
|
+
}, [])
|
|
211
|
+
|
|
212
|
+
return (
|
|
213
|
+
<VirtualScroller
|
|
214
|
+
{...}
|
|
215
|
+
initialState={hasUserNavigatedBackToThisPage ? getSavedListState() : undefined}
|
|
216
|
+
onStateChange={onListStateChange}
|
|
217
|
+
/>
|
|
218
|
+
)
|
|
219
|
+
}
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
* `getItemId(item): number | string`
|
|
223
|
+
* This is simply a proxy for the ["core"](#core) component's `getItemId` [option](#options).
|
|
224
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
225
|
+
* `<VirtualScroller/>` also uses it to create a React `key` for every item's element. When `getItemId()` property is not passed, an item element's `key` will consist of the item's index in the `items` array plus a random-generated prefix that changes every time when `items` property value changes. This means that when the application frequently changes the `items` property, a developer could optimize it a little bit by supplying a custom `getItemId()` function whose result doesn't change when new `items` are supplied, preventing `<VirtualScroller/>` from needlessly re-rendering all visible items every time the `items` property is updated.
|
|
226
|
+
|
|
227
|
+
* `preserveScrollPositionOnPrependItems: boolean` — By default, when prepending new items to the list, the existing items will be pushed downwards on screen. For a user, it would look as if the scroll position has suddenly "jumped", even though technically the scroll position has stayed the same — it's just that the content itself has "jumped". But the user's perception is still that the scroll position has "jumped", as if the application was "buggy". In order to fix such inconvenience, one could pass `true` value here to automatically adjust the scroll position every time when prepending new items to the list. To the end user it would look as if the scroll position is correctly "preserved" when prepending new items to the list, i.e. the application works correctly.
|
|
228
|
+
* This is simply a proxy for the ["core"](#core) component's `.setItems()` method's `preserveScrollPositionOnPrependItems` [option](#options).
|
|
229
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
230
|
+
|
|
231
|
+
* `readyToStart: boolean` — One could initially pass `false` here in order to just initially render the `<VirtualScroller/>` with the provided `initialState` and then hold off calling the `.start()` method of the ["core"](#core) component, effectively "freezing" the `<VirtualScroller/>` until the `false` value is changed to `true`. While in "frozen" state, the `<VirtualScroller/>` will not attempt to re-render itself according to the current scroll position, postponing any such re-renders until `readyToStart` property `false` value is changed to `true`.
|
|
232
|
+
* An example when this could be required is when a user navigates "Back" to the list's page in a web browser. In that case, the application may use the `initialState` property in an attempt to instantly restore the state of the entire list from a previously-saved snapshot, so that it immediately shows the same items that it was showing before the user navigated away from the list's page. But even if the application passes the previously-snapshotted `initialState`, by default the list will still re-render itself according to the current scroll position. And there wouldn't be any issue with that if the page's scroll position has already been restored to what it was before the user navigated away from the list's page. But if by the time the list is mounted, the page's scroll position hasn't been restored yet, the list will re-render itself with an "incorrect" scroll position, and it will "jump" to completely different items, very unexpectedly to the user, as if the application was "buggy". How could scroll position restoration possibly lag behind? In React it's actually very simple: `<VirtualScroller/>` re-renders itself in a `useLayoutEffect()` hook, which, by React's design, runs before any `useLayoutEffect()` hook in any of the parent components, including the top-level "router" component that handles scroll position restoration on page mount. So it becomes a ["chicken-and-egg"](https://en.wikipedia.org/wiki/Chicken_or_the_egg) problem. And `readyToStart: false` property is the only viable workaround for this dilemma: as soon as the top-level "router" component has finished restoring the scroll position, it could somehow signal that to the rest of the application, and then the application would pass `readyToStart: true` property to the `<VirtualScroller/>` component, unblocking it from re-rendering itself.
|
|
233
|
+
|
|
234
|
+
* `getScrollableContainer(): Element`
|
|
235
|
+
* This is simply a proxy for the ["core"](#core) component's `getScrollableContainer` [option](#options).
|
|
236
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
237
|
+
* This function will be initially called right after `<VirtualScroller/>` component is mounted. However, even though all ancestor DOM Elements already exist in the DOM tree by that time, the corresponding ancestor React Elements haven't "mounted" yet, so their `ref`s are still `null`. This means that `getScrollableContainer()` shouldn't use any `ref`s and should instead get the DOM Element of the scrollable container directly from the `document`.
|
|
238
|
+
|
|
239
|
+
Example of an incorrect `getScrollableContainer()` that won't work:
|
|
240
|
+
|
|
241
|
+
```js
|
|
242
|
+
function ListContainer() {
|
|
243
|
+
const scrollableContainer = useRef()
|
|
244
|
+
|
|
245
|
+
const getScrollableContainer = useCallback(() => {
|
|
246
|
+
// This won't work: it will return `null` because `<ListContainer/>` hasn't "mounted" yet.
|
|
247
|
+
return scrollableContainer.current
|
|
248
|
+
}, [])
|
|
249
|
+
|
|
250
|
+
return (
|
|
251
|
+
<div ref={scrollableContainer} style={{ height: "400px", overflow: "scroll" }}>
|
|
252
|
+
<VirtualScroller
|
|
253
|
+
{...}
|
|
254
|
+
getScrollableContainer={getScrollableContainer}
|
|
255
|
+
/>
|
|
256
|
+
</div>
|
|
257
|
+
)
|
|
258
|
+
}
|
|
259
|
+
```
|
|
260
|
+
|
|
261
|
+
Example of a correct `getScrollableContainer()` that would work:
|
|
262
|
+
|
|
263
|
+
```js
|
|
264
|
+
function ListContainer() {
|
|
265
|
+
const getScrollableContainer = useCallback(() => {
|
|
266
|
+
return document.getElementById("scrollable-container")
|
|
267
|
+
}, [])
|
|
268
|
+
|
|
269
|
+
return (
|
|
270
|
+
<div id="scrollable-container" style={{ height: "400px", overflow: "scroll" }}>
|
|
271
|
+
<VirtualScroller
|
|
272
|
+
{...}
|
|
273
|
+
getScrollableContainer={getScrollableContainer}
|
|
274
|
+
/>
|
|
275
|
+
</div>
|
|
276
|
+
)
|
|
277
|
+
}
|
|
278
|
+
```
|
|
279
|
+
|
|
280
|
+
<!--
|
|
281
|
+
(this property has been ignored for a long time and was eventually removed)
|
|
282
|
+
|
|
283
|
+
* `tbody: boolean` — When the container for the list items is going to be a `<tbody/>`, a developer must pass a `tbody: true` property in order for the `<VirtualScroller/>` to work correctly.
|
|
284
|
+
* This is simply a proxy for the ["core"](#core) component's `tbody` option.
|
|
285
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
286
|
+
-->
|
|
287
|
+
|
|
288
|
+
* `itemsContainerComponentRef: object` — Could be used to get access to the `itemsContainerComponent` instance.
|
|
289
|
+
* For example, if `itemsContainerComponent` is `"ul"` then `itemsContainerComponentRef.current` will be set to the `<ul/>` `Element`.
|
|
290
|
+
|
|
291
|
+
* `onItemInitialRender(item)` — When passed, this function will be called for each item when it's rendered for the first time. It could be used to somehow "initialize" an item, if required.
|
|
292
|
+
* This is simply a proxy for the ["core"](#core) component's `onItemInitialRender` [option](#options).
|
|
293
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
294
|
+
|
|
295
|
+
* `bypass: boolean` — Disables the "virtual" aspect of the list, effectively making it a regular "dumb" list that just renders all items.
|
|
296
|
+
* This is simply a proxy for the ["core"](#core) component's `bypass` [option](#options).
|
|
297
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
298
|
+
|
|
299
|
+
* `getEstimatedVisibleItemRowsCount(): number` — Should be specified if server-side rendering is used. Can be omitted if server-side rendering is not used.
|
|
300
|
+
* This is simply a proxy for the ["core"](#core) component's `getEstimatedVisibleItemRowsCount` [option](#options).
|
|
301
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
302
|
+
|
|
303
|
+
* `getEstimatedItemHeight(): number` — Should be specified if server-side rendering is used. Can be omitted if server-side rendering is not used.
|
|
304
|
+
* This is simply a proxy for the ["core"](#core) component's `getEstimatedItemHeight` [option](#options).
|
|
305
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
306
|
+
|
|
307
|
+
* `getEstimatedInterItemVerticalSpacing(): number` — Should be specified if server-side rendering is used. Can be omitted if server-side rendering is not used.
|
|
308
|
+
* This is simply a proxy for the ["core"](#core) component's `getEstimatedInterItemVerticalSpacing` [option](#options).
|
|
309
|
+
* Only the initial value of this property is used, and any changes to it will be ignored.
|
|
310
|
+
|
|
311
|
+
* Any other ["core"](#core) component [options](#options) could be passed here.
|
|
312
|
+
* Such as:
|
|
313
|
+
* `measureItemsBatchSize`
|
|
314
|
+
* Only the initial values of those options will be used, any any changes to those will be ignored.
|
|
315
|
+
|
|
316
|
+
<!-- * `onMount()` — Is called after `<VirtualScroller/>` component has been mounted and before `VirtualScroller.onMount()` is called. -->
|
|
317
|
+
|
|
318
|
+
<!-- * `shouldUpdateLayoutOnScreenResize(event)` — The `shouldUpdateLayoutOnScreenResize` option of `VirtualScroller` class. -->
|
|
319
|
+
|
|
320
|
+
<!--
|
|
321
|
+
If one considers that `useEffect()` hooks [run in the order from child element to parent element](https://stackoverflow.com/questions/58352375/what-is-the-correct-order-of-execution-of-useeffect-in-react-parent-and-child-co), one can conclude that there's no way that the application's `useLayoutEffect()` hook could run before the `useLayoutEffect()` hook in a `<VirtualScroller/>` component. Therefore, there's only one option to make it work, and that would be only rendering `<VirtualScroller/>` after the scrollable container has mounted:
|
|
322
|
+
|
|
323
|
+
```js
|
|
324
|
+
import React, { useState, useLayoutEffect } from 'react'
|
|
325
|
+
import VirtualScroller from 'virtual-scroller'
|
|
326
|
+
|
|
327
|
+
function ListContainer() {
|
|
328
|
+
return (
|
|
329
|
+
<div id="ListContainer">
|
|
330
|
+
<List/>
|
|
331
|
+
</div>
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
function List() {
|
|
336
|
+
const [scrollableContainerHasMounted, setScrollableContainerHasMounted] = useState()
|
|
337
|
+
|
|
338
|
+
useLayoutEffect(() => {
|
|
339
|
+
setScrollableContainerHasMounted(true)
|
|
340
|
+
}, [])
|
|
341
|
+
|
|
342
|
+
if (!scrollableContainerHasMounted) {
|
|
343
|
+
return null
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
return (
|
|
347
|
+
<VirtualScroller
|
|
348
|
+
items={...}
|
|
349
|
+
itemComponent={...}
|
|
350
|
+
getScrollableContainer={getScrollableContainer}
|
|
351
|
+
/>
|
|
352
|
+
)
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
function getScrollableContainer() {
|
|
356
|
+
return document.getElementById('ListContainer')
|
|
357
|
+
}
|
|
358
|
+
```
|
|
359
|
+
|
|
360
|
+
```css
|
|
361
|
+
#ListContainer {
|
|
362
|
+
max-height: 30rem;
|
|
363
|
+
overflow-y: auto;
|
|
364
|
+
}
|
|
365
|
+
```
|
|
366
|
+
-->
|
|
367
|
+
</details>
|
|
368
|
+
|
|
369
|
+
#####
|
|
370
|
+
|
|
371
|
+
<details>
|
|
372
|
+
<summary>Instance methods</summary>
|
|
373
|
+
|
|
374
|
+
#####
|
|
375
|
+
|
|
376
|
+
<!--
|
|
377
|
+
* `renderItem(i)` — Calls `.forceUpdate()` on the `itemComponent` instance for the item with index `i`. Does nothing if the item isn't currently rendered. Is only supported for `itemComponent`s that are `React.Component`s. The `i` item index argument could be replaced with the item object itself, in which case `<VirtualScroller/>` will get `i` as `items.indexOf(item)`.
|
|
378
|
+
-->
|
|
379
|
+
|
|
380
|
+
<!-- * `getItemCoordinates(i)` — A proxy for the corresponding `VirtualScroller` method. -->
|
|
381
|
+
|
|
382
|
+
<!-- * `getElement()` — Returns the items container `Element`. -->
|
|
383
|
+
|
|
384
|
+
* `updateLayout()` — Forces a re-calculation and re-render of the list.
|
|
385
|
+
* This is simply a proxy for the ["core"](#core) component's `.updateLayout()` method.
|
|
386
|
+
|
|
387
|
+
</details>
|
|
388
|
+
|
|
389
|
+
#####
|
|
390
|
+
|
|
391
|
+
<details>
|
|
392
|
+
<summary>More on <code>state</code>, <code>setState</code> and <code>onHeightChange()</code></summary>
|
|
393
|
+
|
|
394
|
+
#####
|
|
395
|
+
|
|
396
|
+
If the `itemComponent` has any internal state, it should be stored in the "virtual scroller" `state` rather than in the usual React state. This is because an item component gets unmounted as soon as it goes off screen, and when it does, all its React state is lost. If the user then scrolls back, the item will be re-rendered "from scratch", without any previous state, which could cause a "jump of content" if the item was somehow "expanded" before it got unmounted.
|
|
397
|
+
|
|
398
|
+
For example, consider a social network feed where the feed items (posts) can be expanded or collapsed via a "Show more"/"Show less" button. Suppose a user clicks a "Show more" button in a post resulting in that post expanding in height. Then the user scrolls down, and since the post is no longer visible, it gets unmounted. Since no state is preserved by default, when the user scrolls back up and the post gets mounted again, its previous state will be lost and it will render in a default non-expanded state, resulting in a perceived "jump" of page content by the difference in height between the expanded and non-expanded post state.
|
|
399
|
+
|
|
400
|
+
To fix that, `itemComponent` receives the following state management properties:
|
|
401
|
+
|
|
402
|
+
* `state` — The state of the item component. It is persisted throughout the entire lifecycle of the list.
|
|
403
|
+
|
|
404
|
+
* In the example described above, `state` might look like `{ expanded: true }`.
|
|
405
|
+
|
|
406
|
+
* This is simply a proxy for the ["core"](#core) component's `.getState().itemStates[i]`.
|
|
407
|
+
|
|
408
|
+
* `setState(newState)` — Use this function to save the item component state whenever it changes.
|
|
409
|
+
|
|
410
|
+
* In the example described above, `setState({ expanded: true/false })` would be called whenever a user clicks a "Show more"/"Show less" button.
|
|
411
|
+
|
|
412
|
+
* This is simply a proxy for the ["core"](#core) component's `.setItemState(item, newState)`.
|
|
413
|
+
|
|
414
|
+
* `onHeightDidChange()` — Call this function immediately after (if ever) the item element height has changed.
|
|
415
|
+
|
|
416
|
+
* In the example described above, `onHeightDidChange()` would be called immediately after a user has clicked a "Show more"/"Show less" button and the component has re-rendered itself. Because that sequence of events has resulted in a change of the item element's height, `VirtualScroller` should re-measure the item's height in order for its internal calculations to stay in sync.
|
|
417
|
+
|
|
418
|
+
* This is simply a proxy for the ["core"](#core) component's `.onItemHeightDidChange(item)`.
|
|
419
|
+
|
|
420
|
+
Example of using `state`/`setState()`/`onHeightDidChange()`:
|
|
421
|
+
|
|
422
|
+
```js
|
|
423
|
+
function ItemComponent({
|
|
424
|
+
item,
|
|
425
|
+
state,
|
|
426
|
+
setState,
|
|
427
|
+
onHeightDidChange
|
|
428
|
+
}) {
|
|
429
|
+
const [internalState, setInternalState] = useState(state)
|
|
430
|
+
|
|
431
|
+
const hasMounted = useRef()
|
|
432
|
+
|
|
433
|
+
useLayoutEffect(() => {
|
|
434
|
+
if (hasMounted.current) {
|
|
435
|
+
setState(internalState)
|
|
436
|
+
onHeightDidChange()
|
|
437
|
+
} else {
|
|
438
|
+
// Skip the initial mount.
|
|
439
|
+
// Only handle the changes of the `internalState`.
|
|
440
|
+
hasMounted.current = true
|
|
441
|
+
}
|
|
442
|
+
}, [internalState])
|
|
443
|
+
|
|
444
|
+
return (
|
|
445
|
+
<section>
|
|
446
|
+
<h1>
|
|
447
|
+
{item.title}
|
|
448
|
+
</h1>
|
|
449
|
+
{internalState && internalState.expanded &&
|
|
450
|
+
<p>{item.text}</p>
|
|
451
|
+
}
|
|
452
|
+
<button onClick={() => {
|
|
453
|
+
setInternalState({
|
|
454
|
+
...internalState,
|
|
455
|
+
expanded: !expanded
|
|
456
|
+
})
|
|
457
|
+
}}>
|
|
458
|
+
{internalState && internalState.expanded ? 'Show less' : 'Show more'}
|
|
459
|
+
</button>
|
|
460
|
+
</section>
|
|
461
|
+
)
|
|
462
|
+
}
|
|
463
|
+
```
|
|
464
|
+
</details>
|
|
465
|
+
|
|
466
|
+
#####
|
|
467
|
+
|
|
468
|
+
<details>
|
|
469
|
+
<summary>Server-Side Render</summary>
|
|
470
|
+
|
|
471
|
+
#####
|
|
472
|
+
|
|
473
|
+
By default, on server side, it will just render the first item, as if the list only had one item. This is because on server side it doesn't know how many items it should render because it doesn't know neither the item height nor the screen height.
|
|
474
|
+
|
|
475
|
+
To fix that, a developer should specify certain properties — `getEstimatedVisibleItemRowsCount(): number` and `getEstimatedItemHeight(): number` and `getEstimatedInterItemVerticalSpacing(): number` — so that it could calculate how many items it should render and how much space it should leave for scrolling. For more technical details, see the description of these parameters in the ["core"](#core) component's [options](#options).
|
|
476
|
+
</details>
|
|
477
|
+
|
|
478
|
+
## DOM
|
|
479
|
+
|
|
480
|
+
`virtual-scroller/dom` exports a `VirtualScroller` class that implements a "virtual scroller" in a standard [Document Object Model](https://en.wikipedia.org/wiki/Document_Object_Model) environment such as a web browser.
|
|
481
|
+
|
|
482
|
+
The `VirtualScroller` class is based on the ["core"](#core) component, and its constructor has the following arguments:
|
|
483
|
+
|
|
484
|
+
* `itemsContainerElement` — Items container DOM `Element`. Alternatively, one could pass a `getItemsContainerElement()` function that returns a DOM `Element`.
|
|
485
|
+
* `items` — The list of items.
|
|
486
|
+
* `renderItem(item): Element` — A function that transforms an `item` into a DOM `Element`.
|
|
487
|
+
* `options` — (optional) See the "Available options" section below.
|
|
488
|
+
|
|
489
|
+
<!-- It `.start()`s automatically upon being created, so there's no need to call `.start()` after creating it. -->
|
|
490
|
+
|
|
491
|
+
Code example:
|
|
492
|
+
|
|
493
|
+
```js
|
|
494
|
+
import VirtualScroller from 'virtual-scroller/dom'
|
|
495
|
+
|
|
496
|
+
// A list of comments.
|
|
497
|
+
const items = [
|
|
498
|
+
{
|
|
499
|
+
username: 'john.smith',
|
|
500
|
+
date: new Date(),
|
|
501
|
+
comment: 'I woke up today'
|
|
502
|
+
},
|
|
503
|
+
...
|
|
504
|
+
]
|
|
505
|
+
|
|
506
|
+
function renderItem(item) {
|
|
507
|
+
const { username, date, comment } = item
|
|
508
|
+
|
|
509
|
+
// Comment element.
|
|
510
|
+
const element = document.createElement('article')
|
|
511
|
+
|
|
512
|
+
// Comment author.
|
|
513
|
+
const author = document.createElement('a')
|
|
514
|
+
author.setAttribute('href', `/users/${username}`)
|
|
515
|
+
author.textContent = `@${username}`
|
|
516
|
+
element.appendChild(author)
|
|
517
|
+
|
|
518
|
+
// Comment date.
|
|
519
|
+
const time = document.createElement('time')
|
|
520
|
+
time.setAttribute('datetime', date.toISOString())
|
|
521
|
+
time.textContent = date.toString()
|
|
522
|
+
element.appendChild(time)
|
|
523
|
+
|
|
524
|
+
// Comment text.
|
|
525
|
+
const text = document.createElement('p')
|
|
526
|
+
text.textContent = comment
|
|
527
|
+
element.appendChild(text)
|
|
528
|
+
|
|
529
|
+
// Return the DOM Element.
|
|
530
|
+
return element
|
|
531
|
+
}
|
|
532
|
+
|
|
533
|
+
// Where the list items will be rendered.
|
|
534
|
+
const itemsContainerElement = document.getElementById('comments')
|
|
535
|
+
|
|
536
|
+
// Create a "virtual scroller" instance.
|
|
537
|
+
// It automatically renders the list and starts listening to scroll events.
|
|
538
|
+
const virtualScroller = new VirtualScroller(
|
|
539
|
+
itemsContainerElement,
|
|
540
|
+
items,
|
|
541
|
+
renderItem
|
|
542
|
+
)
|
|
24
543
|
|
|
25
|
-
|
|
26
|
-
|
|
544
|
+
// When the list will no longer be rendered, the "virtual scroller" should be stopped.
|
|
545
|
+
// For example, that could happen when the user navigates away from the page.
|
|
546
|
+
//
|
|
547
|
+
// virtualScroller.stop()
|
|
548
|
+
```
|
|
549
|
+
<details>
|
|
550
|
+
<summary>Available <code>options</code></summary>
|
|
27
551
|
|
|
28
|
-
|
|
552
|
+
#####
|
|
29
553
|
|
|
30
|
-
|
|
554
|
+
<!-- * `onMount()` — Is called before `VirtualScroller.onMount()` is called. -->
|
|
31
555
|
|
|
32
|
-
|
|
556
|
+
* `onItemUnmount(itemElement: Element)` — Will be called every time when the list unmounts a DOM `Element` for some item that is no longer visible. Rather than discarding such a DOM `Element`, the application could reuse it for another item. Why? Because they say that reusing existing DOM `Element`s is 2-6 times [faster](https://github.com/ChrisAntaki/dom-pool#what-performance-gains-can-i-expect) than creating new ones.
|
|
33
557
|
|
|
34
|
-
|
|
558
|
+
* `readyToStart: boolean` — By default, the list gets rendered and starts working immediately after `new VirtualScroller()` constructor is called. Theoretically, one could imagine how such streamlined pipeline might not be suitable for all possible edge cases, so to opt out of the immediate auto-start behavior, a developer could pass a `readyToStart: false` option when creating a `VirtualScroller` instance. In that case, the `VirtualScroller` instance will perform just the initial render (with the initial `state`), after which it will "freeze" itself until the developer manually calls `.start()` instance method, at which point the list will be unblocked from re-rendering itself in response to user's actions, such as scrolling the page.
|
|
35
559
|
|
|
36
|
-
|
|
37
|
-
It turns out that mounting and unmounting large trees of components (like timelines of Tweets) is very expensive in React.
|
|
38
|
-
Over time, we developed a new infinite scrolling component called VirtualScroller. With this new component, we know exactly what slice of Tweets are being rendered into a timeline at any given time, avoiding the need to make expensive calculations as to where we are visually.
|
|
560
|
+
* `readyToRender: boolean` — The `readyToStart: false` option described above "freezes" the list for any updates but it still performs the initial render of it. If even the initial render of the list should be postponed, pass `readyToRender: false` option, and it will not only prevent the automatic "start" of the `VirtualScroller` at creation time, but it will also prevent the automatic initial render of it until the developer manually calls `.start()` instance method.
|
|
39
561
|
|
|
40
|
-
|
|
562
|
+
* Any other [options](#options) are simply passed through to the ["core"](#core) component.
|
|
563
|
+
</details>
|
|
41
564
|
|
|
42
|
-
|
|
565
|
+
#####
|
|
43
566
|
|
|
44
|
-
|
|
567
|
+
<details>
|
|
568
|
+
<summary>Instance methods</summary>
|
|
45
569
|
|
|
46
|
-
|
|
570
|
+
#####
|
|
47
571
|
|
|
48
|
-
|
|
572
|
+
The following instance methods are just proxies for the corresponding methods of the ["core"](#core) component:
|
|
49
573
|
|
|
50
|
-
|
|
574
|
+
* `start()`
|
|
575
|
+
* `stop()`
|
|
576
|
+
* `setItems(items, options)`
|
|
577
|
+
* `setItemState(item, itemState)`
|
|
578
|
+
* `onItemHeightDidChange(item)`
|
|
51
579
|
|
|
52
|
-
|
|
580
|
+
<!-- * `getItemCoordinates(item)` -->
|
|
581
|
+
</details>
|
|
53
582
|
|
|
54
|
-
|
|
55
|
-
npm install virtual-scroller --save
|
|
56
|
-
```
|
|
583
|
+
## Core
|
|
57
584
|
|
|
58
|
-
|
|
585
|
+
The default export is a "core" `VirtualScroller` class: it implements the core logic of a "virtual scroller" component and can be used to build a "virtual scroller" for any UI framework or even any [rendering engine](#rendering-engine) other than DOM. This core class is not meant to be used in applications directly. Instead, prefer using one of the high-level components provided by this library: [`virtual-scroller/react`](#react) or [`virtual-scroller/dom`](#dom). Or implement your own: see `source/test` folder for an example of using the core component to build an "imaginary" renderer implementation.
|
|
59
586
|
|
|
60
|
-
|
|
587
|
+
### State
|
|
61
588
|
|
|
62
|
-
The
|
|
589
|
+
The core `VirtualScroller` component works as a "state machine", i.e. at any given moment in time, anything that is rendered on screen is precisely expressed by the `state`, and vice versa. I'll call it a "contract".
|
|
63
590
|
|
|
64
|
-
|
|
591
|
+
So every time the user scrolls, the "virtual scroller" core component recalculates the currently-visible item indexes and updates the `state`, which triggers a re-render.
|
|
65
592
|
|
|
66
|
-
The
|
|
593
|
+
The "re-render" part is completely outsourced to a given higher-level "implementation", such as [`virtual-scroller/dom`](#dom), which passes a `render(state)` function as a parameter to the core component. And, since the "re-render" must not break the "contract", it must render everything immediately and in-full in that function.
|
|
67
594
|
|
|
68
|
-
|
|
595
|
+
Sometimes though, by design, re-rendering could only be done "asynchronously" (i.e. after a short delay), such as in React and [`virtual-scroller/react`](#react). In that case, in order to not break the "contract", the `state` update will have to be put on hold by the same exact delay. `virtual-scroller/react` achieves that by passing custom `setState()` and `getState()` functions as parameters to the core component, instead of passing a `render()` function parameter. The custom `setState()` and `getState()` functions temporarily "hide" the `state` changes until those changes have been rendered by React.
|
|
69
596
|
|
|
70
597
|
<details>
|
|
71
598
|
<summary><code>state</code> properties</summary>
|
|
@@ -74,7 +601,7 @@ A higher-level wrapper around the core `VirtualScroller` component must manage t
|
|
|
74
601
|
|
|
75
602
|
The main `state` properties are:
|
|
76
603
|
|
|
77
|
-
* `items: any[]` — The list of items (can be updated via [`.setItems()`](#
|
|
604
|
+
* `items: any[]` — The list of items (can be updated via [`.setItems()`](#updating-items)).
|
|
78
605
|
|
|
79
606
|
* `firstShownItemIndex: number` — The index of the first item that should be rendered.
|
|
80
607
|
|
|
@@ -88,19 +615,19 @@ The following `state` properties are only used for saving and restoring `Virtual
|
|
|
88
615
|
|
|
89
616
|
* `itemStates: any[]` — The "states" of all items. If an item's appearance is not "static" and could change, then every aspect of the item's appearance that could change should be represented in the item's "state", and that "state" must be preserved somewhere. That's because of the nature of how `VirtualScroller` works: no-longer-visible items get un-rendered, and when they later become visible again, they should precisely restore their latest-rendered appearance by re-rendering from a previously preserved "state".
|
|
90
617
|
|
|
91
|
-
* The item "state" could be preserved anywhere in the application, or the developer could use `VirtualScroller`'s built-in item "state" storage. To preserve an item's state in the built-in storage, call `.setItemState(
|
|
618
|
+
* The item "state" could be preserved anywhere in the application, or the developer could use `VirtualScroller`'s built-in item "state" storage. To preserve an item's state in the built-in storage, call `.setItemState(item, itemState)` instance method (described below) immediately after an item's state has changed.
|
|
92
619
|
|
|
93
|
-
* An example would be an item representing a social media comment, with a "Show more"/"Show less" button that shows or hides the full text of the comment. Immediately after the full text of a comment has been shown or hidden, it should call `.setItemState(
|
|
620
|
+
* An example would be an item representing a social media comment, with a "Show more"/"Show less" button that shows or hides the full text of the comment. Immediately after the full text of a comment has been shown or hidden, it should call `.setItemState(item, { showMore: true/false })` instance method along with `.onItemHeightDidChange(item)` instance method (described below), so that next time when the item is rendered, it could restore its appearance from `virtualScroller.getState().itemStates[i]`.
|
|
94
621
|
|
|
95
622
|
* For another similar example, consider a social network feed, where each post optionally has an attachment. Suppose there's a post in the feed having a YouTube video attachment. The attachment is initially shown as a small thumbnail that expands into a full-sized embedded YouTube video player when a user clicks on it. If the expanded/collapsed state of such attachment wasn't preserved, then the following "glitch" would be observed: the user expands the video, then scrolls down so that the post with the video is no longer visible, the post gets unmounted due to going off screen, then the user scrolls back up so that the post with the video is visible again, the post gets mounted again, but the video is not expanded and instead a small thumbnail is shown because there's no previous "state" to restore from.
|
|
96
623
|
|
|
97
|
-
* In this example, besides preserving the item state itself, one should also call `.onItemHeightDidChange(
|
|
624
|
+
* In this example, besides preserving the item state itself, one should also call `.onItemHeightDidChange(item)` instance method (described below) right after the YouTube video has been expanded/collapsed.
|
|
98
625
|
|
|
99
626
|
* `itemHeights: number[]` — The measured heights of all items. If an item's height hasn't been measured yet then it's `undefined`.
|
|
100
627
|
|
|
101
|
-
* By default, items are only measured once: when they're initially rendered. If an item's height changes afterwards, then `.onItemHeightDidChange(
|
|
628
|
+
* By default, items are only measured once: when they're initially rendered. If an item's height changes afterwards, then `.onItemHeightDidChange(item)` instance method must be called right after it happens (described later in the document), otherwise `VirtualScroller`'s calculations will be off. For example, if an item is a social media comment, and there's a "Show more"/"Show less" button that shows the full text of the comment, then it must call `.onItemHeightDidChange(item)` immediately after the comment text has been expanded or collapsed.
|
|
102
629
|
|
|
103
|
-
* Besides the requirement of calling `.onItemHeightDidChange(
|
|
630
|
+
* Besides the requirement of calling `.onItemHeightDidChange(item)`, every change in an item's height must also be reflected in the actual data: the change in height must be either a result of the item's internal properties changing or it could be a result of changing the item's "state". The reason is that when an item gets hidden, it's no longer rendered, so when it becomes visible again, it should precisely restore its last-rendered appearance based on the item's properties and any persisted "state".
|
|
104
631
|
|
|
105
632
|
* `verticalSpacing: number?` — Vertical item spacing. Is `undefined` until it has been measured. Is only measured once, when at least two rows of items have been rendered.
|
|
106
633
|
|
|
@@ -109,12 +636,10 @@ The following `state` properties are only used for saving and restoring `Virtual
|
|
|
109
636
|
* `scrollableContainerWidth: number?` — The width of the scrollable container. For DOM implementations, that's gonna be either the browser window width or some scrollable parent element width. Is `undefined` until it has been measured after the `VirtualScroller` has been `start()`-ed.
|
|
110
637
|
</details>
|
|
111
638
|
|
|
112
|
-
#### Example
|
|
113
|
-
|
|
114
|
-
A general idea of using the low-level <code>VirtualScroller</code> class:
|
|
115
|
-
|
|
116
639
|
#####
|
|
117
640
|
|
|
641
|
+
Code example:
|
|
642
|
+
|
|
118
643
|
```js
|
|
119
644
|
import VirtualScroller from 'virtual-scroller'
|
|
120
645
|
|
|
@@ -124,11 +649,11 @@ const items = [
|
|
|
124
649
|
...
|
|
125
650
|
]
|
|
126
651
|
|
|
127
|
-
const getContainerElement = () => document.getElementById(
|
|
652
|
+
const getContainerElement = () => document.getElementById('fruits-list')
|
|
128
653
|
|
|
129
654
|
const virtualScroller = new VirtualScroller(getContainerElement, items, {
|
|
655
|
+
// Re-renders the list based on the `state`.
|
|
130
656
|
render(state) {
|
|
131
|
-
// Re-renders the list based on its `state`.
|
|
132
657
|
const {
|
|
133
658
|
items,
|
|
134
659
|
firstShownItemIndex,
|
|
@@ -153,112 +678,18 @@ virtualScroller.start()
|
|
|
153
678
|
virtualScroller.stop()
|
|
154
679
|
```
|
|
155
680
|
|
|
156
|
-
|
|
157
|
-
* `items` — The list of items.
|
|
158
|
-
* `render(state, prevState)` — "Renders" the list.
|
|
159
|
-
|
|
160
|
-
#####
|
|
161
|
-
|
|
162
|
-
<details>
|
|
163
|
-
<summary>An example of implementing a high-level <code>virtual-scroller/dom</code> component on top of the low-level <code>VirtualScroller</code> class.
|
|
164
|
-
</summary>
|
|
165
|
-
|
|
166
|
-
#####
|
|
167
|
-
|
|
168
|
-
```js
|
|
169
|
-
import VirtualScroller from 'virtual-scroller'
|
|
170
|
-
|
|
171
|
-
const items = [
|
|
172
|
-
{ title: 'Apple' },
|
|
173
|
-
{ title: 'Banana' },
|
|
174
|
-
{ title: 'Cranberry' }
|
|
175
|
-
]
|
|
176
|
-
|
|
177
|
-
function renderItem(item) {
|
|
178
|
-
const div = document.createElement('div')
|
|
179
|
-
div.innerText = item.title
|
|
180
|
-
return div
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
const container = document.getElementById('list')
|
|
184
|
-
|
|
185
|
-
function render(state, prevState) {
|
|
186
|
-
const {
|
|
187
|
-
items,
|
|
188
|
-
beforeItemsHeight,
|
|
189
|
-
afterItemsHeight,
|
|
190
|
-
firstShownItemIndex,
|
|
191
|
-
lastShownItemIndex
|
|
192
|
-
} = state
|
|
193
|
-
|
|
194
|
-
// Set `paddingTop` and `paddingBottom` on the container element:
|
|
195
|
-
// it emulates the non-visible items as if they were rendered.
|
|
196
|
-
container.style.paddingTop = Math.round(beforeItemsHeight) + 'px'
|
|
197
|
-
container.style.paddingBottom = Math.round(afterItemsHeight) + 'px'
|
|
198
|
-
|
|
199
|
-
// Perform an intelligent "diff" re-render as the user scrolls the page.
|
|
200
|
-
// This also requires that the list of `items` hasn't been changed.
|
|
201
|
-
// On initial render, `prevState` is `undefined`.
|
|
202
|
-
if (prevState && items === prevState.items) {
|
|
203
|
-
|
|
204
|
-
// Remove no longer visible items.
|
|
205
|
-
let i = prevState.lastShownItemIndex
|
|
206
|
-
while (i >= prevState.firstShownItemIndex) {
|
|
207
|
-
if (i >= firstShownItemIndex && i <= lastShownItemIndex) {
|
|
208
|
-
// The item is still visible.
|
|
209
|
-
} else {
|
|
210
|
-
// The item is no longer visible. Remove it.
|
|
211
|
-
container.removeChild(container.childNodes[i - prevState.firstShownItemIndex])
|
|
212
|
-
}
|
|
213
|
-
i--
|
|
214
|
-
}
|
|
215
|
-
|
|
216
|
-
// Add newly visible items.
|
|
217
|
-
let prependBefore = container.firstChild
|
|
218
|
-
let i = firstShownItemIndex
|
|
219
|
-
while (i <= lastShownItemIndex) {
|
|
220
|
-
if (i >= prevState.firstShownItemIndex && i <= prevState.lastShownItemIndex) {
|
|
221
|
-
// The item is already being rendered.
|
|
222
|
-
// Next items will be appended rather than prepended.
|
|
223
|
-
prependBefore = undefined
|
|
224
|
-
} else {
|
|
225
|
-
if (prependBefore) {
|
|
226
|
-
container.insertBefore(renderItem(items[i]), prependBefore)
|
|
227
|
-
} else {
|
|
228
|
-
container.appendChild(renderItem(items[i]))
|
|
229
|
-
}
|
|
230
|
-
}
|
|
231
|
-
i++
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
else {
|
|
235
|
-
// Re-render the list from scratch.
|
|
236
|
-
while (container.firstChild) {
|
|
237
|
-
container.removeChild(container.firstChild)
|
|
238
|
-
}
|
|
239
|
-
let i = firstShownItemIndex
|
|
240
|
-
while (i <= lastShownItemIndex) {
|
|
241
|
-
container.appendChild(renderItem(items[i]))
|
|
242
|
-
i++
|
|
243
|
-
}
|
|
244
|
-
}
|
|
245
|
-
}
|
|
246
|
-
|
|
247
|
-
const virtualScroller = new VirtualScroller(() => element, items, { render })
|
|
248
|
-
|
|
249
|
-
// Start VirtualScroller listening for scroll events.
|
|
250
|
-
virtualScroller.start()
|
|
681
|
+
`VirtualScroller` class constructor arguments:
|
|
251
682
|
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
683
|
+
* `getContainerElement()` — returns the container "element" for the list item "elements".
|
|
684
|
+
* `items` — an array of items.
|
|
685
|
+
* `options` — (optional)
|
|
686
|
+
* `render(state, prevState)` — "re-renders" the list according to the new `state`.
|
|
687
|
+
* The `render()` function can only be specified when it immediately re-renders the list. Sometimes, an immediate re-render is not possible. For example, in React framework, re-render is done "asynchronously", i.e. with a short delay. In such case, instead of specifying a `render` parameter when creating a `virtualScroller` instance, one should omit it and then call an instance method — `virtualScroller.useState({ getState, setState/updateState })` — where `getState` function returns the currently-rendered state and `setState/updateState` function is responsible for triggerring an eventual "re-render" of the list according to the new `state`.
|
|
257
688
|
|
|
258
689
|
#### Options
|
|
259
690
|
|
|
260
691
|
<details>
|
|
261
|
-
<summary
|
|
692
|
+
<summary>Available <code>options</code></summary>
|
|
262
693
|
|
|
263
694
|
#####
|
|
264
695
|
|
|
@@ -282,11 +713,20 @@ virtualScroller.start()
|
|
|
282
713
|
|
|
283
714
|
* `getColumnsCount(container: ScrollableContainer): number` — (advanced) Provides support for ["grid"](#grid-layout) layout. Should return the columns count. The `container` argument provides a `.getWidth()` method for getting the available area width.
|
|
284
715
|
|
|
285
|
-
|
|
716
|
+
* `getEstimatedVisibleItemRowsCount(): number` and/or `getEstimatedItemHeight(): number` and/or `getEstimatedInterItemVerticalSpacing(): number` — These functions are only used during the initial render of the list, i.e. when `VirtualScroller` doesn't know anything about the item dimensions.
|
|
717
|
+
* `getEstimatedVisibleItemRowsCount()` is used to guess how many rows of items should be rendered in order to cover the screen area. Sidenote: It will actually render more items than that, with a "prerender margin" on top and bottom, just to account for future scrolling.
|
|
718
|
+
* `getEstimatedItemHeight()` is used to guess the average item height before any of the items have been rendered yet. This average item height is then used to calculate the size of the scrollbar, i.e. how much the user can scroll. It can also be used to calculate the count of visible rows of items if the screen size is known and `getEstimatedVisibleItemRowsCount()` function is not specified.
|
|
719
|
+
* `getEstimatedInterItemVerticalSpacing()` is used to guess the vertical spacing between the items. It is used to calculate the size of the scrollbar, i.e. how much the user can scroll.
|
|
720
|
+
* After the initial render has finished, the list will measure the heights of the rendered items and will use those values to calculate the average item height, the vertical spacing between the items and the count of visible rows of items, and with these new values it will re-render itself.
|
|
721
|
+
* This means that on client side, `getEstimatedVisibleItemRowsCount()` and `getEstimatedItemHeight()` and `getEstimatedInterItemVerticalSpacing()` don't really matter because the list will immediately re-render itself with the correct measured values anyway, and the user will not even observe the results of the initial render because a follow-up render happens immediately.
|
|
722
|
+
* On server side though, `getEstimatedVisibleItemRowsCount()` and `getEstimatedItemHeight()` and `getEstimatedInterItemVerticalSpacing()` completely determine the output of a "server-side render".
|
|
723
|
+
* When these parameters aren't specified, the list will render just the first item during the initial render.
|
|
724
|
+
|
|
725
|
+
#### "Advanced" (rarely-used) options
|
|
286
726
|
|
|
287
|
-
* `bypass: boolean` — Pass `true` to
|
|
727
|
+
* `bypass: boolean` — Pass `true` to disable the "virtualization" behavior and just render the entire list of items.
|
|
288
728
|
|
|
289
|
-
* `getInitialItemState
|
|
729
|
+
* `getInitialItemState(item): any?` — Creates the initial state for an item. It can be used to populate the default initial states for list items. By default, an item's state is `undefined`.
|
|
290
730
|
|
|
291
731
|
* `initialScrollPosition: number` — If passed, the page will be scrolled to this `scrollY` position.
|
|
292
732
|
|
|
@@ -294,7 +734,7 @@ virtualScroller.start()
|
|
|
294
734
|
|
|
295
735
|
<!-- * `customState: object` — (advanced) A developer might want to store some "custom" (additional) state along with the `VirtualScroller` state, for whatever reason. To do that, pass the initial value of such "custom" state as the `customState` option when creating a `VirtualScroller` instance. -->
|
|
296
736
|
|
|
297
|
-
* `getItemId(item)` — (advanced) When `items` are dynamically updated via `.setItems()`, `VirtualScroller` detects an "incremental" update by comparing "new" and "old" item ["references"](https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0): this way, `VirtualScroller` can understand that the "new" `items` are (mostly) the same as the "old" `items` when some items get prepended or appended to the list, in which case it doesn't re-render the whole list from scratch, but rather just renders the "new" items that got prepended or appended. Sometimes though, some of the "old" items might get updated: for example, if `items` is a list of comments, then some of those comments might get edited in-between the refreshes. In that case, the edited comment object reference should change in order to indicate that the comment's content has changed and that the comment should be re-rendered (at least that's how it has to be done in React world). At the same time, changing the edited comment object reference would break `VirtualScroller`'s "incremental" update detection, and it would re-render the whole list of comments from scratch, which is not what it should be doing in such cases. So, in cases like this, `VirtualScroller` should have some way to understand that the updated item, even if its object reference has changed, is still the same as the old one, so that it doesn't break "incremental" update detection. For that, `getItemId(item)` parameter could be passed, which `VirtualScroller` would use to compare "old" and "new" items (instead of the default "reference equality" check), and that would fix the "re-rendering the whole list from scratch" issue. It can also be used when `items` are fetched from an external API, in which case all item object references change on every such fetch.
|
|
737
|
+
* `getItemId(item): number | string` — (advanced) When `items` are dynamically updated via `.setItems()`, `VirtualScroller` detects an "incremental" update by comparing "new" and "old" item ["references"](https://codeburst.io/explaining-value-vs-reference-in-javascript-647a975e12a0): this way, `VirtualScroller` can understand that the "new" `items` are (mostly) the same as the "old" `items` when some items get prepended or appended to the list, in which case it doesn't re-render the whole list from scratch, but rather just renders the "new" items that got prepended or appended. Sometimes though, some of the "old" items might get updated: for example, if `items` is a list of comments, then some of those comments might get edited in-between the refreshes. In that case, the edited comment object reference should change in order to indicate that the comment's content has changed and that the comment should be re-rendered (at least that's how it has to be done in React world). At the same time, changing the edited comment object reference would break `VirtualScroller`'s "incremental" update detection, and it would re-render the whole list of comments from scratch, which is not what it should be doing in such cases. So, in cases like this, `VirtualScroller` should have some way to understand that the updated item, even if its object reference has changed, is still the same as the old one, so that it doesn't break "incremental" update detection. For that, `getItemId(item)` parameter could be passed, which `VirtualScroller` would use to compare "old" and "new" items (instead of the default "reference equality" check), and that would fix the "re-rendering the whole list from scratch" issue. It can also be used when `items` are fetched from an external API, in which case all item object references change on every such fetch.
|
|
298
738
|
|
|
299
739
|
* `onItemInitialRender(item)` — (advanced) Will be called for each `item` when it's about to be rendered for the first time. This function could be used to somehow "initialize" an item before it gets rendered for the first time. For example, consider a list of items that must be somehow "preprocessed" (parsed, enhanced, etc) before being rendered, and such "preprocessing" puts some load on the CPU (and therefore takes some time). In such case, instead of "preprocessing" the whole list of items up front, the application could "preprocess" only the items that're actually visible, preventing the unnecessary work and reducing the "time to first render".
|
|
300
740
|
* The function is guaranteed to be called at least once for each item that ever gets rendered.
|
|
@@ -305,27 +745,27 @@ virtualScroller.start()
|
|
|
305
745
|
|
|
306
746
|
<!-- * `shouldUpdateLayoutOnScreenResize(event: Event): boolean` — By default, `VirtualScroller` always performs a re-layout on window `resize` event. The `resize` event is not only triggered when a user resizes the window itself: it's also [triggered](https://developer.mozilla.org/en-US/docs/Web/API/Window/fullScreen#Notes) when the user switches into (and out of) fullscreen mode. By default, `VirtualScroller` performs a re-layout on all window `resize` events, except for ones that don't result in actual window width or height change, and except for cases when, for example, a video somewhere in a list is maximized into fullscreen. There still can be other "custom" cases: for example, when an application uses a custom "slideshow" component (rendered outside of the list DOM element) that goes into fullscreen when a user clicks a picture or a video in the list. For such "custom" cases `shouldUpdateLayoutOnScreenResize(event)` option / property can be specified. -->
|
|
307
747
|
|
|
308
|
-
* `measureItemsBatchSize: number` — (advanced) (experimental) Imagine a situation when a user doesn't gradually scroll through a huge list but instead hits an End key to scroll right to the end of such huge list: this will result in the whole list rendering at once
|
|
748
|
+
* `measureItemsBatchSize: number` — (advanced) (experimental) Imagine a situation when a user doesn't gradually scroll through a huge list but instead hits an End key to scroll right to the end of such huge list: this will result in the whole list rendering at once, because an item needs to know the height of all previous items in order to render at correct scroll position, which could be CPU-intensive in some cases — for example, when using React due to its slow performance when initially rendering components on a page. To prevent freezing the UI in the process, a `measureItemsBatchSize` could be configured, that would limit the maximum count of items that're being rendered in a single pass for measuring their height: if `measureItemsBatchSize` is configured, then such items will be rendered and measured in batches. By default it's set to `100`. This is an experimental feature and could be removed in future non-major versions of this library. For example, the future React 17 will come with [Fiber](https://www.youtube.com/watch?v=ZCuYPiUIONs) rendering engine that is said to resolve such freezing issues internally. In that case, introducing this option may be reconsidered.
|
|
309
749
|
|
|
310
|
-
*
|
|
750
|
+
<!-- * (alternative description) `getEstimatedItemHeight(): number` — By default, `<VirtualScroller/>` uses an average measured item height as an estimate for the height of any item that hasn't been rendered yet. This way, it is able to guess what will be the total height of the items below the current scroll position, which is required in order to display a correct scrollbar. However, if the application thinks that it has a better idea of what the average item height is gonna be, it could force `<VirtualScroller/>` to use that value instead of the average measured one. -->
|
|
311
751
|
|
|
312
|
-
* `
|
|
752
|
+
* `prerenderMarginRatio` — (currently unused) The list component renders not only the items that're currently visible but also the items that lie within some additional vertical distance (called "prerender margin") on top and bottom to account for future scrolling. This way, it doesn't have to recalculate the layout on each scroll event and is only forced to recalculate the layout if the user scrolls past the "prerender margin". Therefore, "prerender margin" is an optimization that "throttles" layout recalculation. By default, the "prerender margin" is equal to scrollable container height: this seems to be the most optimal value to account for "Page Up" / "Page Down" scrolling. This parameter is currently not customizable because the default value of `1` seems to work fine in all possible use cases.
|
|
313
753
|
</details>
|
|
314
754
|
|
|
315
755
|
#####
|
|
316
756
|
|
|
317
757
|
<details>
|
|
318
|
-
<summary
|
|
758
|
+
<summary>Instance methods</summary>
|
|
319
759
|
|
|
320
760
|
#####
|
|
321
761
|
|
|
322
|
-
* `start()` — `VirtualScroller` starts listening
|
|
762
|
+
* `start()` — Performs an initial render of the `VirtualScroller` and starts listening to scroll events.
|
|
323
763
|
|
|
324
|
-
* `stop()` —
|
|
764
|
+
* `stop()` — Stops listening to scroll events. Call this method when the list is about to be removed from the page. To re-start the `VirtualScroller`, call `.start()` method again.
|
|
325
765
|
|
|
326
766
|
* `getState(): object` — Returns `VirtualScroller` state.
|
|
327
767
|
|
|
328
|
-
* `setItems(newItems: any[], options: object?)` — Updates `VirtualScroller` `items`. For example, it can be used to prepend or append new items to the list. See [
|
|
768
|
+
* `setItems(newItems: any[], options: object?)` — Updates `VirtualScroller` `items`. For example, it can be used to prepend or append new items to the list. See [Updating Items](#updating-items) section for more details. Available options:
|
|
329
769
|
* `preserveScrollPositionOnPrependItems: boolean` — Set to `true` to enable "restore scroll position after prepending new items" feature (should be used when implementing a "Show previous items" button).
|
|
330
770
|
|
|
331
771
|
#### Custom (External) State Management
|
|
@@ -342,423 +782,184 @@ A developer might prefer to use custom (external) state management rather than t
|
|
|
342
782
|
|
|
343
783
|
* `setState(newState: object)` — Sets the externally managed `VirtualScroller` `state`. Must call `.onRender()` right after the updated `state` gets "rendered". A higher-order `VirtualScroller` implementation could either "render" the list immediately in its `setState()` function, in which case it would be better to use the default state management instead and pass a custom `render()` function, or the `setState()` function could "schedule" an "asynchronous" "re-render", like the React implementation does, in which case such `setState()` function would be called an ["asynchronous"](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous) one, meaning that state updates aren't "rendered" immediately and are instead queued and then "rendered" in a single compound state update for better performance.
|
|
344
784
|
|
|
345
|
-
* `updateState(stateUpdate: object)` — (optional) `setState()` parameter could be replaced with `updateState()` parameter. The only difference between the two is that `updateState()` gets called with just the portion of the state that is being updated while `setState()` gets called with the whole updated state object, so it's just a matter of preference.
|
|
346
|
-
|
|
347
|
-
For a usage example, see `./source/react/VirtualScroller.js`. The steps are:
|
|
348
|
-
|
|
349
|
-
* Create a `VirtualScroller` instance.
|
|
350
|
-
|
|
351
|
-
* Get the initial state value via `virtualScroller.getInitialState()`.
|
|
352
|
-
|
|
353
|
-
* Initialize the externally managed state with the initial state value.
|
|
354
|
-
|
|
355
|
-
* Define `getState()` and `updateState()` functions for reading or updating the externally managed state.
|
|
356
|
-
|
|
357
|
-
* Call `virtualScroller.useState({ getState, updateState })`.
|
|
358
|
-
|
|
359
|
-
* "Render" the list and call `virtualScroller.start()`.
|
|
360
|
-
|
|
361
|
-
When using custom (external) state management, contrary to the default (internal) state management approach, the `render()` function parameter can't be passed to the `VirtualScroller` constructor. The reason is that `VirtualScroller` wouldn't know when exactly should it call such `render()` function because by design it can only be called right after the state has been updated, and `VirtualScroller` doesn't know when exactly does the state get updated, because state updates are done via an "external" `updateState()` function that could as well apply state updates "asynchronously" (after a short delay), like in React, rather than "synchronously" (immediately). That's why the `updateState()` function must re-render the list by itself, at any time it finds appropriate, and right after the list has been re-rendered, it must call `virtualScroller.onRender()`.
|
|
362
|
-
|
|
363
|
-
#### "Advanced" (rarely used) instance methods
|
|
364
|
-
|
|
365
|
-
* `onItemHeightDidChange(i: number)` — (advanced) If an item's height could've changed, this function should be called immediately after the item's height has potentially changed. The function re-measures the item's height (the item must still be rendered) and re-calculates `VirtualScroller` layout. An example for using this function would be having an "Expand"/"Collapse" button in a list item.
|
|
366
|
-
|
|
367
|
-
* There's also a convention that every change in an item's height must come as a result of changing the item's "state". See the descripton of `itemStates` and `itemHeights` properties of the `VirtualScroller` [state](#state) for more details.
|
|
368
|
-
|
|
369
|
-
* Implementation-wise, calling `onItemHeightDidChange()` manually could be replaced with detecting item height changes automatically via [Resize Observer](https://caniuse.com/#search=Resize%20Observer) in some future version.
|
|
370
|
-
|
|
371
|
-
* `setItemState(i: number, itemState: any?)` — (advanced) Preserves a list item's "state" inside `VirtualScroller`'s built-in item "state" storage. See the descripton of `itemStates` property of the `VirtualScroller` [state](#state) for more details.
|
|
372
|
-
|
|
373
|
-
* A developer could use it to preserve an item's "state" if it could change. The reason is that offscreen items get unmounted and any unsaved state is lost in the process. If an item's state is correctly preserved, the item's latest-rendered appearance could be restored from that state when the item gets mounted again due to becoming visible again.
|
|
374
|
-
|
|
375
|
-
* Calling `setItemState()` doesn't trigger a re-layout of `VirtualScroller` because changing a list item's state doesn't necessarily mean a change of its height, so a re-layout might not be required. If an item's height did change as a result of changing its state, then `VirtualScroller` layout must be updated, and to do that, one should call `onItemHeightDidChange(i)` right after the change in the item's state has been reflected on screen.
|
|
376
|
-
|
|
377
|
-
* `getItemScrollPosition(i: number): number?` — (advanced) Returns an item's scroll position inside the scrollable container. Returns `undefined` if any of the items before this item haven't been rendered yet.
|
|
378
|
-
|
|
379
|
-
<!-- * `getItemCoordinates(i: number): object` — Returns coordinates of item with index `i` relative to the "scrollable container": `top` is the top offset of the item relative to the start of the "scrollable container", `bottom` is the top offset of the item's bottom edge relative to the start of the "scrollable container", `height` is the item's height. -->
|
|
380
|
-
|
|
381
|
-
* `updateLayout()` — (advanced) Triggers a re-layout of `VirtualScroller`. It's what's called every time on page scroll or window resize. You most likely won't ever need to call this method manually. Still, one could imagine a hypothetical case when a developer might want to call this method. For example, when the list's top position changes not as a result of scrolling the page or resizing the window, but rather because of some unrelated "dynamic" changes of the page's content. For example, if some DOM elements above the list are removed (like a closeable "info" notification element) or collapsed (like an "accordion" panel), then the list's top position changes, which means that now some of the previoulsy shown items might go off screen, revealing an unrendered blank area to the user. The area would be blank because the "shift" of the list's vertical position happened not as a result of the user scrolling the page or resizing the window, and, therefore, it won't be registered by the `VirtualScroller` component. To fix that, a developer might want to trigger a re-layout manually.
|
|
382
|
-
</details>
|
|
383
|
-
|
|
384
|
-
## DOM
|
|
385
|
-
|
|
386
|
-
`virtual-scroller/dom` component implements a `VirtualScroller` in a standard [Document Object Model](https://en.wikipedia.org/wiki/Document_Object_Model) environment (a web browser).
|
|
387
|
-
|
|
388
|
-
The DOM `VirtualScroller` component constructor accepts arguments:
|
|
389
|
-
|
|
390
|
-
* `container` — Container DOM `Element`.
|
|
391
|
-
* `items` — The list of items.
|
|
392
|
-
* `renderItem(item)` — A function that "renders" an `item` as a DOM `Element`.
|
|
393
|
-
* `options` — (optional) Core `VirtualScroller` options.
|
|
394
|
-
|
|
395
|
-
It `.start()`s automatically upon being created, so there's no need to call `.start()` after creating it.
|
|
396
|
-
|
|
397
|
-
```js
|
|
398
|
-
import VirtualScroller from 'virtual-scroller/dom'
|
|
399
|
-
|
|
400
|
-
const messages = [
|
|
401
|
-
{
|
|
402
|
-
username: 'john.smith',
|
|
403
|
-
date: new Date(),
|
|
404
|
-
text: 'I woke up today'
|
|
405
|
-
},
|
|
406
|
-
...
|
|
407
|
-
]
|
|
408
|
-
|
|
409
|
-
function renderMessage(message) {
|
|
410
|
-
// Message element.
|
|
411
|
-
const root = document.createElement('article')
|
|
412
|
-
|
|
413
|
-
// Message author.
|
|
414
|
-
const author = document.createElement('a')
|
|
415
|
-
author.setAttribute('href', `/users/${message.username}`)
|
|
416
|
-
author.textContent = `@${message.username}`
|
|
417
|
-
root.appendChild(author)
|
|
418
|
-
|
|
419
|
-
// Message date.
|
|
420
|
-
const time = document.createElement('time')
|
|
421
|
-
time.setAttribute('datetime', message.date.toISOString())
|
|
422
|
-
time.textContent = message.date.toString()
|
|
423
|
-
root.appendChild(time)
|
|
424
|
-
|
|
425
|
-
// Message text.
|
|
426
|
-
const text = document.createElement('p')
|
|
427
|
-
text.textContent = message.text
|
|
428
|
-
root.appendChild(text)
|
|
429
|
-
|
|
430
|
-
// Return message element.
|
|
431
|
-
return root
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
const virtualScroller = new VirtualScroller(
|
|
435
|
-
document.getElementById('messages'),
|
|
436
|
-
messages,
|
|
437
|
-
renderMessage
|
|
438
|
-
)
|
|
439
|
-
|
|
440
|
-
// When the `VirtualScroller` component is no longer needed on the page:
|
|
441
|
-
// virtualScroller.stop()
|
|
442
|
-
```
|
|
443
|
-
<details>
|
|
444
|
-
<summary>Additional DOM <code>VirtualScroller</code> options</summary>
|
|
445
|
-
|
|
446
|
-
#####
|
|
447
|
-
|
|
448
|
-
<!-- * `onMount()` — Is called before `VirtualScroller.onMount()` is called. -->
|
|
449
|
-
|
|
450
|
-
* `onItemUnmount(itemElement)` — Is called after a `VirtualScroller` item DOM `Element` is unmounted. Can be used to add DOM `Element` ["pooling"](https://github.com/ChrisAntaki/dom-pool#what-performance-gains-can-i-expect).
|
|
451
|
-
</details>
|
|
452
|
-
|
|
453
|
-
#####
|
|
454
|
-
|
|
455
|
-
<details>
|
|
456
|
-
<summary>DOM <code>VirtualScroller</code> instance methods</summary>
|
|
457
|
-
|
|
458
|
-
#####
|
|
459
|
-
|
|
460
|
-
* `start()` — A proxy for the corresponding `VirtualScroller` method.
|
|
461
|
-
|
|
462
|
-
* `stop()` — A proxy for the corresponding `VirtualScroller` method.
|
|
463
|
-
|
|
464
|
-
* `setItems(items, options)` — A proxy for the corresponding `VirtualScroller` method.
|
|
465
|
-
|
|
466
|
-
* `onItemHeightDidChange(i)` — A proxy for the corresponding `VirtualScroller` method.
|
|
467
|
-
|
|
468
|
-
* `setItemState(i, itemState)` — A proxy for the corresponding `VirtualScroller` method.
|
|
469
|
-
|
|
470
|
-
<!-- * `getItemCoordinates(i)` — A proxy for the corresponding `VirtualScroller` method. -->
|
|
471
|
-
</details>
|
|
472
|
-
|
|
473
|
-
## React
|
|
474
|
-
|
|
475
|
-
`virtual-scroller/react` component implements a `VirtualScroller` in a [React](https://reactjs.org/) environment.
|
|
476
|
-
|
|
477
|
-
The required properties are:
|
|
478
|
-
|
|
479
|
-
* `items` — The list of items.
|
|
480
|
-
|
|
481
|
-
* `itemComponent` — List item React component.
|
|
482
|
-
|
|
483
|
-
* The `itemComponent` will receive properties:
|
|
484
|
-
* `item: any` — The item object itself (an element of the `items` array).
|
|
485
|
-
* `state: any?` — Item's state. See the description of `itemStates` property of `VirtualScroller` `state` for more details.
|
|
486
|
-
* `setState(newState: any?)` — Can be called to replace item's state. See the description of `setItemState(i, newState)` function of `VirtualScroller` for more details.
|
|
487
|
-
* `onHeightDidChange(i)` — If an item's height could change after the initial render, this function should be called immediately after the item's height has potentially changed — in a `useLayoutEffect()`. See the description of `onItemHeightDidChange()` function of `VirtualScroller` for more details.
|
|
488
|
-
|
|
489
|
-
* For best performance, make sure that `itemComponent` is a `React.memo()` component or a `React.PureComponent`. Otherwise, list items will keep re-rendering themselves as the user scrolls because the containing `<VirtualScroller/>` component gets re-rendered on scroll.
|
|
490
|
-
|
|
491
|
-
#####
|
|
492
|
-
|
|
493
|
-
```js
|
|
494
|
-
import React from 'react'
|
|
495
|
-
import PropTypes from 'prop-types'
|
|
496
|
-
import VirtualScroller from 'virtual-scroller/react'
|
|
497
|
-
|
|
498
|
-
function Messages({ messages }) {
|
|
499
|
-
return (
|
|
500
|
-
<VirtualScroller
|
|
501
|
-
items={messages}
|
|
502
|
-
itemComponent={Message}
|
|
503
|
-
/>
|
|
504
|
-
)
|
|
505
|
-
}
|
|
506
|
-
|
|
507
|
-
function Message({ item: message }) {
|
|
508
|
-
const {
|
|
509
|
-
username,
|
|
510
|
-
date,
|
|
511
|
-
text
|
|
512
|
-
} = message
|
|
513
|
-
return (
|
|
514
|
-
<article>
|
|
515
|
-
<a href={`/users/${username}`}>
|
|
516
|
-
@{username}
|
|
517
|
-
</a>
|
|
518
|
-
<time dateTime={date.toISOString()}>
|
|
519
|
-
{date.toString()}
|
|
520
|
-
</time>
|
|
521
|
-
<p>
|
|
522
|
-
{text}
|
|
523
|
-
</p>
|
|
524
|
-
</article>
|
|
525
|
-
)
|
|
526
|
-
}
|
|
527
|
-
|
|
528
|
-
const message = PropTypes.shape({
|
|
529
|
-
username: PropTypes.string.isRequired,
|
|
530
|
-
date: PropTypes.instanceOf(Date).isRequired,
|
|
531
|
-
text: PropTypes.string.isRequired
|
|
532
|
-
})
|
|
533
|
-
|
|
534
|
-
Messages.propTypes = {
|
|
535
|
-
messages: PropTypes.arrayOf(message).isRequired
|
|
536
|
-
}
|
|
537
|
-
|
|
538
|
-
Message.propTypes = {
|
|
539
|
-
item: message.isRequired
|
|
540
|
-
}
|
|
541
|
-
```
|
|
785
|
+
* `updateState(stateUpdate: object)` — (optional) `setState()` parameter could be replaced with `updateState()` parameter. The only difference between the two is that `updateState()` gets called with just the portion of the state that is being updated while `setState()` gets called with the whole updated state object, so it's just a matter of preference.
|
|
542
786
|
|
|
543
|
-
|
|
544
|
-
<summary>Managing <code>itemComponent</code> state</summary>
|
|
787
|
+
For a usage example, see `./source/react/VirtualScroller.js`. The steps are:
|
|
545
788
|
|
|
546
|
-
|
|
789
|
+
* Create a `VirtualScroller` instance.
|
|
547
790
|
|
|
548
|
-
|
|
791
|
+
* Get the initial state value via `virtualScroller.getInitialState()`.
|
|
549
792
|
|
|
550
|
-
|
|
793
|
+
* Initialize the externally managed state with the initial state value.
|
|
551
794
|
|
|
552
|
-
|
|
795
|
+
* Define `getState()` and `updateState()` functions for reading or updating the externally managed state.
|
|
553
796
|
|
|
554
|
-
* `
|
|
797
|
+
* Call `virtualScroller.useState({ getState, updateState })`.
|
|
555
798
|
|
|
556
|
-
|
|
799
|
+
* "Render" the list and call `virtualScroller.start()`.
|
|
557
800
|
|
|
558
|
-
|
|
801
|
+
When using custom (external) state management, contrary to the default (internal) state management approach, the `render()` function parameter can't be passed to the `VirtualScroller` constructor. The reason is that `VirtualScroller` wouldn't know when exactly should it call such `render()` function because by design it can only be called right after the state has been updated, and `VirtualScroller` doesn't know when exactly does the state get updated, because state updates are done via an "external" `updateState()` function that could as well apply state updates "asynchronously" (after a short delay), like in React, rather than "synchronously" (immediately). That's why the `updateState()` function must re-render the list by itself, at any time it finds appropriate, and right after the list has been re-rendered, it must call `virtualScroller.onRender()`.
|
|
559
802
|
|
|
560
|
-
|
|
803
|
+
#### "Advanced" (rarely used) instance methods
|
|
561
804
|
|
|
562
|
-
|
|
805
|
+
* `onItemHeightDidChange(item)` — (advanced) If an item's height could've changed, this function should be called immediately after the item's height has potentially changed. The function re-measures the item's height (the item must still be rendered) and re-calculates `VirtualScroller` layout. An example for using this function would be having an "Expand"/"Collapse" button in a list item.
|
|
563
806
|
|
|
564
|
-
*
|
|
807
|
+
* There's also a convention that every change in an item's height must come as a result of changing the item's "state". See the descripton of `itemStates` and `itemHeights` properties of the `VirtualScroller` [state](#state) for more details.
|
|
565
808
|
|
|
566
|
-
* `
|
|
809
|
+
* Implementation-wise, calling `onItemHeightDidChange(item)` manually could be replaced with detecting item height changes automatically via [Resize Observer](https://caniuse.com/#search=Resize%20Observer) in some future version.
|
|
567
810
|
|
|
568
|
-
|
|
811
|
+
* `setItemState(item, itemState: any?)` — (advanced) Preserves a list item's "state" inside `VirtualScroller`'s built-in item "state" storage. See the descripton of `itemStates` property of the `VirtualScroller` [state](#state) for more details.
|
|
569
812
|
|
|
570
|
-
*
|
|
813
|
+
* A developer could use it to preserve an item's "state" if it could change. The reason is that offscreen items get unmounted and any unsaved state is lost in the process. If an item's state is correctly preserved, the item's latest-rendered appearance could be restored from that state when the item gets mounted again due to becoming visible again.
|
|
571
814
|
|
|
572
|
-
|
|
573
|
-
function ItemComponent({
|
|
574
|
-
item,
|
|
575
|
-
state,
|
|
576
|
-
setState,
|
|
577
|
-
onHeightDidChange
|
|
578
|
-
}) {
|
|
579
|
-
const [internalState, setInternalState] = useState(state)
|
|
815
|
+
* Calling `setItemState()` doesn't trigger a re-layout of `VirtualScroller` because changing a list item's state doesn't necessarily mean a change of its height, so a re-layout might not be required. If an item's height did change as a result of changing its state, then `VirtualScroller` layout must be updated, and to do that, one should call `onItemHeightDidChange(item)` right after the change in the item's state has been reflected on screen.
|
|
580
816
|
|
|
581
|
-
|
|
817
|
+
* `getItemScrollPosition(item): number?` — (advanced) Returns an item's scroll position inside the scrollable container. Returns `undefined` if any of the items before this item haven't been rendered yet.
|
|
582
818
|
|
|
583
|
-
|
|
584
|
-
if (hasMounted.current) {
|
|
585
|
-
setState(internalState)
|
|
586
|
-
onHeightDidChange()
|
|
587
|
-
} else {
|
|
588
|
-
// Skip the initial mount.
|
|
589
|
-
// Only handle the changes of the `internalState`.
|
|
590
|
-
hasMounted.current = true
|
|
591
|
-
}
|
|
592
|
-
}, [internalState])
|
|
819
|
+
<!-- * `getItemCoordinates(item): object` — Returns coordinates of item with index `i` relative to the "scrollable container": `top` is the top offset of the item relative to the start of the "scrollable container", `bottom` is the top offset of the item's bottom edge relative to the start of the "scrollable container", `height` is the item's height. -->
|
|
593
820
|
|
|
594
|
-
|
|
595
|
-
<section>
|
|
596
|
-
<h1>
|
|
597
|
-
{item.title}
|
|
598
|
-
</h1>
|
|
599
|
-
{internalState && internalState.expanded &&
|
|
600
|
-
<p>{item.text}</p>
|
|
601
|
-
}
|
|
602
|
-
<button onClick={() => {
|
|
603
|
-
setInternalState({
|
|
604
|
-
...internalState,
|
|
605
|
-
expanded: !expanded
|
|
606
|
-
})
|
|
607
|
-
}}>
|
|
608
|
-
{internalState && internalState.expanded ? 'Show less' : 'Show more'}
|
|
609
|
-
</button>
|
|
610
|
-
</section>
|
|
611
|
-
)
|
|
612
|
-
}
|
|
613
|
-
```
|
|
821
|
+
* `updateLayout()` — (advanced) Triggers a re-layout of `VirtualScroller`. It's what's called every time on page scroll or window resize. You most likely won't ever need to call this method manually. Still, one could imagine a hypothetical case when a developer might want to call this method. For example, when the list's top position changes not as a result of scrolling the page or resizing the window, but rather because of some unrelated "dynamic" changes of the page's content. For example, if some DOM elements above the list are removed (like a closeable "info" notification element) or collapsed (like an "accordion" panel), then the list's top position changes, which means that now some of the previoulsy shown items might go off screen, revealing an unrendered blank area to the user. The area would be blank because the "shift" of the list's vertical position happened not as a result of the user scrolling the page or resizing the window, and, therefore, it won't be registered by the `VirtualScroller` component. To fix that, a developer might want to trigger a re-layout manually.
|
|
614
822
|
</details>
|
|
615
823
|
|
|
616
824
|
#####
|
|
617
825
|
|
|
618
826
|
<details>
|
|
619
|
-
<summary
|
|
827
|
+
<summary>Example: implement <code>virtual-scroller/dom</code> component using the "core" <code>VirtualScroller</code> component
|
|
828
|
+
</summary>
|
|
620
829
|
|
|
621
830
|
#####
|
|
622
831
|
|
|
623
|
-
Note: When passing any core `VirtualScroller` class options, only the initial values of those options will be applied, and any updates to those options will be ignored. That's because those options are only passed to the `VirtualScroller` base class constructor at initialization time. That means that none of those options should depend on any variable state or props. For example, if `getColumnsCount()` parameter was defined as `() => props.columnsCount`, then, if the `columnsCount` property changes, the underlying `VirtualScroller` instance won't see that change.
|
|
624
|
-
|
|
625
|
-
* `itemComponentProps: object` — The props passed to `itemComponent`.
|
|
626
|
-
|
|
627
|
-
* `getColumnsCount(): number` — The `getColumnsCount()` option of `VirtualScroller`.
|
|
628
|
-
|
|
629
|
-
* `as` — A component used as a container for the list items. Is `"div"` by default.
|
|
630
|
-
|
|
631
|
-
* `initialState: object` — The initial state for `VirtualScroller`. For example, one could snapshot the `<VirtualScroller/>` state before it is unmounted and then pass it back as the `state` property when the `<VirtualScroller/>` is re-mounted, like in the cases when navigating "Back" to a page in a web browser. This is simply the `state` option of `VirtualScroller` constructor.
|
|
632
|
-
|
|
633
|
-
* `getInitialItemState: (item: any) => any?` — Creates the initial state for an item. It can be used to populate the default initial states for list items. By default, an item's state is `undefined`. This is simply the `getInitialItemState` option of `VirtualScroller` constructor.
|
|
634
|
-
|
|
635
|
-
<!-- * `initialCustomState: object` — (advanced) The initial "custom" state for `VirtualScroller`: the `initialCustomState` option of `VirtualScroller`. It can be used to initialize the "custom" part of `VirtualScroller` state in cases when `VirtualScroller` state is used to store some "custom" list state. -->
|
|
636
|
-
|
|
637
|
-
* `onStateChange(newState: object, previousState: object?)` — The `onStateChange` option of `VirtualScroller`. Could be used to restore a `VirtualScroller` state on "Back" navigation:
|
|
638
|
-
|
|
639
832
|
```js
|
|
640
|
-
import
|
|
641
|
-
readVirtualScrollerState,
|
|
642
|
-
saveVirtualScrollerState
|
|
643
|
-
} from './globalStorage'
|
|
644
|
-
|
|
645
|
-
function Example() {
|
|
646
|
-
const virtualScrollerState = useRef()
|
|
833
|
+
import VirtualScroller from 'virtual-scroller'
|
|
647
834
|
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
})
|
|
835
|
+
const items = [
|
|
836
|
+
{ title: 'Apple' },
|
|
837
|
+
{ title: 'Banana' },
|
|
838
|
+
{ title: 'Cranberry' }
|
|
839
|
+
]
|
|
654
840
|
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
state={hasUserNavigatedBack ? readVirtualScrollerState() : undefined}
|
|
660
|
-
onStateChange={state => virtualScrollerState.current = state}
|
|
661
|
-
/>
|
|
662
|
-
)
|
|
841
|
+
function renderItem(item) {
|
|
842
|
+
const div = document.createElement('div')
|
|
843
|
+
div.innerText = item.title
|
|
844
|
+
return div
|
|
663
845
|
}
|
|
664
|
-
```
|
|
665
846
|
|
|
666
|
-
|
|
847
|
+
const container = document.getElementById('list')
|
|
667
848
|
|
|
668
|
-
|
|
849
|
+
function render(state, prevState) {
|
|
850
|
+
const {
|
|
851
|
+
items,
|
|
852
|
+
beforeItemsHeight,
|
|
853
|
+
afterItemsHeight,
|
|
854
|
+
firstShownItemIndex,
|
|
855
|
+
lastShownItemIndex
|
|
856
|
+
} = state
|
|
669
857
|
|
|
670
|
-
|
|
671
|
-
|
|
858
|
+
// Set `paddingTop` and `paddingBottom` on the container element:
|
|
859
|
+
// it emulates the non-visible items as if they were rendered.
|
|
860
|
+
container.style.paddingTop = Math.round(beforeItemsHeight) + 'px'
|
|
861
|
+
container.style.paddingBottom = Math.round(afterItemsHeight) + 'px'
|
|
672
862
|
|
|
673
|
-
|
|
863
|
+
// Perform an intelligent "diff" re-render as the user scrolls the page.
|
|
864
|
+
// This also requires that the list of `items` hasn't been changed.
|
|
865
|
+
// On initial render, `prevState` is `undefined`.
|
|
866
|
+
if (prevState && items === prevState.items) {
|
|
674
867
|
|
|
675
|
-
|
|
868
|
+
// Remove no longer visible items.
|
|
869
|
+
let i = prevState.lastShownItemIndex
|
|
870
|
+
while (i >= prevState.firstShownItemIndex) {
|
|
871
|
+
if (i >= firstShownItemIndex && i <= lastShownItemIndex) {
|
|
872
|
+
// The item is still visible.
|
|
873
|
+
} else {
|
|
874
|
+
// The item is no longer visible. Remove it.
|
|
875
|
+
container.removeChild(container.childNodes[i - prevState.firstShownItemIndex])
|
|
876
|
+
}
|
|
877
|
+
i--
|
|
878
|
+
}
|
|
676
879
|
|
|
677
|
-
|
|
880
|
+
// Add newly visible items.
|
|
881
|
+
let prependBefore = container.firstChild
|
|
882
|
+
let i = firstShownItemIndex
|
|
883
|
+
while (i <= lastShownItemIndex) {
|
|
884
|
+
if (i >= prevState.firstShownItemIndex && i <= prevState.lastShownItemIndex) {
|
|
885
|
+
// The item is already being rendered.
|
|
886
|
+
// Next items will be appended rather than prepended.
|
|
887
|
+
prependBefore = undefined
|
|
888
|
+
} else {
|
|
889
|
+
if (prependBefore) {
|
|
890
|
+
container.insertBefore(renderItem(items[i]), prependBefore)
|
|
891
|
+
} else {
|
|
892
|
+
container.appendChild(renderItem(items[i]))
|
|
893
|
+
}
|
|
894
|
+
}
|
|
895
|
+
i++
|
|
896
|
+
}
|
|
897
|
+
}
|
|
898
|
+
else {
|
|
899
|
+
// Re-render the list from scratch.
|
|
900
|
+
while (container.firstChild) {
|
|
901
|
+
container.removeChild(container.firstChild)
|
|
902
|
+
}
|
|
903
|
+
let i = firstShownItemIndex
|
|
904
|
+
while (i <= lastShownItemIndex) {
|
|
905
|
+
container.appendChild(renderItem(items[i]))
|
|
906
|
+
i++
|
|
907
|
+
}
|
|
908
|
+
}
|
|
909
|
+
}
|
|
678
910
|
|
|
679
|
-
|
|
911
|
+
const virtualScroller = new VirtualScroller(() => element, items, { render })
|
|
680
912
|
|
|
681
|
-
|
|
913
|
+
// Start VirtualScroller listening for scroll events.
|
|
914
|
+
virtualScroller.start()
|
|
682
915
|
|
|
683
|
-
|
|
916
|
+
// Stop VirtualScroller listening for scroll events
|
|
917
|
+
// when the user navigates to another page:
|
|
918
|
+
// router.onPageUnload(virtualScroller.stop)
|
|
919
|
+
```
|
|
920
|
+
</details>
|
|
684
921
|
|
|
685
|
-
|
|
922
|
+
## Updating Items
|
|
686
923
|
|
|
687
|
-
|
|
924
|
+
If the list represents a social media feed, it has to be updated periodically as new posts get published.
|
|
688
925
|
|
|
689
|
-
|
|
926
|
+
A user looking at the feed in real time always "knows" which posts are new and which ones are old. Analogous, the "virtual scroller" also has to have a way of "knowing" which posts are new and which ones are old, so that it could correctly "carry over" its measurements and calculations from the old `items` to the new `items` without any ["content jumping"](https://css-tricks.com/content-jumping-avoid/) glitches.
|
|
690
927
|
|
|
691
|
-
|
|
692
|
-
If one considers that `useEffect()` hooks [run in the order from child element to parent element](https://stackoverflow.com/questions/58352375/what-is-the-correct-order-of-execution-of-useeffect-in-react-parent-and-child-co), one can conclude that there's no way that the application's `useLayoutEffect()` hook could run before the `useLayoutEffect()` hook in a `<VirtualScroller/>` component. Therefore, there's only one option to make it work, and that would be only rendering `<VirtualScroller/>` after the scrollable container has mounted:
|
|
928
|
+
The most obvious way of telling old items from new ones would be direct comparison using `===` operator.
|
|
693
929
|
|
|
694
930
|
```js
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
function ListContainer() {
|
|
699
|
-
return (
|
|
700
|
-
<div id="ListContainer">
|
|
701
|
-
<List/>
|
|
702
|
-
</div>
|
|
703
|
-
)
|
|
931
|
+
function isOldItem(item) {
|
|
932
|
+
return prevItems.some(_ => _ === item)
|
|
704
933
|
}
|
|
934
|
+
```
|
|
705
935
|
|
|
706
|
-
|
|
707
|
-
const [scrollableContainerHasMounted, setScrollableContainerHasMounted] = useState()
|
|
708
|
-
|
|
709
|
-
useLayoutEffect(() => {
|
|
710
|
-
setScrollableContainerHasMounted(true)
|
|
711
|
-
}, [])
|
|
712
|
-
|
|
713
|
-
if (!scrollableContainerHasMounted) {
|
|
714
|
-
return null
|
|
715
|
-
}
|
|
716
|
-
|
|
717
|
-
return (
|
|
718
|
-
<VirtualScroller
|
|
719
|
-
items={...}
|
|
720
|
-
itemComponent={...}
|
|
721
|
-
getScrollableContainer={getScrollableContainer}
|
|
722
|
-
/>
|
|
723
|
-
)
|
|
724
|
-
}
|
|
936
|
+
And it would work in case of appending or prepending items:
|
|
725
937
|
|
|
726
|
-
|
|
727
|
-
|
|
938
|
+
```js
|
|
939
|
+
async function updateFeed() {
|
|
940
|
+
const lastItem = items[items.length - 1]
|
|
941
|
+
const nextItems = await fetch(`https://social.com/feed?after=${lastItem.id}`)
|
|
942
|
+
items = items.concat(nextItems)
|
|
943
|
+
virtualScroller.setItems(items)
|
|
728
944
|
}
|
|
729
945
|
```
|
|
730
946
|
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
947
|
+
But it wouldn't work in a more simple case of just re-creating all items every time:
|
|
948
|
+
|
|
949
|
+
```js
|
|
950
|
+
async function updateFeed() {
|
|
951
|
+
items = await fetch('https://social.com/feed')
|
|
952
|
+
virtualScroller.setItems(items)
|
|
735
953
|
}
|
|
736
954
|
```
|
|
737
|
-
-->
|
|
738
|
-
</details>
|
|
739
955
|
|
|
740
|
-
|
|
956
|
+
In such case, a developer should pass a `getItemId(item)` parameter to the "virtual scroller". This way, the "virtual scroller" will be able to tell new items from old ones, even if their "object reference" has changed.
|
|
741
957
|
|
|
742
|
-
|
|
743
|
-
<summary><code><VirtualScroller/></code> instance methods</summary>
|
|
958
|
+
With this, when new items are appended to the list, the page scroll position will remain unchanged and there'll be no ["content jumping"](https://css-tricks.com/content-jumping-avoid/). Same goes for prepending new items to the list: when new items are prepended to the list, the page scroll position will remain unchanged. But in the latter case, the prepended items will also push the previously-existing ones downwards, and to the user it would look as if the scroll position has "jumped", even though technically it hasn't. To fix that, pass `preserveScrollPositionOnPrependItems: true` option to the "virtual scroller", and it will automatically adjust the scroll position right after prepending new items so that to the user it looks as if the scroll position is correctly "preserved".
|
|
744
959
|
|
|
745
|
-
|
|
960
|
+
<!-- For implementing "infinite scroll" lists, a developer could also use [`on-scroll-to`](https://gitlab.com/catamphetamine/on-scroll-to) component. -->
|
|
746
961
|
|
|
747
962
|
<!--
|
|
748
|
-
* `renderItem(i)` — Calls `.forceUpdate()` on the `itemComponent` instance for the item with index `i`. Does nothing if the item isn't currently rendered. Is only supported for `itemComponent`s that are `React.Component`s. The `i` item index argument could be replaced with the item object itself, in which case `<VirtualScroller/>` will get `i` as `items.indexOf(item)`.
|
|
749
|
-
-->
|
|
750
|
-
|
|
751
|
-
<!-- * `getItemCoordinates(i)` — A proxy for the corresponding `VirtualScroller` method. -->
|
|
752
|
-
|
|
753
|
-
* `updateLayout()` — A proxy for the corresponding `VirtualScroller` method.
|
|
754
|
-
</details>
|
|
755
|
-
|
|
756
|
-
## Dynamically Loaded Lists
|
|
757
|
-
|
|
758
|
-
All previous examples described cases with static `items` list. When there's a need to update the `items` list dynamically, one can use `virtualScroller.setItems(newItems)` instance method. For example:
|
|
759
|
-
* When the user clicks "Show previous items" button, the `newItems` argument should be `previousItems.concat(currentlyShownItems)`.
|
|
760
|
-
* When the user clicks "Show next items" button, the `newItems` argument should be `currentlyShownItems.concat(nextItems)`.
|
|
761
|
-
|
|
762
963
|
<details>
|
|
763
964
|
<summary>Find out what are "incremental" and "non-incremental" items updates, and why "incremental" updates are better.</summary>
|
|
764
965
|
|
|
@@ -774,84 +975,105 @@ For example, suppose a user navigates to a page where a list of `items: object[]
|
|
|
774
975
|
|
|
775
976
|
Another example. Suppose a user navigates to a page where they can filter a huge list by a query entered in a search bar. In that case, when the user edits the query in the search bar, `VirtualScroller.setItems()` method is called with a list of filtered items, and the entire list is rerendered from scratch. In this case, it's ok to reset the `VirtualScroller` state and the scroll position.
|
|
776
977
|
|
|
777
|
-
<!--
|
|
778
|
-
`virtualScroller.setItems(newItems)` also receives an optional second `options` argument having shape `{ state }` where `state` can be used for updating "custom state" previously set in `getInitialState(customState)` and can be an `object` or a function `(previousState, { prependedCount, appendedCount }) => object`. If the items update is not incremental (i.e. if `newItems` doesn't contain previous `items`) then both `prependedCount` and `appendedCount` will be `undefined`.
|
|
779
|
-
-->
|
|
780
|
-
|
|
781
978
|
When new items are appended to the list, the page scroll position remains unchanged. Same's for prepending new items to the list: the scroll position of the page stays the same, resulting in the list "jumping" down when new items get prepended. To fix that, pass `preserveScrollPositionOnPrependItems: true` option to the `VirtualScroller`. When using `virtual-scroller/dom` component, pass that option when creating a new instance, and when using `virtual-scroller/react` React component, pass `preserveScrollPositionOnPrependItems` property.
|
|
782
979
|
|
|
783
980
|
For implementing "infinite scroll" lists, a developer could also use [`on-scroll-to`](https://gitlab.com/catamphetamine/on-scroll-to) component.
|
|
784
981
|
</details>
|
|
982
|
+
-->
|
|
785
983
|
|
|
786
984
|
## Grid Layout
|
|
787
985
|
|
|
788
|
-
To display items using a "grid" layout
|
|
986
|
+
To display items using a "grid" layout — i.e. with multiple columns in each row — supply a `getColumnsCount()` parameter to the "virtual scroller".
|
|
789
987
|
|
|
790
|
-
For example, to show a three-column layout
|
|
988
|
+
For example, to only show a three-column layout if the screen is wider than `1280px`:
|
|
791
989
|
|
|
792
990
|
```js
|
|
793
|
-
function getColumnsCount(
|
|
794
|
-
// The `
|
|
795
|
-
|
|
991
|
+
function getColumnsCount(scrollableContainer) {
|
|
992
|
+
// The `scrollableContainer` argument provides a `.getWidth()` method.
|
|
993
|
+
// In the most common case, `scrollableContainer` is the web browser window.
|
|
994
|
+
if (scrollableContainer.getWidth() > 1280) {
|
|
796
995
|
return 3
|
|
797
996
|
}
|
|
798
997
|
return 1
|
|
799
998
|
}
|
|
800
|
-
|
|
801
|
-
<VirtualScroller getColumnsCount={getColumnsCount} .../>
|
|
802
999
|
```
|
|
803
1000
|
|
|
804
1001
|
```css
|
|
805
|
-
.
|
|
1002
|
+
.list {
|
|
806
1003
|
display: flex;
|
|
807
1004
|
flex-wrap: wrap;
|
|
808
1005
|
}
|
|
809
1006
|
|
|
810
|
-
.item {
|
|
1007
|
+
.list-item {
|
|
811
1008
|
flex-basis: 33.333333%;
|
|
812
1009
|
box-sizing: border-box;
|
|
813
1010
|
}
|
|
814
1011
|
|
|
815
1012
|
@media screen and (max-width: 1280px) {
|
|
816
|
-
.item {
|
|
1013
|
+
.list-item {
|
|
817
1014
|
flex-basis: 100%;
|
|
818
1015
|
}
|
|
819
1016
|
}
|
|
820
1017
|
```
|
|
821
1018
|
|
|
822
|
-
##
|
|
1019
|
+
## Tips & Tricks
|
|
823
1020
|
|
|
824
|
-
###
|
|
1021
|
+
### Adding Spacing Between List Items
|
|
825
1022
|
|
|
826
|
-
|
|
1023
|
+
To add some vertical spacing between the list items, one could add `margin-top` / `margin-bottom` or `border-top` / `border-bottom` on the list item elements. Before doing so, read the couple of sections below to avoid issues with "margin collapse" or unintended side-effects of `:first-child` / `:last-child` CSS selectors.
|
|
827
1024
|
|
|
828
|
-
###
|
|
1025
|
+
### Using `margin` on List Items Correctly
|
|
829
1026
|
|
|
830
|
-
|
|
1027
|
+
CSS has a pretty weird and unintuitive feature called ["margin collapse"](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing): if two adjacent sibling elements both have a margin, or if the first/last child and its parent both have a margin, then those two margins will be combined either as `margin1 + margin2` or `Math.max(margin1, margin2)`, depending on the circumstances, and the latter is the essense of the issue.
|
|
1028
|
+
|
|
1029
|
+
For example, if a first child element has `margin-top` and no `padding-top` or `border-top`, and the parent has `margin-top`, then the margins of the child and the parent will be combined as `Math.max(margin1, margin2)`.
|
|
1030
|
+
|
|
1031
|
+
And if a first child element has `margin-top` and also `padding-top` or `border-top`, and the parent has `margin-top`, then the margins of the child and the parent will be combined as `margin1 + margin2`.
|
|
1032
|
+
|
|
1033
|
+
Weird and unexpected. And it's not limited to just having or not having `padding` or `border` — the exact rules are much more [convoluted](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing).
|
|
1034
|
+
|
|
1035
|
+
So why does this become an issue with the "virtual scroller"? It's because "virtual scroller" will add or remove `padding-top` and `padding-bottom` to the list element (which is the "parent"), changing the formula of how the list's `margin` is combined with the list items' `margin`.
|
|
1036
|
+
|
|
1037
|
+
The result will be ["content jumping"](https://css-tricks.com/content-jumping-avoid/) when scrolling to or past the top or the bottom of the list.
|
|
1038
|
+
|
|
1039
|
+
To avoid such issues, when setting `margin` on list items, do any of the following:
|
|
1040
|
+
* Set `padding-top` and `padding-bottom` on the list element
|
|
1041
|
+
* Set `border-top` and `border-bottom` on the list element
|
|
1042
|
+
* Set `margin-top` and `margin-bottom` on list items
|
|
1043
|
+
* Reset `margin-top` on the first item of the list
|
|
1044
|
+
* Reset `margin-bottom` on the last item of the list
|
|
1045
|
+
|
|
1046
|
+
Here's an example of how to set `margin` on list items correctly:
|
|
831
1047
|
|
|
832
1048
|
```css
|
|
833
|
-
/*
|
|
834
|
-
|
|
1049
|
+
/* Adds a `20px` vertical spacing above and below the list. */
|
|
1050
|
+
.list {
|
|
1051
|
+
margin-top: 20px;
|
|
1052
|
+
margin-bottom: 20px;
|
|
1053
|
+
}
|
|
1054
|
+
/* Adds a `10px` vertical spacing between list items. */
|
|
835
1055
|
.list-item {
|
|
836
|
-
margin: 10px;
|
|
1056
|
+
margin-top: 10px;
|
|
1057
|
+
margin-bottom: 10px;
|
|
837
1058
|
}
|
|
838
|
-
/* Fixes margin
|
|
1059
|
+
/* Fixes "margin collapse" issue for the first item. */
|
|
839
1060
|
.list-item:first-child {
|
|
840
1061
|
margin-top: 0;
|
|
841
1062
|
}
|
|
842
|
-
/* Fixes margin
|
|
1063
|
+
/* Fixes "margin collapse" issue for the last item. */
|
|
843
1064
|
.list-item:last-child {
|
|
844
|
-
margin-
|
|
1065
|
+
margin-bottom: 0;
|
|
845
1066
|
}
|
|
846
1067
|
```
|
|
847
1068
|
|
|
848
|
-
###
|
|
1069
|
+
### Using `:first-child` or `:last-child` CSS Selectors
|
|
849
1070
|
|
|
850
|
-
When
|
|
1071
|
+
When using `:first-child` or `:last-child` CSS selectors to add style to the first or last item in the list, one should check that such added style doesn't affect the item's `height`, i.e. one should not add any `border` or `padding` in a `:first-child` or `:last-child` CSS selector, otherwise the list items will "jump" by the amount of added `height` during scrolling.
|
|
851
1072
|
|
|
852
|
-
|
|
1073
|
+
Here's an example of a `:first-child`/`:last-child` style that will not work correctly with `VirtualScroller`:
|
|
853
1074
|
|
|
854
1075
|
```css
|
|
1076
|
+
/* Adds a 1px black border around each item in the list. Will not work correctly with `VirtualScroller`. */
|
|
855
1077
|
.list-item {
|
|
856
1078
|
border-bottom: 1px solid black;
|
|
857
1079
|
}
|
|
@@ -860,20 +1082,47 @@ An example of a `:first-child`/`:last-child` style that will not work correctly
|
|
|
860
1082
|
}
|
|
861
1083
|
```
|
|
862
1084
|
|
|
863
|
-
###
|
|
1085
|
+
### "Find on page" / Keyboard Focus Management / Text-To-Speech
|
|
1086
|
+
|
|
1087
|
+
Because "virtual scroller" only renders the items that're currently visible on screen, native web-browser features such as "Find on page" across the list items, shifting focus from one item to another using a `Tab` key, reading out loud the entire list contents using a "screen reader" — all those features simply can't work.
|
|
1088
|
+
|
|
1089
|
+
"Find on page" though is perhaps the simplest one of them to be able to work around: one could add a custom "🔍 Search" input field somewhere at the top of the list where a user would be able to input a search query and then the application would manually filter the items array and update the list to show only the matched ones.
|
|
1090
|
+
|
|
1091
|
+
### Image Dimensions
|
|
1092
|
+
|
|
1093
|
+
`VirtualScroller` measures item heights as soon as the items have rendered for the first time, and later uses those measurements to determine exactly which items should currently be visible when the user scrolls. This means that dynamic-height elements like `<img/>`s should have their dimensions fixed from the very start. For example, when rendering a simple `<img src="..."/>` element without specifying `width` and `height`, initially it renders itself with zero width and zero height, and only after the image file header has been downloaded and parsed does it resize itself to the actual size of the image. This would result in `VirtualScroller` initially measuring the image inside the list item as zero-width and zero-height, which will later cause a "jump of content" during scrolling because the item's height wasn't measured correctly. To avoid this bug, any `<img/>`s that're rendered inside `VirtualScroller` items must define their dimensions from the start, for example, using any of the following ways:
|
|
1094
|
+
|
|
1095
|
+
* Set explicit `width` and `height` in `<img/>` attributes or via CSS.
|
|
1096
|
+
|
|
1097
|
+
* Set `width: 100%` on the `<img/>` element and lock the [aspect ratio](https://www.w3schools.com/howto/howto_css_aspect_ratio.asp) by doing the following:
|
|
1098
|
+
* Wrap the `<img/>` element in a parent `<div/>` which has `position: relative` and `padding-bottom: ${100/aspectRatio}%`.
|
|
1099
|
+
* Set `position: absolute` on the `<img/>` element.
|
|
1100
|
+
|
|
1101
|
+
### How It Handles Window Resize
|
|
864
1102
|
|
|
865
|
-
|
|
1103
|
+
`VirtualScroller` automatically handles window resize. Here's a short technical description of how it does that internally for those who're curious. Anyone else should just skip this section.
|
|
866
1104
|
|
|
867
|
-
|
|
1105
|
+
When the items container width changes — for example, as a result of a window resize — any previously-measured item heights have to be reset because they're no longer relevant:
|
|
868
1106
|
|
|
869
|
-
*
|
|
1107
|
+
* If item elements include multi-line text content, the count of text lines might've changed because there's more or less width available now.
|
|
870
1108
|
|
|
871
|
-
|
|
1109
|
+
* Some CSS [`@media()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) rules might have been added or removed, affecting the items layout.
|
|
1110
|
+
|
|
1111
|
+
If a resize happens when the list is showing items starting from the `N`-th one, all of the `N - 1` previous items' heights have to be remeasured too. Not right now though, because those items are currently not visible. They will be remeasured only if the user scrolls up to them. Until then, `VirtualScroller` will keep using the previously-measured item heights which, although no longer relevant, can't simply be thrown away without replacing them with the new measurements. So if the user will be scrolling up, those "stale" item heights will be gradually replaced with newly-measured ones, and the scroll position will be automatically corrected to avoid ["content jumping"](https://css-tricks.com/content-jumping-avoid/) during scrolling.
|
|
1112
|
+
|
|
1113
|
+
The "stale" item heights mentioned above are stored in `VirtualScroller` state under `beforeResize` key:
|
|
1114
|
+
|
|
1115
|
+
* `itemHeights: number[]`
|
|
1116
|
+
* `verticalSpacing: number`
|
|
1117
|
+
* `columnsCount: number`
|
|
1118
|
+
|
|
1119
|
+
<!--
|
|
1120
|
+
(I briefly revisited this seciton and it seems like this edge case is no longer reproduced in Chrome. Hence, commented out this edge case description)
|
|
872
1121
|
|
|
873
|
-
|
|
1122
|
+
This automatic scroll position correction works fine in all cases except for the single one that I've discovered.
|
|
874
1123
|
|
|
875
1124
|
<details>
|
|
876
|
-
<summary>
|
|
1125
|
+
<summary>See an example of a single edge case when the automatic scroll position correction doesn't seem to work.</summary>
|
|
877
1126
|
|
|
878
1127
|
#####
|
|
879
1128
|
|
|
@@ -931,26 +1180,17 @@ For now, I don't see it as a bug that would be worth fixing. The user could just
|
|
|
931
1180
|
</details>
|
|
932
1181
|
|
|
933
1182
|
#####
|
|
1183
|
+
-->
|
|
934
1184
|
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
* `itemHeights: number[]`
|
|
938
|
-
* `verticalSpacing: number`
|
|
939
|
-
* `columnsCount: number`
|
|
940
|
-
|
|
941
|
-
### `<tbody/>`
|
|
942
|
-
|
|
943
|
-
Due to the [inherent limitations](https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1) of the `<tbody/>` HTML tag, when a `<tbody/>` is used as a container for the list items, the `VirtualScroller` code has to use a workaround involving CSS variables, and CSS variables aren't supported in Internet Explorer, so using a `<tbody/>` as a list items container won't work in Internet Explorer: in such case, `VirtualScroller` renders in "bypass" mode (render all items). In all browsers other than Internet Explorer it works as usual.
|
|
944
|
-
|
|
945
|
-
### Search, focus management.
|
|
1185
|
+
### Using `<tbody/>` in Internet Explorer
|
|
946
1186
|
|
|
947
|
-
Due to
|
|
1187
|
+
Due to the [inherent limitations](https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1) of the `<tbody/>` HTML tag, when a `<tbody/>` is used as a container for the list items, the `VirtualScroller` ["core"](#core) component has to use a workaround that is based on CSS variables, and CSS variables aren't supported in Internet Explorer. Because of that, using a `<tbody/>` as a list items container won't work in Internet Explorer. In that case, `VirtualScroller` will render itself in "bypass" mode, i.e. it will just render all items from the start, without any "virtualization".
|
|
948
1188
|
|
|
949
|
-
### "Item index N height changed unexpectedly" warning on page load in
|
|
1189
|
+
### "Item index N height changed unexpectedly" warning on page load in development mode
|
|
950
1190
|
|
|
951
|
-
`VirtualScroller` assumes there'd be no "unexpected" (unannounced) changes in items' heights. If an item's height changes for whatever reason, a developer must announce it immediately by calling `.onItemHeightDidChange(
|
|
1191
|
+
`VirtualScroller` assumes there'd be no "unexpected" (unannounced) changes in items' heights. If an item's height changes for whatever reason, a developer must announce it immediately by calling `.onItemHeightDidChange(item)` instance method.
|
|
952
1192
|
|
|
953
|
-
There might still be cases outside of a developer's control when items' heights do change "unexpectedly". One such case is when running an application in "development" mode and the CSS styles or custom fonts haven't loaded yet, resulting in different item height measurements "before" and "after" the page has fully loaded.
|
|
1193
|
+
There might still be cases outside of a developer's control when items' heights do change "unexpectedly". One such case is when running an application in "development" mode in a bundler such as Webpack, and the CSS styles or custom fonts haven't loaded yet, resulting in different item height measurements "before" and "after" the page has fully loaded. Note that this is not a bug of `VirtualScroller`. It's just an inconvenience introduced by a bundler such as Webpack, and only in "development" mode, i.e. it won't happen in production.
|
|
954
1194
|
|
|
955
1195
|
<details>
|
|
956
1196
|
|
|
@@ -996,14 +1236,14 @@ export default function suppressVirtualScrollerDevModePageLoadWarnings() {
|
|
|
996
1236
|
```
|
|
997
1237
|
</details>
|
|
998
1238
|
|
|
999
|
-
###
|
|
1239
|
+
### Only the first item is rendered on page load in development mode
|
|
1000
1240
|
|
|
1001
1241
|
<details>
|
|
1002
1242
|
<summary>See the description of this very rare dev mode bug.</summary>
|
|
1003
1243
|
|
|
1004
1244
|
#####
|
|
1005
1245
|
|
|
1006
|
-
`VirtualScroller` calculates the shown item indexes when
|
|
1246
|
+
`VirtualScroller` calculates the shown item indexes when the list gets initially rendered. But if the page styles are applied after the list is initially rendered — for example, if styles are applied "asynchronously" via javascript, like Webpack does it in development mode with its dynamic `style-loader` — then the list might not render correctly and will only show the first item. The reason for that is because calling `.getBoundingClientRect()` on the list items container DOM element returns an "incorrect" `top` position at the time of the initial render because the styles haven't been applied yet, and so `VirtualScroller` thinks that it's not even visible on screen.
|
|
1007
1247
|
|
|
1008
1248
|
For example, consider a page:
|
|
1009
1249
|
|
|
@@ -1014,9 +1254,20 @@ For example, consider a page:
|
|
|
1014
1254
|
</div>
|
|
1015
1255
|
```
|
|
1016
1256
|
|
|
1017
|
-
|
|
1257
|
+
```css
|
|
1258
|
+
.sidebar {
|
|
1259
|
+
position: fixed;
|
|
1260
|
+
width: 25%;
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
main {
|
|
1264
|
+
margin-left: 25%;
|
|
1265
|
+
}
|
|
1266
|
+
```
|
|
1267
|
+
|
|
1268
|
+
The sidebar is styled as `position: fixed`, but until the page styles have been applied, the sidebar is gonna be rendered like a regular `<div/>`, meaning that the `<main/>` element will initially be rendered below the entire sidebar block, causing the `<main/>` element to think that it's not even visible on screen, and so the list will only render the first item. Then, when page styles have been loaded and applied, the sidebar becomes `position: fixed`, and it no longer pushes the `<main/>` element downwards, making the `<main/>` element start at the top of the page, but `VirtualScroller` has already been initially rendered and it won't re-render itself until it has a reason to do so — that is when the user scrolls or the window is resized.
|
|
1018
1269
|
|
|
1019
|
-
This type of a bug
|
|
1270
|
+
This type of a bug won't occur in production, but it could appear in development mode when using Webpack. `VirtualScroller` works around this development-mode bug by periodically calling `.getBoundingClientRect()` on the list items container DOM element (every second) to check if the `top` coordinate of the list has changed unexpectedly as a result of applying CSS styles, and if it has then it recalculates the currently-visible item indexes and re-renders the list.
|
|
1020
1271
|
</details>
|
|
1021
1272
|
|
|
1022
1273
|
## Debug
|
|
@@ -1053,7 +1304,7 @@ new VirtualScroller(getItemsContainerElement, items, {
|
|
|
1053
1304
|
|
|
1054
1305
|
## CDN
|
|
1055
1306
|
|
|
1056
|
-
|
|
1307
|
+
To include this library directly via a `<script/>` tag on a page, one can use any npm CDN service, e.g. [unpkg.com](https://unpkg.com) or [jsdelivr.com](https://jsdelivr.com)
|
|
1057
1308
|
|
|
1058
1309
|
```html
|
|
1059
1310
|
<!-- Core. -->
|
|
@@ -1078,15 +1329,11 @@ One can use any npm CDN service, e.g. [unpkg.com](https://unpkg.com) or [jsdeliv
|
|
|
1078
1329
|
<!--
|
|
1079
1330
|
## Possible enhancements
|
|
1080
1331
|
|
|
1081
|
-
* Use [Resize Observer](https://caniuse.com/#search=Resize%20Observer) instead of calling `.onItemHeightDidChange(
|
|
1332
|
+
* Use [Resize Observer](https://caniuse.com/#search=Resize%20Observer) instead of calling `.onItemHeightDidChange(item)` manually.
|
|
1082
1333
|
|
|
1083
1334
|
* Currently React `<VirtualScroller/>` passes `onHeightDidChange()` property and provides `.renderItem(i)` instance method. Both these features could be replaced with doing it internally in `VirtualScroller`'s `.setItems(newItems)` method: it could detect the items that have changed (`prevItems[i] !== newItems[i]`) and recalculate heights for such items, while the changed `item` properties would also cause the relevant React elements to be rerendered.
|
|
1084
1335
|
-->
|
|
1085
1336
|
|
|
1086
|
-
## TypeScript
|
|
1087
|
-
|
|
1088
|
-
This library comes with TypeScript "typings". If you happen to find any bugs in those, create an issue.
|
|
1089
|
-
|
|
1090
1337
|
## Possible enhancements
|
|
1091
1338
|
|
|
1092
1339
|
### Alternative approach in DOM rendering
|