| 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202 |
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
1×
26×
1×
1×
1×
1×
1×
1×
26×
26×
26×
26×
26×
26×
1×
26×
26×
26×
1×
1×
1×
1×
1×
1×
1×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
26×
5×
26×
31×
31×
26×
22×
22×
2×
2×
26×
17×
2×
2×
2×
26×
1×
1×
1×
1×
26×
15×
15×
15×
15×
26×
17×
17×
17×
17×
17×
17×
26×
32×
32×
32×
26×
26×
2×
26×
1×
198×
2×
13×
72×
2×
24×
355×
2×
61×
2×
22×
613×
2×
22×
2×
2×
26×
3×
1×
1×
1×
2×
2×
13×
200×
2×
13×
2×
26×
2×
13×
2×
2×
16×
2×
21×
2×
13×
2×
2×
37×
197×
2×
13×
13×
2×
5×
1×
4504×
2×
31×
39×
2×
13×
2×
29×
2×
13×
13×
5×
5×
2×
15×
4×
6×
6×
2×
13×
2×
24×
2×
13×
13×
13×
13×
65×
2×
13×
2×
13×
18×
2×
18×
18×
18×
1×
1×
1×
17×
2×
11×
11×
2×
11×
2×
11×
2×
11×
2×
11×
8×
2×
8×
8×
2×
4×
4×
4×
351×
2×
12×
1×
714×
2×
77×
71×
1×
30×
30×
2192×
1×
5542×
1×
376×
1×
2×
1×
451×
1×
154×
1×
154×
1×
1×
1×
1×
1×
1×
17×
1×
5×
1×
5×
1×
1×
2×
2×
2×
1×
2×
1×
27×
1×
9×
1×
26×
3×
3×
3×
3×
36×
36×
36×
3×
3×
3×
26×
26×
26×
11×
11×
26×
10×
10×
10×
10×
10×
10×
10×
26×
26×
23×
23×
26×
22×
22×
22×
22×
22×
22×
19×
19×
19×
22×
22×
22×
4×
1×
3×
2×
2×
4×
4×
3×
1×
2×
2×
2×
3×
3×
2×
2×
1×
1×
1×
1×
2×
2×
2×
2×
1×
1×
1×
1×
2×
2×
2×
2×
2×
1×
1×
1×
1×
2×
2×
6×
6×
6×
1×
5×
4×
4×
6×
6×
2×
2×
2×
2×
2×
2×
1×
1×
1×
1×
2×
1×
1×
1×
1×
1×
1×
1×
22×
22×
22×
22×
22×
26×
26×
23×
23×
23×
26×
5×
5×
5×
5×
5×
5×
5×
5×
5×
5×
5×
5×
5×
5×
15×
15×
15×
5×
10×
10×
5×
5×
26×
8×
8×
8×
1×
7×
7×
7×
1×
6×
6×
6×
6×
6×
5×
1×
1×
1×
4×
3×
3×
3×
3×
3×
5×
5×
5×
5×
5×
5×
5×
5×
5×
1×
4×
4×
4×
2×
1×
1×
1×
1×
1×
1×
1×
4×
2148×
2148×
1596×
552×
196×
196×
137×
59×
59×
1×
1×
27×
27×
27×
22×
22×
22×
22×
5×
5×
5×
5×
27×
27×
18×
18×
18×
18×
18×
18×
9×
9×
9×
9×
55×
55×
55×
1×
2159×
2159×
10×
2159×
2×
2159×
142×
2159×
19×
2159×
185×
2159×
2×
2159×
972×
2159×
1×
| /*
* @license
* Copyright Hôpitaux Universitaires de Genève. All Rights Reserved.
*
* Use of this source code is governed by an Apache-2.0 license that can be
* found in the LICENSE file at https://github.com/DSI-HUG/dejajs-components/blob/master/LICENSE
*/
import { coerceBooleanProperty, coerceNumberProperty } from '@angular/cdk/coercion';
import { AfterContentInit, AfterViewInit, ChangeDetectionStrategy, ChangeDetectorRef, Component, ContentChild, ContentChildren, ElementRef, EventEmitter, HostBinding, Input, Optional, Output, Self, ViewChild, ViewEncapsulation } from '@angular/core';
import { ControlValueAccessor, NgControl } from '@angular/forms';
import { BehaviorSubject, combineLatest as observableCombineLatest, from as observableFrom, fromEvent as observableFromEvent, merge as observableMerge, Observable, of as observableOf, Subject, Subscription, timer as observableTimer } from 'rxjs';
import { debounceTime, filter, first, map, merge, switchMap, takeWhile, tap } from 'rxjs/operators';
import { DejaClipboardService } from '../../common/core/clipboard/clipboard.service';
import { Position } from '../../common/core/graphics/position';
import { Rect } from '../../common/core/graphics/rect';
import { GroupingService } from '../../common/core/grouping/index';
import { IItemBase } from '../../common/core/item-list/item-base';
import { DejaItemEvent } from '../../common/core/item-list/item-event';
import { ItemListBase } from '../../common/core/item-list/item-list-base';
import { ItemListService, IViewListResult } from '../../common/core/item-list/item-list.service';
import { IItemTree } from '../../common/core/item-list/item-tree';
import { DejaItemsEvent } from '../../common/core/item-list/items-event';
import { ViewportMode } from '../../common/core/item-list/viewport.service';
import { IViewPort } from '../../common/core/item-list/viewport.service';
import { ViewPortService } from '../../common/core/item-list/viewport.service';
import { KeyCodes } from '../../common/core/keycodes.enum';
import { SortingService } from '../../common/core/sorting/index';
import { DejaChildValidatorDirective } from '../../common/core/validation/child-validator.directive';
import { IDejaDragEvent } from '../dragdrop';
import { DejaItemComponent } from './../../common/core/item-list/item.component';
import { DejaTreeListScrollEvent } from './tree-list-scroll-event';
const noop = () => { };
/** Composant de liste évoluée avec gestion de viewport et templating */
@Component({
changeDetection: ChangeDetectionStrategy.OnPush,
encapsulation: ViewEncapsulation.None,
providers: [ViewPortService],
selector: 'deja-tree-list',
styles: [
require('./tree-list.component.scss'),
],
template: require('./tree-list.component.html'),
})
export class DejaTreeListComponent extends ItemListBase implements AfterViewInit, AfterContentInit, ControlValueAccessor {
/** Texte à afficher par default dans la zone de recherche */
@Input() public placeholder: string;
/** Texte affiché si aucune donnée n'est présente dans le tableau */
@Input() public nodataholder: string;
/** Correspond au ngModel du champ de filtrage ou recherche */
@Input() public query = '';
/** Permet de définir un template de ligne par binding */
@Input() public itemTemplateExternal: any;
/** Permet de définir un template de ligne parente par binding. */
@Input() public parentItemTemplateExternal: any;
/** Permet de définir un template pour le loader par binding. */
@Input() public loaderTemplateExternal: any;
/** Permet de définir un template d'entête de colonne par binding. */
@Input() public headerTemplateExternal: any;
/** Permet de définir un template comme prefixe de la zone de recherche par binding. */
@Input() public searchPrefixTemplateExternal: any;
/** Permet de définir un template comme suffixe de la zone de recherche par binding. */
@Input() public searchSuffixTemplateExternal: any;
/** Largeur des éléments par defaut si différent de 100% */
@Input() public itemsWidth: number = null;
/** Exécuté lorsque le déplacement d'une ligne est terminée. */
@Output() public itemDragEnd = new EventEmitter<IDejaDragEvent>();
/** Exécuté lorsque le déplacement d'une ligne commence. */
@Output() public itemDragStart = new EventEmitter<IDejaDragEvent>();
/** Exécuté lorsque la scrollbar change de position. */
@Output() public scroll = new EventEmitter<DejaTreeListScrollEvent>();
/** Exécuté lorsque l'utilisateur sélectionne ou désélectionne une ligne. */
@Output() public selectedChange = new EventEmitter<DejaItemsEvent | DejaItemEvent>();
/** Exécuté lorsque le calcul du viewPort est executé. */
@Output() public viewPortChanged = new EventEmitter<IViewPort>();
/** Internal use */
@ViewChild('inputelement') public input: ElementRef;
// NgModel implementation
public onTouchedCallback: () => void = noop;
public onChangeCallback: (_: any) => void = noop;
private _keyboardNavigation = false;
// Templates
@ContentChild('itemTemplate') private itemTemplateInternal: any;
@ContentChild('parentItemTemplate') private parentItemTemplateInternal: any;
@ContentChild('loaderTemplate') private loaderTemplateInternal: any;
@ContentChild('headerTemplate') private headerTemplateInternal: any;
@ContentChild('searchPrefixTemplate') private searchPrefixTemplateInternal: any;
@ContentChild('searchSuffixTemplate') private searchSuffixTemplateInternal: any;
@ContentChildren(DejaItemComponent) public options: DejaItemComponent[];
// protected _items: IItemBase[]; In the base class, correspond to the model
private clickedItem: IItemBase;
private rangeStartIndex = 0;
private filterExpression = '';
private _searchArea = false;
private _sortable = false;
private _itemsDraggable = false;
private hasCustomService = false;
private hasLoadingEvent = false;
private _modelIsValue = false;
@HostBinding('attr.disabled') private _disabled: boolean = null;
private keyboardNavigation$ = new Subject();
private mouseUp$sub: Subscription;
private clearFilterExpression$ = new BehaviorSubject<void>(null);
private writeValue$ = new Subject<any>();
private selectItems$ = new Subject<any>();
private contentInitialized$ = new Subject();
public setQuery$ = new Subject<string>();
constructor(changeDetectorRef: ChangeDetectorRef, public viewPort: ViewPortService, public elementRef: ElementRef, @Self() @Optional() public _control: NgControl, @Optional() private clipboardService: DejaClipboardService) {
super(changeDetectorRef, viewPort);
if (this._control) {
this._control.valueAccessor = this;
}
observableFrom(this.clearFilterExpression$).pipe(
takeWhile(() => this._isAlive),
debounceTime(400))
.subscribe(() => this.filterExpression = '');
observableFrom(this.keyboardNavigation$).pipe(
takeWhile(() => this._isAlive),
tap(() => this._keyboardNavigation = true),
debounceTime(1000))
.subscribe(() => {
this._keyboardNavigation = false;
this.changeDetectorRef.markForCheck();
});
observableFromEvent(window, 'resize').pipe(
takeWhile(() => this._isAlive),
debounceTime(5))
.subscribe(() => {
this.viewPort.deleteSizeCache();
this.viewPort.refresh();
this.changeDetectorRef.markForCheck();
});
observableFrom(this.setQuery$).pipe(
takeWhile(() => this._isAlive),
debounceTime(250),
tap((query) => {
this.query = query;
this.setCurrentItem(undefined);
}),
switchMap(() => this.calcViewList$()))
.subscribe(noop);
const selectItems$ = observableCombineLatest(this.selectItems$, this.contentInitialized$).pipe(
map(([value]) => value),
map((value) => this.getVirtualSelectedEntities(value)),
map((value) => (value instanceof Array && value) || (value && [value]) || []),
tap((values) => super.setSelectedItems(values)));
const selectModels$ = observableCombineLatest(this.writeValue$, this.contentInitialized$).pipe(
map(([value]) => {
Iif (this.modelIsValue === undefined) {
if (value instanceof Array) {
const av = value || [];
const modelType = av.length && typeof av[0];
this.modelIsValue = modelType && modelType === 'string' || modelType === 'number';
} else {
const modelType = typeof value;
this.modelIsValue = value === '' || modelType === 'string' || modelType === 'number';
}
}
Iif (this.modelIsValue) {
this.query = '';
}
return value;
}),
map((value) => this.getVirtualSelectedEntities(value)),
tap((value) => super.setSelectedModels(!value || this._multiSelect || value instanceof Array ? value : [value])));
observableMerge(selectModels$, selectItems$).pipe(
takeWhile(() => this._isAlive))
.subscribe(() => {
super.getItemListService().ensureSelection();
this.changeDetectorRef.markForCheck();
});
this._viewPortChanged = this.viewPortChanged;
this.maxHeight = 0;
}
@ViewChild('listElement') public set listElememtRef(elem: ElementRef) {
this.listElement = elem.nativeElement;
}
public keyboardNavigation() {
return this._keyboardNavigation;
}
/** Définit la longueur minimale de caractères dans le champ de recherche avant que la recherche ou le filtrage soient effectués */
@Input('min-search-length')
public set minSearchlength(value: number | string) {
this._minSearchLength = coerceNumberProperty(value);
}
public get minSearchlength() {
return this._minSearchLength;
}
/** Affiche un barre de recherche au dessus de la liste. */
@Input()
public set searchArea(value: boolean | string) {
this._searchArea = coerceBooleanProperty(value);
}
public get searchArea() {
return this._searchArea || this.minSearchlength > 0;
}
/** Définit une valeur indiquant si en reactive form le model renvoyé doit être un obeject oue une valeur */
@Input()
public set modelIsValue(value: boolean | string) {
this._modelIsValue = coerceBooleanProperty(value);
}
public get modelIsValue() {
return this._modelIsValue;
}
/** Retourne ou définit une valeur indiquant si les lignes de la liste peuvent être déplacées manuelement par l'utilisateur */
@Input()
public set sortable(value: boolean | string) {
this._sortable = coerceBooleanProperty(value);
}
public get sortable() {
return this._sortable;
}
/** Retourne ou définit une valeur indiquant si les lignes peuvent être déplacées vers un autre composant */
@Input()
public set itemsDraggable(value: boolean | string) {
this._itemsDraggable = coerceBooleanProperty(value);
}
public get itemsDraggable() {
return this._itemsDraggable;
}
@Input()
/** Définit le nombre de lignes à sauter en cas de pression sur les touches PageUp ou PageDown */
public set pageSize(value: number | string) {
this._pageSize = coerceNumberProperty(value);
}
/** Retourne le nombre de lignes à sauter en cas de pression sur les touches PageUp ou PageDown */
public get pageSize() {
if (this._pageSize === 0) {
const vpRowHeight = this.getViewPortRowHeight();
const containerHeight = this.maxHeight || this.listElement.clientHeight;
return Math.floor(containerHeight / vpRowHeight);
}
return this._pageSize;
}
/** Définit un texte de conseil en cas d'erreur de validation ou autre */
@Input()
public set hintLabel(value: string) {
this.setHintLabel(value);
}
/** Retourne un texte de conseil en cas d'erreur de validation ou autre */
public get hintLabel(): string {
return this._hintLabel;
}
/** Définit la hauteur d'une ligne pour le calcul du viewport en pixels (la valeur par défaut sera utilisée si aucune valeur n'est setté). */
@Input()
public set viewPortRowHeight(value: number | string) {
this.setViewPortRowHeight(value);
}
/**
* Les valeurs acceptées en paramètre se trouvent dans l'enum ViewportMode (disabled, constant, variable ou auto)
* Attention, une désactivation du viewport dégrade considérablement les performances de la liste et ne doit pas être activée si la liste
* est suceptible de contenir beaucoup d'éléments.
*/
@Input()
public set viewportMode(mode: ViewportMode | string) {
this.setViewportMode(mode);
}
/** Retourne le champ utilisé pour la liste des enfants d'un parent */
@Input()
public set childrenField(value: string) {
super.setChildrenField(value);
}
/** Définit le champ utilisé pour la liste des enfants d'un parent */
public get childrenField() {
return this._childrenField;
}
/** Définit le champ à utiliser comme valeur d'affichage. */
@Input()
public set textField(value: string) {
super.setTextField(value);
}
/** Définit le champ à utiliser comme valeur de comparaison. */
@Input()
public set valueField(value: string) {
super.setValueField(value);
}
/** Définit le champ à utiliser comme champ de recherche.
* Ce champ peut indiquer, un champ contenant une valeur, un texte indexé, ou une fonction.
*/
@Input()
public set searchField(value: string) {
super.setSearchField(value);
}
/** Retourne le champ à utiliser comme champ de recherche.
* Ce champ peut indiquer, un champ contenant une valeur, un texte indexé, ou une fonction.
*/
public get searchField() {
return this._searchField;
}
/** Définit la hauteur maximum avant que le composant affiche une scrollbar
* spécifier une grande valeur pour ne jamais afficher de scrollbar
* Spécifier 0 pour que le composant determine sa hauteur à partir du container
*/
@Input()
public set maxHeight(value: number) {
super.setMaxHeight(value);
}
/** Retourne la hauteur maximum avant que le composant affiche une scrollbar
* spécifier une grande valeur pour ne jamais afficher de scrollbar
* Spécifier 0 pour que le composant determine sa hauteur à partir du container
*/
public get maxHeight() {
return this.getMaxHeight();
}
/** Définit la ligne courant ou ligne active */
@Input()
public set currentItem(item: IItemBase) {
super.setCurrentItem(item);
if (item) {
this.ensureItemVisible(item);
}
}
/** Retourne la ligne courant ou ligne active */
public get currentItem() {
return super.getCurrentItem();
}
/** Retourne le nombre de niveau pour une liste hierarchique */
public get depthMax() {
return this._depthMax;
}
/** Définit une valeur indiquant si plusieurs lignes peuvent être sélectionées. */
@Input()
public set multiSelect(value: boolean | string) {
super.setMultiSelect(coerceBooleanProperty(value));
}
/** Retourne une valeur indiquant si plusieurs lignes peuvent être sélectionées. */
public get multiSelect() {
return this._multiSelect;
}
/** Définit la liste des éléments selectionés en mode multiselect */
@Input()
public set selectedItems(value: IItemBase[]) {
if (value !== undefined) {
this.selectItems$.next(value);
}
}
/** Retourne la liste des éléments selectionés en mode multiselect */
public get selectedItems() {
return super.getSelectedItems();
}
/** Définit l'élément selectioné en mode single select */
@Input()
public set selectedItem(value: IItemBase | string) {
Eif (value !== undefined) {
this.selectItems$.next(value);
}
}
/** Retourne l'éléments selectioné en mode single select */
public get selectedItem() {
const selectedItem = super.getSelectedItems();
return selectedItem && selectedItem[0];
}
/** Définit le model selectioné en mode single select */
@Input()
public set selectedModel(value: any) {
if (value !== undefined) {
this.writeValue(value);
}
}
/** Retourne le model selectioné en mode single select */
public get selectedModel() {
const selectedModel = super.getSelectedModels();
return selectedModel && selectedModel[0];
}
/** Définit la liste des models selectionés en mode multiselect */
@Input()
public set selectedModels(value: any[]) {
if (value !== undefined) {
this.writeValue(value);
}
}
/** Retourne la liste des models selectionés en mode multiselect */
public get selectedModels() {
return super.getSelectedModels();
}
/** Definit le service de liste utilisé par ce composant. Ce srevice permet de controller dynamiquement la liste, ou de faire du lazyloading. */
@Input()
public set itemListService(itemListService: ItemListService) {
Eif (itemListService !== undefined) {
this.hasCustomService = true;
this.setItemListService(itemListService);
Iif (itemListService && itemListService.lastQuery) {
this.query = itemListService.lastQuery.toString();
}
}
}
/** Retourne le service de liste utilisé par ce composant. Ce srevice permet de controller dynamiquement la liste, ou de faire du lazyloading. */
public get itemListService() {
return this.getItemListService();
}
/** Definit le service utilisé pour le tri de la liste */
@Input()
public set sortingService(value: SortingService) {
this.setSortingService(value);
}
/** Definit le service utilisé pour le regroupement de la liste */
@Input()
public set groupingService(value: GroupingService) {
this.setGroupingService(value);
}
/** Définit la liste des éléments */
@Input()
public set items(items: IItemBase[] | Promise<IItemBase[]> | Observable<IItemBase[]>) {
delete this.hintLabel;
super.setItems$(items).pipe(
switchMap((itms) => {
if (this.minSearchlength > 0 && !this.query) {
// Waiting for query
this._itemList = [];
this.changeDetectorRef.markForCheck();
return observableOf(itms);
} else {
return this.calcViewList$().pipe(map(() => itms));
}
}))
.subscribe(noop);
}
/**
* Set a observable called before the list will be displayed
*/
@Input()
public set loadingItems(fn: (query: string | RegExp, selectedItems: IItemBase[]) => Observable<IItemBase[]>) {
this.hasLoadingEvent = !!fn;
super.setLoadingItems(fn);
}
/**
* Set a promise or an observable called before an item selection
*/
@Input()
public set selectingItem(fn: (item: IItemBase) => Promise<IItemBase> | Observable<IItemBase>) {
super.setSelectingItem(fn);
}
/**
* Set a promise or an observable called before an item deselection
*/
@Input()
public set unselectingItem(fn: (item: IItemBase) => Promise<IItemBase> | Observable<IItemBase>) {
super.setUnselectingItem(fn);
}
/**
* Set a promise or an observable called before an item expand
*/
@Input()
public set expandingItem(fn: (item: IItemTree) => Promise<IItemTree> | Observable<IItemTree>) {
super.setExpandingItem(fn);
}
/**
* Set a promise or an observable called before an item collapse
*/
@Input()
public set collapsingItem(fn: (item: IItemTree) => Promise<IItemTree> | Observable<IItemTree>) {
super.setCollapsingItem(fn);
}
/** Définit la liste des éléments (tout type d'objet métier) */
@Input()
public set models(items: any[] | Observable<any[]>) {
super.setModels$(items).pipe(
first(),
switchMap(() => this.calcViewList$()))
.subscribe(noop);
}
/** Permet de désactiver la liste */
@Input()
public set disabled(value: boolean | string) {
const disabled = coerceBooleanProperty(value);
this._disabled = disabled || null;
this.changeDetectorRef.markForCheck();
}
public get disabled() {
return this._disabled;
}
/** Definit si le waiter doit être affiché dans la liste. */
@Input()
public set waiter(value: boolean) {
if (value !== undefined) {
this._waiter = value;
}
}
/** Retourne si le waiter doit être affiché dans la liste. */
public get waiter() { return this._waiter; }
@ViewChild(DejaChildValidatorDirective)
public set inputValidatorDirective(value: DejaChildValidatorDirective) {
if (value) {
value.parentControl = this._control;
}
}
public set currentItemIndex(value: number) {
super.setCurrentItemIndex(value);
this.changeDetectorRef.markForCheck();
}
public get currentItemIndex() {
return this.getCurrentItemIndex();
}
public get itemTemplate() {
return this.itemTemplateExternal || this.itemTemplateInternal;
}
public get parentItemTemplate() {
return this.parentItemTemplateExternal || this.parentItemTemplateInternal;
}
public get loaderTemplate() {
return this.loaderTemplateExternal || this.loaderTemplateInternal;
}
public get headerTemplate() {
return this.headerTemplateExternal || this.headerTemplateInternal;
}
public get searchPrefixTemplate() {
return this.searchPrefixTemplateExternal || this.searchPrefixTemplateInternal;
}
public get searchSuffixTemplate() {
return this.searchSuffixTemplateExternal || this.searchSuffixTemplateInternal;
}
// ************* ControlValueAccessor Implementation **************
public get value() {
return this._multiSelect ? this.selectedItems : this.selectedItem;
}
public set value(val) {
this.writeValue(val);
this.onChangeCallback(val);
this.onTouchedCallback();
}
public writeValue(value: any) {
this.writeValue$.next(value);
}
public registerOnChange(fn: any) {
this.onChangeCallback = fn;
}
public registerOnTouched(fn: any) {
this.onTouchedCallback = fn;
}
public setDisabledState(isDisabled: boolean) {
this.disabled = isDisabled;
}
// ************* End of ControlValueAccessor Implementation **************
/** Change l'état d'expansion de toute les lignes parentes */
public toggleAll$(collapsed?: boolean): Observable<IItemTree[]> {
return super.toggleAll$(collapsed).pipe(
switchMap((items) => this.calcViewList$().pipe(first(), map(() => items))));
}
/** Change l'état d'expansion de toute les lignes parentes */
public toggleAll(collapsed?: boolean) {
this.toggleAll$(collapsed).pipe(first()).subscribe(noop);
}
/** Positionne a scrollbar pour assurer que l'élément spécifié soit visible */
public ensureItemVisible(item: IItemBase | number) {
super.ensureItemVisible(item);
}
/** Efface le contenu de la liste */
public clearViewPort() {
super.clearViewPort();
}
public ngAfterContentInit() {
if (!this.items && this.options && this.options.length) {
const selectedModels = [] as any[];
this.valueField = 'value';
this.textField = 'text';
const models = this.options.map((option) => {
const model = {
text: option.text,
value: option.value,
};
Iif (option.selected) {
selectedModels.push(model);
}
return model;
});
this.models = models;
Iif (selectedModels.length) {
this.selectedModels = selectedModels;
}
Iif (models.length > 100) {
// tslint:disable-next-line:no-debugger
debugger;
console.error('Select options with more than 100 items can have performance options. Please bind directly the items in code behind with items or models input.');
}
}
this.contentInitialized$.next(true);
}
public ngAfterViewInit() {
// FIXME Issue angular/issues/6005
// see http://stackoverflow.com/questions/34364880/expression-has-changed-after-it-was-checked
if (this._itemList.length === 0 && (this.hasCustomService || this.hasLoadingEvent)) {
observableTimer(1).pipe(
first(),
switchMap(() => this.calcViewList$()))
.subscribe(noop);
}
observableFromEvent(this.listElement, 'scroll').pipe(
takeWhile(() => this._isAlive),
map((event: any) => [event, event.target.scrollTop, event.target.scrollLeft]),
map(([event, scrollTop, scrollLeft]: [Event, number, number]) => {
const e = {
originalEvent: event,
scrollLeft: scrollLeft,
scrollTop: scrollTop,
} as DejaTreeListScrollEvent;
this.scroll.emit(e);
return scrollTop;
}))
.subscribe((scrollPos) => this.viewPort.scrollPosition$.next(scrollPos));
let keyDown$ = observableFromEvent(this.listElement, 'keydown');
if (this.input) {
const inputKeyDown$ = observableFromEvent(this.input.nativeElement, 'keydown') as Observable<KeyboardEvent>;
keyDown$ = keyDown$.pipe(merge(inputKeyDown$));
}
keyDown$.pipe(takeWhile(() => this._isAlive),
filter(() => !this.disabled),
filter((event: KeyboardEvent) => {
const keyCode = event.keyCode || (<any>KeyCodes)[event.code];
return keyCode === KeyCodes.Home ||
keyCode === KeyCodes.End ||
keyCode === KeyCodes.PageUp ||
keyCode === KeyCodes.PageDown ||
keyCode === KeyCodes.UpArrow ||
keyCode === KeyCodes.DownArrow ||
keyCode === KeyCodes.Space ||
keyCode === KeyCodes.Enter;
}),
switchMap((event) => this.ensureListCaches$().pipe(map(() => event))),
map((event: KeyboardEvent) => {
Iif (!this.rowsCount) {
return true;
}
// Set current item from index for keyboard features only
const setCurrentIndex = (index: number) => {
this.currentItemIndex = index;
this.ensureItemVisible(this.currentItemIndex);
this.viewPort.refresh();
};
const currentIndex = this.rangeStartIndex >= 0 ? this.rangeStartIndex : this.rangeStartIndex = this.currentItemIndex;
const keyCode = event.keyCode || (<any>KeyCodes)[event.code];
switch (keyCode) {
case KeyCodes.Home:
if (event.shiftKey) {
this.selectRange$(currentIndex, 0).pipe(first()).subscribe(noop);
} else if (!event.ctrlKey) {
this.rangeStartIndex = 0;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(0);
return false;
case KeyCodes.End:
if (event.shiftKey) {
this.selectRange$(currentIndex, this.rowsCount - 1).pipe(first()).subscribe(noop);
} else Eif (!event.ctrlKey) {
this.rangeStartIndex = this.rowsCount - 1;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(this.rowsCount - 1);
return false;
case KeyCodes.PageUp:
const upindex = Math.max(0, this.currentItemIndex - this._pageSize);
if (event.shiftKey) {
this.selectRange$(currentIndex, upindex).pipe(first()).subscribe(noop);
} else Eif (!event.ctrlKey) {
this.rangeStartIndex = upindex;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(upindex);
return false;
case KeyCodes.PageDown:
const dindex = Math.min(this.rowsCount - 1, this.currentItemIndex + this._pageSize);
if (event.shiftKey) {
this.selectRange$(currentIndex, dindex).pipe(first()).subscribe(noop);
} else Eif (!event.ctrlKey) {
this.rangeStartIndex = dindex;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(dindex);
return false;
case KeyCodes.UpArrow:
const uaindex = Math.max(0, this.currentItemIndex - 1);
Eif (uaindex !== -1) {
if (event.shiftKey) {
this.selectRange$(currentIndex, uaindex).pipe(first()).subscribe(noop);
} else Eif (!event.ctrlKey) {
this.rangeStartIndex = uaindex;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(uaindex);
}
return false;
case KeyCodes.DownArrow:
const daindex = Math.min(this.rowsCount - 1, this.currentItemIndex + 1);
Eif (daindex !== -1) {
if (event.shiftKey) {
this.selectRange$(currentIndex, daindex).pipe(first()).subscribe(noop);
} else if (!event.ctrlKey) {
this.rangeStartIndex = daindex;
this.selectRange$(this.rangeStartIndex).pipe(first()).subscribe(noop);
}
setCurrentIndex(daindex);
}
return false;
case KeyCodes.Space:
const target = event.target as HTMLElement;
Iif (target.tagName === 'INPUT' && !event.ctrlKey && !event.shiftKey) {
return true;
}
const sitem = this.currentItem as IItemTree;
Eif (sitem) {
Iif (this.isCollapsible(sitem)) {
this.toggleCollapse$(currentIndex, !sitem.collapsed).pipe(first()).subscribe(noop);
} else if (sitem.selected) {
this.toggleSelect$([sitem], false).pipe(first()).subscribe(noop);
} else Iif (this.multiSelect && event.ctrlKey) {
this.toggleSelect$([sitem], !sitem.selected).pipe(first()).subscribe(noop);
} else {
this.unselectAll$().pipe(
switchMap(() => this.toggleSelect$([sitem], true)),
first())
.subscribe(noop);
}
}
return false;
case KeyCodes.Enter:
const eitem = this.currentItem as IItemTree;
Eif (eitem) {
Iif (this.isCollapsible(eitem)) {
this.toggleCollapse$(currentIndex, !eitem.collapsed).pipe(first()).subscribe(noop);
} else Eif (this.isSelectable(eitem)) {
this.unselectAll$().pipe(
switchMap(() => this.toggleSelect$([eitem], true)),
first())
.subscribe(noop);
}
}
return false;
default:
return true;
}
}))
.subscribe((continuePropagation) => {
Eif (!continuePropagation) {
this.keyboardNavigation$.next();
this.changeDetectorRef.markForCheck();
event.preventDefault();
return false;
}
});
let keyUp$ = observableFromEvent(this.listElement, 'keyup') as Observable<Event>;
if (this.input) {
const inputKeyup$ = observableFromEvent(this.input.nativeElement, 'keyup') as Observable<KeyboardEvent>;
const inputDrop$ = observableFromEvent(this.input.nativeElement, 'drop') as Observable<KeyboardEvent>;
keyUp$ = keyUp$.pipe(merge(inputKeyup$, inputDrop$));
}
// Ensure list cache
keyUp$.pipe(
takeWhile(() => this._isAlive),
filter(() => !this.disabled),
tap(() => {
Iif ((this.query || '').length < this.minSearchlength) {
this._itemList = [];
return;
}
}),
filter((event: KeyboardEvent) => {
const keyCode = event.keyCode || (<any>KeyCodes)[event.code];
return keyCode >= KeyCodes.Key0 ||
keyCode === KeyCodes.Backspace ||
keyCode === KeyCodes.Space ||
keyCode === KeyCodes.Delete;
}))
.subscribe((event: KeyboardEvent) => {
// Set current item from index for keyboard features only
const setCurrentIndex = (index: number) => {
this.currentItemIndex = index;
this.ensureItemVisible(this.currentItemIndex);
};
Eif (!this.searchArea) {
Eif ((/[a-zA-Z0-9]/).test(event.key)) {
// Valid char
this.clearFilterExpression$.next(null);
// Search next
this.filterExpression += event.key;
const rg = new RegExp(`^${this.filterExpression}`, 'i');
this.findNextMatch$((item) => {
Eif (item && this.isSelectable(item)) {
const label = this.getTextValue(item);
if (rg.test(label)) {
return true;
}
}
event.preventDefault();
return false;
}, this.currentItemIndex).pipe(
first())
.subscribe((result) => {
Eif (result.index >= 0) {
setCurrentIndex(result.index);
}
});
}
} else {
// Autocomplete, filter the list
this.keyboardNavigation$.next();
}
});
this.viewPort.element$.next(this.listElement);
}
public mousedown(e: MouseEvent) {
Iif (this.mouseUp$sub) {
this.mouseUp$sub.unsubscribe();
this.mouseUp$sub = undefined;
}
if (this.disabled) {
return undefined;
}
const target = e.target as HTMLElement;
const itemIndex = this.getItemIndexFromHTMLElement(target);
if (itemIndex === undefined) {
return undefined;
}
const isExpandButton = (el: HTMLElement) => {
return el.id === 'expandbtn' || el.parentElement.id === 'expandbtn';
};
const item = this._itemList[itemIndex - this.vpStartRow];
this.clickedItem = item;
if ((!isExpandButton(target) || !this.isCollapsible(item)) && this.isSelectable(item) && (!e.ctrlKey || !this.multiSelect) && (e.button === 0 || !item.selected)) {
if (e.shiftKey && this.multiSelect) {
// Select all from current to clicked
this.selectRange$(itemIndex, this.currentItemIndex).pipe(
first())
.subscribe(() => this.changeDetectorRef.markForCheck());
return false;
} else if (!e.ctrlKey) {
Iif (!this.multiSelect && item.selected) {
return undefined;
}
this.unselectAll$().pipe(first()).subscribe(() => {
this.currentItemIndex = itemIndex;
this.toggleSelect$([item], true).pipe(
first())
.subscribe(() => this.changeDetectorRef.markForCheck());
});
}
}
this.mouseUp$sub = observableFromEvent(this.listElement, 'mouseup').pipe(
first(),
filter(() => !this.disabled))
.subscribe((upevt: MouseEvent) => {
// Because .first()
this.mouseUp$sub = undefined;
const upTarget = upevt.target as HTMLElement;
const upIndex = this.getItemIndexFromHTMLElement(upTarget);
Iif (upIndex === undefined) {
return;
}
const upItem = this._itemList[upIndex - this.vpStartRow];
Iif (this.clickedItem && upItem !== this.clickedItem) {
return;
}
if (upevt.shiftKey) {
return;
}
Iif (upevt.button !== 0) {
// Right click menu
return;
}
Iif (this.isCollapsible(upItem) && (isExpandButton(upTarget) || !this.isSelectable(upItem))) {
const treeItem = upItem as IItemTree;
this.toggleCollapse$(upIndex, !treeItem.collapsed).pipe(first()).subscribe(() => {
this.currentItemIndex = upIndex;
});
} else if (upevt.ctrlKey) {
if (this.multiSelect) {
this.toggleSelect$([upItem], !upItem.selected).pipe(
first())
.subscribe(() => {
this.currentItemIndex = upIndex;
this.changeDetectorRef.markForCheck();
});
} else {
const o = this.selectedItem && this.selectedItem !== upItem ? this.toggleSelect$([this.selectedItem], false).pipe(switchMap(() => this.toggleSelect$([upItem], true))) : this.toggleSelect$([upItem], !upItem.selected);
o.pipe(first())
.subscribe(() => {
this.currentItemIndex = upIndex;
this.changeDetectorRef.markForCheck();
});
}
}
this.rangeStartIndex = -1;
});
}
public getDragContext(index: number) {
if (!this.clipboardService || (!this.sortable && !this.itemsDraggable)) {
return null;
}
return {
dragendcallback: (event: IDejaDragEvent) => {
this.itemDragEnd.emit(event);
delete this._ddStartIndex;
delete this._ddTargetIndex;
this.calcViewList$().pipe(first()).subscribe(noop); // Comment this line to debug dragdrop
},
dragstartcallback: (event: IDejaDragEvent) => {
const targetIndex = this.getItemIndexFromHTMLElement(event.target as HTMLElement);
if (targetIndex === undefined) {
return;
}
this._ddStartIndex = index;
event.dragObject = this._itemList[targetIndex - this.vpStartRow];
this.itemDragStart.emit(event);
},
object: {
index: index,
},
};
}
public getDropContext() {
if (!this.clipboardService || !this.sortable) {
return null;
}
const dragcallback = (event: IDejaDragEvent) => {
if (this._ddStartIndex === undefined) {
return;
}
const targetIndex = this.getItemIndexFromHTMLElement(event.target as HTMLElement);
if (targetIndex === undefined) {
return;
}
// Faire calculer le target final en fonction de la hierarchie par le service
this.calcDragTargetIndex$(this._ddStartIndex, targetIndex).pipe(
switchMap((finalTarget) => {
if (finalTarget !== undefined && finalTarget !== this._ddTargetIndex) {
this._ddTargetIndex = finalTarget;
return this.calcViewList$().pipe(
first(),
map(() => finalTarget));
} else {
return observableOf(finalTarget);
}
}))
.subscribe(noop);
event.preventDefault();
return;
};
return {
dragentercallback: dragcallback,
dragovercallback: dragcallback,
dropcallback: (event: IDejaDragEvent) => {
delete this._ddStartIndex;
delete this._ddTargetIndex;
this.drop$().pipe(
switchMap(() => this.calcViewList$().pipe(first())))
.subscribe(noop);
event.preventDefault();
},
};
}
public dragLeave(event: DragEvent) {
const listRect = this.listElement.getBoundingClientRect();
const listBounds = Rect.fromLTRB(listRect.left,
listRect.top,
listRect.right,
listRect.bottom);
if (!listBounds.containsPoint(new Position(event.pageX, event.pageY))) {
this._ddTargetIndex = this._ddStartIndex;
this.calcViewList$().pipe(first()).subscribe(noop);
}
}
public onSelectionChange() {
let outputEmitter = null;
let output = null;
if (this.multiSelect) {
const models = this.selectedModels;
outputEmitter = {
items: this.selectedItems,
models: models,
} as DejaItemsEvent;
Iif (this.modelIsValue) {
const valueField = this.getValueField();
if (models.find((m) => !!m[valueField])) {
output = models.map((m) => m[valueField] !== undefined ? m[valueField] : m);
}
} else {
output = models;
}
} else {
const model = this.selectedModel;
outputEmitter = {
item: this.selectedItems[0],
model: model,
} as DejaItemEvent;
Iif (this.modelIsValue) {
const valueField = this.getValueField();
output = model[valueField] !== undefined ? model[valueField] : model;
} else {
output = model;
}
}
this.onChangeCallback(output);
this.selectedChange.emit(outputEmitter);
}
public selectRange$(indexFrom: number, indexTo?: number): Observable<number> {
return super.selectRange$(indexFrom, indexTo).pipe(tap((selectedCount) => {
Eif (selectedCount) {
// Raise event
this.onSelectionChange();
}
return selectedCount;
}), tap(() => this.changeDetectorRef.markForCheck()));
}
public toggleSelect$(items: IItemBase[], state: boolean): Observable<IItemBase[]> {
Iif (!this._multiSelect && !items[0].selected === !state) {
return observableOf(items);
} else {
return super.toggleSelect$(items, state).pipe(
tap(() => {
// Raise event
this.onSelectionChange();
}));
}
}
public calcViewList$(): Observable<IViewListResult> {
return super.calcViewList$(this.query).pipe(
tap(() => this.changeDetectorRef.markForCheck()));
}
public getItemClass(item: IItemTree) {
const classNames = ['listitem'] as string[];
if (item.className) {
classNames.push(item.className);
}
if (item.collapsing || item.expanding) {
classNames.push('hide');
}
if (item.depth < this.depthMax) {
classNames.push('parent');
}
if (item.collapsed) {
classNames.push('collapsed');
}
if (item.selected) {
classNames.push('selected');
}
if (item.selectable === false) {
classNames.push('unselectable');
}
if (item.depth === this._depthMax && item.odd) {
classNames.push('odd');
}
return classNames.join(' ');
}
}
|