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.
Files changed (231) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +825 -578
  3. package/bundle/index-dom-bypass.html +198 -0
  4. package/bundle/index-dom-grid.html +204 -0
  5. package/bundle/index-dom-scrollableContainer.html +215 -0
  6. package/bundle/index-dom-tbody-scrollableContainer.html +81 -0
  7. package/bundle/index-dom-tbody.html +65 -0
  8. package/bundle/index-dom.html +116 -83
  9. package/bundle/{index-bypass.html → index-react-bypass.html} +83 -78
  10. package/bundle/{index-grid.html → index-react-grid.html} +78 -91
  11. package/bundle/{index-scrollableContainer.html → index-react-scrollableContainer.html} +96 -91
  12. package/bundle/index-react-strictMode.html +199 -0
  13. package/bundle/index-react-tbody-scrollableContainer.html +96 -0
  14. package/bundle/index-react-tbody.html +80 -0
  15. package/bundle/{messages.js → items.js} +1 -1
  16. package/bundle/lib/babel.min.js +25 -0
  17. package/bundle/lib/prop-types.min.js +1 -0
  18. package/bundle/lib/react-dom.development.js +29924 -0
  19. package/bundle/lib/react-dom.production.min.js +267 -0
  20. package/bundle/lib/react.development.js +3343 -0
  21. package/bundle/lib/react.production.min.js +31 -0
  22. package/bundle/style.base.css +33 -0
  23. package/{website/style.css → bundle/style.list.css} +10 -43
  24. package/bundle/style.list.grid.css +23 -0
  25. package/bundle/virtual-scroller-dom.js +1 -1
  26. package/bundle/virtual-scroller-dom.js.map +1 -1
  27. package/bundle/virtual-scroller-react.js +1 -1
  28. package/bundle/virtual-scroller-react.js.map +1 -1
  29. package/bundle/virtual-scroller.js +1 -1
  30. package/bundle/virtual-scroller.js.map +1 -1
  31. package/commonjs/BeforeResize.js +1 -2
  32. package/commonjs/BeforeResize.js.map +1 -1
  33. package/commonjs/DOM/VirtualScroller.js +67 -44
  34. package/commonjs/DOM/VirtualScroller.js.map +1 -1
  35. package/commonjs/DOM/tbody.js +15 -15
  36. package/commonjs/DOM/tbody.js.map +1 -1
  37. package/commonjs/ItemHeights.js +10 -13
  38. package/commonjs/ItemHeights.js.map +1 -1
  39. package/commonjs/Layout.defaults.js +21 -0
  40. package/commonjs/Layout.defaults.js.map +1 -0
  41. package/commonjs/Layout.js +78 -67
  42. package/commonjs/Layout.js.map +1 -1
  43. package/commonjs/Layout.test.js +8 -4
  44. package/commonjs/Layout.test.js.map +1 -1
  45. package/commonjs/Scroll.js +3 -3
  46. package/commonjs/Scroll.js.map +1 -1
  47. package/commonjs/ScrollableContainerResizeHandler.js +4 -5
  48. package/commonjs/ScrollableContainerResizeHandler.js.map +1 -1
  49. package/commonjs/VirtualScroller.constructor.js +53 -31
  50. package/commonjs/VirtualScroller.constructor.js.map +1 -1
  51. package/commonjs/VirtualScroller.items.js +50 -4
  52. package/commonjs/VirtualScroller.items.js.map +1 -1
  53. package/commonjs/VirtualScroller.js +44 -28
  54. package/commonjs/VirtualScroller.js.map +1 -1
  55. package/commonjs/VirtualScroller.layout.js +42 -31
  56. package/commonjs/VirtualScroller.layout.js.map +1 -1
  57. package/commonjs/VirtualScroller.onContainerResize.js +1 -2
  58. package/commonjs/VirtualScroller.onContainerResize.js.map +1 -1
  59. package/commonjs/VirtualScroller.onRender.js +1 -1
  60. package/commonjs/VirtualScroller.onRender.js.map +1 -1
  61. package/commonjs/VirtualScroller.state.js +18 -9
  62. package/commonjs/VirtualScroller.state.js.map +1 -1
  63. package/commonjs/VirtualScroller.verticalSpacing.js +39 -6
  64. package/commonjs/VirtualScroller.verticalSpacing.js.map +1 -1
  65. package/commonjs/react/VirtualScroller.js +98 -37
  66. package/commonjs/react/VirtualScroller.js.map +1 -1
  67. package/commonjs/react/useClassName.js +2 -2
  68. package/commonjs/react/useClassName.js.map +1 -1
  69. package/commonjs/react/useForwardedRef.js +50 -0
  70. package/commonjs/react/useForwardedRef.js.map +1 -0
  71. package/commonjs/react/useInstanceMethods.js +4 -4
  72. package/commonjs/react/useInstanceMethods.js.map +1 -1
  73. package/commonjs/react/useItemKeys.js +28 -5
  74. package/commonjs/react/useItemKeys.js.map +1 -1
  75. package/commonjs/react/useOnItemHeightDidChange.js +28 -12
  76. package/commonjs/react/useOnItemHeightDidChange.js.map +1 -1
  77. package/commonjs/react/useSetItemState.js +31 -12
  78. package/commonjs/react/useSetItemState.js.map +1 -1
  79. package/commonjs/react/useState.js +10 -11
  80. package/commonjs/react/useState.js.map +1 -1
  81. package/commonjs/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +3 -3
  82. package/commonjs/react/useStateWithRepeatableRead.js.map +1 -0
  83. package/commonjs/react/useStyle.js +10 -4
  84. package/commonjs/react/useStyle.js.map +1 -1
  85. package/commonjs/react/useValidateTableBodyItemsContainer.js +24 -0
  86. package/commonjs/react/useValidateTableBodyItemsContainer.js.map +1 -0
  87. package/commonjs/react/useVirtualScroller.js +12 -14
  88. package/commonjs/react/useVirtualScroller.js.map +1 -1
  89. package/commonjs/test/ItemsContainer.js +10 -10
  90. package/commonjs/test/ItemsContainer.js.map +1 -1
  91. package/commonjs/test/VirtualScroller.js +25 -10
  92. package/commonjs/test/VirtualScroller.js.map +1 -1
  93. package/dom/index.d.ts +11 -9
  94. package/index.d.ts +19 -9
  95. package/modules/BeforeResize.js +1 -2
  96. package/modules/BeforeResize.js.map +1 -1
  97. package/modules/DOM/VirtualScroller.js +67 -44
  98. package/modules/DOM/VirtualScroller.js.map +1 -1
  99. package/modules/DOM/tbody.js +14 -13
  100. package/modules/DOM/tbody.js.map +1 -1
  101. package/modules/ItemHeights.js +11 -14
  102. package/modules/ItemHeights.js.map +1 -1
  103. package/modules/Layout.defaults.js +11 -0
  104. package/modules/Layout.defaults.js.map +1 -0
  105. package/modules/Layout.js +77 -67
  106. package/modules/Layout.js.map +1 -1
  107. package/modules/Layout.test.js +8 -4
  108. package/modules/Layout.test.js.map +1 -1
  109. package/modules/Scroll.js +3 -3
  110. package/modules/Scroll.js.map +1 -1
  111. package/modules/ScrollableContainerResizeHandler.js +4 -5
  112. package/modules/ScrollableContainerResizeHandler.js.map +1 -1
  113. package/modules/VirtualScroller.constructor.js +53 -31
  114. package/modules/VirtualScroller.constructor.js.map +1 -1
  115. package/modules/VirtualScroller.items.js +51 -5
  116. package/modules/VirtualScroller.items.js.map +1 -1
  117. package/modules/VirtualScroller.js +44 -28
  118. package/modules/VirtualScroller.js.map +1 -1
  119. package/modules/VirtualScroller.layout.js +42 -31
  120. package/modules/VirtualScroller.layout.js.map +1 -1
  121. package/modules/VirtualScroller.onContainerResize.js +1 -2
  122. package/modules/VirtualScroller.onContainerResize.js.map +1 -1
  123. package/modules/VirtualScroller.onRender.js +1 -1
  124. package/modules/VirtualScroller.onRender.js.map +1 -1
  125. package/modules/VirtualScroller.state.js +18 -9
  126. package/modules/VirtualScroller.state.js.map +1 -1
  127. package/modules/VirtualScroller.verticalSpacing.js +38 -6
  128. package/modules/VirtualScroller.verticalSpacing.js.map +1 -1
  129. package/modules/react/VirtualScroller.js +97 -38
  130. package/modules/react/VirtualScroller.js.map +1 -1
  131. package/modules/react/useClassName.js +3 -3
  132. package/modules/react/useClassName.js.map +1 -1
  133. package/modules/react/useForwardedRef.js +42 -0
  134. package/modules/react/useForwardedRef.js.map +1 -0
  135. package/modules/react/useInstanceMethods.js +4 -4
  136. package/modules/react/useInstanceMethods.js.map +1 -1
  137. package/modules/react/useItemKeys.js +28 -5
  138. package/modules/react/useItemKeys.js.map +1 -1
  139. package/modules/react/useOnItemHeightDidChange.js +28 -12
  140. package/modules/react/useOnItemHeightDidChange.js.map +1 -1
  141. package/modules/react/useSetItemState.js +31 -12
  142. package/modules/react/useSetItemState.js.map +1 -1
  143. package/modules/react/useState.js +10 -11
  144. package/modules/react/useState.js.map +1 -1
  145. package/modules/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +2 -2
  146. package/modules/react/useStateWithRepeatableRead.js.map +1 -0
  147. package/modules/react/useStyle.js +10 -4
  148. package/modules/react/useStyle.js.map +1 -1
  149. package/modules/react/useValidateTableBodyItemsContainer.js +16 -0
  150. package/modules/react/useValidateTableBodyItemsContainer.js.map +1 -0
  151. package/modules/react/useVirtualScroller.js +10 -12
  152. package/modules/react/useVirtualScroller.js.map +1 -1
  153. package/modules/test/ItemsContainer.js +10 -10
  154. package/modules/test/ItemsContainer.js.map +1 -1
  155. package/modules/test/VirtualScroller.js +25 -10
  156. package/modules/test/VirtualScroller.js.map +1 -1
  157. package/package.json +1 -1
  158. package/react/as.d.ts +42 -0
  159. package/react/index.d.ts +204 -63
  160. package/source/BeforeResize.js +1 -2
  161. package/source/DOM/VirtualScroller.js +65 -40
  162. package/source/DOM/tbody.js +15 -14
  163. package/source/ItemHeights.js +11 -12
  164. package/source/Layout.defaults.js +8 -0
  165. package/source/Layout.js +69 -56
  166. package/source/Layout.test.js +7 -2
  167. package/source/Scroll.js +3 -3
  168. package/source/ScrollableContainerResizeHandler.js +4 -4
  169. package/source/VirtualScroller.constructor.js +40 -31
  170. package/source/VirtualScroller.items.js +47 -2
  171. package/source/VirtualScroller.js +49 -27
  172. package/source/VirtualScroller.layout.js +43 -30
  173. package/source/VirtualScroller.onContainerResize.js +1 -2
  174. package/source/VirtualScroller.onRender.js +1 -1
  175. package/source/VirtualScroller.state.js +18 -11
  176. package/source/VirtualScroller.verticalSpacing.js +32 -6
  177. package/source/react/VirtualScroller.js +111 -36
  178. package/source/react/useClassName.js +3 -3
  179. package/source/react/useForwardedRef.js +39 -0
  180. package/source/react/useInstanceMethods.js +12 -4
  181. package/source/react/useItemKeys.js +22 -4
  182. package/source/react/useOnItemHeightDidChange.js +29 -10
  183. package/source/react/useSetItemState.js +32 -10
  184. package/source/react/useState.js +7 -8
  185. package/source/react/{useStateNoStaleBug.js → useStateWithRepeatableRead.js} +1 -1
  186. package/source/react/useStyle.js +3 -2
  187. package/source/react/useValidateTableBodyItemsContainer.js +16 -0
  188. package/source/react/useVirtualScroller.js +4 -6
  189. package/source/test/ItemsContainer.js +10 -10
  190. package/source/test/VirtualScroller.js +16 -10
  191. package/website/index-dom-bypass.html +198 -0
  192. package/website/index-dom-grid.html +204 -0
  193. package/website/index-dom-scrollableContainer.html +215 -0
  194. package/website/index-dom-tbody-scrollableContainer.html +81 -0
  195. package/website/index-dom-tbody.html +65 -0
  196. package/website/index-dom.html +117 -84
  197. package/website/index-react-bypass.html +200 -0
  198. package/website/{index-grid.html → index-react-grid.html} +79 -92
  199. package/website/index-react-scrollableContainer.html +213 -0
  200. package/website/index-react-strictMode.html +199 -0
  201. package/website/index-react-tbody-scrollableContainer.html +96 -0
  202. package/website/index-react-tbody.html +80 -0
  203. package/website/{index-bypass.html → index-react.html} +84 -70
  204. package/website/index.html +84 -69
  205. package/website/{messages.js → items.js} +1 -1
  206. package/website/lib/babel.min.js +25 -0
  207. package/website/lib/prop-types.min.js +1 -0
  208. package/website/lib/react-dom.development.js +29924 -0
  209. package/website/lib/react-dom.production.min.js +267 -0
  210. package/website/lib/react.development.js +3343 -0
  211. package/website/lib/react.production.min.js +31 -0
  212. package/website/style.base.css +33 -0
  213. package/website/style.list.css +92 -0
  214. package/website/style.list.grid.css +23 -0
  215. package/bundle/index-tbody-scrollableContainer.html +0 -70
  216. package/bundle/index-tbody.html +0 -57
  217. package/bundle/on-scroll-to-dom.js +0 -2
  218. package/bundle/on-scroll-to-dom.js.map +0 -1
  219. package/bundle/on-scroll-to-react.js +0 -2
  220. package/bundle/on-scroll-to-react.js.map +0 -1
  221. package/bundle/on-scroll-to.js +0 -2
  222. package/bundle/on-scroll-to.js.map +0 -1
  223. package/commonjs/react/useStateNoStaleBug.js.map +0 -1
  224. package/modules/react/useStateNoStaleBug.js.map +0 -1
  225. package/website/index-scrollableContainer.html +0 -208
  226. package/website/index-tbody-scrollableContainer.html +0 -70
  227. package/website/index-tbody.html +0 -57
  228. package/website/lib/on-scroll-to-dom.js +0 -2
  229. package/website/lib/on-scroll-to-dom.js.map +0 -1
  230. package/website/lib/on-scroll-to-react.js +0 -2
  231. 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, includes a [React](#react) component.
8
- * For those who prefer "vanilla" DOM, there's a [DOM](#dom) component.
9
- * For everyone else, there's a low-level [core](#core) component that supports any type of [rendering engine](#rendering-engine), not just DOM. Use it to create your own implementation for any framework or environment.
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) (no frameworks):
13
+ [DOM](#dom) component
14
14
 
15
- * [Basic](https://catamphetamine.gitlab.io/virtual-scroller/index-dom.html)
16
- * [Dynamically loaded](https://catamphetamine.gitlab.io/virtual-scroller/index-dom.html?dynamic=✓)
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
- * [Basic](https://catamphetamine.gitlab.io/virtual-scroller/)
21
- * [Dynamically loaded](https://catamphetamine.gitlab.io/virtual-scroller/?dynamic=✓)
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
- [Grid Layout](#grid-layout):
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
+ ![A screen recording showing the poor responsiveness on Twitter's website before they used virtualization](https://cdn-images-1.medium.com/max/2600/1*mDPjaeBNhCAbEcbKV-IX3Q.gif)
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
- * [Basic](https://catamphetamine.gitlab.io/virtual-scroller/index-grid.html)
26
- * [Dynamically loaded](https://catamphetamine.gitlab.io/virtual-scroller/index-grid.html?dynamic=✓)
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
- ## Rationale
552
+ #####
29
553
 
30
- Rendering really long lists in HTML can be performance intensive which sometimes leads to slow page load times and wasting mobile users' battery. For example, consider a chat app rendering a list of a thousand of the most recent messages: when using React the full render cycle can take up to 100 milliseconds or more on a modern PC. If the chat message component is complex enough (rich text formatting, pictures, videos, attachments, buttons) then it could take up to a second or more (on a modern PC). Now imagine users viewing the website on their aged low-tier smartphones and it quickly results in annoying user experience resulting in them closing the website and the website losing its user base.
554
+ <!-- * `onMount()` Is called before `VirtualScroller.onMount()` is called. -->
31
555
 
32
- In 2017 Twitter completely redesigned their website with responsiveness and performance in mind using the latest performance-boosting techniques available at that time. They wrote an [article](https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3) about it where they briefly mentioned this:
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
- ![Twitter website responsiveness before using the VirtualScroller technique](https://cdn-images-1.medium.com/max/2600/1*mDPjaeBNhCAbEcbKV-IX3Q.gif)
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
- > 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.
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
- 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.
562
+ * Any other [options](#options) are simply passed through to the ["core"](#core) component.
563
+ </details>
41
564
 
42
- 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.
565
+ #####
43
566
 
44
- ## How it works
567
+ <details>
568
+ <summary>Instance methods</summary>
45
569
 
46
- `VirtualScroller` works by measuring each list item's height as it's being rendered, and then, as the user scrolls, it hides the items that are no longer visible, and shows the now-visible items as they're scrolled to. The hidden items at the top are compensated by setting `padding-top` on the list element, and the hidden items at the bottom are compensated by setting `padding-bottom` on the list element. The component listens to `scroll` / `resize` events and re-renders the currently visible items as the user scrolls (or if the browser window is resized).
570
+ #####
47
571
 
48
- To observe list item elements being dynamically mounted and unmounted, go to the [demo](https://catamphetamine.gitlab.io/virtual-scroller) page, open Developer Tools ("Elements" tab), find `<div id="root"/>` element, expand it, see `<div id="messages"/>` element, expand it and observe the changes to it while scrolling the page.
572
+ The following instance methods are just proxies for the corresponding methods of the ["core"](#core) component:
49
573
 
50
- To add some inter-item spacing, one could use `margin-top` / `margin-bottom` or `border-top` / `border-bottom`: see the [Gotchas](#gotchas) section for more details on how to do that properly.
574
+ * `start()`
575
+ * `stop()`
576
+ * `setItems(items, options)`
577
+ * `setItemState(item, itemState)`
578
+ * `onItemHeightDidChange(item)`
51
579
 
52
- ## Install
580
+ <!-- * `getItemCoordinates(item)` -->
581
+ </details>
53
582
 
54
- ```
55
- npm install virtual-scroller --save
56
- ```
583
+ ## Core
57
584
 
58
- If you're not using a bundler then use a [standalone version from a CDN](#cdn).
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
- ## Core
587
+ ### State
61
588
 
62
- The default export is a low-level `VirtualScroller` class: it implements the core logic of a `VirtualScroller` component and can be used for building a `VirtualScroller` component 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/dom`](#dom) or [`virtual-scroller/react`](#react) packages. Or implement your own: see `source/test` folder for an example of using the core class to build an "imaginary" renderer implementation.
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
- #### State
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 core `VirtualScroller` component works by dynamically updating its `state` as the user scrolls the page. The `state` provides the calculations on which items should be rendered (and which should not be) depending on the current scroll position.
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
- A higher-level wrapper around the core `VirtualScroller` component must manage the rendering of the items using the information from the `state`. At any given time, `state` should correspond exactly to what's rendered on the screen: whenever `state` gets updated, the corresponding changes should be immediately (without any "timeout" or "delay") rendered on the screen.
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()`](#dynamically-loaded-lists)).
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(i, itemState)` instance method (described below) immediately after an item's state has changed.
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(i, { showMore: true/false })` instance method along with `.onItemHeightDidChange(i)` instance method (described below), so that next time when the item is rendered, it could restore its appearance from `virtualScroller.getState().itemStates[i]`.
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(i)` instance method (described below) right after the YouTube video has been expanded/collapsed.
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(i)` 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(i)` immediately after the comment text has been expanded or collapsed.
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(i)`, 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".
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
- * `getContainerElement()` Returns the list "element" that is gonna contain all list item "elements".
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
- // Stop VirtualScroller listening for scroll events
253
- // when the user navigates to another page:
254
- // router.onPageUnload(virtualScroller.stop)
255
- ```
256
- </details>
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><code>VirtualScroller</code> <code>options</code></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
- #### "Advanced" (rarely used) options
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 turn off `VirtualScroller` behavior and just render the full list of items.
727
+ * `bypass: boolean` — Pass `true` to disable the "virtualization" behavior and just render the entire list of items.
288
728
 
289
- * `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`.
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 (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.
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
- * `getEstimatedItemHeight: () => number` or `getEstimatedVisibleItemRowsCount: () => number` — These functions are only used during the initial render of the list to estimate how many of the list items should be rendered initially to cover the screen space plus some extra vertical margin (called "prerender margin") for future scrolling. The list will then immediately re-render itself the second time anyway, just to make sure that the layout has been calculated correctly, so the values returned by these functions doesn't have to be 100% accurate. But the more accurate they are, the more accurate is the initial render. The only purpose for the existence of these parameters is eliminating any potential initial "flash" of empty space on screen caused by the list of items being only half-rendered. These two parameters are mutually exclusive: one may only provide one of them. If none of these parameters is provided, then the list initially renders with just the first item being shown, then measures the first item's size, and then rerenders itself again using the measured item height as a substitute for `getEstimatedItemHeight()`.
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
- * `prerenderMargin` — The list component renders not only the items that're currently visible but also the items that lie within some extra vertical margin (called "prerender margin") on top and bottom for future scrolling: this way, there'll be significantly less layout recalculations as the user scrolls, because now it doesn't have to recalculate layout on each scroll event. By default, the "prerender margin" is equal to the screen height: this seems to be the optimal value for "Page Up" / "Page Down" navigation and optimized mouse wheel scrolling. This parameter is currently ignored because the default value seems to fit all possible use cases.
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><code>VirtualScroller</code> instance methods</summary>
758
+ <summary>Instance methods</summary>
319
759
 
320
760
  #####
321
761
 
322
- * `start()` — `VirtualScroller` starts listening for scroll events. Should be called after the list has been rendered initially.
762
+ * `start()` — Performs an initial render of the `VirtualScroller` and starts listening to scroll events.
323
763
 
324
- * `stop()` — `VirtualScroller` stops listening for scroll events. Should be called when the list is about to be removed from the page. To re-start the `VirtualScroller`, call `.start()` method again.
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 [Dynamically Loaded Lists](#dynamically-loaded-lists) section for more details. Available options:
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
- <details>
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
- If the `itemComponent` has any internal state, it should be stored in the `VirtualScroller` `state`. The need for saving and restoring list item component state arises because item components get unmounted as they go off screen. If the item component's state is not persested somehow, it would be lost when the item goes off screen. If the user then decides to scroll back up, that item would get re-rendered "from scratch", potentually causing a "jump of content" if it was somehow "expanded" prior to being hidden.
791
+ * Get the initial state value via `virtualScroller.getInitialState()`.
549
792
 
550
- For example, consider a social network feed where feed items (posts) can be expanded or collapsed via a "Show more"/"Show less" button. Suppose a user clicks a "Show more" button on 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 as a collapsed post instead of an expanded one, resulting in a perceived "jump" of page content by the difference in height of the post being expanded and collapsed.
793
+ * Initialize the externally managed state with the initial state value.
551
794
 
552
- To fix that, `itemComponent` receives the following state management properties:
795
+ * Define `getState()` and `updateState()` functions for reading or updating the externally managed state.
553
796
 
554
- * `state` — Saved state of the item component. Use this property to render the item component.
797
+ * Call `virtualScroller.useState({ getState, updateState })`.
555
798
 
556
- * In the example described above, `state` might look like `{ expanded: true }`.
799
+ * "Render" the list and call `virtualScroller.start()`.
557
800
 
558
- * This is simply a proxy for `virtualScroller.getState().itemStates[i]`.
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
- * `setState(newItemState)` Use this function to save the item component state whenever it changes.
803
+ #### "Advanced" (rarely used) instance methods
561
804
 
562
- * In the example described above, `setState()` would be called whenever a user clicks a "Show more"/"Show less" button.
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
- * This is simply a proxy for `virtualScroller.setItemState(i, itemState)`.
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
- * `onHeightDidChange()` Call this function immediately after (if ever) the item element height has changed.
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
- * 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 results in a change of the item element's height, so `VirtualScroller` should re-measure it in order for its internal calculations to stay correct.
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
- * This is simply a proxy for `virtualScroller.onItemHeightDidChange(i)`.
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
- ```js
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
- const hasMounted = useRef()
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
- useLayoutEffect(() => {
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
- return (
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><code>&lt;VirtualScroller/&gt;</code> optional properties</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
- useEffect(() => {
649
- return () => {
650
- // Save `VirtualScroller` state before the page unmounts.
651
- saveVirtualScrollerState(virtualScrollerState.current)
652
- }
653
- })
835
+ const items = [
836
+ { title: 'Apple' },
837
+ { title: 'Banana' },
838
+ { title: 'Cranberry' }
839
+ ]
654
840
 
655
- return (
656
- <VirtualScroller
657
- items={...}
658
- itemComponent={...}
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
- * `preserveScrollPositionOnPrependItems: boolean` — The `preserveScrollPositionOnPrependItems` option of `VirtualScroller.setItems()` method.
847
+ const container = document.getElementById('list')
667
848
 
668
- * `getItemId(item): any` — The `getItemId` option of `VirtualScroller` class. The React component also uses it as a source for a React `key` for rendering an `item`. If `getItemId()` is not supplied, then item `key`s are autogenerated from a random-generated prefix (that changes every time `items` are updated) and an `item` index. Can be used to prevent `<VirtualScroller/>` from re-rendering all visible items every time `items` property is updated.
849
+ function render(state, prevState) {
850
+ const {
851
+ items,
852
+ beforeItemsHeight,
853
+ afterItemsHeight,
854
+ firstShownItemIndex,
855
+ lastShownItemIndex
856
+ } = state
669
857
 
670
- * `readyToStart: boolean` — One could pass `false` to delay the `start()` of the `VirtualScroller` until everything's "ready".
671
- * For example, when navigating "Back" to a "Catalog" page, the application could fully restore the `VirtualScroller` state from a snapshot, but for that to work, the scroll position has to be restored independently by the application "router". When `VirtualScroller` attempts to "rehydrate" itself from a state snapshot, the scroll position should already be restored by the application "router". By default, `<VirtualScroller/>` component "rehydrates" itself in a `useLayoutEffect()`, which happens before `useLayoutEffect()` or `useEffect()` of the application "router" component according to the order in which React effects get executed: from child to parent. But at the same time, the application "router" component typically restores the scroll position in `useEffect()` meaning that the scroll position is not yet restored at the time `<VirtualScroller/>` component "rehydrates" itself. So the `<VirtualScroller/>` component should somehow "wait" for the application "router" to restore the scroll position, after which it should attempt to "rehydrate" itself. That's what the `readyToStart` property is for: until the scroll position is restored, it should pass `readyToStart={false}` property to the `<VirtualScroller/>`.
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
- * `bypass: boolean` The `bypass` option of `VirtualScroller` class.
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
- * `tbody: boolean` The `tbody` option of `VirtualScroller` class.
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
- * `getEstimatedItemHeight: () => number` — The `getEstimatedItemHeight` option of `VirtualScroller` class.
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
- * `getEstimatedVisibleItemRowsCount: () => number` The `getEstimatedVisibleItemRowsCount` option of `VirtualScroller` class.
911
+ const virtualScroller = new VirtualScroller(() => element, items, { render })
680
912
 
681
- * `measureItemsBatchSize: number` The `measureItemsBatchSize` option of `VirtualScroller`.
913
+ // Start VirtualScroller listening for scroll events.
914
+ virtualScroller.start()
682
915
 
683
- <!-- * `onMount()` — Is called after `<VirtualScroller/>` component has been mounted and before `VirtualScroller.onMount()` is called. -->
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
- * `onItemInitialRender(item)` — The `onItemInitialRender` option of `VirtualScroller` class.
922
+ ## Updating Items
686
923
 
687
- <!-- * `shouldUpdateLayoutOnScreenResize(event)` The `shouldUpdateLayoutOnScreenResize` option of `VirtualScroller` class. -->
924
+ If the list represents a social media feed, it has to be updated periodically as new posts get published.
688
925
 
689
- * `getScrollableContainer(): Element` The `getScrollableContainer` option of `VirtualScroller` class. The scrollable container DOM Element must exist by the time `<VirtualScroller/>` component is mounted.
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
- import React, { useState, useLayoutEffect } from 'react'
696
- import VirtualScroller from 'virtual-scroller'
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
- function List() {
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
- function getScrollableContainer() {
727
- return document.getElementById('ListContainer')
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
- ```css
732
- #ListContainer {
733
- max-height: 30rem;
734
- overflow-y: auto;
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
- <details>
743
- <summary><code>&lt;VirtualScroller/&gt;</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 (i.e. multiple columns in a row), supply a `getColumnsCount(container: ScrollableContainer): number` parameter to `VirtualScroller`.
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 on screens wider than `1280px`:
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(container) {
794
- // The `container` argument provides a `.getWidth()` method.
795
- if (container.getWidth() > 1280) {
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
- .container {
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
- ## Gotchas
1019
+ ## Tips & Tricks
823
1020
 
824
- ### Images
1021
+ ### Adding Spacing Between List Items
825
1022
 
826
- `VirtualScroller` measures item heights as soon as they've rendered and later uses those measurements to determine which items should be rendered when the user scrolls. This means that things like `<img/>`s require special handling to prevent them from changing their size. For example, when rendering a simple `<img src="..."/>` first it renders an element with zero width and height and only after the image file header has been parsed does it resize itself to the actual image's width and height. When used inside `VirtualScroller` items such images would result in scroll position "jumping" as the user scrolls. To avoid that, any `<img/>`s rendered inside `VirtualScroller` items must either have their `width` and `height` set explicitly or have their [aspect ratio](https://www.w3schools.com/howto/howto_css_aspect_ratio.asp) set explicitly by making them `position: absolute` and wrapping them in a parent `<div/>` having `position: relative` and `padding-bottom: ${100/aspectRatio}%`.
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
- ### Margin collapse
1025
+ ### Using `margin` on List Items Correctly
829
1026
 
830
- If any vertical CSS `margin` is set on the list items, then this may lead to page content "jumping" by the value of that margin while scrolling. The reason is that when the top of the list is visible on screen, no `padding-top` gets applied to the list element, and the CSS spec states that having `padding` on an element disables its ["margin collapse"](https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Box_Model/Mastering_margin_collapsing), so, while there's no `padding-top` on the list element, its margins do "collapse" with outer margins, but when the first item is no longer visible (and no longer rendered), `padding-top` gets applied to the list element to compensate for the non-rendered items, and that `padding-top` prevents the list's margins from "collapsing" with outer margins. So that results in the page content "jumping" when the first item in the list becomes invisible or becomes visible again. To fix that, don't set any `margin-top` on the first item of the list, and don't set any `margin-bottom` on the last item of the list. An example of fixing `margin` for the first and the last items of the list:
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
- /* This margin is supposed to "collapse" with the outer ones
834
- but requires a fix below to work correctly with `VirtualScroller`. */
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 "collapse" for the first item. */
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 "collapse" for the last item. */
1063
+ /* Fixes "margin collapse" issue for the last item. */
843
1064
  .list-item:last-child {
844
- margin-top: 0;
1065
+ margin-bottom: 0;
845
1066
  }
846
1067
  ```
847
1068
 
848
- ### Styling `:first-child` and `:last-child`
1069
+ ### Using `:first-child` or `:last-child` CSS Selectors
849
1070
 
850
- When styling the first and the last items of the list via `:first-child` and `:last-child`, one should also check that such styles don't change the item's height, which means that one should not add any `border` or `padding` styles to `:first-child` and `:last-child`, otherwise the list items will jump by that extra height during scrolling.
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
- An example of a `:first-child`/`:last-child` style that will not work correctly with `VirtualScroller`:
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
- ### Resize
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
- When the container width changes, all items' heights must be recalculated because:
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
- * If item elements render multi-line text, the lines count might've changed because there's more or less width available now.
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
- * Some CSS [`@media()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) rules might have been added or removed, affecting item layout.
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
- If the list currently shows items starting from the `N`-th one, then all `N - 1` previous items have to be remeasured. But they can't be remeasured until they're rendered again, so `VirtualScroller` temporarily uses their old heights until those items get re-measured after they become visible again as the user scrolls up.
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
- When such upper items get rendered and re-measured, the scroll position is automatically corrected to avoid ["content jumping"](https://css-tricks.com/content-jumping-avoid/).
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>I found a single edge case when the automatic correction of scroll position doesn't seem to work.</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
- The "before resize" layout parameters snapshot is stored in `VirtualScroller` state in `beforeResize` object:
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 offscreen list items not being rendered native browser features like "Find on page", moving focus through items via `Tab` key, screen reader announcement and such won't work. A workaround for "search on page" is adding a custom "🔍 Search" input field that would filter items by their content and then call `VirtualScroller.setItems()`.
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 dev mode.
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(i)` instance method.
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
- ### If only the first item is rendered on page load in dev mode.
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 its `.onMount()` method is called, but if the page styles are applied after `VirtualScroller` is mounted (for example, if styles are applied via javascript, like Webpack does it in dev mode with its `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 container DOM element on mount returns "incorrect" `top` position because the styles haven't been applied yet, and so `VirtualScroller` thinks it's offscreen.
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
- The sidebar is styled as `position: fixed`, but until the page styles have been applied it's gonna be a regular `<div/>` meaning that `<main/>` will be rendered below the sidebar causing it to be offscreen and so the list will only render the first item. Then, the page styles are loaded and applied and the sidebar is now `position: fixed` so `<main/>` is now rendered at the top of the page but `VirtualScroller` has already been rendered and it won't re-render until the user scrolls or the window is resized.
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 doesn't occur in production, but it can appear in development mode when using Webpack. The workaround `VirtualScroller` implements for such cases is calling `.getBoundingClientRect()` on the list container DOM element periodically (every second) to check if the `top` coordinate has changed as a result of CSS being applied: if it has then it recalculates the shown item indexes and re-renders.
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
- One can use any npm CDN service, e.g. [unpkg.com](https://unpkg.com) or [jsdelivr.net](https://jsdelivr.net)
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(i)` manually.
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