virtual-scroller 1.8.1 → 1.9.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 (247) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +337 -160
  3. package/bundle/virtual-scroller-dom.js +1 -1
  4. package/bundle/virtual-scroller-dom.js.map +1 -1
  5. package/bundle/virtual-scroller-react.js +1 -1
  6. package/bundle/virtual-scroller-react.js.map +1 -1
  7. package/bundle/virtual-scroller.js +1 -1
  8. package/bundle/virtual-scroller.js.map +1 -1
  9. package/commonjs/BeforeResize.js +23 -27
  10. package/commonjs/BeforeResize.js.map +1 -1
  11. package/commonjs/DOM/Engine.js +7 -7
  12. package/commonjs/DOM/Engine.js.map +1 -1
  13. package/commonjs/DOM/ItemsContainer.js +1 -1
  14. package/commonjs/DOM/ItemsContainer.js.map +1 -1
  15. package/commonjs/DOM/ListTopOffsetWatcher.js +15 -9
  16. package/commonjs/DOM/ListTopOffsetWatcher.js.map +1 -1
  17. package/commonjs/DOM/ScrollableContainer.js +28 -28
  18. package/commonjs/DOM/ScrollableContainer.js.map +1 -1
  19. package/commonjs/DOM/VirtualScroller.js +20 -17
  20. package/commonjs/DOM/VirtualScroller.js.map +1 -1
  21. package/commonjs/DOM/tbody.js +16 -10
  22. package/commonjs/DOM/tbody.js.map +1 -1
  23. package/commonjs/ItemHeights.js +13 -7
  24. package/commonjs/ItemHeights.js.map +1 -1
  25. package/commonjs/Layout.js +15 -13
  26. package/commonjs/Layout.js.map +1 -1
  27. package/commonjs/Layout.test.js +8 -3
  28. package/commonjs/Layout.test.js.map +1 -1
  29. package/commonjs/{ListHeightChangeWatcher.js → ListHeightMeasurement.js} +26 -28
  30. package/commonjs/ListHeightMeasurement.js.map +1 -0
  31. package/commonjs/Resize.js +38 -28
  32. package/commonjs/Resize.js.map +1 -1
  33. package/commonjs/Scroll.js +28 -44
  34. package/commonjs/Scroll.js.map +1 -1
  35. package/commonjs/VirtualScroller.columns.js +43 -0
  36. package/commonjs/VirtualScroller.columns.js.map +1 -0
  37. package/commonjs/VirtualScroller.constructor.js +408 -0
  38. package/commonjs/VirtualScroller.constructor.js.map +1 -0
  39. package/commonjs/VirtualScroller.items.js +305 -0
  40. package/commonjs/VirtualScroller.items.js.map +1 -0
  41. package/commonjs/VirtualScroller.js +132 -1872
  42. package/commonjs/VirtualScroller.js.map +1 -1
  43. package/commonjs/VirtualScroller.layout.js +562 -0
  44. package/commonjs/VirtualScroller.layout.js.map +1 -0
  45. package/commonjs/VirtualScroller.onRender.js +357 -0
  46. package/commonjs/VirtualScroller.onRender.js.map +1 -0
  47. package/commonjs/VirtualScroller.resize.js +186 -0
  48. package/commonjs/VirtualScroller.resize.js.map +1 -0
  49. package/commonjs/VirtualScroller.state.js +301 -0
  50. package/commonjs/VirtualScroller.state.js.map +1 -0
  51. package/commonjs/VirtualScroller.verticalSpacing.js +65 -0
  52. package/commonjs/VirtualScroller.verticalSpacing.js.map +1 -0
  53. package/commonjs/getItemCoordinates.js.map +1 -1
  54. package/commonjs/getItemsDiff.js.map +1 -1
  55. package/commonjs/getVerticalSpacing.js.map +1 -1
  56. package/commonjs/package.json +5 -0
  57. package/commonjs/react/VirtualScroller.js +180 -620
  58. package/commonjs/react/VirtualScroller.js.map +1 -1
  59. package/commonjs/react/useClassName.js +26 -0
  60. package/commonjs/react/useClassName.js.map +1 -0
  61. package/commonjs/react/useHandleItemsChange.js +116 -0
  62. package/commonjs/react/useHandleItemsChange.js.map +1 -0
  63. package/commonjs/react/useInstanceMethods.js +37 -0
  64. package/commonjs/react/useInstanceMethods.js.map +1 -0
  65. package/commonjs/react/useItemKeys.js +60 -0
  66. package/commonjs/react/useItemKeys.js.map +1 -0
  67. package/commonjs/react/useOnItemHeightChange.js +32 -0
  68. package/commonjs/react/useOnItemHeightChange.js.map +1 -0
  69. package/commonjs/react/useOnItemStateChange.js +32 -0
  70. package/commonjs/react/useOnItemStateChange.js.map +1 -0
  71. package/commonjs/react/useState.js +140 -0
  72. package/commonjs/react/useState.js.map +1 -0
  73. package/commonjs/react/useStyle.js +29 -0
  74. package/commonjs/react/useStyle.js.map +1 -0
  75. package/commonjs/react/useVirtualScroller.js +62 -0
  76. package/commonjs/react/useVirtualScroller.js.map +1 -0
  77. package/commonjs/react/useVirtualScrollerStartStop.js +20 -0
  78. package/commonjs/react/useVirtualScrollerStartStop.js.map +1 -0
  79. package/commonjs/test/Engine.js +23 -0
  80. package/commonjs/test/Engine.js.map +1 -0
  81. package/commonjs/test/ItemsContainer.js +127 -0
  82. package/commonjs/test/ItemsContainer.js.map +1 -0
  83. package/commonjs/test/ScrollableContainer.js +130 -0
  84. package/commonjs/test/ScrollableContainer.js.map +1 -0
  85. package/commonjs/test/VirtualScroller.js +281 -0
  86. package/commonjs/test/VirtualScroller.js.map +1 -0
  87. package/commonjs/utility/debounce.js +2 -2
  88. package/commonjs/utility/debounce.js.map +1 -1
  89. package/commonjs/utility/debug.js.map +1 -1
  90. package/commonjs/utility/getStateSnapshot.js +2 -2
  91. package/commonjs/utility/getStateSnapshot.js.map +1 -1
  92. package/commonjs/utility/px.js.map +1 -1
  93. package/commonjs/utility/px.test.js +1 -1
  94. package/commonjs/utility/px.test.js.map +1 -1
  95. package/commonjs/utility/shallowEqual.js +1 -1
  96. package/commonjs/utility/shallowEqual.js.map +1 -1
  97. package/commonjs/utility/throttle.js.map +1 -1
  98. package/dom/index.cjs +4 -0
  99. package/dom/index.cjs.js +9 -0
  100. package/dom/index.d.ts +6 -4
  101. package/dom/index.js +1 -1
  102. package/dom/package.json +10 -4
  103. package/index.cjs +4 -0
  104. package/index.cjs.js +9 -0
  105. package/index.d.ts +30 -15
  106. package/index.js +1 -1
  107. package/modules/BeforeResize.js +22 -27
  108. package/modules/BeforeResize.js.map +1 -1
  109. package/modules/DOM/Engine.js +6 -6
  110. package/modules/DOM/Engine.js.map +1 -1
  111. package/modules/DOM/ItemsContainer.js +1 -1
  112. package/modules/DOM/ItemsContainer.js.map +1 -1
  113. package/modules/DOM/ListTopOffsetWatcher.js +15 -9
  114. package/modules/DOM/ListTopOffsetWatcher.js.map +1 -1
  115. package/modules/DOM/ScrollableContainer.js +28 -28
  116. package/modules/DOM/ScrollableContainer.js.map +1 -1
  117. package/modules/DOM/VirtualScroller.js +19 -16
  118. package/modules/DOM/VirtualScroller.js.map +1 -1
  119. package/modules/DOM/tbody.js +11 -9
  120. package/modules/DOM/tbody.js.map +1 -1
  121. package/modules/ItemHeights.js +12 -6
  122. package/modules/ItemHeights.js.map +1 -1
  123. package/modules/Layout.js +14 -12
  124. package/modules/Layout.js.map +1 -1
  125. package/modules/Layout.test.js +8 -3
  126. package/modules/Layout.test.js.map +1 -1
  127. package/modules/{ListHeightChangeWatcher.js → ListHeightMeasurement.js} +25 -27
  128. package/modules/ListHeightMeasurement.js.map +1 -0
  129. package/modules/Resize.js +38 -28
  130. package/modules/Resize.js.map +1 -1
  131. package/modules/Scroll.js +28 -44
  132. package/modules/Scroll.js.map +1 -1
  133. package/modules/VirtualScroller.columns.js +36 -0
  134. package/modules/VirtualScroller.columns.js.map +1 -0
  135. package/modules/VirtualScroller.constructor.js +371 -0
  136. package/modules/VirtualScroller.constructor.js.map +1 -0
  137. package/modules/VirtualScroller.items.js +288 -0
  138. package/modules/VirtualScroller.items.js.map +1 -0
  139. package/modules/VirtualScroller.js +132 -1860
  140. package/modules/VirtualScroller.js.map +1 -1
  141. package/modules/VirtualScroller.layout.js +549 -0
  142. package/modules/VirtualScroller.layout.js.map +1 -0
  143. package/modules/VirtualScroller.onRender.js +337 -0
  144. package/modules/VirtualScroller.onRender.js.map +1 -0
  145. package/modules/VirtualScroller.resize.js +176 -0
  146. package/modules/VirtualScroller.resize.js.map +1 -0
  147. package/modules/VirtualScroller.state.js +283 -0
  148. package/modules/VirtualScroller.state.js.map +1 -0
  149. package/modules/VirtualScroller.verticalSpacing.js +54 -0
  150. package/modules/VirtualScroller.verticalSpacing.js.map +1 -0
  151. package/modules/getItemCoordinates.js.map +1 -1
  152. package/modules/getItemsDiff.js.map +1 -1
  153. package/modules/getVerticalSpacing.js.map +1 -1
  154. package/modules/react/VirtualScroller.js +176 -625
  155. package/modules/react/VirtualScroller.js.map +1 -1
  156. package/modules/react/useClassName.js +18 -0
  157. package/modules/react/useClassName.js.map +1 -0
  158. package/modules/react/useHandleItemsChange.js +108 -0
  159. package/modules/react/useHandleItemsChange.js.map +1 -0
  160. package/modules/react/useInstanceMethods.js +28 -0
  161. package/modules/react/useInstanceMethods.js.map +1 -0
  162. package/modules/react/useItemKeys.js +52 -0
  163. package/modules/react/useItemKeys.js.map +1 -0
  164. package/modules/react/useOnItemHeightChange.js +24 -0
  165. package/modules/react/useOnItemHeightChange.js.map +1 -0
  166. package/modules/react/useOnItemStateChange.js +24 -0
  167. package/modules/react/useOnItemStateChange.js.map +1 -0
  168. package/modules/react/useState.js +132 -0
  169. package/modules/react/useState.js.map +1 -0
  170. package/modules/react/useStyle.js +19 -0
  171. package/modules/react/useStyle.js.map +1 -0
  172. package/modules/react/useVirtualScroller.js +51 -0
  173. package/modules/react/useVirtualScroller.js.map +1 -0
  174. package/modules/react/useVirtualScrollerStartStop.js +12 -0
  175. package/modules/react/useVirtualScrollerStartStop.js.map +1 -0
  176. package/modules/test/Engine.js +11 -0
  177. package/modules/test/Engine.js.map +1 -0
  178. package/modules/test/ItemsContainer.js +120 -0
  179. package/modules/test/ItemsContainer.js.map +1 -0
  180. package/modules/test/ScrollableContainer.js +123 -0
  181. package/modules/test/ScrollableContainer.js.map +1 -0
  182. package/modules/test/VirtualScroller.js +270 -0
  183. package/modules/test/VirtualScroller.js.map +1 -0
  184. package/modules/utility/debounce.js +2 -2
  185. package/modules/utility/debounce.js.map +1 -1
  186. package/modules/utility/debug.js.map +1 -1
  187. package/modules/utility/getStateSnapshot.js +2 -2
  188. package/modules/utility/getStateSnapshot.js.map +1 -1
  189. package/modules/utility/px.js.map +1 -1
  190. package/modules/utility/px.test.js +1 -1
  191. package/modules/utility/px.test.js.map +1 -1
  192. package/modules/utility/shallowEqual.js +1 -1
  193. package/modules/utility/shallowEqual.js.map +1 -1
  194. package/modules/utility/throttle.js.map +1 -1
  195. package/package.json +46 -23
  196. package/react/index.cjs +4 -0
  197. package/react/index.cjs.js +9 -0
  198. package/react/index.d.ts +10 -9
  199. package/react/index.js +1 -1
  200. package/react/package.json +10 -4
  201. package/rollup.config.mjs +62 -0
  202. package/runnable/create-commonjs-package-json.js +11 -0
  203. package/source/BeforeResize.js +16 -21
  204. package/source/DOM/Engine.js +8 -10
  205. package/source/DOM/ListTopOffsetWatcher.js +13 -8
  206. package/source/DOM/ScrollableContainer.js +23 -21
  207. package/source/DOM/VirtualScroller.js +27 -11
  208. package/source/DOM/tbody.js +30 -21
  209. package/source/ItemHeights.js +9 -4
  210. package/source/Layout.js +12 -9
  211. package/source/Layout.test.js +8 -3
  212. package/source/{ListHeightChangeWatcher.js → ListHeightMeasurement.js} +21 -20
  213. package/source/Resize.js +41 -25
  214. package/source/Scroll.js +27 -35
  215. package/source/VirtualScroller.columns.js +26 -0
  216. package/source/VirtualScroller.constructor.js +336 -0
  217. package/source/VirtualScroller.items.js +302 -0
  218. package/source/VirtualScroller.js +144 -1875
  219. package/source/VirtualScroller.layout.js +539 -0
  220. package/source/VirtualScroller.onRender.js +345 -0
  221. package/source/VirtualScroller.resize.js +189 -0
  222. package/source/VirtualScroller.state.js +284 -0
  223. package/source/VirtualScroller.verticalSpacing.js +51 -0
  224. package/source/react/VirtualScroller.js +243 -587
  225. package/source/react/useClassName.js +14 -0
  226. package/source/react/useHandleItemsChange.js +115 -0
  227. package/source/react/useInstanceMethods.js +25 -0
  228. package/source/react/useItemKeys.js +59 -0
  229. package/source/react/useOnItemHeightChange.js +28 -0
  230. package/source/react/useOnItemStateChange.js +28 -0
  231. package/source/react/useState.js +114 -0
  232. package/source/react/useStyle.js +20 -0
  233. package/source/react/useVirtualScroller.js +59 -0
  234. package/source/react/useVirtualScrollerStartStop.js +12 -0
  235. package/source/test/Engine.js +11 -0
  236. package/source/test/ItemsContainer.js +87 -0
  237. package/source/test/ScrollableContainer.js +88 -0
  238. package/source/test/VirtualScroller.js +232 -0
  239. package/source/utility/debounce.js +2 -2
  240. package/source/utility/px.test.js +1 -1
  241. package/babel.config.js +0 -25
  242. package/babel.js +0 -5
  243. package/commonjs/ListHeightChangeWatcher.js.map +0 -1
  244. package/dom/index.commonjs.js +0 -4
  245. package/index.commonjs.js +0 -4
  246. package/modules/ListHeightChangeWatcher.js.map +0 -1
  247. package/react/index.commonjs.js +0 -4
package/README.md CHANGED
@@ -1,6 +1,12 @@
1
1
  # VirtualScroller
2
2
 
3
- A universal open-source implementation of Twitter's [`VirtualScroller`](https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3) component: a component for efficiently rendering large lists of *variable height* items. Automatically measures items as they're rendered and supports items of variable/dynamic height. Also includes a [React](#react) component for those who're using React. Also provides a low-level component that supports any type of [rendering engine](#rendering-engine), not just DOM.
3
+ A universal open-source implementation of Twitter's [`VirtualScroller`](https://medium.com/@paularmstrong/twitter-lite-and-high-performance-react-progressive-web-apps-at-scale-d28a00e780a3) component: a component for efficiently rendering large lists of *variable height* items. Supports grid layout.
4
+
5
+ <!-- Automatically measures items as they're rendered and supports items of variable/dynamic height. -->
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.
4
10
 
5
11
  ## Demo
6
12
 
@@ -53,19 +59,19 @@ If you're not using a bundler then use a [standalone version from a CDN](#cdn).
53
59
 
54
60
  ## Core
55
61
 
56
- 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. Hence, the core component is not meant to be used in applications directly: instead, use the high-level components exported from [`virtual-scroller/dom`](#dom) or [`virtual-scroller/react`](#react) packages.
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.
57
63
 
58
64
  #### State
59
65
 
60
- 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) depending on the current scroll position. A high-level wrapper around `VirtualScroller` supplies a function that renders the actual list using the information from the `state`.
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.
67
+
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.
61
69
 
62
70
  <details>
63
71
  <summary>Show the list of all <code>state</code> properties</summary>
64
72
 
65
73
  #####
66
74
 
67
- A high-level wrapper should supply either `getState`/`setState` functions, or `onStateChange` function (or both of them), and those functions are gonna be responsible for rendering the actual list using the information from `state`.
68
-
69
75
  The main `state` properties are:
70
76
 
71
77
  * `items: any[]` — The list of items (can be updated via [`.setItems()`](#dynamically-loaded-lists)).
@@ -86,45 +92,58 @@ The following `state` properties are only used for saving and restoring `Virtual
86
92
 
87
93
  * `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.
88
94
 
89
- * `columnsCount: number?` — The count of items in a row. Is `undefined` if no `getColumnsCount()` parameter has been passed to `VirtualScroller`.
95
+ * `columnsCount: number?` — The count of items in a row. Is `undefined` if no `getColumnsCount()` parameter has been passed to `VirtualScroller`, or if the columns count is `1`.
96
+
97
+ * `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.
90
98
  </details>
91
99
 
92
100
  #### Example
93
101
 
94
- <details>
95
- <summary>A general idea of using the low-level <code>VirtualScroller</code> class.</summary>
102
+ A general idea of using the low-level <code>VirtualScroller</code> class:
96
103
 
97
104
  #####
98
105
 
99
106
  ```js
100
107
  import VirtualScroller from 'virtual-scroller'
101
108
 
102
- const items = [...]
103
-
104
- const getItemsContainerElement = () => ...
109
+ const items = [
110
+ { name: 'Apple' },
111
+ { name: 'Banana' },
112
+ ...
113
+ ]
105
114
 
106
- const virtualScroller = new VirtualScroller(getItemsContainerElement, items, {
107
- onStateChange(state) {
108
- // Re-render the list based on its state:
109
- // * items
110
- // * firstShownItemIndex
111
- // * lastShownItemIndex
112
- // * beforeItemsHeight
113
- // * afterItemsHeight
115
+ const getContainerElement = () => document.getElementById(...)
116
+
117
+ const virtualScroller = new VirtualScroller(getContainerElement, items, {
118
+ render(state) {
119
+ // Re-renders the list based on its `state`.
120
+ const {
121
+ items,
122
+ firstShownItemIndex,
123
+ lastShownItemIndex,
124
+ beforeItemsHeight,
125
+ afterItemsHeight
126
+ } = state
127
+
128
+ container.paddingTop = beforeItemsHeight
129
+ container.paddingBottom = afterItemsHeight
130
+
131
+ container.children = items
132
+ .slice(firstShownItemIndex, lastShownItemIndex + 1)
133
+ .map(createItemElement)
114
134
  }
115
135
  })
116
136
 
117
137
  // Start listening to scroll events.
118
- virtualScroller.listen()
138
+ virtualScroller.start()
119
139
 
120
140
  // Stop listening to scroll events.
121
141
  virtualScroller.stop()
122
142
  ```
123
143
 
124
- * `getItemsContainerElement()` function returns the list "element" that is gonna contain all list item "elements".
125
- * `items` is the list of items.
126
- * `onStateChange(state)` is one of the available list `options`.
127
- </details>
144
+ * `getContainerElement()` Returns the list "element" that is gonna contain all list item "elements".
145
+ * `items` The list of items.
146
+ * `render(state, prevState)` "Renders" the list.
128
147
 
129
148
  #####
130
149
 
@@ -151,22 +170,25 @@ function renderItem(item) {
151
170
 
152
171
  const container = document.getElementById('list')
153
172
 
154
- function onStateChange(newState, prevState) {
173
+ function render(state, prevState) {
155
174
  const {
156
175
  items,
157
176
  beforeItemsHeight,
158
177
  afterItemsHeight,
159
178
  firstShownItemIndex,
160
179
  lastShownItemIndex
161
- } = newState
180
+ } = state
181
+
162
182
  // Set `paddingTop` and `paddingBottom` on the container element:
163
183
  // it emulates the non-visible items as if they were rendered.
164
184
  container.style.paddingTop = Math.round(beforeItemsHeight) + 'px'
165
185
  container.style.paddingBottom = Math.round(afterItemsHeight) + 'px'
186
+
166
187
  // Perform an intelligent "diff" re-render as the user scrolls the page.
167
188
  // This also requires that the list of `items` hasn't been changed.
168
189
  // On initial render, `prevState` is `undefined`.
169
190
  if (prevState && items === prevState.items) {
191
+
170
192
  // Remove no longer visible items.
171
193
  let i = prevState.lastShownItemIndex
172
194
  while (i >= prevState.firstShownItemIndex) {
@@ -178,6 +200,7 @@ function onStateChange(newState, prevState) {
178
200
  }
179
201
  i--
180
202
  }
203
+
181
204
  // Add newly visible items.
182
205
  let prependBefore = container.firstChild
183
206
  let i = firstShownItemIndex
@@ -195,7 +218,8 @@ function onStateChange(newState, prevState) {
195
218
  }
196
219
  i++
197
220
  }
198
- } else {
221
+ }
222
+ else {
199
223
  // Re-render the list from scratch.
200
224
  while (container.firstChild) {
201
225
  container.removeChild(container.firstChild)
@@ -208,12 +232,10 @@ function onStateChange(newState, prevState) {
208
232
  }
209
233
  }
210
234
 
211
- const options = { onStateChange }
212
-
213
- const virtualScroller = new VirtualScroller(() => element, items, options)
235
+ const virtualScroller = new VirtualScroller(() => element, items, { render })
214
236
 
215
237
  // Start VirtualScroller listening for scroll events.
216
- virtualScroller.listen()
238
+ virtualScroller.start()
217
239
 
218
240
  // Stop VirtualScroller listening for scroll events
219
241
  // when the user navigates to another page:
@@ -228,37 +250,47 @@ virtualScroller.listen()
228
250
 
229
251
  #####
230
252
 
231
- * `estimatedItemHeight: number` — Is used for the initial render of the list: determines how many list items are rendered initially to cover the screen height plus some extra vertical margin (called "prerender margin") for future scrolling. If not set then the list first renders just the first item, measures it, and then assumes it to be the `estimatedItemHeight` from which it calculates how many items to show on the second render pass to fill the screen height plus the "prerender margin". Therefore, this setting is only for the initial render minor optimization and is not required.
253
+ * `state: object` — The initial state for `VirtualScroller`. Can be used, for example, to quicky restore the list when it's re-rendered on "Back" navigation.
232
254
 
233
- * `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.
255
+ * `render(state: object, previousState: object?)` When a developer doesn't pass custom `getState()`/`updateState()` parameters (more on that later), `VirtualScroller` uses the default ones. The default `updateState()` function relies on a developer-supplied `render()` function that must "render" the current `state` of the `VirtualScroller` on the screen. See DOM `VirtualScroller` implementation for an example of such a `render()` function.
234
256
 
235
- * `state: object` — The initial state for `VirtualScroller`. Can be used, for example, to quicky restore the list when it's re-rendered on "Back" navigation.
257
+ * `onStateChange(newState: object, previousState: object?)` — An "on change" listener for the `VirtualScroller` `state` that gets called whenever `state` gets updated, including when setting the initial `state`.
258
+
259
+ * Is not called when individual item heights (including "before resize" ones) or individual item states are updated: instead, individual item heights or states are updated in-place, as `state.itemHeights[i] = newItemHeight` or `state.itemStates[i] = newItemState`. That's because those `state` properties are the ones that don’t affect the presentation, so there's no need to re-render the list when those properties do change — updates to those properties are just an effect of a re-render rather than a cause for a new re-render.
260
+
261
+ * `onStateChange()` parameter could be used to keep a copy of `VirtualScroller` `state` so that it could be quickly restored in case the `VirtualScroller` component gets unmounted and then re-mounted back again — for example, when the user navigates away by clicking on a list item and then navigates "Back" to the list.
262
+
263
+ * (advanced) If state updates are done "asynchronously" via a custom (external) `updateState()` function, then `onStateChange()` gets called after such state updates get "rendered" (after `virtualScroller.onRender()` gets called).
236
264
 
237
- * `customState: object` — (advanced) The initial "custom" state for `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.
265
+ * `getScrollableContainer(): Element` — (advanced) If the list is being rendered in a "scrollable container" (for example, if one of the parent elements of the list is styled with `max-height` and `overflow: auto`), then passing the "scrollable container" DOM Element is required for correct operation. "Gotchas":
238
266
 
239
- * `getState(): object`(advanced) By default, `VirtualScroller` manages `state` internally by storing it in an instance variable. For more control, the `state` could be managed externally, in which case a developer should supply `getState`/`setState` options, in which case `getState` should return the externally stored `VirtualScroller` `state`. React `VirtualScroller` component implementation uses this option.
267
+ * If `getColumnsCount()` parameter depends on the "scrollable container" argument for getting the available area width, then the "scrollable container" element must already exist when creating a `VirtualScroller` class instance, because the initial `state` is calculated at construction time.
240
268
 
241
- * `setState(stateUpdate: object, { willUpdateState, didUpdateState })` (advanced) By default, `VirtualScroller` manages `state` internally by storing it in an instance variable. For more control, the `state` could be managed externally, in which case a developer should supply `getState`/`setState` options, in which case `setState` should update the externally stored `VirtualScroller` `state` (including setting the initial `state`), and it should do that by merging the previous `state` with the `stateUpdate` argument. `setState` must also call two functions: `willUpdateState(newState, prevState)` right before the state is updated and `didUpdateState(prevState)` right after the state is updated. The list should be re-rendered as part of either `setState` or `onStateChange`. `setState` could be ["asynchronous"](https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous), that is when state updates aren't applied immediately and are instead queued and then applied in a single state update for performance. React `VirtualScroller` component implementation uses this option.
269
+ * When used with one of the DOM environment `VirtualScroller` implementations, the width and height of a "scrollable container" should only change when the browser window is resized, i.e. not manually via `scrollableContainerElement.width = 720`, because `VirtualScroller` only listens to browser window resize events, and any other changes in "scrollable container" width won't be detected.
242
270
 
243
- * `onStateChange(newState: object, prevState: object?)` — Is called whenever `VirtualScroller` `state` is updated (including setting the initial `state`). Is not called when individual item heights (including "before resize" ones) or states are updated: instead, individual item heights or states are updated in-place — `state.itemHeights[i] = newItemHeight` or `state.itemStates[i] = newItemState`. That's because those `state` properties are the ones that don’t affect the presentation, so there's no need to re-render the list when those do change — updating those properties is just an effect of some change rather than cause for one. In order for a `VirtualScroller` implementation to work, a developer must either supply `getState`/`setState` options or `onStateChange` option (or both). The list should be re-rendered as part of either `setState` or `onStateChange`.
271
+ * `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.
244
272
 
245
- * `scrollableContainer: Element` — (advanced) If the list is being rendered in a "scrollable container" (for example, if one of the parent elements of the list is styled with `max-height` and `overflow: auto`), then passing the "scrollable container" DOM Element is required for correct operation. *This feature is considered [experimental](https://github.com/catamphetamine/virtual-scroller/issues/8).* The width and height of the `scrollableContainer` shouldn't change unless window is resized.
273
+ #### "Advanced" (rarely used) options
274
+
275
+ * `bypass: boolean` — Pass `true` to turn off `VirtualScroller` behavior and just render the full list of items.
246
276
 
247
277
  * `initialScrollPosition: number` — If passed, the page will be scrolled to this `scrollY` position.
248
278
 
249
279
  * `onScrollPositionChange(scrollY: number)` — Is called whenever a user scrolls the page.
250
280
 
251
- * `bypass: boolean` — Pass `true` to turn off `VirtualScroller` behavior and just render the full list of items.
281
+ <!-- * `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. -->
252
282
 
253
283
  * `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.
254
284
 
255
- * `onItemInitialRender(item)` — Is called for each `item` when it's about to be rendered for the first time. Is guaranteed to be called at least once for each item rendered, though, in "asynchronous" rendering systems like React, it could be called multiple times for a given item, because "an item is calculated to be rendered" doesn't necessarily mean that the actual rendering will take place before a later calculation supercedes the former one. This function can be used to somehow "initialize" items before they're 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, a developer could "preprocess" the items as they're being rendered, thereby eliminating any associated lag or freezing that would be inevitable have all the items been "preprocessed" up front. If a user only wants to see a few of the items, "preprocessing" all the items up front would simply be a waste.
285
+ * `onItemInitialRender(item)` — (advanced) Is called for each `item` when it's about to be rendered for the first time. Is guaranteed to be called at least once for each item rendered, though, in "asynchronous" rendering systems like React, it could be called multiple times for a given item, because "an item is calculated to be rendered" doesn't necessarily mean that the actual rendering will take place before a later calculation supercedes the former one. This function can be used to somehow "initialize" items before they're 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, a developer could "preprocess" the items as they're being rendered, thereby eliminating any associated lag or freezing that would be inevitable have all the items been "preprocessed" up front. If a user only wants to see a few of the items, "preprocessing" all the items up front would simply be a waste.
256
286
 
257
- * `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.
287
+ <!-- * `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. -->
258
288
 
259
289
  * `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.
260
290
 
261
- * `getColumnsCount(container: ScrollableContainer): number` — (advanced) Provides support for ["grid"](#grid-layout) layout. The `container` argument provides a `.getWidth()` method.
291
+ * `estimatedItemHeight: number` — Is used for the initial render of the list: determines how many list items are rendered initially to cover the screen height plus some extra vertical margin (called "prerender margin") for future scrolling. If not set then the list first renders just the first item, measures it, and then assumes it to be the `estimatedItemHeight` from which it calculates how many items to show on the second render pass to fill the screen height plus the "prerender margin". Therefore, this setting is only for the initial render minor optimization and is not required.
292
+
293
+ * `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.
262
294
  </details>
263
295
 
264
296
  #####
@@ -268,42 +300,79 @@ virtualScroller.listen()
268
300
 
269
301
  #####
270
302
 
271
- * `listen()` — Starts `VirtualScroller` listening for scroll events. Should be called immediately after the list has been rendered on a page.
303
+ * `start()` — `VirtualScroller` starts listening for scroll events. Should be called after the list has been rendered initially.
304
+
305
+ * `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.
306
+
307
+ * `getState(): object` — Returns `VirtualScroller` state.
308
+
309
+ * `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:
310
+ * `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).
311
+
312
+ #### Custom (External) State Management
313
+
314
+ A developer might prefer to use custom (external) state management rather than the default one. That might be the case when a certain high-order `VirtualScroller` implementation comes with a specific state management paradigm, like in React. In such case, `VirtualScroller` provides the following instance methods:
315
+
316
+ * `onRender()` — When using custom (external) state management, the `.onRender()` function must be called every time right after the list has been "rendered" (including the initial render).
272
317
 
273
- * `stop()` — Stops `VirtualScroller` listening for scroll events. Should be called when the list is about to be removed from the page. Once stopped, a `VirtualScroller` can't be restarted.
318
+ * `getInitialState(): object` — Returns the initial `VirtualScroller` state for the cases when a developer configures `VirtualScroller` for custom (external) state management.
274
319
 
275
- * `getState(): object` Returns `VirtualScroller` state. Is used for React `VirtualScroller` component implementation.
320
+ * `useState({ getState, updateState })` Enables custom (external) state management.
276
321
 
277
- <!-- * `willUpdateState(newState: object, prevState: object?)` — If custom `setState` is defined, then it must call `VirtualScroller`'s `.willUpdateState()` instance method right before updating the `state`. The `prevState` argument should be `undefined` when (and only when) setting initial `state`. -->
278
- <!-- * `didUpdateState(prevState: object?)` — If custom `setState` is defined, then it must call `VirtualScroller`'s `.didUpdateState()` instance method right after updating the `state`. The `prevState` argument should be `undefined` when (and only when) setting initial `state`. -->
322
+ * `getState(): object` — Returns the externally managed `VirtualScroller` `state`.
279
323
 
280
- * `onItemHeightChange(i: number)` — Must be called whenever a list item's height changes (for example, when a user clicks an "Expand"/"Collapse" button of a list item): it re-measures the item's height and updates `VirtualScroller` layout. Every change in an item's height must come as a result of changing some kind of state, be it the item's state in `VirtualScroller` via `.onItemStateChange()`, or some other state managed by the application. Implementation-wise, calling `onItemHeightChange()` manually could be replaced with detecting item height changes automatically via [Resize Observer](https://caniuse.com/#search=Resize%20Observer).
324
+ * `updateState(stateUpdate: object)` — Updates 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 `updateState()` function, like the DOM implementation does, or the `updateState()` function could "schedule" a "re-render", like the React implementation does, in which case such `updateState()` 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.
281
325
 
282
- * `onItemStateChange(i: number, itemState: object?)` — Updates a list item's state inside `VirtualScroller` state. Must be called whenever an item's "state" changes: this way, the item's state is preserved when the item is unmounted due to going off screen, and then restored when the item is on screen again. Calling `onItemStateChange()` 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, call `onItemHeightChange(i)` after calling `onItemStateChange()`. For example, consider a social network feed, each post optionally having 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 isn't been managed in `VirtualScroller`, then, when the user expands the video, then scrolls down so that the post with the video is no longer visible and is unmounted as a result, then scrolls back up so that the post with the video is visible again, the video's expanded state would be lost, and it would be rendered as a small thumbnail as if the user didn't click on it. And don't forget about calling `onItemHeightChange(i)` in such cases: if `onItemHeightChange(i)` isn't called after expanding the thumbnail into a video player, then the scroll position would "jump" when such item goes off screen, because `VirtualScroller` would have based its calculations on the initially measured item height, not the "expanded" one.
326
+ For a usage example, see `./source/react/VirtualScroller.js`. The steps are:
283
327
 
284
- * `getItemScrollPosition(i: number): number?` — 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.
328
+ * Create a `VirtualScroller` instance.
285
329
 
286
- * `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: `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
+ * Get the initial state value via `virtualScroller.getInitialState()`.
331
+
332
+ * Initialize the externally managed state with the initial state value.
333
+
334
+ * Define `getState()` and `updateState()` functions for reading or updating the externally managed state.
335
+
336
+ * Call `virtualScroller.useState({ getState, updateState })`.
337
+
338
+ * "Render" the list and call `virtualScroller.start()`.
339
+
340
+ 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()`.
341
+
342
+ #### "Advanced" (rarely used) instance methods
343
+
344
+ * `onItemHeightChange(i: number)` — (advanced) Must be called whenever a list item's height changes (for example, when a user clicks an "Expand"/"Collapse" button of a list item): it re-measures the item's height and updates `VirtualScroller` layout. Every change in an item's height must come as a result of changing some kind of a state, be it the item's state in `VirtualScroller` via `.onItemStateChange()`, or some other state managed by the application. Implementation-wise, calling `onItemHeightChange()` manually could be replaced with detecting item height changes automatically via [Resize Observer](https://caniuse.com/#search=Resize%20Observer).
345
+
346
+ * `onItemStateChange(i: number, itemState: object?)` — (advanced) Updates a list item's state inside `VirtualScroller` state. Must be called whenever an item's "state" changes: this way, the item's state is preserved when the item is unmounted due to going off screen, and then restored when the item is on screen again. Calling `onItemStateChange()` 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, call `onItemHeightChange(i)` after calling `onItemStateChange()`. For example, consider a social network feed, each post optionally having 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 isn't been managed in `VirtualScroller`, then, when the user expands the video, then scrolls down so that the post with the video is no longer visible and is unmounted as a result, then scrolls back up so that the post with the video is visible again, the video's expanded state would be lost, and it would be rendered as a small thumbnail as if the user didn't click on it. And don't forget about calling `onItemHeightChange(i)` in such cases: if `onItemHeightChange(i)` isn't called after expanding the thumbnail into a video player, then the scroll position would "jump" when such item goes off screen, because `VirtualScroller` would have based its calculations on the initially measured item height, not the "expanded" one.
347
+
348
+ * `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.
287
349
 
288
350
  <!-- * `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. -->
289
351
 
290
- * `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, it can be called manually when the list's top position changes not as a result of scrolling the page or resizing the window. For example, if some DOM elements above the list are removed (like a closeable "info" panel) 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, and the user might be seeing a blank area where items haven't been rendered yet because they were off-screen during the previous `VirtualScroller` layout. `VirtualScroller` automatically performs a layout only on page scroll or window resize; in all other cases, when layout needs to be re-run, call it manually via this instance method.
352
+ * `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.
291
353
  </details>
292
354
 
293
355
  ## DOM
294
356
 
295
357
  `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).
296
358
 
297
- Here's an example of using `virtual-scroller/dom` component (it's basically the source code for the [DOM demo](https://catamphetamine.gitlab.io/virtual-scroller/index-dom.html)).
359
+ The DOM `VirtualScroller` component constructor accepts arguments:
360
+
361
+ * `container` — Container DOM `Element`.
362
+ * `items` — The list of items.
363
+ * `renderItem(item)` — A function that "renders" an `item` as a DOM `Element`.
364
+ * `options` — (optional) Core `VirtualScroller` options.
365
+
366
+ It `.start()`s automatically upon being created, so there's no need to call `.start()` after creating it.
298
367
 
299
368
  ```js
300
369
  import VirtualScroller from 'virtual-scroller/dom'
301
370
 
302
371
  const messages = [
303
372
  {
304
- username: ...,
305
- date: ...,
306
- text: ...
373
+ username: 'john.smith',
374
+ date: new Date(),
375
+ text: 'I woke up today'
307
376
  },
308
377
  ...
309
378
  ]
@@ -311,20 +380,24 @@ const messages = [
311
380
  function renderMessage(message) {
312
381
  // Message element.
313
382
  const root = document.createElement('article')
383
+
314
384
  // Message author.
315
385
  const author = document.createElement('a')
316
386
  author.setAttribute('href', `/users/${message.username}`)
317
387
  author.textContent = `@${message.username}`
318
388
  root.appendChild(author)
389
+
319
390
  // Message date.
320
391
  const time = document.createElement('time')
321
392
  time.setAttribute('datetime', message.date.toISOString())
322
393
  time.textContent = message.date.toString()
323
394
  root.appendChild(time)
395
+
324
396
  // Message text.
325
397
  const text = document.createElement('p')
326
398
  text.textContent = message.text
327
399
  root.appendChild(text)
400
+
328
401
  // Return message element.
329
402
  return root
330
403
  }
@@ -335,23 +408,14 @@ const virtualScroller = new VirtualScroller(
335
408
  renderMessage
336
409
  )
337
410
 
338
- // For "Single Page Apps":
339
- // router.onPageUnload(virtualScroller.stop)
411
+ // When the `VirtualScroller` component is no longer needed on the page:
412
+ // virtualScroller.stop()
340
413
  ```
341
414
  <details>
342
- <summary>Show the list of DOM <code>VirtualScroller</code> arguments and options.</summary>
415
+ <summary>Show the list of additional DOM <code>VirtualScroller</code> options.</summary>
343
416
 
344
417
  #####
345
418
 
346
- DOM `VirtualScroller` constructor takes arguments:
347
-
348
- * `container` — Items list container DOM `Element`.
349
- * `items` — The items list.
350
- * `renderItem(item)` — Renders an `item` as a DOM `Element`.
351
- * `options` — `VirtualScroller` options.
352
-
353
- Additional `options`:
354
-
355
419
  <!-- * `onMount()` — Is called before `VirtualScroller.onMount()` is called. -->
356
420
 
357
421
  * `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).
@@ -364,6 +428,10 @@ Additional `options`:
364
428
 
365
429
  #####
366
430
 
431
+ * `start()` — A proxy for the corresponding `VirtualScroller` method.
432
+
433
+ * `stop()` — A proxy for the corresponding `VirtualScroller` method.
434
+
367
435
  * `setItems(items, options)` — A proxy for the corresponding `VirtualScroller` method.
368
436
 
369
437
  * `onItemHeightChange(i)` — A proxy for the corresponding `VirtualScroller` method.
@@ -371,15 +439,23 @@ Additional `options`:
371
439
  * `onItemStateChange(i, itemState)` — A proxy for the corresponding `VirtualScroller` method.
372
440
 
373
441
  <!-- * `getItemCoordinates(i)` — A proxy for the corresponding `VirtualScroller` method. -->
374
-
375
- * `stop()` — A proxy for the corresponding `VirtualScroller` method.
376
442
  </details>
377
443
 
378
444
  ## React
379
445
 
380
446
  `virtual-scroller/react` component implements a `VirtualScroller` in a [React](https://reactjs.org/) environment.
381
447
 
382
- Here's an example of using `virtual-scroller/react` component (it's basically the source code for the [React demo](https://catamphetamine.gitlab.io/virtual-scroller)).
448
+ The required properties are:
449
+
450
+ * `items` — The list of items.
451
+
452
+ * `itemComponent` — List item React component.
453
+
454
+ * The `itemComponent` will receive a `children` property which is gonna be the item object itself (an element of the `items` array).
455
+
456
+ * 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.
457
+
458
+ #####
383
459
 
384
460
  ```js
385
461
  import React from 'react'
@@ -391,19 +467,10 @@ function Messages({ messages }) {
391
467
  <VirtualScroller
392
468
  items={messages}
393
469
  itemComponent={Message}
470
+ />
394
471
  )
395
472
  }
396
473
 
397
- const message = PropTypes.shape({
398
- username: PropTypes.string.isRequired,
399
- date: PropTypes.instanceOf(Date).isRequired,
400
- text: PropTypes.string.isRequired
401
- })
402
-
403
- Messages.propTypes = {
404
- messages: PropTypes.arrayOf(message).isRequired
405
- }
406
-
407
474
  function Message({ children: message }) {
408
475
  const {
409
476
  username,
@@ -425,85 +492,151 @@ function Message({ children: message }) {
425
492
  )
426
493
  }
427
494
 
495
+ const message = PropTypes.shape({
496
+ username: PropTypes.string.isRequired,
497
+ date: PropTypes.instanceOf(Date).isRequired,
498
+ text: PropTypes.string.isRequired
499
+ })
500
+
501
+ Messages.propTypes = {
502
+ messages: PropTypes.arrayOf(message).isRequired
503
+ }
504
+
428
505
  Message.propTypes = {
429
506
  children: message.isRequired
430
507
  }
431
508
  ```
432
509
 
433
510
  <details>
434
- <summary>Show the list of React <code>&lt;VirtualScroller/&gt;</code> properties.</summary>
511
+ <summary>Managing <code>itemComponent</code> state.</summary>
435
512
 
436
513
  #####
437
514
 
438
- * `items` The items list.
515
+ 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.
439
516
 
440
- * `itemComponent` List item component. For best performance, make sure it's a `React.PureComponent` or a `React.memo()`, otherwise it'll be re-rendering as the user scrolls and new items get shown or older ones get hidden.
517
+ 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.
441
518
 
442
- * `itemComponentProps: object` (optional) The props passed to `itemComponent`.
519
+ To fix that, `itemComponent` receives the following state management properties:
443
520
 
444
- * `as` — A component used as a container for the list items. Is `"div"` by default.
521
+ * `state` — Saved state of the item component. Use this property as the initial value for the item component state.
445
522
 
446
- * `estimatedItemHeight: number` (optional) The `estimatedItemHeight` option of `VirtualScroller` class.
523
+ * In the example described above, `state` might look like `{ expanded: true }`.
447
524
 
448
- * `bypass: boolean` (optional) The `bypass` option of `VirtualScroller` class.
525
+ * This is simply a proxy for `virtualScroller.getState().itemStates[i]`.
449
526
 
450
- * `preserveScrollPositionOnPrependItems: boolean` — (optional) The `preserveScrollPositionOnPrependItems` option of `VirtualScroller.setItems()` method.
527
+ * `onStateChange(newItemState)` — Use this function to save the item component state whenever it changes.
451
528
 
452
- * `measureItemsBatchSize: number` (optional) The `measureItemsBatchSize` option of `VirtualScroller`.
529
+ * In the example described above, `onStateChange()` would be called whenever a user clicks a "Show more"/"Show less" button.
453
530
 
454
- * `getColumnsCount(): number` (optional) The `getColumnsCount()` option of `VirtualScroller`.
531
+ * This is simply a proxy for `virtualScroller.onItemStateChange(i, itemState)`.
455
532
 
456
- <!-- * `onMount()` — (optional) Is called after `<VirtualScroller/>` component has been mounted and before `VirtualScroller.onMount()` is called. -->
533
+ * `onHeightChange()` — Call this function whenever the item element height changes.
457
534
 
458
- * `getItemId(item): any` (optional) 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.
535
+ * In the example described above, `onHeightChange()` would be called whenever a user clicks a "Show more"/"Show less" button, 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.
459
536
 
460
- * `onItemInitialRender(item)` (optional) The `onItemInitialRender` option of `VirtualScroller` class.
537
+ * This is simply a proxy for `virtualScroller.onItemHeightChange(i)`.
461
538
 
462
- * `shouldUpdateLayoutOnScreenResize(event)` — (optional) The `shouldUpdateLayoutOnScreenResize` option of `VirtualScroller` class.
539
+ ```js
540
+ function ItemComponent({
541
+ state: savedState,
542
+ onStateChange,
543
+ onHeightChange,
544
+ children: item
545
+ }) {
546
+ const [state, setState] = useState(savedState)
547
+
548
+ useLayoutEffect(() => {
549
+ onStateChange(state)
550
+ onHeightChange()
551
+ }, [state])
463
552
 
464
- * `initialState: object` — (optional) The initial state for `VirtualScroller`: the `state` option of `VirtualScroller`. For example, can be used to quicky restore the list on "Back" navigation.
553
+ return (
554
+ <section>
555
+ <h1>
556
+ {item.title}
557
+ </h1>
558
+ {state.expanded &&
559
+ <p>{item.text}</p>
560
+ }
561
+ <button onClick={() => {
562
+ setState({
563
+ ...state,
564
+ expanded: !expanded
565
+ })
566
+ }}>
567
+ {state.expanded ? 'Show less' : 'Show more'}
568
+ </button>
569
+ </section>
570
+ )
571
+ }
572
+ ```
573
+ </details>
465
574
 
466
- * `initialCustomState: object` — (advanced) (optional) The initial "custom" state for `VirtualScroller`: the `customState` 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.
575
+ #####
467
576
 
468
- * `onStateChange(newState: object, prevState: object)` — (optional) Is called whenever `VirtualScroller` `state` is updated (including setting the initial `state`). For example, can be used to keep `VirtualScroller` `state` copy in an instance variable and later in `componentWillUnmount()` persist it somewhere in global application state for quickly restoring it later on "Back" navigation:
577
+ <details>
578
+ <summary>Show the list of React <code>&lt;VirtualScroller/&gt;</code> optional properties.</summary>
579
+
580
+ #####
581
+
582
+ 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.
583
+
584
+ * `itemComponentProps: object` — The props passed to `itemComponent`.
585
+
586
+ * `getColumnsCount(): number` — The `getColumnsCount()` option of `VirtualScroller`.
587
+
588
+ * `as` — A component used as a container for the list items. Is `"div"` by default.
589
+
590
+ * `initialState: object` — The initial state for `VirtualScroller`: the `state` option of `VirtualScroller`. For example, can be used to quicky restore the list on "Back" navigation.
591
+
592
+ <!-- * `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. -->
593
+
594
+ * `onStateChange(newState: object, previousState: object?)` — The `onStateChange` option of `VirtualScroller`. Could be used to restore a `VirtualScroller` state on "Back" navigation:
469
595
 
470
596
  ```js
471
597
  import {
472
- getVirtualScrollerState,
473
- setVirtualScrollerState
474
- } from './globalState'
598
+ readVirtualScrollerState,
599
+ saveVirtualScrollerState
600
+ } from './globalStorage'
475
601
 
476
- class Example extends React.Component {
477
- componentWillUnmount() {
478
- saveVirtualScrollerState(this.virtualScrollerState)
479
- }
480
- render() {
481
- return (
482
- <VirtualScroller
483
- items={...}
484
- itemComponent={...}
485
- state={hasUserNavigatedBack ? getVirtualScrollerState() : undefined}
486
- onStateChange={state => this.virtualScrollerState = state}/>
487
- )
488
- }
602
+ function Example() {
603
+ const virtualScrollerState = useRef()
604
+
605
+ useEffect(() => {
606
+ return () => {
607
+ // Save `VirtualScroller` state before the page unmounts.
608
+ saveVirtualScrollerState(virtualScrollerState.current)
609
+ }
610
+ })
611
+
612
+ return (
613
+ <VirtualScroller
614
+ items={...}
615
+ itemComponent={...}
616
+ state={hasUserNavigatedBack ? readVirtualScrollerState() : undefined}
617
+ onStateChange={state => virtualScrollerState.current = state}
618
+ />
619
+ )
489
620
  }
490
621
  ```
491
- </details>
492
622
 
493
- #####
623
+ * `preserveScrollPositionOnPrependItems: boolean` — The `preserveScrollPositionOnPrependItems` option of `VirtualScroller.setItems()` method.
494
624
 
495
- <details>
496
- <summary>Show the list of properties passed to <code>itemComponent</code>.</summary>
625
+ * `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.
497
626
 
498
- #####
627
+ * `bypass: boolean` — The `bypass` option of `VirtualScroller` class.
628
+
629
+ * `tbody: boolean` — The `tbody` option of `VirtualScroller` class.
499
630
 
500
- * `children` — The list item (an element of the `items` array).
631
+ * `estimatedItemHeight: number` — The `estimatedItemHeight` option of `VirtualScroller` class.
501
632
 
502
- * `state` — (advanced) List item element state. If a list item element renders differently depending on some "state" then that state should be "managed" (stored and later restored) as the list item becomes hidden and later visible again. See `onStateChange` property description.
633
+ * `measureItemsBatchSize: number` — The `measureItemsBatchSize` option of `VirtualScroller`.
503
634
 
504
- * `onStateChange(newItemState)` — (advanced) Can be called to save the list item element state when it changes. The need for saving and restoring list item element state arises because item elements get unmounted as they go off screen. 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. To prevent that, define a "state" of an item element — for example, `{ expanded: true }` — and then call `onStateChange(newState)` every time the item element state changes, and read that state from the `state` property when rendering the item element. Calling `onStateChange()` simply updates the item element `state`, and doesn't re-render the item element: it's just a proxy for `VirtualScroller.onItemStateChange(i, itemState)`.
635
+ <!-- * `onMount()` — Is called after `<VirtualScroller/>` component has been mounted and before `VirtualScroller.onMount()` is called. -->
505
636
 
506
- * `onHeightChange()` — (advanced) Call this function whenever the item element height changes. In the example above, `onHeightChange()` should be called when a user clicks a "Show more"/"Show less" button 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. This is simply a proxy for `VirtualScroller.onItemHeightChange(i)`.
637
+ * `onItemInitialRender(item)` — The `onItemInitialRender` option of `VirtualScroller` class.
638
+
639
+ <!-- * `shouldUpdateLayoutOnScreenResize(event)` — The `shouldUpdateLayoutOnScreenResize` option of `VirtualScroller` class. -->
507
640
  </details>
508
641
 
509
642
  #####
@@ -513,42 +646,20 @@ class Example extends React.Component {
513
646
 
514
647
  #####
515
648
 
516
- * `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 find the index of the item by itself.
649
+ <!--
650
+ * `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)`.
651
+ -->
517
652
 
518
653
  <!-- * `getItemCoordinates(i)` — A proxy for the corresponding `VirtualScroller` method. -->
519
654
 
520
655
  * `updateLayout()` — A proxy for the corresponding `VirtualScroller` method.
521
656
  </details>
522
657
 
523
- ## Rendering Engine
524
-
525
- `VirtualScroller` is written in such a way that it supports any type of a rendering engine, not just DOM. For example, it could support something like React Native or `<canvas/>`: for that, someone would have to write custom versions of [`Screen.js`](https://gitlab.com/catamphetamine/virtual-scroller/-/blob/master/source/DOM/Screen.js) and [`ScrollableContainer.js`](https://gitlab.com/catamphetamine/virtual-scroller/-/blob/master/source/DOM/ScrollableContainer.js), and then instruct `VirtualScroller` to use those instead of the default ones by passing custom `engine` object when constructing a `VirtualScroller` instance:
526
-
527
- ```js
528
- import VirtualScroller from 'virtual-scroller'
529
-
530
- import Container from './Container'
531
- import ScrollableContainer from './ScrollableContainer'
532
-
533
- new VirtualScroller(getItemsContainerElement, items, {
534
- scrollableContainer,
535
- engine: {
536
- createItemsContainer(getItemsContainerElement) {
537
- return new Container(getItemsContainerElement)
538
- },
539
- createScrollableContainer(scrollableContainer, getItemsContainerElement) {
540
- return new ScrollableContainer(scrollableContainer, getItemsContainerElement)
541
- }
542
- },
543
- ...
544
- })
545
- ```
546
-
547
- `getItemsContainerElement()` function would simply return a list "element", whatever that could mean. The concept of an "element" is "something, that can be rendered", so it could be anything, not just a DOM Element. Any operations with "elements" are done either in `Container.js` or in `ScrollableContainer.js`: `Container.js` defines the operations that could be applied to the list "container", or its items, such as getting its height or getting an items' height, and `ScrollableContainer.js` defines the operations that could be applied to a "scrollable container", such as getting its dimensions, listening for "resize" and "scroll" events, controlling scroll position, etc.
548
-
549
658
  ## Dynamically Loaded Lists
550
659
 
551
- All previous examples described cases with a static `items` list. When there's a need to update the `items` list dynamically, one can use `virtualScroller.setItems(newItems)` instance method. For example, when the user clicks "Show previous items" button, the `newItems` should be `previousItems.concat(currentlyShownItems)`, and when the user clicks "Show next items" button, the `newItems` should be `currentlyShownItems.concat(nextItems)`.
660
+ 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:
661
+ * When the user clicks "Show previous items" button, the `newItems` argument should be `previousItems.concat(currentlyShownItems)`.
662
+ * When the user clicks "Show next items" button, the `newItems` argument should be `currentlyShownItems.concat(nextItems)`.
552
663
 
553
664
  <details>
554
665
  <summary>Find out what are "incremental" and "non-incremental" items updates, and why "incremental" updates are better.</summary>
@@ -653,15 +764,23 @@ An example of a `:first-child`/`:last-child` style that will not work correctly
653
764
 
654
765
  ### Resize
655
766
 
656
- When the container width changes, all items' heights must be recalculated because some CSS [`@media()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) rules might have been added or removed. 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 rendered again, so `VirtualScroller` snapshots those items' heights before the resize, and then uses those snapshotted heights until the items are re-measured when they become visible again as the user scrolls up.
767
+ When the container width changes, all items' heights must be recalculated because:
768
+
769
+ * If item elements render multi-line text, the lines count might've changed because there's more or less width available now.
770
+
771
+ * Some CSS [`@media()`](https://developer.mozilla.org/en-US/docs/Web/CSS/Media_Queries) rules might have been added or removed, affecting item layout.
772
+
773
+ 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.
657
774
 
658
- Also, when such snapshotted upper items get re-rendered and re-measured, the scroll position has to be corrected to avoid ["content jumping"](https://css-tricks.com/content-jumping-avoid/).
775
+ 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/).
659
776
 
660
777
  <details>
661
- <summary>Correcting scroll position though doesn't seem to work in a particular case when using Chrome web browser on a desktop</summary>
778
+ <summary>I found a single edge case when the automatic correction of scroll position doesn't seem to work.</summary>
662
779
 
663
780
  #####
664
781
 
782
+ (was reproduced in Chrome web browser on a desktop)
783
+
665
784
  When the user scrolls up past the "prerender margin", which equals to the screen height by default, the list content does "jump" because the web browser doesn't want to apply the scroll position correction while scrolling for some weird reason. Looks like a bug in the web browser.
666
785
 
667
786
  ```
@@ -706,20 +825,24 @@ var unlisten = () => document.removeEventListener('scroll', listener)
706
825
  // `scrollToY()` method in `./source/DOM/ScrollableContainer.js`.
707
826
  ```
708
827
 
709
- Also, pressing the "Home" key wouldn't scroll up past the "prerender margin", which is equal to the screen height by default. The reason is the same: applying scroll position correction while the "Home" key is pressed cancels the effect of the "Home" button.
828
+ Also, pressing the "Home" key wouldn't scroll up past the "prerender margin", which is equal to the screen height by default. The reason is the same: applying scroll position correction while the "Home" key is pressed cancels the effect of pressing the "Home" key.
710
829
 
711
- A possible workaround for those bugs would be postponing scroll position correction until the user stops scrolling, and instead change `margin-bottom` of some "spacer" element at the top of the list (or maybe even before the list). When the user stops scrolling, the scroll position would get corrected by the value of `margin-bottom` of that "spacer" element, after which the `margin-bottom` value on that "spacer" element would be reset. But this type of a workaround would only work in a DOM environment because it requires the support of "negative" margin.
830
+ A hypothetical workaround for this edge case bug could be rewriting the scroll position automatic correction code to postpone scroll position correction until the user stops scrolling, and instead change `margin-bottom` of some "spacer" element at the top of the list (or maybe even before the list). When the user stops scrolling, the scroll position would get corrected by the value of `margin-bottom` of that "spacer" element, after which the `margin-bottom` value on that "spacer" element would be reset. But this type of a workaround would only work in a DOM environment because it requires the support of "negative" margin.
712
831
 
713
832
  For now, I don't see it as a bug that would be worth fixing. The user could just refresh the page, or not scroll up at all because they've already seen that content.
714
833
  </details>
715
834
 
716
835
  #####
717
836
 
718
- The "before resize" snapshot is stored in `VirtualScroller` state in `beforeResize` object: `itemHeights: number[]`, `verticalSpacing: number`, `columnsCount: number`.
837
+ The "before resize" layout parameters snapshot is stored in `VirtualScroller` state in `beforeResize` object:
838
+
839
+ * `itemHeights: number[]`
840
+ * `verticalSpacing: number`
841
+ * `columnsCount: number`
719
842
 
720
843
  ### `<tbody/>`
721
844
 
722
- Due to the [inherent limitations](https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1) of the `<tbody/>` HTML tag, when used as a container for the list items, a workaround involving CSS variables has to be used, 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).
845
+ 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.
723
846
 
724
847
  ### Search, focus management.
725
848
 
@@ -743,7 +866,7 @@ For example, consider a page:
743
866
  </div>
744
867
  ```
745
868
 
746
- 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`'s `.render()` has already been called and it won't re-render until the user scrolls or the window is resized.
869
+ 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.
747
870
 
748
871
  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.
749
872
  </details>
@@ -752,6 +875,34 @@ This type of a bug doesn't occur in production, but it can appear in development
752
875
 
753
876
  Set `window.VirtualScrollerDebug` to `true` to output debug messages to `console`.
754
877
 
878
+ ## Rendering Engine
879
+
880
+ (advanced)
881
+
882
+ `VirtualScroller` is written in such a way that it supports any type of a rendering engine, not just DOM. For example, it could support something like React Native or `<canvas/>`: for that, someone would have to write custom versions of [`Screen.js`](https://gitlab.com/catamphetamine/virtual-scroller/-/blob/master/source/DOM/Screen.js) and [`ScrollableContainer.js`](https://gitlab.com/catamphetamine/virtual-scroller/-/blob/master/source/DOM/ScrollableContainer.js), and then instruct `VirtualScroller` to use those instead of the default ones by passing custom `engine` object when constructing a `VirtualScroller` instance:
883
+
884
+ ```js
885
+ import VirtualScroller from 'virtual-scroller'
886
+
887
+ import Container from './Container'
888
+ import ScrollableContainer from './ScrollableContainer'
889
+
890
+ new VirtualScroller(getItemsContainerElement, items, {
891
+ getScrollableContainer,
892
+ engine: {
893
+ createItemsContainer(getItemsContainerElement) {
894
+ return new Container(getItemsContainerElement)
895
+ },
896
+ createScrollableContainer(getScrollableContainer, getItemsContainerElement) {
897
+ return new ScrollableContainer(getScrollableContainer, getItemsContainerElement)
898
+ }
899
+ },
900
+ ...
901
+ })
902
+ ```
903
+
904
+ `getItemsContainerElement()` function would simply return a list "element", whatever that could mean. The concept of an "element" is "something, that can be rendered", so it could be anything, not just a DOM Element. Any operations with "elements" are done either in `Container.js` or in `ScrollableContainer.js`: `Container.js` defines the operations that could be applied to the list "container", or its items, such as getting its height or getting an items' height, and `ScrollableContainer.js` defines the operations that could be applied to a "scrollable container", such as getting its dimensions, listening for "resize" and "scroll" events, controlling scroll position, etc.
905
+
755
906
  ## CDN
756
907
 
757
908
  One can use any npm CDN service, e.g. [unpkg.com](https://unpkg.com) or [jsdelivr.net](https://jsdelivr.net)
@@ -814,6 +965,32 @@ I've fantasised a bit about moving to `transforms` in this library's `DOM` and `
814
965
  The points listed above aren't something difficult to implement, it's just that I don't want to do it unless there're any real observed performance issues related to the "reflows" during scrolling. "If it works, no need to change it".
815
966
  </details>
816
967
 
968
+ ## Tests
969
+
970
+ This component comes with about 80% code coverage (for the core `VirtualScroller`).
971
+
972
+ To run tests:
973
+
974
+ ```
975
+ npm test
976
+ ```
977
+
978
+ To generate a code coverage report:
979
+
980
+ ```
981
+ npm run test-coverage
982
+ ```
983
+
984
+ The code coverage report can be viewed by opening `./coverage/lcov-report/index.html`.
985
+
986
+ The `handlebars@4.5.3` [work](https://github.com/handlebars-lang/handlebars.js/issues/1646#issuecomment-578306544)[around](https://github.com/facebook/jest/issues/9396#issuecomment-573328488) in `devDependencies` is for the test coverage to not produce empty reports:
987
+
988
+ ```
989
+ Handlebars: Access has been denied to resolve the property "statements" because it is not an "own property" of its parent.
990
+ You can add a runtime option to disable the check or this warning:
991
+ See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details
992
+ ```
993
+
817
994
  ## GitHub
818
995
 
819
996
  On March 9th, 2020, GitHub, Inc. silently [banned](https://medium.com/@catamphetamine/how-github-blocked-me-and-all-my-libraries-c32c61f061d3) my account (erasing all my repos, issues and comments) without any notice or explanation. Because of that, all source codes had to be promptly moved to GitLab. The [GitHub repo](https://github.com/catamphetamine/virtual-scroller) is now only used as a backup (you can star the repo there too), and the primary repo is now the [GitLab one](https://gitlab.com/catamphetamine/virtual-scroller). Issues can be reported in any repo.