-
Notifications
You must be signed in to change notification settings - Fork 107
/
ui-scroll.js
947 lines (803 loc) · 31.6 KB
/
ui-scroll.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
/*!
globals: angular, window
List of used element methods available in JQuery but not in JQuery Lite
element.before(elem)
element.height()
element.outerHeight(true)
element.height(value) = only for Top/Bottom padding elements
element.scrollTop()
element.scrollTop(value)
*/
angular.module('ui.scroll', [])
.directive('uiScrollViewport', function () {
return {
restrict: 'A',
controller: [
'$log',
'$scope',
'$element',
function (console, scope, element) {
let self = this;
self.container = element;
self.viewport = element;
angular.forEach(element.children(),
(child => {
if (child.tagName.toLowerCase() === 'tbody') {
self.viewport = angular.element(child);
}
}));
}
]
};
})
.directive('uiScroll', [
'$log',
'$injector',
'$rootScope',
'$timeout',
'$q',
'$parse',
function (console, $injector, $rootScope, $timeout, $q, $parse) {
const $animate = ($injector.has && $injector.has('$animate')) ? $injector.get('$animate') : null;
const isAngularVersionLessThen1_3 = angular.version.major === 1 && angular.version.minor < 3;
return {
require: ['?^^uiScrollViewport'],
restrict: 'A',
transclude: 'element',
priority: 1000,
terminal: true,
link: link
};
// Element manipulation routines
function insertElement(newElement, previousElement) {
previousElement.after(newElement);
return [];
}
function removeElement(wrapper) {
wrapper.element.remove();
wrapper.scope.$destroy();
return [];
}
function insertElementAnimated(newElement, previousElement) {
if (!$animate) {
return insertElement(newElement, previousElement);
}
if (isAngularVersionLessThen1_3) {
const deferred = $q.defer();
// no need for parent - previous element is never null
$animate.enter(newElement, null, previousElement, () => deferred.resolve());
return [deferred.promise];
}
// no need for parent - previous element is never null
return [$animate.enter(newElement, null, previousElement)];
}
function removeElementAnimated(wrapper) {
if (!$animate) {
return removeElement(wrapper);
}
if (isAngularVersionLessThen1_3) {
const deferred = $q.defer();
$animate.leave(wrapper.element, () => {
wrapper.scope.$destroy();
return deferred.resolve();
});
return [deferred.promise];
}
return [($animate.leave(wrapper.element)).then(() => wrapper.scope.$destroy())];
}
function Buffer(bufferSize) {
const buffer = Object.create(Array.prototype);
angular.extend(buffer, {
size: bufferSize,
reset(startIndex) {
buffer.remove(0, buffer.length);
buffer.eof = false;
buffer.bof = false;
buffer.first = startIndex;
buffer.next = startIndex;
buffer.minIndex = startIndex;
buffer.maxIndex = startIndex;
buffer.minIndexUser = null;
buffer.maxIndexUser = null;
},
append(items) {
items.forEach((item) => {
++buffer.next;
buffer.insert('append', item);
});
buffer.maxIndex = buffer.eof ? buffer.next - 1 : Math.max(buffer.next - 1, buffer.maxIndex);
},
prepend(items) {
items.reverse().forEach((item) => {
--buffer.first;
buffer.insert('prepend', item);
});
buffer.minIndex = buffer.bof ? buffer.minIndex = buffer.first : Math.min(buffer.first, buffer.minIndex);
},
/**
* inserts wrapped element in the buffer
* the first argument is either operation keyword (see below) or a number for operation 'insert'
* for insert the number is the index for the buffer element the new one have to be inserted after
* operations: 'append', 'prepend', 'insert', 'remove', 'update', 'none'
*/
insert(operation, item) {
const wrapper = {
item : item
};
if (operation % 1 === 0) {// it is an insert
wrapper.op = 'insert';
buffer.splice(operation, 0, wrapper);
} else {
wrapper.op = operation;
switch (operation) {
case 'append':
buffer.push(wrapper);
break;
case 'prepend':
buffer.unshift(wrapper);
break;
}
}
},
// removes elements from buffer
remove(arg1, arg2) {
if (angular.isNumber(arg1)) {
// removes items from arg1 (including) through arg2 (excluding)
for (let i = arg1; i < arg2; i++) {
removeElement(buffer[i]);
}
return buffer.splice(arg1, arg2 - arg1);
}
// removes single item(wrapper) from the buffer
buffer.splice(buffer.indexOf(arg1), 1);
return removeElementAnimated(arg1);
},
effectiveHeight(elements) {
if (!elements.length)
return 0;
let top = Number.MAX_VALUE;
let bottom = Number.MIN_VALUE;
elements.forEach((wrapper) => {
if (wrapper.element[0].offsetParent) {
// element style is not display:none
top = Math.min(top, wrapper.element.offset().top);
bottom = Math.max(bottom, wrapper.element.offset().top + wrapper.element.outerHeight(true));
}
});
return Math.max(0, bottom - top);
}
});
return buffer;
}
function Viewport(buffer, element, viewportController, attrs) {
const PADDING_MIN = 0.3;
const PADDING_DEFAULT = 0.5;
let topPadding;
let bottomPadding;
const viewport = viewportController && viewportController.viewport ? viewportController.viewport : angular.element(window);
const container = viewportController && viewportController.container ? viewportController.container : undefined;
viewport.css({
'overflow-y': 'auto',
'display': 'block'
});
function Cache() {
const cache = Object.create(Array.prototype);
angular.extend(cache, {
add(item) {
let existedItem = cache.find(i => i.index === item.scope.$index);
if (existedItem) {
existedItem.height = item.element.outerHeight();
return;
}
cache.push({
index: item.scope.$index,
height: item.element.outerHeight()
});
},
clear() {
cache.length = 0;
}
});
return cache;
}
function Padding(template) {
let result;
switch (template.tagName) {
case 'dl':
throw new Error(`ui-scroll directive does not support <${template.tagName}> as a repeating tag: ${template.outerHTML}`);
case 'tr':
let table = angular.element('<table><tr><td><div></div></td></tr></table>');
result = table.find('tr');
break;
case 'li':
result = angular.element('<li></li>');
break;
default:
result = angular.element('<div></div>');
}
result.cache = new Cache();
return result;
}
function bufferPadding() {
return viewport.outerHeight() * Math.max(PADDING_MIN, +attrs.padding || PADDING_DEFAULT); // some extra space to initiate preload
}
angular.extend(viewport, {
createPaddingElements(template) {
topPadding = new Padding(template);
bottomPadding = new Padding(template);
element.before(topPadding);
element.after(bottomPadding);
},
applyContainerStyle() {
if (container && container !== viewport)
viewport.css('height', window.getComputedStyle(container[0]).height);
},
bottomDataPos() {
let scrollHeight = viewport[0].scrollHeight;
scrollHeight = scrollHeight != null ? scrollHeight : viewport[0].document.documentElement.scrollHeight;
return scrollHeight - bottomPadding.height();
},
topDataPos() {
return topPadding.height();
},
bottomVisiblePos() {
return viewport.scrollTop() + viewport.outerHeight();
},
topVisiblePos() {
return viewport.scrollTop();
},
insertElement(e, sibling) {
return insertElement(e, sibling || topPadding);
},
insertElementAnimated(e, sibling) {
return insertElementAnimated(e, sibling || topPadding);
},
shouldLoadBottom() {
return !buffer.eof && viewport.bottomDataPos() < viewport.bottomVisiblePos() + bufferPadding();
},
clipBottom() {
// clip the invisible items off the bottom
let overage = 0;
let overageHeight = 0;
let itemHeight = 0;
let emptySpaceHeight = viewport.bottomDataPos() - viewport.bottomVisiblePos() - bufferPadding();
for (let i = buffer.length - 1; i >= 0; i--) {
itemHeight = buffer[i].element.outerHeight(true);
if(overageHeight + itemHeight > emptySpaceHeight) {
break;
}
bottomPadding.cache.add(buffer[i]);
overageHeight += itemHeight;
overage++;
}
if (overage > 0) {
buffer.eof = false;
buffer.remove(buffer.length - overage, buffer.length);
buffer.next -= overage;
viewport.adjustPadding();
}
},
shouldLoadTop() {
return !buffer.bof && (viewport.topDataPos() > viewport.topVisiblePos() - bufferPadding());
},
clipTop() {
// clip the invisible items off the top
let overage = 0;
let overageHeight = 0;
let itemHeight = 0;
let emptySpaceHeight = viewport.topVisiblePos() - viewport.topDataPos() - bufferPadding();
for (let i = 0; i < buffer.length; i++) {
itemHeight = buffer[i].element.outerHeight(true);
if(overageHeight + itemHeight > emptySpaceHeight) {
break;
}
topPadding.cache.add(buffer[i]);
overageHeight += itemHeight;
overage++;
}
if (overage > 0) {
// we need to adjust top padding element before items are removed from top
// to avoid strange behaviour of scroll bar during remove top items when we are at the very bottom
topPadding.height(topPadding.height() + overageHeight);
buffer.bof = false;
buffer.remove(0, overage);
buffer.first += overage;
}
},
adjustPadding() {
if (!buffer.length)
return;
// precise heights calculation, items that were in buffer once
let topPaddingHeight = topPadding.cache.reduce((summ, item) => summ + (item.index < buffer.first ? item.height : 0), 0);
let bottomPaddingHeight = bottomPadding.cache.reduce((summ, item) => summ + (item.index >= buffer.next ? item.height : 0), 0);
// average item height based on buffer data
let visibleItemsHeight = buffer.reduce((summ, item) => summ + item.element.outerHeight(true), 0);
let averageItemHeight = (visibleItemsHeight + topPaddingHeight + bottomPaddingHeight) / (buffer.maxIndex - buffer.minIndex + 1);
// average heights calculation, items that have never been reached
let adjustTopPadding = buffer.minIndexUser !== null && buffer.minIndex > buffer.minIndexUser;
let adjustBottomPadding = buffer.maxIndexUser !== null && buffer.maxIndex < buffer.maxIndexUser;
let topPaddingHeightAdd = adjustTopPadding ? (buffer.minIndex - buffer.minIndexUser) * averageItemHeight : 0;
let bottomPaddingHeightAdd = adjustBottomPadding ? (buffer.maxIndexUser - buffer.maxIndex) * averageItemHeight : 0;
// paddings combine adjustment
topPadding.height(topPaddingHeight + topPaddingHeightAdd);
bottomPadding.height(bottomPaddingHeight + bottomPaddingHeightAdd);
},
adjustScrollTopAfterMinIndexSet(topPaddingHeightOld) {
// additional scrollTop adjustment in case of datasource.minIndex external set
if (buffer.minIndexUser !== null && buffer.minIndex > buffer.minIndexUser) {
let diff = topPadding.height() - topPaddingHeightOld;
viewport.scrollTop(viewport.scrollTop() + diff);
}
},
adjustScrollTopAfterPrepend(updates) {
if(!updates.prepended.length)
return;
const height = buffer.effectiveHeight(updates.prepended);
const paddingHeight = topPadding.height() - height;
if (paddingHeight >= 0) {
topPadding.height(paddingHeight);
}
else {
topPadding.height(0);
viewport.scrollTop(viewport.scrollTop() - paddingHeight);
}
},
resetTopPadding() {
topPadding.height(0);
topPadding.cache.clear();
},
resetBottomPadding() {
bottomPadding.height(0);
bottomPadding.cache.clear();
}
});
return viewport;
}
function Adapter($attr, viewport, buffer, adjustBuffer) {
const viewportScope = viewport.scope() || $rootScope;
let disabled = false;
let self = this;
createValueInjector('adapter')(self);
let topVisibleInjector = createValueInjector('topVisible');
let topVisibleElementInjector = createValueInjector('topVisibleElement');
let topVisibleScopeInjector = createValueInjector('topVisibleScope');
let isLoadingInjector = createValueInjector('isLoading');
// Adapter API definition
Object.defineProperty(this, 'disabled', {
get: () => disabled,
set: (value) => (!(disabled = value)) ? adjustBuffer() : null
});
this.isLoading = false;
this.isBOF = () => buffer.bof;
this.isEOF = () => buffer.eof;
this.applyUpdates = (arg1, arg2) => {
if (angular.isFunction(arg1)) {
// arg1 is the updater function, arg2 is ignored
buffer.slice(0).forEach((wrapper) => {
// we need to do it on the buffer clone, because buffer content
// may change as we iterate through
applyUpdate(wrapper, arg1(wrapper.item, wrapper.scope, wrapper.element));
});
} else {
// arg1 is item index, arg2 is the newItems array
if (arg1 % 1 !== 0) {// checking if it is an integer
throw new Error('applyUpdates - ' + arg1 + ' is not a valid index');
}
const index = arg1 - buffer.first;
if ((index >= 0 && index < buffer.length)) {
applyUpdate(buffer[index], arg2);
}
}
adjustBuffer();
};
this.append = (newItems) => {
buffer.append(newItems);
adjustBuffer();
};
this.prepend = (newItems) => {
buffer.prepend(newItems);
adjustBuffer();
};
this.loading = (value) => {
isLoadingInjector(value);
};
this.calculateProperties = () => {
let item, itemHeight, itemTop, isNewRow, rowTop;
let topHeight = 0;
for (let i = 0; i < buffer.length; i++) {
item = buffer[i];
itemTop = item.element.offset().top;
isNewRow = rowTop !== itemTop;
rowTop = itemTop;
if (isNewRow) {
itemHeight = item.element.outerHeight(true);
}
if (isNewRow && (viewport.topDataPos() + topHeight + itemHeight <= viewport.topVisiblePos())) {
topHeight += itemHeight;
} else {
if (isNewRow) {
topVisibleInjector(item.item);
topVisibleElementInjector(item.element);
topVisibleScopeInjector(item.scope);
}
break;
}
}
};
// private function definitions
function createValueInjector(attribute) {
let expression = $attr[attribute];
let scope = viewportScope;
let assign;
if (expression) {
let match = expression.match(/^(\S+)(?:\s+on\s+(\w(?:\w|\d)*))?$/);
if (!match)
throw new Error('Expected injection expression in form of \'target\' or \'target on controller\' but got \'' + expression + '\'');
let target = match[1];
let controllerName = match[2];
if (controllerName) {
let candidate = viewport;
scope = undefined;
while (candidate.length) {
let controller = candidate.attr('ng-controller');
if (controller === controllerName) {
scope = candidate.scope();
break;
}
candidate = candidate.parent();
}
if (!scope)
throw new Error('Failed to locate target controller \'' + controllerName + '\' to inject \'' + target + '\'');
}
assign = $parse(target).assign;
}
return (value) => {
if (self !== value) // just to avoid injecting adapter reference in the adapter itself. Kludgy, I know.
self[attribute] = value;
if (assign)
assign(scope, value);
};
}
function applyUpdate(wrapper, newItems) {
if (!angular.isArray(newItems)) {
return;
}
let keepIt;
let pos = (buffer.indexOf(wrapper)) + 1;
newItems.reverse().forEach((newItem) => {
if (newItem === wrapper.item) {
keepIt = true;
pos--;
} else {
buffer.insert(pos, newItem);
}
});
if (!keepIt) {
wrapper.op = 'remove';
}
}
}
function link($scope, element, $attr, controllers, linker) {
const match = $attr.uiScroll.match(/^\s*(\w+)\s+in\s+([(\w|\$)\.]+)\s*$/);
if (!(match))
throw new Error('Expected uiScroll in form of \'_item_ in _datasource_\' but got \'' + $attr.uiScroll + '\'');
let datasource = null;
const itemName = match[1];
const datasourceName = match[2];
const bufferSize = Math.max(3, +$attr.bufferSize || 10);
const viewportController = controllers[0];
let startIndex = parseInt($attr.startIndex, 10);
startIndex = isNaN(startIndex) ? 1 : startIndex;
let ridActual = 0;// current data revision id
let pending = [];
let buffer = new Buffer(bufferSize);
let viewport = new Viewport(buffer, element, viewportController, $attr);
let adapter = new Adapter($attr, viewport, buffer, adjustBuffer);
if (viewportController)
viewportController.adapter = adapter;
let isDatasourceValid = () => angular.isObject(datasource) && angular.isFunction(datasource.get);
datasource = $parse(datasourceName)($scope); // try to get datasource on scope
if (!isDatasourceValid()) {
datasource = $injector.get(datasourceName); // try to inject datasource as service
if (!isDatasourceValid()) {
throw new Error(datasourceName + ' is not a valid datasource');
}
}
let indexStore = {};
function defineProperty(datasource, propName, propUserName) {
let descriptor = Object.getOwnPropertyDescriptor(datasource, propName);
if (!descriptor || (!descriptor.set && ! descriptor.get)) {
Object.defineProperty(datasource, propName, {
set: (value) => {
indexStore[propName] = value;
$timeout(() => {
buffer[propUserName] = value;
if(!pending.length) {
let topPaddingHeightOld = viewport.topDataPos();
viewport.adjustPadding();
if(propName === 'minIndex'){
viewport.adjustScrollTopAfterMinIndexSet(topPaddingHeightOld);
}
}
});
},
get: () => indexStore[propName]
});
}
}
defineProperty(datasource, 'minIndex', 'minIndexUser');
defineProperty(datasource, 'maxIndex', 'maxIndexUser');
const fetchNext = (datasource.get.length !== 2) ? (success) => datasource.get(buffer.next, bufferSize, success)
: (success) => {
datasource.get({
index: buffer.next,
append: buffer.length ? buffer[buffer.length - 1].item : void 0,
count: bufferSize
}, success);
};
const fetchPrevious = (datasource.get.length !== 2) ? (success) => datasource.get(buffer.first - bufferSize, bufferSize, success)
: (success) => {
datasource.get({
index: buffer.first - bufferSize,
prepend: buffer.length ? buffer[0].item : void 0,
count: bufferSize
}, success);
};
adapter.reload = reload;
/**
* Build padding elements
*
* Calling linker is the only way I found to get access to the tag name of the template
* to prevent the directive scope from pollution a new scope is created and destroyed
* right after the builder creation is completed
*/
linker((clone, scope) => {
viewport.createPaddingElements(clone[0]);
// we do not include the clone in the DOM. It means that the nested directives will not
// be able to reach the parent directives, but in this case it is intentional because we
// created the clone to access the template tag name
scope.$destroy();
clone.remove();
});
$scope.$on('$destroy', () => {
unbindEvents();
viewport.unbind('mousewheel', wheelHandler);
});
viewport.bind('mousewheel', wheelHandler);
$timeout(() => {
viewport.applyContainerStyle();
reload();
});
/* Private function definitions */
function isInvalid(rid) {
return (rid && rid !== ridActual) || $scope.$$destroyed;
}
function bindEvents() {
viewport.bind('resize', resizeAndScrollHandler);
viewport.bind('scroll', resizeAndScrollHandler);
}
function unbindEvents() {
viewport.unbind('resize', resizeAndScrollHandler);
viewport.unbind('scroll', resizeAndScrollHandler);
}
function reload() {
viewport.resetTopPadding();
viewport.resetBottomPadding();
if (arguments.length)
startIndex = arguments[0];
buffer.reset(startIndex);
adjustBuffer();
}
function isElementVisible(wrapper) {
return wrapper.element.height() && wrapper.element[0].offsetParent;
}
function visibilityWatcher(wrapper) {
if (isElementVisible(wrapper)) {
buffer.forEach((item) => {
if (angular.isFunction(item.unregisterVisibilityWatcher)) {
item.unregisterVisibilityWatcher();
delete item.unregisterVisibilityWatcher;
}
});
adjustBuffer();
}
}
function insertWrapperContent(wrapper, insertAfter) {
createElement(wrapper, insertAfter, viewport.insertElement);
if (!isElementVisible(wrapper)) {
wrapper.unregisterVisibilityWatcher = wrapper.scope.$watch(() => visibilityWatcher(wrapper));
}
wrapper.element.addClass('ng-hide'); // hide inserted elements before data binding
}
function createElement(wrapper, insertAfter, insertElement) {
let promises;
let sibling = (insertAfter > 0) ? buffer[insertAfter - 1].element : undefined;
linker((clone, scope) => {
promises = insertElement(clone, sibling);
wrapper.element = clone;
wrapper.scope = scope;
scope[itemName] = wrapper.item;
});
if (adapter.transform)
adapter.transform(wrapper.scope, wrapper.element);
return promises;
}
function updateDOM() {
let promises = [];
const toBePrepended = [];
const toBeRemoved = [];
const inserted = [];
buffer.forEach((wrapper, i) => {
switch (wrapper.op) {
case 'prepend':
toBePrepended.unshift(wrapper);
break;
case 'append':
insertWrapperContent(wrapper, i);
wrapper.op = 'none';
inserted.push(wrapper);
break;
case 'insert':
promises = promises.concat(createElement(wrapper, i, viewport.insertElementAnimated));
wrapper.op = 'none';
inserted.push(wrapper);
break;
case 'remove':
toBeRemoved.push(wrapper);
}
});
toBeRemoved.forEach((wrapper) => promises = promises.concat(buffer.remove(wrapper)));
if (toBePrepended.length)
toBePrepended.forEach((wrapper) => {
insertWrapperContent(wrapper);
wrapper.op = 'none';
});
buffer.forEach((item, i) => item.scope.$index = buffer.first + i);
return {
prepended: toBePrepended,
removed: toBeRemoved,
inserted: inserted,
animated: promises
};
}
function updatePaddings(rid, updates) {
// schedule another adjustBuffer after animation completion
if (updates.animated.length) {
$q.all(updates.animated).then(() => {
viewport.adjustPadding();
adjustBuffer(rid);
});
} else {
viewport.adjustPadding();
}
}
function enqueueFetch(rid, updates) {
if (viewport.shouldLoadBottom()) {
if(!updates || buffer.effectiveHeight(updates.inserted) > 0) {
// this means that at least one item appended in the last batch has height > 0
if (pending.push(true) === 1) {
fetch(rid);
adapter.loading(true);
}
}
} else if (viewport.shouldLoadTop()) {
if ((!updates || buffer.effectiveHeight(updates.prepended) > 0) || pending[0]) {
// this means that at least one item appended in the last batch has height > 0
// pending[0] = true means that previous fetch was appending. We need to force at least one prepend
// BTW there will always be at least 1 element in the pending array because bottom is fetched first
if (pending.push(false) === 1) {
fetch(rid);
adapter.loading(true);
}
}
}
}
function adjustBuffer(rid) {
if(!rid) { // dismiss pending requests
pending = [];
rid = ++ridActual;
}
let updates = updateDOM();
// We need the item bindings to be processed before we can do adjustment
$timeout(() => {
// show elements after data binging has been done
updates.inserted.forEach(w => w.element.removeClass('ng-hide'));
updates.prepended.forEach(w => w.element.removeClass('ng-hide'));
if (isInvalid(rid)) {
return;
}
updatePaddings(rid, updates);
enqueueFetch(rid);
if (!pending.length) {
adapter.calculateProperties();
}
});
}
function adjustBufferAfterFetch(rid) {
let updates = updateDOM();
// We need the item bindings to be processed before we can do adjustment
$timeout(() => {
// show elements after data binging has been done
updates.inserted.forEach(w => w.element.removeClass('ng-hide'));
updates.prepended.forEach(w => w.element.removeClass('ng-hide'));
viewport.adjustScrollTopAfterPrepend(updates);
if (isInvalid(rid)) {
return;
}
updatePaddings(rid, updates);
enqueueFetch(rid, updates);
pending.shift();
if (pending.length)
fetch(rid);
else {
adapter.loading(false);
bindEvents();
adapter.calculateProperties();
}
});
}
function fetch(rid) {
if (pending[0]) {// scrolling down
if (buffer.length && !viewport.shouldLoadBottom()) {
adjustBufferAfterFetch(rid);
} else {
fetchNext((result) => {
if (isInvalid(rid)) {
return;
}
if (result.length < bufferSize) {
buffer.eof = true;
}
if (result.length > 0) {
viewport.clipTop();
buffer.append(result);
}
adjustBufferAfterFetch(rid);
});
}
} else { // scrolling up
if (buffer.length && !viewport.shouldLoadTop()) {
adjustBufferAfterFetch(rid);
} else {
fetchPrevious((result) => {
if (isInvalid(rid)) {
return;
}
if (result.length < bufferSize) {
buffer.bof = true;
// log 'bof is reached'
}
if (result.length > 0) {
if (buffer.length) {
viewport.clipBottom();
}
buffer.prepend(result);
}
adjustBufferAfterFetch(rid);
});
}
}
}
function resizeAndScrollHandler() {
if (!$rootScope.$$phase && !adapter.isLoading && !adapter.disabled) {
enqueueFetch(ridActual);
if (pending.length) {
unbindEvents();
} else {
adapter.calculateProperties();
$scope.$apply();
}
}
}
function wheelHandler(event) {
if(!adapter.disabled) {
let scrollTop = viewport[0].scrollTop;
let yMax = viewport[0].scrollHeight - viewport[0].clientHeight;
if ((scrollTop === 0 && !buffer.bof) || (scrollTop === yMax && !buffer.eof)) {
event.preventDefault();
}
}
}
}
}
]);