-
-
Notifications
You must be signed in to change notification settings - Fork 19
Expand file tree
/
Copy pathindex.android.ts
More file actions
1194 lines (1098 loc) · 47.4 KB
/
Copy pathindex.android.ts
File metadata and controls
1194 lines (1098 loc) · 47.4 KB
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
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* eslint-disable no-redeclare */
import {
ChangeType,
ChangedData,
ContentView,
CoreTypes,
Property,
ProxyViewContainer,
Trace,
Utils,
View,
ViewBase,
booleanConverter,
paddingBottomProperty,
paddingLeftProperty,
paddingRightProperty,
paddingTopProperty,
profile
} from '@nativescript/core';
import { CollectionViewItemEventData, Orientation, reorderLongPressEnabledProperty, reorderingEnabledProperty, reverseLayoutProperty, scrollBarIndicatorVisibleProperty, sharedPoolProperty } from '.';
import { CLog, CLogTypes, CollectionViewBase, ListViewViewTypes, isScrollEnabledProperty, orientationProperty } from './index-common';
import { SharedCollectionViewPool, getSharedCollectionViewPool } from './shared-pool';
export * from './index-common';
declare module '@nativescript/core/ui/core/view' {
interface ViewCommon {
layoutChangeListenerIsSet: boolean;
layoutChangeListener: android.view.View.OnLayoutChangeListener;
//@ts-ignore
_raiseLayoutChangedEvent();
handleGestureTouch(event: android.view.MotionEvent);
}
}
@NativeClass
class SimpleCallback extends androidx.recyclerview.widget.ItemTouchHelper.SimpleCallback {
owner: WeakRef<CollectionView>;
constructor(param1: number, param2: number) {
super(param1, param2);
return global.__native(this);
}
onMove(
recyclerview: androidx.recyclerview.widget.RecyclerView,
viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder,
target: androidx.recyclerview.widget.RecyclerView.ViewHolder
): boolean {
const startPosition = viewHolder.getAdapterPosition();
const endPosition = target.getAdapterPosition();
if (this.startPosition === -1) {
this.startPosition = startPosition;
}
this.endPosition = endPosition;
const owner = this.owner && this.owner.get();
if (owner) {
owner._reorderItemInSource(startPosition, endPosition);
return true;
}
return false;
}
startPosition = -1;
endPosition = -1;
onSelectedChanged(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, state: number) {
if (viewHolder) {
if (this.startPosition === -1) {
this.startPosition = viewHolder.getAdapterPosition();
}
}
if (!viewHolder) {
// this is where we identify the end of the drag and call the end event
const owner = this.owner && this.owner.get();
if (this.endPosition === -1) {
this.endPosition = this.startPosition;
}
if (owner) {
const item = owner.getItemAtIndex(this.startPosition);
owner._callItemReorderedEvent(this.startPosition, this.endPosition, item);
}
this.startPosition = -1;
this.endPosition = -1;
owner.isDragging = false;
}
}
onSwiped(viewHolder: androidx.recyclerview.widget.RecyclerView.ViewHolder, direction: number) {}
isItemViewSwipeEnabled() {
// disabled for now
return false;
}
isLongPressDragEnabled() {
// we use our custom longpress gesture handler
return false;
}
}
@NativeClass
class LongPressGestureListenerImpl extends android.view.GestureDetector.SimpleOnGestureListener {
constructor(private _owner: WeakRef<CollectionView>) {
super();
return global.__native(this);
}
public onLongPress(motionEvent: android.view.MotionEvent): void {
const owner = this._owner && this._owner.get();
if (owner) {
owner.onReorderLongPress(motionEvent);
}
}
}
let LayoutParams: typeof android.view.ViewGroup.LayoutParams;
const extraLayoutSpaceProperty = new Property<CollectionViewBase, number>({
name: 'extraLayoutSpace'
});
const itemViewCacheSizeProperty = new Property<CollectionViewBase, number>({
name: 'itemViewCacheSize'
});
const nestedScrollingEnabledProperty = new Property<CollectionViewBase, boolean>({
name: 'nestedScrollingEnabled',
defaultValue: true,
valueConverter: booleanConverter
});
export class CollectionView extends CollectionViewBase {
public static DEFAULT_TEMPLATE_VIEW_TYPE = 0;
public static CUSTOM_TEMPLATE_ITEM_TYPE = 1;
public nativeViewProtected: CollectionViewRecyclerView & {
scrollListener: com.nativescript.collectionview.OnScrollListener;
layoutManager: androidx.recyclerview.widget.RecyclerView.LayoutManager;
owner?: WeakRef<CollectionView>;
};
private templateTypeNumberString = new Map<string, number>();
private templateStringTypeNumber = new Map<number, string>();
private _currentNativeItemType = 0;
private currentSpanCount = 1;
private _scrollOrLoadMoreChangeCount = 0;
private _nScrollListener: com.nativescript.collectionview.OnScrollListener.Listener;
scrolling = false;
needsScrollStartEvent = false;
private _hlayoutParams: android.view.ViewGroup.LayoutParams;
private _vlayoutParams: android.view.ViewGroup.LayoutParams;
private _lastLayoutKey: string;
private _listViewAdapter: com.nativescript.collectionview.Adapter;
// reordering
private _simpleItemTouchCallback: SimpleCallback;
private _itemTouchHelper: androidx.recyclerview.widget.ItemTouchHelper;
public animateItemUpdate = false;
public nestedScrollingEnabled: boolean;
public itemViewCacheSize: number;
public extraLayoutSpace: number;
private _sharedPool: SharedCollectionViewPool;
get templateTarget(): SharedCollectionViewPool | this {
if (this.sharedPool) {
return this._sharedPool;
}
return this;
}
// for simplicity we always store view holders in a shared pool, even if it's only used by this collectionview
private get viewHolders(): Set<CollectionViewCellHolder> {
return this._sharedPool._viewHolders;
}
private set viewHolders(value: Set<CollectionViewCellHolder>) {
this._sharedPool._viewHolders = value;
}
@profile
public createNativeView() {
// storing the class in a property for reuse in the future cause a materializing which is pretty slow!
if (!CollectionViewRecyclerView) {
CollectionViewRecyclerView = com.nativescript.collectionview.RecyclerView as any;
}
const recyclerView = (CollectionViewRecyclerView as any).createRecyclerView(this._context);
// const expMgr = new RecyclerViewExpandableItemManager(null);
// adapter.setDisplayHeadersAtStartUp(true).setStickyHeaders(true); //Make headers sticky
// Endless scroll with 1 item threshold
// .setLoadingMoreAtStartUp(true)
// .setEndlessScrollListener(this, new ProgressItem())
// .setEndlessScrollThreshold(1); //Default=1
// const fastScroller = new com.l4digital.fastscroll.FastScroller(this._context);
// fastScroller.setSectionIndexer(adapter);
// fastScroller.attachRecyclerView(recyclerView);
return recyclerView;
}
@profile
public initNativeView() {
this.setOnLayoutChangeListener();
super.initNativeView();
const nativeView = this.nativeViewProtected;
this.attachSharedPool();
// nativeView.owner = new WeakRef(this);
// nativeView.sizeChangedListener = new com.nativescript.collectionview.SizeChangedListener({
// onSizeChanged: (w, h, oldW, oldH) => this.onSizeChanged(w, h),
// });
// const orientation = this._getLayoutManagarOrientation();
// initGridLayoutManager();
let layoutManager: androidx.recyclerview.widget.RecyclerView.LayoutManager;
if (CollectionViewBase.layoutStyles[this.layoutStyle]) {
layoutManager = CollectionViewBase.layoutStyles[this.layoutStyle].createLayout(this);
} else {
layoutManager = new com.nativescript.collectionview.PreCachingGridLayoutManager(this._context, 1);
// layoutManager = new PreCachingGridLayoutManager(this._context, 1);
// (layoutManager as any).owner = new WeakRef(this);
}
// this.spanSize
nativeView.setLayoutManager(layoutManager);
nativeView.layoutManager = layoutManager;
nativeView.sizeChangedListener = new com.nativescript.collectionview.SizeChangedListener({
onSizeChanged() {},
onMeasure: () => this.updateInnerSize()
});
this.spanSize = this._getSpanSize;
const animator = new com.h6ah4i.android.widget.advrecyclerview.animator.RefactoredDefaultItemAnimator();
// Change animations are enabled by default since support-v7-recyclerview v22.
// Need to disable them when using animation indicator.
animator.setSupportsChangeAnimations(false);
nativeView.setItemAnimator(animator);
this.refresh();
}
public disposeNativeView() {
// clear the cache
// this.eachChildView((view) => {
// view.parent._removeView(view);
// return true;
// });
// this._realizedItems.clear();
const nativeView = this.nativeViewProtected;
this._sharedPool?.detachFromCollectionView(this);
if (nativeView.scrollListener) {
this.nativeView.removeOnScrollListener(nativeView.scrollListener);
nativeView.scrollListener = null;
this._nScrollListener = null;
}
nativeView.sizeChangedListener = null;
nativeView.layoutManager = null;
this._listViewAdapter = null;
this._itemTouchHelper = null;
this._simpleItemTouchCallback = null;
this.disposeViewHolderViews();
this._hlayoutParams = null;
this._vlayoutParams = null;
this.clearTemplateTypes();
super.disposeNativeView();
}
onLoaded() {
super.onLoaded();
this.attachScrollListener();
this.refresh();
}
_getSpanSize: (item, index) => number;
public getViewForItemAtIndex(index: number): View {
return this.enumerateViewHolders<View>((v) => (v.getAdapterPosition() === index ? v.view : undefined));
}
//@ts-ignore
set spanSize(inter: (item, index) => number) {
if (!(typeof inter === 'function')) {
return;
}
this._getSpanSize = inter;
const layoutManager = this.layoutManager;
if (layoutManager && layoutManager['setSpanSizeLookup']) {
if (inter) {
layoutManager['setSpanSizeLookup'](
new com.nativescript.collectionview.SpanSizeLookup(
new com.nativescript.collectionview.SpanSizeLookup.Interface({
getSpanSize: (position) => {
const dataItem = this.getItemAtIndex(position);
return Math.min(inter(dataItem, position), this.currentSpanCount);
}
})
)
);
} else {
layoutManager['setSpanSizeLookup'](null);
}
}
}
get spanSize() {
return this._getSpanSize;
}
private attachScrollListener() {
if (this._scrollOrLoadMoreChangeCount > 0 && this.isLoaded) {
const nativeView = this.nativeViewProtected;
if (!nativeView.scrollListener) {
this._nScrollListener = new com.nativescript.collectionview.OnScrollListener.Listener({
onScrollStateChanged: this.onScrollStateChanged.bind(this),
onScrolled: this.onScrolled.bind(this)
});
const scrollListener = new com.nativescript.collectionview.OnScrollListener(this._nScrollListener);
nativeView.addOnScrollListener(scrollListener);
nativeView.scrollListener = scrollListener;
}
}
}
private detachScrollListener() {
if (this._scrollOrLoadMoreChangeCount === 0 && this.isLoaded) {
const nativeView = this.nativeViewProtected;
if (nativeView.scrollListener) {
this.nativeView.removeOnScrollListener(nativeView.scrollListener);
nativeView.scrollListener = null;
this._nScrollListener = null;
}
}
}
private computeScrollEventData(view: androidx.recyclerview.widget.RecyclerView, eventName: string, dx?: number, dy?: number) {
const horizontal = this.isHorizontal();
const offset = horizontal ? view.computeHorizontalScrollOffset() : view.computeVerticalScrollOffset();
const range = horizontal ? view.computeHorizontalScrollRange() : view.computeVerticalScrollRange();
const extent = horizontal ? view.computeHorizontalScrollExtent() : view.computeVerticalScrollExtent();
return {
object: this,
eventName,
scrollOffset: offset / Utils.layout.getDisplayDensity(),
scrollOffsetPercentage: offset / (range - extent),
dx,
dy
};
}
public onScrolled(view: androidx.recyclerview.widget.RecyclerView, dx: number, dy: number) {
if (!this || !this.scrolling) {
return;
}
if (this.needsScrollStartEvent) {
this.needsScrollStartEvent = false;
if (this.hasListeners(CollectionViewBase.scrollStartEvent)) {
this.notify(this.computeScrollEventData(view, CollectionViewBase.scrollStartEvent, dx, dy));
}
}
if (this.hasListeners(CollectionViewBase.scrollEvent)) {
this.notify(this.computeScrollEventData(view, CollectionViewBase.scrollEvent, dx, dy));
}
if (this.hasListeners(CollectionViewBase.loadMoreItemsEvent) && this.items) {
const layoutManager = view.getLayoutManager();
if (layoutManager['findLastCompletelyVisibleItemPosition']) {
const lastVisibleItemPos = layoutManager['findLastCompletelyVisibleItemPosition']();
const loadMoreItemIndex = this.items.length - this.loadMoreThreshold;
if (lastVisibleItemPos === loadMoreItemIndex) {
this.notify({ eventName: CollectionViewBase.loadMoreItemsEvent });
}
} else if (layoutManager['findLastCompletelyVisibleItemPositions'] && layoutManager['getSpanCount']) {
let positions = Array.create('int', layoutManager['getSpanCount']());
positions = layoutManager['findLastCompletelyVisibleItemPositions'](positions);
let lastVisibleItemPos = 0;
for (let i = 0; i < positions.length; i++) {
if (positions[i] > lastVisibleItemPos) {
lastVisibleItemPos = positions[i];
}
}
const loadMoreItemIndex = this.items.length - this.loadMoreThreshold;
if (lastVisibleItemPos >= loadMoreItemIndex) {
this.notify({ eventName: CollectionViewBase.loadMoreItemsEvent });
}
}
}
}
public onScrollStateChanged(view: androidx.recyclerview.widget.RecyclerView, newState: number) {
if (this.scrolling && newState === 0) {
// SCROLL_STATE_IDLE
this.scrolling = false;
if (this.hasListeners(CollectionViewBase.scrollEndEvent)) {
this.notify(this.computeScrollEventData(view, CollectionViewBase.scrollEndEvent));
}
} else if (!this.scrolling && newState === 1) {
//SCROLL_STATE_DRAGGING
this.needsScrollStartEvent = true;
this.scrolling = true;
}
}
public addEventListener(arg: string, callback: any, thisArg?: any) {
super.addEventListener(arg, callback, thisArg);
if (arg === CollectionViewBase.scrollEvent || arg === CollectionViewBase.scrollStartEvent || arg === CollectionViewBase.scrollEndEvent || arg === CollectionViewBase.loadMoreItemsEvent) {
this._scrollOrLoadMoreChangeCount++;
this.attachScrollListener();
}
}
public removeEventListener(arg: string, callback: any, thisArg?: any) {
super.removeEventListener(arg, callback, thisArg);
if (arg === CollectionViewBase.scrollEvent || arg === CollectionViewBase.scrollStartEvent || arg === CollectionViewBase.scrollEndEvent || arg === CollectionViewBase.loadMoreItemsEvent) {
this._scrollOrLoadMoreChangeCount--;
this.detachScrollListener();
}
}
//@ts-ignore
get android(): androidx.recyclerview.widget.RecyclerView {
return this.nativeView;
}
get layoutManager() {
return this.nativeViewProtected && this.nativeViewProtected.layoutManager;
}
_getViewLayoutParams() {
if (this.isHorizontal()) {
if (!this._hlayoutParams) {
LayoutParams = LayoutParams || android.view.ViewGroup.LayoutParams;
this._hlayoutParams = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
}
return this._hlayoutParams;
} else {
if (!this._vlayoutParams) {
LayoutParams = LayoutParams || android.view.ViewGroup.LayoutParams;
this._vlayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
}
return this._vlayoutParams;
}
}
defaultPoolSize = 10;
desiredPoolSize: Map<string, number> = new Map();
private setNativePoolSize(key: string, nativeIndex: number) {
if (this.desiredPoolSize.has(key)) {
this.nativeViewProtected.getRecycledViewPool().setMaxRecycledViews(nativeIndex, this.desiredPoolSize.get(key));
} else {
if (this.defaultPoolSize >= 0) {
this.nativeViewProtected.getRecycledViewPool().setMaxRecycledViews(nativeIndex, this.defaultPoolSize);
}
}
}
private setPoolSizes() {
if (!this.nativeViewProtected || !this.templateTypeNumberString) {
return;
}
this.desiredPoolSize.forEach((v, k) => {
if (this.templateTypeNumberString.has(k)) {
this.nativeViewProtected.getRecycledViewPool().setMaxRecycledViews(this.templateTypeNumberString.get(k), v);
}
});
}
public setPoolSize(key: string, size: number) {
this.desiredPoolSize.set(key, size);
this.setPoolSizes();
}
getTemplateFromSelector(templateKey) {
if (this.templateTarget !== this) {
return this.templateTarget.getTemplateFromSelector(templateKey);
}
return super.getTemplateFromSelector(templateKey);
}
[paddingTopProperty.getDefault](): CoreTypes.LengthType {
return { value: this._defaultPaddingTop, unit: 'px' };
}
[paddingTopProperty.setNative](value: CoreTypes.LengthType) {
this._setPadding({ top: this.effectivePaddingTop });
}
[paddingRightProperty.getDefault](): CoreTypes.LengthType {
return { value: this._defaultPaddingRight, unit: 'px' };
}
[paddingRightProperty.setNative](value: CoreTypes.LengthType) {
this._setPadding({ right: this.effectivePaddingRight });
}
[paddingBottomProperty.getDefault](): CoreTypes.LengthType {
return { value: this._defaultPaddingBottom, unit: 'px' };
}
[paddingBottomProperty.setNative](value: CoreTypes.LengthType) {
this._setPadding({ bottom: this.effectivePaddingBottom });
}
[paddingLeftProperty.getDefault](): CoreTypes.LengthType {
return { value: this._defaultPaddingLeft, unit: 'px' };
}
[paddingLeftProperty.setNative](value: CoreTypes.LengthType) {
this._setPadding({ left: this.effectivePaddingLeft });
}
public [orientationProperty.getDefault](): Orientation {
return 'vertical';
}
[orientationProperty.setNative](value: Orientation) {
const layoutManager = this.layoutManager;
if (!layoutManager || !layoutManager['setOrientation']) {
return;
}
if (this.isHorizontal()) {
layoutManager['setOrientation'](0);
} else {
layoutManager['setOrientation'](1);
}
this.updateScrollBarVisibility(this.scrollBarIndicatorVisible);
}
[isScrollEnabledProperty.setNative](value: boolean) {
const layoutManager = this.layoutManager;
if (layoutManager && (layoutManager as any).setScrollEnabled) {
(layoutManager as any).setScrollEnabled(value);
}
}
[reverseLayoutProperty.setNative](value: boolean) {
const layoutManager = this.layoutManager;
if (layoutManager && (layoutManager as any).setReverseLayout) {
(layoutManager as any).setReverseLayout(value);
// layoutManager['setStackFromEnd'](value);
}
}
[nestedScrollingEnabledProperty.setNative](value: boolean) {
this.nativeViewProtected.setNestedScrollingEnabled(value);
}
[extraLayoutSpaceProperty.setNative](value: number) {
const layoutManager = this.layoutManager;
if (layoutManager && layoutManager['setExtraLayoutSpace']) {
layoutManager['setExtraLayoutSpace'](value);
}
}
[itemViewCacheSizeProperty.setNative](value: number) {
this.nativeViewProtected.setItemViewCacheSize(value);
}
[scrollBarIndicatorVisibleProperty.getDefault](): boolean {
return true;
}
[scrollBarIndicatorVisibleProperty.setNative](value: boolean) {
this.updateScrollBarVisibility(value);
}
protected updateScrollBarVisibility(value) {
if (!this.nativeViewProtected) {
return;
}
if (this.orientation === 'horizontal') {
this.nativeViewProtected.setHorizontalScrollBarEnabled(value);
} else {
this.nativeViewProtected.setVerticalScrollBarEnabled(value);
}
}
private enumerateViewHolders<T = any>(cb: (v: CollectionViewCellHolder) => T) {
let result: T, v: CollectionViewCellHolder;
for (let it = this.viewHolders.values(), cellItemView: CollectionViewCellHolder = null; (cellItemView = it.next().value); ) {
result = cb(cellItemView);
if (result) {
return result;
}
}
return result;
}
public startDragging(index: number) {
if (this.reorderEnabled && this._itemTouchHelper) {
// let viewHolder: CollectionViewCellHolder;
const viewHolder = this.enumerateViewHolders<CollectionViewCellHolder>((v) => (v.getAdapterPosition() === index ? v : undefined));
if (viewHolder) {
this.startViewHolderDragging(index, viewHolder);
}
}
}
isDragging = false;
startViewHolderDragging(index, viewHolder: CollectionViewCellHolder) {
// isDragging is to prevent longPress from triggering and starting a new drag
// when triggered manually
if (!this.isDragging && this.shouldMoveItemAtIndex(index)) {
this.isDragging = true;
this._itemTouchHelper.startDrag(viewHolder);
}
}
onReorderLongPress(motionEvent: android.view.MotionEvent) {
const collectionView = this.nativeViewProtected;
if (!collectionView) {
return;
}
const view = collectionView.findChildViewUnder(motionEvent.getX(), motionEvent.getY());
const viewHolder = view != null ? collectionView.getChildViewHolder(view) : null;
if (viewHolder) {
this.startViewHolderDragging(viewHolder.getAdapterPosition(), viewHolder as CollectionViewCellHolder);
}
}
_reorderItemInSource(oldPosition: number, newPosition: number) {
const adapter = this._listViewAdapter;
// 3. Tell adapter to render the model update.
adapter.notifyItemMoved(oldPosition, newPosition);
// on android _reorderItemInSource is call on every "move" and needs to update the adapter/items
// we will call events only at then end
super._reorderItemInSource(oldPosition, newPosition, false);
}
_longPressGesture: androidx.core.view.GestureDetectorCompat;
_itemTouchListerner: androidx.recyclerview.widget.RecyclerView.OnItemTouchListener;
public [reorderLongPressEnabledProperty.setNative](value: boolean) {
if (value) {
if (!this._longPressGesture) {
this._longPressGesture = new androidx.core.view.GestureDetectorCompat(this._context, new LongPressGestureListenerImpl(new WeakRef(this)));
this._itemTouchListerner = new androidx.recyclerview.widget.RecyclerView.OnItemTouchListener({
onInterceptTouchEvent: (view: android.view.View, event: android.view.MotionEvent) => {
if (this.reorderEnabled && this._longPressGesture) {
this._longPressGesture.onTouchEvent(event);
}
return false;
},
onTouchEvent: (param0: androidx.recyclerview.widget.RecyclerView, param1: globalAndroid.view.MotionEvent) => {},
onRequestDisallowInterceptTouchEvent: (disallowIntercept: boolean) => {}
});
}
this.nativeViewProtected.addOnItemTouchListener(this._itemTouchListerner);
} else {
if (this._itemTouchListerner) {
this.nativeViewProtected.removeOnItemTouchListener(this._itemTouchListerner);
}
}
}
public [reorderingEnabledProperty.setNative](value: boolean) {
if (value) {
if (!this._simpleItemTouchCallback) {
const ItemTouchHelper = androidx.recyclerview.widget.ItemTouchHelper;
this._simpleItemTouchCallback = new SimpleCallback(ItemTouchHelper.UP | ItemTouchHelper.DOWN | ItemTouchHelper.START | ItemTouchHelper.END, 0);
this._simpleItemTouchCallback.owner = new WeakRef(this);
this._itemTouchHelper = new androidx.recyclerview.widget.ItemTouchHelper(this._simpleItemTouchCallback);
this._itemTouchHelper.attachToRecyclerView(this.nativeViewProtected);
}
}
}
onItemViewLoaderChanged() {
if (this.itemViewLoader) {
this.refresh();
}
}
onItemTemplateSelectorChanged(oldValue, newValue) {
super.onItemTemplateSelectorChanged(oldValue, newValue);
this.clearTemplateTypes();
this.refresh();
}
onItemTemplateChanged(oldValue, newValue) {
super.onItemTemplateChanged(oldValue, newValue); // TODO: update current template with the new one
this.refresh();
}
onItemTemplatesChanged(oldValue, newValue) {
super.onItemTemplatesChanged(oldValue, newValue); // TODO: update current template with the new one
this.refresh();
}
private setOnLayoutChangeListener() {
if (this.nativeViewProtected) {
const owner = this;
this.layoutChangeListenerIsSet = true;
this.layoutChangeListener =
this.layoutChangeListener ||
new android.view.View.OnLayoutChangeListener({
onLayoutChange(v: android.view.View, left: number, top: number, right: number, bottom: number, oldLeft: number, oldTop: number, oldRight: number, oldBottom: number): void {
if (left !== oldLeft || top !== oldTop || right !== oldRight || bottom !== oldBottom) {
owner.onLayout(left, top, right, bottom);
if (owner.hasListeners(View.layoutChangedEvent)) {
owner._raiseLayoutChangedEvent();
}
}
}
});
this.nativeViewProtected.addOnLayoutChangeListener(this.layoutChangeListener);
}
}
_updateSpanCount() {
const layoutManager = this.layoutManager;
if (layoutManager && layoutManager['setSpanCount']) {
const newValue = (this.currentSpanCount = this.computeSpanCount());
if (newValue !== layoutManager['getSpanCount']()) {
layoutManager['setSpanCount'](newValue);
layoutManager.requestLayout();
}
}
}
updateInnerSize() {
super.updateInnerSize();
this._updateSpanCount();
}
_onColWidthPropertyChanged(oldValue: CoreTypes.PercentLengthType, newValue: CoreTypes.PercentLengthType) {
this._updateSpanCount();
super._onColWidthPropertyChanged(oldValue, newValue);
}
_onRowHeightPropertyChanged(oldValue: CoreTypes.PercentLengthType, newValue: CoreTypes.PercentLengthType) {
this._updateSpanCount();
super._onRowHeightPropertyChanged(oldValue, newValue);
}
public onLayout(left: number, top: number, right: number, bottom: number) {
this._layedOut = true;
super.onLayout(left, top, right, bottom);
const p = CollectionViewBase.plugins[this.layoutStyle];
if (p && p.onLayout) {
p.onLayout(this, left, top, right, bottom);
}
this.plugins.forEach((k) => {
const p = CollectionViewBase.plugins[k];
p.onLayout && p.onLayout(this, left, top, right, bottom);
});
// there is no need to call refresh if it was triggered before with same size.
// this refresh is just to handle size change
const layoutKey = this._innerWidth + '_' + this._innerHeight;
if (this._isDataDirty || (this._lastLayoutKey && this._lastLayoutKey !== layoutKey)) {
setTimeout(() => this.refresh(), 0);
}
this._lastLayoutKey = layoutKey;
}
public onSourceCollectionChanged(event: ChangedData<any>) {
if (!this._listViewAdapter || this._dataUpdatesSuspended) {
return;
}
if (Trace.isEnabled()) {
CLog(CLogTypes.log, 'onItemsChanged', event.action, event.index, event.addedCount, event.removed, event.removed && event.removed.length);
}
switch (event.action) {
case ChangeType.Delete: {
this._listViewAdapter.notifyItemRangeRemoved(event.index, event.removed.length);
return;
}
case ChangeType.Add: {
if (event.addedCount > 0) {
this._listViewAdapter.notifyItemRangeInserted(event.index, event.addedCount);
}
// Reload the items to avoid duplicate Load on Demand indicators:
return;
}
case ChangeType.Update: {
if (event.addedCount > 0) {
this._listViewAdapter.notifyItemRangeChanged(event.index, event.addedCount);
}
return;
}
case ChangeType.Splice: {
const added = event.addedCount;
const removed = (event.removed && event.removed.length) || 0;
if (added > 0 && added === removed) {
// notifyItemRangeChanged wont create a fade effect
if (!this.animateItemUpdate) {
this._listViewAdapter.notifyItemRangeChanged(event.index, added);
} else {
this._listViewAdapter.notifyItemRangeRemoved(event.index, added);
this._listViewAdapter.notifyItemRangeInserted(event.index, added);
}
} else {
if (!this.animateItemUpdate) {
if (added > removed) {
if (removed > 0) {
this._listViewAdapter.notifyItemRangeChanged(event.index, removed);
}
this._listViewAdapter.notifyItemRangeInserted(event.index + removed, added - removed);
} else {
if (added > 0) {
this._listViewAdapter.notifyItemRangeChanged(event.index, added);
}
this._listViewAdapter.notifyItemRangeRemoved(event.index + added, removed - added);
}
} else {
if (event.removed && event.removed.length > 0) {
this._listViewAdapter.notifyItemRangeRemoved(event.index, event.removed.length);
}
if (event.addedCount > 0) {
this._listViewAdapter.notifyItemRangeInserted(event.index, event.addedCount);
}
}
}
return;
}
}
this._listViewAdapter.notifyDataSetChanged();
}
eachChild(callback: (child: ViewBase) => boolean) {
// used for css updates (like theme change)
this.enumerateViewHolders((v) => {
const view = v.view;
if (view) {
if (view.parent instanceof CollectionView) {
callback(view);
} else {
// in some cases (like item is unloaded from another place (like angular) view.parent becomes undefined)
if (view.parent) {
callback(view.parent);
}
}
}
});
}
refreshVisibleItems() {
const view = this.nativeViewProtected;
if (!view) {
return;
}
const ids = Array.from(this.viewHolders)
.map((s) => s['position'])
.filter((s) => s !== null)
.sort((a, b) => a - b);
this._listViewAdapter.notifyItemRangeChanged(ids[0], ids[ids.length - 1] - ids[0] + 1);
}
public isItemAtIndexVisible(index: number): boolean {
const view = this.nativeViewProtected;
if (!view) {
return false;
}
const layoutManager = this.layoutManager as androidx.recyclerview.widget.LinearLayoutManager;
if (layoutManager['findFirstVisibleItemPosition']) {
const first = layoutManager.findFirstVisibleItemPosition();
const last = layoutManager.findLastVisibleItemPosition();
return index >= first && index <= last;
}
return false;
}
_layedOut = false;
@profile
public refresh() {
if (!this.nativeViewProtected) {
return;
}
const view = this.nativeViewProtected;
if (!this.isLoaded) {
this._isDataDirty = true;
return;
}
this._isDataDirty = false;
this._lastLayoutKey = this._innerWidth + '_' + this._innerHeight;
let adapter = this._listViewAdapter;
if (!adapter) {
adapter = this._listViewAdapter = this.createComposedAdapter(this.nativeViewProtected);
adapter.setHasStableIds(!!this._itemIdGenerator);
view.setAdapter(adapter);
} else if (!view.getAdapter()) {
view.setAdapter(adapter);
}
this._updateSpanCount();
adapter.notifyDataSetChanged();
this.notify({ eventName: CollectionViewBase.dataPopulatedEvent });
}
//@ts-ignore
get scrollOffset() {
const view = this.nativeViewProtected;
if (!view) {
return 0;
}
return (this.isHorizontal() ? view.computeHorizontalScrollOffset() : view.computeVerticalScrollOffset()) / Utils.layout.getDisplayDensity();
}
get verticalOffsetX() {
const view = this.nativeViewProtected;
if (!view) {
return 0;
}
return view.computeHorizontalScrollOffset() / Utils.layout.getDisplayDensity();
}
get verticalOffsetY() {
const view = this.nativeViewProtected;
if (!view) {
return 0;
}
return view.computeVerticalScrollOffset() / Utils.layout.getDisplayDensity();
}
public scrollToIndex(index: number, animated: boolean = true) {
const view = this.nativeViewProtected;
if (!view) {
return;
}
if (animated) {
view.smoothScrollToPosition(index);
} else {
view.scrollToPosition(index);
}
}
scrollToOffset(offSetValue) {
const view = this.nativeViewProtected;
if (view && this.isScrollEnabled) {
if (this.orientation === 'horizontal') {
view.scrollBy(offSetValue, 0);
} else {
view.scrollBy(0, offSetValue);
}
}
}
private _setPadding(newPadding: { top?: number; right?: number; bottom?: number; left?: number }) {
const nativeView = this.nativeViewProtected;
const padding = {
top: nativeView.getPaddingTop(),
right: nativeView.getPaddingRight(),
bottom: nativeView.getPaddingBottom(),
left: nativeView.getPaddingLeft()
};
// tslint:disable-next-line:prefer-object-spread
const newValue = Object.assign(padding, newPadding);
nativeView.setClipToPadding(false);
nativeView.setPadding(newValue.left, newValue.top, newValue.right, newValue.bottom);
this.updateInnerSize();
}
private createComposedAdapter(recyclerView: CollectionViewRecyclerView) {
const adapter = new com.nativescript.collectionview.Adapter();
adapter.adapterInterface = new com.nativescript.collectionview.AdapterInterface({
getItemId: this.getItemId.bind(this),
getItemViewType: this.getItemViewType.bind(this),
getItemCount: this.getItemCount.bind(this),
onCreateViewHolder: this.onCreateViewHolder.bind(this),
onBindViewHolder: this.onBindViewHolder.bind(this),
onViewRecycled: this.onViewRecycled.bind(this)
});
// const composedAdapter = new com.h6ah4i.android.widget.advrecyclerview.composedadapter.ComposedAdapter();
// composedAdapter.addAdapter(new CollectionViewAdapter(new WeakRef(this)));
return adapter;
}
public getItemCount() {
return this.items ? this.items.length : 0;
}
public getItem(i: number) {
if (this.items && i < this.items.length) {
return this.getItemAtIndex(i);
}
return null;
}
public getItemId(i: number) {
let id = -1;
if (this._itemIdGenerator && this.items) {
const item = this.getItemAtIndex(i);
id = this._itemIdGenerator(item, i, this.items);
}
return long(id);
}
onItemIdGeneratorChanged(oldValue, newValue) {
super.onItemIdGeneratorChanged(oldValue, newValue);
if (this._listViewAdapter) {
this._listViewAdapter.setHasStableIds(!!newValue);
}
}
public clearTemplateTypes() {
this._currentNativeItemType = 0;
this.templateTypeNumberString.clear();
this.templateStringTypeNumber.clear();
}
public getItemViewType(position: number) {
let selectorType: string = 'default';
if (this._itemTemplateSelector) {
const selector = this._itemTemplateSelector;
const dataItem = this.getItemAtIndex(position);
if (dataItem) {
selectorType = selector.call(this, dataItem, position, this.items);
}
}
return this.templateKeyToNativeItem(selectorType);
// if (!this.templateTypeNumberString.has(selectorType)) {
// resultType = this._currentNativeItemType;
// this.templateTypeNumberString.set(selectorType, resultType);
// this.templateStringTypeNumber.set(resultType, selectorType);
// this._currentNativeItemType++;
// } else {
// resultType = this.templateTypeNumberString.get(selectorType);
// }
// return resultType;
}
public templateKeyToNativeItem(key: string): number {
if (!this.templateTypeNumberString) {
this.templateTypeNumberString = new Map<string, number>();
this._currentNativeItemType = 0;
this._itemTemplatesInternal.forEach((v, i) => {
this.templateTypeNumberString.set(v.key, this._currentNativeItemType);
this.templateStringTypeNumber.set(this._currentNativeItemType, v.key);
this.setNativePoolSize(v.key, this._currentNativeItemType);
this._currentNativeItemType++;
});
this._currentNativeItemType = Math.max(this._itemTemplatesInternal.size, 100);
// templates will be numbered 0,1,2,3... for named templates
// default/unnamed templates will be numbered 100, 101, 102, 103...
}