infinite-scroll.js 13KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386
  1. import { Directive, ElementRef, EventEmitter, Input, NgZone, Output } from '@angular/core';
  2. import { Content } from '../content/content';
  3. import { DomController } from '../../platform/dom-controller';
  4. /**
  5. * @name InfiniteScroll
  6. * @description
  7. * The Infinite Scroll allows you to perform an action when the user
  8. * scrolls a specified distance from the bottom or top of the page.
  9. *
  10. * The expression assigned to the `infinite` event is called when
  11. * the user scrolls to the specified distance. When this expression
  12. * has finished its tasks, it should call the `complete()` method
  13. * on the infinite scroll instance.
  14. *
  15. * @usage
  16. * ```html
  17. * <ion-content>
  18. *
  19. * <ion-list>
  20. * <ion-item *ngFor="let i of items">{% raw %}{{i}}{% endraw %}</ion-item>
  21. * </ion-list>
  22. *
  23. * <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
  24. * <ion-infinite-scroll-content></ion-infinite-scroll-content>
  25. * </ion-infinite-scroll>
  26. *
  27. * </ion-content>
  28. * ```
  29. *
  30. * ```ts
  31. * @Component({...})
  32. * export class NewsFeedPage {
  33. * items = [];
  34. *
  35. * constructor() {
  36. * for (let i = 0; i < 30; i++) {
  37. * this.items.push( this.items.length );
  38. * }
  39. * }
  40. *
  41. * doInfinite(infiniteScroll) {
  42. * console.log('Begin async operation');
  43. *
  44. * setTimeout(() => {
  45. * for (let i = 0; i < 30; i++) {
  46. * this.items.push( this.items.length );
  47. * }
  48. *
  49. * console.log('Async operation has ended');
  50. * infiniteScroll.complete();
  51. * }, 500);
  52. * }
  53. *
  54. * }
  55. * ```
  56. *
  57. * ## `waitFor` method of InfiniteScroll
  58. *
  59. * In case if your async operation returns promise you can utilize
  60. * `waitFor` method inside your template.
  61. *
  62. * ```html
  63. * <ion-content>
  64. *
  65. * <ion-list>
  66. * <ion-item *ngFor="let item of items">{{item}}</ion-item>
  67. * </ion-list>
  68. *
  69. * <ion-infinite-scroll (ionInfinite)="$event.waitFor(doInfinite())">
  70. * <ion-infinite-scroll-content></ion-infinite-scroll-content>
  71. * </ion-infinite-scroll>
  72. *
  73. * </ion-content>
  74. * ```
  75. *
  76. * ```ts
  77. * @Component({...})
  78. * export class NewsFeedPage {
  79. * items = [];
  80. *
  81. * constructor() {
  82. * for (var i = 0; i < 30; i++) {
  83. * this.items.push( this.items.length );
  84. * }
  85. * }
  86. *
  87. * doInfinite(): Promise<any> {
  88. * console.log('Begin async operation');
  89. *
  90. * return new Promise((resolve) => {
  91. * setTimeout(() => {
  92. * for (var i = 0; i < 30; i++) {
  93. * this.items.push( this.items.length );
  94. * }
  95. *
  96. * console.log('Async operation has ended');
  97. * resolve();
  98. * }, 500);
  99. * })
  100. * }
  101. * }
  102. * ```
  103. *
  104. * ## Infinite Scroll Content
  105. *
  106. * By default, Ionic uses the infinite scroll spinner that looks
  107. * best for the platform the user is on. However, you can change the
  108. * default spinner or add text by adding properties to the
  109. * `ion-infinite-scroll-content` component.
  110. *
  111. * ```html
  112. * <ion-content>
  113. *
  114. * <ion-infinite-scroll (ionInfinite)="doInfinite($event)">
  115. * <ion-infinite-scroll-content
  116. * loadingSpinner="bubbles"
  117. * loadingText="Loading more data...">
  118. * </ion-infinite-scroll-content>
  119. * </ion-infinite-scroll>
  120. *
  121. * </ion-content>
  122. * ```
  123. *
  124. *
  125. * ## Further Customizing Infinite Scroll Content
  126. *
  127. * The `ion-infinite-scroll` component holds the infinite scroll logic.
  128. * It requires a child component in order to display the content.
  129. * Ionic uses `ion-infinite-scroll-content` by default. This component
  130. * displays the infinite scroll and changes the look depending
  131. * on the infinite scroll's state. Separating these components allows
  132. * developers to create their own infinite scroll content components.
  133. * You could replace our default content with custom SVG or CSS animations.
  134. *
  135. * @demo /docs/demos/src/infinite-scroll/
  136. *
  137. */
  138. export class InfiniteScroll {
  139. constructor(_content, _zone, _elementRef, _dom) {
  140. this._content = _content;
  141. this._zone = _zone;
  142. this._elementRef = _elementRef;
  143. this._dom = _dom;
  144. this._lastCheck = 0;
  145. this._highestY = 0;
  146. this._thr = '15%';
  147. this._thrPx = 0;
  148. this._thrPc = 0.15;
  149. this._position = POSITION_BOTTOM;
  150. this._init = false;
  151. /**
  152. * @internal
  153. */
  154. this.state = STATE_ENABLED;
  155. /**
  156. * @output {event} Emitted when the scroll reaches
  157. * the threshold distance. From within your infinite handler,
  158. * you must call the infinite scroll's `complete()` method when
  159. * your async operation has completed.
  160. */
  161. this.ionInfinite = new EventEmitter();
  162. _content.setElementClass('has-infinite-scroll', true);
  163. }
  164. /**
  165. * @input {string} The threshold distance from the bottom
  166. * of the content to call the `infinite` output event when scrolled.
  167. * The threshold value can be either a percent, or
  168. * in pixels. For example, use the value of `10%` for the `infinite`
  169. * output event to get called when the user has scrolled 10%
  170. * from the bottom of the page. Use the value `100px` when the
  171. * scroll is within 100 pixels from the bottom of the page.
  172. * Default is `15%`.
  173. */
  174. get threshold() {
  175. return this._thr;
  176. }
  177. set threshold(val) {
  178. this._thr = val;
  179. if (val.indexOf('%') > -1) {
  180. this._thrPx = 0;
  181. this._thrPc = (parseFloat(val) / 100);
  182. }
  183. else {
  184. this._thrPx = parseFloat(val);
  185. this._thrPc = 0;
  186. }
  187. }
  188. /**
  189. * @input {boolean} If true, Whether or not the infinite scroll should be
  190. * enabled or not. Setting to `false` will remove scroll event listeners
  191. * and hide the display.
  192. */
  193. set enabled(shouldEnable) {
  194. this.enable(shouldEnable);
  195. }
  196. /**
  197. * @input {string} The position of the infinite scroll element.
  198. * The value can be either `top` or `bottom`.
  199. * Default is `bottom`.
  200. */
  201. get position() {
  202. return this._position;
  203. }
  204. set position(val) {
  205. if (val === POSITION_TOP || val === POSITION_BOTTOM) {
  206. this._position = val;
  207. }
  208. else {
  209. console.error(`Invalid value for ion-infinite-scroll's position input. Its value should be '${POSITION_BOTTOM}' or '${POSITION_TOP}'.`);
  210. }
  211. }
  212. _onScroll(ev) {
  213. if (this.state === STATE_LOADING || this.state === STATE_DISABLED) {
  214. return 1;
  215. }
  216. if (this._lastCheck + 32 > ev.timeStamp) {
  217. // no need to check less than every XXms
  218. return 2;
  219. }
  220. this._lastCheck = ev.timeStamp;
  221. // ******** DOM READ ****************
  222. const infiniteHeight = this._elementRef.nativeElement.scrollHeight;
  223. if (!infiniteHeight) {
  224. // if there is no height of this element then do nothing
  225. return 3;
  226. }
  227. // ******** DOM READ ****************
  228. const d = this._content.getContentDimensions();
  229. const height = d.contentHeight;
  230. const threshold = this._thrPc ? (height * this._thrPc) : this._thrPx;
  231. // ******** DOM READS ABOVE / DOM WRITES BELOW ****************
  232. let distanceFromInfinite;
  233. if (this._position === POSITION_BOTTOM) {
  234. distanceFromInfinite = d.scrollHeight - infiniteHeight - d.scrollTop - height - threshold;
  235. }
  236. else {
  237. (void 0) /* assert */;
  238. distanceFromInfinite = d.scrollTop - infiniteHeight - threshold;
  239. }
  240. if (distanceFromInfinite < 0) {
  241. // ******** DOM WRITE ****************
  242. this._dom.write(() => {
  243. this._zone.run(() => {
  244. if (this.state !== STATE_LOADING && this.state !== STATE_DISABLED) {
  245. this.state = STATE_LOADING;
  246. this.ionInfinite.emit(this);
  247. }
  248. });
  249. });
  250. return 5;
  251. }
  252. return 6;
  253. }
  254. /**
  255. * Call `complete()` within the `infinite` output event handler when
  256. * your async operation has completed. For example, the `loading`
  257. * state is while the app is performing an asynchronous operation,
  258. * such as receiving more data from an AJAX request to add more items
  259. * to a data list. Once the data has been received and UI updated, you
  260. * then call this method to signify that the loading has completed.
  261. * This method will change the infinite scroll's state from `loading`
  262. * to `enabled`.
  263. */
  264. complete() {
  265. if (this.state !== STATE_LOADING) {
  266. return;
  267. }
  268. if (this._position === POSITION_BOTTOM) {
  269. this.state = STATE_ENABLED;
  270. return;
  271. }
  272. (void 0) /* assert */;
  273. /* New content is being added at the top, but the scrollTop position stays the same,
  274. which causes a scroll jump visually. This algorithm makes sure to prevent this.
  275. (Frame 1)
  276. complete() is called, but the UI hasn't had time to update yet.
  277. Save the current content dimensions.
  278. Wait for the next frame using _dom.read, so the UI will be updated.
  279. (Frame 2)
  280. Read the new content dimensions.
  281. Calculate the height difference and the new scroll position.
  282. Delay the scroll position change until other possible dom reads are done using _dom.write to be performant.
  283. (Still frame 2, if I'm correct)
  284. Change the scroll position (= visually maintain the scroll position).
  285. Change the state to re-enable the InfiniteScroll. This should be after changing the scroll position, or it could cause the InfiniteScroll to be triggered again immediately.
  286. (Frame 3)
  287. Done.
  288. */
  289. // ******** DOM READ ****************
  290. // Save the current content dimensions before the UI updates
  291. const prevDim = this._content.getContentDimensions();
  292. // ******** DOM READ ****************
  293. this._dom.read(() => {
  294. // UI has updated, save the new content dimensions
  295. const newDim = this._content.getContentDimensions();
  296. // New content was added on top, so the scroll position should be changed immediately to prevent it from jumping around
  297. const newScrollTop = newDim.scrollHeight - (prevDim.scrollHeight - prevDim.scrollTop);
  298. // ******** DOM WRITE ****************
  299. this._dom.write(() => {
  300. this._content.scrollTop = newScrollTop;
  301. this.state = STATE_ENABLED;
  302. });
  303. });
  304. }
  305. /**
  306. * Pass a promise inside `waitFor()` within the `infinite` output event handler in order to
  307. * change state of infiniteScroll to "complete"
  308. */
  309. waitFor(action) {
  310. const enable = this.complete.bind(this);
  311. action.then(enable, enable);
  312. }
  313. /**
  314. * Call `enable(false)` to disable the infinite scroll from actively
  315. * trying to receive new data while scrolling. This method is useful
  316. * when it is known that there is no more data that can be added, and
  317. * the infinite scroll is no longer needed.
  318. * @param {boolean} shouldEnable If the infinite scroll should be
  319. * enabled or not. Setting to `false` will remove scroll event listeners
  320. * and hide the display.
  321. */
  322. enable(shouldEnable) {
  323. this.state = (shouldEnable ? STATE_ENABLED : STATE_DISABLED);
  324. this._setListeners(shouldEnable);
  325. }
  326. /**
  327. * @hidden
  328. */
  329. _setListeners(shouldListen) {
  330. if (this._init) {
  331. if (shouldListen) {
  332. if (!this._scLsn) {
  333. this._scLsn = this._content.ionScroll.subscribe(this._onScroll.bind(this));
  334. }
  335. }
  336. else {
  337. this._scLsn && this._scLsn.unsubscribe();
  338. this._scLsn = null;
  339. }
  340. }
  341. }
  342. /**
  343. * @hidden
  344. */
  345. ngAfterContentInit() {
  346. this._init = true;
  347. this._setListeners(this.state !== STATE_DISABLED);
  348. if (this._position === POSITION_TOP) {
  349. this._content.scrollDownOnLoad = true;
  350. }
  351. }
  352. /**
  353. * @hidden
  354. */
  355. ngOnDestroy() {
  356. this._setListeners(false);
  357. }
  358. }
  359. InfiniteScroll.decorators = [
  360. { type: Directive, args: [{
  361. selector: 'ion-infinite-scroll'
  362. },] },
  363. ];
  364. /** @nocollapse */
  365. InfiniteScroll.ctorParameters = () => [
  366. { type: Content, },
  367. { type: NgZone, },
  368. { type: ElementRef, },
  369. { type: DomController, },
  370. ];
  371. InfiniteScroll.propDecorators = {
  372. 'threshold': [{ type: Input },],
  373. 'enabled': [{ type: Input },],
  374. 'position': [{ type: Input },],
  375. 'ionInfinite': [{ type: Output },],
  376. };
  377. const STATE_ENABLED = 'enabled';
  378. const STATE_DISABLED = 'disabled';
  379. const STATE_LOADING = 'loading';
  380. const POSITION_TOP = 'top';
  381. const POSITION_BOTTOM = 'bottom';
  382. //# sourceMappingURL=infinite-scroll.js.map