-
Notifications
You must be signed in to change notification settings - Fork 727
/
VFilterSelect.java
2264 lines (1968 loc) · 76.9 KB
/
VFilterSelect.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
/*
* Copyright 2000-2014 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.client.ui;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import com.google.gwt.aria.client.Roles;
import com.google.gwt.core.client.Scheduler;
import com.google.gwt.core.client.Scheduler.ScheduledCommand;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.Display;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.BlurEvent;
import com.google.gwt.event.dom.client.BlurHandler;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.FocusEvent;
import com.google.gwt.event.dom.client.FocusHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyDownEvent;
import com.google.gwt.event.dom.client.KeyDownHandler;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.event.dom.client.LoadEvent;
import com.google.gwt.event.dom.client.LoadHandler;
import com.google.gwt.event.logical.shared.CloseEvent;
import com.google.gwt.event.logical.shared.CloseHandler;
import com.google.gwt.i18n.client.HasDirection.Direction;
import com.google.gwt.user.client.Command;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.Window;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.PopupPanel;
import com.google.gwt.user.client.ui.PopupPanel.PositionCallback;
import com.google.gwt.user.client.ui.SuggestOracle.Suggestion;
import com.google.gwt.user.client.ui.TextBox;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.ApplicationConnection;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.ComponentConnector;
import com.vaadin.client.ComputedStyle;
import com.vaadin.client.ConnectorMap;
import com.vaadin.client.DeferredWorker;
import com.vaadin.client.Focusable;
import com.vaadin.client.UIDL;
import com.vaadin.client.VConsole;
import com.vaadin.client.WidgetUtil;
import com.vaadin.client.ui.aria.AriaHelper;
import com.vaadin.client.ui.aria.HandlesAriaCaption;
import com.vaadin.client.ui.aria.HandlesAriaInvalid;
import com.vaadin.client.ui.aria.HandlesAriaRequired;
import com.vaadin.client.ui.menubar.MenuBar;
import com.vaadin.client.ui.menubar.MenuItem;
import com.vaadin.shared.AbstractComponentState;
import com.vaadin.shared.EventId;
import com.vaadin.shared.ui.ComponentStateUtil;
import com.vaadin.shared.ui.combobox.FilteringMode;
import com.vaadin.shared.util.SharedUtil;
/**
* Client side implementation of the Select component.
*
* TODO needs major refactoring (to be extensible etc)
*/
@SuppressWarnings("deprecation")
public class VFilterSelect extends Composite implements Field, KeyDownHandler,
KeyUpHandler, ClickHandler, FocusHandler, BlurHandler, Focusable,
SubPartAware, HandlesAriaCaption, HandlesAriaInvalid,
HandlesAriaRequired, DeferredWorker {
/**
* Represents a suggestion in the suggestion popup box
*/
public class FilterSelectSuggestion implements Suggestion, Command {
private final String key;
private final String caption;
private String untranslatedIconUri;
/**
* Constructor
*
* @param uidl
* The UIDL recieved from the server
*/
public FilterSelectSuggestion(UIDL uidl) {
key = uidl.getStringAttribute("key");
caption = uidl.getStringAttribute("caption");
if (uidl.hasAttribute("icon")) {
untranslatedIconUri = uidl.getStringAttribute("icon");
}
}
/**
* Gets the visible row in the popup as a HTML string. The string
* contains an image tag with the rows icon (if an icon has been
* specified) and the caption of the item
*/
@Override
public String getDisplayString() {
final StringBuffer sb = new StringBuffer();
final Icon icon = client.getIcon(client
.translateVaadinUri(untranslatedIconUri));
if (icon != null) {
sb.append(icon.getElement().getString());
}
String content;
if ("".equals(caption)) {
// Ensure that empty options use the same height as other
// options and are not collapsed (#7506)
content = " ";
} else {
content = WidgetUtil.escapeHTML(caption);
}
sb.append("<span>" + content + "</span>");
return sb.toString();
}
/**
* Get a string that represents this item. This is used in the text box.
*/
@Override
public String getReplacementString() {
return caption;
}
/**
* Get the option key which represents the item on the server side.
*
* @return The key of the item
*/
public String getOptionKey() {
return key;
}
/**
* Get the URI of the icon. Used when constructing the displayed option.
*
* @return
*/
public String getIconUri() {
return client.translateVaadinUri(untranslatedIconUri);
}
/**
* Executes a selection of this item.
*/
@Override
public void execute() {
onSuggestionSelected(this);
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof FilterSelectSuggestion)) {
return false;
}
FilterSelectSuggestion other = (FilterSelectSuggestion) obj;
if ((key == null && other.key != null)
|| (key != null && !key.equals(other.key))) {
return false;
}
if ((caption == null && other.caption != null)
|| (caption != null && !caption.equals(other.caption))) {
return false;
}
if (!SharedUtil.equals(untranslatedIconUri,
other.untranslatedIconUri)) {
return false;
}
return true;
}
}
/**
* Represents the popup box with the selection options. Wraps a suggestion
* menu.
*/
public class SuggestionPopup extends VOverlay implements PositionCallback,
CloseHandler<PopupPanel> {
private static final int Z_INDEX = 30000;
/** For internal use only. May be removed or replaced in the future. */
public final SuggestionMenu menu;
private final Element up = DOM.createDiv();
private final Element down = DOM.createDiv();
private final Element status = DOM.createDiv();
private boolean isPagingEnabled = true;
private long lastAutoClosed;
private int popupOuterPadding = -1;
private int topPosition;
/**
* Default constructor
*/
SuggestionPopup() {
super(true, false, true);
debug("VFS.SP: constructor()");
setOwner(VFilterSelect.this);
menu = new SuggestionMenu();
setWidget(menu);
getElement().getStyle().setZIndex(Z_INDEX);
final Element root = getContainerElement();
up.setInnerHTML("<span>Prev</span>");
DOM.sinkEvents(up, Event.ONCLICK);
down.setInnerHTML("<span>Next</span>");
DOM.sinkEvents(down, Event.ONCLICK);
root.insertFirst(up);
root.appendChild(down);
root.appendChild(status);
DOM.sinkEvents(root, Event.ONMOUSEDOWN | Event.ONMOUSEWHEEL);
addCloseHandler(this);
Roles.getListRole().set(getElement());
setPreviewingAllNativeEvents(true);
}
/**
* Shows the popup where the user can see the filtered options
*
* @param currentSuggestions
* The filtered suggestions
* @param currentPage
* The current page number
* @param totalSuggestions
* The total amount of suggestions
*/
public void showSuggestions(
final Collection<FilterSelectSuggestion> currentSuggestions,
final int currentPage, final int totalSuggestions) {
debug("VFS.SP: showSuggestions(" + currentSuggestions + ", "
+ currentPage + ", " + totalSuggestions + ")");
/*
* We need to defer the opening of the popup so that the parent DOM
* has stabilized so we can calculate an absolute top and left
* correctly. This issue manifests when a Combobox is placed in
* another popupView which also needs to calculate the absoluteTop()
* to position itself. #9768
*
* After deferring the showSuggestions method, a problem with
* navigating in the combo box occurs. Because of that the method
* navigateItemAfterPageChange in ComboBoxConnector class, which
* navigates to the exact item after page was changed also was
* marked as deferred. #11333
*/
final SuggestionPopup popup = this;
Scheduler.get().scheduleDeferred(new ScheduledCommand() {
@Override
public void execute() {
// Add TT anchor point
getElement().setId("VAADIN_COMBOBOX_OPTIONLIST");
menu.setSuggestions(currentSuggestions);
final int x = VFilterSelect.this.getAbsoluteLeft();
topPosition = tb.getAbsoluteTop();
topPosition += tb.getOffsetHeight();
setPopupPosition(x, topPosition);
int nullOffset = (nullSelectionAllowed
&& "".equals(lastFilter) ? 1 : 0);
boolean firstPage = (currentPage == 0);
final int first = currentPage * pageLength + 1
- (firstPage ? 0 : nullOffset);
final int last = first
+ currentSuggestions.size()
- 1
- (firstPage && "".equals(lastFilter) ? nullOffset
: 0);
final int matches = totalSuggestions - nullOffset;
if (last > 0) {
// nullsel not counted, as requested by user
status.setInnerText((matches == 0 ? 0 : first) + "-"
+ last + "/" + matches);
} else {
status.setInnerText("");
}
// We don't need to show arrows or statusbar if there is
// only one page
if (totalSuggestions <= pageLength || pageLength == 0) {
setPagingEnabled(false);
} else {
setPagingEnabled(true);
}
setPrevButtonActive(first > 1);
setNextButtonActive(last < matches);
// clear previously fixed width
menu.setWidth("");
menu.getElement().getFirstChildElement().getStyle()
.clearWidth();
setPopupPositionAndShow(popup);
// Fix for #14173
// IE9 and IE10 have a bug, when resize an a element with
// box-shadow.
// IE9 and IE10 need explicit update to remove extra
// box-shadows
if (BrowserInfo.get().isIE9() || BrowserInfo.get().isIE10()) {
forceReflow();
}
}
});
}
/**
* Should the next page button be visible to the user?
*
* @param active
*/
private void setNextButtonActive(boolean active) {
if (enableDebug) {
debug("VFS.SP: setNextButtonActive(" + active + ")");
}
if (active) {
DOM.sinkEvents(down, Event.ONCLICK);
down.setClassName(VFilterSelect.this.getStylePrimaryName()
+ "-nextpage");
} else {
DOM.sinkEvents(down, 0);
down.setClassName(VFilterSelect.this.getStylePrimaryName()
+ "-nextpage-off");
}
}
/**
* Should the previous page button be visible to the user
*
* @param active
*/
private void setPrevButtonActive(boolean active) {
if (enableDebug) {
debug("VFS.SP: setPrevButtonActive(" + active + ")");
}
if (active) {
DOM.sinkEvents(up, Event.ONCLICK);
up.setClassName(VFilterSelect.this.getStylePrimaryName()
+ "-prevpage");
} else {
DOM.sinkEvents(up, 0);
up.setClassName(VFilterSelect.this.getStylePrimaryName()
+ "-prevpage-off");
}
}
/**
* Selects the next item in the filtered selections
*/
public void selectNextItem() {
debug("VFS.SP: selectNextItem()");
final int index = menu.getSelectedIndex() + 1;
if (menu.getItems().size() > index) {
selectItem(menu.getItems().get(index));
} else {
selectNextPage();
}
}
/**
* Selects the previous item in the filtered selections
*/
public void selectPrevItem() {
debug("VFS.SP: selectPrevItem()");
final int index = menu.getSelectedIndex() - 1;
if (index > -1) {
selectItem(menu.getItems().get(index));
} else if (index == -1) {
selectPrevPage();
} else {
if (!menu.getItems().isEmpty()) {
selectLastItem();
}
}
}
/**
* Select the first item of the suggestions list popup.
*
* @since 7.2.6
*/
public void selectFirstItem() {
debug("VFS.SP: selectFirstItem()");
selectItem(menu.getFirstItem());
}
/**
* Select the last item of the suggestions list popup.
*
* @since 7.2.6
*/
public void selectLastItem() {
debug("VFS.SP: selectLastItem()");
selectItem(menu.getLastItem());
}
/*
* Sets the selected item in the popup menu.
*/
private void selectItem(final MenuItem newSelectedItem) {
menu.selectItem(newSelectedItem);
// Set the icon.
FilterSelectSuggestion suggestion = (FilterSelectSuggestion) newSelectedItem
.getCommand();
setSelectedItemIcon(suggestion.getIconUri());
// Set the text.
setText(suggestion.getReplacementString());
}
/*
* Using a timer to scroll up or down the pages so when we receive lots
* of consecutive mouse wheel events the pages does not flicker.
*/
private LazyPageScroller lazyPageScroller = new LazyPageScroller();
private class LazyPageScroller extends Timer {
private int pagesToScroll = 0;
@Override
public void run() {
debug("VFS.SP.LPS: run()");
if (pagesToScroll != 0) {
if (!waitingForFilteringResponse) {
/*
* Avoid scrolling while we are waiting for a response
* because otherwise the waiting flag will be reset in
* the first response and the second response will be
* ignored, causing an empty popup...
*
* As long as the scrolling delay is suitable
* double/triple clicks will work by scrolling two or
* three pages at a time and this should not be a
* problem.
*/
filterOptions(currentPage + pagesToScroll, lastFilter);
}
pagesToScroll = 0;
}
}
public void scrollUp() {
debug("VFS.SP.LPS: scrollUp()");
if (pageLength > 0 && currentPage + pagesToScroll > 0) {
pagesToScroll--;
cancel();
schedule(200);
}
}
public void scrollDown() {
debug("VFS.SP.LPS: scrollDown()");
if (pageLength > 0
&& totalMatches > (currentPage + pagesToScroll + 1)
* pageLength) {
pagesToScroll++;
cancel();
schedule(200);
}
}
}
@Override
public void onBrowserEvent(Event event) {
debug("VFS.SP: onBrowserEvent()");
if (event.getTypeInt() == Event.ONCLICK) {
final Element target = DOM.eventGetTarget(event);
if (target == up || target == DOM.getChild(up, 0)) {
lazyPageScroller.scrollUp();
} else if (target == down || target == DOM.getChild(down, 0)) {
lazyPageScroller.scrollDown();
}
} else if (event.getTypeInt() == Event.ONMOUSEWHEEL) {
boolean scrollNotActive = !menu.isScrollActive();
debug("VFS.SP: onBrowserEvent() scrollNotActive: "
+ scrollNotActive);
if (scrollNotActive) {
int velocity = event.getMouseWheelVelocityY();
debug("VFS.SP: onBrowserEvent() velocity: " + velocity);
if (velocity > 0) {
lazyPageScroller.scrollDown();
} else {
lazyPageScroller.scrollUp();
}
}
}
/*
* Prevent the keyboard focus from leaving the textfield by
* preventing the default behaviour of the browser. Fixes #4285.
*/
handleMouseDownEvent(event);
}
/**
* Should paging be enabled. If paging is enabled then only a certain
* amount of items are visible at a time and a scrollbar or buttons are
* visible to change page. If paging is turned of then all options are
* rendered into the popup menu.
*
* @param paging
* Should the paging be turned on?
*/
public void setPagingEnabled(boolean paging) {
debug("VFS.SP: setPagingEnabled(" + paging + ")");
if (isPagingEnabled == paging) {
return;
}
if (paging) {
down.getStyle().clearDisplay();
up.getStyle().clearDisplay();
status.getStyle().clearDisplay();
} else {
down.getStyle().setDisplay(Display.NONE);
up.getStyle().setDisplay(Display.NONE);
status.getStyle().setDisplay(Display.NONE);
}
isPagingEnabled = paging;
}
@Override
public void setPosition(int offsetWidth, int offsetHeight) {
debug("VFS.SP: setPosition(" + offsetWidth + ", " + offsetHeight
+ ")");
int top = topPosition;
int left = getPopupLeft();
// reset menu size and retrieve its "natural" size
menu.setHeight("");
if (currentPage > 0 && !hasNextPage()) {
// fix height to avoid height change when getting to last page
menu.fixHeightTo(pageLength);
}
final int desiredHeight = offsetHeight = getOffsetHeight();
final int desiredWidth = getMainWidth();
debug("VFS.SP: desired[" + desiredWidth + ", " + desiredHeight
+ "]");
Element menuFirstChild = menu.getElement().getFirstChildElement();
final int naturalMenuWidth = WidgetUtil
.getRequiredWidth(menuFirstChild);
if (popupOuterPadding == -1) {
popupOuterPadding = WidgetUtil
.measureHorizontalPaddingAndBorder(getElement(), 2);
}
if (naturalMenuWidth < desiredWidth) {
menu.setWidth((desiredWidth - popupOuterPadding) + "px");
menuFirstChild.getStyle().setWidth(100, Unit.PCT);
}
if (BrowserInfo.get().isIE()
&& BrowserInfo.get().getBrowserMajorVersion() < 11) {
// Must take margin,border,padding manually into account for
// menu element as we measure the element child and set width to
// the element parent
double naturalMenuOuterWidth = WidgetUtil
.getRequiredWidthDouble(menuFirstChild)
+ getMarginBorderPaddingWidth(menu.getElement());
/*
* IE requires us to specify the width for the container
* element. Otherwise it will be 100% wide
*/
double rootWidth = Math.max(desiredWidth - popupOuterPadding,
naturalMenuOuterWidth);
getContainerElement().getStyle().setWidth(rootWidth, Unit.PX);
}
final int vfsHeight = VFilterSelect.this.getOffsetHeight();
final int spaceAvailableAbove = top - vfsHeight;
final int spaceAvailableBelow = Window.getClientHeight() - top;
if (spaceAvailableBelow < offsetHeight
&& spaceAvailableBelow < spaceAvailableAbove) {
// popup on top of input instead
top -= offsetHeight + vfsHeight;
if (top < 0) {
offsetHeight += top;
top = 0;
}
} else {
offsetHeight = Math.min(offsetHeight, spaceAvailableBelow);
}
// fetch real width (mac FF bugs here due GWT popups overflow:auto )
offsetWidth = menuFirstChild.getOffsetWidth();
if (offsetHeight < desiredHeight) {
int menuHeight = offsetHeight;
if (isPagingEnabled) {
menuHeight -= up.getOffsetHeight() + down.getOffsetHeight()
+ status.getOffsetHeight();
} else {
final ComputedStyle s = new ComputedStyle(menu.getElement());
menuHeight -= s.getIntProperty("marginBottom")
+ s.getIntProperty("marginTop");
}
// If the available page height is really tiny then this will be
// negative and an exception will be thrown on setHeight.
int menuElementHeight = menu.getItemOffsetHeight();
if (menuHeight < menuElementHeight) {
menuHeight = menuElementHeight;
}
menu.setHeight(menuHeight + "px");
final int naturalMenuWidthPlusScrollBar = naturalMenuWidth
+ WidgetUtil.getNativeScrollbarSize();
if (offsetWidth < naturalMenuWidthPlusScrollBar) {
menu.setWidth(naturalMenuWidthPlusScrollBar + "px");
}
}
if (offsetWidth + left > Window.getClientWidth()) {
left = VFilterSelect.this.getAbsoluteLeft()
+ VFilterSelect.this.getOffsetWidth() - offsetWidth;
if (left < 0) {
left = 0;
menu.setWidth(Window.getClientWidth() + "px");
}
}
setPopupPosition(left, top);
menu.scrollSelectionIntoView();
}
/**
* Was the popup just closed?
*
* @return true if popup was just closed
*/
public boolean isJustClosed() {
debug("VFS.SP: justClosed()");
final long now = (new Date()).getTime();
return (lastAutoClosed > 0 && (now - lastAutoClosed) < 200);
}
/*
* (non-Javadoc)
*
* @see
* com.google.gwt.event.logical.shared.CloseHandler#onClose(com.google
* .gwt.event.logical.shared.CloseEvent)
*/
@Override
public void onClose(CloseEvent<PopupPanel> event) {
if (enableDebug) {
debug("VFS.SP: onClose(" + event.isAutoClosed() + ")");
}
if (event.isAutoClosed()) {
lastAutoClosed = (new Date()).getTime();
}
}
/**
* Updates style names in suggestion popup to help theme building.
*
* @param uidl
* UIDL for the whole combo box
* @param componentState
* shared state of the combo box
*/
public void updateStyleNames(UIDL uidl,
AbstractComponentState componentState) {
debug("VFS.SP: updateStyleNames()");
setStyleName(VFilterSelect.this.getStylePrimaryName()
+ "-suggestpopup");
menu.setStyleName(VFilterSelect.this.getStylePrimaryName()
+ "-suggestmenu");
status.setClassName(VFilterSelect.this.getStylePrimaryName()
+ "-status");
if (ComponentStateUtil.hasStyles(componentState)) {
for (String style : componentState.styles) {
if (!"".equals(style)) {
addStyleDependentName(style);
}
}
}
}
}
/**
* The menu where the suggestions are rendered
*/
public class SuggestionMenu extends MenuBar implements SubPartAware,
LoadHandler {
private VLazyExecutor delayedImageLoadExecutioner = new VLazyExecutor(
100, new ScheduledCommand() {
@Override
public void execute() {
debug("VFS.SM: delayedImageLoadExecutioner()");
if (suggestionPopup.isVisible()
&& suggestionPopup.isAttached()) {
setWidth("");
getElement().getFirstChildElement().getStyle()
.clearWidth();
suggestionPopup
.setPopupPositionAndShow(suggestionPopup);
}
}
});
/**
* Default constructor
*/
SuggestionMenu() {
super(true);
debug("VFS.SM: constructor()");
addDomHandler(this, LoadEvent.getType());
setScrollEnabled(true);
}
/**
* Fixes menus height to use same space as full page would use. Needed
* to avoid height changes when quickly "scrolling" to last page.
*/
public void fixHeightTo(int pageItemsCount) {
setHeight(getPreferredHeight(pageItemsCount));
}
/*
* Gets the preferred height of the menu including pageItemsCount items.
*/
String getPreferredHeight(int pageItemsCount) {
if (currentSuggestions.size() > 0) {
final int pixels = (getPreferredHeight() / currentSuggestions
.size()) * pageItemsCount;
return pixels + "px";
} else {
return "";
}
}
/**
* Sets the suggestions rendered in the menu
*
* @param suggestions
* The suggestions to be rendered in the menu
*/
public void setSuggestions(
Collection<FilterSelectSuggestion> suggestions) {
if (enableDebug) {
debug("VFS.SM: setSuggestions(" + suggestions + ")");
}
clearItems();
final Iterator<FilterSelectSuggestion> it = suggestions.iterator();
boolean isFirstIteration = true;
while (it.hasNext()) {
final FilterSelectSuggestion s = it.next();
final MenuItem mi = new MenuItem(s.getDisplayString(), true, s);
Roles.getListitemRole().set(mi.getElement());
WidgetUtil.sinkOnloadForImages(mi.getElement());
this.addItem(mi);
// By default, first item on the list is always highlighted,
// unless adding new items is allowed.
if (isFirstIteration && !allowNewItem) {
selectItem(mi);
}
// If the filter matches the current selection, highlight that
// instead of the first item.
if (tb.getText().equals(s.getReplacementString())
&& s == currentSuggestion) {
selectItem(mi);
}
isFirstIteration = false;
}
}
/**
* Send the current selection to the server. Triggered when a selection
* is made or on a blur event.
*/
public void doSelectedItemAction() {
debug("VFS.SM: doSelectedItemAction()");
// do not send a value change event if null was and stays selected
final String enteredItemValue = tb.getText();
if (nullSelectionAllowed && "".equals(enteredItemValue)
&& selectedOptionKey != null
&& !"".equals(selectedOptionKey)) {
if (nullSelectItem) {
reset();
return;
}
// null is not visible on pages != 0, and not visible when
// filtering: handle separately
client.updateVariable(paintableId, "filter", "", false);
client.updateVariable(paintableId, "page", 0, false);
client.updateVariable(paintableId, "selected", new String[] {},
immediate);
afterUpdateClientVariables();
suggestionPopup.hide();
return;
}
updateSelectionWhenReponseIsReceived = waitingForFilteringResponse;
if (!waitingForFilteringResponse) {
doPostFilterSelectedItemAction();
}
}
/**
* Triggered after a selection has been made
*/
public void doPostFilterSelectedItemAction() {
debug("VFS.SM: doPostFilterSelectedItemAction()");
final MenuItem item = getSelectedItem();
final String enteredItemValue = tb.getText();
updateSelectionWhenReponseIsReceived = false;
// check for exact match in menu
int p = getItems().size();
if (p > 0) {
for (int i = 0; i < p; i++) {
final MenuItem potentialExactMatch = getItems().get(i);
if (potentialExactMatch.getText().equals(enteredItemValue)) {
selectItem(potentialExactMatch);
// do not send a value change event if null was and
// stays selected
if (!"".equals(enteredItemValue)
|| (selectedOptionKey != null && !""
.equals(selectedOptionKey))) {
doItemAction(potentialExactMatch, true);
}
suggestionPopup.hide();
return;
}
}
}
if (allowNewItem) {
if (!prompting && !enteredItemValue.equals(lastNewItemString)) {
/*
* Store last sent new item string to avoid double sends
*/
lastNewItemString = enteredItemValue;
client.updateVariable(paintableId, "newitem",
enteredItemValue, immediate);
afterUpdateClientVariables();
}
} else if (item != null
&& !"".equals(lastFilter)
&& (filteringmode == FilteringMode.CONTAINS ? item
.getText().toLowerCase()
.contains(lastFilter.toLowerCase()) : item
.getText().toLowerCase()
.startsWith(lastFilter.toLowerCase()))) {
doItemAction(item, true);
} else {
// currentSuggestion has key="" for nullselection
if (currentSuggestion != null
&& !currentSuggestion.key.equals("")) {
// An item (not null) selected
String text = currentSuggestion.getReplacementString();
setText(text);
selectedOptionKey = currentSuggestion.key;
} else {
// Null selected
setText("");
selectedOptionKey = null;
}
}
suggestionPopup.hide();
}
private static final String SUBPART_PREFIX = "item";
@Override
public com.google.gwt.user.client.Element getSubPartElement(
String subPart) {
int index = Integer.parseInt(subPart.substring(SUBPART_PREFIX
.length()));
MenuItem item = getItems().get(index);
return item.getElement();
}
@Override
public String getSubPartName(
com.google.gwt.user.client.Element subElement) {
if (!getElement().isOrHasChild(subElement)) {
return null;
}
Element menuItemRoot = subElement;
while (menuItemRoot != null
&& !menuItemRoot.getTagName().equalsIgnoreCase("td")) {
menuItemRoot = menuItemRoot.getParentElement().cast();
}
// "menuItemRoot" is now the root of the menu item
final int itemCount = getItems().size();
for (int i = 0; i < itemCount; i++) {
if (getItems().get(i).getElement() == menuItemRoot) {
String name = SUBPART_PREFIX + i;
return name;
}
}
return null;
}
@Override
public void onLoad(LoadEvent event) {
debug("VFS.SM: onLoad()");
// Handle icon onload events to ensure shadow is resized
// correctly
delayedImageLoadExecutioner.trigger();
}
/**
* @deprecated use {@link SuggestionPopup#selectFirstItem()} instead.
*/
@Deprecated
public void selectFirstItem() {
debug("VFS.SM: selectFirstItem()");
MenuItem firstItem = getItems().get(0);
selectItem(firstItem);
}
/**
* @deprecated use {@link SuggestionPopup#selectLastItem()} instead.