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
@@ -1,33 +1,19 @@
1
- function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) { symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); } keys.push.apply(keys, symbols); } return keys; }
1
+ function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); enumerableOnly && (symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; })), keys.push.apply(keys, symbols); } return keys; }
2
2
 
3
- function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
3
+ function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = null != arguments[i] ? arguments[i] : {}; i % 2 ? ownKeys(Object(source), !0).forEach(function (key) { _defineProperty(target, key, source[key]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)) : ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } return target; }
4
4
 
5
5
  function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
6
6
 
7
7
  function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
8
8
 
9
- function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
9
+ function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); Object.defineProperty(Constructor, "prototype", { writable: false }); return Constructor; }
10
10
 
11
11
  function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
12
12
 
13
- // For some weird reason, in Chrome, `setTimeout()` would lag up to a second (or more) behind.
14
- // Turns out, Chrome developers have deprecated `setTimeout()` API entirely without asking anyone.
15
- // Replacing `setTimeout()` with `requestAnimationFrame()` can work around that Chrome bug.
16
- // https://github.com/bvaughn/react-virtualized/issues/722
17
- import { setTimeout, clearTimeout } from 'request-animation-frame-timeout';
18
- import { supportsTbody, BROWSER_NOT_SUPPORTED_ERROR, addTbodyStyles, setTbodyPadding } from './DOM/tbody';
19
- import DOMEngine from './DOM/Engine';
20
- import Layout, { LAYOUT_REASON } from './Layout';
21
- import Resize from './Resize';
22
- import BeforeResize from './BeforeResize';
23
- import Scroll from './Scroll';
24
- import ListHeightChangeWatcher from './ListHeightChangeWatcher';
25
- import ItemHeights from './ItemHeights';
26
- import _getItemsDiff from './getItemsDiff';
27
- import getVerticalSpacing from './getVerticalSpacing';
28
- import log, { warn, isDebug, reportError } from './utility/debug';
29
- import shallowEqual from './utility/shallowEqual';
30
- import getStateSnapshot from './utility/getStateSnapshot';
13
+ import VirtualScrollerConstructor from './VirtualScroller.constructor.js';
14
+ import { hasTbodyStyles, addTbodyStyles } from './DOM/tbody.js';
15
+ import { LAYOUT_REASON } from './Layout.js';
16
+ import log from './utility/debug.js';
31
17
 
32
18
  var VirtualScroller = /*#__PURE__*/function () {
33
19
  /**
@@ -43,989 +29,155 @@ var VirtualScroller = /*#__PURE__*/function () {
43
29
 
44
30
  _classCallCheck(this, VirtualScroller);
45
31
 
46
- _defineProperty(this, "getActualColumnsCountForState", function () {
47
- return _this._getColumnsCount ? _this._getColumnsCount(_this.scrollableContainer) : undefined;
48
- });
49
-
50
- _defineProperty(this, "getVerticalSpacing", function () {
51
- return _this.verticalSpacing || 0;
52
- });
53
-
54
- _defineProperty(this, "getListTopOffsetInsideScrollableContainer", function () {
55
- var listTopOffset = _this.scrollableContainer.getItemsContainerTopOffset();
56
-
57
- if (_this.listTopOffsetWatcher) {
58
- _this.listTopOffsetWatcher.onListTopOffset(listTopOffset);
59
- }
60
-
61
- return listTopOffset;
62
- });
63
-
64
32
  _defineProperty(this, "stop", function () {
65
- _this.isRendered = false;
66
-
67
- _this.resize.stop();
68
-
69
- _this.scroll.stop();
70
-
71
- if (_this.listTopOffsetWatcher) {
72
- _this.listTopOffsetWatcher.stop();
33
+ if (!_this._isActive) {
34
+ throw new Error('[virtual-scroller] Can\'t stop a `VirtualScroller` that hasn\'t been started');
73
35
  }
74
36
 
75
- _this.cancelLayoutTimer({});
76
- });
77
-
78
- _defineProperty(this, "willUpdateState", function (newState, prevState) {
79
- // Ignore setting initial state.
80
- if (!prevState) {
81
- return;
82
- } // This function isn't currently used.
83
- // Was previously used to capture scroll position in order to
84
- // restore it later after the new state is rendered.
85
-
86
- });
87
-
88
- _defineProperty(this, "didUpdateState", function (prevState) {
89
- var newState = _this.getState();
90
-
91
- if (_this.onStateChange) {
92
- if (!shallowEqual(newState, prevState)) {
93
- _this.onStateChange(newState, prevState);
94
- }
95
- } // Ignore setting initial state.
96
-
97
-
98
- if (!prevState) {
99
- return;
100
- }
101
-
102
- if (!_this.isRendered) {
103
- return;
104
- }
105
-
106
- log('~ Rendered ~');
107
-
108
- if (isDebug()) {
109
- log('State', getStateSnapshot(newState));
110
- }
111
-
112
- var layoutUpdateReason;
113
-
114
- if (_this.firstNonMeasuredItemIndex !== undefined) {
115
- layoutUpdateReason = LAYOUT_REASON.ACTUAL_ITEM_HEIGHTS_HAVE_BEEN_MEASURED;
116
- }
117
-
118
- if (_this.resetLayoutAfterResize) {
119
- layoutUpdateReason = LAYOUT_REASON.VIEWPORT_WIDTH_CHANGED;
120
- } // If `this.resetLayoutAfterResize` flag was reset after calling
121
- // `this.measureItemHeightsAndSpacingAndUpdateTablePadding()`
122
- // then there would be a bug because
123
- // `this.measureItemHeightsAndSpacingAndUpdateTablePadding()`
124
- // calls `this.setState({ verticalSpacing })` which calls
125
- // `this.didUpdateState()` immediately, so `this.resetLayoutAfterResize`
126
- // flag wouldn't be reset by that time and would trigger things
127
- // like `this.itemHeights.reset()` a second time.
128
- //
129
- // So, instead read the value of `this.resetLayoutAfterResize` flag
130
- // and reset it right away to prevent any such potential bugs.
131
- //
132
-
133
-
134
- var resetLayoutAfterResize = _this.resetLayoutAfterResize; // Reset `this.firstNonMeasuredItemIndex`.
135
-
136
- _this.firstNonMeasuredItemIndex = undefined; // Reset `this.resetLayoutAfterResize` flag.
137
-
138
- _this.resetLayoutAfterResize = undefined; // Reset `this.newItemsWillBeRendered` flag.
139
-
140
- _this.newItemsWillBeRendered = undefined; // Reset `this.itemHeightsThatChangedWhileNewItemsWereBeingRendered`.
141
-
142
- _this.itemHeightsThatChangedWhileNewItemsWereBeingRendered = undefined; // Reset `this.itemStatesThatChangedWhileNewItemsWereBeingRendered`.
143
-
144
- _this.itemStatesThatChangedWhileNewItemsWereBeingRendered = undefined;
145
-
146
- if (resetLayoutAfterResize) {
147
- // Reset measured item heights on viewport width change.
148
- _this.itemHeights.reset(); // Reset `verticalSpacing` (will be re-measured).
149
-
150
-
151
- _this.verticalSpacing = undefined;
152
- }
153
-
154
- var previousItems = prevState.items;
155
- var newItems = newState.items; // Even if `this.newItemsWillBeRendered` flag is `true`,
156
- // `newItems` could still be equal to `previousItems`.
157
- // For example, when `setState()` calls don't update `state` immediately
158
- // and a developer first calls `setItems(newItems)` and then calls `setItems(oldItems)`:
159
- // in that case, `this.newItemsWillBeRendered` flag will be `true` but the actual `items`
160
- // in state wouldn't have changed due to the first `setState()` call being overwritten
161
- // by the second `setState()` call (that's called "batching state updates" in React).
162
-
163
- if (newItems !== previousItems) {
164
- var itemsDiff = _this.getItemsDiff(previousItems, newItems);
165
-
166
- if (itemsDiff) {
167
- // The call to `.onPrepend()` must precede the call to `.measureItemHeights()`
168
- // which is called in `.onRendered()`.
169
- // `this.itemHeights.onPrepend()` updates `firstMeasuredItemIndex`
170
- // and `lastMeasuredItemIndex` of `this.itemHeights`.
171
- var prependedItemsCount = itemsDiff.prependedItemsCount;
172
-
173
- _this.itemHeights.onPrepend(prependedItemsCount);
174
- } else {
175
- _this.itemHeights.reset(); // `newState.itemHeights` is an array of `undefined`s.
176
-
177
-
178
- _this.itemHeights.initialize(newState.itemHeights);
179
- }
180
-
181
- if (!resetLayoutAfterResize) {
182
- // The call to `this.onNewItemsRendered()` must precede the call to
183
- // `.measureItemHeights()` which is called in `.onRendered()` because
184
- // `this.onNewItemsRendered()` updates `firstMeasuredItemIndex` and
185
- // `lastMeasuredItemIndex` of `this.itemHeights` in case of a prepend.
186
- //
187
- // If after prepending items the scroll position
188
- // should be "restored" so that there's no "jump" of content
189
- // then it means that all previous items have just been rendered
190
- // in a single pass, and there's no need to update layout again.
191
- //
192
- if (_this.onNewItemsRendered(itemsDiff, newState) !== 'SEAMLESS_PREPEND') {
193
- layoutUpdateReason = LAYOUT_REASON.ITEMS_CHANGED;
194
- }
195
- }
196
- }
197
-
198
- var stateUpdate; // Re-measure item heights.
199
- // Also, measure vertical spacing (if not measured) and fix `<table/>` padding.
200
- //
201
- // This block should go after `if (newItems !== previousItems) {}`
202
- // because `this.itemHeights` can get `.reset()` there, which would
203
- // discard all the measurements done here, and having currently shown
204
- // item height measurements is required.
205
- //
206
-
207
- if (newState.firstShownItemIndex !== prevState.firstShownItemIndex || newState.lastShownItemIndex !== prevState.lastShownItemIndex || newState.items !== prevState.items || resetLayoutAfterResize) {
208
- var verticalSpacingStateUpdate = _this.measureItemHeightsAndSpacingAndUpdateTablePadding();
209
-
210
- if (verticalSpacingStateUpdate) {
211
- stateUpdate = _objectSpread(_objectSpread({}, stateUpdate), verticalSpacingStateUpdate);
212
- }
213
- } // Clean up "before resize" item heights and adjust the scroll position accordingly.
214
- // Calling `this.beforeResize.cleanUpBeforeResizeItemHeights()` might trigger
215
- // a `this.setState()` call but that wouldn't matter because `beforeResize`
216
- // properties have already been modified directly in `state` (a hacky technique)
217
-
218
-
219
- var cleanedUpBeforeResize = _this.beforeResize.cleanUpBeforeResizeItemHeights(prevState);
220
-
221
- if (cleanedUpBeforeResize !== undefined) {
222
- var scrollBy = cleanedUpBeforeResize.scrollBy,
223
- beforeResize = cleanedUpBeforeResize.beforeResize;
224
- log('Correct scroll position by', scrollBy);
225
-
226
- _this.scroll.scrollByY(scrollBy);
227
-
228
- stateUpdate = _objectSpread(_objectSpread({}, stateUpdate), {}, {
229
- beforeResize: beforeResize
230
- });
231
- }
232
-
233
- if (layoutUpdateReason) {
234
- _this.updateStateRightAfterRender({
235
- stateUpdate: stateUpdate,
236
- reason: layoutUpdateReason
237
- });
238
- } else if (stateUpdate) {
239
- _this.setState(stateUpdate);
240
- }
241
- });
242
-
243
- _defineProperty(this, "updateShownItemIndexes", function (_ref) {
244
- var stateUpdate = _ref.stateUpdate;
245
- var startedAt = Date.now(); // Get shown item indexes.
246
-
247
- var _this$getShownItemInd = _this.getShownItemIndexes(),
248
- firstShownItemIndex = _this$getShownItemInd.firstShownItemIndex,
249
- lastShownItemIndex = _this$getShownItemInd.lastShownItemIndex,
250
- shownItemsHeight = _this$getShownItemInd.shownItemsHeight,
251
- firstNonMeasuredItemIndex = _this$getShownItemInd.firstNonMeasuredItemIndex; // If scroll position is scheduled to be restored after render,
252
- // then the "anchor" item must be rendered, and all of the prepended
253
- // items before it, all in a single pass. This way, all of the
254
- // prepended items' heights could be measured right after the render
255
- // has finished, and the scroll position can then be immediately restored.
256
-
257
-
258
- if (_this.listHeightChangeWatcher.hasSnapshot()) {
259
- if (lastShownItemIndex < _this.listHeightChangeWatcher.getAnchorItemIndex()) {
260
- lastShownItemIndex = _this.listHeightChangeWatcher.getAnchorItemIndex();
261
- } // `firstShownItemIndex` is always `0` when prepending items.
262
- // And `lastShownItemIndex` always covers all prepended items in this case.
263
- // None of the prepended items have been rendered before,
264
- // so their heights are unknown. The code at the start of this function
265
- // did therefore set `firstNonMeasuredItemIndex` to non-`undefined`
266
- // in order to render just the first prepended item in order to
267
- // measure it, and only then make a decision on how many other
268
- // prepended items to render. But since we've instructed the code
269
- // to show all of the prepended items at once, there's no need to
270
- // "redo layout after render". Additionally, if layout was re-done
271
- // after render, then there would be a short interval of visual
272
- // "jitter" due to the scroll position not being restored because it'd
273
- // wait for the second layout to finish instead of being restored
274
- // right after the first one.
275
-
276
-
277
- firstNonMeasuredItemIndex = undefined;
278
- } // Validate the heights of items to be hidden on next render.
279
- // For example, a user could click a "Show more" button,
280
- // or an "Expand YouTube video" button, which would result
281
- // in the actual height of the list item being different
282
- // from what has been initially measured in `this.itemHeights[i]`,
283
- // if the developer didn't call `.onItemStateChange()` and `.onItemHeightChange(i)`.
284
-
285
-
286
- if (!_this.validateWillBeHiddenItemHeightsAreAccurate(firstShownItemIndex, lastShownItemIndex)) {
287
- log('~ Because some of the will-be-hidden item heights (listed above) have changed since they\'ve last been measured, redo layout. ~'); // Redo layout, now with the correct item heights.
288
-
289
- return _this.updateShownItemIndexes({
290
- stateUpdate: stateUpdate
291
- });
292
- } // Measure "before" items height.
293
-
294
-
295
- var beforeItemsHeight = _this.layout.getBeforeItemsHeight(firstShownItemIndex); // Measure "after" items height.
296
-
297
-
298
- var afterItemsHeight = _this.layout.getAfterItemsHeight(lastShownItemIndex, _this.getItemsCount());
299
-
300
- var layoutDuration = Date.now() - startedAt; // Debugging.
301
-
302
- log('~ Layout values ' + (_this.bypass ? '(bypass) ' : '') + '~');
303
-
304
- if (layoutDuration < SLOW_LAYOUT_DURATION) {// log('Calculated in', layoutDuration, 'ms')
305
- } else {
306
- warn('Layout calculated in', layoutDuration, 'ms');
307
- }
308
-
309
- if (_this._getColumnsCount) {
310
- log('Columns count', _this.getColumnsCount());
311
- }
312
-
313
- log('First shown item index', firstShownItemIndex);
314
- log('Last shown item index', lastShownItemIndex);
315
- log('Before items height', beforeItemsHeight);
316
- log('After items height (actual or estimated)', afterItemsHeight);
317
- log('Average item height (used for estimated after items height calculation)', _this.itemHeights.getAverage());
318
-
319
- if (isDebug()) {
320
- log('Item heights', _this.getState().itemHeights.slice());
321
- log('Item states', _this.getState().itemStates.slice());
322
- } // Optionally preload items to be rendered.
323
-
324
-
325
- _this.onBeforeShowItems(_this.getState().items, _this.getState().itemHeights, firstShownItemIndex, lastShownItemIndex); // Set `this.firstNonMeasuredItemIndex`.
326
-
327
-
328
- _this.firstNonMeasuredItemIndex = firstNonMeasuredItemIndex; // Set "previously calculated layout".
329
- //
330
- // The "previously calculated layout" feature is not currently used.
331
- //
332
- // The current layout snapshot could be stored as a "previously calculated layout" variable
333
- // so that it could theoretically be used when calculating new layout incrementally
334
- // rather than from scratch, which would be an optimization.
335
- //
336
- // Currently, this feature is not used, and `shownItemsHeight` property
337
- // is not returned at all, so don't set any "previously calculated layout".
338
- //
339
-
340
- if (shownItemsHeight === undefined) {
341
- _this.previouslyCalculatedLayout = undefined;
342
- } else {
343
- // If "previously calculated layout" feature would be implmeneted,
344
- // then this code would set "previously calculate layout" instance variable.
345
- //
346
- // What for would this instance variable be used?
347
- //
348
- // Instead of using a `this.previouslyCalculatedLayout` instance variable,
349
- // this code could use `this.getState()` because it reflects what's currently on screen,
350
- // but there's a single edge case when it could go out of sync —
351
- // updating item heights externally via `.onItemHeightChange(i)`.
352
- //
353
- // If, for example, an item height was updated externally via `.onItemHeightChange(i)`
354
- // then `this.getState().itemHeights` would get updated immediately but
355
- // `this.getState().beforeItemsHeight` or `this.getState().afterItemsHeight`
356
- // would still correspond to the previous item height, so those would be "stale".
357
- // On the other hand, same values in `this.previouslyCalculatedLayout` instance variable
358
- // can also be updated immediately, so they won't go out of sync with the updated item height.
359
- // That seems the only edge case when using a separate `this.previouslyCalculatedLayout`
360
- // instance variable instead of using `this.getState()` would theoretically be justified.
361
- //
362
- _this.previouslyCalculatedLayout = {
363
- firstShownItemIndex: firstShownItemIndex,
364
- lastShownItemIndex: lastShownItemIndex,
365
- beforeItemsHeight: beforeItemsHeight,
366
- shownItemsHeight: shownItemsHeight
367
- };
368
- } // Update `VirtualScroller` state.
369
- // `VirtualScroller` automatically re-renders on state updates.
370
- //
371
- // All `state` properties updated here should be overwritten in
372
- // the implementation of `setItems()` and `onResize()` methods
373
- // so that the `state` is not left in an inconsistent state
374
- // whenever there're concurrent `setState()` updates that could
375
- // possibly conflict with one another — instead, those state updates
376
- // should overwrite each other in terms of priority.
377
- // These "on scroll" updates have the lowest priority compared to
378
- // the state updates originating from `setItems()` and `onResize()` methods.
379
- //
380
-
381
-
382
- _this.setState(_objectSpread({
383
- firstShownItemIndex: firstShownItemIndex,
384
- lastShownItemIndex: lastShownItemIndex,
385
- beforeItemsHeight: beforeItemsHeight,
386
- afterItemsHeight: afterItemsHeight
387
- }, stateUpdate));
388
- });
389
-
390
- _defineProperty(this, "onUpdateShownItemIndexes", function (_ref2) {
391
- var reason = _ref2.reason,
392
- stateUpdate = _ref2.stateUpdate;
393
-
394
- // In case of "don't do anything".
395
- var skip = function skip() {
396
- if (stateUpdate) {
397
- _this.setState(stateUpdate);
398
- }
399
- }; // If new `items` have been set and are waiting to be applied,
400
- // or if the viewport width has changed requiring a re-layout,
401
- // then temporarily stop all other updates like "on scroll" updates.
402
- // This prevents `state` being inconsistent, because, for example,
403
- // both `setItems()` and this function could update `VirtualScroller` state
404
- // and having them operate in parallel could result in incorrectly calculated
405
- // `beforeItemsHeight` / `afterItemsHeight` / `firstShownItemIndex` /
406
- // `lastShownItemIndex`, because, when operating in parallel, this function
407
- // would have different `items` than the `setItems()` function, so their
408
- // results could diverge.
409
-
410
-
411
- if (_this.newItemsWillBeRendered || _this.resetLayoutAfterResize || _this.isResizing) {
412
- return skip();
413
- } // If there're no items then there's no need to re-layout anything.
414
-
415
-
416
- if (_this.getItemsCount() === 0) {
417
- return skip();
418
- } // Cancel a "re-layout when user stops scrolling" timer.
37
+ _this._isActive = false;
38
+ log('~ Stop ~');
419
39
 
40
+ _this.resize.stop();
420
41
 
421
- _this.scroll.cancelScheduledLayout(); // Cancel a re-layout that is scheduled to run at the next "frame",
422
- // because a re-layout will be performed right now.
42
+ _this.scroll.stop(); // Stop `ListTopOffsetWatcher` if it has been started.
43
+ // There seems to be no need to restart `ListTopOffsetWatcher`.
44
+ // It's mainly a hacky workaround for development mode anyway.
423
45
 
424
46
 
425
- stateUpdate = _this.cancelLayoutTimer({
426
- stateUpdate: stateUpdate
427
- }); // Perform a re-layout.
47
+ if (_this.listTopOffsetWatcher && _this.listTopOffsetWatcher.isStarted()) {
48
+ _this.listTopOffsetWatcher.stop();
49
+ } // Cancel any scheduled layout.
428
50
 
429
- log("~ Update Layout (on ".concat(reason, ") ~"));
430
51
 
431
- _this.updateShownItemIndexes({
432
- stateUpdate: stateUpdate
433
- });
52
+ _this.cancelLayoutTimer({});
434
53
  });
435
54
 
436
55
  _defineProperty(this, "updateLayout", function () {
437
- return _this.onUpdateShownItemIndexes({
56
+ _this.hasToBeStarted();
57
+
58
+ _this.onUpdateShownItemIndexes({
438
59
  reason: LAYOUT_REASON.MANUAL
439
60
  });
440
61
  });
441
62
 
442
- _defineProperty(this, "layout", function () {
443
- return _this.updateLayout();
63
+ _defineProperty(this, "onRender", function () {
64
+ _this._onRender(_this.getState(), _this.previousState);
444
65
  });
445
66
 
446
- var onStateChange = options.onStateChange,
447
- customState = options.customState,
448
- initialScrollPosition = options.initialScrollPosition,
449
- onScrollPositionChange = options.onScrollPositionChange,
450
- measureItemsBatchSize = options.measureItemsBatchSize,
451
- getScrollableContainer = options.getScrollableContainer,
452
- getColumnsCount = options.getColumnsCount,
453
- getItemId = options.getItemId,
454
- tbody = options.tbody,
455
- _useTimeoutInRenderLoop = options._useTimeoutInRenderLoop,
456
- _waitForScrollingToStop = options._waitForScrollingToStop;
457
- var getState = options.getState,
458
- setState = options.setState;
459
- var bypass = options.bypass,
460
- estimatedItemHeight = options.estimatedItemHeight,
461
- onItemInitialRender = options.onItemInitialRender,
462
- onItemFirstRender = options.onItemFirstRender,
463
- scrollableContainer = options.scrollableContainer,
464
- state = options.state,
465
- engine = options.engine;
466
- log('~ Initialize ~'); // If `state` is passed then use `items` from `state`
467
- // instead of the `items` argument.
468
-
469
- if (state) {
470
- items = state.items;
471
- } // `getScrollableContainer` option is deprecated.
472
- // Use `scrollableContainer` instead.
473
-
474
-
475
- if (!scrollableContainer && getScrollableContainer) {
476
- scrollableContainer = getScrollableContainer();
477
- } // Could support non-DOM rendering engines.
478
- // For example, React Native, `<canvas/>`, etc.
479
-
480
-
481
- if (!engine) {
482
- engine = DOMEngine;
483
- } // Sometimes, when `new VirtualScroller()` instance is created,
484
- // `getItemsContainerElement()` might not be ready to return the "container" DOM Element yet
485
- // (for example, because it's not rendered yet). That's the reason why it's a getter function.
486
- // For example, in React `<VirtualScroller/>` component, a `VirtualScroller`
487
- // instance is created in the React component's `constructor()`, and at that time
488
- // the container Element is not yet available. The container Element is available
489
- // in `componentDidMount()`, but `componentDidMount()` is not executed on server,
490
- // which would mean that React `<VirtualScroller/>` wouldn't render at all
491
- // on server side, while with the `getItemsContainerElement()` approach, on server side,
492
- // it still "renders" a list with a predefined amount of items in it by default.
493
- // (`initiallyRenderedItemsCount`, or `1`).
494
-
495
-
496
- this.getItemsContainerElement = getItemsContainerElement;
497
- this.itemsContainer = engine.createItemsContainer(getItemsContainerElement); // Remove any accidental text nodes from container (like whitespace).
498
- // Also guards against cases when someone accidentally tries
499
- // using `VirtualScroller` on a non-empty element.
500
-
501
- if (getItemsContainerElement()) {
502
- this.itemsContainer.clear();
503
- }
504
-
505
- this.scrollableContainer = engine.createScrollableContainer(scrollableContainer, getItemsContainerElement); // if (prerenderMargin === undefined) {
506
- // // Renders items which are outside of the screen by this "prerender margin".
507
- // // Is the screen height by default: seems to be the optimal value
508
- // // for "Page Up" / "Page Down" navigation and optimized mouse wheel scrolling.
509
- // prerenderMargin = this.scrollableContainer ? this.scrollableContainer.getHeight() : 0
510
- // }
511
- // Work around `<tbody/>` not being able to have `padding`.
512
- // https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1
513
-
514
- if (tbody) {
515
- if (engine !== DOMEngine) {
516
- throw new Error('[virtual-scroller] `tbody` option is only supported for DOM rendering engine');
517
- }
518
-
519
- log('~ <tbody/> detected ~');
520
- this.tbody = true;
521
-
522
- if (!supportsTbody()) {
523
- log('~ <tbody/> not supported ~');
524
- reportError(BROWSER_NOT_SUPPORTED_ERROR);
525
- bypass = true;
526
- }
527
- }
528
-
529
- if (bypass) {
530
- log('~ "bypass" mode ~');
531
- } // In `bypass` mode, `VirtualScroller` doesn't wait
532
- // for the user to scroll down to render all items:
533
- // instead, it renders all items right away, as if
534
- // the list is rendered without using `VirtualScroller`.
535
- // It was added just to measure how much is the
536
- // performance difference between using a `VirtualScroller`
537
- // and not using a `VirtualScroller`.
538
- // It turned out that unmounting large React component trees
539
- // is a very long process, so `VirtualScroller` does seem to
540
- // make sense when used in a React application.
541
-
542
-
543
- this.bypass = bypass; // this.bypassBatchSize = bypassBatchSize || 10
544
- // Using `setTimeout()` in render loop is a workaround
545
- // for avoiding a React error message:
546
- // "Maximum update depth exceeded.
547
- // This can happen when a component repeatedly calls
548
- // `.setState()` inside `componentWillUpdate()` or `componentDidUpdate()`.
549
- // React limits the number of nested updates to prevent infinite loops."
67
+ VirtualScrollerConstructor.call(this, getItemsContainerElement, items, options);
68
+ }
69
+ /**
70
+ * Should be invoked after a "container" DOM Element is mounted (inserted into the DOM tree).
71
+ */
550
72
 
551
- this._useTimeoutInRenderLoop = _useTimeoutInRenderLoop;
552
73
 
553
- if (getItemId) {
554
- this.isItemEqual = function (a, b) {
555
- return getItemId(a) === getItemId(b);
556
- };
557
- } else {
558
- this.isItemEqual = function (a, b) {
559
- return a === b;
560
- };
561
- }
562
-
563
- this.initialItems = items; // this.prerenderMargin = prerenderMargin
74
+ _createClass(VirtualScroller, [{
75
+ key: "start",
76
+ value: function start() {
77
+ if (this._isActive) {
78
+ throw new Error('[virtual-scroller] `VirtualScroller` has already been started');
79
+ } // If has been stopped previously.
564
80
 
565
- this.onStateChange = onStateChange;
566
- this._getColumnsCount = getColumnsCount;
567
81
 
568
- if (onItemInitialRender) {
569
- this.onItemInitialRender = onItemInitialRender;
570
- } // `onItemFirstRender(i)` is deprecated, use `onItemInitialRender(item)` instead.
571
- else if (onItemFirstRender) {
572
- this.onItemInitialRender = function (item) {
573
- warn('`onItemFirstRender(i)` is deprecated, use `onItemInitialRender(item)` instead.');
82
+ var isRestart = this._isActive === false;
574
83
 
575
- var _this$getState = _this.getState(),
576
- items = _this$getState.items;
84
+ if (!isRestart) {
85
+ // If no custom one has been configured, uses the default one.
86
+ // Also sets the initial state.
87
+ if (!this._usesCustomStateStorage) {
88
+ this.useDefaultStateStorage();
89
+ } // If `render()` function parameter was passed,
90
+ // perform an initial render.
577
91
 
578
- var i = items.indexOf(item); // The `item` could also be non-found due to the inconsistency bug:
579
- // The reason is that `i` can be non-consistent with the `items`
580
- // passed to `<VirtualScroller/>` in React due to `setState()` not being
581
- // instanteneous: when new `items` are passed to `<VirtualScroller/>`,
582
- // `VirtualScroller.setState({ items })` is called, and if `onItemFirstRender(i)`
583
- // is called after the aforementioned `setState()` is called but before it finishes,
584
- // `i` would point to an index in "previous" `items` while the application
585
- // would assume that `i` points to an index in the "new" `items`,
586
- // resulting in an incorrect item being assumed by the application
587
- // or even in an "array index out of bounds" error.
588
92
 
589
- if (i >= 0) {
590
- onItemFirstRender(i);
93
+ if (this._render) {
94
+ this._render(this.getState());
591
95
  }
592
- };
593
- }
594
-
595
- log('Items count', items.length);
596
-
597
- if (estimatedItemHeight) {
598
- log('Estimated item height', estimatedItemHeight);
599
- } // There're three main places where state is updated:
600
- //
601
- // * On scroll.
602
- // * On window resize.
603
- // * On set new items.
604
- //
605
- // State updates may be "asynchronous" (like in React), in which case the
606
- // corresponding operation is "pending" until the state update is applied.
607
- //
608
- // If there's a "pending" window resize or a "pending" update of the set of items,
609
- // then "on scroll" updates aren't dispatched.
610
- //
611
- // If there's a "pending" on scroll update and the window is resize or a new set
612
- // of items is set, then that "pending" on scroll update gets overwritten.
613
- //
614
- // If there's a "pending" update of the set of items, then window resize handler
615
- // sees that "pending" update and dispatches its own state update so that the
616
- // "pending" state update originating from `setItems()` is not lost.
617
- //
618
- // If there's a "pending" window resize, and a new set of items is set,
619
- // then the state update of the window resize handler gets overwritten.
620
- // Create default `getState()`/`setState()` functions.
621
-
622
-
623
- if (!getState) {
624
- getState = function getState() {
625
- return _this.state;
626
- };
627
-
628
- setState = function setState(stateUpdate, _ref3) {
629
- var willUpdateState = _ref3.willUpdateState,
630
- didUpdateState = _ref3.didUpdateState;
631
- var prevState = getState(); // Because this variant of `.setState()` is "synchronous" (immediate),
632
- // it can be written like `...prevState`, and no state updates would be lost.
633
- // But if it was "asynchronous" (not immediate), then `...prevState`
634
- // wouldn't work in all cases, because it could be stale in cases
635
- // when more than a single `setState()` call is made before
636
- // the state actually updates, making `prevState` stale.
637
-
638
- var newState = _objectSpread(_objectSpread({}, prevState), stateUpdate);
639
-
640
- willUpdateState(newState, prevState);
641
- _this.state = newState; // // Is only used in tests.
642
- // if (this._onStateUpdate) {
643
- // this._onStateUpdate(stateUpdate)
644
- // }
645
-
646
- didUpdateState(prevState);
647
- };
648
- }
649
-
650
- this.getState = getState;
651
-
652
- this.setState = function (stateUpdate) {
653
- if (isDebug()) {
654
- log('Set state', getStateSnapshot(stateUpdate));
655
96
  }
656
97
 
657
- setState(stateUpdate, {
658
- willUpdateState: _this.willUpdateState,
659
- didUpdateState: _this.didUpdateState
660
- });
661
- };
98
+ log('~ Start ~'); // `this._isActive = true` should be placed somewhere at the start of this function.
662
99
 
663
- if (state) {
664
- if (isDebug()) {
665
- log('Initial state (passed)', getStateSnapshot(state));
666
- }
667
- } // Check if the current `columnsCount` matches the one from state.
668
- // For example, a developer might snapshot `VirtualScroller` state
669
- // when the user navigates from the page containing the list
670
- // in order to later restore the list's state when the user goes "Back".
671
- // But, the user might have also resized the window while being on that
672
- // "other" page, and when they come "Back", their snapshotted state
673
- // no longer qualifies. Well, it does qualify, but only partially.
674
- // For example, `itemStates` are still valid, but first and last shown
675
- // item indexes aren't.
100
+ this._isActive = true; // Reset `ListHeightMeasurement` just in case it has some "leftover" state.
676
101
 
102
+ this.listHeightMeasurement.reset(); // Reset `_isResizing` flag just in case it has some "leftover" value.
677
103
 
678
- if (state) {
679
- var shouldResetLayout;
680
- var columnsCountForState = this.getActualColumnsCountForState();
104
+ this._isResizing = undefined; // Reset `_isSettingNewItems` flag just in case it has some "leftover" value.
681
105
 
682
- if (columnsCountForState !== state.columnsCount) {
683
- warn('~ Columns Count changed from', state.columnsCount || 1, 'to', columnsCountForState || 1, '~');
684
- shouldResetLayout = true;
685
- }
686
-
687
- var columnsCount = this.getActualColumnsCount();
688
- var firstShownItemIndex = Math.floor(state.firstShownItemIndex / columnsCount) * columnsCount;
689
-
690
- if (firstShownItemIndex !== state.firstShownItemIndex) {
691
- warn('~ First Shown Item Index', state.firstShownItemIndex, 'is not divisible by Columns Count', columnsCount, '~');
692
- shouldResetLayout = true;
693
- }
694
-
695
- if (shouldResetLayout) {
696
- warn('Reset Layout');
697
- state = _objectSpread(_objectSpread({}, state), this.getInitialLayoutState(state.items));
698
- }
699
- } // Reset `verticalSpacing` so that it re-measures it after the list
700
- // has been rendered initially. The rationale is that the `state`
701
- // can't be "trusted" in a sense that the user might have resized
702
- // their window after the `state` has been snapshotted, and changing
703
- // window width might have activated different CSS `@media()` "queries"
704
- // resulting in a potentially different vertical spacing.
705
-
706
-
707
- if (state) {
708
- state = _objectSpread(_objectSpread({}, state), {}, {
709
- verticalSpacing: undefined
710
- });
711
- } // Create `ItemHeights` instance.
712
-
713
-
714
- this.itemHeights = new ItemHeights(this.itemsContainer, function (i) {
715
- return _this.getState().itemHeights[i];
716
- }, function (i, height) {
717
- return _this.getState().itemHeights[i] = height;
718
- }); // Initialize `ItemHeights` from the initially passed `state`.
719
-
720
- if (state) {
721
- this.itemHeights.initialize(state.itemHeights);
722
- }
106
+ this._isSettingNewItems = undefined; // Work around `<tbody/>` not being able to have `padding`.
107
+ // https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1
723
108
 
724
- this.layout = new Layout({
725
- bypass: bypass,
726
- estimatedItemHeight: estimatedItemHeight,
727
- measureItemsBatchSize: measureItemsBatchSize === undefined ? 50 : measureItemsBatchSize,
728
- getPrerenderMargin: function getPrerenderMargin() {
729
- return _this.getPrerenderMargin();
730
- },
731
- getVerticalSpacing: function getVerticalSpacing() {
732
- return _this.getVerticalSpacing();
733
- },
734
- getVerticalSpacingBeforeResize: function getVerticalSpacingBeforeResize() {
735
- return _this.getVerticalSpacingBeforeResize();
736
- },
737
- getColumnsCount: function getColumnsCount() {
738
- return _this.getColumnsCount();
739
- },
740
- getColumnsCountBeforeResize: function getColumnsCountBeforeResize() {
741
- return _this.getState().beforeResize && _this.getState().beforeResize.columnsCount;
742
- },
743
- getItemHeight: function getItemHeight(i) {
744
- return _this.getState().itemHeights[i];
745
- },
746
- getItemHeightBeforeResize: function getItemHeightBeforeResize(i) {
747
- return _this.getState().beforeResize && _this.getState().beforeResize.itemHeights[i];
748
- },
749
- getBeforeResizeItemsCount: function getBeforeResizeItemsCount() {
750
- return _this.getState().beforeResize ? _this.getState().beforeResize.itemHeights.length : 0;
751
- },
752
- getAverageItemHeight: function getAverageItemHeight() {
753
- return _this.itemHeights.getAverage();
754
- },
755
- getMaxVisibleAreaHeight: function getMaxVisibleAreaHeight() {
756
- return _this.scrollableContainer && _this.scrollableContainer.getHeight();
757
- },
758
- //
759
- // The "previously calculated layout" feature is not currently used.
109
+ if (this.tbody) {
110
+ if (!hasTbodyStyles(this.getItemsContainerElement())) {
111
+ addTbodyStyles(this.getItemsContainerElement());
112
+ }
113
+ } // If there was a pending state update that didn't get applied
114
+ // because of stopping the `VirtualScroller`, apply that state update now.
760
115
  //
761
- // The current layout snapshot could be stored as a "previously calculated layout" variable
762
- // so that it could theoretically be used when calculating new layout incrementally
763
- // rather than from scratch, which would be an optimization.
116
+ // The pending state update won't get applied if the scrollable container width
117
+ // has changed but that's ok because that state update currently could only contain:
118
+ // * `scrollableContainerWidth`
119
+ // * `verticalSpacing`
120
+ // * `beforeResize`
121
+ // All of those get rewritten in `onResize()` anyway.
764
122
  //
765
- getPreviouslyCalculatedLayout: function getPreviouslyCalculatedLayout() {
766
- return _this.previouslyCalculatedLayout;
767
- }
768
- });
769
- this.resize = new Resize({
770
- bypass: bypass,
771
- scrollableContainer: this.scrollableContainer,
772
- onStart: function onStart() {
773
- log('~ Scrollable container resize started ~');
774
- _this.isResizing = true;
775
- },
776
- onStop: function onStop() {
777
- log('~ Scrollable container resize finished ~');
778
- _this.isResizing = undefined;
779
- },
780
- onNoChange: function onNoChange() {
781
- // There might have been some missed `this.onUpdateShownItemIndexes()` calls
782
- // due to setting `this.isResizing` flag to `true` during the resize.
783
- // So, update shown item indexes just in case.
784
- _this.onUpdateShownItemIndexes({
785
- reason: LAYOUT_REASON.VIEWPORT_SIZE_UNCHANGED
786
- });
787
- },
788
- onHeightChange: function onHeightChange() {
789
- return _this.onUpdateShownItemIndexes({
790
- reason: LAYOUT_REASON.VIEWPORT_HEIGHT_CHANGED
791
- });
792
- },
793
- onWidthChange: function onWidthChange(prevWidth, newWidth) {
794
- log('~ Scrollable container width changed from', prevWidth, 'to', newWidth, '~');
795
-
796
- _this.onResize();
797
- }
798
- });
799
- this.scroll = new Scroll({
800
- bypass: this.bypass,
801
- scrollableContainer: this.scrollableContainer,
802
- itemsContainer: this.itemsContainer,
803
- waitForScrollingToStop: _waitForScrollingToStop,
804
- onScroll: function onScroll() {
805
- var _ref4 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
806
- delayed = _ref4.delayed;
807
-
808
- _this.onUpdateShownItemIndexes({
809
- reason: delayed ? LAYOUT_REASON.STOPPED_SCROLLING : LAYOUT_REASON.SCROLL
810
- });
811
- },
812
- initialScrollPosition: initialScrollPosition,
813
- onScrollPositionChange: onScrollPositionChange,
814
- isImmediateLayoutScheduled: function isImmediateLayoutScheduled() {
815
- return _this.layoutTimer;
816
- },
817
- hasNonRenderedItemsAtTheTop: function hasNonRenderedItemsAtTheTop() {
818
- return _this.getState().firstShownItemIndex > 0;
819
- },
820
- hasNonRenderedItemsAtTheBottom: function hasNonRenderedItemsAtTheBottom() {
821
- return _this.getState().lastShownItemIndex < _this.getItemsCount() - 1;
822
- },
823
- getLatestLayoutVisibleArea: function getLatestLayoutVisibleArea() {
824
- return _this.latestLayoutVisibleArea;
825
- },
826
- getListTopOffset: this.getListTopOffsetInsideScrollableContainer,
827
- getPrerenderMargin: function getPrerenderMargin() {
828
- return _this.getPrerenderMargin();
829
- }
830
- });
831
- this.listHeightChangeWatcher = new ListHeightChangeWatcher({
832
- itemsContainer: this.itemsContainer,
833
- getListTopOffset: this.getListTopOffsetInsideScrollableContainer
834
- });
835
123
 
836
- if (engine.watchListTopOffset) {
837
- this.listTopOffsetWatcher = engine.watchListTopOffset({
838
- getListTopOffset: this.getListTopOffsetInsideScrollableContainer,
839
- onListTopOffsetChange: function onListTopOffsetChange(_ref5) {
840
- var reason = _ref5.reason;
841
- return _this.onUpdateShownItemIndexes({
842
- reason: LAYOUT_REASON.TOP_OFFSET_CHANGED
843
- });
844
- }
845
- });
846
- }
847
-
848
- this.beforeResize = new BeforeResize({
849
- getState: this.getState,
850
- getVerticalSpacing: this.getVerticalSpacing,
851
- getColumnsCount: this.getColumnsCount
852
- }); // Possibly clean up "before resize" property in state.
853
- // "Before resize" state property is cleaned up when all "before resize" item heights
854
- // have been re-measured in an asynchronous `this.setState({ beforeResize: undefined })` call.
855
- // If `VirtualScroller` state was snapshotted externally before that `this.setState()` call
856
- // has been applied, then "before resize" property might have not been cleaned up properly.
857
-
858
- this.beforeResize.onInitialState(state); // `this.verticalSpacing` acts as a "true" source for vertical spacing value.
859
- // Vertical spacing is also stored in `state` but `state` updates could be
860
- // "asynchronous" (not applied immediately) and `this.onUpdateShownItemIndexes()`
861
- // requires vertical spacing to be correct at any time, without any delays.
862
- // So, vertical spacing is also duplicated in `state`, but the "true" source
863
- // is still `this.verticalSpacing`.
864
- //
865
- // `this.verticalSpacing` must be initialized before calling `this.getInitialState()`.
866
- //
867
-
868
- this.verticalSpacing = state ? state.verticalSpacing : undefined; // Set initial `state`.
869
-
870
- this.setState(state || this.getInitialState(customState));
871
- }
872
- /**
873
- * Returns the initial state of the `VirtualScroller`.
874
- * @param {object} [customState] — Any additional "custom" state may be stored in `VirtualScroller`'s state. For example, React implementation stores item "refs" as "custom" state.
875
- * @return {object}
876
- */
877
124
 
125
+ var stateUpdate = this._stoppedStateUpdate;
126
+ this._stoppedStateUpdate = undefined; // Reset `this.verticalSpacing` so that it re-measures it in cases when
127
+ // the `VirtualScroller` was previously stopped and is now being restarted.
128
+ // The rationale is that a previously captured inter-item vertical spacing
129
+ // can't be "trusted" in a sense that the user might have resized the window
130
+ // after the previous `state` has been snapshotted.
131
+ // If the user has resized the window, then changing window width might have
132
+ // activated different CSS `@media()` "queries" resulting in a potentially different
133
+ // vertical spacing after the restart.
134
+ // If it's not a restart then `this.verticalSpacing` is `undefined` anyway.
878
135
 
879
- _createClass(VirtualScroller, [{
880
- key: "getInitialState",
881
- value: function getInitialState(customState) {
882
- var items = this.initialItems;
136
+ this.verticalSpacing = undefined;
137
+ var verticalSpacingStateUpdate = this.measureItemHeightsAndSpacing();
883
138
 
884
- var state = _objectSpread(_objectSpread(_objectSpread({}, customState), this.getInitialLayoutState(items)), {}, {
885
- items: items,
886
- itemStates: new Array(items.length)
887
- });
888
-
889
- if (isDebug()) {
890
- log('Initial state (autogenerated)', getStateSnapshot(state));
139
+ if (verticalSpacingStateUpdate) {
140
+ stateUpdate = _objectSpread(_objectSpread({}, stateUpdate), verticalSpacingStateUpdate);
891
141
  }
892
142
 
893
- log('First shown item index', state.firstShownItemIndex);
894
- log('Last shown item index', state.lastShownItemIndex);
895
- return state;
896
- }
897
- }, {
898
- key: "getInitialLayoutState",
899
- value: function getInitialLayoutState(items) {
900
- var itemsCount = items.length;
901
-
902
- var _this$layout$getIniti = this.layout.getInitialLayoutValues({
903
- itemsCount: itemsCount,
904
- columnsCount: this.getActualColumnsCount()
905
- }),
906
- firstShownItemIndex = _this$layout$getIniti.firstShownItemIndex,
907
- lastShownItemIndex = _this$layout$getIniti.lastShownItemIndex,
908
- beforeItemsHeight = _this$layout$getIniti.beforeItemsHeight,
909
- afterItemsHeight = _this$layout$getIniti.afterItemsHeight;
910
-
911
- var itemHeights = new Array(itemsCount); // Optionally preload items to be rendered.
912
-
913
- this.onBeforeShowItems(items, itemHeights, firstShownItemIndex, lastShownItemIndex);
914
- return {
915
- itemHeights: itemHeights,
916
- columnsCount: this.getActualColumnsCountForState(),
917
- verticalSpacing: this.verticalSpacing,
918
- firstShownItemIndex: firstShownItemIndex,
919
- lastShownItemIndex: lastShownItemIndex,
920
- beforeItemsHeight: beforeItemsHeight,
921
- afterItemsHeight: afterItemsHeight
922
- };
923
- } // Bind to `this` in order to prevent bugs when this function is passed by reference
924
- // and then called with its `this` being unintentionally `window` resulting in
925
- // the `if` condition being "falsy".
926
-
927
- }, {
928
- key: "getActualColumnsCount",
929
- value: function getActualColumnsCount() {
930
- return this.getActualColumnsCountForState() || 1;
931
- } // Bind to `this` in order to prevent bugs when this function is passed by reference
932
- // and then called with its `this` being unintentionally `window` resulting in
933
- // the `if` condition being "falsy".
934
-
935
- }, {
936
- key: "getVerticalSpacingBeforeResize",
937
- value: function getVerticalSpacingBeforeResize() {
938
- // `beforeResize.verticalSpacing` can be `undefined`.
939
- // For example, if `this.setState({ verticalSpacing })` call hasn't been applied
940
- // before the resize happened (in case of an "asynchronous" state update).
941
- return this.getState().beforeResize && this.getState().beforeResize.verticalSpacing || 0;
942
- }
943
- }, {
944
- key: "getColumnsCount",
945
- value: function getColumnsCount() {
946
- return this.getState() && this.getState().columnsCount || 1;
947
- }
948
- }, {
949
- key: "getItemsCount",
950
- value: function getItemsCount() {
951
- return this.getState().items.length;
952
- }
953
- }, {
954
- key: "getPrerenderMargin",
955
- value: function getPrerenderMargin() {
956
- // The list component renders not only the items that're currently visible
957
- // but also the items that lie within some extra vertical margin (called
958
- // "prerender margin") on top and bottom for future scrolling: this way,
959
- // there'll be significantly less layout recalculations as the user scrolls,
960
- // because now it doesn't have to recalculate layout on each scroll event.
961
- // By default, the "prerender margin" is equal to the screen height:
962
- // this seems to be the optimal value for "Page Up" / "Page Down" navigation
963
- // and optimized mouse wheel scrolling (a user is unlikely to continuously
964
- // scroll past the screen height, because they'd stop to read through
965
- // the newly visible items first, and when they do stop scrolling, that's
966
- // when layout gets recalculated).
967
- var renderAheadMarginRatio = 1; // in scrollable container heights.
143
+ this.resize.start();
144
+ this.scroll.start(); // If `scrollableContainerWidth` hasn't been measured yet,
145
+ // measure it and write it to state.
968
146
 
969
- return this.scrollableContainer.getHeight() * renderAheadMarginRatio;
970
- }
971
- /**
972
- * Calls `onItemFirstRender()` for items that haven't been
973
- * "seen" previously.
974
- * @param {any[]} items
975
- * @param {number[]} itemHeights
976
- * @param {number} firstShownItemIndex
977
- * @param {number} lastShownItemIndex
978
- */
979
-
980
- }, {
981
- key: "onBeforeShowItems",
982
- value: function onBeforeShowItems(items, itemHeights, firstShownItemIndex, lastShownItemIndex) {
983
- if (this.onItemInitialRender) {
984
- var i = firstShownItemIndex;
985
-
986
- while (i <= lastShownItemIndex) {
987
- if (itemHeights[i] === undefined) {
988
- this.onItemInitialRender(items[i]);
989
- }
990
-
991
- i++;
147
+ if (this.getState().scrollableContainerWidth === undefined) {
148
+ var scrollableContainerWidth = this.scrollableContainer.getWidth();
149
+ stateUpdate = _objectSpread(_objectSpread({}, stateUpdate), {}, {
150
+ scrollableContainerWidth: scrollableContainerWidth
151
+ });
152
+ } else {
153
+ // Reset layout:
154
+ // * If the scrollable container width has changed while stopped.
155
+ // * If the restored state was calculated for another scrollable container width.
156
+ var newWidth = this.scrollableContainer.getWidth();
157
+ var prevWidth = this.getState().scrollableContainerWidth;
158
+
159
+ if (newWidth !== prevWidth) {
160
+ log('~ Scrollable container width changed from', prevWidth, 'to', newWidth, '~'); // `stateUpdate` doesn't get passed to `this.onResize()`, and, therefore,
161
+ // won't be applied. But that's ok because currently it could only contain:
162
+ // * `scrollableContainerWidth`
163
+ // * `verticalSpacing`
164
+ // * `beforeResize`
165
+ // All of those get rewritten in `onResize()` anyway.
166
+
167
+ return this.onResize();
992
168
  }
993
- }
994
- }
995
- }, {
996
- key: "onMount",
997
- value: function onMount() {
998
- warn('`.onMount()` instance method name is deprecated, use `.listen()` instance method name instead.');
999
- this.listen();
1000
- }
1001
- }, {
1002
- key: "render",
1003
- value: function render() {
1004
- warn('`.render()` instance method name is deprecated, use `.listen()` instance method name instead.');
1005
- this.listen();
1006
- }
1007
- /**
1008
- * Should be invoked after a "container" DOM Element is mounted (inserted into the DOM tree).
1009
- */
169
+ } // If the `VirtualScroller` uses custom (external) state storage, then
170
+ // check if the columns count has changed between calling `.getInitialState()`
171
+ // and `.start()`. If it has, perform a re-layout "from scratch".
1010
172
 
1011
- }, {
1012
- key: "listen",
1013
- value: function listen() {
1014
- if (this.isRendered === false) {
1015
- throw new Error('[virtual-scroller] Can\'t restart a `VirtualScroller` after it has been stopped');
1016
- }
1017
-
1018
- log('~ Rendered (initial) ~'); // `this.isRendered = true` should be the first statement in this function,
1019
- // otherwise `DOMVirtualScroller` would enter an infinite re-render loop.
1020
173
 
1021
- this.isRendered = true;
1022
- var stateUpdate = this.measureItemHeightsAndSpacingAndUpdateTablePadding();
1023
- this.resize.listen();
1024
- this.scroll.listen(); // Work around `<tbody/>` not being able to have `padding`.
1025
- // https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1
174
+ if (this._usesCustomStateStorage) {
175
+ var columnsCount = this.getActualColumnsCount();
176
+ var columnsCountFromState = this.getState().columnsCount || 1;
1026
177
 
1027
- if (this.tbody) {
1028
- addTbodyStyles(this.getItemsContainerElement());
178
+ if (columnsCount !== columnsCountFromState) {
179
+ return this.onResize();
180
+ }
1029
181
  } // Re-calculate layout and re-render the list.
1030
182
  // Do that even if when an initial `state` parameter, containing layout values,
1031
183
  // has been passed. The reason is that the `state` parameter can't be "trusted"
@@ -1034,48 +186,19 @@ var VirtualScroller = /*#__PURE__*/function () {
1034
186
 
1035
187
 
1036
188
  this.onUpdateShownItemIndexes({
1037
- reason: LAYOUT_REASON.MOUNTED,
189
+ reason: LAYOUT_REASON.STARTED,
1038
190
  stateUpdate: stateUpdate
1039
191
  });
1040
- }
1041
- }, {
1042
- key: "measureItemHeightsAndSpacingAndUpdateTablePadding",
1043
- value: function measureItemHeightsAndSpacingAndUpdateTablePadding() {
1044
- // Measure "newly shown" item heights.
1045
- // Also re-validate already measured items' heights.
1046
- this.itemHeights.measureItemHeights(this.getState().firstShownItemIndex, this.getState().lastShownItemIndex); // Update item vertical spacing.
192
+ } // Could be passed as a "callback" parameter, so bind it to `this`.
1047
193
 
1048
- var verticalSpacing = this.measureVerticalSpacing(); // Update `<tbody/>` `padding`.
1049
- // (`<tbody/>` is different in a way that it can't have `margin`, only `padding`).
1050
- // https://gitlab.com/catamphetamine/virtual-scroller/-/issues/1
1051
-
1052
- if (this.tbody) {
1053
- setTbodyPadding(this.getItemsContainerElement(), this.getState().beforeItemsHeight, this.getState().afterItemsHeight);
1054
- } // Return a state update.
1055
-
1056
-
1057
- if (verticalSpacing !== undefined) {
1058
- return {
1059
- verticalSpacing: verticalSpacing
1060
- };
1061
- }
1062
- }
1063
194
  }, {
1064
- key: "getVisibleArea",
1065
- value: function getVisibleArea() {
1066
- var visibleArea = this.scroll.getVisibleAreaBounds();
1067
- this.latestLayoutVisibleArea = visibleArea; // Subtract the top offset of the list inside the scrollable container.
1068
-
1069
- var listTopOffsetInsideScrollableContainer = this.getListTopOffsetInsideScrollableContainer();
1070
- return {
1071
- top: visibleArea.top - listTopOffsetInsideScrollableContainer,
1072
- bottom: visibleArea.bottom - listTopOffsetInsideScrollableContainer
1073
- };
1074
- }
1075
- /**
1076
- * Returns the list's top offset relative to the scrollable container's top edge.
1077
- * @return {number}
1078
- */
195
+ key: "hasToBeStarted",
196
+ value: function hasToBeStarted() {
197
+ if (!this._isActive) {
198
+ throw new Error('[virtual-scroller] `VirtualScroller` hasn\'t been started');
199
+ }
200
+ } // Bind it to `this` because this function could hypothetically be passed
201
+ // as a "callback" parameter.
1079
202
 
1080
203
  }, {
1081
204
  key: "getItemScrollPosition",
@@ -1094,479 +217,30 @@ var VirtualScroller = /*#__PURE__*/function () {
1094
217
 
1095
218
  return this.getListTopOffsetInsideScrollableContainer() + itemTopOffsetInList;
1096
219
  }
1097
- }, {
1098
- key: "onUnmount",
1099
- value: function onUnmount() {
1100
- warn('`.onUnmount()` instance method name is deprecated, use `.stop()` instance method name instead.');
1101
- this.stop();
1102
- }
1103
- }, {
1104
- key: "destroy",
1105
- value: function destroy() {
1106
- warn('`.destroy()` instance method name is deprecated, use `.stop()` instance method name instead.');
1107
- this.stop();
1108
- }
1109
- }, {
1110
- key: "cancelLayoutTimer",
1111
- value: function cancelLayoutTimer(_ref6) {
1112
- var stateUpdate = _ref6.stateUpdate;
1113
-
1114
- if (this.layoutTimer) {
1115
- clearTimeout(this.layoutTimer);
1116
- this.layoutTimer = undefined; // Merge state updates.
1117
-
1118
- if (stateUpdate || this.layoutTimerStateUpdate) {
1119
- stateUpdate = _objectSpread(_objectSpread({}, this.layoutTimerStateUpdate), stateUpdate);
1120
- this.layoutTimerStateUpdate = undefined;
1121
- return stateUpdate;
1122
- }
1123
- } else {
1124
- return stateUpdate;
1125
- }
1126
- }
1127
- }, {
1128
- key: "scheduleLayoutTimer",
1129
- value: function scheduleLayoutTimer(_ref7) {
1130
- var _this2 = this;
1131
-
1132
- var reason = _ref7.reason,
1133
- stateUpdate = _ref7.stateUpdate;
1134
- this.layoutTimerStateUpdate = stateUpdate;
1135
- this.layoutTimer = setTimeout(function () {
1136
- _this2.layoutTimerStateUpdate = undefined;
1137
- _this2.layoutTimer = undefined;
1138
-
1139
- _this2.onUpdateShownItemIndexes({
1140
- reason: reason,
1141
- stateUpdate: stateUpdate
1142
- });
1143
- }, 0);
1144
- }
1145
220
  /**
1146
- * Should be called right before `state` is updated.
1147
- * @param {object} prevState
1148
- * @param {object} newState
221
+ * Forces a re-measure of an item's height.
222
+ * @param {number} i — Item index
1149
223
  */
1150
224
 
1151
- }, {
1152
- key: "onNewItemsRendered",
1153
- value: // After a new set of items has been rendered:
1154
- //
1155
- // * Restores scroll position when using `preserveScrollPositionOnPrependItems`
1156
- // and items have been prepended.
1157
- //
1158
- // * Applies any "pending" `itemHeights` updates — those ones that happened
1159
- // while an asynchronous `setState()` call in `setItems()` was pending.
1160
- //
1161
- // * Either creates or resets the snapshot of the current layout.
1162
- //
1163
- // The current layout snapshot could be stored as a "previously calculated layout" variable
1164
- // so that it could theoretically be used when calculating new layout incrementally
1165
- // rather than from scratch, which would be an optimization.
1166
- //
1167
- // The "previously calculated layout" feature is not currently used.
1168
- //
1169
- function onNewItemsRendered(itemsDiff, newLayout) {
1170
- // If it's an "incremental" update.
1171
- if (itemsDiff) {
1172
- var prependedItemsCount = itemsDiff.prependedItemsCount,
1173
- appendedItemsCount = itemsDiff.appendedItemsCount;
1174
-
1175
- var _this$getState2 = this.getState(),
1176
- itemHeights = _this$getState2.itemHeights,
1177
- itemStates = _this$getState2.itemStates; // See if any items' heights changed while new items were being rendered.
1178
-
1179
-
1180
- if (this.itemHeightsThatChangedWhileNewItemsWereBeingRendered) {
1181
- for (var _i = 0, _Object$keys = Object.keys(this.itemHeightsThatChangedWhileNewItemsWereBeingRendered); _i < _Object$keys.length; _i++) {
1182
- var i = _Object$keys[_i];
1183
- itemHeights[prependedItemsCount + parseInt(i)] = this.itemHeightsThatChangedWhileNewItemsWereBeingRendered[i];
1184
- }
1185
- } // See if any items' states changed while new items were being rendered.
1186
-
1187
-
1188
- if (this.itemStatesThatChangedWhileNewItemsWereBeingRendered) {
1189
- for (var _i2 = 0, _Object$keys2 = Object.keys(this.itemStatesThatChangedWhileNewItemsWereBeingRendered); _i2 < _Object$keys2.length; _i2++) {
1190
- var _i3 = _Object$keys2[_i2];
1191
- itemStates[prependedItemsCount + parseInt(_i3)] = this.itemStatesThatChangedWhileNewItemsWereBeingRendered[_i3];
1192
- }
1193
- }
1194
-
1195
- if (prependedItemsCount === 0) {
1196
- // Adjust `this.previouslyCalculatedLayout`.
1197
- if (this.previouslyCalculatedLayout) {
1198
- if (this.previouslyCalculatedLayout.firstShownItemIndex === newLayout.firstShownItemIndex && this.previouslyCalculatedLayout.lastShownItemIndex === newLayout.lastShownItemIndex) {// `this.previouslyCalculatedLayout` stays the same.
1199
- // `firstShownItemIndex` / `lastShownItemIndex` didn't get changed in `setItems()`,
1200
- // so `beforeItemsHeight` and `shownItemsHeight` also stayed the same.
1201
- } else {
1202
- warn('Unexpected (non-matching) "firstShownItemIndex" or "lastShownItemIndex" encountered in "didUpdateState()" after appending items');
1203
- warn('Previously calculated layout', this.previouslyCalculatedLayout);
1204
- warn('New layout', newLayout);
1205
- this.previouslyCalculatedLayout = undefined;
1206
- }
1207
- }
1208
-
1209
- return 'SEAMLESS_APPEND';
1210
- } else {
1211
- if (this.listHeightChangeWatcher.hasSnapshot()) {
1212
- if (newLayout.firstShownItemIndex === 0) {
1213
- // Restore (adjust) scroll position.
1214
- log('~ Restore Scroll Position ~');
1215
- var listBottomOffsetChange = this.listHeightChangeWatcher.getListBottomOffsetChange({
1216
- beforeItemsHeight: newLayout.beforeItemsHeight
1217
- });
1218
- this.listHeightChangeWatcher.reset();
1219
-
1220
- if (listBottomOffsetChange) {
1221
- log('Scroll down by', listBottomOffsetChange);
1222
- this.scroll.scrollByY(listBottomOffsetChange);
1223
- } else {
1224
- log('Scroll position hasn\'t changed');
1225
- } // Create new `this.previouslyCalculatedLayout`.
1226
-
1227
-
1228
- if (this.previouslyCalculatedLayout) {
1229
- if (this.previouslyCalculatedLayout.firstShownItemIndex === 0 && this.previouslyCalculatedLayout.lastShownItemIndex === newLayout.lastShownItemIndex - prependedItemsCount) {
1230
- this.previouslyCalculatedLayout = {
1231
- beforeItemsHeight: 0,
1232
- shownItemsHeight: this.previouslyCalculatedLayout.shownItemsHeight + listBottomOffsetChange,
1233
- firstShownItemIndex: 0,
1234
- lastShownItemIndex: newLayout.lastShownItemIndex
1235
- };
1236
- } else {
1237
- warn('Unexpected (non-matching) "firstShownItemIndex" or "lastShownItemIndex" encountered in "didUpdateState()" after prepending items');
1238
- warn('Previously calculated layout', this.previouslyCalculatedLayout);
1239
- warn('New layout', newLayout);
1240
- this.previouslyCalculatedLayout = undefined;
1241
- }
1242
- }
1243
-
1244
- return 'SEAMLESS_PREPEND';
1245
- } else {
1246
- warn("Unexpected \"firstShownItemIndex\" ".concat(newLayout.firstShownItemIndex, " encountered in \"didUpdateState()\" after prepending items. Expected 0."));
1247
- }
1248
- }
1249
- }
1250
- } // Reset `this.previouslyCalculatedLayout` in any case other than
1251
- // SEAMLESS_PREPEND or SEAMLESS_APPEND.
1252
-
1253
-
1254
- this.previouslyCalculatedLayout = undefined;
1255
- }
1256
- }, {
1257
- key: "updateStateRightAfterRender",
1258
- value: function updateStateRightAfterRender(_ref8) {
1259
- var reason = _ref8.reason,
1260
- stateUpdate = _ref8.stateUpdate;
1261
-
1262
- // In React, `setTimeout()` is used to prevent a React error:
1263
- // "Maximum update depth exceeded.
1264
- // This can happen when a component repeatedly calls
1265
- // `.setState()` inside `componentWillUpdate()` or `componentDidUpdate()`.
1266
- // React limits the number of nested updates to prevent infinite loops."
1267
- if (this._useTimeoutInRenderLoop) {
1268
- // Cancel a previously scheduled re-layout.
1269
- stateUpdate = this.cancelLayoutTimer({
1270
- stateUpdate: stateUpdate
1271
- }); // Schedule a new re-layout.
1272
-
1273
- this.scheduleLayoutTimer({
1274
- reason: reason,
1275
- stateUpdate: stateUpdate
1276
- });
1277
- } else {
1278
- this.onUpdateShownItemIndexes({
1279
- reason: reason,
1280
- stateUpdate: stateUpdate
1281
- });
1282
- }
1283
- }
1284
- }, {
1285
- key: "measureVerticalSpacing",
1286
- value: function measureVerticalSpacing() {
1287
- if (this.verticalSpacing === undefined) {
1288
- var _this$getState3 = this.getState(),
1289
- firstShownItemIndex = _this$getState3.firstShownItemIndex,
1290
- lastShownItemIndex = _this$getState3.lastShownItemIndex;
1291
-
1292
- log('~ Measure item vertical spacing ~');
1293
- var verticalSpacing = getVerticalSpacing({
1294
- itemsContainer: this.itemsContainer,
1295
- renderedItemsCount: lastShownItemIndex - firstShownItemIndex + 1
1296
- });
1297
-
1298
- if (verticalSpacing === undefined) {
1299
- log('Not enough items rendered to measure vertical spacing');
1300
- } else {
1301
- log('Item vertical spacing', verticalSpacing);
1302
- this.verticalSpacing = verticalSpacing;
1303
-
1304
- if (verticalSpacing !== 0) {
1305
- return verticalSpacing;
1306
- }
1307
- }
1308
- }
1309
- }
1310
- }, {
1311
- key: "remeasureItemHeight",
1312
- value: function remeasureItemHeight(i) {
1313
- var _this$getState4 = this.getState(),
1314
- firstShownItemIndex = _this$getState4.firstShownItemIndex;
1315
-
1316
- return this.itemHeights.remeasureItemHeight(i, firstShownItemIndex);
1317
- }
1318
- }, {
1319
- key: "onItemStateChange",
1320
- value: function onItemStateChange(i, newItemState) {
1321
- if (isDebug()) {
1322
- log('~ Item state changed ~');
1323
- log('Item', i); // Uses `JSON.stringify()` here instead of just outputting the JSON objects as is
1324
- // because outputting JSON objects as is would show different results later when
1325
- // the developer inspects those in the web browser console if those state objects
1326
- // get modified in between they've been output to the console and the developer
1327
- // decided to inspect them.
1328
-
1329
- log('Previous state' + '\n' + JSON.stringify(this.getState().itemStates[i], null, 2));
1330
- log('New state' + '\n' + JSON.stringify(newItemState, null, 2));
1331
- }
1332
-
1333
- this.getState().itemStates[i] = newItemState; // Schedule the item state update for after the new items have been rendered.
1334
-
1335
- if (this.newItemsWillBeRendered) {
1336
- if (!this.itemStatesThatChangedWhileNewItemsWereBeingRendered) {
1337
- this.itemStatesThatChangedWhileNewItemsWereBeingRendered = {};
1338
- }
1339
-
1340
- this.itemStatesThatChangedWhileNewItemsWereBeingRendered[String(i)] = newItemState;
1341
- }
1342
- }
1343
225
  }, {
1344
226
  key: "onItemHeightChange",
1345
227
  value: function onItemHeightChange(i) {
1346
- log('~ Re-measure item height ~');
1347
- log('Item', i);
1348
-
1349
- var _this$getState5 = this.getState(),
1350
- itemHeights = _this$getState5.itemHeights,
1351
- firstShownItemIndex = _this$getState5.firstShownItemIndex,
1352
- lastShownItemIndex = _this$getState5.lastShownItemIndex; // Check if the item is still rendered.
1353
-
1354
-
1355
- if (!(i >= firstShownItemIndex && i <= lastShownItemIndex)) {
1356
- // There could be valid cases when an item is no longer rendered
1357
- // by the time `.onItemHeightChange(i)` gets called.
1358
- // For example, suppose there's a list of several items on a page,
1359
- // and those items are in "minimized" state (having height 100px).
1360
- // Then, a user clicks an "Expand all items" button, and all items
1361
- // in the list are expanded (expanded item height is gonna be 700px).
1362
- // `VirtualScroller` demands that `.onItemHeightChange(i)` is called
1363
- // in such cases, and the developer has properly added the code to do that.
1364
- // So, if there were 10 "minimized" items visible on a page, then there
1365
- // will be 10 individual `.onItemHeightChange(i)` calls. No issues so far.
1366
- // But, as the first `.onItemHeightChange(i)` call executes, it immediately
1367
- // ("synchronously") triggers a re-layout, and that re-layout finds out
1368
- // that now, because the first item is big, it occupies most of the screen
1369
- // space, and only the first 3 items are visible on screen instead of 10,
1370
- // and so it leaves the first 3 items mounted and unmounts the rest 7.
1371
- // Then, after `VirtualScroller` has rerendered, the code returns to
1372
- // where it was executing, and calls `.onItemHeightChange(i)` for the
1373
- // second item. It also triggers an immediate re-layout that finds out
1374
- // that only the first 2 items are visible on screen, and it unmounts
1375
- // the third one too. After that, it calls `.onItemHeightChange(i)`
1376
- // for the third item, but that item is no longer rendered, so its height
1377
- // can't be measured, and the same's for all the rest of the original 10 items.
1378
- // So, even though the developer has written their code properly, there're
1379
- // still situations when the item could be no longer rendered by the time
1380
- // `.onItemHeightChange(i)` gets called.
1381
- return warn('The item is no longer rendered. This is not necessarily a bug, and could happen, for example, when there\'re several `onItemHeightChange(i)` calls issued at the same time.');
1382
- }
1383
-
1384
- var previousHeight = itemHeights[i];
1385
-
1386
- if (previousHeight === undefined) {
1387
- return reportError("\"onItemHeightChange()\" has been called for item ".concat(i, ", but that item hasn't been rendered before."));
1388
- }
1389
-
1390
- var newHeight = this.remeasureItemHeight(i);
1391
- log('Previous height', previousHeight);
1392
- log('New height', newHeight);
1393
-
1394
- if (previousHeight !== newHeight) {
1395
- log('~ Item height has changed ~'); // Update or reset previously calculated layout.
1396
-
1397
- this.updatePreviouslyCalculatedLayoutOnItemHeightChange(i, previousHeight, newHeight); // Recalculate layout.
1398
-
1399
- this.onUpdateShownItemIndexes({
1400
- reason: LAYOUT_REASON.ITEM_HEIGHT_CHANGED
1401
- }); // Schedule the item height update for after the new items have been rendered.
1402
-
1403
- if (this.newItemsWillBeRendered) {
1404
- if (!this.itemHeightsThatChangedWhileNewItemsWereBeingRendered) {
1405
- this.itemHeightsThatChangedWhileNewItemsWereBeingRendered = {};
1406
- }
228
+ this.hasToBeStarted();
1407
229
 
1408
- this.itemHeightsThatChangedWhileNewItemsWereBeingRendered[String(i)] = newHeight;
1409
- }
1410
- }
1411
- } // Updates the snapshot of the current layout when an item's height changes.
1412
- //
1413
- // The "previously calculated layout" feature is not currently used.
1414
- //
1415
- // The current layout snapshot could be stored as a "previously calculated layout" variable
1416
- // so that it could theoretically be used when calculating new layout incrementally
1417
- // rather than from scratch, which would be an optimization.
1418
- //
1419
-
1420
- }, {
1421
- key: "updatePreviouslyCalculatedLayoutOnItemHeightChange",
1422
- value: function updatePreviouslyCalculatedLayoutOnItemHeightChange(i, previousHeight, newHeight) {
1423
- if (this.previouslyCalculatedLayout) {
1424
- var heightDifference = newHeight - previousHeight;
1425
-
1426
- if (i < this.previouslyCalculatedLayout.firstShownItemIndex) {
1427
- // Patch `this.previouslyCalculatedLayout`'s `.beforeItemsHeight`.
1428
- this.previouslyCalculatedLayout.beforeItemsHeight += heightDifference;
1429
- } else if (i > this.previouslyCalculatedLayout.lastShownItemIndex) {
1430
- // Could patch `.afterItemsHeight` of `this.previouslyCalculatedLayout` here,
1431
- // if `.afterItemsHeight` property existed in `this.previouslyCalculatedLayout`.
1432
- if (this.previouslyCalculatedLayout.afterItemsHeight !== undefined) {
1433
- this.previouslyCalculatedLayout.afterItemsHeight += heightDifference;
1434
- }
1435
- } else {
1436
- // Patch `this.previouslyCalculatedLayout`'s shown items height.
1437
- this.previouslyCalculatedLayout.shownItemsHeight += newHeight - previousHeight;
1438
- }
1439
- }
230
+ this._onItemHeightChange(i);
1440
231
  }
1441
232
  /**
1442
- * Validates the heights of items to be hidden on next render.
1443
- * For example, a user could click a "Show more" button,
1444
- * or an "Expand YouTube video" button, which would result
1445
- * in the actual height of the list item being different
1446
- * from what has been initially measured in `this.itemHeights[i]`,
1447
- * if the developer didn't call `.onItemStateChange()` and `.onItemHeightChange(i)`.
233
+ * Updates an item's state in `state.itemStates[]`.
234
+ * @param {number} i Item index
235
+ * @param {any} i Item's new state
1448
236
  */
1449
237
 
1450
238
  }, {
1451
- key: "validateWillBeHiddenItemHeightsAreAccurate",
1452
- value: function validateWillBeHiddenItemHeightsAreAccurate(firstShownItemIndex, lastShownItemIndex) {
1453
- var isValid = true;
1454
- var i = this.getState().firstShownItemIndex;
1455
-
1456
- while (i <= this.getState().lastShownItemIndex) {
1457
- if (i >= firstShownItemIndex && i <= lastShownItemIndex) {// The item's still visible.
1458
- } else {
1459
- // The item will be hidden. Re-measure its height.
1460
- // The rationale is that there could be a situation when an item's
1461
- // height has changed, and the developer has properly added an
1462
- // `.onItemHeightChange(i)` call to notify `VirtualScroller`
1463
- // about that change, but at the same time that wouldn't work.
1464
- // For example, suppose there's a list of several items on a page,
1465
- // and those items are in "minimized" state (having height 100px).
1466
- // Then, a user clicks an "Expand all items" button, and all items
1467
- // in the list are expanded (expanded item height is gonna be 700px).
1468
- // `VirtualScroller` demands that `.onItemHeightChange(i)` is called
1469
- // in such cases, and the developer has properly added the code to do that.
1470
- // So, if there were 10 "minimized" items visible on a page, then there
1471
- // will be 10 individual `.onItemHeightChange(i)` calls. No issues so far.
1472
- // But, as the first `.onItemHeightChange(i)` call executes, it immediately
1473
- // ("synchronously") triggers a re-layout, and that re-layout finds out
1474
- // that now, because the first item is big, it occupies most of the screen
1475
- // space, and only the first 3 items are visible on screen instead of 10,
1476
- // and so it leaves the first 3 items mounted and unmounts the rest 7.
1477
- // Then, after `VirtualScroller` has rerendered, the code returns to
1478
- // where it was executing, and calls `.onItemHeightChange(i)` for the
1479
- // second item. It also triggers an immediate re-layout that finds out
1480
- // that only the first 2 items are visible on screen, and it unmounts
1481
- // the third one too. After that, it calls `.onItemHeightChange(i)`
1482
- // for the third item, but that item is no longer rendered, so its height
1483
- // can't be measured, and the same's for all the rest of the original 10 items.
1484
- // So, even though the developer has written their code properly, the
1485
- // `VirtualScroller` still ends up having incorrect `itemHeights[]`:
1486
- // `[700px, 700px, 100px, 100px, 100px, 100px, 100px, 100px, 100px, 100px]`
1487
- // while it should have been `700px` for all of them.
1488
- // To work around such issues, every item's height is re-measured before it
1489
- // gets hidden.
1490
- var previouslyMeasuredItemHeight = this.getState().itemHeights[i];
1491
- var actualItemHeight = this.remeasureItemHeight(i);
1492
-
1493
- if (actualItemHeight !== previouslyMeasuredItemHeight) {
1494
- if (isValid) {
1495
- log('~ Validate will-be-hidden item heights. ~'); // Update or reset previously calculated layout.
1496
-
1497
- this.updatePreviouslyCalculatedLayoutOnItemHeightChange(i, previouslyMeasuredItemHeight, actualItemHeight);
1498
- }
1499
-
1500
- isValid = false;
1501
- warn('Item index', i, 'is no longer visible and will be unmounted. Its height has changed from', previouslyMeasuredItemHeight, 'to', actualItemHeight, 'since it was last measured. This is not necessarily a bug, and could happen, for example, on screen width change, or when there\'re several `onItemHeightChange(i)` calls issued at the same time, and the first one triggers a re-layout before the rest of them have had a chance to be executed.');
1502
- }
1503
- }
1504
-
1505
- i++;
1506
- }
1507
-
1508
- return isValid;
1509
- }
1510
- }, {
1511
- key: "getShownItemIndexes",
1512
- value: function getShownItemIndexes() {
1513
- var itemsCount = this.getItemsCount();
1514
-
1515
- var _this$getVisibleArea = this.getVisibleArea(),
1516
- visibleAreaTop = _this$getVisibleArea.top,
1517
- visibleAreaBottom = _this$getVisibleArea.bottom;
1518
-
1519
- if (this.bypass) {
1520
- return {
1521
- firstShownItemIndex: 0,
1522
- lastShownItemIndex: itemsCount - 1 // shownItemsHeight: this.getState().itemHeights.reduce((sum, itemHeight) => sum + itemHeight, 0)
1523
-
1524
- };
1525
- } // Find the indexes of the items that are currently visible
1526
- // (or close to being visible) in the scrollable container.
1527
- // For scrollable containers other than the main screen, it could also
1528
- // check the visibility of such scrollable container itself, because it
1529
- // might be not visible.
1530
- // If such kind of an optimization would hypothetically be implemented,
1531
- // then it would also require listening for "scroll" events on the screen.
1532
- // Overall, I suppose that such "actual visibility" feature would be
1533
- // a very minor optimization and not something I'd deal with.
1534
-
1535
-
1536
- var isVisible = visibleAreaTop < this.itemsContainer.getHeight() && visibleAreaBottom > 0;
1537
-
1538
- if (!isVisible) {
1539
- log('The entire list is off-screen. No items are visible.');
1540
- return this.layout.getNonVisibleListShownItemIndexes();
1541
- } // Get shown item indexes.
1542
-
1543
-
1544
- return this.layout.getShownItemIndexes({
1545
- itemsCount: this.getItemsCount(),
1546
- visibleAreaTop: visibleAreaTop,
1547
- visibleAreaBottom: visibleAreaBottom
1548
- });
1549
- }
1550
- /**
1551
- * Updates the "from" and "to" shown item indexes.
1552
- * If the list is visible and some of the items being shown are new
1553
- * and are required to be measured first, then
1554
- * `firstNonMeasuredItemIndex` is defined.
1555
- * If the list is visible and all items being shown have been encountered
1556
- * (and measured) before, then `firstNonMeasuredItemIndex` is `undefined`.
1557
- *
1558
- * The `stateUpdate` parameter is just an optional "additional" state update.
1559
- */
239
+ key: "onItemStateChange",
240
+ value: function onItemStateChange(i, newItemState) {
241
+ this.hasToBeStarted();
1560
242
 
1561
- }, {
1562
- key: "updateItems",
1563
- value:
1564
- /**
1565
- * @deprecated
1566
- * `.updateItems()` has been renamed to `.setItems()`.
1567
- */
1568
- function updateItems(newItems, options) {
1569
- return this.setItems(newItems, options);
243
+ this._onItemStateChange(i, newItemState);
1570
244
  }
1571
245
  /**
1572
246
  * Updates `items`. For example, can prepend or append new items to the list.
@@ -1578,409 +252,8 @@ var VirtualScroller = /*#__PURE__*/function () {
1578
252
  key: "setItems",
1579
253
  value: function setItems(newItems) {
1580
254
  var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
1581
-
1582
- // * @param {object} [newCustomState] — If `customState` was passed to `getInitialState()`, this `newCustomState` updates it.
1583
- var _this$getState6 = this.getState(),
1584
- previousItems = _this$getState6.items; // Even if `newItems` are equal to `this.state.items`,
1585
- // still perform a `setState()` call, because, if `setState()` calls
1586
- // were "asynchronous", there could be a situation when a developer
1587
- // first calls `setItems(newItems)` and then `setItems(oldItems)`:
1588
- // if this function did `return` `if (newItems === this.state.items)`
1589
- // then `setState({ items: newItems })` would be scheduled as part of
1590
- // `setItems(newItems)` call, but the subsequent `setItems(oldItems)` call
1591
- // wouldn't do anything resulting in `newItems` being set as a result,
1592
- // and that wouldn't be what the developer intended.
1593
-
1594
-
1595
- var _this$getState7 = this.getState(),
1596
- itemStates = _this$getState7.itemStates;
1597
-
1598
- var _ref9 = this.resetLayoutAfterResize ? this.resetLayoutAfterResize.stateUpdate : this.getState(),
1599
- itemHeights = _ref9.itemHeights;
1600
-
1601
- log('~ Update items ~');
1602
- var layoutUpdate;
1603
- var itemsUpdateInfo; // Compare the new items to the current items.
1604
-
1605
- var itemsDiff = this.getItemsDiff(previousItems, newItems); // See if it's an "incremental" items update.
1606
-
1607
- if (itemsDiff) {
1608
- var _ref10 = this.resetLayoutAfterResize ? this.resetLayoutAfterResize.stateUpdate : this.getState(),
1609
- firstShownItemIndex = _ref10.firstShownItemIndex,
1610
- lastShownItemIndex = _ref10.lastShownItemIndex,
1611
- beforeItemsHeight = _ref10.beforeItemsHeight,
1612
- afterItemsHeight = _ref10.afterItemsHeight;
1613
-
1614
- var shouldRestoreScrollPosition = firstShownItemIndex === 0 && ( // `preserveScrollPosition` option name is deprecated,
1615
- // use `preserveScrollPositionOnPrependItems` instead.
1616
- options.preserveScrollPositionOnPrependItems || options.preserveScrollPosition);
1617
- var prependedItemsCount = itemsDiff.prependedItemsCount,
1618
- appendedItemsCount = itemsDiff.appendedItemsCount;
1619
- layoutUpdate = this.layout.getLayoutUpdateForItemsDiff({
1620
- firstShownItemIndex: firstShownItemIndex,
1621
- lastShownItemIndex: lastShownItemIndex,
1622
- beforeItemsHeight: beforeItemsHeight,
1623
- afterItemsHeight: afterItemsHeight
1624
- }, {
1625
- prependedItemsCount: prependedItemsCount,
1626
- appendedItemsCount: appendedItemsCount
1627
- }, {
1628
- itemsCount: newItems.length,
1629
- columnsCount: this.getActualColumnsCount(),
1630
- shouldRestoreScrollPosition: shouldRestoreScrollPosition
1631
- });
1632
-
1633
- if (prependedItemsCount > 0) {
1634
- log('Prepend', prependedItemsCount, 'items');
1635
- itemHeights = new Array(prependedItemsCount).concat(itemHeights);
1636
-
1637
- if (itemStates) {
1638
- itemStates = new Array(prependedItemsCount).concat(itemStates);
1639
- } // Restore scroll position after prepending items (if requested).
1640
-
1641
-
1642
- if (shouldRestoreScrollPosition) {
1643
- log('Will restore scroll position');
1644
- this.listHeightChangeWatcher.snapshot({
1645
- previousItems: previousItems,
1646
- newItems: newItems,
1647
- prependedItemsCount: prependedItemsCount
1648
- }); // "Seamless prepend" scenario doesn't result in a re-layout,
1649
- // so if any "non measured item" is currently pending,
1650
- // it doesn't get reset and will be handled after `state` is updated.
1651
-
1652
- if (this.firstNonMeasuredItemIndex !== undefined) {
1653
- this.firstNonMeasuredItemIndex += prependedItemsCount;
1654
- }
1655
- } else {
1656
- log('Reset layout'); // Reset layout because none of the prepended items have been measured.
1657
-
1658
- layoutUpdate = this.layout.getInitialLayoutValues({
1659
- itemsCount: newItems.length,
1660
- columnsCount: this.getActualColumnsCount()
1661
- }); // Unschedule a potentially scheduled layout update
1662
- // after measuring a previously non-measured item
1663
- // because the list will be re-layout anyway
1664
- // due to the new items being set.
1665
-
1666
- this.firstNonMeasuredItemIndex = undefined;
1667
- }
1668
- }
1669
-
1670
- if (appendedItemsCount > 0) {
1671
- log('Append', appendedItemsCount, 'items');
1672
- itemHeights = itemHeights.concat(new Array(appendedItemsCount));
1673
-
1674
- if (itemStates) {
1675
- itemStates = itemStates.concat(new Array(appendedItemsCount));
1676
- }
1677
- }
1678
-
1679
- itemsUpdateInfo = {
1680
- prepend: prependedItemsCount > 0,
1681
- append: appendedItemsCount > 0
1682
- };
1683
- } else {
1684
- log('Items have changed, and', itemsDiff ? 'a re-layout from scratch has been requested.' : 'it\'s not a simple append and/or prepend.', 'Rerender the entire list from scratch.');
1685
- log('Previous items', previousItems);
1686
- log('New items', newItems); // Reset item heights and item states.
1687
-
1688
- itemHeights = new Array(newItems.length);
1689
- itemStates = new Array(newItems.length);
1690
- layoutUpdate = this.layout.getInitialLayoutValues({
1691
- itemsCount: newItems.length,
1692
- columnsCount: this.getActualColumnsCount()
1693
- }); // Unschedule a potentially scheduled layout update
1694
- // after measuring a previously non-measured item
1695
- // because the list will be re-layout from scratch
1696
- // due to the new items being set.
1697
-
1698
- this.firstNonMeasuredItemIndex = undefined; // Also reset any potential pending scroll position restoration.
1699
- // For example, imagine a developer first called `.setItems(incrementalItemsUpdate)`
1700
- // and then called `.setItems(differentItems)` and there was no state update
1701
- // in between those two calls. This could happen because state updates aren't
1702
- // required to be "synchronous". On other words, calling `this.setState()`
1703
- // doesn't necessarily mean that the state is applied immediately.
1704
- // Imagine also that such "delayed" state updates could be batched,
1705
- // like they do in React inside event handlers (though that doesn't apply to this case):
1706
- // https://github.com/facebook/react/issues/10231#issuecomment-316644950
1707
- // If `this.listHeightChangeWatcher` wasn't reset on `.setItems(differentItems)`
1708
- // and if the second `this.setState()` call overwrites the first one
1709
- // then it would attempt to restore scroll position in a situation when
1710
- // it should no longer do that. Hence the reset here.
1711
-
1712
- this.listHeightChangeWatcher.reset();
1713
- itemsUpdateInfo = {
1714
- replace: true
1715
- };
1716
- }
1717
-
1718
- log('~ Update state ~'); // const layoutValuesAfterUpdate = {
1719
- // ...this.getState(),
1720
- // ...layoutUpdate
1721
- // }
1722
- // `layoutUpdate` is equivalent to `layoutValuesAfterUpdate` because
1723
- // `layoutUpdate` contains all the relevant properties.
1724
-
1725
- log('First shown item index', layoutUpdate.firstShownItemIndex);
1726
- log('Last shown item index', layoutUpdate.lastShownItemIndex);
1727
- log('Before items height', layoutUpdate.beforeItemsHeight);
1728
- log('After items height (actual or estimated)', layoutUpdate.afterItemsHeight); // Optionally preload items to be rendered.
1729
- //
1730
- // `layoutUpdate` is equivalent to `layoutValuesAfterUpdate` because
1731
- // `layoutUpdate` contains all the relevant properties.
1732
- //
1733
-
1734
- this.onBeforeShowItems(newItems, itemHeights, layoutUpdate.firstShownItemIndex, layoutUpdate.lastShownItemIndex); // `this.newItemsWillBeRendered` signals that new `items` are being rendered,
1735
- // and that `VirtualScroller` should temporarily stop all other updates.
1736
- //
1737
- // `this.newItemsWillBeRendered` is cleared in `didUpdateState()`.
1738
- //
1739
- // The values in `this.newItemsWillBeRendered` are used, for example,
1740
- // in `.onResize()` handler in order to not break state consistency when
1741
- // state updates are "asynchronous" (delayed) and there's a window resize event
1742
- // in between calling `setState()` below and that call actually being applied.
1743
- //
1744
-
1745
- this.newItemsWillBeRendered = _objectSpread(_objectSpread({}, itemsUpdateInfo), {}, {
1746
- count: newItems.length,
1747
- // `layoutUpdate` now contains all layout-related properties, even if those that
1748
- // didn't change. So `firstShownItemIndex` is always in `this.newItemsWillBeRendered`.
1749
- layout: layoutUpdate
1750
- }); // `layoutUpdate` now contains all layout-related properties, even if those that
1751
- // didn't change. So this part is no longer relevant.
1752
- //
1753
- // // If `firstShownItemIndex` is gonna be modified as a result of setting new items
1754
- // // then keep that "new" `firstShownItemIndex` in order for it to be used by
1755
- // // `onResize()` handler when it calculates "new" `firstShownItemIndex`
1756
- // // based on the new columns count (corresponding to the new window width).
1757
- // if (layoutUpdate.firstShownItemIndex !== undefined) {
1758
- // this.newItemsWillBeRendered = {
1759
- // ...this.newItemsWillBeRendered,
1760
- // firstShownItemIndex: layoutUpdate.firstShownItemIndex
1761
- // }
1762
- // }
1763
- // Update `VirtualScroller` state.
1764
- //
1765
- // This state update should overwrite all the `state` properties
1766
- // that are also updated in the "on scroll" handler (`getShownItemIndexes()`):
1767
- //
1768
- // * `firstShownItemIndex`
1769
- // * `lastShownItemIndex`
1770
- // * `beforeItemsHeight`
1771
- // * `afterItemsHeight`
1772
- //
1773
- // That's because this `setState()` update has a higher priority
1774
- // than that of the "on scroll" handler, so it should overwrite
1775
- // any potential state changes dispatched by the "on scroll" handler.
1776
- //
1777
-
1778
- var newState = _objectSpread(_objectSpread({}, layoutUpdate), {}, {
1779
- items: newItems,
1780
- itemStates: itemStates,
1781
- itemHeights: itemHeights
1782
- }); // Introduced `shouldIncludeBeforeResizeValuesInState()` getter just to prevent
1783
- // cluttering `state` with `beforeResize: undefined` property if `beforeResize`
1784
- // hasn't ever been set in `state` previously.
1785
-
1786
-
1787
- if (this.beforeResize.shouldIncludeBeforeResizeValuesInState()) {
1788
- if (this.shouldDiscardBeforeResizeItemHeights()) {
1789
- // Reset "before resize" item heights because now there're new items prepended
1790
- // with unknown heights, or completely new items with unknown heights, so
1791
- // `beforeItemsHeight` value won't be preserved anyway.
1792
- newState.beforeResize = undefined;
1793
- } else {
1794
- // Overwrite `beforeResize` property in `state` even if it wasn't modified
1795
- // because state updates could be "asynchronous" and in that case there could be
1796
- // some previous `setState()` call from some previous `setItems()` call that
1797
- // hasn't yet been applied, and that previous call might have scheduled setting
1798
- // `state.beforeResize` property to `undefined` in order to reset it, but this
1799
- // next `setState()` call might not require resetting `state.beforeResize` property
1800
- // so it should undo resetting it by simply overwriting it with its normal value.
1801
- newState.beforeResize = this.resetLayoutAfterResize ? this.resetLayoutAfterResize.stateUpdate.beforeResize : this.getState().beforeResize;
1802
- }
1803
- } // `newState` should also overwrite all `state` properties that're updated in `onResize()`
1804
- // because `setItems()`'s state updates always overwrite `onResize()`'s state updates.
1805
- // (The least-priority ones are `onScroll()` state updates, but those're simply skipped
1806
- // if there's a pending `setItems()` or `onResize()` update).
1807
- //
1808
- // `state` property exceptions:
1809
- //
1810
- // `verticalSpacing` property is not updated here because it's fine setting it to
1811
- // `undefined` in `onResize()` — it will simply be re-measured after the component re-renders.
1812
- //
1813
- // `columnsCount` property is also not updated here because by definition it's only
1814
- // updated in `onResize()`.
1815
- // Render.
1816
-
1817
-
1818
- this.setState(newState);
1819
- }
1820
- }, {
1821
- key: "getItemsDiff",
1822
- value: function getItemsDiff(previousItems, newItems) {
1823
- return _getItemsDiff(previousItems, newItems, this.isItemEqual);
1824
- } // Returns whether "before resize" item heights should be discarded
1825
- // as a result of calling `setItems()` with a new set of items
1826
- // when an asynchronous `setState()` call inside that function
1827
- // hasn't been applied yet.
1828
- //
1829
- // If `setItems()` update was an "incremental" one and no items
1830
- // have been prepended, then `firstShownItemIndex` is preserved,
1831
- // and all items' heights before it should be kept in order to
1832
- // preserve the top offset of the first shown item so that there's
1833
- // no "content jumping".
1834
- //
1835
- // If `setItems()` update was an "incremental" one but there're
1836
- // some prepended items, then it means that now there're new items
1837
- // with unknown heights at the top, so the top offset of the first
1838
- // shown item won't be preserved because there're no "before resize"
1839
- // heights of those items.
1840
- //
1841
- // If `setItems()` update was not an "incremental" one, then don't
1842
- // attempt to restore previous item heights after a potential window
1843
- // width change because all item heights have been reset.
1844
- //
1845
-
1846
- }, {
1847
- key: "shouldDiscardBeforeResizeItemHeights",
1848
- value: function shouldDiscardBeforeResizeItemHeights() {
1849
- if (this.newItemsWillBeRendered) {
1850
- var _this$newItemsWillBeR = this.newItemsWillBeRendered,
1851
- prepend = _this$newItemsWillBeR.prepend,
1852
- replace = _this$newItemsWillBeR.replace;
1853
- return prepend || replace;
1854
- }
1855
- }
1856
- }, {
1857
- key: "onResize",
1858
- value: function onResize() {
1859
- // Reset "previously calculated layout".
1860
- //
1861
- // The "previously calculated layout" feature is not currently used.
1862
- //
1863
- // The current layout snapshot could be stored as a "previously calculated layout" variable
1864
- // so that it could theoretically be used when calculating new layout incrementally
1865
- // rather than from scratch, which would be an optimization.
1866
- //
1867
- this.previouslyCalculatedLayout = undefined; // Cancel any potential scheduled scroll position restoration.
1868
-
1869
- this.listHeightChangeWatcher.reset(); // Get the most recent items count.
1870
- // If there're a "pending" `setItems()` call then use the items count from that call
1871
- // instead of using the count of currently shown `items` from `state`.
1872
- // A `setItems()` call is "pending" when `setState()` operation is "asynchronous", that is
1873
- // when `setState()` calls aren't applied immediately, like in React.
1874
-
1875
- var itemsCount = this.newItemsWillBeRendered ? this.newItemsWillBeRendered.count : this.getState().itemHeights.length; // If layout values have been calculated as a result of a "pending" `setItems()` call,
1876
- // then don't discard those new layout values and use them instead of the ones from `state`.
1877
- //
1878
- // A `setItems()` call is "pending" when `setState()` operation is "asynchronous", that is
1879
- // when `setState()` calls aren't applied immediately, like in React.
1880
- //
1881
-
1882
- var layout = this.newItemsWillBeRendered ? this.newItemsWillBeRendered.layout : this.getState(); // Update `VirtualScroller` state.
1883
-
1884
- var newState = {
1885
- // This state update should also overwrite all the `state` properties
1886
- // that are also updated in the "on scroll" handler (`getShownItemIndexes()`):
1887
- //
1888
- // * `firstShownItemIndex`
1889
- // * `lastShownItemIndex`
1890
- // * `beforeItemsHeight`
1891
- // * `afterItemsHeight`
1892
- //
1893
- // That's because this `setState()` update has a higher priority
1894
- // than that of the "on scroll" handler, so it should overwrite
1895
- // any potential state changes dispatched by the "on scroll" handler.
1896
- //
1897
- // All these properties might have changed, but they're not
1898
- // recalculated here becase they'll be recalculated after
1899
- // this new state is applied (rendered).
1900
- //
1901
- firstShownItemIndex: layout.firstShownItemIndex,
1902
- lastShownItemIndex: layout.lastShownItemIndex,
1903
- beforeItemsHeight: layout.beforeItemsHeight,
1904
- afterItemsHeight: layout.afterItemsHeight,
1905
- // Reset item heights, because if scrollable container's width (or height)
1906
- // has changed, then the list width (or height) most likely also has changed,
1907
- // and also some CSS `@media()` rules might have been added or removed.
1908
- // So re-render the list entirely.
1909
- itemHeights: new Array(itemsCount),
1910
- columnsCount: this.getActualColumnsCountForState(),
1911
- // Re-measure vertical spacing after render because new CSS styles
1912
- // might be applied for the new window width.
1913
- verticalSpacing: undefined
1914
- };
1915
- var firstShownItemIndex = layout.firstShownItemIndex,
1916
- lastShownItemIndex = layout.lastShownItemIndex; // Get the `columnsCount` for the new window width.
1917
-
1918
- var newColumnsCount = this.getActualColumnsCount(); // Re-calculate `firstShownItemIndex` and `lastShownItemIndex`
1919
- // based on the new `columnsCount` so that the whole row is visible.
1920
-
1921
- var newFirstShownItemIndex = Math.floor(firstShownItemIndex / newColumnsCount) * newColumnsCount;
1922
- var newLastShownItemIndex = Math.min(Math.ceil((lastShownItemIndex + 1) / newColumnsCount) * newColumnsCount, itemsCount) - 1; // Potentially update `firstShownItemIndex` if it needs to be adjusted in order to
1923
- // correspond to the new `columnsCount`.
1924
-
1925
- if (newFirstShownItemIndex !== firstShownItemIndex) {
1926
- log('Columns Count changed from', this.getState().columnsCount || 1, 'to', newColumnsCount);
1927
- log('First Shown Item Index needs to change from', firstShownItemIndex, 'to', newFirstShownItemIndex);
1928
- } // Always rewrite `firstShownItemIndex` and `lastShownItemIndex`
1929
- // as part of the `state` update, even if it hasn't been modified.
1930
- //
1931
- // The reason is that there could be two subsequent `onResize()` calls:
1932
- // the first one could be user resizing the window to half of its width,
1933
- // resulting in an "asynchronous" `setState()` call, and then, before that
1934
- // `setState()` call is applied, a second resize event happens when the user
1935
- // has resized the window back to its original width, meaning that the
1936
- // `columnsCount` is back to its original value.
1937
- // In that case, the final `newFirstShownItemIndex` will be equal to the
1938
- // original `firstShownItemIndex` that was in `state` before the user
1939
- // has started resizing the window, so, in the end, `state.firstShownItemIndex`
1940
- // property wouldn't have changed, but it still has to be part of the final
1941
- // state update in order to overwrite the previous update of `firstShownItemIndex`
1942
- // property that has been scheduled to be applied in state after the first resize
1943
- // happened.
1944
- //
1945
-
1946
-
1947
- newState.firstShownItemIndex = newFirstShownItemIndex;
1948
- newState.lastShownItemIndex = newLastShownItemIndex;
1949
- var verticalSpacing = this.getVerticalSpacing();
1950
- var columnsCount = this.getColumnsCount(); // `beforeResize` is always overwritten in `state` here.
1951
- // (once it has started being tracked in `state`)
1952
-
1953
- if (this.shouldDiscardBeforeResizeItemHeights() || newFirstShownItemIndex === 0) {
1954
- if (this.beforeResize.shouldIncludeBeforeResizeValuesInState()) {
1955
- newState.beforeResize = undefined;
1956
- }
1957
- } // Snapshot "before resize" values in order to preserve the currently
1958
- // shown items' vertical position on screen so that there's no "content jumping".
1959
- else {
1960
- // Keep "before resize" values in order to preserve the currently
1961
- // shown items' vertical position on screen so that there's no
1962
- // "content jumping". These "before resize" values will be discarded
1963
- // when (if) the user scrolls back to the top of the list.
1964
- newState.beforeResize = {
1965
- verticalSpacing: verticalSpacing,
1966
- columnsCount: columnsCount,
1967
- itemHeights: this.beforeResize.snapshotBeforeResizeItemHeights({
1968
- firstShownItemIndex: firstShownItemIndex,
1969
- newFirstShownItemIndex: newFirstShownItemIndex,
1970
- newColumnsCount: newColumnsCount
1971
- })
1972
- };
1973
- } // `this.resetLayoutAfterResize` tells `VirtualScroller` that it should
1974
- // temporarily stop other updates (like "on scroll" updates) and wait
1975
- // for the new `state` to be applied, after which the `didUpdateState()`
1976
- // function will clear this flag and perform a re-layout.
1977
-
1978
-
1979
- this.resetLayoutAfterResize = {
1980
- stateUpdate: newState
1981
- }; // Rerender.
1982
-
1983
- this.setState(newState);
255
+ this.hasToBeStarted();
256
+ return this._setItems(newItems, options);
1984
257
  }
1985
258
  }]);
1986
259
 
@@ -1988,5 +261,4 @@ var VirtualScroller = /*#__PURE__*/function () {
1988
261
  }();
1989
262
 
1990
263
  export { VirtualScroller as default };
1991
- var SLOW_LAYOUT_DURATION = 15; // in milliseconds.
1992
264
  //# sourceMappingURL=VirtualScroller.js.map