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
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
|
/*
* Copyright 2000-2016 Vaadin Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.vaadin.ui;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Stream;
import com.vaadin.event.ConnectorEvent;
import com.vaadin.event.ContextClickEvent;
import com.vaadin.event.EventListener;
import com.vaadin.server.KeyMapper;
import com.vaadin.server.data.SortOrder;
import com.vaadin.shared.MouseEventDetails;
import com.vaadin.shared.Registration;
import com.vaadin.shared.data.DataCommunicatorConstants;
import com.vaadin.shared.data.sort.SortDirection;
import com.vaadin.shared.ui.grid.ColumnState;
import com.vaadin.shared.ui.grid.GridConstants;
import com.vaadin.shared.ui.grid.GridConstants.Section;
import com.vaadin.shared.ui.grid.GridServerRpc;
import com.vaadin.shared.ui.grid.GridState;
import com.vaadin.shared.ui.grid.HeightMode;
import com.vaadin.ui.renderers.AbstractRenderer;
import com.vaadin.ui.renderers.Renderer;
import com.vaadin.ui.renderers.TextRenderer;
import com.vaadin.util.ReflectTools;
import elemental.json.Json;
import elemental.json.JsonObject;
import elemental.json.JsonValue;
/**
* A grid component for displaying tabular data.
*
* @author Vaadin Ltd
* @since 8.0
*
* @param <T>
* the grid bean type
*/
public class Grid<T> extends AbstractSingleSelect<T> implements HasComponents {
@Deprecated
private static final Method ITEM_CLICK_METHOD = ReflectTools
.findMethod(ItemClickListener.class, "accept", ItemClick.class);
/**
* An event fired when an item in the Grid has been clicked.
*
* @param <T>
* the grid bean type
*/
public static class ItemClick<T> extends ConnectorEvent {
private final T item;
private final Column<T, ?> column;
private final MouseEventDetails mouseEventDetails;
/**
* Creates a new {@code ItemClick} event containing the given item and
* Column originating from the given Grid.
*
*/
public ItemClick(Grid<T> source, Column<T, ?> column, T item,
MouseEventDetails mouseEventDetails) {
super(source);
this.column = column;
this.item = item;
this.mouseEventDetails = mouseEventDetails;
}
/**
* Returns the clicked item.
*
* @return the clicked item
*/
public T getItem() {
return item;
}
/**
* Returns the clicked column.
*
* @return the clicked column
*/
public Column<T, ?> getColumn() {
return column;
}
/**
* Returns the source Grid.
*
* @return the grid
*/
@Override
public Grid<T> getSource() {
return (Grid<T>) super.getSource();
}
/**
* Returns the mouse event details.
*
* @return the mouse event details
*/
public MouseEventDetails getMouseEventDetails() {
return mouseEventDetails;
}
}
/**
* A listener for item click events.
*
* @param <T>
* the grid bean type
*
* @see ItemClick
* @see Registration
*/
@FunctionalInterface
public interface ItemClickListener<T> extends EventListener<ItemClick<T>> {
/**
* Invoked when this listener receives a item click event from a Grid to
* which it has been added.
*
* @param event
* the received event, not null
*/
@Override
public void accept(ItemClick<T> event);
}
/**
* ContextClickEvent for the Grid Component.
*
* @param <T>
* the grid bean type
*/
public static class GridContextClickEvent<T> extends ContextClickEvent {
private final T item;
private final int rowIndex;
private final Column<?, ?> column;
private final Section section;
/**
* Creates a new context click event.
*
* @param source
* the grid where the context click occurred
* @param mouseEventDetails
* details about mouse position
* @param section
* the section of the grid which was clicked
* @param rowIndex
* the index of the row which was clicked
* @param item
* the item which was clicked
* @param column
* the column which was clicked
*/
public GridContextClickEvent(Grid<T> source,
MouseEventDetails mouseEventDetails, Section section,
int rowIndex, T item, Column<?, ?> column) {
super(source, mouseEventDetails);
this.item = item;
this.section = section;
this.column = column;
this.rowIndex = rowIndex;
}
/**
* Returns the item of context clicked row.
*
* @return item of clicked row; <code>null</code> if header or footer
*/
public T getItem() {
return item;
}
/**
* Returns the clicked column.
*
* @return the clicked column
*/
public Column<?, ?> getColumn() {
return column;
}
/**
* Return the clicked section of Grid.
*
* @return section of grid
*/
public Section getSection() {
return section;
}
/**
* Returns the clicked row index.
* <p>
* Header and Footer rows for index can be fetched with
* {@link Grid#getHeaderRow(int)} and {@link Grid#getFooterRow(int)}.
*
* @return row index in section
*/
public int getRowIndex() {
return rowIndex;
}
@Override
public Grid<T> getComponent() {
return (Grid<T>) super.getComponent();
}
}
/**
* A callback interface for generating description texts for an item.
*
* @param <T>
* the grid bean type
*/
@FunctionalInterface
public interface DescriptionGenerator<T>
extends Function<T, String>, Serializable {
}
/**
* A callback interface for generating details for a particular row in Grid.
*
* @param <T>
* the grid bean type
*/
@FunctionalInterface
public interface DetailsGenerator<T>
extends Function<T, Component>, Serializable {
}
/**
* A helper base class for creating extensions for the Grid component.
*
* @param <T>
*/
public abstract static class AbstractGridExtension<T>
extends AbstractListingExtension<T> {
@Override
public void extend(AbstractListing<T, ?> grid) {
if (!(grid instanceof Grid)) {
throw new IllegalArgumentException(
getClass().getSimpleName() + " can only extend Grid");
}
super.extend(grid);
}
/**
* Adds given component to the connector hierarchy of Grid.
*
* @param c
* the component to add
*/
protected void addComponentToGrid(Component c) {
getParent().addExtensionComponent(c);
}
/**
* Removes given component from the connector hierarchy of Grid.
*
* @param c
* the component to remove
*/
protected void removeComponentFromGrid(Component c) {
getParent().removeExtensionComponent(c);
}
@Override
public Grid<T> getParent() {
return (Grid<T>) super.getParent();
}
}
private final class GridServerRpcImpl implements GridServerRpc {
@Override
public void sort(String[] columnIds, SortDirection[] directions,
boolean isUserOriginated) {
assert columnIds.length == directions.length : "Column and sort direction counts don't match.";
sortOrder.clear();
if (columnIds.length == 0) {
// Grid is not sorted anymore.
getDataCommunicator()
.setBackEndSorting(Collections.emptyList());
getDataCommunicator().setInMemorySorting(null);
return;
}
for (int i = 0; i < columnIds.length; ++i) {
Column<T, ?> column = columnKeys.get(columnIds[i]);
sortOrder.add(new SortOrder<>(column, directions[i]));
}
// Set sort orders
// In-memory comparator
Comparator<T> comparator = sortOrder.stream()
.map(order -> order.getSorted()
.getComparator(order.getDirection()))
.reduce((x, y) -> 0, Comparator::thenComparing);
getDataCommunicator().setInMemorySorting(comparator);
// Back-end sort properties
List<SortOrder<String>> sortProperties = new ArrayList<>();
sortOrder.stream()
.map(order -> order.getSorted()
.getSortOrder(order.getDirection()))
.forEach(s -> s.forEach(sortProperties::add));
getDataCommunicator().setBackEndSorting(sortProperties);
}
@Override
public void itemClick(String rowKey, String columnId,
MouseEventDetails details) {
Column<T, ?> column = columnKeys.containsKey(columnId)
? columnKeys.get(columnId) : null;
T item = getDataCommunicator().getKeyMapper().get(rowKey);
fireEvent(new ItemClick<>(Grid.this, column, item, details));
}
@Override
public void contextClick(int rowIndex, String rowKey, String columnId,
Section section, MouseEventDetails details) {
T item = null;
if (rowKey != null) {
item = getDataCommunicator().getKeyMapper().get(rowKey);
}
fireEvent(new GridContextClickEvent<T>(Grid.this, details, section,
rowIndex, item, getColumn(columnId)));
}
@Override
public void columnsReordered(List<String> newColumnOrder,
List<String> oldColumnOrder) {
// TODO Auto-generated method stub
}
@Override
public void columnVisibilityChanged(String id, boolean hidden,
boolean userOriginated) {
// TODO Auto-generated method stub
}
@Override
public void columnResized(String id, double pixels) {
// TODO Auto-generated method stub
}
}
/**
* Class for managing visible details rows.
*
* @param <T>
* the grid bean type
*/
public static class DetailsManager<T> extends AbstractGridExtension<T> {
private Set<T> visibleDetails = new HashSet<>();
private Map<T, Component> components = new HashMap<>();
private DetailsGenerator<T> generator;
/**
* Sets the details component generator.
*
* @param generator
* the generator for details components
*/
public void setDetailsGenerator(DetailsGenerator<T> generator) {
if (this.generator != generator) {
removeAllComponents();
}
this.generator = generator;
visibleDetails.forEach(this::refresh);
}
@Override
public void remove() {
removeAllComponents();
super.remove();
}
private void removeAllComponents() {
// Clean up old components
components.values().forEach(this::removeComponentFromGrid);
components.clear();
}
@Override
public void generateData(T data, JsonObject jsonObject) {
if (generator == null || !visibleDetails.contains(data)) {
return;
}
if (!components.containsKey(data)) {
Component detailsComponent = generator.apply(data);
Objects.requireNonNull(detailsComponent,
"Details generator can't create null components");
if (detailsComponent.getParent() != null) {
throw new IllegalStateException(
"Details component was already attached");
}
addComponentToGrid(detailsComponent);
components.put(data, detailsComponent);
}
jsonObject.put(GridState.JSONKEY_DETAILS_VISIBLE,
components.get(data).getConnectorId());
}
@Override
public void destroyData(T data) {
// No clean up needed. Components are removed when hiding details
// and/or changing details generator
}
/**
* Sets the visibility of details component for given item.
*
* @param data
* the item to show details for
* @param visible
* {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public void setDetailsVisible(T data, boolean visible) {
boolean refresh = false;
if (!visible) {
refresh = visibleDetails.remove(data);
if (components.containsKey(data)) {
removeComponentFromGrid(components.remove(data));
}
} else {
refresh = visibleDetails.add(data);
}
if (refresh) {
refresh(data);
}
}
/**
* Returns the visibility of details component for given item.
*
* @param data
* the item to show details for
*
* @return {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public boolean isDetailsVisible(T data) {
return visibleDetails.contains(data);
}
@Override
public Grid<T> getParent() {
return super.getParent();
}
}
/**
* This extension manages the configuration and data communication for a
* Column inside of a Grid component.
*
* @param <T>
* the grid bean type
* @param <V>
* the column value type
*/
public static class Column<T, V> extends AbstractGridExtension<T> {
private final Function<T, ? extends V> valueProvider;
private Function<SortDirection, Stream<SortOrder<String>>> sortOrderProvider;
private Comparator<T> comparator;
private StyleGenerator<T> styleGenerator = item -> null;
private DescriptionGenerator<T> descriptionGenerator;
/**
* Constructs a new Column configuration with given header caption,
* renderer and value provider.
*
* @param caption
* the header caption
* @param valueProvider
* the function to get values from items
* @param renderer
* the type of value
*/
protected Column(String caption, Function<T, ? extends V> valueProvider,
Renderer<V> renderer) {
Objects.requireNonNull(caption, "Header caption can't be null");
Objects.requireNonNull(valueProvider,
"Value provider can't be null");
Objects.requireNonNull(renderer, "Renderer can't be null");
ColumnState state = getState();
this.valueProvider = valueProvider;
state.renderer = renderer;
state.caption = caption;
sortOrderProvider = d -> Stream.of();
// Add the renderer as a child extension of this extension, thus
// ensuring the renderer will be unregistered when this column is
// removed
addExtension(renderer);
Class<V> valueType = renderer.getPresentationType();
if (Comparable.class.isAssignableFrom(valueType)) {
comparator = (a, b) -> {
@SuppressWarnings("unchecked")
Comparable<V> comp = (Comparable<V>) valueProvider.apply(a);
return comp.compareTo(valueProvider.apply(b));
};
state.sortable = true;
} else if (Number.class.isAssignableFrom(valueType)) {
/*
* Value type will be Number whenever using NumberRenderer.
* Provide explicit comparison support in this case even though
* Number itself isn't Comparable.
*/
comparator = (a, b) -> {
return compareNumbers((Number) valueProvider.apply(a),
(Number) valueProvider.apply(b));
};
state.sortable = true;
} else {
state.sortable = false;
}
}
@SuppressWarnings("unchecked")
private static int compareNumbers(Number a, Number b) {
assert a.getClass() == b.getClass();
// Most Number implementations are Comparable
if (a instanceof Comparable && a.getClass().isInstance(b)) {
return ((Comparable<Number>) a).compareTo(b);
} else if (a.equals(b)) {
return 0;
} else {
// Fall back to comparing based on potentially truncated values
int compare = Long.compare(a.longValue(), b.longValue());
if (compare == 0) {
// This might still produce 0 even though the values are not
// equals, but there's nothing more we can do about that
compare = Double.compare(a.doubleValue(), b.doubleValue());
}
return compare;
}
}
@Override
public void generateData(T data, JsonObject jsonObject) {
ColumnState state = getState(false);
String communicationId = state.id;
assert communicationId != null : "No communication ID set for column "
+ state.caption;
@SuppressWarnings("unchecked")
Renderer<V> renderer = (Renderer<V>) state.renderer;
JsonObject obj = getDataObject(jsonObject,
DataCommunicatorConstants.DATA);
V providerValue = valueProvider.apply(data);
JsonValue rendererValue = renderer.encode(providerValue);
obj.put(communicationId, rendererValue);
String style = styleGenerator.apply(data);
if (style != null && !style.isEmpty()) {
JsonObject styleObj = getDataObject(jsonObject,
GridState.JSONKEY_CELLSTYLES);
styleObj.put(communicationId, style);
}
if (descriptionGenerator != null) {
String description = descriptionGenerator.apply(data);
if (description != null && !description.isEmpty()) {
JsonObject descriptionObj = getDataObject(jsonObject,
GridState.JSONKEY_CELLDESCRIPTION);
descriptionObj.put(communicationId, description);
}
}
}
/**
* Gets a data object with the given key from the given JsonObject. If
* there is no object with the key, this method creates a new
* JsonObject.
*
* @param jsonObject
* the json object
* @param key
* the key where the desired data object is stored
* @return data object for the given key
*/
private JsonObject getDataObject(JsonObject jsonObject, String key) {
if (!jsonObject.hasKey(key)) {
jsonObject.put(key, Json.createObject());
}
return jsonObject.getObject(key);
}
@Override
protected ColumnState getState() {
return getState(true);
}
@Override
protected ColumnState getState(boolean markAsDirty) {
return (ColumnState) super.getState(markAsDirty);
}
/**
* This method extends the given Grid with this Column.
*
* @param grid
* the grid to extend
*/
private void extend(Grid<T> grid) {
super.extend(grid);
}
/**
* Sets the identifier to use with this Column in communication.
*
* @param id
* the identifier string
*/
private void setId(String id) {
Objects.requireNonNull(id, "Communication ID can't be null");
getState().id = id;
}
/**
* Sets whether the user can sort this column or not.
*
* @param sortable
* {@code true} if the column can be sorted by the user;
* {@code false} if not
* @return this column
*/
public Column<T, V> setSortable(boolean sortable) {
getState().sortable = sortable;
return this;
}
/**
* Gets whether the user can sort this column or not.
*
* @return {@code true} if the column can be sorted by the user;
* {@code false} if not
*/
public boolean isSortable() {
return getState(false).sortable;
}
/**
* Sets the header caption for this column.
*
* @param caption
* the header caption
*
* @return this column
*/
public Column<T, V> setCaption(String caption) {
Objects.requireNonNull(caption, "Header caption can't be null");
getState().caption = caption;
return this;
}
/**
* Gets the header caption for this column.
*
* @return header caption
*/
public String getCaption() {
return getState(false).caption;
}
/**
* Sets a comparator to use with in-memory sorting with this column.
* Sorting with a back-end is done using
* {@link Column#setSortProperty(String...)}.
*
* @param comparator
* the comparator to use when sorting data in this column
* @return this column
*/
public Column<T, V> setComparator(Comparator<T> comparator) {
Objects.requireNonNull(comparator, "Comparator can't be null");
this.comparator = comparator;
return this;
}
/**
* Gets the comparator to use with in-memory sorting for this column
* when sorting in the given direction.
*
* @param sortDirection
* the direction this column is sorted by
* @return comparator for this column
*/
public Comparator<T> getComparator(SortDirection sortDirection) {
Objects.requireNonNull(comparator,
"No comparator defined for sorted column.");
boolean reverse = sortDirection != SortDirection.ASCENDING;
return reverse ? comparator.reversed() : comparator;
}
/**
* Sets strings describing back end properties to be used when sorting
* this column. This method is a short hand for
* {@link #setSortBuilder(Function)} that takes an array of strings and
* uses the same sorting direction for all of them.
*
* @param properties
* the array of strings describing backend properties
* @return this column
*/
public Column<T, V> setSortProperty(String... properties) {
Objects.requireNonNull(properties, "Sort properties can't be null");
sortOrderProvider = dir -> Arrays.stream(properties)
.map(s -> new SortOrder<>(s, dir));
return this;
}
/**
* Sets the sort orders when sorting this column. The sort order
* provider is a function which provides {@link SortOrder} objects to
* describe how to sort by this column.
*
* @param provider
* the function to use when generating sort orders with the
* given direction
* @return this column
*/
public Column<T, V> setSortOrderProvider(
Function<SortDirection, Stream<SortOrder<String>>> provider) {
Objects.requireNonNull(provider,
"Sort order provider can't be null");
sortOrderProvider = provider;
return this;
}
/**
* Gets the sort orders to use with back-end sorting for this column
* when sorting in the given direction.
*
* @param direction
* the sorting direction
* @return stream of sort orders
*/
public Stream<SortOrder<String>> getSortOrder(SortDirection direction) {
return sortOrderProvider.apply(direction);
}
/**
* Sets the style generator that is used for generating class names for
* cells in this column. Returning null from the generator results in no
* custom style name being set.
*
* @param cellStyleGenerator
* the cell style generator to set, not null
* @return this column
* @throws NullPointerException
* if {@code cellStyleGenerator} is {@code null}
*/
public Column<T, V> setStyleGenerator(
StyleGenerator<T> cellStyleGenerator) {
Objects.requireNonNull(cellStyleGenerator,
"Cell style generator must not be null");
this.styleGenerator = cellStyleGenerator;
getParent().getDataCommunicator().reset();
return this;
}
/**
* Gets the style generator that is used for generating styles for
* cells.
*
* @return the cell style generator
*/
public StyleGenerator<T> getStyleGenerator() {
return styleGenerator;
}
/**
* Sets the description generator that is used for generating
* descriptions for cells in this column.
*
* @param cellDescriptionGenerator
* the cell description generator to set, or
* <code>null</code> to remove a previously set generator
* @return this column
*/
public Column<T, V> setDescriptionGenerator(
DescriptionGenerator<T> cellDescriptionGenerator) {
this.descriptionGenerator = cellDescriptionGenerator;
getParent().getDataCommunicator().reset();
return this;
}
/**
* Gets the description generator that is used for generating
* descriptions for cells.
*
* @return the cell description generator, or <code>null</code> if no
* generator is set
*/
public DescriptionGenerator<T> getDescriptionGenerator() {
return descriptionGenerator;
}
}
private final class SingleSelection extends AbstractSingleSelection {
private T selectedItem = null;
SingleSelection() {
addDataGenerator((item, json) -> {
if (isSelected(item)) {
json.put(DataCommunicatorConstants.SELECTED, true);
}
});
}
@Override
public Optional<T> getSelectedItem() {
return Optional.ofNullable(selectedItem);
}
@Override
protected boolean isKeySelected(String key) {
return Objects.equals(key, getSelectedKey());
}
@Override
protected String getSelectedKey() {
return itemToKey(selectedItem);
}
@Override
protected void doSetSelectedKey(String key) {
if (selectedItem != null) {
getDataCommunicator().refresh(selectedItem);
}
selectedItem = keyToItem(key);
if (selectedItem != null) {
getDataCommunicator().refresh(selectedItem);
}
}
}
private KeyMapper<Column<T, ?>> columnKeys = new KeyMapper<>();
private Set<Column<T, ?>> columnSet = new LinkedHashSet<>();
private List<SortOrder<Column<T, ?>>> sortOrder = new ArrayList<>();
private DetailsManager<T> detailsManager;
private Set<Component> extensionComponents = new HashSet<>();
private StyleGenerator<T> styleGenerator = item -> null;
private DescriptionGenerator<T> descriptionGenerator;
/**
* Constructor for the {@link Grid} component.
*/
public Grid() {
setSelectionModel(new SingleSelection());
registerRpc(new GridServerRpcImpl());
detailsManager = new DetailsManager<>();
addExtension(detailsManager);
addDataGenerator(detailsManager);
addDataGenerator((item, json) -> {
String styleName = styleGenerator.apply(item);
if (styleName != null && !styleName.isEmpty()) {
json.put(GridState.JSONKEY_ROWSTYLE, styleName);
}
if (descriptionGenerator != null) {
String description = descriptionGenerator.apply(item);
if (description != null && !description.isEmpty()) {
json.put(GridState.JSONKEY_ROWDESCRIPTION, description);
}
}
});
}
/**
* Adds a new column to this {@link Grid} with given header caption, typed
* renderer and value provider.
*
* @param caption
* the header caption
* @param valueProvider
* the value provider
* @param renderer
* the column value class
* @param <T>
* the type of this grid
* @param <V>
* the column value type
*
* @return the new column
*
* @see {@link AbstractRenderer}
*/
public <V> Column<T, V> addColumn(String caption,
Function<T, ? extends V> valueProvider,
AbstractRenderer<? super T, V> renderer) {
Column<T, V> column = new Column<>(caption, valueProvider, renderer);
column.extend(this);
column.setId(columnKeys.key(column));
columnSet.add(column);
addDataGenerator(column);
return column;
}
/**
* Adds a new text column to this {@link Grid} with given header caption
* string value provider. The column will use a {@link TextRenderer}.
*
* @param caption
* the header caption
* @param valueProvider
* the value provider
*
* @return the new column
*/
public Column<T, String> addColumn(String caption,
Function<T, String> valueProvider) {
return addColumn(caption, valueProvider, new TextRenderer());
}
/**
* Removes the given column from this {@link Grid}.
*
* @param column
* the column to remove
*/
public void removeColumn(Column<T, ?> column) {
if (columnSet.remove(column)) {
columnKeys.remove(column);
removeDataGenerator(column);
column.remove();
}
}
/**
* Sets the details component generator.
*
* @param generator
* the generator for details components
*/
public void setDetailsGenerator(DetailsGenerator<T> generator) {
this.detailsManager.setDetailsGenerator(generator);
}
/**
* Sets the visibility of details component for given item.
*
* @param data
* the item to show details for
* @param visible
* {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public void setDetailsVisible(T data, boolean visible) {
detailsManager.setDetailsVisible(data, visible);
}
/**
* Returns the visibility of details component for given item.
*
* @param data
* the item to show details for
*
* @return {@code true} if details component should be visible;
* {@code false} if it should be hidden
*/
public boolean isDetailsVisible(T data) {
return detailsManager.isDetailsVisible(data);
}
/**
* Gets an unmodifiable collection of all columns currently in this
* {@link Grid}.
*
* @return unmodifiable collection of columns
*/
public Collection<Column<T, ?>> getColumns() {
return Collections.unmodifiableSet(columnSet);
}
/**
* Gets a {@link Column} of this grid by its identifying string.
*
* @param columnId
* the identifier of the column to get
* @return the column corresponding to the given column id
*/
public Column<T, ?> getColumn(String columnId) {
return columnKeys.get(columnId);
}
@Override
public Iterator<Component> iterator() {
return Collections.unmodifiableSet(extensionComponents).iterator();
}
/**
* Sets the number of frozen columns in this grid. Setting the count to 0
* means that no data columns will be frozen, but the built-in selection
* checkbox column will still be frozen if it's in use. Setting the count to
* -1 will also disable the selection column.
* <p>
* The default value is 0.
*
* @param numberOfColumns
* the number of columns that should be frozen
*
* @throws IllegalArgumentException
* if the column count is less than -1 or greater than the
* number of visible columns
*/
public void setFrozenColumnCount(int numberOfColumns) {
if (numberOfColumns < -1 || numberOfColumns > columnSet.size()) {
throw new IllegalArgumentException(
"count must be between -1 and the current number of columns ("
+ columnSet.size() + "): " + numberOfColumns);
}
getState().frozenColumnCount = numberOfColumns;
}
/**
* Gets the number of frozen columns in this grid. 0 means that no data
* columns will be frozen, but the built-in selection checkbox column will
* still be frozen if it's in use. -1 means that not even the selection
* column is frozen.
* <p>
* <em>NOTE:</em> this count includes {@link Column#isHidden() hidden
* columns} in the count.
*
* @see #setFrozenColumnCount(int)
*
* @return the number of frozen columns
*/
public int getFrozenColumnCount() {
return getState(false).frozenColumnCount;
}
/**
* Sets the number of rows that should be visible in Grid's body. This
* method will set the height mode to be {@link HeightMode#ROW}.
*
* @param rows
* The height in terms of number of rows displayed in Grid's
* body. If Grid doesn't contain enough rows, white space is
* displayed instead. If <code>null</code> is given, then Grid's
* height is undefined
* @throws IllegalArgumentException
* if {@code rows} is zero or less
* @throws IllegalArgumentException
* if {@code rows} is {@link Double#isInfinite(double) infinite}
* @throws IllegalArgumentException
* if {@code rows} is {@link Double#isNaN(double) NaN}
*/
public void setHeightByRows(double rows) {
if (rows <= 0.0d) {
throw new IllegalArgumentException(
"More than zero rows must be shown.");
} else if (Double.isInfinite(rows)) {
throw new IllegalArgumentException(
"Grid doesn't support infinite heights");
} else if (Double.isNaN(rows)) {
throw new IllegalArgumentException("NaN is not a valid row count");
}
getState().heightMode = HeightMode.ROW;
getState().heightByRows = rows;
}
/**
* Gets the amount of rows in Grid's body that are shown, while
* {@link #getHeightMode()} is {@link HeightMode#ROW}.
*
* @return the amount of rows that are being shown in Grid's body
* @see #setHeightByRows(double)
*/
public double getHeightByRows() {
return getState(false).heightByRows;
}
/**
* {@inheritDoc}
* <p>
* <em>Note:</em> This method will set the height mode to be
* {@link HeightMode#CSS}.
*
* @see #setHeightMode(HeightMode)
*/
@Override
public void setHeight(float height, Unit unit) {
getState().heightMode = HeightMode.CSS;
super.setHeight(height, unit);
}
/**
* Defines the mode in which the Grid widget's height is calculated.
* <p>
* If {@link HeightMode#CSS} is given, Grid will respect the values given
* via a {@code setHeight}-method, and behave as a traditional Component.
* <p>
* If {@link HeightMode#ROW} is given, Grid will make sure that the body
* will display as many rows as {@link #getHeightByRows()} defines.
* <em>Note:</em> If headers/footers are inserted or removed, the widget
* will resize itself to still display the required amount of rows in its
* body. It also takes the horizontal scrollbar into account.
*
* @param heightMode
* the mode in to which Grid should be set
*/
public void setHeightMode(HeightMode heightMode) {
/*
* This method is a workaround for the fact that Vaadin re-applies
* widget dimensions (height/width) on each state change event. The
* original design was to have setHeight and setHeightByRow be equals,
* and whichever was called the latest was considered in effect.
*
* But, because of Vaadin always calling setHeight on the widget, this
* approach doesn't work.
*/
getState().heightMode = heightMode;
}
/**
* Returns the current {@link HeightMode} the Grid is in.
* <p>
* Defaults to {@link HeightMode#CSS}.
*
* @return the current HeightMode
*/
public HeightMode getHeightMode() {
return getState(false).heightMode;
}
/**
* Sets the style generator that is used for generating class names for rows
* in this grid. Returning null from the generator results in no custom
* style name being set.
*
* @see StyleGenerator
*
* @param styleGenerator
* the row style generator to set, not null
* @throws NullPointerException
* if {@code styleGenerator} is {@code null}
*/
public void setStyleGenerator(StyleGenerator<T> styleGenerator) {
Objects.requireNonNull(styleGenerator,
"Style generator must not be null");
this.styleGenerator = styleGenerator;
getDataCommunicator().reset();
}
/**
* Gets the style generator that is used for generating class names for
* rows.
*
* @see StyleGenerator
*
* @return the row style generator
*/
public StyleGenerator<T> getStyleGenerator() {
return styleGenerator;
}
/**
* Sets the description generator that is used for generating descriptions
* for rows.
*
* @param descriptionGenerator
* the row description generator to set, or <code>null</code> to
* remove a previously set generator
*/
public void setDescriptionGenerator(
DescriptionGenerator<T> descriptionGenerator) {
this.descriptionGenerator = descriptionGenerator;
getDataCommunicator().reset();
}
/**
* Gets the description generator that is used for generating descriptions
* for rows.
*
* @return the row description generator, or <code>null</code> if no
* generator is set
*/
public DescriptionGenerator<T> getDescriptionGenerator() {
return descriptionGenerator;
}
/**
* Adds an item click listener. The listener is called when an item of this
* {@code Grid} is clicked.
*
* @param listener
* the item click listener, not null
* @return a registration for the listener
*/
public Registration addItemClickListener(
ItemClickListener<? super T> listener) {
Objects.requireNonNull(listener, "listener cannot be null");
addListener(GridConstants.ITEM_CLICK_EVENT_ID, ItemClick.class,
listener, ITEM_CLICK_METHOD);
return () -> removeListener(ItemClick.class, listener);
}
@Override
protected GridState getState() {
return getState(true);
}
@Override
protected GridState getState(boolean markAsDirty) {
return (GridState) super.getState(markAsDirty);
}
private void addExtensionComponent(Component c) {
if (extensionComponents.add(c)) {
c.setParent(this);
markAsDirty();
}
}
private void removeExtensionComponent(Component c) {
if (extensionComponents.remove(c)) {
c.setParent(null);
markAsDirty();
}
}
}
|