-
Notifications
You must be signed in to change notification settings - Fork 46
/
MaterialComboBox.java
1379 lines (1174 loc) · 40 KB
/
MaterialComboBox.java
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
/*
* #%L
* GwtMaterial
* %%
* Copyright (C) 2015 - 2017 GwtMaterialDesign
* %%
* 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.
* #L%
*/
package gwt.material.design.addins.client.combobox;
import com.google.gwt.core.client.GWT;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Style;
import com.google.gwt.event.dom.client.DomEvent;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.logical.shared.*;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.ui.Widget;
import gwt.material.design.addins.client.MaterialAddins;
import gwt.material.design.addins.client.base.constants.AddinsCssName;
import gwt.material.design.addins.client.combobox.async.DefaultComboBoxDisplayLoader;
import gwt.material.design.addins.client.combobox.events.ComboBoxEvents;
import gwt.material.design.addins.client.combobox.events.HasComboBoxHandlers;
import gwt.material.design.addins.client.combobox.events.SelectItemEvent;
import gwt.material.design.addins.client.combobox.events.UnselectItemEvent;
import gwt.material.design.addins.client.combobox.js.JsComboBox;
import gwt.material.design.addins.client.combobox.js.JsComboBoxOptions;
import gwt.material.design.addins.client.combobox.js.LanguageOptions;
import gwt.material.design.addins.client.combobox.js.options.Data;
import gwt.material.design.addins.client.combobox.js.options.Params;
import gwt.material.design.addins.client.combobox.js.options.Template;
import gwt.material.design.addins.client.dark.AddinsDarkThemeReloader;
import gwt.material.design.client.MaterialDesignBase;
import gwt.material.design.client.async.AsyncWidgetCallback;
import gwt.material.design.client.async.IsAsyncWidget;
import gwt.material.design.client.async.loader.AsyncDisplayLoader;
import gwt.material.design.client.async.mixin.AsyncWidgetMixin;
import gwt.material.design.client.base.*;
import gwt.material.design.client.base.mixin.EnabledMixin;
import gwt.material.design.client.base.mixin.FieldTypeMixin;
import gwt.material.design.client.base.mixin.ReadOnlyMixin;
import gwt.material.design.client.base.mixin.StatusTextMixin;
import gwt.material.design.client.constants.CssName;
import gwt.material.design.client.constants.FieldType;
import gwt.material.design.client.events.ClearEvent;
import gwt.material.design.client.events.ClearingEvent;
import gwt.material.design.client.events.ClosingEvent;
import gwt.material.design.client.events.OpeningEvent;
import gwt.material.design.client.ui.MaterialLabel;
import gwt.material.design.client.ui.MaterialToast;
import gwt.material.design.client.ui.html.Label;
import gwt.material.design.client.ui.html.OptGroup;
import gwt.material.design.client.ui.html.Option;
import gwt.material.design.jquery.client.api.Event;
import gwt.material.design.jquery.client.api.Functions;
import gwt.material.design.jquery.client.api.JQueryElement;
import gwt.material.design.jquery.client.api.KeyEvent;
import java.util.*;
import static gwt.material.design.addins.client.combobox.js.JsComboBox.$;
//@formatter:off
/**
* ComboBox component used on chat module
* <p>
* <h3>XML Namespace Declaration</h3>
* <pre>
* {@code
* xmlns:ma='urn:import:gwt.material.design.addins.client'
* }
* </pre>
* <p>
* <h3>UiBinder Usage:</h3>
* <pre>
* {@code
* <combobox:MaterialComboBox>
* <m:html.Option value="1" text="Sample 1"/>
* <m:html.Option value="2" text="Sample 2"/>
* <m:html.Option value="3" text="Sample 3"/>
* </combobox:MaterialComboBox>
* }
* </pre>
*
* @author kevzlou7979
* @author Ben Dol
* @see <a href="http://gwtmaterialdesign.github.io/gwt-material-demo/#combobox">Material ComboBox</a>
* @see <a href="https://github.com/select2/select2">Select2 4.0.3</a>
*/
//@formatter:on
public class MaterialComboBox<T> extends AbstractValueWidget<List<T>> implements JsLoader, HasPlaceholder,
HasComboBoxHandlers<T>, HasReadOnly, HasFieldTypes, IsAsyncWidget<MaterialComboBox, List<T>>, HasLabel, HasOpenClose, HasSingleValue<T> {
static {
if (MaterialAddins.isDebug()) {
MaterialDesignBase.injectDebugJs(MaterialComboBoxDebugClientBundle.INSTANCE.select2DebugJs());
MaterialDesignBase.injectCss(MaterialComboBoxDebugClientBundle.INSTANCE.select2DebugCss());
} else {
MaterialDesignBase.injectJs(MaterialComboBoxClientBundle.INSTANCE.select2Js());
MaterialDesignBase.injectCss(MaterialComboBoxClientBundle.INSTANCE.select2Css());
}
}
private int selectedIndex;
private boolean open;
private boolean suppressChangeEvent;
private boolean enableFocus;
protected List<T> values = new ArrayList<>();
private Label label = new Label();
private MaterialLabel errorLabel = new MaterialLabel();
protected MaterialWidget listbox = new MaterialWidget(Document.get().createSelectElement());
private KeyFactory<T, String> keyFactory = new AllowBlankKeyFactory<>();
private JsComboBoxOptions options = JsComboBoxOptions.create();
private StatusTextMixin<AbstractValueWidget, MaterialLabel> statusTextMixin;
private ReadOnlyMixin<MaterialComboBox, MaterialWidget> readOnlyMixin;
private EnabledMixin<MaterialWidget> enabledMixin;
private FieldTypeMixin<MaterialComboBox> fieldTypeMixin;
private AsyncWidgetMixin<MaterialComboBox, List<T>> asyncWidgetMixin;
public MaterialComboBox() {
super(Document.get().createDivElement(), CssName.INPUT_FIELD, AddinsCssName.COMBOBOX);
setAsyncDisplayLoader(new DefaultComboBoxDisplayLoader<>(this));
}
public MaterialComboBox(List<T> items) {
this();
setItems(items);
}
@Override
protected void onLoad() {
label.setInitialClasses(AddinsCssName.SELECT2LABEL);
addWidget(listbox);
addWidget(label);
addWidget(errorLabel);
errorLabel.setMarginTop(8);
listbox.setGwtDisplay(Style.Display.BLOCK);
super.onLoad();
load();
registerHandler(addSelectionHandler(valueChangeEvent -> $(getElement()).find("input").val("")));
}
@Override
public void load() {
JsComboBox jsComboBox = getJsComboBox();
jsComboBox.select2(options);
setId(DOM.createUniqueId());
jsComboBox.on(ComboBoxEvents.CHANGE, event -> {
if (!suppressChangeEvent) {
ValueChangeEvent.fire(this, getValue());
}
return true;
});
jsComboBox.on(ComboBoxEvents.SELECT, event -> {
SelectItemEvent.fire(this, getValue());
displayArrowForAllowClearOption(false);
return true;
});
jsComboBox.on(ComboBoxEvents.UNSELECT, event -> {
UnselectItemEvent.fire(this, getValue());
displayArrowForAllowClearOption(true);
return true;
});
jsComboBox.on(ComboBoxEvents.OPENING, (e, param1) -> {
OpeningEvent.fire(this);
return true;
});
jsComboBox.on(ComboBoxEvents.OPEN, (event1, o) -> {
if (isAsynchronous()) {
event1.stopPropagation();
event1.preventDefault();
load(getAsyncCallback());
} else {
OpenEvent.fire(this, null);
}
open = true;
return true;
});
jsComboBox.on(ComboBoxEvents.CLOSING, (e, param1) -> {
ClosingEvent.fire(this);
if (getValue() != null && !getValue().isEmpty()) {
focus();
}
return true;
});
jsComboBox.on(ComboBoxEvents.CLOSE, (event1, o) -> {
CloseEvent.fire(this, null);
open = false;
return true;
});
jsComboBox.on(ComboBoxEvents.CLEAR, (e, param1) -> {
ClearEvent.fire(this);
return true;
});
jsComboBox.on(ComboBoxEvents.CLEARING, (e, param1) -> {
ClearingEvent.fire(this);
return true;
});
if (enableFocus) {
body().on(ComboBoxEvents.FOCUS, getSelectContainerSelector(), (e, param1) -> {
if (!e.getCurrentTarget().getClassName().contains("select2-container--focus")) {
DomEvent.fireNativeEvent(Document.get().createFocusEvent(), this, getElement());
}
return false;
});
}
body().on(ComboBoxEvents.KEYUP, getSearchFieldElement(), e -> {
KeyEvent keyEvent = (KeyEvent) e;
DomEvent.fireNativeEvent(Document.get().createKeyUpEvent(keyEvent.ctrlKey, keyEvent.altKey, keyEvent.shiftKey, Boolean.parseBoolean(keyEvent.metaKey), keyEvent.keyCode), this, getElement());
return true;
});
displayArrowForAllowClearOption(false);
if (getTextColor() != null) {
$(getElement()).find(".select2-selection__rendered").css("color", getTextColor().getCssName());
}
addFocusHandler(event -> {
if (!isMultiple()) {
open();
}
});
getStatusTextMixin().getStatusDisplayMixin().setContainer(new MaterialWidget($(getElement())));
AddinsDarkThemeReloader.get().reload(MaterialComboBoxDarkTheme.class);
}
@Override
protected void onUnload() {
super.onUnload();
unload();
}
@Override
public void unload() {
JsComboBox jsComboBox = getJsComboBox();
jsComboBox.off(ComboBoxEvents.CHANGE);
jsComboBox.off(ComboBoxEvents.SELECT);
jsComboBox.off(ComboBoxEvents.UNSELECT);
jsComboBox.off(ComboBoxEvents.OPENING);
jsComboBox.off(ComboBoxEvents.OPEN);
jsComboBox.off(ComboBoxEvents.CLOSING);
jsComboBox.off(ComboBoxEvents.CLOSE);
jsComboBox.off(ComboBoxEvents.CLEAR);
jsComboBox.off(ComboBoxEvents.CLEARING);
jsComboBox.off(ComboBoxEvents.FOCUS);
jsComboBox.off(ComboBoxEvents.KEYUP);
body().off("focus");
jsComboBox.select2("destroy");
}
public void focus() {
getJsComboBox().select2("focus");
}
public void destroy() {
getJsComboBox().select2("destroy");
}
@Override
public void reload() {
unload();
load();
}
@Override
public void reset() {
super.reset();
setSelectedIndex(0);
displayArrowForAllowClearOption(false);
}
@Override
public void add(Widget child) {
if (child instanceof OptGroup) {
for (Widget w : ((OptGroup) child).getChildren()) {
if (w instanceof Option) {
values.add((T) ((Option) w).getValue());
}
}
} else if (child instanceof Option) {
values.add((T) ((Option) child).getValue());
}
listbox.add(child);
}
/**
* Programmatically open the combobox component
*/
@Override
public void open() {
getJsComboBox().select2("open");
}
/**
* Programmatically close the combobox component
*/
@Override
public void close() {
getJsComboBox().select2("close");
}
@Override
public boolean isOpen() {
return open;
}
@Override
public void clear() {
final Iterator<Widget> it = iterator();
while (it.hasNext()) {
final Widget widget = it.next();
if (widget != label && widget != errorLabel && widget != listbox) {
it.remove();
}
}
listbox.clear();
values.clear();
}
public boolean isInitialized() {
return getJsComboBox().hasClass("select2-hidden-accessible");
}
public void addWidget(Widget widget) {
super.add(widget);
}
/**
* Add OptionGroup directly to combobox component
*
* @param group - Option Group component
*/
public void addGroup(OptGroup group) {
listbox.add(group);
}
/**
* Add item directly to combobox component with existing OptGroup
*
* @param text - The text you want to labeled on the option item
* @param value - The value you want to pass through in this option
* @param optGroup - Add directly this option into the existing group
*/
public void addItem(String text, T value, OptGroup optGroup) {
if (!values.contains(value)) {
values.add(value);
optGroup.add(buildOption(text, value));
}
}
/**
* Add Value directly to combobox component
*
* @param text - The text you want to labeled on the option item
* @param value - The value you want to pass through in this option
*/
public Option addItem(String text, T value) {
if (!values.contains(value)) {
Option option = buildOption(text, value);
values.add(value);
listbox.add(option);
return option;
}
return null;
}
public Option addItem(T value) {
return addItem(keyFactory.generateKey(value), value);
}
public void setItems(Collection<T> items) {
clear();
addItems(items);
}
public void addItems(Collection<T> items) {
if (items != null) {
items.forEach(this::addItem);
}
}
/**
* Build the Option Element with provided params
*/
protected Option buildOption(String text, T value) {
Option option = new Option();
option.setText(text);
option.setValue(keyFactory.generateKey(value));
return option;
}
/**
* Sets the parent element of the dropdown
*/
public void setDropdownParent(String dropdownParent) {
options.dropdownParent = $(dropdownParent);
}
public JQueryElement getDropdownParent() {
return options.dropdownParent;
}
/**
* Will get the Selection Results ul element containing all the combobox items.
*/
public JQueryElement getDropdownResultElement() {
String dropdownId = getDropdownContainerElement().attr("id").toString();
if (dropdownId != null && !(dropdownId.isEmpty())) {
dropdownId = dropdownId.replace("container", "results");
return $("#" + dropdownId);
} else {
GWT.log("The element dropdown-result ul element is undefined.", new NullPointerException());
}
return null;
}
/**
* Will get the Clear Icon element
*/
public JQueryElement getClearIconElement() {
return $(getElement()).find(".select2-selection__clear");
}
public JQueryElement getArrowIconElement() {
return $(getElement()).find(".select2-selection__arrow");
}
/**
* Will automatically check for allowClear option to display / hide the
* arrow caret.
*/
protected void displayArrowForAllowClearOption(boolean displayArrow) {
if (isAllowClear()) {
if (displayArrow && getArrowIconElement() != null) {
getArrowIconElement().css("display", "block");
} else {
getArrowIconElement().css("display", "none");
}
}
}
/**
* Will get the Selection dropdown container rendered
*/
public JQueryElement getDropdownContainerElement() {
JQueryElement element = $(getElement()).find(".select2 .selection .select2-selection__rendered");
if (element == null) {
GWT.log("The element dropdown-container element is undefined.", new NullPointerException());
}
return element;
}
/**
* Set the upper label above the combobox
*/
@Override
public void setLabel(String text) {
label.setText(text);
}
@Override
public String getLabel() {
return label.getText();
}
@Override
public String getPlaceholder() {
return options.placeholder;
}
@Override
public void setPlaceholder(String placeholder) {
options.placeholder = placeholder;
}
/**
* Check if allow clear option is enabled
*/
public boolean isAllowClear() {
return options.allowClear;
}
/**
* Add a clear button on the right side of the combobox
*/
public void setAllowClear(boolean allowClear) {
options.allowClear = allowClear;
}
/**
* Get the maximum number of items to be entered on multiple combobox
*/
public int getLimit() {
return options.maximumSelectionLength;
}
/**
* Set the maximum number of items to be entered on multiple combobox
*/
public void setLimit(int limit) {
options.maximumSelectionLength = limit;
}
/**
* Check whether the search box is enabled on combobox
*/
public boolean isHideSearch() {
return options.minimumResultsForSearch.equals("Infinity");
}
/**
* Set the option to display the search box inside the combobox component
*/
public void setHideSearch(boolean hideSearch) {
if (hideSearch) {
options.minimumResultsForSearch = "Infinity";
}
}
/**
* Check whether the multiple option is enabled
*/
public boolean isMultiple() {
if (listbox != null) {
return listbox.getElement().hasAttribute("multiple");
}
return false;
}
/**
* Sets multi-value select boxes.
*/
public void setMultiple(boolean multiple) {
if (multiple) {
getJsComboBox().attr("multiple", "multiple");
} else {
getJsComboBox().removeAttr("multiple");
}
}
public void setAcceptableValues(Collection<T> values) {
setItems(values);
}
@Override
public List<T> getValue() {
if (!isMultiple()) {
int index = getSelectedIndex();
T value;
if (index != -1) {
// Check when the value is a custom tag
if (isTags()) {
value = (T) getJsComboBox().val();
} else {
value = values.get(index);
}
// Check whether we add an item with null value
if (index == 0 && value == null) {
return isAllowBlank() ? new ArrayList<>() : null;
}
return Collections.singletonList(value);
}
} else {
return getSelectedValues();
}
return new ArrayList<>();
}
/**
* Gets the value for currently selected item. If multiple items are
* selected, this method will return the value of the first selected item.
*
* @return the value for selected item, or {@code null} if none is selected
*/
public List<T> getSelectedValue() {
return getValue();
}
@Override
public void setValue(List<T> value) {
setValue(value, false);
}
/**
* Set the selected value using a single item, generally used
* in single selection mode.
*/
@Override
public void setSingleValue(T value) {
setValue(Collections.singletonList(value));
}
/**
* Set the selected value using a single item, generally used
* in single selection mode.
*/
@Override
public void setSingleValue(T value, boolean fireEvents) {
int index = this.values.indexOf(value);
if (index < 0 && value instanceof String) {
index = getIndexByString((String) value);
}
if (index > -1) {
List<T> before = getValue();
setSelectedIndex(index);
if (fireEvents) {
ValueChangeEvent.fireIfNotEqual(this, before, Collections.singletonList(value));
}
}
}
/**
* Only return a single value even if multi support is activate.
*/
@Override
public T getSingleValue() {
List<T> values = getSelectedValue();
if (values != null && !values.isEmpty()) {
return values.get(0);
}
return null;
}
@Override
public void setValue(List<T> values, boolean fireEvents) {
if (values == null) {
reset();
if (fireEvents) {
ValueChangeEvent.fire(this, null);
}
} else if (!isMultiple()) {
if (!values.isEmpty()) {
setSingleValue(values.get(0), fireEvents);
}
} else {
setValues(values, fireEvents);
}
}
// TODO: Optimize performance (maybe use a map)
public T getValueByString(String key) {
for (T value : values) {
if (keyFactory.generateKey(value).equals(key)) {
return value;
}
}
return null;
}
// TODO: Optimize performance (maybe use a map)
public int getIndexByString(String key) {
int index = -1;
for (T value : values) {
if (keyFactory.generateKey(value).equals(key)) {
return values.indexOf(value);
}
}
return index;
}
/**
* Set directly all the values that will be stored into
* combobox and build options into it.
*/
public void setValues(List<T> values) {
setValues(values, true);
}
/**
* Set directly all the values that will be stored into
* combobox and build options into it.
*/
public void setValues(List<T> values, boolean fireEvents) {
String[] stringValues = new String[values.size()];
for (int i = 0; i < values.size(); i++) {
stringValues[i] = keyFactory.generateKey(values.get(i));
}
suppressChangeEvent = !fireEvents;
getJsComboBox().val(stringValues).trigger("change", selectedIndex);
suppressChangeEvent = false;
}
/**
* Gets the index of the value pass in this method
*
* @param value - The Object you want to pass as value on combobox
*/
public int getValueIndex(T value) {
return values.indexOf(value);
}
/**
* Sets the currently selected index.
* <p>
* After calling this method, only the specified item in the list will
* remain selected. For a ListBox with multiple selection enabled.
*
* @param selectedIndex - the index of the item to be selected
*/
public void setSelectedIndex(int selectedIndex) {
this.selectedIndex = selectedIndex;
if (values.size() > 0) {
T value = values.get(selectedIndex);
if (value != null || isAllowBlank()) {
getJsComboBox().val(keyFactory.generateKey(value)).trigger("change.select2", selectedIndex);
} else {
GWT.log("Value index is not found.", new IndexOutOfBoundsException());
}
}
}
/**
* Gets the text for currently selected item. If multiple items are
* selected, this method will return the text of the first selected item.
*
* @return the text for selected item, or {@code null} if none is selected
*/
public int getSelectedIndex() {
Object o = $(getElement()).find("option:selected").last().prop("index");
if (o != null) {
return Integer.parseInt(o.toString());
}
return -1;
}
public void unselect() {
getJsComboBox().val("").change();
getJsComboBox().trigger(new Event(ComboBoxEvents.UNSELECT));
}
/**
* Get all the values sets on combobox
*/
public List<T> getValues() {
return values;
}
/**
* Get the selected vales from multiple combobox
*/
public List<T> getSelectedValues() {
Object[] curVal = (Object[]) getJsComboBox().val();
List<T> selectedValues = new ArrayList<>();
if (curVal == null || curVal.length < 1) {
return selectedValues;
}
List<String> keyIndex = getValuesKeyIndex();
for (Object val : curVal) {
if (val instanceof String) {
int selectedIndex = keyIndex.indexOf(val);
if (selectedIndex != -1) {
selectedValues.add(values.get(selectedIndex));
} else {
if (isTags() && val instanceof String) {
selectedValues.add((T) val);
}
}
}
}
return selectedValues;
}
protected List<String> getValuesKeyIndex() {
List<String> keys = new ArrayList<>();
for (T value : values) {
keys.add(keyFactory.generateKey(value));
}
return keys;
}
/**
* Use your own key factory for value keys.
*/
public void setKeyFactory(KeyFactory<T, String> keyFactory) {
this.keyFactory = keyFactory;
}
@Override
public void setReadOnly(boolean value) {
getReadOnlyMixin().setReadOnly(value);
}
@Override
public boolean isReadOnly() {
return getReadOnlyMixin().isReadOnly();
}
@Override
public void setToggleReadOnly(boolean toggle) {
getReadOnlyMixin().setToggleReadOnly(toggle);
registerHandler(addValueChangeHandler(valueChangeEvent -> {
if (isToggleReadOnly()) {
setReadOnly(true);
}
}));
}
@Override
public boolean isToggleReadOnly() {
return getReadOnlyMixin().isToggleReadOnly();
}
/**
* Check whether the dropdown will be close or not when result is selected
*/
public boolean isCloseOnSelect() {
return options.closeOnSelect;
}
/**
* Allow or Prevent the dropdown from closing when a result is selected (Default true)
*/
public void setCloseOnSelect(boolean closeOnSelect) {
options.closeOnSelect = closeOnSelect;
}
public MaterialWidget getListbox() {
return listbox;
}
public Label getLabelWidget() {
return label;
}
public MaterialLabel getErrorLabel() {
return errorLabel;
}
public boolean isTags() {
return options.tags;
}
/**
* Note: Tags will only support String as generic params starting 2.x.
*/
public void setTags(boolean tags) {
if (tags) GWT.log("Note: Tags will only support String as generic params.");
options.tags = tags;
}
/**
* Will provide a set of text objecs that can be used for i18n language support.
*/
public void setLanguage(LanguageOptions language) {
options.language = language;
}
public LanguageOptions getLanguage() {
return options.language;
}
/**
* Supports customization of the container width.
*
* @see <a href="https://select2.org/appearance#container-width">Example</a>
*/
public void setContainerWidth(String width) {
options.width = width;
}
public String getContainerWidth() {
return options.width;
}
public Object getContainerCss() {
return options.containerCss;
}
/**
* Adds custom CSS to the container. Expects key-value pairs:
* <pre>
* { 'css-property': 'value' }
* </pre>
*/
public void setContainerCss(Object containerCss) {
this.options.containerCss = containerCss;
}
public String getContainerCssClass() {
return options.containerCssClass;
}
/**
* Appended a class to the container
*/
public void setContainerCssClass(String containerCssClass) {
this.options.containerCssClass = containerCssClass;
}
public Object[] getData() {
return options.data;
}
/**
* Allows rendering dropdown options from an array.
*/
public void setData(Object[] data) {
this.options.data = data;
}
public Object getDataAdapter() {
return options.dataAdapter;
}
/**
* Used to override the built-in DataAdapter.
*/
public void setDataAdapter(Object dataAdapter) {
this.options.dataAdapter = dataAdapter;
}
public boolean isDebug() {
return options.debug;
}
/**
* Enable debugging messages in the browser console.
*/
public void setDebug(boolean debug) {
this.options.debug = debug;
}
public Object getDir() {
return options.dir;
}
public void setDir(Object dir) {
this.options.dir = dir;
}
public Object getDropdownAdapter() {
return options.dropdownAdapter;
}
/**
* Used to override the built-in DropdownAdapter
*/
public void setDropdownAdapter(Object dropdownAdapter) {
this.options.dropdownAdapter = dropdownAdapter;
}
public boolean isDropdownAutoWidth() {
return options.dropdownAutoWidth;
}
/**
* Will adapt dropdown width to it's parent
*/
public void setDropdownAutoWidth(boolean dropdownAutoWidth) {
this.options.dropdownAutoWidth = dropdownAutoWidth;
}
public Object getDropdownCss() {
return options.dropdownCss;
}
/**